Skip to content

Modeled C: no facade form for a polled tagged message (Steam ManualDispatch, SDL_PollEvent): the payload read stays unsafe #2425

Done

Description

@ehartford

Summary

The facade spec (§16.2b) has no clause for a polled tagged message: a C API that hands the program a record whose integer tag says which struct a payload pointer points to, and whose size field bounds it. Steam's manual callback dispatch is the case at hand. Without a clause, a downstream program has to read the payload with unsafe casts and dereferences even when everything else about the library is modeled.

§16.2b.9 Callbacks covers C calling into a With function (callback-scope handles, borrowed arguments, userdata). It does not cover the reverse shape, where the program pulls messages and C never calls it. A search of docs/spec/016_ffi.md for tagged, discriminated or payload forms finds only the variadic discriminant rule (§16.2b, "Discriminated variadic contracts"), which is about arguments, not received records.

The case: Steamworks manual dispatch (WIPE, src/steam.w)

use c_import("steam/steam_api_flat.h", lang: "c++", link: "steam_api", no_methods: true)

SteamAPI_ManualDispatch_RunFrame(self.pipe)
unsafe:
    var msg = CallbackMsg_t {}
    while SteamAPI_ManualDispatch_GetNextCallback(self.pipe, &raw mut msg):
        if msg.m_iCallback == GameOverlayActivated_t_k_iCallback and msg.m_pubParam != null and msg.m_cubParam >= OVERLAY_BYTES:
            let event = msg.m_pubParam as *const GameOverlayActivated_t
            let active = (*event).m_bActive != 0
            ...
        else if msg.m_iCallback == UserStatsStored_t_k_iCallback and msg.m_pubParam != null and msg.m_cubParam >= STORED_BYTES:
            let event = msg.m_pubParam as *const UserStatsStored_t
            ...
        else if msg.m_iCallback == SteamShutdown_t_k_iCallback:
            ...
        SteamAPI_ManualDispatch_FreeLastCallback(self.pipe)

The facts the program knows and the compiler can't see:

  • CallbackMsg_t.m_iCallback is a tag. Each callback struct carries its own tag as a constant (GameOverlayActivated_t_k_iCallback, …), and the tag selects the payload type.
  • m_pubParam points to a payload of that type, and m_cubParam is its size in bytes. The program checks the size before reading.
  • The payload is borrowed from the dispatch. It is valid from GetNextCallback until FreeLastCallback, and it must not outlive that call.
  • FreeLastCallback must follow every successful GetNextCallback, before the next one.

Every other unsafe site in WIPE's Steam binding (init and status, the interface pointers, string and buffer parameters, borrowed origin text) maps onto existing clauses: resource … from … ok … drop, of … lend, buffer param … len …, out param, and returns borrow CStr from. A Steam facade can model all of those today. The callback pump is the only part that has to stay unsafe.

The same shape elsewhere

This isn't specific to Steam. Any pull-model event API with a tagged payload has it: SDL_PollEvent filling an SDL_Event union discriminated by type, Win32 MSG with message/wParam/lParam, X11 XEvent with type, and libinput_get_event with libinput_event_get_type.

What a clause would need to state

This list is the facts, not a syntax proposal:

  1. The tag: which field (or call) gives the discriminant.
  2. The cases: for each tag value (a constant from the import), the payload type and where the payload lives (a pointer field, or the union member).
  3. The bound: which field gives the payload size, and that a case is rejected, not read, when the size is short.
  4. The lifetime: the payload is borrowed from the producing call (GetNextCallback) until the release call (FreeLastCallback), with the release required before the next produce.
  5. Unknown tags: they surface as an "other" case carrying the tag and do nothing else.

With those facts, the program could match on a modeled message and get each case's payload as a borrowed, typed view, with no unsafe, no casts, and the size check and release enforced by the facade.

Acceptance

  • A facade over the Steam manual-dispatch surface lets the pump above be written without unsafe: match on the message, read GameOverlayActivated_t and UserStatsStored_t as borrowed views, release enforced.
  • A short payload (m_cubParam less than the case's size) never reaches a case arm.
  • A payload view used after the release call is a compile error.
  • An unknown tag is a case the program can match, not undefined behavior.

Found while modeling Steamworks for WIPE (withlang-dev/wipe), which builds with the live compiler.

Activity

  1. ehartford commented on Oct 16, 2026

    @ehartford
    ContributorAuthor

    The evidence for this clause ships with the library

    The Steamworks SDK includes sdk/public/steam/steam_api.json, a machine-readable description of the whole flat API (SDK 1.65 counted):

    • callback_structs: 196 entries, each with its callback_id. For example {"callback_id": 101, "struct": "SteamServersConnected_t", "fields": []}. That is the tag-to-payload table this issue asks a facade to state, for every callback the SDK defines. A facade built from it would not need anyone to write the cases by hand.
    • interfaces: 34, with 921 flat methods. Each method has its methodname_flat and parameter annotations: array_count 26, out_string_count 16, out_array_count 14, out_struct 6, plus out_array_call, out_string, out_buffer_count and buffer_count. Each interface has its accessors (for example SteamAPI_SteamInput_v007) and version_string.
    • 81 methods marked callresult. These are async calls whose result comes back through the same manual dispatch as a tagged message (SteamAPI_ManualDispatch_GetAPICallResult), so they're this same shape a second time.

    For example, GetConnectedControllers is described as {"paramname": "handlesOut", "paramtype": "InputHandle_t *", "out_array_count": "STEAM_INPUT_MAX_COUNT"}, which is exactly a buffer param … len … fact.

    Relation to D121 step 3 (#2424, "annotations the library ships"): that step reads __attribute__((…)) tokens through the Clang bridge. Steam's annotations are a JSON sidecar beside the headers, not attributes, so that reader doesn't see them. A sidecar reader would be a second source for the same evidence tier.

    What the JSON does not say, and a registry facts file would have to: SteamAPI_InitFlat and SteamAPI_Shutdown as a resource with its status (k_ESteamAPIInitResult_OK), how long returned text such as GetStringForActionOrigin's stays valid, and the dispatch lifetime this issue describes (payload valid from GetNextCallback until FreeLastCallback).

    This is the evidence behind the game-toolkit plan's with add steam step (docs/plans/game-toolkit.md §3.2.1), which builds the Steam facade from the developer's SDK, so nobody writes one per project.

  2. self-assigned this
    on Oct 16, 2026
  3. ehartford commented on Oct 16, 2026

    @ehartford
    ContributorAuthor

    Decision Brief (D98 — Normative Spec Addition to §16.2b)

    1. Question

    How should a c facade block (§16.2b) declare a polled tagged message (such as Steamworks CallbackMsg_t from SteamAPI_ManualDispatch_GetNextCallback / SteamAPI_ManualDispatch_FreeLastCallback, or SDL_PollEvent over SDL_Event) so that tag dispatch, payload size validation, payload borrow lifetime, release-before-next-poll, and unknown-tag handling are all enforced without unsafe?

    2. Recommendation & Why

    Add a message <Name> wraps <CRecord> item to §16.2b.9 (or §16.2b.9a Polled tagged messages):

    c facade "steam/steam_api_flat.h":
        message CallbackMsg wraps CallbackMsg_t
            from SteamAPI_ManualDispatch_GetNextCallback
            of Pipe
            out param 2
            ok return == true
            release SteamAPI_ManualDispatch_FreeLastCallback
            tag m_iCallback
            payload m_pubParam size m_cubParam
            case GameOverlayActivated when GameOverlayActivated_t_k_iCallback: GameOverlayActivated_t
            case UserStatsStored when UserStatsStored_t_k_iCallback: UserStatsStored_t
            case SteamShutdown when SteamShutdown_t_k_iCallback
    

    And for inline tagged unions (SDL_PollEvent):

    c facade "SDL3/SDL.h":
        message Event wraps SDL_Event
            from SDL_PollEvent
            out param 1
            ok return == true
            tag type
            case Quit when SDL_EVENT_QUIT
            case KeyDown when SDL_EVENT_KEY_DOWN field key
    

    Semantics:

    1. Producer & Release (from … release …):
      • The polling function (pipe.get_next_callback() -> Option[CallbackMsg]) allocates CallbackMsg_t on the stack, calls SteamAPI_ManualDispatch_GetNextCallback(pipe, &mut raw_msg), and returns Some(msg) when ok holds or None otherwise.
      • When release <fn> is stated, CallbackMsg is a linear/ephemeral scoped guard bound to the receiver (pipe): its Drop calls SteamAPI_ManualDispatch_FreeLastCallback(pipe) automatically at the end of the while let Some(msg) = pipe.get_next_callback(): iteration (including on continue, break, ?, or return), and the receiver (pipe) is borrowed for msg's scope so a second get_next_callback() cannot run before msg is released.
    2. Tag, Size Bound & Cases (tag …, payload … size …, case …):
      • The facade synthesizes an enum view for match msg.kind(): (or direct match msg: projection):
        • Variant(&PayloadType) when a payload type or union field is declared;
        • unit Variant when no payload is declared;
        • Other(TagType) for any unrecognized tag value.
      • When payload <ptr_field> size <len_field> is stated, a Variant(&PayloadType) arm is entered only when raw.ptr_field != null and raw.len_field >= sizeof[PayloadType](); a short or null payload never reaches the typed arm and instead yields Other(raw.tag).
    3. Lifetime:
      • Every &PayloadType view projected from msg carries msg as its borrow origin. Using the payload view after msg drops (i.e. after FreeLastCallback) is a compile-time borrow error.

    Why:

    3. Alternatives & Why Not

    • Alternative A: Explicit pipe.free_last_callback() call required in user code, tracked by a typestate/linear check.
      • Why not: Requires the user to write ceremony at the end of every loop body and before every continue/return. Binding FreeLastCallback to the polled message guard's scope (Drop) is strictly safer and more ergonomic.
    • Alternative B: Only support pointer+size envelopes (m_pubParam / m_cubParam), leaving C union events (SDL_Event) to a separate construct.
      • Why not: SDL_PollEvent has the exact same producer + tag + borrowed-case-payload shape; supporting field <union_member> alongside payload <ptr> size <len> handles Steam, SDL, X11, and Win32 with one facade item.

    4. Proposed Normative Diff (docs/spec/016_ffi.md)

    @@ -1060,6 +1060,49 @@
    +#### 16.2b.9a Polled tagged messages
    +
    +A foreign pull-loop record whose discriminant field selects which payload
    +type a pointer field or union member holds is modeled as a `message`:
    +
    +```
    +message CallbackMsg wraps CallbackMsg_t
    +    from SteamAPI_ManualDispatch_GetNextCallback
    +    of Pipe
    +    out param 2
    +    ok return == true
    +    release SteamAPI_ManualDispatch_FreeLastCallback
    +    tag m_iCallback
    +    payload m_pubParam size m_cubParam
    +    case GameOverlayActivated when GameOverlayActivated_t_k_iCallback: GameOverlayActivated_t
    +    case UserStatsStored when UserStatsStored_t_k_iCallback: UserStatsStored_t
    +    case SteamShutdown when SteamShutdown_t_k_iCallback
    +```
    +
    +`from` and `ok` present the polling call as returning `Option[Message]`.
    +When `release` is stated, the `Message` value is an ephemeral guard whose
    +destruction invokes the release function and holds an exclusive borrow of
    +the producing resource for its scope, so the release runs on every exit path
    +and before the next poll.
    +
    +Each `case` maps a tag constant from the import to a variant of the message's
    +synthesized sum view: a borrowed `&Payload` (from `payload <ptr> size <len>`
    +or `field <union_member>`), or a payload-less variant when no type or field is
    +named. An unrecognized tag produces `Other(tag)`. When `payload <ptr> size
    +<len>` is stated, the wrapper verifies `ptr != null` and `len >=
    +sizeof[Payload]()` before projecting `&Payload`; a short buffer never reaches
    +the case arm. The projected `&Payload` carries the `Message` guard as its
    +origin and cannot outlive the release call.
  4. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): unchanged, and the next step is Eric's ruling (C interop, §16.2b). §16.2b has no clause for a polled tagged message; the decision brief above (D98 form) awaits a ruling.

  5. added this to the post-v0.16.0 milestone on Oct 28, 2026
  6. ehartford commented on Nov 18, 2026

    @ehartford
    ContributorAuthor

    Ruled, 2026-11-18 (D216): a message item, with tag, case Name when CONST [field f | : Type] (a range may state a family), payload P size N (non-null, large enough and aligned, else Other), and release f as a guard that borrows the producer exclusively. The generated sum is ephemeral and open: a match on it must have a wildcard arm, and an .Other(tag) arm that compares the tag with a constant that has a named case is warned. A bool return means produced. Pointer fields inside a payload stay raw for now. Each case is cited; thread affinity of the poll is stated if contracts can, or recorded as a gap.

  7. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    Started on D216 (2026-11-25). Nothing is merged yet: per the ruling the spec words come to Eric as one diff with the implementation, so the work stays on a local branch (d216-message) until it is whole.

    What exists today. Nothing of the item: message in the grammar is only the resource clause that names an error-text operation. A contract that writes message Event wraps SDL_Event gets "expected 'resource', 'handle', 'fn', 'domain', …".

    Checked first, because the design rests on it: a sum whose cases hold views can be an ephemeral type today. This compiles and runs with the installed compiler (main):

    enum Event ephemeral:
        Key(&K)
        Motion(&M)
        Other(u32)
    

    So the generated type is ordinary rendered source, as a resource's is.

    The pieces, in the order I am taking them

    1. Parser: the item and its lines (from f(out param N), tag F, case Name when CONST [field f | : Type], a range when A..B, payload P size N, release f), as a new facade item node.
    2. Verifier (SemaFacade): the record and its tag field exist and the tag is an integer; each when constant is a constant of the import; a field is a member of the record (a union member for the SDL shape); a : Type is a record of the import; no tag is claimed by two cases; the producer's out parameter is a pointer to the record and its return is bool.
    3. Renderer: the ephemeral sum with Other(tag), and the poll operation. For the pointer form, the non-null, size and alignment tests before a typed case; with release, the guard that borrows the producing resource exclusively.
    4. Sema: a match on the generated sum needs a wildcard arm (the sum is open), and the warning for an .Other(tag) arm that compares with a constant that has a named case. There is no open-sum notion in the compiler today, so this is new.
    5. Fixtures over an inline header for both shapes, compile-error tests for each refusal, the SDL and Steam contracts with every case cited from the pinned packages, and the spec diff.

    Recorded gap, as the ruling asks: whether a contract can state "main thread only" for the poll. I have not looked yet.

  8. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    Progress (2026-11-25), still local on d216-message:

    Slices 1 and 2 are done. The item parses (both shapes, the range form, and C field names that are With keywords such as SDL's type), and it is verified against the import: the record and an integer tag, a producer that fills a writable pointer to the record and returns bool, each case's constant, ranges, no tag value under two cases, field f a member of the record, : T only with a payload, the payload's pointer and size fields, release only with a payload, Other reserved. Fifteen wrong contracts each get one error naming the line; they become the compile-error tests.

    The shape of the loop. The ruling fixes the contract's lines, not what the program writes. The shape I am building, to come to Eric in the diff:

    for ev in events():
        match ev:
            .Key(k) => …
            .Motion(m) => …
            _ => {}
    

    The record lives in the generator; each iteration yields the ephemeral sum; with release f the generator calls it when the body returns, so "free before the next poll" is not the program's to remember. A hand-written version of what the renderer will emit runs today (three events, no leak under the debug allocator), so nothing new is needed below the facade for it.

    Something the ruling's context should know. D216 says "reading a union member is unsafe, so every event loop was written under unsafe". That is not what the compiler does for an imported union: SemaCheck (the §16.4 check) exempts a C union on purpose ("a C union reads any arm: punning is what the C code it mirrors does"), and a program that writes raw.key.key = 5 and reads raw.motion.x compiles and prints 5 with no unsafe. So for SDL's shape the only unsafe in a hand-written loop today is the poll call itself; the pointer form (Steam) does need it, for the cast and the dereference. The item is still what makes the tag-to-member pairing stated once, and I am not reopening the ruling; this is for the spec words, which should not claim the read is unsafe.

  9. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    D216 is built and waits only on the spec words. Branch d216-message (local, seven commits on main, not pushed, as the ruling asks for one diff with the words).

    What is built

    • The item parses and is verified against the import (22 refusals, each one error naming the line).
    • Both shapes are presented: a C union (field f) and a payload pointer (: T, payload P size N, release f). A typed case in the pointer form is entered only when the pointer is non-null, large enough and aligned; otherwise it is Other(tag).
    • The program writes for m in Name.poll(…): match m with no unsafe. The producer's other parameters are the poll's; release runs after each body, an early break included (test: 4 releases of 4).
    • The sum is open: a match without _ is an error, and an .Other(tag) arm that compares with a constant a case names is warned.
    • A message or a view from it cannot leave the loop body. Building that exposed a hole in generators, fixed on main in An ephemeral value a generator yields from its own frame cannot leave the loop body #3608.

    Evidence

    • Local, at c42831e0a: both compilers check the source; release build; :unit-return-review, :ceremony-census, :self-audit, :native-compile-error-tests, :behavior-tests green; battery green. Tests: behav_d216_message_union, behav_d216_message_pointer, 22 err_d216_*.
    • Against the real SDL 3.4.16 (with get c.sdl, the pinned package): a project contract over SDL_Event / SDL_PollEvent, each case cited from SDL3/SDL_events.h, verifies; a program that queues a key press and a quit request receives .KeyDown (scancode A) and .Quit through Event.poll().
    • Steam is not tried: the Steamworks SDK is not a with get package and I have no pinned copy to cite from. The pointer form is tested against a header of the same shape.

    The words to bless

    Proposed as a new subsection after §16.2b.9. Exact text:

    16.2b.9a Polled messages

    Some libraries hand the program a record it must ask for: the program
    calls a function that fills the record, and an integer field of the record
    says which of its parts is meaningful. A message item states that pairing
    once.

    message Event wraps SDL_Event
        from SDL_PollEvent(out param 0)
        tag type
        case KeyDown when SDL_EVENT_KEY_DOWN field key
        case Window when SDL_EVENT_WINDOW_FIRST..SDL_EVENT_WINDOW_LAST field window
    
    message Callback wraps CallbackMsg_t
        from SteamAPI_ManualDispatch_GetNextCallback(out param 1)
        tag m_iCallback
        case OverlayActivated when GameOverlayActivated_t_k_iCallback : GameOverlayActivated_t
        payload m_pubParam size m_cubParam
        release SteamAPI_ManualDispatch_FreeLastCallback
    
    • from f(out param N) names the function that fills the record and the
      parameter it fills, a writable pointer to the record. f returns bool:
      true means it produced a message.
    • tag F names the integer field that selects the case.
    • case Name when CONST names a case and the tag value that selects it;
      when A..B names every value from A to B. No tag value belongs to
      two cases. A case carries nothing, a member of the record (field f), or
      the record a payload pointer points to (: T).
    • payload P size N names the pointer field and the field holding the
      payload's size in bytes. A message that states it carries its cases as
      : T.
    • release f names the function that ends the payload's life. It takes
      what from's function was given, the record aside.

    A field is named as C names it, also when the name is a With keyword.

    What the item presents. A sum Name with the stated cases and one
    more, Other(tag), for a tag value no case names; and Name.poll(…),
    whose parameters are those of the from function without the record. The
    program iterates it:

    for event in Event.poll():
        match event:
            .KeyDown(key) => …
            _ => {}
    

    Each iteration polls once and stops when the function returns false. The
    record belongs to the iteration, and a case's value is a view of it: the sum
    is an ephemeral type (§5.5), and neither it nor a view taken from it
    outlives the loop body. With release, the release runs when the body
    ends, however it ends, before the next poll.

    A case stated : T is entered only when the pointer is not null, the size
    is at least the size of T, and the pointer is aligned for T. Otherwise
    the value is Other(tag).

    The sum is open. A match on a message's sum must have a _ arm.
    Other(tag) covers a tag the library adds later; it does not cover a case a
    later contract names, and a match that listed every case would stop
    compiling when one is added. An .Other(tag) arm that compares the tag
    with a constant some case names is warned: the tag is never that value
    there.

    Verification (§16.2b.13). The record, the tag and every named field
    exist; the tag is an integer; each when constant is an integer constant of
    the import; the from function's parameter is a writable pointer to the
    record and its return is bool; a : T type is a record of the import;
    release has the parameters stated above. A line that does not hold is an
    error.

    Pointer fields inside a case's value are raw pointers (§16.1).

    Four things to know before blessing

    1. D216's context says "reading a union member is unsafe". For an
      imported C union it is not (the checker exempts C unions on purpose).
      The draft therefore does not say the item removes an unsafe read for
      the union shape; what it removes is the unsafe poll call and, for the
      pointer form, the cast and dereference.
    2. The loop shape (for m in Name.poll(…)) is my choice; the ruling fixed
      the contract's lines only.
    3. release f "borrows the producing resource exclusively" in the ruling.
      As built, the release runs at the end of each body (also on break), so
      "free before the next poll" cannot be got wrong; but when the producer's
      other parameter is a plain handle value (Steam's HSteamPipe is an
      integer), there is no resource to borrow, and nothing stops a second
      poll loop nested inside the first. If the parameter is a facade
      resource, the poll should take it mut: not built yet.
    4. Thread affinity (SDL: events are pumped on the thread that initialized
      video): §16.2b.10 has no clause that says "this thread only", so the
      poll is presented without it. Recorded as a gap, as the ruling asks.

    Labelling human attn needed: the words are yours. On a yes I apply them with the version and changelog, push, and open the PR.

  10. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    Ruled by Eric, 2026-11-25 (answers to briefs.md).

    The words were not answered: the copy of the brief that was read still had a placeholder where the text goes. The full text is in briefs.md now and in the comment above on this issue.

    One answer was given, on note 3: build the mut borrow for a facade-resource parameter before landing, as the ruling asks. A producer with no resource to borrow is recorded as a gap. It matters only for the pointer form with release. That part is mine now; the label stays for the words.

  11. ehartford commented on Nov 25, 2026

    @ehartford
    ContributorAuthor

    Ruled by Eric, 2026-11-25 (second answer of the day): yes to the words, with five edits; the loop shape stands.

    1. when A..B: say "A and B included".
    2. Verification gains the rules the text relies on: no tag value belongs to two cases, and A ≤ B in a range; payload's field is a pointer and size's field is an integer; a : T case needs a payload line, and a release line needs one too; a message does not mix field and : T cases.
    3. release: say what its return is, or that it is ignored.
    4. Other(tag): the tag has the type of the tag field.
    5. The two gaps are stated in the subsection itself, one sentence each: the poll is presented without thread affinity; a message with release whose from function takes no resource does not prevent a nested poll.

    The added sentence: yes, scoped to messages that state release: "Where the message states release and a parameter of the from function receives a facade resource, poll takes it mut: …". A union-form message copies its record, so its loop body may call the resource.

    Suggested, not a condition: for a release message with no resource to borrow, a per-message "loop active" flag that panics on re-entry closes the nested-poll hole (the outer body would otherwise hold a view of a payload the inner loop released, with no unsafe).

    Label removed. Mine now: the mut poll, the verification rules of edit 2, the re-entry flag, the edited words, then the PR.

  12. ehartford commented on Nov 26, 2026

    @ehartford
    ContributorAuthor

    Ruled by Eric, 2026-11-25 (third answer): A. The guard is an Atomic flag taken with one atomic swap or compare-and-swap (never a load then a store), cleared by defer; rendered contract text is fixed so it can name a standard type, with its own test; a threaded test; then the mut poll for the resource case. The sentence, approved as written:

    A message with release whose from function receives no resource has nothing to borrow: a poll of that message begun while another is running panics.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions