GCC Pipeline, Make & POSIX Types

Signed integer overflow checks silently deleted at -O2, strlen() truncating binary frames at 0x00, unsigned size_t wraparound on -1 errors, and decimal 644 permission literals cause catastrophic C bugs. You will master the four-stage GCC/ar pipeline, feature-test macros, POSIX boundary types, and ISO C11 Undefined Behavior defenses.

20 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Build multi-file ISO C11 targets across GCC stages (-E, -S, -c, ar rcs, link) with -Wall -Wextra -Werror.
  • Configure _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 before headers using man 2 and man 3 interface contracts.
  • Audit C11 code for Undefined Behavior, -fno-common collisions, size_t/ssize_t wraparound, and octal 0644 bugs.

Why Sloppy C Types and Opaque Builds Break Systems Software

Consider a network packet validator written as if (payload_len + 16 < payload_len) return -1; where payload_len is a signed int, paired with size_t n = read(fd, buf, cap); and open(path, O_CREAT | O_WRONLY, 644). Under -O0 unit tests on small ASCII inputs, every line appears to work. Under -O2 in production, GCC deletes the signed-overflow check completely—allowing an attacker passing INT_MAX - 4 to allocate a 12-byte heap buffer for a 2 GiB copy—while a -1 read() failure wraps unsigned size_t n to 18,446,744,073,709,551,615 (SIZE_MAX), and decimal 644 stamps sticky bit 01204 (--w----r-T) onto disk!

Naive C habits fail because developers conflate hardware assembly behavior with the abstract machine specified by ISO/IEC 9899:2011 (ISO C11), rely on IDE build buttons that hide linker flags and archive ordering, and guess header contracts instead of reading manual sections. Writing reliable Ring 3 systems code requires deterministic command-line builds, exact POSIX boundary types, and zero tolerance for Undefined Behavior (UB).

note: Think of a precision machine shop with an assembly blueprint, calipers calibrated in millimeters versus signed tolerances, and standardized part bins. Reading the wrong scale or skipping the torque specification produces parts that look close on the bench and shear under load.

Where it stops working: Unlike physical tolerances that degrade gradually, mixing unsigned size_t with signed ssize_t -1 or decimal 644 with octal 0644 flips exact bits instantaneously.

definition (Four-Stage GCC Pipeline, Feature Macros & C11 UB): Four-Stage Translation Pipeline & Tentative Definitions: Originating in early Unix cpp -> cc1 -> as -> ld passes, GCC lowers ISO C11 source across preprocessing (-E -> .i), compilation (-S -> .s), assembly (-c -> relocatable Executable and Linkable Format .o), and linking (ar rcs static .a archives or -fPIC -shared .so objects). Feature-Test Macros (_POSIX_C_SOURCE, named by IEEE 1003.1 to gate namespace exposure) unlock POSIX declarations above ISO C11, while Undefined Behavior (UB, C11 §3.4.3) designates operations—such as signed overflow or strict-aliasing violations—for which the standard imposes zero requirements.

Across Stage 3 (gcc -c), the assembler partitions each relocatable .o file into distinct ELF sections: .text (machine instructions), .rodata (string literals and const tables), .data (initialized globals), .bss (Block Started by Symbol: zero-initialized globals occupying zero on-disk bytes), and .symtab + .rela.text relocation records. In ISO C11, writing int g_status; at file scope without extern is a tentative definition; GCC 10+ enables -fno-common by default, emitting a strong .bss definition in every .o that includes such a header and failing at link time with multiple definition. Declare extern int g_status; in .h headers, define it once in one .c file, and mark file-private helpers static (STB_LOCAL in nm / readelf -sW). Furthermore, the GNU linker resolves static .a archives in a single left-to-right pass, so gcc main.o -L. -lsysbuf succeeds whereas gcc -L. -lsysbuf main.o leaves main.o's symbols unresolved!

Struct layout and boundary sizing obey exact binary alignment arithmetic. Every scalar type of alignment A = 2^k bytes must start at a byte offset O satisfying O_aligned = (O + A - 1) & ~(A - 1). Inside struct padded_hdr { uint8_t tag; uint32_t seq; uint16_t flags; }, tag occupies byte 0, seq (A = 4) rounds offset 1 up to (1 + 3) & ~3 = 4 (inserting 3 padding bytes [1..3]), flags (A = 2) lands at byte 8, and total sizeof(struct padded_hdr) rounds 10 up to a multiple of max(A) = 4, yielding 12 bytes! Likewise, decimal 644 equals 512 + 128 + 4 = 01204 in octal, whereas octal 0644 equals 6 * 64 + 4 * 8 + 4 * 1 = 420 in base 10 (rw-r--r--).

Type / CategoryC11 / POSIX SpecificationExact Bit / Sign Contract & Engineering Rule
size_t / ssize_tUnsigned capacity vs signed returnsize_t (%zu) sizes buffers; ssize_t (%zd) holds 0..SSIZE_MAX or -1 error
off_t (_FILE_OFFSET_BITS=64)Signed 64-bit byte coordinateAddresses up to 2^63 - 1 (8 EiB) on both 64-bit x86-64 and 32-bit ARMv7
mode_t & uint8_tOctal permission mask & raw byteWrite leading-zero 0644 (never 644); pass (const uint8_t *, len), never strlen()
man 1 / man 2 / man 3Linux manual sections1 shell utilities, 2 Linux kernel syscalls, 3 glibc library functions
Implementation-DefinedDocumented target ABI choicePlain char is unsigned [0..255] on ARMv7 EABI vs signed [-128..127] on x86-64
Undefined Behavior (UB)Unreachable on valid pathsSigned overflow (a + b < a folded to 0 at -O2), shift >= width, -fstrict-aliasing casts
fig_m01_l02_arch.svg — Four-stage GCC/archive builds, struct padded_hdr…

Figure 1.2. Four-stage GCC/archive builds, struct padded_hdr byte-alignment math, and signed/unsigned POSIX boundary contracts.

step_m01_l02.svg — Feature-test macros, strict C11 warning/sanitizer…step 1/4
  1. Step 1. Stage 1 (-E) — Define _POSIX_C_SOURCE and _FILE_OFFSET_BITS=64 on lines 1..2 before any header is included.
  2. Step 2. Stage 2 (-S -O2) — Compile strict C11 to assembly; use unsigned subtraction so -O2 never deletes signed-overflow guards.
  3. Step 3. Stage 3 (-c & ar rcs) — Emit ELF .text/.rodata/.data/.bss sections under -fno-common and index static .a archives.
  4. Step 4. Stage 4 (ld + ASan/UBSan) — Place -lsysbuf after caller .o files and gate CI with -fsanitize=address,undefined.

Figure 1.2b. Feature-test macros, strict C11 warning/sanitizer flags, and single-pass archive link ordering eliminate silent type and symbol bugs at build time.

Feature-Test Macros,Incremental Make & Sanitizer Flags

Under strict -std=c11, GCC defines __STRICT_ANSI__ and hides POSIX symbols (fileno, pread, fdatasync, strnlen) inside <stdio.h> and <unistd.h> unless #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 appear before the very first #include in every translation unit. Pair -Wall -Wextra -Werror with -MMD -MP in GNU Make so header edits trigger automatic rebuilds, and run CI tests under AddressSanitizer and UndefinedBehaviorSanitizer (-fsanitize=address,undefined -fno-omit-frame-pointer).

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02$ bat -H 2 -H 9 -H 12 Makefile File: Makefile    CC     := gcc  CFLAGS := -std=c11 -Wall -Wextra -Werror -MMD -MP -g -O2    SAN    := -fsanitize=address,undefined -fno-omit-frame-pointer        .PHONY: all sanitize clean    all: inspector        libsysbuf.a: sysbuf.o  	ar rcs $@ $^        inspector: inspector.o libsysbuf.a  	$(CC) $(CFLAGS) inspector.o -L. -lsysbuf -o $@        sanitize: sysbuf.c inspector.c    	$(CC) $(CFLAGS) $(SAN) inspector.c sysbuf.c -o inspector_san        -include *.d    clean:    	rm -f *.o *.d *.a inspector inspector_san
  1. -MMD -MP emits .d header dependency rules so editing a .h struct layout rebuilds affected .o files automatically.
  2. ar rcs creates static archive libsysbuf.a and writes the symbol index table required by ld.
  3. Place -lsysbuf AFTER inspector.o so the single-pass linker resolves inspector.o's undefined references.

Auditing Binary Frames, Struct Padding, Strict Aliasing & Octal Modes

Save type_bridge.c below. It proves seven foundational systems C contracts in one sanitizer-clean binary: sizeof(raw_frame) (16) vs strlen() truncating at embedded 0x00 (2), array-to-pointer decay (sizeof(buf_ptr) == sizeof(void *)), unsigned subtraction capacity checks (safe_frame_fits), 64-bit off_t, octal 0644 (420) vs decimal 644 (01204), offsetof()/alignof() padding math, and -fstrict-aliasing-safe float -> uint32_t bit extraction via memcpy() (compiled to a single register move at -O2).

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02$ bat -H 1 -H 2 -H 23 -H 29 type_bridge.c File: type_bridge.c  #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <stdalign.h>    #include <stddef.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <sys/types.h>        struct padded_hdr {        uint8_t tag;        uint32_t seq;        uint16_t flags;    };        static size_t pointer_sizeof(const uint8_t *buf_ptr) {        return sizeof(buf_ptr);    }        static uint32_t pun_float_bits(float v) {      uint32_t bits = 0U;        memcpy(&bits, &v, sizeof(bits));        return bits;    }        static int safe_frame_fits(size_t payload, size_t hdr_sz, size_t cap) {      return (hdr_sz <= cap) && (payload <= cap - hdr_sz);    }        int main(void) {        const uint8_t raw_frame[16] = {            0x4BU, 0x53U, 0x00U, 0x41U, 0x10U, 0x20U, 0x30U, 0x40U        };        size_t arr_bytes = sizeof(raw_frame);        size_t cstr_len = strlen((const char *)raw_frame);        size_t ptr_bytes = pointer_sizeof(raw_frame);        mode_t oct_mode = 0644;        mode_t dec_bug = 644;        uint32_t fbits = pun_float_bits(1.0f);        int ovf_rejected = !safe_frame_fits(SIZE_MAX - 4U, 12U, 4096U);            printf("arr_sizeof=%zu strlen_at_nul=%zu ptr_decayed=%d ovf_guard=%d\n",               arr_bytes, cstr_len,               ptr_bytes != arr_bytes && ptr_bytes == sizeof(void *),               ovf_rejected);        printf("ssize_signed=%d off_bits=%zu oct_0644=%u dec_644_oct=0%o\n",               (ssize_t)-1 < 0, sizeof(off_t) * 8U,               (unsigned int)oct_mode, (unsigned int)dec_bug);        printf("hdr_sz=%zu seq_off=%zu align=%zu f32_hex=0x%08x\n",               sizeof(struct padded_hdr), offsetof(struct padded_hdr, seq),               alignof(struct padded_hdr), fbits);        return EXIT_SUCCESS;    }
  1. Feature-test macros MUST precede every #include so <features.h> exposes 64-bit off_t and POSIX.1-2008 prototypes.
  2. memcpy(&bits, &v, sizeof(bits)) extracts IEEE-754 bits legally under C11 -fstrict-aliasing and compiles to zero memory traffic at -O2.
  3. Unsigned subtraction cap - hdr_sz avoids signed integer overflow UB that GCC -O2 would fold away.

Stepping Through All Four GCC Stages, nm & Sanitizers

Execute all four GCC translation stages (-E, -S, -c, and final link with -fsanitize=address,undefined), inspect symbol visibility in type_bridge.o with nm (t local static helpers vs T global main), and verify ./type_bridge.

learner@ksa: ~/gl-c01/m01-l02
learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -E type_bridge.c -o type_bridge.ilearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -S type_bridge.c -o type_bridge.slearner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -c type_bridge.c -o type_bridge.olearner@ksa:~/gl-c01/m01-l02nm type_bridge.o | grep -c ' T main$'1learner@ksa:~/gl-c01/m01-l02gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror -fsanitize=address,undefined type_bridge.c -o type_bridgelearner@ksa:~/gl-c01/m01-l02./type_bridge && rm -f type_bridge.i type_bridge.s type_bridge.o type_bridgearr_sizeof=16 strlen_at_nul=2 ptr_decayed=1 ovf_guard=1ssize_signed=1 off_bits=64 oct_0644=420 dec_644_oct=01204hdr_sz=12 seq_off=4 align=4 f32_hex=0x3f800000learner@ksa:~/gl-c01/m01-l02

Why Strict Types, Visibility & Sanitizers Catch Silent Corruption

Stepping across .i -> .s -> .o -> ELF proved each layer's contract empirically. In type_bridge.o, nm reported main as T (STB_GLOBAL in .text) while static helpers stayed module-private so they cannot collide across .o files. At runtime under ASan + UBSan, raw_frame occupied 16 stack bytes while strlen() stopped at raw_frame[2] == 0x00 (2), pointer_sizeof() confirmed array-to-pointer decay (8 bytes on 64-bit), struct padded_hdr measured 12 bytes (seq_off=4, align=4), safe_frame_fits() blocked SIZE_MAX - 4U + 12U wraparound without UB, and memcpy() extracted 0x3f800000 (1.0f) cleanly.

Guided Practice: Reordering Struct Fields & Fixing Aliasing UB

Examine struct padded_hdr (12 bytes: uint8_t tag; uint32_t seq; uint16_t flags;) and the broken strict-aliasing cast uint32_t bad = *(uint32_t *)&float_val;:

  1. Step 1 (Eliminate internal padding): Reorder the three members of struct padded_hdr from largest alignment (uint32_t) to smallest (uint8_t) without adding non-portable __attribute__((packed)) (which causes unaligned bus faults on strict ARM hardware), and compute the new sizeof(struct compact_hdr) (8 bytes) using the alignment formula above.
  2. Step 2 (Verify with _Static_assert): Add _Static_assert(sizeof(struct compact_hdr) == 8, "compact layout"); in a local copy of type_bridge.c, replace any pointer-cast punning with memcpy(), and confirm gcc -std=c11 -O2 -Wall -Wextra -Werror exits 0.

Create three files (frame.h, frame.c, driver_cli.c) where frame.h declares extern size_t g_frames_encoded; and size_t encode_u32_be(uint8_t *dst, size_t cap, uint32_t val); (writing big-endian bytes via unsigned shifts val >> 24, (val >> 16) & 0xFFU, etc.). Archive frame.o into libframe.a via ar rcs, confirm nm -g libframe.a lists encode_u32_be and g_frames_encoded, verify that wrong link order (gcc -L. -lframe driver_cli.o) fails while gcc driver_cli.o -L. -lframe succeeds, and run under -fsanitize=address,undefined.

Common Production Pitfalls

warning: Symptom: GCC rejects fileno(), pread(), or strnlen() with implicit declaration of function under -std=c11 -Werror even though #define _POSIX_C_SOURCE 200809L is present in the .c file. Root Cause: A project header (such as #include "config.h") included <stdio.h> above the #define, freezing <features.h> in strict ISO C11 mode for the rest of the translation unit. Fix: Place #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64 on lines 1–2 of every .c file (or pass -D_POSIX_C_SOURCE=200809L -D_FILE_OFFSET_BITS=64 in CFLAGS).

warning: Symptom: A length guard if (signed_len + hdr_sz < signed_len) return -1; passes -Wall -Wextra cleanly yet allows heap corruption at -O2, or int status; inside common.h triggers multiple definition of 'status' on GCC 13. Root Cause: Signed integer overflow is ISO C11 Undefined Behavior so -O2 folds a + 16 < a to false, and GCC 10+ defaults to -fno-common so tentative definitions in headers emit colliding .bss globals. Fix: Validate capacities via unsigned size_t subtraction (if (len > cap - hdr_sz)), and declare extern int status; in headers with exactly one .c definition.

Knowledge Check

quiz · 1 of 4

You need the authoritative header requirements, return contract, and error codes for the Linux kernel write() system call rather than the user terminal messaging utility. Which command opens the right manual section?

quiz · 2 of 4

(Review from earlier lesson) Why does compiling with gcc -c sysbuf.c -o sysbuf.o succeed even when sysbuf.c defines Ring 3 helper functions without defining main()?

quiz · 3 of 4

What permission bitmask is produced in C if a developer writes mode_t m = 644; instead of mode_t m = 0644;?

quiz · 4 of 4

A packet parser validates int payload_len (>= 0) with if (payload_len + 16 < payload_len) return -1; before malloc((size_t)(payload_len + 16)). Why does gcc -std=c11 -O2 delete that guard when you review the generated .s assembly?

Key takeaways

  • Compile multi-file systems C projects explicitly across preprocessing (-E), compilation (-S), assembly (-c), archiving (ar rcs), and linking with -std=c11 -Wall -Wextra -Werror and -fsanitize=address,undefined.
  • Define feature-test macros (_POSIX_C_SOURCE 200809L, _FILE_OFFSET_BITS 64) before the very first #include, and use extern declarations in headers so GCC -fno-common never hits tentative-definition collisions.
  • Consult man 2 for Linux kernel syscalls and man 3 for glibc functions, verifying SYNOPSIS, RETURN VALUE, and ERRORS before writing callers.
  • Pair unsigned size_t capacities with signed ssize_t / off_t return checks, pass (const uint8_t *, len) for binary data, write octal 0644 permissions, and replace signed-overflow or pointer-aliasing UB with unsigned subtraction and memcpy().
  • Next, we will link C11 translation units against glibc (libc.so.6), trace dynamic .plt/.got.plt relocations and C Runtime (CRT) _start initialization, inspect errno, and count exact traps under strace.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure