@@ -4560,6 +4560,11 @@ static void* tmalloc_small(mstate m, size_t nb) {
45604560
45614561#if !ONLY_MSPACES
45624562
4563+ #if __wasilibc_unmodified_upstream // Forward declaration of try_init_allocator.
4564+ #else
4565+ static void try_init_allocator (void );
4566+ #endif
4567+
45634568void * dlmalloc (size_t bytes ) {
45644569 /*
45654570 Basic algorithm:
@@ -4588,6 +4593,13 @@ void* dlmalloc(size_t bytes) {
45884593 ensure_initialization (); /* initialize in sys_alloc if not using locks */
45894594#endif
45904595
4596+ #if __wasilibc_unmodified_upstream // Try to initialize the allocator.
4597+ #else
4598+ if (!is_initialized (gm )) {
4599+ try_init_allocator ();
4600+ }
4601+ #endif
4602+
45914603 if (!PREACTION (gm )) {
45924604 void * mem ;
45934605 size_t nb ;
@@ -5197,6 +5209,42 @@ static void internal_inspect_all(mstate m,
51975209}
51985210#endif /* MALLOC_INSPECT_ALL */
51995211
5212+ #ifdef __wasilibc_unmodified_upstream // Define a function that initializes the initial state of dlmalloc
5213+ #else
5214+ /* ------------------ Exported try_init_allocator -------------------- */
5215+
5216+ /* Symbol marking the end of data, bss and explicit stack, provided by wasm-ld. */
5217+ extern unsigned char __heap_base ;
5218+
5219+ /* Initialize the initial state of dlmalloc to be able to use free memory between __heap_base and initial. */
5220+ static void try_init_allocator (void ) {
5221+ /* Check that it is a first-time initialization. */
5222+ assert (!is_initialized (gm ));
5223+
5224+ char * base = (char * )& __heap_base ;
5225+ /* Calls sbrk(0) that returns the initial memory position. */
5226+ char * init = (char * )CALL_MORECORE (0 );
5227+ int initial_heap_size = init - base ;
5228+
5229+ /* Check that initial heap is long enough to serve a minimal allocation request. */
5230+ if (initial_heap_size <= MIN_CHUNK_SIZE + TOP_FOOT_SIZE + MALLOC_ALIGNMENT ) {
5231+ return ;
5232+ }
5233+
5234+ /* Initialize mstate. */
5235+ ensure_initialization ();
5236+
5237+ /* Initialize the dlmalloc internal state. */
5238+ gm -> least_addr = base ;
5239+ gm -> seg .base = base ;
5240+ gm -> seg .size = initial_heap_size ;
5241+ gm -> magic = mparams .magic ;
5242+ gm -> release_checks = MAX_RELEASE_CHECK_RATE ;
5243+ init_bins (gm );
5244+ init_top (gm , (mchunkptr )base , initial_heap_size - TOP_FOOT_SIZE );
5245+ }
5246+ #endif
5247+
52005248/* ------------------ Exported realloc, memalign, etc -------------------- */
52015249
52025250#if !ONLY_MSPACES
0 commit comments