Skip to content

RT-374: deliver mapped process detach on the exiting thread - #5565

Closed
l-CatDemon-l wants to merge 9 commits into
ItsNotRexed:mainfrom
l-CatDemon-l:catdemon/rt374-process-detach
Closed

l-CatDemon-l wants to merge 9 commits into
ItsNotRexed:mainfrom
l-CatDemon-l:catdemon/rt374-process-detach

Conversation

@l-CatDemon-l

@l-CatDemon-l l-CatDemon-l commented Nov 23, 2026 •

Copy link
Copy Markdown

Claimed as RT-374 in the coordination tracker.

Depends on: #3790

What and why

When a mapped executable ends through _exit, _Exit, quick_exit or ExitProcess, the host exits before the mapped images receive process detach. Calling detach early on the guest thread preserves its TLS but leaves other workers running during the callbacks.

The first exit caller retains its TLS while the host reports the exit status. That caller then invokes native ExitProcess. The primary TLS helper delivers mapped DLL detach and EXE TLS detach after Windows stops the other threads. The mapped DLL receives the native termination pointer. Forced TerminateProcess skips detach, and explicit unload and failed-startup rollback keep their existing semantics.

Before releasing the caller, the loader drains in-flight mapping and initialization and freezes the module tables. During native detach the shim lookups read those tables directly. They bypass the registry locks and the host module-name cache, which may have been held by a worker that Windows stopped. TLS helpers remain mapped through detach. A later run reclaims their stale clone files as it would after forced termination.

ntdll!RtlExitUserProcess, imported or found with GetProcAddress, is served like ExitProcess and takes the same handoff. Natively it delivers the same process detach, which the branch otherwise skipped for an exit that bypassed the shim.

If end_run could not duplicate the exit caller's handle, finish_run opens the parked caller by thread id before releasing it, so it no longer parks forever when that caller dies before native ExitProcess. The wait cannot bound a hung detach: native ExitProcess ends every other thread, the host's included, before it issues DLL_PROCESS_DETACH, and Windows does not bound DllMain either.

Exits that do not go through the title's imports are not handed off: the last thread leaving with ExitThread, and process exits issued from inside host DLLs (for example the UCRT's own abort path after terminate()). For those the mapped modules get no process detach; ntdll!RtlExitUserProcess and every ExitProcess/CRT exit the title imports or looks up are served.

main is merged in (97b5773) rather than rebased, so the commits already reviewed and tested keep their hashes. The only conflict was end_run in runtime/shims/process.cpp: it keeps main's pre-signal g_running snapshot (b6299c9) with this PR's reentry check and exit handoff, and parks while running || g_release_exit. The branch carries #3790 on purpose: the fix builds on its Loader::detach_initialised_modules(). Once #3790 is merged the branch no longer duplicates it; if the maintainers prefer, it can be rebased onto main after #3790 lands.

This follows the released #5161 work and retains #3790's ancestry. Thanks to tomgamer22 for the handoff and to Hiiva for the held-lock reproduction and the independent integration with current main.

Tested

Windows 11 x64, MSVC 19.44 (VS 2022 Build Tools), Windows SDK 10.0.26100, Python 3.13, RelWithDebInfo, RTX 4070 Ti. Synthetic fixtures, no game files.

At 37bf686:

  • 24/24 focused CTests (process detach, native/mapped startup, rollback, CRT atexit, bundled and shim lookups, TLS, exceptions, exit codes); process_detach 20/20 repeats.
  • Each lock-held lookup case (Loader, bundled registry, library shim cache) 10/10 and 100/100 in a loop with exit 23: DLL lookups, DLL detach with the termination pointer and the EXE TLS detach all arrive, matching native. Before this change the same cases lose the EXE TLS detach and the lookups.
  • Exception-handling and worker-exit controls with a held lock match native 10/10; a lookup under heap pressure 50/50.
  • Full CTest: all pass except d3d12_vulkan_device, which times out on this machine without this PR too.

At 540b8dd (after the merge with main 561b65a):

  • process_detach 10/10 repeats, now including RtlExitUserProcess in the entry, entry-with-worker and worker-exit scenarios, compared with the same guest run natively.
  • startup_rollback 10/10 repeats; focused CTests 24/25; full CTest (-j4, without d3d12_vulkan_device) 222/225.
  • The three failures are not touched by this PR. run_tiny_game_abort_exit_codes fails only in its native runs: tiny_game.exe started directly exits with 0xC0000139 before main, while all five runs through gta6rt pass with the expected codes. d3d12_method_variants and xbox_present fault on process exit after their output; they link only gta6rt_d3d12_com, which this PR does not change. Both passed at 37bf686, before main was merged.
  • Independent probes (separate build): guest exit through ntdll!RtlExitUserProcess and through kernel32!ExitProcess from GetProcAddress delivers DllMain (non-null lpReserved), DLL and EXE TLS process detach exactly as native, 10/10 each (37bf686 delivered none on the RtlExitUserProcess route); a held Loader::ranges_mutex_ with a C++ throw/catch in DllMain, and a worker-thread exit with the loader or lookup-cache mutex held, match native 10/10 each while the parent fef0a07 truncates detach; process_detach passes --repeat until-fail:5.
  • git diff --check is clean.

AI-assisted (Codex and Claude Code).

  • No game data, keys, or decryption.

kmeyer43 and others added 6 commits November 22, 2026 15:37
Preserve upstream Unicode-safe console diagnostics alongside entry-thread startup. Retain merged process completion and TLS lifecycle changes. Verified focused TLS/rollback tests, CPU CTest and native/upstream/fixed synthetic comparisons.
Layer on PR ItsNotRexed#3790 for RT-374 review. Keep TLS helpers and mappings alive through native process detach; compare synthetic native/mapped exit routes and worker quiescence. Document remaining integration and lock-stress qualification.
Freeze the run loader on the exit caller. Route its detach-time lookups directly to stable module data and bypass the host name cache. Verify callbacks complete with a worker holding each real lookup lock.

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 37bf686 (draft).

  • Configured runtime (Ninja/RelWithDebInfo, BUILD_TESTING, WINDOWS_RUNTIME, Vulkan 1.4.363); built gta6rt plus the new fixtures. ctest -R "process_detach|startup_rollback|tls_startup" --output-on-failure -> 4/4 passed (process_detach 4.06 s, startup_rollback, tls_startup_native, tls_startup_mapped).
  • Direct: python -I runtime/test/check_process_detach.py --driver process_detach_driver.exe --guest process_detach_guest.exe -> "PASS: 98 child processes, including 20 independent exit races per implementation; early-detach control confirms the worker can run before native shutdown".
  • Thread assumption verified: in worker_exit the native and mapped runs both deliver DLL TLS, DLL DllMain and EXE TLS process-detach on the exiting worker's tid with that thread's TLS (0x98/0x97), not the entry thread's (0x88/0x77).
  • git diff --check clean.

Notes, not blockers: the ExitThread case checks status/no-hang only, not detach parity; finish_run parks forever if DuplicateHandle failed and there is no timeout on a hung detach; check_startup_rollback.cmake and startup_rollback_test.cpp lack a trailing newline.

finish_run parked forever when end_run's DuplicateHandle had failed, so a
caller that died without reaching native ExitProcess left the host hung.
The caller is still parked on g_release_exit at that point, so open it by
thread id first and keep the infinite park only when that fails as well.
Say why the wait cannot bound a hung detach: native ExitProcess ends the
host thread before any DLL_PROCESS_DETACH runs, and does not bound DllMain
either. Add the missing final newlines to the startup rollback test files
(review on ItsNotRexed#5565).

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@memorypressure

Copy link
Copy Markdown

FAIL to merge, two verified reasons: runtime/shims/process.cpp conflicts with current main 561b65a, and your branch merges in open PR #3790 (detach_initialised_modules — its head is an ancestor of yours, the symbol is nowhere on main), so merging this as-is also imports that PR's unreviewed diff. The C++ side cannot be built or tested on this host either way, and the branch reports no CI checks. Please rebase onto main without the #3790 merge (or after #3790 lands) and resolve the process.cpp conflict. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only review).

main's b6299c9 reads g_running before end_run signals the host; this
branch added the native exit handoff around the same lines. Keep both: the
reentry check from the detach handoff comes first, then main's snapshot of
g_running, and the park keeps waiting while a handoff is pending
(running || g_release_exit). Every other file merges cleanly against
3faac55, the base of this branch and of ItsNotRexed#3790's main merge.

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@Hiiva Hiiva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent Windows review of draft head 37bf686, plus a separately identified current-main integration. The held-lock lookup and stopped-worker cases that blocked TEST-1168 now pass in the tested configurations.

Exact owner head, preserved before the upstream advance:

  • The unchanged process-detach suite passed all 98 child runs.
  • Fifteen independent controls passed: our original held-loader fixture, a routing-disabled negative control for the loader/registry/cache locks, and the original event-based worker probe through actual gta6rt for _exit, _Exit, quick_exit and ExitProcess.

Current-main integration:

  • Locally merged this unchanged head with main 561b65a and published #5039 at 73c7309 plus #5074 at 10aac54. Local verification commit: 98423b54adf2471c0b2e5466e6907f80b546bcaf.
  • The only textual conflict was in process.cpp. The resolution retains main's pre-signal running snapshot, this PR's reentry and native-exit handoff, and parks with running || g_release_exit. Main's existing-thread TLS implementation remains present.
  • All eight focused CTests passed: process_detach, loader_tls, process_cmdline, startup_rollback, tls_startup_native, tls_startup_mapped, run_tiny_atexit and run_tiny_tls_exit. This includes the 98-child detach suite, 85 TLS checks with existing-thread/thread-pool coverage, 10 native/mapped termination paths, six full-cleanup TLS paths, both registration-reset controls and upstream's parking regression.
  • The same 15 independent controls also passed against this integration. The held-lock controls acquire their locks after prepare_process_exit has frozen the loader state; they do not cover a lock held during preparation. With production routing active, the original held-loader fixture completes its DLL lookups and later EXE TLS callback. With only ProcessDetachLookup activation disabled in an ignored source copy, the unheld case completes; holding the real loader or registry mutex truncates lookup and later EXE TLS, while the held cache allows mapped lookups but truncates the host lookup and later EXE TLS. All return 23 without timing out. This isolates the actual bypass path under the forced schedules.
  • The unchanged event-based worker probe reports reserved=1 and progress=0 for both native and actual mapped execution in all four immediate-exit modes, with matching exit codes. The worker can acknowledge only after the detach callback signals it. Thread-handle status is not used as evidence that the worker stopped.

Windows 11 x64, MSVC 19.44.35228, Windows SDK 10.0.26100.0, RelWithDebInfo. Synthetic fixtures only; no game files or GPU. Tracked trees and diff checks are clean.

This is a bounded behavior review. The draft still needs its current-main rebase and retains its explicit #3790 dependency; the local integration above does not remove those merge prerequisites. I found no additional issue in this tested scope. AI-assisted: yes.

A title that ends the process through ntdll!RtlExitUserProcess, imported
or found with GetProcAddress, bypassed the process shim. The loader was
never prepared for exit on that thread, so on_host_process_detach skipped
the mapped modules: no DllMain or TLS process detach, while native Windows
delivers them. Serve it as ExitProcess is served, so it takes the same
end_run / prepare_process_exit / finish_run handoff.

process_detach gains the RtlExitUserProcess mode (looked up at run time
from ntdll) in the entry, entry_with_worker and worker_exit scenarios,
compared with the same guest run natively (review on ItsNotRexed#5565, h-verify B6).

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@l-CatDemon-l

Copy link
Copy Markdown
Author

Thanks all. Pushed 4c1d5f1 → 97b5773 → 540b8dd on top of the reviewed 37bf686 (fast-forward, no rewrite).

@Hiiva thank you for the independent integration. Your merge with main resolved process.cpp the same way as 97b5773: main's pre-signal running snapshot, this PR's reentry and exit handoff, park on running || g_release_exit.

@Kam471, on your notes:

  1. ExitThread: by design that case checks only the exit status and that nothing hangs. Natively, ExitThread on the last thread runs DLL_PROCESS_DETACH on that thread with its own TLS; under the loader that thread is already gone when the host finishes the run, so TLS parity can't be compared. The description now lists it, with exits from inside host DLLs, as not handed off.
  2. finish_run: when end_run's DuplicateHandle fails, it now opens the parked caller by thread id before releasing it (4c1d5f1); the infinite park is left only if that fails too. A timeout around detach isn't possible from the host: native ExitProcess terminates every other thread, the host's included, before it issues DLL_PROCESS_DETACH, and Windows doesn't bound DllMain either.
  3. Final newlines added (4c1d5f1).

@memorypressure: the process.cpp conflict with main 561b65a is resolved by merge commit 97b5773. I merged rather than rebased so the hashes already tested stay valid. The branch carries #3790 on purpose, per Depends on: #3790: the fix builds on its Loader::detach_initialised_modules(). Once #3790 is merged the branch no longer duplicates it; if the maintainers prefer, I can rebase onto main after #3790 lands.

Also new: ntdll!RtlExitUserProcess (imported or via GetProcAddress) now takes the same exit handoff (540b8dd). An independent probe showed 37bf686 skipped detach for it, while native delivers it.

Checks at 540b8dd (Windows 11, MSVC 19.44, RTX 4070 Ti): process_detach 10/10 repeats including the new RtlExitUserProcess mode against native; startup_rollback 10/10; full CTest 222/225 without d3d12_vulkan_device. The three failures are outside this PR: run_tiny_game_abort_exit_codes fails only when tiny_game.exe runs natively (0xC0000139 before main; all gta6rt runs pass), and d3d12_method_variants and xbox_present fault on exit in code this PR doesn't touch.

This stays a draft while #3790, which it builds on, is still a draft; I'll mark it ready for review once #3790 is.

AI-assisted.

@Hiiva Hiiva left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up independent Windows review of exact head 540b8dd, following my earlier review of 37bf686.

The new RtlExitUserProcess route matches native Windows in the tested cases:

  • The unchanged process_detach runner passes all 104 child processes. This includes the three new RtlExitUserProcess scenarios, exiting-worker TLS checks, 20 independent exit races per implementation, the early-detach negative control, and the loader/registry/cache lock-held lookup cases.
  • startup_rollback, tls_startup_native and tls_startup_mapped pass in a fresh RelWithDebInfo build of this exact head.
  • A separate event-based worker fixture runs through actual gta6rt, using both a static ntdll!RtlExitUserProcess import and GetModuleHandleW/GetProcAddress lookup. The original DLL probe is unchanged; the EXE only adds these two routes and links ntdll.lib. Across native, previous 37bf686 and current 540b8dd, all nine children return the expected codes. Both Rtl routes deliver process detach on native and current, with non-null reserved and no worker acknowledgment after detach signals its event. The previous head returns23 but delivers no mapped detach. The direct ExitProcess control delivers detach in all three configurations.

The worker result is based on an event it can acknowledge only after the callback signals it, not on GetExitCodeThread or thread-handle status. The stock early-detach control separately confirms that its worker can progress before native shutdown.

I also read the new OpenThread fallback and the process.cpp merge resolution. The pre-signal running snapshot, reentry handoff, and running || g_release_exit parking remain present. DuplicateHandle/OpenThread failure paths were source-reviewed only, without fault injection. This pass does not repeat the prior #5039/#5074 integration or claim a full-suite run.

Windows11 x64, MSVC19.44.35228, SDK10.0.26100.0. Fresh build, unchanged tracked tree, synthetic fixtures only, no GPU or game files. No additional finding in this scope. The explicit #3790 dependency and owner's draft status remain applicable. AI-assisted.

@l-CatDemon-l

Copy link
Copy Markdown
Author

@shayderrr could you say why this was closed? RT-374 is claimed for it in the tracker, and it is a draft only because it builds on #3790 (Depends on: #3790), which is itself still a draft. If the problem is carrying #3790's commits, I can rebase it onto main once #3790 lands, or split out the part that does not need #3790. Happy to do whichever you prefer. AI-assisted.

@tomgamer22 tomgamer22 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code read at 37bf686e. This machine has no MSVC, so nothing was built. I'm the author of the closed #5161. I'm posting a comment rather than a verdict.

The #5161 review points are handled:

  • Termination vs unload. On termination DllMain gets the native non-null lpReserved (pe_loader.cpp:648, via tls_host.cpp:833-835). Startup rollback still passes null (main.cpp:62), and TLS callbacks keep getting nullptr, as on Windows.
  • Threads during detach. The first exit caller parks in end_run (shims/process.cpp:94-105) and then calls native ExitProcess itself, so detach runs after Windows has stopped the other threads. on_host_process_detach acts only on that thread (pe_loader.cpp:593-597), and detach_started_ stops a second detach.

Points worth a look:

  1. New lock-order deadlock (pe_loader.cpp:612-615, reached from process.cpp:94):
    • Thread A runs a TLS DLL_THREAD_ATTACH/DETACH callback in on_host_thread_event. It holds SharedTlsLock (:417) and the Windows loader lock. If that callback calls exit/ExitProcess, prepare_process_exit now blocks on mutex_.
    • Thread B is in Loader::initialise(). It holds mutex_ (:851) and waits for ExclusiveTlsLock in set_initialised (:884), or for the loader lock if the DllMain it runs calls LoadLibrary.
    • Before this PR end_run took no Loader lock, and natively this exit doesn't hang. It's narrow, but a test with a lock held during prepare would catch it. The held-lock cases in process_detach_driver.cpp:66-71 take their locks only after prepare.
  2. Order against host DLLs. Mapped detach runs inside the primary helper's DllMain (tls_host.cpp:833, enabled at pe_loader.cpp:599-609). That DllMain sits at a fixed place in the host's reverse load order. Host DLLs loaded at run time (prefer_host_copy, lazy host imports) get their DLL_PROCESS_DETACH before mapped DllMains that may still call into them.
  3. Direct ExitThread of the entry thread. run_entry claims g_exited and g_exit_tid stays 0. finish_run then exits on the host thread, and on_host_process_detach skips (:596), so mapped modules get no PROCESS_DETACH at all. The PR documents this, but the test checks only the exit status, so a note in the RT-374 row would help.
  4. Rollback test. startup_rollback_dll.cpp:59-85 ignores lpReserved, so nothing asserts that rollback still passes null.

Also, the merge base is 3faac557 and the diff still carries #3790's part, so it will need main merged in.

AI-assisted (Claude Code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants