bootcc — State #
Position (updated after ROOT-CAUSING G15 (2+ case switch SEGV) — fixed the qsort insertion-sort logic (tools/tcc_runtime.S/.M1, committed 53e87b9); a REMAINING crash (corrupted struct switch_t at the qsort call) keeps D6 segfaulting; prior "sw.n offset" diagnosis CORRECTED, tracked below):
G15 = the persist tcc (bootcc-built, ~/.jcode/scratch/tccx64/persist/tcc) SEGVs at COMPILE time on ANY switch with 2+ case labels (NOT a goto issue — that was a G14-era red herring; the minimal repro is g3/hunt/g15_D6.c: case 1: p=1; break; case 2: p=3; break;). 1-case+default switches work because the qsort short-circuits at n=1. Two stacked bugs found:
(1) qsort logic (FIXED, committed 53e87b9) — the hand-written insertion sort in FUNCTION_qsort (tools/tcc_runtime.S, transcribed to tools/tcc_runtime.M1 by mk-tcc-runtime.sh) had three defects, all reachable only for n>=2: it passed the ELEMENT (arr[j]) + key VALUE to the comparator, but case_cmp(pa,pb) expects the ADDRESS of each element (pa is pointer-to-case_t*), so case_cmp read *pa = case_t->v1 (a small int) and dereferenced it as a case_t* -> SEGV; the shift was arr[j]=arr[j-1] (reads arr[-1] at j=0) instead of arr[j+1]=arr[j]; and the key was placed at arr[j] instead of arr[j+1] (off-by-one). Fixed to the standard insertion sort (comparator gets &arr[j] and &key, shift arr[j+1]=arr[j], place key at arr[j+1]); regenerated tcc_runtime.M1 via mk-tcc-runtime.sh (host binutils as/objcopy/objdump + byte transcription). This is a BOOTCC fix (tools/tcc_runtime), committed to bootcc git.
(2) remaining crash (RE-INVESTIGATE, prior diagnosis CORRECTED) — the persist still SEGVs on D6 AFTER the qsort fix (now later: base=0x2 deref). Prior note said "sw.n loaded from sw.p+8 (wrong offset)" — that was WRONG: it assumed the PRISTINE switch_case layout (n@0,max@4,def@8,p@16), but the SCRATCH tccgen.c uses a DIFFERENT struct switch_t { struct case_t{int64_t v1,v2; int sym;} **p; int n; int def_sym; } *cur_switch (p@0, n@8, def_sym@12). Under THAT layout the emitted M1 (arg rdi=*(r13-112)=sw.p @offset 0, arg rsi=(int32)*(r13-104)=sw.n @offset 8, rdx=8, rcx=&case_cmp) is CORRECT — sw.n IS at sw.p+8. A rule-7 tiny repro g3/hunt/g15_caller.c (f(s.p,s.n,8,cmpfn) with the same layout) compiles+runs rc=0 on BOTH persist and oracle, so the bootcc's cg_call arg emission is NOT generally broken. So the G15SW dump and the qsort call read sw.p from DIFFERENT locations. M1 evidence (persist-g15/tcc.M1, qsort call at line 70938): the arg setup is lea_rax,[r13-112]; mov_rax,[rax] (rdi=sw.p) + lea_rax,[r13-112]; add_rax,8; movsx_rax,DWORD_PTR_[rax] (rsi=sw.n) — the qsort call reads sw.p/sw.n from a FRAME slot at r13-112, while the G15SW dump (immediately before) reads the live value (0x8224c28). So the bootcc spills cur_switch's struct to a frame slot and the qsort call reads the STALE/spilled copy (p=0x2) instead of re-loading the live cur_switch. A second tiny repro g15_glob.c (global struct S *g, f(g->p,g->n,8,cmpfn)) also compiles+runs rc=0 on persist AND oracle, so the bug needs the EXACT tccgen.c shape (a struct switch_t *cur_switch ST_DATA global, mutated across the case-collection loop, then read at the qsort call). NEXT: (1) insert a cur_switch = <reassign>; or a call the bootcc thinks may clobber the spilled slot between the G15SW dump and the qsort call and re-check; (2) grep the bootcc's cg (src/boot_sym.c) for how a ST_DATA struct * global is spilled/re-loaded (the frame-slot spill of a global-pointer member); (3) likely fix = a missing re-load of cur_switch before the qsort call (or a wrong clobber-set).
Verification of (1): full regression green (b-ladder b1-b7 + g3 sz1-5/argonly/seven/ret40/s_str all rc==oracle), bootcc suite 0 failed, gate GO, frontier HOLDS 06:0000000 (tcc_runtime.M1 is NOT part of the bootcc build — it's only linked into the persist, so make determinism is unaffected). Carried non-blocking (unchanged): G18 (dynamic-libc -run TLS boundary — platform gap), G12 (missing "initializer not constant" diagnostic), G17 (external -o static Unwind* gap). NEXT increment: re-investigate (2) — the qsort is called with a corrupted struct switch_t (p=0x2); instrument the BOOTCC to print cur_switch/->p/->n at the call, and build a rule-7 tiny repro with a GLOBAL struct pointer to isolate how the bootcc materializes cur_switch; then fix + rebuild persist + re-run g15_D6 + full regression.
Position (updated after CLOSING G19 (x86-64-Linux va-codegen) — b7 now compiles AND runs rc=0 == oracle, so the whole va ladder b1-b7 matches the host oracle; SCRATCH-TCC-ONLY change per the G8/G16 fixture precedent, bootcc git stays clean):
G19 = the persist tcc (tcc 0.9.27 + M2 port, built by bootcc from ~/.jcode/scratch/tccx64/) had no x86-64-Linux va-codegen: pristine 0.9.27 keeps TOK_builtin_va_start #ifdef TCC_TARGET_PE-only and has no gen_va_start/gen_va_arg for x86-64, so the host 0.9.27's injected-macro path could not resolve and b7 (va_start/va_arg loop; oracle rc=0) failed persist rc=1. The host works around it with macros + a runtime: #define __builtin_va_start(ap,last) (*(ap)=*(__builtin_va_list)((char*)__builtin_frame_address(0)-24)), #define __builtin_va_arg(ap,t) (*(t*)(__va_arg(ap,__builtin_va_arg_types(t),sizeof(t),__alignof__(t)))), and void *__va_arg(...) in libtcc1.a. Three missing pieces, ALL in the scratch tcc SOURCE (NOT bootcc git):
(1) Seed __builtin_va_list as an array-of-1 typedef (tccgen.c seed_builtin_va_list, per-file prologue): the __builtin_va_arg macro does *(t*)(ptr), so __builtin_va_list must be POINTERABLE. G16 had seeded it as a bare VT_STRUCT typedef (24 B, r=8) — enough for sizeof (b1/b2/b3 = 24/24/48) but *(__builtin_va_list)(...) then failed "pointer expected". Now seeded as VT_TYPEDEF|VT_ARRAY|VT_PTR with ref = a 1-element array whose element is the 24-byte struct (c=24,r=8); only size/align are consumed, so sizeof is UNCHANGED and b1-b3 still pass.
(2) Seed a void* __va_arg(...) prototype (tccgen.c, same prologue): on x86-64 __va_arg is a PLAIN identifier (the reserved TOK___va_arg is ARM64-only), so NO tcctok.h change is needed — just a global function symbol. The critical detail: it MUST be VT_EXTERN + r = VT_CONST|VT_SYM. A bare local VT_FUNC symbol has r=0, which gcall_or_jmp (x86_64-gen.c:625) routes to the INDIRECT branch (load(r,vtop); o(0x41); o(0xff); o(0xd0+reg)) = a broken call *%r11 through the frame pointer. The first rebuild (array-of-1 + local __va_arg) compiled b7 but SEGFAULTED rc=139 exactly here (lea 0x0(%rbp),%r11; call *%r11). VT_EXTERN|VT_CONST|VT_SYM makes it the constant/relocation case → call <__va_arg@plt>, resolved at link to libtcc1.a's va_list.o.
(3) Fix the ELLIPSIS prolog's va struct init (x86_64-gen.c): pristine emitted a 12-byte struct (gp/fp/overflow only, wrong offsets) and never set reg_save. Replaced with the 24-byte SysV layout the oracle uses (extracted from a host-compiled sum(), rule-7 ov7.c): at rbp-0x18: gp=movl $0x8,-0x18, fp=movl $0x30,-0x14, overflow=lea 0x10(%rbp); mov -0x10, reg_save=lea -0xc8(%rbp); mov -0x8; the XMM save loop -0x28..-0x98 and GPR save loop -0xa0..-0xc8 (rdi@-0xc8) were already correct.
Evidence (ladder g3/hunt/b_ladder_va.sh, -o exe channel, host /usr/bin/tcc oracle): b7 persist compile+run rc=0 == oracle rc=0 (sum(3,10,20,30)-60==0 proves the sum is correct, not just no-crash); b1-b4 rc=0 == oracle (sizeof/shadow unchanged); b5 (int __builtin_va_list=5) persist "redefinition of '__builtin_va_list'" == oracle (the old G16 bare-struct seed silently accepted b5 rc=0 — the proper array-of-1 predefined now correctly rejects it); b6 (typedef int __builtin_va_list) persist "incompatible redefinition" == oracle. Disasm: persist sum() prolog byte-identical to host (frame sub $0xf0, struct init, XMM/GPR saves, va_start→memmove(&ap,&struct,24)), and the __va_arg call is now call <__va_arg@plt> (was the broken call *%r11). Persist rebuilt 1012831 B (M1=202077). seen_stack_size is now computed-but-unused in the prolog (harmless). SCRATCH-TCC-ONLY (tccgen.c + x86_64-gen.c); bootcc git clean — G8/G16 fixture precedent (the tests/codegen corpus tests bootcc-vs-oracle and cannot cover a scratch-TARGET change; the persist ladder + this STATE block are the record). Bootcc suite (unaffected by the scratch change): 0 failed (codegen/libtcc/libtcc-so), gate GO, frontier HOLDS 06:0000000. Carried non-blocking (unchanged): G18 (dynamic-libc -run TLS boundary — platform gap, tcc-wide under -static), G12 (missing "initializer not constant" diagnostic), G17 (external -o static _Unwind_* gap), G15 (compiled-tcc goto-to-label SEGV — fixtures absent, re-verify). G19 CLOSED; b7 is the acceptance and it passes.
Position (updated after CLOSING G3 (struct-return/arg >16 B ABI) COMPLETELY through G3c + G4 — G3a 669846f (return path), G3b 65fd6fa (arg path), G3c d2b81f7 (consumer path), G4 9da32e1 (corpus tests/codegen/g3_bigret.c); full suite 0 failed (codegen 91, libtcc-so 828), gate GO 5/5, frontier HOLDS 06:0000000):
G3 is done end-to-end. The two remaining consumer shapes (G3c) both failed first and are fixed in one increment, each with a rule-7 tiny repro: (shape2) u = g(f()) -- a >16-byte CALL RESULT consumed as a call arg -- hit codegen: not an lvalue because cg_call's by-address push called cg_addr on an EX_CALL (a call result has no lvalue address); fixed by branching the large-arg push on EX_CALL: cg_val(ai) leaves rax holding the result's G_BIGRET address (the exact by-address word needed), while any other large aggregate stays cg_addr(ai) (cg_val would LOAD the first eightbyte of the value -- applying cg_val unconditionally broke g3_argonly to a segfault, caught by the matrix). (shape3) f().a -- a MEMBER READ on a call result -- compiled but returned the wrong value (rc=1 vs oracle 0) because cg_addr's non-lvalue EX_MEMBER path materialized the result through the 16-B itmp temp (cg_ttmp_pick + cg_store_agg), truncating bytes past 15; fixed by detecting a large call base (agg_t_is_large(enode[base].typ) with op EX_CALL) and applying the member offset directly to the address rax already holds (G_BIGRET), skipping the temp; the 9..16-B member-read path is byte-for-byte unchanged. Corpus tests/codegen/g3_bigret.c (1666 B, all four shapes at once: s=f(), t=g(s), u=g(f()), f().a; acc=6+66+66+1=139 -> 139%7=6) discriminates two-way WITHOUT stash (safe git show 669846f^:src/boot_sym.c swap): pre-G3 engine runs it to rc=3 (fields dropped), post-G3 rc=6 == oracle. Stale gcc control goldens cleared before the suite (the G9/G10 trap). G3 probe ladder (~/.jcode/scratch/tccx64/g3/hunt/): g3_sz1/3/4/5 (returns 16/24/32/40 B), g3_argonly (24 B by-value arg), g3_seven (7 int args, excess-arg stack layout), g3_ret40 (full consumer mix) -- all rc=0 == tcc oracle. Carried non-blocking (unchanged): G19 (va-codegen, blocks b7), G12 (initializer-not-constant diagnostic), G17 (external -o static Unwind* gap), G15 (compiled-tcc goto SEGV -- fixtures absent, re-verify). NEXT increment: pick a carried product gap -- G19 (va-codegen, blocks b7) is the highest-value; rule-7 tiny repro first. G3 is CLOSED; do not re-open it without a failing probe.
Position (updated after CLOSING G3 (struct-return/arg >16 B ABI) through G3a + G3b — G3a committed 669846f (return path), G3b committed 65fd6fa (arg path); direct-chain matrix g3_sz1/3/4/5 + g3_argonly + g3_seven all rc=0 == tcc oracle):
G3 = aggregates >16 bytes cannot ride the one- or two-System-V-eightbytes value path (tail past byte 15 dropped), so tcc itself lowers them to memcpy/memmove (x86_64-gen.c "for struct arguments, we need to call memcpy"). G3a (return): self-consistent G_BIGRET global-buffer convention (8 NULL quads = 64 B emitted after :ELF_data; ST_RETURN large branch memmoves the value into G_BIGRET and returns &G_BIGRET in rax; ST_DECL large branch memmoves out of it) — NOT tcc's hidden-%rdi ABI, but the oracle comparison is behavioral (stdout+exit), so it is acceptable. G3b (arg): caller cg_call (all 4 push loops) passes a >16-byte struct arg BY ADDRESS — cg_addr(ai); push_rax, one 8-byte word, same slot count as a scalar; callee prologue stores only the pointer into the param slot (8-byte store, no arg-register clobber) in BOTH register and stack bind branches, then a phase-2 walk after ALL params are bound memmoves each large param's full value out of the pointer (dst=&slot, src=*slot; the clobber set is safe because no arg value still lives in a caller-saved register). Two real bugs found along the way (rule-7 tiny repros): (1) the phase-2 memmove initially had dst/src swapped — rc=9 (oracle 0) on g3_argonly, it copied g's uninitialized slot into the caller's s instead of filling g's slot; (2) the vendored M2 miscompiles eslots[si].off/.sz used DIRECTLY as fprintf format-args inside a second while-loop in emit_function_asm (segfault rc=139 in WHILE_emit_function_asm_36, bisected empty-loop OK -> guards OK -> +es_find local OK -> +direct struct-member fprintf ARG crashes; materializing .off/.sz into locals first fixes it) — phase 2 stays within the subset this function already relies on: reuses the existing p walker, nested-if guards (no &&), no new top-level locals. Probe ladder in ~/.jcode/scratch/tccx64/g3/hunt/: g3_sz1/2 (16B, 2reg path, pre-existing), g3_sz3/4/5 (24/32/40B return), g3_argonly (24B by-address arg), g3_seven (7 int args — excess-arg stack layout [rbp+24+8(i-6)] already worked, regression guard), g3_ret40 (G3c: g(f()) + f().a, NOT yet passing). NEXT increment G3c: the consumer path — f() returns a >16B struct by value and the result is consumed as a call ARG (g(f())) or member read (f().a); the large call result lands in G_BIGRET (rax=&G_BIGRET) but cg_call's push for that arg currently does cg_val (8-byte rax read = the pointer, not the value) — needs the non-16B temp / address-materialization path for a large call-result arg. Then G4: corpus tests/codegen/g3_bigret.c (<4095 B) two-way discriminator, clear stale goldens, make test, sh tools/gate.sh, commit + STATE. Carried non-blocking (unchanged): G19 (va-codegen, blocks b7), G12, G17, G15 (fixtures absent).
Position (updated after REFUTING G18 bug #2 direction (a) — "drop CONFIG_TCC_STATIC from scratch config.h" — as a DEAD END, and RE-CHARACTERIZING the s_str -run gap as a tcc-0.9.27-WIDE platform boundary (not a persist-specific defect), while CONFIRMING the s_str goal is MET through the working DYNAMIC -o exe channel):
Direction (a) is dead on three independent grounds, all verified this increment (rule-7, g3/hunt/g18_dyn_repro.sh, config restored via trap, persist left untouched): (1) no <dlfcn.h> in pnut (portable_libc/include has none) — dropping the define makes tcc.c #include <dlfcn.h> fail the persist EMIT at tcc.c:387 ("codegen: undeclared identifier", inside the # ifndef CONFIG_TCC_STATIC guard in tcc.h:40) — the persist is built by bootcc from these headers, so the header is simply absent; (2) no dlopen/dlsym/dlclose/dlerror anywhere in M2libc (the persist's own libc has no dynamic-loading surface to call); (3) the persist binary is fully static (readelf: no PT_INTERP) — a REAL dlopen would require implementing an ELF dynamic loader inside a static M2-Planet binary, which defeats the static-by-design bootstrap. So the tccrun.c:797 dlopen dummy is not a "bug to remove" — it is the correct, load-bearing behavior for a static binary that cannot dlopen. The PARITY ANCHOR (decisive, g3/hunt/g18_parity.sh): tcc -static -run s_str gives rc=1 on BOTH persist and oracle (persist Unknown relocation type: 23, oracle Unknown relocation type for got: 23 — both TPOFF32, tcc's internal memory-linker cannot apply TLS, tcc-0.9.27-wide). Hence the s_str -run gap is NOT persist-specific: the oracle only makes plain -run s_str (rc=0) work by DLOPEN'ing libc.so.6 dynamically (kernel ld.so does glibc TLS), and that dlopen capability is exactly the platform boundary the static persist lacks. The s_str GOAL is nonetheless MET via the working channel: persist -o exe s_str → rc=0, the produced ELF runs rc=0, fully dynamic (PT_INTERP /lib64/ld-linux-x86-64.so.2 + .interp + .dynsym + NEEDED libc.so.6) matching the oracle's -o exe output — the -o exe path uses REAL dynamic linking (the host linker), not tcc's internal memory linker, so TLS is handled by ld.so and no reloc-23 appears. Re-characterization: G18 bug #2 = the tcc-0.9.27 internal memory-linker cannot apply TPOFF32 (TLS) relocs, and a static binary cannot dlopen to sidestep it — a platform capability boundary shared with the oracle under -static, not a persist codegen bug and not a config bug. NO source change this increment (investigation only; the persist rebuild under direction (a) failed at emit and was rolled back, persist is still 1011423 B / M1=201567), so make green (libtcc-so 819/0), frontier HOLDS 06:0000000, and the full 5/5 gate does not apply (short-circuits to NO-GO on "no worktree changes", which is correct). Carried non-blocking (unchanged): G3 (struct-return >16 B), G19 (va-codegen, blocks b7), G12 (initializer-not-constant diagnostic), G17 (external -o static _Unwind_* gap), G15 (compiled-tcc goto SEGV — fixtures not in hunt dir, re-verify). NEXT increment: the s_str -run boundary is tcc-wide (matching it under -static is already achieved — both rc=1 — and closing plain -run would require a real dlopen inside a static M2 binary, out of scope), so MOVE to a carried product gap; pick G3 (struct-return >16 B ABI) or G19 (va-codegen, blocks b7) — rule-7 tiny repro first. Do NOT chase the -run/dlopen boundary as if it were a persist bug.
Position (updated after CLOSING the carried ".o mode 000 / -o exe mode 005" bug — root cause pinned to the syscall layer: open() is declared VARIADIC in glibc (int open(const char, int, ...)), and bootcc's variadic caller ABI passes the mode as the FIRST ellipsis arg on the STACK (named args -> registers, excess args -> stack; see cg_call), while FUNCTION_open was a raw SysV syscall wrapper that trapped with %rdx still holding the caller's stale value — so the mode reached the kernel as garbage (000 for .o, 005 for -o exe vs oracle 664/775). FIXED in src/boot_sym.c FUNCTION_open (read the mode from [rsp+24]: ret +8, saved r13 +16, mode +24 — matches M2libc's own all-stack open() and the printf/scanf/cg_va stack-ellipsis convention), COMMITTED 7219c76 (+ corpus tests/codegen/openmode.c two-way discriminator + mem_file.c now declares open variadic to match reality); gate GO 5/5, frontier HOLDS 06:0000000, full suite 0 failed (codegen 90, libtcc 455, libtcc-so 819 — 1407 total); AND RE-REFUTING the "teach the linker TLS" next-step premise (G18 bug #2 addendum): tcc -static -run s_str fails the SAME Unknown relocation type: 23 under the ORACLE too, so the TPOFF32 memory-link gap is tcc-0.9.27-wide, NOT persist-specific; the real near-blocker for glibc -run under the static persist build is tccrun.c:797's CONFIG_TCC_STATIC dlopen dummy (returns NULL -> falls to static libc.a), and the DYNAMIC -o exe channel already works for s_str (real dynamic ELF, kernel ld.so handles TLS, rc=0):*
The mode bug was the session's headline. Discrimination (rule 7, g18_mode_var.sh through current bootcc): open(char*,int,int) (non-variadic prototype) creates the file mode 775 == oracle; open(char*,int,...) (the REAL glibc signature) creates it mode 0 while oracle gives 775 — the same two sources, differing only in the ellipsis. Caller M1 is the smoking gun: non-variadic emits pop_rdx; pop_rsi; pop_rdi (all three args to registers), variadic emits only pop_rsi; pop_rdi with the mode left pushed on the stack. So the bug is a single outlier in an otherwise self-consistent custom variadic ABI: FUNCTION_printf/scanf/cg_va all READ their ellipsis args from the stack (which is why they work), but FUNCTION_open assumed SysV %rdx. close/read/write/lseek are non-variadic so their register args are always filled and untouched. The fix reads the mode from the stack; the one non-variadic open caller in the repo (mem_file.c, O_RDONLY so mode is ignored) was declared variadic to match glibc. Corpus openmode.c discriminates both ways WITHOUT a mode syscall: create a 0644 file, close, re-open for READ — mode 0 (bug) has no read bit -> re-open EACCES -> exit 1; mode 0644 (fixed) -> exit 0; oracle (real glibc) always exit 0. Two-way re-verify (reverse-apply the FUNCTION_open change, NOT stash — the earlier g18_corpus.sh stash-dance incident is the cautionary tale): WITHOUT fix openmode exit=1, WITH fix exit=0, restore exit=0. End-to-end: the REBUILT persist tcc (1011423 B, M1=201567) now writes -c mode 664 and -o mode 775, exact oracle match (was 000/005), and persist -run on a no-libc program still works. G18 bug #2 addendum (TLS premise refuted): the recorded next step "teach scratch tcc's internal linker TLS (PT_TLS ingest + TPOFF32)" was a false premise — (1) #include <errno.h>; return e==0?0:42 (tls1.c) fails rc=255 "unrecognized file type" IDENTICAL to non-TLS glibc calls (bl1 abs, bl2 getpid), so errno does not isolate reloc-23; (2) DECISIVE: the ORACLE tcc -static -run s_str ALSO gives Unknown relocation type: 23 (rc=1) — the memory-link TPOFF32 limit is tcc-0.9.27-wide, not persist-specific; oracle handles s_str only by dlopen'ing libc.so.6 dynamically (kernel ld.so does glibc TLS); both oracle and persist segfault (139) on -static -run errno (memory runner has no TLS at all); (3) the persist's -o exe DYNAMIC channel already produced a correct dynamic ELF for s_str (PT_INTERP, NEEDED libc.so.6, EXEC) that runs rc=0 once chmod'd (modulo the mode bug, now fixed). Hence the only real -run blocker left for the static persist build is the dlopen dummy: either build a NON-static persist (real dlopen -> libc.so.6 path like the oracle; scratch tcc is static because the hand-written config.h defines CONFIG_TCC_STATIC) or make the -run link prefer libc.so like the oracle. Carried non-blocking (unchanged): G3 (struct-return >16 B), G19 (va-codegen, blocks b7), G12 (initializer-not-constant diagnostic), G17 (external -o static Unwind* gap), G15 (compiled-tcc goto SEGV — re-verify). NEXT increment: try the (a) direction for G18 bug #2 — drop CONFIG_TCC_STATIC from the scratch config.h (or make the -run link prefer libc.so + libc_nonshared.a like the oracle), rebuild persist, re-run the t1–t6 ladder + s_str; rule-7 tiny repro first.
Position (updated after CLOSING G18 bug #1 (a real bootcc codegen bug: cg_switch's DENSE jump-table bounds check sent out-of-range values to the after-switch label instead of the default label, silently skipping a present default — C 6.8.4.2; the bootcc-built tcc's switch(obj_type) had obj_type=0 = ld script below the dense range, so the ld-script default never ran and libc.so was never followed) — FIXED in src/boot_sym.c cg_switch (compute def_lab, route jl/jg to it when has_default else after-switch), COMMITTED 84c2c06 (+ corpus tests/codegen/switch_default_oob.c + tools/.frontier_state); gate GO 5/5, frontier HOLDS 06:0000000, full suite 0 failed (codegen 89, libtcc 450, libtcc-so 810 — the new test passes in all three harnesses); AND RE-CHARACTERIZING G18 bug #2: it is NOT the ldscript parser (the prior hypothesis was wrong) — it is a PLATFORM CAPABILITY gap: the static persist binary cannot dlopen, so the shared-libc path the ld script points at fails, and tcc falls back to static libc.a whose members carry TPOFF32 relocs tcc's internal linker cannot apply. s_str (the goal) is still blocked; the next increment is teaching scratch tcc's internal linker TLS (direction (b))😉:
G18 bug #1 was the session's headline: root-caused with the rule-7 tiny repro g3/hunt/g18_sw2.c (switch(x) cases {1,2,3} + default, f(0) must be 999): bootcc rc=1 (out-of-range skipped default), oracle rc=0. M1 showed the dense dispatch cmp_rax,%1; jl %L2 where L2 is the after-switch/return path — the default label was emitted but never referenced out-of-range. Fix: cg_switch (src/boot_sym.c ~6400) now computes def_lab (the default case's label; endl when no default) and the dense jl/jg target def_lab when has_default — matching the sparse path, which was already correct (it always used sw_lab of the default). Verification: tiny repro rc=0 == oracle; corpus tests/codegen/switch_default_oob.c (dense default + a no-default guard so the else branch is exercised too) DISCRIMINATES both ways — with fix rc=0 == oracle, stashed rc=1 ≠ oracle (g18_corpus.sh, full rebuild each way); cleared stale gcc control dirs (the G9/G10 stale-golden trap — the 3 emit failures after the fix were exactly this: the gcc control dir was pre-fix), then gate GO (worktree changes / make green / rebuild determinism / trailing newlines / frontier HOLDS 06:0000000); committed 84c2c06 (fix + corpus + frontier state). G18 bug #2 — the re-characterization (decisive evidence, -DG18LD instrumentation of the persist tcc, since removed and persist rebuilt clean 1011412 B, M1=201565): tcc_load_ldscript (tccelf.c:3019, byte-identical to pristine) WORKS — it lexes OUTPUT_FORMAT(elf64-x86-64) and GROUP, then calls ld_add_file('/lib/x86_64-linux-gnu/libc.so.6') -> tcc_add_file_internal -> obj_type=2 (AFF_BINTYPE_DYN) -> TCC_OUTPUT_MEMORY branch -> dlopen('/usr/lib/x86_64-linux-gnu/libc.so.6', RTLD_GLOBAL|RTLD_LAZY) returns NULL -> -1 -> unrecognized file type -> falls to libc.a -> TPOFF32 (reloc-23) in the internal linker. The NULL has a named origin: tccrun.c:797 (byte-identical to pristine 0.9.27), under #ifdef CONFIG_TCC_STATIC, tcc ships /* dummy function for profiling */ ST_FUNC void *dlopen(...){ return NULL; } (plus no-op dlclose/dlerror/dlsym) — the scratch config.h (hand-written M2 porting artifact) defines CONFIG_TCC_STATIC, so the persist tcc's own dlopen is the dummy. The persist binary is fully static (no .interp/.dynamic; readelf: no PT_INTERP), so a REAL dlopen would need to implement ELF dynamic loading inside a static M2-Planet binary — out of scope for this increment. Hence G18 bug #2 = the static persist tcc cannot follow the ld script to the shared libc; it is a platform capability gap, NOT a bootcc codegen bug and NOT a parser bug. Consequence on the ladder (clean switch-fixed persist 1011412 B): t1/t2 (bare #include <stdio.h>/<string.h>, NO glibc call) went rc=0 -> rc=255 — this is the fix EXPOSING, not causing, the failure: before the fix the switch skipped the default, tcc_add_file_internal returned tcc_open's fd (6, nonzero) with no error, tcc_add_library_internal treated the ld script as "not found" SILENTLY and fell to libc.a, which happened to link when no TLS symbols were pulled (t1/t2); after the fix the ld script is genuinely attempted, dlopen fails, and tcc_error_noabort("unrecognized file type") sets the error flag -> tcc aborts rc=-1 (255 mod 256). t3 (sprintf) = rc=1 Unknown relocation type: 23 (oracle 0); t4 persist=1 oracle=2 (oracle nonzero — probe-design smell, the oracle itself fails that shape); t5=1 oracle=0; t6 persist=1 oracle=1 (matches). s_str (#include <stdio.h>+<string.h>, sprintf/strcmp/strlen) still rc=1 (oracle rc=0) — GOAL NOT MET. Grounding for the next increment: x86_64-link.c (byte-identical to pristine) handles R_X86_64_GOTTPOFF (three switch sites, GOT-mediated) but has NO R_X86_64_TPOFF32 case and emits NO PT_TLS segment — grep tdata|tbss|PT_TLS across tccelf.c/x86_64-link.c/tcc.h is EMPTY, so the loader does not even INGEST TLS sections from input objects; a TLS-free libc is not an option either (M2libc lacks strcmp/strlen/printf; glibc's errno is __thread so any errno-pulling member brings TPOFF32). NEXT increment (direction (b), the only path to s_str): teach scratch tcc's internal linker TLS — (1) a rule-7 tiny failing repro first: int main(void){ return errno; } (pulls glibc errno.o -> TPOFF32 -> expect reloc-23 under persist, oracle rc=0; confirm readelf -r on a member shows which TLS relocs appear: TPOFF32 and possibly DTPMOD64); (2) ingest .tdata/.tbss in tcc_load_object_file (tccelf.c) into a per-file TLS view; (3) in x86_64-link.c, allocate a PT_TLS segment (tdata then tbss, memsz>size for BSS), set each TLS symbol's tp-offset (its offset within tdata, negative for tbss), add the R_X86_64_TPOFF32 case (add32le(ptr, val) where val = tp-offset; verify the addend convention against a host-built static TLS binary), and handle DTPMOD64 if present (static single-module: module index 0); (4) emit the PT_TLS program header in the output (p_filesz = tdata size, p_memsz = tdata+tbss, p_align = max align). Scratch-tcc change = G8/G16 fixture precedent (STATE-only commit, bootcc git clean). Carried non-blocking: G19 (va-codegen, blocks b7 — host 0.9.27 injects __builtin_va_start/__builtin_va_arg macros + libtcc1.a __va_arg runtime; pristine has none for x86-64-Linux), G3 (struct-return >16 B ABI), G12 (missing "initializer not constant" diagnostic), G17 (external -o static-link _Unwind_* gap), G15 (compiled-tcc goto-to-label SEGV — re-verify status), .o files mode 000.
(Addendum, re-verified 2026-09-06: the "stashed rc=1" two-way claim above came from the ORIGINAL g18_corpus.sh, whose git stash push src/boot_sym.c was a NO-OP on a clean tree (the fix is committed in HEAD), so its later git stash pop popped an OLD unrelated WIP stash (comma-declarator work) into src/boot_sym.c -> merge conflict; the fix was never actually removed, making that "WITHOUT fix" leg INVALID. Repaired with git checkout HEAD -- src/boot_sym.c (both pre-existing stashes intact, nothing lost) and rewrote g18_corpus.sh to reverse-apply 84c2c06^ directly (no stash). VALID two-way re-run: WITH fix rc=0 == oracle; WITHOUT fix (84c2c06^) rc=1 != oracle; restored rc=0; tree clean, fix present. LESSON: a clean-tree stash-dance is a landmine — a no-op stash push leaves the tree unchanged, then a stash pop grabs whichever old stash is at the top of the stack; use git checkout <commit>^ -- file to remove a committed fix instead.)
Position (updated after FIXING gap G16 — the persist tcc's front-end did not recognize __builtin_va_list, so glibc's stdarg.h line typedef __builtin_va_list va_list; failed "undeclared" and blocked #include <stdio.h>: FIX in scratch tcc tccgen.c (seed_builtin_va_list(), NOT under git — G8 fixture precedent; bootcc git clean, no product change); full suite 0 failed, gate GO, frontier HOLDS; persist tcc rebuilt 1011412 B (M1=201565); b1–b6 ladder matches the oracle and discriminates BOTH stash directions; s_str now passes stdarg.h and reaches NEW linker gap G18 (TLS reloc R_X86_64_TPOFF32=23 rejected by tcc's internal linker); b7 reaches NEW gap G19 (no x86-64-Linux va codegen upstream — host 0.9.27 injects it via macros + libtcc1.a __va_arg runtime):
G16: the scratch tcc (tcc 0.9.27 + M2 porting) keeps TOK_builtin_va_list commented out (tcctok.h:146 — identical to pristine), so __builtin_va_list is a plain identifier; the tcc-bundled glibc stdarg.h (/usr/lib/x86_64-linux-gnu/tcc/include/stdarg.h: typedef __builtin_va_list va_list;) hit parse_btype's sym_find(tok) -> nothing -> error: '__builtin_va_list' undeclared (b1/b2/b3 baseline persist rc=1, oracle rc=0). The oracle (Debian tcc 0.9.27) registers the name as a predefined global typedef carrying the 24-byte SysV x86-64 va_list struct (gp_offset 4 + fp_offset 4 + overflow_arg_area 8 + reg_save_area 8, align 8), re-established per file; the pristine source contains NO registration code anywhere (confirmed: __builtin_va_list appears in no pristine .c/.h except the commented token), so the Debian host build injects it. Fix (M2-portable C, NO lexer change — re-enabling the token would corrupt the M2 token table): seed_builtin_va_list() in scratch tccgen.c, called from tccgen_compile's per-file prologue (after func_old_type setup, before tcc_debug_start): intern the 17-char name via tok_alloc, push a struct symbol (VT_STRUCT|VT_UNION, size 24 through sym_push(...,0,24), st->r=8), then global_identifier_push the typedef (VT_TYPEDEF|VT_STRUCT|VT_UNION, ref=struct). Only size (24) and alignment (8) are consumed (sizeof / local layout / arrays); no fields. Verified on the canonical -run channel (ladder g3/hunt): b1 sizeof = 24, b2 <stdarg.h> va_list = 24, b3 array[2] = 48 — baseline rc=1 -> fix rc=0, all == oracle; b4 (local shadow) rc=0 both (unchanged); b5 file-scope int __builtin_va_list=5 — baseline rc=0 (silently accepted, under-reported) -> fix rc=1 error: redefinition of '__builtin_va_list' (oracle rc=1); b6 typedef int __builtin_va_list — baseline rc=0 -> fix rc=1 error: incompatible redefinition (oracle rc=1). Two-way stash re-verify (g16stash2.sh, full persist rebuild with the call commented out entirely): WITHOUT fix M1=201562 / 1011403 B -> b1=1 b2=1 b3=1 b4=0 b5=0 b6=0; WITH fix M1=201565 / 1011412 B -> b1=0 b2=0 b3=0 b4=0 b5=1 b6=1; restore reproduces the fixed build exactly — discriminates both directions and the rebuild provably took effect (distinct binary sizes). (Incident: the first stash attempt was a broken sed that prepended a comment BEFORE the call, leaving it active -> both builds byte-identical, the G13 stale-output trap; corrected by commenting the whole line + detecting the ACTIVE (uncommented) call. Include chain confirmed: tcc.c:23 # include "libtcc.c" (space-form) -> libtcc.c:41 #include "tccgen.c", so the fix IS in the TU — seed_builtin_va_list 2x in tcc.M1, __builtin_va_list string in the binary.) No regressions: smoke2 pure-C ladder s_loc=14 s_fn=55 s_ptr=30, n-matrix n1=2 n2=1 n3=2 n4=1, full suite 0 failed (libtcc-so 801/0). Corpus note: the fix is in the scratch tcc SOURCE (not bootcc git), so the tests/codegen corpus (which tests bootcc vs oracle) cannot cover it — G8 fixture precedent: the persist ladder + this STATE block are the record. bootcc itself uses __va_list (vendor/M2libc/stdarg.h), never __builtin_va_list. G18 (new, now the blocker of the s_str goal): with G16 fixed, #include <stdio.h> (s_str) advances past stdarg.h and fails in the INTERNAL linker with tcc: error: Unknown relocation type: 23. 23 = R_X86_64_TPOFF32 (TLS). Disambiguation ladder (t1–t6): bare #include <stdio.h> / <string.h> with no glibc call -> rc=0 both; ANY glibc symbol use (sprintf/strlen/strcmp) -> reloc-23 under persist, oracle rc=0. The user object is clean (readelf -r t3.o: only R_X86_64_PC32 + R_X86_64_PLT32); persist tcc is statically linked (CONFIG_TCC_STATIC — a hand-written config.h artifact, pristine has no such define) and its -run memory link pulls STATIC /usr/lib/x86_64-linux-gnu/libc.a (strace: persist opens libc.a + libtcc1.a; oracle opens libc.so + libc_nonshared.a); static glibc members carry TPOFF32 relocs (malloc.o, cxa_thread_atexit_impl.o, inet_ntoa.o). The scratch x86_64-link.c is byte-identical to pristine 0.9.27 (which also has no TPOFF32 case) — tcc's internal linker simply does not handle TLS, and the oracle sidesteps it by linking glibc dynamically. G18 = persist tcc static-libc/TLS link gap. Two candidate directions: (a) drop CONFIG_TCC_STATIC (or make the -run link prefer libc.so + libc_nonshared.a like the oracle) — a config-only change, try first; (b) teach x86_64-link.c TPOFF32 — deep. G19 (new): the full va program b7 (va_start/va_arg loop; oracle rc=0) -> persist rc=1 warning: implicit declaration of function '__builtin_va_start'. Root: pristine 0.9.27 has NO x86-64-Linux va codegen — TOK_builtin_va_start is #ifdef TCC_TARGET_PE-only, the x86-64-Linux token is TOK_builtin_va_arg_types (classify-only, x86_64-gen.c:1195), and gen_va_start/gen_va_arg exist only for arm64. The host tcc 0.9.27 works around it with injected macros (strings in the binary): #define __builtin_va_start(ap,last) (*(ap)=*(__builtin_va_list)((char*)__builtin_frame_address(0)-24)) and #define __builtin_va_arg(ap,t) (*(t*)(__va_arg(ap,__builtin_va_arg_types(t),sizeof(t),__alignof__(t)))) plus the runtime void *__va_arg(...) in libtcc1.a's va_list.o. b7 needs that macro/runtime path, not a front-end fix. Carried non-blocking: G3 (struct-return >16 B ABI), .o files mode 000, G12 (missing "initializer not constant" diagnostic), G17 (external -o static-link _Unwind_* gap — persist statically linked, pulls static libc.a needing libgcc unwind; -run unaffected), G15 (compiled-tcc goto-to-label SEGV, last seen in G14's W2 probe — re-verify status). NEXT increment G18 (the s_str goal: try (a) first — drop CONFIG_TCC_STATIC from scratch config.h so the -run memory link pulls libc.so + libc_nonshared.a like the oracle; rebuild; re-run t1–t6 + s_str).
Position (updated after FIXING bug G14 — #ifndef on a defined macro evaluated TRUE in the bootcc-built tcc because label interning merged prefix-related names (do_if into do_ifdef): COMMITTED 8d3dba6 (src/boot_sym.c + tests/codegen/prefix_labels.c); gate GO, frontier HOLDS 06:0000000; persist tcc rebuilt 1010890 B with the n-matrix fixed (n3=2); smoke2 stdio test advances past the glibc guard to a NEW front-end gap G16 (typedef __builtin_va_list va_list unparseable):
G14 was NOT a miscompile of the c = (define_find(tok) != 0) ^ c expression (x1-x3 plain XOR/OR/AND matrices and the exact-shape Y1 repro all matched across oracle/direct/compiled) — it was a LABEL-INTERNING collision. Root cause (rule-7 ladder W1: the parse_ifdef switch shape with labels do_ifdef/do_if where one is a strict prefix of the other): clab_id_for (src/boot_sym.c ~4856) match loop stopped as soon as the QUERY hit its own NUL (while(nm[k]!=0 && ...); if(nm[k]==0) return) without checking the stored name also ended — so a query that is a strict prefix of an earlier-stored name (do_if vs do_ifdef) returned the stored name's ID. The M1 then had a DUPLICATE :L5 (confirmed by label audit; in M1-Planet the last definition wins), and the linker retargeted goto do_ifdef to the LAST :L5 (do_if's continuation), skipping the XOR: #ifndef on a defined macro kept c=1 -> branch taken -> glibc's #ifndef __GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION guard misfired and the stdio include failed. Disambiguation ladder: W2 (labels alpha/beta, no prefix) direct=110 CORRECT (isolated the name dependence); W1 pre-existing (identical with G13 stashed); the scratch tcc's parse() stores do_ifdef: (tccpp.c:1875) before looking up do_if: (1888) -> collision fires in exactly the order it did. Other prefix pairs exist in tcc (redo/redo_start/redo_no_start, add_char/add_char_nonext, add_cstr/add_cstr1, error/error_func) — all fixed by the same one-line guard. Fix: if(nm[k]==0 && clab_nm[p]==0) (exact match only). Only one instance of this loop pattern in the engine. Note: W2's compiled-tcc SEGV (139) is the SEPARATE G15 (goto-to-label-in-switch-case under the compiled tcc), not G14. Verification: corpus tests/codegen/prefix_labels.c (949 B) discriminates both directions (with fix main=9; without fix main=5, codegen 87/88); v-ladder v1 (shorter stored first, was passing) + v2 (longer stored first, was failing) both green; full suite 3+23+17+88+445+801 = 0 failed; gate GO; persist tcc REBUILT (1010890 B, M1=201428): n-matrix n1=2 n2=1 n3=2 n4=1 (n3 was 1), pure-C smoke2 ladder still green (s_loc=14 s_fn=55 s_ptr=30), and #include <stdio.h> (s_str) now gets PAST the guard to a new distinct blocker (below). NEXT increment G16: the stdio test now fails at tcc's stdarg.h:4 typedef __builtin_va_list va_list; with error: ';' expected (got "va_list") — the front-end does not accept __builtin_va_list as a typedefable type (tcc uses it pervasively: stdarg.h, x86_64-gen.c classify_x86_64_va_arg). Oracle compiles it natively.
Position (updated after FIXING bug G13 — a user label immediately above a switch case/default (L: default: stmt) dropped that case's body (dispatch never reached it; the body was dead code), which is what made the bootcc-built tcc HANG on any skipped #if branch: COMMITTED a2ddb96 (src/boot_sym.c + tests/codegen/label_above_case.c); gate GO, frontier HOLDS 06:0000000; NEW compiled-tcc defects G14 (#ifndef on a defined macro evaluates TRUE) + G15 (goto-to-label-above-default segfault) recorded):
G13 is a bootcc parser/codegen bug found while resuming the retarget/smoke2 line: the bootcc-built tcc (persist/tcc) hung (timeout 124) on any program whose preprocessor skipped a directive branch containing plain text (#if 0 int x = 1; #endif, #ifdef Q ... #else ..., and the glibc path — #include <stdio.h> pulled in bits/libc-header-start.h whose #ifndef __GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION guard skipped lines). Isolation ladder (z1-zb, e1-e5): empty/comment-only skips were fine; ANY skipped line of ordinary text hung; gdb attach showed the spin inside FUNCTION_preprocess_skip (0x607919), and its disassembly showed the switch's default case (the _default: default: p++; break; plain-text path) jumped straight to the loop bottom WITHOUT p++ — the statement was dropped, so c = *p never advanced. Direct bootcc chain on the same shapes worked, and the r-ladder (r1-r6) reduced it to r3: int g(int c){ int p=0; switch(c){ case 1: p=100; break; L: default: p++; break; } return p; } — oracle=1, bootcc=0. Root cause (confirmed by the -s -x statement dump): the parser nests L: default: as ST_LABEL{a: ST_DEFAULT{a: body}} in the switch body's next-chain, but cg_switch's collection walk tested only DIRECT chain children for ST_CASE/ST_DEFAULT, so the case was never registered (has_default stayed 0, no sw_lab allocated, dispatch emitted only cmp 1; je L3; jmp %L2 to the switch END) while the body was still emitted via cg_stmt(ST_LABEL) as unreachable code. Fix in cg_switch (src/boot_sym.c ~6435 + ~6562): BOTH the collection walk and the body walk now descend through ST_LABEL wrappers (while(op == ST_LABEL) cs = cs.a) before testing for ST_CASE/ST_DEFAULT; the body walk emits the user label(s) first, then the switch-case label, so the case line-up (index i) stays in sync with the collection walk. Verification: r-ladder 6/6 (r3 now 1/1); direct-chain z-ladder no longer hangs (z1=2 z2=3 z8=2 z9=2 zb=2); full suite 1339 passed 0 failed (codegen 87 with the new test); gate GO 6/6 frontier HOLDS 06:0000000; rebuilt persist tcc (1010889 B, M1 201426->201428) — the compiled tcc's z/e preprocessor matrix no longer hangs (z1=2 z2=3 z5=6 z8/9/zb=2 e2=4 f1=1), smoke2 pure-C ladder green (s_loc=14 s_fn=55 s_ptr=30), 36/36 battery + 8/8 g2 ladder + 7/7 cast probes match oracle. (Incident: the persist rebuild initially "succeeded" silently with the OLD binary because stale hung persist/tcc/gdb/strace processes from this session held the output file open; hex2 then failed to open it — killed the stragglers and rebuilt to a fresh name. Also: the G13 r-ladder files initially clobbered the 36-case battery's r1-r6 fixtures in the HUNT dir; restored from run10.sh, battery re-verified 36/36.) New corpus tests/codegen/label_above_case.c (2119 B) discriminates BOTH ways: with fix exit 11 (== oracle: 1 + 3 + 7 across three probes — label-above-default reached via dispatch, label-above-case reached via dispatch, label-above-default reached via goto), fix stashed exit 7. TWO NEW compiled-tcc (NOT direct-chain) defects surfaced during verification, separate from G13: (G14) the compiled tcc's #ifndef on a DEFINED object-like macro evaluates TRUE — e1 (#define FOO then #ifndef FOO ->1 / #else ->2) returns 1 where oracle returns 2, and this is exactly why glibc's guard still fires (__GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION is defined by stdio.h, the #ifndef should be false, but the built tcc treats it as true -> #error "Never include <bits/libc-header-start.h> directly.") — so s_p/s_str (#include <stdio.h>) still FAIL under persist (rc=1) even after G13; candidate sites: the c = 1; goto do_ifdef for TOK_IFNDEF or the define_find(tok) != 0 result in parse_ifdef (tccpp.c ~1870). (G15) the compiled tcc SEGVs (rc=139) at RUNTIME on a goto L; L: default: switch shape (g13b/g13c: case 1: goto L; L: default: p += 7; break; with main calling g(1)) while the direct chain compiles it correctly and the oracle returns 7 — the goto target resolution or the case-body layout in the COMPILED tcc is wrong (direct bootcc handles it, so it is another compiled-tcc miscompile, likely in the same label/case emission area). Carried non-blocking: G3 (struct-return >16 B ABI), .o files mode 000, G12 (missing "initializer not constant" diagnostic). NEXT increment G14 (the #ifndef-evaluates-true in the compiled tcc — it is the last gate between persist tcc and #include <stdio.h>).
Position (updated after FIXING bug g2b — 64-bit file-scope global initializers emitted the wrong bytes (suffixed literals came out EIGHT ZERO bytes; unsuffixed literals kept only the low dword): COMMITTED e7a035a (src/bootcc.h + src/boot_sym.c + tests/codegen/g2b_global64_init.c); gate GO, frontier HOLDS 06:0000000; NEW pre-existing gap G12 (missing "initializer not constant" diagnostic) recorded):
g2b closes the last residual of the original g2 bug (a 64-bit global initialized with 0xe8d4a51000ULL read back as zero). Two INDEPENDENT defects sat behind the old bind_global_scalar path, each isolated with a rule-7 ladder (g3/hunt/gi1..gi8): (a) a SUFFIXED literal — bind_global_scalar fed the whole initializer text ("0xe8d4a51000ULL") to the 32-bit strtoint, which requires NUL-terminated input and bailed on the non-NUL U/L/LL suffix, returning 0, so unsigned long long a = 0xe8d4a51000ULL emitted EIGHT ZERO bytes into its :GLOBAL_ slot (gi2/gi3); (b) an UNSUFFIXED literal — ginit is a 32-bit int and emit_globals zero-padded past byte 3, so unsigned long long a = 0x100000001 kept only the low dword (gi6: 01 00 00 80; gi8 lost the upper half entirely). (Confirmed the strtoint behaviour standalone in g3/hunt/strt.c: strtoint("0xe8d4a51000ULL")==0, strtoint("0xe8d4a51000")==0x35051000 wraps.) Fix, all M2-portable (no engine-side 64-bit int): (1) struct symbol gains int ginit_hi (src/bootcc.h) — high 32 bits of a 64-bit scalar init, 0 for 32-bit globals (calloc default); (2) bind_global_scalar (src/boot_sym.c ~1856) now routes a BARE TOK_INT literal initializer through ex_lit_halves — the width- and suffix-independent routine G10 hardened — to fill BOTH ginit and ginit_hi, then advance(); the islit guard is a bare-literal-only lookahead (skip_nl(cur->next) must be a terminator ; , }, newline-skipped) so an EXPRESSION initializer (1+2, (a|b), ~x, 0x100+0x20) still takes eval_const, which consumes the whole expression — a non-literal init keeps eval_const (and ginit_hi stays 0); (3) emit_globals (src/boot_sym.c ~8675) now emits bytes 4-7 from ginit_hi (little-endian) alongside bytes 0-3 from ginit. No engine-side shift of an int by >= 32 (would break the m2==gcc gate). Verification: the full ladder (gi1-gi8 + g2) matches oracle under the M2 direct chain with correct 8-byte LE data (gi2/gi4/gi6 01 00 00 00 01 00 00 00; gi3/gi8/g2 00 10 a5 d4 e8 00 00 00; gi9 expression-init green); cleared stale gcc goldens, full suite 1314 passed 0 failed (codegen 86 — the new test is in the corpus); gate GO 6/6 frontier 06:0000000; rebuilt persist tcc (1010854 B) 36/36 battery + 8/8 g2 ladder + 7/7 cast probes all match oracle. New corpus tests/codegen/g2b_global64_init.c (1460 B, under the 4095 limit) discriminates BOTH ways: with fix exit 234 (== oracle 0xe8 hi + 0x01 hi + 0x01 lo), fix stashed exit 1. NEW pre-existing gap G12 (NOT a g2b regression, confirmed present with the fix stashed): a MISSING-DIAGNOSTIC leniency gap, not a miscompile. A global initialized by a plain global identifier (int a = 5; int b = a;) is INVALID C — an initializer must be a constant expression, and a non-const global is not one — so the oracle REJECTS the file with error: initializer element is not constant; bootcc instead accepts it silently and emits zero for b (gi11 / g12a/g12d/g12e all oracle=1[error] vs bootcc=0[zero, no error]). The ONLY valid cross-global constant reference is an ENUM constant, which bootcc ALREADY handles correctly via eval_atom -> s->ivalue (g12c: oracle=7 == bootcc=7). So the residual is a missing "initializer element is not constant" diagnostic on the non-enum-constant path in bind_global_scalar/eval_atom — a diagnostic-parity gap, low value (tcc never emits such an initializer, so it is NOT on the self-host/retarget path). Deferred. Carried non-blocking gaps: G3 (struct-return >16 B still needs the ABI fix — the copy path is fixed, the return-via-pointer convention is not), .o files written mode 000. NEXT increment: resume the retarget/smoke2 line (the bootcc-built tcc -run path — where the real blockers live); G12 (the diagnostic) is deferred, low value, and not on that path.
Position (updated after FIXING bug G9 (64->32 narrowing cast dropped in cg_cast) + bug G10 (unmasked >> 16 sign-extended in ex_lit_halves under the 32-bit-int gcc engine build) and closing G8 as a FIXTURE bug — G9: (int)x kept all 64 bits, so a later promoted width-8 compare read the full-width operand and (int)x == x collapsed to x == x (always true); G10: any hex literal with bit 31 set in the low 32 bits parsed to DIFFERENT values under the two engine builds (M2 64-bit int vs gcc 32-bit int); G8: the scratch tcc fixture's CValue.i/ExprValue.v were 32-bit long, truncating tokc.i at parse — restored to uint64_t, matching pristine 0.9.27; COMMITTED dfbcf49 (src/boot_sym.c + tests/codegen/cast64_to32_cmp.c); gate GO, frontier HOLDS 06:0000000):
G8 is a FIXTURE bug, not a bootcc bug, and this block corrects the scratch fixture's provenance record: the scratch fixture at ~/.jcode/scratch/tccx64/ is the tcc 0.9.27 sources with M2-Planet porting guards (tcc.h: NORETURN/ALIGNED stubs, bitfields widened to enums, HAVE_LONG_LONG guards; x86_64-gen.c:1244 VLA _onstack[nb_args] -> _onstack[1000]; tcc.c byte-identical to pristine 0.9.27; 45 diff lines vs pristine 0.9.27 but 525 vs 0.9.26, so it is 0.9.27-derived) plus a hand-written config.h whose TCC_VERSION "0.9.26" makes -dumpversion print 0.9.26 (a config artifact, NOT the source version — earlier notes calling the scratch "pristine 0.9.26" are corrected: pristine is 0.9.27 + porting). The G8 defect: the fixture's CValue.i and ExprValue.v were 32-bit long, so tokc.i was truncated at parse for 64-bit integer constants — the store path recovered the full width through other fields, but the compare path emitted a sign-extended imm32 (cmp $0xffffffffd4a51000 where pristine emits a register compare). Fix: uint64_t, restoring the pristine 0.9.27 shape (pristine already carries uint64_t i;/uint64_t v;). G9 is a bootcc codegen bug in src/boot_sym.c cg_cast: the truncation guard was w == 1 || w == 2, so a 64->32 narrowing cast was a NO-OP. Rule-7 minimal repro g1.c (unsigned long long x = 0xe8d4a51000ULL; return ((int)x == x);): oracle=0, bootcc-direct=1; disasm showed the cast operand materialized as a full 64-bit load. Disambiguation ladder: k2 (cast stored to a named int var — truncation survives via the store) PASSES, h4 (int==int, no promotion) PASSES, g3 (2^32) and g4 (signed neg) PASS, so the drop is specific to a width-4 cast operand consumed by a later width-8 compare. Fix: guard widened to w == 4 with a new branch — signed re-sign-extends the low dword (movsx_rax,DWORD_PTR_[rax]), unsigned zero-extends (mov_eax,[rax]), in the existing push/lea/add_rsp %8 pattern. That same pattern misfired tcc's OWN gen_op8 gate (!ll || (int)vtop->c.i == vtop->c.i), forcing the 64-bit const-compare down the cmp $imm32 path — the m4/m5/b2-b7/r1 battery failures. G10 is a bootcc literal-parser bug found chasing the m2==gcc emit drift the new corpus test exposed: ex_lit_halves' upper-half extractions lo >> 16/hi >> 16 were UNMASKED; once the running low half has bit 31 set (any hex literal >= 0x80000000 in the low 32 bits) the shift sign-extends under the gcc probe build's 32-bit int and pollutes the p1/q1 carry chain, while the M2 build's 64-bit int zero-extends the same shift — proven by a per-digit trace harness (hi = 0xffd8 under a 32-bit int vs 0xe8 under 64-bit for 0xe8d4a51000). Fix: mask both extractions & 0xFFFF so the halves are width-independent (the exact class the m2==gcc gate exists to catch; the new corpus's constant, low-32 0xd4a51000 with bit 31 set, exposed it). New corpus tests/codegen/cast64_to32_cmp.c (1247 B, under the 4095 libtcc-driver limit): signed + unsigned 64->32 narrowing in a compare, parameterized through three small functions to defeat constant folding; DISCRIMINATES both ways (oracle=0, with-fix=0, fix stashed=111). Verification: make all green; full suite 1313/0 (tokenizer 3, pp 23, parser 17, codegen 85, libtcc in-process 430, ltcc-so 774) after clearing the stale gcc golden drivers (rm -rf $TMPDIR/bootcc-libtcc-gcc $TMPDIR/boot-ltcc-so-gcc — the stale-golden trap after any emit-affecting engine change); gate GO 6/6 (frontier HOLDS 06:0000000); rebuilt persist tcc 1010854 B (M1=201426) -> full 64-bit battery 36/36 (m1-m5, b1-b8, c1-c6, ld1-ld9, r1-r8) match the oracle, cast probes g1/g3/g4/k1-k4 all 0/0. Carried gaps (NOT blocking): G3 struct-return >16 B (SysV hidden-pointer ABI); .o files written mode 000 (a distinct constant-corruption symptom; pristine tccelf.c ~1989 uses mode = 0666 for OBJ / 0777 else); NEXT increment g2 residual: static unsigned long long gx = 0xe8d4a51000ULL file-scope global initializes to 0 in the bootcc output — a 64-bit GLOBAL-INIT bug, distinct from G9's cast bug (the rule-7 repro already exists at scratch g2.c).
Position (updated after FIXING bug G7 — block-scoping / name shadowing in the flat eslot table: a name redeclared in a sibling (or nested, or switch-case-body) block resolved to the FIRST slot of that name, so the declaration store wrote at the NEW width into the OLD slot and clobbered a neighbour local; COMMITTED 4b57f72 (src/boot_sym.c + tests/codegen/block_scope.c); gate GO, frontier HOLDS 06:0000000):
G7 is FIXED in src/boot_sym.c (committed 4b57f72). Root cause (NOT width allocation — a distinct-names control w7_diff passed, which is what first disambiguated it): es_find returned the FIRST slot matching a name in the flat eslot table, so a redeclaration of a/b in a SIBLING block resolved to the earlier block's slot; the declaration store then writes at the NEW declaration's width (cg_store(esize(stnode[s].dt)), ~8050-8054), so an 8-byte long store landed in the earlier 4-byte int slot and clobbered the neighbouring bad local. Probe g3/b1b9.c (block B1 int a; unsigned b then sibling block B9 long a; unsigned long b) returned 1, oracle 0; w7_instr.c (a distinct bit per check) fired only bit 2 (B9's check2), confirming B9's stores hit B1's slots. Fix: each slot now records the block it was declared in — eslot.bid = the innermost open ST_BLOCK's stnode index (0 = function/global scope) — and both passes keep an open-block ancestor stack (es_scope_stack/es_push/es_pop). layout_stmt and cg_block walk the SAME ST_BLOCK tree, so each pushes/pops the same block node index at the same tree position; the switch body (which cg_switch unwraps with if(ST_BLOCK) body_top = body_top.a and walks directly, bypassing cg_block) pushes the same ST_BLOCK node too, guarded on ST_BLOCK so a non-block body matches layout. es_find now resolves to the VISIBLE slot in the DEEPEST open block: es_rank(i) is the open-block position of the slot's bid (0 for function scope, -1 when the block is closed/not an ancestor), and the scan keeps the highest rank with a strict-greater tie-break that preserves the old first-match behaviour for the rank-0 parameter-vs-file-global case (param is added before the global, so it still wins). A note on a WRONG first attempt: a scope-DEPTH counter was tried and reverted — B1/B9 are siblings at the SAME nesting depth so depth cannot distinguish them, and a top-of-block decl must stay visible within its own block. New corpus tests/codegen/block_scope.c (1568 B, under the 4095 libtcc-driver limit): sibling same-name int/long (the G7 trigger), a nested x shadow with the outer surviving, a switch-case-body a/b shadow, and a distinct-names control — oracle rc=0 == bootcc rc=0 and it DISCRIMINATES (rc=4 with the fix stashed). All prior corpora stay green (84/84 codegen, 425 libtcc, 765 so); rebuilt scratch tcc 1009267 B. Gate GO (make green, determinism, newlines, frontier 06:0000000 holds). NEXT increment: no further named G-frontier is currently open (G3 known gap — a >16-byte struct-return RHS into a struct falls to the 2-reg path — is recorded but non-blocking and was carried from before G4); the natural next increment is either to hunt the next divergence by compiling real tcc.c surface (rule-7 tiny-failing-repro discipline) or to close the G3 struct-return gap.
Position (updated after FIXING bug G6 — char/short relational comparisons didn't apply integer promotion, so signed char c=-1; unsigned char u=1; c < u compared UNSIGNED (0xff vs 1, false) where C promotes both to signed int (-1 < 1, true); COMMITTED 745a1c6 (src/boot_sym.c + tests/codegen/char_promote.c); gate GO, frontier HOLDS 06:0000000):
G6 is FIXED in src/boot_sym.c ex_node_unsigned (committed 745a1c6). Root cause (rule-7 repro g3/g6b.c: signed char c=-1; unsigned char u=1; return (c<u)?1:0; oracle 1, bootcc 0; disasm showed BOTH LOADS CORRECT — movsbq for c (-1) and movzbq for u (1) — but cmp %ecx,%eax; setb UNSIGNED because ex_node_unsigned read typ->signed_p directly and u's declared type is unsigned): C integer promotion says a signed/unsigned type narrower than int promotes to plain (SIGNED) int, so the comparison is signed -1 < 1. Fix: ex_node_unsigned returns signed for any operand type with esize < 4 (char/short and their unsigned forms); only width-4+ unsigned operands (unsigned int/long/long long) make the comparison unsigned; pointer types (width 8) are untouched. New corpus tests/codegen/char_promote.c (1970 B, under the 4095 libtcc-driver limit): signed/unsigned char + short pairs, an unsigned-char-positive control, and an int-vs-unsigned control that must stay unsigned — oracle rc=0 == bootcc rc=0 and it DISCRIMINATES (rc=4 with the fix stashed). G4/G5 corpora stay green; rebuilt scratch tcc (1009271 B) unchanged at r1/triv/q2 rc=7 and compiles the G6 shape rc=1. Gate GO (make green, determinism, newlines, frontier 06:0000000 holds). NEXT increment G7: a function redeclaring a name in a sibling block (pair repro B1+B9: int/unsigned block then a long/unsigned long block, returns 1, oracle 0; B9 alone and B9+B10 two-long-only both pass, so pure width-8 is fine). Originally framed as a slot-allocation/width interaction in alloc_local/frame layout (disasm showed a 4-byte type with a wider store); later disambiguated by a distinct-names control that PASSED, so the true root cause is block-scope/name-shadowing in the flat eslot table — see the G7 line above (FIXED 4b57f72).
Position (updated after FIXING bug G5 — integer-literal u/U suffix dropped, so int a=-7; a < 1u compared SIGNED (true) where C's usual-arithmetic-conversion makes it 0xfffffff9 vs 1 (false); COMMITTED 27b4011 (src/boot_sym.c + tests/codegen/ulit_unsigned.c); gate GO, frontier HOLDS 06:0000000; G6 (signed char zero-extend on load) is the next increment):
G5 is FIXED in src/boot_sym.c ex_primary (committed 27b4011). Root cause (rule-7 repro g3/g5.c: int a=-7; return (a < 1u)?1:0; oracle 0, bootcc 1; disasm cmp %ecx,%eax; setl — SIGNED): ex_lit_halves only consumed the digits of the literal and ex_primary marked EVERY integer literal sign=1 + make_type() (which defaults signed_p=1), so a u-suffixed literal carried no unsigned-ness; cg_cmp classifies through ex_node_unsigned (reads typ->signed_p first) and thus emitted signed setcc. Fix: the tokenizer keeps the FULL literal text in cur->s and a u/U in that text can only be a SUFFIX (hex digits are 0-9a-f), so ex_primary now sets enode[jx].sign=0 + typ->signed_p=0 whenever the text carries u/U (covers 1u, 1UL, 0x10U); the G2 bit-31 u32 zero-extend idiom is untouched. New corpus tests/codegen/ulit_unsigned.c (1471 B, under the 4095 libtcc-driver limit): negative/positive int vs u-literal across < > <= != ==, hex 0x10U, and a signed-literal control — oracle rc=2 == bootcc rc=2 and it DISCRIMINATES (rc=4 with the fix stashed). No golden drift: the only u-literal in the parse corpus is tests/parse/unsigned.c:15 (10u), which flows through the -s symbol dump only (gate parse phase green). Rebuilt scratch tcc (1009271 B) unchanged at r1/triv/q2 rc=7. Gate GO (make green, determinism, newlines, frontier 06:0000000 holds). NEXT increment G6: a signed char local is ZERO-extended on load instead of sign-extended, so signed char c=-1; unsigned char u=1; c < u compares 0xff vs 1 and c > u fires (c8b repro, pre-existing — present with the G4/G5 fixes stashed). Then G7 (width-4 + width-8 locals in one scope emit wrong code).
Position (updated after FIXING bug G4 — signed-vs-unsigned relational comparisons of width-4 operands compared a 64-bit cmp rax,rcx of two operands each extended with ITS OWN sign, so int -4 != (unsigned)-4 came out true; COMMITTED 96f0822 (src/boot_sym.c + tools/amd64_defs_extra.M1 + tests/codegen/cmp_mixed_sign.c); gate GO, frontier HOLDS 06:0000000; NEW front-end bugs G5/G6/G7 recorded):
G4 is FIXED in src/boot_sym.c cg_cmp (committed 96f0822). Root cause (gdb + direct-chain disasm, rule-7 repros g3/{sgn,v1..v6,g4a,g4b}.c): a comparison between a signed and an unsigned 32-bit-class operand loaded each side with its OWN sign (movsx for signed int, mov eax zero-extend for unsigned int) and then emitted a 64-bit cmp rax,rcx, so int -4 (0xfffffffffffffffc) and (unsigned)-4 (0x00000000fffffffc) compared UNEQUAL where C says equal; the same shape misfired tcc's own load() guard if (fc != sv->c.i) (fc int, c.i unsigned int, both -4) at x86_64-gen.c:390, forcing the 64-bit-CONST path movabs $-4; mov (%rax) -- a local slot offset reloaded as an absolute pointer -- and segfaulting EVERY bootcc-built tcc compile of int x=5; return x+2; (r1). Fix: cg_cmp computes w = max(rwidth(a), rwidth(b)) and emits the new 32-bit cmp_eax,ecx (39 C8, added to tools/amd64_defs_extra.M1 because the vendored amd64_defs.M1 is checksum-gated) when w <= 4, else the existing cmp_rax,rcx; after cg_binlr both rax/rcx hold the correct value in the low 32 bits regardless of per-operand extension, and setcc reads the same flags for a 32-bit cmp of equal low halves. Verified: all direct-chain repros now match the oracle; the permanent corpus tests/codegen/cmp_mixed_sign.c (width-4 signed/unsigned shapes, all six relational ops, short-promotion) is oracle rc=0 == bootcc rc=0 and passes the libtcc in-process emit/link/run three-pass; the rebuilt scratch tcc (1009271 B) compiles r1 to 8b 45 fc (mov -0x4(%rbp),%eax, rbp-relative) and -run returns 7. Gate GO (make green, determinism, newlines, frontier 06:0000000 holds). THREE new pre-existing front-end/codegen bugs were found while writing the corpus (each verified present with the G4 fix stashed + rebuilt; NONE are G4 regressions): (G5) the u suffix on an INTEGER LITERAL is not recorded, so int a=-7; a < 1u compares SIGNED (bootcc true, oracle false); (G6) a signed char local is ZERO-extended on load instead of sign-extended, so signed char c=-1; unsigned char u=1; c < u compares 0xff vs 1 (c > u fires); (G7) a function MIXING width-4 and width-8 (long) locals in one scope emits wrong code (pair repro B1+B9 returns 1, oracle 0; B9 alone and B9+B10 two-long-only both pass, so pure width-8 is fine -- initially read as a slot-allocation/width interaction; a later distinct-names control PASSED and re-root-caused it to block-scope name-shadowing in the flat eslot table, FIXED 4b57f72). NEXT increment: G5 (literal u suffix) -- smallest and most front-end-local. GATE-HAZARD NOTE: the libtcc in-process driver reads the snippet into a fixed SNIP_MAX 4096 buffer (tests/libtcc/driver.c:36) and truncates sources > 4095 bytes mid-token, making the engine parser segfault (rc=139, at_compound_assign) -- the m2==gcc emit gate still "passes" there (stale M1 copy) so this fails OPAQUELY at libtcc-run; keep tests/codegen/*.c under 4095 bytes (this corpus is 3295 B) or grow SNIP_MAX as its own increment.
Position (updated after FIXING bug G3 — >16-byte struct copies lost their tail — COMMITTED 467dd5a (src/boot_sym.c + tests/codegen/agg_copy_gt16.c); gate GO, smoke2 rc=7, q2 (g()+4) now rc=7 in the built tcc; NEW bug G4 (local reload emitted as absolute address, no calls needed) root-caused to a VT_LOCAL->VT_CONST bit-0 drop in tccgen.c, is the next increment):
G3 (the scratch tcc miscompiles a call inside a binary expression — g()+4 returned 3; g()+h(), g()*h(), x=g();x+4 segfaulted) is FIXED. Root cause (boundary probes via the direct chain, rule-7 repros g3/svswap.c + bnd_16/24/40.c): a 32-byte struct copy (the shape of tcc's vswap at tccgen.c:667, a by-value copy of the 48-byte SValue) loaded both eightbytes (rax=[0..7], rdx=[8..15]) but the store emitted only mov_[rbx],rax — 8 bytes — because cg_load_agg2 hardcodes rax/rdx, cg_store(w) stores only 8 bytes when w>8, and agg_t_is_2reg covers only 8<size<=16. tcc's real vswap copies a 48-byte SValue, so bytes 8..47 (including c) were lost and gen_opi's first vswap no-op'd, turning g()+4 into mov $4,%ecx; add $4,%ecx (the constant added to itself; the call result discarded). tcc's own lowering for >16-byte structs is a memcpy call (x86_64-gen.c:818), and bootcc already links a SysV FUNCTION_memmove. Fix in src/boot_sym.c: new agg_t_is_large(t) (struct/union, size>16) + cg_copy_large_agg_memmove(l,b,size) (RHS address first for C evaluation order, cg_addr(b); mov_rsi,rax; cg_addr(l); mov_rdi,rax; mov_rdx,%size; push_r13; call %FUNCTION_memmove; pop_r13), routed from (a) cg_assign EX_ASGN before the 2reg branch, guarded enode[enode[e].b].lv != 0 (lvalue RHS — a struct-RETURNING-CALL RHS still falls through to the old 2reg path, a known deliberate gap) and (b) the cg_stmt ST_DECL initializer after the agg_t_is_2reg block, building an EX_IDENT dst node for the new local. New permanent corpus tests/codegen/agg_copy_gt16.c (32- and 48-byte structs, vswap-shaped swap + direct a=b assign). Two gate-side incidents root-caused, NOT miscompiles: (1) my forward decl was cg_copy_large_agg_memmove(void) vs the (int,int,int) definition — M2 silently accepted it (make all rc=0) but the libtcc-emit gate's host-gcc reference driver rejects C89 signature conflicts (that gate is the only thing that catches what M2 tolerates; after any engine-source change, clear the cached gcc reference drivers /tmp/bootcc-libtcc-gcc/driver, /tmp/boot-ltcc-so-gcc/driver + $TMPDIR=/home/lrvick/.jcode/scratch variants); decl fixed. (2) a stale Sep-1 cached gcc driver. Verification: direct chain svswap 1->0, bnd_16 0, bnd_24 32->0, bnd_40 64->0; new corpus rc=0==oracle; full gate green (make test rc=0, 0 FAIL: tokenizer 3, pp 23, parser 17, codegen 80 (+1), libtcc 405/0, ltcc-so 729/0). Self-host: rebuilt scratch tcc (1011605 B): smoke2 triv.c rc=7 (goal holds), q2.c g()+4 rc=7 (was 3 — G3 fixed end-to-end). Direct chain compiles p4/p5/p6 correctly (7/12/7). NEW BUG G4 (now that G3 no longer masks it): in the BUILT tcc, a local saved via a call or assignment and then re-read in an expression is stored correctly (mov %eax,-0x4(%rbp)) but RELOADED as an ABSOLUTE address load — movabs $0xfffffffc,%rax; mov (%rax),%eax (segv) instead of mov -0x4(%rbp),%eax (p4 g()+h(), p5 g()*h(), p6 x=g();x+4 all rc=139 in the built tcc; the store half is correct in every case, and q2 g()+4 works because it reloads through rax without the broken reload). The direct chain emits the correct r13-relative reload for all three, so this is bootcc miscompiling tcc's OWN local-load codegen — a distinct engine defect. Refined this session (rule-7 bisection, probes g3/r1..r7): the minimal failing repro is r1: int main(void){int x=5; return x+2;} — a plain const-initialized local, NO calls, NO structs (all 7 probes segv rc=139 in the built tcc; the direct chain compiles r1 correctly rc=7 since it uses bootcc's OWN codegen, not tcc's x86_64-gen.c). Exact disasm diff (store is correct in BOTH; only the reload differs): store mov %eax,-0x4(%rbp); oracle load mov -0x4(%rbp),%eax (modrm 0x45 = rbp-base via gen_modrm's VT_LOCAL branch o(0x45|op_reg); g(c)); built-tcc load movabs $0xfffffff4,%rax; mov (%rax),%eax (base DROPPED — offset -4 becomes an absolute pointer in rax, then dereferenced). DEDUCTION: the STORE uses the same SValue and the same gen_modrm(VT_LOCAL) and is correct, so gen_modrm's VT_LOCAL path is FINE in the built tcc; therefore the LOAD's SValue must reach load() with r & VT_VALMASK == VT_CONST (0x30) instead of VT_LOCAL (0x32) — a difference of exactly bit 0 (0x02) — so the local is mis-typed as an absolute address (then the int is dereferenced from [rax]). So bootcc miscompiles the C in tccgen.c that computes/reads the local-reference SValue's r tag (the vpushsym/vpush identifier-reference path, tccgen.c:~936-1032, where sym->r = ... | VT_LOCAL / p->r = lvalue_type(...) | VT_LOCAL), dropping bit 0 of the register tag. Same CLASS as G2 (a bit-level codegen defect), a DIFFERENT construct. NEXT increment (G4): (1) extract the exact C construct from tccgen.c's identifier-reference path that bootcc miscompiles into a tiny DIRECT-CHAIN failing repro (must fail the direct chain — the self-host r1 does not, because bootcc's own codegen is correct; so reduce to the specific r = ... | VT_LOCAL / SValue-tag arithmetic construct); (2) fix bootcc's codegen for that construct; (3) add a tests/codegen/ corpus; (4) full gate + rebuild scratch tcc + re-verify r1 (rc=7) and smoke2 (rc=7) + commit + STATE.
Position (updated after FIXING bug G2 — the scratch tcc -run cross-call rip=0 crash; commit 8786da5; smoke2 still rc=7, cross-call no longer crashes, but a NEW latent engine bug G3 is now exposed):
G2 (scratch tcc -run of a program whose main calls a second function jumped to rip=0) is FIXED. Root cause (gdb ground-truth + hardware watchpoint, not a prior hypothesis): the r_info was stored CORRECTLY by put_elf_reloca (0x200000004) but was clobbered DOWNSTREAM by two remap passes — tccelf_end_file (sym 2->4) then sort_syms (sym 4->0 -> *ABS* -> call to 0). The corruption source: ELFW(R_TYPE)(i) = (i) & 0xffffffffL — the 32-bit 0xffffffff mask immediate was emitted by cg_const_rax through M1's sign-extending mov $imm32, landing as 0xffffffffffffffff in the 64-bit AND. R_TYPE then returned the full r_info instead of the low-32 type, so R_INFO(sym,type) folded the type into the symbol field (sym 2->4), and sort_syms indexed old_to_new_syms[4] (out of bounds for a 4-entry non-zeroed table) -> 0 -> *ABS*. Fix: a u32 flag set at the INTEGER-LITERAL parse site (a direct literal with hi==0 and bit-31 set is necessarily C-unsigned/long and must zero-extend), and cg_const_rax routes u32 literals through the existing 16-bit-piece zero-extend idiom; folded negatives (-1) keep sign-extending (different node, u32==0). Rule-7 repro tests/codegen/u32_mask_zeroext.c was FAILING (v=200000004 vs oracle v=4), now PASSES. Full gate green: codegen 79, parse 17, pp 23, tokenizer 3, libtcc 395, ltcc-so 711. Scratch tcc rebuilt (1011822 B): smoke2 -run triv.c STILL rc=7; cross-call q2.c no longer rip=0. NEW BUG G3 (now that G2's crash no longer masks it): the scratch tcc miscompiles a call inside a binary expression — int g(void){return 3;} int main(void){return g()+4;} returns 3 not 7 (disasm: mov $4,%ecx; add $4,%ecx — the constant lands in ecx and is added to ITSELF; the call result in eax is never consumed; oracle emits add $4,%eax). Also x=g(); x+4, g()+h(), g()*h() segfault (rc=134/139). The DIRECT bootcc chain compiles the SAME source correctly (rc=7), so this is bootcc miscompiling tcc's OWN x86_64-gen.c op-emission, NOT the engine miscompiling user source. NEXT: root-cause G3 in the engine's x86_64-gen.c compilation (failing direct-chain repro of the tcc_gen_op pattern first).
Position (updated after FIXING the true smoke2 root cause — chained pointer arithmetic lost its element scale; frontier HOLDS at 06:0000000; smoke2 advances from the put_elf_sym SEGV rc=139 to two new, precisely-diagnosed blockers in the compiled tcc's own runtime-library path):
the root cause of the smoke2 put_elf_sym SEGV was NOT a prologue stack-arg offset, NOT a macro-arg-split, and NOT upstream frame corruption — all three prior hypotheses were disproven this session (7-arg forwarding repro passes; x64m1..x64m5 pass 155==155 with net stack = exactly the 7 correct args). The true cause: ex_bin (src/boot_sym.c) creates every binary-op result node as TYPE_INT and never inherits a pointer operand's type, so (T*)p + a + b kept its scale through the first ADD (left operand a pointer) but the ADD's RESULT was typed int, and the second ADD emitted a plain unscaled byte add — the pointer advanced 1, not sizeof. Forensics: gdb data dump of the tccelf.c:169 loop ElfSym *sym = (ElfSym*)s->data + first_sym + i showed sym +1 byte per iteration (0x8c4430 -> 0x8c4431, not +24); the byte-shifted row gave name=0x48c43d0 (below image base 0x600000) -> SEGV at name[0]. Fix: ex_bin now inherits the pointer type for EX_ADD/EX_SUB when either operand is a pointer (T* + int -> T*). New corpus tests/codegen/ptr_scale_chained.c VERIFIED DISCRIMINATING (with fix rc=102 == tcc 102 stdout "102"; fix stashed -> rc=52). All suites green (3+23+17+72 codegen + libtcc in-process + so = 0 failed; the two gcc oracles refreshed — cached by existence only, built pre-fix); two clean M2 builds cmp byte-identical; gate GO. The scratch config.h also got an environment completion (tcc sources byte-identical): CONFIG_TRIPLET "x86_64-linux-gnu" + CONFIG_TCCDIR "/usr/lib/x86_64-linux-gnu/tcc" (a normal Debian install's config), which removed the three "not found" errors (libtcc1.a and libgcc_s paths now resolve — confirmed in the binary's embedded strings). smoke2 now: the put_elf_sym SEGV is GONE — the compiled tcc completes triv.c codegen + ELF symbol emission and reaches the runtime-library stage, but two DISTINCT bugs in the compiled tcc's own logic (i.e. further bootcc codegen defects manifesting inside tcc, not in the build chain) surfaced: (A) "library 'c' not found" although LIBPATHS contains the right dir — strace shows it NEVER stats any path (the tcc_add_library loop appears to iterate 0 times; LIBRARY_PATH env changes nothing); (B) after that it opens //lib/x86_64-linux-gnu/libgcc_s.so.1, reads 8192 bytes OK, then SPINS in a tight malloc/brk loop (RIP=0x6afaa1 inside its own .text, char-scan loop; fully static image, no glibc; the earlier "sigsuspend in libc" was a mis-attach to the timeout-wrapper PID). NEXT: pin bug (A) with a minimal bootcc repro. See TASKS/NEXT.md.
Position (updated after CLOSING the x86_64 retarget EMIT path — the M2-built build/amd64/bootcc now compiles the FULL x86_64 tcc.c cleanly to ~2.3 MB M1; frontier HOLDS at 06:0000000, no ratchet exception):
three real blockers on the x86_64 retarget probe cleared, each isolated with a repro and (for engine defects) a TCC-parity corpus. (1) abort environment gap: the x86_64 backend's gen_mov64 dead-code fallback calls abort() (x86_64-gen.c:607/615) which portable_libc's stdlib.h does not declare — the first x86_64-specific codegen: undeclared identifier was on abort (the i386 backend never calls it); the scratch assert.h shim in /home/lrvick/.jcode/scratch/tccx64/ gains void abort(void); (environment completion, tcc sources byte-identical). (2) MULTI-LINE MACRO ARGUMENT (src/boot_pp.c clone_arg): a function-like macro argument spanning multiple lines was truncated at end-of-line because clone_arg passed the line's eol as the argument bound; it now passes NULL (the argument's own continuation-newline tokens bound it), and pp_walk gained a cross-line re-anchor (a spanned flag: when a macro expansion's resume token lands past the line's eol, set cur=nt, emit the consumed eol, and break so the outer loop re-runs line setup). (3) BARE FUNCTION-SCOPE ENUM SEGFAULT (src/boot_sym.c parse_local_decl): x86_64-gen.c:1195 classify_x86_64_va_arg holds a function-scope BARE ENUM (enum __va_arg_type { ... };, no declarator); parse_local_decl built an ST_DECL with name=NULL and layout_stmt called alloc_local(NULL) -> segfault in es_add (rc=139 after the M1 had emitted); the fix skips the ST_DECL node for a bare type declaration (no declarator name), consuming a trailing comma and keeping the new_sym call guarded by ty != NULL. New corpora tests/codegen/multiline_macro_arg.c (5) + tests/codegen/bare_enum_local.c (6), both TCC-parity green (71 codegen suites, 0 failed). USER CORRECTION CODIFIED (AUTONOMY.md rule 6): "we must never rely on GCC — bootcc must be fully buildable with M2Libc/M2" — the product build must be pure M2-Planet; GCC may exist only as an optional m2==gcc byte-drift oracle, never a build input, gate requirement, or validation path. The faithful x86_64 probe (frontier-probe) is gcc-built, so the increment was re-validated gcc-free: the M2-built build/amd64/bootcc compiles the full x86_64 tcc.c cleanly (m2-rc=0, err-bytes=0, tccx64-m2.M1 = 2,302,506 bytes) and the i386 tcc.c (2,191,066-byte M1); the product build is confirmed pure M2 -> blood-elf -> M1 -> hex2. The two libtcc-so-emit failures were stale-oracle artifacts ($GCDIR/driver cached by existence only, built pre-change); refreshing cleared them. make test all suites 0 failed; two clean M2 builds cmp byte-identical; sh tools/gate.sh GO (frontier HOLDS 06:0000000 — the frontier measures the i386-target tcc.c emit, unaffected by the x86_64 probe work). NEXT: wire tools/build-tcc.sh to the x86_64 target (M2-built bootcc, x86_64 AFLAGS, scratch tcc copy) and run the 4-step chain to assemble the ~2.3 MB M1 into an ELF tcc -> smoke2 tcc -run triv.c must return rc=7. See TASKS/NEXT.md.
Position (updated after FIXING the enum-typed-variable-as-constant misclassification — the first engine blocker on the x86_64 retarget path; frontier HOLDS at 06:0000000, no ratchet exception):
the engine classified ANY SC_AUTO enum-typed symbol as an enumerator (is_enum_const in src/boot_sym.c checked only type->kind == TYPE_ENUM && storage == SC_AUTO), so a function-local enum M mode; — or a file-scope enum M g; — was built as an rvalue EX_CONST (lv=0) and any assignment to it died "lvalue required in assignment" at boot_sym.c:2227. This wall first surfaced on the x86_64 retarget probe (x86_64-gen.c:1127, the X86_64_Mode mode; locals), which is the COHERENT fix for the smoke2 stop-rule goal: the bootcc-built tcc is an ELF 64-bit x86-64 process that self-identifies (i386 Linux) (config.h:10 TCC_TARGET_I386, -DPTR_SIZE=4), so it EMITS 32-bit code that in-process -run (TCC_OUTPUT_MEMORY -> tcc_relocate -> main()) cannot execute in a 64-bit host — a hard architectural wall (a gcc reference tcc with the same i386 config segfaults identically; the known-good control is the x86_64 system tcc 0.9.27, where host==target==64-bit). Fix: struct symbol gains int is_enum (src/bootcc.h); the enumerator registration in parse_enum is the ONLY place it is set (es->is_enum = 1), and is_enum_const now returns s->is_enum != 0 — enumerators are constants by registration, enum-typed variables are ordinary lvalues at ANY scope. (The first-cut scope_index != 1 hack was replaced because it would have left a file-scope enum M g; broken.) Repros v7 (local enum assign) and v12 (file-scope enum global + local) both pass -x with lv=1; the x86_64 x86_64-gen.c -e probe now advances PAST the 1127 wall to a distinct later blocker (codegen: undeclared identifier at token line 2274, beyond the file's 2258 lines — a token-stream offset, the NEXT increment on the retarget path). New corpus tests/codegen/enum_local.c (local enum decl+assign, file-scope enum global store, three enumerator values; returns 4) is TCC-parity green (der=4 tcc=4, stdout identical) and passes the libtcc in-process + -ltcc/dlopen suites. make test is 3 tokenizer + 23 preprocessor + 17 parser + 69 codegen + 350 libtcc in-process + 630 libtcc shared-object = 0 failed; m2==gcc emitted-M1 gate holds; two clean M2 builds cmp byte-identical; sh tools/gate.sh GO. This is a NO-ADVANCE increment (frontier measures the i386-target tcc.c emit, unaffected by the fix). NEXT: reduce the x86_64 x86_64-gen.c "undeclared identifier" (token line 2274) blocker. See TASKS/NEXT.md.
Position (updated after the codegen-hardening bundle + the struct-copy size-clamp that unblocks the bootcc-built tcc -run past "cannot cast from/to void" — frontier HOLDS at 06:0000000 (no ratchet exception); smoke2 advances rc=1 -> rc=139 at a NEW link/lib-path blocker):
The headline fix is the STRUCT-COPY SIZE CLAMP (src/boot_sym.c cg_assign + new cg_store_agg_n): the SysV 9..16-byte aggregate ASSIGN path copied BOTH eightbytes (16 bytes) unconditionally, so a 12-byte struct FuncAttr copy (s->f = ad->f in post_type, bootcc-built tcc) wrote 4 spare bytes into the ADJACENT CType type.t, zeroing the function's return type; the built tcc then read func_vt = sym->type = VT_VOID in gfunc_prolog and failed every function with "cannot cast from/to void". The store now writes EXACTLY the aggregate's real size (second half as 4/2/1-byte chunks totalling size-8; size 16 unchanged), which is strictly less overwriting and strictly more correct. The built tcc now compiles triv.c's codegen cleanly and reaches the LINK phase. Bundled with it: (1) sal_rbx ModRM byte 48C1E1->48C1E3 (rcx->rbx; the wide-constant idiom's middle-16 shift, root of the 4 codegen regressions); (2) cg_const_rax hi==0 single mov $imm32 sign-extension (was zero-extending, so -9 printed 4294967287); (3) parse_specifier long long int trailing-int (was a spurious global int + lost function). Runtime: the printf digit-stack drop + fopen path fixes (tcc_runtime.S/.M1, 149 symbols). New corpora tests/codegen/{anonunion,goto_label,multistr,bitinit}.c. make test is 3+23+17+68+345+621 = 0 failed; two clean M2 builds cmp byte-identical; sh tools/gate.sh GO. NEW -run blocker (stop-rule goal step): the built tcc links triv.c but cannot find its standard libraries at the CONFIG-hardcoded absolute paths — /tcc/libtcc1.a (CONFIG_TCCDIR "/tcc", config.h:5), //lib/libgcc_s.so.1 (CONFIG_SYSROOT "/" + CONFIG_LDDIR "lib"), and libc — none exist in the build environment; it then segfaults (rc=139) in the missing-library error path. The i386 target (config.h:10 TCC_TARGET_I386) is a separate latent concern (the i386 gfunc_prolog is compiled) but did NOT cause the void-cast error — that was the struct-copy clobber, now fixed. NEXT: resolve the library path (where libtcc1.a/libc/libgcc_s live, and whether the freestanding tools/tcc_runtime.M1 is meant to replace them for the -run link) and the error-path segfault. See TASKS/NEXT.md.
Position (updated after FIXING the entire -v crash chain in the real tcc.c built by bootcc — four verified engine fixes, commit e099b0e; frontier HOLDS at 06:0000000 (no ratchet exception); -v is now rc=139 at a NEW distinct NULL-deref):
(1) SWITCH CASE-LABEL OVERFLOW (src/boot_sym.c cg_switch): the fixed 64-slot sw_lab/sw_val/sw_isdef arrays overflowed on next_nomacro1's 97 labels (96 cases + default; tccpp.c:2583-3100), and writes at label 65+ ran past the arrays into the ADJACENT sw_val[] slots (e.g. sw_val[0] got a label number, so the " " case compared cmp $0x1 instead of cmp $0x20); now #define SW_MAX 256 with guarded writes and grown save_lab/save_val/save_def[SW_MAX] — the largest switches in tcc are 98 (tccpp.c), 68 (tccelf.c), 50 (libtcc.c), 46 (tccgen.c). (2) _start NEVER PASSED ARGV (src/boot_sym.c emit_runtime): for these static ELFs the kernel sets up the stack ([rsp]=argc, [rsp+8]=argv, gdb-verified) but leaves rdi/rsi zeroed, while the emitted _start did mov rbp,rsp; call main relying on them; _start now loads argc/argv from the stack (mov rax,rsp; mov rax,[rax]; mov rdi,rax; lea rsi,[rsp+8]) before calling main. (3) FOR-LOOP continue SKIPPED THE INCREMENT (src/boot_sym.c cg_for): con_lab[con_n] = lc pointed continue at the loop TOP, orphaning the increment block, so for(i=0;i<n;i++){if(..)continue;} spun forever — this is what froze tcc_parse_args' option scan (strstart called 40+ times with val="h"); continue now targets a new label li before the increment when one exists (li = lc for increment-less for-loops, so their behavior is unchanged). (4) ESC_FV.C RAW NUL BYTE (test file): the previous session's write-tool backslash mangling left a NUL at offset 111 in the comment; bootcc -e (byte stream) was fine but the libtcc in-process driver reads into a NUL-terminated buffer, truncating the snippet so main was missing from the M1 (4 failures); rewritten via python3 (chr(92)), od -c-verified, all tests scanned clean. New regression tests: tests/codegen/switch_many.c (74 labels, fallthroughs, hits first/middle/beyond-64 + default), tests/codegen/argc_argv.c (argc must be 1), tests/codegen/for_continue.c (continue must run the increment) — plus the prior session's neg_int_loop.c and the rewritten esc_fv.c. make test is 3 tokenizer + 23 preprocessor + 17 parser + 64 codegen + 325 libtcc in-process + 585 libtcc shared-object = 0 failed; two clean M2 builds cmp byte-identical; sh tools/gate.sh GO. -v progress: rc=139 (old crash) → 1 (argv zero) → 124 (continue spin) → 139 at a NEW, distinct, documented blocker: NULL-deref at mov (%rdi),%rax in an unnamed early-runtime function (0x6007b3 in the last build), called from a printf/error path (caller region ~0x66d638: printf(STRING_84), then 2× call 0x6004a2, then the crashing fn with rdi=NULL) — addresses shift on every rebuild, re-nm after each build; the likely target is the version/error1 output path, exactly what -v needs. The prior session's "sprintf drops last digit" and "member-store/garbage buf_ptr" theories remain disproven/unreproduced. NEXT: identify the crashing function by nm + disasm after a fresh 4-step rebuild and fix the NULL argument. See TASKS/NEXT.md.
Position (updated after FIXING the stage-5 X-macro enum wall + the nine real-tcc defects it exposed + the pre-existing static 2D array row-stride bug — the full real tcc.c -e now PASSES CLEAN; frontier 05:0000386 -> 06:0000000, stage 5 -> stage 6):
the last wall between bootcc and a cleanly-emitted full tcc fell in one increment (commit cb92319). (1) X-MACRO ENUM (tcc.h:1067): directives inside the enum tcc_token { ... } braces now expand in place to the ,TOK_X rows, and enum constants resolve in expressions including the forward-referencing TOK_LAST = TOK_IDENT - 1. (2) Nine engine defects past the enum, each with a tests/codegen/ corpus: prototype param-name leak into definitions (emit_function_asm now prefers the is_def type — kept at M2's four-local limit, since a fifth local there miscompiles under M2 and corrupts an UNRELATED function's run-time emit), bare while (0); -> ST_EMPTY, trailing char const, pp ## paste rescan, return-comma, selfref typedef, sizeof-arg call, struct-ternary assign, enum-init-newline. (3) STATIC 2D ARRAY ROW STRIDE (pre-existing in HEAD, not a WIP regression — HEAD fails identically): esize() intentionally reports the decaying 8-byte width for any TYPE_ARRAY (alloc_local overrides to t->size for frames; es_add stores 8 for the decayed value), but ginit_fill's row advance and pointee_sz's index scale used esize(ty->base) as a ROW STRIDE, so int m[4][4] data rows landed at 8 (not 16) and names[i] scaled by 8 (not 4) — data and code consistently wrong while the -s type dump looked right; pinned by host-gcc A/B (same broken bytes) + a fprintf trace showing the outer row advance at 8. New elem_bytes(t) (array element -> t->size, else esize) fixes the five ginit_fill sites + pointee_sz, leaving decay semantics untouched. Probes exact: const-index 2D int (14), variable-index diagonal loop (34), char[4][4] string-init const_trailing (40). Nine new corpora; stale /tmp gcc reference drivers rebuilt. make test 3 tokenizer + 23 preprocessor + 17 parser + 59 codegen + 300 libtcc in-process + 540 libtcc shared-object = 0 failed; m2==gcc emit gate holds for every corpus; two-clean-build cmp byte-identical; gate GO, ratchet advanced (no exception). NEXT: LINK + RUN the emitted full-tcc M1 through the vendored blood-elf/M1/hex2 chain and smoke-test its CLI on a trivial C file — the stop-rule goal ("bootcc builds a runnable tinycc 0.9.2x that compiles/runs a program"). See TASKS/NEXT.md.
Position (updated after FIXING the comma-declarator chain clobber + parenthesized macro bodies — the stage-5 -e wall moved past ptable (tccpp.c:415) and past CH_EOF (tcc.h:568) to TOK_ELSE (tcc.h:1067 X-macro enum); frontier scalar HOLDS at 05:0000386 because the next wall is at the same misattributed line 386):
two verified engine fixes, each isolated with repros. (1) COMMA-DECLARATOR CLOBBER (src/boot_sym.c block_parse): TokenSym *ts, **ptable; failed "codegen: undeclared identifier" on ptable — parse_local_decl chains comma-declarators through stnode[].next (the same field the statement list uses) and returns the HEAD, and block_parse did stnode[prev].next = s; prev = s; with s = HEAD, so the next statement's link clobbered the first->second declarator edge, orphaning every declarator after the first (never alloc_local'd). Fix: after linking, advance prev to the chain TAIL (while(0 != stnode[t].next) t = stnode[t].next;). (2) PARENTHESIZED MACRO BODIES (src/boot_pp.c define_macro + new no_ws flag): the next wall CH_EOF (#define CH_EOF (-1), tcc.h:568) showed repros ce4..ce7 that #define X (5) / (-1) never expanded while #define X 5 / -1 did — define_macro treated ANY leading ( as function-like, so #define X (5) (with a space) became a zero-arg function-like macro with an EMPTY body. Fix: struct token gained int no_ws (1 iff no whitespace/newline before this token), set in the reader (boot_reader.c g_rd_gap gap flag: 0 = immediately after previous token, 1 = separated), and the function-like check now requires 0 != p->no_ws. New corpora: tests/codegen/comma_decl.c (scalar + pointer comma locals, bootcc_exit=42 == tcc_exit=42) and tests/pp/paren_macro.c golden (X->(5), Y->(-1), F(4)->4 + 1). make test 3 tokenizer + 23 preprocessor + 17 parser + 50 codegen + 255 libtcc in-process + 459 libtcc shared-object = 0 failed (the /tmp gcc reference drivers were rebuilt from the updated sources). NO RATCHET EXCEPTION: the scalar holds at 05:0000386 because line 386 is a misattribution artifact (tcc.c is only 371 lines) and the new wall TOK_ELSE sits at the same reported line; the engine is strictly more capable (comma-decls + paren-macro-bodies both verified). NEXT: the X-macro enum wall — the preprocessor must process #define DEF(id, str) ,id / #include "tcctok.h" / #undef DEF INSIDE enum tcc_token { ... } (tcc.h:1067), and the parser must resolve enum constants in expressions incl. the cross-referencing TOK_LAST = TOK_IDENT - 1. See TASKS/NEXT.md.
Position (updated after FIXING local brace-initializers, empty-replacement-list macros, and the fixed-width-int environment — the full real tcc.c -x now PASSES CLEAN and -e runs to line 386; frontier 03:0001609 → 05:0000386, stage 3 → stage 5):
three coupled fixes, each isolated with a repro and a -P/EXT-trace forensics pass (chase the FIRST stream anomaly, not the reported error line). (1) LOCAL BRACE INITIALIZER (src/boot_sym.c local_agg_fill): i386-asm.c:1609 static uint8_t reg_saved[] = { 3, 6, 7 }; failed because the array branch looped for(i<n) with n = array_len (unknown size → 0 iterations, list never consumed); replaced by a while(1) that for unknown-size arrays iterates until } and then fixes the shared type node in place (array_len/size/align, which propagates through the stored type pointer). (2) EMPTY REPLACEMENT-LIST MACROS (src/boot_pp.c): the libtcc.c:1212 "expected type in declaration" wall was actually a desync ~1500 lines earlier — PUB_FUNC (an object-like macro with an EMPTY body) never expanded and leaked into the stream as a raw identifier, whose NULL-specifier recovery shredded the FlagDef typedef; expand_macro now returns a lazy POINTER sentinel for empty bodies (no &global, M2-safe) and both callers skip it. (3) FIXED-WIDTH INT TYPES (environment completion, tcc sources byte-identical): libtcc.c:1178 (uintptr_t)val cast needs the fixed-width types that a real 32-bit glibc build gets via <stdio.h>→<sys/types.h> but this harness lacks (tcc.h's <stdint.h> is #ifdef _WIN32-only, portable_libc has no stdint.h); since multi-word -D values cannot survive argv splitting, a single-word MARKER -DSTDC_INT_TYPES is the transport and build_defs_file (src/bootcc.c) emits NINE REAL typedefs into the prepended defs file (uintptr_t/intptr_t int-sized since PTR_SIZE=4, uint64_t/int64_t long long since HAVE_LONG_LONG); size_t/ssize_t already come from portable_libc and are NOT redefined. A fourth defect the (3) wall exposed, fixed the same pass: STRING-LITERAL-INITIALIZED CHAR ARRAYS + MULTI-LINE AGGREGATE INITIALIZERS (C 6.7.9) — eval_const leaves cur on the terminating newline so every comma/brace check in BOTH local_agg_fill and ginit_fill now skips it first, and a string literal for a char array is ONE element that fills the whole member (per-byte stores via new agg_emit_store_v/ginit_put; also fixed local_agg_fill's never-initialized loop index i). M2-subset: the byte extract is written if(bv < 0) bv += 256; (a char-index inside & mis-compiled). Proof: 16 isolated repros (ar1..ar16) pass; full real tcc.c -x CLEAN (rc=0), -e to line 386. make test 3+22+17+49+250+450 = 0 failed; two-clean-build determinism green; gate GO (no ratchet exception — the scalar advanced forward). NEXT: reduce the stage-5 -e wall at line 386 (codegen "undeclared identifier"; tcc.c is 371 lines so the line is in an included file) and fix it. See TASKS/NEXT.md.
Position (updated after ADDING -DHAVE_LONG_LONG to the frontier build + fixing bare -DNAME to mean -DNAME=1 — the full real tcc.c -x now parses ALL of tccgen.c and stops at i386-asm.c:1609; recorded scalar 03:0001609 via the documented --force exception):
the tccgen.c:3160 "expected ';' after expression statement" was not a bootcc defect: that code only coheres with HAVE_LONG_LONG defined (without it the preprocessed stream is if (cond) else stmt, invalid C), and real tcc builds define it on long-long compilers, so the frontier AFLAGS now carry -DHAVE_LONG_LONG. The flag exposed a genuine preprocessor defect: a bare -DNAME was emitted as #define NAME (empty replacement list), making #if NAME evaluate to 0; cpp semantics are -DNAME ≡ -DNAME=1 — build_defs_file (src/bootcc.c) now emits #define NAME 1, and tests/pp/define.c proves #if FEATX == 1 on the bare -DFEATX. The ratchet exception is documented in LOG.md: the harness change moved the first-error line NUMBER down (3160 → 1609) while the engine parses strictly FURTHER — 1609 is in i386-asm.c, which in include order comes after all of tccgen.c (the line scalar is only monotonic within a file). The NEW first -x wall is i386-asm.c:1609 static uint8_t reg_saved[] = { 3, 6, 7 }; — a local array declaration with a BRACE initializer (isolated repro: int f(void){ int a[] = { 3, 6, 7 }; return a[1]; } fails "expected ';' after declaration"). make test 3+22+17+49+250+450 = 0 failed; two-clean-build determinism green. NEXT: add brace-initializer support to the declaration parser so -x advances past i386-asm.c:1609. See TASKS/NEXT.md.
Position (updated after FIXING the unary-operand cast precedence + token file metadata — the full real tcc.c -x now parses PAST tccgen.c:2504; frontier 03:0003160):
the "expected ')'" at the first cast was NOT a missing feature: ex_cast/is_paren_type already existed, but ex_unary's eight unary operators (* & - + ! ~ ++ --) took their operand from ex_unary() itself, so -(long double)-vtop->c.i (tccgen.c:2504) never routed the ( through cast detection — ex_primary's group-expression branch parsed long as an identifier and died at double. Fixed per the C grammar (unary operator's operand is a cast-expression): all eight sites now call ex_cast() (sizeof/typeof expression fallbacks unchanged). The error's file attribution (tccasm.c:2504 on a 1277-line file) exposed the second bug: token file pointers aimed at the reusable include-stack slot, so each later same-depth include renamed every closed header's tokens; include_file now interns paths into an append-only fn_pool (fn_intern) and the inc_pool stack keeps cycle detection. -P stream forensics settled it: token ORDER was coherent (the wall was parser + metadata, not preprocessor). block_parse also got a NULL-cur guard (EOF-in-body reported, no SEGV). New tests/parse/cast.c golden (m2==gcc). The NEW first -x blocker is tccgen.c:3160 vpushi((unsigned)mask): the preprocessed stream there is if (cond) else stmt — invalid C, because tccgen.c only coheres with HAVE_LONG_LONG defined (real tcc builds set it on long-long compilers; bootcc's AFLAGS do not yet). make test 3+22+17+49+250+450 = 0 failed; two-clean-build determinism green. NEXT: add -DHAVE_LONG_LONG to the frontier AFLAGS (tcc's own configure decision on a long-long compiler) and advance the frontier past 03:0003160. See TASKS/NEXT.md.
Position (updated after FIXING the tcc.c:375 desync via preprocessor line splicing — the full real tcc.c -x now parses PAST line 375 to a C cast; frontier 03:0002504):
the "expected ';' after expression statement" at tcc.c:375 (main's closing }) was a preprocessor bug, not a parser desync: src/boot_pp.c never implemented C translation phase 2 (line splicing), so a \+newline was two tokens and a directive's eol was the first physical newline — truncating multi-line #define bodies to line one (tccpp.c:693 PEEKC's 7-line body became a lone \, and 19 expansions injected bare \ punct tokens into function bodies) while the leftover continuation lines leaked as orphan code. libtcc.c (the ONE_SOURCE aggregator) is the poison, which is why tcc.h+main parsed clean. Fixed with tok_is_cont/find_eol (eol = first non-continuation newline; macro bodies and emitted code lines drop \); also fixed an ASan heap-UAF (do_include freed the path that token file pointers referenced — filename now points at the persistent inc_pool slot). Supporting changes so the parse actually advances: node pools heap-allocated (M2 won't bake >1MB statics; a full TU needs >8K rows), long double added as TYPE_LDOUBLE (tccgen.c:2026), and line_error now reports the current token's file/lineno (new cur_token() accessor) so diagnostics name the real construct. New tests/pp/continuation.c golden. Full real tcc.c -x passes 375; first error is now a C cast (type)expr ("expected ')'"). make test 3+22+14+49+250+450 = 0 failed; two-clean-build determinism green. NEXT: implement C cast support in the parser so -x advances past the first cast (frontier past 03:0002504). See TASKS/NEXT.md.
Position (updated after ADDING the autonomy guardrail set — gate, frontier ratchet, watchdogs, park rules):
the guardrails for fully autonomous cranking now exist and are machine-enforced:
tools/gate.sh is the single definition of a completed increment (worktree
changes + make green + make clean+make+cmp determinism + trailing-
newline sweep + frontier non-regression; prints GO/NO-GO, rewrites
tools/.frontier_state only on GO, which is committed with the increment);
tools/frontier.sh measures real-tcc.c progress as a comparable
STAGE:DETAIL scalar (-P tokens -> -s syms+main -> -x first-error line
-> -x clean -> -e first-error line -> -e clean) with a ratchet (regression
= NO-GO; --force needs a LOG entry) — baseline recorded: 03:0000375
(-x stops at tcc.c:375); every harness invocation (bootcc, drivers,
toolchain, tcc -run, emitted programs) is under a timeout watchdog
(60s default / BOOTCC_TEST_TIMEOUT; 300-600s builds), so a hang fails one
case, never the session; AUTONOMY.md carries the park rules (3 strikes ->
TASKS/PARKED.md in state/tried/why/unpark form; K=3 gate-green increments
with no frontier advance -> park; a STOP file means do no work). Every
increment from now on must end with sh tools/gate.sh printing GO. The
engine itself is unchanged this increment (make test 3+21+14+49+250+450 =
0 failed; determinism green). NEXT: reduce/fix the context-dependent tcc.c:375
desync (top-level reducer), which must move the frontier scalar past
03:0000375. See TASKS/NEXT.md.
Position (updated after FIXING the FILE *ppfp = stdout; blocker at its root + the two-typedef-param parser self-loop; full real tcc.c -x now passes main's FILE *ppfp = stdout;):
the real tcc.c main FILE *ppfp = stdout; "lvalue required in assignment" was
NOT a declaration-parser bug: angle-bracket #include <...> was silently
DROPPING the header's content (src/boot_pp.c — do_dir had the line's eol
token but do_include passed NULL to parse_header_name, whose angle-bracket
loop guard NULL != eol && ... then accumulated an EMPTY name, so resolve_hdr("")
returned NULL and the include was skipped; quoted includes worked). With
<stdio.h> dropped, FILE/stdout were undeclared and the declaration parsed
as an implicit one with an undeclared base -> the lvalue error. Fixed by threading
eol through. Exposing the real headers then surfaced a second bug (src/boot_sym.c
parse_params): any prototype with TWO params of the same typedef (e.g. two
size_t, from <string.h>'s memmem) self-looped the param list and hung the
-s/-x dump forever, because a typedef stores its RESOLVED type (kind
TYPE_LONG, not TYPE_TYPEDEF) so the tag-only copy guard missed it and both params
aliased one shared node. Fixed by copying a fresh, unlinked node whenever
decl == pt. make test = 3+21+14+49+250+450 = 0 failed (new tests/pp/angle.*
tests/parse/dupparam.*); determinism; M2-subset. The full real tcc.c-x(gcc host) now parses PASTmain'sFILE *ppfp = stdout;and the full-sregistersint main(1281 symbols). NEXT blocker: a context-dependent parse desync at tcc.c:375 (end of main, "expected ';' after expression statement") that does not reproduce from tcc.h+main alone. See TASKS/NEXT.md.
Position (updated after ADDING the C comma operator to expressions; real tcc.c -x reaches main's closing }):
bootcc's body parser only treated , as a call-arg/declaration separator, so
a = 1, b = 2;, for(a=0,b=1;;), and parenthesised (a=1, a+10) all errored
(expected ',' / expected ')' in if). A new ex_seq() (comma loop over
ex_assign) is now the parser at every statement expression position and
parenthesised groups; the existing EX_COM codegen already evaluated it. The
full real tcc.c -x on the gcc host now parses through main up to its
closing } — the next blocker is an unbalanced if at tcc.c:375 (end of
main; context-dependent, not reproduced by the 129-line ddmin main). The
comma operator itself is fully green. make test = 3+20+13+49+250+450 = 0
failed; determinism; M2-subset. See TASKS/NEXT.md.
Position (updated after FIXING adjacent-string-literal concatenation in the body parser; real tcc.c -e now reaches the end of main):
the first body-parser/codegen blocker on the real tcc.c was a C string-concatenation
gap: ex_primary read a single TOK_STRING, so adjacent literals (("a" "b"), or
tcc's snprintf(..., "%.*s%s" "-tcc", ...)) errored expected ')' after argument list (e.g. tcctools' tcc_tool_cross). Fixed by calling the existing
asm_read_strings() (which merges a run of adjacent literals) in ex_primary's
string branch and dropping the single advance(). Added tools/reduce-tcc.py — a
deterministic mechanical ddmin reducer (oracle: exit/grep-absent/grep-present,
prelude #include "tcc.h", -I/-D args) so any "silent drop / crash / body error"
on the 200k-token real TU reduces in seconds-mechanical instead of manual probing.
The real tcc.c -e (gcc host) now gets past tcctools and into main, next erroring
at tcc.c:377 expected ')' in if (the very end of main — an unbalanced if in
main's body 246-374). Regressions: tests/codegen/strconcat.c. make test =
3+20+13+48+245 libtcc in-process + 441 libtcc shared-object = 0 failed; determinism; M2-subset. Next target: reduce
tcc.c main (the unbalanced if) with the reducer to a single construct and fix.
See TASKS/NEXT.md.
Position (updated after FIXING the real-tcc parser desync — bare unsigned/signed type is now implicit-int):
the gcc-host parse of the FULL real tcc.c now registers int main (1183 symbols,
exit 0, main=1, 2/2). The desync was parse_specifier (src/boot_sym.c): a bare
unsigned/signed return type (tcc.c's static unsigned getclock_ms(void)) set
sign but left kind=(-1), so parse_specifier returned NULL and parse_external
swallowed the rest of the file, never registering main. The fix applies C's
implicit-int rule (a saw_sign flag → default the bare unsigned/signed to
TYPE_INT). Regressions: tests/parse/unsigned.c+.expected and a corrected
tests/parse/decls.expected (the old golden had silently omitted the bare-unsigned
global). make test is 3+20+13+47+240+432 = 0 failed; determinism green; M2-subset
holds. The parser now runs the real tcc.c on the gcc host to int main. The M2 host
still segfaults on the FULL large TU (documented); next verify whether the M2 crash
threshold was the same desync or a separate host effect, and keep scaling bootcc
toward parsing+running the full tcc.c. See TASKS/NEXT.md.
Position (updated after driving the gcc-host at the FULL real tcc.c ⇒ documented parser desync, silent main-drop):
on the gcc host (the forward/canonical path), bootcc -s ... $TCC/tcc.c parses
cleanly through struct TCCState, the help/help2/version string arrays, and all
libtcc.c/tcctools.c functions up through default_outputfile, then SILENTLY STOPS:
int main is never registered (its body-locals are dumped at file scope) and bootcc
exits 0. Deterministic: the real tcc.c gives main=0 while the identical composite
with short help arrays gives main=1. Not a single clean grammar construct (same near-
identical inputs flip main registered/dropped); ASan/UBSan/-Wuninitialized flag nothing
(all allocs calloc, no OOB) — a stateful parser desync from the accumulated real TU.
The M2 host additionally segfaults (prior increment). This is the recorded first-parser
blocker on the real tcc.c. make test stays 3+20+12+47+240+432 = 0 failed (no engine
change). Next task: reduce the accumulated TU to the exact desync-triggering construct
and fix it, or obtain a memory-sanitizer to catch the state corruption. See TASKS/NEXT.md.
Position (updated after driving tcc.c through the PARSER ⇒ documented M2-host first-unsupported-construct):
with the whole tcc.c preprocessing green (previous increment), the parser run
bootcc -s -I $TCC -I portable_libc/include -DPTR_SIZE=4 -DLDOUBLE_SIZE=12 -DCHAR_BIT=8
on the real composite (tcc.c, or #include "tcc.h" + #include "libtcc.c") makes
the M2-Planet-built bootcc SEGFAULT (exit 139, dangling cur in parse_external's
fallback skip loop). A GCC build of the SAME bootcc sources parses the SAME
composite to completion (exit 0, 2342 symbols) — so the GRAMMAR is not the
blocker; the M2 host fails on large TU slices. Characterized via tccgen.c slices:
the crash is NON-MONOTONIC (head-2760 OK / head-2800 crash / head-2820 OK / …), a
heap-layout-fragility signature (deterministic 3/3 on head-2800: M2 exit 139 vs
gcc exit 0, 1372 symbols). This is the documented exact first-unsupported-construct
of the auto-bootstrap path: parsing large real backend TU slices (~1300-1400
symbols) crashes the M2 host, while the gcc-hosted bootcc / -ltcc-SO path parses
the full tinycc composite cleanly. Path implication: extend the gcc-hosted libtcc
consumer path from its small corpus toward the full real tcc.c (which the M2 host
cannot parse at this size). make test stays 3+20+12+47+240+432 = 0 failed (no
engine change this increment). See TASKS/NEXT.md.
Position (updated after -D defines + the #elif-tail fix ⇒ full tcc.c preprocess):
bootcc now preprocesses the ENTIRE tcc.c translation unit: bootcc -P -I $TCC -I portable_libc/include -DPTR_SIZE=4 -DLDOUBLE_SIZE=12 -DCHAR_BIT=8 $TCC/tcc.c
exits 0 with 201,314 preprocessed token lines (previously it died on
tccpp.c:1193: #error add long double size support). Two bootcc bugs were
fixed to get there. (1) #elif-tail bug (src/boot_pp.c do_dir): after a
matched #if, a later #elif/#else region was NOT marked dead, so an
#error in it fired even though the #if already matched — the exact shape
of the LDOUBLE_SIZE chain. The #elif handler now sets cf_top->emitting=0
when a prior branch matched (mirroring #else). (2) command-line -D name[=value] defines: bootcc had none, and hand-rolled value scanning kept
hitting M2-Planet codegen bugs (&argv[i][2] → byte load; char-by-char char*
and local-array comparisons). The fix records -D strings (src/boot_pp.c
def_pool/add_define/def_count_of/def_arg_at), and src/bootcc.c writes a
temp #define source (build_defs_file), re-tokenizes it, and splices it in
front of the input stream so the battle-tested lexer/define_macro handles the
replacement text. Both -D name=value and -Dname=value and bare -D NAME
work. Regressions: tests/pp/elif_tail.*, tests/pp/define.c+define.defines
(the pp harness gains a .defines sidecar like .incdir). make test is
3+20+12+47+240+432 = 0 failed; determinism green; M2-subset holds. The
previously documented first-stop (the #error) is now past: with a full
201k-token preprocess, the next churn target is driving that fully-preprocessed
tcc.c through the PARSER — capture the first parser blocker — and the remaining
long-tails (amd64-only backend, hex2 4-byte R_X86_64_64 reloc, runtime
realloc/stat) stay open. See TASKS/NEXT.md.
Position (updated after the preprocessor repeated-parameter macro-cycle fix):
the real blocker for parsing a tcc.c TU was NOT parse_external (as previously
believed) but a bootcc preprocessor infinite loop: a function-like macro whose
body uses the same parameter more than once (e.g. tccpp.c's TOK_HASH_FUNC,
#define M(a,c) ((a)+((a)<<5)+((a)>>27)+(c))) made bootcc -P spin forever in
chain_tail, because subst_body (src/boot_pp.c) spliced the SAME argument
token chain in on every parameter substitution, sewing a->toks back into
itself into a token cycle. Determined by isolation (M(a)=(a+a) hangs while
M(a)=(a) and M(a,b)=(a+b) terminate) and a gdb backtrace on
WHILE_chain_tail_0. Fixed by a clone_chain() deep-copy helper used in the
parameter-substitution block, so reusing a parameter stays acyclic. New
regression tests/pp/macroreuse.c + .expected (both the TOK_HASH_FUNC
shape and TWICE(a)). After the fix bootcc -P -I $TCC tcc.c no longer hangs;
it now reaches a clean first-stop #error add long double size support
(tccpp.c:1193), because tcc needs command-line -D defines (PTR_SIZE/
LDOUBLE_SIZE/CHAR_BIT) and bootcc does not yet support -D. make test is
3 tokenizer + 18 pp (macroreuse 17->18) + 12 parser + 47 codegen + 240 libtcc
in-process + 432 libtcc shared-object = 0 failures, determinism gate green
(two clean M2 builds cmp identical). Next concrete increment: add -D name[=value]
macro defines to the CLI so tcc.c preprocesses past the #error (see TASKS/NEXT.md).
The prior runtime+file/mem position (below) is unchanged and correct.
Position (updated after the emitted-runtime MEMORY+STRING+FILE increment — a slice of QUEUE 3 "Reduce a fixed target/long-tail mismatch ... blocking tinycc-as-is"):
the emitted freestanding runtime (src/boot_sym.c emit_runtime), which already
carried _start, exit, _raw_write/_raw_read, putchar, the formatted-IO
printf/scanf variadic helpers plus a boot-side variadic va_list path, and the
malloc/free brk(12) bump heap — now also emits the memory-block helpers
memcpy/memmove/memset/memcmp, the string helpers
strlen/strcmp/strcpy/strncpy, and the five SysV amd64 syscall wrappers
open/close/read/write/lseek, each a raw :FUNCTION_<name> M1 macro-asm
block (rbx-preserving, caller-saved only otherwise). Proven by the TCC-parity corpus
tests/codegen/mem_file.c, which calls every helper through the emitted runtime and
then opens/reads/lseeks/closes ITS OWN source file byte by byte (stdout=377292
exit=55 identical to tcc -run); the __TINYC__ branch needs <fcntl.h> for open
or tcc 9.0.27 warns onto stderr and breaks byte-parity. make test is 3 tokenizer +
17 pp + 12 parser + 47 codegen (mem_file brings 46->47) + 240 libtcc in-process + 432
libtcc shared-object = 0 failures, the m2==gcc emitted-M1 gate holds for every corpus,
two clean M2 builds cmp byte-identical, M2-subset discipline holds, and mem_file.c
carries a trailing newline (also: the per-harness cached gcc reference drivers were
rebuilt against the grown runtime — a cache-staleness fix, not a code bug). Still open
on the runtime/libc arm: realloc, a stat-style wrapper, and file/dir breadth
(fcntl/ioctl/getcwd/readlink). The non-runtime long-tail items remain fully
open: the amd64-only backend, the vendored hex2 linker's missing 8-byte R_X86_64_64
absolute data pointer (only the 4-byte & absolute is reachable), and the exact first
construct that STOPS parsing tcc.c itself (the prior slice found bootcc parses tcc.h's
gen_le32 prototype block then silently advances no further — a parse_external
NULL-base skip swallowing the tcc.h tail — so no int main body compiles yet). See
TASKS/NEXT.md.
Position (updated after the first tcc.c slice probe — const-qualified pointer declarators):
bootcc builds via the vendored M2-Planet into a static x86-64 ELF with a
working tokenizer, C preprocessor, and the parser engine. src/bootcc.h
carries the 32-bit-clean type system (enum type_kind and struct type with
kind,size,align,signedness,array_len,flags,offset and base/members/params/tag
links) plus struct symbol; src/boot_type.c supplies type allocation and
stable kind names; src/boot_sym.c builds the symbol table, the full
declarator parser (multi-level pointers, array extents, ANSI + K&R function
declarations/definitions, typedef resolution, storage classes feeding
linkage, struct/union member typing, struct/enum constant evaluators).
The expression-compiler milestone generalised a function definition: instead
of skip_body()-ing it, src/boot_sym.c now parses the body into a flat
integer-indexed pool of typed expression rows (enode[]) and statement rows
(stnode[]). Children are row indices, never interior pointers — a constraint
hard-won on M2-Planet: the node allocators went from
struct exode* p = &enode[i] interior-pointer dereference to direct
enode[i].field indexing so the self-hosted binary produces the correct
trees. -x/--exprs prints each body's typed tree deterministically.
The expression grammar covers the full precedence cascade over C operators
(|| && | ^ & == != < <= > >= << >> + - * / %, unary + - ! ~ * & ++ --,
casts, ?:, assignment and every compound-assign incl. the two-token
/= <<= >>= the tokenizer emits, comma), lvalue/rvalue typing, ./->
member access, subscript, calls, sizeof/typeof/alignof, and
short-circuit &&/||. Constant folding applies C/TCC integer semantics
(32-bit signed wraparound, division/modulo truncate toward zero, shift counts
masked to 5 bits) and each foldable node carries its folded value. The
statement grammar parses blocks, if/else-if/else, while, do-while, for (with
local-declaration and expression init), switch/case/default, goto+labels,
break/continue, return, and local declarations with initializers; a function
prologue pushes a fresh scope registering the parameter types so references
resolve to real types, and epilogue pops it.
bootcc -s|--symbols keeps printing the typed global symbol dump
(storage/linkage, sizes/aligns, member offsets, function params, enumerator
values); -x|--exprs additionally shows the compiled body trees. Three new
tests/parse/{expr,fold,stmts}.exprs goldens gate the -x output in
tests/run-parse-tests.sh; each is additionally byte-compared with a gcc
build of the same sources, and tests/parse/fold.c is cross-checked
value-for-value against the TCC 0.9.27 binary on the amd64 ABI (overflow,
division/mod, shift masking, bitwise, comparisons, ternary, sizeof,
compound assignment).
make test passes 3 tokenizer + 14 preprocessor + 9 parser + 15 codegen
suites (0 failed). Two clean M2-Planet builds cmp byte-identical
(byte-deterministic).
The x86-64 codegen milestone closed the final parser-engine chunk: walking
the flat statement/expression trees (enode[]/stnode[]) into x86-64 M1
macro-asm on TCC 0.9.27's SysV amd64 ABI, then emitting a standalone object
(bootcc -e) that the vendored blood-elf/M1/hex2 chain statically links into
a runnable ELF64. The backend emits per-function prologue/epilogue, spills
the 6 register args, lays out int/long/char/short/pointer locals on
the stack, evaluates expression trees to registers (add/sub/mul, signed
div/mod, masked shifts, setcc comparisons, short-circuit &&/||,
?:, casts, compound assignment, inc/dec, member/index access, and SysV
calls across the register-arg boundary), and lowers the whole statement set:
if/else, while/do/for, switch dispatch, goto/labels, break/continue, return.
Host==target==amd64 so int-wrap / div-mod-truncation / shift-mask replicate
TCC 0.9.27 at runtime. make elf SRC=prog.c links any one-file program into
an executable; tests/run-codegen-tests.sh (a runtime TCC-parity gate) runs
each tests/codegen/*.c ELF and now compares BOTH its stdout bytes and its
exit status to tcc -run on the identical source. The gate is green for an
8-corpus set that prints via the emitted runtime and exercises the fixed
codegen core: fold_arith=198, loop_sum=2, ops_tern=9, print_hello,
io_print (stdout "val=10\n"), expr_edges (stdout "ok"), switch_dense
(stdout "1", exit 7 for a switch over the dense range 0..4 inside a loop),
and struct_byval (a 12-byte struct pt{x,y,z} passed by value to sum3
reading all three members, stdout "43\n", exit 3 for 43%8). Each corpus's
stdout plus exit code is byte-identical to TCC 0.9.27 on amd64.
This increment closed the honest codegen gaps that masked the emitter's
correctness. The emitted runtime now provides putchar/_raw_write (Linux
amd64 write syscall) so the corpus can drive byte-for-byte stdout; print
helpers are written in C on top of putchar (single-arg, no string literals),
which stays inside the M2-host build's working subset.
Four real codegen bugs were found and fixed while building the corpus:
- array decay: an array identifier in an rvalue position used to load the first element instead of decaying to its base address (C semantics), breaking array-based printing.
- multi-dim array decay: an
EX_INDEX/EX_MEMBERwhose result type is an array now decays (keeps its address) instead of loading, fixingt[i][j]. - switch block-unwrap:
cg_switchwalkedstnode[s].aassuming the case/default chain were top-level siblings, but a{...}switch body is aST_BLOCKwhose child chain holds the cases -- so the switch was NEVER dispatched (it always fell through). The emitter now unwraps the block before collecting and labelling cases. - r13 across calls: every compiled function sets
mov r13,rspas its frame base without restoring the caller's r13 (SysV callee-saved), so a caller reading its own r13-relative locals after calling a bootcc-compiled function read garbage at the callee's frame.cg_callnow pushes/pops r13 around each call. This was silently masked because the old corpus never used r13-relative locals after a call.
The switch also gained a dense-range classifier: for a contiguous non-default
case range it lowers to an indirect jump table (jmp_rcx through a per-case
JTAB<n> of case-label addresses emitted in the data section) instead of a
compare/chain. This jump-table leg is now actually enabled (boot_emit arms
it via toggle_jump_tables(1)), and the structural blocker is closed with a
toolchain-true encoding. The vendored hex2 linker has NO 8-byte
(R_X86_64_64, absolute-address data) pointer form: hex2_word.c
WordStorePointer writes only 4-byte pointers, where % is a PC-relative
displacement and & is a 4-byte absolute address. So each JTAB<n> slot is
emitted as &L<label> — a 4-byte absolute case address — which resolves to
the case's link-time address because the emitted ELF is linked at the low
base 0x00600000 and every in-text case label fits a 32-bit address. The
dispatch scales the case index by 4, computes the slot address with
lea_rbx,[rip+...] + add_rbx,rax, reads the slot with mov_eax,[rax]
(zero-extends the 4-byte address to 64-bit), mov_rcx,rax, jmp_rcx.
This session delivered the struct-by-VALUE argument half of the SysV amd64
aggregate classifier. boot_sym.c gains agg_t_is_2reg/agg_is_2reg (a
9..16-byte struct/union maps to two integer register positions, else one),
push_agg_lo/push_agg_hi (the two ABI eightbytes), and cg_call now counts
aggregate register/stack word positions per argument instead of raw argument
count, so a struct param fills two consecutive caller registers while the
stack-arg arithmetic (tot-6) and trailing scalar-arg register placement stay
correct. The function prologue spills a 9..16-byte param from BOTH of its
incoming registers and advances the running register index by +2 for such
params. A 12-byte-struct argument corpus is now runtime-gated byte-identical to
TCC.
Honest scope carried forward: struct-by-value with >=2 real arguments, stdarg,
long long, and multi-TU objects are still not laid out. The M2-host (0.x)
itself still mis-lowers a few RUNTIME emitter paths --
any call with >=2 real arguments, and any use of a string literal in emitted
code, crash bootcc -e under the M2 build (both are confirmed reproducible; the
gcc-built reference binary emits these paths correctly, and the crash also
reproduces on a plain scalar h(int,int) two-arg call, so it is a pre-existing
M2 limitation rather than a struct-specific regression). So the M2 runtime
corpus stays single-argument and literal-free; the ABI tail (mixed/struct
multi-arg calls, variadic, 64-bit arithmetic) must be revisited under the M2
vendor fork, where those emitter paths are compiled correctly.
This session closed the struct-by-RETURN half to mirror the argument half:
the SysV classifier now works in both directions. cg_value_agg/cg_store_agg
move a 9..16-byte aggregate's two eightbytes (bytes 0..7 -> rax, bytes 8..15
-> rdx); ST_RETURN emits those loads for a struct-typed return, and the
caller's ST_DECL (declaration-style struct initializer) and EX_ASGN
(whole-struct assignment) both read the two registers back into the destination
local, the mirror of the two-register prologue spill. A second 12-byte-struct
corpus (struct_ret.c) builds a struct pt{x,y,z} in a callee, returns it,
and the caller reads x+y+z from both a =-initialized and an =-assigned
local, printing "43" and returning 43%8 = 3 -- byte-identical to TCC 0.9.27 on
stdout and exit status. All prior scalar corpora stay byte-identical; make test is green (9 codegen suites) and the two-clean-build cmp gate holds.
This session closed the M2-host emitter crashes that blocked the codegen/ABI
runtime tail, both via boot-side restructure (preferred over a vendor patch
per vendor/VENDOR.md's "restructure the subset first" policy):
- A
FUNCTION_arg_atlabel clash:src/boot_sym.candsrc/boot_pp.ceach declared astaticfunction namedarg_at. In M2-Planet's single-TU build two bodies land under oneFUNCTION_arg_atlabel and the linker keeps the last (boot_pp'sstruct macro_arg*walker), socg_call's comma-chain walk dereferenced garbage andbootcc -ecrashed on ANY call with >=2 real arguments. boot_pp's is renamedpp_arg_at. Nowh(int,int)and a 4-argh(1,2,3,4)emit byte-identically to the gcc reference, andtests/codegen/multi_arg.cis TCC-parity green (derr=254 tcc=254). - String-literal emission: M2-Planet mis-lowers an array of pointers
(
char* strpool[]) to byte strides/loads (achar* pool[4]; pool[1]probe segfaults under the vendored M2), so-ecrashed once it hit the literal pool. The pool is now a flatchar strpool_data[MAX*1024]arena where slotilives atstrpool_data + i*1024(no pointer-array indexing). Also fixed a long-latent bug the crash had masked: a TOK_STRING token includes its surrounding quotes, soemit_strpoolused to emit the"bytes; astr_content()decode (strip quotes + resolve escapes) now stores/emits the true literal, giving:STRING_0='h' 'i' '00'. String literals now emit byte-identically to the gcc reference.
make test is green at 37 suites (3 tokenizer + 14 preprocessor + 9 parser +
11 codegen), 0 failed; the two-clean-build cmp gate and the m2==gcc gates
still hold. The aggregate-marshalling increment added tests/codegen/ mixed_agg.c (a struct pt combined with a leading and trailing scalar) to
the TCC-parity corpus — green at exit 15.
The aggregate+trailing-scalar caller marshalling fix (see LOG.md): the call
argument list is now linked right-nested so every real argument is a
top-level node — the struct argument is no longer folded into a comma subtree
with the preceding scalar (which had clobbered the scalar and read the struct
as a lone byte), so both System-V eightbytes are pushed intact between the
scalars — and a 9..16-byte aggregate param now gets a 16-byte frame slot so
the prologue's two eightbyte spills do not overrun into a neighbouring scalar
param. -e stays byte-identical to the gcc reference for two-arg scalar,
mixed-agg, multi-arg and struct-byval cases.
The two-aggregate-argument increment closed the four-register-position edge:
f(struct pt a, struct pt b) no longer hangs. Root cause was in
parse_params: a bare struct/union/enum/typedef parameter is the SHARED tag
node, so two params of the same tag aliased one object; the second
tail->next = decl wrote a self-loop (an infinite walk in the prologue) and
each decl->tag = pn renamed the same node, clobbering the canonical tag.
Each such by-value param now gets a fresh node (type_copy_node, sharing the
tag's members/base), so the param list stays acyclic and the canonical tag is
preserved. With the parse hang gone, the caller's existing marshalling (push
all four eightbytes, pop A into rdi:rsi and B into rdx:rcx) and the
callee's +2-per-aggregate spill work end-to-end: tests/codegen/two_agg.c
(int two_sum(struct pt a, struct pt b) reading a.x+a.z+b.y = 10) is
TCC-parity green (derr=10 tcc=10). The fix also corrects the stmts.exprs
golden (a single by-value struct pt q param no longer renames the canonical
tag, so the dump shows struct(pt) with members). -e stays byte-identical
to the gcc reference for two_agg, mixed_agg, multi_arg and struct_byval;
make test is green (3 tokenizer + 14 pp + 9 parser + 12 codegen = 38
suites, 0 failed); two clean M2 builds cmp byte-identical.
The undeclared-extern increment closed the last crash on external calls:
putchar(65) with no prior prototype no longer segfaults the parser. Root
cause sat in ex_primary's enum-constant probe and identifier retype, both
guarded by the short-circuit chain NULL != s && NULL != s->type && s->type->kind == TYPE_ENUM: the M2 host mis-lowers short-circuit && and
evaluated s->type->kind even when s was NULL, so ANY undeclared
identifier (a bare call, an assignment read, a local init) made bootcc -x
and -e exit 139 (_END_IF_ex_primary_4 dereferenced address 0x8). The
guard is now nested (if (NULL != s) { if (NULL != s->type && ...) }) and
the retype is explicit (if (NULL == s) ... else if (NULL == s->type) ... else), so an undeclared symbol only ever gets a fresh make_type() node.
Per C rules the undeclared call is given an implicit int return and lowers
to a single SysV call %FUNCTION_<extern> with no callee-type deref, so both
-x and -e are byte-identical to the gcc reference. New
tests/codegen/extern_call.c (calls the emitted-runtime-provided putchar
extern plus a compiled function) is TCC-parity green (derr=2 tcc=2, stdout
identical); all prior -e outputs (two_agg, mixed_agg, multi_arg,
struct_byval) stay m2==gcc byte-identical. make test is green (3 tokenizer
- 14 pp + 9 parser + 13 codegen = 39 suites, 0 failed); two clean M2 builds
cmpbyte-identical.
This session closed string-literal RUNTIME output. The "string data not
placed" gap was a boot-side emit bug, not a linker one: M1's single-quoted data
row is exactly two hex digits, but emit_strpool wrote printable bytes as
'%c' rows ('h'/'i'), so M1 parsed each as an undefined label reference
and the emitted string bytes never reached the binary (lea rip+STRING_n
pointed at junk; STRING_0/STRING_1 looked "one byte apart" because the rows
resolved to zero/undefined). emit_strpool now emits every byte as a
two-digit hex row through a new emit_hex_byte helper (digits '0'..'9'/
'a'..'f' computed arithmetically, since M2-Planet cannot initialise a global
char array from a string literal), so "hi\n" emits as '68' '69' '0a' '00'
and the data-section bytes are really placed. With the data landing, a second
bug surfaced: char s[8] = "hi\n" stored the literal POINTER value into the
array (eight bytes e6 01 60 ...) instead of copying the bytes. A new
cg_str_init lowers a char-array string-literal initializer to a runtime
byte-copy loop from STRING_n into the freshly laid-out array local
(NUL-terminating included), matching C semantics. New
tests/codegen/string_out.c (char s[8] = "hi\n" printed through the emitted
putchar/putbuf runtime) is TCC-parity green (derr=0 tcc=0, stdout
identical); all prior corpus -e outputs (string_out, two_agg, mixed_agg,
multi_arg, struct_byval, extern_call) stay m2==gcc byte-identical. make test
is green (3 tokenizer + 14 pp + 9 parser + 14 codegen = 40 suites, 0 failed);
two clean M2 builds cmp byte-identical.
This session closed 64-bit long long integers end to end. The declarator's
primitive path now recognizes a double long long and yields TYPE_LLONG, a
distinct 64-bit kind (same size/align/register width as long on amd64,
-s/-x dumps show long long/llong), so left-shift past bit 31 stops
being masked to 5 bits, signed 64-bit div/mod truncate toward zero, and
int/long long widening/narrowing is exact — the backend already computes
in full 64-bit registers, so only the size/align/kind plumbing had to join
up. The supporting fix was a real frame bug the new corpus exposed:
alloc_local reserved a single pointer-sized (8-byte) slot for any
TYPE_ARRAY local regardless of element count, so char buf[24] overran the
frame and segfaulted; array locals now reserve their whole t->size byte
span. New tests/codegen/llong.c (a 40-bit 2^40 built from runtime long long shifts, a 64-bit multiply whose low 64 bits need the 128-bit
product, signed 64-bit div/mod, and their negatives, printed as decimals)
is TCC-parity green on stdout+exit. All prior corpora stay TCC-parity green,
the -e output for every codegen corpus stays m2==gcc byte-identical
(verified llong.c and all prior), two clean M2 builds cmp
byte-identical, and make test is 3 tokenizer + 14 preprocessor + 9 parser
- 16 codegen = 42 suites, 0 failed.
The variadic calling-convention increment (step 1 of printf) closed the gap
for declaring and calling variadic functions through the SysV amd64 ABI.
parse_params detects a trailing , ... (the lexer emits it as the punct
pair .. then .), consumes both tokens and records a variadic flag via
make_func(..., variadic) (stored as array_len on the TYPE_FUNC node, an
honest reuse since a function type carries no array extent). cg_call
branches on that flag: named leading args fill the six register slots
(rdi/rsi/rdx/rcx/r8/r9, +2 per 9..16-byte aggregate) in declared order and
every EXCESS argument is pushed on the stack right-to-left (last arg lowest
address), matching GCC/TCC even when registers are left over; the post-call
add_rsp unwinds tot - named_reg stack words instead of tot - 6. A
freestanding variadic emit_runtime_printf (no libc) lowers
%d/%i/%u/%x/%ld/%lld/%lu/%lx/%p/%c/%s by reading varargs from the callee's
stack home/tail ([rbp+24..80], walking rbx DOWN the frame and advancing the
format pointer r14 after each conversion) and emitting through the existing
putchar/put_dec/put_uns/put_hex runtime. New
tests/codegen/variadic.c (printf("%d+%d=%d\n", a, b, a + b)) is TCC-parity
green (derr=0 tcc=0, stdout identical); every prior corpus stays m2==gcc
byte-identical and TCC-parity green. make test is now 3 tokenizer + 14
preprocessor + 9 parser + 17 codegen = 43 suites, 0 failed; two clean M2
builds cmp byte-identical and the m2==gcc gate holds.
The boot-side va_list increment (step 2 of printf) closed the CALLEE half so
a variadic function can read its own excess arguments. A trailing-...
declaration can now define a body (it already parsed; only the reader was
missing), via a low-budget __builtin_va_arg(k) builtin that desugars to a
new EX_VAARG node (k folded to a constant in ex_va_arg). Because bootcc
variadic CALLS push every excess argument as one 8-byte word on the caller's
stack tail (see step 1), the receiver does not need a register-spill region to
index: cg_va emits lea rax,[rbp+24+8k] + mov rax,[rax] for the k-th
excess argument, while the named leading arguments are still read from their
register spills by the prologue. A per-function cur_vtc flag (set from the
function type's variadic array_len in emit_function_asm) rejects
__builtin_va_arg outside a variadic function. New tests/codegen/va_list.c
defines int sum(int x,...) in bootcc, reads x (named, from rdi's spill)
plus three stack excess args, prints the total 2112 via the emitted putchar
runtime and returns 2112%256=64; the TCC branch reads the same source through
a real #ifdef __TINYC__ <stdarg> (va_list/va_arg), and both are
TCC-parity green on stdout+exit (derr=64 tcc=64). make test is 3 tokenizer +
14 preprocessor + 9 parser + 18 codegen = 44 suites, 0 failed; -e stays
m2==gcc byte-identical for va_list.c and every prior corpus; two clean M2
builds cmp byte-identical.
Format-decoder breadth + scanf reader + float specials (two increments):
the freestanding emit_runtime_printf %-handler now parses [flags] [width][.precision] (- left-align, 0 zero-pad, minimum width, .digits
precision; integer zero-pad-to-precision, %s truncate) and renders it
without libc (proven by tests/codegen/pf_fmt.c/pf_long.c); %f/%e/%g
dispatch to a raw-M1 leg that bit-tests the IEEE-754 word (exponent 0x7FF) and
prints nan/inf/-inf (finite decimal body deferred), proven by
tests/codegen/pf_float.c built through a TCC-union branch. A matching
emit_runtime_scanf mirrors the printf vararg cache and reads whitespace/
sign/32-bit (%d/%i/%u) and lowercase-hex (%x) values, l/ll widening
to 64 bits, one byte at a time from stdin via a new _raw_read read(2) helper,
storing through the vararg pointer and returning the item count —
tests/codegen/scanf.c (%d) + scanf2.c (%u/%x/%lld/%llu incl. max
uint64) are TCC-parity green. Two runtime bugs surfaced and fixed there: the
scanf vararg cache read its pointer slots starting at [rbp+16] (the caller's
pushed <save r13, where the first excess arg actually sits above it at
[rbp+24]) and clobbered the arg-walker, so the first target was garbage — the
cache now starts at [rbp+24]; and the %f NaN test zeroed the mantissa probe
(a stale shr_rax,cl after sal_rax,!12) while mov_rbx,2047 clobbered the
cursor rbx. cg_call also pops r13 before unwinding a variadic call's excess
words. make test is 3 tokenizer + 14 preprocessor + 9 parser + 23 codegen =
words. make test is 3 tokenizer + 14 preprocessor + 9 parser + 23 codegen =
49 suites, 0 failed; -e is m2==gcc byte-identical for every corpus; two
clean M2 builds cmp byte-identical.
The finite-float-decimal increment gave %f a general finite body on the
emitted runtime. :pf_flo bit-tests IEEE-754 (exponent 0x7FF => nan/inf/
-inf, unchanged) and otherwise jumps to :flo_fin, which splits the value's
sign ((raw>>63)&1), 53-bit mantissa m ((R & 2^52-1) | (1<<52) for normals,
R & (2^52-1) for subnormals, where R clears the sign bit) and true binary
exponent e (field-1075 for normals, -1074 subnormal), then renders
value = m*2^e integer-only to the fixed 6 fractional digits: I = m>>k (k=-e,
with k>=64 => I=0) is the integer part, and the fraction is round((m&2^k-1) * 1e6 / 2^k) computed as ((product>>(k-1))+1)>>1 on the 128-bit product
mul 1e6 (left word / 2^k shift handles 64..72-bit), a carry of 1000000
propagates into I. :flo_out prints - (sign), I via put_uns, ., and a
zero-padded 6-digit fraction — all integer-only, no libc. The printf frame grew
sub_rsp 224→384 (epilogue balanced) for the new [rbp-328..-336] slots; the
frame stack/unwind stays 16-aligned. New tests/codegen/pf_double.c covers eight
exact decimals (0.0, -0.0, 1.0, 1.5, 0.5, 0.25, 2.75, 5.0, -3.0, 4.0,
65536.0, 0.75; subnormal/zero and a big integer part incl.) via raw-bit patterns
built at runtime from helper-returned pieces so 32-bit constant folding cannot
collapse the shifts; the TCC branch prints the identical values through a union
and real libc %f. TCC-parity green on stdout+exit. make test passes 3
tokenizer + 14 preprocessor + 9 parser + 24 codegen = 50 suites, 0 failed; -e
stays m2==gcc byte-identical for every corpus (pf_double verified; a
pre-existing, unrelated fold_arith 2^31-immediate text variant is unchanged by
this increment); two clean M2 builds cmp byte-identical.
%e/%g forms and %f field width / precision / flags (01503f4): the
freestanding printf float leg now renders a finite double under %e (one digit
before the point, [precision] after it, two-digit e±XX), under %g (the
shorter of the %f/%e forms with libc-style trailing-zero trimming, default
precision 6), and %f/%e/%g honor field width (left - / zero 0 pad)
plus the + and space sign flags. The %e/%g scientific mantissa is now
recomputed from the raw mantissa/exponent bits (m=[-240], e=[-248], kept
from flo_fin) via round(value * 10^(P - e10)) reused through flo_r6, then
split into d1/F with the exponent carried when the rounding crosses a decade
— replacing the old re-normalisation of the %f body's already-P-rounded value,
which double-rounded small fractional mantissas (.1e of 0.75 printed
8.0e-01 instead of 7.5e-01). While landing it three runtime bugs are fixed:
the space sign flag [rbp-348] collided with the 8-byte content-length slot
[rbp-352] (so % f printed no leading space) and now lives at [rbp-272];
flo_f6 always printed the fraction even after a %g trimmed GDIG to 0, so
a whole number emitted a trailing 0 (1.0 -> 10) and now exits early; and
the %e/%g mantissa double-rounding above. New corpora pf_expg.c,
pf_dbg.c, e1_float.c are TCC-parity green on stdout+exit (the #ifdef __TINYC__ union branch reinterprets the same bit patterns through libc
printf). make test passes 3 tokenizer + 14 preprocessor + 9 parser + 27
codegen = 53 suites, 0 failed; -e stays m2==gcc byte-identical; two clean
M2 builds cmp byte-identical.
scanf field width / assignment-suppression (db6bbf5): emit_runtime_scanf
now parses an optional * flag and a decimal field width after %, before the
l/ll length and conversion char. * consumes the input and advances the
vararg-pointer walker but skips the store-through-pointer and does not count
toward the returned item count; a nonzero width caps the number of field chars
the sign/digit readers consume (whitespace-skip happens before the field and
does not count), matching libc. Width enforcement threads sf_wroom/sf_wdec
through the decimal and hex readers (width 0 == unlimited), and sf_store
branches to a suppression path that advances the walker without dereferencing
or counting. The terminating peeked byte is pushed back through a one-byte
pending buffer ([rbp-184] guard, byte at [rbp-104]), so a width-limited
field does not lose its last byte to the next conversion. New
tests/codegen/scanfw.c reads "12345678 001 42\n22" via %3d %3x %*2d then
%d %llu, prints values + counts and returns n1*10+n2=22, stdout+exit
byte-identical to tcc -run. make test passes 3 tokenizer + 14 preprocessor
- 9 parser + 28 codegen = 54 suites, 0 failed;
-estaysm2==gccbyte-identical for every corpus (scanfw verified; the unrelated pre-existingfold_arith2^31-immediate text variant is unchanged); two clean M2 buildscmpbyte-identical.
The GNU inline-asm slice (the compiler-as-a-library tail) closed the first
slice of libtcc/asm compatibility. src/boot_sym.c's stmt_parse recognizes
asm/asm volatile/__asm__ (with optional volatile/__volatile__),
reads the "..." template (concatenating adjacent string literals via a new
asm_read_strings), and records an ST_ASM node (decoded template in name,
volatile flag in ival); dump_stmt/st_name print it for -x. The codegen
(cg_stmt -> cg_asm) splits the template on \n/; and hands each AT&T
instruction to a small mini x86 encoder (asm_stmt) that emits real machine
bytes as inline raw 'XX' rows into the M1 code stream, so the running
program executes the embedded assembly on amd64 (host==target). Supported
subset: mov/movl (imm->reg B8+r imm32 zero-extending, reg->reg 89 /r),
add (01 /r / imm 81 C0+r), sub (29 /r / 81 E8+r), xor (31 /r),
inc/dec (FF C0+r/FF C8+r), imul $imm,%s,%d (6B /r ib), nop,
ret, int; only the eight classic 32-bit general registers (modrm 0..7,
both %eax/%rax spellings), no memory/%rip/labels/clobbers, and
unsupported text is a hard error. M2-subset lessons re-applied: the encoder
never reads individual char-array elements (a[0]=='$' miscompiles under
the vendored M2) and never relies on compound short-circuit &&, using
register-vs-immediate detection (asm_reg == -1) and nested ifs; and the
two-operand reg-reg modrm must put the AT&T source in the reg field and the
destination in the r/m field ((a_r<<3)|b_r) or the direction reverses. Two
TCC-parity facts shaped the corpus: a GNU extension like "return the rax
inline asm left" makes TCC warn function might return no value (stderr
noise the gate compares), so the value-carrier helper fans out under
#ifdef __TINYC__ (TCC computes the same 12 in C; bootcc runs the genuine
asm body), while the asm statements in main are compiled by both paths. New
tests/codegen/inline_asm.c (asm computes 5 + (2*3) + 1 = 12 into rax
inside a helper, main returns it; stdout empty, exit 12) is TCC-parity green
on stdout+exit. make test passes 3 tokenizer + 14 preprocessor + 9 parser +
29 codegen = 55 suites, 0 failed; -e stays m2==gcc byte-identical for
every corpus including inline_asm (scanfw unchanged; only the pre-existing
fold_arith 2^31-immediate text variant differs); two clean M2 builds cmp
byte-identical.
libtcc drop-in front half (the compiler-as-a-library tail, slice 2) is
done: include/libtcc.h mirrors TinyCC 0.9.27's public API subset and
src/libtcc.c implements it on bootcc's own frontend + x86-64 emitter, so a
driver linked against bootcc-as-a-library compiles a C source STRING at
runtime: tcc_new/tcc_set_output_type/tcc_compile_string/tcc_output_file
/tcc_relocate/tcc_get_symbol/tcc_run. tcc_compile_string runs the exact
CLI -E block over the string staged to a temp .c, so the emitted M1 is
byte-identical to bootcc -e on the same source. Shared frontend state
(FILE* input, line, filename, hold_string, string_index) and the
line_error/require_token diagnostics moved out of bootcc.c's main TU into
a new src/boot_diag.c so BOTH the CLI and the driver link the engine. The
tiny tests/libtcc/driver.c reads the corpus tests/libtcc/snippet.c into a
runtime source string and drives the API; tests/run-libtcc-tests.sh (wired
into make test) builds the driver through M2, emits M1, links it via the
vendored blood-elf/M1/hex2 chain, and requires stdout+exit to match tcc -run
on the snippet (PASS: boot=42 tcc=42) plus an m==gcc gate (driver->M1 from M2
vs a gcc build of the same driver sources byte-identical). make test is 59
suites (3 tokenizer + 14 pp + 9 parser + 31 codegen + 2 libtcc), 0 failed.
Still open (honest, next increment): tcc_get_symbol returns the symbol's
link-time address (at the fixed blood-elf base, e.g. main@0x602B87) and
tcc_run forks/execs the produced executable, both verified TCC-parity green
across the whole codegen corpus — so the IN-PROCESS half is done. What stays
open is a true in-memory relocator that mmap-copies the emitted text into a
fresh region and relocates it (an in-memory JIT), which is not built here, and
a real -ltcc-linked parity side (no system libtcc.so; the vendored 0.9.26
tree's shared build failed to build in-session, so parity currently uses
tcc -run). The GNU inline-asm slice keeps growing on QUEUE's one-instruction
encoder: after the mini slicing (01a3c27), the breadth increment (a94fba9)
added memory disp(%reg) operands, the sixteen 64/32-bit registers with
REX.W/REX.B(/R)-correct mov/add/sub/xor/inc/dec/imul, local L<n> labels with
jmp/call to labels and C functions, and clobber-list rejection, all green
under new TCC-parity corpora (asm_breadth, asm_call). The honest bound of that
slice was %rip-relative access to a file-scope global variable (the emitter
placed no named :GLOBAL_<name> symbol rows and the hex2 linker rejects
absolute data references out of the text section) — and this gap is now closed:
slice 5 (460bbb5) makes file-scope initialized globals land as
:GLOBAL_<name> data labels carrying their real little-endian value bytes
(parse_external/bind_global_scalar binds a defined global and eval_consts
the scalar into a new symbol.ginit; emit_globals emits those bytes),
registers every file-scope object as a kind-1 global eslot so the C-side
codegen and the inline-asm lea/mov sym(%rip) path both reach it through
the existing lea_rax,[rip+DWORD] %GLOBAL_x pseudo, and adds
tests/codegen/asm_global.c (lea/load of an int and a long global,
TCC-parity green, der=12 tcc=12). A true
assembler segment (a real text blob with relocations) instead of the
one-instruction encoder stays on QUEUE.md. The
jump-table increment closed the R_X86_64_64 leg by using 4-byte absolute
slots (&L<n>), a real constraint that stays in force: hex2 has no 8-byte
data pointer, so a jump table is only correct while every in-text case label
fits a 32-bit address (true at the low 0x00600000 base for all current
corpora). A general emitted-runtime signed-int local whose slot is loaded
with mov_eax (zero-extends) is also a known latent edge versus TCC for
negative-index iteration, sidestepped in the corpus by keeping print/scan
buffer indices non-negative. Each of these open items is its own follow-up.
This increment opens inline asm beyond the one-instruction encoder. The
mini AT&T encoder's fixed set (reg/mem mov/add/sub/xor/inc/dec/
imul, a lea %rax-only sym(%rip), local labels, branches) is now
lengthened into a genuine assembler segment whose body is emitted as raw
byte rows the M1 toolchain assembles in-order, with every symbolic reference
routed through boot's M1 relocation pseudos. It closes the QUEUE "asm through
a true assembler segment" line by reaching a larger/arbitrary instruction
set: and/or/cmp (register/memory/immediate), test, the unary neg/
not, and the shl/shr/sar shift family (imm8 / by-one / %cl), plus a
real SSE slice — movd/movq GPR<->XMM and pxor/paddd/psubd, all
modrm-coded through REX.R/REX.B for XMM8..XMM15 and gated byte-for-byte
against GNU as (paddd %xmm1,%xmm0 -> 66 0F FE C1). Two new TCC-parity
corpora pass stdout+exit and hold m2==gcc emitted-M1 byte identity
(tests/codegen/asm_sse.c returns 5+6 via PADDD lanes = 11 with movd/
movq; tests/codegen/asm_ops.c returns 9 via the or/and/shl/shr/sar/neg/
not chain). make test is green: 3 tokenizer + 14 pp + 9 parser + 34 codegen
- 140 libtcc, 0 failed; two clean M2 builds
cmpbyte-identical. The honest, deliberate bounds kept open (the task's "keep open" list): the deeper SSE/SSE2/arbitrary-opcode breadth beyond the listed forms, full TCC asm operand-constraint ((r)/+/=etc.) semantics, the real-ltccshared-object side, and a true in-memory relocator (in-memory JIT) all stay on QUEUE.md; the emitted ELF still links at the low base with only 4-byte hex2 data pointers, so anR_X86_64_64absolute data pointer / 8-byte jump-table slot is still not expressible.
This increment reaches full GNU extended-asm operand-constraint semantics in
the assembler segment. The parser now accepts (and the emitter lowers) the
: "=r"(lval) : "r"(expr) : clobber output/input/clobber lists that used to be
a hard operand/constraint/clobber lists are not supported error, instead of
only the bare-template form. src/boot_sym.c keeps a global flat operand pool
(asmo_expr/asmo_kind, a slice per ST_ASM node in stnode[].a/.c) filled at
parse time (constraint letters =r/+r/r/i/n, the optional parenthised
operand expression stored as an enode row index) and consumed at codegen.
cg_asm hands template operands %0..%N to the caller-saved registers in a
fixed 6-slot order (rcx,rdx,rsi,rdi,r10,r11 — every one has both mov_<reg>,rax
and mov_rax,<reg> in the M1 defs), substitutes each %<dig> in the template
with the concrete %reg token (and an i-constraint with its folded $const),
spills/loads read-only and read-write inputs so their evaluation cannot clobber
one another, and stores =r/=+r outputs back into their C lvalues with the
existing store path — all through the same raw-byte assembler segment. %%
still means a literal % and a bare %reg passes through, so the existing
non-extended corpora are untouched. The codegen uses only flat if/else branch
chains and no interior char-array read-backs (asmo_append_reg writes the
token byte-by-byte) because M2-Planet mis-compiles the local-array + deep &&
form. New TCC-parity corpus tests/codegen/asm_constraints.c — =r write-only
output + two r inputs (addq %2,%1; movq %1,%0 => 9+4=13), +r read-write
(addq %1,%0 doubles x => 10), and an i immediate doubled in the template
(5+7=12) — returns 35, TCC-parity green on stdout+exit, stays m2==gcc emitted-M1
byte-identical, and is exercised by the in-process libtcc suite. make test is
green: 3 tokenizer + 14 pp + 9 parser + 35 codegen + 144 libtcc, 0 failed; two
clean M2 builds cmp byte-identical; M2-subset still compiles. Honest bounds
carried forward (kept open, per the task): deeper SSE/SSE2/arbitrary-opcode
breadth, "m" memory-operand constraints and XMM<->mem forms, the real
-ltcc shared-object parity side, and a true in-memory relocator (in-memory
JIT) remain on QUEUE.md; the emitted ELF still links at the low base with only
4-byte hex2 data pointers (no R_X86_64_64 absolute data pointer).
The GNU extended-asm operand-constraint increment opened "=r"/"+r"/"r"/"i"/"n" constraints with template %N substitution into the caller-saved registers; this session closed the two residuals that QUEUE line carried. The operand pool now accepts the memory-operand constraints "m"/"=m"/"+m" - a C-expression lvalue whose address (cg_addr, the lea_rax,[rip+DWORD] %GLOBAL_ / lea_rax,[r13+DWORD] %-off pseudos) is loaded into a caller-saved slot register and substituted into the template as a (%base) token that the assembler's existing asm_mem/asm_em_mem path decodes to a disp32 modrm, so the body reads/writes the memory directly (a =m/+m output needs no write-back). It also accepts the SSE constraints "x"/"=x"/"+x" - an %xmm register slot substituted by name, with =x/+x outputs stored back through a (REX.W) movq %xmmN,%rax then cg_addr+cg_store. On the SSE encoder side a new asm_xmm_mem (0x6E/0x7E, 66-prefix + REX.W for the 64-bit movq) reaches a memory operand, so movd/movq can move between a register-based memory operand and an %xmm register in either direction. tests/codegen/asm_mem.c (=x++r+=m+=r outputs, a "m" input, and the XMM<->mem and mem-reg arithmetic shapes) returns 50, stdout+exit byte-identical to tcc -run, and holds m2==gcc emitted-M1. make test is green (3 tokenizer + 14 preprocessor + 9 parser + 36 codegen = 62 suites, 0 failed, plus the 148-check libtcc in-process suite), two clean M2 builds cmp byte-identical, and the M2-subset discipline (byte-by-byte register token writers, flat if/else, no short-circuit &&) holds. Honest bounds kept open per the task: deeper SSE2/arbitrary-opcode breadth, the real -ltcc shared-object side and a true in-memory relocator (in-memory JIT), and the emitted ELF still links at the low base with only 4-byte hex2 data pointers (no R_X86_64_64 absolute data pointer).
The broadened SSE2/arbitrary-opcode increment opened the rest of the
[66|F2|F3] (REX) 0F <op> + shared-modrm shape in the inline-asm assembler
segment. asm_sse_prefix/asm_sse_rr/asm_sse_rm/
asm_gpr_to_xmm_op/asm_xmm_to_gpr_op parameterize the SSE prefix byte
(none/66/F2/F3), the 0x0F opcode, REX.W, and the modrm reg/r-m fields; the
new asm_sse_rop mnemonic map widens the reachable set past the single
movd/movq/pxor/paddd/psubd slice to: the packed-FP arithmetic/logic (addps/
addpd/addss/addsd, sub/mul/div, min/max, and/andn/or/xor for the ps/pd
families), the packed-integer arithmetic/logic/compare family (paddb/w/d/q,
psubb/w/d/q, pand/por/pxor, pcmpeqb/w/d, pcmpgtb/w/d), the 16/32/64-bit
move shapes (movdqa/movdqu/movaps/movups/movapd/movupd/movss/movsd both
XMM<->XMM and XMM<->mem, with store op = load op + 1), the imm8 compare
predicates (cmpps/cmppd/cmpss/cmpsd), and the scalar INT<->FP conversions
(cvtsi2ss/cvtsi2sd, cvttss2si/cvtss2si/cvtsd2si/cvttsd2si, cvtdq2ps/
cvtps2dq/cvttps2dq). A real encoder bug was caught and fixed against GNU as:
the XMM->GPR scalar conversions encode the destination GPR in the modrm reg
field (unlike movd/movq, which keep the XMM there), so cvttss2si %xmm3,%eax is
F3 0F 2C C3; the superseded movd/movq-only asm_xmm_rr was
removed. New TCC-parity corpus tests/codegen/asm_sse2.c returns 62 and its
byte blob is byte-identical to GNU as for the identical text; make test is
green (3 tokenizer + 14 pp + 9 parser + 37 codegen = 63 suites, 0 failed,
plus the 152-check libtcc in-process suite, holding the m2==gcc emit gates);
two clean M2 builds cmp byte-identical; M2-subset holds. The sym(%rip)
memory operand with an %xmm dest stays behind the GPR
lea_rax,[rip+DWORD] through-path; a true -ltcc side and an in-memory
relocator (JIT) remain QUEUE tails.
Invariants carried forward: must stay M2-subset-compilable, and in
particular avoid interior-pointer-to-struct-member patterns M2 mis-compiles
(both the declarator relink and the node pools index by row functionally for
that reason, and the codegen reads eslots[i].field/enode[i].field
directly). Deterministic. Do not regress make test; keep the two-clean-
build cmp gate and the TCC-parity gates green.
This NEXT increment (deeper SSE2 / arbitrary-opcode breadth) is done and
verified: make test is green (3 tokenizer + 14 pp + 9 parser + 37 codegen =
63 suites plus 152 libtcc in-process checks, 0 failed) with the m2==gcc
emitted-M1 gate held for asm_sse2 and every codegen corpus, the two-clean-build
cmp gate byte-identical, and M2-subset discipline intact.
This NEXT increment (the TRUE in-memory relocator for the libtcc half) is
done and verified: tcc_relocate and the runner now build a real in-memory
image — src/libtcc.c's load_image reads the emitted executable's first
PT_LOAD header, copies the whole text+data image (code, strpool, globals,
JTAB rows) byte-for-byte into a driver-local RWE IMG_BUF[], and re-bases the
in-range absolute JTAB case words by the copy delta (every PC-relative
lea_rax,[rip+DWORD] %GLOBAL_/%FUNCTION_ and branch is displacement-invariant
under a wholesale move, so no rip fixup is needed) — and tcc_get_symbol
returns a pointer INTO that live in-memory image (image + (link - link_vaddr)),
reported by a new tcc_image_info and asserted by the harness to land in
[imgbase, imgbase+imglen) for all 37 corpora (not the fixed 0x00600000 base).
Honest run bound kept open per the task: a direct CALL-based run of the
freestanding image in the host's process corrupts the emitted variadic/fd-I/O
(scanf) reads, because the emitted program is a standalone process (entered
via its own _start, clobbering every callee-saved register), so tcc_run
still runs the produced executable (byte-identical stdout+exit vs tcc -run);
the in-memory entry stays a QUEUE tail behind a process-isolation boundary
(a memfd/clone), and the real -ltcc shared-object half plus an
R_X86_64_64 absolute data pointer remain open. make test stays green:
3 tokenizer + 14 pp + 9 parser + 37 codegen + 152 libtcc = 0 failed, the
crank:** the real -ltcc shared-object parity side (see TASKS/NEXT.md); a
process-isolated in-memory entry and the R_X86_64_64 absolute data pointer
remain open QUEUE tails.
This NEXT increment (the real -ltcc shared-object parity side for the
libtcc run half) is done and verified: bootcc-as-a-library is now exposed
through a genuine ELF shared library build/amd64/libtcc.so, built with the
host gcc (-fPIC -shared) from the SAME engine + libtcc.c sources bootcc's
CLI and the M2 driver link, exporting the include/libtcc.h subset. An
unmodified TinyCC consumer binary that links -ltcc (-L build/amd64 -ltcc)
or dlopens libtcc.so now drives the whole documented libtcc flow
(tcc_new -> tcc_set_output_type -> tcc_compile_string -> tcc_output_file ->
tcc_relocate -> tcc_get_symbol("main") -> tcc_run) on the same corpus path,
with tcc_relocate building the real in-memory image, tcc_get_symbol resolving
a pointer INTO it, and tcc_run running byte-identical stdout+exit vs
tcc -run. The paren anchor is gcc (the honest bound: no in-tree system
libtcc.so; the vendored M2 tree's shared build still fails), using the same
M2-subset sources the m2==gcc gate proves byte-identical. Two consumers use
only the public API: a -ltcc-linked driver (tests/libtcc/driver.c) and a
dlopen+dlsym driver (tests/libtcc/dlopen_driver.c). A new
tests/run-ltcc-so-tests.sh harness (a make test phase, 266 checks) asserts,
for every corpus, that the -ltcc and dlopen consumers lower the source to
the SAME M1 as the gcc-engine reference, link+run it, and place every main
pointer inside [imgbase,imgbase+imglen) for both consumers, matching
tcc -run stdout+exit byte-for-byte. make test stays green: 3 tokenizer +
14 pp + 9 parser + 37 codegen + 152 libtcc in-process + 266 libtcc
shared-object = 0 failed; the emitted-M1 gates hold, two clean M2 builds cmp
byte-identical (no engine source changed; the increment is purely additive:
makefile targets, the two host-gcc consumers, and the new harness), and
M2-subset discipline intact. Next on the crank: a process-isolated
in-memory image entry (a memfd/clone boundary); an R_X86_64_64 absolute data
pointer in the vendored hex2 linker remains open.
This NEXT increment (process-isolated in-memory image entry for the libtcc
run half) is done and verified: tcc_run now enters the relocated
freestanding image from a FORKED CHILD through a real memfd+fexecve-like
boundary — no named-file exec. The isolation mechanism was determined
empirically: a fork+direct-jmp clone boundary enters the in-memory code but
corrupts the two variadic/fd-I/O scanf stdin readers (scanf, scanfw),
because the clone child shares the host's open file description and raw-fd
reader; the memfd + /proc/self/fd/N exec boundary (memfd_create an anonymous
file, stream the image's PT_LOAD bytes into it, execve the fd path) is a real
child PROCESS with its own _start, stack and fd 0/1, so a scanf runtime
reads the inherited stdin exactly once and stdout+exit stay byte-identical to
tcc -run for every corpus (all 37 + the three scanf readers), with no
named path in the exec. memfd_create is reached under __M2__ as a raw
inline-M1 syscall 319 and under gcc as a manual glibc declaration under
_GNU_SOURCE (M2-Planet also defines __GNUC__, so __M2__ discriminates);
the sub-child argv is the flat long save[2] form (the M2-subset char**
truncates a pointer). boot prints a memfd-run (anon fd exec, no named file)
marker to stderr, and new libtcc-memfd-* + libtcc-so-memfd-* harness
assertions grep it per corpus per consumer. make test is green: 3 tokenizer +
14 pp + 9 parser + 37 codegen + 190 libtcc in-process + 342 libtcc
shared-object = 0 failed; the m2==gcc emitted-M1 gate holds for every corpus
(38 in-process + 76 shared-object emit gates); two clean M2 builds cmp
byte-identical; M2-subset discipline intact. Next on the crank: a direct
call-based IN-PROCESS run of the freestanding image stays open at the same run
wall (a standalone process entered via its own _start is not ABI-safe to
call in the host process — the fork+memfd-exec child is the process-isolated
entry, exactly what isolates it); the sym(%rip)-with-%xmm-dest SSE memory
operand (not a hex2 relocation) and the R_X86_64_64 absolute data pointer in
the vendored hex2 linker remain open queues.
This NEXT increment (the sym(%rip)-with-%xmm-dest SSE memory operand) is
done and verified: a %(rip)-relative SYMBOL operand on an SSE instruction
whose destination is an %xmm register now reaches a real file-scope global.
The SSE mem decoders already recorded the rip-ness (g_sym_is/g_sym) but
the SSE mem emitters (asm_xmm_mem, asm_sse_rm) only know the register-base
g_base state a plain sym(%rip) leaves at -1, so a statement like
movq GLOBAL_x(%rip), %xmm0 had no encoder form. A new guard helper
asm_sse_sym_addr (src/boot_sym.c) is called before every SSE-memory emit
(both movd/movq XMM<->mem directions and the broadened SSE2
[66|F2|F3] 0F load/store shapes): for a sym(%rip) operand it materializes
the address through the existing GPR symbolic path — the M1
lea_rax,[rip+DWORD] %GLOBAL_/%FUNCTION_ pseudo (hex2 cannot relocate a raw
&sym byte ref from code) — into the caller-saved %rax scratch, then
rewrites the working mem state to 0(%rax) so the shared modrm coder emits a
correct r/m operand with the %xmm destination in the reg field and the
direction unchanged (0x6E load / 0x7E store / sse_op(+1)). New TCC-parity
corpus tests/codegen/asm_sse_rip.c (movq gdata0(%rip)->xmm0, movq
gdata1(%rip)->xmm1, paddd, movq %xmm0->gstore(%rip), reload gstore(%rip)->xmm2,
movq %xmm2->%rax) returns 42, stdout+exit green vs tcc -run, and holds the
m2==gcc emitted-M1 gate on both the libtcc in-process and -ltcc/dlopen
shared-object suites. make test is green: 3 tokenizer + 14 pp + 9 parser +
38 codegen + 195 libtcc in-process + 351 libtcc shared-object = 0 failed; the
m2==gcc emitted-M1 gate holds for every corpus; two clean M2 builds cmp
byte-identical; M2-subset discipline intact. Next on the crank: the
R_X86_64_64 absolute data pointer in the vendored hex2 linker stays open (it
constrains every data-symbol reach to the lea_rax,[rip+DWORD] pseudo; this
increment extends the same pseudo to the SSE %xmm-dest mem form and does NOT
add an absolute data pointer); a direct call-based IN-PROCESS run of the
freestanding image stays open at the same run wall (a standalone process
entered via its own _start is not ABI-safe to call in the host process — the
fork+memfd-exec child is the process-isolated entry, exactly what isolates it).
This NEXT increment (a true ABSOLUTE data pointer for the inline-asm
data-symbol reaches) is done and verified: the QUEUE R_X86_64_64
absolute-data-pointer tail is loosened on the reach side by the smallest
verifiable step, without forking/patching the external vendored hex2 linker
(which would be required to close the full relocatable-8-byte bound): the
inline-asm sym(%rip) reaches (lea sym(%rip),%reg, mov sym(%rip),%reg,
mov %reg,sym(%rip), and the SSE %xmm-dest mem side) now carry the
symbol's ABSOLUTE address as a true data pointer — the M1
mov_<reg>, &<kind><sym> line, whose &-modifier hex2 resolves to a 4-byte
absolute address (the SAME &-modifier its &L<n> jump-table case slots use
under the low 0x00600000 base) — into ANY caller-saved GPR the reach names,
instead of being pinned to the lea_rax,[rip+DWORD]-into-%rax channel. A
new asm_abs_name maps a bootcc register index to the vendored
mov_<name>, carrier macro (the 48 C7 Cx mov r/m64,imm32 forms for
rax/rbx/rcx/rdi/rdx/rsi in asm_defs.M1); asm_lea_sym/asm_sym_mov carry
the absolute address directly in the destination/carrier register (a %rbx/
%rcx/%rdx/%rsi/%rdi, never clobbering %rax), asm_sse_sym_addr
rewrites the SSE mem operand to 0(%rbx), and the store path chooses %rbx
(or %rax when the source register is itself %rbx) as the carrier before
storing through the shared byte-exact modrm coder. New TCC-parity corpus
tests/codegen/asm_abs_gpr.c returns 12 byte-identical to tcc -run and
holds the m2==gcc emitted-M1 gate on both the libtcc in-process and
-ltcc/dlopen shared-object suites. make test is green: 3 tokenizer + 14 pp
- 9 parser + 39 codegen + 200 libtcc in-process + 360 libtcc shared-object =
0 failed; the m2==gcc emitted-M1 gate holds for every corpus; two clean M2
builds
cmpbyte-identical; M2-subset discipline intact. Next on the crank: the fullR_X86_64_64relocatable absolute-data-pointer (a new hex2 linker relocation form, as opposed to the existing 4-byte&data pointer this increment uses for the reach carrier) stays open, so the C-side global path and the integerlea/mov sym(%rip)codegen still route through thelea_rax,[rip+DWORD]pseudo; a direct call-based IN-PROCESS run of the freestanding image stays open at the same run wall (a standalone process entered via its own_startis not ABI-safe to call in the host process — the fork+memfd-exec child is the process-isolated entry, exactly what isolates it).
Position (updated after the codegen-global &-absolute data-pointer increment):
the codegen GLOBAL half of the R_X86_64_64 absolute-data-pointer tail is now
closed on the integer CG-side (the fallback relaxed the LAST %rax-pin), not
by forking/patching the vendored hex2/M1 toolchain (that toolchain in
~/Sources/bootstrap is outside the bootcc worktree and cannot be edited here
per AUTONOMY/VENDOR.md). src/boot_sym.c: cg_slot_addr's GLOBAL branch now
emits mov_rax, &GLOBAL_<name> (the vendored &-absolute hex2 modifier, the
same one the &L<n> jump-table slots use under the low 0x00600000 base) in
place of the former lea_rax,[rip+DWORD] %GLOBAL_<name> pseudo, and a new
cg_store_ptr(e) materializes a plain store's address straight into the
store-carrier %rbx (a caller-saved GPR other than %rax) as mov_rbx, &GLOBAL_<name>, routing the cg_assign scalar/aggregate and cg_incdec
global-stores through it and skipping the lea_rax,[rip+] + mov_rbx,%rax
pair. Because the injected &GLOBAL_<name> absolute words land inside the
libtcc in-memory image's vaddr range, load_image's word rebaser patches them
with the jump-table slots, so the whole libtcc in-process and -ltcc/dlopen
in-memory-relocate suites stay green. New TCC-parity corpus
tests/codegen/cg_glob_abs.c (plain C global int/long reads, stored global
+=, post-inc/dec, read-back arithmetic) returns/prints 42 byte-identical to
tcc -run and holds the m2==gcc emitted-M1 gate; the emitted M1 has 17
&GLOBAL absolute-carrier lines and no lea_rax,[rip+DWORD] %GLOBAL for the
codegen global path. make test is green: 3 tokenizer + 14 pp + 9 parser + 40
codegen + 205 libtcc in-process + 369 libtcc shared-object = 0 failed; the
m2==gcc emitted-M1 gate holds for every corpus; two clean M2 builds cmp
byte-identical; M2-subset discipline intact. (Pre-existing, unrelated gaps
left open: a bare --g pre-decrement statement and global array/struct
MEMBER reads both still hit "not an lvalue" on the pristine binary too; the
corpus stays on the verified scalar global path.) Honest bounds kept open:
the full 8-byte relocatable R_X86_64_64-equivalent absolute (a NEW hex2
linker relocation form, not the 4-byte & absolute used here) stays out of
reach in the vendored hex2 linker, and a direct call-based IN-PROCESS run of
the freestanding image stays open at the same run wall (a standalone process
entered via its own _start is not ABI-safe to call in the host process; the
fork+memfd-exec child is the documented process-isolated entry). #
Position (updated after the codegen-global aggregate array-index/struct-member reach increment):
the codegen-global &-absolute reach is WIDENED from the scalar proof to aggregate
reaches, closing the two pre-existing gaps that surfaced on that proof (a bare --g/++g
pre-increment/decrement statement errored "codegen: not an lvalue" because the parser stores a
PRE-inc/dec target in the b field while cg_incdec read the a field; a global
ARRAY-INDEX (garr[2]) or STRUCT-MEMBER (gpt.a) READ returned 0 because array/struct/union
file-scope initializers were skip_rhs()-dropped and the :GLOBAL_ slot was emitted zeroed).
src/boot_sym.c: (1) cg_incdec now selects the target from the correct b/a field for
pre/post and, like the store path, loads the current value BEFORE materializing the store
address into %rbx (the cg_addr walk for an aggregate subscript/member recomputes the base
through %rbx, so pinning the carrier first corrupted it on index/member inc/dec) -- it now
covers ++g[0]/--gpt.b/g[0]++ bare statements; (2) aggregate file-scope initializers are
now captured into a bounded per-symbol byte buffer (struct symbol.ginitb[AGG_INIT_MAX] +
glen, flat arrays/structs of scalar constants, optional per-level {...}) by the new
ginit_fill/ginit_put, and emit_globals places those bytes as the :GLOBAL_<name>
2-digit-hex data rows (zero-padded past the high-water mark) so an initialized array element /
struct member READs its real value through the same mov_rax, &GLOBAL_<name> absolute carrier,
and STORE back to an array element / struct member (incl. pre/post inc/dec as bare statements)
works. New TCC-parity corpus tests/codegen/cg_glob_agg.c (int array + struct global reads,
element/member store-back, ++garr[0]/--gpt.b bare pre-inc/dec) prints/returns 76 byte-
identical to tcc -run (stdout "76\n"), and the whole codegen (now 41) + libtcc in-process
(210) + shared-object (378) corpus holds the m2==gcc emitted-M1 gate (gcc reference drivers
rebuilt from the updated sources) and the two-clean-build cmp determinism gate. make test
is 3 tokenizer + 14 pp + 9 parser + 41 codegen + 210 libtcc in-process + 378 libtcc
shared-object = 0 failed; M2-subset discipline holds (flat if/else guards, no new interior
char-array read-backs). Honest bounds kept open: the full 8-byte relocatable
R_X86_64_64-equivalent absolute data pointer (a NEW hex2 linker relocation form, not the
4-byte & absolute these increments use) stays in the vendored hex2 linker (whose source
lives outside the bootcc worktree in ~/Sources/bootstrap), and a direct call-based
IN-PROCESS run of the freestanding image stays open at the same run wall (a standalone
process entered via its own _start is not ABI-safe to call in the host process; the
fork+memfd-exec child is the documented process-isolated entry).
Position (updated after the codegen LOCAL aggregate-initializer increment):
the LOCAL (block-scope) aggregate initializer is now a first-class declaration
form: a struct pt p = {1,2,3}; or int a[3] = {1,2,3}; inside a function
body (previously a parser gap that errored expected ';' after declaration)
parses and materializes each constant element/member into the callee's local
frame, so reads back the real value. src/boot_sym.c: parse_local_decl's
= initializer branch detects an aggregate-typed declarator followed by {,
lowers it to a chain of EX_ASGN store expressions with member/index targets
(recursively in storage order, optional per-level braces, leaf constants read
by eval_const() via new local_agg_fill/agg_emit_store/agg_const_node),
wraps the chain in a new EX_AGGLIST marker node, and stashes it on the ST_DECL
.e. cg_val evaluates EX_AGGLIST by walking its right-leaning EX_COMMA
tree of assignments, so the existing cg_assign member/index store path writes
each byte into the local; cg_stmt's ST_DECL routes an EX_AGGLIST initializer
straight to that store path (no trailing whole-slot store, and crucially BEFORE
the agg_t_is_2reg whole-struct-by-value branch so a 9..16-byte struct braced
init is not misread as a two-register aggregate return). New TCC-parity corpus
tests/codegen/cg_local_agg.c (local struct pt {1,2,3} + int[4] + array of
struct pt with nested braces + char[4], incl. a char store-back) prints/returns
273 byte-identical to tcc -run (stdout "273\n"); the whole codegen (now 42) +
libtcc in-process (215) + shared-object (387) corpus holds the m2==gcc emitted-M1
gate (the /tmp gcc reference driver rebuilt from the updated engine sources) and
the two-clean-build cmp determinism gate. make test is 3 tokenizer + 14 pp +
9 parser + 42 codegen + 215 libtcc in-process + 387 libtcc shared-object = 0
failed; M2-subset discipline holds (flat if/else guards, no new interior char-array
read-backs). Honest bounds kept open: the full 8-byte relocatable
R_X86_64_64-equivalent absolute data pointer (a NEW hex2 linker relocation form,
not the 4-byte & absolute these increments use) stays in the vendored hex2 linker
(whose source lives outside the bootcc worktree in ~/Sources/bootstrap), and a
direct call-based IN-PROCESS run of the freestanding image stays open at the same
run wall (a standalone process entered via its own _start is not ABI-safe to call
in the host process; the fork+memfd-exec child is the documented process-isolated
entry).
This increment — first tcc.c slice probe + const-qualified pointer declarators #
Swung the first real-slice probe at tcc 0.9.27 per TASKS/NEXT.md. The full
tcc.h+tcc.c preprocess is too slow to yield a parser diagnostic in one session
(the M2-host preprocesses the whole input before any parse/emit phase), so the
-e probe used a hand-built slice (the task's option 2) of the densest tcc
data-table idiom. The first parser blocker surfaced and was FIXED IN src/:
declarator_slot (src/boot_sym.c) captured a trailing const/volatile
qualifier as the identifier name after a *, so any CONST-QUALIFIED POINTER
declarator (char *const p, char *const a[]) declared a symbol named const
and every reach to the real name died "codegen: undeclared identifier". The loop
now skips const/volatile after each *. New TCC-parity corpus
tests/codegen/constptr.c; make test is 3 tokenizer + 14 pp + 9 parser + 44
codegen + 225 libtcc in-process + 405 libtcc shared-object = 0 failed, m2==gcc
emitted-M1 gate holds for every corpus, two clean M2 builds cmp byte-identical.
Next-task seed (the genuinely first tcc RUNTIME blocker): a FILE-SCOPE
pointer initialized from a string literal or another global's address
(char *table[] = {"x","y"}; const char *p = "hello") compiles but SEGFAULTS
(139) at runtime — bind_global_scalar stores eval_const() (0) into the
:GLOBAL_ slot instead of the string/absolute address, so a deref hits 0. This is
the data-section/&-carrier-relocation gap on the global-initializer side. That
is the concrete seed recorded in TASKS/NEXT.md.
Position (updated after the build-tcc x86_64 wiring increment):
the stop-rule 4-step chain now BUILDS and RUNS the bootcc-built tcc: sh tools/build-tcc.sh links a 1,010,289-byte ELF (blood-elf --64 -> M1 amd64 defs
-> hex2 @0x00600000) where tcc -dumpversion prints 0.9.26 rc=0 (smoke1
PASS). Two changes landed: (1) tools/build-tcc.sh emits with the M2-built
build/amd64/bootcc (AUTONOMY rule 6 — the gcc frontier-probe stays an oracle,
never a build input), TCC_SRC defaults to the scratch x86_64 copy
/home/lrvick/.jcode/scratch/tccx64/tcc.c (pristine tcc-0.9.27 untouched), AFLAGS
retargeted x86_64 (-DPTR_SIZE=8 -DLDOUBLE_SIZE=16 -DCHAR_BIT=8 -DHAVE_LONG_LONG
-DSTDC_INT_TYPES -DTCC_IS_NATIVE); the vendored chain steps are already amd64
and unchanged. (2) src/boot_sym.c emit_runtime gains :FUNCTION_abort — the
x86_64 backend's gen_mov64 dead-code fallback calls abort() (x86_64-gen.c:
607/615) which the i386 path never referenced, so the freestanding runtime had
no such label and hex2 refused the TU ("Target label FUNCTION_abort is not
valid"); the minimal stub exits with status 134 (=128+SIGABRT) via the exit
syscall. All suites green (3 tokenizer + 23 pp + 17 parser + 71 codegen + 360
libtcc in-process + 648 libtcc so = 0 failed; the two cached gcc oracles under
$TMPDIR/bootcc-libtcc-gcc + boot-ltcc-so-gcc refreshed after the emit change),
two clean M2 builds cmp byte-identical, frontier holds 06:0000000, gate GO.
smoke2 (tcc -run triv.c, expect rc=7) now segfaults (rc=139) — precisely
root-caused (gdb, debug build at fixed path /home/lrvick/.jcode/scratch/tccx64/
dbg/tcc): the crash is in FUNCTION_put_elf_sym (tccelf.c) at movsbq (%rax),%rax (the name[0] read in if (name && name[0])) with the 7th
argument (first SysV stack argument) = 0x48c43c0 (garbage, below the image base
0x600000); the prologue loads that arg from [rbp+24] (lea 0x18(%rbp)) while
the caller set_elf_sym pushes 4 stack words then pops into r9/r8/rcx/rdx and
calls. The prologue stack-arg load formula is at src/boot_sym.c:8007/8018
(lea_rax,[rbp+DWORD] %24+(i-6)*8), cg_va at :5788 uses the same base, and
the caller-side excess-arg push is at :5689-5730 — the exact caller/callee
asymmetry is the NEXT increment. Minimal 7/8/9-arg repros (scratch x64d1-x64d6,
incl. pointer-deref and stack-arg forwarding) ALL pass with bootcc==tcc (both
sides use a self-consistent convention), so the next step is a discriminating
repro that actually fails, then the offset fix + a tests/codegen/ corpus. The
gcc-oracle tcc (same scratch source/headers/defines, gcc -O1) ALSO segfaults
but at an unrelated earlier point (__sigsetjmp in tcc_compile, libtcc.c:634 —
portable_libc setjmp.h defines jmp_buf as a 4-byte int while glibc setjmp
writes ~24 bytes), so it is NOT a valid control for this crash; the
host-installed tcc returns rc=7 correctly. Exact crash state + repro inventory
recorded at scratch /home/lrvick/.jcode/scratch/tccx64/smoke2-crash-notes.md.
smoke2 position (updated after the local pointer-array string-init fix):
bug A (the "library 'c' not found" root cause) is FIXED + committed. The defect
was in local_agg_fill (src/boot_sym.c): a string literal stored in a NON-char
aggregate element (a char * array element) was folded through eval_const,
which returns 0 for a string token, so every element was stored NULL. The
smoke2 construct is exactly const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL } (libtcc.c:1143) — the compiled tcc stored mov $0x0 for
all three (disasm-confirmed), so *pp was NULL and tcc_add_library returned -1
without ever stat'ing a candidate. Fixed by emitting a real EX_STR node as the
store RHS (lea [rip+%STRING_n]); corpus tests/codegen/ptrarr_str_init.c
(rc=31==tcc, rc=100 without the fix). All suites green (73 codegen), gate GO,
frontier holds 06:0000000. The NEXT smoke2 blocker is bug B: the compiled tcc
HANGS (rc=124) in a char-scanning loop (RIP=0x6afaa1, cmpb $0x25/dec %r8
shape) after opening + reading 8192 bytes of
//lib/x86_64-linux-gnu/libgcc_s.so.1 — a string/loop walk over the ELF data
that never terminates, a second distinct engine defect (fully static image;
gdb/strace captures + persist build helper at
/home/lrvick/.jcode/scratch/tccx64/). Re-running sh tools/build-tcc.sh with
the fixed engine is the next step to confirm the library stage now resolves and
to re-pin bug B at its exact line.
smoke2 position (updated after the runtime printf flag-spin fix):
bug B (the compiled tcc's hang after reading libgcc_s.so.1) was NOT an engine
codegen defect: the spin site (RIP=0x6afaba in the persist debug build) is the
hand-written full-tcc runtime's format engine, TR_pe_flags in
tools/tcc_runtime.S (linked into the build-tcc.sh chain via
tools/tcc_runtime.M1, which the engine does not emit -- the engine's own
printf, src/boot_sym.c:8851+, advances r14 per flag and is correct, which is
why the 73 codegen corpora never hit it). The flag-skip loop detected a flag
char (-/0/+/space after '%') but jumped back to re-read the SAME byte without
incq %r14, so ANY flagged conversion (%08x, %-16s, %-8s, %08X -- all used by
tccpe.c/libtcc.c) spun forever. The prior "eb 00 self-loop / FUNCTION_printf
M1 line 397 label-resolution bug" theory was a misread: the eb 00 at
0x6afac8 is a benign forward jmp TR_pe_width (the vsnprintf entry's
mov rbx,rcx is followed by a zero-length jump). Fixed by adding a
TR_pe_flag case that consumes the flag byte (incq %r14) and rescans;
regenerated tools/tcc_runtime.M1 via tools/mk-tcc-runtime.sh (verified the new
bytes: 4 jes -> TR_pe_flag, fallthrough eb 05 -> TR_pe_width,
49 ff c6 incq, eb e5 back to TR_pe_flags). Failing repro (rule 7):
fprintf(stderr, "%04d\n", 42) through the full build-tcc chain hung rc=124
before, exits 0 after (scratch /home/lrvick/.jcode/scratch/tccx64/rf.bin).
All suites green after the change (73 codegen, 370 libtcc in-process,
666 libtcc so); gate GO, frontier holds 06:0000000. The NEXT smoke2 blocker
is now the library-resolution stage proper: tcc -run triv.c prints
tcc: error: library 'c' not found plus
//lib/x86_64-linux-gnu/libgcc_s.so.1: error: unrecognized character \x7f
(the .so's first byte being parsed as C source) and exits rc=1. Bug A's fix is
confirmed present at the syscall level (tcc now opens+reads the libc
candidates, /usr/lib/x86_64-linux-gnu/libc.a has a valid !<arch> header),
yet the error still prints -- so either the archive/ELF content check
(read_elf_header / the !<arch> member scan in libtcc.c) or the
tcc_add_library error-exit path has a further codegen defect, or
CONFIG_TCC_STATIC/s->static_link is not set and the .so path is taken
(then parsed as source). Next increment: root-cause which of those three it
is (strace + disasm of the compiled tcc's tcc_add_library/readelf path), tiny
failing repro, fix, corpus, gate, commit.