Commit Graph

53 Commits

Author SHA1 Message Date
MechaCat02
0aa3eadca7 [Kernel] Add null-safe XThread::TryGetCurrentThread() accessor
The additive event_log extraction tracer needs a current-thread lookup that
returns nullptr instead of asserting when called from boot code before any
XThread exists (GetCurrentThread asserts on non-guest threads). New read-only
static accessor over the thread-local; no behaviour change. Fixes the native
Linux build of the phase-a args/file.read tracer.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:42:54 +02:00
The-Little-Wolf
dc4db67f9c [Kernel] - Change OddObj to X_DISPATCH_HEADER
- Change OddObj to X_DISPATCH_HEADER
- Add unknown X_KWAIT_REASON flag
- Fixed InitializeGuestObject mistake
- Replaces unknowns in kthread using nukernel as reference
2026-05-16 23:57:19 +02:00
Gliniak
80f2b535e9 [Kernel] Added KeSaveFloatingPointState and KeRestoreFloatingPointState from nukernel 2026-05-05 10:45:31 +02:00
Herman S.
65b74819aa [Threading] Implement priority boost on wake
When a thread wakes from a kernel wait, the Xenon scheduler boosts its
effective priority by the increment passed to the signaling call
(KeSetEvent, KeReleaseSemaphore, KeReleaseMutant). The boost is clamped
to the per-thread max_dynamic_priority cap, respects the guest
boost_disabled flag, and is drained on the next quantum expiry.
Guest KTHREAD priority fields are now initialized from parent process
defaults, and the previously unknown fields involved have been renamed
to match their identified purpose.
2026-04-11 17:05:05 +09:00
Herman S.
b3d8a21b72 [Threading] Add thread priority mapping with timer-driven quantum decay
And default ignore_thread_priorities to false.

Map Xenon's 0-31 priority range across all 5 host priority levels
instead of collapsing 0-17 into kNormal.

Use timer-driven quantum decay (~20ms period) matching Xenon's
60-quantum / 3-per-tick cycle to prevent starvation by gradually lowering
effective priority for non-real-time threads (< 18), piggybacking on the
existing 1ms timestamp timer.
2026-04-10 08:21:42 +09:00
Herman S.
8cd7f69cbc [Kernel] Fix macro collisions with macOS system headers
Rename IPPROTO_TCP/UDP/VDP enum values to XE_IPPROTO_* to avoid
collision with macOS <netinet/in.h> macros. Add #undef WAIT_ANY
guard for macOS <sys/wait.h> macro.
2026-03-27 00:11:59 +09:00
Herman S.
cb12f7fa1e [Build] Generalize POSIX platform guards
Most non-Windows code paths use standard POSIX APIs (sockets, signals,
dlopen, threading) that work on any POSIX platform. Change Linux-specific
guards to !WIN32 or #else where the code is portable. Linux-specific
APIs (SIGRTMIN, Vulkan/X11, fontconfig/GTK) remain Linux-guarded.
2026-03-26 23:10:47 +09:00
Herman S.
b24ea8ef99 [CPU/XThread] Add DWARF .eh_frame unwind info for JIT code on Linux
Generate per-function CIE+FDE records and register them via
__register_frame so the C++ exception unwinder can propagate through
JIT frames. Replace setjmp/longjmp fiber reentry with throw/catch
on Linux to ensure destructors and RAII guards run during fiber
stack switches.
2026-03-11 00:02:34 +09:00
Herman S.
f45a254774 [Linux/Threading] Self-suspend with condition variable instead of spin 2026-03-11 00:02:26 +09:00
Herman S.
22f21fada9 [XThread] Replace guest exception handling with setjmp/longjmp 2026-03-11 00:01:35 +09:00
Gliniak
7e1506ff23 [Kernel] XThread: Added mutex to set_name.
There is a small chance that game will spam requests for thread name change which will cause invalid free
2026-01-31 18:32:52 +01:00
Adrian
4702bfb94c [XBDM] Cleanup Stubs 2025-07-27 18:57:19 +02:00
The-Little-Wolf
39621ddec8 [KERNEL] - Replacing Unk
- Changes here are from Chrispy's Nukernel
2025-07-26 22:27:21 +02:00
Gliniak
e85c2392ba [Kernel] Implemented: KeSetPriorityThread 2025-05-12 21:10:35 +02:00
Xphalnos
5f918ef28d [Misc] Replaced const with constexpr where possible 2025-03-25 19:50:37 +01:00
Gliniak
b9061e6292 [LINT] Linted files + Added lint job to CI 2024-03-12 19:19:30 +01:00
disjtqz
a7b047b2a2 Implement kernel processes 2023-10-12 22:13:40 +02:00
disjtqz
d0a6cec024 total apc rework 2023-10-11 17:43:59 +02:00
disjtqz
b5ddd30572 moved xsemaphore to xthread.d
add typed guest pointer template
add X_KSPINLOCK, rework spinlock functions.
rework irql related code, use irql on pcr instead of on XThread
add guest linked list helper functions
renamed ProcessInfoBlock to X_KPROCESS
assigned names to many kernel structure fields
2023-10-11 17:43:59 +02:00
disjtqz
32f7241526 fix user apc/kernel apc mixup 2023-10-10 10:58:41 +02:00
Gliniak
9333373872 [Thread] Set pointer for: stack_kernel
Based on disassembly and info from console it is used to store initial thread data like:
 - start_address, context, etc.
2023-06-12 07:40:52 +02:00
chss95cs@gmail.com
2fa2f1a78c Add more wrapper functions to ppc_context_t in kernel, want to switch…
… over to referencing state through ppc_context as much as possible, it'll make implementing things like kernel processes much easier in the future

Move forward definitions of kernel types into kernel_fwd.h

Stub implementation of  XamLoaderGetMediaInfoEx
Partially implement XamSetDashContext
implement XamGetDashContext
Stub implementation of XamUserIsUnsafeProgrammingAllowed
Stub implementation of XamUserGetSubscriptionType
Expanded the supported object types for ObReferenceObjectByHandle and wrapped the logic for encoding the type in a constexpr function
ObReferenceObjectByName was taking lpstring_t for first param, but the function actually takes X_ANSI_STRING ptr

NtReleaseMutant actually does not return anything from KeReleaseMutant, it just checks the handle and returns whether it was invalid.

Changed the raise/lower irql functions to just set the irql on the pcr instead of setting it on field of Processor, processor is a shared object and irql is per-thread

Semi-stub implementation of KeGetImagePageTableEntry. I locked at it in the HV and got it so the values are in the same range the HV returns + actually reflect the page & memory range, but i doubt its equal to the values the hv returns on real hw. Used by modern dashboards, don't know for what.
Log error message for ObDereferenceObject w/ null ptr.

Allocate a special fixed page that dashboards reference, currently don't know what the data on that page is supposed to be.
Add current_irql field to X_KPCR
Added Device object member of XObject::Type enum
Added some notes about other gpu registers, found a table of register names and indices in xam
2023-04-23 10:39:52 -04:00
chss95cs@gmail.com
1f86dc0454 Check for and allow null critical sections, but log them.
stub XeKeysGetConsoleType
Removed the breakpoints in HandleCppException and RtlRaiseException until we have a real implementation of them. Some apps can continue fine afterwards.
Stub version of HalGetCurrentAVPack
Implement MmIsAddressValid
Implement RtlGetStackLimits
2023-04-16 17:34:46 -04:00
chss95cs@gmail.com
a63f424c0a Directly check PEB for IsDebuggerAttached
Add constexpr getters to magicdiv class so it can be used from jitted x64/dxbc
Track the guest return address as well for guest/host sync, if multiple entries have the same guest stack find the first one with a matching guest retaddr. this fixes epic mickey 2 (which the previous guest-stack change had allowed to go ingame for a bit) and potentially also a crash in fable3.
Break if under debugger when stackpoints are overflowed

Add much more useful output for host exceptions, print out xenia_canary.exe relative offsets if exception is in module, formatmessage for ntstatus/win32err, strerror

Minor d3d12 microoptimization, instead of doing SetEventOnCompletion + WaitForSingleObject do SetEventOnCompletion w/ nullptr so that the wait happens in kernel mode, avoiding two extra context switches

add unimplemented kernel functions:
ExAllocatePoolWithTag
ObReferenceObject

ObDereferenceObject has no return value.
Log a message when ObDereferenceObject/Reference receive unregistered guest kernel objects
gave ObLookupThreadByThreadId its correct error status
hoist object_types initialization out of ObReferenceObjectByHandle
Fix out parameter values on error for a few kernel funcs
add note about msr to KeSetCurrentStackPointers
add X_STATUS_OBJECT_TYPE_MISMATCH check for xeNtSetEvent
add msr_mask field to X_KPCR
2022-12-04 12:38:19 -08:00
chss95cs@gmail.com
90c771526d "Fix" debug console, we were checking the cvar before any cvars were loaded, and the condition it checks in AttachConsole is somehow always false
Remove dead #if 0'd code in math.h

On amd64, page_size == 4096 constant, on amd64 w/ win32, allocation_granularity == 65536. These values for x86 windows havent changed over the last 20 years so this is probably safe
and gives a modest code size reduction

Enable XE_USE_KUSER_SHARED. This sources host time from KUSER_SHARED instead of from QueryPerformanceCounter, which is far faster, but only has a granularity of 100 nanoseconds.

In some games seemingly random crashes were happening that were hard to trace because
the faulting thread was actually not the one that was misbehaving, another threads stack was underflowing into the faulting thread.

Added a bunch of code to synchronize the guest stack and host stack so that if a guest longjmps the host's stack will be adjusted.
Changes were also made to allow the guest to call into a piece of an existing x64 function.

This synchronization might have a slight performance impact on lower end cpus, to disable it set enable_host_guest_stack_synchronization to false.
It is possible it may have introduced regressions, but i dont know of any yet

So far, i know the synchronization change fixes the "hub crash" in super sonic and allows the game "london 2012" to go ingame.

Removed emit_useless_fpscr_updates, not emitting these updates breaks the raiden game

MapGuestAddressToMachineCode now returns nullptr if no address was found, instead of the start of the function

add Processor::LookupModule

Add Backend::DeinitializeBackendContext
Use WriteRegisterRangeFromRing_WithKnownBound<0, 0xFFFF> in WriteRegisterRangeFromRing for inlining (previously regressed on performance of ExecutePacketType0)

add notes about flags that trap in XamInputGetCapabilities

0 == 3 in XamInputGetCapabilities

Name arg 2 of XamInputSetState

PrefetchW in critical section kernel funcs if available & doing cmpxchg

Add terminated field to X_KTHREAD, set it on termination

Expanded the logic of NtResumeThread/NtSuspendThread to include checking the type of the handle (in release, LookupObject doesnt seem to do anything with the type)
and returning X_STATUS_OBJECT_TYPE_MISMATCH if invalid. Do termination check in NtSuspendThread.

Add basic host exception messagebox, need to flesh it out more (maybe use the new stack tracking stuff if on guest thrd?)

Add rdrand patching hack, mostly affects users with nvidia cards who have many threads on zen

Use page_size_shift in more places

Once again disable precompilation! Raiden is mostly weird ppc asm which probably breaks the precompilation. The code is still useful for running the compiler over the whole of an xex in debug to test for issues
"Fix" debug console, we were checking the cvar before any cvars were loaded, and the condition it checks in AttachConsole is somehow always false

Remove dead #if 0'd code in math.h

On amd64, page_size == 4096 constant, on amd64 w/ win32, allocation_granularity == 65536. These values for x86 windows havent changed over the last 20 years so this is probably safe
and gives a modest code size reduction

Enable XE_USE_KUSER_SHARED. This sources host time from KUSER_SHARED instead of from QueryPerformanceCounter, which is far faster, but only has a granularity of 100 nanoseconds.

In some games seemingly random crashes were happening that were hard to trace because
the faulting thread was actually not the one that was misbehaving, another threads stack was underflowing into the faulting thread.

Added a bunch of code to synchronize the guest stack and host stack so that if a guest longjmps the host's stack will be adjusted.
Changes were also made to allow the guest to call into a piece of an existing x64 function.

This synchronization might have a slight performance impact on lower end cpus, to disable it set enable_host_guest_stack_synchronization to false.
It is possible it may have introduced regressions, but i dont know of any yet

So far, i know the synchronization change fixes the "hub crash" in super sonic and allows the game "london 2012" to go ingame.

Removed emit_useless_fpscr_updates, not emitting these updates breaks the raiden game

MapGuestAddressToMachineCode now returns nullptr if no address was found, instead of the start of the function

add Processor::LookupModule

Add Backend::DeinitializeBackendContext
Use WriteRegisterRangeFromRing_WithKnownBound<0, 0xFFFF> in WriteRegisterRangeFromRing for inlining (previously regressed on performance of ExecutePacketType0)

add notes about flags that trap in XamInputGetCapabilities

0 == 3 in XamInputGetCapabilities

Name arg 2 of XamInputSetState

PrefetchW in critical section kernel funcs if available & doing cmpxchg

Add terminated field to X_KTHREAD, set it on termination

Expanded the logic of NtResumeThread/NtSuspendThread to include checking the type of the handle (in release, LookupObject doesnt seem to do anything with the type)
and returning X_STATUS_OBJECT_TYPE_MISMATCH if invalid. Do termination check in NtSuspendThread.

Add basic host exception messagebox, need to flesh it out more (maybe use the new stack tracking stuff if on guest thrd?)

Add rdrand patching hack, mostly affects users with nvidia cards who have many threads on zen

Use page_size_shift in more places

Once again disable precompilation! Raiden is mostly weird ppc asm which probably breaks the precompilation. The code is still useful for running the compiler over the whole of an xex in debug to test for issues
2022-11-27 09:39:33 -08:00
chss95cs@gmail.com
e21fd22d09 add x_kthread priority/fpu_exceptions_on fields, set fpu_exceptions_on in KeEnableFpuExceptions, set priority in SetPriority
add msr field on context
write to msr for mtmsr/mfmsr, do not have correct default value for msr yet, nor has mtmsrd been reimplemented
do not evaluate assert expressions in release at all, while still avoiding unused variable warnings
2022-11-06 11:03:10 -08:00
chss95cs@gmail.com
c1d922eebf Minor decoder optimizations, kernel fixes, cpu backend fixes 2022-11-05 10:50:33 -07:00
chss95cs@gmail.com
efbeae660c Drastically reduce cpu time wasted by XMADecoderThread spinning, went from 13% of all cpu time to about 0.6% in my tests
Commented out lock in WatchMemoryRange, lock is always held by caller
properly set the value/check the irql for spinlocks in xboxkrnl_threading
2022-10-15 03:07:07 -07:00
Gliniak
e9f1a534df [Kernel/Thread] Changed default stack location 2021-06-25 23:45:23 -05:00
emoose
052ce3d389 [Kernel] Make KeEnter/LeaveCriticalRegion only affect the caller thread
Adds a new X_KTHREAD::apc_disable_count field at 0xB0 into X_KTHREAD based on where 360 kernel seems to store it, and made CriticalRegion funcs act on that, instead of locking things between all threads, and changes DeliverAPCs to check that field before running the APCs.

XThread::LockApc/UnlockApc were also updated too as those previously called into EnterCrit/LeaveCrit to work, but AFAIK the code that uses LockApc/UnlockApc does have an actual need for locking between threads, so changed them to work on XThread::global_critical_region_ directly instead.
2021-06-25 23:11:14 -05:00
Joel Linn
a86d7173e1 Refactor FourCC magic uses
- Use new fourcc_t type
- Improves compiler compatibility by removing multi chars
2021-06-02 22:28:43 -05:00
gibbed
1513dd235b [Kernel] Code reentrance for guest fibers.
[Kernel] Code reentrance using exceptions for guest fibers.
2020-12-05 14:17:33 -06:00
gibbed
164aa8e8ca [Kernel] Scope object type enum. 2020-11-22 20:34:07 -06:00
Triang3l
a319617185 [Kernel] Thread affinity cleanup 2020-11-14 18:09:47 +03:00
Gliniak
2dc6b0b2ad [Kernel/Thread] Added missing paramteter to KeSetAffinityThread 2020-11-14 17:48:30 +03:00
gibbed
5bf0b34445 C++17ification.
C++17ification!

- Filesystem interaction now uses std::filesystem::path.
- Usage of const char*, std::string have been changed to
  std::string_view where appropriate.
- Usage of printf-style functions changed to use fmt.
2020-04-07 16:09:41 -05:00
gibbed
4cc2aaf5b9 Remove unnecessary usage of xe::be. 2018-05-27 16:35:01 -05:00
Dr. Chat
4c55039c22 Remove xenia-cpu dependency on xenia-kernel 2017-02-06 21:57:18 -06:00
Ben Vanik
6777ce6668 Reconcile debugger and save state stuff into a single implementation.
Fixes #497 and fixes #496.
Still rough edges, but at least less duplication.
2016-01-18 11:48:21 -08:00
Ben Vanik
948aa2400d Formatting all code. Too gnarly to rebase properly. 2015-12-29 13:13:34 -08:00
Dr. Chat
5cb591b993 Compensate for static TLS when accessing dynamic TLS. 2015-12-29 13:10:01 -08:00
Dr. Chat
bca5fb5382 XThread acquire mutants on restore 2015-12-29 13:10:00 -08:00
Dr. Chat
eee0bb070c Store thread TLS in guest memory rather than using host APIs 2015-12-29 13:09:58 -08:00
Dr. Chat
68f9949829 Make XObject::GetWaitHandle a protected function 2015-12-29 13:09:55 -08:00
Dr. Chat
621d3f8abb XThread free stack on destruction 2015-12-29 13:09:49 -08:00
Dr. Chat
6f4626118e Fix infinite loop in StepToSafePoint after stepping to an address once 2015-12-29 13:09:46 -08:00
Dr. Chat
4301641bdf XThread Save/Restore 2015-12-29 13:09:16 -08:00
Dr. Chat
666f5543a8 Cleanup ThreadState and XThread 2015-12-29 12:32:46 -08:00
Dr. Chat
7fc22f1987 Add a static kType field to all objects 2015-11-12 19:01:55 -06:00
Dr. Chat
3cbc65ac29 XThread Get/Set Last Error 2015-09-25 18:22:13 -05:00