Skip to content

Curated libc contract overlay for c_import modeled surfaces #379

Closed

Description

@ehartford

Summary

Ship the curated libc contract overlay the spec names as a standard toolchain deliverable. Since the safe/raw classification landed (commit 1373e45), every pointer-taking import is raw — even fopen(path, mode) and strlen(s), the spec's own §16.3c examples — so the §16.1 pitch ("modeled C functions just call") currently holds only for value-typed signatures. The overlay supplies contract evidence (NUL-termination, retention, nullability, buffer/length pairing, ownership) so high-traffic libc calls present modeled surfaces out of the box.

Spec

§16.3c Contract-Driven Coercion — Contract metadata sources (new in v7.0):

  • "The facts that make a binding modeled come from, in priority order: explicit annotations in the importing project, curated contract overlays shipped with the toolchain, and package-supplied binding metadata (with get c.*)."
  • "The toolchain maintains a curated libc overlay as a standard deliverable, so common calls such as fopen, strlen, and write present modeled surfaces out of the box; libraries without overlays import with raw surfaces until contracts are supplied."
  • "An overlay supplies evidence, never exemptions — it cannot weaken the rules below." (the str→*const c_char facts 1-3, byte-buffer ptr+len pairing, no hidden allocation, nullability as Option, etc.)
    §16.1: modeled bindings are ordinary With calls; unmodeled contracts stay raw/explicit.

Current state

  • ci_function_requires_raw_abi (src/SemaDecl.w:478-496) marks any import raw when the signature is variadic or any param/return type trips ci_type_requires_raw_contract (src/SemaDecl.w:461-476: TY_PTR/TY_REF/TY_SLICE/TY_FN/TY_EXTERN_FN, recursing through generic args). Raw bindings require unsafe to call (test err_c_import_raw_call_requires_unsafe.w).
  • The only modeled coercion today is bool→int (Sema.try_ci_coercion, src/SemaDiag.w:41-48); string-context "magic" was deliberately removed (req verdicts 16.3.4.28/.31/.43: no context reinterpretation, no strlen guessing).
  • There is no overlay format, no overlay lookup, and no per-parameter contract storage. Result: unsafe { strlen(s) } is required and strlen(s) with a With str is a type error (test err_c_import_str_to_c_char_requires_contract.w).
  • Evidence priority order has no implementation: explicit-annotation (CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Align @[effect] with §16.3d (declared effect contracts) #402) and package metadata (with get c.*) sources are also absent.

Implementation plan

Phase A — overlay format and plumbing:

  1. Define the overlay schema as binding metadata keyed by (header-ish domain, symbol name) with per-parameter and return facts, e.g.:
  2. Add overlay lookup in c_import binding generation: when ci_function_requires_raw_abi would classify raw, first consult the overlay; if every pointer-bearing param/return has facts, generate the modeled binding instead:
    • cstr_in param: accept With str; emit the §16.3c bridge — pass directly when provably NUL-terminated static storage (string literals), else build a call-scoped NUL-terminated temporary, freed after the call; interior-NUL handling per Bug: str→C-string conversion ignores interior NUL (§16.3c) #426 (proven NUL = compile error; dynamic NUL = loud runtime per binding error model).
    • buf_in pair: accept str/[]u8 and expand to (ptr, len) at the call.
    • nullable_ptr return: type as Option[*T] (machinery exists: behav_c_import_nullable_ptr_none.w).
    • Anything without facts: stay raw (unchanged classification).
  3. Wire the priority order: project-local explicit annotations (when CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Align @[effect] with §16.3d (declared effect contracts) #402 land) override overlay entries; overlay overrides package metadata. Structure lookup as a chain so sources can land incrementally.
    Phase B — curated libc content:
  4. Ship overlay entries for the high-traffic surface: stdio (fopen, fclose, fread, fwrite, fgets, printf-family stays raw/variadic), string (strlen, strcmp, strchr with borrowed returns), stdlib (getenv nullable+borrowed, malloc/free stay raw — ownership belongs to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357 wrappers), unistd (write, read, close). Each entry must cite the contract it asserts; entries are evidence, so wrong entries are bugs, not tuning.
  5. Include the overlay version in the c_import cache key (Zcu.c_import_cache_key_frontend, src/compiler/Frontend.w:352-374 — add a #overlay: fingerprint line) so editing the overlay invalidates cached bindings.

Test plan

  • test/spec/spec_ss16_3c_libc_overlay.w: use c_import("stdio.h", ...)/string.h; strlen("abc") == 3 callable without unsafe; fopen/fclose round-trip on a temp file without unsafe; write(fd, data) with a str under the modeled pair. //! expect-stdout: ok.
  • test/compile_errors/err_c_import_unoverlaid_stays_raw.w: inline-header import of a custom void f(char *p); (no overlay) — calling without unsafe → //! expect-error: (raw surface retained).
  • Interior NUL: proven interior NUL passed to a cstr_in param is a compile error (shared with Bug: str→C-string conversion ignores interior NUL (§16.3c) #426's tests).
  • Nullability: overlaid getenv("NOPE") returns Option; None observed.
  • Cache: changing overlay fingerprint invalidates (internals test around the cache key; allow-list analogue already exists per Frontend.w:361-364).
  • Negative guarantee: no overlay entry can make an unbounded ptr-only buffer modeled (schema-level test or review gate).

Acceptance criteria

  • Overlay format defined, documented, and embedded with the toolchain; lookup chain implements the §16.3c priority order.
  • fopen, strlen, write (documented contracts) callable without unsafe; semantics match §16.3c (no silent truncation, no hidden caller-owned allocation, nullability preserved).
  • Un-overlaid pointer functions remain raw — classification logic in SemaDecl.w unchanged for the no-evidence case.
  • Overlay participates in the c_import cache key.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Traceability

Spec reference: §16.3c Contract-Driven Coercion (Contract metadata sources — new in v7.0), §16.1.

Activity

  1. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    Resolved design direction (maintainer decision)

    The curated overlay replaces the blanket const char*-as-cstring rule shipped in commit 1e53f8a — it does not merely supplement it. Rationale:

    • The blanket rule (Sema.ci_type_is_const_c_string_input / ci_param_type_requires_raw_contract in src/SemaDecl.w:472-488) assumes every const char* param is a NUL-terminated string input. That is exactly the "strlen guessing" / "context reinterpretation" the §16.3c req verdicts (16.3.4.28/.31/.43) forbid. const char* is also used for non-terminated byte buffers, single chars, and opaque data, so the blanket rule is unsound in the general case — a silent FFI memory-safety hazard.
    • The spec is load-bearing in this repo (per AGENTS.md, a spec/compiler disagreement is a compiler bug). "An overlay supplies evidence, never exemptions" → modeling must be evidence-driven, one coherent model, not two overlapping mechanisms.

    Implementation outline (for a dedicated session)

    1. Remove the blanket const char* exemption (ci_type_is_const_c_string_input and its use in ci_param_type_requires_raw_contract). With it gone, a const char*-param extern reverts to raw/unsafe unless the overlay supplies a cstr_in fact.
    2. Add the overlay (Phase A): ordered, deterministic data table keyed by (domain, symbol) with per-param/return facts (cstr_in, buf_in(ptr,len), buf_out(ptr,cap), retains, consumes; returns nullable_ptr→Option, owned(destructor)→feeds CoreFoundation's reference-counted type family: model it as a D51 convention profile #357, borrowed). Lookup in ci_function_requires_raw_abi: modeled iff every pointer-bearing param/return has facts.
    3. Curated content (Phase B): stdio/string/stdlib/unistd. strlen (and the others exercised by behav_c_import_const_c_string_arg.w) move into the overlay so that test keeps passing through the evidenced path, not the blanket rule.
    4. Overlay version into the c_import cache key (Zcu.c_import_cache_key_frontend, src/compiler/Frontend.w).

    Note / caveat

    This is a behavior change: generic const char* externs not covered by the overlay revert to raw (require unsafe). Acceptable per the spec-faithful reading; flagged here so the change is intentional, not a surprise. The migration is mechanical (add the contract to the project or the overlay). Deferred to a dedicated session because an overlay subsystem with a behavior change is high-risk to land at the tail of a long run.

  2. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    FINAL decision: Option 1 (overlay replaces blanket rule), take the breaking change

    No external users → no migration, no deprecation cycle. The blanket const char*→cstring rule (commit 1e53f8a) is removed; const char* params become modeled only when the overlay supplies a cstr_in fact. This is the cheapest this change will ever be — every added test/dependent makes ripping out the blanket rule harder later.

    Paper trail for future-me reading the removal in git log: the blanket rule was unsound (const char* is also non-terminated buffers / single chars / opaque data) and was exactly the "strlen guessing" §16.3c forbids. It is replaced by evidence-driven overlay contracts, one coherent model.

    Day-one overlay coverage (REQUIRED — do not land the removal without this)

    The removal must ship with enough real libc coverage that it is a net correctness improvement, not just purity. If the first overlay entry is only strlen, the blanket rule has been rebuilt by hand for one symbol. Minimum tier-1 set, each citing the contract it asserts:

    cstr_in, value return (pure wins):
    strlen, strcmp, strncmp, strcasecmp, strncasecmp, atoi, atol, atof

    cstr_in, nullable borrowed ptr return → Option:
    strchr, strrchr, strstr, strpbrk, getenv

    buf_in(ptr,len) pairs:
    memcmp, memchr (nullable Option return), write

    behav_c_import_const_c_string_arg.w (strlen) must keep passing through the overlay, not the blanket rule — update the test's comment to say so; the assertions stay identical.

    Explicitly stays RAW day one (the blanket rule was wrong or unproven here)

    Not tonight

    Decision is made; implementation is a fresh-session job — overlay format + lookup + per-param contract storage + reverting the blanket rule + overlay cache-key fingerprint, with fixpoint kept green throughout. Threading a behavior change through sema is not tail-of-a-long-run work.

  3. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    Landed: cstr_in core + the breaking change (commit a88df01)

    Option 1 is implemented for the cstr_in fact:

    • Blanket rule removed. ci_param_type_requires_raw_contract (the unconditional const char* exemption from 1e53f8a) is gone.
    • Evidence-driven overlay. ci_overlay_cstr_in_param_count (src/SemaDecl.w) is the curated table; ci_function_requires_raw_abi models a pointer param only when the overlay vouches for it as cstr_in. try_ci_coercion (src/SemaDiag.w) gates the str→C-string coercion on the function being modeled (not in ci_raw_syms) — raw functions get no string magic.
    • Day-one content: strlen, strcmp, strncmp, strcasecmp, strncasecmp, strspn, strcspn, atoi, atol, atoll, atof.
    • Cache: already covered — the c_import cache key hashes the compiler binary (frontend_cimport_compiler_fingerprint_line), so overlay edits invalidate cached bindings. No separate fingerprint needed.
    • Tests: behav_c_import_const_c_string_arg (strlen via overlay), behav_c_import_overlay_strcmp, err_c_import_const_char_requires_overlay_evidence (non-curated const-char* now requires unsafe). Behavior 694 / compile-error 605 / spec 173, fixpoint holds.

    Behavior change is live: generic const char* externs not in the overlay now require unsafe.

    Remaining facts + an architectural finding

    While prototyping nullable_ptr I hit a design constraint worth recording:

    • nullable_ptr borrowed returns (strchr/strrchr/strstr/strpbrk/getenv). Making these modeled (safe to call) is only half of it — to be spec-correct the return must be typed Option[*T]. Pointer returns become Option[*T] only when clang sees a _Nullable annotation (that is why malloc from stdlib.h is Option but an unannotated inline char *strchr(...) is a plain *mut u8). So the overlay must rewrite the return to Option[*T] at binding generation (ci_emit flat-fn path, src/CImport.w:~1390), not merely exempt it from the raw check in sema. Shipping the exemption alone yields a plain nullable pointer — exactly the unsound shape Option 1 set out to remove.
    • Blocker: the overlay tables live in src/SemaDecl.w (which uses Sema); src/CImport.w does not use Sema and adding it risks a dependency cycle. The clean fix is a dependency-free CiOverlay module that both CImport.w (for return rewriting) and SemaDecl.w (for raw classification) use. That refactor is the right first step for the remaining facts.
    • buf_in(ptr,len) pairs (memcmp/memchr/write). Arity-changing: one With []u8/str arg expands to two C args at the call. Needs call-lowering work.
    • owned returns (fopen/strdup). Deferred to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357's owning-wrapper mechanism.

    Next session: extract CiOverlay, then add nullable_ptr (with Option[*T] return rewriting) and buf_in.

  4. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    nullable_ptr attempt: validated approach + one focused codegen blocker (reverted, diagnosed)

    Implemented the next fact (nullable_ptr borrowed returns) end-to-end and reverted it after isolating a single MIR-typing bug. Recording the full diagnosis so the next session starts de-risked.

    What worked (architecture is sound):

    • Extracted a dependency-free src/CiOverlay.w leaf module holding the overlay tables. Both SemaDecl.w (raw classification) and CImport.w (binding generation) use CiOverlay with no dependency cycle. Build + fixpoint green — the module auto-discovers (build globs src/) and bare cross-module calls resolve.
    • Added ci_overlay_return_is_borrowed_ptr (getenv/strchr/strrchr/strstr/strpbrk) and, in ci_translate_function (src/CImport.w), wrapped such returns: if borrowed_ptr and ret starts "*" and not already Option: ret = "Option[" ++ ret ++ "]". In ci_function_requires_raw_abi the return is exempted from raw when the overlay vouches a borrowed ptr.
    • Result: strchr/getenv compile and model correctly — callable without unsafe, typed Option[*T]. Sema is happy (it builds the None aggregate, proving it typed the result as Option).

    The blocker (codegen, not design):
    Calling a modeled c_import function whose return I wrapped as Option[*T] fails at codegen:

    error: aggregate rvalue missing destination struct type fn=main count=0 dest_sema=14 current_ret=void
    
    • src/CodegenDispatch.w:3303. dest_sema=14 is ty_void (14th base type). With WITH_DEBUG_MIR_CODEGEN=1: [mir-call] callee=getenv then [mir-agg] fn=main count=0 dest_ty_kind=0 — the None aggregate's destination type is void, i.e. the modeled call's Option[*T] return type is not propagated to the MIR call result.
    • Working contrast: malloc (_Nullable → Option[*mut c_void], test behav_c_import_nullable_ptr_none.w) works — but it is raw, called under unsafe. The modeled call path (which also applies the str→cstr arg coercion) is what drops the return type. This path was never exercised before because every previously-modeled c_import function had a scalar return.

    Fix direction for next session: make the modeled c_import call lowering (the coercion-applying path in MirLower/SemaCheck call handling) carry the callee's aggregate (Option[*T]) return type onto the MIR call result, the way the raw/_Nullable path does. Then re-apply the (small, known-good) CiOverlay extraction + ci_translate_function Option-wrap + the two tests (strchr Some/None/deref, getenv None). Repro is instant: ./out/release/bin/with build <test.w> (compile-time error, no full rebuild needed).

    Shipped state remains the cstr_in core (a88df01); this attempt is reverted.

  5. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    The nullable_ptr codegen blocker is now tracked as #603 (modeled c_import Option[*T] returns mistype the aggregate destination as void). #603 blocks the nullable_ptr fact here; cstr_in core (a88df01) is unaffected. Fixing #603 unblocks re-applying nullable_ptr.

  6. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    Landed: nullable_ptr borrowed returns (490f61b, c9c1d6b) — #603 closed

    strchr, strrchr, strstr, strpbrk, getenv are now modeled (callable without unsafe), via ci_overlay_return_is_borrowed_ptr in src/SemaDecl.w.

    Corrected design note (supersedes the earlier "rewrite the return to Option[*T] at binding-gen" plan): raw C pointers are natively nullable in With — == None and .unwrap() work directly on a plain *T (malloc returns a plain *mut c_void and is used exactly this way). So a borrowed nullable-pointer return is left a plain raw pointer; the overlay fact only makes the call safe, and dereferencing the borrowed pointer stays unsafe. No Option binding-text wrap, no CImport change, no codegen change, no CiOverlay module / dependency-cycle concern. The earlier blocker (#603) was an artifact of the wrong wrap and is closed.

    Tests: behav_c_import_overlay_strchr_borrowed, behav_c_import_overlay_getenv_none, err_c_import_uncurated_ptr_return_raw. Behavior 696, compile-error 606, fixpoint holds.

    Overlay coverage now

    • cstr_in (value return): strlen, strcmp, strncmp, strcasecmp, strncasecmp, strspn, strcspn, atoi, atol, atoll, atof.
    • cstr_in + borrowed nullable-ptr return: strchr, strrchr, strstr, strpbrk, getenv.

    Remaining facts

  7. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    buf_in: design-heavy, deferred with rationale

    buf_in (collapse a (ptr, len) C pair into one With []u8) needs new wrapper-generation infrastructure: emit the raw C function under a mangled extern name plus a safe With wrapper (fn f(buf: []u8) ...: unsafe { __raw_f(buf.ptr, buf.len) }). The wrapper is sound — the slice's length invariant makes the (ptr, len) call safe — and it is CImport-only (no cross-module/codegen concerns). The hard part is not the mechanism; it is that every clean libc target carries a semantic decision:

    • write / read — the spec's headline buf_in examples — are unavailable: c_import write collides with the With prelude and is omitted (see spec_ss16_ffi_and_c_import.w::test_c_import_system_prelude_collision_is_omitted). read is buf_out (writes into the buffer), a mutable-slice variant — a different fact.
    • memcmp(const void*, const void*, size_t) — two buffers share one length. n semantics are a real choice (require a.len == b.len? compare min? compare common prefix?) — the spec does not specify, so picking one is a design decision, not a mechanical translation.
    • memchr(const void*, int, size_t) — buf_in and a borrowed nullable-pointer return at once; the cleanest target but it composes two facts.

    So buf_in is not a "one more overlay line" addition like cstr_in/nullable_ptr; it is a wrapper-gen feature whose every entry needs a contract decision (in vs out direction, two-buffer length relationship). It warrants a deliberate design pass (and a buf_out companion fact), not tail-end grinding.

    #379 status: substantially delivered

    The two clean, high-traffic modeling facts are shipped and the unsound blanket rule is gone:

    • cstr_in (value returns): strlen, strcmp, strncmp, strcasecmp/strncasecmp, strspn, strcspn, atoi/atol/atoll/atof.
    • nullable_ptr (borrowed returns): strchr, strrchr, strstr, strpbrk, getenv.

    Remaining facts are tracked here but are each their own design effort:

    Leaving #379 open for buf_in/owned, but the core overlay (evidence model + the high-traffic surface) is in.

  8. ehartford commented on Jun 18, 2026

    @ehartford
    ContributorAuthor

    Landed: buf_in + @[link_name] (commits dba8b5e2, c1bd993)

    • @[link_name("symbol")] extern-fn attribute added (the primitive the wrapper needs to rename a raw binding while keeping C linkage).
    • buf_in fact: memchr, memcmp are modeled — a (ptr, len) C pair collapses into one With []u8. ci_emit_buf_wrapper (src/CImport.w) generates a renamed raw extern (@[link_name], hidden) plus a safe slice-taking fn wrapper; the slice length invariant makes the call memory-safe. memcmp requires equal lengths (panics) per the agreed contract. ci_function_requires_raw_abi exempts any c_import fn with a slice param (C has no slices → it's a generated safe wrapper).
    • Tests: behav_c_import_overlay_memchr, behav_c_import_overlay_memcmp. Behavior 701, fixpoint holds.

    Overlay coverage now

    • cstr_in (value returns): strlen, strcmp, strncmp, strcasecmp/strncasecmp, strspn, strcspn, atoi/atol/atoll/atof
    • nullable_ptr (borrowed returns): strchr, strrchr, strstr, strpbrk, getenv
    • buf_in (byte buffers): memchr, memcmp

    buf_out scoped to #604 (prerequisite — NOT deferred)

    buf_out (memset/explicit_bzero) writes into the buffer, so it needs a []mut u8 argument. With currently cannot construct one (slice exprs yield []T; split_at_mut yields VecRange; bare collections don't coerce) — shipping a buf_out wrapper now would be uncallable and would regress the raw memset surface. The wrapper generator already handles the mutable case (is_mut → []mut u8 + &raw mut); only the []mut T argument coercion (a missing, spec-promised coercion) and the overlay entries remain. Tracked with full root-cause analysis + design + size estimate in #604, which blocks buf_out here.

    Remaining for #379

  9. ehartford commented on Jun 19, 2026

    @ehartford
    ContributorAuthor

    Closing: curated libc overlay shipped (cstr_in + nullable_ptr + buf_in)

    The overlay subsystem and its expressible high-traffic surface are delivered, and the unsound blanket rule is gone:

    • Breaking change: removed the blanket const char*→cstring assumption (1e53f8a); modeling is now evidence-driven via the curated overlay.
    • cstr_in (value returns): strlen, strcmp, strncmp, strcasecmp/strncasecmp, strspn, strcspn, atoi/atol/atoll/atof.
    • nullable_ptr (borrowed returns, natively-nullable raw pointers): strchr, strrchr, strstr, strpbrk, getenv.
    • buf_in (byte buffers → []u8): memchr, memcmp. Via generated safe wrappers over @[link_name]'d raw externs (new attribute, also generally useful).
    • Cache invalidation handled by the compiler-image hash already in the c_import cache key.

    Downstream (tracked separately, NOT part of this overlay issue):

    Closing #379 on the shipped overlay; the two remaining facts live with their actual prerequisites (#604, #357).

  10. added 2 commits that reference this issue on Jun 19, 2026
  11. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    buf_out is now shipped: #604 stage 1 landed parameter-position []mut T with call-site coercion (4188d5e7), unblocking the mutable-buffer contract, and 8274956e curates memset/explicit_bzero as []mut u8 — callable with a plain array/Vec argument, no unsafe in user code, slice length bounding the C write. (explicit_bzero's entry is inert on Darwin, active where libc declares it.) That completes the buf_in/buf_out pair from this issue's fact list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions