Skip to content

Commit 4528095

Browse files
jeffhostetlerdscho
authored andcommitted
mimalloc: use "weak" random seed when statically linked
Always use the internal "use_weak" random seed when initializing the "mimalloc" heap when statically linked on Windows. The imported "mimalloc" routines support several random sources to seed the heap data structures, including BCrypt.dll and RtlGenRandom. Crashes have been reported when using BCrypt.dll if it initialized during an `atexit()` handler function. Granted, such DLL initialization should not happen in an atexit handler, but yet the crashes remain. It should be noted that on Windows when statically linked, the mimalloc startup code (called by the GCC CRT to initialize static data prior to calling `main()`) always uses the internal "weak" random seed. "mimalloc" does not try to load an alternate random source until after the OS initialization has completed. Heap data is stored in `__declspec(thread)` TLS data and in theory each Git thread will have its own heap data. However, testing shows that the "mimalloc" library doesn't actually call `os_random_buf()` (to load a new random source) when creating these new per-thread heap structures. However, if an atexit handler is forced to run on a non-main thread, the "mimalloc" library *WILL* try to create a new heap and seed it with `os_random_buf()`. (The reason for this is still a mystery to this author.) The `os_random_buf()` call can cause the (previously uninitialized BCrypt.dll library) to be dynamically loaded and a call made into it. Crashes have been reported in v2.40.1.vfs.0.0 while in this call. As a workaround, the fix here forces the use of the internal "use_weak" random code for the subsequent `os_random_buf()` calls. Since we have been using that random generator for the majority of the program, it seems safe to use it for the final few mallocs in the atexit handler (of which there really shouldn't be that many. Signed-off-by: Jeff Hostetler <[email protected]> Signed-off-by: Johannes Schindelin <[email protected]>
1 parent febf841 commit 4528095

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

compat/mimalloc/init.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,11 @@ static bool _mi_heap_init(void) {
302302
_mi_memcpy_aligned(tld, &tld_empty, sizeof(*tld));
303303
_mi_memcpy_aligned(heap, &_mi_heap_empty, sizeof(*heap));
304304
heap->thread_id = _mi_thread_id();
305+
#if defined(_WIN32) && !defined(MI_SHARED_LIB)
306+
_mi_random_init_weak(&heap->random); // match mi_heap_main_init()
307+
#else
305308
_mi_random_init(&heap->random);
309+
#endif
306310
heap->cookie = _mi_heap_random_next(heap) | 1;
307311
heap->keys[0] = _mi_heap_random_next(heap);
308312
heap->keys[1] = _mi_heap_random_next(heap);

0 commit comments

Comments
 (0)