diff --git a/src/init.c b/src/init.c index b934f5fd..e12ac5d6 100644 --- a/src/init.c +++ b/src/init.c @@ -132,18 +132,13 @@ static const mi_tld_t tld_empty = { // the thread-local default heap for allocation mi_decl_thread mi_heap_t* _mi_heap_default = (mi_heap_t*)&_mi_heap_empty; - - -#define tld_main_stats ((mi_stats_t*)((uint8_t*)&tld_main + offsetof(mi_tld_t,stats))) -#define tld_main_os ((mi_os_tld_t*)((uint8_t*)&tld_main + offsetof(mi_tld_t,os))) - extern mi_heap_t _mi_heap_main; static mi_tld_t tld_main = { 0, false, &_mi_heap_main, & _mi_heap_main, - { MI_SEGMENT_SPAN_QUEUES_EMPTY, 0, 0, 0, 0, 0, 0, NULL, tld_main_stats, tld_main_os }, // segments - { 0, tld_main_stats }, // os + { MI_SEGMENT_SPAN_QUEUES_EMPTY, 0, 0, 0, 0, 0, 0, NULL, &tld_main.stats, &tld_main.os }, // segments + { 0, &tld_main.stats }, // os { MI_STATS_NULL } // stats }; @@ -205,10 +200,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; @@ -371,7 +371,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 8b74c47d..97438d75 100644 --- a/src/page.c +++ b/src/page.c @@ -841,6 +841,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));