Secure entry for privileged native applications

Status: proposed. This document specifies a build mode; it does not describe an existing security guarantee. Implementation and adversarial qualification must precede use for a privileged executable.

Delivery scope: secure entry, then verified provenance

Stage 1 trusts the reviewed compiler, SDK, build host and hook against hostile callers/inherited state. Stage 2 verifies provenance. Baseline b896056a9 remains unqualified for privileged production use.

Stage 1: secure entry

Ship Linux x86_64 static-musl first. Embedded code means linked native modules, with no bytecode/archive fallback. All rows are mandatory regardless of IDs or AT_SECURE. "Present" means accepted internal implementation, not qualification.

Runtime requirementState at or before b896056a9Missing before Stage 1 enables privileged builds
Environment allowlistPresent: empty environ before/after hook; implicit getenv disabled.Test LD_*, SIGIL_*, allocator/locale attacks; raw envp only reaches the trusted hook.
DescriptorsPartial: 0/1/2 repaired; runtime ports CLOEXEC.Close inherited FDs above 2 independently of NOFILE; explicitly retained hook FDs require validation/CLOEXEC.
Code loadingPresent internally: fixed entry/bindings; no module/package/FFI/path loading.Enforce in public images; reject missing modules and appended/replaced bundle dispatch.
Linking, allocator, constructorsPartial: static PIE/RELRO/NX, stock allocator, named startup inventory.Review complete final-ELF pre-hook/exit inventory and libc startup; exclude IFUNC and dynamic linking.
Umask, cwd, signalsPartial: signals reset/drained/blocked, timers disarmed; dumps/core disabled.Establish umask 077 and safe cwd; verify hook replacements, limits and post-hook signal state.
Linux privilegesPartial: original IDs and internal group/ID/capability operations.Reviewed drop helpers; verify groups/all IDs/caps/securebits and nonroot regain refusal.
Generic audited launcherPartial: internal immutable C plans/raw-child/pidfd machinery; typed adapter/integration missing.Stage 1 Sigil primitive: explicit absolute executable/argv, no shell/PATH search; child env from nothing; explicit FD mapping/unlisted-FD closure; checked setgroups/GID/UID order and capability bounding; requested no-new-privs; optional session/controlling TTY; CLOEXEC exec-error pipe; async-signal-safe child only.
Debug surfacesPresent: secure profile excludes interpreter/compiler, REPL/nREPL/tracing/debug dispatch.Enforce final-image/dependency exclusions and behavioral mutations.
Secure executionPresent: irreversible secure mode; ordinary-entry AT_SECURE defenses.True setuid and root-init AT_SECURE=0 VM tests, beyond forced unprivileged observations.
Hook/handoffPresent: pre-runtime hook, sealed typed original-ID context, direct entry.Public-image ordering/consumer tests; project hook must bound argv and normalize resource profiles.
Startup refusalPresent: raw exit 126; no ordinary finalizers.Cover every new guard/unsupported config; never fall back to ordinary builds.
Public selection/reportInternal schemas exist; public output refuses.Enable secure-release after runtime gates; distinct versioned runtime report marked provenance-unverified, never a Stage 2 receipt.

Ward contract 7 accepts the distinct versioned provenance-unverified runtime report. Contract 10's minimum launcher belongs in Stage 1, in Sigil, for any secure-entry program. The parent pins the absolute executable; the child uses only async-signal-safe operations, with no ordinary fork/spawn fallback. Ward owns executable/identity authorization, PAM/NSS, TTY/resource/environment policy; Sigil owns launch mechanics. Both programs need the mode; ward-login needs its secure config/hook. Other runtime contract rows remain Stage 1 requirements.

Stage 1 merge/enable gates, using fresh evidence and the standard resource limits:

  1. Run existing test/integration/ drivers with fresh inputs: test-runtime-policy.sgl, test-native-secure-environment.sgl, test-allocator-secure-environment.sgl, test-secure-entry-hook.sgl, test-secure-native-profile.sgl, test-secure-startup.sgl, test-secure-elf.sgl, test-secure-link-startup.sgl and test-secure-public-config.sgl. Add high-FD, cwd/umask, capability/ID-failure and post-hook cases. Every guard needs a detected compiling behavioral mutant.
  2. Build both actual Ward targets through the public secure config. Check final ELF constructors, modules/entry and excluded symbols. Test hostile env/argv, hardlinks, rename races, replaced/appended manifests and normalization failures. Run test-secure-spawn-plan.sgl/test-secure-spawn-process.sgl plus adapter tests for path/argv refusals, empty-built env, FD closure, credential/capability order/failures, NNP, session/TTY options and parent-visible exec errors. Inspect child objects; behavioral mutants must detect atfork, allocation/callback, PATH/shell, credential-order and CLOEXEC-error regressions.
  3. With separate authorization, test true setuid-root and root-init execution, real capability/ID drops and failed regain in a disposable VM. Fresh full suite; resolve or obtain release-review disposition of the three native-runner failures. Independent line-by-line runtime security review must include the generic launcher ABI, child syscall set and FD/error lifetimes. Ward contract review must approve exact images/tests before enablement. Publish the privileged-programs guide.

Stage 2: verified provenance

Follow-upCurrent state; no Stage 1 dependency
Exhaustive compiler reads/build-tool/host-loader provenancePending; declarations checked, syscall probes diagnostic only.
Source-to-archive relationLimited full-byte witnesses accepted: 1073 libc members, CRT transform, two Zig roots. Complete imports/reads pending.
Normalized map, relocations, merged constantsPending; raw contributor/ELF checks exist.
Normalized hook/module binding provenancePending; Stage 1 retains its existing fixed-binding and runtime ordering guards.
Canonical production receiptSchema/sidecars exist; qualified publication/evidence binding pending. Distinct from Stage 1's runtime report.

Stage 1 implies no Stage 2 claim; runtime safeguards cannot move to provenance. Stage 1 implementation is authorized; enablement still requires its runtime gates.

The distinct Stage 1 format is specified in Secure entry runtime report. It records provenance-unverified assurance and explicit unrun privileged qualification, with inline inventory and image byte bindings. Format validation does not grant runtime qualification or installation authority. The public producer must independently check its supported runtime/image policy before emitting that report. Applications requiring the Stage 2 production receipt must reject it. The public build path composes fresh source/hook selection, object/ELF/startup checks and the retained marker before emitting that report and its image. It does not run exhaustive provenance capture or grant privileged installation authority.

Selection and initial platform boundary

The final application's config selects secure-entry?: #t. The application package may name a C hook through secure-entry-hook: "application_entry". The hook is defined in one of the package's linked C libraries, using the existing library / c-sources: mechanism. Dependencies cannot select a hook or weaken the final executable's policy.

(package
  name: "privileged-service"
  sigil: "0.24.4"
  entry: '((privileged-service main) main)
  secure-entry-hook: "privileged_service_entry"
  configs: (list
    (config
      name: 'secure-release
      backend: 'native
      toolchain: 'musl
      static?: #t
      debug?: #f
      optimize: 2
      secure-entry?: #t
      features: '(release allocator-stock))))

Build with sigil build privileged-service --config secure-release. The mode always creates a custom runtime and links the complete selected module closure. It never reuses a CLI executable or adds an SGLPAK trailer. bundle?: retains its existing default; secure mode replaces the packaging step with the self-contained link. Plain sigil bundle must reject a secure config instead of silently copying a runtime. A hook without secure mode is a configuration error, as is an invalid C identifier or an unresolved hook.

The first qualified target is Linux ELF with static-pie musl, using the pinned toolchain already supported by the build system. Other targets and dynamic linking fail configuration validation. This restriction is essential for root-started processes: with AT_SECURE=0, a dynamic loader can process LD_PRELOAD before application main, even if the application uses no constructors. A future dynamic mode needs a separate, narrower contract.

Require static PIE (-static -pie -fPIE with the pinned compiler), full RELRO (-z relro -z now), -fstack-protector-strong, and -fstack-clash-protection. Qualification checks the final ELF is ET_DYN with no interpreter, has GNU_RELRO covering all relocation-protected state, has no exported or undefined dynamic symbols, and has no weak undefined symbols. Static relocation metadata needed by the pinned CRT is permitted only after inventory; an empty .dynsym is allowed, but it does not permit dynamic lookup. Record each hardening flag and its object/ELF verification result in the receipt. If the pinned toolchain cannot produce this combination, fail qualification; do not silently omit a check or substitute an ET_EXEC executable.

Require effective optimization of at least 2, no debug/dev features or DEV_BUILD, and the stock allocator. Explicit allocator-mimalloc, typed MI_* settings, conflicting allocator flags, unsupported backends, runtime reuse, and custom entrypoint substitutions fail the build. The build must validate the effective config after command-line overrides. It must not silently fall back to ordinary mode when a combination is unsupported.

Optimization is a production configuration choice, not the security criterion. Production requires absence of debug instrumentation and hooks: VM opcode/call tracing, profiler collection, GC stress/audit/fault hooks, compiler developer entrypoints, sanitizer startup, function instrumentation, and test-only defines are unavailable in the secure runtime. Debug symbols alone are not executable instrumentation. Validate the effective flags and exported interfaces, and inspect the resulting objects and ELF; an optimized binary that retains an instrumentation hook is not qualified.

The secure setting, hook symbol, runtime policy version, complete module list, and allocator choice enter compile and link cache identities. Runtime archives compiled for ordinary programs cannot be reused for secure programs.

Entry contract

The public C header is <sigil/secure-entry.h>:

typedef struct {
    uint32_t abi_version;
    uint32_t byte_size;
    uint64_t real_uid;
    uint64_t effective_uid;
    uint64_t saved_uid;
    uint64_t real_gid;
    uint64_t effective_gid;
    uint64_t saved_gid;
    uint64_t kernel_secure;
} SigilEntryIdentity;

typedef struct SigilEntryHandoff SigilEntryHandoff;

int application_entry(int argc, char **argv, char **envp,
                      const SigilEntryIdentity *identity,
                      SigilEntryHandoff *handoff);

The hook returns zero to continue. Any other return value terminates through _exit(126) without creating a VM or running application module initializers. With no named hook, the built-in prologue still runs in full. A privileged application must supply a hook when its identity or policy requires one.

The generated main performs these operations in order:

  1. Set non-dumpable state with PR_SET_DUMPABLE=0 and both soft and hard RLIMIT_CORE to zero, checking both operations before handling caller data.
  2. Protect every qualified PT_GNU_RELRO page range with checked read-only mprotect before the hook. Derive ranges from in-memory program headers and the executing image's load bias, with checked bounds/alignment; never reopen the image. Pinned musl rcrt1/_dlstart_c performs static relocations without sealing RELRO, so the prologue must do so. Qualification checks every range is read-only in /proc/self/maps at runtime and uses a write fault mutation control. Record this runtime evidence in the receipt.
  3. Snapshot real/effective/saved UID and GID with checked getresuid and getresgid, and capture the kernel secure-execution bit. Convert each ID to u64 with checked nonnegative, lossless conversion; abort on any failure. Initialize the identity's ABI version (1) and byte size, and require an exact supported version/size at the hook boundary. Set a process-wide, irreversible restricted-runtime policy. Do not inspect environment entries, executable paths, bundles, or user modules. Retain the raw envp pointer for the hook, then point libc environ at a static empty vector without scanning or freeing the inherited entries.
  4. Block all blockable signals. Save no inherited signal handlers for reuse. Reject argc <= 0, a NULL argv, or NULL argv[0].
  5. Disarm ITIMER_REAL, ITIMER_VIRTUAL, and ITIMER_PROF. Drain inherited pending blockable signals with nonblocking sigtimedwait until none remain. Reset every supported catchable disposition to SIG_DFL, including dispositions inherited as SIG_IGN. Skip uncatchable signals and the libc-reserved signal numbers, whose invalid operations are documented.
  6. Check descriptors 0, 1, and 2 with fcntl(F_GETFD). For each closed descriptor, open /dev/null with O_RDWR|O_NOFOLLOW, verify that it is the expected character device, and install it at that descriptor. Clear FD_CLOEXEC on each repaired descriptor. Preserve already-open descriptors. Any unexpected system-call error terminates before runtime initialization. Close every inherited descriptor above 2 with checked close_range(3, UINT32_MAX, 0), including descriptors above a lowered NOFILE limit. Linux 5.9 or later is required; unavailable/denied operations refuse instead of falling back to a limit-based scan. Set umask 077 and change cwd through a checked, CLOEXEC directory descriptor opened on /; close that descriptor before the hook. The directory must be root-owned and not writable by group or other users.
  7. Call the selected hook with raw argc/argv/envp and the original identity snapshot while signals remain blocked and timers remain disarmed. The hook may normalize IDs, supplementary groups, limits, descriptors, working directory, umask, and child-environment policy. It must check all security-critical results itself.
  8. After a successful hook, enforce non-dumpable state and zero core limits again. Refuse closed standard descriptors, an umask permitting group/other access, or a cwd that is not a root-owned, non-group/other-writable directory. Preserve stricter owner-bit masks. A trusted hook choosing another cwd must select it from trusted configuration and validate its path/mount policy; these metadata checks do not authorize caller-selected paths. Hook-created descriptors require the hook's explicit validation/CLOEXEC policy. Then seal the handoff and apply its selected final signal mask. The default final mask is empty; a checked hook setter can select another mask. The hook must leave signals blocked until this boundary, must not arm timers, and must not install handlers that depend on runtime initialization. Preserve its explicitly installed dispositions. Do not drain signals that arrived during the hook: they remain pending and are delivered when allowed by the final mask. Record the pending signal set at this boundary in the immutable built-in context, including SIGTERM if the hook keeps it blocked. A hook that consumes a termination signal must explicitly record that decision in its typed output. No termination signal is silently discarded. Discard any environment installed by the hook before runtime startup too; validated values needed later belong in the typed handoff.
  9. Only now call sigil_stdio_init, initialize the shadow stack, create the VM, register linked native primitives, initialize linked Sigil modules, and call the compiled application's entry procedure.

Before the hook, the built-in prologue uses only the C/syscall operations needed for these checks. It does not allocate managed objects, use stdio, create threads, initialize locale/timezone, or load libraries. Diagnostics use fixed strings and write when stderr is usable, followed by _exit(126). The sole intended filesystem operation is repairing descriptors via the fixed /dev/null device. No constructor performs that operation.

The contract begins at the first application instruction in main. Kernel image loading and the qualified libc/CRT startup necessarily precede it; libc establishing environ and reading auxiliary-vector metadata is not an application environment option. Qualification must audit that startup and prove it consumes no caller-selected loader, allocator, locale, or tuning options. There is no promise to prevent termination before main: an unblocked inherited timer signal can kill the process before it reaches the prologue, and SIGKILL/SIGSTOP cannot be reset or drained. Tests block inherited timer signals before exec to exercise the surviving pending state. Later signals from an authorized sender are also outside the pending-state reset guarantee.

The original IDs are observations, not authenticated application policy. The mode does not require root, elevate privilege, change IDs, clear supplementary groups, authenticate users, or establish a PAM session. An application that normalizes real IDs must retain the snapshot for its authorization/audit policy. It must reject unexpected real, effective, or saved IDs itself. Supplementary group lists require separate application checks when relevant.

Checked hook credential drop

The trusted C hook may explicitly call sigil_secure_drop_privileges from <sigil/secure-credentials.h>. Its versioned SigilSecureDropPolicy selects one nonzero final UID and GID, up to 64 exact supplementary groups, and whether to set no-new-privileges. Initialize the complete policy, including abi_version = SIGIL_SECURE_DROP_ABI_VERSION and byte_size = sizeof(policy). The helper is compiled in the secure runtime source profile, but the generic prologue never calls it automatically. The application owns target identity and group authorization; an explicit group list is not authentication.

This initial helper clears every effective, permitted, inheritable, ambient and bounding capability. It locks NOROOT, KEEP_CAPS disabled and ambient-raise disabled, while locking normal UID fixups on. Incompatible existing locks, unknown securebits, unsupported capability widths, sentinel IDs and malformed policies refuse. No permitted capability is enabled to make a drop succeed. Existing no-new-privileges is preserved and a true request sets it. A false request does not prevent a later privileged exec from changing credentials; the application must request no-new-privileges when that prohibition is needed. Selective capability retention and the audited launcher remain separate work.

Call only in the single-threaded, nonreentrant entry hook with every blockable signal masked. Private bounded static scratch avoids implicit libc/TLS paths under the actual stack-protector and stack-clash flags; the object gate checks that generated result. Inherited filesystem IDs must equal effective IDs. Unsupported overrides refuse before changing groups, IDs or capability policy. The helper sets and checks nondumpability and both core limits zero. It sets groups, stages GID setters before UID setters, and retains a differing existing real/saved ID across effective/filesystem changes. After each setter it reasserts nondumpability and verifies real/effective/saved/filesystem IDs before finishing the next step. The last real/saved changes do not change effective or filesystem IDs, avoiding an all-equal dumpability-reset interval.

Before returning, verify all four UID/GID views, exact groups, every capability set, securebits, keepcaps, NNP, dumpability and core limits. Any syscall or verification failure blocks signals and exits 126 through raw syscalls without rollback, callbacks, NSS, formatting, allocation or runtime cleanup. A partial drop never returns to application code. The hook should call this once at its chosen final-drop boundary, after completing operations requiring privilege.

test-secure-credentials.sgl distinguishes syscall-state model evidence from real ordinary nonroot refusal. Model cases cover root-init/mixed/already-final IDs, extra saved-ID staging, exact groups, NNP variants, mismatched state and every normal-path syscall failure. Compiling mutants must specifically expose an unsafe dump window or return through forbidden state. Separate production object mutants reject external calls, TLS and indirect callbacks. A real nonroot hook refusal verifies that failure precedes handoff/runtime return. Successful real privileged drops, kernel regain refusal, true setuid/root-init images and selective-capability launcher behavior remain unqualified until the separately authorized VM and final-image gates run.

Typed hook handoff

Hook output never travels through environment entries, rewritten argv, or an untyped global variable. A package with a hook may declare secure-entry-fields: '((caller-uid u64) (command string 4096) (interactive boolean)). The build validates unique field names, supported types, and bounded string or byte lengths, and emits a constant schema into the executable. Supported initial types are boolean, signed/unsigned 64-bit integer, UTF-8 string, bytes, and bounded string lists. A declaration such as (validated-argv strings 64 16384) limits both item count and total bytes. At most 64 fields and 64 KiB of copied payload are permitted; a larger schema fails the build. The schema and field order enter the closure digest and receipt.

SigilEntryHandoff is a bounded builder in private static storage, initialized before the hook without a VM or managed allocation. C setters accept a schema field index and a value of its declared type, copy string/byte content, and report type, range, encoding, or capacity errors. Every field is single-assignment: a second set fails even if its value is identical. Every setter error latches a startup error that the hook cannot clear. The builder header also carries checked ABI version and byte size fields. They never retain pointers into argv, envp, or the hook's stack. All declared fields are required. After hook success, seal the builder, reject missing/invalid fields, and retain an owned copy until the VM's read-only context object is created. The original identity snapshot is a separate built-in component the hook cannot overwrite.

(sigil secure-entry) exposes entry-context, entry-identity, and typed field readers. The context is an opaque runtime object with no mutation or pointer-access API, not a mutable vector, alist, or ordinary mutable struct. Scalar reads return typed values; string/byte/list reads return fresh copies so modifying a returned value cannot modify the sealed context. Native extensions remain trusted code and must not retain or mutate the builder after sealing. The runtime roots the context for the process lifetime and publishes no setters. A project may include validated argument values in this record; privilege policy must consume the record rather than reinterpret raw argv.

The native module's typed interface uses entry-context with no arguments, entry-context? with one value, and entry-identity with a context and identity field symbol. Identity fields are abi-version, byte-size, real-uid, effective-uid, saved-uid, real-gid, effective-gid, saved-gid, and kernel-secure. They return exact nonnegative integers. entry-mode-flags, entry-pending-signals, and entry-signal-mask each take a context and return exact nonnegative integers. The six field readers entry-boolean-ref, entry-i64-ref, entry-u64-ref, entry-string-ref, entry-bytes-ref, and entry-strings-ref take a context and declared field symbol. Wrong handles, unknown fields, or a reader of the wrong type raise a typed runtime error. Missing process context is a fatal invariant failure before application initialization. Module bindings contain reader procedures, never the context value itself. These native interfaces precede public build integration.

The handoff schema describes observations and decisions the project hook actually validated. The toolchain does not turn a copied caller string into an authorized command, path, or authenticated identity. Bounds and type failures abort before any application module initializes. Test missing fields, wrong types, invalid UTF-8, oversized payloads, mutation attempts, modified original argv/envp after sealing, duplicate sets, incompatible ABI/size, tiny inherited stack limits, saved-ID capture, and hooks that refuse startup.

Immutable code closure

All application and reachable dependency modules, including implicit core imports, are linked into the ELF. The build uses the existing native module graph and initializer ordering, independently of SIGIL_NATIVE_DEPS. It must reject unresolved imports, duplicate selected dependency names, unavailable source/precompiled objects, and language-reader cases whose actual runtime closure cannot be proven. It must not retain the normal bytecode fallback. Native C registration and compiled module initializers run after the hook; their binding relationships are fixed by the build. Generate direct native initializer references from the selected module table. Never discover them with dlsym(RTLD_DEFAULT) or silently omit a module whose initializer is not found; an unresolved direct initializer is a link failure. The ordinary runtime's sigil_init_native_modules dynamic-lookup implementation is absent.

The secure emitter omits bundle dispatch, executable-directory detection, SIGIL_LIB, SIGIL_LIB_PATH, -L, ../lib, summary paths, script dispatch, compiler helper commands, and boot-eval. Its entry module and procedure are fixed at link time. A caller's arguments, including -L, belong to the application; the launcher does not parse them as runtime switches.

Secure entry uses a separate secure-native runtime source profile, not the ordinary runtime with its loader disabled. The compiler, expander, macro system, bytecode interpreter/deserializer, eval, load, REPL, archive code loader, runtime import parser, and module file loader are absent from the linked closure, including their implementations and registration code.

Split shared native execution state, allocation, native closure application, binding cells, and static module registration from the current combined VM, native, and module source units. Compile the secure archive from an explicit reviewed source/export allowlist with a distinct cache identity. Do not use the ordinary src/*.c archive and assume dead stripping will remove every forbidden function. Link-time pruning reduces the approved profile further; it is not the primary exclusion mechanism. A native application still has runtime values, GC, native closures, and binding lookup; it has no engine for executing newly supplied Sigil source or bytecode.

Resolve imports and macros at build time. Emit direct initializer and binding references to the fixed linked module table. There is no runtime sigil_module_load, path list, source reader extension, or module-resolution fallback to call, even for a computed name. A missing runtime import fails the build. Macro/syntax exports required during compilation belong only to the build compiler's metadata; do not emit runtime macro objects or registration for them. The entry trampoline calls the compiled procedure directly instead of evaluating an entry expression. The irreversible mode survives ID changes.

Preflight every reachable Sigil module, runtime export, native primitive, and C object against the secure profile. Imports requiring the compiler, expander, macro system, eval, load, REPL, bytecode execution, dynamic import, reader extensions, or the FFI module fail with the dependency path that introduced the capability. Reject unresolved native calls instead of supplying a disabled stub. A dependency cannot opt back in with a config or replace a source file under a familiar module name.

Canonical core dependency inspection distinguishes procedure closures from literal data, fixed binding aliases and fresh prompt-tag constructors. It checks actual source publication origins and producers rather than inferring procedure identity from names. Initializer effects remain roots, including installing the runtime exception prompt tag. Retaining an alias retains its source dependency; retaining a procedure conservatively retains dependencies of its complete body and nested closures. Unclassified value initializer effects fail inspection even when that declaration was not requested.

The dependency plan grants no runtime authority. Full canonical core and selected subsets remain pending until selected-source recompilation and independent native, binding, literal and initializer validation succeed. Selected replay filters original syntax under the same captured source authority and keeps native core declarations in module cells at every subset size. It rechecks actual replayed publications and all binding dependencies against the selected source population and frozen C bindings. Missing source dependencies refuse instead of acquiring native authority from a name. Project roots come from selected import, reexport and hygiene cells in every retained source unit, including unread procedure bodies and reexports. Secure conversion captures imports used as tail values or discarded reads as well as ordinary value destinations. An exact frozen C cell/value can supply native authority; other core roots require a current source binding and its captured source identity. Owned core cells and values are snapshotted immediately after authenticated seed initialization. Project phase work cannot replace fixed callable, prompt-tag or symbol bindings. Selected closure, alias, literal and prompt constructors must describe those original initialized values. Distinct prompt constructors require distinct tags, and the source exception tag must have actually become the VM's exception root. Mutable phase capture data may evolve for expansion, but a changed phase value cannot become runtime literal data. These value checks supplement the final native initializer and content proof. The contents-only native validator grants no emission authority. A separate initializer trace follows the actual native entry function and its one module body call, with bounded continuation and value tables. It requires the fixed module shell, ordered source construction and alias reads, distinct fresh prompt tags and exactly one installation of the constructed exception tag. Branches, cycles, unknown calls and unclassified effects refuse. Inspection alone leaves both full and selected core programs pending. Explicit graph normalization can admit the exact project-derived subset after every source, value, native content and initialization obligation passes. The full core stays pending permanently. Private revalidation checks the graph's exact selected program and admission state without toggling pending for inspection. Every later graph output revalidates all selected units and the initializer proof; any graph failure revokes a previous core admission. The build compiler exposes a sigil-secure-source-inventory datum, schema 1, only for an admitted graph. It records selected core artifact authority, sorted native cell constructors and callable native contracts separately, with their exact encoded arities, the three port parameter constructors, actual core source constructor roles, and modules in selected initialization order. Each module records its framed source digest, sorted captured inputs (path, byte length, primary/fold-case flags and SHA-256), source publications, selected imports, private hygiene/reexport coordinates and separate value/syntax export facets. All references use logical provider/name coordinates and source hashes. No VM address or callable object is serialized. The inventory revalidates the complete graph before opening its output and after writing. It grants no provider authority and is input data for the final JSON receipt, not a claim that an executable has passed qualification. The runtime-only (sigil secure-entry) provider has a separate reviewed reader contract shared with its C constructor. The build graph reserves that provider and stores distinct private, non-callable descriptors in its original owned cells. Those descriptors are compilation metadata, not runtime values; phase code cannot call them, and strict native literal admission rejects their serialization. An original descriptor or its authenticated source alias selects a fixed reader contract. Emitted imports, reexports and captured hygiene reads verify that their actual value is the original runtime NativeProc and that its original provider/cell, C implementation, name and encoded arity still match. A name alone never authorizes a native implementation. Applications read the real hook context from emitted procedures after runtime provider initialization. Inspection data and direct-WASM analyses are not native initialization certificates.

The build-only (sigil compiler) procedure (compile-to-secure-native-graph core-source modules new-output-directory) accepts an ordered nonempty list of (module-name source-path) string pairs. It verifies the selected toolchain core, evaluates the closed source graph in its isolated VM, and admits every retained native unit before creating any output. The output directory must be an absolute new path. The compiler reserves it with mode 0700, writes unit-0.c for the selected core followed by unit-1.c and later project units, and writes inventory.sgl. Initializers are named sigil_secure_unit_0_init, sigil_secure_unit_1_init, and so on. Callers cannot supply C identifiers or individual output paths. The returned ordered list contains (module-name C-output initializer) string triples, including the core first. A later I/O failure raises a compiler error and retains partial staging output for diagnosis; callers must consume outputs only after success. This Linux-hosted compiler entry emits library units, not a qualified executable or production receipt. Runtime linking must still initialize the fixed native providers, then these units in dependency order, before the application entry. The (sigil build secure-profile) helper supplies the initial x86_64 Linux musl compiler and hardening arguments, and reads the runtime source profile as one data record. It rejects malformed records, duplicate source aliases, unsupported path forms and resolved paths outside the selected runtime source directory. The linked profile gate consumes these same inputs. This helper validates input shape and containment; the build must separately bind the actual source/toolchain bytes, compile in fresh staging and qualify the resulting objects and ELF.

The internal (sigil build secure-selection) helper validates the initial fixed production config and selects source imports from explicit package-owned rows. Its target feature set is required and recorded, so conditional imports do not use ambient host features. It refuses missing or duplicate providers, reserved providers, source escapes, custom language readers, cycles and an entry owned by a dependency. Source contents are observed without executing module initializers. Its observed digests must later match the compiler's authoritative source inventory. The current fixed profile accepts optimization level 2 and rejects custom compiler/linker settings and collector budgets. These internal helpers alone do not emit a qualified executable or receipt. The public runtime producer composes them with the Stage 1 runtime/image gates. The final caller must bind command-line overrides, compiler features, hook ownership and all required qualification evidence.

Hook input selection consumes the final package record's own library C-source declarations. It validates the shared hook/schema contract, relative source patterns, canonical source containment and per-source include directories. It rejects missing or duplicate inputs, source/include escapes, custom compile or link settings, and application native initializers. The unqualified candidate builder checks an optional per-source include table and records the actual compiler arguments and ordered source/object/process mapping. Before linking, it checks hook definitions across those fresh outputs and retains the selected owned hook's exact code in a binary sidecar with size and digest metadata. These checks do not establish complete header provenance, final linked-code identity or startup qualification; the final-ELF gates must prove those obligations before the build can publish a qualified executable.

The internal (sigil build elf) reader captures bounded ELF64 little-endian metadata without executing the artifact. It refuses malformed table ranges, unsupported section numbering, noncanonical UTF-8 names and stated size/count limits. (sigil build secure-objects) uses that snapshot to require exactly one strong, ordinary function definition of the hook in the supplied owned objects, with captured read-only executable code. Competing definitions and IFUNC symbols refuse. The caller must supply the actual compilation outputs; this helper does not establish final linked-code or startup provenance.

The ELF reader also inspects loader-visible PT_DYNAMIC entries and REL/RELA sections from the same captured image. It limits total dynamic slots to 4096 and relocations to 65536, requires null termination and zero dynamic padding, and preserves signed RELA addends. These are metadata primitives; the final qualifier must separately bind loader ranges, relocation targets, hardening and source/object/startup provenance.

The internal (sigil build secure-elf) structural floor binds loader-visible tables to captured file ranges, checks NOW/PIE and RELRO/NX load layout, and rejects dynamic exports, undefined nonlocal symbols, IFUNC and unsupported relocation kinds or targets. Its result is explicitly elf-floor-only, with the captured image and pending source/toolchain, startup, hook/entry, capability, runtime-RELRO and stack-hardening obligations. This helper alone cannot emit a qualified receipt; final caller integration remains required.

The captured-input producer (sigil build secure-compile) copies selected sources, headers and the compiler SDK into private staging before conversion or C compilation. It fixes the target features and command environment, records preprocessed inputs and actual header dependencies, and replays the captured driver's literal linker arguments to obtain a map without changing the ELF bytes. The input closure and embedded marker bind the captured source, toolchain, compiler inventory and compilation-unit digests. The result remains an unqualified candidate.

(sigil build secure-link) admits only the pinned driver's fixed argument sequence, ordered producer objects and private CRT/libc/compiler-rt archives. It hashes those actual inputs and rechecks them after replay. Its bounded map parser preserves output/input/symbol coordinates, including ELF TLS-relative symbols, and rejects unowned contributors. The startup inventory binds named CRT, libc, TLS, stack-guard, memory-helper and generated-main symbols to those contributors and records their final code digests. It refuses application definitions of CRT callback boundaries, callback arrays, non-no-op _init/_fini, IFUNC producer objects and startup-source body changes. The fixed-device libc exception is explicit in its evidence.

This evidence is labeled link-startup-only. It does not establish archive member byte normalization, transitive CRT/include coverage, merged constant provenance, normalized hook/module relocations, hook ordering, complete capability exclusions or runtime hardening. Those obligations remain pending, and neither this helper nor the captured producer can publish a qualified executable or production receipt. Constructor/preinit links, a strong _init override, emitted ELF IFUNC, final-code changes, input mutation and map/argument refusals independently exercise this boundary without running mutant images.

sigil_secure_core_module_init constructs the fixed C core first in the actual sealed-context VM. It refuses prior modules or native registrations and preserves an existing error. Only successful registration of all reviewed primitive families publishes completed core state. The 193 native call entries and three port parameters are constructor consistency checks, not source binding authority; the selected Scheme core still supplies source-owned bindings such as force. compile-to-secure-native-program takes the graph compiler's three inputs plus entry-module and entry-name strings. Before creating output it selects one owned exported zero-argument function through the admitted source's export metadata and definition-origin proof. Both value publications and lexical-cell publications require one source definition and one matching marked publication. Lexical-cell targets use value-derived constructor analysis with continuation/capture alias tracking and whole-unit write/escape refusal. The snapshot is taken directly from that proven publication, including when a sibling captures the entry. Rest arguments, imported entries, ambiguous definitions and binding writes are initially unsupported and refuse. It returns (secure-native-program-v1 (entry-module entry-name) module-rows) and emits sigil_secure_application_entry in the selected unit. That wrapper references the exact native C function directly and uses the actual module pointer captured during its proven source publication. That publication checks the closure's native function and capture count, then snapshots its captures into private GC-rooted runtime storage once. The wrapper uses this snapshot, so replacing or modifying the public closure cannot change its function or capture array. Captured objects retain their ordinary source-language mutation semantics. Runtime export-table or binding cell changes cannot select another entry function. There is no application entry name lookup at runtime. sigil_secure_call_entry provides the wrapper's one-shot startup/error boundary. It requires the original constructed core, real typed provider and completed linked module state, then invokes the direct C body in that captured module. Missing module publication, incomplete startup and repeated calls refuse. Existing errors, aborts and exception unwinds are preserved. An entry-call failure remains a failure, with the current module restored. The caller roots any returned value and chooses the final status before sigil_secure_finish. Application privilege policy reads validated handoff fields, not raw argv. The pure (sigil build secure-entry) generator consumes that compiler-selected program layout, an optional hook name and typed field declarations. It emits a main function whose first operation is the hardened prologue, followed by fixed constructors, linked unit initializers, the entry call and explicit finish. Successful entry return exits 0, entry failure exits 1, and startup failure exits 126. It validates field count and aggregate storage bounds before emission and escapes string bytes without C trigraph or variable-width escape ambiguity. This code-generation helper grants no hook ownership or final ELF qualification; the build caller must establish those separately before publishing a receipt or exposing the secure build option.

Secure literal admission accepts only data the native emitter can reconstruct: immediates, symbols without NUL bytes, keywords, strings, bytevectors, representable bignums, pairs, and vectors. Procedures, module objects and other runtime objects, including nested values, refuse before output. Cycles and shared mutable objects within a literal refuse because tree reconstruction cannot preserve their identity. Admission is bounded to 65,536 nodes and depth 256 per literal. Decimal bignums must fit the current emitter's 1,023-character reconstruction buffer. Exceeding a bound is a build error with the limit named.

Qualification inspects the unstripped final ELF and link map. The receipt contains the exact linked module/export/primitive and source/object manifests, a sorted symbol inventory, the secure profile's allowlist identity, and the absence check result for forbidden implementations. Check both unexpected linked objects and forbidden symbols, including internal aliases. Refuse a link containing dlopen, dlsym, FFI registration/implementation symbols, an exported or undefined dynamic symbol, or any weak undefined symbol. Refuse a link that lacks sufficient symbol/provenance evidence. Negative controls add each prohibited capability through a dependency or direct native reference and must fail. Stripping cannot substitute for this check; preserve the inspection evidence and bind the receipt to the distributed ELF digest.

This mode loses runtime eval/load, REPLs, dynamic modules, bytecode plugins, runtime macros, and extension-aware read. reader.c remains in the secure source profile for data reading, including the separately specified strict .sgv reader. Datum parsing is not code execution: its entrypoints must have no compiler, expander, loader, user reader callback, or language-extension dependency. The strict .sgv API and validation rules are a separate reader feature, not implemented by secure entry. Character/byte/line I/O and separately compiled data parsers remain available. The source/symbol exclusion checks must allow the data reader while rejecting executable language-reader dispatch and extension registration. Native extensions are trusted build inputs and require review for explicit dynamic linking, executable mappings, or an independently supplied interpreter.

An appended trailer, a hardlink in another directory, a replaced executable pathname, an absent /proc, and a changed current directory therefore cannot select executable code. Resource embedding is initially unsupported in this mode rather than reopening a pathname for assets; applications may read data from explicitly selected, permission-checked locations after the hook.

Audited fork and exec

The mode provides a standalone C sigil_secure_spawn primitive, exposed to Sigil through (sigil secure-entry). Ordinary fork, PTY spawning, shell execution, PATH search, and generic process-spawn implementations are not available in the secure profile. All preparation and validation take place in the parent. No caller-provided pre-exec callback is accepted.

The single-threaded parent must be non-dumpable with both core limits zero, as the secure entry prologue establishes, before it may create a child. The standalone C interface checks these conditions as well. The parent constructs an immutable, bounded SigilSecureSpawnPlan holding an already-open, permission-checked ELF executable fd, copied argv/envp, an explicit descriptor map, final signal mask, and typed optional credential, group, rlimit, working-directory-fd, and no-new-privileges actions. Credential actions include explicit capability sets (inheritable, permitted, effective, bounding and ambient), securebits with lock bits, keepcaps, and all three target UID/GID values. Session actions include umask, dumpability, setsid or setpgid, controlling-terminal TIOCSCTTY, and foreground process group tcsetpgrp on a selected terminal fd. Incompatible session actions are rejected before cloning. A typed pre-exec barrier names a parent-prepared CLOEXEC nonblocking pipe ends and exact ready/release bytes, with bounded timeout and explicit EOF/failure behavior; it is not an arbitrary callback. The application owns path/ancestor authorization, command policy, PAM, and the decision to change identities. The primitive validates plan sizes, duplicate descriptor targets, action ordering, and available kernel operations before creating a child. It does not authenticate the requested identity.

Use a direct clone3(CLONE_PIDFD) syscall with fork semantics, never libc fork, so user pthread_atfork handlers cannot execute. The kernel returns the pidfd atomically with child creation, avoiding PID lookup and competing reaper races. The parent blocks all blockable signals across clone3, restoring its old mask on both success and failure; the child inherits the blocked mask. No VM address space or descriptor table is shared with the parent. Before unmasking, the child resets every catchable disposition, including ignored signals, to the plan's checked defaults, so no inherited runtime handler or self-pipe writer can run. The child performs a fixed reviewed raw-syscall sequence: arrange descriptors; apply limits while privileged; set groups, securebits/keepcaps and capabilities needed across the ID transition; call setresgid before setresuid; verify all real/effective/saved IDs with getresgid/getresuid; install final capabilities and locked securebits, clear keepcaps as specified; set umask and final dumpability; perform checked session/terminal and working-directory actions; close all unlisted fds; exchange the pre-exec barrier; install the final signal mask; and execveat the fixed executable fd. Session operations that require a different credential phase are explicit validated plan phases, not freely reorderable actions. Final credential/capability verification occurs after all privilege changes and before barrier release. Terminal calls use raw ioctl requests, including TIOCSPGRP for tcsetpgrp, without libc. There is no allocation, stdio, logging formatter, NSS, PAM, environment merge, Sigil callback, runtime cleanup, or exit handler in that interval. Failures write a fixed operation/errno record to a CLOEXEC error pipe and call _exit. Only the parent formats an error. Because this path bypasses libc's child bookkeeping, the child must not call libc facilities that depend on repaired thread state; its trampoline uses direct syscalls until exec.

The child sets dumpability and both core limits to zero before changing any credentials. A caller cannot enable core dumps while the child still has copied parent memory. Linux credential changes can reset dumpability according to the host's suid_dumpable setting. For an all-equal final identity, keep a differing existing real or saved ID across effective/filesystem-ID changes, reassert dumpability zero, then finish real/saved-ID changes without changing effective/filesystem IDs again. If necessary, first retain the old effective ID as the saved ID. Reassert zero after every setter. Mixed final identities remain mixed during a possible dumpability reset; exact unchanged ID tuples skip the setter and retain any existing filesystem-ID override. This ordering is a security invariant of the fixed trampoline, not a callback or caller choice. The source audit and real privileged qualification must cover it.

The immutable C plan captures filesystem IDs and inherited NNP. If an ID tuple will change, its inherited filesystem ID must equal its effective ID; otherwise preparation refuses before a setter can normalize an override. Exact unchanged tuples preserve their filesystem IDs. The child checks all four ID views before actions, after each identity setter and at final verification, and verifies groups immediately after setting them. Each nondumpability assertion is read back. Final checks include keepcaps, inherited-or-requested NNP and requested umask. Umask setter/readback failures produce the same fixed parent-visible error records as other child failures. Unsupported capability widths refuse. test-secure-spawn-state.sgl supplies independent query/state/ordering models and compiling behavioral mutants; the real nonroot process gate adds filesystem, keepcaps, NNP and umask denials and preserves the existing exec/pidfd/FD/session controls. These state models and ordinary executions do not qualify successful privileged kernel transitions. The typed adapter and source-provider admission are implemented internally and require their separate review before enablement.

Typed launch interface

Native provider contract sigil-secure-entry-v2 adds the ten operations below to the twelve existing handoff readers. The handoff layout and C spawn options retain ABI version 1. Compiler and runtime derive the same closed provider count, with the existing checks on original native procedures, cells, arities and module ownership. No generic foreign-pointer, callback, compiler or loader API is admitted to implement these operations.

OperationArguments and result
spawn-plan(absolute-path executable-fd argv envp fd-map actions) returns an owned opaque plan.
spawn-plan?One value; true only for an open plan owned by this secure VM.
spawn-plan-close!One open plan; releases its copied strings and pinned descriptors.
secure-spawnOne open plan; returns an owned opaque process. The plan remains reusable.
spawn-process?One value; true only for an open process owned by this secure VM.
spawn-process-idOne open process; returns its numeric PID for reporting, not process lookup.
spawn-startup(process timeout-ms) returns #(pending step errno), #(failed step errno) or #(no-error-record 0 0).
spawn-wait(process nonblocking?) returns #f while pending, otherwise #(exited pid status), #(killed pid signal) or #(dumped pid signal).
spawn-signal!(process signal-number) signals through its pinned pidfd.
spawn-process-close!One already-reaped process; closes its pidfd/error pipe. Refuses a live or unreaped child.

absolute-path is a nonempty, NUL-free absolute string of at most 4095 bytes. The caller supplies a readable, already-authorized ELF descriptor. A parent-only O_PATH | O_CLOEXEC lookup compares the path's device/inode with that descriptor; this is coordinate binding, not file authorization. Symlinks are followed. The application must authorize ancestors, symlinks, executable contents and command selection. The plan duplicates the descriptor, and exec uses only that duplicate, so later pathname replacement cannot select another executable. There is no shell, PATH lookup, environment merge or pathname-exec fallback.

argv and envp are finite proper lists of strings or bytevectors. The plan copies them and rejects embedded NUL bytes. Their combined bound is 256 entries and 64 KiB. argv must be nonempty; envp may be empty. fd-map is a finite proper list of (source-fd target-fd) rows, at most 64, with distinct targets from 0 through 4095. Descriptors omitted from the map are closed in the child, including 0 through 2 if omitted. Sources are pinned before cloning. Fd cycles are handled without clobbering a source. The C plan validator additionally checks descriptor types, action compatibility and kernel support.

actions is a finite proper list of at most twelve distinct forms. List order does not reorder the fixed child sequence. All numbers must be exact, nonnegative integers within the relevant width; booleans must be #t or #f. Unknown forms, duplicate tags, improper/cyclic lists, out-of-range values and callbacks raise errors before cloning.

Action formMeaning and bounds
(ids (ruid euid suid) (rgid egid sgid))Explicit three-ID tuples; each ID is at most 2^32 - 2, excluding the syscall's unchanged sentinel.
(groups (gid ...))Explicit supplementary groups, at most 64; the empty list requests clearing them.
(capabilities (effective permitted inheritable) (effective permitted inheritable) (effective permitted inheritable) bounding ambient)Three staged capability sets, before IDs, after IDs and final, plus final bounding/ambient masks; each mask is unsigned 64-bit and checked against kernel capability support.
(securebits before final)Explicit staged securebits including lock bits, each at most 255; checked against keepcaps/transition rules.
(limits ((resource soft hard) ...))At most 16 distinct supported resource numbers with unsigned 64-bit limits; C validation enforces soft/hard and no-core constraints.
(signal-mask mask)Final unsigned 64-bit Linux signal mask; SIGKILL/SIGSTOP bits are rejected. Default is empty.
(working-directory fd)Pin a directory descriptor and change cwd in the child. Default preserves cwd.
(umask mask)Set and verify a permission mask from 0 through #o777. Default preserves the inherited mask.
(no-new-privileges boolean)Request NNP when true; false preserves inherited NNP and cannot clear it.
(session operation phase pgrp)Operation is none, setsid or setpgid; phase is before-ids or after-ids. The C validator checks the process-group coordinate and compatibility.
(terminal fd controlling? foreground? foreground-pgrp)Pin a terminal descriptor; request controlling/foreground operations in the selected session phase. Zero foreground group selects the child's group. The fd only survives exec when also explicitly mapped.
(barrier ready-fd release-fd ready-byte release-byte timeout-ms)Pin prepared nonblocking pipe endpoints, exchange bytes from 0 through 255 and enforce a bounded timeout, at most 60000 ms.

FD inputs and process-group coordinates fit a nonnegative signed C integer. spawn-startup timeouts are at most 60000 ms, and signal numbers range from 0 through 64, with zero providing the kernel's permission/existence check. Syscall/plan failures raise parent-side I/O errors with an operation step and errno; malformed typed requests raise type errors, and arity is checked by every native operation. Child failures retain their fixed structured record.

An error-pipe EOF means only that no error record was received. It is not proof that the intended program initialized or even reached exec. Applications must combine startup observation with wait status and any required application handshake. Waiting is explicit and serialized by the single-threaded parent; another reaper must not consume this launcher's children.

Capsules contain monotonic opaque tokens, never exposed native addresses. The native registry contains no GC pointers and runs no foreign finalizers or tracers. Callers must keep handles and explicitly close every plan and reaped process; losing a handle leaks that resource until process exit. There are at most 256 live resources across both kinds. Exhaustion is a recoverable I/O error: close an owned handle before retrying. Closed tokens never alias later resources. Token-space exhaustion is fatal rather than reusing a token.

test-secure-spawn-bindings.sgl exercises the actual typed boundary, opaque ownership/GC, copied argv/env, failure records, pidfd signaling, both TTY phases, resource exhaustion/recovery and compiling guard mutants. The generated Sigil application in test-secure-spawn-app.sgl imports the fixed native provider and checks caught refusals and a real descriptor-only child lifecycle. These tests are ordinary nonroot executions and do not qualify privileged ID/capability transitions. Public image/report checks are separate from those kernel tests.

Barrier polling shares one bounded kernel timeout across ready/release. A readiness race that returns EAGAIN fails the launch instead of blocking.

Use atomic CLOEXEC pipes and descriptor copies; close descriptor ranges around the allowlist with close_range. The initial profile requires Linux 5.9 or newer for that operation and refuses an unsupported kernel rather than leave unlisted fds open. Descriptor remapping and temporary copies are planned in the parent so cycles cannot clobber sources. The executable fd and error pipe never reach the exec'd program. clone3 with atomic pidfd creation and execveat availability are qualification requirements, without a fallback to libc fork, pathname exec, or a later pidfd_open. The parent returns a typed process handle holding the CLOEXEC pidfd. A libc _Fork variant could be qualified separately, but would need an explicit race-free child-reaping contract if it cannot create its pidfd atomically.

Tests register hostile pthread_atfork handlers, exhaust/close descriptors, introduce descriptor-map cycles, cause each child-step failure, and verify that only allowlisted fds reach a fixture ELF. No atfork receipt may occur. Inspect the trampoline's call graph and negative controls, including a mutation to ordinary fork, signal delivery during clone/barrier, attempted inherited self-pipe writes, each credential/session phase, all saved IDs, and barrier timeout/EOF. The primitive can be linked by a native helper without linking the Sigil compiler or VM.

Runtime behavior after the hook

Secure mode preserves the hook's explicit dispositions and selected final mask; the empty mask is only the default when the hook selects none. Signals arriving during the hook remain pending, with the boundary set recorded in the immutable context. VM creation must not silently ignore SIGPIPE, and terminal helpers that install handlers or change process-global signal policy are unavailable. The runtime installs no crash handler, automatic stack/backtrace dumper, or crash-report file writer. Unrecoverable runtime failures use a fixed nonallocating diagnostic and _exit; explicit application error reporting must redact its own secrets. Before and after the hook, enforce non-dumpable state and a zero core limit; the second check covers credential changes that could reset dumpability.

No runtime initialization creates a thread, and the initial secure profile has no thread-create or background DNS resolver facility. APIs needing them are rejected by the capability preflight, including a transitive dependency that would create them lazily. Numeric-address and Unix-socket operations can remain in the single-thread profile. Native dependencies must obey the same contract; constructors and source evidence cover their hidden thread starts.

Every descriptor opened or duplicated by the runtime is CLOEXEC atomically: O_CLOEXEC, SOCK_CLOEXEC, accept4, pipe2, or F_DUPFD_CLOEXEC as appropriate. This includes file ports, sockets, resolver-free event sources, pidfds, temporary files, and spawn-error pipes. Only an explicit child descriptor map clears CLOEXEC in the child. Already-open caller descriptors are not silently claimed by the runtime; repaired stdio descriptors are the documented exception and the spawn plan still controls their inheritance. Test /proc/self/fd inventories at runtime and in an exec'd fixture, without assuming that setting CLOEXEC after open is race-free.

Inventory .fini_array, legacy .dtors, DT_FINI, and exit registration as well as initialization. Reject application/dependency destructor callbacks and automatic user finalizer/atexit registrations. Normal secure application completion takes the explicit runtime resource-release path and _exit, bypassing libc exit callbacks and CRT finalization; language exit cannot select ordinary libc exit. Known resource release may close owned ports and release memory, but must not dispatch arbitrary user callbacks. Audit any unavoidable CRT finalizer even though this exit path does not invoke it.

An automatic complete syscall allowlist is not an initial feature. The toolchain can publish an advisory catalog for the qualified runtime profile, and consumers can collect scenario-specific syscall traces for their own confined role. Such a catalog or observed trace is not an exhaustive proof for arbitrary native extensions and must not be advertised as a generated seccomp policy. Record its profile/source identity and completeness limits if supplied.

The built-in prologue and spawn trampoline instead have exact inventories. Use direct Linux syscalls for these paths, avoiding libc wrapper-dependent substitutions. For the initial x86_64 profile the prologue's closed syscall set is prctl, prlimit64, mprotect, getresuid, getresgid, rt_sigprocmask, setitimer, rt_sigtimedwait, rt_sigaction, rt_sigpending, fcntl, openat, fstat, dup3, close_range, fchdir, umask, close, write, and exit_group. Auxv access and pointer replacement make no syscall. The spawn parent/trampoline set is clone3, pipe2, fcntl, rt_sigprocmask, rt_sigaction, dup3, close_range, close, prlimit64, setgroups, prctl, capset, capget, setresgid, setresuid, getresgid, getresuid, umask, setsid, getgroups, setpgid, ioctl, fchdir, read, write, ppoll, execveat, and exit_group, plus parent-only fstat, pread64, mmap, mprotect, munmap, pidfd_send_signal, and waitid. Parent preparation checks the already-open regular ELF fd and copies bounded plan contents into private pages, seals those pages read-only, and releases them explicitly. The added memory and file-inspection calls are forbidden in the post-clone child. Parent handle cleanup, signaling and waiting use the atomically created pidfd; signaling uses pidfd_send_signal and reaping uses waitid(P_PIDFD), with no numeric-PID lookup or fallback. The parent requires SIGCHLD=SIG_DFL without SA_NOCLDWAIT before cloning so this handle owns the wait lifecycle. Child error exit uses the raw exit syscall selected by this single-threaded child contract, recorded as exit_group here. Each inventory maps names to architecture-specific syscall numbers, call sites, argument constraints and failure paths, separates parent from child, and binds the inspected object and source digests. Hook/application syscalls and libc/CRT startup are separate inventories. Compare complete call graphs and negative controls against these exact sets; unlisted syscall sites fail the build. An implementation needing another syscall must revise and review the list, not label this part advisory.

Libc before the hook

Audit the exact pinned libc and CRT source, not only ELF callback arrays. Static musl startup establishes environ, scans pointer entries to locate auxv, derives program-name metadata from argv/AT_EXECFN, initializes TLS and the stack guard, and under kernel secure execution can open the fixed /dev/null device to repair fds 0-2. This is an explicit unavoidable startup operation in the libc-based profile; it does not select code from an executable pathname. This audited fixed-device exception belongs in the receipt and consumer verification policy. A stricter zero-filesystem startup contract would require a separately reviewed custom CRT.

The pinned static-musl profile has no glibc dynamic loader or GLIBC_TUNABLES processing. No pre-main allocator/environment configuration consumer may be introduced. Dynamic glibc is outside this initial profile: its secure-execution filtering is loader-version-specific and must be audited for a setuid build, while a root-started equal-ID daemon can have AT_SECURE=0 and its loader can act before the hook. Treating init's environment as trusted is a different, weaker contract; a main hook cannot retroactively sanitize loader choices. The separate native helper owns its qualified libc/PAM startup and receives an explicitly clean environment.

In the pinned static x86_64 musl sources, CRT/TLS initialization installs no private signal handlers. The prologue resets kernel slots 32, 33 and 34 too: musl uses them for timers, cancellation and synchronized set-ID operations, respectively. Thread and POSIX timer creation are excluded from this profile. Single-thread libc set-ID wrappers do not install a synchronization handler. The standalone gate records the exact musl source digests and real ELF/symbol inventory, observes these slots before the prologue, and verifies post-entry libc setresgid/setresuid calls with unchanged real/effective/saved IDs. Separate slot-32 and slot-33 mutations must fail. This unprivileged control does not qualify credential transitions or a future threaded/dynamic-libc profile.

Runtime environment policy and ordinary binaries

Introduce one internal environment-policy accessor for implicit runtime configuration. In a secure runtime it always returns NULL, without calling libc getenv. In an ordinary runtime it does the same whenever Linux getauxval(AT_SECURE) is nonzero; ID mismatch and supported issetugid platform checks provide additional protection. The secure bit is never inferred from an environment variable and cannot be disabled later.

Route every implicit runtime getenv through this accessor: VM scheduling and tracing, profiling, GC tuning/debug/stress/statistics files, stdout buffering, module/compiler debugging, feature/check overrides, temporary-directory defaults, timezone-directory configuration, and test fault switches. Inventory raw getenv, environ, secure_getenv, and equivalent platform APIs so new direct reads cannot bypass the policy. Explicit application environment APIs (getenv, environment enumeration, child-process environments) remain explicit application operations after the hook, but the inherited environment is no longer installed then. The hook receives raw envp separately and must validate any fields it copies into the handoff. Discarding libc's ambient environment also prevents implicit locale/timezone options from surviving through libc calls that do not use Sigil's getenv wrapper. An application may deliberately construct its own environment after startup; that is a trusted application action, not an inherited runtime override. Child environments still require explicit construction, especially for a dynamically linked helper. The hook may validate a child-environment policy or copy selected values into the handoff, but its modifications to libc environ do not survive startup. The contract does not promise to preserve hook environment normalization. Automatic timezone-directory discovery and its setenv("TZDIR", ...) are skipped entirely under restricted execution; explicit application timezone operations retain their separately documented semantics.

For ordinary generated native entrypoints under kernel secure execution, suppress all environment/argv/relative code paths and bundle dispatch. Runtime imports are limited to registered modules, regardless of caller-added paths. The CLI, development entrypoints, and bytecode-only launchers refuse secure execution before interpreting argv or creating a VM. A fully linked ordinary native program can run using registered modules and runtime defaults; one needing a filesystem or appended bytecode dependency fails closed. Ordinary init-started programs with equal IDs and AT_SECURE=0 keep their current behavior and are not promoted to secure-entry programs.

The archive startup path constructor skips its work under kernel secure execution and is compiled out of secure runtime objects. Archive discovery and the non-Linux compiler-hash constructor likewise cannot run in a secure closure. Ordinary mimalloc must ignore environment options under kernel secure execution, including its raw early environ lookup, because blocking Sigil's own getenv is insufficient. Secure mode itself links the stock libc allocator and no mimalloc object, constructor, or environment reader.

Constructor and startup inventory

Each secure link produces an unstripped inspection image, linker map, and machine-readable constructor inventory before any optional strip operation. Inspect the final ELF, not only the source tree. Resolve every address and relocation in .preinit_array, .init_array, legacy .ctors, DT_PREINIT_ARRAY, DT_INIT_ARRAY, and DT_INIT; inspect .init and reject unknown initialization code. Reject PT_INTERP, DT_NEEDED, and IFUNC/IRELATIVE resolvers for the initial qualified static-musl closure. The test must fail on missing symbols, unresolved addresses, unsupported ELF forms, or unknown constructors.

The allowed initial inventory is only the pinned toolchain's audited CRT initialization, with its exact symbols and object provenance recorded from the actual link (for example frame_dummy and _init where emitted). It must have no environment, filesystem, or executable-path side effects. No Sigil, application, mimalloc, dependency, or sanitizer constructor is allowed. capture_exe_path_at_startup and sgs_capture_compiler_at_startup must be absent, not merely placed after another constructor. Deliberately adding a C constructor, preinit callback, or IFUNC resolver must make qualification fail. Changing the toolchain or constructor set requires an explicit reviewed inventory update. The checked inventory accompanies the executable so review can name every pre-main callback rather than just count callbacks.

The link also emits a .secure-entry.json receipt with schema/policy version, compiler revision and source identity, target/toolchain identity, optimization and allocator settings, fixed hook and entry names, sorted module names and source/object digests, a closure digest, final ELF digest, and the complete constructor/startup inventory. Bind the receipt to the final distributed ELF after stripping, retaining the inspection image and link map separately. Embed an immutable mode marker and closure digest in the executable. These receipts describe and bind a build; they do not replace trusted compiler provenance, review, or deployment authorization.

The marker generator in (sigil build secure-marker) emits a separate C unit after computing the input closure digest. Its retained .sigil.secure-entry section contains the mode, profile and digest as fixed NUL-terminated bytes. The input closure excludes this marker unit and the final ELF to avoid a hash cycle. Final inspection requires one exact marker in a read-only, nonexecutable file-backed mapping, including when section collection is enabled. Input-object provenance is a separate required gate; finding a marker alone does not qualify an executable.

Receipt format is UTF-8 JSON, schema version 1, with lexicographically sorted object keys, ordered module/symbol lists, no build timestamp, and digest strings in sha256:<64 lowercase hex digits> form. The main receipt has these required fields:

{
  "schema": 1,
  "mode": "secure-entry",
  "profile": "secure-native-v1",
  "target": "x86_64-linux-musl",
  "minimum_linux": "5.9",
  "spawn_primitive": "clone3-pidfd-execveat",
  "compiler": {"revision": "<revision>", "source_digest": "sha256:<digest>"},
  "config": {"name": "secure-release", "effective_digest": "sha256:<digest>"},
  "toolchain": {"identity": "<pinned identity>", "digest": "sha256:<digest>"},
  "allocator": "stock",
  "instrumentation": "absent",
  "thread_policy": "disabled",
  "ambient_environment": "discarded-before-hook",
  "entry": {"module": ["application", "main"], "procedure": "main", "hook": "application_entry", "hook_digest": "sha256:<digest>"},
  "handoff_schema": [],
  "context_schema_digest": "sha256:<digest>",
  "module_table_digest": "sha256:<digest>",
  "dependency_closure": {"digest": "sha256:<digest>", "roots": [["application", "main"]]},
  "disabled_features": ["compiler", "dynamic-loading", "eval", "expander", "ffi", "instrumentation", "load", "macros", "repl", "runtime-module-loading", "threads"],
  "hardening": {"static_pie": true, "full_relro": true, "runtime_relro": "read-only", "stack_protector_strong": true, "stack_clash_protection": true, "dynamic_symbols": "no-exported-or-undefined", "weak_undefined_symbols": "absent", "evidence_digest": "sha256:<digest>"},
  "closure_digest": "sha256:<digest>",
  "elf_digest": "sha256:<digest>",
  "profile_allowlist_digest": "sha256:<digest>",
  "forbidden_capabilities": {"result": "absent", "inventory_digest": "sha256:<digest>"},
  "artifacts": {
    "modules": {"file": "program.modules.json", "digest": "sha256:<digest>"},
    "symbols": {"file": "program.symbols.json", "digest": "sha256:<digest>"},
    "startup": {"file": "program.startup.json", "digest": "sha256:<digest>"},
    "runtime_state": {"file": "program.runtime-state.json", "digest": "sha256:<digest>"},
    "context_schema": {"file": "program.context-schema.json", "digest": "sha256:<digest>"},
    "syscalls": {"file": "program.syscalls.json", "digest": "sha256:<digest>"},
    "closure_tests": {"file": "program.closure-tests.json", "digest": "sha256:<digest>"},
    "link_map": {"file": "program.link-map", "digest": "sha256:<digest>"}
  }
}

Sigil owns this schema; application verifiers consume its fields without renaming or substituting an application-specific receipt. Required field semantics are:

FieldType and required meaning
schema, mode, profileInteger schema version 1, literal secure-entry, reviewed source/export profile identity.
compiler.revision, compiler.source_digestFull compiler commit and digest of the actual compiler sources, including local changes if allowed by qualification.
configSelected config name and digest of all effective resolved options/flags after overrides; its full value is retained in the build evidence.
target, minimum_linux, spawn_primitiveExact target triple, minimum qualified kernel, and fixed spawn implementation identity.
toolchainPinned compiler/linker/libc/CRT identity and closure digest.
allocator, instrumentation, thread_policy, ambient_environmentRequired stock allocator, absent instrumentation, disabled threads, and discarded ambient environment policy.
entryFixed entry module/procedure and hook symbol. hook_digest hashes the hook's linked code plus owned read-only data and relocations against resolved identities; source/object provenance is also retained. A missing hook has an explicit null symbol and digest for the built-in-only prologue.
handoff_schema, context_schema_digestOrdered application fields with types/bounds, plus SHA-256 of the complete canonical context schema sidecar, including ABI versions/byte sizes and immutable built-in identity/pending-signal fields.
module_table_digestSHA-256 of the exact ordered linked initializer/binding table, with relocations normalized to qualified module/symbol identities.
dependency_closureRoots and digest of the complete runtime module/native/object dependency graph in artifacts.modules, not just the entry package.
disabled_featuresSorted complete capability exclusions, checked against source/export and final-symbol evidence, including FFI and dynamic lookup.
hardeningEach required hardening setting and its independently checked object/ELF/runtime result; evidence binds flag records, inspected ELF ranges and runtime maps/write-fault controls. Required booleans are true, runtime_relro is read-only, dynamic_symbols is no-exported-or-undefined, and weak_undefined_symbols is absent.
closure_digest, elf_digest, profile_allowlist_digestInput closure, final distributed ELF, and exact reviewed profile allowlist SHA-256 digests.
forbidden_capabilitiesMandatory absent result plus digest of the module/object/symbol exclusion evidence.
artifactsFile and SHA-256 for each required sidecar: modules, symbols, startup, runtime state, context schema, syscall inventory, closure tests, and unstripped link map. File names are relative adjacent basenames, never arbitrary installation paths.

runtime-state.json inventories signal dispositions/final-mask policy, pending signal handling, crash/core policy, descriptor ownership/CLOEXEC, timers, threads/lazy initialization, allocation, finalizers and exit paths. Each item names its implementing source/object and qualification evidence. syscalls.json contains the exact prologue/spawn inventories and their code/source bindings; any runtime-wide advisory catalog is a separately labeled section. context-schema.json includes the complete public identity/builder ABI, version/byte sizes, built-in read-only fields, and ordered application schema; its artifact digest must equal context_schema_digest.

closure-tests.json contains one entry per named required adversarial test and mutation control: name (stable string), privilege_mode (one of unprivileged, forced-at-secure, real-setuid-vm, root-init-vm), source_digest, fixture_digest, closure_digest, result (pass, fail, or not-run), and mutation_result (an object with mutation name/source digest and detected, missed, or not-run). Preserve separate rows for different privilege modes. Test code, fixture binary, and tested closure identities are bound explicitly; results for one closure cannot qualify another. Required unrun cases remain visible and make the relevant privilege qualification incomplete. A build receipt can describe an unprivileged build without claiming VM qualification; a privileged installation verifier must require all tests for its intended privilege mode to pass with detected mutations. Subsequent signed qualification can bind the same ELF/closure without changing its immutable build inputs.

The example is pretty-printed; the writer sorts keys lexicographically rather than treating this example's display order as canonical. modules.json records every runtime module, entry/export and native primitive, source/object digests, linked object source profile, and dependency edges. Build-only syntax metadata is explicitly excluded from runtime exports. symbols.json names every retained symbol and its kind, section, address, object provenance, and allowlist classification. Its forbidden-capability result includes compiler, expansion/macros, eval/load, REPL, bytecode execution, dynamic module/source loading, and executable reader extensions, dlopen/dlsym, FFI, exported/undefined dynamic symbols and weak undefined symbols. Empty dynamic symbol tables are permitted. Data-reading symbols from reader.c are explicitly allowed. startup.json records CRT entry, TLS/stack initialization, initialization and finalization callbacks in execution order, absent dynamic-loader/IFUNC features, their source evidence digests, and the fixed-device libc exception. The link map binds those inventories to the actual unstripped link.

A consumer verifier rejects unsupported schema/profile versions, missing fields/artifacts, digest mismatches, a different expected hook/schema/module entry, unexpected compiler/toolchain/allocator settings, an unreviewed startup inventory, missing/failed hardening, incomplete required privilege-mode test results, or any non-absent forbidden capability. It recomputes the final ELF and sidecar digests before installation. The runtime does not read these sidecars at startup. The embedded closure digest covers inputs before the final link; the ELF digest lives only in the receipt, avoiding a hash self-reference. Receipt generation is a mandatory build gate, not optional documentation emitted after a successful link.

Qualification and rollout

New orchestration and ELF inventory drivers use (sigil shell). Native C fixtures create hostile exec state and assert the hook boundary; they are test payloads rather than an alternate scripting driver. Run the following matrix with an optimized secure executable and ordinary native controls:

CaseRequired evidence
Hostile environmentSIGIL_LIB, SIGIL_LIB_PATH, SIGIL_VM_*, yield/GC/debug/check/features, stdout, TMPDIR, TZDIR, MIMALLOC_*, and LD_* cannot select runtime behavior or execute a marker library. Clean and hostile runs agree.
HardlinkLink the unprivileged fixture into an attacker-controlled bin/ beside a forged lib/; neither its initializer nor a forged archive entry executes.
RenameExec a fixture, synchronize at its hook, replace its original pathname with a marker executable/archive, then continue. The original linked entry still runs. Repeat with rename churn.
ArgvDirectly test argc=0, NULL argv, and NULL argv[0] at the C entry boundary; no runtime/hook proceeds. Also record Linux's normalization of empty exec argv separately. Test huge argv at the OS limit and caller -L strings. Application-specific argument bounds belong in the hook.
DescriptorsTest each subset of closed fds 0-2 and preserved open fds. The hook checks access modes, device identity for repaired fds, and no leaked repair descriptor.
Signals/timersExec with ignored dispositions, blocked pending ordinary/realtime signals, and each armed itimer. Hook sees default dispositions, blocked mask, no inherited pending blockable signals, and disarmed timers. Test default empty and explicit final masks, preserve/record SIGTERM arriving during the hook, and ensure no runtime handler overwrites hook policy.
Hook orderNon-dumpable state and zero core limits precede caller-data handling. Hook observes all original real/effective/saved IDs and version/size, records success through a dedicated fd, and can refuse. No stdio/VM/module/allocator-environment initialization precedes it.
Code closureMissing/corrupt linked modules, computed imports, explicit file load, path insertion, changed cwd, modified/appended manifests, and compiler/debug entry requests fail without opening code files.
ConstructorsEnumerate the actual final ELF and provenance, verify absence of disallowed callbacks, and run constructor/preinit/IFUNC negative controls.
Ordinary controlOrdinary unprivileged programs keep existing load behavior; forced kernel-secure decisions ignore paths/options, allow complete linked closures, and reject CLI or incomplete closures.
Build refusal/cacheInvalid target/config/allocator/hook combinations fail, mode changes invalidate cached runtime/entry objects, and output cannot reuse a CLI base.

The unprivileged local suite interposes getauxval at fixture link time to force kernel-secure decisions, without a production runtime test switch. It is not an environment switch, CLI flag, or supported release config. Record exactly which rows use forced decisions; secure-entry fixtures need no simulated AT_SECURE because their policy is unconditional. Test real auxiliary-vector observation separately. Forcing a decision does not test kernel credential transitions, libc secure-startup behavior, loader filtering, or root execution. Actual setuid-root and file-capability qualification requires an isolated VM and separate authorization. Never install setuid fixtures on a development host. A successful local suite must not be reported as a real root test.

Run focused native and build-policy tests, then the complete Sigil test suite. Review changes to the runtime environment policy, prologue, module loader, allocator, emitted C, and final constructor inventory line by line. The user guide must explain the platform boundary and remaining PAM, identity, environment, descriptor, resource, configuration ownership, and child-exec responsibilities. Privileged deployment requires the qualified toolchain and application-specific security review; secure entry alone does not make an application safe against bugs in its own code or dependencies.

Privileged consumer contract mapping

The following maps the initial privileged consumer contract and its three runtime extensions to this proposal. These are design commitments, not claims of passed implementation tests.

RequirementDisposition and responsibility
1. Entry orderMet by the proposed prologue and linked hook. Raw argc/argv/envp, original IDs, and kernel state reach the hook before Sigil initialization. The general mode permits a built-in-only prologue; a consumer needing identity/resource policy must name its hook and verify that name in the receipt. Its own bounds, credential, and environment decisions belong in that hook.
2. No ambient loadingMet by fixed linked modules and registered-module-only imports. No eval/REPL/toolchain startup interface or file fallback is part of the secure closure. Native code deliberately loading another image remains application code requiring review.
3. Executing-image bindingMet by linking all modules and the fixed entry into the ELF. No image fd, archive pathname, trailer, or runtime manifest is needed.
4. AllocatorMet by enforcing stock allocation and excluding mimalloc objects. Runtime environment configuration is disabled unconditionally after the hook as well as before it.
5. Constructor inventoryMet differently by the narrow initial target: dynamic dependencies and IFUNC resolvers are rejected. Audit pinned static libc/CRT entry, TLS setup, callback order, and the final ELF, and reject unknown callbacks. No library may self-attest that its constructor is safe.
6. Runtime policyMet by a compile-time irreversible policy, independent of credentials or AT_SECURE, including root-started equal-ID daemons. PAM loading belongs in the separately exec'd native helper with a clean environment.
7. Production configMet by the explicit optimized config, stock allocator validation, named-hook receipt, compiler/module/closure digests, mode marker, and inventory. A consumer must require its specific hook even though the general toolchain can also build services needing only the built-in prologue.
8. Closure testsMet by the specified hostile-input, ELF inspection, and negative-control matrix, extended to huge argv and changed cwd. Locale/loader variables are included in the environment cases. Real setuid and root-started VM tests remain required qualification, separately authorized; forced unprivileged tests cannot replace them.
9. Typed immutable handoffMet by the versioned/size-checked saved-ID snapshot and static single-assignment bounded builder, sealed into a read-only context. Context schema and ABI evidence are receipt inputs; missing, duplicate or mutable context fails startup.
10. Launch primitiveMet by the raw clone3 atomic-pidfd plan and fixed callback-free execveat trampoline, including descriptor, credential/group, session/terminal and barrier phases. No libc fork fallback exists.
11. Post-hook stateMet by preserved explicit signal policy, no crash/debug/thread/finalizer machinery, atomic CLOEXEC, exact startup/spawn inventories and runtime-state evidence. The general runtime syscall catalog remains advisory.

The initial consumer uses the same static-pie musl hardening floor as this general mode, with a separately exec'd native glibc/Linux-PAM helper, each compiled for its own libc. If a dynamically linked Sigil frontend is mandatory, that needs a separately reviewed loader boundary before implementation can claim the same contract. A plain main hook cannot defeat LD_PRELOAD that a non-secure dynamic loader already processed.