Kernel: correct equeue event delivery and waiter lifetime (#723)

Ports the event-queue rework from the archived silent-hill-minimal branch
(968e9606, 9e3abb12, 2be9cfbf, f157a115) onto current upstream. The equeue
implementation had not been touched upstream since that branch forked, so
none of it had landed.

Behaviour fixed:

- Per-waiter event reservation. A blocked waiter used to wake on "the queue
  has any pending event" (TryWake => HasPendingEvents) and then re-read the
  queue on resume, so a woken waiter could find the event already drained by
  another waiter and park again with the wake consumed. Events are now
  reserved to the waiter they are delivered to.
- Level-triggered events are preserved instead of being cleared by an
  unrelated read; only events that declare clear-on-read reset their trigger
  state.
- Queued interrupts are bound to the registration generation that produced
  them, so an event registered after a queue was reused cannot consume an
  interrupt raised for the previous registration.
- Deleting an equeue now terminates its waiters instead of leaving them
  blocked on a handle that no longer resolves.
- sceKernelTriggerUserEvent stores its third argument in the event's udata
  (0x18) rather than its data word (0x10). The guest reads it back with
  sceKernelGetEventUserData, which loads 0x18, so every triggered user event
  previously read back as 0. This matches the reference behaviour in shadPS4,
  where TriggerEvent takes udata and sceKernelGetEventUserData returns
  ev->udata. The upstream test asserting the data word is updated, since it
  encoded the inconsistency rather than the ABI.

KernelPthreadState gains TryGetCurrentThreadIdentity and a new
KernelSyncTraceFormatter carries the shared, opt-in diagnostic formatting the
ported code calls; both are gated behind the existing trace flag and do no
work when it is off.

Tests: 662 pass, 0 fail (SharpEmu.Libs.Tests 588 -> 598).
This commit is contained in:
kuba
2026-07-31 11:13:15 +02:00
committed by GitHub
parent 82c2c7f48c
commit 816ec4ad27
6 changed files with 1393 additions and 139 deletions
@@ -156,7 +156,13 @@ public sealed class KernelEventQueueCompatExportsTests
Assert.Equal(eventIdent, BinaryPrimitives.ReadUInt64LittleEndian(evt[0x00..]));
Assert.Equal(KernelEventQueueCompatExports.KernelEventFilterUser,
BinaryPrimitives.ReadInt16LittleEndian(evt[0x08..]));
Assert.Equal(triggerData, BinaryPrimitives.ReadUInt64LittleEndian(evt[0x10..]));
// sceKernelTriggerUserEvent's third argument is the event's *udata*, not
// its data word: the guest reads it back with sceKernelGetEventUserData,
// which loads offset 0x18. Routing the payload to data(0x10) instead left
// sceKernelGetEventUserData returning 0 for every triggered user event.
Assert.Equal(triggerData, BinaryPrimitives.ReadUInt64LittleEndian(evt[0x18..]));
Assert.Equal(0UL, BinaryPrimitives.ReadUInt64LittleEndian(evt[0x10..]));
}
private static ulong CreateEqueue()
@@ -0,0 +1,151 @@
// Copyright (C) 2026 SharpEmu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
using System.Buffers.Binary;
using SharpEmu.HLE;
using SharpEmu.Libs.Kernel;
using Xunit;
namespace SharpEmu.Libs.Tests.Kernel;
public sealed class KernelEventQueueWaiterLifetimeTests
{
private const ulong BaseAddress = 0x1_0000_0000;
private const ulong HandleAddress = BaseAddress + 0x100;
private const ulong EventsAddress = BaseAddress + 0x200;
private const ulong OutCountAddress = BaseAddress + 0x300;
[Fact]
public void DeleteEqueue_CompletesStagedWaiterAsDeleted()
{
var (memory, ctx, handle) = CreateEqueue();
var waiter = StageGuestWait(ctx, handle, threadHandle: 0x701);
ctx[CpuRegister.Rdi] = handle;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_OK,
KernelEventQueueCompatExports.KernelDeleteEqueue(ctx));
Assert.True(waiter.TryWake());
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_DELETED,
waiter.Resume());
Assert.Equal(0u, ReadUInt32(memory, OutCountAddress));
Assert.False(KernelEventQueueCompatExports.IsValidEqueue(handle));
ctx[CpuRegister.Rdi] = handle;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND,
KernelEventQueueCompatExports.KernelDeleteEqueue(ctx));
}
[Fact]
public void DeletedGenerationWaiter_CannotConsumeNewQueueEvent()
{
var (memory, ctx, oldHandle) = CreateEqueue();
var oldWaiter = StageGuestWait(ctx, oldHandle, threadHandle: 0x702);
ctx[CpuRegister.Rdi] = oldHandle;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_OK,
KernelEventQueueCompatExports.KernelDeleteEqueue(ctx));
var newHandle = CreateEqueue(ctx, memory);
Assert.NotEqual(oldHandle, newHandle);
var expected = new KernelEventQueueCompatExports.KernelQueuedEvent(
Ident: 0x77,
Filter: KernelEventQueueCompatExports.KernelEventFilterUser,
Flags: KernelEventQueueCompatExports.KernelEventFlagClear,
Fflags: 1,
Data: 0x1234,
UserData: 0x5678);
Assert.True(KernelEventQueueCompatExports.EnqueueEvent(
newHandle,
expected));
Assert.True(oldWaiter.TryWake());
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_ERROR_DELETED,
oldWaiter.Resume());
Assert.True(
KernelEventQueueCompatExports.TryReservePendingEventForTest(
newHandle,
out var delivered));
Assert.Equal(expected, delivered);
ctx[CpuRegister.Rdi] = newHandle;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_OK,
KernelEventQueueCompatExports.KernelDeleteEqueue(ctx));
}
private static (FakeCpuMemory Memory, CpuContext Context, ulong Handle)
CreateEqueue()
{
var memory = new FakeCpuMemory(BaseAddress, 0x1000);
var ctx = new CpuContext(memory, Generation.Gen5);
return (memory, ctx, CreateEqueue(ctx, memory));
}
private static ulong CreateEqueue(CpuContext ctx, FakeCpuMemory memory)
{
ctx[CpuRegister.Rdi] = HandleAddress;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_OK,
KernelEventQueueCompatExports.KernelCreateEqueue(ctx));
return ReadUInt64(memory, HandleAddress);
}
private static IGuestThreadBlockWaiter StageGuestWait(
CpuContext ctx,
ulong handle,
ulong threadHandle)
{
var previousThread = GuestThreadExecution.EnterGuestThread(threadHandle);
var previousFrame = GuestThreadExecution.EnterImportCallFrame(
returnRip: 0x1_0000 + threadHandle,
resumeRsp: 0x2_0000 + threadHandle,
returnSlotAddress: 0x3_0000 + threadHandle);
try
{
ctx[CpuRegister.Rdi] = handle;
ctx[CpuRegister.Rsi] = EventsAddress;
ctx[CpuRegister.Rdx] = 1;
ctx[CpuRegister.Rcx] = OutCountAddress;
ctx[CpuRegister.R8] = 0;
Assert.Equal(
(int)OrbisGen2Result.ORBIS_GEN2_OK,
KernelEventQueueCompatExports.KernelWaitEqueue(ctx));
Assert.True(GuestThreadExecution.TryConsumeCurrentThreadBlock(
out var reason,
out _,
out var hasContinuation,
out _,
out var waiter,
out _));
Assert.Equal("sceKernelWaitEqueue", reason);
Assert.True(hasContinuation);
return Assert.IsAssignableFrom<IGuestThreadBlockWaiter>(waiter);
}
finally
{
GuestThreadExecution.RestoreImportCallFrame(previousFrame);
GuestThreadExecution.RestoreGuestThread(previousThread);
}
}
private static uint ReadUInt32(FakeCpuMemory memory, ulong address)
{
Span<byte> bytes = stackalloc byte[sizeof(uint)];
Assert.True(memory.TryRead(address, bytes));
return BinaryPrimitives.ReadUInt32LittleEndian(bytes);
}
private static ulong ReadUInt64(FakeCpuMemory memory, ulong address)
{
Span<byte> bytes = stackalloc byte[sizeof(ulong)];
Assert.True(memory.TryRead(address, bytes));
return BinaryPrimitives.ReadUInt64LittleEndian(bytes);
}
}