Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
Upgrade vendored mimalloc 3.2.8->3.3.2 + platform-correct override; regen vendored checksums (#424)
Martin Vogeleab4148de867
diff --git a/Makefile.cbm b/Makefile.cbmindex 198b80e6c..3404ab56a 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -235,11 +235,34 @@ MONGOOSE_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -Ivendored -DMG_ENAB$(SANITIZE)# mimalloc (vendored, global allocator override)+#+# Override strategy is platform-specific:+# * Unix (macOS/Linux): rely on static-link-order override — the prod mimalloc+# object is linked first so its strong malloc/free symbols win. We do NOT+# define MI_MALLOC_OVERRIDE here: that would compile alloc-override.c's+# forwarding definitions (malloc/free/posix_memalign/...) which, on macOS's+# two-level namespace, makes the binary's free == mi_free while system+# libraries keep allocating via the system allocator — pointers crossing that+# boundary hit "mimalloc: error: mi_free: invalid pointer". (Repro:+# `codebase-memory-mcp index <dir>` aborted on every run.)+# * Windows (MinGW, static CRT): the link-order trick fails (#424's allocator+# mismatch), so we define MI_MALLOC_OVERRIDE=1 to compile the static-CRT+# override added in mimalloc 3.3.0 (the _MSC_VER / _ACRTIMP /+# _CRT_HYBRIDPATCHABLE entry points) which take precedence over the static+# CRT's malloc/free.+# Note: mimalloc's source gates the override body on MI_MALLOC_OVERRIDE (CMake+# derives it from the MI_OVERRIDE option); MI_OVERRIDE alone is not read by the+# source — it is kept here only as this project's prod/test marker.MIMALLOC_SRC = vendored/mimalloc/src/static.c+MIMALLOC_OVERRIDE_DEFINE :=+ifeq ($(IS_MINGW),yes)+MIMALLOC_OVERRIDE_DEFINE := -DMI_MALLOC_OVERRIDE=1+endifMIMALLOC_CFLAGS = -std=c11 -O2 -w \-Ivendored/mimalloc/include \-Ivendored/mimalloc/src \- -DMI_OVERRIDE=1+ -DMI_OVERRIDE=1 \+ $(MIMALLOC_OVERRIDE_DEFINE)MIMALLOC_CFLAGS_TEST = -std=c11 -g -O1 -w \-Ivendored/mimalloc/include \-Ivendored/mimalloc/src \diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex d497d0070..9c768aece 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -123,6 +123,19 @@ GENEOFRESULT=$(cli index_repository "{\"repo_path\":\"$TMPDIR\"}")echo "$RESULT"+# Allocator-integrity guard: the prod binary overrides the global allocator with+# mimalloc. A misconfigured override (e.g. compiling alloc-override.c's+# forwarding defs on a platform where system libs keep using the system+# allocator) corrupts free() and mimalloc prints "mimalloc: error: ..." to+# stderr — often WITHOUT a non-zero exit. Treat any such line as a hard failure.+if grep -qiE 'mimalloc: error|mi_free: invalid pointer|mi_assert' "$CLI_STDERR"; then+ echo "FAIL: mimalloc reported an allocator error during indexing"+ echo "--- stderr ---"+ cat "$CLI_STDERR"+ echo "--- end stderr ---"+ exit 1+fi+STATUS=$(echo "$RESULT" | python3 -c "import json,sys; d=json.loads(sys.stdin.read()); print(d.get('status',''))" 2>/dev/null || echo "")if [ "$STATUS" != "indexed" ]; thenecho "FAIL: index status is '$STATUS', expected 'indexed'"diff --git a/scripts/vendored-checksums.txt b/scripts/vendored-checksums.txtindex f1d2467bc..8bd534b87 100644--- a/scripts/vendored-checksums.txt+++ b/scripts/vendored-checksums.txt@@ -1,43 +1,43 @@dd4f25cae53209d45d73f8e6a2b9c219e8fc7434d97f20eba9af1a8b850030fd /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc-new-delete.h-243db1b073ce985873545b746288546efb8ccadeb9860e674a7f0f701af8bac9 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc-override.h-d8fa83fa364f31ad4cf64f8374d05c47de6b7533acc4bd7f754c156365ee887f /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc-stats.h-4da2c50ba4df75b730c734d5cf061fe2102f512c33d9be81f4447c65bdf0b498 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc.h-6e6c79c07c9b919b56bcbb401f24ab62c80efadc33f1e6b5d52f20c04dfb35d5 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/atomic.h-1be8a0b86f5aa7777aeb5c63e6ead510650e8dfca346a9afa2a177730548bbd3 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/bits.h-76c539614defd59f4ef47a2772115103947686cf3c60201aee22ad23ebb54fbb /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/internal.h-8cd6039a16578b2a0f1a10aa3f5655d1523c16b782cdced4dc0aeceb968ee2e3 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/prim.h-71df63d3f46168905ca18037e65f3d8bff3c6074c0409438ab962ac0036b1538 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/track.h-764f00e99e75aa53d03aa56856197e053e5be281f9359b90afcfb874d613f5ce /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/types.h-75b8b7ff54eef2e4eb0d9096b982271d107207c766b831bb440e980e814ba225 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-aligned.c-5e1e8512694566cd712c9e87e70746dcb635b05460b88c80e8bab80fa785b5b1 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-override.c-4110c34bbd3f212055354cca73303acc773f383a84e37e8db9d4df95338e374d /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-posix.c-b17f7ffa64b2fc6acc81ce83ecb1eb08cd84511df83992b54610ae93cedc987d /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc.c-7e5f22bfabfa6d489f59552f3e1f783c87e6bd1bffa137bd0f44c55643f2b8b6 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/arena-meta.c-6d8f16d215f9eedb79fe0574bca4a53937a0fe02c70957f6a5c35102a048e061 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/arena.c-88ecfe29bcb4f593b18b12cd38275170022c1ed5f6d3aace717b348041ad8846 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/bitmap.c-9436fbb74caf51f1335bf3346215fa8797479c5e49de53434ad65f0079e19d17 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/bitmap.h-870f684570f510d2223ac0f9dffb50c3313d305013b1b36a05c4775e6f3c5cd1 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/free.c-2acf977461f6d9b19882a1304639522878a3a29975fed29a2436c689f1d4440a /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/heap.c-6ca201e66cd8a6253aa7a49a02ce4e2a78dbb784590b6c981f0a86797e2d1a14 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/init.c-a73005e7f79be3ae492a91e744984ebc7c1caae2c2a848cc6ee24ae27554bdba /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/libc.c-66923db208586382f61bb1d2af6aafc0d953e8a05ce1df9a1a523a69c433d72d /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/options.c-57adf368243ed88579d30b0dba8c269c392f84a0f7a1942565a1573a5e7a4b73 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/os.c-aa1c547629e863341580605079935363505cf14e25e5b67bcb4505e2cab5f7b4 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page-map.c-4acfd399659053c3aa07167708c47a3a9566d7e77632f01249994bd577f6ec01 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page-queue.c-64e5ed0391dfeddb4d1074605e8b3b023026ba2892e46fbd034dc5bcdce6f02d /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page.c-3a47caa3c5ab0320e7d802f54cd8c48a8fa37c168bf5885f9d7b8b1efe778ca7 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/emscripten/prim.c-d732b1d8bae4e8ede6d1e68a9d002dd0470b33f9ac5269dd932f558f311fbf09 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/osx/alloc-override-zone.c+21fcf61c4443341ac6bf6ea528af31dc7267e8e3456fc64bfd07704503032175 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc-override.h+5260df227ea1612b8678a06b063cc8f48e739b551554541cdeb4d430a7e257b3 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc-stats.h+869161433ab2d807a75752d0762accf5b68b6b24ce67e417af46bf181b9b6c72 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc.h+e9512b521a82cc0cbc262f6060dd70bb4243ac4a7d69d6ab8b1ef8e56f181a21 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/atomic.h+57a7297e18ae464a7bfd3fc25a46229008602385697305c69ed289b89ece7631 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/bits.h+5aeeff21d667daf4aadcc66f634aa957ecd688d15b277828f367c8c2274251a8 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/internal.h+555302d2fcd05e974441d0c9c9208c26e860db4b3f17b9025a08f42e0f4807ba /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/prim.h+1f378b4b6063c078d2aeb5d916c1d30b5db787a44ab9118e7daf673b086882c6 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/track.h+b54e760da2a8d9d8a9cb708e280268c2d194c99bc518b21f72db70100578ad6a /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/include/mimalloc/types.h+70420b4430da4bb6b5197fd27c6c0df485249c53a986bc9536c9fb643fc7613b /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-aligned.c+6c8e9b0d042481c55791edb7330daec64bedaf26f0e70c9ca40de3cc17a690fe /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-override.c+98d0eb877d7b9cdf7e9f857aaf3c739b69f746b91221e0e427e82bdd7cec90b3 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc-posix.c+a92d58e47220e5b6d138b83d92498771be4195ee59136a134e4461f6f726b9b8 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/alloc.c+86fde644ede2e8d582e53499568a1713516a20326e0350eaa06a28029cece91b /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/arena-meta.c+a1d6900d2b9a17461aa2a72a7791dfb22f6167b86f7ac6f15f981d9735aa2adb /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/arena.c+de16033e029488e9ade4152ea1274e1a5ecbdc2c8a8d8ee50b745fd037ee6f6c /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/bitmap.c+2e7a54ff44592a1fe8fe929e691322622f8aa1e0b1e80954781f332a88dd6cd1 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/bitmap.h+c9a845dd7b9020f26d73761d235fb75e7bc4a3682576de750050ac4098211b43 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/free.c+ae8e88737c9861e8e071fe5f1e7acc52093bcffd136a359a6b473101e968c14f /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/heap.c+eca1fe77d72ab2aaccc447c8119056e9c4e8851bda9a95472b573539f76107ad /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/init.c+ebd95b475f15d5387e6ef3c88a9cb47b88e64d7e55998ae1dc656614676a443b /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/libc.c+96ef01e41f4b3043118e8c801e660b1d3f185d6fb824e5298a038aee89b6a392 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/options.c+011e965f28c0e2c885a6834d51bd756a458dd37ebfed6fd4d9ad6607ce0390ed /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/os.c+1be3a208c678fc34187c2a8ffb75f3fe1eecc674bbf8b2af4d1f329506b1fad5 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page-map.c+7ec275805c9f00eb66710ffa99817b3ed1dba9826435d08f4866f7935152f6ae /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page-queue.c+d3614a59f2407a32e75b051deb1aff31b233f587d325dcc5420ba508551b687e /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/page.c+7488e9e562ca85d2d757ec48e4d334935263a2333aa05b6061d8520f427c5890 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/emscripten/prim.c+ce14eb6dfd55f241095b55f70983931a2d92f7a6a622a9b360cdd70ab3b53208 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/osx/alloc-override-zone.c247a9952465eb105be03a9962e922b085ce5d52034775551a61cd8594275be73 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/osx/prim.ccc771788e5ba591efb681829a8724f8662a1f50f3db39cf5ebe7738b8ed57e44 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/prim.c-bffb37e2d9b49926ee38630ea74928cd0dc501c2ddbff9921b0b756a8e52eb63 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/unix/prim.c-6aa2a235bd87a36b134ba7c362f31cfa776032dcbe2ee2cd06a48992be0ed586 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/wasi/prim.c+c1ae32eaac7ccf18c10058cca99723892f8bd027318590151f5011c929c7e3be /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/unix/prim.c+bee9c655a17e1e93bf4908e0a902fd3b566628447b1446fcbfa92bca2e76ca15 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/wasi/prim.c4f3110ef2054c95cb275be96cb279224d3d46a728c5117bd1435425f382de778 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/windows/etw.h-56c25c6eb535b20c7f4f5200567fa4d8055ec2331ef1f2f1d45421f7f1aaf26c /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/windows/prim.c-6f061e2eb12a1421b1987c89a3ef72737d0b45e55ba7bec6571d0548d1a8b1de /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/random.c+5cde60fcef94cd79ab816030be00f8c1bdf18fab343563508c681ec6e762d1f1 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/prim/windows/prim.c+a96a1acc75fd6595811b28420cf0495b87fac98c4dbc73aa0d742b6824f607c8 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/random.c4059be2a6676693be3433f5aedc711f56301772e65f3573654c236d6d1cfd074 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/static.c-dbddfce623493448ba8f0fe42e28cb89b262b8202e979e1edfadbaa36c3190b4 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/stats.c-dfe152dadbc3d762b57e51dee2ddb405d15a0a3b73b9fb118d4d54d400196983 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/theap.c-45b14df16dee692ed0515e0da61bf477d23fe503da9eaf3b438ef62202f5877f /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/threadlocal.c+16825bbc252de422982b5728df7eda181d952824f5e3ce958c7fc85feae64b8e /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/stats.c+7f76bcace4b0578f2063477752138adabd99f7b10a276998e296a312c47a7cfe /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/theap.c+49be69a4b674e09690a63870830f3ffb05698ed4210949ef5add11957a08325b /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mimalloc/src/threadlocal.ccb23c6e2782eb6a115beb0bb41d66dfb31ccf9eeb4b0950788895dc9963ccda3 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mongoose/mongoose.c008e31c8006e42983e0f3d7efbf123101de817d9eabe55a2c051159d2da59f19 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/mongoose/mongoose.hdab3009c0d76b0c5e05ad8abc7c9f8f6effca547fea3c0394be96418a85c1081 /Users/martinvogel/project_dir/codebase-memory-mcp/vendored/nomic/code_tokens.hdiff --git a/vendored/mimalloc/include/mimalloc-override.h b/vendored/mimalloc/include/mimalloc-override.hindex 48a8a6226..46e054528 100644--- a/vendored/mimalloc/include/mimalloc-override.h+++ b/vendored/mimalloc/include/mimalloc-override.h@@ -19,7 +19,7 @@ not accidentally mix pointers from different allocators).// Standard C allocation#define malloc(n) mi_malloc(n)-#define calloc(n,c) mi_calloc(n,c)+#define calloc(c,n) mi_calloc(c,n)#define realloc(p,n) mi_realloc(p,n)#define free(p) mi_free(p)@@ -30,26 +30,26 @@ not accidentally mix pointers from different allocators).// Microsoft extensions#define _expand(p,n) mi_expand(p,n)#define _msize(p) mi_usable_size(p)-#define _recalloc(p,n,c) mi_recalloc(p,n,c)+#define _recalloc(p,c,n) mi_recalloc(p,c,n)#define _strdup(s) mi_strdup(s)#define _strndup(s,n) mi_strndup(s,n)-#define _wcsdup(s) (wchar_t*)mi_wcsdup((const unsigned short*)(s))+#define _wcsdup(s) mi_wcsdup(s)#define _mbsdup(s) mi_mbsdup(s)-#define _dupenv_s(b,n,v) mi_dupenv_s(b,n,v)-#define _wdupenv_s(b,n,v) mi_wdupenv_s((unsigned short*)(b),n,(const unsigned short*)(v))+#define _dupenv_s(buf,n,nm) mi_dupenv_s(buf,n,nm)+#define _wdupenv_s(buf,n,nm) mi_wdupenv_s(buf,n,nm)// Various Posix and Unix variants#define reallocf(p,n) mi_reallocf(p,n)#define malloc_size(p) mi_usable_size(p)#define malloc_usable_size(p) mi_usable_size(p)-#define malloc_good_size(sz) mi_malloc_good_size(sz)+#define malloc_good_size(n) mi_malloc_good_size(n)#define cfree(p) mi_free(p)#define valloc(n) mi_valloc(n)#define pvalloc(n) mi_pvalloc(n)-#define reallocarray(p,s,n) mi_reallocarray(p,s,n)-#define reallocarr(p,s,n) mi_reallocarr(p,s,n)+#define reallocarray(p,c,n) mi_reallocarray(p,c,n)+#define reallocarr(ptrp,c,n) mi_reallocarr(ptrp,c,n)#define memalign(a,n) mi_memalign(a,n)#define aligned_alloc(a,n) mi_aligned_alloc(a,n)#define posix_memalign(p,a,n) mi_posix_memalign(p,a,n)@@ -58,11 +58,11 @@ not accidentally mix pointers from different allocators).// Microsoft aligned variants#define _aligned_malloc(n,a) mi_malloc_aligned(n,a)#define _aligned_realloc(p,n,a) mi_realloc_aligned(p,n,a)-#define _aligned_recalloc(p,s,n,a) mi_aligned_recalloc(p,s,n,a)+#define _aligned_recalloc(p,c,n,a) mi_aligned_recalloc(p,c,n,a)#define _aligned_msize(p,a,o) mi_usable_size(p)#define _aligned_free(p) mi_free(p)#define _aligned_offset_malloc(n,a,o) mi_malloc_aligned_at(n,a,o)#define _aligned_offset_realloc(p,n,a,o) mi_realloc_aligned_at(p,n,a,o)-#define _aligned_offset_recalloc(p,s,n,a,o) mi_recalloc_aligned_at(p,s,n,a,o)+#define _aligned_offset_recalloc(p,c,n,a,o) mi_recalloc_aligned_at(p,c,n,a,o)#endif // MIMALLOC_OVERRIDE_Hdiff --git a/vendored/mimalloc/include/mimalloc-stats.h b/vendored/mimalloc/include/mimalloc-stats.hindex a714f41c7..1c620fd1c 100644--- a/vendored/mimalloc/include/mimalloc-stats.h+++ b/vendored/mimalloc/include/mimalloc-stats.h@@ -9,9 +9,10 @@ terms of the MIT license. A copy of the license can be found in the file#define MIMALLOC_STATS_H#include <mimalloc.h>-#include <stdint.h>+#include <string.h> // memset+#include <stdint.h> // int64_t-#define MI_STAT_VERSION 4 // increased on every backward incompatible change+#define MI_STAT_VERSION 5 // increased on every backward incompatible change// alignment for atomic fields#if defined(_MSC_VER)@@ -44,7 +45,7 @@ typedef struct mi_stat_counter_s {MI_STAT_COUNTER(reset) /* reset bytes */ \MI_STAT_COUNTER(purged) /* purged bytes */ \MI_STAT_COUNT(page_committed) /* committed memory inside pages */ \- MI_STAT_COUNT(pages_abandoned) /* abandonded pages count */ \+ MI_STAT_COUNT(pages_abandoned) /* abandoned pages count */ \MI_STAT_COUNT(threads) /* number of threads */ \MI_STAT_COUNT(malloc_normal) /* allocated bytes <= MI_LARGE_OBJ_SIZE_MAX */ \MI_STAT_COUNT(malloc_huge) /* allocated bytes in huge pages */ \@@ -73,10 +74,12 @@ typedef struct mi_stat_counter_s {MI_STAT_COUNT(_segments_reserved) \/* only on v3 */ \MI_STAT_COUNT(heaps) \+ MI_STAT_COUNT(theaps) \MI_STAT_COUNTER(pages_reclaim_on_alloc) \MI_STAT_COUNTER(pages_reclaim_on_free) \MI_STAT_COUNTER(pages_reabandon_full) \- MI_STAT_COUNTER(pages_unabandon_busy_wait)+ MI_STAT_COUNTER(pages_unabandon_busy_wait) \+ MI_STAT_COUNTER(heaps_delete_wait)// Size bins for chunkstypedef enum mi_chunkbin_e {@@ -115,8 +118,17 @@ typedef struct mi_stats_s#undef MI_STAT_COUNT#undef MI_STAT_COUNTER-// helper-#define mi_stats_t_decl(name) mi_stats_t name = { 0 }; name.size = sizeof(mi_stats_t); name.version = MI_STAT_VERSION;+// Initialization+static inline void mi_stats_header_init(mi_stats_t* stats) {+ stats->size = sizeof(*stats);+ stats->version = MI_STAT_VERSION;+}+static inline void mi_stats_init(mi_stats_t* stats) {+ memset(stats,0,sizeof(*stats));+ mi_stats_header_init(stats);+}++#define mi_stats_t_decl(name) mi_stats_t name; mi_stats_init(&name);// Exported definitions#ifdef __cplusplusdiff --git a/vendored/mimalloc/include/mimalloc.h b/vendored/mimalloc/include/mimalloc.hindex bf570d155..f373f5dc8 100644--- a/vendored/mimalloc/include/mimalloc.h+++ b/vendored/mimalloc/include/mimalloc.h@@ -8,7 +8,7 @@ terms of the MIT license. A copy of the license can be found in the file#ifndef MIMALLOC_H#define MIMALLOC_H-#define MI_MALLOC_VERSION 3208 // major + minor + 2 digits patch+#define MI_MALLOC_VERSION 30302 // major + 2 digits minor + 2 digits patch// ------------------------------------------------------// Compiler specific attributes@@ -114,7 +114,7 @@ mi_decl_export void* mi_expand(void* p, size_t newsize)mi_decl_export void mi_free(void* p) mi_attr_noexcept;mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_strdup(const char* s) mi_attr_noexcept mi_attr_malloc;mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_strndup(const char* s, size_t n) mi_attr_noexcept mi_attr_malloc;-mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_realpath(const char* fname, char* resolved_name) mi_attr_noexcept mi_attr_malloc;+mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_realpath(const char* fname, char* resolved_name) mi_attr_noexcept;// ------------------------------------------------------// Extended allocation functions@@ -133,6 +133,9 @@ mi_decl_nodiscard mi_decl_export void* mi_reallocf(void* p, size_t newsize)mi_decl_nodiscard mi_decl_export size_t mi_usable_size(const void* p) mi_attr_noexcept;mi_decl_nodiscard mi_decl_export size_t mi_good_size(size_t size) mi_attr_noexcept;+// `mi_free_small` is for special applications like language runtimes.+// it should only be used to free objects from `mi_(heap_)(m|z)alloc_small` and is potentially a tiny bit faster than `mi_free`+mi_decl_export void mi_free_small(void* p) mi_attr_noexcept;// -------------------------------------------------------------------------------------// Aligned allocation@@ -242,7 +245,8 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc(mi_heap_tmi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_zalloc(mi_heap_t* heap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_calloc(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(2, 3);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_mallocn(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(2, 3);-mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc_small(mi_heap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);+mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc_small(mi_heap_t* heap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);+mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_zalloc_small(mi_heap_t* heap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);mi_decl_nodiscard mi_decl_export void* mi_heap_realloc(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3);mi_decl_nodiscard mi_decl_export void* mi_heap_reallocn(mi_heap_t* heap, void* p, size_t count, size_t size) mi_attr_noexcept mi_attr_alloc_size2(3, 4);@@ -250,7 +254,7 @@ mi_decl_nodiscard mi_decl_export void* mi_heap_reallocf(mi_heap_t* theap, void*mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_heap_strdup(mi_heap_t* heap, const char* s) mi_attr_noexcept mi_attr_malloc;mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_heap_strndup(mi_heap_t* heap, const char* s, size_t n) mi_attr_noexcept mi_attr_malloc;-mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_heap_realpath(mi_heap_t* heap, const char* fname, char* resolved_name) mi_attr_noexcept mi_attr_malloc;+mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_heap_realpath(mi_heap_t* heap, const char* fname, char* resolved_name) mi_attr_noexcept;mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc_aligned(mi_heap_t* heap, size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2) mi_attr_alloc_align(3);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc_aligned_at(mi_heap_t* heap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);@@ -324,6 +328,7 @@ mi_decl_export bool mi_manage_os_memory(void* start, size_t size, bool is_commmi_decl_export void mi_debug_show_arenas(void) mi_attr_noexcept;mi_decl_export void mi_arenas_print(void) mi_attr_noexcept;mi_decl_export size_t mi_arena_min_alignment(void);+mi_decl_export size_t mi_arena_min_size(void);typedef void* mi_arena_id_t;mi_decl_export void* mi_arena_area(mi_arena_id_t arena_id, size_t* size);@@ -342,7 +347,7 @@ mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t a// Used for example for separate interpreters in one process.// -------------------------------------------------------typedef void* mi_subproc_id_t;+typedef struct { void* _mi_subproc_id; } mi_subproc_id_t; // abstract typemi_decl_export mi_subproc_id_t mi_subproc_main(void);mi_decl_export mi_subproc_id_t mi_subproc_current(void);mi_decl_export mi_subproc_id_t mi_subproc_new(void);@@ -375,6 +380,7 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_malloc(mi_theapmi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_zalloc(mi_theap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_calloc(mi_theap_t* theap, size_t count, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(2, 3);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_malloc_small(mi_theap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);+mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_zalloc_small(mi_theap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_malloc_aligned(mi_theap_t* theap, size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2) mi_attr_alloc_align(3);mi_decl_nodiscard mi_decl_export void* mi_theap_realloc(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3);@@ -401,6 +407,8 @@ mi_decl_export bool mi_manage_memory(void* start, size_t size, bool is_committe//mi_decl_export bool mi_theap_reload(mi_theap_t* theap, mi_arena_id_t arena);//mi_decl_export void mi_theap_unload(mi_theap_t* theap);+// unsafe: assumes the page belonging to `p` is only accessed by the calling thread.+mi_decl_export bool mi_unsafe_heap_page_is_under_utilized(mi_heap_t* heap, void* p, size_t perc_threshold) mi_attr_noexcept;// ------------------------------------------------------// Deprecated@@ -422,7 +430,6 @@ mi_decl_export void mi_stats_print(void* out) mi_attr_noexcept; // backward commi_decl_export void mi_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; // not deprecated but declared in `mimalloc-stats.h` now.-// ------------------------------------------------------// Options// ------------------------------------------------------@@ -476,6 +483,7 @@ typedef enum mi_option_e {mi_option_allow_thp, // allow transparent huge pages? (=1) (on Android =0 by default). Set to 0 to disable THP for the process.mi_option_minimal_purge_size, // set minimal purge size (in KiB) (=0). By default set to either 64 or 2048 if THP is enabled.mi_option_arena_max_object_size, // set maximal object size that can be allocated in an arena (in KiB) (=2GiB on 64-bit).+ mi_option_arena_is_numa_local, // experimental_mi_option_last,// legacy option namesmi_option_large_os_pages = mi_option_allow_large_os_pages,@@ -518,18 +526,20 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_pvalloc(size_t size)mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_aligned_alloc(size_t alignment, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2) mi_attr_alloc_align(1);mi_decl_nodiscard mi_decl_export void* mi_reallocarray(void* p, size_t count, size_t size) mi_attr_noexcept mi_attr_alloc_size2(2,3);-mi_decl_nodiscard mi_decl_export int mi_reallocarr(void* p, size_t count, size_t size) mi_attr_noexcept;+mi_decl_nodiscard mi_decl_export int mi_reallocarr(void* ptrp, size_t count, size_t size) mi_attr_noexcept;mi_decl_nodiscard mi_decl_export void* mi_aligned_recalloc(void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept;mi_decl_nodiscard mi_decl_export void* mi_aligned_offset_recalloc(void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept;-mi_decl_nodiscard mi_decl_export mi_decl_restrict unsigned short* mi_wcsdup(const unsigned short* s) mi_attr_noexcept mi_attr_malloc;-mi_decl_nodiscard mi_decl_export mi_decl_restrict unsigned char* mi_mbsdup(const unsigned char* s) mi_attr_noexcept mi_attr_malloc;-mi_decl_export int mi_dupenv_s(char** buf, size_t* size, const char* name) mi_attr_noexcept;-mi_decl_export int mi_wdupenv_s(unsigned short** buf, size_t* size, const unsigned short* name) mi_attr_noexcept;-mi_decl_export void mi_free_size(void* p, size_t size) mi_attr_noexcept;mi_decl_export void mi_free_size_aligned(void* p, size_t size, size_t alignment) mi_attr_noexcept;mi_decl_export void mi_free_aligned(void* p, size_t alignment) mi_attr_noexcept;+mi_decl_export int mi_dupenv_s(char** buf, size_t* size, const char* name) mi_attr_noexcept;++// wide characters+#include <wchar.h> // wchar_t+mi_decl_export int mi_wdupenv_s(wchar_t** buf, size_t* size, const wchar_t* name) mi_attr_noexcept;+mi_decl_nodiscard mi_decl_export mi_decl_restrict wchar_t* mi_wcsdup(const wchar_t* s) mi_attr_noexcept mi_attr_malloc;+mi_decl_nodiscard mi_decl_export mi_decl_restrict unsigned char* mi_mbsdup(const unsigned char* s) mi_attr_noexcept mi_attr_malloc;// The `mi_new` wrappers implement C++ semantics on out-of-memory instead of directly returning `NULL`.// (and call `std::get_new_handler` and potentially raise a `std::bad_alloc` exception).diff --git a/vendored/mimalloc/include/mimalloc/atomic.h b/vendored/mimalloc/include/mimalloc/atomic.hindex 699c78b45..e4abde6b0 100644--- a/vendored/mimalloc/include/mimalloc/atomic.h+++ b/vendored/mimalloc/include/mimalloc/atomic.h@@ -97,7 +97,6 @@ terms of the MIT license. A copy of the license can be found in the file#define mi_atomic_increment_acq_rel(p) mi_atomic_add_acq_rel(p,(uintptr_t)1)#define mi_atomic_decrement_acq_rel(p) mi_atomic_sub_acq_rel(p,(uintptr_t)1)-static inline void mi_atomic_yield(void);static inline intptr_t mi_atomic_addi(_Atomic(intptr_t)*p, intptr_t add);static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub);@@ -159,14 +158,18 @@ static inline void mi_atomic_maxi64_relaxed(volatile int64_t* p, int64_t x) {#elif defined(_MSC_VER)-// Legacy MSVC plain C compilation wrapper that uses Interlocked operations to model C11 atomics.+// Deprecated: MSVC plain C compilation wrapper that uses Interlocked operations to model C11 atomics.+// It is recommended to always compile as C++ when using MSVC.+#include <intrin.h>#ifdef _WIN64-typedef LONG64 msc_intptr_t;-#define MI_64(f) f##64+typedef LONG64 msc_intptr_t;+#define MI_MSC_64(f) f##64+#define MI_MSC_XX(f) f##64#else-typedef LONG msc_intptr_t;-#define MI_64(f) f+typedef LONG msc_intptr_t;+#define MI_MSC_64(f) f+#define MI_MSC_XX(f) f##32#endiftypedef enum mi_memory_order_e {@@ -180,23 +183,23 @@ typedef enum mi_memory_order_e {static inline uintptr_t mi_atomic_fetch_add_explicit(_Atomic(uintptr_t)*p, uintptr_t add, mi_memory_order mo) {(void)(mo);- return (uintptr_t)MI_64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, (msc_intptr_t)add);+ return (uintptr_t)MI_MSC_64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, (msc_intptr_t)add);}static inline uintptr_t mi_atomic_fetch_sub_explicit(_Atomic(uintptr_t)*p, uintptr_t sub, mi_memory_order mo) {(void)(mo);- return (uintptr_t)MI_64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, -((msc_intptr_t)sub));+ return (uintptr_t)MI_MSC_64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, -((msc_intptr_t)sub));}static inline uintptr_t mi_atomic_fetch_and_explicit(_Atomic(uintptr_t)*p, uintptr_t x, mi_memory_order mo) {(void)(mo);- return (uintptr_t)MI_64(_InterlockedAnd)((volatile msc_intptr_t*)p, (msc_intptr_t)x);+ return (uintptr_t)MI_MSC_64(_InterlockedAnd)((volatile msc_intptr_t*)p, (msc_intptr_t)x);}static inline uintptr_t mi_atomic_fetch_or_explicit(_Atomic(uintptr_t)*p, uintptr_t x, mi_memory_order mo) {(void)(mo);- return (uintptr_t)MI_64(_InterlockedOr)((volatile msc_intptr_t*)p, (msc_intptr_t)x);+ return (uintptr_t)MI_MSC_64(_InterlockedOr)((volatile msc_intptr_t*)p, (msc_intptr_t)x);}static inline bool mi_atomic_compare_exchange_strong_explicit(_Atomic(uintptr_t)*p, uintptr_t* expected, uintptr_t desired, mi_memory_order mo1, mi_memory_order mo2) {(void)(mo1); (void)(mo2);- uintptr_t read = (uintptr_t)MI_64(_InterlockedCompareExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)desired, (msc_intptr_t)(*expected));+ const uintptr_t read = (uintptr_t)MI_MSC_64(_InterlockedCompareExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)desired, (msc_intptr_t)(*expected));if (read == *expected) {return true;}@@ -210,68 +213,119 @@ static inline bool mi_atomic_compare_exchange_weak_explicit(_Atomic(uintptr_t)*p}static inline uintptr_t mi_atomic_exchange_explicit(_Atomic(uintptr_t)*p, uintptr_t exchange, mi_memory_order mo) {(void)(mo);- return (uintptr_t)MI_64(_InterlockedExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)exchange);+ return (uintptr_t)MI_MSC_64(_InterlockedExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)exchange);}static inline void mi_atomic_thread_fence(mi_memory_order mo) {(void)(mo);_Atomic(uintptr_t) x = 0;mi_atomic_exchange_explicit(&x, 1, mo);}+static inline uintptr_t mi_atomic_load_explicit(_Atomic(uintptr_t) const* p, mi_memory_order mo) {(void)(mo);-#if defined(_M_IX86) || defined(_M_X64)- return *p;-#else- uintptr_t x = *p;- if (mo > mi_memory_order_relaxed) {- while (!mi_atomic_compare_exchange_weak_explicit((_Atomic(uintptr_t)*)p, &x, x, mo, mi_memory_order_relaxed)) { /* nothing */ };- }- return x;-#endif+ // assert(mo<=mi_memory_order_acquire); // others are not used by mimalloc+ #if defined(_M_IX86) || defined(_M_X64)+ return (uintptr_t)MI_MSC_XX(__iso_volatile_load)((volatile const intptr_t*)p);+ #elif defined(_M_ARM) || defined(_M_ARM64)+ if (mo == mi_memory_order_relaxed) {+ return (uintptr_t)MI_MSC_XX(__iso_volatile_load)((volatile const intptr_t*)p);+ }+ else if (mo <= mi_memory_order_acquire) {+ return MI_MSC_XX(__ldar)((volatile const uintptr_t*)p);+ }+ else {+ const uintptr_t u = (uintptr_t)MI_MSC_XX(__iso_volatile_load)((volatile const intptr_t*)p);+ __dmb(15); // _ARM(64)_BARRIER_SY+ return u;+ }+ #else+ #warning "define mi_atomic_load_explicit for MSVC C compilation on this platform (which should be readonly, see issue #1277)"+ return MI_MSC_XX(__iso_volatile_load)((volatile const intptr_t*)p);+ #endif}static inline void mi_atomic_store_explicit(_Atomic(uintptr_t)*p, uintptr_t x, mi_memory_order mo) {(void)(mo);-#if defined(_M_IX86) || defined(_M_X64)- *p = x;-#else- mi_atomic_exchange_explicit(p, x, mo);-#endif+ // assert(mo<=mi_memory_order_release); // others are not used by mimalloc+ #if defined(_M_IX86) || defined(_M_X64)+ MI_MSC_XX(__iso_volatile_store)((volatile intptr_t*)p, x);+ #elif defined(_M_ARM) || defined(_M_ARM64)+ if (mo == mi_memory_order_relaxed) {+ MI_MSC_XX(__iso_volatile_store)((volatile intptr_t*)p, x);+ }+ else if (mo <= mi_memory_order_release) {+ MI_MSC_XX(__stlr)((volatile uintptr_t*)p,x);+ }+ else {+ mi_atomic_exchange_explicit(p, x, mo);+ }+ #else+ mi_atomic_exchange_explicit(p, x, mo);+ #endif}+static inline int64_t mi_atomic_loadi64_explicit(_Atomic(int64_t)*p, mi_memory_order mo) {(void)(mo);-#if defined(_M_X64)- return *p;-#else- int64_t old = *p;- int64_t x = old;- while ((old = InterlockedCompareExchange64(p, x, old)) != x) {- x = old;- }- return x;-#endif+ // assert(mo<=mi_memory_order_acquire); // others are not used by mimalloc+ #if defined(_M_IX86) || defined(_M_X64)+ return __iso_volatile_load64((volatile const int64_t*)p);+ #elif defined(_M_ARM) || defined(_M_ARM64)+ if (mo == mi_memory_order_relaxed) {+ return __iso_volatile_load64((volatile const int64_t*)p);+ }+ #if defined(_M_ARM64)+ else if (mo <= mi_memory_order_acquire) {+ return __ldar64((volatile const uintptr_t*)p);+ }+ #endif+ else {+ const int64_t i = __iso_volatile_load64((volatile const int64_t*)p);+ __dmb(15); // _ARM(64)_BARRIER_SY+ return i;+ }+ #else+ #warning "define mi_atomic_loadi64_explicit for MSVC C compilation on this platform (which should be readonly, see issue #1277)"+ return __iso_volatile_load64((volatile const int64_t*)p);+ #endif}+static inline void mi_atomic_storei64_explicit(_Atomic(int64_t)*p, int64_t x, mi_memory_order mo) {(void)(mo);-#if defined(x_M_IX86) || defined(_M_X64)- *p = x;-#else- InterlockedExchange64(p, x);-#endif+ // assert(mo<=mi_memory_order_release); // others are not used by mimalloc+ #if defined(_M_IX86) || defined(_M_X64)+ __iso_volatile_store64((volatile int64_t*)p,x);+ #elif defined(_M_ARM) || defined(_M_ARM64)+ if (mo == mi_memory_order_relaxed) {+ __iso_volatile_store64((volatile int64_t*)p,x);+ }+ #if defined(_M_ARM64)+ else if (mo == mi_memory_order_release) {+ __stlr64((volatile uint64_t*)p, (uint64_t)x);+ }+ #endif+ else {+ InterlockedExchange64(p, x);+ }+ #else+ InterlockedExchange64(p, x);+ #endif}// These are used by the statisticsstatic inline int64_t mi_atomic_addi64_relaxed(volatile _Atomic(int64_t)*p, int64_t add) {-#ifdef _WIN64- return (int64_t)mi_atomic_addi((int64_t*)p, add);-#else- int64_t current;- int64_t sum;- do {- current = *p;- sum = current + add;- } while (_InterlockedCompareExchange64(p, sum, current) != current);- return current;-#endif+ #ifdef _WIN64+ return (int64_t)mi_atomic_addi((int64_t*)p, add);+ #elif defined(_M_ARM)+ return _InterlockedExchangeAdd64(p, add);+ #else+ // x86+ int64_t current;+ int64_t sum;+ do {+ current = __iso_volatile_load64((volatile const int64_t*)p);+ sum = current + add;+ } while (_InterlockedCompareExchange64(p, sum, current) != current);+ return current;+ #endif}static inline void mi_atomic_void_addi64_relaxed(volatile int64_t* p, const volatile int64_t* padd) {@@ -293,7 +347,7 @@ static inline void mi_atomic_addi64_acq_rel(volatile _Atomic(int64_t*)p, int64_t}static inline bool mi_atomic_casi64_strong_acq_rel(volatile _Atomic(int64_t*)p, int64_t* exp, int64_t des) {- int64_t read = _InterlockedCompareExchange64(p, des, *exp);+ const int64_t read = _InterlockedCompareExchange64(p, des, *exp);if (read == *exp) {return true;}@@ -337,21 +391,12 @@ static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub) {// -----------------------------------------------------------------------// Once and Guard+// Guard// -----------------------------------------------------------------------typedef _Atomic(uintptr_t) mi_atomic_once_t;--// Returns true only on the first invocation-static inline bool mi_atomic_once( mi_atomic_once_t* once ) {- if (mi_atomic_load_relaxed(once) != 0) return false; // quick test- uintptr_t expected = 0;- return mi_atomic_cas_strong_acq_rel(once, &expected, (uintptr_t)1); // try to set to 1-}-typedef _Atomic(uintptr_t) mi_atomic_guard_t;-// Allows only one thread to execute at a time+// Allows only one thread to execute at a time (without blocking anyone)#define mi_atomic_guard(guard) \uintptr_t _mi_guard_expected = 0; \for(bool _mi_guard_once = true; \@@ -359,77 +404,6 @@ typedef _Atomic(uintptr_t) mi_atomic_guard_t;(mi_atomic_store_release(guard,(uintptr_t)0), _mi_guard_once = false) )--// -----------------------------------------------------------------------// Yield-// ------------------------------------------------------------------------#if defined(__cplusplus)-#include <thread>-static inline void mi_atomic_yield(void) {- std::this_thread::yield();-}-#elif defined(_WIN32)-static inline void mi_atomic_yield(void) {- YieldProcessor();-}-#elif defined(__SSE2__)-#include <emmintrin.h>-static inline void mi_atomic_yield(void) {- _mm_pause();-}-#elif (defined(__GNUC__) || defined(__clang__)) && \- (defined(__x86_64__) || defined(__i386__) || \- defined(__aarch64__) || defined(__arm__) || \- defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) || defined(__POWERPC__))-#if defined(__x86_64__) || defined(__i386__)-static inline void mi_atomic_yield(void) {- __asm__ volatile ("pause" ::: "memory");-}-#elif defined(__aarch64__)-static inline void mi_atomic_yield(void) {- __asm__ volatile("wfe");-}-#elif defined(__arm__)-#if __ARM_ARCH >= 7-static inline void mi_atomic_yield(void) {- __asm__ volatile("yield" ::: "memory");-}-#else-static inline void mi_atomic_yield(void) {- __asm__ volatile ("nop" ::: "memory");-}-#endif-#elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) || defined(__POWERPC__)-#ifdef __APPLE__-static inline void mi_atomic_yield(void) {- __asm__ volatile ("or r27,r27,r27" ::: "memory");-}-#else-static inline void mi_atomic_yield(void) {- __asm__ __volatile__ ("or 27,27,27" ::: "memory");-}-#endif-#endif-#elif defined(__sun)-// Fallback for other archs-#include <synch.h>-static inline void mi_atomic_yield(void) {- smt_pause();-}-#elif defined(__wasi__)-#include <sched.h>-static inline void mi_atomic_yield(void) {- sched_yield();-}-#else-#include <unistd.h>-static inline void mi_atomic_yield(void) {- sleep(0);-}-#endif--// ----------------------------------------------------------------------// Locks// These should be light-weight in-process only locks.@@ -439,95 +413,90 @@ static inline void mi_atomic_yield(void) {#pragma warning(disable:26110) // unlock with holding lock#endif-#define mi_lock(lock) for(bool _go = (mi_lock_acquire(lock),true); _go; (mi_lock_release(lock), _go=false) )+#define mi_lock(lock) for(bool _mi_go = (mi_lock_acquire(lock),true); _mi_go; (mi_lock_release(lock), _mi_go=false) )+#define mi_lock_maybe(lock,acquire) for(bool _mi_go = (acquire ? (mi_lock_acquire(lock),true) : true); _mi_go; _mi_go = (acquire ? (mi_lock_release(lock),false) : false) )+#if defined(_WIN32)-#if 1-#define mi_lock_t SRWLOCK // slim reader-writer lock+typedef struct mi_lock_s {+ SRWLOCK mutex; // slim reader-writer lock+} mi_lock_t;-static inline bool mi_lock_try_acquire(mi_lock_t* lock) {- return TryAcquireSRWLockExclusive(lock);-}-static inline void mi_lock_acquire(mi_lock_t* lock) {- AcquireSRWLockExclusive(lock);-}-static inline void mi_lock_release(mi_lock_t* lock) {- ReleaseSRWLockExclusive(lock);-}-static inline void mi_lock_init(mi_lock_t* lock) {- InitializeSRWLock(lock);-}-static inline void mi_lock_done(mi_lock_t* lock) {- (void)(lock);-}--#else-#define mi_lock_t CRITICAL_SECTION+#define MI_LOCK_INITIALIZER { SRWLOCK_INIT }static inline bool mi_lock_try_acquire(mi_lock_t* lock) {- return TryEnterCriticalSection(lock);+ return TryAcquireSRWLockExclusive(&lock->mutex);}static inline void mi_lock_acquire(mi_lock_t* lock) {- EnterCriticalSection(lock);+ AcquireSRWLockExclusive(&lock->mutex);}static inline void mi_lock_release(mi_lock_t* lock) {- LeaveCriticalSection(lock);+ ReleaseSRWLockExclusive(&lock->mutex);}static inline void mi_lock_init(mi_lock_t* lock) {- InitializeCriticalSection(lock);+ InitializeSRWLock(&lock->mutex);}static inline void mi_lock_done(mi_lock_t* lock) {- DeleteCriticalSection(lock);+ (void)(lock);}-#endif-#elif defined(MI_USE_PTHREADS)#include <string.h> // memcpyvoid _mi_error_message(int err, const char* fmt, ...);-#define mi_lock_t pthread_mutex_t+typedef struct mi_lock_s {+ pthread_mutex_t mutex;+} mi_lock_t;++#define MI_LOCK_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }static inline bool mi_lock_try_acquire(mi_lock_t* lock) {- return (pthread_mutex_trylock(lock) == 0);+ return (pthread_mutex_trylock(&lock->mutex) == 0);}static inline void mi_lock_acquire(mi_lock_t* lock) {- const int err = pthread_mutex_lock(lock);+ const int err = pthread_mutex_lock(&lock->mutex);if (err != 0) {_mi_error_message(err, "internal error: lock cannot be acquired (err %i)\n", err);}}static inline void mi_lock_release(mi_lock_t* lock) {- pthread_mutex_unlock(lock);+ pthread_mutex_unlock(&lock->mutex);}static inline void mi_lock_init(mi_lock_t* lock) {if(lock==NULL) return;- // use instead of pthread_mutex_init since that can cause allocation on some platforms (and recursively initialize)- const mi_lock_t temp_lock = PTHREAD_MUTEX_INITIALIZER;- memcpy(lock,&temp_lock,sizeof(temp_lock));+ // use this instead of pthread_mutex_init since that can cause allocation on some platforms (and recursively initialize)+ const pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;+ memcpy(&lock->mutex,&mutex,sizeof(mutex));}static inline void mi_lock_done(mi_lock_t* lock) {- pthread_mutex_destroy(lock);+ pthread_mutex_destroy(&lock->mutex);}#elif defined(__cplusplus)+#include <thread>#include <mutex>-#define mi_lock_t std::mutex+#include <new>++typedef struct mi_lock_s {+ std::mutex mutex;+} mi_lock_t;++#define MI_LOCK_INITIALIZER { }static inline bool mi_lock_try_acquire(mi_lock_t* lock) {- return lock->try_lock();+ return lock->mutex.try_lock();}static inline void mi_lock_acquire(mi_lock_t* lock) {- lock->lock();+ lock->mutex.lock();}static inline void mi_lock_release(mi_lock_t* lock) {- lock->unlock();+ lock->mutex.unlock();}static inline void mi_lock_init(mi_lock_t* lock) {- (void)(lock);+ new(&lock->mutex) std::mutex();}static inline void mi_lock_done(mi_lock_t* lock) {(void)(lock);@@ -537,21 +506,32 @@ static inline void mi_lock_done(mi_lock_t* lock) {// fall back to poor man's locks.// this should only be the case in a single-threaded environment (like __wasi__)+#include <errno.h>+#ifndef EFAULT+#define EFAULT (14)+#endif+void _mi_error_message(int err, const char* fmt, ...);+void _mi_prim_thread_yield(void);++typedef struct mi_lock_s {+ _Atomic(uintptr_t) mutex;+} mi_lock_t;-#define mi_lock_t _Atomic(uintptr_t)+#define MI_LOCK_INITIALIZER { MI_ATOMIC_VAR_INIT(0) }static inline bool mi_lock_try_acquire(mi_lock_t* lock) {uintptr_t expected = 0;- return mi_atomic_cas_strong_acq_rel(lock, &expected, (uintptr_t)1);+ return mi_atomic_cas_strong_acq_rel(&lock->mutex, &expected, (uintptr_t)1);}static inline void mi_lock_acquire(mi_lock_t* lock) {- for (int i = 0; i < 1000; i++) { // for at most 1000 tries?+ for (int i = 0; i < 10000; i++) { // for at most 10000 tries?if (mi_lock_try_acquire(lock)) return;- mi_atomic_yield();+ _mi_prim_thread_yield();}+ _mi_error_message(EFAULT, "internal error: lock cannot be acquired (due to lack of native lock primitives)\n");}static inline void mi_lock_release(mi_lock_t* lock) {- mi_atomic_store_release(lock, (uintptr_t)0);+ mi_atomic_store_release(&lock->mutex, (uintptr_t)0);}static inline void mi_lock_init(mi_lock_t* lock) {mi_lock_release(lock);@@ -563,4 +543,20 @@ static inline void mi_lock_done(mi_lock_t* lock) {#endif-#endif // MI_ATOMIC_H+typedef struct mi_atomic_once_s {+ _Atomic(uintptr_t) tid;+ mi_lock_t lock;+} mi_atomic_once_t;++// Returns `true` only on the first invocation, signifying we can execute an action once.+// If it returns `true`, the caller should call `_mi_atomic_once_release` after performing the action.+// Other threads (than the initial thread that entered) will block until `_mi_atomic_once_release` has been called.+bool _mi_atomic_once_enter(mi_atomic_once_t* once); // defined in `libc.c`+void _mi_atomic_once_release(mi_atomic_once_t* once); // defined in `libc.c`++#define mi_atomic_do_once \+ static mi_atomic_once_t _mi_once = { MI_ATOMIC_VAR_INIT(0), MI_LOCK_INITIALIZER }; \+ for(bool _mi_exec = _mi_atomic_once_enter(&_mi_once); _mi_exec; (_mi_atomic_once_release(&_mi_once),_mi_exec=false))+++#endif // __MIMALLOC_ATOMIC_Hdiff --git a/vendored/mimalloc/include/mimalloc/bits.h b/vendored/mimalloc/include/mimalloc/bits.hindex c40b32f6b..617877283 100644--- a/vendored/mimalloc/include/mimalloc/bits.h+++ b/vendored/mimalloc/include/mimalloc/bits.h@@ -108,6 +108,9 @@ typedef int32_t mi_ssize_t;#if MI_ARCH_X64 && (defined(__AVX2__) || defined(__BMI2__)) && !defined(__BMI1__) // msvc#define __BMI1__ 1#endif+#if MI_ARCH_X64 && defined(__AVX2__) && !defined(__LZCNT__) // msvc+#define __LZCNT__ 1+#endif// Define big endian if needed// #define MI_BIG_ENDIAN 1@@ -123,9 +126,9 @@ typedef int32_t mi_ssize_t;#define MI_MAX_VABITS (32)#endif-// use a flat page-map (or a 2-level one)+// use a flat page-map or a 2-level one#ifndef MI_PAGE_MAP_FLAT-#if MI_MAX_VABITS <= 40 && !defined(__APPLE__)+#if MI_MAX_VABITS <= 40 && !defined(__APPLE__) && MI_SECURE==0 && !MI_PAGE_META_IS_SEPARATED#define MI_PAGE_MAP_FLAT 1#else#define MI_PAGE_MAP_FLAT 0@@ -222,11 +225,11 @@ static inline size_t mi_ctz(size_t x) {}static inline size_t mi_clz(size_t x) {- #if defined(__GNUC__) && MI_ARCH_X64 && defined(__BMI1__) // on x64 lzcnt is defined for 0+ #if defined(__GNUC__) && MI_ARCH_X64 && defined(__LZCNT__) // on x64 lzcnt is defined for 0size_t r;__asm ("lzcnt\t%1, %0" : "=r"(r) : "r"(x) : "cc");return r;- #elif defined(_MSC_VER) && MI_ARCH_X64 && defined(__BMI1__)+ #elif defined(_MSC_VER) && MI_ARCH_X64 && defined(__LZCNT__)return _lzcnt_u64(x);#elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)unsigned long idx;@@ -273,12 +276,7 @@ static inline bool mi_bsf(size_t x, size_t* idx) {// return false if `x==0` (with `*idx` undefined) and true otherwise,// with the `idx` is set to the bit index (`0 <= *idx < MI_BFIELD_BITS`).static inline bool mi_bsr(size_t x, size_t* idx) {- #if defined(__GNUC__) && MI_ARCH_X64 && defined(__BMI1__) && (!defined(__clang_major__) || __clang_major__ >= 9)- // on x64 the carry flag is set on zero which gives better codegen- bool is_zero;- __asm ("lzcnt\t%2, %1" : "=@ccc"(is_zero), "=r"(*idx) : "r"(x) : "cc");- return !is_zero;- #elif 0 && defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)+ #if 0 && defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)unsigned long i;return (mi_msc_builtinz(_BitScanReverse)(&i, x) ? (*idx = (size_t)i, true) : false);#elsediff --git a/vendored/mimalloc/include/mimalloc/internal.h b/vendored/mimalloc/include/mimalloc/internal.hindex bf0b6975a..febf2559e 100644--- a/vendored/mimalloc/include/mimalloc/internal.h+++ b/vendored/mimalloc/include/mimalloc/internal.h@@ -131,6 +131,7 @@ void _mi_strlcat(char* dest, const char* src, size_t dest_size);size_t _mi_strlen(const char* s);size_t _mi_strnlen(const char* s, size_t max_len);char* _mi_strnstr(char* s, size_t max_len, const char* pat);+bool _mi_streq(const char* s, const char* t);bool _mi_getenv(const char* name, char* result, size_t result_size);// "options.c"@@ -175,10 +176,12 @@ mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id);mi_threadid_t _mi_thread_id(void) mi_attr_noexcept;size_t _mi_thread_seq_id(void) mi_attr_noexcept;bool _mi_is_heap_main(const mi_heap_t* heap);+bool _mi_is_theap_main(const mi_theap_t* theap);void _mi_theap_guarded_init(mi_theap_t* theap);void _mi_theap_options_init(mi_theap_t* theap);mi_theap_t* _mi_theap_default_safe(void); // ensure the returned theap is initialized-+mi_theap_t* _mi_theap_main_safe(void);+// os.cvoid _mi_os_init(void); // called from process initvoid* _mi_os_alloc(size_t size, mi_memid_t* memid);@@ -284,13 +287,16 @@ size_t _mi_bin(size_t size); // for stats// "theap.c"mi_theap_t* _mi_theap_create(mi_heap_t* heap, mi_tld_t* tld);-void _mi_theap_delete(mi_theap_t* theap);+void _mi_theap_delete(mi_theap_t* theap, bool acquire_tld_theaps_lock);void _mi_theap_default_set(mi_theap_t* theap);void _mi_theap_cached_set(mi_theap_t* theap);void _mi_theap_collect_retired(mi_theap_t* theap, bool force);+void _mi_theap_collect_abandon(mi_theap_t* theap);bool _mi_theap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg);void _mi_theap_page_reclaim(mi_theap_t* theap, mi_page_t* page);-void _mi_theap_free(mi_theap_t* theap);+bool _mi_theap_free(mi_theap_t* theap, bool acquire_heap_theaps_lock, bool acquire_tld_theaps_lock);+void _mi_theap_incref(mi_theap_t* theap);+void _mi_theap_decref(mi_theap_t* theap);// "heap.c"void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page);@@ -298,7 +304,7 @@ mi_decl_cold mi_theap_t* _mi_heap_theap_get_or_init(const mi_heap_t* heap); //mi_decl_cold mi_theap_t* _mi_heap_theap_get_peek(const mi_heap_t* heap); // get the theap for a heap without initializing (and return NULL in that case)void _mi_heap_move_pages(mi_heap_t* heap_from, mi_heap_t* heap_to); // in "arena.c"void _mi_heap_destroy_pages(mi_heap_t* heap_from); // in "arena.c"-+void _mi_heap_force_destroy(mi_heap_t* heap); // allow destroying the main heap// "stats.c"void _mi_stats_init(void);@@ -412,7 +418,7 @@ typedef struct mi_option_desc_s {Inlined definitions----------------------------------------------------------- */#define MI_UNUSED(x) (void)(x)-#ifndef NDEBUG+#if (MI_DEBUG>1)#define MI_UNUSED_RELEASE(x)#else#define MI_UNUSED_RELEASE(x) MI_UNUSED(x)@@ -428,6 +434,7 @@ typedef struct mi_option_desc_s {#define MI_INIT74(x) MI_INIT64(x),MI_INIT8(x),x(),x()#define MI_INIT5(x) MI_INIT4(x),x()+#define MI_INIT6(x) MI_INIT4(x),x(),x()#include <string.h>// initialize a local variable to zero; use memset as compilers optimize constant sized memset's@@ -439,9 +446,8 @@ static inline bool _mi_is_power_of_two(uintptr_t x) {}// Is a pointer aligned?-static inline bool _mi_is_aligned(void* p, size_t alignment) {- mi_assert_internal(alignment != 0);- return (((uintptr_t)p % alignment) == 0);+static inline bool _mi_is_aligned(const void* p, size_t alignment) {+ return (alignment==0 || ((uintptr_t)p % alignment) == 0);}// Align upwards@@ -456,13 +462,11 @@ static inline uintptr_t _mi_align_up(uintptr_t sz, size_t alignment) {}}-// Align a pointer upwards-static inline uint8_t* _mi_align_up_ptr(void* p, size_t alignment) {- return (uint8_t*)_mi_align_up((uintptr_t)p, alignment);+static inline void* _mi_align_up_ptr(const void* p, size_t alignment) {+ return (void*)_mi_align_up((uintptr_t)p, alignment);}-static inline uintptr_t _mi_align_down(uintptr_t sz, size_t alignment) {mi_assert_internal(alignment != 0);uintptr_t mask = alignment - 1;@@ -474,7 +478,8 @@ static inline uintptr_t _mi_align_down(uintptr_t sz, size_t alignment) {}}-static inline void* mi_align_down_ptr(void* p, size_t alignment) {+// align a pointer downwards+static inline void* _mi_align_down_ptr(const void* p, size_t alignment) {return (void*)_mi_align_down((uintptr_t)p, alignment);}@@ -560,8 +565,13 @@ static inline bool mi_count_size_overflow(size_t count, size_t size, size_t* totextern mi_decl_hidden const mi_theap_t _mi_theap_empty; // read-only empty theap, initial value of the thread local default theap (in the MI_TLS_MODEL_THREAD_LOCAL)extern mi_decl_hidden const mi_theap_t _mi_theap_empty_wrong; // read-only empty theap used to signal that a theap for a heap could not be allocated++static inline mi_heap_t* _mi_theap_heap(const mi_theap_t* theap) {+ return mi_atomic_load_ptr_acquire(mi_heap_t,&theap->heap);+}+static inline bool mi_theap_is_initialized(const mi_theap_t* theap) {- return (theap != NULL && theap->heap != NULL);+ return (theap != NULL && _mi_theap_heap(theap) != NULL);}static inline mi_page_t* _mi_theap_get_free_small_page(mi_theap_t* theap, size_t size) {@@ -709,19 +719,35 @@ static inline size_t mi_page_usable_block_size(const mi_page_t* page) {return mi_page_block_size(page) - MI_PADDING_SIZE;}-// This may change if we locate page info outside the page data slices+static inline bool mi_page_meta_is_separated(const mi_page_t* page) {+ #if MI_PAGE_META_IS_SEPARATED+ // usually separated but can still be in front for direct OS allocations (due to size or alignment) or due to MI_PAGE_META_ALIGNED_FREE_SMALL+ return (page->memid.memkind == MI_MEM_ARENA && page != _mi_align_down_ptr(page->page_start, MI_ARENA_SLICE_ALIGN));+ #else+ MI_UNUSED(page);+ return false;+ #endif+}+static inline uint8_t* mi_page_slice_start(const mi_page_t* page) {- return (uint8_t*)page;+ if (mi_page_meta_is_separated(page)) {+ // page meta info is at a separate location (at `arena->pages`)+ return (uint8_t*)_mi_align_down_ptr(page->page_start, MI_ARENA_SLICE_ALIGN);+ }+ else {+ // page meta info is at the start of the page slices+ return (uint8_t*)page;+ }}-// This gives the offset relative to the start slice of a page. This may change if we ever-// locate page info outside the page-data itself.+// This gives the offset relative to the start slice of a page.static inline size_t mi_page_slice_offset_of(const mi_page_t* page, size_t offset_relative_to_page_start) {return (page->page_start - mi_page_slice_start(page)) + offset_relative_to_page_start;}+// Currently committed part of a pagestatic inline size_t mi_page_committed(const mi_page_t* page) {- return (page->slice_committed == 0 ? mi_page_size(page) : page->slice_committed - (page->page_start - mi_page_slice_start(page)));+ return (page->slice_committed == 0 ? mi_page_size(page) : page->slice_committed - mi_page_slice_offset_of(page,0));}// are all blocks in a page freed?@@ -746,7 +772,7 @@ static inline bool mi_page_is_expandable(const mi_page_t* page) {}-static inline bool mi_page_is_full(mi_page_t* page) {+static inline bool mi_page_is_full(const mi_page_t* page) {const bool full = (page->reserved == page->used);mi_assert_internal(!full || page->free == NULL);return full;@@ -798,9 +824,11 @@ static inline mi_page_flags_t mi_page_flags(const mi_page_t* page) {return (mi_page_xthread_id(page) & MI_PAGE_FLAG_MASK);}-static inline void mi_page_flags_set(mi_page_t* page, bool set, mi_page_flags_t newflag) {- if (set) { mi_atomic_or_relaxed(&page->xthread_id, newflag); }- else { mi_atomic_and_relaxed(&page->xthread_id, ~newflag); }+static inline bool mi_page_flags_set(mi_page_t* page, bool set, mi_page_flags_t newflag) {+ mi_page_flags_t old;+ if (set) { old = mi_atomic_or_relaxed(&page->xthread_id, newflag); }+ else { old = mi_atomic_and_relaxed(&page->xthread_id, ~newflag); }+ return ((old & newflag) == newflag);}static inline bool mi_page_is_in_full(const mi_page_t* page) {@@ -808,7 +836,17 @@ static inline bool mi_page_is_in_full(const mi_page_t* page) {}static inline void mi_page_set_in_full(mi_page_t* page, bool in_full) {- mi_page_flags_set(page, in_full, MI_PAGE_IN_FULL_QUEUE);+ const bool was_in_full = mi_page_flags_set(page, in_full, MI_PAGE_IN_FULL_QUEUE);+ if (was_in_full != in_full) {+ // optimize: maintain pages_full_size to avoid visiting the full queue (issue #1220)+ mi_theap_t* const theap = page->theap;+ mi_assert_internal(theap!=NULL);+ if (theap != NULL) {+ const size_t size = page->capacity * mi_page_block_size(page);+ if (in_full) { theap->pages_full_size += size; }+ else { mi_assert_internal(size <= theap->pages_full_size); theap->pages_full_size -= size; }+ }+ }}static inline bool mi_page_has_interior_pointers(const mi_page_t* page) {@@ -844,12 +882,12 @@ static inline bool mi_page_is_abandoned_mapped(const mi_page_t* page) {static inline void mi_page_set_abandoned_mapped(mi_page_t* page) {mi_assert_internal(mi_page_is_abandoned(page));- mi_atomic_or_relaxed(&page->xthread_id, MI_THREADID_ABANDONED_MAPPED);+ mi_atomic_or_relaxed(&page->xthread_id, (mi_threadid_t)MI_THREADID_ABANDONED_MAPPED);}static inline void mi_page_clear_abandoned_mapped(mi_page_t* page) {mi_assert_internal(mi_page_is_abandoned_mapped(page));- mi_atomic_and_relaxed(&page->xthread_id, MI_PAGE_FLAG_MASK);+ mi_atomic_and_relaxed(&page->xthread_id, (mi_threadid_t)MI_PAGE_FLAG_MASK);}@@ -907,7 +945,7 @@ static inline bool mi_page_is_owned(const mi_page_t* page) {// get ownership; returns true if the page was not owned before.static inline bool mi_page_claim_ownership(mi_page_t* page) {- const uintptr_t old = mi_atomic_or_acq_rel(&page->xthread_free, 1);+ const uintptr_t old = mi_atomic_or_acq_rel(&page->xthread_free, (uintptr_t)1);return ((old&1)==0);}@@ -916,17 +954,23 @@ static inline bool mi_page_claim_ownership(mi_page_t* page) {Guarded objects------------------------------------------------------------------- */#if MI_GUARDED-// we always align guarded pointers in a block at an offset// the block `next` field is then used as a tag to distinguish regular offset aligned blocks from guarded ones#define MI_BLOCK_TAG_ALIGNED ((mi_encoded_t)(0))#define MI_BLOCK_TAG_GUARDED (~MI_BLOCK_TAG_ALIGNED)+#endifstatic inline bool mi_block_ptr_is_guarded(const mi_block_t* block, const void* p) {+#if MI_GUARDEDconst ptrdiff_t offset = (uint8_t*)p - (uint8_t*)block;return (offset >= (ptrdiff_t)(sizeof(mi_block_t)) && block->next == MI_BLOCK_TAG_GUARDED);+#else+ MI_UNUSED(block); MI_UNUSED(p);+ return false;+#endif}+#if MI_GUARDEDstatic inline bool mi_theap_malloc_use_guarded(mi_theap_t* theap, size_t size) {// this code is written to result in fast assembly as it is on the hot path for allocationconst size_t count = theap->guarded_sample_count - 1; // if the rate was 0, this will underflow and count for a long time..@@ -1006,7 +1050,7 @@ static inline uint32_t mi_ptr_encode_canary(const void* null, const void* p, constatic inline mi_block_t* mi_block_nextx( const void* null, const mi_block_t* block, const uintptr_t* keys ) {mi_track_mem_defined(block,sizeof(mi_block_t));mi_block_t* next;- #ifdef MI_ENCODE_FREELIST+ #if MI_ENCODE_FREELISTnext = (mi_block_t*)mi_ptr_decode(null, block->next, keys);#elseMI_UNUSED(keys); MI_UNUSED(null);@@ -1018,7 +1062,7 @@ static inline mi_block_t* mi_block_nextx( const void* null, const mi_block_t* blstatic inline void mi_block_set_nextx(const void* null, mi_block_t* block, const mi_block_t* next, const uintptr_t* keys) {mi_track_mem_undefined(block,sizeof(mi_block_t));- #ifdef MI_ENCODE_FREELIST+ #if MI_ENCODE_FREELISTblock->next = mi_ptr_encode(null, next, keys);#elseMI_UNUSED(keys); MI_UNUSED(null);@@ -1028,7 +1072,7 @@ static inline void mi_block_set_nextx(const void* null, mi_block_t* block, const}static inline mi_block_t* mi_block_next(const mi_page_t* page, const mi_block_t* block) {- #ifdef MI_ENCODE_FREELIST+ #if MI_ENCODE_FREELISTmi_block_t* next = mi_block_nextx(page,block,page->keys);// check for free list corruption: is `next` at least in the same page?// TODO: check if `next` is `page->block_size` aligned?@@ -1044,7 +1088,7 @@ static inline mi_block_t* mi_block_next(const mi_page_t* page, const mi_block_t*}static inline void mi_block_set_next(const mi_page_t* page, mi_block_t* block, const mi_block_t* next) {- #ifdef MI_ENCODE_FREELIST+ #if MI_ENCODE_FREELISTmi_block_set_nextx(page,block,next, page->keys);#elseMI_UNUSED(page);diff --git a/vendored/mimalloc/include/mimalloc/prim.h b/vendored/mimalloc/include/mimalloc/prim.hindex 75ad758e8..aecfc8074 100644--- a/vendored/mimalloc/include/mimalloc/prim.h+++ b/vendored/mimalloc/include/mimalloc/prim.h@@ -126,6 +126,9 @@ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap);// Is this thread part of a thread pool?bool _mi_prim_thread_is_in_threadpool(void);+// Yield to other threads. Should be similar to `sleep(0)`.+// Is called only in rare situations and does not have to be lightning fast.+void _mi_prim_thread_yield(void);//-------------------------------------------------------------------// Access to TLS (thread local storage) slots.@@ -253,14 +256,16 @@ extern mi_decl_hidden bool _mi_process_is_initialized; // has mi_// but unfortunately, it seems we cannot test for this reliably at this time (see issue #883)// Nevertheless, it seems needed on older graviton platforms (see issue #851).// For now, we only enable this for specific platforms.-#if !defined(__APPLE__) /* on apple (M1) the wrong register is read (tpidr_el0 instead of tpidrro_el0) so fall back to TLS slot assembly (<https://github.com/microsoft/mimalloc/issues/343#issuecomment-763272369>)*/ \- && !defined(__CYGWIN__) \- && !defined(MI_LIBC_MUSL) \- && (!defined(__clang_major__) || __clang_major__ >= 14) /* older clang versions emit bad code; fall back to using the TLS slot (<https://lore.kernel.org/linux-arm-kernel/202110280952.352F66D8@keescook/T/>) */- #if (defined(__GNUC__) && (__GNUC__ >= 7) && defined(__aarch64__)) /* aarch64 for older gcc versions (issue #851) */ \- || (defined(__GNUC__) && (__GNUC__ >= 11) && defined(__x86_64__)) \- || (defined(__clang_major__) && (__clang_major__ >= 14) && (defined(__aarch64__) || defined(__x86_64__)))- #define MI_USE_BUILTIN_THREAD_POINTER 1+#if !defined(MI_USE_BUILTIN_THREAD_POINTER) /* allow user override */+ #if !defined(__APPLE__) /* on apple (M1) the wrong register is read (tpidr_el0 instead of tpidrro_el0) so fall back to TLS slot assembly (<https://github.com/microsoft/mimalloc/issues/343#issuecomment-763272369>)*/ \+ && !defined(__CYGWIN__) \+ && !defined(MI_LIBC_MUSL) \+ && (!defined(__clang_major__) || __clang_major__ >= 14) /* older clang versions emit bad code; fall back to using the TLS slot (<https://lore.kernel.org/linux-arm-kernel/202110280952.352F66D8@keescook/T/>) */+ #if (defined(__GNUC__) && (__GNUC__ >= 7) && defined(__aarch64__)) /* aarch64 for older gcc versions (issue #851) */ \+ || (defined(__GNUC__) && (__GNUC__ >= 11) && defined(__x86_64__)) \+ || (defined(__clang_major__) && (__clang_major__ >= 14) && (defined(__aarch64__) || defined(__x86_64__)))+ #define MI_USE_BUILTIN_THREAD_POINTER 1+ #endif#endif#endif@@ -276,8 +281,10 @@ static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {// Get a unique id for the current thread.#if defined(MI_PRIM_THREAD_ID)-static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {- return MI_PRIM_THREAD_ID(); // used for example by CPython for a free threaded build (see python/cpython#115488)+static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+ const mi_threadid_t tid = MI_PRIM_THREAD_ID(); // used for example by CPython for a free threaded build (see python/cpython#115488)+ mi_assert_internal( (tid & 0x03) == 0 ); // mimalloc reserves the bottom 2 bits+ return tid;}#elif defined(_WIN32)@@ -363,14 +370,14 @@ static inline mi_theap_t* _mi_theap_cached(void);#if defined(_WIN32)#define MI_TLS_MODEL_DYNAMIC_WIN32 1-#elif defined(__APPLE__) // macOS+#elif defined(__APPLE__) && MI_HAS_TLS_SLOT && !defined(__POWERPC__) // macOS on arm64 or x64// #define MI_TLS_MODEL_DYNAMIC_PTHREADS 1 // also works but a bit slower#define MI_TLS_MODEL_FIXED_SLOT 1#define MI_TLS_MODEL_FIXED_SLOT_DEFAULT 108 // seems unused. @apple: it would be great to get 2 official slots for custom allocators :-)#define MI_TLS_MODEL_FIXED_SLOT_CACHED 109// we used before __PTK_FRAMEWORK_OLDGC_KEY9 (89) but that seems used now.// see <https://github.com/rweichler/substrate/blob/master/include/pthread_machdep.h>-#elif defined(__OpenBSD__) || defined(__ANDROID__)+#elif defined(__APPLE__) || defined(__OpenBSD__) || defined(__ANDROID__)#define MI_TLS_MODEL_DYNAMIC_PTHREADS 1// #define MI_TLS_MODEL_DYNAMIC_PTHREADS_DEFAULT_ENTRY_IS_NULL 1#else@@ -497,11 +504,11 @@ static inline bool _mi_thread_is_initialized(void) {// Get (and possible create) the theap belonging to a heap// We cache the last accessed theap in `_mi_theap_cached` for better performance.static inline mi_theap_t* _mi_heap_theap(const mi_heap_t* heap) {- mi_theap_t* theap = _mi_theap_cached();+ mi_theap_t* theap = _mi_theap_cached();#if MI_THEAP_INITASNULL- if mi_likely(theap!=NULL && theap->heap==heap) return theap;+ if mi_likely(theap!=NULL && _mi_theap_heap(theap)==heap) return theap;#else- if mi_likely(theap->heap==heap) return theap;+ if mi_likely(_mi_theap_heap(theap)==heap) return theap;#endifreturn _mi_heap_theap_get_or_init(heap);}@@ -510,14 +517,14 @@ static inline mi_theap_t* _mi_heap_theap(const mi_heap_t* heap) {static inline mi_theap_t* _mi_heap_theap_peek(const mi_heap_t* heap) {mi_theap_t* theap = _mi_theap_cached();#if MI_THEAP_INITASNULL- if mi_unlikely(theap==NULL || theap->heap!=heap)+ if mi_unlikely(theap==NULL || _mi_theap_heap(theap)!=heap)#else- if mi_unlikely(theap->heap!=heap)+ if mi_unlikely(_mi_theap_heap(theap)!=heap)#endif{theap = _mi_heap_theap_get_peek(heap); // don't update the cache on a query (?)}- mi_assert(theap==NULL || theap->heap==heap);+ mi_assert(theap==NULL || _mi_theap_heap(theap)==heap);return theap;}diff --git a/vendored/mimalloc/include/mimalloc/track.h b/vendored/mimalloc/include/mimalloc/track.hindex 8f8b93f9a..1f4021297 100644--- a/vendored/mimalloc/include/mimalloc/track.h+++ b/vendored/mimalloc/include/mimalloc/track.h@@ -84,7 +84,8 @@ defined, undefined, or not accessible at all:#include "../src/prim/windows/etw.h"-#define mi_track_init() EventRegistermicrosoft_windows_mimalloc();+#define mi_track_init() EventRegistermicrosoft_windows_mimalloc()+#define mi_track_done() EventUnregistermicrosoft_windows_mimalloc()#define mi_track_malloc_size(p,reqsize,size,zero) EventWriteETW_MI_ALLOC((UINT64)(p), size)#define mi_track_free_size(p,size) EventWriteETW_MI_FREE((UINT64)(p), size)@@ -104,7 +105,7 @@ defined, undefined, or not accessible at all:// Utility definitions#ifndef mi_track_resize-#define mi_track_resize(p,oldsize,newsize) mi_track_free_size(p,oldsize); mi_track_malloc(p,newsize,false)+#define mi_track_resize(p,oldsize,newsize) do{ mi_track_free_size(p,oldsize); mi_track_malloc(p,newsize,false); } while(0)#endif#ifndef mi_track_align@@ -115,6 +116,10 @@ defined, undefined, or not accessible at all:#define mi_track_init()#endif+#ifndef mi_track_done+#define mi_track_done()+#endif+#ifndef mi_track_mem_defined#define mi_track_mem_defined(p,size)#endifdiff --git a/vendored/mimalloc/include/mimalloc/types.h b/vendored/mimalloc/include/mimalloc/types.hindex 52cb3fcc5..31fdace9c 100644--- a/vendored/mimalloc/include/mimalloc/types.h+++ b/vendored/mimalloc/include/mimalloc/types.h@@ -54,17 +54,12 @@ terms of the MIT license. A copy of the license can be found in the file// Define MI_STAT as 1 to maintain statistics; set it to 2 to have detailed statistics (but costs some performance).// #define MI_STAT 1-// Define MI_SECURE to enable security mitigations. Level 1 has minimal performance impact,-// but protects most metadata with guard pages:-// #define MI_SECURE 1 // guard page around metadata; check pointer validity on free-//-// Level 2 has more performance impact but protect well against various buffer overflows-// by surrounding all mimalloc pages with guard pages:-// #define MI_SECURE 2 // guard page around each mimalloc page (can fragment VMA's with large theaps..)-//-// The next two levels can have more performance cost:-// #define MI_SECURE 3 // randomize allocations, encode free lists (detect corrupted free list (buffer overflow), and invalid pointer free)-// #define MI_SECURE 4 // checks for double free. (may be more expensive)+// Define MI_SECURE to enable security mitigations+// #define MI_SECURE 1 // guard pages around meta data, randomize arena allocation addresses (like ASLR), abort on detected meta data corruption+// #define MI_SECURE 2 // randomize relative allocation addresses (within mimalloc pages)+// #define MI_SECURE 3 // encode free lists (detect corrupted free list (buffer overflow), and invalid pointer free)+// #define MI_SECURE 4 // checks for double free (may be more expensive) (`-DMI_SECURE=ON`)+// #define MI_SECURE 5 // guard page at the end of each mimalloc page (expensive!) (`-DMI_SECURE_FULL=ON`)#if !defined(MI_SECURE)#define MI_SECURE 0@@ -91,11 +86,9 @@ terms of the MIT license. A copy of the license can be found in the file#endif#endif-// Use guard pages behind objects of a certain size (set by the MIMALLOC_DEBUG_GUARDED_MIN/MAX options)-// Padding should be disabled when using guard pages-// #define MI_GUARDED 1-#if MI_GUARDED-#define MI_PADDING 0+// Enable guard pages behind objects of a certain size (set by the MIMALLOC_GUARDED_MIN/MAX/SAMPLE_RATE options)+#if !defined(MI_GUARDED) && MI_DEBUG && !defined(NDEBUG) && !MI_PAGE_META_ALIGNED_FREE_SMALL+#define MI_GUARDED 1#endif// Reserve extra padding at the end of each block to be more resilient against theap block overflows.@@ -123,6 +116,40 @@ terms of the MIT license. A copy of the license can be found in the file#define MI_ENABLE_LARGE_PAGES 1#endif+// Place page meta info at the start of the page area or keep it separate?+// Separate keeps the page info at the arena start (default) which is more secure+// and reduces wasted space due to alignment and block sizes.+// (but also reserves more memory up front (about 2MiB per GiB))+#if !defined(MI_PAGE_META_IS_SEPARATED)+#if MI_PAGE_MAP_FLAT+#define MI_PAGE_META_IS_SEPARATED 0+#else+#define MI_PAGE_META_IS_SEPARATED 1+#endif+#endif++// We can choose to only put page info of small pages at the start of the page area.+// This can be used to have a slightly faster `mi_free_small` function for specialized+// cases (like language runtime systems).+#if !defined(MI_PAGE_META_ALIGNED_FREE_SMALL)+#define MI_PAGE_META_ALIGNED_FREE_SMALL 0+#endif++// Configuration checks+#if !MI_PAGE_META_IS_SEPARATED && MI_SECURE+#error "secure mode should use separated page infos"+#endif+#if MI_PAGE_META_ALIGNED_FREE_SMALL && MI_SECURE+#error "secure mode cannot use MI_PAGE_META_ALIGNED_FREE_SMALL"+#endif+#if MI_PAGE_META_IS_SEPARATED && MI_PAGE_MAP_FLAT+#error "cannot have a flat page map with separated page infos"+#endif+#if MI_DEBUG && NDEBUG+#warning "mimalloc assertions enabled in a release build"+#endif++// --------------------------------------------------------------// Sizes of internal data-structures// (comments specify sizes on 64-bit, usually 32-bit is halved)@@ -132,7 +159,7 @@ terms of the MIT license. A copy of the license can be found in the file#ifndef MI_ARENA_SLICE_SHIFT#ifdef MI_SMALL_PAGE_SHIFT // backward compatibility#define MI_ARENA_SLICE_SHIFT MI_SMALL_PAGE_SHIFT- #elif MI_SECURE && __APPLE__ && MI_ARCH_ARM64+ #elif MI_SECURE>=5 && __APPLE__ && MI_ARCH_ARM64#define MI_ARENA_SLICE_SHIFT (17) // 128 KiB to not waste too much due to 16 KiB guard pages#else#define MI_ARENA_SLICE_SHIFT (13 + MI_SIZE_SHIFT) // 64 KiB (32 KiB on 32-bit)@@ -313,7 +340,7 @@ typedef size_t mi_page_flags_t;// There are two special threadid's: 0 for pages that are abandoned (and not in a theap queue),// and 4 for abandoned & mapped threads -- abandoned-mapped pages are abandoned but also mapped// in an arena (in `mi_heap_t.arena_pages.pages_abandoned`) so these can be quickly found for reuse.-// Abondoning partially used pages allows for sharing of this memory between threads (in particular if threads are blocked)+// Abandoning partially used pages allows for sharing of this memory between threads (in particular if threads are blocked)#define MI_THREADID_ABANDONED MI_ZU(0)#define MI_THREADID_ABANDONED_MAPPED (MI_PAGE_FLAG_MASK + 1)@@ -392,12 +419,6 @@ typedef struct mi_page_s {#define MI_PAGE_OSPAGE_BLOCK_ALIGN2 (4*MI_KiB) // also aligns any multiple of this size to avoid TLB misses.#define MI_PAGE_MAX_OVERALLOC_ALIGN MI_ARENA_SLICE_SIZE // (64 KiB) limit for which we overallocate in arena pages, beyond this use OS allocation-#if (MI_ENCODE_FREELIST || MI_PADDING) && MI_SIZE_SIZE == 8-#define MI_PAGE_INFO_SIZE ((MI_INTPTR_SHIFT+2)*32) // 160 >= sizeof(mi_page_t)-#else-#define MI_PAGE_INFO_SIZE ((MI_INTPTR_SHIFT+1)*32) // 128/96 >= sizeof(mi_page_t)-#endif-// The max object sizes are intended to not waste more than ~ 12.5% internally over the page sizes.#define MI_SMALL_MAX_OBJ_SIZE ((MI_SMALL_PAGE_SIZE-MI_PAGE_OSPAGE_BLOCK_ALIGN2)/6) // = 10 KiB#if MI_ENABLE_LARGE_PAGES@@ -423,7 +444,7 @@ typedef enum mi_page_kind_e {MI_PAGE_MEDIUM, // medium blocks go into 512KiB pagesMI_PAGE_LARGE, // larger blocks go into 4MiB pages (if `MI_ENABLE_LARGE_PAGES==1`)MI_PAGE_SINGLETON // page containing a single block.- // used for blocks `> MI_LARGE_MAX_OBJ_SIZE` or an aligment `> MI_PAGE_MAX_OVERALLOC_ALIGN`.+ // used for blocks `> MI_LARGE_MAX_OBJ_SIZE` or an alignment `> MI_PAGE_MAX_OVERALLOC_ALIGN`.} mi_page_kind_t;@@ -482,21 +503,23 @@ typedef struct mi_padding_s {// A thread-local heap ("theap") owns a set of thread-local pages.struct mi_theap_s {mi_tld_t* tld; // thread-local data- mi_heap_t* heap; // the heap this theap belongs to.+ _Atomic(mi_heap_t*) heap; // the heap this theap belongs to.+ _Atomic(size_t) refcount; // reference countunsigned long long heartbeat; // monotonic heartbeat countuintptr_t cookie; // random cookie to verify pointers (see `_mi_ptr_cookie`)mi_random_ctx_t random; // random number context used for secure allocationsize_t page_count; // total number of pages in the `pages` queues.size_t page_retired_min; // smallest retired index (retired pages are fully free, but still in the page queues)size_t page_retired_max; // largest retired index into the `pages` array.+ size_t pages_full_size; // optimization: total size of blocks in the pages of the full queue (issue #1220)long generic_count; // how often is `_mi_malloc_generic` called?long generic_collect_count; // how often is `_mi_malloc_generic` called without collecting?mi_theap_t* tnext; // list of theaps in this thread- mi_theap_t* tprev;+ mi_theap_t* tprev;mi_theap_t* hnext; // list of theaps of the owning `heap`mi_theap_t* hprev;-+long page_full_retain; // how many full pages can be retained per queue (before abandoning them)bool allow_page_reclaim; // `true` if this theap should not reclaim abandoned pagesbool allow_page_abandon; // `true` if this theap can abandon pages to reduce memory footprint@@ -604,6 +627,7 @@ struct mi_tld_s {int numa_node; // thread preferred numa nodemi_subproc_t* subproc; // sub-process this thread belongs to.mi_theap_t* theaps; // list of theaps in this thread (so we can abandon all when the thread terminates)+ mi_lock_t theaps_lock; // lock as the theaps list is sometimes accessed from another thread (on `mi_heap_free`)bool recurse; // true if deferred was called; used to prevent infinite recursion.bool is_in_threadpool; // true if this thread is part of a threadpool (and can run arbitrary tasks)mi_memid_t memid; // provenance of the tld memory itself (meta or OS)@@ -632,7 +656,7 @@ typedef struct mi_bbitmap_s mi_bbitmap_t; // atomic binned bitmap (defined intypedef struct mi_arena_pages_s {mi_bitmap_t* pages; // all registered pages (abandoned and owned)mi_bitmap_t* pages_abandoned[MI_ARENA_BIN_COUNT]; // abandoned pages per size bin (a set bit means the start of the page)- // followed by the bitmaps (whose sizes depend on the arena size)+ // followed by the bitmaps (whose siz`es depend on the arena size)} mi_arena_pages_t;@@ -651,10 +675,14 @@ typedef struct mi_arena_s {mi_commit_fun_t* commit_fun; // custom commit/decommit memoryvoid* commit_fun_arg; // user argument for a custom commit function+ size_t total_size; // for (user given) memory more than MI_ARENA_MAX_SIZE, we use N arena's to cover it. The first (parent) has the total size (and the other sub-arena's 0).+ mi_arena_t* parent; // if this is a sub arena, this points to the first one in the memory area.+mi_bbitmap_t* slices_free; // is the slice free? (a binned bitmap with size classes)mi_bitmap_t* slices_committed; // is the slice committed? (i.e. accessible)mi_bitmap_t* slices_dirty; // is the slice potentially non-zero?mi_bitmap_t* slices_purge; // slices that can be purged+ mi_page_t* pages_meta; // pre-allocated `slice_count` page meta info -- only used if `MI_PAGE_META_IS_SEPARATED!=0`mi_arena_pages_t pages_main; // arena page bitmaps for the main heap are allocated up front as well// followed by the bitmaps (whose sizes depend on the arena size)diff --git a/vendored/mimalloc/src/alloc-aligned.c b/vendored/mimalloc/src/alloc-aligned.cindex fe8ae1725..97dc6045b 100644--- a/vendored/mimalloc/src/alloc-aligned.c+++ b/vendored/mimalloc/src/alloc-aligned.c@@ -34,9 +34,14 @@ static mi_decl_restrict void* mi_theap_malloc_guarded_aligned(mi_theap_t* theap,if mi_unlikely(theap==NULL) { theap = _mi_theap_empty_get(); }#endifmi_assert_internal(alignment > 0 && alignment < MI_PAGE_MAX_OVERALLOC_ALIGN);+ if mi_unlikely(alignment >= MI_PAGE_MAX_OVERALLOC_ALIGN || size > (MI_MAX_ALLOC_SIZE - MI_PADDING_SIZE - alignment)) {+ _mi_error_message(EOVERFLOW, "(guarded) aligned allocation request is too large (size %zu, alignment %zu)\n", size, alignment);+ return NULL;+ }const size_t oversize = size + alignment - 1;- void* base = _mi_theap_malloc_guarded(theap, oversize, zero);- void* p = _mi_align_up_ptr(base, alignment);+ void* const base = _mi_theap_malloc_guarded(theap, oversize, zero);+ if (base==NULL) return NULL;+ void* const p = _mi_align_up_ptr(base, alignment);mi_track_align(base, p, (uint8_t*)p - (uint8_t*)base, size);mi_assert_internal(mi_usable_size(p) >= size);mi_assert_internal(_mi_is_aligned(p, alignment));@@ -74,9 +79,7 @@ static mi_decl_noinline void* mi_theap_malloc_zero_aligned_at_overalloc(mi_theap// in the first (and single) page such that the page info is `MI_PAGE_ALIGN` bytes before it (and can be found in the _mi_page_map).if mi_unlikely(offset != 0) {// todo: cannot support offset alignment for very large alignments yet- #if MI_DEBUG > 0_mi_error_message(EOVERFLOW, "aligned allocation with a large alignment cannot be used with an alignment offset (size %zu, alignment %zu, offset %zu)\n", size, alignment, offset);- #endifreturn NULL;}oversize = (size <= MI_SMALL_SIZE_MAX ? MI_SMALL_SIZE_MAX + 1 /* ensure we use generic malloc path */ : size);@@ -86,7 +89,9 @@ static mi_decl_noinline void* mi_theap_malloc_zero_aligned_at_overalloc(mi_theap}else {// otherwise over-allocate- oversize = (size < MI_MAX_ALIGN_SIZE ? MI_MAX_ALIGN_SIZE : size) + alignment - 1; // adjust for size <= 16; with size 0 and aligment 64k, we would allocate a 64k block and pointing just beyond that.+ mi_assert_internal(size <= (MI_MAX_ALLOC_SIZE - MI_PADDING_SIZE) && alignment <= MI_PAGE_MAX_OVERALLOC_ALIGN);+ mi_assert_internal(size < SIZE_MAX - alignment); // `oversize` cannot overflow+ oversize = (size < MI_MAX_ALIGN_SIZE ? MI_MAX_ALIGN_SIZE : size) + alignment - 1; // adjust for size <= 16; with size 0 and alignment 64k, we would allocate a 64k block and pointing just beyond that.p = mi_theap_malloc_zero_no_guarded(theap, oversize, zero, usable);if (p == NULL) return NULL;}@@ -150,9 +155,7 @@ static mi_decl_noinline void* mi_theap_malloc_zero_aligned_at_generic(mi_theap_tmi_assert_internal(alignment != 0 && _mi_is_power_of_two(alignment));// we don't allocate more than MI_MAX_ALLOC_SIZE (see <https://sourceware.org/ml/libc-announce/2019/msg00001.html>)if mi_unlikely(size > (MI_MAX_ALLOC_SIZE - MI_PADDING_SIZE)) {- #if MI_DEBUG > 0_mi_error_message(EOVERFLOW, "aligned allocation request is too large (size %zu, alignment %zu)\n", size, alignment);- #endifreturn NULL;}@@ -328,12 +331,12 @@ mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc_aligned(mi_heap_t* heap,static void* mi_theap_realloc_zero_aligned_at(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, size_t offset, bool zero) mi_attr_noexcept {mi_assert(alignment > 0);- if (alignment <= sizeof(uintptr_t)) return _mi_theap_realloc_zero(theap,p,newsize,zero,NULL,NULL);+ if (alignment <= sizeof(uintptr_t) && offset==0) return _mi_theap_realloc_zero(theap,p,newsize,zero,NULL,NULL);if (p == NULL) return mi_theap_malloc_zero_aligned_at(theap,newsize,alignment,offset,zero,NULL);size_t size = mi_usable_size(p);if (newsize <= size && newsize >= (size - (size / 2))&& (((uintptr_t)p + offset) % alignment) == 0) {- return p; // reallocation still fits, is aligned and not more than 50% waste+ return p; // reallocation still fits, is aligned and not more than 25% waste}else {// note: we don't zero allocate upfront so we only zero initialize the expanded part@@ -354,8 +357,7 @@ static void* mi_theap_realloc_zero_aligned_at(mi_theap_t* theap, void* p, size_tstatic void* mi_theap_realloc_zero_aligned(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, bool zero) mi_attr_noexcept {mi_assert(alignment > 0);if (alignment <= sizeof(uintptr_t)) return _mi_theap_realloc_zero(theap,p,newsize,zero,NULL,NULL);- size_t offset = ((uintptr_t)p % alignment); // use offset of previous allocation (p can be NULL)- return mi_theap_realloc_zero_aligned_at(theap,p,newsize,alignment,offset,zero);+ return mi_theap_realloc_zero_aligned_at(theap,p,newsize,alignment,0,zero);}static void* mi_theap_realloc_aligned_at(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {diff --git a/vendored/mimalloc/src/alloc-override.c b/vendored/mimalloc/src/alloc-override.cindex 882e0607a..93d066dc1 100644--- a/vendored/mimalloc/src/alloc-override.c+++ b/vendored/mimalloc/src/alloc-override.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2021, Microsoft Research, Daan Leijen+Copyright (c) 2018-2026, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -9,11 +9,8 @@ terms of the MIT license. A copy of the license can be found in the file#error "this file should be included from 'alloc.c' (so aliases can work)"#endif-#if defined(MI_MALLOC_OVERRIDE) && defined(_WIN32) && !(defined(MI_SHARED_LIB) && defined(_DLL))-#error "It is only possible to override "malloc" on Windows when building as a DLL (and linking the C runtime as a DLL)"-#endif-#if defined(MI_MALLOC_OVERRIDE) && !(defined(_WIN32))+#if defined(MI_MALLOC_OVERRIDE) && !defined(_DLL)#if defined(__APPLE__)#include <AvailabilityMacros.h>@@ -51,7 +48,6 @@ typedef void* mi_nothrow_t;#define MI_FORWARD02(fun,x,y) { fun(x,y); }#endif-#if defined(__APPLE__) && defined(MI_SHARED_LIB_EXPORT) && defined(MI_OSX_INTERPOSE)// define MI_OSX_IS_INTERPOSED as we should not provide forwarding definitions for// functions that are interposed (or the interposing does not work)@@ -95,12 +91,12 @@ typedef void* mi_nothrow_t;MI_INTERPOSE_FUN(vfree,mi_cfree),#endif};- MI_INTERPOSE_DECLS(_mi_interposes_10_7) __OSX_AVAILABLE(10.7) = {- MI_INTERPOSE_MI(strndup),- };- MI_INTERPOSE_DECLS(_mi_interposes_10_15) __OSX_AVAILABLE(10.15) = {- MI_INTERPOSE_MI(aligned_alloc),- };+ #if defined(MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)+ MI_INTERPOSE_DECLS(_mi_interposes_10_7) = { MI_INTERPOSE_MI(strndup) };+ #endif+ #if defined(MAC_OS_X_VERSION_10_15) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15)+ MI_INTERPOSE_DECLS(_mi_interposes_10_15) = { MI_INTERPOSE_MI(aligned_alloc) };+ #endif#ifdef __cplusplusextern "C" {@@ -129,8 +125,90 @@ typedef void* mi_nothrow_t;};#elif defined(_MSC_VER)- // cannot override malloc unless using a dll.- // we just override new/delete which does work in a static library.+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRT_HYBRIDPATCHABLE+ void* __cdecl _expand(_Pre_notnull_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Size) {+ return mi_expand(_Block, _Size);+ }+ _Check_return_ _ACRTIMP+ size_t __cdecl _msize_base(_Pre_notnull_ void* _Block) _CRT_NOEXCEPT {+ return mi_malloc_size(_Block);+ }+ _Check_return_ _ACRTIMP _CRT_HYBRIDPATCHABLE+ size_t __cdecl _msize(_Pre_notnull_ void* _Block) {+ return mi_malloc_size(_Block);+ }+ _ACRTIMP+ void __cdecl _free_base(_Pre_maybenull_ _Post_invalid_ void* _Block) {+ mi_free(_Block);+ }+ _ACRTIMP _CRT_HYBRIDPATCHABLE+ void __cdecl free(_Pre_maybenull_ _Post_invalid_ void* _Block) {+ mi_free(_Block);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRT_JIT_INTRINSIC _CRTRESTRICT _CRT_HYBRIDPATCHABLE+ void* __cdecl malloc(_In_ _CRT_GUARDOVERFLOW size_t _Size) {+ return mi_malloc(_Size);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _malloc_base(_In_ size_t _Size) {+ return mi_malloc(_Size);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _realloc_base(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ size_t _Size) {+ return mi_realloc(_Block, _Size);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT _CRT_HYBRIDPATCHABLE+ void* __cdecl realloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Size) {+ return mi_realloc(_Block, _Size);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _calloc_base(_In_ size_t _Count, _In_ size_t _Size) {+ return mi_calloc(_Count, _Size);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRT_JIT_INTRINSIC _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl calloc(_In_ _CRT_GUARDOVERFLOW size_t _Count, _In_ _CRT_GUARDOVERFLOW size_t _Size) {+ return mi_calloc(_Count, _Size);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _recalloc_base(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ size_t _Count, _In_ size_t _Size) {+ return mi_recalloc(_Block, _Count, _Size);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _recalloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Count, _In_ _CRT_GUARDOVERFLOW size_t _Size) {+ return mi_recalloc(_Block, _Count, _Size);+ }+ _ACRTIMP+ void __cdecl _aligned_free(_Pre_maybenull_ _Post_invalid_ void* _Block) {+ mi_free(_Block);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_malloc(_In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment) {+ return mi_malloc_aligned(_Size, _Alignment);+ }+ _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_offset_malloc(_In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment, _In_ size_t _Offset) {+ return mi_malloc_aligned_at(_Size, _Alignment, _Offset);+ }+ _Check_return_ _ACRTIMP+ size_t __cdecl _aligned_msize(_Pre_notnull_ void* _Block, _In_ size_t _Alignment, _In_ size_t _Offset) {+ MI_UNUSED(_Alignment); MI_UNUSED(_Offset); return mi_malloc_size(_Block);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_offset_realloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment, _In_ size_t _Offset) {+ return mi_realloc_aligned_at(_Block, _Size, _Alignment, _Offset);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_offset_recalloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Count, _In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment, _In_ size_t _Offset) {+ return mi_recalloc_aligned_at(_Block, _Count, _Size, _Alignment, _Offset);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_realloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment) {+ return mi_realloc_aligned(_Block, _Size, _Alignment);+ }+ _Success_(return != 0) _Check_return_ _Ret_maybenull_ _Post_writable_byte_size_(_Count * _Size) _ACRTIMP _CRTALLOCATOR _CRTRESTRICT+ void* __cdecl _aligned_recalloc(_Pre_maybenull_ _Post_invalid_ void* _Block, _In_ _CRT_GUARDOVERFLOW size_t _Count, _In_ _CRT_GUARDOVERFLOW size_t _Size, _In_ size_t _Alignment) {+ return mi_recalloc_aligned(_Block, _Count, _Size, _Alignment);+ }#else// On all other systems forward allocation primitives to our APImi_decl_export void* malloc(size_t size) MI_FORWARD1(mi_malloc, size)@@ -215,7 +293,7 @@ typedef void* mi_nothrow_t;void _ZdlPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete(void*, std::align_val_t, std::nothrow_t const&)void _ZdaPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete[](void*, std::align_val_t, std::nothrow_t const&)- #if (MI_INTPTR_SIZE==8)+ #if (MI_INTPTR_SIZE==8) || (MI_INTPTR_SIZE==4 && defined(__EMSCRIPTEN__)) // pr #1257void* _Znwm(size_t n) MI_FORWARD1(mi_new,n) // new 64-bitvoid* _Znam(size_t n) MI_FORWARD1(mi_new,n) // new[] 64-bitvoid* _ZnwmRKSt9nothrow_t(size_t n, mi_nothrow_t tag) { MI_UNUSED(tag); return mi_new_nothrow(n); }@@ -278,7 +356,9 @@ extern "C" {void cfree(void* p) { mi_free(p); }void* pvalloc(size_t size) { return mi_pvalloc(size); }void* memalign(size_t alignment, size_t size) { return mi_memalign(alignment, size); }-void* _aligned_malloc(size_t alignment, size_t size) { return mi_aligned_alloc(alignment, size); }+#if !defined(_WIN32)+void* _aligned_malloc(size_t size, size_t alignment) { return mi_malloc_aligned(size,alignment); }+#endifvoid* reallocarray(void* p, size_t count, size_t size) { return mi_reallocarray(p, count, size); }// some systems define reallocarr so mark it as a weak symbol (#751)mi_decl_weak int reallocarr(void* p, size_t count, size_t size) { return mi_reallocarr(p, count, size); }@@ -313,4 +393,4 @@ mi_decl_weak int reallocarr(void* p, size_t count, size_t size) { return mi_r#pragma GCC visibility pop#endif-#endif // MI_MALLOC_OVERRIDE && !_WIN32+#endif // MI_MALLOC_OVERRIDEdiff --git a/vendored/mimalloc/src/alloc-posix.c b/vendored/mimalloc/src/alloc-posix.cindex 225752fd8..60639ff49 100644--- a/vendored/mimalloc/src/alloc-posix.c+++ b/vendored/mimalloc/src/alloc-posix.c@@ -61,14 +61,14 @@ int mi_posix_memalign(void** p, size_t alignment, size_t size) mi_attr_noexceptif (alignment==0 || !_mi_is_power_of_two(alignment)) return EINVAL; // not a power of 2void* q = mi_malloc_aligned(size, alignment);if (q==NULL && size != 0) return ENOMEM;- mi_assert_internal(((uintptr_t)q % alignment) == 0);+ mi_assert_internal(_mi_is_aligned(q,alignment));*p = q;return 0;}mi_decl_nodiscard mi_decl_restrict void* mi_memalign(size_t alignment, size_t size) mi_attr_noexcept {void* p = mi_malloc_aligned(size, alignment);- mi_assert_internal(((uintptr_t)p % alignment) == 0);+ mi_assert_internal(_mi_is_aligned(p,alignment));return p;}@@ -95,27 +95,43 @@ mi_decl_nodiscard mi_decl_restrict void* mi_aligned_alloc(size_t alignment, size*/// C11 also requires alignment to be a power-of-two (and > 0) which is checked in mi_malloc_alignedvoid* p = mi_malloc_aligned(size, alignment);- mi_assert_internal(((uintptr_t)p % alignment) == 0);+ mi_assert_internal(_mi_is_aligned(p,alignment));return p;}-mi_decl_nodiscard void* mi_reallocarray( void* p, size_t count, size_t size ) mi_attr_noexcept { // BSD- void* newp = mi_reallocn(p,count,size);+mi_decl_nodiscard void* mi_reallocarray( void* p, size_t count, size_t size ) mi_attr_noexcept { // BSD <https://man.freebsd.org/cgi/man.cgi?query=reallocarray>+ size_t total;+ if mi_unlikely(mi_count_size_overflow(count, size, &total)) {+ errno = EOVERFLOW;+ return NULL;+ }+ void* newp = mi_realloc(p,total);if (newp==NULL) { errno = ENOMEM; }return newp;}-mi_decl_nodiscard int mi_reallocarr( void* p, size_t count, size_t size ) mi_attr_noexcept { // NetBSD- mi_assert(p != NULL);- if (p == NULL) {- errno = EINVAL;- return EINVAL;+mi_decl_nodiscard int mi_reallocarr( void* ptrp, size_t count, size_t size ) mi_attr_noexcept { // NetBSD <https://man.netbsd.org/reallocarr.3>+ mi_assert(size != 0);+ mi_assert(ptrp != NULL);+ if (ptrp == NULL || size == 0) {+ return (errno = EINVAL);+ }+ size_t total;+ if mi_unlikely(mi_count_size_overflow(count, size, &total)) {+ return (errno = EOVERFLOW);+ }+ void** op = (void**)ptrp;+ if (total == 0) {+ free(*op);+ *op = NULL;+ return 0;+ }+ else {+ void* newp = mi_realloc(*op,total);+ if (newp == NULL) { return (errno = ENOMEM); }+ *op = newp;+ return 0;}- void** op = (void**)p;- void* newp = mi_reallocarray(*op, count, size);- if mi_unlikely(newp == NULL) { return errno; }- *op = newp;- return 0;}void* mi__expand(void* p, size_t newsize) mi_attr_noexcept { // Microsoft@@ -124,12 +140,13 @@ void* mi__expand(void* p, size_t newsize) mi_attr_noexcept { // Microsoftreturn res;}-mi_decl_nodiscard mi_decl_restrict unsigned short* mi_wcsdup(const unsigned short* s) mi_attr_noexcept {+mi_decl_nodiscard mi_decl_restrict wchar_t* mi_wcsdup(const wchar_t* s) mi_attr_noexcept {if (s==NULL) return NULL;- size_t len;- for(len = 0; s[len] != 0; len++) { }- size_t size = (len+1)*sizeof(unsigned short);- unsigned short* p = (unsigned short*)mi_malloc(size);+ size_t wlen;+ for(wlen = 0; s[wlen] != 0 && wlen < PTRDIFF_MAX; wlen++) { } // prevent overflow on wlen+1+ size_t size;+ if (mi_mul_overflow(wlen+1, sizeof(wchar_t), &size) || size > PTRDIFF_MAX) return NULL;+ wchar_t* p = (wchar_t*)mi_malloc(size);if (p != NULL) {_mi_memcpy(p,s,size);}@@ -141,36 +158,36 @@ mi_decl_nodiscard mi_decl_restrict unsigned char* mi_mbsdup(const unsigned char*}int mi_dupenv_s(char** buf, size_t* size, const char* name) mi_attr_noexcept {- if (buf==NULL || name==NULL) return EINVAL;if (size != NULL) *size = 0;- char* p = getenv(name); // mscver warning 4996+ if (buf==NULL || name==NULL) return EINVAL;+ char* p = getenv(name);if (p==NULL) {*buf = NULL;}else {*buf = mi_strdup(p);if (*buf==NULL) return ENOMEM;- if (size != NULL) *size = _mi_strlen(p);+ if (size != NULL) { *size = _mi_strlen(p) + 1; } // cannot overflow as mi_strdup is limited to PTRDIFF_MAX}return 0;}-int mi_wdupenv_s(unsigned short** buf, size_t* size, const unsigned short* name) mi_attr_noexcept {- if (buf==NULL || name==NULL) return EINVAL;+int mi_wdupenv_s(wchar_t** buf, size_t* size, const wchar_t* name) mi_attr_noexcept {if (size != NULL) *size = 0;+ if (buf==NULL || name==NULL) return EINVAL;#if !defined(_WIN32) || (defined(WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP))// not supported*buf = NULL;return EINVAL;#else- unsigned short* p = (unsigned short*)_wgetenv((const wchar_t*)name); // msvc warning 4996+ wchar_t* p = (wchar_t*)_wgetenv(name);if (p==NULL) {*buf = NULL;}else {*buf = mi_wcsdup(p);if (*buf==NULL) return ENOMEM;- if (size != NULL) *size = wcslen((const wchar_t*)p);+ if (size != NULL) { *size = wcslen(p) + 1; } // cannot overflow as wcsdup is limited to PTRDIFF_MAX}return 0;#endifdiff --git a/vendored/mimalloc/src/alloc.c b/vendored/mimalloc/src/alloc.cindex d7b34e8cb..aa556bd05 100644--- a/vendored/mimalloc/src/alloc.c+++ b/vendored/mimalloc/src/alloc.c@@ -33,8 +33,8 @@ static mi_decl_forceinline void* mi_page_malloc_zero(mi_theap_t* theap, mi_page_{if (page->block_size != 0) { // not the empty theapmi_assert_internal(mi_page_block_size(page) >= size);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);}// check the free list@@ -91,7 +91,7 @@ static mi_decl_forceinline void* mi_page_malloc_zero(mi_theap_t* theap, mi_page_else {block->next = 0;mi_track_mem_defined(block, bsize);- }+ }}#if MI_PADDING // && !MI_TRACK_ENABLED@@ -265,6 +265,15 @@ mi_decl_nodiscard mi_decl_restrict void* mi_zalloc_small(size_t size) mi_attr_noreturn mi_theap_malloc_small_zero(_mi_theap_default(), size, true, NULL);}+mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_zalloc_small(mi_theap_t* theap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_small_zero(theap, size, true, NULL);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc_small(mi_heap_t* heap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_small_zero_nonnull(_mi_heap_theap(heap), size, true, NULL);+}++mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_zalloc(mi_theap_t* theap, size_t size) mi_attr_noexcept {return _mi_theap_malloc_zero(theap, size, true, NULL);}@@ -366,7 +375,7 @@ void* _mi_theap_realloc_zero(mi_theap_t* theap, void* p, size_t newsize, bool zeif (usable_pre!=NULL) { *usable_pre = mi_page_usable_block_size(page); }}if mi_unlikely(newsize<=size && newsize>=(size/2) && newsize>0 // note: newsize must be > 0 or otherwise we return NULL for realloc(NULL,0)- && mi_page_heap(page)==theap->heap) // and within the same heap+ && mi_page_heap(page)==_mi_theap_heap(theap)) // and within the same heap{mi_assert_internal(p!=NULL);// todo: do not track as the usable size is still the same in the free; adjust potential padding?@@ -481,6 +490,7 @@ mi_decl_nodiscard void* mi_heap_recalloc(mi_heap_t* heap, void* p, size_t count,mi_decl_nodiscard static mi_decl_restrict char* mi_theap_strdup(mi_theap_t* theap, const char* s) mi_attr_noexcept {if (s == NULL) return NULL;size_t len = _mi_strlen(s);+ if (len > MI_MAX_ALLOC_SIZE - 1) return NULL; // prevent overflow on len+1char* t = (char*)mi_theap_malloc(theap,len+1);if (t == NULL) return NULL;_mi_memcpy(t, s, len);@@ -500,6 +510,7 @@ mi_decl_nodiscard mi_decl_restrict char* mi_heap_strdup(mi_heap_t* heap, const cmi_decl_nodiscard static mi_decl_restrict char* mi_theap_strndup(mi_theap_t* theap, const char* s, size_t n) mi_attr_noexcept {if (s == NULL) return NULL;const size_t len = _mi_strnlen(s,n); // len <= n+ if (len > MI_MAX_ALLOC_SIZE - 1) return NULL; // prevent overflow on len+1char* t = (char*)mi_theap_malloc(theap, len+1);if (t == NULL) return NULL;_mi_memcpy(t, s, len);@@ -539,17 +550,51 @@ mi_decl_nodiscard static mi_decl_restrict char* mi_theap_realpath(mi_theap_t* threturn mi_theap_strndup(theap, buf, PATH_MAX);}}+#else++#include <unistd.h> // pathconf++static size_t mi_path_max(void) {+ static _Atomic(size_t) path_max = 0;+ size_t pmax = mi_atomic_load_acquire(&path_max);+ if (pmax == 0) {+ long m = 0;+ #ifdef _PC_PATH_MAX+ m = pathconf("/",_PC_PATH_MAX);+ #endif+ if (m <= 0) pmax = 4096; // guess+ else if (m < 256) pmax = 256; // at least 256+ else if (m > 64*1024) pmax = 64*1024; // at most 64 KiB+ else pmax = m;+ size_t expected = 0;+ mi_atomic_cas_strong_acq_rel(&path_max, &expected, pmax);+ }+ return pmax;+}+char* mi_theap_realpath(mi_theap_t* theap, const char* fname, char* resolved_name) mi_attr_noexcept {if (resolved_name != NULL) {return realpath(fname,resolved_name);}else {+ /*char* rname = realpath(fname, NULL);if (rname == NULL) return NULL;- char* result = mi_theap_strdup(theap, rname);- mi_cfree(rname); // use checked free (which may be redirected to our free but that's ok)+ char* result = mi_heap_strdup(heap, rname);+ mi_cfree(rname); // note: may leak the original pointer if allocated internally with the system allocator// note: with ASAN realpath is intercepted and mi_cfree may leak the returned pointer :-(+ return result;+ */+ const size_t n = mi_path_max();+ char* const buf = (char*)mi_zalloc(n+1);+ if (buf == NULL) {+ errno = ENOMEM;+ return NULL;+ }+ char* rname = realpath(fname,buf);+ char* result = mi_theap_strndup(theap,rname,n); // ok if `rname==NULL`+ mi_free(buf);return result;}}@@ -750,7 +795,7 @@ static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {}uint8_t* guard_page = (uint8_t*)block + block_size - os_page_size;// note: the alignment of the guard page relies on blocks being os_page_size aligned which- // is ensured in `mi_arena_page_alloc_fresh`.+ // is ensured in `mi_arena_page_alloc_fresh`.mi_assert_internal(_mi_is_aligned(block, os_page_size));mi_assert_internal(_mi_is_aligned(guard_page, os_page_size));if (!page->memid.is_pinned && _mi_is_aligned(guard_page, os_page_size)) {@@ -770,7 +815,8 @@ static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {// give up to place it right in front of the guard page if the offset is too large for unalignmentoffset = MI_PAGE_MAX_OVERALLOC_ALIGN;}- void* p = (uint8_t*)block + offset;+ uint8_t* const p = (uint8_t*)block + offset;+ mi_assert_internal(p == guard_page - obj_size);mi_track_align(block, p, offset, obj_size);mi_track_mem_defined(block, sizeof(mi_block_t));return p;@@ -778,31 +824,35 @@ static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {mi_decl_restrict void* _mi_theap_malloc_guarded(mi_theap_t* theap, size_t size, bool zero) mi_attr_noexcept{- #if defined(MI_PADDING_SIZE)- mi_assert(MI_PADDING_SIZE==0);- #endif// allocate multiple of page size ending in a guard page// ensure minimal alignment requirement?+ if mi_unlikely(size >= MI_MAX_ALLOC_SIZE - MI_PADDING_SIZE) { // check up front so the `req_size` won't overflow+ _mi_error_message(EOVERFLOW, "(guarded) allocation request is too large (%zu bytes)\n", size);+ return NULL;+ }const size_t os_page_size = _mi_os_page_size();const size_t obj_size = (mi_option_is_enabled(mi_option_guarded_precise) ? size : _mi_align_up(size, MI_MAX_ALIGN_SIZE));const size_t bsize = _mi_align_up(_mi_align_up(obj_size, MI_MAX_ALIGN_SIZE) + sizeof(mi_block_t), MI_MAX_ALIGN_SIZE);- const size_t req_size = _mi_align_up(bsize + os_page_size, os_page_size);- mi_block_t* const block = (mi_block_t*)_mi_malloc_generic(theap, req_size, (zero ? 1 : 0), NULL);+ const size_t req_size = _mi_align_up(bsize + os_page_size, os_page_size);+ mi_block_t* const block = (mi_block_t*)_mi_malloc_generic(theap, req_size, 0 /* don't zero */, NULL);if (block==NULL) return NULL;void* const p = mi_block_ptr_set_guarded(block, obj_size);+ if (p == NULL) return p;+ if (zero) {+ _mi_memzero_aligned(p,obj_size); // we have to zero here as padding might have written here (if the blocksize > reqsize + os_page_size)+ }// stats- mi_track_malloc(p, size, zero);- if (p != NULL) {- if (!mi_theap_is_initialized(theap)) { theap = _mi_theap_default(); }- #if MI_STAT>1- mi_theap_stat_adjust_decrease(theap, malloc_requested, req_size);- mi_theap_stat_increase(theap, malloc_requested, size);- #endif- mi_theap_stat_counter_increase(theap, malloc_guarded_count, 1);- }+ mi_track_malloc(p, obj_size, zero);+ if (!mi_theap_is_initialized(theap)) { theap = _mi_theap_default(); }+ mi_theap_stat_counter_increase(theap, malloc_guarded_count, 1);+ #if MI_STAT>1+ // adjust stats to only count the allocated size of the block (and not the guard page)+ mi_theap_stat_adjust_decrease(theap, malloc_requested, req_size);+ mi_theap_stat_increase(theap, malloc_requested, size);+ #endif#if MI_DEBUG>3- if (p != NULL && zero) {+ if (zero) {mi_assert_expensive(mi_mem_is_zero(p, size));}#endifdiff --git a/vendored/mimalloc/src/arena-meta.c b/vendored/mimalloc/src/arena-meta.cindex 7ff336e8c..cee38caa1 100644--- a/vendored/mimalloc/src/arena-meta.c+++ b/vendored/mimalloc/src/arena-meta.c@@ -46,7 +46,7 @@ static mi_decl_cache_align _Atomic(mi_meta_page_t*) mi_meta_pages = MI_ATOMIC_V#if MI_DEBUG > 1static mi_meta_page_t* mi_meta_page_of_ptr(void* p, size_t* block_idx) {- mi_meta_page_t* mpage = (mi_meta_page_t*)((uint8_t*)mi_align_down_ptr(p,MI_META_PAGE_ALIGN) + _mi_os_secure_guard_page_size());+ mi_meta_page_t* mpage = (mi_meta_page_t*)((uint8_t*)_mi_align_down_ptr(p,MI_META_PAGE_ALIGN) + _mi_os_secure_guard_page_size());if (block_idx != NULL) {*block_idx = ((uint8_t*)p - (uint8_t*)mpage) / MI_META_BLOCK_SIZE;}@@ -118,7 +118,7 @@ mi_decl_noinline void* _mi_meta_zalloc( size_t size, mi_memid_t* pmemid )mi_meta_page_t* mpage = mpage0;while (mpage != NULL) {size_t block_idx;- if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, block_count, 0, &block_idx)) {+ if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, 0, block_count, &block_idx)) {// found and claimed `block_count` blocks*pmemid = _mi_memid_create_meta(mpage, block_idx, block_count);return mi_meta_block_start(mpage,block_idx);@@ -136,7 +136,7 @@ mi_decl_noinline void* _mi_meta_zalloc( size_t size, mi_memid_t* pmemid )mpage = mi_meta_page_zalloc();if (mpage != NULL) {size_t block_idx;- if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, block_count, 0, &block_idx)) {+ if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, 0, block_count, &block_idx)) {// found and claimed `block_count` blocks*pmemid = _mi_memid_create_meta(mpage, block_idx, block_count);return mi_meta_block_start(mpage,block_idx);diff --git a/vendored/mimalloc/src/arena.c b/vendored/mimalloc/src/arena.cindex 872ea4900..a5686d554 100644--- a/vendored/mimalloc/src/arena.c+++ b/vendored/mimalloc/src/arena.c@@ -33,21 +33,31 @@ mi_arena_id_t _mi_arena_id_none(void) {}mi_arena_t* _mi_arena_from_id(mi_arena_id_t id) {- return (mi_arena_t*)id;+ mi_arena_t* const arena = (mi_arena_t*)id;+ mi_assert_internal(arena==NULL || arena->parent==NULL); // id's should never point to sub-arena's+ return arena;+}++mi_arena_id_t mi_arena_id_from_arena(mi_arena_t* arena) {+ mi_assert_internal(arena==NULL || arena->parent==NULL);+ return (arena==NULL ? _mi_arena_id_none() : (mi_arena_id_t)arena);}-static bool mi_arena_id_is_suitable(mi_arena_t* arena, mi_arena_t* req_arena) {- return ((arena == req_arena) || // they match,- (req_arena == NULL && !arena->is_exclusive)); // or the arena is not exclusive, and we didn't request a specific one+static bool mi_arena_is_suitable(mi_arena_t* arena, mi_arena_t* req_arena) {+ if (arena == req_arena) return true; // they match+ if (arena == NULL) return false;+ if (req_arena == NULL && !arena->is_exclusive) return true; // or the arena is not exclusive, and we didn't request a specific one+ if (arena->parent != NULL && arena->parent == req_arena) return true; // sub-arena? (note that req_arena is never a sub arena)+ return false;}bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_t* request_arena) {if (memid.memkind == MI_MEM_ARENA) {- return mi_arena_id_is_suitable(memid.mem.arena.arena, request_arena);+ return mi_arena_is_suitable(memid.mem.arena.arena, request_arena);}else {- return mi_arena_id_is_suitable(NULL, request_arena);+ return mi_arena_is_suitable(NULL, request_arena);}}@@ -57,7 +67,7 @@ size_t mi_arenas_get_count(mi_subproc_t* subproc) {mi_arena_t* mi_arena_from_index(mi_subproc_t* subproc, size_t idx) {mi_assert_internal(idx < mi_arenas_get_count(subproc));- return mi_atomic_load_ptr_relaxed(mi_arena_t, &subproc->arenas[idx]);+ return mi_atomic_load_ptr_acquire(mi_arena_t, &subproc->arenas[idx]);}static size_t mi_arena_info_slices(mi_arena_t* arena) {@@ -79,6 +89,10 @@ size_t mi_arena_min_alignment(void) {return MI_ARENA_SLICE_ALIGN;}+size_t mi_arena_min_size(void) {+ return MI_ARENA_MIN_SIZE;+}+static size_t mi_arena_max_object_size(void) {size_t max_size = mi_option_get_size(mi_option_arena_max_object_size);max_size = _mi_align_up(max_size, MI_ARENA_SLICE_SIZE);@@ -124,15 +138,34 @@ static uint8_t* mi_arena_start(mi_arena_t* arena) {// Start of a sliceuint8_t* mi_arena_slice_start(mi_arena_t* arena, size_t slice_index) {+ mi_assert_internal(slice_index < arena->slice_count);return (mi_arena_start(arena) + mi_size_of_slices(slice_index));}+mi_page_t* mi_arena_page_at_slice(mi_arena_t* arena, size_t slice_index) {+ mi_assert_internal(slice_index < arena->slice_count);+ if (arena->pages_meta != NULL) {+ mi_page_t* const page = &arena->pages_meta[slice_index];+ #if MI_PAGE_META_ALIGNED_FREE_SMALL+ // pages with small blocks still have the page at the start of the slice (and set the `block_size` in pages_meta to 0)+ if (page->block_size>0) return page;+ #else+ return page;+ #endif+ }+ // fall through (for MI_PAGE_META_ALIGNED_FREE_SMALL)+ return (mi_page_t*)mi_arena_slice_start(arena,slice_index);+}+// Arena areavoid* mi_arena_area(mi_arena_id_t arena_id, size_t* size) {if (size != NULL) *size = 0;mi_arena_t* arena = _mi_arena_from_id(arena_id);if (arena == NULL) return NULL;- if (size != NULL) { *size = mi_size_of_slices(arena->slice_count); }+ if (size != NULL) {+ mi_assert_internal(mi_size_of_slices(arena->slice_count) <= arena->total_size);+ *size = arena->total_size;+ }return mi_arena_start(arena);}@@ -183,7 +216,7 @@ static mi_decl_noinline void* mi_arena_try_alloc_at(mi_arena_t* arena, size_t slice_count, bool commit, size_t tseq, mi_memid_t* memid){size_t slice_index;- if (!mi_bbitmap_try_find_and_clearN(arena->slices_free, slice_count, tseq, &slice_index)) return NULL;+ if (!mi_bbitmap_try_find_and_clearN(arena->slices_free, tseq, slice_count, &slice_index)) return NULL;// claimed it!void* p = mi_arena_slice_start(arena, slice_index);@@ -206,7 +239,7 @@ static mi_decl_noinline void* mi_arena_try_alloc_at(if (already_committed < slice_count) {// not all committed, try to commit nowbool commit_zero = false;- if (!_mi_os_commit_ex(p, mi_size_of_slices(slice_count), &commit_zero, mi_size_of_slices(slice_count - already_committed))) {+ if (!mi_arena_commit(arena, p, mi_size_of_slices(slice_count), &commit_zero, mi_size_of_slices(slice_count - already_committed))) {// if the commit fails, release ownership, and return NULL;// note: this does not roll back dirty bits but that is ok.mi_bbitmap_setN(arena->slices_free, slice_index, slice_count);@@ -234,7 +267,7 @@ static mi_decl_noinline void* mi_arena_try_alloc_at(_mi_os_reuse(p, mi_size_of_slices(slice_count));// if the OS has overcommit, and this is the first time we access these pages, then// count the commit now (as at arena reserve we didn't count those commits as these are on-demand)- if (_mi_os_has_overcommit() && touched_slices > 0) {+ if (_mi_os_has_overcommit() && touched_slices > 0 && !arena->memid.is_pinned /* huge pages, issue #1236 */) {mi_subproc_stat_increase( arena->subproc, committed, mi_size_of_slices(touched_slices));}}@@ -319,7 +352,7 @@ static bool mi_arena_reserve(mi_subproc_t* subproc, size_t req_size, bool allow_// commit eagerly?bool arena_commit = false;const bool overcommit = _mi_os_has_overcommit();- if (mi_option_get(mi_option_arena_eager_commit) == 2) { arena_commit = overcommit; }+ if (mi_option_get(mi_option_arena_eager_commit) == 2) { arena_commit = overcommit || mi_option_is_enabled(mi_option_allow_large_os_pages); }else if (mi_option_get(mi_option_arena_eager_commit) == 1) { arena_commit = true; }// on an OS with overcommit (Linux) we don't count the commit yet as it is on-demand. Once a slice@@ -349,9 +382,9 @@ static bool mi_arena_reserve(mi_subproc_t* subproc, size_t req_size, bool allow_Arena iteration----------------------------------------------------------- */-static inline bool mi_arena_is_suitable(mi_arena_t* arena, mi_arena_t* req_arena, bool match_numa, int numa_node, bool allow_pinned) {+static inline bool mi_arena_is_suitable_ex(mi_arena_t* arena, mi_arena_t* req_arena, bool match_numa, int numa_node, bool allow_pinned) {if (!allow_pinned && arena->memid.is_pinned) return false;- if (!mi_arena_id_is_suitable(arena, req_arena)) return false;+ if (!mi_arena_is_suitable(arena, req_arena)) return false;if (req_arena == NULL) { // if not specific, check numa affinityconst bool numa_suitable = (numa_node < 0 || arena->numa_node < 0 || arena->numa_node == numa_node);if (match_numa) { if (!numa_suitable) return false; }@@ -366,7 +399,7 @@ static size_t mi_arena_start_idx(mi_heap_t* heap, size_t tseq, size_t arena_cyclconst size_t hseq = heap->heap_seq;const size_t hcount = mi_atomic_load_relaxed(&heap->subproc->heap_count);if (arena_cycle <= 1) return 0;- if (hseq==0 || hcount<=1) return (tseq % arena_cycle); // common for single heap programs+ if (hseq==0 || hcount<=1 || arena_cycle > 0x8FF) return (tseq % arena_cycle); // common for single heap programs// spread heaps evenly among arena's, and then evenly for threads in their fractionsize_t start;@@ -377,8 +410,8 @@ static size_t mi_arena_start_idx(mi_heap_t* heap, size_t tseq, size_t arena_cyclstart = (hseq % arena_cycle);}else {- const size_t hspot = (hseq % hcount);- start = (frac * hspot) / 256;+ const size_t hspot = (hseq % hcount);+ start = (frac * hspot) / 256; // (arena_cycle * (hseq % hcount)) / hcountif (frac >= 512) { // at least 2 arena's per heap?start = start + (tseq % (frac/256));}@@ -419,7 +452,7 @@ static size_t mi_arena_start_idx(mi_heap_t* heap, size_t tseq, size_t arena_cycl#define mi_forall_suitable_arenas(heap, req_arena, tseq, match_numa, numa_node, allow_large, name_arena) \mi_forall_arenas(heap, req_arena,tseq,name_arena) { \- if (mi_arena_is_suitable(name_arena, req_arena, match_numa, numa_node, allow_large)) { \+ if (mi_arena_is_suitable_ex(name_arena, req_arena, match_numa, numa_node, allow_large)) { \#define mi_forall_suitable_arenas_end() \}} \@@ -481,13 +514,16 @@ static mi_decl_noinline void* mi_arenas_try_alloc(// don't create arena's while preloading (todo: or should we?)if (_mi_preloading()) return NULL;+ // don't create arena's if OS allocation is disallowed+ if (mi_option_is_enabled(mi_option_disallow_os_alloc)) return NULL;+// otherwise, try to reserve a new arena -- but one thread at a time.. (todo: allow 2 or 4 to reduce contention?)mi_subproc_t* const subproc = heap->subproc;const size_t arena_count = mi_arenas_get_count(subproc);mi_lock(&subproc->arena_reserve_lock) {if (arena_count == mi_arenas_get_count(subproc)) {// we are the first to enter the lock, reserve a fresh arena- mi_arena_id_t arena_id = 0;+ mi_arena_id_t arena_id = _mi_arena_id_none();mi_arena_reserve(subproc, mi_size_of_slices(slice_count), allow_large, &arena_id);}else {@@ -586,7 +622,7 @@ static bool mi_abandoned_page_unown(mi_page_t* page, mi_theap_t* current_theap)static bool mi_arena_try_claim_abandoned(size_t slice_index, mi_arena_t* arena, bool* keep_abandoned) {// found an abandoned page of the right size- mi_page_t* const page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_page_t* const page = mi_arena_page_at_slice(arena, slice_index);// can we claim ownership?if (!mi_page_claim_ownership(page)) {// there was a concurrent free that reclaims this page ..@@ -610,7 +646,7 @@ static mi_arena_pages_t* mi_heap_arena_pages(mi_heap_t* heap, mi_arena_t* arena)mi_assert_internal(arena!=NULL);mi_assert_internal(heap!=NULL);mi_assert(arena->arena_idx < MI_MAX_ARENAS);- return mi_atomic_load_ptr_relaxed(mi_arena_pages_t, &heap->arena_pages[arena->arena_idx]);+ return mi_atomic_load_ptr_acquire(mi_arena_pages_t, &heap->arena_pages[arena->arena_idx]);}static mi_arena_t* mi_page_arena_pages(mi_page_t* page, size_t* slice_index, size_t* slice_count, mi_arena_pages_t** parena_pages) {@@ -655,7 +691,7 @@ static mi_arena_pages_t* mi_heap_ensure_arena_pages(mi_heap_t* heap, mi_arena_t*static mi_page_t* mi_arenas_page_try_find_abandoned(mi_theap_t* theap, size_t slice_count, size_t block_size){- mi_heap_t* const heap = theap->heap;+ mi_heap_t* const heap = _mi_theap_heap(theap);const size_t tseq = theap->tld->thread_seq;mi_arena_t* const req_arena = heap->exclusive_arena;@@ -683,7 +719,7 @@ static mi_page_t* mi_arenas_page_try_find_abandoned(mi_theap_t* theap, size_t slif (mi_bitmap_try_find_and_claim(bitmap, tseq, &slice_index, &mi_arena_try_claim_abandoned, arena)) {// found an abandoned page of the right size// and claimed ownership.- mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_page_t* page = mi_arena_page_at_slice(arena, slice_index);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));mi_assert_internal(mi_heap_has_page(heap, arena, page));@@ -695,8 +731,7 @@ static mi_page_t* mi_arenas_page_try_find_abandoned(mi_theap_t* theap, size_t slmi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));mi_assert_internal(page->slice_committed > 0 || mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));mi_assert_internal(mi_bitmap_is_setN(arena->slices_dirty, slice_index, slice_count));- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_block_size(page) == block_size);mi_assert_internal(!mi_page_is_full(page));@@ -708,146 +743,196 @@ static mi_page_t* mi_arenas_page_try_find_abandoned(mi_theap_t* theap, size_t slreturn NULL;}--// Allocate a fresh page-static mi_page_t* mi_arenas_page_alloc_fresh(mi_theap_t* theap, size_t slice_count, size_t block_size, size_t block_alignment, bool commit)-{- const bool allow_large = (MI_SECURE < 2); // 2 = guard page at end of each arena page- const bool os_align = (block_alignment > MI_PAGE_MAX_OVERALLOC_ALIGN);+static uint8_t* mi_arenas_page_alloc_fresh_area(mi_theap_t* theap, size_t slice_count, size_t block_size, size_t block_alignment, bool os_align, bool commit, mi_memid_t* memid) {+ MI_UNUSED_RELEASE(block_size);+ const bool allow_large = (MI_SECURE < 5); // 5 = guard page at end of each arena pageconst size_t page_alignment = MI_ARENA_SLICE_ALIGN;- mi_heap_t* const heap = theap->heap;+ mi_heap_t* const heap = _mi_theap_heap(theap);mi_tld_t* const tld = theap->tld;mi_arena_t* const req_arena = heap->exclusive_arena;const int numa_node = (heap->numa_node >= 0 ? heap->numa_node : tld->numa_node);-// try to allocate from free space in arena's- mi_memid_t memid = _mi_memid_none();- mi_page_t* page = NULL;+ uint8_t* start = NULL;+ *memid = _mi_memid_none();const size_t alloc_size = mi_size_of_slices(slice_count);if (!mi_option_is_enabled(mi_option_disallow_arena_alloc) && // allowed to allocate from arena's?!os_align && // not large alignmentslice_count <= mi_arena_max_object_size()/MI_ARENA_SLICE_SIZE) // and not too large{- page = (mi_page_t*)mi_arenas_try_alloc(heap, slice_count, page_alignment, commit, allow_large, req_arena, tld->thread_seq, numa_node, &memid);- if (page != NULL) {- mi_arena_pages_t* const arena_pages = mi_heap_ensure_arena_pages(heap, memid.mem.arena.arena);+ start = (uint8_t*)mi_arenas_try_alloc(heap, slice_count, page_alignment, commit, allow_large, req_arena, tld->thread_seq, numa_node, memid);+ if (start != NULL) {+ mi_arena_pages_t* const arena_pages = mi_heap_ensure_arena_pages(heap, memid->mem.arena.arena);if (arena_pages==NULL) {- _mi_arenas_free(page, mi_size_of_slices(slice_count), page->memid); // roll back- page = NULL;+ _mi_arenas_free(start, mi_size_of_slices(slice_count), *memid); // roll back+ start = NULL;}else {- mi_assert_internal(mi_bitmap_is_clearN(arena_pages->pages, memid.mem.arena.slice_index, memid.mem.arena.slice_count));- mi_bitmap_set(arena_pages->pages, memid.mem.arena.slice_index);+ // note: the following assert should hold if we could check it atomically, but in a concurrent setting we may already allocate in slice_count+ // mi_assert_internal(mi_bitmap_is_clearN(arena_pages->pages, memid->mem.arena.slice_index, memid->mem.arena.slice_count));+ mi_assert_internal(mi_bitmap_is_clear(arena_pages->pages, memid->mem.arena.slice_index));+ mi_bitmap_set(arena_pages->pages, memid->mem.arena.slice_index);}}}// otherwise fall back to the OS- if (page == NULL) {+ if (start == NULL) {if (os_align) {// note: slice_count already includes the pagemi_assert_internal(slice_count >= mi_slice_count_of_size(block_size) + mi_slice_count_of_size(page_alignment));- page = (mi_page_t*)mi_arena_os_alloc_aligned(alloc_size, block_alignment, page_alignment /* align offset */, commit, allow_large, req_arena, &memid);+ start = (uint8_t*)mi_arena_os_alloc_aligned(alloc_size, block_alignment, page_alignment /* align offset */, commit, allow_large, req_arena, memid);}else {- page = (mi_page_t*)mi_arena_os_alloc_aligned(alloc_size, page_alignment, 0 /* align offset */, commit, allow_large, req_arena, &memid);+ start = (uint8_t*)mi_arena_os_alloc_aligned(alloc_size, page_alignment, 0 /* align offset */, commit, allow_large, req_arena, memid);}}- if (page == NULL) return NULL;- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(!os_align || _mi_is_aligned((uint8_t*)page + page_alignment, block_alignment));-- // guard page at the end of mimalloc page?- #if MI_SECURE < 2- const size_t page_noguard_size = alloc_size;- #else- mi_assert(alloc_size > _mi_os_secure_guard_page_size());- const size_t page_noguard_size = alloc_size - _mi_os_secure_guard_page_size();- if (memid.initially_committed) {- _mi_os_secure_guard_page_set_at((uint8_t*)page + page_noguard_size, memid);- }- #endif-- // claimed free slices: initialize the page partly- if (!memid.initially_zero && memid.initially_committed) {- mi_track_mem_undefined(page, slice_count * MI_ARENA_SLICE_SIZE);- _mi_memzero_aligned(page, sizeof(*page));- }- else if (memid.initially_committed) {- mi_track_mem_defined(page, slice_count * MI_ARENA_SLICE_SIZE);- }- #if MI_DEBUG > 1- if (memid.initially_zero && memid.initially_committed) {- if (!mi_mem_is_zero(page, page_noguard_size)) {- _mi_error_message(EFAULT, "internal error: page memory was not zero initialized.\n");- memid.initially_zero = false;- _mi_memzero_aligned(page, sizeof(*page));- }- }- #endif- mi_assert(MI_PAGE_INFO_SIZE >= mi_page_info_size());+ if (start == NULL) return NULL;+ mi_assert_internal(_mi_is_aligned(start, MI_PAGE_ALIGN));+ mi_assert_internal(!os_align || _mi_is_aligned(start + page_alignment, block_alignment));+ return start;+}- size_t block_start;+static size_t mi_page_block_start(size_t block_size, bool os_align)+{#if MI_GUARDED// in a guarded build, we align pages with blocks a multiple of an OS page size, to the OS page size// this ensures that all blocks in such pages are OS page size aligned (which is needed for the guard pages)const size_t os_page_size = _mi_os_page_size();mi_assert_internal(MI_PAGE_ALIGN >= os_page_size);if (!os_align && block_size % os_page_size == 0 && block_size > os_page_size /* at least 2 or more */ ) {- block_start = _mi_align_up(mi_page_info_size(), os_page_size);+ return _mi_align_up(mi_page_info_size(), os_page_size);}else#endifif (os_align) {- block_start = MI_PAGE_ALIGN;+ return MI_PAGE_ALIGN;}else if (_mi_is_power_of_two(block_size) && block_size <= MI_PAGE_MAX_START_BLOCK_ALIGN2) {// naturally align power-of-2 blocks up to MI_PAGE_MAX_START_BLOCK_ALIGN2 size (4KiB)- block_start = _mi_align_up(mi_page_info_size(), block_size);+ return _mi_align_up(mi_page_info_size(), block_size);}else if (block_size != 0 && (block_size % MI_PAGE_OSPAGE_BLOCK_ALIGN2) == 0) {// also align large pages that are a multiple of MI_PAGE_OSPAGE_BLOCK_ALIGN2 (4KiB)- block_start = _mi_align_up(mi_page_info_size(), MI_PAGE_OSPAGE_BLOCK_ALIGN2);+ return _mi_align_up(mi_page_info_size(), MI_PAGE_OSPAGE_BLOCK_ALIGN2);}else {// otherwise start after the info- block_start = mi_page_info_size();+ return mi_page_info_size();+ }+}++// Allocate a fresh page+static mi_page_t* mi_arenas_page_alloc_fresh(mi_theap_t* theap, size_t slice_count, size_t block_size, size_t block_alignment, bool commit)+{+ const bool os_align = (block_alignment > MI_PAGE_MAX_OVERALLOC_ALIGN);+ const size_t alloc_size = mi_size_of_slices(slice_count);+ mi_memid_t memid = _mi_memid_none();+ uint8_t* const slice_start = mi_arenas_page_alloc_fresh_area(theap,slice_count,block_size,block_alignment,os_align,commit,&memid);+ if (!slice_start) return NULL;++ // guard page at the end of mimalloc page?+ #if MI_SECURE>=5+ mi_assert(alloc_size > _mi_os_secure_guard_page_size());+ const size_t page_noguard_size = alloc_size - _mi_os_secure_guard_page_size();+ if (memid.initially_committed) {+ _mi_os_secure_guard_page_set_at(slice_start + page_noguard_size, memid);+ }+ #else+ const size_t page_noguard_size = alloc_size;+ #endif++ // allocate the page meta info+ mi_page_t* page = NULL;+ bool page_meta_is_separate = false;+ size_t block_start = 0;++ // allocate page meta info at the arena start?+ if (memid.memkind == MI_MEM_ARENA) {+ mi_arena_t* const arena = memid.mem.arena.arena;+ if (arena->pages_meta != NULL) {+ mi_assert_internal(MI_PAGE_META_IS_SEPARATED!=0);+ mi_page_t* const page_meta = &arena->pages_meta[memid.mem.arena.slice_index];+ mi_assert_internal(page_meta->block_size == 0);+ #if MI_PAGE_META_ALIGNED_FREE_SMALL+ // if `block_size <= MI_SMALL_SIZE_MAX` we put the page info in front of the slice,+ // (note: it is important that `page_meta->block_size == 0` for `mi_arena_page_at_slice`)+ if (block_size > MI_SMALL_SIZE_MAX)+ #endif+ {+ page = page_meta;+ page_meta_is_separate = true;+ block_start = 0;+ #if !defined(MI_PAGE_BLOCK_START_MAX_OFFSET)+ #define MI_PAGE_BLOCK_START_MAX_OFFSET (8*MI_INTPTR_BITS) /* 512 */+ #endif+ if (block_size >= MI_INTPTR_SIZE && block_size <= MI_PAGE_BLOCK_START_MAX_OFFSET && _mi_is_power_of_two(block_size)) {+ block_start += block_size;+ }+ mi_assert_internal(page->block_size == 0);+ _mi_memzero_aligned(page, sizeof(*page));+ }+ }+ }+ if (page == NULL) {+ // put page meta info in front of the slice+ page = (mi_page_t*)slice_start;+ block_start = mi_page_block_start(block_size, os_align);}- const size_t reserved = (os_align ? 1 : (page_noguard_size - block_start) / block_size);- mi_assert_internal(reserved > 0 && reserved <= UINT16_MAX);// commit first block?size_t commit_size = 0;if (!memid.initially_committed) {commit_size = _mi_align_up(block_start + block_size, MI_PAGE_MIN_COMMIT_SIZE);if (commit_size > page_noguard_size) { commit_size = page_noguard_size; }- bool is_zero;- if mi_unlikely(!mi_arena_commit( mi_memid_arena(memid), page, commit_size, &is_zero, 0)) {- _mi_arenas_free(page, alloc_size, memid);+ bool is_zero = false;+ if mi_unlikely(!mi_arena_commit( mi_memid_arena(memid), slice_start, commit_size, &is_zero, 0)) {+ _mi_arenas_free(slice_start, alloc_size, memid);return NULL;}- if (!memid.initially_zero && !is_zero) {- _mi_memzero_aligned(page, commit_size);+ }+ if (!memid.initially_zero && !page_meta_is_separate) {+ _mi_memzero_aligned(page, sizeof(*page));+ }++ // claimed free slices: initialize the page partly+ if (!memid.initially_zero && memid.initially_committed) {+ mi_track_mem_undefined(slice_start, slice_count * MI_ARENA_SLICE_SIZE);+ }+ else if (memid.initially_committed) {+ mi_track_mem_defined(slice_start, slice_count * MI_ARENA_SLICE_SIZE);+ }+ #if MI_DEBUG > 1+ if (memid.initially_zero && memid.initially_committed) {+ if (!mi_mem_is_zero(slice_start, page_noguard_size)) {+ _mi_error_message(EFAULT, "internal error: page memory was not zero initialized.\n");+ memid.initially_zero = false;+ if (block_start > 0) { _mi_memzero_aligned(page, sizeof(*page)); }}}+ #endif+ const size_t reserved = (os_align ? 1 : (page_noguard_size - block_start) / block_size);+ mi_assert_internal(reserved > 0 && reserved <= UINT16_MAX);// initializepage->reserved = (uint16_t)reserved;- page->page_start = (uint8_t*)page + block_start;+ page->page_start = slice_start + block_start;page->block_size = block_size;page->slice_committed = commit_size;page->memid = memid;page->free_is_zero = memid.initially_zero;+ mi_assert_internal(page->free==NULL);+ mi_assert_internal(page_meta_is_separate == mi_page_meta_is_separated(page));+ mi_assert_internal(mi_page_slice_start(page) == slice_start);// and own itmi_page_claim_ownership(page);// register in the page mapif mi_unlikely(!_mi_page_map_register(page)) {- _mi_arenas_free( page, alloc_size, memid );+ _mi_arenas_free( slice_start, alloc_size, memid );return NULL;}@@ -855,7 +940,7 @@ static mi_page_t* mi_arenas_page_alloc_fresh(mi_theap_t* theap, size_t slice_coumi_theap_stat_increase(theap, pages, 1);mi_theap_stat_increase(theap, page_bins[_mi_page_stats_bin(page)], 1);- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page),MI_PAGE_ALIGN));mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_block_size(page) == block_size);mi_assert_internal(mi_page_is_abandoned(page));@@ -937,8 +1022,7 @@ mi_page_t* _mi_arenas_page_alloc(mi_theap_t* theap, size_t block_size, size_t blreturn NULL;}// mi_assert_internal(page == NULL || _mi_page_segment(page)->subproc == tld->subproc);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(block_alignment <= MI_PAGE_MAX_OVERALLOC_ALIGN || _mi_is_aligned(mi_page_start(page), block_alignment));@@ -946,8 +1030,8 @@ mi_page_t* _mi_arenas_page_alloc(mi_theap_t* theap, size_t block_size, size_t bl}void _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx) {- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_all_free(page));mi_assert_internal(mi_page_is_abandoned(page));@@ -983,9 +1067,9 @@ void _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx) {// recommit guard page at the end?// we must do this since we may later allocate large spans over this page and cannot have a guard page in between- #if MI_SECURE >= 2+ #if MI_SECURE >= 5if (!page->memid.is_pinned) {- _mi_os_secure_guard_page_reset_before((uint8_t*)page + mi_page_full_size(page), page->memid);+ _mi_os_secure_guard_page_reset_before(mi_page_slice_start(page) + mi_page_full_size(page), page->memid);}#endif@@ -1018,7 +1102,8 @@ void _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx) {mi_assert_internal(mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));}}- _mi_arenas_free(page, mi_page_full_size(page), page->memid);+ if (mi_page_meta_is_separated(page)) { page->block_size = 0; } // for assertion checking+ _mi_arenas_free( mi_page_slice_start(page), mi_page_full_size(page), page->memid);}/* -----------------------------------------------------------@@ -1026,8 +1111,8 @@ void _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx) {----------------------------------------------------------- */void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap) {- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));mi_assert_internal(!mi_page_all_free(page));@@ -1035,7 +1120,7 @@ void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap) {mi_assert_internal(_mi_thread_id()==current_theap->tld->thread_id);// mi_assert_internal(current_theap == _mi_page_associated_theap(page));- mi_heap_t* heap = mi_page_heap(page); mi_assert_internal(heap==current_theap->heap);+ mi_heap_t* heap = mi_page_heap(page); mi_assert_internal(heap==_mi_theap_heap(current_theap));if (page->memid.memkind==MI_MEM_ARENA && !mi_page_is_full(page)) {// make available for allocationssize_t bin = _mi_bin(mi_page_block_size(page));@@ -1053,7 +1138,7 @@ void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap) {const bool was_clear = mi_bitmap_set(arena_pages->pages_abandoned[bin], slice_index);MI_UNUSED(was_clear); mi_assert_internal(was_clear);mi_atomic_increment_relaxed(&heap->abandoned_count[bin]);- mi_theap_stat_increase(current_theap, pages_abandoned, 1);+ mi_theap_stat_increase(current_theap, pages_abandoned, 1);}else {// page is full (or a singleton), or the page is OS/externally allocated@@ -1076,8 +1161,8 @@ void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap) {// this is called from `free.c:mi_free_try_collect_mt` only.bool _mi_arenas_page_try_reabandon_to_mapped(mi_page_t* page) {- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));mi_assert_internal(!mi_page_is_abandoned_mapped(page));@@ -1104,8 +1189,8 @@ bool _mi_arenas_page_try_reabandon_to_mapped(mi_page_t* page) {// called from `mi_free` if trying to unabandon an abandoned pagevoid _mi_arenas_page_unabandon(mi_page_t* page, mi_theap_t* current_theapx) {- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));mi_assert_internal(current_theapx==NULL || _mi_thread_id()==current_theapx->tld->thread_id);@@ -1183,7 +1268,7 @@ void _mi_arenas_free(void* p, size_t size, mi_memid_t memid) {}mi_assert_internal(slice_index < arena->slice_count);mi_assert_internal(slice_index >= mi_arena_info_slices(arena));- if (slice_index < mi_arena_info_slices(arena) || slice_index > arena->slice_count) {+ if (slice_index < mi_arena_info_slices(arena) || slice_index >= arena->slice_count) {_mi_error_message(EINVAL, "trying to free from an invalid arena block: %p, size %zu, memid: 0x%zx\n", p, size, memid);return;}@@ -1220,25 +1305,41 @@ void _mi_arenas_collect(bool force_purge, bool visit_all, mi_tld_t* tld) {// Is a pointer contained in the given arena area?-bool mi_arena_contains(mi_arena_id_t arena_id, const void* p) {- mi_arena_t* arena = _mi_arena_from_id(arena_id);- return (mi_arena_start(arena) <= (const uint8_t*)p &&+static bool mi_arena_strictly_contains(mi_arena_t* arena, const void* p) {+ return (arena != NULL &&+ mi_arena_start(arena) <= (const uint8_t*)p &&mi_arena_start(arena) + mi_size_of_slices(arena->slice_count) >(const uint8_t*)p);}// Is a pointer inside any of our arenas?-bool _mi_arenas_contain(const void* p) {+static bool mi_arenas_contain_ex(const void* p, mi_arena_t* parent) {mi_subproc_t* subproc = _mi_subproc();const size_t max_arena = mi_arenas_get_count(subproc);for (size_t i = 0; i < max_arena; i++) {mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &subproc->arenas[i]);- if (arena != NULL && mi_arena_contains(arena,p)) {- return true;+ if (arena != NULL) {+ if (parent==NULL || arena==parent || arena->parent==parent) {+ if (mi_arena_strictly_contains(arena, p)) {+ return true;+ }+ }}}return false;}+// Is a pointer inside any of our arenas?+bool _mi_arenas_contain(const void* p) {+ return mi_arenas_contain_ex(p, NULL);+}++// Is a pointer contained in the given arena area?+bool mi_arena_contains(mi_arena_id_t arena_id, const void* p) {+ mi_arena_t* arena = _mi_arena_from_id(arena_id);+ if (arena==NULL) return false;+ else if (mi_arena_strictly_contains(arena, p)) return true;+ else return mi_arenas_contain_ex(p, arena); // maybe a subarena?+}/* -----------------------------------------------------------@@ -1262,7 +1363,7 @@ static void mi_arenas_unsafe_destroy(mi_subproc_t* subproc) {}// try to lower the max arena.size_t expected = arena_count;- mi_atomic_cas_strong_acq_rel(&subproc->arena_count, &expected, 0);+ mi_atomic_cas_strong_acq_rel(&subproc->arena_count, &expected, (size_t)0);}@@ -1282,7 +1383,7 @@ static bool mi_arenas_add(mi_subproc_t* subproc, mi_arena_t* arena, mi_arena_id_{mi_assert_internal(arena != NULL);mi_assert_internal(arena->slice_count > 0);- if (arena_id != NULL) { *arena_id = NULL; }+ if (arena_id != NULL) { *arena_id = _mi_arena_id_none(); }// try to find a NULL entrymi_arena_t* expected;@@ -1293,7 +1394,7 @@ static bool mi_arenas_add(mi_subproc_t* subproc, mi_arena_t* arena, mi_arena_id_expected = NULL;if (mi_atomic_cas_ptr_strong_release(mi_arena_t, &subproc->arenas[i], &expected, arena)) {// success- if (arena_id != NULL) { *arena_id = arena; }+ if (arena_id != NULL) { *arena_id = mi_arena_id_from_arena(arena); }return true;}}@@ -1306,7 +1407,7 @@ static bool mi_arenas_add(mi_subproc_t* subproc, mi_arena_t* arena, mi_arena_id_expected = NULL;if (mi_atomic_cas_ptr_strong_release(mi_arena_t, &subproc->arenas[count], &expected, arena)) {mi_subproc_stat_counter_increase(arena->subproc, arena_count, 1);- if (arena_id != NULL) { *arena_id = arena; }+ if (arena_id != NULL) { *arena_id = mi_arena_id_from_arena(arena); }return true;}}@@ -1335,7 +1436,12 @@ static size_t mi_arena_info_slices_needed(size_t slice_count, size_t* bitmap_basconst size_t base_size = _mi_align_up(sizeof(mi_arena_t), MI_BCHUNK_SIZE);const size_t bitmaps_count = 4 + MI_ARENA_BIN_COUNT; // commit, dirty, purge, pages, and abandonedconst size_t bitmaps_size = bitmaps_count * mi_bitmap_size(slice_count, NULL) + mi_bbitmap_size(slice_count, NULL); // + free- const size_t size = base_size + bitmaps_size;+ #if MI_PAGE_META_IS_SEPARATED+ const size_t pages_size = slice_count * sizeof(mi_page_t);+ #else+ const size_t pages_size = 0;+ #endif+ const size_t size = base_size + bitmaps_size + pages_size;const size_t os_page_size = _mi_os_page_size();const size_t info_size = _mi_align_up(size, os_page_size) + _mi_os_secure_guard_page_size();@@ -1372,41 +1478,29 @@ static mi_arena_pages_t* mi_arena_pages_alloc(mi_arena_t* arena) {return arena_pages;}--static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t size, int numa_node, bool exclusive,- mi_memid_t memid, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept+static mi_arena_t* mi_arena_initialize(mi_subproc_t* subproc, void* start,+ size_t slice_count, mi_arena_t* parent, size_t total_size,+ int numa_node, bool exclusive,+ mi_memid_t memid, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id){- mi_assert(_mi_is_aligned(start,MI_ARENA_SLICE_SIZE));- mi_assert(start!=NULL);- if (arena_id != NULL) { *arena_id = _mi_arena_id_none(); }- if (start==NULL) return false;- if (!_mi_is_aligned(start,MI_ARENA_SLICE_SIZE)) {- // we can align the start since the memid tracks the real base of the memory.- void* const aligned_start = _mi_align_up_ptr(start, MI_ARENA_SLICE_SIZE);- const size_t diff = (uint8_t*)aligned_start - (uint8_t*)start;- if (diff >= size || (size - diff) < MI_ARENA_SLICE_SIZE) {- _mi_warning_message("after alignment, the size of the arena becomes too small (memory at %p with size %zu)\n", start, size);- return false;- }- start = aligned_start;- size = size - diff;- }+ mi_assert_internal(_mi_is_aligned(start,MI_ARENA_SLICE_ALIGN));+ mi_assert_internal(mi_size_of_slices(slice_count)>=MI_ARENA_MIN_SIZE);- const size_t slice_count = _mi_align_down(size / MI_ARENA_SLICE_SIZE, MI_BCHUNK_BITS);if (slice_count > MI_BITMAP_MAX_BIT_COUNT) { // 16 GiB for now- // todo: allow larger areas (either by splitting it up in arena's or having larger arena's)- _mi_warning_message("cannot use OS memory since it is too large (size %zu MiB, maximum is %zu MiB)", size/MI_MiB, mi_size_of_slices(MI_BITMAP_MAX_BIT_COUNT)/MI_MiB);- return false;+ // note: this should never happen if called from `mi_manage_os_memory` (as that allocates sub-arenas when needed)+ _mi_warning_message("cannot use OS memory since it is too large (size %zu MiB, maximum is %zu MiB)", mi_size_of_slices(slice_count)/MI_MiB, mi_size_of_slices(MI_BITMAP_MAX_BIT_COUNT)/MI_MiB);+ return NULL;}+size_t bitmap_base;const size_t info_slices = mi_arena_info_slices_needed(slice_count, &bitmap_base);if (slice_count < info_slices+1) {- _mi_warning_message("cannot use OS memory since it is not large enough (size %zu KiB, minimum required is %zu KiB)", size/MI_KiB, mi_size_of_slices(info_slices+1)/MI_KiB);- return false;+ _mi_warning_message("cannot use OS memory since it is not large enough (size %zu KiB, minimum required is %zu KiB)", mi_size_of_slices(slice_count)/MI_KiB, mi_size_of_slices(info_slices+1)/MI_KiB);+ return NULL;}else if (info_slices >= MI_ARENA_MAX_CHUNK_OBJ_SLICES) {- _mi_warning_message("cannot use OS memory since it is too large with respect to the maximum object size (size %zu MiB, meta-info slices %zu, maximum object slices are %zu)", size/MI_MiB, info_slices, MI_ARENA_MAX_CHUNK_OBJ_SLICES);- return false;+ _mi_warning_message("cannot use OS memory since it is too large with respect to the maximum object size (size %zu MiB, meta-info slices %zu, maximum object slices are %zu)", mi_size_of_slices(slice_count)/MI_MiB, info_slices, MI_ARENA_MAX_CHUNK_OBJ_SLICES);+ return NULL;}mi_arena_t* arena = (mi_arena_t*)start;@@ -1425,11 +1519,11 @@ static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t s}if (!ok) {_mi_warning_message("unable to commit meta-data for OS memory");- return false;+ return NULL;}}else if (!memid.is_pinned) {- // if MI_SECURE, set a guard page at the end+ // if MI_SECURE, set a guard page at the end of the arena info// todo: this does not respect the commit_fun as the memid is of external memory_mi_os_secure_guard_page_set_before((uint8_t*)arena + mi_size_of_slices(info_slices), memid);}@@ -1438,27 +1532,39 @@ static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t s}// init- arena->subproc = subproc;- arena->memid = memid;+ arena->subproc = subproc;+ arena->memid = memid;arena->is_exclusive = exclusive;- arena->slice_count = slice_count;- arena->info_slices = info_slices;- arena->numa_node = numa_node; // TODO: or get the current numa node if -1? (now it allows anyone to allocate on -1)+ arena->slice_count = slice_count;+ arena->info_slices = info_slices;+ if (numa_node<0 && mi_option_is_enabled(mi_option_arena_is_numa_local)) {+ arena->numa_node = _mi_os_numa_node();+ }+ else {+ arena->numa_node = numa_node;+ }arena->purge_expire = 0;- arena->commit_fun = commit_fun;+ arena->commit_fun = commit_fun;arena->commit_fun_arg = commit_fun_arg;- // mi_lock_init(&arena->abandoned_visit_lock);+ arena->parent = parent;+ arena->total_size = total_size;// init bitmapsuint8_t* base = mi_arena_start(arena) + bitmap_base;- arena->slices_free = mi_arena_bbitmap_init(slice_count,&base);- arena->slices_committed = mi_arena_bitmap_init(slice_count,&base);- arena->slices_dirty = mi_arena_bitmap_init(slice_count,&base);+ arena->slices_free = mi_arena_bbitmap_init(slice_count, &base);+ arena->slices_committed = mi_arena_bitmap_init(slice_count, &base);+ arena->slices_dirty = mi_arena_bitmap_init(slice_count, &base);arena->slices_purge = mi_arena_bitmap_init(slice_count, &base);arena->pages_main.pages = mi_arena_bitmap_init(slice_count, &base);- for( size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {- arena->pages_main.pages_abandoned[i] = mi_arena_bitmap_init(slice_count,&base);+ for (size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {+ arena->pages_main.pages_abandoned[i] = mi_arena_bitmap_init(slice_count, &base);}+ #if MI_PAGE_META_IS_SEPARATED+ arena->pages_meta = (mi_page_t*)base;+ base += (slice_count * sizeof(mi_page_t));+ #else+ arena->pages_meta = NULL;+ #endifmi_assert_internal(mi_size_of_slices(info_slices) >= (size_t)(base - mi_arena_start(arena)));// reserve our meta info (and reserve slices outside the memory area)@@ -1466,19 +1572,83 @@ static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t sif (memid.initially_committed) {mi_bitmap_unsafe_setN(arena->slices_committed, 0, arena->slice_count);}- else {- mi_bitmap_setN(arena->slices_committed, 0, info_slices, NULL);- }if (!memid.initially_zero) {mi_bitmap_unsafe_setN(arena->slices_dirty, 0, arena->slice_count);}- else {- mi_bitmap_setN(arena->slices_dirty, 0, info_slices, NULL);- }- return mi_arenas_add(subproc, arena, arena_id);+ if (!mi_arenas_add(subproc, arena, arena_id)) { return NULL; }+ return arena;}+static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t size, int numa_node, bool exclusive,+ mi_memid_t memid, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept+{+ // checks+ mi_assert(_mi_is_aligned(start, MI_ARENA_SLICE_SIZE));+ mi_assert(start!=NULL);+ if (arena_id != NULL) { *arena_id = _mi_arena_id_none(); }+ if (start==NULL) return false;+ if (!_mi_is_aligned(start, MI_ARENA_SLICE_SIZE)) {+ // we can align the start since the memid tracks the real base of the memory.+ void* const aligned_start = _mi_align_up_ptr(start, MI_ARENA_SLICE_SIZE);+ const size_t diff = (uint8_t*)aligned_start - (uint8_t*)start;+ if (diff >= size || (size - diff) < MI_ARENA_SLICE_SIZE) {+ _mi_warning_message("after alignment, the size of the arena becomes too small (memory at %p with size %zu)\n", start, size);+ return false;+ }+ start = aligned_start;+ size = size - diff;+ }++ // allocate enough arena's to span the full memory area+ // the first arena is the owner, the rest are "sub-arena" (with `parent` pointing to the first one)+ size_t total_slice_count = _mi_align_down(size / MI_ARENA_SLICE_SIZE, MI_BCHUNK_BITS);+ size_t total_size = mi_size_of_slices(total_slice_count);+ if (total_size < MI_ARENA_MIN_SIZE) {+ _mi_warning_message("cannot use OS memory since it is not large enough (size %zu KiB, minimum required is %zu KiB)", size/MI_KiB, MI_ARENA_MIN_SIZE/MI_KiB);+ return false;+ }++ mi_arena_t* parent = NULL;+ do {+ // counting down on the total_slice_count+ size_t slice_count = total_slice_count;+ if (slice_count > MI_BITMAP_MAX_BIT_COUNT) { // 16 GiB for now (with 64KiB slices)+ slice_count = MI_BITMAP_MAX_BIT_COUNT;+ }++ // initialize+ mi_arena_t* arena = mi_arena_initialize( subproc, start, slice_count, parent,+ (parent==NULL ? total_size : 0), numa_node, exclusive,+ memid, commit_fun, commit_fun_arg,+ (parent==NULL ? arena_id : NULL));+ if (arena==NULL) {+ // failed to initialize due to failing commit or too many arena's+ if (parent==NULL) {+ return false;+ }+ else {+ // partial success, but failed to use the full area..+ // todo: roll-back in this case? that requires a lock on the arena's array though+ mi_assert(mi_size_of_slices(total_slice_count) <= parent->total_size);+ parent->total_size -= mi_size_of_slices(total_slice_count);+ return true;+ }+ }++ // success+ if (parent==NULL) {+ parent = arena;+ memid.memkind = MI_MEM_NONE;+ }+ mi_assert(slice_count <= total_slice_count);+ total_slice_count -= slice_count;+ start = (uint8_t*)start + mi_size_of_slices(slice_count);+ }+ while (total_slice_count > 0);++ return true;+}bool mi_manage_os_memory_ex(void* start, size_t size, bool is_committed, bool is_pinned, bool is_zero, int numa_node, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept {mi_memid_t memid = _mi_memid_create(MI_MEM_EXTERNAL);@@ -1490,7 +1660,7 @@ bool mi_manage_os_memory_ex(void* start, size_t size, bool is_committed, bool isreturn mi_manage_os_memory_ex2(_mi_subproc(), start, size, numa_node, exclusive, memid, NULL, NULL, arena_id);}-bool mi_manage_memory(void* start, size_t size, bool is_committed, bool is_zero, bool is_pinned, int numa_node, bool exclusive, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept+bool mi_manage_memory(void* start, size_t size, bool is_committed, bool is_pinned, bool is_zero, int numa_node, bool exclusive, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept{mi_memid_t memid = _mi_memid_create(MI_MEM_EXTERNAL);memid.mem.os.base = start;@@ -1543,7 +1713,7 @@ int mi_reserve_os_memory(size_t size, bool commit, bool allow_large) mi_attr_noe// Return idx of the slice past the last used slicestatic size_t mi_arena_used_slices(mi_arena_t* arena) {size_t idx;- if (mi_bitmap_bsr(arena->slices_dirty, &idx)) {+ if (mi_bbitmap_bsr_inv(arena->slices_free, &idx)) {return (idx + 1);}else {@@ -1602,7 +1772,7 @@ static size_t mi_debug_show_page_bfield(char* buf, size_t* k, mi_arena_t* arena,void* start = mi_arena_slice_start(arena, slice_index + bit);mi_page_t* page = _mi_safe_ptr_page(start);char c = ' ';- if (start==page) {+ if (page!=NULL && start==mi_page_slice_start(page)) {mi_assert_internal(bit_of_page <= 0);bit_set_count++;c = 'p';@@ -1625,7 +1795,7 @@ static size_t mi_debug_show_page_bfield(char* buf, size_t* k, mi_arena_t* arena,// else if (mi_bitmap_is_setN(arena->pages_purge, slice_index + bit, NULL)) { c = '*'; }else if (mi_bbitmap_is_setN(arena->slices_free, slice_index+bit,1)) {if (mi_bitmap_is_set(arena->slices_purge, slice_index + bit)) { c = '~'; color = MI_ORANGE; }- else if (mi_bitmap_is_setN(arena->slices_committed, slice_index + bit, 1)) { c = '_'; color = MI_GRAY; }+ else if (mi_bitmap_is_set(arena->slices_committed, slice_index + bit)) { c = '_'; color = MI_GRAY; }else { c = '.'; color = MI_GRAY; }}if (bit==MI_BFIELD_BITS-1 && bit_of_page > 1) { c = '>'; }@@ -1731,7 +1901,10 @@ static void mi_debug_show_arenas_ex(mi_heap_t* heap, bool show_pages, bool narroif (arena == NULL) break;mi_assert(arena->subproc == subproc);// slice_total += arena->slice_count;- _mi_raw_message("arena %zu at %p: %zu slices (%zu MiB)%s, subproc: %p\n", i, arena, arena->slice_count, (size_t)(mi_size_of_slices(arena->slice_count)/MI_MiB), (arena->memid.is_pinned ? ", pinned" : ""), arena->subproc);+ _mi_raw_message("%sarena %zu at %p: %zu slices (%zu MiB)%s%s, subproc: %p, numa: %i\n",+ (arena->parent==NULL ? "" : "(sub)"), i, arena, arena->slice_count, (size_t)(mi_size_of_slices(arena->slice_count)/MI_MiB),+ (arena->memid.is_pinned ? ", pinned" : ""), (arena->is_exclusive ? ", exclusive" : ""),+ arena->subproc, arena->numa_node);//if (show_inuse) {// free_total += mi_debug_show_bbitmap("in-use slices", arena->slice_count, arena->slices_free, true, NULL);//}@@ -1953,15 +2126,21 @@ static bool mi_arena_try_purge_visitor(size_t slice_index, size_t slice_count, mreturn true; // continue}-// returns true if anything was purged-static bool mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force)+// returns+// -1 = nothing was purged+// 0 = nothing was purged yet because have not yet reached the expire time+// 1 = some pages in the arena were purged+static int mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force){// check pre-conditions- if (arena->memid.is_pinned) return false;+ if (arena->memid.is_pinned) return -1;// expired yet?mi_msecs_t expire = mi_atomic_loadi64_relaxed(&arena->purge_expire);- if (!force && (expire == 0 || expire > now)) return false;+ if (!force) {+ if (expire==0) return -1;+ if (expire > now) return 0;+ }// reset expiremi_atomic_storei64_release(&arena->purge_expire, (mi_msecs_t)0);@@ -1976,7 +2155,7 @@ static bool mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force)const size_t minslices = mi_slice_count_of_size(_mi_os_minimal_purge_size());_mi_bitmap_forall_setc_rangesn(arena->slices_purge, minslices, &mi_arena_try_purge_visitor, arena, &vinfo);- return vinfo.any_purged;+ return (vinfo.any_purged ? 1 : -1);}@@ -2009,18 +2188,21 @@ static void mi_arenas_try_purge(bool force, bool visit_all, mi_subproc_t* subproif (i >= max_arena) { i -= max_arena; }mi_arena_t* arena = mi_arena_from_index(subproc,i);if (arena != NULL) {- if (mi_arena_try_purge(arena, now, force)) {+ const int purged = mi_arena_try_purge(arena, now, force);+ if (purged >= 0) { // purged, or arena expire is not yet reachedany_purged = true;- if (max_purge_count <= 1) {- all_visited = false;- break;+ if (purged >= 1) { // purged+ if (max_purge_count <= 1) {+ all_visited = false;+ break;+ }+ max_purge_count--;}- max_purge_count--;}}}if (all_visited && !any_purged) {- mi_atomic_storei64_release(&subproc->purge_expire, 0);+ mi_atomic_storei64_release(&subproc->purge_expire, (mi_msecs_t)0);}}}@@ -2055,7 +2237,7 @@ static bool mi_heap_visit_page(mi_page_t* page, mi_heap_visit_info_t* vinfo) {static bool mi_heap_visit_page_at(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {MI_UNUSED(slice_count);mi_heap_visit_info_t* vinfo = (mi_heap_visit_info_t*)arg;- mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_page_t* page = mi_arena_page_at_slice(arena, slice_index);return mi_heap_visit_page(page, vinfo);}@@ -2121,7 +2303,7 @@ static bool mi_heap_delete_page(const mi_heap_t* heap, const mi_heap_area_t* areMI_UNUSED(block); MI_UNUSED(block_size); MI_UNUSED(heap);mi_heap_delete_visit_info_t* info = (mi_heap_delete_visit_info_t*)arg;mi_heap_t* heap_target = info->heap_target;- mi_theap_t* const theap = info->theap; mi_assert_internal(theap->heap == heap);+ mi_theap_t* const theap = NULL; // info->theap; mi_assert_internal(_mi_theap_heap(theap) == heap);mi_page_t* const page = (mi_page_t*)area->reserved1;mi_page_claim_ownership(page); // claim ownership@@ -2154,8 +2336,14 @@ static bool mi_heap_delete_page(const mi_heap_t* heap, const mi_heap_area_t* aremi_arena_t* const arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages);mi_assert_internal(mi_bitmap_is_set(arena_pages->pages, slice_index));mi_bitmap_clear(arena_pages->pages, slice_index);- mi_theap_stat_decrease(theap, page_bins[sbin], 1);- mi_theap_stat_decrease(theap, pages, 1);+ if (theap != NULL) {+ mi_theap_stat_decrease(theap, page_bins[sbin], 1);+ mi_theap_stat_decrease(theap, pages, 1);+ }+ else {+ mi_heap_stat_decrease((mi_heap_t*)heap, page_bins[_mi_page_stats_bin(page)], 1);+ mi_heap_stat_decrease((mi_heap_t*)heap, pages, 1);+ }mi_theap_t* theap_target = info->theap_target;// and then add it to the new target heap@@ -2181,13 +2369,13 @@ static bool mi_heap_delete_page(const mi_heap_t* heap, const mi_heap_area_t* arestatic void mi_heap_delete_pages(mi_heap_t* heap, mi_heap_t* heap_target) {mi_theap_t* const theap_target = (heap_target != NULL ? _mi_heap_theap(heap_target) : NULL);- mi_theap_t* const theap = _mi_heap_theap(heap);- mi_heap_delete_visit_info_t info = { heap_target, theap_target, theap };+ // mi_theap_t* const theap = _mi_heap_theap(heap);+ mi_heap_delete_visit_info_t info = { heap_target, theap_target, NULL };_mi_heap_visit_blocks(heap, false, false, &mi_heap_delete_page, &info);#if MI_DEBUG>1// no more arena pages?for (size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {- mi_arena_pages_t* const arena_pages = mi_atomic_load_relaxed(&heap->arena_pages[i]);+ mi_arena_pages_t* const arena_pages = mi_atomic_load_ptr_relaxed(mi_arena_pages_t, &heap->arena_pages[i]);if (arena_pages!=NULL) {mi_assert_internal(mi_bitmap_is_all_clear(arena_pages->pages));}@@ -2222,7 +2410,7 @@ void _mi_heap_destroy_pages(mi_heap_t* heap_from) {static bool mi_arena_page_register(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {MI_UNUSED(arg); MI_UNUSED(slice_count);mi_assert_internal(slice_count == 1);- mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_page_t* page = mi_arena_page_at_slice(arena, slice_index);mi_assert_internal(mi_bitmap_is_setN(page->memid.mem.arena.arena->pages, page->memid.mem.arena.slice_index, 1));if (!_mi_page_map_register(page)) return false; // breakmi_assert_internal(_mi_ptr_page(page)==page);diff --git a/vendored/mimalloc/src/bitmap.c b/vendored/mimalloc/src/bitmap.cindex aa4d23619..67269e8bf 100644--- a/vendored/mimalloc/src/bitmap.c+++ b/vendored/mimalloc/src/bitmap.c@@ -12,6 +12,7 @@ Concurrent bitmap that can set/reset sequences of bits atomically#include "mimalloc.h"#include "mimalloc/internal.h"#include "mimalloc/bits.h"+#include "mimalloc/prim.h" // _mi_prim_thread_yield#include "bitmap.h"#ifndef MI_OPT_SIMD@@ -119,7 +120,7 @@ static inline void mi_bfield_atomic_clear_once_set(_Atomic(mi_bfield_t)*b, size_mi_subproc_stat_counter_increase(_mi_subproc(), pages_unabandon_busy_wait, 1);}while ((old&mask)==0) { // busy wait- mi_atomic_yield();+ _mi_prim_thread_yield();old = mi_atomic_load_acquire(b);}}@@ -220,13 +221,13 @@ static inline bool mi_bfield_atomic_try_clearX(_Atomic(mi_bfield_t)*b, bool* all// Check if a bit is setstatic inline bool mi_bfield_atomic_is_set(const _Atomic(mi_bfield_t)*b, const size_t idx) {- const mi_bfield_t x = mi_atomic_load_relaxed(b);+ const mi_bfield_t x = mi_atomic_load_acquire(b);return ((x & mi_bfield_mask(1,idx)) != 0);}// Check if a bit is clearstatic inline bool mi_bfield_atomic_is_clear(const _Atomic(mi_bfield_t)*b, const size_t idx) {- const mi_bfield_t x = mi_atomic_load_relaxed(b);+ const mi_bfield_t x = mi_atomic_load_acquire(b);return ((x & mi_bfield_mask(1, idx)) == 0);}@@ -239,14 +240,14 @@ static inline bool mi_bfield_atomic_is_xset(mi_xset_t set, const _Atomic(mi_bfie// Check if all bits corresponding to a mask are set.static inline bool mi_bfield_atomic_is_set_mask(const _Atomic(mi_bfield_t)* b, mi_bfield_t mask) {mi_assert_internal(mask != 0);- const mi_bfield_t x = mi_atomic_load_relaxed(b);+ const mi_bfield_t x = mi_atomic_load_acquire(b);return ((x & mask) == mask);}// Check if all bits corresponding to a mask are clear.static inline bool mi_bfield_atomic_is_clear_mask(const _Atomic(mi_bfield_t)* b, mi_bfield_t mask) {mi_assert_internal(mask != 0);- const mi_bfield_t x = mi_atomic_load_relaxed(b);+ const mi_bfield_t x = mi_atomic_load_acquire(b);return ((x & mask) == 0);}@@ -259,7 +260,7 @@ static inline bool mi_bfield_atomic_is_xset_mask(mi_xset_t set, const _Atomic(mi// Count bits in a maskstatic inline size_t mi_bfield_atomic_popcount_mask(_Atomic(mi_bfield_t)*b, mi_bfield_t mask) {- const mi_bfield_t x = mi_atomic_load_relaxed(b);+ const mi_bfield_t x = mi_atomic_load_acquire(b);return mi_bfield_popcount(x & mask);}@@ -962,6 +963,19 @@ static bool mi_bchunk_bsr(mi_bchunk_t* chunk, size_t* pidx) {return false;}+static bool mi_bchunk_bsr_inv(mi_bchunk_t* chunk, size_t* pidx) {+ for (size_t i = MI_BCHUNK_FIELDS; i > 0; ) {+ i--;+ mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[i]);+ size_t idx;+ if (mi_bsr(~b, &idx)) {+ *pidx = (i*MI_BFIELD_BITS) + idx;+ return true;+ }+ }+ return false;+}+static size_t mi_bchunk_popcount(mi_bchunk_t* chunk) {size_t popcount = 0;for (size_t i = 0; i < MI_BCHUNK_FIELDS; i++) {@@ -1059,7 +1073,6 @@ static void mi_bchunks_unsafe_setN(mi_bchunk_t* chunks, mi_bchunkmap_t* cmap, si// last chunkif (n > 0) {mi_assert_internal(n < MI_BCHUNK_BITS);- mi_assert_internal(chunk_idx < MI_BCHUNK_FIELDS);mi_bchunk_setN(&chunks[chunk_idx], 0, n, NULL);}}@@ -1428,22 +1441,28 @@ bool _mi_bitmap_forall_setc_ranges(mi_bitmap_t* bitmap, mi_forall_set_fun_t* vismi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);- mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], 0);-#if MI_DEBUG > 1+ mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], (mi_bfield_t)0);+ #if MI_DEBUG > 1const size_t bpopcount = mi_popcount(b);size_t rngcount = 0;-#endif+ #endifsize_t bidx;while (mi_bfield_find_least_bit(b, &bidx)) {size_t rng = mi_ctz(~(b>>bidx)); // all the set bits from bidx-#if MI_DEBUG > 1+ #if MI_DEBUG > 1rngcount += rng;-#endif+ #endifconst size_t idx = base_idx + bidx;mi_assert_internal(rng>=1 && rng<=MI_BFIELD_BITS);mi_assert_internal((idx % MI_BFIELD_BITS) + rng <= MI_BFIELD_BITS);mi_assert_internal((idx / MI_BCHUNK_BITS) < mi_bitmap_chunk_count(bitmap));- if (!visit(idx, rng, arena, arg)) return false;+ if (!visit(idx, rng, arena, arg)) {+ // break early: reset the non-visited bits+ if (b!=0) {+ mi_atomic_or_relaxed(&chunk->bfields[j], b);+ }+ return false;+ }// clear rng bits in bb = b & ~mi_bfield_mask(rng, bidx);}@@ -1481,18 +1500,23 @@ bool _mi_bitmap_forall_setc_rangesn(mi_bitmap_t* bitmap, size_t rngslices, mi_fomi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);- mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], 0); // atomic clear+ mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], (mi_bfield_t)0); // atomic clearmi_bfield_t skipped = 0; // but track which bits we skip so we can restore themfor(size_t shift = 0; rngslices + shift <= MI_BFIELD_BITS; shift += rngslices) { // per `rngslices` to keep alignmentconst mi_bfield_t rngmask = mi_bfield_mask(rngslices, shift);if ((b & rngmask) == rngmask) {const size_t idx = base_idx + shift;if (!visit(idx, rngslices, arena, arg)) {- // break early- if (skipped != 0) {- mi_atomic_or_relaxed(&chunk->bfields[j], skipped);- return false;+ // break early: restore non-visited entries+ mi_bfield_t notyet_visited = 0;+ if (shift + rngslices < MI_BFIELD_BITS) {+ notyet_visited = (b & (~(mi_bfield_t)0 << (shift + rngslices)));}+ mi_assert_internal((notyet_visited & skipped) == 0);+ if ((notyet_visited | skipped) != 0) {+ mi_atomic_or_relaxed(&chunk->bfields[j], notyet_visited | skipped);+ }+ return false;}}else {@@ -1547,6 +1571,32 @@ void mi_bbitmap_unsafe_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {mi_bchunks_unsafe_setN(&bbitmap->chunks[0], &bbitmap->chunkmap, idx, n);}+bool mi_bbitmap_bsr_inv(mi_bbitmap_t* bbitmap, size_t* idx) {+ const size_t chunk_count = mi_bbitmap_chunk_count(bbitmap);+ const size_t chunkmap_max = _mi_divide_up(chunk_count, MI_BFIELD_BITS);+ size_t skip_at_top = chunk_count % MI_BFIELD_BITS;+ for (size_t i = chunkmap_max; i > 0; ) {+ i--;+ mi_bfield_t cmap = mi_atomic_load_relaxed(&bbitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ // don't consider top 0 bits; set those to 1 here+ if (skip_at_top > 0) {+ const size_t mask_top = (~mi_bfield_zero()) << (MI_BFIELD_BITS - skip_at_top);+ skip_at_top = 0; // only for the first iteration+ cmap |= mask_top;+ }+ if (mi_bsr(~cmap, &cmap_idx)) {+ // highest chunk+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ size_t cidx;+ if (mi_bchunk_bsr_inv(&bbitmap->chunks[chunk_idx], &cidx)) {+ *idx = (chunk_idx * MI_BCHUNK_BITS) + cidx;+ return true;+ }+ }+ }+ return false;+}/* --------------------------------------------------------------------------------diff --git a/vendored/mimalloc/src/bitmap.h b/vendored/mimalloc/src/bitmap.hindex 6e9d2f1d8..ca51a4e04 100644--- a/vendored/mimalloc/src/bitmap.h+++ b/vendored/mimalloc/src/bitmap.h@@ -281,6 +281,10 @@ mi_chunkbin_t mi_bbitmap_debug_get_bin(const mi_bchunk_t* chunkmap_bins, size_tsize_t mi_bbitmap_size(size_t bit_count, size_t* chunk_count);+// If a bit is clear in the bitmap, return `true` and set `idx` to the index of the highest bit that was clear.+// Otherwise return `false` (and `*idx` is undefined).+// Used for debug output.+bool mi_bbitmap_bsr_inv(mi_bbitmap_t* bbitmap, size_t* idx);// Initialize a bitmap to all clear; avoid a mem_zero if `already_zero` is true// returns the size of the bitmap.@@ -319,13 +323,13 @@ bool mi_bbitmap_try_clearNC(mi_bbitmap_t* bbitmap, size_t idx, size_t n);bool mi_bbitmap_try_find_and_clear(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // 1-bitbool mi_bbitmap_try_find_and_clear8(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // 8-bits// bool mi_bbitmap_try_find_and_clearX(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // MI_BFIELD_BITS-bool mi_bbitmap_try_find_and_clearNX(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // < MI_BFIELD_BITS-bool mi_bbitmap_try_find_and_clearNC(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // > MI_BFIELD_BITS <= MI_BCHUNK_BITS-bool mi_bbitmap_try_find_and_clearN_(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // > MI_BCHUNK_BITS+bool mi_bbitmap_try_find_and_clearNX(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx); // < MI_BFIELD_BITS+bool mi_bbitmap_try_find_and_clearNC(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx); // > MI_BFIELD_BITS <= MI_BCHUNK_BITS+bool mi_bbitmap_try_find_and_clearN_(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx); // > MI_BCHUNK_BITS// Find a sequence of `n` bits in the bbitmap with all bits set, and try to atomically clear all.// Returns true on success, and in that case sets the index: `0 <= *pidx <= MI_BITMAP_MAX_BITS-n`.-mi_decl_nodiscard static inline bool mi_bbitmap_try_find_and_clearN(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx) {+mi_decl_nodiscard static inline bool mi_bbitmap_try_find_and_clearN(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx) {if (n==1) return mi_bbitmap_try_find_and_clear(bbitmap, tseq, pidx); // small pagesif (n==8) return mi_bbitmap_try_find_and_clear8(bbitmap, tseq, pidx); // medium pages// if (n==MI_BFIELD_BITS) return mi_bbitmap_try_find_and_clearX(bbitmap, tseq, pidx); // large pagesdiff --git a/vendored/mimalloc/src/free.c b/vendored/mimalloc/src/free.cindex 9be8f26c3..6f33340d0 100644--- a/vendored/mimalloc/src/free.c+++ b/vendored/mimalloc/src/free.c@@ -15,7 +15,7 @@ terms of the MIT license. A copy of the license can be found in the file// forward declarationsstatic void mi_check_padding(const mi_page_t* page, const mi_block_t* block);static bool mi_check_is_double_free(const mi_page_t* page, const mi_block_t* block);-static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block);+static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool was_guarded);static void mi_stat_free(const mi_page_t* page, const mi_block_t* block);@@ -25,16 +25,17 @@ static void mi_stat_free(const mi_page_t* page, const mi_block_t* block);// regular free of a (thread local) block pointer// fast path written carefully to prevent spilling on the stack-static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, bool track_stats, bool check_full)+static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, bool was_guarded, bool track_stats, bool check_full){- // checks+ MI_UNUSED(was_guarded);+ // checksif mi_unlikely(mi_check_is_double_free(page, block)) return;- mi_check_padding(page, block);+ if (!was_guarded) { mi_check_padding(page, block); }if (track_stats) { mi_stat_free(page, block); }- #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN && !MI_GUARDED+ #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSANmemset(block, MI_DEBUG_FREED, mi_page_block_size(page));#endif- if (track_stats) { mi_track_free_size(block, mi_page_usable_size_of(page, block)); } // faster then mi_usable_size as we already know the page and that p is unaligned+ if (track_stats) { mi_track_free_size(block, mi_page_usable_size_of(page, block, was_guarded)); } // faster then mi_usable_size as we already know the page and that p is unaligned// actual free: push on the local free listmi_block_set_next(page, block, page->local_free);@@ -53,17 +54,20 @@ static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, boolstatic void mi_decl_noinline mi_free_try_collect_mt(mi_page_t* page, mi_block_t* mt_free) mi_attr_noexcept;// Free a block multi-threaded-static inline void mi_free_block_mt(mi_page_t* page, mi_block_t* block) mi_attr_noexcept+static inline void mi_free_block_mt(mi_page_t* page, mi_block_t* block, bool was_guarded) mi_attr_noexcept{+ MI_UNUSED(was_guarded);// adjust stats (after padding check and potentially recursive `mi_free` above)mi_stat_free(page, block); // stat_free may access the padding- mi_track_free_size(block, mi_page_usable_size_of(page, block));+ mi_track_free_size(block, mi_page_usable_size_of(page, block, was_guarded));// _mi_padding_shrink(page, block, sizeof(mi_block_t));#if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN // note: when tracking, cannot use mi_usable_size with multi-threading- size_t dbgsize = mi_usable_size(block);- if (dbgsize > MI_MiB) { dbgsize = MI_MiB; }- _mi_memset_aligned(block, MI_DEBUG_FREED, dbgsize);+ if (!was_guarded) {+ size_t dbgsize = mi_usable_size(block);+ if (dbgsize > MI_MiB) { dbgsize = MI_MiB; }+ _mi_memset_aligned(block, MI_DEBUG_FREED, dbgsize);+ }#endif// push atomically on the page thread free list@@ -99,12 +103,19 @@ mi_block_t* _mi_page_ptr_unalign(const mi_page_t* page, const void* p) {// forward declaration for a MI_GUARDED build#if MI_GUARDEDstatic void mi_block_unguard(mi_page_t* page, mi_block_t* block, void* p); // forward declaration-static inline void mi_block_check_unguard(mi_page_t* page, mi_block_t* block, void* p) {- if (mi_block_ptr_is_guarded(block, p)) { mi_block_unguard(page, block, p); }+static inline bool mi_block_check_unguard(mi_page_t* page, mi_block_t* block, void* p) {+ if (mi_block_ptr_is_guarded(block, p)) {+ mi_block_unguard(page, block, p);+ return true;+ }+ else {+ return false;+ }}#else-static inline void mi_block_check_unguard(mi_page_t* page, mi_block_t* block, void* p) {+static inline bool mi_block_check_unguard(mi_page_t* page, mi_block_t* block, void* p) {MI_UNUSED(page); MI_UNUSED(block); MI_UNUSED(p);+ return false;}#endif@@ -124,16 +135,16 @@ static inline mi_block_t* mi_validate_block_from_ptr( const mi_page_t* page, voistatic void mi_decl_noinline mi_free_generic_local(mi_page_t* page, void* p) mi_attr_noexcept {mi_assert_internal(p!=NULL && page != NULL);mi_block_t* const block = (mi_page_has_interior_pointers(page) ? _mi_page_ptr_unalign(page, p) : mi_validate_block_from_ptr(page,p));- mi_block_check_unguard(page, block, p);- mi_free_block_local(page, block, true /* track stats */, true /* check for a full page */);+ const bool was_guarded = mi_block_check_unguard(page, block, p);+ mi_free_block_local(page, block, was_guarded, true /* track stats */, true /* check for a full page */);}// free a pointer owned by another thread (page parameter comes first for better codegen)static void mi_decl_noinline mi_free_generic_mt(mi_page_t* page, void* p) mi_attr_noexcept {mi_assert_internal(p!=NULL && page != NULL);mi_block_t* const block = (mi_page_has_interior_pointers(page) ? _mi_page_ptr_unalign(page, p) : mi_validate_block_from_ptr(page,p));- mi_block_check_unguard(page, block, p);- mi_free_block_mt(page, block);+ const bool was_guarded = mi_block_check_unguard(page, block, p);+ mi_free_block_mt(page, block, was_guarded);}// generic free (for runtime integration)@@ -165,9 +176,8 @@ static inline mi_page_t* mi_validate_ptr_page(const void* p, const char* msg)// Free a block// Fast path written carefully to prevent register spilling on the stack-static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable)+static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable, mi_page_t* page){- mi_page_t* const page = mi_validate_ptr_page(p,"mi_free");if mi_unlikely(page==NULL) return; // page will be NULL if p==NULLmi_assert_internal(p!=NULL && page!=NULL);if (usable!=NULL) { *usable = mi_page_usable_block_size(page); }@@ -176,7 +186,7 @@ static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable)if mi_likely(xtid == 0) { // `tid == mi_page_thread_id(page) && mi_page_flags(page) == 0`// thread-local, aligned, and not a full pagemi_block_t* const block = mi_validate_block_from_ptr(page,p);- mi_free_block_local(page, block, true /* track stats */, false /* no need to check if the page is full */);+ mi_free_block_local(page, block, false /* was guarded */, true /* track stats */, false /* no need to check if the page is full */);}else if (xtid <= MI_PAGE_FLAG_MASK) { // `tid == mi_page_thread_id(page) && mi_page_flags(page) != 0`// page is local, but is full or contains (inner) aligned blocks; use generic path@@ -186,7 +196,7 @@ static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable)else if ((xtid & MI_PAGE_FLAG_MASK) == 0) { // `tid != mi_page_thread_id(page) && mi_page_flags(page) == 0`// blocks are aligned (and not a full page); push on the thread_free listmi_block_t* const block = mi_validate_block_from_ptr(page,p);- mi_free_block_mt(page,block);+ mi_free_block_mt(page,block,false /* was_guarded */);}else {// page is full or contains (inner) aligned blocks; use generic multi-thread path@@ -195,13 +205,39 @@ static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable)}void mi_free(void* p) mi_attr_noexcept {- mi_free_ex(p, NULL);+ mi_page_t* const page = mi_validate_ptr_page(p,"mi_free");+ mi_free_ex(p, NULL, page);}void mi_ufree(void* p, size_t* usable) mi_attr_noexcept {- mi_free_ex(p, usable);+ mi_page_t* const page = mi_validate_ptr_page(p,"mi_ufree");+ mi_free_ex(p, usable, page);+}++void mi_free_small(void* p) mi_attr_noexcept {+ // We can only call `mi_free_small` for pointers allocated with `mi_(heap_)malloc_small`.+ // If we keep page info in front of the page area for small objects, we can find the info+ // just by aligning down the pointer instead of looking it up in the page map.+ #if MI_PAGE_META_ALIGNED_FREE_SMALL+ #if MI_GUARDED+ #warning "MI_PAGE_META_ALIGNED_FREE_SMALL ignored as MI_GUARDED is defined"+ mi_free(p);+ #elif MI_ARENA_SLICE_ALIGN < MI_SMALL_PAGE_SIZE+ #warning "MI_PAGE_META_ALIGNED_FREE_SMALL ignored as the MI_ARENA_SLICE_ALIGN is less than the small page size"+ mi_free(p);+ #else+ mi_page_t* const page = (mi_page_t*)_mi_align_down_ptr(p,MI_SMALL_PAGE_SIZE);+ mi_assert(page == mi_validate_ptr_page(p,"mi_free_small"));+ mi_assert((void*)page == _mi_align_down_ptr(page->page_start,MI_SMALL_PAGE_SIZE));+ mi_assert(page->block_size <= MI_SMALL_SIZE_MAX); // note: not `MI_SMALL_MAX_OBJ_SIZE` as we need to match `mi_(heap_)malloc_small`+ mi_free_ex(p, NULL, page);+ #endif+ #else+ mi_free(p);+ #endif}+// --------------------------------------------------------------------------------------------// `mi_free_try_collect_mt`: Potentially collect a page in a free in an abandoned page.// 1. if the page becomes empty, free it@@ -231,7 +267,7 @@ static bool mi_abandoned_page_try_reabandon_to_mapped(mi_page_t* page)return _mi_arenas_page_try_reabandon_to_mapped(page);}-// Release ownership of a page. This may free or reabandond the page if other blocks are concurrently+// Release ownership of a page. This may free or reabandoned the page if other blocks are concurrently// freed in the meantime. Returns `true` if the page was freed.// By passing the captured `expected_thread_free`, we can often avoid calling `mi_page_free_collect`.static void mi_abandoned_page_unown_from_free(mi_page_t* page, mi_block_t* expected_thread_free) {@@ -277,7 +313,7 @@ static mi_decl_noinline bool mi_abandoned_page_try_reclaim(mi_page_t* page, longmi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));mi_assert_internal(!mi_page_all_free(page));- mi_assert_internal(page->block_size <= MI_SMALL_SIZE_MAX);+ mi_assert_internal(page->block_size <= MI_MEDIUM_MAX_OBJ_SIZE);mi_assert_internal(reclaim_on_free >= 0);// dont reclaim if we just have terminated this thread and we should@@ -298,7 +334,7 @@ static mi_decl_noinline bool mi_abandoned_page_try_reclaim(mi_page_t* page, longelse if (reclaim_on_free == 1 && // if cross-thread is allowed!theap->tld->is_in_threadpool && // and we are not part of a threadpool!mi_page_is_mostly_used(page) && // and the page is not too full- _mi_arena_memid_is_suitable(page->memid, theap->heap->exclusive_arena)) { // and it fits our memory+ _mi_arena_memid_is_suitable(page->memid, _mi_theap_heap(theap)->exclusive_arena)) { // and it fits our memory// across threadsmax_reclaim = _mi_option_get_fast(mi_option_page_cross_thread_max_reclaim);}@@ -344,7 +380,7 @@ static void mi_decl_noinline mi_free_try_collect_mt(mi_page_t* page, mi_block_t*// try to: 1. free it, 2. reclaim it, or 3. reabandon it to be mappedif (mi_abandoned_page_try_free(page)) return;- if (page->block_size <= MI_SMALL_SIZE_MAX && reclaim_on_free >= 0) { // early test for better codegen+ if (page->block_size <= MI_MEDIUM_MAX_OBJ_SIZE && reclaim_on_free >= 0) { // early test for better codegenif (mi_abandoned_page_try_reclaim(page, reclaim_on_free)) return;}if (mi_abandoned_page_try_reabandon_to_mapped(page)) return;@@ -361,15 +397,11 @@ static void mi_decl_noinline mi_free_try_collect_mt(mi_page_t* page, mi_block_t*// Bytes available in a blockstatic size_t mi_decl_noinline mi_page_usable_aligned_size_of(const mi_page_t* page, const void* p) mi_attr_noexcept {const mi_block_t* block = _mi_page_ptr_unalign(page, p);- const size_t size = mi_page_usable_size_of(page, block);+ const bool is_guarded = mi_block_ptr_is_guarded(block,p);+ const size_t size = mi_page_usable_size_of(page, block, is_guarded);const ptrdiff_t adjust = (uint8_t*)p - (uint8_t*)block;mi_assert_internal(adjust >= 0 && (size_t)adjust <= size);- const size_t aligned_size = (size - adjust);- #if MI_GUARDED- if (mi_block_ptr_is_guarded(block, p)) {- return aligned_size - _mi_os_page_size();- }- #endif+ const size_t aligned_size = (size - adjust);return aligned_size;}@@ -377,7 +409,7 @@ static inline size_t _mi_usable_size(const void* p, const mi_page_t* page) mi_atif mi_unlikely(page==NULL) return 0;if mi_likely(!mi_page_has_interior_pointers(page)) {const mi_block_t* block = (const mi_block_t*)p;- return mi_page_usable_size_of(page, block);+ return mi_page_usable_size_of(page, block, false /* is guarded */);}else {// split out to separate routine for improved code generation@@ -489,12 +521,18 @@ static bool mi_page_decode_padding(const mi_page_t* page, const mi_block_t* bloc}// Return the exact usable size of a block.-static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block) {- size_t bsize;- size_t delta;- bool ok = mi_page_decode_padding(page, block, &delta, &bsize);- mi_assert_internal(ok); mi_assert_internal(delta <= bsize);- return (ok ? bsize - delta : 0);+static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool is_guarded) {+ if (is_guarded) {+ const size_t bsize = mi_page_block_size(page);+ return (bsize - _mi_os_page_size());+ }+ else {+ size_t bsize;+ size_t delta;+ bool ok = mi_page_decode_padding(page, block, &delta, &bsize);+ mi_assert_internal(ok); mi_assert_internal(delta <= bsize);+ return (ok ? bsize - delta : 0);+ }}// When a non-thread-local block is freed, it becomes part of the thread delayed free@@ -517,15 +555,13 @@ void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const simi_track_mem_noaccess(padding,sizeof(mi_padding_t));}#else-static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block) {- MI_UNUSED(block);+static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool is_guarded) {+ MI_UNUSED(is_guarded); MI_UNUSED(block);return mi_page_usable_block_size(page);}void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const size_t min_size) {- MI_UNUSED(page);- MI_UNUSED(block);- MI_UNUSED(min_size);+ MI_UNUSED(page); MI_UNUSED(block); MI_UNUSED(min_size);}#endifdiff --git a/vendored/mimalloc/src/heap.c b/vendored/mimalloc/src/heap.cindex 080cfd127..f0a016527 100644--- a/vendored/mimalloc/src/heap.c+++ b/vendored/mimalloc/src/heap.c@@ -33,46 +33,42 @@ void mi_heap_stats_merge_to_main(mi_heap_t* heap) {_mi_stats_merge_into(&mi_heap_main()->stats, &heap->stats);}-static mi_theap_t* mi_heap_init_theap(const mi_heap_t* const_heap)+static mi_decl_noinline mi_theap_t* mi_heap_init_theap(const mi_heap_t* const_heap){mi_heap_t* heap = (mi_heap_t*)const_heap;mi_assert_internal(heap!=NULL);if (_mi_is_heap_main(heap)) {// this can be called if the (main) thread is not yet initialized (as no allocation happened)- mi_thread_init();- mi_theap_t* theap = _mi_heap_theap(heap);- mi_assert_internal(theap!=NULL);+ // but `theap_main_init_get()` will call `mi_thread_init()`+ mi_theap_t* const theap = _mi_theap_main_safe();+ mi_assert_internal(theap!=NULL && _mi_is_heap_main(_mi_theap_heap(theap)));return theap;}// otherwise initialize the theap for this heap// get the thread local- mi_theap_t* theap = NULL;- if (heap->theap==0) {- // initialize thread locals- heap->theap = _mi_thread_local_create();- if (heap->theap==0) {- _mi_error_message(EFAULT, "unable to dynamically create a thread local for a heap\n");- return NULL;- }- }- else {- // get current thread local- theap = (mi_theap_t*)_mi_thread_local_get(heap->theap);+ mi_assert_internal(heap->theap != 0);+ if (heap->theap==0) { // paranoia+ _mi_error_message(EFAULT, "no thread-local reserved for heap (%p)\n", heap);+ return NULL;}+ mi_theap_t* theap = (mi_theap_t*)_mi_thread_local_get(heap->theap);// create a fresh theap?if (theap==NULL) {+ // set first an invalid value to ensure the thread local storage is allocated+ if (!_mi_thread_local_set(heap->theap, (mi_theap_t*)1)) {+ _mi_error_message(EFAULT, "unable to allocate memory for thread local storage\n");+ return NULL;+ }+ // then allocate the theaptheap = _mi_theap_create(heap, _mi_theap_default_safe()->tld);+ _mi_thread_local_set(heap->theap, theap); // Cannot fail now as it was set before. Always set so the local is valid or NULL (and not 1)if (theap==NULL) {_mi_error_message(EFAULT, "unable to allocate memory for a thread local heap\n");return NULL;- }- if (!_mi_thread_local_set(heap->theap, theap)) {- _mi_error_message(EFAULT, "unable to allocate memory for a thread local storage\n");- return NULL;- }+ }}return theap;}@@ -81,7 +77,7 @@ static mi_theap_t* mi_heap_init_theap(const mi_heap_t* const_heap)// get the theap for a heap without initializing (and return NULL in that case)mi_theap_t* _mi_heap_theap_get_peek(const mi_heap_t* heap) {if (heap==NULL || _mi_is_heap_main(heap)) {- return __mi_theap_main; // don't call _mi_theap_main as it may still be NULL+ return _mi_theap_main_safe();}else {return (mi_theap_t*)_mi_thread_local_get(heap->theap);@@ -103,17 +99,26 @@ mi_theap_t* _mi_heap_theap_get_or_init(const mi_heap_t* heap)mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t exclusive_arena_id) {// always allocate heap data in the (subprocess) main heap- mi_heap_t* heap_main = mi_heap_main();+ mi_heap_t* const heap_main = mi_heap_main();// todo: allocate heap data in the exclusive arena ?- mi_heap_t* heap = (mi_heap_t*)mi_heap_zalloc( heap_main, sizeof(mi_heap_t) );+ mi_heap_t* const heap = (mi_heap_t*)mi_heap_zalloc( heap_main, sizeof(mi_heap_t) );if (heap==NULL) return NULL;+ // reserve a thread local slot for this heap (see also issue #1230)+ const mi_thread_local_t theap_slot = _mi_thread_local_create();+ if (theap_slot == 0) {+ _mi_error_message(EFAULT, "unable to dynamically create a thread local for a heap\n");+ mi_free(heap);+ return NULL;+ }+// init fields+ heap->theap = theap_slot;heap->subproc = heap_main->subproc;heap->heap_seq = mi_atomic_increment_relaxed(&heap_main->subproc->heap_total_count);heap->exclusive_arena = _mi_arena_from_id(exclusive_arena_id);heap->numa_node = -1; // no initial affinity-+ mi_stats_header_init(&heap->stats);mi_lock_init(&heap->theaps_lock);mi_lock_init(&heap->os_abandoned_pages_lock);mi_lock_init(&heap->arena_pages_lock);@@ -135,22 +140,41 @@ mi_heap_t* mi_heap_new(void) {return mi_heap_new_in_arena(0);}-// free the heap resources (assuming the pages are already moved/destroyed)+// free all theaps belonging to this heap (without deleting their pages as we do this arena wise for efficiency)+static void mi_heap_free_theaps(mi_heap_t* heap) {+ // This can run concurrently with a thread that terminates (see `init.c:mi_thread_theaps_done`),+ // and we need to ensure we free theaps atomically.+ // We do this in a loop where we release the theaps_lock at every potential re-iteration to unblock+ // potential concurrent thread termination which tries to remove the theap from our theaps list.+ bool all_freed;+ do {+ all_freed = true;+ mi_theap_t* theap = NULL;+ mi_lock(&heap->theaps_lock) {+ theap = heap->theaps;+ while(theap != NULL) {+ mi_theap_t* next = theap->hnext;+ if (!_mi_theap_free(theap, false /* dont re-acquire the heap->theaps_lock */, true /* acquire the tld->theaps_lock though */ )) {+ all_freed = false;+ }+ theap = next;+ }+ }+ if (!all_freed) {+ mi_heap_stat_counter_increase(heap,heaps_delete_wait,1);+ _mi_prim_thread_yield();+ }+ else {+ mi_assert_internal(heap->theaps==NULL);+ }+ }+ while(!all_freed);+}++// free the heap resources (assuming the pages are already moved/destroyed, and all theaps have been freed)static void mi_heap_free(mi_heap_t* heap) {mi_assert_internal(heap!=NULL && !_mi_is_heap_main(heap));- // free all theaps belonging to this heap- mi_theap_t* theap = NULL;- mi_lock(&heap->theaps_lock) { theap = heap->theaps; }- while(theap != NULL) {- mi_theap_t* next = NULL;- mi_lock(&heap->theaps_lock) { next = theap->hnext; }- _mi_theap_free(theap);- theap = next;- }- mi_lock(&heap->theaps_lock) { theap = heap->theaps; }- mi_assert_internal(theap==NULL);-// free all arena pages infosmi_lock(&heap->arena_pages_lock) {for (size_t i = 0; i < MI_MAX_ARENAS; i++) {@@ -175,6 +199,7 @@ static void mi_heap_free(mi_heap_t* heap) {_mi_thread_local_free(heap->theap);mi_lock_done(&heap->theaps_lock);mi_lock_done(&heap->os_abandoned_pages_lock);+ mi_lock_done(&heap->arena_pages_lock);mi_free(heap);}@@ -184,18 +209,25 @@ void mi_heap_delete(mi_heap_t* heap) {_mi_warning_message("cannot delete the main heap\n");return;}+ mi_heap_free_theaps(heap);_mi_heap_move_pages(heap, mi_heap_main());mi_heap_free(heap);}+void _mi_heap_force_destroy(mi_heap_t* heap) {+ if (heap==NULL) return;+ mi_heap_free_theaps(heap);+ _mi_heap_destroy_pages(heap);+ if (!_mi_is_heap_main(heap)) { mi_heap_free(heap); } // todo: release locks of the main heap?+}+void mi_heap_destroy(mi_heap_t* heap) {if (heap==NULL) return;if (_mi_is_heap_main(heap)) {_mi_warning_message("cannot destroy the main heap\n");return;}- _mi_heap_destroy_pages(heap);- mi_heap_free(heap);+ _mi_heap_force_destroy(heap);}mi_heap_t* mi_heap_of(const void* p) {@@ -217,3 +249,25 @@ bool mi_heap_contains(const mi_heap_t* heap, const void* p) {bool mi_check_owned(const void* p) {return mi_any_heap_contains(p);}++// unsafe heap utilization function for DragonFly (see issue #1258)+// If the page of pointer `p` belongs to `heap` (or `heap==NULL`) and has less than `perc_threshold` used blocks in its used area return `true`.+// This function is unsafe in general as it assumes we are the only thread accessing the page of `p`.+bool mi_unsafe_heap_page_is_under_utilized(mi_heap_t* heap, void* p, size_t perc_threshold) mi_attr_noexcept {+ if (p==NULL) return false;+ const mi_page_t* const page = _mi_safe_ptr_page(p); // Get the page containing this pointer+ if (page==NULL || page->used==page->capacity || page->capacity < page->reserved) return false;+ // If the page is the head of the queue, it is currently being used for+ // allocations; we skip it to avoid immediate thrashing.+ if (page->prev == NULL) return false;++ // match heap?+ const mi_heap_t* const page_heap = mi_page_heap(page);+ if (page_heap==NULL) return false;+ if (heap!=NULL && page_heap!=heap) return false;++ // check utilization+ if (page->capacity==0) return false;+ if (perc_threshold>=100) return true;+ return (perc_threshold >= ((100UL*page->used) / page->capacity));+}diff --git a/vendored/mimalloc/src/init.c b/vendored/mimalloc/src/init.cindex 3161450fd..1fabd8918 100644--- a/vendored/mimalloc/src/init.c+++ b/vendored/mimalloc/src/init.c@@ -67,17 +67,11 @@ const mi_page_t _mi_page_empty = {#define MI_STAT_COUNT_NULL() {0,0,0}// Empty statistics+#define MI_STAT_COUNT(stat) {0,0,0},+#define MI_STAT_COUNTER(stat) {0},+#define MI_STATS_NULL \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- { 0 }, { 0 }, \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- { 0 }, { 0 }, { 0 }, { 0 }, \- { 0 }, { 0 }, { 0 }, { 0 }, \- \- { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, \- MI_INIT5(MI_STAT_COUNT_NULL), \- { 0 }, { 0 }, { 0 }, { 0 }, \+ MI_STAT_FIELDS() \\{ MI_INIT4(MI_STAT_COUNT_NULL) }, \{ { 0 }, { 0 }, { 0 }, { 0 } }, \@@ -97,9 +91,9 @@ const mi_page_t _mi_page_empty = {static mi_decl_cache_align mi_subproc_t subproc_main#if __cplusplus-= { }; // empty initializer to prevent running the constructor (with msvc)+ = { }; // empty initializer to prevent running the constructor (with msvc)#else-= { 0 }; // C zero initialize+ = { 0 }; // C zero initialize#endifstatic mi_subproc_t* subprocs = &subproc_main;@@ -111,6 +105,7 @@ static mi_decl_cache_align mi_tld_t tld_empty = {0, // default numa node&subproc_main, // subprocNULL, // theaps list+ MI_LOCK_INITIALIZER, // theaps lockfalse, // recursefalse, // is_in_threadpoolMI_MEMID_STATIC // memid@@ -118,12 +113,14 @@ static mi_decl_cache_align mi_tld_t tld_empty = {mi_decl_cache_align const mi_theap_t _mi_theap_empty = {&tld_empty, // tld- NULL, // heap+ MI_ATOMIC_VAR_INIT(NULL), // heap+ MI_ATOMIC_VAR_INIT(1), // refcount0, // heartbeat0, // cookie{ {0}, {0}, 0, true }, // random0, // page countMI_BIN_FULL, 0, // page retired min/max+ 0, // pages_full_size0, 0, // generic countNULL, NULL, // tnext, tprevNULL, NULL, // hnext, hprev@@ -141,12 +138,14 @@ mi_decl_cache_align const mi_theap_t _mi_theap_empty = {mi_decl_cache_align const mi_theap_t _mi_theap_empty_wrong = {&tld_empty, // tld- NULL, // heap+ MI_ATOMIC_VAR_INIT(NULL), // heap+ MI_ATOMIC_VAR_INIT(1), // refcount0, // heartbeat0, // cookie{ {0}, {0}, 0, true }, // random0, // page countMI_BIN_FULL, 0, // page retired min/max+ 0, // pages_full_size0, 0, // generic countNULL, NULL, // tnext, tprevNULL, NULL, // hnext, hprev@@ -173,6 +172,7 @@ static mi_decl_cache_align mi_tld_t tld_main = {0, // numa node&subproc_main, // subproc&theap_main, // theaps list+ MI_LOCK_INITIALIZER, // theaps lockfalse, // recursefalse, // is_in_threadpoolMI_MEMID_STATIC // memid@@ -180,12 +180,14 @@ static mi_decl_cache_align mi_tld_t tld_main = {mi_decl_cache_align mi_theap_t theap_main = {&tld_main, // thread local data- &heap_main, // main heap+ MI_ATOMIC_VAR_INIT(&heap_main), // main heap+ MI_ATOMIC_VAR_INIT(1), // refcount0, // heartbeat0, // initial cookie{ {0x846ca68b}, {0}, 0, true }, // random0, // page countMI_BIN_FULL, 0, // page retired min/max+ 0, // pages_full_size0, 0, // generic countNULL, NULL, // tnext, tprevNULL, NULL, // hnext, hprev@@ -208,13 +210,15 @@ mi_decl_cache_align mi_heap_t heap_main= { 0 }; // C zero initialize#endif-mi_threadid_t _mi_thread_id(void) mi_attr_noexcept {- return _mi_prim_thread_id();-}-// the theap belonging to the main heapmi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_main = NULL;+mi_threadid_t _mi_thread_id(void) mi_attr_noexcept {+ mi_threadid_t tid = _mi_prim_thread_id();+ mi_assert_internal( (tid & 0x03) == 0 ); // mimalloc reserves the bottom 2 bits+ return tid;+}+#if MI_TLS_MODEL_THREAD_LOCAL// the thread-local main theap for allocationmi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_default = (mi_theap_t*)&_mi_theap_empty;@@ -226,6 +230,10 @@ bool _mi_process_is_initialized = false; // set to `true` in `mi_process_init`.mi_stats_t _mi_stats_main = { sizeof(mi_stats_t), MI_STAT_VERSION, MI_STATS_NULL };+#undef MI_STAT_COUNT+#undef MI_STAT_COUNTER++#if MI_GUARDEDmi_decl_export void mi_theap_guarded_set_sample_rate(mi_theap_t* theap, size_t sample_rate, size_t seed) {theap->guarded_sample_rate = sample_rate;@@ -280,9 +288,11 @@ static void mi_subproc_main_init(void) {subproc_main.heap_count = 1;mi_atomic_store_ptr_release(mi_heap_t, &subproc_main.heap_main, &heap_main);__mi_stat_increase_mt(&subproc_main.stats.heaps, 1);+ mi_stats_header_init(&subproc_main.stats);mi_lock_init(&subproc_main.arena_reserve_lock);mi_lock_init(&subproc_main.heaps_lock);mi_lock_init(&subprocs_lock);+ mi_lock_init(&tld_empty.theaps_lock);}}@@ -290,6 +300,7 @@ static void mi_subproc_main_init(void) {static void mi_tld_main_init(void) {if (tld_main.thread_id == 0) {tld_main.thread_id = _mi_prim_thread_id();+ mi_lock_init(&tld_main.theaps_lock);}}@@ -354,6 +365,7 @@ static mi_tld_t* mi_tld_alloc(void) {}tld->memid = memid;tld->theaps = NULL;+ mi_lock_init(&tld->theaps_lock);tld->subproc = &subproc_main;tld->numa_node = _mi_os_numa_node();tld->thread_id = _mi_prim_thread_id();@@ -367,6 +379,7 @@ static mi_tld_t* mi_tld_alloc(void) {#define MI_TLD_INVALID ((mi_tld_t*)1)mi_decl_noinline static void mi_tld_free(mi_tld_t* tld) {+ mi_lock_done(&tld->theaps_lock);if (tld != NULL && tld != MI_TLD_INVALID) {mi_atomic_decrement_relaxed(&tld->subproc->thread_count);_mi_meta_free(tld, sizeof(mi_tld_t), tld->memid);@@ -388,6 +401,22 @@ mi_theap_t* _mi_theap_default_safe(void) {return _mi_theap_default();}+// return the main theap ensuring it is initialized.+mi_theap_t* _mi_theap_main_safe(void) {+ mi_theap_t* theap = __mi_theap_main;+ if mi_unlikely(theap==NULL) { // if thread_init or default_set was never called+ mi_thread_init(); // sets the default slot to the main theap+ theap = _mi_theap_default();+ mi_assert_internal(theap!=NULL);+ mi_assert_internal(_mi_is_theap_main(theap));+ if (_mi_is_theap_main(theap)) {+ __mi_theap_main = theap;+ }+ }+ mi_assert_internal(theap!=NULL && _mi_is_theap_main(theap));+ return theap;+}+mi_subproc_t* _mi_subproc_main(void) {return &subproc_main;@@ -420,7 +449,7 @@ mi_heap_t* _mi_subproc_heap_main(mi_subproc_t* subproc) {}mi_heap_t* mi_heap_main(void) {- return _mi_subproc_heap_main(_mi_subproc()); // don't use _mi_theap_main() so this call works during process_init+ return _mi_subproc_heap_main(_mi_subproc()); // don't use mi_theap_main_init_get() so this call works during process_init}bool _mi_is_heap_main(const mi_heap_t* heap) {@@ -428,25 +457,40 @@ bool _mi_is_heap_main(const mi_heap_t* heap) {return (_mi_subproc_heap_main(heap->subproc) == heap);}+bool _mi_is_theap_main(const mi_theap_t* theap) {+ return (mi_theap_is_initialized(theap) && _mi_is_heap_main(_mi_theap_heap(theap)));+}+/* -----------------------------------------------------------Sub process----------------------------------------------------------- */++mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id) {+ return (mi_subproc_t*)(subproc_id._mi_subproc_id);+}++mi_subproc_id_t _mi_subproc_to_id(mi_subproc_t* subproc) {+ mi_subproc_id_t id = { subproc };+ return id;+}+mi_subproc_id_t mi_subproc_main(void) {- return _mi_subproc_main();+ return _mi_subproc_to_id(_mi_subproc_main());}mi_subproc_id_t mi_subproc_current(void) {- return _mi_subproc();+ return _mi_subproc_to_id(_mi_subproc());}mi_subproc_id_t mi_subproc_new(void) {static _Atomic(size_t) subproc_total_count;mi_memid_t memid;mi_subproc_t* subproc = (mi_subproc_t*)_mi_meta_zalloc(sizeof(mi_subproc_t),&memid);- if (subproc == NULL) return NULL;+ if (subproc == NULL) return _mi_subproc_to_id(NULL);subproc->memid = memid;subproc->subproc_seq = mi_atomic_increment_relaxed(&subproc_total_count) + 1;+ mi_stats_header_init(&subproc->stats);mi_lock_init(&subproc->arena_reserve_lock);mi_lock_init(&subproc->heaps_lock);mi_lock(&subprocs_lock) {@@ -455,18 +499,16 @@ mi_subproc_id_t mi_subproc_new(void) {if (subprocs!=NULL) { subprocs->prev = subproc; }subprocs = subproc;}- return subproc;-}--mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id) {- return (subproc_id == NULL ? &subproc_main : (mi_subproc_t*)subproc_id);+ return _mi_subproc_to_id(subproc);}// destroy all subproc resources including arena's, heap's etc.-static void mi_subproc_unsafe_destroy(mi_subproc_t* subproc)+static void mi_subproc_unsafe_destroy(mi_subproc_t* subproc, bool acquire_subprocs_lock){+ if (subproc==NULL) return;+// remove from the subproc list- mi_lock(&subprocs_lock) {+ mi_lock_maybe(&subprocs_lock, acquire_subprocs_lock) {if (subproc->next!=NULL) { subproc->next->prev = subproc->prev; }if (subproc->prev!=NULL) { subproc->prev->next = subproc->next; }else { mi_assert_internal(subprocs==subproc); subprocs = subproc->next; }@@ -477,29 +519,38 @@ static void mi_subproc_unsafe_destroy(mi_subproc_t* subproc)mi_heap_t* heap = subproc->heaps;while (heap != NULL) {mi_heap_t* next = heap->next;- if (heap!=subproc->heap_main) {mi_heap_destroy(heap); }+ if (heap!=subproc->heap_main) { mi_heap_destroy(heap); }heap = next;}mi_assert_internal(subproc->heaps == subproc->heap_main);- mi_heap_destroy(subproc->heap_main);+ _mi_heap_force_destroy(subproc->heap_main); // no warning if destroying the main heap}+ // remove associated arenas+ _mi_arenas_unsafe_destroy_all(subproc);+// merge stats back into the main subproc?if (subproc!=&subproc_main) {- _mi_arenas_unsafe_destroy_all(subproc);_mi_stats_merge_into(&subproc_main.stats, &subproc->stats);+ }- // safe to release- // todo: should we refcount subprocesses?- mi_lock_done(&subproc->arena_reserve_lock);- mi_lock_done(&subproc->heaps_lock);+ // safe to release+ // todo: should we refcount subprocesses?+ mi_lock_done(&subproc->arena_reserve_lock);+ mi_lock_done(&subproc->heaps_lock);+ if (subproc!=&subproc_main) {_mi_meta_free(subproc, sizeof(mi_subproc_t), subproc->memid);}+ else {+ // for the main subproc, also release the global page map+ _mi_page_map_unsafe_destroy(&subproc_main);+ }}void mi_subproc_destroy(mi_subproc_id_t subproc_id) {- if (subproc_id == NULL) return;- mi_subproc_unsafe_destroy(_mi_subproc_from_id(subproc_id));+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL || subproc==&subproc_main) return;+ mi_subproc_unsafe_destroy(subproc, true /* take lock */);}static void mi_subprocs_unsafe_destroy_all(void) {@@ -508,12 +559,12 @@ static void mi_subprocs_unsafe_destroy_all(void) {while (subproc!=NULL) {mi_subproc_t* next = subproc->next;if (subproc!=&subproc_main) {- mi_subproc_unsafe_destroy(subproc);+ mi_subproc_unsafe_destroy(subproc, false /* take subprocs lock */);}subproc = next;}- }- mi_subproc_unsafe_destroy(&subproc_main);+ }+ mi_subproc_unsafe_destroy(&subproc_main, true /* take subprocs lock */);}@@ -562,6 +613,7 @@ static mi_theap_t* _mi_thread_init_theap_default(void) {// note: we cannot access thread-locals yet as that can cause (recursive) allocation// (on macOS <= 14 for example where the loader allocates thread-local data on demand).mi_tld_t* tld = mi_tld_alloc();+ if (tld==NULL) return NULL; // things are very wrong if this fails (out of memory)// allocate and initialize the theap for the main heaptheap = _mi_theap_create(mi_heap_main(), tld);}@@ -576,19 +628,50 @@ static mi_theap_t* _mi_thread_init_theap_default(void) {static void mi_thread_theaps_done(mi_tld_t* tld){// reset the thread local theaps- __mi_theap_main = NULL;_mi_theap_default_set((mi_theap_t*)&_mi_theap_empty);_mi_theap_cached_set((mi_theap_t*)&_mi_theap_empty);-- // delete all theaps in this thread- mi_theap_t* curr = tld->theaps;- while (curr != NULL) {- mi_theap_t* next = curr->tnext; // save `tnext` as `curr` will be freed- // never destroy theaps; if a dll is linked statically with mimalloc,- // there may still be delete/free calls after the mi_fls_done is called. Issue #207- _mi_theap_delete(curr);- curr = next;+ __mi_theap_main = NULL;++ // abandon the pages of all theaps in this thread+ mi_lock(&tld->theaps_lock) {+ mi_theap_t* theap = tld->theaps;+ while (theap != NULL) {+ mi_theap_t* next = theap->tnext;+ // never destroy theaps; if a dll is linked statically with mimalloc,+ // there may still be delete/free calls after the mi_fls_done is called. Issue #207+ _mi_theap_collect_abandon(theap);+ mi_assert_internal(theap->page_count==0);+ theap = next;+ }}++ // free the theaps of this thread.+ // This can run concurrently with a `mi_heap_free_theaps` and we need to ensure we free theaps atomically.+ // We do this in a loop where we release the theaps_lock at every potential re-iteration to unblock+ // potential concurrent `mi_heap_free_theaps` which tries to remove the theap from our theaps list.+ bool all_freed;+ do {+ all_freed = true;+ mi_lock(&tld->theaps_lock) {+ mi_theap_t* theap = tld->theaps;+ while (theap != NULL) {+ mi_theap_t* next = theap->tnext;+ mi_assert_internal(theap->page_count==0);+ if (!_mi_theap_free(theap, true /* acquire heap->theaps_lock */, false /* dont re-acquire the tld->theaps_lock*/ )) {+ all_freed = false;+ }+ theap = next;+ }+ }+ if (!all_freed) {+ mi_subproc_stat_counter_increase(tld->subproc,heaps_delete_wait,1);+ _mi_prim_thread_yield();+ }+ else {+ mi_assert_internal(tld->theaps==NULL);+ }+ } while (!all_freed);+mi_assert(_mi_theap_default()==(mi_theap_t*)&_mi_theap_empty); // careful to not re-initialize the default theap during theap_deletemi_assert(!mi_theap_is_initialized(_mi_theap_default()));}@@ -613,11 +696,10 @@ static void mi_thread_theaps_done(mi_tld_t* tld)// Set up handlers so `mi_thread_done` is called automaticallystatic void mi_process_setup_auto_thread_done(void) {- static bool tls_initialized = false; // fine if it races- if (tls_initialized) return;- tls_initialized = true;- _mi_prim_thread_init_auto_done();- _mi_theap_default_set(&theap_main);+ mi_atomic_do_once {+ _mi_prim_thread_init_auto_done();+ _mi_theap_default_set(&theap_main);+ }}@@ -635,7 +717,7 @@ void mi_thread_init(void) mi_attr_noexceptif (_mi_thread_is_initialized()) return;// initialize the default theap- _mi_thread_init_theap_default();+ if (_mi_thread_init_theap_default() == NULL) return; // out-of-memory on tld/theap allocationmi_heap_stat_increase(mi_heap_main(), threads, 1);// _mi_verbose_message("thread init: 0x%zx\n", _mi_thread_id());@@ -649,7 +731,11 @@ void _mi_thread_done(mi_theap_t* _theap_main){// NULL can be passed on some platformsif (_theap_main==NULL) {- _theap_main = __mi_theap_main;+ _theap_main = __mi_theap_main; // don't call `mi_theap_main_safe` as that re-initializes the thread+ if (_theap_main==NULL) { // can happen if `mi_theap_main_safe` is never called; but then the default is main+ _theap_main = _mi_theap_default();+ mi_assert_internal(_theap_main==NULL || _mi_is_theap_main(_theap_main));+ }}// prevent re-entrancy through theap_done/theap_set_default_direct (issue #699)@@ -699,8 +785,8 @@ mi_decl_cold mi_decl_noinline mi_theap_t* _mi_theap_empty_get(void) {#else// with only direct entries, use the "arbitrary user data" field// and assume it is NULL (see also <http://www.nynaeve.net/?p=98>)-#define MI_TLS_INITIAL_EXPANSION_SLOT (0)#define MI_TLS_INITIAL_SLOT (5)+#define MI_TLS_INITIAL_EXPANSION_SLOT (0)#endif// we initially use the last of the expansion slots as the default NULL.@@ -710,38 +796,62 @@ mi_decl_hidden size_t _mi_theap_default_expansion_slot = MI_TLS_INITIAL_EXPANSIOmi_decl_hidden size_t _mi_theap_cached_slot = MI_TLS_INITIAL_SLOT;mi_decl_hidden size_t _mi_theap_cached_expansion_slot = MI_TLS_INITIAL_EXPANSION_SLOT;-static size_t mi_win_tls_slot_alloc(size_t* extended) {- const DWORD slot = TlsAlloc();- if (slot==TLS_OUT_OF_INDEXES || slot >= MI_TLS_DIRECT_SLOTS + MI_TLS_EXPANSION_SLOTS - 1) {- // note: we also fail if the program already allocated the maximum number of expansion slots (as we use the last one as the default)+static DWORD mi_tls_raw_index_default = TLS_OUT_OF_INDEXES;+static DWORD mi_tls_raw_index_cached = TLS_OUT_OF_INDEXES;++static bool mi_win_tls_slot_alloc(size_t* slot, size_t* extended, DWORD* raw_index) {+ const DWORD index = TlsAlloc();+ *raw_index = index;+ if (index==TLS_OUT_OF_INDEXES) {*extended = 0;- return 0;+ *slot = 0;+ return false;}- else if (slot<MI_TLS_DIRECT_SLOTS) {+ else if (index<MI_TLS_DIRECT_SLOTS) {*extended = 0;- return (slot + MI_TLS_DIRECT_FIRST);+ *slot = index + MI_TLS_DIRECT_FIRST;+ return true;+ }+ #if !MI_WIN_DIRECT_TLS+ else if (index < MI_TLS_DIRECT_SLOTS + MI_TLS_EXPANSION_SLOTS - 1) { // check maximum number of expansion slots - 1 (as we use the last one as the default)+ *extended = index - MI_TLS_DIRECT_SLOTS;+ *slot = MI_TLS_EXPANSION_SLOT;+ return true;}+ #endifelse {- #if MI_WIN_DIRECT_TLS+ // to high an index for us+ _mi_error_message(EFAULT, "returned tls index was too high (%u)\n", index);+ TlsFree(index);+ *raw_index = TLS_OUT_OF_INDEXES;*extended = 0;- return 0;- #else- *extended = (slot - MI_TLS_DIRECT_SLOTS);- return MI_TLS_EXPANSION_SLOT;- #endif+ *slot = 0;+ return false;+ }+}++static void mi_win_tls_slot_free(DWORD* raw_index) {+ if (*raw_index != TLS_OUT_OF_INDEXES) {+ TlsFree(*raw_index);+ *raw_index = TLS_OUT_OF_INDEXES;}}-mi_decl_cold mi_theap_t* _mi_win_tls_slots_init(void) {- static mi_atomic_once_t tls_slots_init;- if (mi_atomic_once(&tls_slots_init)) {- _mi_theap_default_slot = mi_win_tls_slot_alloc(&_mi_theap_default_expansion_slot);- _mi_theap_cached_slot = mi_win_tls_slot_alloc(&_mi_theap_cached_expansion_slot);- if (_mi_theap_cached_slot==0) {+static void mi_tls_slots_init(void) {+ mi_atomic_do_once {+ bool ok = mi_win_tls_slot_alloc(&_mi_theap_default_slot, &_mi_theap_default_expansion_slot, &mi_tls_raw_index_default);+ if (ok) {+ ok = mi_win_tls_slot_alloc(&_mi_theap_cached_slot, &_mi_theap_cached_expansion_slot, &mi_tls_raw_index_cached);+ }+ if (!ok) {_mi_error_message(EFAULT, "unable to allocate fast TLS user slot (0x%zx)\n", _mi_theap_cached_slot);}}- return (mi_theap_t*)&_mi_theap_empty;+}++static void mi_tls_slots_done(void) {+ mi_win_tls_slot_free(&mi_tls_raw_index_default);+ mi_win_tls_slot_free(&mi_tls_raw_index_cached );}static void mi_win_tls_slot_set(size_t slot, size_t extended_slot, void* value) {@@ -761,43 +871,90 @@ static void mi_win_tls_slot_set(size_t slot, size_t extended_slot, void* value)mi_decl_hidden pthread_key_t _mi_theap_default_key = 0;mi_decl_hidden pthread_key_t _mi_theap_cached_key = 0;-mi_decl_cold mi_theap_t* _mi_tls_keys_init(void) {- static mi_atomic_once_t tls_keys_init;- if (mi_atomic_once(&tls_keys_init)) {- pthread_key_create(&_mi_theap_default_key, NULL);- pthread_key_create(&_mi_theap_cached_key, NULL);+// create a non-zero pthread key+static int mi_pthread_key_create( pthread_key_t* pkey ) {+ pthread_key_t key;+ int err = pthread_key_create(&key, NULL);+ if (err!=0) return err;+ if (key==0) {+ // if we get a zero key, create another one as we use 0 for an invalid key+ pthread_key_t key2;+ err = pthread_key_create(&key2, NULL);+ pthread_key_delete(key); // delete the old key+ if (err!=0) return err;+ key = key2;+ }+ mi_assert_internal(key!=0);+ *pkey = key;+ return 0;+}++static void mi_tls_slots_init(void) {+ mi_atomic_do_once {+ int err = mi_pthread_key_create(&_mi_theap_default_key);+ if (err==0) {+ err = mi_pthread_key_create(&_mi_theap_cached_key);+ }+ if (err!=0) {+ _mi_error_message(EFAULT, "unable to allocate pthread keys (error %d)\n", err);+ }}- return (mi_theap_t*)&_mi_theap_empty;+}++static void mi_tls_slots_done(void) {+ if (_mi_theap_default_key != 0) {+ pthread_key_delete(_mi_theap_default_key);+ _mi_theap_default_key = 0;+ }+ if (_mi_theap_cached_key != 0) {+ pthread_key_delete(_mi_theap_cached_key);+ _mi_theap_cached_key = 0;+ }+}++#else++static void mi_tls_slots_init(void) {+ // nothing+}++static void mi_tls_slots_done(void) {+ // nothing}#endifvoid _mi_theap_cached_set(mi_theap_t* theap) {+ mi_theap_t* prev = _mi_theap_cached();+ if (prev==theap) return;+ // set+ mi_tls_slots_init();#if MI_TLS_MODEL_THREAD_LOCAL__mi_theap_cached = theap;#elif MI_TLS_MODEL_FIXED_SLOTmi_prim_tls_slot_set(MI_TLS_MODEL_FIXED_SLOT_CACHED, theap);#elif MI_TLS_MODEL_DYNAMIC_WIN32- _mi_win_tls_slots_init();mi_win_tls_slot_set(_mi_theap_cached_slot, _mi_theap_cached_expansion_slot, theap);#elif MI_TLS_MODEL_DYNAMIC_PTHREADS- _mi_tls_keys_init();if (_mi_theap_cached_key!=0) pthread_setspecific(_mi_theap_cached_key, theap);#endif+ // update refcounts (so cached theap memory keeps available until no longer cached)+ _mi_theap_incref(theap);+ _mi_theap_decref(prev);}void _mi_theap_default_set(mi_theap_t* theap) {+ mi_theap_t* const theap_old = _mi_theap_default();mi_assert_internal(theap != NULL);mi_assert_internal(theap->tld->thread_id==0 || theap->tld->thread_id==_mi_thread_id());+ mi_tls_slots_init();#if MI_TLS_MODEL_THREAD_LOCAL__mi_theap_default = theap;#elif MI_TLS_MODEL_FIXED_SLOTmi_prim_tls_slot_set(MI_TLS_MODEL_FIXED_SLOT_DEFAULT, theap);#elif MI_TLS_MODEL_DYNAMIC_WIN32- _mi_win_tls_slots_init();mi_win_tls_slot_set(_mi_theap_default_slot, _mi_theap_default_expansion_slot, theap);#elif MI_TLS_MODEL_DYNAMIC_PTHREADS- _mi_tls_keys_init();if (_mi_theap_default_key!=0) pthread_setspecific(_mi_theap_default_key, theap);#endif@@ -805,10 +962,15 @@ void _mi_theap_default_set(mi_theap_t* theap) {if (mi_theap_is_initialized(theap)) {// ensure the default theap is passed to `_mi_thread_done` as on some platforms we cannot access TLS at thread termination (as it would allocate again)_mi_prim_thread_associate_default_theap(theap);- if (_mi_is_heap_main(theap->heap)) {+ if (_mi_is_heap_main(_mi_theap_heap(theap))) {__mi_theap_main = theap;}}++ // ensure either the default slot contains the main theap, or __mi_theap_main is initialized+ if (mi_theap_is_initialized(theap_old) && _mi_is_heap_main(_mi_theap_heap(theap_old))) {+ __mi_theap_main = theap_old;+ }}void mi_thread_set_in_threadpool(void) mi_attr_noexcept {@@ -932,13 +1094,8 @@ static void mi_detect_cpu_features(void) {// Initialize the process; called by thread_init or the process loader-void mi_process_init(void) mi_attr_noexcept {- // ensure we are called once- static mi_atomic_once_t process_init;- // #if _MSC_VER < 1920- // mi_heap_main_init(); // vs2017 can dynamically re-initialize theap_main- // #endif- if (!mi_atomic_once(&process_init)) return;+static void mi_process_init_once(void) mi_attr_noexcept {+ _mi_process_is_initialized = true;_mi_verbose_message("process init: 0x%zx\n", _mi_thread_id());mi_detect_cpu_features();@@ -978,6 +1135,16 @@ void mi_process_init(void) mi_attr_noexcept {}}+// Initialize the process; called by thread_init or the process loader+void mi_process_init(void) mi_attr_noexcept {+ // #if _MSC_VER < 1920+ // mi_heap_main_init(); // vs2017 can dynamically re-initialize _mi_heap_main+ // #endif+ mi_atomic_do_once {+ mi_process_init_once();+ }+}+// Called when the process is done (cdecl as it is used with `at_exit` on some platforms)void mi_cdecl mi_process_done(void) mi_attr_noexcept {// only shutdown if we were initialized@@ -1002,21 +1169,25 @@ void mi_cdecl mi_process_done(void) mi_attr_noexcept {#endif#endif+ // done with tracking tools+ mi_track_done()+// Forcefully release all retained memory; this can be dangerous in general if overriding regular malloc/free// since after process_done there might still be other code running that calls `free` (like at_exit routines,// or C-runtime termination code.if (mi_option_is_enabled(mi_option_destroy_on_exit)) {- mi_subprocs_unsafe_destroy_all();- _mi_page_map_unsafe_destroy(_mi_subproc_main());+ mi_subprocs_unsafe_destroy_all(); // destroys all subprocs, arenas, and the page_map!}else {mi_heap_stats_merge_to_subproc(mi_heap_main());}-++ // careful now to no longer access any allocator functionalityif (mi_option_is_enabled(mi_option_show_stats) || mi_option_is_enabled(mi_option_verbose)) {- mi_subproc_stats_print_out(NULL, NULL, NULL);+ mi_subproc_stats_print_out(mi_subproc_main(), NULL, NULL);}mi_lock_done(&subprocs_lock);+ mi_tls_slots_done();_mi_allocator_done();_mi_verbose_message("process done: 0x%zx\n", tld_main.thread_id);os_preloading = true; // don't call the C runtime anymorediff --git a/vendored/mimalloc/src/libc.c b/vendored/mimalloc/src/libc.cindex 4c891c1e6..c74003a14 100644--- a/vendored/mimalloc/src/libc.c+++ b/vendored/mimalloc/src/libc.c@@ -22,6 +22,7 @@ char _mi_toupper(char c) {}int _mi_strnicmp(const char* s, const char* t, size_t n) {+ mi_assert_internal(s!=NULL && t!=NULL);if (n == 0) return 0;for (; *s != 0 && *t != 0 && n > 0; s++, t++, n--) {if (_mi_toupper(*s) != _mi_toupper(*t)) break;@@ -29,6 +30,15 @@ int _mi_strnicmp(const char* s, const char* t, size_t n) {return (n == 0 ? 0 : *s - *t);}+bool _mi_streq(const char* s, const char* t) {+ if (s==NULL && t==NULL) return true;+ if (s==NULL || t==NULL) return false;+ for (; *s != 0 && *t != 0; s++, t++) {+ if (*s != *t) break;+ }+ return (*s == *t);+}+void _mi_strlcpy(char* dest, const char* src, size_t dest_size) {if (dest==NULL || src==NULL || dest_size == 0) return;// copy until end of src, or when dest is (almost) full@@ -51,13 +61,6 @@ void _mi_strlcat(char* dest, const char* src, size_t dest_size) {_mi_strlcpy(dest, src, dest_size);}-size_t _mi_strlen(const char* s) {- if (s==NULL) return 0;- size_t len = 0;- while(s[len] != 0) { len++; }- return len;-}-size_t _mi_strnlen(const char* s, size_t max_len) {if (s==NULL) return 0;size_t len = 0;@@ -65,6 +68,10 @@ size_t _mi_strnlen(const char* s, size_t max_len) {return len;}+size_t _mi_strlen(const char* s) {+ return _mi_strnlen(s,PTRDIFF_MAX);+}+char* _mi_strnstr(char* s, size_t max_len, const char* pat) {if (s==NULL) return NULL;if (pat==NULL) return s;@@ -94,6 +101,43 @@ bool _mi_getenv(const char* name, char* result, size_t result_size) {}#endif++// --------------------------------------------------------+// Define our own primitives for doing an action once+// --------------------------------------------------------++// Returns `true` only on the first invocation, signifying we can execute an action once.+// If it returns `true`, the caller should call `_mi_atomic_once_release` after performing the action.+// Other threads (than the initial thread that entered) will block until `_mi_atomic_once_release` has been called.+bool _mi_atomic_once_enter(mi_atomic_once_t* once) {+ const uintptr_t once_tid = mi_atomic_load_acquire(&once->tid);+ if mi_likely(once_tid == 1) {+ return false; // already executed+ }+ const mi_threadid_t current_tid = _mi_thread_id();+ if (once_tid == current_tid) {+ return false; // recursive invocation; we need this for process_init for example+ }++ mi_lock_acquire(&once->lock);+ uintptr_t expected = 0;+ if (mi_atomic_cas_strong_acq_rel(&once->tid, &expected, current_tid)) { // could use atomic_load/store as well+ return true; // should execute and release+ }+ else {+ mi_lock_release(&once->lock);+ return false; // already another thread entered and released+ }+}++void _mi_atomic_once_release(mi_atomic_once_t* once) {+ if (mi_atomic_load_acquire(&once->tid)>1) { // paranoia+ mi_atomic_store_release(&once->tid,1); // done executing+ mi_lock_release(&once->lock);+ }+}++// --------------------------------------------------------// Define our own limited `_mi_vsnprintf` and `_mi_snprintf`// This is mostly to avoid calling these when libc is not yet@@ -244,7 +288,8 @@ int _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {else x = va_arg(args, unsigned int);}else if (c == 'p') {- x = va_arg(args, uintptr_t);+ void* const p = va_arg(args, void*);+ x = (uintptr_t)p;mi_outs("0x", &out, end);start = out;width = (width >= 2 ? width - 2 : 0);diff --git a/vendored/mimalloc/src/options.c b/vendored/mimalloc/src/options.cindex 0b71ebbad..4fe7fe5ab 100644--- a/vendored/mimalloc/src/options.c+++ b/vendored/mimalloc/src/options.c@@ -77,7 +77,7 @@ int mi_version(void) mi_attr_noexcept {#endif#ifndef MI_DEFAULT_GUARDED_SAMPLE_RATE-#if MI_GUARDED+#if MI_GUARDED && !MI_DEBUG#define MI_DEFAULT_GUARDED_SAMPLE_RATE 4000#else#define MI_DEFAULT_GUARDED_SAMPLE_RATE 0@@ -136,11 +136,7 @@ static mi_option_desc_t mi_options[_mi_option_last] ={ 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_page_reset) }, // reset page memory on free{ 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_abandoned_page_purge) },{ 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_segment_reset) }, // reset segment memory on free (needs eager commit)-#if defined(__NetBSD__)- { 0, MI_OPTION_UNINIT, MI_OPTION(eager_commit_delay) }, // the first N segments per thread are not eagerly committed-#else{ 1, MI_OPTION_UNINIT, MI_OPTION(deprecated_eager_commit_delay) },-#endif{ 1000,MI_OPTION_UNINIT, MI_OPTION_LEGACY(purge_delay,reset_delay) }, // purge delay in milli-seconds{ 0, MI_OPTION_UNINIT, MI_OPTION(use_numa_nodes) }, // 0 = use available numa nodes, otherwise use at most N nodes.{ 0, MI_OPTION_UNINIT, MI_OPTION_LEGACY(disallow_os_alloc,limit_os_alloc) }, // 1 = do not use OS memory for allocation (but only reserved arenas)@@ -179,9 +175,10 @@ static mi_option_desc_t mi_options[_mi_option_last] =MI_OPTION_UNINIT, MI_OPTION(page_cross_thread_max_reclaim) }, // don't reclaim (small) pages across threads if we already own N pages in that size class{ MI_DEFAULT_ALLOW_THP,MI_OPTION_UNINIT, MI_OPTION(allow_thp) }, // allow transparent huge pages? (=1) (on Android =0 by default). Set to 0 to disable THP for the process.- { 0, MI_OPTION_UNINIT, MI_OPTION(minimal_purge_size) }, // set minimal purge size (in KiB) (=0). By default set to either 64 or 2048 if THP is enabled.+ { 0, MI_OPTION_UNINIT, MI_OPTION(minimal_purge_size) }, // set minimal purge size (in KiB) (=0). Using 0 resolves to either 64 (or 2048 if `mi_option_allow_thp==2`).{ MI_DEFAULT_ARENA_MAX_OBJECT_SIZE,MI_OPTION_UNINIT, MI_OPTION(arena_max_object_size) }, // set maximal object size that can be allocated in an arena (in KiB) (=2GiB on 64-bit).+ { 0, MI_OPTION_UNINIT, MI_OPTION(arena_is_numa_local) }, // associate local numa node with an initial arena allocation};static void mi_option_init(mi_option_desc_t* desc);@@ -221,8 +218,8 @@ void _mi_options_post_init(void) {mi_decl_export void mi_options_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept{// show version- const int vermajor = MI_MALLOC_VERSION/1000;- const int verminor = (MI_MALLOC_VERSION%1000)/100;+ const int vermajor = MI_MALLOC_VERSION/10000;+ const int verminor = (MI_MALLOC_VERSION%10000)/100;const int verpatch = (MI_MALLOC_VERSION%100);_mi_fprintf(out, arg, "v%i.%i.%i%s%s (built on %s, %s)\n", vermajor, verminor, verpatch,#if defined(MI_CMAKE_BUILD_TYPE)@@ -291,7 +288,9 @@ mi_decl_nodiscard size_t mi_option_get_size(mi_option_t option) {const long x = mi_option_get(option);size_t size = (x < 0 ? 0 : (size_t)x);if (mi_option_has_size_in_kib(option)) {- size *= MI_KiB;+ if (mi_mul_overflow(size, MI_KiB, &size)) {+ size = MI_MAX_ALLOC_SIZE;+ }}return size;}@@ -355,36 +354,41 @@ static void mi_cdecl mi_out_stderr(const char* msg, void* arg) {#ifndef MI_MAX_DELAY_OUTPUT#define MI_MAX_DELAY_OUTPUT ((size_t)(16*1024))#endif-static char mi_output_buffer[MI_MAX_DELAY_OUTPUT+1];+static char out_buf[MI_MAX_DELAY_OUTPUT+1];static _Atomic(size_t) out_len;+static mi_lock_t out_buf_lock = MI_LOCK_INITIALIZER;static void mi_cdecl mi_out_buf(const char* msg, void* arg) {MI_UNUSED(arg);if (msg==NULL) return;- if (mi_atomic_load_relaxed(&out_len)>=MI_MAX_DELAY_OUTPUT) return;+ if (mi_atomic_load_acquire(&out_len)>=MI_MAX_DELAY_OUTPUT) return;size_t n = _mi_strlen(msg);- if (n==0) return;- // claim space- size_t start = mi_atomic_add_acq_rel(&out_len, n);- if (start >= MI_MAX_DELAY_OUTPUT) return;- // check bound- if (start+n >= MI_MAX_DELAY_OUTPUT) {- n = MI_MAX_DELAY_OUTPUT-start-1;+ if (n==0 || n >= MI_MAX_DELAY_OUTPUT) return;+ // copy msg into the buffer+ mi_lock(&out_buf_lock) {+ const size_t start = mi_atomic_add_acq_rel(&out_len, n);+ if (start < MI_MAX_DELAY_OUTPUT) {+ // check bound+ if (start+n >= MI_MAX_DELAY_OUTPUT) {+ n = MI_MAX_DELAY_OUTPUT-start-1;+ }+ _mi_memcpy(&out_buf[start], msg, n);+ }}- mi_assert_internal(start + n <= MI_MAX_DELAY_OUTPUT);- _mi_memcpy(&mi_output_buffer[start], msg, n);}static void mi_out_buf_flush(mi_output_fun* out, bool no_more_buf, void* arg) {if (out==NULL) return;// claim (if `no_more_buf == true`, no more output will be added after this point)- size_t count = mi_atomic_add_acq_rel(&out_len, (no_more_buf ? MI_MAX_DELAY_OUTPUT : 1));- // and output the current contents- if (count>MI_MAX_DELAY_OUTPUT) count = MI_MAX_DELAY_OUTPUT;- mi_output_buffer[count] = 0;- out(mi_output_buffer,arg);- if (!no_more_buf) {- mi_output_buffer[count] = '\n'; // if continue with the buffer, insert a newline+ mi_lock(&out_buf_lock) {+ size_t count = mi_atomic_add_acq_rel(&out_len, (no_more_buf ? MI_MAX_DELAY_OUTPUT : 1));+ // and output the current contents+ if (count>MI_MAX_DELAY_OUTPUT) count = MI_MAX_DELAY_OUTPUT;+ out_buf[count] = 0;+ out(out_buf,arg);+ if (!no_more_buf) {+ out_buf[count] = '\n'; // if continue with the buffer, insert a newline+ }}}@@ -402,30 +406,29 @@ static void mi_cdecl mi_out_buf_stderr(const char* msg, void* arg) {// Default output handler// ---------------------------------------------------------// Should be atomic but gives errors on many platforms as generally we cannot cast a function pointer to a uintptr_t.-// For now, don't register output from multiple threads.-static mi_output_fun* volatile mi_out_default; // = NULL+// The program should only install a single output handler from a single thread+// since otherwise the argument and output function may not match.+static _Atomic(void*) mi_out_default; // = // is `mi_output_fun*` (but some platforms don't support atomic function pointers)static _Atomic(void*) mi_out_arg; // = NULLstatic mi_output_fun* mi_out_get_default(void** parg) {+ mi_output_fun* const out = (mi_output_fun*)mi_atomic_load_ptr_acquire(void,&mi_out_default);if (parg != NULL) { *parg = mi_atomic_load_ptr_acquire(void,&mi_out_arg); }- mi_output_fun* out = mi_out_default;return (out == NULL ? &mi_out_buf : out);}void mi_register_output(mi_output_fun* out, void* arg) mi_attr_noexcept {- mi_out_default = (out == NULL ? &mi_out_stderr : out); // stop using the delayed output buffer+ mi_atomic_store_ptr_release(void,&mi_out_default, (void*)(out == NULL ? &mi_out_stderr : out)); // stop using the delayed output buffermi_atomic_store_ptr_release(void,&mi_out_arg, arg);- if (out!=NULL) mi_out_buf_flush(out,true,arg); // output all the delayed output now+ if (out!=NULL) { mi_out_buf_flush(out,true,arg); } // output all the delayed output now}// add stderr to the delayed output after the module is loadedstatic void mi_add_stderr_output(void) {mi_assert_internal(mi_out_default == NULL);- if (mi_out_default==NULL) {- mi_out_buf_flush(&mi_out_stderr, false, NULL); // flush current contents to stderr- mi_out_default = &mi_out_buf_stderr; // and add stderr to the delayed output- }+ mi_out_buf_flush(&mi_out_stderr, false, NULL); // flush current contents to stderr+ mi_atomic_store_ptr_release(void,&mi_out_default,(void*)&mi_out_buf_stderr); // and add stderr to the delayed output+ mi_atomic_store_ptr_release(void,&mi_out_arg,NULL);}// --------------------------------------------------------@@ -649,11 +652,11 @@ static void mi_option_init(mi_option_desc_t* desc) {buf[i] = _mi_toupper(s[i]);}buf[len] = 0;- if (buf[0] == 0 || strstr("1;TRUE;YES;ON", buf) != NULL) {+ if (buf[0] == 0 || _mi_streq(buf,"1") || _mi_streq(buf,"TRUE") || _mi_streq(buf,"YES") || _mi_streq(buf,"ON")) {desc->value = 1;desc->init = MI_OPTION_INITIALIZED;}- else if (strstr("0;FALSE;NO;OFF", buf) != NULL) {+ else if (_mi_streq(buf,"0") || _mi_streq(buf,"FALSE") || _mi_streq(buf,"NO") || _mi_streq(buf,"OFF")) {desc->value = 0;desc->init = MI_OPTION_INITIALIZED;}@@ -672,7 +675,7 @@ static void mi_option_init(mi_option_desc_t* desc) {else { size = (size + MI_KiB - 1) / MI_KiB; }if (end[0] == 'I' && end[1] == 'B') { end += 2; } // KiB, MiB, GiB, TiBelse if (*end == 'B') { end++; } // Kb, Mb, Gb, Tb- if (overflow || size > MI_MAX_ALLOC_SIZE) { size = (MI_MAX_ALLOC_SIZE / MI_KiB); }+ if (overflow || size > (MI_MAX_ALLOC_SIZE / MI_KiB)) { size = (MI_MAX_ALLOC_SIZE / MI_KiB); }value = (size > LONG_MAX ? LONG_MAX : (long)size);}if (*end == 0) {diff --git a/vendored/mimalloc/src/os.c b/vendored/mimalloc/src/os.cindex 45d1d8ea7..febecb0c9 100644--- a/vendored/mimalloc/src/os.c+++ b/vendored/mimalloc/src/os.c@@ -57,7 +57,7 @@ size_t _mi_os_minimal_purge_size(void) {if (minsize != 0) {return _mi_align_up(minsize, _mi_os_page_size());}- else if (mi_os_mem_config.has_transparent_huge_pages && mi_option_is_enabled(mi_option_allow_thp)) {+ else if (mi_os_mem_config.has_transparent_huge_pages && mi_option_get(mi_option_allow_thp) == 2) {return _mi_os_large_page_size();}else {@@ -106,10 +106,57 @@ void _mi_os_init(void) {bool _mi_os_decommit(void* addr, size_t size);bool _mi_os_commit(void* addr, size_t size, bool* is_zero);+// On systems with enough virtual address bits, we can do efficient aligned allocation by using+// the 2TiB to 30TiB area to allocate those. If we have at least 46 bits of virtual address+// space (64TiB) we use this technique. (but see issue #939)+#if (MI_INTPTR_SIZE >= 8) && !defined(MI_NO_ALIGNED_HINT) // && !defined(WIN32) && !defined(ANDROID)++// Return a MI_HINT_ALIGN (4MiB) aligned address that is probably available.+// If this returns NULL, the OS will determine the address but on some OS's that may not be+// properly aligned which can be more costly as it needs to be adjusted afterwards.+// For a size > 16GiB this always returns NULL in order to guarantee good ASLR randomization;+// (otherwise an initial large allocation of say 2TiB has a 50% chance to include (known) addresses+// in the middle of the 2TiB - 6TiB address range (see issue #372))++#define MI_HINT_ALIGN ((uintptr_t)4 << 20) // 4MiB alignment+#define MI_HINT_BASE ((uintptr_t)2 << 40) // 2TiB start+#define MI_HINT_AREA ((uintptr_t)4 << 40) // upto (2+4) 6TiB (since before win8 there is "only" 8TiB available to processes)+#define MI_HINT_MAX ((uintptr_t)30 << 40) // wrap after 30TiB (area after 32TiB is used for huge OS pages)++void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size)+{+ static mi_decl_cache_align _Atomic(uintptr_t) aligned_base; // = 0++ // todo: perhaps only do alignment hints if THP is enabled?+ if (try_alignment <= mi_os_mem_config.alloc_granularity || try_alignment > MI_HINT_ALIGN) return NULL;+ if (mi_os_mem_config.virtual_address_bits < 46) return NULL; // < 64TiB virtual address space+ size = _mi_align_up(size, MI_HINT_ALIGN);+ if (size > 16*MI_GiB) return NULL; // guarantee the chance of fixed valid address is at least 1/(MI_HINT_AREA / 1<<34)+ size += MI_HINT_ALIGN; // put in virtual gaps between hinted blocks; this splits VLA's but increases guarded areas.++ uintptr_t hint = mi_atomic_add_acq_rel(&aligned_base, size);+ if (hint == 0 || hint > MI_HINT_MAX) { // wrap or initialize+ uintptr_t init = MI_HINT_BASE;+ #if (MI_SECURE>=1 || defined(NDEBUG)) // security: randomize start of aligned allocations unless in debug mode+ mi_theap_t* const theap = _mi_theap_default(); // don't use `mi_theap_get_default()` as that can cause allocation recursively (issue #1267)+ if (!mi_theap_is_initialized(theap)) return NULL; // no hint as we lack randomness at this point+ const uintptr_t r = _mi_theap_random_next(theap);+ init = init + ((MI_HINT_ALIGN * ((r>>17) & 0xFFFFF)) % MI_HINT_AREA); // (randomly 20 bits)*4MiB == 0 to 4TiB+ #endif+ uintptr_t expected = hint + size;+ mi_atomic_cas_strong_acq_rel(&aligned_base, &expected, init);+ hint = mi_atomic_add_acq_rel(&aligned_base, size); // this may still give 0 or > MI_HINT_MAX but that is ok, it is a hint after all+ }+ mi_assert_internal(hint%MI_HINT_ALIGN == 0);+ if (hint%try_alignment != 0) return NULL;+ return (void*)hint;+}+#elsevoid* _mi_os_get_aligned_hint(size_t try_alignment, size_t size) {- MI_UNUSED(try_alignment); MI_UNUSED(size);- return NULL;+ MI_UNUSED(try_alignment); MI_UNUSED(size);+ return NULL;}+#endif/* -----------------------------------------------------------@@ -251,6 +298,13 @@ static void* mi_os_prim_alloc_at(void* hint_addr, size_t size, size_t try_alignmif (size == 0) return NULL;if (!commit) { allow_large = false; }if (try_alignment == 0) { try_alignment = 1; } // avoid 0 to ensure there will be no divide by zero when aligning++ // try to align along large OS page size for larger allocations+ const size_t large_page_size = mi_os_mem_config.large_page_size;+ if (large_page_size > 0 && hint_addr == NULL && size >= 8*large_page_size && _mi_is_power_of_two(try_alignment) && try_alignment < large_page_size) {+ try_alignment = large_page_size;+ }+*is_zero = false;void* p = NULL;int err = _mi_prim_alloc(hint_addr, size, try_alignment, commit, allow_large, is_large, is_zero, &p);@@ -280,27 +334,30 @@ static void* mi_os_prim_alloc(size_t size, size_t try_alignment, bool commit, bo// Primitive aligned allocation from the OS.// This function guarantees the allocated memory is aligned.-static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commit, bool allow_large, bool* is_large, bool* is_zero, void** base) {+static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commit, bool allow_large, mi_memid_t* memid) {+ mi_assert_internal(memid!=NULL);mi_assert_internal(alignment >= _mi_os_page_size() && ((alignment & (alignment - 1)) == 0));mi_assert_internal(size > 0 && (size % _mi_os_page_size()) == 0);- mi_assert_internal(is_large != NULL);- mi_assert_internal(is_zero != NULL);- mi_assert_internal(base != NULL);+ *memid = _mi_memid_none();if (!commit) allow_large = false;if (!(alignment >= _mi_os_page_size() && ((alignment & (alignment - 1)) == 0))) return NULL;size = _mi_align_up(size, _mi_os_page_size());- // try a direct allocation if the alignment is below the default, or if larger than 1/8 fraction of the size.- const bool try_direct_alloc = (alignment <= mi_os_mem_config.alloc_granularity || alignment > size/8);+ // try a direct allocation if the alignment is below the default, or less than or equal to 1/4 fraction of the size.+ const bool try_direct_alloc = (alignment <= mi_os_mem_config.alloc_granularity || alignment <= size/4);+ bool os_is_large = false;+ bool os_is_zero = false;+ void* os_base = NULL;+ size_t os_size = size;void* p = NULL;if (try_direct_alloc) {- p = mi_os_prim_alloc(size, alignment, commit, allow_large, is_large, is_zero);+ p = mi_os_prim_alloc(size, alignment, commit, allow_large, &os_is_large, &os_is_zero);}// aligned already?- if (p != NULL && ((uintptr_t)p % alignment) == 0) {- *base = p;+ if (p != NULL && _mi_is_aligned(p,alignment)) {+ os_base = p;}else {// if not aligned, free it, overallocate, and unmap around it@@ -315,43 +372,47 @@ static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commitif (!mi_os_mem_config.has_partial_free) { // win32 virtualAlloc cannot free parts of an allocated block// over-allocate uncommitted (virtual) memory- p = mi_os_prim_alloc(over_size, 1 /*alignment*/, false /* commit? */, false /* allow_large */, is_large, is_zero);+ p = mi_os_prim_alloc(over_size, 1 /*alignment*/, false /* commit? */, false /* allow_large */, &os_is_large, &os_is_zero);if (p == NULL) return NULL;// set p to the aligned part in the full region- // note: on Windows VirtualFree needs the actual base pointer- // this is handledby having the `base` field in the memid.- *base = p; // remember the base+ // note: Windows VirtualFree needs the actual base pointer+ // this is handled though by having the `base` field in the memid+ os_base = p; // remember the base+ os_size = over_size;p = _mi_align_up_ptr(p, alignment);// explicitly commit only the aligned partif (commit) {if (!_mi_os_commit(p, size, NULL)) {- mi_os_prim_free(*base, over_size, 0, NULL);+ mi_os_prim_free(os_base, over_size, 0, NULL);return NULL;}}}else { // mmap can free inside an allocation// overallocate...- p = mi_os_prim_alloc(over_size, 1, commit, false, is_large, is_zero);+ p = mi_os_prim_alloc(over_size, 1, commit, false, &os_is_large, &os_is_zero);if (p == NULL) return NULL;// and selectively unmap parts around the over-allocated area.- void* aligned_p = _mi_align_up_ptr(p, alignment);- size_t pre_size = (uint8_t*)aligned_p - (uint8_t*)p;- size_t mid_size = _mi_align_up(size, _mi_os_page_size());- size_t post_size = over_size - pre_size - mid_size;+ void* const aligned_p = _mi_align_up_ptr(p, alignment);+ const size_t pre_size = (uint8_t*)aligned_p - (uint8_t*)p;+ const size_t mid_size = _mi_align_up(size, _mi_os_page_size());+ const size_t post_size = over_size - pre_size - mid_size;mi_assert_internal(pre_size < over_size&& post_size < over_size&& mid_size >= size);if (pre_size > 0) { mi_os_prim_free(p, pre_size, (commit ? pre_size : 0), NULL); }if (post_size > 0) { mi_os_prim_free((uint8_t*)aligned_p + mid_size, post_size, (commit ? post_size : 0), NULL); }// we can return the aligned pointer on `mmap` systemsp = aligned_p;- *base = aligned_p; // since we freed the pre part, `*base == p`.+ os_base = aligned_p; // since we freed the pre part, `*base == p`.+ os_size = mid_size;}}- mi_assert_internal(p == NULL || (p != NULL && *base != NULL && ((uintptr_t)p % alignment) == 0));+ mi_assert_internal(p != NULL && os_base != NULL && _mi_is_aligned(p,alignment));+ mi_assert_internal(os_base <= p && size <= os_size);+ *memid = _mi_memid_create_os(os_base,os_size,commit,os_is_zero,os_is_large);return p;}@@ -383,16 +444,9 @@ void* _mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, bool allosize = _mi_os_good_alloc_size(size);alignment = _mi_align_up(alignment, _mi_os_page_size());- bool os_is_large = false;- bool os_is_zero = false;- void* os_base = NULL;- void* p = mi_os_prim_alloc_aligned(size, alignment, commit, allow_large, &os_is_large, &os_is_zero, &os_base );+ void* p = mi_os_prim_alloc_aligned(size, alignment, commit, allow_large, memid );if (p == NULL) return NULL;- *memid = _mi_memid_create_os(p, size, commit, os_is_zero, os_is_large);- memid->mem.os.base = os_base;- memid->mem.os.size += ((uint8_t*)p - (uint8_t*)os_base); // todo: return from prim_alloc_aligned?-mi_assert_internal(memid->mem.os.size >= size);mi_assert_internal(_mi_is_aligned(p,alignment));if (commit) { mi_assert_internal(memid->initially_committed); }@@ -435,6 +489,7 @@ void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t offsemi_assert(offset <= size);mi_assert((alignment % _mi_os_page_size()) == 0);*memid = _mi_memid_none();+ if (offset > size) return NULL;if (offset == 0) {// regular aligned allocationreturn _mi_os_alloc_aligned(size, alignment, commit, allow_large, memid);@@ -442,6 +497,7 @@ void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t offseelse {// overallocate to align at an offsetconst size_t extra = _mi_align_up(offset, alignment) - offset;+ if (size >= SIZE_MAX - extra) return NULL; // too largeconst size_t oversize = size + extra;void* const start = _mi_os_alloc_aligned(oversize, alignment, commit, allow_large, memid);if (start == NULL) return NULL;@@ -449,7 +505,7 @@ void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t offsevoid* const p = (uint8_t*)start + extra;mi_assert(_mi_is_aligned((uint8_t*)p + offset, alignment));// decommit the overallocation at the start- if (commit && extra > _mi_os_page_size()) {+ if (commit && extra >= _mi_os_page_size()) {_mi_os_decommit(start, extra);}return p;@@ -469,9 +525,9 @@ static void* mi_os_page_align_areax(bool conservative, void* addr, size_t size,// page align conservatively within the range, or liberally straddling pages outside the rangevoid* start = (conservative ? _mi_align_up_ptr(addr, _mi_os_page_size())- : mi_align_down_ptr(addr, _mi_os_page_size()));- void* end = (conservative ? mi_align_down_ptr((uint8_t*)addr + size, _mi_os_page_size())- : _mi_align_up_ptr((uint8_t*)addr + size, _mi_os_page_size()));+ : _mi_align_down_ptr(addr, _mi_os_page_size()));+ void* end = (conservative ? _mi_align_down_ptr((uint8_t*)addr + size, _mi_os_page_size())+ : _mi_align_up_ptr((uint8_t*)addr + size, _mi_os_page_size()));ptrdiff_t diff = (uint8_t*)end - (uint8_t*)start;if (diff <= 0) return NULL;@@ -519,7 +575,6 @@ bool _mi_os_commit(void* addr, size_t size, bool* is_zero) {static bool mi_os_decommit_ex(void* addr, size_t size, bool* needs_recommit, size_t stat_size) {mi_assert_internal(needs_recommit!=NULL);- mi_os_stat_decrease(committed, stat_size);// page alignsize_t csize;@@ -532,6 +587,9 @@ static bool mi_os_decommit_ex(void* addr, size_t size, bool* needs_recommit, sizif (err != 0) {_mi_warning_message("cannot decommit OS memory (error: %d (0x%x), address: %p, size: 0x%zx bytes)\n", err, err, start, csize);}+ else if (*needs_recommit) {+ mi_os_stat_decrease(committed, stat_size);+ }mi_assert_internal(err == 0);return (err == 0);}@@ -663,10 +721,16 @@ static uint8_t* mi_os_claim_huge_pages(size_t pages, size_t* total_size) {if (start == 0) {// Initialize the start address after the 32TiB areastart = ((uintptr_t)8 << 40); // 8TiB virtual start address- #if (MI_SECURE>0 || MI_DEBUG==0) // security: randomize start of huge pages unless in debug mode- uintptr_t r = _mi_theap_random_next(_mi_theap_default());- start = start + ((uintptr_t)MI_HUGE_OS_PAGE_SIZE * ((r>>17) & 0x0FFF)); // (randomly 12bits)*1GiB == between 0 to 4TiB- #endif+ #if (MI_SECURE>0 || MI_DEBUG==0) // security: randomize start of huge pages unless in debug mode+ mi_theap_t* const theap = _mi_theap_default(); // don't use `mi_theap_get_default()` as that can cause allocation recursively (issue #1267)+ if (mi_theap_is_initialized(theap)) { // todo: or no hint at all if we lack randomness?+ const uintptr_t r = _mi_theap_random_next(theap);+ start = start + ((uintptr_t)MI_HUGE_OS_PAGE_SIZE * ((r>>17) & 0x0FFF)); // (randomly 12bits)*1GiB == between 0 to 4TiB+ }+ else {+ _mi_warning_message("failed to randomize the start address of huge pages allocation (%zu bytes at %p)", size, start);+ }+ #endif}end = start + size;} while (!mi_atomic_cas_weak_acq_rel(&mi_huge_start, &huge_start, end));@@ -739,16 +803,17 @@ void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_mse}}}- mi_assert_internal(page*MI_HUGE_OS_PAGE_SIZE <= size);+ const size_t allocated = page * MI_HUGE_OS_PAGE_SIZE;+ mi_assert_internal(allocated <= size);if (pages_reserved != NULL) { *pages_reserved = page; }- if (psize != NULL) { *psize = page * MI_HUGE_OS_PAGE_SIZE; }+ if (psize != NULL) { *psize = allocated; }if (page != 0) {mi_assert(start != NULL);- *memid = _mi_memid_create_os(start, size, true /* is committed */, all_zero, true /* is_large */);+ *memid = _mi_memid_create_os(start, allocated, true /* is committed */, all_zero, true /* is_large */);memid->memkind = MI_MEM_OS_HUGE;mi_assert(memid->is_pinned);#ifdef MI_TRACK_ASAN- if (all_zero) { mi_track_mem_defined(start,size); }+ if (all_zero) { mi_track_mem_defined(start,allocated); }#endif}return (page == 0 ? NULL : start);diff --git a/vendored/mimalloc/src/page-map.c b/vendored/mimalloc/src/page-map.cindex d8393e72b..acc0ee9f7 100644--- a/vendored/mimalloc/src/page-map.c+++ b/vendored/mimalloc/src/page-map.c@@ -42,6 +42,9 @@ bool _mi_page_map_init(void) {if (vbits >= 48) { vbits = 47; }#endif}+ if (vbits < MI_ARENA_SLICE_SHIFT) {+ vbits = MI_ARENA_SLICE_SHIFT;+ }// Allocate the page map and commit bitsmi_page_map_max_address = (void*)(vbits >= MI_SIZE_BITS ? (SIZE_MAX - MI_ARENA_SLICE_SIZE + 1) : (MI_PU(1) << vbits));@@ -127,13 +130,13 @@ static size_t mi_page_map_get_idx(mi_page_t* page, uint8_t** page_start, size_t*size_t page_size;*page_start = mi_page_area(page, &page_size);if (page_size > MI_LARGE_PAGE_SIZE) { page_size = MI_LARGE_PAGE_SIZE - MI_ARENA_SLICE_SIZE; } // furthest interior pointer- *slice_count = mi_slice_count_of_size(page_size) + (((uint8_t*)*page_start - (uint8_t*)page)/MI_ARENA_SLICE_SIZE); // add for large aligned blocks+ *slice_count = mi_slice_count_of_size(page_size) + ((*page_start - mi_page_slice_start(page))/MI_ARENA_SLICE_SIZE); // add for large aligned blocksreturn _mi_page_map_index(page);}bool _mi_page_map_register(mi_page_t* page) {mi_assert_internal(page != NULL);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));mi_assert_internal(_mi_page_map != NULL); // should be initialized before multi-thread access!if mi_unlikely(_mi_page_map == NULL) {if (!_mi_page_map_init()) return false;@@ -193,7 +196,7 @@ mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_att// A 2-level page map#define MI_PAGE_MAP_SUB_SIZE (MI_PAGE_MAP_SUB_COUNT * sizeof(mi_page_t*))-#define MI_PAGE_MAP_ENTRIES_PER_CBIT (MI_PAGE_MAP_COUNT / MI_BFIELD_BITS)+#define MI_PAGE_MAP_ENTRIES_PER_CBIT (MI_PAGE_MAP_COUNT < MI_BFIELD_BITS ? 1 : (MI_PAGE_MAP_COUNT / MI_BFIELD_BITS))mi_decl_cache_align _Atomic(mi_submap_t)* _mi_page_map;static size_t mi_page_map_count;@@ -236,6 +239,9 @@ bool _mi_page_map_init(void) {if (vbits >= 48) { vbits = 47; }#endif}+ if (vbits < MI_PAGE_MAP_SUB_SHIFT + MI_ARENA_SLICE_SHIFT) {+ vbits = MI_PAGE_MAP_SUB_SHIFT + MI_ARENA_SLICE_SHIFT;+ }// Allocate the page map and commit bitsmi_assert(MI_MAX_VABITS >= vbits);@@ -308,7 +314,7 @@ void _mi_page_map_unsafe_destroy(mi_subproc_t* subproc) {mi_page_map_count = 0;mi_page_map_memid = _mi_memid_none();mi_page_map_max_address = NULL;- mi_atomic_store_release(&mi_page_map_commit, 0);+ mi_atomic_store_release(&mi_page_map_commit, (mi_bfield_t)0);}@@ -383,13 +389,13 @@ static size_t mi_page_map_get_idx(mi_page_t* page, size_t* sub_idx, size_t* slicsize_t page_size;uint8_t* page_start = mi_page_area(page, &page_size);if (page_size > MI_LARGE_PAGE_SIZE) { page_size = MI_LARGE_PAGE_SIZE - MI_ARENA_SLICE_SIZE; } // furthest interior pointer- *slice_count = mi_slice_count_of_size(page_size) + ((page_start - (uint8_t*)page)/MI_ARENA_SLICE_SIZE); // add for large aligned blocks- return _mi_page_map_index(page, sub_idx);+ *slice_count = mi_slice_count_of_size(page_size) + ((page_start - mi_page_slice_start(page))/MI_ARENA_SLICE_SIZE); // add for large aligned blocks+ return _mi_page_map_index(page_start, sub_idx);}bool _mi_page_map_register(mi_page_t* page) {mi_assert_internal(page != NULL);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));mi_assert_internal(_mi_page_map != NULL); // should be initialized before multi-thread access!if mi_unlikely(_mi_page_map == NULL) {if (!_mi_page_map_init()) return false;@@ -404,7 +410,7 @@ bool _mi_page_map_register(mi_page_t* page) {void _mi_page_map_unregister(mi_page_t* page) {mi_assert_internal(_mi_page_map != NULL);mi_assert_internal(page != NULL);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));if mi_unlikely(_mi_page_map == NULL) return;// get index and countsize_t slice_count;diff --git a/vendored/mimalloc/src/page-queue.c b/vendored/mimalloc/src/page-queue.cindex 4c54cb9a2..731672b02 100644--- a/vendored/mimalloc/src/page-queue.c+++ b/vendored/mimalloc/src/page-queue.c@@ -115,9 +115,12 @@ mi_decl_nodiscard mi_decl_export size_t mi_good_size(size_t size) mi_attr_noexceif (size <= MI_LARGE_MAX_OBJ_SIZE) {return _mi_bin_size(mi_bin(size + MI_PADDING_SIZE));}- else {+ else if (size <= MI_MAX_ALLOC_SIZE) {return _mi_align_up(size + MI_PADDING_SIZE,_mi_os_page_size());}+ else {+ return size;+ }}#if (MI_DEBUG>1)@@ -205,25 +208,25 @@ static mi_page_queue_t* mi_page_queue_of(const mi_page_t* page) {// range of entries in `_mi_page_small_free`.static inline void mi_theap_queue_first_update(mi_theap_t* theap, const mi_page_queue_t* pq) {mi_assert_internal(mi_theap_contains_queue(theap,pq));- size_t size = pq->block_size;+ const size_t size = pq->block_size;if (size > MI_SMALL_SIZE_MAX) return;mi_page_t* page = pq->first;if (pq->first == NULL) page = (mi_page_t*)&_mi_page_empty;// find index in the right direct page array- size_t start;- size_t idx = _mi_wsize_from_size(size);- mi_page_t** pages_free = theap->pages_free_direct;-+ const size_t idx = _mi_wsize_from_size(size);+ mi_page_t** const pages_free = theap->pages_free_direct;if (pages_free[idx] == page) return; // already set// find start slot+ size_t start;if (idx<=1) {start = 0;}else {// find previous size; due to minimal alignment upto 3 previous bins may need to be skipped+ mi_assert_internal(pq > &theap->pages[0]); // since idx > 1size_t bin = mi_bin(size);const mi_page_queue_t* prev = pq - 1;while( bin == mi_bin(prev->block_size) && prev > &theap->pages[0]) {diff --git a/vendored/mimalloc/src/page.c b/vendored/mimalloc/src/page.cindex 8f9fbab28..97d2fc279 100644--- a/vendored/mimalloc/src/page.c+++ b/vendored/mimalloc/src/page.c@@ -41,10 +41,12 @@ static bool mi_page_extend_free(mi_theap_t* theap, mi_page_t* page);#if (MI_DEBUG>=3)static size_t mi_page_list_count(mi_page_t* page, mi_block_t* head) {- mi_assert_internal(_mi_ptr_page(page) == page);+ mi_assert_internal(_mi_ptr_page(page->page_start) == page);+ const uint8_t* slice_start = mi_page_slice_start(page);+ mi_assert_internal(_mi_is_aligned(slice_start,MI_PAGE_ALIGN));size_t count = 0;while (head != NULL) {- mi_assert_internal((uint8_t*)head - (uint8_t*)page > (ptrdiff_t)MI_LARGE_PAGE_SIZE || page == _mi_ptr_page(head));+ mi_assert_internal((uint8_t*)head - slice_start > (ptrdiff_t)MI_LARGE_PAGE_SIZE || page == _mi_ptr_page(head));count++;head = mi_block_next(page, head);}@@ -152,10 +154,15 @@ static void mi_page_thread_collect_to_local(mi_page_t* page, mi_block_t* head)}// if `count > max_count` there was a memory corruption (possibly infinite list due to double multi-threaded free)- if (count > max_count) {+ if mi_unlikely(count > max_count) {_mi_error_message(EFAULT, "corrupted thread-free list\n");return; // the thread-free items cannot be freed}+ // if `count > page->used` there was another kind memory corruption (either in the page meta-data or in the linked list)+ else if mi_unlikely(count > page->used) {+ _mi_error_message(EFAULT, "corrupted meta-data in thread-free list\n");+ return; // the thread-free items cannot be freed+ }// and append the current local free listmi_block_set_next(page, last, page->local_free);@@ -279,8 +286,8 @@ void _mi_page_reclaim(mi_theap_t* theap, mi_page_t* page) {// called from `mi_free` on a reclaim, and fresh_alloc if we get an abandoned pagevoid _mi_theap_page_reclaim(mi_theap_t* theap, mi_page_t* page){- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);mi_assert_internal(mi_page_is_owned(page));mi_assert_internal(mi_page_is_abandoned(page));@@ -608,7 +615,7 @@ static mi_decl_noinline void mi_page_free_list_extend( mi_page_t* const page, co----------------------------------------------------------- */#define MI_MAX_EXTEND_SIZE (4*1024) // heuristic, one OS page seems to work well.-#if (MI_SECURE>=3)+#if (MI_SECURE>=2)#define MI_MIN_EXTEND (8*MI_SECURE) // extend at least by this many#else#define MI_MIN_EXTEND (1)@@ -667,7 +674,7 @@ static bool mi_page_extend_free(mi_theap_t* theap, mi_page_t* page) {}// and append the extend the free list- if (extend < MI_MIN_SLICES || MI_SECURE<3) { //!mi_option_is_enabled(mi_option_secure)) {+ if (extend < MI_MIN_SLICES || MI_SECURE<2) { //!mi_option_is_enabled(mi_option_secure)) {mi_page_free_list_extend(page, bsize, extend );}else {@@ -686,7 +693,7 @@ static bool mi_page_extend_free(mi_theap_t* theap, mi_page_t* page) {mi_decl_nodiscard bool _mi_page_init(mi_theap_t* theap, mi_page_t* page) {mi_assert(page != NULL);mi_assert(theap!=NULL);- page->heap = (_mi_is_heap_main(theap->heap) ? NULL : theap->heap); // faster for `mi_page_associated_theap`+ page->heap = (_mi_is_heap_main(_mi_theap_heap(theap)) ? NULL : _mi_theap_heap(theap)); // faster for `mi_page_associated_theap`mi_page_set_theap(page, theap);size_t page_size;@@ -856,7 +863,7 @@ static mi_page_t* mi_find_free_page(mi_theap_t* theap, mi_page_queue_t* pq) {// check the first page: we even do this with candidate search or otherwise we re-search every timemi_page_t* page = pq->first;if mi_likely(page != NULL && mi_page_free_quick_collect(page)) {- #if (MI_SECURE>=3) // in secure mode, we extend half the time to increase randomness+ #if (MI_SECURE>=2) // in secure mode, we extend half the time to increase randomnessif (page->capacity < page->reserved && ((_mi_theap_random_next(theap) & 1) == 1)) {(void)mi_page_extend_free(theap, page); // ok if this failsmi_assert_internal(mi_page_immediate_available(page));@@ -878,21 +885,24 @@ static mi_page_t* mi_find_free_page(mi_theap_t* theap, mi_page_queue_t* pq) {a certain number of allocations.----------------------------------------------------------- */-static mi_deferred_free_fun* volatile deferred_free = NULL;-static _Atomic(void*) deferred_arg; // = NULL+// The program should only install a single deferred free handler before doing allocation.+static _Atomic(void*) deferred_free; // is `mi_deferred_free_fun*` (but some platforms don't support atomic function pointers)+static _Atomic(void*) deferred_arg;void _mi_deferred_free(mi_theap_t* theap, bool force) {theap->heartbeat++;- if (deferred_free != NULL && !theap->tld->recurse) {+ mi_deferred_free_fun* const fun = (mi_deferred_free_fun*)mi_atomic_load_ptr_acquire(void,&deferred_free);+ if (fun != NULL && !theap->tld->recurse) {theap->tld->recurse = true;- deferred_free(force, theap->heartbeat, mi_atomic_load_ptr_relaxed(void,&deferred_arg));+ void* const arg = mi_atomic_load_ptr_acquire(void,&deferred_arg);+ fun(force, theap->heartbeat, arg);theap->tld->recurse = false;}}void mi_register_deferred_free(mi_deferred_free_fun* fn, void* arg) mi_attr_noexcept {- deferred_free = fn;mi_atomic_store_ptr_release(void,&deferred_arg, arg);+ mi_atomic_store_ptr_release(void,&deferred_free, (void*)fn);}@@ -1013,8 +1023,8 @@ void* _mi_malloc_generic(mi_theap_t* theap, size_t size, size_t zero_huge_alignmmi_assert_internal(mi_page_immediate_available(page));mi_assert_internal(mi_page_block_size(page) >= size);- mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));- mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_is_aligned(mi_page_slice_start(page), MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);// and try again, this time succeeding! (i.e. this should never recurse through _mi_page_malloc)if (usable!=NULL) { *usable = mi_page_usable_block_size(page); }diff --git a/vendored/mimalloc/src/prim/emscripten/prim.c b/vendored/mimalloc/src/prim/emscripten/prim.cindex ab3d59eed..1ba0936e0 100644--- a/vendored/mimalloc/src/prim/emscripten/prim.c+++ b/vendored/mimalloc/src/prim/emscripten/prim.c@@ -12,6 +12,9 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc/atomic.h"#include "mimalloc/prim.h"+#include <sched.h> // sched_yield+#include <unistd.h> // getentropy+// Design// ======//@@ -223,7 +226,9 @@ void _mi_prim_thread_init_auto_done(void) {}void _mi_prim_thread_done_auto_done(void) {- // nothing to do+ if (_mi_heap_default_key != (pthread_key_t)(-1)) { // do not leak the key, see issue #809+ pthread_key_delete(_mi_heap_default_key);+ }}void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {@@ -250,3 +255,7 @@ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {bool _mi_prim_thread_is_in_threadpool(void) {return false;}++void _mi_prim_thread_yield(void) {+ sched_yield();+}diff --git a/vendored/mimalloc/src/prim/osx/alloc-override-zone.c b/vendored/mimalloc/src/prim/osx/alloc-override-zone.cindex aa971c39f..fdbe095c2 100644--- a/vendored/mimalloc/src/prim/osx/alloc-override-zone.c+++ b/vendored/mimalloc/src/prim/osx/alloc-override-zone.c@@ -41,10 +41,18 @@ extern malloc_zone_t* malloc_default_purgeable_zone(void) __attribute__((weak_immalloc zone members------------------------------------------------------ */+static bool is_mimalloc_zone( malloc_zone_t* zone );+static size_t zone_size(malloc_zone_t* zone, const void* p) {- MI_UNUSED(zone);- if (!mi_is_in_heap_region(p)){ return 0; } // not our pointer, bail out- return mi_usable_size(p);+ if (mi_any_heap_contains(p)) {+ return mi_usable_size(p);+ }+ else if (!is_mimalloc_zone(zone)) { // can happen due to interpose+ return zone->size(zone,p);+ }+ else {+ return 0;+ }}static void* zone_malloc(malloc_zone_t* zone, size_t size) {@@ -63,14 +71,24 @@ static void* zone_valloc(malloc_zone_t* zone, size_t size) {}static void zone_free(malloc_zone_t* zone, void* p) {- MI_UNUSED(zone);- // mi_cfree(p); // checked free as `zone_free` may be called with invalid pointers- mi_free(p); // with the page_map and pagemap_commit=1 we can use the regular free+ if (mi_any_heap_contains(p)) {+ mi_free(p); // with the page_map and pagemap_commit=1 we can use the regular free+ }+ else if (!is_mimalloc_zone(zone)) { // can happen due to interpose+ zone->free(zone,p);+ }}static void* zone_realloc(malloc_zone_t* zone, void* p, size_t newsize) {- MI_UNUSED(zone);- return mi_realloc(p, newsize);+ if (p == NULL || mi_any_heap_contains(p)) {+ return mi_realloc(p, newsize);+ }+ else if (!is_mimalloc_zone(zone)) { // can happen due to interpose+ return zone->realloc(zone,p,newsize);+ }+ else {+ return NULL;+ }}static void* zone_memalign(malloc_zone_t* zone, size_t alignment, size_t size) {@@ -79,8 +97,9 @@ static void* zone_memalign(malloc_zone_t* zone, size_t alignment, size_t size) {}static void zone_destroy(malloc_zone_t* zone) {- MI_UNUSED(zone);- // todo: ignore for now?+ if (!is_mimalloc_zone(zone)) {+ zone->destroy(zone);+ }}static unsigned zone_batch_malloc(malloc_zone_t* zone, size_t size, void** ps, unsigned count) {@@ -241,6 +260,9 @@ static malloc_zone_t mi_malloc_zone = {}#endif+static bool is_mimalloc_zone( malloc_zone_t* zone ) {+ return (zone==NULL || zone==&mi_malloc_zone);+}#if defined(MI_OSX_INTERPOSE) && defined(MI_SHARED_LIB_EXPORT)@@ -254,11 +276,8 @@ static malloc_zone_t mi_malloc_zone = {// `malloc_zone_calloc` etc. see <https://github.com/aosm/libmalloc/blob/master/man/malloc_zone_malloc.3>// -------------------------------------------------------static inline malloc_zone_t* mi_get_default_zone(void)-{- static bool init;- if mi_unlikely(!init) {- init = true;+static inline malloc_zone_t* mi_get_default_zone(void) {+ mi_atomic_do_once {malloc_zone_register(&mi_malloc_zone); // by calling register we avoid a zone error on free (see <http://eatmyrandom.blogspot.com/2010/03/mallocfree-interception-on-mac-os-x.html>)}return &mi_malloc_zone;@@ -329,7 +348,7 @@ static bool zone_check(malloc_zone_t* zone) {static malloc_zone_t* zone_from_ptr(const void* p) {MI_UNUSED(p);- return mi_get_default_zone();+ return (mi_any_heap_contains(p) ? mi_get_default_zone() : NULL);}static void zone_log(malloc_zone_t* zone, void* p) {diff --git a/vendored/mimalloc/src/prim/unix/prim.c b/vendored/mimalloc/src/prim/unix/prim.cindex ba8dfb1f8..bec22c0ba 100644--- a/vendored/mimalloc/src/prim/unix/prim.c+++ b/vendored/mimalloc/src/prim/unix/prim.c@@ -25,7 +25,7 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc/prim.h"#include <sys/mman.h> // mmap-#include <unistd.h> // sysconf+#include <unistd.h> // sysconf, sleep#include <fcntl.h> // open, close, read, access#include <stdlib.h> // getenv, arc4random_buf@@ -185,8 +185,16 @@ static void unix_detect_physical_memory( size_t page_size, size_t* physical_memoMI_UNUSED(page_size);struct sysinfo info; _mi_memzero_var(info);const int err = sysinfo(&info);- if (err==0 && info.totalram > 0 && info.totalram <= SIZE_MAX) {- *physical_memory_in_kib = (size_t)info.totalram / MI_KiB;+ if (err==0 && info.mem_unit > 0 && info.totalram <= SIZE_MAX) {+ if (info.mem_unit==MI_KiB) {+ *physical_memory_in_kib = (size_t)info.totalram;+ }+ else {+ size_t total = 0;+ if (!mi_mul_overflow((size_t)info.totalram, (size_t)info.mem_unit, &total)) {+ *physical_memory_in_kib = (total / MI_KiB);+ }+ }}#elif defined(_SC_PHYS_PAGES) // do not use by default as it might cause allocation (by using `fopen` to parse /proc/meminfo) (issue #1100)const long pphys = sysconf(_SC_PHYS_PAGES);@@ -213,19 +221,13 @@ void _mi_prim_mem_init( mi_os_mem_config_t* config )// disable transparent huge pages for this process?#if (defined(__linux__) || defined(__ANDROID__)) && defined(PR_GET_THP_DISABLE)- #if defined(MI_NO_THP)- if (true)- #elseif (!mi_option_is_enabled(mi_option_allow_thp)) // disable THP if requested through an option- #endif{config->has_transparent_huge_pages = false;- int val = 0;- if (prctl(PR_GET_THP_DISABLE, &val, 0, 0, 0) != 0) {+ if (prctl(PR_GET_THP_DISABLE, 0, 0, 0, 0) == 0) { // -1 on error, 1 if already disabled// Most likely since distros often come with always/madvise settings.- val = 1;// Disabling only for mimalloc process rather than touching system wide settings- (void)prctl(PR_SET_THP_DISABLE, &val, 0, 0, 0);+ (void)prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);}}#endif@@ -247,15 +249,17 @@ int _mi_prim_free(void* addr, size_t size ) {// mmap//---------------------------------------------+// return errno on failurestatic int unix_madvise(void* addr, size_t size, int advice) {#if defined(__sun)- int res = madvise((caddr_t)addr, size, advice); // Solaris needs cast (issue #520)+ const int res = madvise((caddr_t)addr, size, advice); // Solaris needs cast (issue #520)+ return (res==0 ? 0 : errno);#elif defined(__QNX__)- int res = posix_madvise(addr, size, advice);+ return posix_madvise(addr, size, advice); // posix returns errno#else- int res = madvise(addr, size, advice);- #endif+ const int res = madvise(addr, size, advice); // linux returns -1 on failure and sets errnoreturn (res==0 ? 0 : errno);+ #endif}static void* unix_mmap_prim(void* addr, size_t size, int protect_flags, int flags, int fd) {@@ -436,10 +440,6 @@ int _mi_prim_alloc(void* hint_addr, size_t size, size_t try_alignment, bool commmi_assert_internal(size > 0 && (size % _mi_os_page_size()) == 0);mi_assert_internal(commit || !allow_large);mi_assert_internal(try_alignment > 0);- if (hint_addr == NULL && size >= 8*MI_UNIX_LARGE_PAGE_SIZE && try_alignment > 1 && _mi_is_power_of_two(try_alignment) && try_alignment < MI_UNIX_LARGE_PAGE_SIZE) {- try_alignment = MI_UNIX_LARGE_PAGE_SIZE; // try to align along large page size for larger allocations- }-*is_zero = true;int protect_flags = (commit ? (PROT_WRITE | PROT_READ) : PROT_NONE);*addr = unix_mmap(hint_addr, size, try_alignment, protect_flags, false, allow_large, is_large);@@ -452,7 +452,7 @@ int _mi_prim_alloc(void* hint_addr, size_t size, size_t try_alignment, bool comm//---------------------------------------------static void unix_mprotect_hint(int err) {- #if defined(__linux__) && (MI_SECURE>=2) // guard page around every mimalloc page+ #if defined(__linux__) && (MI_SECURE>=5) // guard page around every mimalloc pageif (err == ENOMEM) {_mi_warning_message("The next warning may be caused by a low memory map limit.\n"" On Linux this is controlled by the vm.max_map_count -- maybe increase it?\n"@@ -533,8 +533,8 @@ int _mi_prim_reset(void* start, size_t size) {// default `MADV_DONTNEED` is used though.static _Atomic(size_t) advice = MI_ATOMIC_VAR_INIT(MADV_FREE);int oadvice = (int)mi_atomic_load_relaxed(&advice);- while ((err = unix_madvise(start, size, oadvice)) != 0 && errno == EAGAIN) { errno = 0; };- if (err != 0 && errno == EINVAL && oadvice == MADV_FREE) {+ while ((err = unix_madvise(start, size, oadvice)) != 0 && err == EAGAIN) { /* try again */ };+ if (err == EINVAL && oadvice == MADV_FREE) {// if MADV_FREE is not supported, fall back to MADV_DONTNEED from now onmi_atomic_store_release(&advice, (size_t)MADV_DONTNEED);err = unix_madvise(start, size, MADV_DONTNEED);@@ -989,3 +989,7 @@ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {bool _mi_prim_thread_is_in_threadpool(void) {return false;}++void _mi_prim_thread_yield(void) {+ sleep(0);+}diff --git a/vendored/mimalloc/src/prim/wasi/prim.c b/vendored/mimalloc/src/prim/wasi/prim.cindex 4e6270dde..790daff02 100644--- a/vendored/mimalloc/src/prim/wasi/prim.c+++ b/vendored/mimalloc/src/prim/wasi/prim.c@@ -13,6 +13,7 @@ terms of the MIT license. A copy of the license can be found in the file#include <stdio.h> // fputs#include <stdlib.h> // getenv+#include <unistd.h> // sbrk, sleep//---------------------------------------------// Initialize@@ -42,8 +43,6 @@ int _mi_prim_free(void* addr, size_t size ) {//---------------------------------------------#if defined(MI_USE_SBRK)- #include <unistd.h> // for sbrk-static void* mi_memory_grow( size_t size ) {void* p = sbrk(size);if (p == (void*)(-1)) return NULL;@@ -89,7 +88,7 @@ static void* mi_prim_mem_grow(size_t size, size_t try_alignment) {{void* current = mi_memory_grow(0); // get current sizeif (current != NULL) {- void* aligned_current = mi_align_up_ptr(current, try_alignment); // and align from there to minimize wasted space+ void* aligned_current = _mi_align_up_ptr(current, try_alignment); // and align from there to minimize wasted spacealloc_size = _mi_align_up( ((uint8_t*)aligned_current - (uint8_t*)current) + size, _mi_os_page_size());base = mi_memory_grow(alloc_size);}@@ -98,7 +97,7 @@ static void* mi_prim_mem_grow(size_t size, size_t try_alignment) {pthread_mutex_unlock(&mi_theap_grow_mutex);#endifif (base != NULL) {- p = mi_align_up_ptr(base, try_alignment);+ p = _mi_align_up_ptr(base, try_alignment);if ((uint8_t*)p + size > (uint8_t*)base + alloc_size) {// another thread used wasm_memory_grow/sbrk in-between and we do not have enough// space after alignment. Give up (and waste the space as we cannot shrink :-( )@@ -286,3 +285,7 @@ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {bool _mi_prim_thread_is_in_threadpool(void) {return false;}++void _mi_prim_thread_yield(void) {+ sleep(0);+}diff --git a/vendored/mimalloc/src/prim/windows/prim.c b/vendored/mimalloc/src/prim/windows/prim.cindex 27d0a38ed..51ad3104f 100644--- a/vendored/mimalloc/src/prim/windows/prim.c+++ b/vendored/mimalloc/src/prim/windows/prim.c@@ -11,6 +11,7 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc/internal.h"#include "mimalloc/prim.h"#include <stdio.h> // fputs, stderr+#include <stdlib.h> // atexit// xbox has no console IO#if !defined(WINAPI_FAMILY_PARTITION) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM)@@ -86,15 +87,13 @@ typedef BOOL (__stdcall *PGetPhysicallyInstalledSystemMemory)( PULONGLONG TotalMtypedef BOOL (__stdcall* PGetVersionExW)(LPOSVERSIONINFOW lpVersionInformation);+//---------------------------------------------// Enable large page support dynamically (if possible)//----------------------------------------------static bool win_enable_large_os_pages(size_t* large_page_size)+static bool win_enable_large_os_pages_once(size_t* large_page_size){- static bool large_initialized = false;- if (large_initialized) return (_mi_os_large_page_size() > 0);- large_initialized = true;if (pGetLargePageMinimum==NULL) return false; // no large page support (xbox etc.)// Try to see if large OS pages are supported@@ -128,6 +127,13 @@ static bool win_enable_large_os_pages(size_t* large_page_size)return (ok!=0);}+static bool win_enable_large_os_pages(size_t* large_page_size) {+ mi_atomic_do_once {+ win_enable_large_os_pages_once(large_page_size);+ }+ return (_mi_os_large_page_size() > 0);+}+//---------------------------------------------// Initialize@@ -417,8 +423,8 @@ static void* _mi_prim_alloc_huge_os_pagesx(void* hint_addr, size_t size, int numMI_MEM_EXTENDED_PARAMETER params[3] = { {{0,0},{0}},{{0,0},{0}},{{0,0},{0}} };// on modern Windows try use NtAllocateVirtualMemoryEx for 1GiB huge pages- static bool mi_huge_pages_available = true;- if (pNtAllocateVirtualMemoryEx != NULL && mi_huge_pages_available) {+ static _Atomic(size_t) mi_huge_pages_available = MI_ATOMIC_VAR_INIT(1);+ if (pNtAllocateVirtualMemoryEx != NULL && mi_atomic_load_acquire(&mi_huge_pages_available) != 0) {params[0].Type.Type = MiMemExtendedParameterAttributeFlags;params[0].Arg.ULong64 = MI_MEM_EXTENDED_PARAMETER_NONPAGED_HUGE;ULONG param_count = 1;@@ -435,7 +441,7 @@ static void* _mi_prim_alloc_huge_os_pagesx(void* hint_addr, size_t size, int num}else {// fall back to regular large pages- mi_huge_pages_available = false; // don't try further huge pages+ mi_atomic_store_release(&mi_huge_pages_available,0); // don't try further huge pages_mi_warning_message("unable to allocate using huge (1GiB) pages, trying large (2MiB) pages instead (status 0x%lx)\n", err);}}@@ -561,10 +567,11 @@ void _mi_prim_process_info(mi_process_info_t* pinfo)pinfo->stime = filetime_msecs(&st);// load psapi on demand- if (pGetProcessMemoryInfo == NULL) {+ mi_atomic_do_once {HINSTANCE hDll = LoadLibrary(TEXT("psapi.dll"));if (hDll != NULL) {pGetProcessMemoryInfo = (PGetProcessMemoryInfo)(void (*)(void))GetProcAddress(hDll, "GetProcessMemoryInfo");+ // FreeLibrary(hDll); // don't free}}@@ -630,7 +637,7 @@ void _mi_prim_out_stderr( const char* msg )// Note: on windows, environment names are not case sensitive.bool _mi_prim_getenv(const char* name, char* result, size_t result_size) {result[0] = 0;- size_t len = GetEnvironmentVariableA(name, result, (DWORD)result_size);+ const size_t len = GetEnvironmentVariableA(name, result, (DWORD)result_size);return (len > 0 && len < result_size);}@@ -663,13 +670,16 @@ typedef LONG (NTAPI *PBCryptGenRandom)(HANDLE, PUCHAR, ULONG, ULONG);static PBCryptGenRandom pBCryptGenRandom = NULL;bool _mi_prim_random_buf(void* buf, size_t buf_len) {- if (pBCryptGenRandom == NULL) {+ mi_assert(buf_len <= ULONG_MAX);+ if (buf_len > ULONG_MAX) return false;+ mi_atomic_do_once {HINSTANCE hDll = LoadLibrary(TEXT("bcrypt.dll"));if (hDll != NULL) {pBCryptGenRandom = (PBCryptGenRandom)(void (*)(void))GetProcAddress(hDll, "BCryptGenRandom");+ // FreeLibrary(hDll); // don't free}- if (pBCryptGenRandom == NULL) return false;}+ if (pBCryptGenRandom == NULL) return false;return (pBCryptGenRandom(NULL, (PUCHAR)buf, (ULONG)buf_len, BCRYPT_USE_SYSTEM_PREFERRED_RNG) >= 0);}@@ -693,47 +703,22 @@ bool _mi_prim_thread_is_in_threadpool(void) {return false;}+void _mi_prim_thread_yield(void) {+ SwitchToThread();+}//----------------------------------------------------------------// Process & Thread Init/Done//-----------------------------------------------------------------#if MI_WIN_USE_FIXED_TLS==1-mi_decl_cache_align size_t _mi_win_tls_offset = 0;-#endif-//static void mi_debug_out(const char* s) {// HANDLE h = GetStdHandle(STD_ERROR_HANDLE);// WriteConsole(h, s, (DWORD)_mi_strlen(s), NULL, NULL);//}-static void mi_win_tls_init(DWORD reason) {- if (reason==DLL_PROCESS_ATTACH || reason==DLL_THREAD_ATTACH) {- #if MI_WIN_USE_FIXED_TLS==1 // we must allocate a TLS slot dynamically- if (_mi_win_tls_offset == 0 && reason == DLL_PROCESS_ATTACH) {- const DWORD tls_slot = TlsAlloc(); // usually returns slot 1- if (tls_slot == TLS_OUT_OF_INDEXES) {- _mi_error_message(EFAULT, "unable to allocate the a TLS slot (rebuild without MI_WIN_USE_FIXED_TLS?)\n");- }- _mi_win_tls_offset = (size_t)tls_slot * sizeof(void*);- }- #endif- #if MI_HAS_TLS_SLOT >= 2 // we must initialize the TLS slot before any allocation- if (_mi_theap_default() == NULL) {- _mi_theap_default_set((mi_theap_t*)&_mi_theap_empty);- #if MI_DEBUG && MI_WIN_USE_FIXED_TLS==1- void* const p = TlsGetValue((DWORD)(_mi_win_tls_offset / sizeof(void*)));- mi_assert_internal(p == (void*)&_mi_theap_empty);- #endif- }- #endif- }-}-static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {MI_UNUSED(reserved);MI_UNUSED(module);- mi_win_tls_init(reason);if (reason==DLL_PROCESS_ATTACH) {_mi_auto_process_init();}@@ -746,7 +731,223 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {}-#if defined(MI_SHARED_LIB)+/* -----------------------------------------------------------------------+ Auto initialize and finalize mimalloc on process and thread start/end.+ By default we use a combination of CRT init and TLS sections for+ both static and dynamic linkage (`MI_WIN_INIT_USE_CRT_TLS`).+------------------------------------------------------------------------- */+#if !defined(MI_WIN_INIT_USE_CRT_TLS) && !defined(MI_WIN_INIT_USE_RAW_DLLMAIN) && !defined(MI_WIN_INIT_USE_TLS_DLLMAIN) && !defined(MI_WIN_INIT_USE_FLS)+ #if !defined(__INTEL_LLVM_COMPILER) && !defined(__INTEL_COMPILER)+ #define MI_WIN_INIT_USE_CRT_TLS 1+ #else+ #define MI_WIN_INIT_USE_TLS_DLLMAIN 1 /* default for Intel ICX, see issue #1268 */+ #endif+#endif++#if defined(MI_WIN_INIT_USE_CRT_TLS)+ #define MI_PRIM_HAS_PROCESS_ATTACH 1+ // nothing to do since `_mi_thread_done` is handled through the DLL_THREAD_DETACH event.+ void _mi_prim_thread_init_auto_done(void) {}+ void _mi_prim_thread_done_auto_done(void) {}+ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);+ }++ static bool mi_module_is_dll(PVOID mod) {+ if (mod==NULL) return false;+ PIMAGE_DOS_HEADER imageDosHeader = (PIMAGE_DOS_HEADER)mod;+ PIMAGE_NT_HEADERS imageNtHeaders = (PIMAGE_NT_HEADERS)((unsigned char*)imageDosHeader + imageDosHeader->e_lfanew);+ return ((imageNtHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL) == IMAGE_FILE_DLL);+ }++ static bool mi_current_module_is_dll(void) {+ HMODULE mod = NULL;+ const BOOL ok = GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)mi_current_module_is_dll, &mod);+ return (ok && mi_module_is_dll(mod));+ }++ // Hook into CRT initialization and finalization.+ static void mi_cdecl mi_crt_done(void) {+ // mi_debug_out(mi_current_module_is_dll() ? "crt dll done\n" : "crt exe done\n");+ mi_win_main(NULL, DLL_PROCESS_DETACH, 0);+ }++ static int mi_cdecl mi_crt_init(void) {+ // mi_debug_out(mi_current_module_is_dll() ? "crt dll init\n" : "crt exe init\n");+ if (mi_current_module_is_dll()) {+ // in a dll, atexit (crt_done) is called after tls process detach+ atexit(&mi_crt_done);+ }+ return 0;+ }++ // We also hook into the Windows loader TLS initialization and finalization.+ static void NTAPI mi_tls_attach(PVOID module, DWORD reason, LPVOID reserved) {+ if (reason == DLL_THREAD_ATTACH) {+ //mi_debug_out("tls thread attach\n");+ mi_win_main(module, reason, reserved);+ }+ else if (reason == DLL_PROCESS_ATTACH) {+ // mi_debug_out(mi_module_is_dll(module) ? "tls dll process attach\n" : "tls exe process attach\n");+ // tls process attach is always called before crt init+ mi_win_main(module, reason, reserved);+ }+ }++ static void NTAPI mi_tls_detach(PVOID module, DWORD reason, LPVOID reserved) {+ if (reason == DLL_THREAD_DETACH) {+ //mi_debug_out("tls thread detach\n");+ mi_win_main(module, reason, reserved);+ }+ else if (reason == DLL_PROCESS_DETACH) {+ // mi_debug_out(mi_module_is_dll(module) ? "tls dll process detach\n" : "tls exe process detach\n");+ if (!mi_module_is_dll(module)) {+ // in an exe, tls process detach is called after atexit (mi_crt_done)+ mi_win_main(module, reason, reserved);+ }+ }+ }++ // Set up TLS callbacks in a statically linked library by using special data sections.+ // See <https://stackoverflow.com/questions/14538159/tls-callback-in-windows>+ // We use 2 entries to ensure we call attach events before constructors+ // are called, and detach events after destructors are called.+ // We also set up a CRT initialization callback.+ #if defined(__cplusplus)+ extern "C" {+ #endif++ typedef int (mi_cdecl* mi_crt_callback_t)(void);+ #if defined(_WIN64)+ #pragma comment(linker, "/INCLUDE:_tls_used")+ #pragma comment(linker, "/INCLUDE:_mi_tls_callback_pre")+ #pragma comment(linker, "/INCLUDE:_mi_tls_callback_post")+ #pragma const_seg(".CRT$XLB")+ extern const PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[];+ const PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[] = { &mi_tls_attach };+ #pragma const_seg()+ #pragma const_seg(".CRT$XLY")+ extern const PIMAGE_TLS_CALLBACK _mi_tls_callback_post[];+ const PIMAGE_TLS_CALLBACK _mi_tls_callback_post[] = { &mi_tls_detach };+ #pragma const_seg()+ #pragma const_seg(".CRT$XIB")+ extern const mi_crt_callback_t _mi_crt_callback_init[];+ const mi_crt_callback_t _mi_crt_callback_init[] = { &mi_crt_init };+ #pragma const_seg()+ #else+ #pragma comment(linker, "/INCLUDE:__tls_used")+ #pragma comment(linker, "/INCLUDE:__mi_tls_callback_pre")+ #pragma comment(linker, "/INCLUDE:__mi_tls_callback_post")+ #pragma data_seg(".CRT$XLB")+ PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[] = { &mi_tls_attach };+ #pragma data_seg()+ #pragma data_seg(".CRT$XLY")+ PIMAGE_TLS_CALLBACK _mi_tls_callback_post[] = { &mi_tls_detach };+ #pragma data_seg()+ #pragma data_seg(".CRT$XIB")+ mi_crt_callback_t _mi_crt_callback_init[] = { &mi_crt_init };+ #pragma data_seg()+ #endif++ #if defined(__cplusplus)+ }+ #endif++/* ----------------------------------------------------------------+ Here we use a combination of the raw DLL main and TLS sections for+ both static and dynamic linkage. This is perhaps the most robust as+ the raw DLL main ensure we can close mimalloc latest possible.+ However, it can lead to link errors with on `_pRawDllMain` if other+ libraries also try to hook into this (like Boost).+*/+#elif defined(MI_WIN_INIT_USE_RAW_DLLMAIN)+ #define MI_PRIM_HAS_PROCESS_ATTACH 1+ // nothing to do since `_mi_thread_done` is handled through the DLL_THREAD_DETACH event.+ void _mi_prim_thread_init_auto_done(void) {}+ void _mi_prim_thread_done_auto_done(void) {}+ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);+ }++ // If linked into a DLL module, this raw entry is called before the CRT attach and+ // after the CRT detach through the CRT _pRawDllMain pointer.+ static BOOL NTAPI mi_dll_main_raw(PVOID module, DWORD reason, LPVOID reserved) {+ mi_win_main(module, reason, reserved);+ return TRUE;+ }++ // Set the value of the CRT _pRawDllMain pointer+ #if defined(__cplusplus)+ extern "C"+ #endif+ PVOID _pRawDllMain = (PVOID)&mi_dll_main_raw;++ // We also hook into the Windows loader TLS initialization and finalization.+ // If we are linked into an EXE module we rely on these as `mi_dll_main_raw`+ // is not called (and otherwise we ignore the TLS callbacks by checking if we are in a DLL).+ static bool mi_module_is_dll(PVOID mod) {+ if (mod==NULL) return false;+ PIMAGE_DOS_HEADER imageDosHeader = (PIMAGE_DOS_HEADER)mod;+ PIMAGE_NT_HEADERS imageNtHeaders = (PIMAGE_NT_HEADERS)((unsigned char*)imageDosHeader + imageDosHeader->e_lfanew);+ return ((imageNtHeaders->FileHeader.Characteristics & IMAGE_FILE_DLL) == IMAGE_FILE_DLL);+ }++ static void NTAPI mi_tls_attach(PVOID module, DWORD reason, LPVOID reserved) {+ if (reason == DLL_PROCESS_ATTACH || reason == DLL_THREAD_ATTACH) {+ if (!mi_module_is_dll(module)) {+ mi_win_main(module, reason, reserved);+ }+ }+ }++ static void NTAPI mi_tls_detach(PVOID module, DWORD reason, LPVOID reserved) {+ if (reason == DLL_PROCESS_DETACH || reason == DLL_THREAD_DETACH) {+ if (!mi_module_is_dll(module)) {+ mi_win_main(module, reason, reserved);+ }+ }+ }++ // Set up TLS callbacks in a statically linked library by using special data sections.+ // See <https://stackoverflow.com/questions/14538159/tls-callback-in-windows>+ // We use 2 entries to ensure we call attach events before constructors+ // are called, and detach events after destructors are called.+ #if defined(__cplusplus)+ extern "C" {+ #endif++ #if defined(_WIN64)+ #pragma comment(linker, "/INCLUDE:_tls_used")+ #pragma comment(linker, "/INCLUDE:_mi_tls_callback_pre")+ #pragma comment(linker, "/INCLUDE:_mi_tls_callback_post")+ #pragma const_seg(".CRT$XLB")+ extern const PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[];+ const PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[] = { &mi_tls_attach };+ #pragma const_seg()+ #pragma const_seg(".CRT$XLY")+ extern const PIMAGE_TLS_CALLBACK _mi_tls_callback_post[];+ const PIMAGE_TLS_CALLBACK _mi_tls_callback_post[] = { &mi_tls_detach };+ #pragma const_seg()+ #else+ #pragma comment(linker, "/INCLUDE:__tls_used")+ #pragma comment(linker, "/INCLUDE:__mi_tls_callback_pre")+ #pragma comment(linker, "/INCLUDE:__mi_tls_callback_post")+ #pragma data_seg(".CRT$XLB")+ PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[] = { &mi_tls_attach };+ #pragma data_seg()+ #pragma data_seg(".CRT$XLY")+ PIMAGE_TLS_CALLBACK _mi_tls_callback_post[] = { &mi_tls_detach };+ #pragma data_seg()+ #endif++ #if defined(__cplusplus)+ }+ #endif++/* --------------------------------------------------------------------+ Legacy options: DllMain, TLS, and FLS+ --------------------------------------------------------------------*/+#elif defined(MI_WIN_INIT_USE_TLS_DLLMAIN) && defined(MI_SHARED_LIB)#define MI_PRIM_HAS_PROCESS_ATTACH 1// Windows DLL: easy to hook into process_init and thread_done@@ -762,7 +963,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {MI_UNUSED(theap);}-#elif !defined(MI_WIN_USE_FLS)+#elif defined(MI_WIN_INIT_USE_TLS_DLLMAIN)#define MI_PRIM_HAS_PROCESS_ATTACH 1static void NTAPI mi_win_main_attach(PVOID module, DWORD reason, LPVOID reserved) {@@ -803,7 +1004,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {#pragma data_seg(".CRT$XLB")PIMAGE_TLS_CALLBACK _mi_tls_callback_pre[] = { &mi_win_main_attach };#pragma data_seg()- #pragma data_seg(".CRT$XLY")+ #pragma data_seg(".CRT$XIY")PIMAGE_TLS_CALLBACK _mi_tls_callback_post[] = { &mi_win_main_detach };#pragma data_seg()#endif@@ -819,7 +1020,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {MI_UNUSED(theap);}-#else // deprecated: statically linked, use fiber api+#elif defined(MI_WIN_INIT_USE_FLS) // deprecated: statically linked, use fiber api#if defined(_MSC_VER) // on clang/gcc use the constructor attribute (in `src/prim/prim.c`)// MSVC: use data section magic for static libraries@@ -876,6 +1077,8 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {mi_assert_internal(mi_fls_key != (DWORD)(-1));FlsSetValue(mi_fls_key, theap);}+#else+#error "define windows process and thread auto initialization"#endif// ----------------------------------------------------@@ -895,7 +1098,6 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {#endifmi_decl_export void _mi_redirect_entry(DWORD reason) {// called on redirection; careful as this may be called before DllMain- mi_win_tls_init(reason);if (reason == DLL_PROCESS_ATTACH) {mi_redirected = true;}@@ -903,6 +1105,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {mi_redirected = false;}else if (reason == DLL_THREAD_DETACH) {+ // mi_debug_out("redirect thread detach\n");_mi_thread_done(NULL);}}diff --git a/vendored/mimalloc/src/random.c b/vendored/mimalloc/src/random.cindex 990e4894f..75b5cfbb0 100644--- a/vendored/mimalloc/src/random.c+++ b/vendored/mimalloc/src/random.c@@ -94,7 +94,8 @@ static void chacha_init(mi_random_ctx_t* ctx, const uint8_t key[32], uint64_t no// since we only use chacha for randomness (and not encryption) we// do not _need_ to read 32-bit values as little endian but we do anyways// just for being compatible :-)- _mi_memzero(ctx, sizeof(*ctx));+ ctx->output_available = 0;+ _mi_memzero(ctx->output,sizeof(ctx->output));for (size_t i = 0; i < 4; i++) {const uint8_t* sigma = (uint8_t*)"expand 32-byte k";ctx->input[i] = read32(sigma,i);@@ -110,6 +111,7 @@ static void chacha_init(mi_random_ctx_t* ctx, const uint8_t key[32], uint64_t nostatic void chacha_split(mi_random_ctx_t* ctx, uint64_t nonce, mi_random_ctx_t* ctx_new) {_mi_memzero(ctx_new, sizeof(*ctx_new));+ ctx_new->weak = ctx->weak;_mi_memcpy(ctx_new->input, ctx->input, sizeof(ctx_new->input));ctx_new->input[12] = 0;ctx_new->input[13] = 0;@@ -178,9 +180,12 @@ static void mi_random_init_ex(mi_random_ctx_t* ctx, bool use_weak) {if (!use_weak) { _mi_warning_message("unable to use secure randomness\n"); }#endifuintptr_t x = _mi_os_random_weak(0);- for (size_t i = 0; i < 8; i++, x++) { // key is eight 32-bit words.+ for (size_t i = 0; i < 32; i+=4, x++) {x = _mi_random_shuffle(x);- ((uint32_t*)key)[i] = (uint32_t)x;+ key[i] = (uint8_t)(x);+ key[i+1] = (uint8_t)(x>>8);+ key[i+2] = (uint8_t)(x>>16);+ key[i+3] = (uint8_t)(x>>24);}ctx->weak = true;}diff --git a/vendored/mimalloc/src/stats.c b/vendored/mimalloc/src/stats.cindex 877266c79..7ca18e238 100644--- a/vendored/mimalloc/src/stats.c+++ b/vendored/mimalloc/src/stats.c@@ -117,7 +117,7 @@ static void mi_stat_counter_add_mt(mi_stat_counter_t* stat, const mi_stat_counte// must be thread safe as it is called from stats_mergestatic void mi_stats_add(mi_stats_t* stats, const mi_stats_t* src) {- if (stats==src) return;+ if (stats==NULL || src==NULL || stats==src) return;// copy all fieldsMI_STAT_FIELDS()@@ -214,10 +214,9 @@ static void mi_stat_print_ex(const mi_stat_count_t* stat, const char* msg, int64}}else {- mi_print_amount(stat->peak, 1, out, arg);- mi_print_amount(stat->total, 1, out, arg);- _mi_fprintf(out, arg, "%11s", " "); // no freed- mi_print_amount(stat->current, 1, out, arg);+ mi_print_amount(stat->peak, 0, out, arg);+ mi_print_amount(stat->total, 0, out, arg);+ mi_print_amount(stat->current, 0, out, arg);_mi_fprintf(out, arg, "\n");}}@@ -237,16 +236,21 @@ static void mi_stat_total_print(const mi_stat_count_t* stat, const char* msg, instatic void mi_stat_counter_print(const mi_stat_counter_t* stat, const char* msg, mi_output_fun* out, void* arg ) {_mi_fprintf(out, arg, " %-10s:", msg);- mi_print_amount(stat->total, -1, out, arg);+ mi_print_amount(stat->total, 0, out, arg);_mi_fprintf(out, arg, "\n");}+static void mi_stat_counter_print_size(const mi_stat_counter_t* stat, const char* msg, mi_output_fun* out, void* arg ) {+ _mi_fprintf(out, arg, " %-10s:", msg);+ mi_print_amount(stat->total, 1, out, arg);+ _mi_fprintf(out, arg, "\n");+}-static void mi_stat_average_print(size_t count, size_t total, const char* msg, mi_output_fun* out, void* arg) {+static void mi_stat_average_print(int64_t count, int64_t total, const char* msg, mi_output_fun* out, void* arg) {const int64_t avg_tens = (count == 0 ? 0 : (total*10 / count));- const long avg_whole = (long)(avg_tens/10);- const long avg_frac1 = (long)(avg_tens%10);- _mi_fprintf(out, arg, " %-10s: %5ld.%ld avg\n", msg, avg_whole, avg_frac1);+ const int64_t avg_whole = avg_tens/10;+ const int64_t avg_frac1 = avg_tens%10;+ _mi_fprintf(out, arg, " %-10s: %5lld.%lld avg\n", msg, avg_whole, avg_frac1);}@@ -335,7 +339,7 @@ mi_decl_export void mi_process_info_print_out(mi_output_fun* out, void* arg) mi__mi_fprintf(out, arg, "\n");}-void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_fun* out0, void* arg0) mi_attr_noexcept {+void _mi_stats_print(const char* name, size_t id, const mi_stats_t* stats, mi_output_fun* out0, void* arg0) mi_attr_noexcept {// wrap the output function to be line bufferedchar buf[256]; _mi_memzero_var(buf);buffered_t buffer = { out0, arg0, NULL, 0, 255 };@@ -352,8 +356,8 @@ void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_fmi_stats_print_bins(stats->malloc_bins, MI_BIN_HUGE, out, arg);#endif#if MI_STAT- mi_stat_print(&stats->malloc_normal, "binned", (stats->malloc_normal_count.total == 0 ? 1 : -1), out, arg);- mi_stat_print(&stats->malloc_huge, "huge", (stats->malloc_huge_count.total == 0 ? 1 : -1), out, arg);+ mi_stat_print(&stats->malloc_normal, "binned", (stats->malloc_normal_count.total == 0 ? -1 : 1), out, arg);+ mi_stat_print(&stats->malloc_huge, "huge", (stats->malloc_huge_count.total == 0 ? -1 : 1), out, arg);mi_stat_count_t total = { 0,0,0 };mi_stat_count_add_mt(&total, &stats->malloc_normal);mi_stat_count_add_mt(&total, &stats->malloc_huge);@@ -371,8 +375,8 @@ void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_f// mi_stat_print(&stats->segments, "segments", -1, out, arg);// mi_stat_print(&stats->segments_abandoned, "-abandoned", -1, out, arg);// mi_stat_print(&stats->segments_cache, "-cached", -1, out, arg);- mi_stat_print(&stats->pages, "pages", -1, out, arg);- mi_stat_print(&stats->pages_abandoned, "abandoned", -1, out, arg);+ mi_stat_print(&stats->pages, "pages", 0, out, arg);+ mi_stat_print(&stats->pages_abandoned, "abandoned", 0, out, arg);mi_stat_counter_print(&stats->pages_reclaim_on_alloc, "reclaima", out, arg);mi_stat_counter_print(&stats->pages_reclaim_on_free, "reclaimf", out, arg);mi_stat_counter_print(&stats->pages_reabandon_full, "reabandon", out, arg);@@ -387,8 +391,8 @@ void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_fmi_print_header("arenas", out, arg);mi_stat_print_ex(&stats->reserved, "reserved", 1, out, arg, "");mi_stat_print_ex(&stats->committed, "committed", 1, out, arg, "");- mi_stat_counter_print(&stats->reset, "reset", out, arg);- mi_stat_counter_print(&stats->purged, "purged", out, arg);+ mi_stat_counter_print_size(&stats->reset, "reset", out, arg);+ mi_stat_counter_print_size(&stats->purged, "purged", out, arg);mi_stat_counter_print(&stats->arena_count, "arenas", out, arg);mi_stat_counter_print(&stats->arena_rollback_count, "rollback", out, arg);@@ -397,11 +401,13 @@ void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_fmi_stat_counter_print(&stats->reset_calls, "resets", out, arg);mi_stat_counter_print(&stats->purge_calls, "purges", out, arg);mi_stat_counter_print(&stats->malloc_guarded_count, "guarded", out, arg);- mi_stat_print_ex(&stats->heaps, "heaps", -1, out, arg, "");+ mi_stat_print_ex(&stats->theaps, "theaps", 0, out, arg, "");+ mi_stat_print_ex(&stats->heaps, "heaps", 0, out, arg, "");+ mi_stat_counter_print(&stats->heaps_delete_wait, "heap waits", out, arg);_mi_fprintf(out, arg, "\n");mi_print_header("process", out, arg);- mi_stat_print_ex(&stats->threads, "threads", -1, out, arg, "");+ mi_stat_print_ex(&stats->threads, "threads", 0, out, arg, "");_mi_fprintf(out, arg, " %-10s: %5i\n", "numa nodes", _mi_os_numa_node_count());mi_process_info_print_out(out, arg);}@@ -416,7 +422,7 @@ void _mi_stats_init(void) {if (mi_process_start == 0) { mi_process_start = _mi_clock_start(); };}-static void mi_stats_add_into(mi_stats_t* to, mi_stats_t* from) {+static void mi_stats_add_into(mi_stats_t* to, const mi_stats_t* from) {mi_assert_internal(to != NULL && from != NULL);if (to == from) return;mi_stats_add(to, from);@@ -429,14 +435,14 @@ void _mi_stats_merge_into(mi_stats_t* to, mi_stats_t* from) {_mi_memzero(from, sizeof(mi_stats_t));}-static mi_stats_t* mi_stats_merge_theap_to_heap(mi_theap_t* theap) mi_attr_noexcept {+static const mi_stats_t* mi_stats_merge_theap_to_heap(mi_theap_t* theap) mi_attr_noexcept {mi_stats_t* stats = &theap->stats;- mi_stats_t* heap_stats = &theap->heap->stats;+ mi_stats_t* heap_stats = &_mi_theap_heap(theap)->stats;_mi_stats_merge_into( heap_stats, stats );return heap_stats;}-static mi_stats_t* mi_heap_get_stats(mi_heap_t* heap) {+static const mi_stats_t* mi_heap_get_stats(mi_heap_t* heap) {if (heap==NULL) { heap = mi_heap_main(); }mi_theap_t* theap = _mi_heap_theap_peek(heap);if (theap==NULL) return &heap->stats;@@ -473,7 +479,7 @@ void mi_subproc_heap_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun*mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);if (subproc==NULL) return;mi_heap_print_visit_info_t vinfo = { out, arg };- mi_subproc_visit_heaps(subproc, &mi_heap_print_visitor, &vinfo);+ mi_subproc_visit_heaps(subproc_id, &mi_heap_print_visitor, &vinfo);_mi_stats_print("subproc", subproc->subproc_seq, &subproc->stats, out, arg);}@@ -482,7 +488,7 @@ void mi_subproc_heap_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun*void mi_subproc_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun* out, void* arg) mi_attr_noexcept {mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);if (subproc==NULL) return;- mi_stats_t_decl(stats);+ mi_stats_t_decl(stats);if (mi_subproc_stats_get(subproc_id, &stats)) {_mi_stats_print("subproc", subproc->subproc_seq, &stats, out, arg);}@@ -502,7 +508,7 @@ void mi_stats_print(void* out) mi_attr_noexcept {void mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept {mi_theap_t* theap = _mi_theap_default();if (theap==NULL || !mi_theap_is_initialized(theap)) return;- _mi_stats_print("heap", theap->heap->heap_seq, &theap->stats, out, arg);+ _mi_stats_print("heap", _mi_theap_heap(theap)->heap_seq, &theap->stats, out, arg);mi_stats_merge_theap_to_heap(_mi_theap_default());}@@ -537,12 +543,15 @@ mi_msecs_t _mi_clock_end(mi_msecs_t start) {mi_decl_export void mi_process_info(size_t* elapsed_msecs, size_t* user_msecs, size_t* system_msecs, size_t* current_rss, size_t* peak_rss, size_t* current_commit, size_t* peak_commit, size_t* page_faults) mi_attr_noexcept{- mi_subproc_t* subproc = _mi_subproc_main();mi_process_info_t pinfo;_mi_memzero_var(pinfo);pinfo.elapsed = _mi_clock_end(mi_process_start);- pinfo.current_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.current)));- pinfo.peak_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.peak)));+ { const mi_subproc_t* subproc = _mi_subproc_main();+ if (subproc!=NULL) {+ pinfo.current_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.current)));+ pinfo.peak_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.peak)));+ }+ }pinfo.current_rss = pinfo.current_commit;pinfo.peak_rss = pinfo.peak_commit;pinfo.utime = 0;@@ -575,34 +584,36 @@ size_t mi_stats_get_bin_size(size_t bin) mi_attr_noexcept {return _mi_bin_size(bin);}-static bool _mi_stats_get(mi_stats_t* stats_in, mi_stats_t* stats_out) mi_attr_noexcept {- if (stats_out == NULL || stats_out->size != sizeof(mi_stats_t) || stats_out->version != MI_STAT_VERSION) return false;- if (stats_in == NULL || stats_in->size != stats_out->size) return false;- _mi_memcpy(stats_out, stats_in, stats_out->size);+static bool mi_stats_copy(mi_stats_t* stats_to, const mi_stats_t* stats_from) mi_attr_noexcept {+ if (stats_to == NULL || stats_to->size != sizeof(mi_stats_t) || stats_to->version != MI_STAT_VERSION) return false;+ if (stats_from == NULL || stats_from->size != stats_to->size) return false;+ _mi_memcpy(stats_to, stats_from, stats_to->size);return true;}bool mi_subproc_stats_get_exclusive(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept {- return _mi_stats_get(&_mi_subproc_from_id(subproc_id)->stats, stats);+ const mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL) return false;+ return mi_stats_copy(stats,&subproc->stats);}bool mi_heap_stats_get(mi_heap_t* heap, mi_stats_t* stats) mi_attr_noexcept {- return _mi_stats_get(mi_heap_get_stats(heap), stats);+ return mi_stats_copy(stats, mi_heap_get_stats(heap));}static bool mi_cdecl mi_heap_aggregate_visitor(mi_heap_t* heap, void* arg) {mi_stats_t* stats = (mi_stats_t*)arg;- mi_stats_add_into(stats, &heap->stats);+ mi_stats_add_into(stats, mi_heap_get_stats(heap));return true;}bool mi_subproc_stats_get(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept {+ if (stats==NULL) return false;mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);- if (stats == NULL || stats->size != sizeof(mi_stats_t) || stats->version != MI_STAT_VERSION) return false;- _mi_memzero(stats,stats->size);- mi_subproc_visit_heaps(subproc, &mi_heap_aggregate_visitor, stats);- mi_stats_add_into(stats, &subproc->stats);+ if (subproc == NULL) return false;+ if (!mi_stats_copy(stats, &subproc->stats)) return false;+ mi_subproc_visit_heaps(subproc_id, &mi_heap_aggregate_visitor, stats);return true;}@@ -651,7 +662,7 @@ static void mi_json_buf_print(mi_json_buf_t* hbuf, const char* msg) {hbuf->buf[hbuf->used] = 0;}-static void mi_json_buf_print_count_bin(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, size_t bin, bool add_comma) {+static void mi_json_buf_print_count_bin(mi_json_buf_t* hbuf, const char* prefix, const mi_stat_count_t* stat, size_t bin, bool add_comma) {const size_t binsize = mi_stats_get_bin_size(bin);const size_t pagesize = (binsize <= MI_SMALL_MAX_OBJ_SIZE ? MI_SMALL_PAGE_SIZE :(binsize <= MI_MEDIUM_MAX_OBJ_SIZE ? MI_MEDIUM_PAGE_SIZE :@@ -662,7 +673,7 @@ static void mi_json_buf_print_count_bin(mi_json_buf_t* hbuf, const char* prefix,mi_json_buf_print(hbuf, buf);}-static void mi_json_buf_print_count_cbin(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, mi_chunkbin_t bin, bool add_comma) {+static void mi_json_buf_print_count_cbin(mi_json_buf_t* hbuf, const char* prefix, const mi_stat_count_t* stat, mi_chunkbin_t bin, bool add_comma) {const char* cbin = " ";switch(bin) {case MI_CBIN_SMALL: cbin = "S"; break;@@ -678,14 +689,14 @@ static void mi_json_buf_print_count_cbin(mi_json_buf_t* hbuf, const char* prefixmi_json_buf_print(hbuf, buf);}-static void mi_json_buf_print_count(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, bool add_comma) {+static void mi_json_buf_print_count(mi_json_buf_t* hbuf, const char* prefix, const mi_stat_count_t* stat, bool add_comma) {char buf[128];_mi_snprintf(buf, 128, "%s{ \"total\": %lld, \"peak\": %lld, \"current\": %lld }%s\n", prefix, stat->total, stat->peak, stat->current, (add_comma ? "," : ""));buf[127] = 0;mi_json_buf_print(hbuf, buf);}-static void mi_json_buf_print_count_value(mi_json_buf_t* hbuf, const char* name, mi_stat_count_t* stat) {+static void mi_json_buf_print_count_value(mi_json_buf_t* hbuf, const char* name, const mi_stat_count_t* stat) {char buf[128];_mi_snprintf(buf, 128, " \"%s\": ", name);buf[127] = 0;@@ -707,14 +718,14 @@ static void mi_json_buf_print_size(mi_json_buf_t* hbuf, const char* name, size_tmi_json_buf_print(hbuf, buf);}-static void mi_json_buf_print_counter_value(mi_json_buf_t* hbuf, const char* name, mi_stat_counter_t* stat) {+static void mi_json_buf_print_counter_value(mi_json_buf_t* hbuf, const char* name, const mi_stat_counter_t* stat) {mi_json_buf_print_value(hbuf, name, stat->total);}#define MI_STAT_COUNT(stat) mi_json_buf_print_count_value(&hbuf, #stat, &stats->stat);#define MI_STAT_COUNTER(stat) mi_json_buf_print_counter_value(&hbuf, #stat, &stats->stat);-static char* mi_stats_get_json_from(mi_stats_t* stats, size_t output_size, char* output_buf) mi_attr_noexcept {+static char* mi_stats_get_json_from(const mi_stats_t* stats, size_t output_size, char* output_buf) mi_attr_noexcept {if (stats==NULL || stats->size!=sizeof(mi_stats_t) || stats->version!=MI_STAT_VERSION) return NULL;mi_json_buf_t hbuf = { NULL, 0, 0, true };if (output_size > 0 && output_buf != NULL) {@@ -769,7 +780,7 @@ static char* mi_stats_get_json_from(mi_stats_t* stats, size_t output_size, char*for (size_t i = 0; i < MI_CBIN_COUNT; i++) {mi_json_buf_print_count_cbin(&hbuf, " ", &stats->chunk_bins[i], (mi_chunkbin_t)i, i!=MI_CBIN_COUNT-1);}- mi_json_buf_print(&hbuf, " ]\n");+ mi_json_buf_print(&hbuf, " ]\n");mi_json_buf_print(&hbuf, "}\n");if (hbuf.used >= hbuf.size) {// failed@@ -786,7 +797,7 @@ char* mi_subproc_stats_get_json(mi_subproc_id_t subproc_id, size_t buf_size, chaif (subproc==NULL) return NULL;mi_stats_t_decl(stats);if (!mi_subproc_stats_get(subproc_id,&stats)) return NULL;- return mi_stats_get_json_from(&subproc->stats, buf_size, buf);+ return mi_stats_get_json_from(&stats, buf_size, buf);}char* mi_heap_stats_get_json(mi_heap_t* heap, size_t buf_size, char* buf) mi_attr_noexcept {diff --git a/vendored/mimalloc/src/theap.c b/vendored/mimalloc/src/theap.cindex 47961afd3..ef53c1e07 100644--- a/vendored/mimalloc/src/theap.c+++ b/vendored/mimalloc/src/theap.c@@ -21,7 +21,7 @@ terms of the MIT license. A copy of the license can be found in the filetypedef bool (theap_page_visitor_fun)(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2);// Visit all pages in a theap; returns `false` if break was called.-static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn, void* arg1, void* arg2)+static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn, bool include_full, void* arg1, void* arg2){if (theap==NULL || theap->page_count==0) return 0;@@ -31,7 +31,8 @@ static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn,size_t count = 0;#endif- for (size_t i = 0; i <= MI_BIN_FULL; i++) {+ const size_t max_bin = (include_full ? MI_BIN_FULL : MI_BIN_FULL - 1);+ for (size_t i = 0; i <= max_bin; i++) {mi_page_queue_t* pq = &theap->pages[i];mi_page_t* page = pq->first;while(page != NULL) {@@ -44,7 +45,7 @@ static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn,page = next; // and continue}}- mi_assert_internal(count == total);+ mi_assert_internal(!include_full || count == total);return true;}@@ -62,7 +63,7 @@ static bool mi_theap_page_is_valid(mi_theap_t* theap, mi_page_queue_t* pq, mi_pa#if MI_DEBUG>=3static bool mi_theap_is_valid(mi_theap_t* theap) {mi_assert_internal(theap!=NULL);- mi_theap_visit_pages(theap, &mi_theap_page_is_valid, NULL, NULL);+ mi_theap_visit_pages(theap, &mi_theap_page_is_valid, true, NULL, NULL);for (size_t bin = 0; bin < MI_BIN_COUNT; bin++) {mi_assert_internal(_mi_page_queue_is_valid(theap, &theap->pages[bin]));}@@ -109,7 +110,7 @@ static bool mi_theap_page_collect(mi_theap_t* theap, mi_page_queue_t* pq, mi_pagstatic void mi_theap_merge_stats(mi_theap_t* theap) {mi_assert_internal(mi_theap_is_initialized(theap));- _mi_stats_merge_into(&theap->heap->stats, &theap->stats);+ _mi_stats_merge_into(&_mi_theap_heap(theap)->stats, &theap->stats);}static void mi_theap_collect_ex(mi_theap_t* theap, mi_collect_t collect)@@ -127,7 +128,7 @@ static void mi_theap_collect_ex(mi_theap_t* theap, mi_collect_t collect)_mi_theap_collect_retired(theap, force);// collect all pages owned by this thread- mi_theap_visit_pages(theap, &mi_theap_page_collect, &collect, NULL);+ mi_theap_visit_pages(theap, &mi_theap_page_collect, (collect!=MI_NORMAL), &collect, NULL); // dont normally visit full pages, see issue #1220// collect arenas (this is program wide so don't force purges on abandonment of threads)//mi_atomic_storei64_release(&theap->tld->subproc->purge_expire, 1);@@ -173,11 +174,14 @@ mi_theap_t* mi_theap_get_default(void) {void _mi_theap_init(mi_theap_t* theap, mi_heap_t* heap, mi_tld_t* tld){mi_assert_internal(theap!=NULL);+ mi_assert_internal(heap!=NULL);mi_memid_t memid = theap->memid;_mi_memcpy_aligned(theap, &_mi_theap_empty, sizeof(mi_theap_t));theap->memid = memid;- theap->heap = heap;+ theap->refcount = 1;theap->tld = tld; // avoid reading the thread-local tld during initialization+ mi_atomic_store_ptr_relaxed(mi_heap_t,&theap->heap,heap);+ mi_assert_internal(theap->stats.size == sizeof(mi_stats_t));_mi_theap_options_init(theap);if (theap->tld->is_in_threadpool) {@@ -191,11 +195,14 @@ void _mi_theap_init(mi_theap_t* theap, mi_heap_t* heap, mi_tld_t* tld)}// push on the thread local theaps list- mi_theap_t* head = theap->tld->theaps;- theap->tprev = NULL;- theap->tnext = head;- if (head!=NULL) { head->tprev = theap; }- theap->tld->theaps = theap;+ mi_theap_t* head = NULL;+ mi_lock(&theap->tld->theaps_lock) {+ head = theap->tld->theaps;+ theap->tprev = NULL;+ theap->tnext = head;+ if (head!=NULL) { head->tprev = theap; }+ theap->tld->theaps = theap;+ }// initialize randomif (head == NULL) { // first theap in this thread?@@ -210,6 +217,7 @@ void _mi_theap_init(mi_theap_t* theap, mi_heap_t* heap, mi_tld_t* tld)}theap->cookie = _mi_theap_random_next(theap) | 1;_mi_theap_guarded_init(theap);+ mi_subproc_stat_increase(_mi_subproc(),theaps,1);// push on the heap's theap listmi_lock(&heap->theaps_lock) {@@ -256,37 +264,70 @@ uintptr_t _mi_theap_random_next(mi_theap_t* theap) {return _mi_random_next(&theap->random);}-// called from `mi_theap_delete` to free the internal theap resources.-void _mi_theap_free(mi_theap_t* theap) {- mi_assert(theap != NULL);- mi_assert_internal(mi_theap_is_initialized(theap));- if (theap==NULL || !mi_theap_is_initialized(theap)) return;+static void mi_theap_free_mem(mi_theap_t* theap) {+ if (theap!=NULL) {+ mi_subproc_stat_decrease(_mi_subproc(),theaps,1);+ // free the used memory+ if (theap->memid.memkind == MI_MEM_HEAP_MAIN) { // note: for now unused as it would access theap_default stats in mi_free of the current theap+ mi_assert_internal(_mi_is_heap_main(mi_heap_of(theap)));+ mi_free(theap);+ }+ else if (theap->memid.memkind == MI_MEM_META) {+ _mi_meta_free(theap, sizeof(*theap), theap->memid);+ }+ else {+ _mi_arenas_free(theap, _mi_align_up(sizeof(*theap),MI_ARENA_MIN_OBJ_SIZE), theap->memid ); // issue #1168, avoid assertion failure+ }+ }+}- // merge stats to the owning heap- mi_theap_merge_stats(theap);+void _mi_theap_incref(mi_theap_t* theap) {+ if (theap!=NULL && theap->memid.memkind > MI_MEM_STATIC) {+ mi_atomic_increment_acq_rel(&theap->refcount);+ }+}- // remove ourselves from the heap theaps list- mi_lock(&theap->heap->theaps_lock) {- if (theap->hnext != NULL) { theap->hnext->hprev = theap->hprev; }- if (theap->hprev != NULL) { theap->hprev->hnext = theap->hnext; }- else { mi_assert_internal(theap->heap->theaps == theap); theap->heap->theaps = theap->hnext; }+void _mi_theap_decref(mi_theap_t* theap) {+ if (theap!=NULL && theap->memid.memkind > MI_MEM_STATIC) {+ if (mi_atomic_decrement_acq_rel(&theap->refcount) == 1) {+ mi_theap_free_mem(theap);+ }}+}- // remove ourselves from the thread local theaps list- if (theap->tnext != NULL) { theap->tnext->tprev = theap->tprev; }- if (theap->tprev != NULL) { theap->tprev->tnext = theap->tnext; }- else { mi_assert_internal(theap->tld->theaps == theap); theap->tld->theaps = theap->tnext; }- // and free the used memory- if (theap->memid.memkind == MI_MEM_HEAP_MAIN) { // note: for now unused as it would access theap_default stats in mi_free of the current theap- mi_assert_internal(_mi_is_heap_main(mi_heap_of(theap)));- mi_free(theap);- }- else if (theap->memid.memkind == MI_MEM_META) {- _mi_meta_free(theap, sizeof(*theap), theap->memid);+// called from `mi_theap_delete` to free the internal theap resources.+bool _mi_theap_free(mi_theap_t* theap, bool acquire_heap_theaps_lock, bool acquire_tld_theaps_lock) {+ mi_assert(theap != NULL);+ if (theap==NULL) return true;++ mi_heap_t* const heap = mi_atomic_exchange_ptr_acq_rel(mi_heap_t, &theap->heap, NULL);+ if (heap==NULL) {+ // concurrent interaction, retry in an outer loop (as the other thread may be blocked on our lock)+ return false;}else {- _mi_arenas_free(theap, _mi_align_up(sizeof(*theap),MI_ARENA_MIN_OBJ_SIZE), theap->memid ); // issue #1168, avoid assertion failure+ // merge stats to the owning heap+ _mi_stats_merge_into(&heap->stats, &theap->stats);++ // remove ourselves from the heap theaps list+ mi_lock_maybe(&heap->theaps_lock, acquire_heap_theaps_lock) {+ if (theap->hnext != NULL) { theap->hnext->hprev = theap->hprev; }+ if (theap->hprev != NULL) { theap->hprev->hnext = theap->hnext; }+ else { mi_assert_internal(heap->theaps == theap); heap->theaps = theap->hnext; }+ theap->hnext = theap->hprev = NULL;+ }++ // remove ourselves from the thread local theaps list+ mi_lock_maybe(&theap->tld->theaps_lock, acquire_tld_theaps_lock) {+ if (theap->tnext != NULL) { theap->tnext->tprev = theap->tprev; }+ if (theap->tprev != NULL) { theap->tprev->tnext = theap->tnext; }+ else { mi_assert_internal(theap->tld->theaps == theap); theap->tld->theaps = theap->tnext; }+ theap->tnext = theap->tprev = NULL;+ }+ theap->tld = NULL;+ _mi_theap_decref(theap);+ return true;}}@@ -411,7 +452,7 @@ void _mi_theap_unsafe_destroy_all(mi_theap_t* theap) {----------------------------------------------------------- */// Safe delete a theap without freeing any still allocated blocks in that theap.-void _mi_theap_delete(mi_theap_t* theap)+void _mi_theap_delete(mi_theap_t* theap, bool acquire_tld_theaps_lock){mi_assert(theap != NULL);mi_assert(mi_theap_is_initialized(theap));@@ -422,7 +463,7 @@ void _mi_theap_delete(mi_theap_t* theap)_mi_theap_collect_abandon(theap);mi_assert_internal(theap->page_count==0);- _mi_theap_free(theap);+ _mi_theap_free(theap, true /* acquire heap->theaps_lock */, acquire_tld_theaps_lock);}@@ -435,7 +476,7 @@ void mi_theap_unload(mi_theap_t* theap) {mi_assert(mi_theap_is_initialized(theap));mi_assert_expensive(mi_theap_is_valid(theap));if (theap==NULL || !mi_theap_is_initialized(theap)) return;- if (theap->heap->exclusive_arena == NULL) {+ if (_mi_theap_heap(theap)->exclusive_arena == NULL) {_mi_warning_message("cannot unload theaps that are not associated with an exclusive arena\n");return;}@@ -455,7 +496,7 @@ void mi_theap_unload(mi_theap_t* theap) {bool mi_theap_reload(mi_theap_t* theap, mi_arena_id_t arena_id) {mi_assert(mi_theap_is_initialized(theap));if (theap==NULL || !mi_theap_is_initialized(theap)) return false;- if (theap->heap->exclusive_arena == NULL) {+ if (_mi_theap_heap(theap)->exclusive_arena == NULL) {_mi_warning_message("cannot reload theaps that were not associated with an exclusive arena\n");return false;}@@ -464,8 +505,8 @@ bool mi_theap_reload(mi_theap_t* theap, mi_arena_id_t arena_id) {return false;}mi_arena_t* arena = _mi_arena_from_id(arena_id);- if (theap->heap->exclusive_arena != arena) {- _mi_warning_message("trying to reload a theap at a different arena address: %p vs %p\n", theap->heap->exclusive_arena, arena);+ if (_mi_theap_heap(theap)->exclusive_arena != arena) {+ _mi_warning_message("trying to reload a theap at a different arena address: %p vs %p\n", _mi_theap_heap(theap)->exclusive_arena, arena);return false;}@@ -645,7 +686,7 @@ static bool mi_theap_visit_areas_page(mi_theap_t* theap, mi_page_queue_t* pq, mi// Visit all theap pages as areasstatic bool mi_theap_visit_areas(const mi_theap_t* theap, mi_theap_area_visit_fun* visitor, void* arg) {if (visitor == NULL) return false;- return mi_theap_visit_pages((mi_theap_t*)theap, &mi_theap_visit_areas_page, (void*)(visitor), arg); // note: function pointer to void* :-{+ return mi_theap_visit_pages((mi_theap_t*)theap, &mi_theap_visit_areas_page, true, (void*)(visitor), arg); // note: function pointer to void* :-{}// Just to pass arguments@@ -657,7 +698,7 @@ typedef struct mi_visit_blocks_args_s {static bool mi_theap_area_visitor(const mi_theap_t* theap, const mi_theap_area_ex_t* xarea, void* arg) {mi_visit_blocks_args_t* args = (mi_visit_blocks_args_t*)arg;- if (!args->visitor(theap->heap, &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;+ if (!args->visitor(_mi_theap_heap(theap), &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;if (args->visit_blocks) {return _mi_theap_area_visit_blocks(&xarea->area, xarea->page, args->visitor, args->arg);}diff --git a/vendored/mimalloc/src/threadlocal.c b/vendored/mimalloc/src/threadlocal.cindex 8e7c92b9f..eea3329bf 100644--- a/vendored/mimalloc/src/threadlocal.c+++ b/vendored/mimalloc/src/threadlocal.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2019-2025, Microsoft Research, Daan Leijen+Copyright (c) 2019-2026, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -16,21 +16,60 @@ that can be allocated.#include "mimalloc/prim.h"/* ------------------------------------------------------------Each thread can have (a dynamically expanding) array of-thread-local values.+ Each thread can have (a dynamically expanding) array of+ thread-local values. Each slot has a value and a version.+ The version is used to safely reuse slots.----------------------------------------------------------- */+typedef struct mi_tls_slot_s {+ size_t version;+ void* value;+} mi_tls_slot_t;typedef struct mi_thread_locals_s {- size_t count;- void* slots[1];+ size_t count;+ mi_tls_slot_t slots[1];} mi_thread_locals_t;-static mi_thread_locals_t mi_thread_locals_empty = { 0, {NULL} };+static mi_thread_locals_t mi_thread_locals_empty = { 0, {{0,NULL}} };mi_decl_thread mi_thread_locals_t* mi_thread_locals = &mi_thread_locals_empty; // always point to a valid `mi_thread_locals_t`++/* -----------------------------------------------------------+ Each key consists of the slot index in the lower bits,+ and its version it the top bits. When we get a value+ the version must match or we return NULL. When we set+ a value, we also set the version of the key.+----------------------------------------------------------- */++#if MI_SIZE_BITS < 64+#define MI_TLS_IDX_BITS (MI_SIZE_BITS/2) // half for the index, half for the version+#else+#define MI_TLS_IDX_BITS (MI_SIZE_BITS/4) // 16 bits for the index, 48 bits for the version+#endif+#define MI_TLS_IDX_MASK ((MI_ZU(1)<<MI_TLS_IDX_BITS)-1)+#define MI_TLS_IDX_MAX MI_TLS_IDX_MASK+#define MI_TLS_VERSION_MAX ((MI_ZU(1)<<(MI_SIZE_BITS - MI_TLS_IDX_BITS))-1)++static size_t mi_key_index( size_t key ) {+ return (key & MI_TLS_IDX_MASK);+}++static size_t mi_key_version( size_t key ) {+ return (key >> MI_TLS_IDX_BITS);+}++static mi_thread_local_t mi_key_create( size_t index, size_t version ) {+ mi_assert_internal(version != 0 && version <= MI_TLS_VERSION_MAX);+ mi_assert_internal(index <= MI_TLS_IDX_MAX);+ const mi_thread_local_t key = ((version << MI_TLS_IDX_BITS) | index);+ mi_assert_internal(key != 0);+ return key;+}++// dynamically reallocate the thread local slots when needed-static mi_thread_locals_t* mi_thread_locals_expand(mi_thread_local_t atleast) {+static mi_thread_locals_t* mi_thread_locals_expand(size_t least_idx) {mi_thread_locals_t* tls_old = mi_thread_locals;const size_t count_old = tls_old->count;size_t count;@@ -44,10 +83,11 @@ static mi_thread_locals_t* mi_thread_locals_expand(mi_thread_local_t atleast) {else {count = 2*count_old; // and double initially}- if (count <= atleast) {- count = atleast + 1;+ if (count <= least_idx) {+ count = least_idx + 1;}- mi_thread_locals_t* tls = (mi_thread_locals_t*)mi_rezalloc(tls_old, sizeof(mi_thread_locals_t) + count*sizeof(void*));+ if (count > MI_TLS_IDX_MAX) { return NULL; } // too large+ mi_thread_locals_t* tls = (mi_thread_locals_t*)mi_rezalloc(tls_old, sizeof(mi_thread_locals_t) + count*sizeof(mi_tls_slot_t));if mi_unlikely(tls==NULL) return NULL;tls->count = count;mi_thread_locals = tls;@@ -56,11 +96,13 @@ static mi_thread_locals_t* mi_thread_locals_expand(mi_thread_local_t atleast) {static mi_decl_noinline bool mi_thread_local_set_expand( mi_thread_local_t key, void* val ) {if (val==NULL) return true;- mi_thread_locals_t* tls = mi_thread_locals_expand(key);+ const size_t idx = mi_key_index(key);+ mi_thread_locals_t* tls = mi_thread_locals_expand(idx);if (tls==NULL) return false;- mi_assert_internal(key < tls->count);mi_assert_internal(tls == mi_thread_locals);- tls->slots[key] = val;+ mi_assert_internal(idx < tls->count);+ tls->slots[idx].value = val;+ tls->slots[idx].version = mi_key_version(key);return true;}@@ -69,8 +111,11 @@ static mi_decl_noinline bool mi_thread_local_set_expand( mi_thread_local_t key,bool _mi_thread_local_set( mi_thread_local_t key, void* val ) {mi_thread_locals_t* tls = mi_thread_locals;mi_assert_internal(tls!=NULL);- if mi_likely(key < tls->count) {- tls->slots[key] = val;+ mi_assert_internal(key!=0);+ const size_t idx = mi_key_index(key);+ if mi_likely(idx < tls->count) {+ tls->slots[idx].value = val;+ tls->slots[idx].version = mi_key_version(key);return true;}else {@@ -82,11 +127,13 @@ bool _mi_thread_local_set( mi_thread_local_t key, void* val ) {void* _mi_thread_local_get( mi_thread_local_t key ) {const mi_thread_locals_t* const tls = mi_thread_locals;mi_assert_internal(tls!=NULL);- if mi_likely(key < tls->count) {- return tls->slots[key];+ mi_assert_internal(key!=0);+ const size_t idx = mi_key_index(key);+ if mi_likely(idx < tls->count && mi_key_version(key) == tls->slots[idx].version) {+ return tls->slots[idx].value;}else {- return NULL;+ return NULL;}}@@ -105,6 +152,7 @@ Create and free fresh TLS key'sstatic mi_lock_t mi_thread_locals_lock; // we need a lock in order to re-allocate the slot bitsstatic mi_bitmap_t* mi_thread_locals_free; // reuse an arena bitmap to track which slots were assigned (1=free, 0=in-use)+static size_t mi_thread_locals_version; // version to be able to reuse slots safelyvoid _mi_thread_locals_init(void) {mi_lock_init(&mi_thread_locals_lock);@@ -119,43 +167,56 @@ void _mi_thread_locals_done(void) {}// strange signature but allows us to reuse the arena code for claiming free pages-static bool mi_thread_local_claim(size_t _slice_index, mi_arena_t* _arena, bool* keep_set) {+static bool mi_thread_local_claim_fun(size_t _slice_index, mi_arena_t* _arena, bool* keep_set) {MI_UNUSED(_slice_index); MI_UNUSED(_arena);*keep_set = false;return true;}-static mi_thread_local_t mi_thread_local_create_expand(void) {- size_t key = 0;- mi_bitmap_t* slots = mi_thread_locals_free;+// When we claim a free slot, we increase the global version counter+// (so if we reuse a slot it will be returning NULL initially when a thread tries to get it)+static mi_thread_local_t mi_thread_local_claim(void) {+ size_t idx = 0;+ if (mi_thread_locals_free != NULL && mi_bitmap_try_find_and_claim(mi_thread_locals_free,0,&idx,&mi_thread_local_claim_fun,NULL)) {+ mi_thread_locals_version++;+ if (mi_thread_locals_version >= MI_TLS_VERSION_MAX) { mi_thread_locals_version = 1; } /* wrap around the version */+ return mi_key_create( idx, mi_thread_locals_version);+ }+ else {+ return 0;+ }+}++static bool mi_thread_local_create_expand(void) {+ mi_bitmap_t* const slots = mi_thread_locals_free;// 1024 bits at a timeconst size_t oldcount = (slots==NULL ? 0 : mi_bitmap_max_bits(slots));const size_t newcount = 1024 + oldcount;+ if (newcount > MI_TLS_IDX_MAX) { return false; }const size_t newsize = mi_bitmap_size( newcount, NULL );- slots = (mi_bitmap_t*)mi_realloc_aligned(slots, newsize, MI_BCHUNK_SIZE);- if (slots != NULL) {- mi_bitmap_init(slots, newcount, true /* or otherwise we would zero all old entries */);- mi_bitmap_unsafe_setN(slots, oldcount, newcount - oldcount);- mi_thread_locals_free = slots;- size_t idx = 0;- if mi_likely(slots!=NULL && mi_bitmap_try_find_and_claim(slots,0,&idx,&mi_thread_local_claim,NULL)) {- key = idx+1;- }+ mi_bitmap_t* newslots = (mi_bitmap_t*)mi_zalloc_aligned(newsize, MI_BCHUNK_SIZE);+ if (newslots==NULL) { return false; }+ if (slots!=NULL) {+ // copy over the previous bitmap+ _mi_memcpy_aligned(newslots, slots, mi_bitmap_size(oldcount, NULL));+ mi_free(slots);}- return key;+ mi_bitmap_init(newslots, newcount, true /* pretend already zero'd so we do not zero out the copied old entries */);+ mi_bitmap_unsafe_setN(newslots, oldcount, newcount - oldcount); /* set the new expanded slots as available */+ mi_thread_locals_free = newslots;+ return true;}+// create a fresh keymi_thread_local_t _mi_thread_local_create(void) {mi_thread_local_t key = 0;mi_lock(&mi_thread_locals_lock) {- mi_bitmap_t* slots = mi_thread_locals_free;- size_t idx = 0;- if mi_likely(slots!=NULL && mi_bitmap_try_find_and_claim(slots,0,&idx,&mi_thread_local_claim,NULL)) {- key = idx+1;- }- else {- key = mi_thread_local_create_expand();+ key = mi_thread_local_claim();+ if (key==0) {+ if (mi_thread_local_create_expand()) {+ key = mi_thread_local_claim();+ }}}return key;@@ -164,11 +225,11 @@ mi_thread_local_t _mi_thread_local_create(void) {// free a keyvoid _mi_thread_local_free(mi_thread_local_t key) {if (key==0) return;- const size_t idx = key-1;+ const size_t idx = mi_key_index(key);mi_lock(&mi_thread_locals_lock) {mi_bitmap_t* const slots = mi_thread_locals_free;if (slots!=NULL && idx < mi_bitmap_max_bits(slots)) {- mi_bitmap_set(slots,key-1);+ mi_bitmap_set(slots,idx);}}}