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.
What you'll learn
- Replace multi-purpose
tempvariables andlong-sized hardware fields with single-purpose<stdint.h>declarations. - Analyze preprocessor token-pasting and precedence hazards to choose between
static inlinefunctions and fully parenthesized macros. - Implement a C11 static-hygiene and
LIFOunwind 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.
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.
- Step 1. _Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.
- Step 2. Passing *fifo_reg++ to a static inline reads the hardware FIFO once; a MAX(a,b) macro reads it twice!
- Step 3. Without outer parentheses, ~MASK_MACRO or 2 * ADD_MACRO re-associates with neighbouring operators.
- 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.
Figure 4.3b. Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A ILP32 makes sizeof(long)==4; uint32_t stays 4 everywhere.
| Mechanism | Type Checking | Argument Evaluation | Best Embedded C11 Use Case |
|---|---|---|---|
enum { FIFO_DEPTH = 32 }; | Integer constant | Compile-time constant | Array bounds, case labels, register bit positions |
static inline uint32_t ... | Strict C11 types | Evaluated once | Register helpers, clamping, bitfield extraction |
#define MASK(n) ((1U) << (n)) | Untyped tokens | Each occurrence evaluated | Compile-time initializers & _Static_assert expressions |
#define PAIR(a,b) do {...} while (0) | Untyped tokens | Each occurrence evaluated | Multi-statement logging or paired debug assertions (__FILE__, __LINE__) |
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 */- C11 _Static_assert locks the 8-byte hardware descriptor size identically across x86_64 and ARMv7-A.
- do { ... } while (0) without a trailing semicolon makes MMIO_WRITE_PAIR safe inside unbraced if/else.
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$ 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(®_a, ®_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; }- ~BAD_SHIFT(3) expands to (~1U) << 3 == 0xFFFFFFF0 because unary ~ binds tighter than <<!
- 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-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-l03learner@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 +++Verification Checks
→ open standalone lab workbench
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/gotoexits inaudit_macro_def(). - Flag file-private symbols lacking
static(STB_LOCAL) linkage and Hungarian/camelCasenaming violations inaudit_symbol_hygiene(). - Verify reverse-order
LIFOresource release (k-1 .. 0) and rejectFIFOor leaked unwind traces inverify_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), GNUmake,ar(binutils), and POSIX/bin/sh. - Target environment (optional hardware step, Section 13): Any
ARMv7-ACortex-A7driver.kobuilt againstLinux kernel6.12 withscripts/checkpatch.plandnm --defined-only.
5. Complete executable commands
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.sh6. Annotated source code
files/core.c enforces the production invariants that starter/core.c breaks:
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$ 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/5CLI verification output (./files/lab_cli):
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=1Defective 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 detectbreakandcontinuetokens hidden inside loop-unsafe macros. - Far transfer: Parse
nm -Psymbol table output from compiled.ofiles to verify zero unexpectedT/D/Bglobals 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$ 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=1The 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
| Symptom | Root cause | Fix | ||
|---|---|---|---|---|
Check 3 fails with flow=0x0 | audit_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=0 | audit_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 trace | expected_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
- Why does
contains_token()check!is_ident_char(p[-1])and!is_ident_char(p[tlen])around"return"instead of using plainstrstr(body, "return")?
- *Hint 1:* Consider a valid macro calling a C helper named
return_code_clamp(x)or readinggoto_count. - *Hint 2:* Without identifier-boundary checks,
strstrtriggers false positives wheneverreturnorgotoappears as a substring of a validsnake_caseidentifier.
- Why must
verify_lifo_unwind()verifytr->released_count == tr->acquired_countbefore looping overreleased_ids?
- *Hint 1:* What happens if 4 resources were acquired (
0..3) and only3, 2were released before returning-ENOMEM? - *Hint 2:* Checking only the prefix loop
0 .. released_count - 1would pass3, 2even though resources1and0leaked 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) becauseunsigned longis64bits onx86_64(LP64) and32bits onARMv7-A(ILP32). - Typed
constvalues,enumconstants, andstatic inlinefunctions are preferred over#definemacros 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 indo { ... } while (0)without a trailing semicolon. - Macros must never hide control-flow exits (
return,goto,break) because invisible jumps bypass caller spinlocks and centralizedgotocleanup spines.