Neverhood original LS thunk / kernel / loader boundary (2026-11-13)

The missing boundary is an owned LS connection and pointer-mapping service, preceded by Win9x NE notification support. The basic far call/RETF and QT return primitives already exist. ThunkConnect32 currently supplies only EAX=1 and ESP+=28; that does not connect the original modules. No small general pure-host loader/selector lifetime defect was proved, so no production repair was made. NO_NATIVE_RESULT; original installation, first room and gameplay remain OPEN.

Read with original DSETUP6E contract and DSETUPE attach/setup. Evidence: scratch/runs/20261113-neverhood-thunk-kernel-2520/. Source baseline is main d657937245231f67227486d7eca59edcb5671f50, plus recorded relevant incoming diff. All source findings concern that pinned tree, not an observed original runtime failure. No media, kernel binary or proprietary dependency was fetched; only sealed2460/2320 selected byteframes and public Wine implementation excerpts were read.

Concrete original contract

Sealed byteframes agree on LS01, checksum DWORD 0x2e32. PE data is preferred VA 0x10009578, NE data export ordinal1 is segment6:002e. The latter's pointer at +8 relocates to segment3:0000, a four-entry table of relocated far pointers. Index1 selects 2:1792 EXECUTEINF; index2 selects 2:12fe DSETUPINSTALLDEVICEDRIVER. Module-local segment numbers are not runtime selectors.

The PE CRT entry 0x10004930, then application DllMain 0x100046b0, calls ThunkConnect32(data32, "thk3216_ThunkData16", "dsetup6e.dll", "dsetupe.dll", hModule, reason). Its return is a real attach gate. The indirect pointer 0x10004719 initially points at 0x1000959c, 32 bytes of CC padding. Data32+0x1c/+0x20 contain 0x24/0x44, locating the QT relay and FT prolog relay areas relative to data32. The second pointer at 0x1000471d points at the latter. The proved selector1/2 stubs use the first pointer. No FT structure-conversion path is proved by those calls.

NE header CS:IP is 1:0054; its startup eventually calls LibMain 2:00a4, which returns AX=1. Separately, DLLENTRYPOINT ordinal2, 2:00ba, returns retf 0x10. It calls helper 3:0010, which inserts data16/name32/CS and tail-jumps through the relocation KERNEL!#651. At that API entry: return IP/CS at SP+0/+2; helper CS at +4; name32 far pointer +6; data16 far pointer +0x0a; reason DWORD +0x0e; instance WORD +0x12; DLL-name pointers +0x14/+0x18. Arguments total 24 bytes. This is distinct from the notification's own 16-byte argument area and the PE connection's six DWORDs.

Selector1 maps PE argument2 at EBP+12, pushes the far pointer and low HWND WORD, and reaches an NE 6-byte Pascal argument area (retf 6). Selector2 maps four pointers at EBP+12/+16/+20/+24, retains four DWORDs and low HWND, and reaches 34 bytes (retf 0x22). After return, the original PE stub sign-extends AX for index1; index2 reconstructs EAX from DX.low16:AX.low16. Matching unmaps must preserve that result. The original PE cleanup remains ret 8 / ret 0x24.

Actual loader and ownership chain

Boundary Existing implementation and concrete limit
PE mapping and attach src/08b-dll-loader.wat:$load_dll reads AddressOfEntryPoint and returns load-base+entry RVA, not exported DllMain. lib/dll-loader.js:loadDll, initializer ordering/import patching, beginScopedDllMain and dllMainSteps surround it with generation pins and the callback gate. The three-DWORD callback is hModule/reason/reserved; clean return requires both sentinel EIP and restored ESP. finishDllInitialization rejects incomplete or FALSE attach and retains quarantine for incomplete callbacks. None of this makes the current TRUE-only ThunkConnect handler meaningful.
Nested host service dllMainSteps recognizes yield18 as well as DLL-load yields. lib/process-boot.js:handleLoadLibraryYield / serviceLoadLibraryYieldSync take the same callback gate before dispatching lib/ne-guest-bridge.js. Request operations are LoadLibrary16, FreeLibrary16, GetProcAddress16 and QT only. A connection needs its own owned request/continuation; it cannot call a host loader synchronously from inside a running WAT handler or silently reuse LoadLibrary16's result settlement.
First proved NE admission boundary lib/ne-image.js:inspectNeDll rejects expected Windows version >=0x0400 with NE DllEntryPoint lifecycle is not implemented. The original header's WORD at file 0xbe is exactly 0x0400. Calling the actual inspector on the sealed 640-byte header/table prefix produces that diagnostic before segment extent validation. Lowering only that version reaches a later file-range error; the prefix is not a complete admitted image. This proves the current Win32-owned route rejects the original layout, without executing it. Removing the guard alone would bypass an intentional missing lifecycle.
NE imports and initialization prepareNeSources and createNeLifecycle preflight the dependency closure, acquire references, stage under leases, call the header initializer, and publish only after nonzero AX. KERNEL/USER are fixed host module identities; VER/LZEXPAND have fileless dynamic identities with owned references; SETUPX is neither builtin class and needs an actual image or a separately implemented API service. A KERNEL ordinal can be admitted without having an implementation; admission is not coverage.
NE relocation/data lookup $win16_apply_relocs resolves internal references using each module's segment-index base; ordinal imports get WIN16_THUNK_SEL:slot records holding module/ordinal. $win16_dll_entry returns packed selector:offset for both code and data; $win16_dll_data_sel reads automatic DS from header +0x0e; $win16_dll_init_entry reads CS:IP at +0x16/+0x14. Name lookup scans resident and nonresident tables and folds both operands to uppercase, despite stale comments claiming case sensitivity. The mixed-case PE request can match the uppercase original data-export name. Data export lookup must not use lifecycle.call(), which enters code and rejects a data selector.
NE teardown createNeLifecycle.releaseOwned invokes WEP by name with WORD0, then final release and dependencies. Failed termination retains ownership and permits explicit retry. Module records refuse final unload while active calls are pinned; $win16_dll_unload returns segment/metadata allocations. There is no separate Win9x DLLENTRYPOINT attach/detach implementation in this lifecycle. A connection holding table pointers must retain the NE image until all PE relays/calls have retired. A lookup return alone grants no execution lifetime.

The old pure-NE loadWin16Dlls / queued LibEntry route is not a way around these requirements. It stages modules for a task already in Win16 mode and queues the header initialization; it neither connects these PE relays nor supplies Win9x notifications. No alternate runtime route is claimed.

What the far bridge already does

src/05c-seg16-ops.wat:$win16_far_transfer recognizes far calls and tail JMPs into the synthetic API selector. Thus the original helper's far JMP is already a supported dispatch shape; it is not missing a generic far-JMP instruction. $th_retf16 consumes IP/CS plus immediate cleanup, and dispatches returns into the reserved thunk selector as continuations. $win16_set_sreg and descriptor flags select segment bases and code width; this is an emulator context switch, not a host-native function call.

src/09e-win16-api.wat:$win16_bridge_frame_begin/end save/restore registers, EIP/decode state, segment registers/bases, width, flags, yields, error and FP/SIMD state. Tokens bind frame generation and owner; two arena slots and an execution lease prevent recycling/borrowing. invoke_target validates code ownership and pins the ready NE module under DLL_LOAD_LOCK. frame_end drops its active-call pin, restores the overwritten PE return slot for QT, revokes the alias, restores the caller, and releases the backing lease. Existing receipt/gate/pin protocols remain intact.

The ordinary invokeNeEntrySync argument vector is limited to 16 WORDs in both JS and WAT. It is useful for startup/notification-sized frames; selector2 needs 17 WORDs, so copying it through that interface is rejected. This is an interface bound, not a reproduced corruption defect and not a reason for a generic thunk rewrite.

The actual QT_Thunk API exists (src/09a0-handlers-base.wat:$handle_QT_Thunk). It takes the target in EDX, parks request4/yield18, and invokeNeQtSync enters $win16_bridge_qt_begin. This path aliases the original PE stack rather than using the bounded copied-word vector. planNeQtStack requires one even, contiguous, mapped 64KiB-aligned window and sufficient scratch; native stack leasing additionally requires fixed main-stack backing or owned virtual-map pages, deliberately excluding unowned heap/fallback stacks. QT sets the far return sentinel over the existing four-byte return slot, preserves BP-relative scratch identity, and pins the actual executable target.

On actual RETF, $win16_bridge_invoke_return checks SS and even, bounded final SP. QT captures EAX, EDX, ECX independently and the adjusted linear SP. win16_guest_qt_settle restores the context first, revalidates the parked request, merges those outputs and resumes its original PE return address. The ordinary invocation result also captures low DX:AX, but its host result is not a substitute for QT's independent registers and real stack adjustment. Consequently a basic cross-mode return primitive is present; no new invented TRUE/combined-result return bridge is warranted.

Missing binding and LS mappings

Public Wine source, pinned to cc5d1d86ee7d60649e6f858106db046c77c8b12c, corroborates an implementation route rather than Microsoft kernel behavior. Its LS connection implementation loads the NE, checks thunk identity/checksum, obtains its relocated target table and writes index-selecting QT/FT relays. The QT relay reads the saved index at EBP-4, loads the selected far target into EDX and jumps to QT_Thunk. Its LS ThunkConnect16 branch does no extra mutation after format validation; demanding symmetric writes would be unjustified. That limited LS behavior cannot justify unconditional success for every #651 call or skipping the original notification.

The missing PE connection is therefore resolve + retain + validate + publish the real table/guest relay, not a BOOL. The existing handler has no call, dependency reference, identity comparison, data mutation or relay. The generated ordinal map lacks KERNEL651 and the actual Win16 API dispatcher has no ThunkConnect16 implementation. Adding an ordinal name alone does not dispatch anything.

Wine's selector implementation demonstrates the other missing ABI: the EBP helpers read a register-relative slot, return a far value in EAX, record unmap state in the slot, and matching unmaps preserve EAX and clear that state. Low integer/null values need special handling. Mappings have references and alias the same bytes. These are zero-stack-argument, register-sensitive routines, not ordinary one-pointer stdcall adapters. All ten imported EBP8/12/16/20/24 map/unmap names are absent from the current API table.

Existing $win16_alias_of allocates another selector over an existing selector's base/limit; it supplies neither arbitrary flat-pointer lookup nor scoped unmap state. $win16_far_to_guest is the opposite direction: table base plus low16 offset, without independent lifetime validation. SetSelectorBase/descriptor setters and QT's stack alias are lower-level ingredients, not MapLS. Wine's 32KiB-window policy must not be copied into this interpreter's documented 64KiB segment-base invariant without auditing offset/return arithmetic. Mapping a PE guest address must preserve guest address identity, mapping bounds and backing ownership; a host ArrayBuffer offset is not a guest far pointer. An LS string alias is also not covered by QT's stack-only lease.

For lifecycle corroboration, Wine's NE notification source separately calls version4 DLLENTRYPOINT with eight WORDs: nearest return are reserved WORD, reserved DWORD, heap, DS, instance, reason DWORD. This agrees with original BP+0x10/+0x12 reads. Its comments acknowledge incomplete FALSE handling; do not import that limitation as a success policy here. Public implementation excerpts and full-file hashes are retained; no public source tree archive was made.

Bounded implementation path and stop condition

  1. Extend the existing owned NE lifecycle with version4 notification ordering, its exact eight-WORD frame, failure/rollback and detach ownership. Keep the admission guard until that works. Bind #651 with its 24-byte Pascal frame, validating LS identity and original notification state; do not conflate this with the header LibMain or WEP.
  2. Implement a connection request within the existing PE callback transaction: preflight/stage through existing NE services; retain the NE image; resolve the data export; verify LS01/checksum, relocated table bounds and relay offsets. Publish table/relays only after prerequisites succeed. Use relocated guest addresses and guest API thunk addresses, never host C/function pointers. Preserve the original DLL's code and generated argument stubs. Connection references, PE generation and active calls must survive nested work; partial failures must revoke unpublished work, and detach must retire relays before releasing the NE table. Do not alter existing callback retirement protocols to make this convenient.
  3. Add scoped LS map/unmap services for the proved helpers with register/slot/result semantics, null handling, same-byte aliases, exhaustion/failure and nested reference accounting. Cover module-backed globals and owned heap/virtual buffers explicitly; pinning a DLL image does not pin an unrelated heap allocation. Revoke aliases before releasing backing. Leave unsupported spans/lifetimes diagnostic rather than copying strings into guessed temporary segments.
  4. Route the generated QT relay to the existing QT API. Preserve 6/34-byte callee cleanup and independent AX/DX through unmaps, letting the original PE reconstruction run. Static planner checks below show these frame sizes fit the existing shape; they do not prove runtime bridge composition. Future authorized focused runtime must observe the original target entry, DS, pointed-to bytes, return registers/SP and teardown, with bad-checksum, stale-module/alias, wrong-SS/cleanup and nested-failure controls, then the locked build before any code commit.

Stop at SETUPX and original downstream behavior after that. EXECUTEINF calls IpOpen/GenInstall/IpClose but does not prove initialization of its returned local WORD. The driver resolves five original SETUPX function pointers; its branch-local1 ignores DiCallClassInstaller's returned AX. Neither is permission to replace the original driver or manufacture installation success. No new proprietary dependency recovery or execution is authorized by this note.

Verification and release

check-boundary.cjs verifies both prior manifests (93 artifact seals), all 45 retained window hashes, exact original header/table/cleanup/relay data, actual inspector rejection and planner behavior, and selected actual-source bodies. It performs 96 checks and six negative controls. Existing pure test-ne-image.js and test-ne-qt-stack.js also pass. No mock guest run or fake bridge test was added. The changed-version control reaches the subsequent range error, wrong magic fails earlier, and cross-window/hole controls exercise the actual planner. Source mutation controls reject a hypothetical binding or changed TRUE body; they do not prove implementation correctness. Test children have independent timeout/kill/wait supervision, with a real deadline control and captured exits.

Git SHA, incoming status, relevant binary diff, source hashes, task-only/new-note patches and reverse reconstruction checks are in the run directory. Only this note is committed. No production or test file outside that directory was edited, and incoming DLL/NE/Host/RPC/Manager/GPU work is preserved. Docs diffcheck and strict pull/push are publication checks; no full build or focused guest runtime is claimed. Box ID none; NOT_CREATED; expiry null; stop N/A. No Worker, Machine/CPU, guest/VM/WASM/native/browser/game execution, box, resource/reserve work, other worker or general cleanup. Ownership is released after publication, then this single-task worker stops.