Bare metal programming with Zig — is this language the right choice?

As a low-level programmer I am looking for particular features in a language and I haven’t found them in Zig yet. Please help me on these:

  1. Volatile Variables — Zig seems to offer volatile pointers, but not volatile variables. Is it a part of the “friction” in language design? Is the following an intended construct? (extracted from [link])
var tick_counter: u32 = 0; // updated in an IRQ
pub fn getTicks() u32 {
  return @as(*volatile u32, @ptrCast(&tick_counter)).*;
}

I would argue that volatile should be reserved only for MMIO as they are the natural way to communicate from an IRQ to the application in the absence of an OS

  1. Compiler barriers — in Zig I haven’t found any way to tell the compiler to ensure that all assignment statements up to a certain point in the code are executed before I can proceed with a DMA transaction or perform any other operation which requires all data in memory. Making everything volatile will not help in such case as they generate overhead with each access.

  2. Guaranteed structure layout in memory — I haven’t found any information that it is possible in Zig to create structures with predictable layout, so they would map peripheral registers. What is the intended way to deal with peripherals with registers?

Thank you for any answers which may help me.

You may can check Zig Embedded Group · GitHub

I believe that asm volatile ( "" ::: "memory" ) should work as a compiler barrier similar to how the same works in C with GCC.

Marking a struct extern gives it the same memory layout as the C ABI for the target.

4 Likes
  1. Loads and stores using volatile pointers can be used for memory mapped I/O only (compiler does not optimize away these stores and loads).
  2. Atomics can be used to specify memory ordering (compiler emits barrier instructions).
  3. packed struct and packed union have defined memory layout.

To define the bit fields of a memory mapped register, use a volatile pointer to a packed struct. (see: Memory-mapped IO registers in zig)

By the way, welcome to ziggit, and
Yes, zig is the right choice for bare metal programming. :slight_smile:

2 Likes