Skip to content

Out-of-range enum discriminants accepted for non-i8/i16 reprs: silent truncation + segfault / silent no-match #1003

Closed

Description

@eas4ai

Summary

The discriminant range check in Sema covers only i8 and i16 reprs. Any other repr (u8, u32, …) accepts arbitrary values at check time, and the program then misbehaves deterministically at runtime — two shapes observed:

  • u8 with B = 300: value truncates to 44, and match on it SEGFAULTS (rc=139).
  • u32 with B = -1: program exits 0 printing nothing — neither match arm fires despite both variants being covered (silent no-match, no exhaustiveness complaint).

Repro (seed stage1 at 450733e; check probes .audit/probes/semadecl/disc_u8_range.w, disc_u32_neg.w; runtime probes disc_rt.w, disc_rt2.w)

enum U8Big: u8:
    A = 1
    B = 300          // check: ok rc=0 (expected range error)
fn main:
    print_i32(U8Big.B as i32)   // prints 44 — truncated
    match U8Big.B:              // SIGSEGV rc=139, deterministic x3
        U8Big.A => print_i32(10)
        U8Big.B => print_i32(20)

Re-run by primary: disc_u8_range/disc_u32_neg check rc=0; disc_range (i8/200) correctly rc=1; dup_disc correctly rc=1 — so the check exists but is repr-gated. disc_rt prints 44 then segfaults (3/3 runs); disc_rt2 (u32/-1) exits 0 with no output.

Root-cause chain (verified by reading + execution)

  1. src/SemaDecl.w:788-794: range validation only for ty_i8 (-128..127) and ty_i16; every other repr (unsigned, wider, bool-sized?) skips validation entirely while duplicate detection (:785-787) still runs — the check is half-built, not absent.
  2. The raw value flows into the enum type record (:795) and is consumed downstream (MirLower.w:8164 area) as a narrowed machine value: 300 becomes 44 in a u8 slot.
  3. The match lowering evidently assumes discriminant validity: matching a value the compiler itself truncated traps (u8 case); the u32 wrap produces a value no arm compares equal to, and exhaustiveness (computed from declared variants, all present) stays silent — a missing-arm fallthrough with no diagnostic.

Severity

High: check-clean programs segfaulting deterministically is the worst Sema gap class — the frontend's job is exactly to reject this. The u32 silent no-match is the same root cause wearing a quieter mask.

Suggested fix (owner's call)

Range-check against the actual repr type (signed/unsigned, all widths) at SemaDecl.w:788-794; reject before the value enters the type record. The duplicate check beside it shows the intended location.

Audit provenance

Read-only end-to-end audit, SemaDecl leg (child complete examination, independently verified by primary: branch inspection + check/build/run re-runs + two new runtime probes). Related: #990 (emit-C ignores repr width — adjacent repr-handling gap, distinct layer).

Activity

  1. ehartford commented on Sep 16, 2026

    @ehartford
    Contributor

    Review: reproduced, with the crash mechanism identified

    Verdict. Established on current main. The discriminant range check exists only for i8 and i16; u8 { B = 300 } and u32 { B = -1 } pass with check. At runtime the u8 program prints cast=44 (300 truncated) and then segfaults in the match; the u32 program's match U32Neg.B selects the A arm on this host (the reporter saw no arm at all), which is wrong either way. The i8 control is correctly rejected with discriminant value 200 out of range for i8. The segfault is not a match-lowering trap as such: MIR shows the out-of-range arm compiled as a comparison that can never be true, so the match falls through to its join block with an uninitialised result temporary (the same fall-through #994 documents), and printing that garbage str crashes inside rt_memcpy.

    Tested revision and compiler

    item value
    source main @ 5809ac1 (2026-09-14); the range check at SemaDecl.w:943-949 is unchanged since 450733e
    compiler with build of 5809ac1 in a detached worktree, self-reports with v0.15.2.1
    platform macOS Darwin 25.6.0, arm64

    Probe matrix

    program with check with run
    enum U8Big: u8 { A = 1, B = 300 }; print B as i32; match U8Big.B with both arms ok cast=44 then SIGSEGV, rc 139
    enum U32Neg: u32 { A = 1, B = -1 }; match U32Neg.B with both arms ok match=A (wrong arm), rc 0
    control: enum I8Big: i8 { A = 1, B = 200 } error: discriminant value 200 out of range for i8 n/a
    enum I32Big: i32 { A = 1, B = 3000000000 }; print B as i64 ok 1 (the #990 index fallback; also unchecked)

    Root cause

    • Sema: src/SemaDecl.w:943-949: after the duplicate check, "Check discriminant fits in repr type range" tests only repr_type_tid == self.ty_i8 and == self.ty_i16. u8, u16, u32, u64, i32, i64 are never range-checked, and negative values are never rejected for unsigned reprs.
    • Downstream, --dump-mir of the u8 program's main:
    _3 = cast(const 300ty135 as ty3);          // the "as i32" cast: 300 truncated in the u8 slot -> 44
    ...
    switchInt(copy _13) -> [1: bb8, otherwise: bb9];    // arm A: compare == 1
    switchInt(copy _14) -> [300: bb10, otherwise: bb7]; // arm B: switch on a bool with case 300, never taken
    

    The B arm's test is emitted with the raw declared value 300 as the case constant on a comparison result, so it cannot match; control falls to the join (bb7) where the result str was never assigned. lldb at the crash: EXC_BAD_ACCESS in rt_memcpy called from fb_append from main, i.e. the f-string formatter copying from the uninitialised str. The u32 MIR has the same shape with case -1.

    Spec

    §13.3 (spec line 2172): the representation type "determines the underlying storage"; spec line 1205 gives the general rule for literals, "a suffixed literal must fit in its declared type". A discriminant that does not fit its repr is the same category of error and is already rejected for two of the eight repr types, so the intended rule is evident from the code itself; a maintainer-authored sentence in §13.3 would make it normative.

    Related PRs

    None since 450733e touch the range check. Neighbours in this queue: #990 (discriminants stored as i32, index fallback) and #994 (non-exhaustive match fall-through reads uninitialised memory), both of which this program also exercises.

    Would I champion a fix? Yes; it is the existing check extended to every repr.

    Acceptance criteria:

    1. SemaDecl.w range-checks every repr type against its signed/unsigned bounds (u8 0..255, u16, u32, u64, i32, i64), rejecting negatives for unsigned reprs, with the existing diagnostic wording; the u8/u32 probes fail with check.
    2. The discriminant value carrier is widened to i64 (shared with emit-c maps every fieldless enum to int32_t regardless of repr type #990's criterion) so u32/i64/u64 bounds can be checked at all.
    3. test/compile_errors fixtures for one unsigned overflow, one negative-on-unsigned, and one wide-signed overflow; the i8 control stays.
    4. Independently, Non-exhaustive expression-position match on integers silently yields zero value #994's fix (an unreachable after an exhausted arm chain) turns this class of latent miscompile into a loud failure should any value ever escape the check again.

    Untested

    u64 values above i64 max cannot be spelled until the carrier is widened; not probed. Linux and Windows not executed.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions