Commit Graph

10 Commits

Author SHA1 Message Date
DarthSidious666 de82c100cd Wire timers to real kernel wakes and make Rtl*printf format guest varargs 2026-09-09 15:33:09 +01:00
DarthSidious666 63bd70e582 Route all 371 kernel ordinals: complete the xbox kernel HLE
Fills in the remaining ~136 unrouted ordinals so every one of the 371 kernel
exports (347 function ordinals + 24 data exports) is routed:

- Add per-ordinal bridge_* functions for Dbg, Ex, ExfInterlocked, Fsc,
  Hal, Interlocked (fastcall), Io, Kd, Ke, Mm, Nt, Ob, Ps, Rtl, and
  port-I/O ordinals -- real implementations where the Win32 mapping is
  clear, documented stubs elsewhere (kept from silently no-op'ing to 0).
- Add a guest-VA -> host-HANDLE shadow table for in-guest kernel objects
  (KEVENT/KSEMAPHORE/KMUTANT) created via KeInitializeEvent/Semaphore/
  Mutant; KeWaitForSingleObject/KeSetEvent/KeWaitForMultipleObjects now
  resolve through it instead of treating a guest VA as a raw Win32 handle.
- New data-export bridges (KeInterruptTime, KeSystemTime, MmGlobalData,
  Ob type objects) at guarded KDATA offsets in the free kernel-data zone.
- Add every new ordinal to bridge_for_ordinal() and stdcall_args_for_
  ordinal() so stdcall stack cleanup stays exact.

Also fixes the kernel ordinal audit:

- test_bridge_ordinals.py anchored its regexes to the function definition
  ("static int stdcall_args_for_ordinal"), since the bridge file gained a
  comment mentioning the name and the old pattern matched that comment
  instead, silently skipping the whole check.
- README updated: 371/371 exports routed, kernel_bridge.c now 8,390 LOC.

Verified: test_bridge_ordinals.py passes all 8 checks (347 routes + 24
data exports = 371, zero missing); xbox_kernel builds and links clean.
2026-09-07 15:54:40 +01:00
sp00nz 0a8097e9e4 v0.7.0 "Non-Local": unwind across recompiled frames, fs: segment, kernel gaps
Control flow that leaves a function without returning from it, and the three
places the toolkit got it wrong.

Non-local jumps. A recompiled function is a real C function, so restoring the
guest esp is only half of a longjmp: the abandoned frames stay on the native
stack and control returns into them once the resume point finishes. Each guest
jmp_buf is now paired with a native one taken at the setjmp call site, the only
place a native setjmp is valid, so the frames actually unwind. The CRT's pair is
detected by the "VC20" cookie MSVC stamps into every jmp_buf.

Frameless callees inherited a dead frame: ebp is read through g_seh_ebp, but
only tail jumps and the SEH helpers ever wrote it, so one reached by an ordinary
call got whatever the last tail jump left behind. Published wherever g_ebp is.

The fs: segment prefix was dropped, putting the TIB at guest address 0 - where a
null pointer also lands. A null check written as "cmp byte [ecx], 0" read the
exception chain head's 0xFF and passed; a null store overwrote that head instead
of faulting. Segment overrides are recorded and based at XBOX_FS_BASE, leaving
page zero free for RECOMP_TRAP_NULL to trap.

Kernel exports implemented but never dispatched: RtlUnwind, XeLoadSection,
XeUnloadSection, NtSuspendThread. Each returned success without acting, which is
worse than a stub. NtSuspendThread was the costly one - a worker that parked
itself never stopped, spinning 289M kernel calls; now 9,789.

MCPX APU never started: the frame thread idles on pause_requested, which init
sets and only the test tone ever cleared, so a title enabling the APU through
SECTL/FECTL got an APU that stayed asleep.

cvtps2pi / cvttps2pi implemented; 36 sat inside one title's WMV decoder as
no-op comments.

New xbox_video library: Media Foundation FMV decode onto a D3D8 texture, plus a
window on the guest framebuffer. Orientation comes from IMF2DBuffer's pitch
sign rather than the RGB32 convention, which had the video upside down.

Diagnostics, since a recompiled title offers no debugger: tools/stackwalk.py
guest backtraces, RECOMP_WATCHDOG_SECS, RECOMP_TRACE_ARGS/DEREF, RECOMP_PEEK
and PEEK_CHAIN, RECOMP_WATCH_VA, RECOMP_PB_SCAN/PB_EXEC, RECOMP_FB_WINDOW.

Fixed: duplicate trace symbols broke the link for any title defining its own
recomp_trace_*; they now live once in the kernel.

Verified: 4639 + 211 conformance vectors 0 mismatches, 146 tests, Halo builds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
2026-08-31 09:36:29 -07:00
sp00nz 828058fded kernel: per-title ordinal remap -- one kernel serves any XDK
Phase 2 routing. The kernel bridge routes ordinals with one hardcoded
table, the ordinal ABI of the XDK it was written against. Titles built
with a different XDK number the same kernel functions differently, so
swapping such a title onto the shared kernel misroutes it -- Burnout 3
(XDK 5849) exited via HalReturnToFirmware during engine setup, where its
ordinal 49 is actually HalRequestSoftwareInterrupt.

Rather than refactor the three hardcoded tables (dispatch, arg-size,
data-export), this adds one translation layer. xbox_kernel_set_ordinal_remap
takes map[title_ordinal] = canonical_ordinal; xbox_kernel_bridge_init
applies it the moment it reads the ordinal, so all three lookups see the
canonical number. Identity by default -- a title that sets no remap, or
whose XDK already matches, is byte-identical. Verified: Halo still exits
3 at render_cameras.c:458, unchanged.

tools/kernel_audit/gen_ordinal_remap.py builds a title's map by matching
each function it imports to the ordinal the kernel's own table gives that
name. Halo (3911) and Crimson (5659) remap nothing -- they ARE the
canonical XDK. Burnout 3 remaps 47 and leaves 3 its parser could not name
as identity.

Result on Burnout 3, on xboxrecomp's kernel: it no longer exits during
engine setup. Ordinal 49 resolves to HalRequestSoftwareInterrupt (benign
stub), xbe_entry_point returns normally, the title enters its host loop
and begins loading crash-mode HUD textures. The specific routing blocker
is fixed.

One layer remains, and it is not routing: the init worker
PsCreateSystemThreadEx spawns runs but does not advance game state (zero
kernel calls from the worker stack region), even though xboxrecomp's
bridge_thread_main and Burnout 3's thread wrapper set the thread up
almost identically. That is a narrow threading-execution integration
difference, the next thing to chase.

This also corrects the record: Burnout 3's table is not "buggy", it is a
different XDK's correct table. xboxrecomp is ahead on kernel code, not on
the routing table, and the reunification keeps both titles' tables.

test_gen_ordinal_remap.py covers the generator; all kernel audit tests
pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 12:53:59 -07:00
sp00nz d7774d5088 kernel: "an xbox_* exists so the wrapper is mechanical" is false
Rebuilt Halo with the kernel fixes and it held: exit=3, still reaching
render_cameras.c:458, and PsCreateSystemThreadEx now genuinely spawns a
worker instead of running it inline -- the <stdlib.h> malloc truncation
fix taking effect.

Then wrote the 23 bridge wrappers for the ordinals Halo's thunk table
binds but the bridge did not route. Every one had a working xbox_*
behind it, so this looked like transcription. It crashed the title
EARLIER than the stubs it replaced, twice, with two different faults, and
both times presented as "0 assert sites" -- the trap run.sh warns about.

Bisected (11 -> 5 -> 3 -> 1) to a memory-model mismatch, not to argument
arithmetic:

  xbox_IoCreateDevice HeapAllocs from GetProcessHeap() and writes that
  NATIVE pointer through its out-parameter. The bridge hands it the
  native address of a 4-BYTE GUEST slot, so a 64-bit pointer goes into 4
  bytes -- clobbering the adjacent guest dword and leaving the title a
  truncated pointer it dereferences. The crash was a write to 0x90909090.

  xbox_ExFreePool calls HeapFree(GetProcessHeap(), P) on guest pool
  memory that was never on the host heap.

These functions were written for a native caller: host pointers, host
allocations. The bridge is a different world -- guest VAs, memory in the
mapped guest space. XBOX_TO_NATIVE converts an address; it cannot convert
an allocator.

So the wrappers are left in place and NOT routed, with the reasoning at
the call site, and tools.kernel_audit.coverage no longer calls category A
"mechanical". Routing one now requires checking which side owns the
allocation and whether any out-pointer must carry a guest VA. The Xc*
crypto group and RtlTimeToTimeFields only read/write bytes at a
caller-supplied address and should be fine; anything that allocates,
frees, or returns a pointer is not.

Halo is back at its best known state, verified: exit=3, milestones held,
render_cameras.c:458 reached.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 03:20:25 -07:00
sp00nz cd8151d336 kernel: data-export table had a shifted block, handing functions data addrs
Went to fix Halo's 29 unsized imports and found something worse in the
same file. kernel_data_va_for_ordinal is consulted BEFORE function
routing when thunks are built, so an ordinal listed there wrongly does
not merely mis-read a variable -- the title gets a data address for a
real kernel function and calls it, jumping into kernel data.

A whole block had drifted:

  17  -> ExEventObjectType slot, but 17 is ExFreePool        (function)
  65  -> IoCompletionObjectType,  but 65 is IoCreateDevice   (function)
  327 -> AlternateSignatureKeys,  but 327 is XeLoadSection   (function)
  328 -> XeImageFileName,         but 328 is XeUnloadSection (function)
  71  -> IoDeviceObjectType,      but 71 is IoFileObjectType
  326 -> XboxLANKey,              but 326 is XeImageFileName
  355 -> XboxLANKey again,        but 355 is XePublicKeyData
  356 -> AlternateSignatureKeys,  but 356 is HalBootSMCVideoMode
  357 -> XePublicKeyData,         but 357 is IdexChannelObject

Crimson Skies imports all four of those functions. In the other
direction the genuine exports at 16, 353, 354, 356 and 357 got no thunk
at all, so a title reading XboxLANKey or KeTimeIncrement read whatever
the function fallback happened to leave.

Fixes the table, adds the eight slots that had nowhere to live
(ExMutant/ExSemaphore/ExTimer/IoFile object types, KeTimeIncrement,
HalBootSMCVideoMode, IdexChannelObject, HalDiskCachePartitionCount), and
adds the 25 missing argument sizes Halo needed -- 7 verified against a
local xbox_* prototype, 18 from published signatures. Under-popping only
leaks, over-popping corrupts a live frame, so nothing uncertain was
guessed high.

Object types were all initialised to 0. That is wrong twice: a title
null-checking one sees "no such type", and ObReferenceObjectByHandle
compares an expected type against the object's, so with every type equal
to 0 a mutant handle passes a check meant for events. Each now gets a
distinct non-zero value.

Also: kernel_bridge.c was missing <stdlib.h>, so C89 implicit declaration
made malloc return `int` and bridge_spawn_thread TRUNCATED its heap
pointer to 32 bits before storing it as a struct pointer. Every field
write then landed somewhere unrelated to the allocation. That is the
PsCreateSystemThreadEx path, which is the one Halo currently papers over
by running workers synchronously. MSVC reported it as C4013 + C4047 and
this file builds /W4 /WX-.

Two new audit tests, because the existing ones covered the routing and
arg-size tables but not this one:
  data_exports_match_their_ordinal          -- every entry vs the export table
  no_data_export_ordinal_is_also_a_function_route -- the tables must not overlap
The runner is now discovery-based; the tests I appended were defined
after the hand-written call list and silently never ran.

  unsized imports   Halo 29 -> 0   Crimson Skies 20 -> 0   SB retail 3 -> 0
                    SB debug 32 -> 5 (KdDebuggerEnabled, IoQueryVolumeInformation,
                    IoDismountVolumeByName, RtlWalkFrameChain, RtlAssert)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 03:11:23 -07:00
sp00nz 0eb45c14cf kernel: make every unhandled import stack-safe, and audit coverage per title
Standing up the Crimson Skies kernel layer. The headline "86 of 147
imports missing" turned out to be three very different problems wearing
one number, so this adds tools.kernel_audit.coverage to split them:

  handled (bridge or thunk)   what already works
  needs a bridge_ wrapper     an xbox_* exists; mechanical
  data export                 needs a value, not a function
  no implementation           real work

For Crimson Skies that is 79 / 65 / 0 / 3, not 61 / 86.

The number that actually mattered was none of those. kernel_bridge.c
keeps an argument-size table separate from its dispatch table, so an
unrouted ordinal is normally harmless -- the generic stub cleans the
right number of bytes off the simulated stack and returns 0. Twenty of
Crimson Skies' imports had NO size entry, so calling any of them would
have popped the wrong amount and corrupted the stack for everything
upstream. That is a silent, far-from-the-cause failure, and it is not
visible as "missing kernel function".

Adds those 20 sizes, taken from the xbox_* prototypes in src/kernel
rather than guessed. Two are __fastcall (IofCallDriver,
IofCompleteRequest) and therefore take ZERO stack bytes -- sizing them
by argument count would have been worse than leaving them out.

Crimson Skies now has 0 unsafe imports, up from 20.

Also fixes two comments in kernel_bridge.c that were off by one against
the export table -- "case 17: DATA export - ExEventObjectType" (17 is
ExFreePool; 16 is ExEventObjectType) and "case 65: DATA export -
IoCompletionObjectType" (65 is IoCreateDevice; 64 is the data export).
Stale-but-plausible commentary in this file is exactly what
test_bridge_ordinals.py was written after.

And fixes a false gap the tool itself introduced: data exports resolve
in kernel_thunks.c, not the bridge, so checking only the bridge reported
all 18 of Crimson Skies' as missing when every one was already handled.

Cross-checked against the other titles, which are NOT yet safe:

  Crimson Skies      147 imports   79 handled    0 unsafe
  SB LOC retail      144 imports   80 handled    3 unsafe
  Halo 2276          166 imports   76 handled   29 unsafe
  SB LOC debug       188 imports   82 handled   32 unsafe

Halo's 29 are worth attention: that project is being actively debugged,
and a wrong-sized stub is the kind of fault that shows up as corrupted
callee-saved registers a long way from the call.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 02:52:43 -07:00
sp00nz c3e83b716a kernel: fix a missing stdcall arg size, and model NV2A W1C/idle registers
Three fixes, all found by one hang in Halo's D3D device init.

1. Ordinal 47 (HalRegisterShutdownNotification) had a bridge but no entry in
   stdcall_args_for_ordinal, so it fell through to `default: return 0` and
   leaked 8 bytes of arguments on every call. D3D's CMiniport::InitHardware
   calls it once; esp came back 8 low and the epilogue's pop edi/esi/ebx each
   read one slot too far down. `this` for the next call became 1, the DMA
   channel was initialised against garbage, and the title hung in a
   push-buffer wait with nothing connecting it back to a stdcall size.

   test_every_routed_ordinal_has_an_arg_size now fails on any bridged ordinal
   with no arg entry -- the existing comment-matching test could not see this
   one, because there was no entry to disagree with. It immediately found a
   second, pre-existing case: ordinal 188 NtCreateDirectoryObject.

2. Interrupt status registers are write-1-to-clear. An ISR acknowledging one
   writes the pending bit back, and against plain RAM that sets it instead, so
   the interrupt never clears. CMiniport::ServiceGrInterrupt acknowledged
   PGRAPH_INTR, read it back still pending, and recursed until the native
   stack was gone. Held at zero, which is the truth: nothing raises GPU
   interrupts here.

3. Queue-empty bits are the mirror image and must read as SET, because nothing
   is queued. CMiniport::TilingUpdateIdle spins until the PFIFO caches report
   empty, so tile setup during InitializeFrameBuffers never finished.

Also restores the PFIFO DMA_PUT -> DMA_GET mirror removed in the previous
commit. It was removed because [dev+0x2304] read as garbage, i.e. no register
to acknowledge -- but that garbage was fix 1's symptom. With the arg size
corrected the pointer is 0xFD800000 and the mirror is correct.

Halo now completes D3D device init, allocates its framebuffers, and runs on
into tag loading.
2026-07-20 05:17:32 -07:00
sp00nz 9b62670379 kernel: re-key the stdcall argument table; audit it against the exports
The bridge has two parallel tables - ordinal->function and ordinal->argument
bytes - and fixing the first did not fix the second. Ordinal 67 was routed
correctly to IoCreateSymbolicLink while its argument entry still read
"40; /* IoCreateFile(10) */", so every call popped 40 bytes instead of 8 and
walked esp 32 bytes off.

That failure does not show up where it happens. It surfaces much later as a
function returning with ebx/esi/edi restored from the wrong stack slots, which
looks nothing like a wrong stdcall size - it looks like the lifter mistranslated
register preservation.

Auditing the whole table against KERNEL_EXPORTS found 39 entries filed under
the wrong ordinal, in the same shifted blocks as the routing table: Io, Ke, Nt
and the entire Xc crypto range. Each entry's value and comment are internally
consistent - they were simply keyed wrongly - so they are re-keyed by the
function named in the comment rather than re-derived, which is mechanical and
checkable. 35 moved, 99 already correct, no collisions.

test_bridge_ordinals.py now checks this too: every argument entry must be
commented with the function its ordinal actually names. That is what catches
this class, and it would have caught ordinal 67 immediately.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 01:55:17 -07:00
sp00nz 25cf8a6ea9 kernel: fix 7 misrouted ordinals; add EEPROM + firmware-return bridges
The bridge dispatch table in kernel_bridge.c maps ordinals to bridge_<Name>
wrappers by hand, and nothing tied those numbers to the real export list. A
block had drifted by one. Cross-checking every route against KERNEL_EXPORTS in
tools/xbe_parser (which matches the published table) found seven wrong:

  14/15  ExAllocatePool, ExAllocatePoolWithTag   (were 15/16)
  23     ExQueryPoolBlockSize                    (was 24)
  9      HalReadSMCTrayState                     (was 47)
  66/67  IoCreateFile, IoCreateSymbolicLink      (were 67/63)

These did not fail loudly - they returned plausible values from the wrong
function, which is what made them expensive. Halo called ordinal 24 expecting
EEPROM settings and got a pool block size; it called 67 to mount D: and got
IoCreateFile's STATUS_OBJECT_PATH_NOT_FOUND. The stdcall argument sizes were
shifted the same way, so those calls also popped the wrong number of bytes.

Adds the two bridges Halo needs, whose implementations already existed with no
wrapper to reach them: ExQueryNonVolatileSetting (24) and HalReturnToFirmware
(49). The latter never returns on hardware, so returning let the title run on
past its own decision to quit and read as a hang.

tools/kernel_audit/test_bridge_ordinals.py locks this down: every route must
match its ordinal, no ordinal routed twice, and every stdcall arg size a whole
number of dwords. KeSetTimerEx->KeSetTimer is listed as a known, deliberate
approximation rather than passing silently.

Also wires up recomp_icall_fail_log() in templates/runtime/recomp_types.h. The
hook was declared and implemented but never called, so an unresolved indirect
call zeroed eax and continued - indistinguishable from a function that
returned 0. That is exactly how Halo's main thread appeared to "run and return
cleanly" while never entering game code.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 00:24:13 -07:00