Fix mimalloc init re-entrancy on Windows (TLS recursion + page-map) #1196
+54
−8
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Description:
Problem
On Windows, accessing
__declspec(thread)storage can trigger on-demand TLS initialization (__dyn_tls_init) which may run user TLS constructors that allocate memory. During mimalloc process initialization, this can cause recursive allocations before global state (like the page map) is ready, leading to assertion failures.Root Causes
mi_prim_get_default_heap()accesses TLS, which can trigger__dyn_tls_initand user constructorsmi_process_init()can occur before_mi_page_mapis initializedmi_atomic_onceis non-blocking, allowing other threads to observe incomplete initializationSolution
This PR addresses the issues by:
MI_TLS_RECURSE_GUARD): Prevents TLS access beforemi_process_initcompletes on Windowsmi_process_init()with atomic state tracking (0=not started, 1=in progress, 2=done)Changes
include/mimalloc/prim.h: AddedMI_TLS_RECURSE_GUARDdefinition for Windowssrc/init.c: Rewrotemi_process_init()with proper synchronization (48 lines)src/page-map.c: Adjusted assertion order in_mi_page_map_register()Testing
Tested on Windows with applications that trigger TLS initialization during mimalloc init. No more assertion failures or crashes.
Compatibility