Fix initialization order issue causing TLS access crash #1209
+21
−2
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.
Problem
Mimalloc v3.2.7 crashes during process initialization before any allocation is made. The crash occurs when using a 2-level page map configuration on 64-bit Windows.
Root Cause
The initialization sequence had an ordering bug:
mi_process_init() set _mi_process_is_initialized = true immediately after the once-guard check _mi_page_map_init() was then called to set up the page map.
During page map initialization, the call chain triggered: _mi_page_map_init() → _mi_os_alloc_aligned() → mi_os_prim_alloc_at() → mi_os_stat_counter_increase() → _mi_subproc() → _mi_theap_default()
_mi_theap_default() checked _mi_process_is_initialized and found it true
It then attempted to access TLS slots that hadn't been initialized yet → CRASH.
The fundamental issue: the process was marked as "initialized" before critical data structures were set up, and functions called during that setup trusted the flag and accessed uninitialized TLS data.
Solution
This PR implements a two-part fix:
Add early-exit guard in _mi_theap_default()
This prevents premature TLS access by returning NULL when the process is not yet initialized.
When _mi_theap_default() returns NULL during early initialization, _mi_subproc() safely falls back to _mi_subproc_main(), which is properly initialized as a static structure.
Move initialization flag assignment
Move _mi_process_is_initialized = true to AFTER _mi_page_map_init() completes, ensuring the flag accurately reflects the actual initialization state.