Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -759,7 +759,11 @@ set_tests_properties(startup_present_signature_unheld_source_control_warp PROPER
if(EXISTS "${INTAKE_PYTHON}")
add_executable(startup_present_producer tests/startup_present_producer.cpp)
target_compile_features(startup_present_producer PRIVATE cxx_std_17)
target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi)
target_include_directories(startup_present_producer PRIVATE src)
target_link_libraries(startup_present_producer PRIVATE d3d12_xs_shim d3d12 dxgi user32)
add_test(NAME startup_output_window_close COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_output_window_close_check.py" "$<TARGET_FILE:startup_present_producer>")
set_tests_properties(startup_output_window_close PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45)
foreach(backend IN ITEMS warp hardware)
add_test(NAME startup_present_producer_${backend} COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/startup_present_producer_check.py" "${backend}" "$<TARGET_FILE:startup_present_producer>")
Expand Down
7 changes: 7 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ column. The same pipeline translated with pairing by number reads COLOR and fail
## Output window and fallback diagnostics

The desktop swap chain has its own top-level window, class `X2WOutputWindow`.
With `run.ps1 -Render`, Close asks the launcher to end the child in its Windows job.
The debugger waits for the child process to exit before returning. Minimize keeps the
session active. In a direct shim host, Close hides the output and leaves the host
active.
Build `startup_present_producer` and run
`ctest --preset release --no-tests=error -R '^startup_output_window_close$'`
to check both host modes with a source-built presenter.
Its title starts with `Xbox2Windows <rev>`, where `<rev>` is `git rev-parse --short=8 HEAD` of the
source tree the shim was built from, with `-dirty` for uncommitted changes to tracked files, or `unknown`
without git. The `D3D12XboxCreateDevice` log line ends with the same `build=<rev>`. The build refreshes
Expand Down
17 changes: 15 additions & 2 deletions src/startup_stubs/d3d12_present.inl
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,27 @@ LONG window_presents;
// With X2W_HIDE_TITLE_WINDOW=1, a timer on this thread hides the title's own window while frames
// are shown here (x2w_startup::TitleWindowHider, docs/startup-runtime.md#switches).
HWND output_handle;
LONG output_closed;
LONG last_frame_shown; // whether the latest present reached this window (set by queue_present)
x2w_startup::TitleWindowHider title_hider; // used on the output window's thread only
DWORD WINAPI output_window_thread(void* ready)
{
WNDCLASSW cls{};
cls.lpfnWndProc = [](HWND window, UINT message, WPARAM w, LPARAM l) -> LRESULT {
if (message == WM_CLOSE) {
ShowWindow(window, SW_MINIMIZE);
wchar_t name[96]{};
const DWORD length = GetEnvironmentVariableW(L"X2W_SESSION_CLOSE_EVENT", name, ARRAYSIZE(name));
if (length && length < ARRAYSIZE(name)) {
if (HANDLE request = OpenEventW(EVENT_MODIFY_STATE, FALSE, name)) {
const BOOL sent = SetEvent(request);
CloseHandle(request);
if (sent) return 0;
}
}
InterlockedExchange(&output_closed, 1);
KillTimer(window, x2w_startup::hide_title_timer);
title_hider.step(window, 0, 0);
ShowWindow(window, SW_HIDE);
return 0;
}
if (message == WM_TIMER && w == x2w_startup::hide_title_timer) {
Expand Down Expand Up @@ -163,7 +176,7 @@ bool present_to_window(ID3D12CommandQueue* queue, const x2w_startup::PlaneStep*
{
X2W_ZONE("window present (blit + fence wait)");
WindowPresenter& p = window_presenter;
if (p.failed || !queue || !steps || !count || !plane_surfaces) return false;
if (p.failed || !queue || !steps || !count || !plane_surfaces || InterlockedCompareExchange(&output_closed, 0, 0)) return false;
HWND window = output_window();
if (!window) return false;
if (!p.chain && !create_window_presenter(queue, window, plane_capacity)) {
Expand Down
34 changes: 34 additions & 0 deletions tests/startup_output_window_close_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""Minimize and close a source-built presenter in direct and managed hosts."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile


def main():
exe = Path(sys.argv[1]).resolve()
debugger = (Path(sys.argv[2]) if len(sys.argv) > 2 else
Path(__file__).resolve().parents[1] / "tools" / "startup" / "debug_launch.py")
env = dict(os.environ, X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1",
X2W_D3D12_LIST_NOOP="1", X2W_TEST_WINDOW_CLOSE="1")
env.pop("X2W_SESSION_CLOSE_EVENT", None)
with tempfile.TemporaryDirectory(prefix="x2w-window-close-") as directory:
direct = subprocess.run([exe], cwd=directory, env=env, timeout=15, capture_output=True, text=True)
if direct.returncode:
print(direct.stdout + direct.stderr)
return direct.returncode
logs = Path(directory) / "managed"
result = subprocess.run([sys.executable, "-B", debugger, exe, directory, logs,
"--console", "0", "--managed-window", "1", "--timeout", "20"],
env=env, timeout=25, capture_output=True, text=True)
if (result.returncode or "stopped by output window close" not in result.stdout or
"exit 0x00000000" not in (logs / "events.txt").read_text(encoding="utf-8")):
print(result.stdout + result.stderr)
return 1
print("Direct host survived Close, and managed Close ended the child and debugger")
return 0


if __name__ == "__main__":
sys.exit(main())
27 changes: 27 additions & 0 deletions tests/startup_present_producer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <cstdio>
#include <cstring>
#include <vector>
#include "startup_stubs/overlay_window.h"

extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**);

Expand All @@ -30,6 +31,7 @@ int main(int argc, char** argv)
const bool use_magenta = argc >= 2 && std::strcmp(argv[1], "auto-magenta") == 0;
const bool automatic = use_magenta || (argc >= 2 && std::strcmp(argv[1], "auto") == 0);
const bool barriers = argc >= 2 && std::strcmp(argv[1], "barriers") == 0;
const bool close_test = GetEnvironmentVariableW(L"X2W_TEST_WINDOW_CLOSE", nullptr, 0) != 0;
const bool hardware = argc == 3 && std::strcmp(argv[2], "hardware") == 0;
ComPtr<ID3D12Debug> debug;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer();
Expand Down Expand Up @@ -109,6 +111,31 @@ int main(int argc, char** argv)
call(queue, 10, 1, arg(lists));
return finish();
};
if (close_test) {
if (!emit(blue) || !present()) return 18;
HWND window = nullptr;
EnumWindows([](HWND candidate, LPARAM found) -> BOOL {
DWORD owner = 0;
GetWindowThreadProcessId(candidate, &owner);
wchar_t name[64]{};
if (owner != GetCurrentProcessId() || !GetClassNameW(candidate, name, ARRAYSIZE(name)) ||
lstrcmpW(name, x2w_startup::presenter_class) != 0) return TRUE;
*reinterpret_cast<HWND*>(found) = candidate;
return FALSE;
}, reinterpret_cast<LPARAM>(&window));
if (!window) return 19;
DWORD_PTR result;
if (!SendMessageTimeoutW(window, WM_SYSCOMMAND, SC_MINIMIZE, 0, SMTO_ABORTIFHUNG, 5000, &result) ||
!IsIconic(window) ||
!SendMessageTimeoutW(window, WM_SYSCOMMAND, SC_RESTORE, 0, SMTO_ABORTIFHUNG, 5000, &result) ||
IsIconic(window) ||
!SendMessageTimeoutW(window, WM_SYSCOMMAND, SC_CLOSE, 0, SMTO_ABORTIFHUNG, 5000, &result)) return 20;
if (GetEnvironmentVariableW(L"X2W_SESSION_CLOSE_EVENT", nullptr, 0)) {
Sleep(10000);
return 21; // The job owner must end the process before it reaches here.
}
return !IsWindowVisible(window) && !IsIconic(window) && present() ? 0 : 22;
}
if (barriers) {
D3D12_RESOURCE_DESC uav_desc = desc;
uav_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
Expand Down
2 changes: 2 additions & 0 deletions tests/startup_run_ps1_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
"--trace-files", "1", "--continue-asserts", "4", *passed]
record = startup / "debugger.json"
got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None
if "-Render" in switches or translate or native:
want.extend(["--managed-window", "1"])
expected = [want, "1" if "-TraceApi" in switches else trace_api_env,
str(sdk) if native else None,
"1234" if manifest in ("normal", "bracket") else None,
Expand Down
52 changes: 45 additions & 7 deletions tools/startup/debug_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
import sys
import threading
import time
import uuid

k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.OpenThread.restype = wt.HANDLE
k32.CreateJobObjectW.restype = wt.HANDLE
k32.CreateEventW.restype = wt.HANDLE
k32.CreateFileW.restype = wt.HANDLE
k32.SuspendThread.restype = wt.DWORD
nt_dll = ctypes.WinDLL("ntdll")
Expand Down Expand Up @@ -182,11 +184,17 @@ def log(text):

k32.SetErrorMode(0x8003)
job = k32.CreateJobObjectW(None, None)
if not job:
print("CreateJobObject failed", ctypes.get_last_error())
return 2
info = EXTENDED_LIMIT()
info.Basic.LimitFlags = 0x2000 | 0x200 | 0x8
info.Basic.ActiveProcessLimit = 1
info.JobMemoryLimit = memory
k32.SetInformationJobObject(wt.HANDLE(job), 9, ctypes.byref(info), ctypes.sizeof(info))
if not k32.SetInformationJobObject(wt.HANDLE(job), 9, ctypes.byref(info), ctypes.sizeof(info)):
print("SetInformationJobObject failed", ctypes.get_last_error())
k32.CloseHandle(wt.HANDLE(job))
return 2

out = inheritable_file(os.path.join(logdir, "stdout.txt"))
err = inheritable_file(os.path.join(logdir, "stderr.txt"))
Expand All @@ -195,6 +203,15 @@ def log(text):
si.dwFlags = 0x100
si.hStdOutput, si.hStdError = out, err
env = dict(os.environ, X2W_TRAP_LOG=trap_log)
env.pop("X2W_SESSION_CLOSE_EVENT", None)
close_event = None
if opts.get("--managed-window") == "1":
name = "Local\\X2W-session-close-" + uuid.uuid4().hex
close_event = k32.CreateEventW(None, True, False, name)
if not close_event:
print("CreateEvent for output window failed", ctypes.get_last_error())
return 2
env["X2W_SESSION_CLOSE_EVENT"] = name
# A process started under a debugger gets the debug heap: no low-fragmentation heap and checks on
# every allocation and free. That multiplies the cost of each free, and a startup run frees a lot.
# _NO_DEBUG_HEAP=1 keeps the ordinary heap; a caller who wants the checks sets _NO_DEBUG_HEAP=0.
Expand All @@ -210,7 +227,10 @@ def log(text):
ctypes.create_unicode_buffer(block), cwd, ctypes.byref(startup), ctypes.byref(pi)):
print("CreateProcess failed", ctypes.get_last_error())
return 2
k32.AssignProcessToJobObject(wt.HANDLE(job), wt.HANDLE(pi.hProcess))
if not k32.AssignProcessToJobObject(wt.HANDLE(job), wt.HANDLE(pi.hProcess)):
print("AssignProcessToJobObject failed", ctypes.get_last_error())
k32.TerminateProcess(wt.HANDLE(pi.hProcess), 2)
return 2
k32.DebugSetProcessKillOnExit(True)
k32.ResumeThread(wt.HANDLE(pi.hThread))
if opts.get("--console", "1") == "1":
Expand Down Expand Up @@ -788,8 +808,20 @@ def capture_loop():
if capture_thread:
capture_thread.start()
stop_requested = False
window_close = False
close_deadline = None
stop_next = 0.0
while not timeout or time.time() - start < timeout:
while close_deadline is not None or not timeout or time.time() - start < timeout:
if close_deadline is not None:
if time.monotonic() >= close_deadline:
break
elif close_event and k32.WaitForSingleObject(wt.HANDLE(close_event), 0) == 0:
window_close = True
log(f"{time.time() - start:7.3f} output window closed: ending the run")
if not k32.TerminateJobObject(wt.HANDLE(job), 0):
log(f"TerminateJobObject failed: {ctypes.get_last_error()}")
break
close_deadline = time.monotonic() + 10
if time.time() >= stop_next:
stop_next = time.time() + 0.5
if os.path.exists(stop_file):
Expand Down Expand Up @@ -1032,6 +1064,8 @@ def capture_loop():
print(f" code at rip-32: {code_bytes.hex(' ')}")
if thread:
k32.CloseHandle(wt.HANDLE(thread))
elif window_close:
print(f"stopped by output window close after {elapsed:.2f} s")
elif exit_code is not None:
print(f"process exited with {exit_code:#010x} after {elapsed:.2f} s")
else:
Expand Down Expand Up @@ -1084,14 +1118,18 @@ def capture_loop():
capture_done.set()
capture_thread.join(30)
print(" " + series.summary() + f" (every {capture_every:g} s, window_<sss>s.png, at most {FILE_CAP} files)")
if exit_code is None:
if exit_code is None and not window_close:
try:
capture_window()
except Exception as error: # diagnostics only
print(f" window capture failed: {error}")
k32.TerminateJobObject(wt.HANDLE(job), 0xDEAD0002)
for h in (out, err, pi.hThread, pi.hProcess):
k32.CloseHandle(wt.HANDLE(h))
child_stopped = not window_close or k32.WaitForSingleObject(wt.HANDLE(pi.hProcess), 2000) == 0
if not child_stopped:
print("output window close: process did not signal exit")
for h in (out, err, pi.hThread, pi.hProcess, close_event, job):
if h:
k32.CloseHandle(wt.HANDLE(h))
events.close()
print(f"modules loaded: {len(modules)}")
with open(os.path.join(logdir, "finished.txt"), "w", encoding="utf-8") as handle:
Expand All @@ -1100,7 +1138,7 @@ def capture_loop():
path = os.path.join(logdir, name)
if os.path.exists(path) and os.path.getsize(path):
print(f"--- {name}\n" + open(path, encoding="utf-8", errors="replace").read()[-3000:])
return 0
return 0 if child_stopped else 2


if __name__ == "__main__":
Expand Down
4 changes: 3 additions & 1 deletion tools/startup/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,13 @@ if ($watchShaders) {
}
$traceArgs = @()
if ($TraceCalls) { $traceArgs = @("--trace-calls", "1") }
$windowArgs = @()
if ($Render) { $windowArgs = @("--managed-window", "1") }
$captureArgs = @()
if ($CaptureEvery -ne 0) { $captureArgs = @("--capture-every", "$CaptureEvery") }
try {
& $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB `
--trace-files 1 --continue-asserts $ContinueAsserts @traceArgs @captureArgs *> "$LogDir.out"
--trace-files 1 --continue-asserts $ContinueAsserts @traceArgs @captureArgs @windowArgs *> "$LogDir.out"
$debuggerExit = $LASTEXITCODE
} finally {
# taskkill /T needs a live parent PID to reach the watcher's workers.
Expand Down
Loading