Skip to content

Fix TLS index and virtual reservation leaks on DLL unload#1261

Closed
jinpzhanAMD wants to merge 2 commits intomicrosoft:dev3from
jinpzhanAMD:dev3
Closed

Fix TLS index and virtual reservation leaks on DLL unload#1261
jinpzhanAMD wants to merge 2 commits intomicrosoft:dev3from
jinpzhanAMD:dev3

Conversation

@jinpzhanAMD
Copy link
Copy Markdown

Summary
When mimalloc is statically linked into a DLL that is repeatedly loaded/unloaded, Application Verifier reports two resource leaks on DLL_PROCESS_DETACH. This PR fixes both.

Changes

  1. Fix VERIFIER STOP 0x350 — TLS index not freed

mi_win_tls_slot_alloc() calls TlsAlloc() twice (for _mi_theap_default_slot and _mi_theap_cached_slot) but TlsFree() is never called on DLL unload.

Fix: Save the raw DWORD returned by TlsAlloc() into mi_tls_raw_default / mi_tls_raw_cached, and free them via mi_win_tls_slots_done() called from mi_process_done(). This avoids trying to reverse-engineer the original TLS index from mimalloc's internal slot representation, which is fragile and error-prone (e.g. expansion slots would compute wrong indices).

  1. Fix VERIFIER STOP 0x903 — Virtual reservation leaked

mi_subproc_unsafe_destroy() only calls _mi_arenas_unsafe_destroy_all() for non-main subprocesses (guarded by if (subproc != &subproc_main)). When mi_subprocs_unsafe_destroy_all() destroys the main subproc, its arena virtual memory reservations (VirtualAlloc(MEM_RESERVE)) are never released via VirtualFree.

Fix: Add _mi_arenas_unsafe_destroy_all(&subproc_main) after mi_subproc_unsafe_destroy(&subproc_main) in mi_subprocs_unsafe_destroy_all().

  1. Enable destroy_on_exit by default

Set mi_option_enable(mi_option_destroy_on_exit) in mi_process_init() so arena and page-map cleanup runs automatically on process/DLL shutdown, which is required for the DLL unload scenario.

Testing
Verified with Windows Application Verifier (leak checks enabled) on a DLL that statically links mimalloc. Both 0x350 and 0x903 verifier stops are resolved after these changes.

jinpzhan added 2 commits April 14, 2026 15:37
Free the raw TLS slots and destroy the main subprocess arenas during process teardown so DLL unload releases allocator state cleanly.
@daanx
Copy link
Copy Markdown
Collaborator

daanx commented Apr 14, 2026

Thank you so much @jinpzhanAMD for the PR -- I added your suggestions in the latest dev3; hope this works now without leaks.

@daanx daanx closed this Apr 14, 2026
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.

2 participants