Lab 4: Mixed-Endian Boot Image Packing — Little-Endian IVT vs Big-Endian DCD

35 minfree previewLinux 6.12C11U-Boot 2025.x← module 4

Implement, compile, and verify lab_m04_ivt_dcd_image against ./check.sh.

Prerequisites in this module

What ./check.sh verifies

  • Strict C11 build and trusted grader link.
  • Repair the C11 build before testing behavior.
  • Serializes known IVT header bytes and runtime pointers.
  • Validates compact file and media geometry independently.
step 1/15

step 1/15 · inspect starter files and specification

An i.MX6ULL SD/eMMC boot image silently refuses to boot -- emitting zero characters on UART1 and falling straight into the USB Serial Downloader -- whenever a custom host packer mixes up the two byte orders mandated by the internal Boot ROM: 32-bit addresses inside the Image Vector Table (IVT) and Boot Data structure are little-endian (ARMv7-A memory words), whereas the 4-byte IVT/DCD tag headers (D1 00 20 40, D2 xx xx 40) and every DCD address/value operand are big-endian! In this laboratory, you will diagnose a byte-order reversal inside starter/core.c, validate DCD command-stream bounds (1768 B max), and pack a 0x0C10-byte .imx fixture under TAP version 13.

learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04ls -lastarter/Makefilestarter/core.cstarter/core.hstarter/main.clearner@ksa:~/gl-e01/lab-m04
starter: starter/Makefile
learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat starter/Makefile File: starter/Makefile    CC = gcc    AR = ar    override CFLAGS += -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP    all: libbsp.a bsp_demo    libbsp.a: core.o    	$(AR) rcs $@ $^    bsp_demo: main.o libbsp.a    	$(CC) $(CFLAGS) main.o libbsp.a -o $@    %.o: %.c core.h    	$(CC) $(CFLAGS) -c $< -o $@    -include core.d main.d    .PHONY: all clean    clean:    	rm -f core.o main.o core.d main.d libbsp.a bsp_demo
starter: starter/core.c
learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat starter/core.c File: starter/core.c    #include "core.h"    #include <string.h>    void put_le32(unsigned char *p, uint32_t value)    {        for (unsigned i=0U;i<4U;++i) p[i]=(unsigned char)(value>>(8U*(3U-i)));    }    uint32_t get_le32(const unsigned char *p)    {        return (uint32_t)p[0]|((uint32_t)p[1]<<8)|            ((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);    }    static unsigned be16(const unsigned char *p)    {        return ((unsigned)p[0]<<8)|p[1];    }    bool dcd_valid(const unsigned char *p, size_t n)    {        if (n<4U || p[0]!=0xd2U || p[3]!=0x40U) return false;        size_t total=be16(p+1);        if (total<4U || total>n || total>1768U) return false;        size_t at=4U;        while (at<total) {            if (total-at<4U) return false;            size_t len=be16(p+at+1);            if (len<4U || len>total-at) return false;            unsigned tag=p[at], param=p[at+3U];            bool w=tag==0xccU && param==4U && len>=12U && (len-4U)%8U==0U;            bool c=tag==0xcfU && param==0x0cU && len==16U;            bool nop=tag==0xc0U && param==0U && len==4U;            if (!w && !c && !nop) return false;            at+=len;        }        return at==total;    }    bool pack_image(unsigned char *out, size_t capacity)    {        if (capacity<0xc10U) return false;        memset(out,0,0xc10U);        out[0]=0xd1U; out[2]=0x20U; out[3]=0x40U;        put_le32(out+4,0x87800000U);        put_le32(out+16,0x877ff420U); put_le32(out+20,0x877ff400U);        put_le32(out+32,0x877ff000U); put_le32(out+36,0x1010U);        memcpy(out+0xc00,"FORMAT-FIXTURE!!",16U);        return true;    }
starter: starter/core.h
learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat starter/core.h File: starter/core.h    #ifndef GL_E01_CORE_H    #define GL_E01_CORE_H    #include <stdbool.h>    #include <stddef.h>    #include <stdint.h>    void put_le32(unsigned char *p, uint32_t value);    uint32_t get_le32(const unsigned char *p);    bool dcd_valid(const unsigned char *p, size_t n);    bool pack_image(unsigned char *out, size_t capacity);    #endif
starter: starter/main.c
learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat starter/main.c File: starter/main.c    #include "core.h"    #include <stdio.h>    int main(void) { puts("GL-E01 BSP laboratory: run ../check.sh for graded evidence"); return 0; }

step 2/15 · 2. learning objectives

  1. Serialize and parse 32-bit little-endian IVT and Boot Data pointers (entry = 0x87800000, boot_data = 0x877FF420, self = 0x877FF400, start = 0x877FF000, length = 0x1010) without host-alignment traps.
  2. Validate big-endian DCD blocks (0xD2 header, 16-bit total length <= 1768 B, 0xCC Write Data, 0xCF Check Data, and 0xC0 NOP subcommands) in dcd_valid().
  3. Reconcile compact .imx file offsets (IVT at 0x0000, payload at 0x0C00) with raw SD/eMMC card geometry (0x0400 LBA 2 leading gap -> payload at 0x1000 in target RAM).
  4. Preserve caller output buffers untouched when pack_image() rejects insufficient capacity < 0x0C10U.

step 3/15 · 3. environment requirements

  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) inside labs/lab_m04_ivt_dcd_image/.
  • Target Boot ROM Contract: Matches i.MX6ULL Boot ROM v0x40 IVT (32 bytes), Boot Data (12 bytes), DCD (<= 1768 bytes, big-endian byte stream), and SD/eMMC 1 KiB (0x400) offset rules.

step 4/15 · 4. required software & hardware

  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils / hex tools (nm, od or hexdump).
  • Hardware: Standard Linux workstation (0 SD cards or physical Cortex-A7 boards required; dd seek=2 bs=512 applies only when flashing real removable media).

step 5/15 · 5. complete executable commands

Execute the commands below from labs/lab_m04_ivt_dcd_image/ to reproduce starter/ failing checks 2 and 3, inspect the byte-swapped IVT bytes, rebuild files/libbsp.a, and verify 5/5 TAP checks:

learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat script.sh File: script.sh    # 1. Grade starter/ in a temporary sandbox to observe checks 2 and 3 fail (# pass 3/5)    TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP"        # 2. Dump the first 40 bytes packed by starter/ vs files/ to see the endianness mismatch at byte +4    TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter -x c - starter/core.c -o "$TMP/dump" <<'EOF' && "$TMP/dump" ; rm -rf "$TMP"    #include "core.h"    #include <stdio.h>    int main(void) {        unsigned char b[0xc10]; pack_image(b, sizeof b);        printf("starter IVT[0..7]=%02X_%02X_%02X_%02X  entry=%02X_%02X_%02X_%02X (get_le32=0x%08X)\n",               b[0],b[1],b[2],b[3], b[4],b[5],b[6],b[7], get_le32(b+4));        return 0;    }    EOF        # 3. Build the repaired archive files/libbsp.a and inspect exported symbols    make -B -C files    nm -g --defined-only files/libbsp.a        # 4. Run the authoritative 5-check TAP version 13 harness    sh check.sh

*Why each step runs:* Step 1 reproduces failing_tap safely in $TMP; Step 2 prints the exact serialized bytes 87_80_00_00 (get_le32 = 0x00008087) emitted by starter/core.c; Step 3 compiles files/libbsp.a cleanly under -Werror; and Step 4 verifies all 5 TAP checks exit 0.

step 6/15 · 6. annotated source code (`starter/core.c` defect vs `files/core.c` fix)

  • Seeded Flaw in starter/core.c:3-6 (put_le32): starter writes p[i] = (unsigned char)(value >> (8U * (3U - i))); -- serializing most-significant byte first (big-endian) while get_le32() (lines 7-11) reconstructs p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24) (little-endian)!
  • Verified Repair in files/core.c:3-6: Changes the shift to p[i] = (unsigned char)(value >> (8U * i)); so 0x87800000U writes [0x00, 0x00, 0x80, 0x87] at out + 4, 0x877ff420U at out + 16 (boot_data), 0x877ff400U at out + 20 (self), 0x877ff000U at out + 32 (Boot Data.start), and 0x1010U at out + 36 (Boot Data.length).
  • dcd_valid (core.c:16-34): Verifies p[0] == 0xd2U && p[3] == 0x40U and big-endian total = be16(p + 1) in [4, 1768] and <= n, then walks every command record checking subtraction bound len <= total - at and legal command shapes: Write Data (0xcc, param == 4, len >= 12, (len - 4) % 8 == 0), Check Data (0xcf, param == 0x0c, len == 16), or NOP (0xc0, param == 0, len == 4).
  • pack_image (core.c:35-44): Rejects capacity < 0xc10U before memset(out, 0, 0xc10U), writes IVT header bytes [0xd1, 0x00, 0x20, 0x40] directly at out[0..3], populates IVT and Boot Data pointers, and places the 16-byte "FORMAT-FIXTURE!!" payload at out + 0xc00 (self + 0xc00 = 0x87800000).

step 7/15 · 7. expected tap-13 output

learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat listing.txt File: listing.txt    # Unmodified starter/ baseline (exits non-zero: # pass 3/5)    TAP version 13    1..5    ok 1 - strict C11 build and trusted grader link    not ok 2 - serializes known IVT header bytes and runtime pointers      ---      message: 'Behavior differs from the independently specified test vectors'      hint: 'Repair case 1; inspect tests.c for the exact input and expected result'      ...    not ok 3 - validates compact file and media geometry independently      ---      message: 'Behavior differs from the independently specified test vectors'      hint: 'Repair case 2; inspect tests.c for the exact input and expected result'      ...    ok 4 - accepts the supported DCD command fixture and rejects malformed input    ok 5 - rejects insufficient output capacity without modifying the destination    # pass 3/5        # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5)    TAP version 13    1..5    ok 1 - strict C11 build and trusted grader link    ok 2 - serializes known IVT header bytes and runtime pointers    ok 3 - validates compact file and media geometry independently    ok 4 - accepts the supported DCD command fixture and rejects malformed input    ok 5 - rejects insufficient output capacity without modifying the destination    # pass 5/5

step 8/15 · 8. explanation of observed behavior

Notice why starter/ passes check 4 (ok 4) and check 5 (ok 5) while failing checks 2 and 3: dcd_valid() uses be16() on big-endian DCD bytes and never calls put_le32(), and pack_image(image, sizeof image - 1U) returns false on line 37 before calling put_le32(). In check 2 (tests.c case 1), image[0..3] (D1 00 20 40) passes line 12 because pack_image() wrote those four header bytes directly, then get_le32(image + 4) == 0x87800000U aborts on line 13 (0x00008087U != 0x87800000U). In check 3 (tests.c case 2), Boot Data.start at image + 32 (0x00f07f87U) aborts line 19. Fixing put_le32() resolves both checks (# pass 5/5).

step 9/15 · 9. experiment variations

  1. Zero-Length DCD Subcommand Infinite-Loop Trap: Remove len < 4U on core.c:25 in a scratch copy and run tests.c case 3 (which mutates d[6] = 0U at line 29 so be16(p + 5) == 0): without len >= 4U, at += 0 spins forever inside while (at < total)!
  2. ROM 1768-Byte DCD Ceiling Breach: Construct an otherwise valid 1772-byte DCD buffer (0xD2, 0x06, 0xEC, 0x40 + 442 NOP records) and confirm dcd_valid() rejects total > 1768U just as the i.MX6ULL Boot ROM does.
  3. Host Unaligned-Pointer Cast vs Bytewise put_le32: Compile tests.c and files/core.c with -fsanitize=undefined,address and verify bytewise put_le32(p + 1, ...) never triggers an unaligned uint32_t * store fault.

step 10/15 · 10. performance measurements

Measured on Linux 7.0.0-42-generic (x86_64) using CLOCK_MONOTONIC across 5 warmup runs and 35 timed samples:

Workload Measured (N = 35, warmup = 5)Host p50Host p95Host p99Cortex-A7 / Boot ROM Context
Full sh check.sh (make -B + gcc link + 4 cases)136.50 ms156.61 ms160.90 msHost build & test-runner latency
verify 4-case .imx / DCD suite (verify 1..4)3530.6 us4584.0 us5507.5 usHost validation of 3088 B .imx + 36 B DCD
Boot ROM SD read of 4112 B (~9 sectors @ 25 MHz)Modeled in RAMModeled in RAMModeled in RAM~350 - 900 us SPI/SDHC transfer + DCD MMIO writes

step 11/15 · 11. troubleshooting

SymptomRoot CauseFix
not ok 2 & not ok 3 (get_le32 reads byte-reversed addresses)put_le32() shifts by 8U * (3U - i) (big-endian)Shift by 8U * i so p[0] holds LSB and p[3] holds MSB
IVT word reads 0xD1002040 instead of 0x402000D1 in ARM RAMWrote 0x402000D1 with big-endian byte order [0x40, 0x20, 0x00, 0xD1]Emit bytes [0xD1, 0x00, 0x20, 0x40] (put_le32(out, 0x402000D1U))
verify 3 hangs when d[6] = 0Udcd_valid() accepted len == 0U and failed to advance atEnforce `if (len < 4U \\len > total - at) return false;`
.imx written at byte 0 of SD card wipes MBR & fails bootConfused compact .imx (starts at 0x400) with full disk imageFlash .imx with dd bs=512 seek=2 conv=fsync (1024-byte offset)

step 12/15 · 12. guided questions

  1. Why does pack_image() store length = 0x1010U (sizeof image + 0x400U) inside Boot Data at out + 36 even though the .imx buffer itself is only 0x0C10U (3088) bytes long?
  • *Hint 1:* Compute self - start (0x877FF400 - 0x877FF000 = 0x400) and inspect where byte 0 of the SD/eMMC card lands in target DDR when the Boot ROM copies from LBA 0.
  • *Hint 2:* Add the 0x400-byte leading media gap (LBA 0..1) to the 0x0C00-byte IVT-to-entry span (0x87800000 - 0x877FF400) plus the 0x10-byte payload (0x400 + 0xC00 + 0x10).
  1. Why do put_le32() and get_le32() operate on unsigned char * byte-by-byte instead of casting *(uint32_t *)p = value?
  • *Hint 1:* Check ISO C11 strict-aliasing rules (Section 6.5p7) and arbitrary caller buffer alignment (p need not be 4-byte aligned).
  • *Hint 2:* What would *(uint32_t *)p = value emit if the host packer were compiled on a big-endian build server?

step 13/15 · 13. independent challenges

  1. Near Transfer — Embedded DCD Pointer Integration (pack_image_with_dcd): Write bool pack_image_with_dcd(unsigned char *out, size_t cap, const unsigned char *dcd, size_t dcd_len) that validates dcd via dcd_valid(), places dcd at out + 0x40 (0x877FF440 in RAM, safely clear of IVT [0x00..0x1F] and Boot Data [0x20..0x2B]), and writes 0x877FF440U into IVT.dcd (out + 8) only when dcd != NULL.
  2. Far Transfer — .imx Binary Dissector & Consistency Auditor: Build a standalone C11 tool that reads a packed .imx image and checks IVT header D1 00 20 40, self > start, boot_data == self + 0x20, dcd == 0 || dcd_valid(...), and entry >= self + 0x40 && entry < start + length.

step 14/15 · 14. solutions & explanations

  • Guided Question 1: Boot Data.start (0x877FF000) represents the destination of byte 0 of the boot medium (0x400 bytes below IVT.self = 0x877FF400), so Boot Data.length must cover the initial 0x400 media offset plus the entire .imx file (0x0C10), totaling 0x1010 bytes (end = 0x87800010).
  • Guided Question 2: Bytewise shifts on unsigned char * are 100% portable across little-endian and big-endian hosts and immune to both unaligned-pointer traps and C11 strict-aliasing undefined behavior.
  • Challenge 1 Guard: Ensure 0x40U + dcd_len <= 0x0C00U (dcd_len <= 3008U, already tighter via dcd_valid's 1768U cap) before memcpy(out + 0x40, dcd, dcd_len) and put_le32(out + 8, 0x877ff440U).

step 15/15 · run verification and inspect output

Run the verification command and confirm the output matches the expected contract.

learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04./check.shlearner@ksa:~/gl-e01/lab-m04
expected output
TAP version 131..5ok 1 - strict C11 build and trusted grader link

Progressive hints & solution

hint 1

Compare starter/Makefile against the module lessons. Focus first on: Strict C11 build and trusted grader link.

hint 2

Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.

solution

Run the check

From labs/lab_m04_ivt_dcd_image/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m04
learner@ksa:~/gl-e01/lab-m04./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linkok 2 - serializes known IVT header bytes and runtime pointersok 3 - validates compact file and media geometry independentlyok 4 - accepts the supported DCD command fixture and rejects malformed inputok 5 - rejects insufficient output capacity without modifying the destination# pass 5/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m04 (starter)
learner@ksa:~/gl-e01/lab-m04./check.shTAP version 131..5ok 1 - strict C11 build and trusted grader linknot ok 2 - serializes known IVT header bytes and runtime pointers  ---  message: 'Behavior differs from the independently specified test vectors'  hint: 'Repair case 1; inspect tests.c for the exact input and expected result'  ...not ok 3 - validates compact file and media geometry independently  ---  message: 'Behavior differs from the independently specified test vectors'  hint: 'Repair case 2; inspect tests.c for the exact input and expected result'  ...ok 4 - accepts the supported DCD command fixture and rejects malformed inputok 5 - rejects insufficient output capacity without modifying the destination# pass 3/5

note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....

inspect harness: check.sh
learner@ksa: ~/gl-e01/lab-m04
learner@ksa:~/gl-e01/lab-m04$ bat check.sh File: check.sh    #!/bin/sh    set -u    cd "$(dirname "$0")" || exit 1    PASS=0    WORK=$(mktemp -d "./.check.XXXXXX") || exit 1    trap 'rm -rf "$WORK"' EXIT HUP INT TERM    printf 'TAP version 13\n1..5\n'    if make -B -C files >"$WORK/build.log" 2>&1 &&       gcc -std=c11 -Wall -Wextra -Werror -pedantic -Ifiles tests.c files/libbsp.a -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then        printf 'ok 1 - strict C11 build and trusted grader link\n'        PASS=$((PASS + 1))    else        printf 'not ok 1 - strict C11 build and trusted grader link\n'        printf "  ---\n  message: 'Compilation failed'\n  hint: 'Fix the C11 diagnostics in files and preserve the exported ABI'\n  ...\n"        printf 'FAIL: repair the C11 build before testing behavior\n' >&2    fi    if [ -x "$WORK/verify" ] && "$WORK/verify" 1 >"$WORK/case2.log" 2>&1; then        printf 'ok 2 - serializes known IVT header bytes and runtime pointers\n'        PASS=$((PASS + 1))    else        printf 'not ok 2 - serializes known IVT header bytes and runtime pointers\n'        printf "  ---\n  message: 'Behavior differs from the independently specified test vectors'\n  hint: 'Repair case 1; inspect tests.c for the exact input and expected result'\n  ...\n"    fi    if [ -x "$WORK/verify" ] && "$WORK/verify" 2 >"$WORK/case3.log" 2>&1; then        printf 'ok 3 - validates compact file and media geometry independently\n'        PASS=$((PASS + 1))    else        printf 'not ok 3 - validates compact file and media geometry independently\n'        printf "  ---\n  message: 'Behavior differs from the independently specified test vectors'\n  hint: 'Repair case 2; inspect tests.c for the exact input and expected result'\n  ...\n"    fi    if [ -x "$WORK/verify" ] && "$WORK/verify" 3 >"$WORK/case4.log" 2>&1; then        printf 'ok 4 - accepts the supported DCD command fixture and rejects malformed input\n'        PASS=$((PASS + 1))    else        printf 'not ok 4 - accepts the supported DCD command fixture and rejects malformed input\n'        printf "  ---\n  message: 'Behavior differs from the independently specified test vectors'\n  hint: 'Repair case 3; inspect tests.c for the exact input and expected result'\n  ...\n"    fi    if [ -x "$WORK/verify" ] && "$WORK/verify" 4 >"$WORK/case5.log" 2>&1; then        printf 'ok 5 - rejects insufficient output capacity without modifying the destination\n'        PASS=$((PASS + 1))    else        printf 'not ok 5 - rejects insufficient output capacity without modifying the destination\n'        printf "  ---\n  message: 'Behavior differs from the independently specified test vectors'\n  hint: 'Repair case 4; inspect tests.c for the exact input and expected result'\n  ...\n"    fi    printf '# pass %d/5\n' "$PASS"    [ "$PASS" -eq 5 ]

Definition of done

Verification checklist

status: 0/3 checks verified

Troubleshooting

Compiler fails under -Werror on sign conversion or unused args

Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.

./check.sh reports missing files in files/

Invoke ./check.sh from inside labs/lab_m04_ivt_dcd_image/ so relative paths to files/ resolve directly.

Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure