Repository navigation
yasc dialect, safe by default, static analysis, error recovery, sanitizers - #28
Merged
Merged
Conversation
…izers Safe by default (-ccompat for regular C): the yasc dialect, -Wall, the flow checks and unsafe C as errors. docs/static_analysis_todo.md has every item; in short: yasc dialect - ownership keywords (owned, view, maybe, out, drop), plain pointers forbidden; per-file dialect (#pragma yasc, -iyasc DIR); regular-C pointers unchecked, GCC attributes refine them - move()/borrow(), C23 auto/__auto_type, view does not escape, borrows(...) on results, members and structs, owned(dealloc), int handles (owned(close)), takes(p), owned out-parameters, owned slots and objects - defer/errdefer, error sets and unions, try/catch, error_name; methods; modules (import/export, .ymi) - examples/yasc: a tutorial, one runnable program per chapter Flow checks on the raw IR (same at every -O, no SSA at -O0) - -Wlifetime: use after move/free, double free, leaks, maybe dereferences, out parameters, borrows, view escapes; values across blocks, correlated conditions, member paths (also of local/global structs and array elements, variable indexes), status locals, nonnull as not maybe - -Wuninitialized/-Wmaybe-uninitialized, -Wreturn-local-addr, -Wdangling-pointer, -Wnull-dereference (post-optimisation), -Warray-bounds=2 (interval analysis, source/ir/bounds.c), -Wtainted-format (globals, members, same-unit summaries) Frontend checks - -Wformat/-security/-n, -Wunused-result/[[nodiscard]], -Wdeprecated-declarations, -Wunused-* (+ local-typedefs), -Wimplicit-fallthrough, -Wparentheses, -Wlogical-not-parentheses, -Wdangling-else, -Wempty-body, -Wswitch, -Wshadow, -Wsign-compare, -Wconversion (value ranges), constant checks (shift-count, div-by-zero, overflow, shift-overflow, tautological-compare, type-limits), -Warray-bounds, -Wsizeof-pointer-memaccess/-array-argument, -Wstrict/-missing-prototypes (C23 `()` is `(void)`), -Wpointer-arith, -Wcast-qual, -Wcast-align, -Waddress-of-packed-member, -Wextra, -Wsystem-headers; quiet in system headers and their macros - __builtin_(dynamic_)object_size, -Wstringop-overflow, -Wformat-overflow/-truncation, -Walloc-size-larger-than, -Walloc-mul-overflow, -Wfree-nonheap-object, -Wmismatched-dealloc - one report-once layer: a static inline called twice reports once at every -O; #pragma GCC/clang diagnostic push/pop/ignored/warning/error Diagnostics and driver - error recovery: keeps parsing after an error, -fmax-errors=N (default 8) - -fsyntax-only, -fdiagnostics-color, -fdiagnostics-format=json|sarif, fix-it hints (snprintf/strlcpy with the right size; owned/view/maybe for a plain pointer decided from the body, aliases followed), -fdiagnostics-parseable-fixits, -Wcross-tu (types and struct layouts compared at link time, .tcc.typesig only with the flag) Stack, YasOS-specific - -Wframe-larger-than=, -Wstack-usage=, -Wvla, -Walloca, -fstack-usage, -fcallgraph-info (indirect calls by calling shape), scripts/stack_usage.py (worst path per entry point; libtcc1's .ci) Runtime instrumentation - -fsanitize=undefined (trap by default; clang-ABI __ubsan_handle_* with -fno-sanitize-trap / -fsanitize-recover), -ftrapv, -fstack-protector[-strong|-all|-explicit], stack_protect / no_stack_protector - -b bounds checking on the armv8m cross for the QEMU (newlib) runs C23 #embed and __has_embed. Fixes found on the way: union-cast copy dropped (param_copy_alias), narrow struct-copy forwarding sign, LICM across __builtin_apply, sanitized pre-decrement reload slot, computed-goto CFG edges (label blocks), a check-only asm goto label leaking a symbol, asm operands in clobbered registers, the -finstrument-functions exit hook, CMP #0 fusion dropping a barrel shift, the return-tail register share, two valgrind uninitialised reads, objsize of a global plus an offset, DATA_ONLY_WANTED, sym_scope on a helper symbol. Objects of every existing test are byte-identical with and without the new checks, and to the previous compiler except where a fix changes code. Verified: tests/ir_tests incl. GCC torture (35 known failures, none new), unit, frontend and asm tests, the selfhost compile gate (both native configurations), build_rootfs, an524 kernel, QEMU self-host fixpoint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 of 4 tasks
…unary/expr_eq out of line
The device tcc (32 KiB stack) overflowed compiling ir_tests 187/287/299/336
and gcc torture compile/20030216-1.c: nested parentheses recurse
unary -> unary_paren -> gexpr -> expr_eq -> expr_cond -> expr_unary_infix
-> unary, and the member access, subscript, assignment (NRVO, objsize)
and -Wtautological-compare bookkeeping had grown into those frames.
Out of line (noinline) now: unary_member ('.'/'->'), unary_subscript +
unary_subscript_end ('[', only a small SubscriptState across the index),
unary_paren_type (AttributeDef, compound literal) + unary_union_cast,
expr_eq_assign (+ expr_eq_objsize_rhs), gexpr_comma, and the operand-hash
variants expr_infix_l_fp / expr_unary_infix_fp (taken while fe_tokfp_on).
ARM frames (unity TU, -O2, native defines), 471ab72 / c35ae0a / now:
unary 72/464/40, unary_paren 200/240/32, gexpr 16/24/16, expr_eq
48/168/16, expr_cond 8/8/8, expr_unary_infix -/32/16, expr_infix_l
-/96/32: the paren cycle 344/936/128 bytes. Host cross, 287 at -O1:
needs 28 KiB of stack (32 at 471ab72, 56 at c35ae0a).
Objects identical (1979 ir_tests objects at -O0/-O1/-O2, -Wall, safe
default; all 53 tinycc unity TUs at the native -O2), diagnostics identical.
Tests: tests/ir_tests/test_parse_stack_depth.py (200 nested levels of
parens, casts, member/subscript and a mix under a fixed RLIMIT_STACK:
471ab72 passes, c35ae0a fails all 9), and
tests/selfhost/test_parser_stack_frames.py (the ARM -fstack-usage frames
of each recursion cycle against a budget; c35ae0a fails all 4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…to .rodata On the device `tcc -ccompat yasc_errors.c yasc_errors+abi.c` (and yasc_error_name.c + yasc_error_name+b.c) failed at link: "YAFF output cannot represent allocated section 'yasc_errname'". The host suite links ELF and never saw it. For a YAFF output, elf_output_file now appends the yasc_errname records (no relocations) to .rodata, 4-aligned, before GC and the GOT build, and defines __start_yasc_errname / __stop_yasc_errname there as LOCAL symbols (as __yaff_initfini: their GOT entries take the R_RELATIVE path). The section keeps its bytes for tcc_yasc_check_error_names and leaves the layout (SHF_ALLOC cleared), so tcc_add_linker_symbols does not define the bounds again. ELF output and YAFF modules without yasc error names are unchanged. Test: tests/ir_tests/test_yasc_errname_yaff.py links both programs as YAFF (-O0, -O2, -O1 --gc-sections, -g), reads the bounds from the image's debug symbol table, checks the bytes between them are the objects' records and resolves the names of the .expect files the way __yasc_error_name does. Fails 6/6 before, passes 6/6 after. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nt, call checks and statement attributes out of the parser's frames The device tcc (32 KiB stack, the kernel's fs lock wants 2 KiB of it left) overflowed compiling the Zig-rendered YasOS kernel (kernel.c, -O2) on the board: at 81 s an ext4 spill write found 1976 bytes left. The deep part is the frontend inliner: an expanded call replays the callee's body inside unary_funcall_body(), and an expansion's calls expand in turn, up to INLINE_NEST_MAX (32) deep -- kernel.c's called-once chains reach 19. A level is unary_funcall_body -> replay_body_recovering -> replay_recovering -> replay_block -> block -> block -> gexpr -> expr_eq -> expr_cond -> expr_unary_infix -> unary -> unary_funcall (+ decl and the initializer when the call initializes a local). ARM frames, 471ab72 -> 70f1f1a: the error recovery's TCCRecover (jmp_buf + saved state) in replay_recovering 0 -> 360, unary_funcall_body 736 -> 1144 (-Wformat FmtCheck and the -Wsizeof-pointer-memaccess state live across the arguments and the replay), block 208 -> 304 (statement attributes' AttributeDef): a level 1308 -> 2260. Now: - replay_recovering and gen_body_recovering keep their TCCRecover on the heap (tcc_recover_release frees it when the compile ends on an error). - unary_funcall_body: the argument checks are one heap CallArgChecks, made only for a callee they apply to; the __builtin_va_arg_pack clone (funcall_va_pack_clone) and the printf-family rewrite (funcall_printf_family, its argument positions from a table) out of line. - block: jumps, statement and label attributes, the switch value copy and the non-local goto in noinline helpers (no SValue/AttributeDef left). - decl: the nested function's 256-byte name buffer in nested_func_label. - The end of every expression: gen_op_checked's -Wconversion record and the checks in their own frames (416 -> 24 on the gen_op path); vstore's 256-byte constant-initializer snapshot on the heap (908 -> 644). ARM frames (unity TUs, -O2, native defines): a level 2260 -> 1196 (1308 at 471ab72), with a declaration 3600 -> 2408. kernel.c (rp2350 config), the ARM-frame-weighted call stack peak (host cross with -finstrument-functions, each function weighted by its ARM -fstack-usage): 471ab72 31140, c35ae0a ~62400, 70f1f1a 49012, now 29004 bytes. Host cross, smallest ulimit -s for kernel.c: 52 / 93 / 75 / 53 KiB. Objects identical (1166 ir_tests sources at -O0/-O1/-O2/-Os, -Wall, the safe default; 3920 gcc torture sources at -O1/-O2/-Wall; all 77 tinycc TUs at the native -O2; kernel.c), diagnostics identical. Tests: test_parse_stack_depth.py: 40 nested inline expansions (return, initialized local, if + compound) under a fixed RLIMIT_STACK at -O1/-O2 (70f1f1a fails all 6); test_parser_stack_frames.py: the inline and inline+declaration cycles, the operator and the store at the end of an expression (70f1f1a fails all 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the anonymous object its own slot
A named scalar local gets no stack in decl_initializer_alloc (it is a
register candidate: sym_push gives it a vreg), and an anonymous one --
`&(int){0}` -- took the same branch but has no vreg: it was addressed at
`loc` as it stood, the first bytes of the local allocated last, at every -O
level. A store through its address overwrote that local.
Found as a device-only regression of bccc13c: vstore_value_1's
`type_size(&vtop->type, &(int){0})` wrote the alignment over orig_dst.r once
the 256-byte buffer below it was gone, so the native tcc lost an
initializer's destination for the allocation tracker
(tests/ir_tests/objsize_builtin.c: `B(p3, 1) = -1` instead of 30 at
-O1/-O2 in the QEMU smoke gate; host cross correct). 471ab72's cross has
the same bug; op/vector.c has the same pattern.
Objects change only where a scalar compound literal's address is taken: of
1166 ir_tests sources none but the new test, of 3920 gcc torture sources
compile/compound-literal-2.c, of the 77 tinycc TUs frontend_gen_store and
frontend_gen_op (the two sites above); kernel.c identical.
Test: bug_scalar_compound_literal_slot.c (a struct local clobbered through
`&(int){0}`, two literals sharing one slot, a named scalar unchanged): fails
at -O0/-O1/-O2/-Os before. Device: the native tcc built from this tree by
this cross compiles objsize_builtin.c to `movs r2, #30` again (QEMU, an524).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The files are plain C. In the safe default (C23 + yasc) a target without __GNUC__ (the CI's Linux-target cross) gets newlib's empty __inline, and the unused static stdio helpers warn -- lib/Makefile builds the runtime with -ccompat for the same reason. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The safe-by-default dialect rejects their plain pointers ("plain pointer
in yasc: say owned or view"), which broke the metrics job's RP2350
benchmark and fp-conformance builds. -ccompat gives the code generated
before the safe default.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed bodies, VLA parameter sizes The CI's ASan cross (--enable-asan) reported leaks in tests whose compile ends at an error or never generates code: - a body save an error cut (save_body_cut, -O1 up): defer_function_body's DeferredFunc and the lexer's message (save_body_raise said it leaked "with the compile"). TCCState.save_body_deferred holds the entry while the body is saved; tccgen_finish frees it and the message. - a nested function's body when the parent's parse ends at an error: the slot keeps func_str and nothing freed it. compile_nested_functions now hands the body to its replay (end_macro freed it there anyway, leaving the pointer behind), so nested_func_release frees a body still in the slot. - a token string skip_or_save_block allocated before "unexpected end of file". - the outermost VLA parameter dimensions a declarator saves, at -fsyntax-only (gen_function_check_only never evaluates them): vla_param_exprs_free there and in tccgen_finish. test_max_errors.py's cut-body test asserts no sanitizer report at every level (red on the ASan cross before: comment/string cuts at -O1 up, the unterminated nested function at all levels); test_vla_alloca.py's -fsyntax-only case was red the same way. Objects unchanged (ir_tests sources at -O0/-O2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The C header left out owned/view/maybe/out/drop but kept what follows
borrows, takes and owned(dealloc): `grid_t * borrows(static) grid_get(void);`
does not parse as C (test_qemu.py test_yasc_modules_c_caller failed to build
its C caller). yasc_export_finish now drops a qualifier's parenthesised
arguments where the parser reads them as one -- borrows/takes in a pointer's
qualifiers or after `struct T`, owned(NAME) -- and a function called takes
keeps its name.
test_yasc_modules.py: test_header_leaves_out_qualifier_arguments (red
before: borrows(static), borrows(s), takes(p), (close) in the header).
Not fixed here: an exported `struct T borrows(x) { ... }` loses its body in
the interface and the C header (`struct tok borrows(text);`).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Without __GNUC__ -- the CI's ARM Linux cross; the YasOS target predefines it -- newlib's sys/cdefs.h deletes `__inline`, so the `static __inline` helpers of stdio.h and machine/endian.h become plain statics and the safe default / -Wall report them unused in every file: the yasc tutorial and example builds (-Werror) and ubsan_runtime.c failed in CI. They are the target's libc headers, quiet as a real sysroot's: the QEMU Makefile, cross_includes.py (used by test_sanitize.py now) and test_yasc_examples.py pass them with -isystem, in the same order. System-header status changes diagnostics only, not code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- test_cross_tu.py linked without -B/-L: the runtime libraries (armv8m-libtcc1.a, fp/libsoftfp.a) are found only where a YasOS cross is configured to look; the CI's cross looks in /usr/local/lib/tcc. - test_stack_usage.py: via_void's `return other(p);` is a tail call on an ARM Linux cross (no R9 to restore), so its frame is not added; `+ 1` keeps the call a call on both. - test_qemu.py's yasc module tests compiled the modules without the QEMU Makefile's -fno-pic -mno-sb-relative-got: on a YasOS cross their globals were R9-relative on bare metal (the 16 yasc_modules*/methods_module runs of the ir_tests baseline). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…de them An -Werror=lifetime error that reached -fmax-errors longjmped out of tcc_ir_lifetime_check, leaking its CFG and some forty per-check arrays: the CI's ASan cross appended the leak report to the JSON diagnostics (test_diag_format.py test_max_errors, -fmax-errors=1). tcc_ir_flow_checks now defers the stop (tcc_max_errors_defer): the Nth error still says "compilation terminated", the diagnostics after it are not said, and tcc_max_errors_stop ends the compile once the checks have returned. A fatal error inside them still leaves at once. error1's longjmp is error_longjmp, shared with the stop. test_diag_format.py: no sanitizer report with -fmax-errors=1 (red on the ASan cross before). Objects unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d install
Tests that ran armv8m-tcc on a C file without include flags found
<stddef.h>, <stdarg.h> and <stdlib.h> only where a YasOS cross (or a stale
`make install` in /usr/local/lib/tcc) has them; the CI's fresh cross has
neither, and /usr/include is the host's glibc ("include file 'stddef.h' not
found", "bits/libc-header-start.h"). They pass cross_includes.INCLUDE_FLAGS
now, as its docstring asks: test_unused, test_stack_usage, test_stack_protector,
test_sanitize (_obj), test_yasc_plain_pointer, test_yasc_modules, test_fixits,
test_diag_format, test_cross_tu and the yasc module compiles of test_qemu;
test_bcheck adds tcc's include/ to its runtime build.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
One squashed commit: the yasc dialect, safe by default, and the static-analysis plan in
docs/static_analysis_todo.md(126 items done, the rest listed there).Summary
#pragma yasc,-iyasc),move/borrow, C23auto, views,borrows(...),owned(dealloc), int handles,takes, defer/errdefer, error sets, try/catch, methods, modules;examples/yasctutorial.-ccompatfor regular C): yasc,-Wall, the flow checks, unsafe C as errors.-Wlifetime,-W(maybe-)uninitialized,-Wreturn-local-addr,-Wdangling-pointer,-Wnull-dereference,-Warray-bounds=2,-Wtainted-format.-Wall/-Wextrasets, object sizes (__builtin_(dynamic_)object_size,-Wstringop-overflow, …), one report-once layer, quiet in system headers and their macros,#pragma GCC diagnostic.-fmax-errors=N(default 8);-fsyntax-only;-fdiagnostics-format=json|sarif; fix-it hints;-Wcross-tu.-Wframe-larger-than=,-Wstack-usage=,-Wvla,-Walloca,-fstack-usage,-fcallgraph-info,scripts/stack_usage.py.-fsanitize=undefined(trap; clang-ABI handlers),-ftrapv,-fstack-protector*,-bon the armv8m cross for QEMU.#embed; about twenty codegen/optimizer bugs found on the way fixed with regression tests.Test plan
tests/ir_testsincl. GCC torture: 35 known failures, none new-Wall -Werror)Companion PRs: matgla/yasos_libc, matgla/yasvi, matgla/yasos.zig (
combined-2026-11-22/feat/yasc-highlight).🤖 Generated with Claude Code