Skip to content

Conversation

@jinpzhanAMD
Copy link

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

  1. TLS recursion: mi_prim_get_default_heap() accesses TLS, which can trigger __dyn_tls_init and user constructors
  2. Page-map race: Recursive allocations during mi_process_init() can occur before _mi_page_map is initialized
  3. Non-blocking initialization: mi_atomic_once is non-blocking, allowing other threads to observe incomplete initialization

Solution

This PR addresses the issues by:

  1. TLS recursion guard (MI_TLS_RECURSE_GUARD): Prevents TLS access before mi_process_init completes on Windows
  2. Proper initialization synchronization: Rewrote mi_process_init() with atomic state tracking (0=not started, 1=in progress, 2=done)
  3. Re-entrancy support: Allows safe recursion on the initializing thread while blocking other threads until completion
  4. Deferred page-map assertion: Moved assertion after initialization check to avoid false positives

Changes

  • include/mimalloc/prim.h: Added MI_TLS_RECURSE_GUARD definition for Windows
  • src/init.c: Rewrote mi_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

  • Windows-specific fix, no impact on other platforms
  • Maintains existing API and behavior
  • No breaking changes

@jinpzhanAMD jinpzhanAMD force-pushed the jinpzhan/fix_mimalloc_init_re-entrancy_on_Windows branch from b822796 to e6c35b6 Compare January 12, 2026 09:28
@jinpzhanAMD
Copy link
Author

@microsoft-github-policy-service agree [company="{AMD}"]

@jinpzhanAMD
Copy link
Author

@microsoft-github-policy-service agree company="AMD"

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.

1 participant