Skip to content

Feature request: external decode context (-fno-ctx-members) #15

Done

Description

@sleevetosleeve

Is your feature request related to a problem? Please describe.
Every constructed generated C struct embeds an asn_struct_ctx_t _asn_ctx member (24 bytes on LP64) as its last field, purely so decoders can pause and resume across buffer boundaries (RC_WMORE). For a small NetMsg ::= SEQUENCE { id INTEGER, body CHOICE { ... } } schema, the generated NetMsg_t measures sizeof = 104, of which 72 bytes are _asn_ctx members; without them it is 32. Consequences:

  • Generated structs are not plain data: they cannot be safely memcpy'd, memset, serialized, or stored in bulk (SEQUENCE OF) without dragging parser scratch along.
  • The hidden mutable state is a thread-safety footgun and complicates debugging (parse state is invisible at the call site).

Describe the solution you'd like
An opt-in codegen flag -fno-ctx-members plus sibling decode entry points:

  • With -fno-ctx-members, generated constructed structs omit _asn_ctx; the type descriptor's ctx_offset becomes a sentinel ((unsigned)-1) and struct_size shrinks automatically. Default output stays byte-identical to today.
  • New sibling entry points ber_decode_ctx(opt_codec_ctx, td, struct_ptr, asn_struct_external_ctx_t *ext_ctx, buf, size) and per-codec variants (xer_/jer_/oer_/uper_/aper_/cbor_decode_ctx, plus an asn_decode_ctx dispatcher). The caller owns one arena (asn_struct_external_ctx_t ext = {0};) with 8 inline frames plus heap overflow, reuses it across RC_WMORE resumes, and resets it before a fresh decode. One arena type is shared by all generated types; frames are keyed by struct instance address. Encoders are unchanged.
  • The arena rides in asn_codec_ctx_t (already threaded through every decoder), so no decoder vtable/signature changes are needed; the ~21 st + specs->ctx_offset fetch sites become dual-path, free routines and size guards become sentinel-aware, and new ASN_STRUCT_RESET_CTX / ASN_STRUCT_FREE_CTX macros use type-agnostic helpers (no new asn_TYPE_operation_s field).
  • Contract: plain ber_decode() cannot resume -fno-ctx-members output; the flag is used together with the *_decode_ctx entry points.

Full design (with the coupling-surface map, prototype evidence, decisions log, rollout and testing plan): docs/external-ctx-design.md, delivered as design-doc PR #14.

Prototype validation (sandbox, real generated code): full-buffer, 1-byte-chunked and 3-byte-chunked BER decodes all pass identically with embedded and external ctx; sizeof(NetMsg_t) 104 -> 32; AddressSanitizer clean.

Describe alternatives you've considered

  • Changing the ber_decode signature in place — rejected (ABI break); sibling functions keep existing callers working.
  • Replacing the member with a pointer _asn_ctx_ptr — rejected: still a member, structs remain non-plain, and it adds a heap allocation per struct.
  • Adding a free_struct_ctx method to asn_TYPE_operation_s — considered, deferred: all decoder scratch is generic ctx->ptr, so type-agnostic arena helpers suffice; can be added later if a type needs custom cleanup.
  • Making external ctx the default — rejected: upstream-compatible default stays; opt-in flag only.
  • The Rust backend already uses this model (plain value structs; Decoded<T>{value,consumed}; Limits; decoder-owned RecordContext/cursors in rust/asn1c-runtime), so this brings the C backend to parity rather than inventing a new pattern.

Additional context

  • Rollout phases (each its own PR off vlm_master): Phase 0 BER/CER (shared machinery + arena + ber_decode_ctx), Phase 1 XER/JER, Phase 2 OER, Phase 3 UPER/APER (SET/SET-OF sites), Phase 4 CBOR. converter-example.c/PDU-collection helpers stay on the plain entry points until all codecs have _ctx versions.
  • Acceptance criteria per phase: both generation modes pass make check; -P expected-output tests for the flag (no _asn_ctx member, sentinel offset); chunked-decode regression driver (full / 1-byte / 3-byte chunks) per codec; ASAN/UBSan clean.
  • Scope note: BIT_STRING_t/OCTET_STRING_t are fixed skeleton structs and keep their embedded member; the dual-path decoders make the mixed mode work.

Activity

  1. added a commit that references this issue on Nov 27, 2026
  2. sleevetosleeve commented on Nov 27, 2026

    @sleevetosleeve
    OwnerAuthor

    Amendment request for the external decode context: route the arena's own allocations through the allocator macros.

    In skeletons/constr_TYPE.c, the arena's heap-overflow array is managed with raw libc calls, while everything else in the skeletons uses the macros:

    • constr_TYPE.c:45: realloc(ext->heap_frames, ncap * sizeof(*nf));
    • constr_TYPE.c:70: free(ext->heap_frames);

    The per-frame parser scratch already goes through the macros (FREEMEM(...ctx.ptr) at constr_TYPE.c:66,69), and dynamic growth elsewhere uses REALLOC (e.g. asn_SET_OF.c:27, constr_SET_OF.c:103,429).

    Please amend the two raw calls so all memory management in this feature uses the macros:

    -			realloc(ext->heap_frames, ncap * sizeof(*nf));
    +			REALLOC(ext->heap_frames, ncap * sizeof(*nf));
    -	free(ext->heap_frames);
    +	FREEMEM(ext->heap_frames);

    Why it matters: consumers can redefine these macros. The aerodale Godot module (which generates its messaging layer with this fork) patches asn_internal.h to route CALLOC/MALLOC/REALLOC/FREEMEM to Godot's allocators; with the raw calls, the arena's overflow array currently bypasses that routing. The pairing is self-consistent (raw realloc/free), so this is not a bug — but the array escapes the consumer's allocator and memory accounting, and it is the only allocation in the feature that does not go through the macros. The 8 inline frames already keep the common case allocation-free; the overflow path is hit by deeply nested or many-element decodes.

    Testing suggestion: tests/tests-skeletons/check-ext-ctx.c (heap-overflow case) should pass unchanged; rerun tests-skeletons plus the check-610 pair under ASan/LSan to confirm the macro pairing stays balanced.

    Found while integrating -fno-ctx-members downstream: generated code now decodes via ber_decode_ctx with a caller-owned asn_struct_external_ctx_t arena.

    Generated by Mistral Vibe.
    Co-Authored-By: Mistral Vibe vibe@mistral.ai

  3. sleevetosleeve commented on Nov 27, 2026

    @sleevetosleeve
    OwnerAuthor

    Amendment implemented in PR #22 (branch vibe/ext-ctx-arena-macros-d2e85d): the arena heap-overflow array in skeletons/constr_TYPE.c now uses REALLOC/FREEMEM instead of raw realloc/free, so redefined allocator macros capture it too. The 8 inline frames stay allocation-free and the per-frame scratch already used FREEMEM, so alloc/free pairing remains balanced.

    Verified locally: tests-skeletons 71/71 (incl. check-ext-ctx under ASan/LSan), tests-asn1c-compiler 17/17, check-610 pair 2/2, check-ext-ctx.sh 1/1 — plus a consumer-style simulation with a patched asn_internal.h routing all four macros to counting allocators: 16 frames + scratch route 17 allocations through the macros and asn_struct_external_ctx_reset() frees all 17, LSan-clean. The pre-fix code failed that simulation (overflow realloc bypassed the macros), confirming the test detects the issue.

    Generated by Mistral Vibe.
    Co-Authored-By: Mistral Vibe vibe@mistral.ai

  4. added 5 commits that reference this issue on Nov 28, 2026
  5. sleevetosleeve commented on Nov 29, 2026

    @sleevetosleeve
    OwnerAuthor

    Closing as done — the external decode context feature is complete on vlm_master and verified downstream (Godot integration working with -fno-ctx-members).

    Shipped across:

    Docs for end users: README section "External decode context (-fno-ctx-members)", the asn1c(1) man page entry, docs/external-ctx-design.md (design + decision log), docs/issue-15-s2s-postmortem.md (post-mortem).

    Tests: tests-skeletons/check-ext-ctx.c, tests-asn1c-smoke/check-ext-ctx.sh, check-610 in both modes, Wrap aliasing regression in the 610 module; full local suites green (skeletons 71/71, c-compiler 94/94, smoke 43/43, compiler 19/19) plus the PKIX1 example make check in both codegen modes.

    Note: the flag remains fork-specific and is rejected as rust-incompatible by the Rust backend, as designed.

    Generated by Mistral Vibe.
    Co-Authored-By: Mistral Vibe vibe@mistral.ai

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions