Single-Purpose Variables, Fixed-Width Types & Defensive do-while(0) Macros

Eliminate LP64/ILP32 width drift, multi-purpose temp aliasing, precedence bugs, and detached-else macro failures before running the Module 4 static-hygiene auditor lab.

20 minfree previewLinux 6.12C11glibc 2.39→ module 4 lab
What you'll learn
  • Replace multi-purpose temp variables and long-sized hardware fields with single-purpose <stdint.h> declarations.
  • Analyze preprocessor token-pasting and precedence hazards to choose between static inline functions and fully parenthesized macros.
  • Implement a C11 static-hygiene and LIFO unwind auditor verifying macro parenthesization, do { ... } while (0) wrapping, and zero hidden control-flow jumps.

Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety

Two habits ported from tiny 8-bit microcontrollers cause severe defects in 32/64-bit Linux systems C. First, reusing a single int temp; variable across a function — first as a loop index, next as a status register mask, and finally as a return code — creates overlapping live ranges where an uninitialized branch reads stale bits. Modern GCC allocates registers via Static Single Assignment (SSA); giving each value a narrow, initialized single-purpose variable (uint32_t sr_val = 0;) costs zero extra stack bytes under -O2 while making dataflow crystal clear.

Second, unsigned long changes width between your x86_64 workstation (LP64: 8 bytes) and your ARMv7-A Cortex-A7 target (ILP32: 4 bytes). Defining an MMIO descriptor or binary header with unsigned long shifts every subsequent field offset by 4 bytes between host unit tests and target silicon! Always use <stdint.h> (uint32_t, uint64_t) or kernel <linux/types.h> (u32, u64), and prefer enum + static inline functions over #define whenever compile-time constant folding is not required.

fig_m04_l03_a.svg — Textual macro substitution occurs before C parsing;…

Figure 4.3a. Textual macro substitution occurs before C parsing; parentheses and do-while(0) preserve AST structure.

mental model: Think of a do { ... } while (0) macro wrapper like shipping a multi-piece circuit subassembly inside one sealed IC package: no matter where the board layout places it, neighboring traces cannot accidentally short into only half of its internal pins.

Where it stops working: do { ... } while (0) protects statement grouping and trailing semicolons, but it STILL evaluates macro arguments each time they appear inside the body — only static inline functions guarantee single evaluation without GNU statement expressions.

definition ( Idiom): A standard C preprocessor idiom that wraps multiple statements inside a do { ... } while (0) loop executing exactly once; unlike a bare { ... } compound block, it requires a trailing semicolon at the invocation site (MACRO(x);), preventing a syntax error before else inside unbraced if (cond) MACRO(x); else ... constructs while optimizing away completely.

ast_m04_l03.svg — Use uint32_t for register structs, static inline for…step 1/4
  1. Step 1. _Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.
  2. Step 2. Passing *fifo_reg++ to a static inline reads the hardware FIFO once; a MAX(a,b) macro reads it twice!
  3. Step 3. Without outer parentheses, ~MASK_MACRO or 2 * ADD_MACRO re-associates with neighbouring operators.
  4. Step 4. The caller supplies the final semicolon after while (0), forming one syntactic statement.

Figure 4.3b. Use uint32_t for register structs, static inline for functions, and do-while(0) for multi-stmt macros.

Anatomy of Preprocessor Substitution Hazards

The C preprocessor (cpp) knows nothing about C expressions, statements, or types — it performs blind token substitution prior to syntax parsing. Consider #define BIT_MASK(n) 1U << n: calling BIT_MASK(2 + 1) expands to 1U << 2 + 1. Because + has higher precedence than << in C, that one happens to shift by 3, yet writing ~BIT_MASK(3) expands to ~1U << 3 (0xFFFFFFF0U instead of 0xFFFFFFF7U!) because unary ~ binds tighter than <<! Only ((1U) << (n)) is immune in both inner and outer contexts.

Now consider #define ACK_BOTH(a, b) *(a) = 1; *(b) = 1; used inside if (irq) ACK_BOTH(r1, r2);: after expansion, *(b) = 1; sits outside the if statement and fires unconditionally! Wrapping in bare { *(a) = 1; *(b) = 1; } fixes the if-only case, but if (irq) ACK_BOTH(r1, r2); else ... expands to { ... }; else ... — the extra empty ; terminates the if, leaving else with a hard compile error! do { *(a) = 1; *(b) = 1; } while (0) solves both.

fig_m04_l03_b.svg — Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A…

Figure 4.3b. Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A ILP32 makes sizeof(long)==4; uint32_t stays 4 everywhere.

MechanismType CheckingArgument EvaluationBest Embedded C11 Use Case
enum { FIFO_DEPTH = 32 };Integer constantCompile-time constantArray bounds, case labels, register bit positions
static inline uint32_t ...Strict C11 typesEvaluated onceRegister helpers, clamping, bitfield extraction
#define MASK(n) ((1U) << (n))Untyped tokensEach occurrence evaluatedCompile-time initializers & _Static_assert expressions
#define PAIR(a,b) do {...} while (0)Untyped tokensEach occurrence evaluatedMulti-statement logging or paired debug assertions (__FILE__, __LINE__)
learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat -H 19 -H 30 mmio_defensive_macros.h File: mmio_defensive_macros.h    /* SPDX-License-Identifier: GPL-2.0 */    #ifndef KSA_MMIO_DEFENSIVE_MACROS_H    #define KSA_MMIO_DEFENSIVE_MACROS_H        #include <stdint.h>        enum ccm_gate_mode {    	CCM_GATE_OFF     = 0x0U,    	CCM_GATE_RUN_ONLY = 0x1U,    	CCM_GATE_ALWAYS  = 0x3U,    };        struct dma_bd_hw {    	uint16_t length;    	uint16_t status;    	uint32_t buf_phys;    };      _Static_assert(sizeof(struct dma_bd_hw) == 8U, "DMA BD must be 8 bytes on LP64 and ILP32");        #define CCM_CG_SHIFT(slot)   (((uint32_t)(slot)) * 2U)    #define CCM_CG_MASK(slot)    (0x3U << CCM_CG_SHIFT(slot))        static inline uint32_t ccm_set_gate_val(uint32_t reg, unsigned int slot, enum ccm_gate_mode mode)    {    	uint32_t mask = CCM_CG_MASK(slot);    	return (reg & ~mask) | ((((uint32_t)mode) << CCM_CG_SHIFT(slot)) & mask);    }      #define MMIO_WRITE_PAIR(reg_a, val_a, reg_b, val_b) \    	do { \    		*(reg_a) = (val_a); \    		*(reg_b) = (val_b); \    	} while (0)        #endif /* KSA_MMIO_DEFENSIVE_MACROS_H */
  1. C11 _Static_assert locks the 8-byte hardware descriptor size identically across x86_64 and ARMv7-A.
  2. do { ... } while (0) without a trailing semicolon makes MMIO_WRITE_PAIR safe inside unbraced if/else.
stdint.h(0p) / C11 _Static_assert(3) at a glance — GL-E00
stdint.h(0p) / C11 _Static_assert(3) GL-E00 Quick Reference stdint.h(0p) / C11 _Static_assert(3) SYNOPSIS       #include <stdint.h>       _Static_assert(constant-expression, "diagnostic string");        DEFENSIVE MACRO & TYPE CHECKLIST Fixed-width Use uint8_t, uint16_t,       uint32_t, uint64_t, uintptr_t for HW registers & binary protocols.       static inline Prefer over #define for typed, single-evaluation helpers       (safe with ptr++ or FIFO reads). Parentheses Wrap EVERY macro arg (x)       and the ENTIRE outer expression ((x) + 1U). do-while(0) Wrap       multi-statement macros in 'do { ... } while (0)' (no trailing       semicolon). Control flow NEVER put 'return', 'goto', or 'break' inside       a macro body. Kernel Systems Academy     Lesson 4.3     stdint.h(0p) / C11 _Static_assert(3) GL-E00 quick reference · full manual page: man 3 stdint.h(0p) / C11 _Static_assert 

Proving Macro Precedence, Side-Effect, and Width Invariants in C11

In verify.c, we verify all four defensive rules quantitatively on our workstation: sizeof(unsigned long) vs sizeof(uint32_t) inside descriptor structs, precedence inversion when outer or inner parentheses are omitted, single evaluation of idx++ inside static inline versus double evaluation in naive MAX macros, and do { ... } while (0) branch binding inside an unbraced if/else.

Passing these assertions sets up lab_m04_c_style_auditor, where you will build a reusable C11 static-hygiene and LIFO unwind analyzer benchmarked with CLOCK_MONOTONIC.

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat -H 27 -H 34 verify.c File: verify.c    #define _POSIX_C_SOURCE 200809L    #include <stdint.h>    #include <stdio.h>        struct hw_desc_fixed {    	uint32_t ctrl;    	uint32_t buf_addr;    };    _Static_assert(sizeof(struct hw_desc_fixed) == 8U, "Fixed-width descriptor must be 8 bytes");        #define BAD_SHIFT(n)  1U << n    #define SAFE_SHIFT(n) ((1U) << (n))        #define SAFE_LATCH(pa, pb, v) \    	do { \    		*(pa) = (v); \    		*(pb) = (v) + 1U; \    	} while (0)        static inline uint32_t max_u32_once(uint32_t a, uint32_t b)    {    	return (a > b) ? a : b;    }        int main(void)    {  	uint32_t broken_inv = ~BAD_SHIFT(3);    	uint32_t safe_inv = ~SAFE_SHIFT(3);    	uint32_t counter = 4U;    	uint32_t mval = max_u32_once(counter++, 2U);    	uint32_t reg_a = 0U, reg_b = 0U;    	int gate_enabled = 0;      	if (gate_enabled)    		SAFE_LATCH(&reg_a, &reg_b, 10U);    	else    		reg_a = 99U;        	if (broken_inv == safe_inv || safe_inv != 0xFFFFFFF7U)    		return 1;    	if (mval != 4U || counter != 5U)    		return 2;    	if (reg_a != 99U || reg_b != 0U)    		return 3;        	printf("LP64_CHECK sizeof_ulong=%zu sizeof_fixed_desc=%zu\n",    	       sizeof(unsigned long), sizeof(struct hw_desc_fixed));    	printf("MACRO_PARENS broken_not=0x%08X safe_not=0x%08X\n", broken_inv, safe_inv);    	printf("INLINE_ONCE result=%u post_counter=%u do_while_else_reg_a=%u reg_b=%u\n",    	       mval, counter, reg_a, reg_b);    	return 0;    }
  1. ~BAD_SHIFT(3) expands to (~1U) << 3 == 0xFFFFFFF0 because unary ~ binds tighter than <<!
  2. do { ... } while (0) keeps both assignments inside the false branch and pairs cleanly with else.

Inspecting LP64 Host Widths and Precedence Bitmasks

Observe the recorded host output: on x86_64 Linux, sizeof(unsigned long) is 8 bytes while sizeof(struct hw_desc_fixed) remains locked at 8 bytes (2 x 4B uint32_t), matching the ARMv7-A DMA hardware descriptor ring byte-for-byte. Had those two fields used unsigned long, the struct would have ballooned to 16 bytes on the host!

Equally stark is MACRO_PARENS: ~BAD_SHIFT(3) silently cleared bits 0..2 (0xFFFFFFF0) instead of clearing bit 3 (0xFFFFFFF7), proving why outer parentheses on #define expressions are mandatory even when parameters appear trivial.

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l03./verifyLP64_CHECK sizeof_ulong=8 sizeof_fixed_desc=8MACRO_PARENS broken_not=0xFFFFFFF0 safe_not=0xFFFFFFF7INLINE_ONCE result=4 post_counter=5 do_while_else_reg_a=99 reg_b=0learner@ksa:~/gl-e00/m04-l03
strace — learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03strace -e trace=write,exit_group ./verifywrite(1, "LP64_CHECK sizeof_ulong=8 sizeof"..., 168) = 168exit_group(0)                           = ?+++ exited with 0 +++

Hidden Macro Control Flow and Side-Effect Double Reads

Before moving into lab_m04_c_style_auditor, lock in the hierarchy of C11 abstractions: use enum for integer constants, const objects for read-only tables, static inline for typed single-evaluation helpers, and reserve #define strictly for compile-time bitmasks, stringification/__LINE__ diagnostics, or type-generic wrappers.

Whenever a macro must exist, audit three things mechanically: inner (param) parentheses, outer (...) or do { ... } while (0) framing, and zero hidden return/goto statements.

Double FIFO Pop from Passing Volatile Register Read to MAX/MIN Macro:

  • Symptom: Reading an I2C or UART receive FIFO inside CLAMP(*rx_fifo_reg, 0, 127) drops every second byte on the wire without setting any hardware overrun flag.
  • Root Cause: A naive #define CLAMP(x, lo, hi) mentions (x) two or three times in its ternary expansion, issuing multiple volatile MMIO read cycles that pop distinct bytes from the hardware FIFO.
  • Fix: Replace value macros with a static inline C11 function, or read the volatile register once into a single-purpose uint32_t sample local variable first.

Deadlocked Mutex from Hidden return Inside CHECK_ERR Macro:

  • Symptom: After an intermittent I2C NAK error, every subsequent thread opening the device hangs forever inside mutex_lock() (D uninterruptible sleep in ps).
  • Root Cause: Calling CHECK_RET(i2c_xfer(...)); between mutex_lock(&dev->lock) and mutex_unlock(&dev->lock) executed a hidden return rc; inside the macro, bypassing goto err_unlock;.
  • Fix: Delete return-hiding macros completely; write explicit if (rc < 0) goto err_unlock; statements so every exit path through held locks is visible.

Guided Practice

In verify.c, add a second broken macro #define BAD_ADD_OFFSET(x) (x) + 0x10U (note inner parameter parentheses are present, outer expression parentheses are missing!) and compare BAD_ADD_OFFSET(4U) * 2U against #define SAFE_ADD_OFFSET(x) ((x) + 0x10U).

Verify that BAD_ADD_OFFSET(4U) * 2U evaluates to 4 + 32 = 36 instead of (4 + 16) * 2 = 40, confirming why both parameter and outer parentheses are required.

Independent Practice

Open labs/lab_m04_c_style_auditor/ and inspect starter/core.c alongside tests.c. Repair the three intentional defects in audit_macro_def(), audit_symbol_hygiene(), and verify_lifo_unwind() so unparenthesized macro args/hidden return tokens are rejected, missing static linkage is flagged, and LIFO release order (k-1 .. 0) is enforced.

Run sh check.sh to confirm 5/5 TAP version 13 checks pass, then run ./files/lab_cli --bench to record CLOCK_MONOTONIC p50/p95/p99 host auditing latency.

Verification Checks

quiz · 1 of 3

Why does #define ACK_IRQ(a, b) { *(a) = 1; *(b) = 1; } fail to compile inside if (pending) ACK_IRQ(r0, r1); else count++;?

quiz · 2 of 3

Why is unsigned long unsafe inside a shared DMA buffer-descriptor struct compiled in both x86_64 host tests and ARMv7-A firmware?

quiz · 3 of 3

Retrieval check from Lesson 4.2: Why are macros like #define TRY_CALL(expr) if ((expr) < 0) return -EIO banned in Linux kernel C?

Kernel C11 Macro Safety, Static Linkage & LIFO Unwind Auditor

env: host

1. Motivation

Production kernel patches fail review immediately when macros hide return jumps, private helpers omit static (STB_GLOBAL namespace pollution), or goto cleanup labels release clocks before unmapping registers.

In this studio, you implement a deterministic C11 static-rule and resource-unwind verifier that catches all three classes of defects automatically before target compilation.

2. Learning objectives

  • Detect unparenthesized macro parameters, bare multi-statement bodies, trailing semicolons, and hidden return/goto exits in audit_macro_def().
  • Flag file-private symbols lacking static (STB_LOCAL) linkage and Hungarian/camelCase naming violations in audit_symbol_hygiene().
  • Verify reverse-order LIFO resource release (k-1 .. 0) and reject FIFO or leaked unwind traces in verify_lifo_unwind().

3. Environment requirements

All automated verification steps run in unprivileged user space on a POSIX Linux host using gcc -std=c11 -Wall -Wextra -Werror and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).

4. Required software and hardware

  • Host workstation: gcc (-std=c11 -Wall -Wextra -Werror), GNU make, ar (binutils), and POSIX /bin/sh.
  • Target environment (optional hardware step, Section 13): Any ARMv7-A Cortex-A7 driver .ko built against Linux kernel 6.12 with scripts/checkpatch.pl and nm --defined-only.

5. Complete executable commands

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat script.sh File: script.sh    make -B -C files    ./files/lab_cli    ./files/lab_cli --bench    sh check.sh

6. Annotated source code

files/core.c enforces the production invariants that starter/core.c breaks:

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat example.c File: example.c    for (size_t i = 0U; i < tr->released_count; i++) {    	uint8_t expected_id = (uint8_t)(tr->acquired_count - 1U - i);    	if (tr->released_ids[i] != expected_id)    		return false;    }

starter/core.c omits the MACRO_HIDDEN_FLOW check on return/goto tokens, skips counting non-static private symbol leaks, and checks FIFO (0 .. k-1) instead of LIFO (k-1 .. 0) release order.

7. Expected output

Passing files/ run (sh check.sh, exit code 0):

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds libcore.a and lab_cli cleanly with -std=c11 -Wall -Wextra -Werror    ok 2 - archives core.o into libcore.a and links independent TAP verifier    ok 3 - detects unparenthesized macro params, missing do-while(0), trailing semicolons, and hidden return/goto    ok 4 - flags non-static private functions leaking STB_GLOBAL symbols and non-snake_case identifiers    ok 5 - enforces strict reverse LIFO goto unwind order (k-1 down to 0) and rejects FIFO or partial-leak traces    # pass 5/5

CLI verification output (./files/lab_cli):

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt    MACRO clean_flags=0x0 hazard_flags=0xf    SYMBOLS global_leaks=1 naming_violations=1    UNWIND lifo_valid=1 fifo_rejected=1

Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.

8. Explanation of observed behavior

When all three invariants are restored, audit_macro_def() verifies token-bounded return/goto absence alongside (param) and do { ... } while (0) framing, audit_symbol_hygiene() enforces STB_LOCAL static linkage on non-header declarations, and verify_lifo_unwind() confirms exact reverse teardown across every partial failure count.

9. Experiment variations

  • Near transfer: Extend audit_macro_def() to detect break and continue tokens hidden inside loop-unsafe macros.
  • Far transfer: Parse nm -P symbol table output from compiled .o files to verify zero unexpected T/D/B globals outside a module's public header.

10. Performance measurements

Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):

learner@ksa: ~/gl-e00/m04-l03
learner@ksa:~/gl-e00/m04-l03$ bat listing.txt File: listing.txt    BENCH lab_m04_c_style_auditor clock=CLOCK_MONOTONIC batches=40x500 p50_ns=106462 p95_ns=125711 p99_ns=126434 sink=1

The CLOCK_MONOTONIC benchmark measures user-space string/array auditing throughput (40 x 500 checks per sample) on the Linux host CPU; these nanosecond figures characterize static-check overhead only and never represent target ARMv7-A runtime execution.

11. Troubleshooting

SymptomRoot causeFix
Check 3 fails with flow=0x0audit_macro_def() is not scanning for token-bounded return and goto keywords.Restore `contains_token(body, "return")contains_token(body, "goto") setting MACRO_HIDDEN_FLOW`.
Check 4 fails with leaks=0audit_symbol_hygiene() ignores symbols where !in_public_header && !is_static.Increment out->global_leak_count whenever a private symbol omits static.
Check 5 accepts fifo trace and rejects lifo traceexpected_id uses i (0..N-1) instead of tr->acquired_count - 1U - i.Compute reverse LIFO index (uint8_t)(tr->acquired_count - 1U - i).

12. Guided questions

  1. Why does contains_token() check !is_ident_char(p[-1]) and !is_ident_char(p[tlen]) around "return" instead of using plain strstr(body, "return")?
  • *Hint 1:* Consider a valid macro calling a C helper named return_code_clamp(x) or reading goto_count.
  • *Hint 2:* Without identifier-boundary checks, strstr triggers false positives whenever return or goto appears as a substring of a valid snake_case identifier.
  1. Why must verify_lifo_unwind() verify tr->released_count == tr->acquired_count before looping over released_ids?
  • *Hint 1:* What happens if 4 resources were acquired (0..3) and only 3, 2 were released before returning -ENOMEM?
  • *Hint 2:* Checking only the prefix loop 0 .. released_count - 1 would pass 3, 2 even though resources 1 and 0 leaked permanently!

13. Independent challenges

Add a multi-parameter macro auditor audit_macro_multi(const char **params, size_t n_params, const char *body) that detects both unparenthesized occurrences AND duplicate evaluation (count > 1) of any parameter so macros susceptible to fn(i++) double-evaluation are flagged for static inline conversion.

14. Solutions and explanations

The reference files/core.c combines token-bounded control-flow scanning, (param) and do { ... } while (0) structural checks, STB_LOCAL static linkage verification, and acquired_count - 1 - i reverse LIFO indexing to pass all 5/5 TAP checks cleanly.

Run locally in your terminal and check off each verification milestone.

Not started

Key takeaways

  • Hardware register layouts and wire headers must use <stdint.h> fixed-width types (uint8_t, uint16_t, uint32_t, uint64_t) because unsigned long is 64 bits on x86_64 (LP64) and 32 bits on ARMv7-A (ILP32).
  • Typed const values, enum constants, and static inline functions are preferred over #define macros because they enforce parameter types and evaluate side-effecting arguments (i++) exactly once.
  • Every expression macro must parenthesize each parameter use and the outer expression (#define OFF(x) (((x) * 4U) + 8U)), while multi-statement macros wrap their body in do { ... } while (0) without a trailing semicolon.
  • Macros must never hide control-flow exits (return, goto, break) because invisible jumps bypass caller spinlocks and centralized goto cleanup spines.
Progress is saved on this device.
up next · module 4 labLab: Kernel C11 Macro Safety, Static Linkage & LIFO Unwind Auditor (60 min)
→ module 4 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure