From 5a6d9ba8079398fad3a1dd67bd749327fc977437 Mon Sep 17 00:00:00 2001 From: daan Date: Wed, 17 Jun 2020 19:07:32 -0700 Subject: [PATCH] fix handling of failing to allocate heap metadata on thread creation, issue #257 --- src/init.c | 14 ++++++++++---- src/page.c | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/init.c b/src/init.c index 92115283..622a5eb0 100644 --- a/src/init.c +++ b/src/init.c @@ -176,10 +176,15 @@ static bool _mi_heap_init(void) { } else { // use `_mi_os_alloc` to allocate directly from the OS - mi_thread_data_t* td = (mi_thread_data_t*)_mi_os_alloc(sizeof(mi_thread_data_t),&_mi_stats_main); // Todo: more efficient allocation? + mi_thread_data_t* td = (mi_thread_data_t*)_mi_os_alloc(sizeof(mi_thread_data_t), &_mi_stats_main); // Todo: more efficient allocation? if (td == NULL) { - _mi_error_message(ENOMEM, "failed to allocate thread local heap memory\n"); - return false; + // if this fails, try once more. (issue #257) + td = (mi_thread_data_t*)_mi_os_alloc(sizeof(mi_thread_data_t), &_mi_stats_main); + if (td == NULL) { + // really out of memory + _mi_error_message(ENOMEM, "unable to allocate thread local heap metadata (%zu bytes)\n", sizeof(mi_thread_data_t)); + return false; + } } // OS allocated so already zero initialized mi_tld_t* tld = &td->tld; @@ -341,7 +346,8 @@ void mi_thread_init(void) mi_attr_noexcept // don't further initialize for the main thread if (_mi_is_main_thread()) return; - _mi_stat_increase(&mi_get_default_heap()->tld->stats.threads, 1); + mi_heap_t* heap = mi_get_default_heap(); + if (mi_heap_is_initialized(heap)) { _mi_stat_increase(&mi_get_default_heap()->tld->stats.threads, 1); } //_mi_verbose_message("thread init: 0x%zx\n", _mi_thread_id()); } diff --git a/src/page.c b/src/page.c index 18f1812e..c8a4e54b 100644 --- a/src/page.c +++ b/src/page.c @@ -816,6 +816,7 @@ void* _mi_malloc_generic(mi_heap_t* heap, size_t size) mi_attr_noexcept if (mi_unlikely(!mi_heap_is_initialized(heap))) { mi_thread_init(); // calls `_mi_heap_init` in turn heap = mi_get_default_heap(); + if (mi_unlikely(!mi_heap_is_initialized(heap))) { return NULL; } } mi_assert_internal(mi_heap_is_initialized(heap));