DCD Commands and a Checked C11 .imx Packer
Solve the cold-boot chicken-and-egg problem with big-endian Device Configuration Data (DCD) command streams, enforce bounded parser invariants, and assemble a verified 3088-byte .imx container in ISO C11.
What you'll learn
- Encode big-endian DCD lengths, addresses, values, and masks.
- Reject truncated or zero-length Write, Check, and NOP commands.
- Construct a compact .imx artifact with independently checked IVT and payload offsets.
Solving the Cold-Boot Chicken-and-Egg Problem with DCD
Think through what happens on cold power-up when IVT.entry points to 0x87800000 in external DDR3 RAM. The i.MX6ULL Boot ROM wants to copy your firmware from SD sector 2+ into 0x877FF000..0x8780XXXX—yet external DDR3 is completely dead at reset until clock gates (CCM), pad drive strengths (IOMUXC), and Multi-Mode DDR Controller (MMDC) timing registers are programmed! Your _start code inside the payload cannot initialize DDR3, because _start itself has nowhere to be copied until DDR3 works! Firmware architectures solve this chicken-and-egg puzzle in one of two ways: either load a small U-Boot SPL into internal OCRAM (0x00908000) to train DDR3 in C, or attach a declarative Device Configuration Data (DCD) bytecode stream at IVT.dcd (0x877FF42C) that the Boot ROM interprets before copying the payload to DDR3.
Examine Figure 4.3a to see how DCD bytecode is framed—and why naive .imx packers break on their very first register write. Whereas IVT and Boot Data pointers (m04-l02) are little-endian 32-bit ARM words, every length, register address, data word, mask, and poll count inside DCD is strictly big-endian (BE16 / BE32)!
- Table Header (
0xD2):[0xD2, len_hi, len_lo, 0x40], where big-endiantotal_len(4 <= total_len <= 1768 B) includes the4-byte0xD2header itself. Write Data(0xCC):[0xCC, cmd_len_be16, param]followed byk >= 1big-endian(addr32, val_or_mask32)pairs (cmd_len = 4 + 8 * k). Inparam, bits[2:0]select access width (1,2, or4bytes) and bits[4:3]select plain write (00), clear-mask (01), or set-mask (10).Check Data(0xCF) &NOP(0xC0):0xCFpolls a status register (param = 0x0Cchecks(*addr & mask) == maskon4-byte width;cmd_len = 12unbounded or16with a big-endiancount32timeout), while0xC0is[0xC0, 0x00, 0x04, 0x00]. If a packer accidentally writes0x020C406C(CCM_CCGR1) withput_le32(), the ROM reads big-endian0x6C400C02—outside its permitted peripheral whitelist—and aborts straight intoUSBSerial Downloader!
Figure 4.3a. Inside the 36-byte big-endian stream (top), why put_le32() triggers silent ROM rejection (bottom left), and parser termination invariants (bottom right).
mental model: A DCD table is a pre-flight punch-card deck fed into the Boot ROM before the main engine (_start) starts: every card carries its own byte length and big-endian register coordinates, so one zero-length card or swapped endian helper derails every operation behind it.
Where it stops working: Unlike syntax-checking a punch card offline, proving that a DCD stream parses cleanly never proves that its register values match your PCB's DDR3 trace delays or voltage rails.
definition (Device Configuration Data (DCD) & Structural vs Electrical Validation): Device Configuration Data (DCD) is a bounded (<= 1768 B) big-endian Boot ROM command table (tag 0xD2, version 0x40) placed between Boot Data (0x002C in compact .imx) and the application payload (0x0C00), containing validated Write Data (0xCC), Check Data (0xCF), and NOP (0xC0) subcommands. Structural validity proves byte framing, big-endian encoding, and non-overlapping container offsets—it never proves that DDR3 timing or pad constants match an unmeasured physical board.
Trace the four-stage encoding, validation, and .imx packing pipeline below:
- Step 1. Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.
- Step 2. Step 2: Validate every CC, CF, and C0 subcommand length >= 4 and <= total - at before advancing the cursor.
- Step 3. Step 3: Assemble (0x00 LE), Boot Data (0x20 LE), DCD (0x2C BE), and payload (0x0C00) into verified.imx.
- Step 4. Step 4: Assert known raw byte vectors (02 0C 40 6C) and separate container-format proof from DDR3 calibration.
Figure 4.3b. Keep LE32 IVT pointers and BE16/BE32 DCD commands strictly separated, and never equate valid framing with calibrated DDR3 timing.
Linker Coordinates, Container Packing & Pre-Boot Trade-Offs
Inspect Figure 4.3b alongside image_layout.lds below to see how linker addresses and .imx file offsets lock together. In image_layout.lds, image_load_base = 0x877FF000 anchors medium byte 0x0000, . = image_load_base + 0x400 (0x877FF400) places .ivt and .dcd, and . = 0x87800000 places .text (KEEP(*(.text.start))), .rodata, and .data up to image_load_end. In the corresponding 3088-byte (0x0C10) verified.imx container, IVT (32 B), Boot Data (12 B), and our 36-byte DCD fixture occupy 0x000..0x04F, zero padding spans 0x050..0xBFF (0x002C + 36 = 0x0050 <= 0x0C00, proving zero metadata/payload overlap!), and the 16-byte fixture payload sits at 0x0C00..0x0C0F (BootData.length = 0x1010 = 4112 B).
Figure 4.3b. Exact byte map of verified.imx (3088 B) and the engineering boundary between structural container proof and board DDR3 calibration.
| Pre-Boot Initialization Strategy | Executed By | Size & Capability Limit | Operational Trade-Off |
|---|---|---|---|
Static DCD stream (0xD2) | Internal Boot ROM | <= 1768 B (<= 220 coalesced pairs); ROM whitelist only | Simple single-stage .imx; cannot probe RAM size or I2C PMICs |
U-Boot SPL in OCRAM | Cortex-A7 (0x00908000) | ~100 KiB OCRAM; full C11 control flow & UART logs | Production standard in U-Boot 2025.x; supports dynamic DDR3 training |
Unbounded Check Data (len = 12) | Internal Boot ROM | Polls *addr & mask forever with zero timeout | Wedges pre-console boot permanently if a PLL/PHY bit fails to lock |
Bounded Check Data (len = 16) | Internal Boot ROM | Polls up to big-endian count iterations | Aborts cleanly into SDP recovery when hardware readiness times out |
learner@ksa:~/gl-e01/m04-l03$ bat -H 4 -H 5 -H 6 -H 7 -H 8 image_layout.lds File: image_layout.lds ENTRY(_start) SECTIONS { image_load_base = 0x877ff000; . = image_load_base + 0x400; .ivt : { KEEP(*(.ivt)) } .dcd : { KEEP(*(.dcd)) } . = 0x87800000; .text : { KEEP(*(.text.start)) *(.text*) } .rodata ALIGN(4) : { *(.rodata*) } .data ALIGN(4) : { *(.data*) } image_load_end = .; .bss (NOLOAD) : { *(.bss*) *(COMMON) } }- Place .ivt and .dcd at image_load_base + 0x400 (0x877FF400), matching SD/eMMC LBA 2.
- Advance location counter to 0x87800000 (compact offset 0x0C00) and pin .text.start first with KEEP().
Implementing a Bounded DCD Validator & .imx Packer in ISO C11
Study valid_dcd() and main() in dcd_encoder_packer.c below. Before advancing at += len, the parser enforces len >= 4U && len <= total - at—preventing a malformed len == 0 command from spinning while (at < total) in an infinite loop and preventing truncated tails from reading past buffer bounds! Equally important, assert(dcd[8] == 0x02U && dcd[9] == 0x0cU && dcd[10] == 0x40U && dcd[11] == 0x6cU) checks the raw big-endian wire bytes directly so a symmetric endian bug in both encoder and decoder can never pass unnoticed.
learner@ksa:~/gl-e01/m04-l03$ bat -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 -H 36 -H 37 -H 38 -H 39 -H 55 -H 56 -H 57 -H 58 -H 59 -H 60 -H 61 -H 62 dcd_encoder_packer.c File: dcd_encoder_packer.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> static void put_be16(unsigned char *p, uint16_t v) { p[0] = (unsigned char)(v >> 8); p[1] = (unsigned char)(v & 0xffU); } static uint16_t get_be16(const unsigned char *p) { return (uint16_t)(((uint16_t)p[0] << 8) | p[1]); } static void put_be32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * (3U - i))); } static void put_le32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * i)); } static bool valid_dcd(const unsigned char *p, size_t n) { if (n < 4U || p[0] != 0xd2U || p[3] != 0x40U) return false; size_t total = get_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 = get_be16(p + at + 1); if (len < 4U || len > total - at) return false; unsigned tag = p[at], param = p[at + 3U]; bool wr = (tag == 0xccU && param == 4U && len >= 12U && (len - 4U) % 8U == 0U); bool ck = (tag == 0xcfU && param == 0x0cU && len == 16U); bool np = (tag == 0xc0U && param == 0U && len == 4U); if (!wr && !ck && !np) return false; at += len; } return at == total; } int main(void) { unsigned char dcd[36] = {0U}; dcd[0] = 0xd2U; put_be16(dcd + 1, 36U); dcd[3] = 0x40U; dcd[4] = 0xccU; put_be16(dcd + 5, 12U); dcd[7] = 0x04U; put_be32(dcd + 8, 0x020c406cU); put_be32(dcd + 12, 0x0c000000U); dcd[16] = 0xcfU; put_be16(dcd + 17, 16U); dcd[19] = 0x0cU; put_be32(dcd + 20, 0x020c406cU); put_be32(dcd + 24, 0x0c000000U); put_be32(dcd + 28, 32U); dcd[32] = 0xc0U; put_be16(dcd + 33, 4U); dcd[35] = 0x00U; assert(dcd[8] == 0x02U && dcd[9] == 0x0cU && dcd[10] == 0x40U && dcd[11] == 0x6cU); assert(valid_dcd(dcd, sizeof dcd) && !valid_dcd(dcd, sizeof dcd - 1U)); unsigned char bad[36]; memcpy(bad, dcd, sizeof dcd); bad[6] = 0U; assert(!valid_dcd(bad, sizeof bad)); memcpy(bad, dcd, sizeof dcd); bad[4] = 0xffU; assert(!valid_dcd(bad, sizeof bad)); unsigned char img[0xc10] = {0U}; img[0] = 0xd1U; img[2] = 0x20U; img[3] = 0x40U; put_le32(img + 4, 0x87800000U); put_le32(img + 12, 0x877ff42cU); put_le32(img + 16, 0x877ff420U); put_le32(img + 20, 0x877ff400U); put_le32(img + 32, 0x877ff000U); put_le32(img + 36, 0x1010U); memcpy(img + 0x2c, dcd, sizeof dcd); memcpy(img + 0xc00, "FORMAT-FIXTURE!!", 16U); FILE *f = fopen("verified.imx", "wb"); if (!f) return 1; bool ok = (fwrite(img, 1U, sizeof img, f) == sizeof img); if (fclose(f) != 0 || !ok) return 1; printf("verified.imx=%zuB DCD=%uB write_addr=02_0C_40_6C cmds=3\n", sizeof img, get_be16(dcd + 1)); return 0; }- Use big-endian helpers for DCD lengths, register addresses, values, and poll counts, never put_le32().
- Reject len < 4 or len > total - at before advancing so a zero-length command cannot cause an infinite loop.
- Place IVT at 0x00, Boot Data at 0x20, DCD at 0x2C, and payload marker at compact offset 0x0C00 (media 0x1000).
Generating verified.imx & Inspecting the Syscall Write Trace
Compile and run dcd_encoder_packer below. Observe in the strace log that file descriptor 3 (verified.imx) receives a single exact 3088-byte write (\321\0 @ = 0xD1 0x00 0x20 0x40 followed by little-endian 0x87800000) before stdout prints the 57-byte audit summary.
learner@ksa:~/gl-e01/m04-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic dcd_encoder_packer.c -o dcd_encoder_packerlearner@ksa:~/gl-e01/m04-l03./dcd_encoder_packerverified.imx=3088B DCD=36B write_addr=02_0C_40_6C cmds=3learner@ksa:~/gl-e01/m04-l03learner@ksa:~/gl-e01/m04-l03strace -e trace=write,exit_group \./dcd_encoder_packerwrite(3, "\321\0 @\0\0\200\207\0\0\0\0,\364\177\207 \364\177\207\0\364\177\207\0\0\0\0\0\0\0\0"..., 3088) = 3088write(1, "verified.imx=3088B DCD=36B write"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++Coalescing Multi-Pair DCD Writes & Bridging to C Runtime Startup
Notice how byte budgeting works when a real MMDC DDR3 init script needs ~65 register writes: emitting 65 separate 12-byte 0xCC commands takes 4 + 65 * 12 = 784 B (and hits the 1768 B ROM ceiling at 147 writes), whereas coalescing k consecutive same-parameter writes into a single 0xCC command consumes only 4 + 8 * k bytes—fitting up to 220 (addr, val) pairs inside 1768 B! Also keep your verification ledger honest: verified.imx proves container structure and endianness, while FORMAT-FIXTURE!! at 0x0C00 is a 16-byte test marker rather than ARMv7-A code or calibrated DDR3 timing. Later: Module m05 (m05-l01) writes the real _start assembly routine that sits at 0x0C00 (0x87800000), establishes an 8-byte-aligned SVC stack, copies .data, zeroes .bss, and enters main().
Common Production Pitfalls
warning: Symptom: Reusing put_le32() from IVT serialization to write 0x020C406C into a DCD Write Data (0xCC) command causes the i.MX6ULL Boot ROM to reject the image and enter USB Serial Downloader with zero UART output. Root Cause: Little-endian bytes 6C 40 0C 02 are parsed by the big-endian DCD interpreter as physical address 0x6C400C02, which falls outside the Boot ROM's allowed DCD address windows (MMDC, IOMUXC, CCM). Fix: Always serialize IVT/Boot Data pointers with put_le32() and every DCD length, address, value, mask, and count with put_be16()/put_be32().
warning: Symptom: Expanding a DCD register list pushes total_dcd_len past 1768 B (or past 0x0C00 - 0x002C), causing silent ROM rejection or corrupting the first instructions of _start. Root Cause: Emitting uncoalesced 12-byte 0xCC commands without asserting total <= 1768U and 0x2C + total <= payload_offset overflows the Boot ROM's fixed DCD buffer limit. Fix: Coalesce adjacent 0xCC pairs (4 + 8 * k bytes) and fail the host packer build whenever total > 1768U or 0x2C + total > payload_offset.
Practice & Retrieval
Guided Practice: Encoding a Coalesced 2-Pair Set-Mask DCD Command
Compute the exact hex framing by hand. Step 1 (Command Header): Encode one Write Data (0xCC) command with set-mask parameter param = 0x14 (4-byte width + set-mask bit 4) carrying k = 2 pairs (0x020C4068, 0x00000003) and (0x020C406C, 0x0C000000): total command length is 4 + 8 * 2 = 20 = 0x0014, giving header CC 00 14 14. Step 2 (Table Header): Combine that 20-byte 0xCC command with one 16-byte bounded 0xCF Check Data command inside a 0xD2 table: 4 + 20 + 16 = 40 = 0x0028, yielding D2 00 28 40.
Independent Practice: Whitelist-Aware Coalescing DCD Compiler
Extend dcd_encoder_packer.c into dcd_range_compiler.c that validates every target addr against allowed i.MX6ULL DCD ranges (IOMUXC [0x020E0000, 0x020E4000), CCM [0x020C4000, 0x020C8000), MMDC [0x021B0000, 0x021B4000), OCRAM [0x00907000, 0x00920000)), coalesces adjacent same-param 0xCC writes automatically, and rejects tables exceeding 1768 B.
→ open standalone lab workbench
1. Motivation
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.
2. Learning Objectives
- Serialize and parse
32-bit little-endianIVTandBoot Datapointers (entry = 0x87800000,boot_data = 0x877FF420,self = 0x877FF400,start = 0x877FF000,length = 0x1010) without host-alignment traps. - Validate big-endian
DCDblocks (0xD2header,16-bit total length<= 1768 B,0xCCWrite Data,0xCFCheck Data, and0xC0NOPsubcommands) indcd_valid(). - Reconcile compact
.imxfile offsets (IVTat0x0000, payload at0x0C00) with rawSD/eMMCcard geometry (0x0400LBA 2leading gap -> payload at0x1000in target RAM). - Preserve caller output buffers untouched when
pack_image()rejects insufficientcapacity < 0x0C10U.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m04_ivt_dcd_image/. - Target Boot ROM Contract: Matches
i.MX6ULLBoot ROM v0x40IVT(32bytes),Boot Data(12bytes),DCD(<= 1768bytes, big-endian byte stream), andSD/eMMC1 KiB(0x400) offset rules.
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils / hex tools (nm,odorhexdump). - Hardware: Standard Linux workstation (
0SDcards or physicalCortex-A7boards required;dd seek=2 bs=512applies only when flashing real removable media).
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/m04-l03$ 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.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
- Seeded Flaw in
starter/core.c:3-6(put_le32):starterwritesp[i] = (unsigned char)(value >> (8U * (3U - i)));-- serializing most-significant byte first (big-endian) whileget_le32()(lines 7-11) reconstructsp[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)(little-endian)! - Verified Repair in
files/core.c:3-6: Changes the shift top[i] = (unsigned char)(value >> (8U * i));so0x87800000Uwrites[0x00, 0x00, 0x80, 0x87]atout + 4,0x877ff420Uatout + 16(boot_data),0x877ff400Uatout + 20(self),0x877ff000Uatout + 32(Boot Data.start), and0x1010Uatout + 36(Boot Data.length). dcd_valid(core.c:16-34): Verifiesp[0] == 0xd2U && p[3] == 0x40Uand big-endiantotal = be16(p + 1)in[4, 1768]and<= n, then walks every command record checking subtraction boundlen <= total - atand legal command shapes:Write Data(0xcc,param == 4,len >= 12,(len - 4) % 8 == 0),Check Data(0xcf,param == 0x0c,len == 16), orNOP(0xc0,param == 0,len == 4).pack_image(core.c:35-44): Rejectscapacity < 0xc10Ubeforememset(out, 0, 0xc10U), writesIVTheader bytes[0xd1, 0x00, 0x20, 0x40]directly atout[0..3], populatesIVTandBoot Datapointers, and places the16-byte"FORMAT-FIXTURE!!"payload atout + 0xc00(self + 0xc00 = 0x87800000).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m04-l03$ 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/58. 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).
9. Experiment Variations
- Zero-Length
DCDSubcommand Infinite-Loop Trap: Removelen < 4Uoncore.c:25in a scratch copy and runtests.ccase3(which mutatesd[6] = 0Uat line29sobe16(p + 5) == 0): withoutlen >= 4U,at += 0spins forever insidewhile (at < total)! - ROM
1768-ByteDCDCeiling Breach: Construct an otherwise valid1772-byteDCDbuffer (0xD2, 0x06, 0xEC, 0x40+442NOPrecords) and confirmdcd_valid()rejectstotal > 1768Ujust as thei.MX6ULLBoot ROM does. - Host Unaligned-Pointer Cast vs Bytewise
put_le32: Compiletests.candfiles/core.cwith-fsanitize=undefined,addressand verify bytewiseput_le32(p + 1, ...)never triggers an unaligneduint32_t *store fault.
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 p50 | Host p95 | Host p99 | Cortex-A7 / Boot ROM Context |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 136.50 ms | 156.61 ms | 160.90 ms | Host build & test-runner latency |
verify 4-case .imx / DCD suite (verify 1..4) | 3530.6 us | 4584.0 us | 5507.5 us | Host validation of 3088 B .imx + 36 B DCD |
Boot ROM SD read of 4112 B (~9 sectors @ 25 MHz) | Modeled in RAM | Modeled in RAM | Modeled in RAM | ~350 - 900 us SPI/SDHC transfer + DCD MMIO writes |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
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 RAM | Wrote 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] = 0U | dcd_valid() accepted len == 0U and failed to advance at | Enforce `if (len < 4U \ | \ | len > total - at) return false;` |
.imx written at byte 0 of SD card wipes MBR & fails boot | Confused compact .imx (starts at 0x400) with full disk image | Flash .imx with dd bs=512 seek=2 conv=fsync (1024-byte offset) |
12. Guided Questions
- Why does
pack_image()storelength = 0x1010U(sizeof image + 0x400U) insideBoot Dataatout + 36even though the.imxbuffer itself is only0x0C10U(3088) bytes long?
- *Hint 1:* Compute
self - start(0x877FF400 - 0x877FF000 = 0x400) and inspect where byte0of theSD/eMMCcard lands in targetDDRwhen the Boot ROM copies fromLBA 0. - *Hint 2:* Add the
0x400-byte leading media gap (LBA 0..1) to the0x0C00-byteIVT-to-entry span (0x87800000 - 0x877FF400) plus the0x10-byte payload (0x400 + 0xC00 + 0x10).
- Why do
put_le32()andget_le32()operate onunsigned 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 (
pneed not be4-byte aligned). - *Hint 2:* What would
*(uint32_t *)p = valueemit if the host packer were compiled on a big-endian build server?
13. Independent Challenges
- Near Transfer — Embedded
DCDPointer Integration (pack_image_with_dcd): Writebool pack_image_with_dcd(unsigned char *out, size_t cap, const unsigned char *dcd, size_t dcd_len)that validatesdcdviadcd_valid(), placesdcdatout + 0x40(0x877FF440in RAM, safely clear ofIVT[0x00..0x1F]andBoot Data[0x20..0x2B]), and writes0x877FF440UintoIVT.dcd(out + 8) only whendcd != NULL. - Far Transfer —
.imxBinary Dissector & Consistency Auditor: Build a standalone C11 tool that reads a packed.imximage and checksIVTheaderD1 00 20 40,self > start,boot_data == self + 0x20,dcd == 0 || dcd_valid(...), andentry >= self + 0x40 && entry < start + length.
14. Solutions & Explanations
- Guided Question 1:
Boot Data.start(0x877FF000) represents the destination of byte0of the boot medium (0x400bytes belowIVT.self = 0x877FF400), soBoot Data.lengthmust cover the initial0x400media offset plus the entire.imxfile (0x0C10), totaling0x1010bytes (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 viadcd_valid's1768Ucap) beforememcpy(out + 0x40, dcd, dcd_len)andput_le32(out + 8, 0x877ff440U).
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
- A
DCDtable begins with[0xD2, len_be16, 0x40], wheretotal_len(4 <= total_len <= 1768 B) includes the4-byte header itself. Write Data(0xCC),Check Data(0xCF), andNOP(0xC0) serialize all16-bit lengths and32-bit addresses, values, masks, and counts in big-endian order—distinct from little-endianIVTpointers.- Bounded parsers must verify
len >= 4andlen <= total - atbefore advancing, preventing zero-length infinite loops and buffer overruns. - Structural
.imxvalidation proves container framing and0x00 / 0x20 / 0x2C / 0x0C00offsets, never board-specificDDR3calibration. - A header uses tag D2 and a big-endian total length including its header.
- Write Data command CC contains command framing followed by big-endian address and value data.
- Its tested structure and offsets, not a calibrated cold boot.