pe: serve implicit TLS data templates through a carrier DLL #692
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/698"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from R0Y00/Xbox2Windows. Originally posted by rasptum on 2026-11-22T20:51:45Z.
Change
pe_map_imagerejected every image whose TLS directory has a data template (MAP_UNSUPPORTED, "TLS data"). MSVC emits such a template for anythread_localor__declspec(thread)variable, and the static C runtime adds its own, so this stopped most C++ images before a single instruction ran. This PR makespe_mapaccept them. Refs #165.Mechanism. Compiled x64 code reaches a thread-local through the thread's
ThreadLocalStoragePointerarray (gs:[0x58]), indexed by the DWORD atAddressOfIndex. ntdll owns that array: it assigns the indexes, sizes the array, and allocates and frees one block per thread.pe_mapdoes not write to it. Instead, for an image with a template or a zero-fill size:pe_mapcopies the relocated template into a small generated DLL (the "carrier") in a private directory under the temporary directory (see "Carrier lifetime" below). The carrier has no code and no entry point: a TLS directory with the copied template and the image's ownSizeOfZeroFillandCharacteristics(alignment), an import table that is only the null descriptor, and three base relocations for the directory's addresses.LoadLibraryExW. Windows assigns it a real index and allocates, aligns, initializes and frees one block per thread, for threads that already exist and for threads created later.AddressOfIndexbefore any TLS callback or entry point runs.Why this mechanism. The alternatives I considered:
pe_mappicks. The array length and the index bitmap are private to ntdll, so a laterLoadLibraryof any DLL with TLS can hand out the same index or replace the array. Not sound.pe_map.dlla fixed-size TLS block of its own and lending it to the image. One image per block, a size fixed at build time, and it collides with the C runtime's own thread-locals inpe_map.dll.The carrier needs none of that: every TLS decision is made by the Windows loader on a well-formed DLL.
Rejected inputs (all after imports are bound, without any notification):
pe_mapMAP_FORMAT, "TLS template outside image"LoadLibraryWfails, error 998MAP_FORMAT, "TLS template ends before it starts"MAP_UNSUPPORTED, "TLS template larger than 16 MiB"MAP_UNSUPPORTED, "TLS template not readable"MAP_MEMORYwith the step and the Windows errorMAP_MEMORYwith the stepKnown differences from a Windows load.
AddressOfIndexcannot be served. MSVC output reads the index; I did not measure other compilers.AddressOfIndexas linked, as before.pe_mapnow writes one carrier per mapped TLS image, holding a copy of the image's template, in a directory of its own under the temporary directory. Both are removed onpe_map_releaseor when the map fails. A process that ends with an image still mapped leaves its carrier directory; nothing removes it later.LoadLibraryExWandFreeLibrary, also whenpe_map_imageor the final release runs inside a loader notification. No existing test maps a TLS-data image from inside a callback.Carrier lifetime (changed after review). Each map call creates
pe_map_tls_<32 random hex digits>under the temporary directory with a protected DACL for the process's user only and holds it open without delete sharing. It writespe_map_tls_<same digits>.dllthere withCREATE_NEW, records its file ID and closes the write handle (the loader's open does not share writing). It reopens the file for reading and deletion, shared for reading only, checks the file ID and the bytes read back, loads it, and checks withGetMappedFileNameWthat the loaded carrier is the file behind the held handle. Cleanup goes through those two handles only, with POSIX delete semantics; nothing is deleted by name or pattern, so a map call removes only what it created. Measured on Windows 10 build 19045: while the two handles are held, writing, renaming or deleting the file and renaming its directory fail with error 32, renaming the directory above fails with error 5, andLoadLibraryExWstill loads the file. Not closed: a process of the same user can replace the file between the close of the write handle and the reopen; the ID and read-back checks then fail the map, but no fixture provokes that race.Files.
tools/pe_map.cpp; new fixturetests/cpu/tls_data.cpp(built twice:cpu_tls_dataandcpu_tls_data_refuse, whose entry point refuses) and testtests/cpu/native_tls_data_check.py(cpu_native_tls_data);tests/cpu/native_tls_value_check.pyandtests/cpu/native_tls_check.pyupdated because they pinned the old rejection;CMakeLists.txt;docs/experiments.md("Implicit TLS data").Verification
Windows 10 Pro 22H2 build 19045, MSVC 19.44.35207.1 (x64),
devpreset, commits11987cd,0dc025candf618e68onmainat3b9bb1a.Full suite,
ctest --preset dev -j 4, run before the last two small checks (aGetMappedFileNameWlength check and passing theBCryptGenRandomstatus through) and comment edits were added to0dc025c: 304 tests, 265 passed, 33 capability skips, 6 failed. None of the six touches this change:gpu_alias_lookup_writes_warpandpixel_aot_blend_scalar_hardwarealso failed in the full run on11987cd, before this change.spirv_ballot_extract_warpandspirv_ballot_extract_hardware(added by #656) fail withD3D12 881: CreateComputeShader: ... Shader version provided: cs_6_6. WARP 10.0.19041.5794 accepts up to cs_6_2 and the RTX 3060 driver 32.0.15.9636 on this Windows 10 build up to cs_6_5.pixel_aot_hardwareandpixel_aot_predicate_rounding_hardwaretimed out at 60 s while another build was running and passed when rerun alone (42.3 s and 50.6 s).Evidence and follow-up
cpu_tls_datais a source-built DLL with the static C runtime. Its template holds an initialized value, a zero-filled value, a 64-byte aligned array, a pointer to a global (a base relocation inside the template), a zero-filled range of three pages and a C++thread_localwith a dynamic initializer. Each case runs in a fresh child process.Measured, native
LoadLibraryWagainstpe_map:cpu_native_tls_value(from #523): the TLS callback and entry point now read 7 on attach, thread attach, thread detach and detach under both loaders. Before this changepe_maprejected the image.SizeOfZeroFill0x10, alignment 4096 and alignment cleared load under Windows;pe_maphands both fields to Windows unchanged and agrees on each. The existingcpu_native_tlscontrol "zero-fill size 16 on an empty template" moved from a rejection to a both-loaders-accept control for the same reason.0xffffffffandpe_mapfails the map if Windows leaves it unchanged, instead of using a wrong index.NoLowMandatoryLabelImages, error 5; a labeled copy of the fixture loads without that policy and fails with error 5 under it), and a map whose entry point refuses after the carrier was loaded (itsDllMainfirst reads the template values, so the carrier was in place; Windows fails the same DLL with error 1114). Both remove their own carrier and leave the other two exactly as they were.Negative controls: the three rejected copies above, each checked for no leftover carrier. Mutations of
pe_map.cppthat the test catches: the old name-and-PID sweep restored, a sweep of every carrier-named directory, the held handles shared for deletion, the held handle closed before the load, the carrier not deleted on release, and a failed map that forgets its carrier instead of cleaning up. All six were run on the final code. Without thepe_map.cppchange the new test fails at the first mapped child with[6, 'TLS data'].Windows 11: legacy-code-archaeologist verified
11987cdon build 26100 (30 of 30 tests);0dc025cis not yet measured there. Not measured: an EXE with TLS data started throughpe_map_run(the path is the same as for a DLL, but there is no fixture yet); a template modified after load; images built by compilers other than MSVC.Overlap: no open pull request touches
tools/pe_map.cppor the TLS tests (checked withgh pr liston 22 November 2026). #543 (index slot must be writable) is merged and this change relies on its check.AI-assisted: written and measured with Claude Code; the outputs above are copied from local runs.
The fixture
tests/cpu/tls_data.cppis original source written for this PR, under the repository's MIT License. If someone has Windows 11 at hand, a run ofctest --preset dev --no-tests=error -R '^cpu_native_tls' -Vthere would close the main gap in the measurements.🤖 Generated with Claude Code
Imported from R0Y00/Xbox2Windows. Originally posted by legacy-code-archaeologist on 2026-11-22T22:18:25Z.
Verification of
11987cdon Windows 11 build 26100.9168 (x64, Intel Skylake), MSVC 19.52.37029,devpreset. It merges cleanly withmain.The Windows-side observations of the new TLS-data test hold on this build. The TLS index numbers differ from a 26300 run, as expected for loader state:
cpu_native_tls(including the #543 index controls) andcpu_native_tls_valuealso pass on this build.AI-assisted (Claude Code).
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-23T02:23:49Z.
The native/mapped thread-local results and the two distinct TLS indexes are good evidence for the carrier approach. Before merging, please narrow the filesystem lifetime.
load_carriercloses the write handle and reopens the carrier by name before loading it. Use a private directory or another way to ensure the path continues to identify the file this invocation wrote until the loader opens it. Please also remove wildcard cleanup of other processes’ carrier paths from the mapping operation, or establish ownership without relying on the file name and PID alone. Add a failure/cleanup control that verifies a failed map only disposes of its own carrier. Keep the separate existing-thread and new-thread comparisons.Imported from R0Y00/Xbox2Windows. Originally posted by rasptum on 2026-11-23T03:34:42Z.
Thanks for the review. All four points are addressed in
0dc025c, a new commit on top of11987cd(nothing rewritten; the branch still merges cleanly withmain). The PR description is updated with the details.1. Filesystem lifetime. Each map call now creates its own directory under the temporary directory,
pe_map_tls_<32 random hex digits>, with a protected DACL for the process's user, and holds it open without delete sharing. The carrier is written there withCREATE_NEW. The write handle still has to close before the load, because the loader's own open does not share writing. The carrier is then reopened for reading and deletion, shared for reading only, and held until release. The reopened file must have the file ID of the one written and read back the same bytes, and afterLoadLibraryExWthe fileGetMappedFileNameWreports for the carrier must be the file behind the held handle. Each check fails the map with its own diagnostic.Measured on Windows 10 build 19045 with a scratch program: while the two handles are held and before the load, opening the file for writing, renaming it, deleting it and renaming its directory fail with error 32, renaming the directory above fails with error 5, and
LoadLibraryExWstill loads the file. Not closed: between closing the write handle and the reopen, a process of the same user could replace the file. The ID and read-back checks would then fail the map rather than load the other file; no fixture provokes that race.2. Wildcard cleanup.
sweep_carriersis gone. A map call deletes only the file and directory it created, through the two handles it holds; nothing is deleted by name or pattern. As a consequence, a carrier left by a process that ended with an image still mapped is no longer removed by anyone. The test asserts that a later process leaves it alone, and the docs list it as a limit.3. Failure/cleanup control.
cpu_native_tls_datagives each child its ownTMP/TEMP. Two failure cases run beside a file in the old carrier layout named after a process that has ended and a carrier directory in the new layout:Windows cannot load the TLS carrier (error 577).cpu_tls_data_refusereads its thread-locals inDllMain(template values, so the carrier is in place) and returns FALSE:entry point returned FALSE. Windows fails the same DLL with error 1114 after the same observation.Both remove their own carrier and leave the two other files byte for byte. Mutations of
pe_map.cpp, each rebuilt and run on the final code:sweep_carriersrestored verbatimpe_map_tls_*directory removed4. Thread comparisons. The loading-thread, existing-thread and new-thread comparisons are unchanged and pass.
Windows 10 Pro 22H2 build 19045, MSVC 19.44.35207.1 (x64),
devpreset, onmainat3b9bb1a:The full suite results are in the PR description; none of its failures is in this area. This commit has not been run on Windows 11; the build 26100 run by legacy-code-archaeologist covers
11987cd.AI-assisted (Claude Code); the outputs above are copied from local runs.
Imported from R0Y00/Xbox2Windows. Originally posted by rasptum on 2026-11-23T04:50:10Z.
Follow-up for the record (CI passed on
f618e68, both Windows jobs): in both Windows jobs, the "carrier refused after it was written" control hung until its 60 s timeout on the windows-2025 runner. It finished in about a second on Windows 10 build 19045. That child set the Microsoft-signed-only policy, which refuses every non-Microsoft image the child loads from then on, not only the carrier. I did not find out what it was waiting for on the runner.f618e68narrows the control. The child's temporary directory now gets an inherited low integrity label (icacls /setintegritylevel (OI)(CI)low), and the child setsNoLowMandatoryLabelImages, which refuses only images with that label. Only the carrier written there is affected:Windows cannot load the TLS carrier (error 5). A copy of the fixture placed in the same directory is the control: it loads without the policy and fails with error 5 under it. The restored old sweep and a failed map that skips its cleanup still fail the control. Nothing else changed; the description above already says this. The refusing-entry-point control ran after this one, so the runner had not reached it before.AI-assisted (Claude Code).