diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 9e4ec30ba9d254..761b7a8abda3d9 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -78,6 +78,8 @@ workflows: - 'actions/setup-python@v7.0.0' '.github/workflows/verify-expat.yml': - 'actions/checkout@v7.0.1' + '.github/workflows/verify-mimalloc.yml': + - 'actions/checkout@v7.0.1' dependencies: 'actions/cache@v6.1.0': ref: 'v6.1.0' diff --git a/.github/workflows/verify-mimalloc.yml b/.github/workflows/verify-mimalloc.yml new file mode 100644 index 00000000000000..3cd52332e6da58 --- /dev/null +++ b/.github/workflows/verify-mimalloc.yml @@ -0,0 +1,38 @@ +name: Verify bundled mimalloc + +on: + workflow_dispatch: + push: + paths: + - 'Objects/mimalloc/**' + - 'Include/internal/mimalloc/**' + - '.github/workflows/verify-mimalloc.yml' + pull_request: + paths: + - 'Objects/mimalloc/**' + - 'Include/internal/mimalloc/**' + - '.github/workflows/verify-mimalloc.yml' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + verify: + runs-on: ubuntu-slim + timeout-minutes: 5 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Download and verify bundled mimalloc files + run: | + ./Objects/mimalloc/refresh.sh + # refresh.sh recreates the vendored files, so also report files + # that exist upstream but are not checked in. + git ls-files -z --others -- Objects/mimalloc/ Include/internal/mimalloc/ \ + | xargs -0 --no-run-if-empty git add --intent-to-add -- + git diff --exit-code Objects/mimalloc/ Include/internal/mimalloc/ diff --git a/Include/internal/mimalloc/mimalloc-new-delete.h b/Include/internal/mimalloc/mimalloc-new-delete.h new file mode 100644 index 00000000000000..362068662d0e51 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc-new-delete.h @@ -0,0 +1,66 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2020 Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MIMALLOC_NEW_DELETE_H +#define MIMALLOC_NEW_DELETE_H + +// ---------------------------------------------------------------------------- +// This header provides convenient overrides for the new and +// delete operations in C++. +// +// This header should be included in only one source file! +// +// On Windows, or when linking dynamically with mimalloc, these +// can be more performant than the standard new-delete operations. +// See +// --------------------------------------------------------------------------- +#if defined(__cplusplus) + #include + #include "mimalloc.h" + + #if defined(_MSC_VER) && defined(_Ret_notnull_) && defined(_Post_writable_byte_size_) + // stay consistent with VCRT definitions + #define mi_decl_new(n) mi_decl_nodiscard mi_decl_restrict _Ret_notnull_ _Post_writable_byte_size_(n) + #define mi_decl_new_nothrow(n) mi_decl_nodiscard mi_decl_restrict _Ret_maybenull_ _Success_(return != NULL) _Post_writable_byte_size_(n) + #else + #define mi_decl_new(n) mi_decl_nodiscard mi_decl_restrict + #define mi_decl_new_nothrow(n) mi_decl_nodiscard mi_decl_restrict + #endif + + void operator delete(void* p) noexcept { mi_free(p); }; + void operator delete[](void* p) noexcept { mi_free(p); }; + + void operator delete (void* p, const std::nothrow_t&) noexcept { mi_free(p); } + void operator delete[](void* p, const std::nothrow_t&) noexcept { mi_free(p); } + + mi_decl_new(n) void* operator new(std::size_t n) noexcept(false) { return mi_new(n); } + mi_decl_new(n) void* operator new[](std::size_t n) noexcept(false) { return mi_new(n); } + + mi_decl_new_nothrow(n) void* operator new (std::size_t n, const std::nothrow_t& tag) noexcept { (void)(tag); return mi_new_nothrow(n); } + mi_decl_new_nothrow(n) void* operator new[](std::size_t n, const std::nothrow_t& tag) noexcept { (void)(tag); return mi_new_nothrow(n); } + + #if (__cplusplus >= 201402L || (defined(_MSC_VER) && _MSC_VER >= 1916)) + void operator delete (void* p, std::size_t n) noexcept { mi_free_sized(p,n); }; + void operator delete[](void* p, std::size_t n) noexcept { mi_free_sized(p,n); }; + #endif + + #if (__cplusplus > 201402L && defined(__cpp_aligned_new)) + void operator delete (void* p, std::align_val_t al) noexcept { mi_free_aligned(p, static_cast(al)); } + void operator delete[](void* p, std::align_val_t al) noexcept { mi_free_aligned(p, static_cast(al)); } + void operator delete (void* p, std::size_t n, std::align_val_t al) noexcept { mi_free_sized_aligned(p, n, static_cast(al)); }; + void operator delete[](void* p, std::size_t n, std::align_val_t al) noexcept { mi_free_sized_aligned(p, n, static_cast(al)); }; + void operator delete (void* p, std::align_val_t al, const std::nothrow_t&) noexcept { mi_free_aligned(p, static_cast(al)); } + void operator delete[](void* p, std::align_val_t al, const std::nothrow_t&) noexcept { mi_free_aligned(p, static_cast(al)); } + + void* operator new (std::size_t n, std::align_val_t al) noexcept(false) { return mi_new_aligned(n, static_cast(al)); } + void* operator new[](std::size_t n, std::align_val_t al) noexcept(false) { return mi_new_aligned(n, static_cast(al)); } + void* operator new (std::size_t n, std::align_val_t al, const std::nothrow_t&) noexcept { return mi_new_aligned_nothrow(n, static_cast(al)); } + void* operator new[](std::size_t n, std::align_val_t al, const std::nothrow_t&) noexcept { return mi_new_aligned_nothrow(n, static_cast(al)); } + #endif +#endif + +#endif // MIMALLOC_NEW_DELETE_H diff --git a/Include/internal/mimalloc/mimalloc-override.h b/Include/internal/mimalloc/mimalloc-override.h new file mode 100644 index 00000000000000..38c4cfee6d33d9 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc-override.h @@ -0,0 +1,72 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2020 Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MIMALLOC_OVERRIDE_H +#define MIMALLOC_OVERRIDE_H + +/* ---------------------------------------------------------------------------- +This header can be used to statically redirect malloc/free and new/delete +to the mimalloc variants. This can be useful if one can include this file on +each source file in a project (but be careful when using external code to +not accidentally mix pointers from different allocators). +-----------------------------------------------------------------------------*/ + +#include "mimalloc.h" + +// Standard C allocation +#define malloc(n) mi_malloc(n) +#define calloc(c,n) mi_calloc(c,n) +#define realloc(p,n) mi_realloc(p,n) +#define free(p) mi_free(p) + +#define strdup(s) mi_strdup(s) +#define strndup(s,n) mi_strndup(s,n) +#define realpath(f,n) mi_realpath(f,n) + +// Microsoft extensions +#define _expand(p,n) mi_expand(p,n) +#define _msize(p) mi_usable_size(p) +#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) mi_wcsdup(s) +#define _mbsdup(s) mi_mbsdup(s) +#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(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,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) +#define _posix_memalign(p,a,n) mi_posix_memalign(p,a,n) + +// C23 +#define free_sized(p,n) mi_free_sized(p,n) +#define free_aligned_sized(p,a,n) mi_free_aligned_sized(p,a,n) + +// 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,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,c,n,a,o) mi_aligned_offset_recalloc(p,c,n,a,o) + +#endif // MIMALLOC_OVERRIDE_H diff --git a/Include/internal/mimalloc/mimalloc-profile.h b/Include/internal/mimalloc/mimalloc-profile.h new file mode 100644 index 00000000000000..7365b78fdec3f6 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc-profile.h @@ -0,0 +1,134 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2024-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MIMALLOC_PROFILE_H +#define MIMALLOC_PROFILE_H + +#include "mimalloc.h" +#include // bool +#include // uint64_t + +//--------------------------------------------------------------------------- +// Initial support for profiling hooks; still experimental +//--------------------------------------------------------------------------- + +#define MI_PROFILE_SAMPLE_DATA_MAX_SIZE (1024) + +// User defined profiler; see `test_profile.c` for an example. +typedef struct mi_profiler_s mi_profiler_t; + +// Profiler data is stored together with each sampled allocation (unless the `on_free` field in the profiler is NULL.) +typedef struct mi_profiler_sample_data_s { + size_t user_data_size; // size of the user_data (should be the `mi_profiler_t.sample_data_size`) + void* user_data[1]; // default, but can be less or more (up to 1KiB), depending on `sample_data_size` +} mi_profiler_sample_data_t; + +// Profiling callback invoked on each sampled allocation. +// If `profiler_data!=NULL` (i.e. when `on_free` is not NULL), then `profiler_data->requested_size == requested_size`. +typedef size_t (mi_cdecl mi_profiler_on_alloc_fun)(mi_profiler_t* profiler, mi_profiler_sample_data_t* profiler_data, void* ptr, size_t requested_size, size_t bytes_sample_rate, uint64_t bytes_since_last_sample, mi_heap_t* heap); + +// Profiling callback invoked on each sampled in-place re-allocation. +typedef size_t (mi_cdecl mi_profiler_on_realloc_inplace_fun)(mi_profiler_t* profiler, mi_profiler_sample_data_t* profiler_data, void* ptr, size_t old_size, mi_heap_t* heap); + +// Profiling callback invoked on a previously sampled allocation. +typedef void (mi_cdecl mi_profiler_on_free_fun)(mi_profiler_t* profiler, mi_profiler_sample_data_t* profiler_data, void* ptr, mi_heap_t* heap); + +// Profiling callback invoked on mi_profiler_snapshot() +typedef void (mi_cdecl mi_profiler_on_snapshot_fun)(mi_profiler_t* profiler); + +// A profiler +// All fields are considered immutable such that they can be copied and accessed concurrently. All fields can be NULL/0. +struct mi_profiler_s { + void* reserved; // opaque; reserved by mimalloc + size_t sample_data_size; // size of required profiler data for each sampled allocation (or zero for no data) + size_t initial_sample_rate;// initial sample rate in bytes (set to at least 1 or higher) (can be adjusted by `on_alloc`) + mi_profiler_on_alloc_fun* on_alloc; // called on a sampled allocation (may be called concurrently) + mi_profiler_on_free_fun* on_free; // called when an allocation, sampled by this profiler since it was last attached, is freed (may be called concurrently) + mi_profiler_on_realloc_inplace_fun* on_realloc_inplace; // (as yet unused) called on in-place reallocation of a previous sampled allocation (may be called concurrently) + mi_profiler_on_snapshot_fun* on_snapshot; // called on mi_profiler_snapshot() (only one thread at a time) + // ... more user fields allowed +}; + +// Exported definitions +#ifdef __cplusplus +extern "C" { +#endif + +// attach a profiler to a particular heap only (this stops the profiler; use `mi_profiler_start` to start sampling). +// `on_free` is only called for allocations sampled by the profiler after it was (last) attached; +// this makes it safe to switch profilers, or to re-attach a profiler after re-initializing its state. +mi_decl_export bool mi_heap_profile(mi_heap_t* heap, mi_profiler_t* profiler); + +// disable profiling for a particular heap; useful for a heap that the profiler uses itself for metadata. +mi_decl_export void mi_heap_profile_disable(mi_heap_t* heap); + +// attach a profiler to any (current and future) heaps in a sub-process (unless those heaps disabled profiling) (see `mi_heap_profile`) +mi_decl_export bool mi_subproc_profile(mi_subproc_id_t subproc_id, mi_profiler_t* profiler); + +// attach a profiler to any heaps in the main sub-process (use NULL to detach) +mi_decl_export bool mi_profile(mi_profiler_t* profiler); + +// start sampling; returns whether the profiler was already running (not a success flag) +mi_decl_export bool mi_profiler_start(mi_profiler_t* profiler); + +// end sampling; returns whether the profiler was running (but `on_free` is still called for sampled allocations until the profiler is detached). +// Note: a profiler can only be deleted once it is detached and no other threads may still use it (call `on_free`). +mi_decl_export bool mi_profiler_stop(mi_profiler_t* profiler); + +// snapshot the current profile (may be called concurrently but only one thread will actually call the snapshot callback) +mi_decl_export void mi_profiler_snapshot(mi_profiler_t* profiler); + +// builtin pprof compatible profiler +// +// With MI_SECURE=0 (and MI_SECURE_ENV=0), the builtin profiler can also be activated using environment variables as: +// `MIMALLOC_PROFILE=` +// (and optionally `MIMALLOC_PROFILE_ALLOC_INTERVAL=`, `MIMALLOC_PROFILE_INUSE_INTERVAL=`, or +// `MIMALLOC_PROFILE_TIME_INTERVAL=` to periodically snapshot while the program is running). +// +// You can also start it programmatically using `mi_pprof_profiler_new` and `mi_profiler_start`: +// ```c +// #include +// #include + +// int main(void) { +// mi_profiler_t* prof = mi_pprof_profiler_new( +// 512 * 1024, // sample roughly every 512 KiB +// "myprofile", // output basename; protobuf format +// 0, 0, 0); // no automatic snapshots +// if (prof == NULL) return 1; +// +// if (!mi_profile(prof)) { +// mi_profile(NULL); +// mi_pprof_profiler_delete(prof); +// return 1; +// } +// mi_profiler_start(prof); +// +// // Run your workload here; join worker threads before cleanup. +// +// mi_profiler_stop(prof); +// mi_profiler_snapshot(prof); +// mi_profile(NULL); // detach before deleting +// mi_pprof_profiler_delete(prof); +// return 0; +// } +// ``` +// +// `base_file_name` selects the text snapshot format if it ends in `.heap` or `.text` (the extension is +// stripped); any other extension, or none, uses the default (protobuf) snapshot format. +// `alloc_interval_size`, if >0, automatically snapshots every that many allocated bytes. +// `inuse_interval_size`, if >0, automatically snapshots every time the in-use bytes grow by that many bytes. +// `time_interval_secs`, if >0, automatically snapshots every that many seconds (checked from allocation events). +mi_decl_export mi_profiler_t* mi_pprof_profiler_new(size_t initial_threshold, const char* base_file_name, size_t alloc_interval_size, size_t inuse_interval_size, size_t time_interval_secs); +mi_decl_export void mi_pprof_profiler_delete(mi_profiler_t* profiler); + + +#ifdef __cplusplus +} +#endif + +#endif // MIMALLOC_PROFILE_H diff --git a/Include/internal/mimalloc/mimalloc-stats.h b/Include/internal/mimalloc/mimalloc-stats.h index b6c2a2f22009d9..dad0f55590c685 100644 --- a/Include/internal/mimalloc/mimalloc-stats.h +++ b/Include/internal/mimalloc/mimalloc-stats.h @@ -1,5 +1,5 @@ /* ---------------------------------------------------------------------------- -Copyright (c) 2018-2025, Microsoft Research, Daan Leijen +Copyright (c) 2024-2026, Microsoft Research, Daan Leijen This is free software; you can redistribute it and/or modify it under the terms of the MIT license. A copy of the license can be found in the file "LICENSE" at the root of this distribution. @@ -9,9 +9,22 @@ terms of the MIT license. A copy of the license can be found in the file #define MIMALLOC_STATS_H #include "mimalloc.h" -#include +#include // memset +#include // int64_t + +#define MI_STAT_VERSION 6 // increased on every backward incompatible change + +// alignment for atomic fields +#if defined(_MSC_VER) +#define mi_decl_align(a) __declspec(align(a)) +#elif defined(__GNUC__) +#define mi_decl_align(a) __attribute__((aligned(a))) +#elif defined(__cplusplus) && __cplusplus >= 201103L +#define mi_decl_align(a) alignas(a) +#else +#define mi_decl_align(a) _Alignas(a) +#endif -#define MI_STAT_VERSION 4 // increased on every backward incompatible change // count allocation over time typedef struct mi_stat_count_s { @@ -34,17 +47,17 @@ typedef struct mi_stat_counter_s { MI_STAT_COUNT(page_committed) /* committed memory inside pages */ \ 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 */ \ - MI_STAT_COUNT(malloc_requested) /* malloc requested bytes */ \ + MI_STAT_COUNT(allocated) /* allocated bytes */ \ + MI_STAT_COUNTER(malloc_count) /* total number of malloc calls */ \ + MI_STAT_COUNTER(free_count) /* total number of free calls */ \ + MI_STAT_COUNTER(freed) /* total free'd bytes (note: total allocated is `allocated.total`) */ \ + MI_STAT_COUNTER(malloc_requested) /* malloc requested bytes */ \ \ MI_STAT_COUNTER(mmap_calls) \ MI_STAT_COUNTER(commit_calls) \ MI_STAT_COUNTER(reset_calls) \ MI_STAT_COUNTER(purge_calls) \ MI_STAT_COUNTER(arena_count) /* number of memory arena's */ \ - MI_STAT_COUNTER(malloc_normal_count) /* number of blocks <= MI_LARGE_OBJ_SIZE_MAX */ \ - MI_STAT_COUNTER(malloc_huge_count) /* number of huge bloks */ \ MI_STAT_COUNTER(malloc_guarded_count) /* number of allocations with guard pages */ \ \ /* internal statistics */ \ @@ -60,10 +73,36 @@ typedef struct mi_stat_counter_s { MI_STAT_COUNT(segments_cache) \ MI_STAT_COUNT(_segments_reserved) \ /* only on v3 */ \ + MI_STAT_COUNT(heaps) \ + MI_STAT_COUNT(theaps) \ + MI_STAT_COUNT(pages_os_abandoned) /* pages in the os abandoned list (bad) */ \ + MI_STAT_COUNT(pages_os_allocated) /* pages allocated outside arenas (bad) */ \ 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_unown_cas_retry) \ + MI_STAT_COUNTER(heaps_delete_wait) \ + MI_STAT_COUNTER(pages_stat_updates) /* calls to successful page_stat_update */ \ + MI_STAT_COUNTER(pages_stat_update_count) /* total free/allocs */ \ + MI_STAT_COUNTER(profile_samples) /* total sampled profiled allocations */ \ + /* deprecated */ \ + MI_STAT_COUNT(malloc_normal) /* allocated bytes <= MI_LARGE_OBJ_SIZE_MAX */ \ + MI_STAT_COUNT(malloc_huge) /* allocated bytes in huge pages */ \ + MI_STAT_COUNTER(malloc_normal_count) /* number of blocks <= MI_LARGE_OBJ_SIZE_MAX */ \ + MI_STAT_COUNTER(malloc_huge_count) /* number of huge bloks */ \ + + +// Size bins for chunks +typedef enum mi_chunkbin_e { + MI_CBIN_SMALL, // slice_count == 1 + MI_CBIN_OTHER, // slice_count: any other from the other bins, and 1 <= slice_count <= MI_BCHUNK_BITS + MI_CBIN_MEDIUM, // slice_count == 8 + MI_CBIN_LARGE, // slice_count == MI_SIZE_BITS (only used if MI_ENABLE_LARGE_PAGES is 1) + MI_CBIN_HUGE, // slice_count > MI_BCHUNK_BITS + MI_CBIN_NONE, // no bin assigned yet (the chunk is completely free) + MI_CBIN_COUNT +} mi_chunkbin_t; // Define the statistics structure @@ -76,7 +115,7 @@ typedef struct mi_stats_s size_t size; // size of the mi_stats_t structure size_t version; - MI_STAT_FIELDS() + mi_decl_align(8) MI_STAT_FIELDS() // future extension mi_stat_count_t _stat_reserved[4]; @@ -85,21 +124,62 @@ typedef struct mi_stats_s // size segregated statistics mi_stat_count_t malloc_bins[MI_BIN_HUGE+1]; // allocation per size bin mi_stat_count_t page_bins[MI_BIN_HUGE+1]; // pages allocated per size bin + mi_stat_count_t chunk_bins[MI_CBIN_COUNT]; // chunks per page sizes } mi_stats_t; #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); +} + +// Always use this to declare and initialize a `mi_stats_t` variable such +// that the version and size can be checked at runtime. +#define mi_stats_t_decl(name) mi_stats_t name; mi_stats_init(&name); // Exported definitions #ifdef __cplusplus extern "C" { #endif -mi_decl_export bool mi_stats_get( mi_stats_t* stats ) mi_attr_noexcept; -mi_decl_export char* mi_stats_get_json( size_t buf_size, char* buf ) mi_attr_noexcept; // use mi_free to free the result if the input buf == NULL +// stats from a heap +mi_decl_export bool mi_heap_stats_get(mi_heap_t* heap, mi_stats_t* stats) mi_attr_noexcept; +mi_decl_export char* mi_heap_stats_get_json(mi_heap_t* heap, size_t buf_size, char* buf) mi_attr_noexcept; // use mi_free to free the result if the input buf == NULL +mi_decl_export void mi_heap_stats_print_out(mi_heap_t* heap, mi_output_fun* out, void* arg) mi_attr_noexcept; + +// stats from a subprocess and its heaps aggregated +mi_decl_export bool mi_subproc_stats_get(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept; +mi_decl_export char* mi_subproc_stats_get_json(mi_subproc_id_t subproc_id, size_t buf_size, char* buf) mi_attr_noexcept; // use mi_free to free the result if the input buf == NULL +mi_decl_export void mi_subproc_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun* out, void* arg) mi_attr_noexcept; +// print subprocess and all its heap stats segregated +mi_decl_export void mi_subproc_heap_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun* out, void* arg) mi_attr_noexcept; + +// stats aggregated for the current subprocess and all its heaps. +mi_decl_export bool mi_stats_get(mi_stats_t* stats) mi_attr_noexcept; +mi_decl_export char* mi_stats_get_json(size_t buf_size, char* buf) mi_attr_noexcept; // use mi_free to free the result if the input buf == NULL +mi_decl_export void mi_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; + +// add the stats of the heap to the subprocess and clear the heap stats +mi_decl_export void mi_heap_stats_merge_to_subproc(mi_heap_t* heap); + +// stats from the subprocess without aggregating its heaps +mi_decl_export bool mi_subproc_stats_get_exclusive(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept; + +mi_decl_export char* mi_stats_as_json(mi_stats_t* stats, size_t buf_size, char* buf) mi_attr_noexcept; // use mi_free to free the result if the input buf == NULL +mi_decl_export size_t mi_stats_get_bin_size(size_t bin) mi_attr_noexcept; + +// get theap stats (only thread safe on theaps belonging to the calling thread) +mi_decl_export bool mi_theap_stats_get(mi_theap_t* theap, mi_stats_t* stats) mi_attr_noexcept; + +// add the theap stats to the stats of the parent heap and clear the theap stats +mi_decl_export void mi_theap_stats_merge_to_heap(mi_theap_t* theap) mi_attr_noexcept; #ifdef __cplusplus } diff --git a/Include/internal/mimalloc/mimalloc.h b/Include/internal/mimalloc/mimalloc.h index 64a5e803bd2096..b1952f8262c2fe 100644 --- a/Include/internal/mimalloc/mimalloc.h +++ b/Include/internal/mimalloc/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 20502 // major + 2 digits minor + 2 digits patch +#define MI_MALLOC_VERSION 30702 // major + 2 digits minor + 2 digits patch // ------------------------------------------------------ // Compiler specific attributes @@ -36,14 +36,24 @@ terms of the MIT license. A copy of the license can be found in the file #define mi_decl_nodiscard #endif -#if defined(_MSC_VER) || defined(__MINGW32__) - #if !defined(MI_SHARED_LIB) - #define mi_decl_export - #elif defined(MI_SHARED_LIB_EXPORT) - #define mi_decl_export __declspec(dllexport) +// mi_decl_export can be predefined, e.g. to export the API from a static library built with -fvisibility=hidden +#if !defined(mi_decl_export) + #if defined(_MSC_VER) || defined(__MINGW32__) + #if !defined(MI_SHARED_LIB) || !MI_SHARED_LIB + #define mi_decl_export + #elif defined(MI_SHARED_LIB_EXPORT) && MI_SHARED_LIB_EXPORT + #define mi_decl_export __declspec(dllexport) + #else + #define mi_decl_export __declspec(dllimport) + #endif + #elif defined(__GNUC__) && defined(MI_SHARED_LIB) && MI_SHARED_LIB && defined(MI_SHARED_LIB_EXPORT) && MI_SHARED_LIB_EXPORT + #define mi_decl_export __attribute__((visibility("default"))) #else - #define mi_decl_export __declspec(dllimport) + #define mi_decl_export #endif +#endif + +#if defined(_MSC_VER) || defined(__MINGW32__) #if defined(__MINGW32__) #define mi_decl_restrict #define mi_attr_malloc __attribute__((malloc)) @@ -56,18 +66,15 @@ terms of the MIT license. A copy of the license can be found in the file #define mi_attr_malloc #endif #define mi_cdecl __cdecl + #define mi_attr_pure #define mi_attr_alloc_size(s) #define mi_attr_alloc_size2(s1,s2) #define mi_attr_alloc_align(p) #elif defined(__GNUC__) // includes clang and icc - #if defined(MI_SHARED_LIB) && defined(MI_SHARED_LIB_EXPORT) - #define mi_decl_export __attribute__((visibility("default"))) - #else - #define mi_decl_export - #endif #define mi_cdecl // leads to warnings... __attribute__((cdecl)) #define mi_decl_restrict #define mi_attr_malloc __attribute__((malloc)) + #define mi_attr_pure __attribute__((pure)) #if (defined(__clang_major__) && (__clang_major__ < 4)) || (__GNUC__ < 5) #define mi_attr_alloc_size(s) #define mi_attr_alloc_size2(s1,s2) @@ -83,9 +90,9 @@ terms of the MIT license. A copy of the license can be found in the file #endif #else #define mi_cdecl - #define mi_decl_export #define mi_decl_restrict #define mi_attr_malloc + #define mi_attr_pure #define mi_attr_alloc_size(s) #define mi_attr_alloc_size2(s1,s2) #define mi_attr_alloc_align(p) @@ -97,7 +104,7 @@ terms of the MIT license. A copy of the license can be found in the file #include // size_t, wchar_t #include // bool -#include // INTPTR_MAX +#include // inline assertions #ifdef __cplusplus extern "C" { @@ -118,10 +125,10 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_strndup(const char* s mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_realpath(const char* fname, char* resolved_name) mi_attr_noexcept; // ------------------------------------------------------ -// Extended functionality +// Extended allocation functions // ------------------------------------------------------ #define MI_SMALL_WSIZE_MAX 128 -#define MI_SMALL_SIZE_MAX (MI_SMALL_WSIZE_MAX*sizeof(void*)) +#define MI_SMALL_SIZE_MAX (MI_SMALL_WSIZE_MAX*sizeof(size_t)) // mimalloc considers `sizeof(size_t)` as the machine word size mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_malloc_small(size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_zalloc_small(size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); @@ -131,16 +138,69 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_mallocn(size_t count, mi_decl_nodiscard mi_decl_export void* mi_reallocn(void* p, size_t count, size_t size) mi_attr_noexcept mi_attr_alloc_size2(2,3); mi_decl_nodiscard mi_decl_export void* mi_reallocf(void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(2); -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_decl_nodiscard mi_decl_export size_t mi_usable_size(const void* p) mi_attr_noexcept mi_attr_pure; +mi_decl_nodiscard mi_decl_export size_t mi_allocated_size(const void* p) mi_attr_noexcept mi_attr_pure; +mi_decl_nodiscard mi_decl_export size_t mi_good_size(size_t size) mi_attr_noexcept mi_attr_pure; + +// `mi_free_sized` can be more efficient (as it calls mi_free_small internally). +mi_decl_export void mi_free_sized(void* p, size_t size) mi_attr_noexcept; -// for compat with v3. +// `mi_free_small` is for special applications like language runtimes. +// it should only be used to free objects from `mi_*alloc_small` and is potentially a tiny bit faster than `mi_free` mi_decl_export void mi_free_small(void* p) mi_attr_noexcept; +// As `mi_free_small` but `p` should not be a NULL pointer. +mi_decl_export void mi_free_small_nonnull(void* p) mi_attr_noexcept; + +mi_decl_export void mi_free_sized_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; + +// Checked free: always checks the pointer is valid before free-ing (and otherwise ignores the pointer) +mi_decl_export bool mi_cfree(void* p) mi_attr_noexcept; + + +// ------------------------------------------------------------------------------------- +// Aligned allocation +// Note that `alignment` always follows `size` for consistency with unaligned +// allocation, but unfortunately this differs from `posix_memalign` and `aligned_alloc`. +// ------------------------------------------------------------------------------------- + +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_malloc_aligned(size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_malloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_zalloc_aligned(size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_zalloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_calloc_aligned(size_t count, size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(1, 2) mi_attr_alloc_align(3); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_calloc_aligned_at(size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(1, 2); +mi_decl_nodiscard mi_decl_export void* mi_realloc_aligned(void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(2) mi_attr_alloc_align(3); +mi_decl_nodiscard mi_decl_export void* mi_realloc_aligned_at(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(2); + + +// ------------------------------------------------------ +// Typed allocation, the type is always the first parameter +// ------------------------------------------------------ + +#define mi_malloc_tp(tp) ((tp*)mi_malloc_csize(sizeof(tp))) +#define mi_zalloc_tp(tp) ((tp*)mi_zalloc_csize(sizeof(tp))) +#define mi_calloc_tp(tp,n) ((tp*)mi_calloc(n,sizeof(tp))) +#define mi_mallocn_tp(tp,n) ((tp*)mi_mallocn(n,sizeof(tp))) +#define mi_reallocn_tp(tp,p,n) ((tp*)mi_reallocn(p,n,sizeof(tp))) +#define mi_recalloc_tp(tp,p,o,n) ((tp*)mi_recalloc(p,o,n,sizeof(tp))) +#define mi_free_tp(tp,p) (mi_free_csize(p,sizeof(tp))) + +#define mi_heap_malloc_tp(tp,hp) ((tp*)mi_heap_malloc(hp,sizeof(tp))) +#define mi_heap_zalloc_tp(tp,hp) ((tp*)mi_heap_zalloc(hp,sizeof(tp))) +#define mi_heap_calloc_tp(tp,hp,n) ((tp*)mi_heap_calloc(hp,n,sizeof(tp))) +#define mi_heap_mallocn_tp(tp,hp,n) ((tp*)mi_heap_mallocn(hp,n,sizeof(tp))) +#define mi_heap_reallocn_tp(tp,hp,p,n) ((tp*)mi_heap_reallocn(hp,p,n,sizeof(tp))) +#define mi_heap_recalloc_tp(tp,hp,p,o,n) ((tp*)mi_heap_recalloc(hp,p,o,n,sizeof(tp))) + + // ------------------------------------------------------ // Internals +// See also `mimalloc-stats.h` for statistics // ------------------------------------------------------ +// Callbacks are always called with their registered argument, but other threads may briefly call a previously registered one. typedef void (mi_cdecl mi_deferred_free_fun)(bool force, unsigned long long heartbeat, void* arg); mi_decl_export void mi_register_deferred_free(mi_deferred_free_fun* deferred_free, void* arg) mi_attr_noexcept; @@ -150,84 +210,78 @@ mi_decl_export void mi_register_output(mi_output_fun* out, void* arg) mi_attr_no typedef void (mi_cdecl mi_error_fun)(int err, void* arg); mi_decl_export void mi_register_error(mi_error_fun* fun, void* arg); -mi_decl_export void mi_collect(bool force) mi_attr_noexcept; -mi_decl_export int mi_version(void) mi_attr_noexcept; -mi_decl_export void mi_stats_reset(void) mi_attr_noexcept; -mi_decl_export void mi_stats_merge(void) mi_attr_noexcept; -mi_decl_export void mi_stats_print(void* out) mi_attr_noexcept; // backward compatibility: `out` is ignored and should be NULL -mi_decl_export void mi_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; -mi_decl_export void mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; -mi_decl_export void mi_options_print(void) mi_attr_noexcept; - +mi_decl_export void mi_collect(bool force) mi_attr_noexcept; +mi_decl_export int mi_version(void) mi_attr_pure; +mi_decl_export void mi_options_print(void) mi_attr_noexcept; +mi_decl_export void mi_process_info_print(void) mi_attr_noexcept; +mi_decl_export void mi_options_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; +mi_decl_export void mi_process_info_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; 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; + // Generally do not use the following as these are usually called automatically mi_decl_export void mi_process_init(void) mi_attr_noexcept; mi_decl_export void mi_cdecl mi_process_done(void) mi_attr_noexcept; mi_decl_export void mi_thread_init(void) mi_attr_noexcept; mi_decl_export void mi_thread_done(void) mi_attr_noexcept; - - -// ------------------------------------------------------------------------------------- -// Aligned allocation -// Note that `alignment` always follows `size` for consistency with unaligned -// allocation, but unfortunately this differs from `posix_memalign` and `aligned_alloc`. -// ------------------------------------------------------------------------------------- - -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_malloc_aligned(size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_malloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_zalloc_aligned(size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_zalloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_calloc_aligned(size_t count, size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(1,2) mi_attr_alloc_align(3); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_calloc_aligned_at(size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(1,2); -mi_decl_nodiscard mi_decl_export void* mi_realloc_aligned(void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(2) mi_attr_alloc_align(3); -mi_decl_nodiscard mi_decl_export void* mi_realloc_aligned_at(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(2); +mi_decl_export void mi_thread_set_in_threadpool(void) mi_attr_noexcept; // communicate that a thread is in a threadpool // ----------------------------------------------------------------- -// Return allocated block size (if the return value is not NULL) +// Return the usable size (`mi_usable_size`) (if the return value is not NULL) +// (no `alloc_size` attribute as the full usable size can be used, see `_FORTIFY_SOURCE`) // ----------------------------------------------------------------- -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc(size_t size, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_ucalloc(size_t count, size_t size, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size2(1,2); -mi_decl_nodiscard mi_decl_export void* mi_urealloc(void* p, size_t newsize, size_t* block_size_pre, size_t* block_size_post) mi_attr_noexcept mi_attr_alloc_size(2); -mi_decl_export void mi_ufree(void* p, size_t* block_size) mi_attr_noexcept; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_ucalloc(size_t count, size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export void* mi_urealloc(void* p, size_t newsize, size_t* usable_size_pre, size_t* usable_size_post) mi_attr_noexcept; +mi_decl_export void mi_ufree(void* p, size_t* usable_size) mi_attr_noexcept; -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_aligned(size_t size, size_t alignment, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_aligned(size_t size, size_t alignment, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_aligned(size_t size, size_t alignment, size_t* usable_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_align(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_aligned(size_t size, size_t alignment, size_t* usable_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_align(2); +mi_decl_nodiscard mi_decl_export void* mi_urealloc_aligned(void* p, size_t newsize, size_t alignment, size_t* usable_size_pre, size_t* usable_size_post) mi_attr_noexcept mi_attr_alloc_align(3); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_small(size_t size, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_small(size_t size, size_t* block_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_small(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_small(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc; // ------------------------------------------------------------------------------------- -// Heaps: first-class, but can only allocate from the same thread that created it. +// Heaps: first-class. Can allocate from any thread (and be free'd from any thread) +// Heaps keep allocations in separate pages from each other (but share the arena's and free'd pages) // ------------------------------------------------------------------------------------- struct mi_heap_s; typedef struct mi_heap_s mi_heap_t; mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_new(void); -mi_decl_export void mi_heap_delete(mi_heap_t* heap); -mi_decl_export void mi_heap_destroy(mi_heap_t* heap); -mi_decl_export mi_heap_t* mi_heap_set_default(mi_heap_t* heap); -mi_decl_export mi_heap_t* mi_heap_get_default(void); -mi_decl_export mi_heap_t* mi_heap_get_backing(void); -mi_decl_export void mi_heap_collect(mi_heap_t* heap, bool force) mi_attr_noexcept; - -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc(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(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_export void mi_heap_delete(mi_heap_t* heap); // move live blocks to the main heap +mi_decl_export void mi_heap_destroy(mi_heap_t* heap); // free all live blocks +mi_decl_export void mi_thread_heap_release(mi_heap_t* heap) mi_attr_noexcept; // the calling thread promises to no longer allocate in the heap (but blocks can still be freed) + +mi_decl_export void mi_heap_set_numa_affinity(mi_heap_t* heap, int numa_node); +mi_decl_export void mi_heap_set_debug_fill_preserve(mi_heap_t* heap, size_t preserve); // in debug mode, do not fill the first `preserve` bytes of blocks on allocation or free +mi_decl_export void mi_heap_collect(mi_heap_t* heap, bool force); + +mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_main(void); +mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_of(const void* p); +mi_decl_nodiscard mi_decl_export bool mi_heap_contains(const mi_heap_t* heap, const void* p); +mi_decl_nodiscard mi_decl_export bool mi_any_heap_contains(const void* p); + +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_malloc(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_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* 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); -mi_decl_nodiscard mi_decl_export void* mi_heap_reallocf(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); +mi_decl_nodiscard mi_decl_export void* mi_heap_reallocf(mi_heap_t* theap, void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3); 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; @@ -245,149 +299,223 @@ mi_decl_nodiscard mi_decl_export void* mi_heap_realloc_aligned_at(mi_heap_t* hea // -------------------------------------------------------------------------------- // Zero initialized re-allocation. -// Only valid on memory that was originally allocated with zero initialization too. -// e.g. `mi_calloc`, `mi_zalloc`, `mi_zalloc_aligned` etc. -// see // -------------------------------------------------------------------------------- -mi_decl_nodiscard mi_decl_export void* mi_rezalloc(void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(2); -mi_decl_nodiscard mi_decl_export void* mi_recalloc(void* p, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(2,3); - -mi_decl_nodiscard mi_decl_export void* mi_rezalloc_aligned(void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(2) mi_attr_alloc_align(3); -mi_decl_nodiscard mi_decl_export void* mi_rezalloc_aligned_at(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(2); -mi_decl_nodiscard mi_decl_export void* mi_recalloc_aligned(void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(2,3) mi_attr_alloc_align(4); -mi_decl_nodiscard mi_decl_export void* mi_recalloc_aligned_at(void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(2,3); - -mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc(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_recalloc(mi_heap_t* heap, void* p, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(3,4); - -mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(3) mi_attr_alloc_align(4); -mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(3); -mi_decl_nodiscard mi_decl_export void* mi_heap_recalloc_aligned(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(3,4) mi_attr_alloc_align(5); -mi_decl_nodiscard mi_decl_export void* mi_heap_recalloc_aligned_at(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(3,4); +mi_decl_nodiscard mi_decl_export void* mi_rezalloc_sized(void* p, size_t oldsize, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3); +mi_decl_nodiscard mi_decl_export void* mi_recalloc_sized(void* p, size_t oldcount, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(3,4); + +mi_decl_nodiscard mi_decl_export void* mi_rezalloc_aligned_sized(void* p, size_t oldsize, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(3) mi_attr_alloc_align(4); +mi_decl_nodiscard mi_decl_export void* mi_rezalloc_aligned_at_sized(void* p, size_t oldsize, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(3); +mi_decl_nodiscard mi_decl_export void* mi_recalloc_aligned_sized(void* p, size_t oldcount, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(3,4) mi_attr_alloc_align(5); +mi_decl_nodiscard mi_decl_export void* mi_recalloc_aligned_at_sized(void* p, size_t oldcount, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(3,4); + +mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc_sized(mi_heap_t* heap, void* p, size_t oldsize, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(4); +mi_decl_nodiscard mi_decl_export void* mi_heap_recalloc_sized(mi_heap_t* heap, void* p, size_t oldcount, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(4,5); + +mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc_aligned_sized(mi_heap_t* heap, void* p, size_t oldsize, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(4) mi_attr_alloc_align(5); +mi_decl_nodiscard mi_decl_export void* mi_heap_rezalloc_aligned_at_sized(mi_heap_t* heap, void* p, size_t oldsize, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(4); +mi_decl_nodiscard mi_decl_export void* mi_heap_recalloc_aligned_sized(mi_heap_t* heap, void* p, size_t oldcount, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(4,5) mi_attr_alloc_align(6); +mi_decl_nodiscard mi_decl_export void* mi_heap_recalloc_aligned_at_sized(mi_heap_t* heap, void* p, size_t oldcount, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(4,5); + +// Use the `_sized` link names to stay binary compatible with the previous signatures (see the deprecated declarations below). +#define mi_rezalloc(p,oldsize,newsize) mi_rezalloc_sized(p,oldsize,newsize) +#define mi_recalloc(p,oldcount,newcount,size) mi_recalloc_sized(p,oldcount,newcount,size) +#define mi_rezalloc_aligned(p,oldsize,newsize,alignment) mi_rezalloc_aligned_sized(p,oldsize,newsize,alignment) +#define mi_rezalloc_aligned_at(p,oldsize,newsize,alignment,offset) mi_rezalloc_aligned_at_sized(p,oldsize,newsize,alignment,offset) +#define mi_recalloc_aligned(p,oldcount,newcount,size,alignment) mi_recalloc_aligned_sized(p,oldcount,newcount,size,alignment) +#define mi_recalloc_aligned_at(p,oldcount,newcount,size,alignment,offset) mi_recalloc_aligned_at_sized(p,oldcount,newcount,size,alignment,offset) +#define mi_heap_rezalloc(heap,p,oldsize,newsize) mi_heap_rezalloc_sized(heap,p,oldsize,newsize) +#define mi_heap_recalloc(heap,p,oldcount,newcount,size) mi_heap_recalloc_sized(heap,p,oldcount,newcount,size) +#define mi_heap_rezalloc_aligned(heap,p,oldsize,newsize,alignment) mi_heap_rezalloc_aligned_sized(heap,p,oldsize,newsize,alignment) +#define mi_heap_rezalloc_aligned_at(heap,p,oldsize,newsize,alignment,offset) mi_heap_rezalloc_aligned_at_sized(heap,p,oldsize,newsize,alignment,offset) +#define mi_heap_recalloc_aligned(heap,p,oldcount,newcount,size,alignment) mi_heap_recalloc_aligned_sized(heap,p,oldcount,newcount,size,alignment) +#define mi_heap_recalloc_aligned_at(heap,p,oldcount,newcount,size,alignment,offset) mi_heap_recalloc_aligned_at_sized(heap,p,oldcount,newcount,size,alignment,offset) // ------------------------------------------------------ -// Analysis +// Visiting pages and individual blocks in a heap. // ------------------------------------------------------ -mi_decl_export bool mi_heap_contains_block(mi_heap_t* heap, const void* p); -mi_decl_export bool mi_heap_check_owned(mi_heap_t* heap, const void* p); -mi_decl_export bool mi_check_owned(const void* p); - // An area of heap space contains blocks of a single size. typedef struct mi_heap_area_s { - void* blocks; // start of the area containing heap blocks + void* blocks; // start of the area containing theap blocks size_t reserved; // bytes reserved for this area (virtual) size_t committed; // current available bytes for this area size_t used; // number of allocated blocks size_t block_size; // size in bytes of each block size_t full_block_size; // size in bytes of a full block including padding and metadata. - int heap_tag; // heap tag associated with this area + void* reserved1; // internal } mi_heap_area_t; typedef bool (mi_cdecl mi_block_visit_fun)(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg); -mi_decl_export bool mi_heap_visit_blocks(const mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg); +// Heap visitors assume no concurrent heap access (except thread exit): no other thread may allocate in the heap, +// or free blocks that belong to it, during the visit. The visitor itself may allocate and free (but not delete the heap): +// freed blocks are never visited, and blocks allocated during the visit may or may not be visited. +mi_decl_export bool mi_heap_visit_blocks(mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg); +mi_decl_export bool mi_heap_visit_abandoned_blocks(mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg); + + +// ------------------------------------------------------ +// Arena memory management +// Arena's are larger memory area's provided by the OS or user +// ------------------------------------------------------ -// Experimental -mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_attr_noexcept; mi_decl_nodiscard mi_decl_export bool mi_is_redirected(void) mi_attr_noexcept; -mi_decl_export int mi_reserve_huge_os_pages_interleave(size_t pages, size_t numa_nodes, size_t timeout_msecs) mi_attr_noexcept; -mi_decl_export int mi_reserve_huge_os_pages_at(size_t pages, int numa_node, size_t timeout_msecs) mi_attr_noexcept; +mi_decl_export int mi_reserve_huge_os_pages_interleave(size_t pages, size_t numa_nodes, size_t timeout_msecs) mi_attr_noexcept; +mi_decl_export int mi_reserve_huge_os_pages_at(size_t pages, int numa_node, size_t timeout_msecs) mi_attr_noexcept; -mi_decl_export int mi_reserve_os_memory(size_t size, bool commit, bool allow_large) mi_attr_noexcept; -mi_decl_export bool mi_manage_os_memory(void* start, size_t size, bool is_committed, bool is_large, bool is_zero, int numa_node) mi_attr_noexcept; +mi_decl_export int mi_reserve_os_memory(size_t size, bool commit, bool allow_large) mi_attr_noexcept; +mi_decl_export bool mi_manage_os_memory(void* start, size_t size, bool is_committed, bool is_pinned /* cannot decommit/reset? */, bool is_zero, int numa_node) mi_attr_noexcept; -mi_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 void mi_debug_show_arenas(void) mi_attr_noexcept; +mi_decl_export void mi_arenas_print(void) mi_attr_noexcept; +mi_decl_export void mi_arenas_purge(void) mi_attr_noexcept; +mi_decl_export size_t mi_arena_min_alignment(void); +mi_decl_export size_t mi_arena_min_size(void); +mi_decl_export size_t mi_arena_max_object_size(void); -// Experimental: heaps associated with specific memory arena's -typedef int mi_arena_id_t; -mi_decl_export void* mi_arena_area(mi_arena_id_t arena_id, size_t* size); -mi_decl_export int mi_reserve_huge_os_pages_at_ex(size_t pages, int numa_node, size_t timeout_msecs, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept; -mi_decl_export int mi_reserve_os_memory_ex(size_t size, bool commit, bool allow_large, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept; -mi_decl_export bool mi_manage_os_memory_ex(void* start, size_t size, bool is_committed, bool is_large, bool is_zero, int numa_node, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept; +typedef void* mi_arena_id_t; +mi_decl_export void* mi_arena_area(mi_arena_id_t arena_id, size_t* size); +mi_decl_export int mi_reserve_huge_os_pages_at_ex(size_t pages, int numa_node, size_t timeout_msecs, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept; +mi_decl_export int mi_reserve_os_memory_ex(size_t size, bool commit, bool allow_large, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept; +mi_decl_export 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_decl_export bool mi_arena_contains(mi_arena_id_t arena_id, const void* p); -#if MI_MALLOC_VERSION >= 182 // Create a heap that only allocates in the specified arena mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t arena_id); -#endif -// Experimental: allow sub-processes whose memory areas stay separated (and no reclamation between them) +// ------------------------------------------------------ +// Subprocesses +// Advanced: allow sub-processes whose memory arena's stay fully separated (and no reclamation between them). // 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 type mi_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); -mi_decl_export void mi_subproc_delete(mi_subproc_id_t subproc); +mi_decl_export void mi_subproc_destroy(mi_subproc_id_t subproc); mi_decl_export void mi_subproc_add_current_thread(mi_subproc_id_t subproc); // this should be called right after a thread is created (and no allocation has taken place yet) -// Experimental: visit abandoned heap areas (that are not owned by a specific heap) -mi_decl_export bool mi_abandoned_visit_blocks(mi_subproc_id_t subproc_id, int heap_tag, bool visit_blocks, mi_block_visit_fun* visitor, void* arg); +typedef bool (mi_cdecl mi_heap_visit_fun)(mi_heap_t* heap, void* arg); +mi_decl_export bool mi_subproc_visit_heaps(mi_subproc_id_t subproc, mi_heap_visit_fun* visitor, void* arg); + + +// ------------------------------------------------------------------------------------- +// A "theap" is a thread-local heap. This API is only provided for special circumstances like runtimes +// that already have a thread-local context and can store the theap there for (slightly) faster allocations. +// This also allows to set a default theap for the current thread so that `malloc` etc. allocate from +// that theap (instead of the main (t)heap). +// Theaps are first-class, but can only allocate from the same thread that created it. +// Allocation through a `theap` may be a tiny bit faster than using plain malloc +// (as we don't need to lookup the thread local variable). +// ------------------------------------------------------------------------------------- + +struct mi_theap_s; +typedef struct mi_theap_s mi_theap_t; + +mi_decl_nodiscard mi_decl_export mi_theap_t* mi_heap_get_theap(mi_heap_t* heap); +mi_decl_nodiscard mi_decl_export mi_heap_t* mi_theap_get_heap(const mi_theap_t* theap); // NULL for an empty theap +mi_decl_nodiscard mi_decl_export mi_theap_t* mi_theap_get_default(void); +mi_decl_export mi_theap_t* mi_theap_set_default(mi_theap_t* theap); // NULL restores the main theap +mi_decl_export void mi_theap_collect(mi_theap_t* theap, bool force) mi_attr_noexcept; + +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_malloc(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(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 mi_decl_restrict void* mi_theap_zalloc_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); +mi_decl_nodiscard mi_decl_export void* mi_theap_rezalloc_sized(mi_theap_t* theap, void* p, size_t oldsize, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(4); +mi_decl_nodiscard mi_decl_export void* mi_theap_realloc_aligned(mi_theap_t* theap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(3) mi_attr_alloc_align(4); +mi_decl_nodiscard mi_decl_export void* mi_theap_rezalloc_aligned_sized(mi_theap_t* theap, void* p, size_t oldsize, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(4) mi_attr_alloc_align(5); + +#define mi_theap_rezalloc(theap,p,oldsize,newsize) mi_theap_rezalloc_sized(theap,p,oldsize,newsize) +#define mi_theap_rezalloc_aligned(theap,p,oldsize,newsize,alignment) mi_theap_rezalloc_aligned_sized(theap,p,oldsize,newsize,alignment) + +// ------------------------------------------------------ +// Experimental +// ------------------------------------------------------ // Experimental: objects followed by a guard page. +// Setting the sample rate on a specific theap can be used to test parts of the program more +// specifically (in combination with `mi_theap_set_default`). // A sample rate of 0 disables guarded objects, while 1 uses a guard page for every object. // A seed of 0 uses a random start point. Only objects within the size bound are eligable for guard pages. -mi_decl_export void mi_heap_guarded_set_sample_rate(mi_heap_t* heap, size_t sample_rate, size_t seed); -mi_decl_export void mi_heap_guarded_set_size_bound(mi_heap_t* heap, size_t min, size_t max); +mi_decl_export void mi_theap_guarded_set_sample_rate(mi_theap_t* theap, size_t sample_rate, size_t seed); +mi_decl_export void mi_theap_guarded_set_size_bound(mi_theap_t* theap, size_t min, size_t max); -// Experimental: communicate that the thread is part of a threadpool -mi_decl_export void mi_thread_set_in_threadpool(void) mi_attr_noexcept; +// very experimental +typedef bool (mi_cdecl mi_commit_fun_t)(bool commit, void* start, size_t size, bool* is_zero, void* user_arg); +mi_decl_export 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; -// Experimental: create a new heap with a specified heap tag. Set `allow_destroy` to false to allow the thread -// to reclaim abandoned memory (with a compatible heap_tag and arena_id) but in that case `mi_heap_destroy` will -// fall back to `mi_heap_delete`. -mi_decl_nodiscard mi_decl_export mi_heap_t* mi_heap_new_ex(int heap_tag, bool allow_destroy, mi_arena_id_t arena_id); +//mi_decl_export bool mi_arena_unload(mi_arena_id_t arena_id, void** base, size_t* accessed_size, size_t* size); +//mi_decl_export bool mi_arena_reload(void* start, size_t size, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id); +//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); -// Experimental and unsafe: assumes the page of `p` is only accessed by the calling thread -mi_decl_nodiscard mi_decl_export bool mi_unsafe_heap_page_is_under_utilized(mi_heap_t* heap, void* p, size_t perc_threshold) mi_attr_noexcept; +// 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 -mi_decl_export int mi_reserve_huge_os_pages(size_t pages, double max_secs, size_t* pages_reserved) mi_attr_noexcept; -mi_decl_export void mi_collect_reduce(size_t target_thread_owned) mi_attr_noexcept; +// Owner-thread only: abandon pages and delete the theap (not its heap or live blocks). +mi_decl_export void mi_theap_delete(mi_theap_t* theap) mi_attr_noexcept; + +// Abandon all theap pages, preserving live blocks and the theap for reuse. The owner must be the current thread or quiescent outside mimalloc (excluding concurrent heap/theap deletion). +mi_decl_export void mi_theap_quiescent_abandon(mi_theap_t* theap) mi_attr_noexcept; +// For runtime's: return the current owner thread-id of the page containing an allocation. +mi_decl_nodiscard mi_decl_export size_t mi_thread_id_of(const void* p) mi_attr_noexcept; // ------------------------------------------------------ -// Convenience +// Deprecated // ------------------------------------------------------ -#define mi_malloc_tp(tp) ((tp*)mi_malloc(sizeof(tp))) -#define mi_zalloc_tp(tp) ((tp*)mi_zalloc(sizeof(tp))) -#define mi_calloc_tp(tp,n) ((tp*)mi_calloc(n,sizeof(tp))) -#define mi_mallocn_tp(tp,n) ((tp*)mi_mallocn(n,sizeof(tp))) -#define mi_reallocn_tp(p,tp,n) ((tp*)mi_reallocn(p,n,sizeof(tp))) -#define mi_recalloc_tp(p,tp,n) ((tp*)mi_recalloc(p,n,sizeof(tp))) +mi_decl_nodiscard mi_decl_export mi_theap_t* mi_heap_theap(mi_heap_t* heap); // use mi_heap_get_theap instead +mi_decl_nodiscard mi_decl_export bool mi_check_owned(const void* p); // use mi_any_heap_contains instead +mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_attr_noexcept; // use mi_any_heap_contains instead -#define mi_heap_malloc_tp(hp,tp) ((tp*)mi_heap_malloc(hp,sizeof(tp))) -#define mi_heap_zalloc_tp(hp,tp) ((tp*)mi_heap_zalloc(hp,sizeof(tp))) -#define mi_heap_calloc_tp(hp,tp,n) ((tp*)mi_heap_calloc(hp,n,sizeof(tp))) -#define mi_heap_mallocn_tp(hp,tp,n) ((tp*)mi_heap_mallocn(hp,n,sizeof(tp))) -#define mi_heap_reallocn_tp(hp,p,tp,n) ((tp*)mi_heap_reallocn(hp,p,n,sizeof(tp))) -#define mi_heap_recalloc_tp(hp,p,tp,n) ((tp*)mi_heap_recalloc(hp,p,n,sizeof(tp))) +mi_decl_export void mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept; +mi_decl_export bool mi_theap_visit_blocks(const mi_theap_t* theap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg); +mi_decl_export int mi_reserve_huge_os_pages(size_t pages, double max_secs, size_t* pages_reserved) mi_attr_noexcept; +mi_decl_export void mi_collect_reduce(size_t target_thread_owned) mi_attr_noexcept; -// ------------------------------------------------------ -// Compatibility with v3 -// ------------------------------------------------------ +mi_decl_export void mi_stats_reset(void) mi_attr_noexcept; +mi_decl_export void mi_stats_merge(void) mi_attr_noexcept; +mi_decl_export void mi_stats_print(void* out) mi_attr_noexcept; // backward compatibility: `out` is ignored and should be NULL -typedef mi_heap_t mi_theap_t; +mi_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. -#define mi_theap_get_default() mi_heap_get_default() -#define mi_theap_set_default(hp) mi_heap_set_default(hp) -#define mi_theap_collect(hp,force) mi_heap_collect(hp,force) -#define mi_theap_malloc(hp,sz) mi_heap_malloc(hp,sz) -#define mi_theap_zalloc(hp,sz) mi_heap_zalloc(hp,sz) -#define mi_theap_calloc(hp,cnt,sz) mi_heap_calloc(hp,cnt,sz) -#define mi_theap_malloc_small(hp,sz) mi_heap_malloc_small(hp,sz) -#define mi_theap_malloc_aligned(hp,sz,a) mi_heap_malloc_aligned(hp,sz,a) -#define mi_theap_realloc(hp,p,newsz) mi_heap_realloc(hp,p,newsz) +mi_decl_export void mi_free_size(void* p, size_t size) mi_attr_noexcept; // use mi_free_sized instead +mi_decl_export void mi_free_size_aligned(void* p, size_t size, size_t alignment) mi_attr_noexcept; // use mi_free_sized_aligned instead + +// deprecated: previous signatures that zero from the usable size of `p` (the names are parenthesized to avoid macro expansion) +mi_decl_nodiscard mi_decl_export void* (mi_rezalloc)(void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(2); +mi_decl_nodiscard mi_decl_export void* (mi_recalloc)(void* p, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(2,3); +mi_decl_nodiscard mi_decl_export void* (mi_rezalloc_aligned)(void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(2) mi_attr_alloc_align(3); +mi_decl_nodiscard mi_decl_export void* (mi_rezalloc_aligned_at)(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(2); +mi_decl_nodiscard mi_decl_export void* (mi_recalloc_aligned)(void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(2,3) mi_attr_alloc_align(4); +mi_decl_nodiscard mi_decl_export void* (mi_recalloc_aligned_at)(void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(2,3); +mi_decl_nodiscard mi_decl_export void* (mi_heap_rezalloc)(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_recalloc)(mi_heap_t* heap, void* p, size_t newcount, size_t size) mi_attr_noexcept mi_attr_alloc_size2(3,4); +mi_decl_nodiscard mi_decl_export void* (mi_heap_rezalloc_aligned)(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(3) mi_attr_alloc_align(4); +mi_decl_nodiscard mi_decl_export void* (mi_heap_rezalloc_aligned_at)(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size(3); +mi_decl_nodiscard mi_decl_export void* (mi_heap_recalloc_aligned)(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept mi_attr_alloc_size2(3,4) mi_attr_alloc_align(5); +mi_decl_nodiscard mi_decl_export void* (mi_heap_recalloc_aligned_at)(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept mi_attr_alloc_size2(3,4); +mi_decl_nodiscard mi_decl_export void* (mi_theap_rezalloc)(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3); +mi_decl_nodiscard mi_decl_export void* (mi_theap_rezalloc_aligned)(mi_theap_t* theap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept mi_attr_alloc_size(3) mi_attr_alloc_align(4); // ------------------------------------------------------ // Options +// The deprecated options no longer have any effect. // ------------------------------------------------------ typedef enum mi_option_e { @@ -396,7 +524,7 @@ typedef enum mi_option_e { mi_option_show_stats, // print statistics on termination mi_option_verbose, // print verbose messages // advanced options - mi_option_eager_commit, // eager commit segments? (after `eager_commit_delay` segments) (=1) + mi_option_deprecated_eager_commit, mi_option_arena_eager_commit, // eager commit arenas? Use 2 to enable just on overcommit systems (=2) mi_option_purge_decommits, // should a memory purge decommit? (=1). Set to 0 to use memory reset on a purge (instead of decommit) mi_option_allow_large_os_pages, // allow use of large (2 or 4 MiB) OS pages, implies eager commit. @@ -405,40 +533,58 @@ typedef enum mi_option_e { mi_option_reserve_os_memory, // reserve specified amount of OS memory in an arena at startup (internally, this value is in KiB; use `mi_option_get_size`) mi_option_deprecated_segment_cache, mi_option_deprecated_page_reset, - mi_option_abandoned_page_purge, // immediately purge delayed purges on thread termination + mi_option_deprecated_abandoned_page_purge, mi_option_deprecated_segment_reset, - mi_option_eager_commit_delay, // the first N segments per thread are not eagerly committed (but per page in the segment on demand) + mi_option_deprecated_eager_commit_delay, mi_option_purge_delay, // memory purging is delayed by N milli seconds; use 0 for immediate purging or -1 for no purging at all. (=10) mi_option_use_numa_nodes, // 0 = use all available numa nodes, otherwise use at most N nodes. mi_option_disallow_os_alloc, // 1 = do not use OS memory for allocation (but only programmatically reserved arenas) mi_option_os_tag, // tag used for OS logging (macOS only for now) (=100) mi_option_max_errors, // issue at most N error messages mi_option_max_warnings, // issue at most N warning messages - mi_option_max_segment_reclaim, // max. percentage of the abandoned segments can be reclaimed per try (=10%) + mi_option_deprecated_max_segment_reclaim, mi_option_destroy_on_exit, // if set, release all memory on exit; sometimes used for dynamic unloading but can be unsafe mi_option_arena_reserve, // initial memory size for arena reservation (= 1 GiB on 64-bit) (internally, this value is in KiB; use `mi_option_get_size`) mi_option_arena_purge_mult, // multiplier for `purge_delay` for the purging delay for arenas (=10) - mi_option_purge_extend_delay, - mi_option_abandoned_reclaim_on_free, // allow to reclaim an abandoned segment on a free (=1) + mi_option_deprecated_purge_extend_delay, mi_option_disallow_arena_alloc, // 1 = do not use arena's for allocation (except if using specific arena id's) mi_option_retry_on_oom, // retry on out-of-memory for N milli seconds (=400), set to 0 to disable retries. (only on windows) - mi_option_visit_abandoned, // allow visiting heap blocks from abandoned threads (=0) + mi_option_deprecated_visit_abandoned, mi_option_guarded_min, // only used when building with MI_GUARDED: minimal rounded object size for guarded objects (=0) mi_option_guarded_max, // only used when building with MI_GUARDED: maximal rounded object size for guarded objects (=0) - mi_option_guarded_precise, // disregard minimal alignment requirement to always place guarded blocks exactly in front of a guard page (=0) - mi_option_guarded_sample_rate, // 1 out of N allocations in the min/max range will be guarded (=1000) + mi_option_deprecated_unsafe_guarded_precise, // deprecated (but can be enabled at build time with -DMI_UNSAFE_GUARDED_PRECISE=1) + mi_option_guarded_sample_rate, // guard an object in the min/max range about every N requested bytes (=0) mi_option_guarded_sample_seed, // can be set to allow for a (more) deterministic re-execution when a guard page is triggered (=0) - mi_option_target_segments_per_thread, // experimental (=0) - mi_option_generic_collect, // collect heaps every N (=10000) generic allocation calls - 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_generic_collect, // collect theaps every N (=10000) generic allocation calls + mi_option_page_reclaim_on_free, // heap-creation default for reclaim on free: -1 disallow, 0 originating theap only (default), 1 allow across theaps + mi_option_page_full_retain, // retain N full (small) pages per size class (=2) + mi_option_page_max_candidates, // max candidate pages to consider for allocation (=4) + mi_option_max_vabits, // max user space virtual address bits to consider (=48) + mi_option_pagemap_commit, // commit the full pagemap (to always catch invalid pointer uses) (=0) + mi_option_page_commit_on_demand, // commit page memory on-demand + mi_option_page_max_reclaim, // don't reclaim pages of the same originating theap if we already own N pages (in that size class) (=-1 (unlimited)) + mi_option_page_cross_thread_max_reclaim, // don't reclaim pages across threads if we already own N pages (in that size class) (=32) + mi_option_allow_thp, // transparent huge pages: 0 disable for the process, 1 allow, 2 allow and avoid splitting on purge. + // default: 2 on Linux, 0 on Android; an explicit minimal_purge_size overrides the purge behavior. + mi_option_arena_purge_min_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: associate local numa node with an initial arena allocation + mi_option_stats_merge_on_collect, // on each theap collection, the theap stats are merged automatically with the parent heap + mi_option_profile_alloc_interval, // number of allocated bytes between automatic snapshots of the heap profiler (=1GiB) + mi_option_profile_inuse_interval, // number of in-use bytes grown between automatic snapshots of the heap profiler (=0, disabled) + mi_option_profile_time_interval, // number of seconds between automatic snapshots of the heap profiler (=0, disabled) + mi_option_profile_sample_rate, // sample rate (in bytes) for heap profiler (=512 KiB) + mi_option_stats_merge_threshold, // on a page stats update, merge theap stats into the parent heap if N bytes were freed/allocated; 0 disables (=4 MiB) + mi_option_arena_purge_immediate_size, // ranges above this size are purged immediately + mi_option_mte, // use memory tagging (MTE) if available (and mimalloc is built with `MI_MTE=PREFER` or `ON`) (=1); on Linux, 2=sync, 3=async, 4=preferred tag check mode _mi_option_last, // legacy option names mi_option_large_os_pages = mi_option_allow_large_os_pages, mi_option_eager_region_commit = mi_option_arena_eager_commit, mi_option_reset_decommits = mi_option_purge_decommits, mi_option_reset_delay = mi_option_purge_delay, - mi_option_abandoned_page_reset = mi_option_abandoned_page_purge, - mi_option_limit_os_alloc = mi_option_disallow_os_alloc + mi_option_limit_os_alloc = mi_option_disallow_os_alloc, + mi_option_minimal_purge_size = mi_option_arena_purge_min_size } mi_option_t; @@ -458,38 +604,44 @@ mi_decl_export void mi_option_set_default(mi_option_t option, long value); // ------------------------------------------------------------------------------------------------------- // "mi" prefixed implementations of various posix, Unix, Windows, and C++ allocation functions. // (This can be convenient when providing overrides of these functions as done in `mimalloc-override.h`.) -// note: we use `mi_cfree` as "checked free" and it checks if the pointer is in our heap before free-ing. +// note: we use `mi_cfree` as "checked free" and it checks if the pointer is in our theap before free-ing. // ------------------------------------------------------------------------------------------------------- -mi_decl_export void mi_cfree(void* p) mi_attr_noexcept; -mi_decl_export void* mi__expand(void* p, size_t newsize) mi_attr_noexcept; -mi_decl_nodiscard mi_decl_export size_t mi_malloc_size(const void* p) mi_attr_noexcept; -mi_decl_nodiscard mi_decl_export size_t mi_malloc_good_size(size_t size) mi_attr_noexcept; -mi_decl_nodiscard mi_decl_export size_t mi_malloc_usable_size(const void *p) mi_attr_noexcept; +mi_decl_nodiscard mi_decl_export size_t mi_malloc_size(const void* p) mi_attr_noexcept mi_attr_pure; +mi_decl_nodiscard mi_decl_export size_t mi_malloc_good_size(size_t size) mi_attr_noexcept mi_attr_pure; +mi_decl_nodiscard mi_decl_export size_t mi_malloc_usable_size(const void *p) mi_attr_noexcept mi_attr_pure; mi_decl_export int mi_posix_memalign(void** p, size_t alignment, size_t size); // mi_attr_noexcept; mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_memalign(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 mi_decl_restrict void* mi_valloc(size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_pvalloc(size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); -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* 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_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; +// C11 +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); + +// C23 +mi_decl_export void mi_free_aligned_sized( void* p, size_t alignment, size_t size ) mi_attr_noexcept; +// mi_decl_export void mi_free_sized( void* p, size_t size ) mi_attr_noexcept; -// wide characters -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; +// MSVC +mi_decl_export void* mi__expand(void* p, size_t newsize) mi_attr_noexcept; +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(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; + +// -------------------------------------------------------- +// C++ wrappers +// 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). +// -------------------------------------------------------- -// 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). mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_new(size_t size) mi_attr_malloc mi_attr_alloc_size(1); mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_new_aligned(size_t size, size_t alignment) mi_attr_malloc mi_attr_alloc_size(1) mi_attr_alloc_align(2); mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_new_nothrow(size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(1); @@ -498,9 +650,73 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_new_n(size_t count, s mi_decl_nodiscard mi_decl_export void* mi_new_realloc(void* p, size_t newsize) mi_attr_alloc_size(2); mi_decl_nodiscard mi_decl_export void* mi_new_reallocn(void* p, size_t newcount, size_t size) mi_attr_alloc_size2(2, 3); -mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_alloc_new(mi_heap_t* heap, size_t size) mi_attr_malloc mi_attr_alloc_size(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_alloc_new(mi_heap_t* heap, size_t size) mi_attr_malloc mi_attr_alloc_size(2); mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_heap_alloc_new_n(mi_heap_t* heap, size_t count, size_t size) mi_attr_malloc mi_attr_alloc_size2(2, 3); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_alloc_new(mi_theap_t* theap, size_t size) mi_attr_malloc mi_attr_alloc_size(2); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_alloc_new_n(mi_theap_t* theap, size_t count, size_t size) mi_attr_malloc mi_attr_alloc_size2(2, 3); +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_alloc_new_nothrow(mi_theap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2); + + +// -------------------------------------------------------------------------- +// Inlined constant size allocations. +// These are meant for runtime systems, or overrides where we need the best +// performance for small, constant-size allocations. +// These are only better than the regular functions if the size or alignment +// are indeed constant at the call site. +// -------------------------------------------------------------------------- + +// Internal machine word size allocation. `wsize` is the allocation size in machine words (`sizeof(size_t)`) +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_wzalloc_small(size_t wsize) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_wmalloc_small(size_t wsize) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_wmalloc_small(mi_theap_t* theap, size_t wsize) mi_attr_noexcept mi_attr_malloc; +mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_theap_wzalloc_small(mi_theap_t* theap, size_t wsize) mi_attr_noexcept mi_attr_malloc; + +static inline size_t mi_wsize_from_size(size_t size) mi_attr_noexcept { + return (size + sizeof(size_t) - 1) / sizeof(size_t); +} + +static inline mi_decl_restrict void* mi_malloc_csize(size_t size) mi_attr_noexcept { + if (size <= MI_SMALL_SIZE_MAX) { return mi_wmalloc_small(mi_wsize_from_size(size)); } else { return mi_malloc(size); } +} +static inline mi_decl_restrict void* mi_zalloc_csize(size_t size) mi_attr_noexcept { + if (size <= MI_SMALL_SIZE_MAX) { return mi_wzalloc_small(mi_wsize_from_size(size)); } else { return mi_zalloc(size); } +} +static inline mi_decl_restrict void* mi_theap_malloc_csize(mi_theap_t* theap, size_t size) mi_attr_noexcept { + assert(theap!=NULL); + if (size <= MI_SMALL_SIZE_MAX) { return mi_theap_wmalloc_small(theap,mi_wsize_from_size(size)); } else { return mi_theap_malloc(theap,size); } +} +static inline mi_decl_restrict void* mi_theap_zalloc_csize(mi_theap_t* theap, size_t size) mi_attr_noexcept { + assert(theap!=NULL); + if (size <= MI_SMALL_SIZE_MAX) { return mi_theap_wzalloc_small(theap,mi_wsize_from_size(size)); } else { return mi_theap_zalloc(theap,size); } +} + +static inline void mi_free_csize(void* p, size_t size) mi_attr_noexcept { + if (size <= MI_SMALL_SIZE_MAX) { mi_free_small(p); } else { mi_free(p); } +} +static inline void mi_free_csize_nonnull(void* p, size_t size) mi_attr_noexcept { + assert(p!=NULL); + if (size <= MI_SMALL_SIZE_MAX) { mi_free_small_nonnull(p); } else { mi_free(p); } +} +static inline void mi_free_csize_aligned(void* p, size_t size, size_t aligned) mi_attr_noexcept { + if (aligned <= size && size <= MI_SMALL_SIZE_MAX) { mi_free_small(p); } else { mi_free(p); } +} +static inline void mi_free_csize_aligned_nonnull(void* p, size_t size, size_t aligned) mi_attr_noexcept { + assert(p!=NULL); + if (aligned <= size && size <= MI_SMALL_SIZE_MAX) { mi_free_small_nonnull(p); } else { mi_free(p); } +} + +// As `mi_free_small` but `p` must be allocated on a page owned by the current thread (be very careful!) +mi_decl_export void mi_free_small_local(void* p) mi_attr_noexcept; + +// As `mi_free_small_local` but `p` cannot be NULL as well. +mi_decl_export void mi_free_small_local_nonnull(void* p) mi_attr_noexcept; + + +// ------------------------------------------------------ +// C++ standard library allocator interface. +// ------------------------------------------------------ + #ifdef __cplusplus } #endif @@ -531,8 +747,8 @@ template struct _mi_stl_allocator_common { using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; - template void construct(U* p, Args&& ...args) { ::new(p) U(std::forward(args)...); } - template void destroy(U* p) mi_attr_noexcept { p->~U(); } + // no construct/destroy: std::allocator_traits provides them, and declaring them + // disables the memmove/memset/trivial-destroy fast paths of the STL containers #else void construct(pointer p, value_type const& val) { ::new(p) value_type(val); } void destroy(pointer p) { p->~value_type(); } @@ -576,7 +792,7 @@ template bool operator!=(const mi_stl_allocator& , const #include // std::shared_ptr -// Common base class for STL allocators in a specific heap +// Common base class for STL allocators in a specific theap template struct _mi_heap_stl_allocator_common : public _mi_stl_allocator_common { using typename _mi_stl_allocator_common::size_type; using typename _mi_stl_allocator_common::value_type; diff --git a/Include/internal/mimalloc/mimalloc/alloc/alloc.h b/Include/internal/mimalloc/mimalloc/alloc/alloc.h new file mode 100644 index 00000000000000..61b15cedb770d7 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/alloc/alloc.h @@ -0,0 +1,63 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ALLOC_ALLOC_H +#define MI_ALLOC_ALLOC_H + +#include "../types.h" +#include "../util/libc.h" +#include "../util/options.h" +#include "page.h" // mi_page_is_small + +mi_decl_restrict void* _mi_page_malloc_zero(mi_theap_t* theap, mi_page_t* page, size_t size, bool zero) mi_attr_noexcept; // called from `_mi_theap_malloc_aligned` +bool _mi_page_can_reset_tail(const mi_page_t* page); +void _mi_page_reset_tail(const mi_page_t* page, void* p, size_t newsize, size_t usable); +mi_decl_restrict void* _mi_theap_malloc_zero(mi_theap_t* theap, size_t size, bool zero, size_t huge_alignment, mi_page_t** ppage) mi_attr_noexcept; // called from `_mi_theap_malloc_aligned` +void* _mi_theap_realloc_zero(mi_theap_t* theap, void* p, size_t oldsize, size_t newsize, bool zero) mi_attr_noexcept; +void _mi_error_count_size_overflow(size_t count, size_t size); // sets `errno` to `ENOMEM` + +// Safe multiply `count*size` into `total`; return `true` on overflow (and set `errno` to `ENOMEM` as required by POSIX). +// Saturating multiply `count*size` (returns `SIZE_MAX` on overflow). +static inline size_t mi_count_size_saturate(size_t count, size_t size) { + size_t total; + return (mi_mul_overflow(count, size, &total) ? SIZE_MAX : total); +} + +static inline bool mi_count_size_overflow(size_t count, size_t size, size_t* total) { + if (count==1) { // quick check for the case where count is one (common for C++ allocators) + *total = size; + return false; + } + else if mi_likely(!mi_mul_overflow(count, size, total)) { + return false; + } + else { + *total = SIZE_MAX; + _mi_error_count_size_overflow(count, size); + return true; + } +} + +// Can a reallocation to `newsize` keep a block of `size` usable bytes in `page` in place? +// Only if it fits with at most 12.5% waste, or if the new size is huge and at least half and we can +// reset the unused tail (see issue #1488). +#ifndef MI_REALLOC_SHRINK_FACTOR +#define MI_REALLOC_SHRINK_FACTOR 8 // size - (size/MI_REALLOC_SHRINK_FACTOR) is the maximum allowed waste when shrinking +#endif +static inline bool mi_realloc_is_in_place(const mi_page_t* page, size_t size, size_t newsize) { + if mi_likely(newsize > size) return false; // grow + if mi_unlikely(newsize <= MI_SMALL_SIZE_MAX && !mi_page_is_small(page)) return false; // keep `mi_free_sized(p,newsize)` valid + if mi_likely(newsize >= size - (size/MI_REALLOC_SHRINK_FACTOR)) return true; // not too much waste + return (newsize > MI_LARGE_MAX_OBJ_SIZE && newsize >= size/2 && _mi_page_can_reset_tail(page)); // huge singleton pages +} + +// Shrink a block in place; for huge blocks we reset the unused tail. +static inline void mi_realloc_shrink_in_place(const mi_page_t* page, void* p, size_t newsize, size_t size) { + if mi_unlikely(size > MI_LARGE_MAX_OBJ_SIZE && newsize < size) { _mi_page_reset_tail(page, p, newsize, size); } +} + +#endif diff --git a/Include/internal/mimalloc/mimalloc/alloc/free.h b/Include/internal/mimalloc/mimalloc/alloc/free.h new file mode 100644 index 00000000000000..6489d9ceda3ef7 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/alloc/free.h @@ -0,0 +1,19 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ALLOC_FREE_H +#define MI_ALLOC_FREE_H + +#include "../types.h" + +mi_block_t* _mi_page_ptr_unalign(const mi_page_t* page, const void* p); +void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const size_t min_size); +void _mi_free_subproc_safe(void* p) mi_attr_noexcept; +size_t _mi_page_usable_size(const mi_page_t* page, const void* p) mi_attr_noexcept; +void* _mi_memtag_canonical(void* p); + +#endif diff --git a/Include/internal/mimalloc/mimalloc/alloc/page.h b/Include/internal/mimalloc/mimalloc/alloc/page.h new file mode 100644 index 00000000000000..a7aab875a218ab --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/alloc/page.h @@ -0,0 +1,972 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ALLOC_PAGE_H +#define MI_ALLOC_PAGE_H + +#include "../types.h" +#include "../prim/prim-mte.h" // mi_ptr_memtag_meta, mi_memtag_exclude_base, MI_ZERO_ON_FREE_MAX +#include "../prim/os.h" +#include "../heap/heap.h" +#include "../heap/page-map.h" +#include "../prim/prim-pac.h" +#include "../arena/arena.h" +#include "../track.h" + +mi_decl_restrict void* _mi_malloc_generic(mi_theap_t* theap, size_t size, size_t zero_huge_alignment, mi_page_t** ppage) mi_attr_noexcept mi_attr_malloc; +mi_decl_restrict void* _mi_malloc_generic_no_sample(mi_theap_t* theap, size_t size, bool zero, mi_page_t** ppage) mi_attr_noexcept mi_attr_malloc; + +void _mi_page_retire(mi_page_t* page) mi_attr_noexcept; // free the page if there are no other pages with many free blocks +void _mi_page_unfull(mi_page_t* page); +bool _mi_page_free(mi_page_t* page, mi_page_queue_t* pq); // false if page release is delayed +void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq, bool owner_done); // abandon the page, to be picked up by another thread... +void _mi_deferred_free(mi_theap_t* theap, bool force); +void _mi_page_check_free_lists(const mi_page_t* page); // check an empty page before it is freed (at `MI_SECURE>=1`) +bool _mi_page_free_collect(mi_page_t* page, bool force); // returns `true` if cross-thread free'd blocks were collected +mi_block_t* _mi_page_free_collect_partly(mi_page_t* page, mi_block_t* head); +mi_decl_nodiscard bool _mi_page_init(mi_theap_t* theap, mi_page_t* page); +void _mi_page_update_stats(mi_page_t* page); + +void _mi_theap_collect_retired(mi_theap_t* theap, bool force); +void _mi_theap_collect_huge_pages(mi_theap_t* theap); +bool _mi_theap_page_reclaim(mi_theap_t* theap, mi_page_t* page); // true if an empty page was freed +#if MI_DEBUG>1 +bool _mi_page_is_valid(mi_page_t* page); +#endif + +// in page-queue.c +bool _mi_page_queue_is_valid(mi_theap_t* theap, const mi_page_queue_t* pq); +size_t _mi_page_stats_bin(const mi_page_t* page); // for stats +size_t _mi_bin_size(size_t bin); // for stats +size_t _mi_bin(size_t size); // for stats +size_t _mi_block_size_of(size_t size); // block size (including padding) for an allocation of `size` bytes + + +static inline mi_page_queue_t* mi_page_queue(const mi_theap_t* theap, size_t size) { + mi_page_queue_t* const pq = &((mi_theap_t*)theap)->pages[_mi_bin(size)]; + if (size <= MI_LARGE_MAX_OBJ_SIZE) { mi_assert_internal(pq->block_size <= MI_LARGE_MAX_OBJ_SIZE); } + return pq; +} + +// Get the block size of a page +static inline size_t mi_page_block_size(const mi_page_t* page) { + mi_assert_internal(page->block_size > 0); + return page->block_size; +} + +// Page start +static inline uint8_t* mi_page_start(const mi_page_t* page) { + return page->page_start; +} + +static inline size_t mi_page_size(const mi_page_t* page) { + return mi_page_block_size(page) * page->reserved; +} + +// Byte size of the committed blocks (`capacity * block_size`); can be read by non-owning threads if `MI_FREE_IS_CHECKED` +static inline size_t mi_page_capacity_size(const mi_page_t* page) { + #if MI_FREE_IS_CHECKED + return mi_atomic_load_relaxed(&page->capacity_size); + #else + return (size_t)page->capacity * mi_page_block_size(page); + #endif +} + +#if MI_FREE_IS_CHECKED +// Is the byte offset `ofs` (below 2^32) at the start of a block? `ofs` is a multiple of `block_size` iff +// `ofs * ceil(2^64/block_size) mod 2^64 < ceil(2^64/block_size)` (Lemire, Kaser, and Kurz, "Faster remainder by direct computation", 2019). +// With a single block in the page, `block_recip == 1` and this checks `ofs == 0`. +static inline bool mi_page_is_block_offset(const mi_page_t* page, size_t ofs) { + return ((uint64_t)ofs * page->block_recip < page->block_recip); +} +#endif + +static inline uint8_t* mi_page_area(const mi_page_t* page, size_t* size) { + if (size) { *size = mi_page_size(page); } + return mi_page_start(page); +} + +static inline size_t mi_page_info_size(void) { + return mi_align_up(sizeof(mi_page_t), MI_MAX_ALIGN_SIZE); +} + +// Can the first block in a page with blocks of size `bsize` have a large cache offset? (see `MI_PAGE_LARGE_CACHE_OFFSET`; smaller blocks use a small cache offset) +static inline bool mi_block_size_has_large_cache_offset(size_t bsize) { + #if MI_PAGE_LARGE_CACHE_OFFSET + return (bsize > MI_SMALL_MAX_OBJ_SIZE); + #else + return false; + #endif +} + +// Is a (non-small) block of size `bsize` allocated in a medium page? +// Blocks of 1/8th of a medium page (64 KiB) leave no space for a cache offset and use a large page instead. +static inline bool mi_block_size_is_medium(size_t bsize) { + #if MI_ENABLE_LARGE_PAGES + if (mi_block_size_has_large_cache_offset(bsize) && bsize == MI_MEDIUM_PAGE_SIZE/8) return false; + #endif + return (bsize <= MI_MEDIUM_MAX_OBJ_SIZE); +} + +// The alignment that every block of size `bsize` is guaranteed to have in any page (or 0 if `bsize==0`). +// This is guaranteed by the block start (see `arena/arena-page-alloc.c:mi_page_meta_in_front_block_start` and `mi_page_meta_select`), +// and used by `mi_malloc_aligned` to avoid over-allocation for naturally aligned blocks. +static inline size_t mi_natural_alignment_of_size(size_t bsize) { + const size_t lowbit = bsize & (~bsize + 1); // largest power of 2 that divides `bsize` + if (bsize <= MI_SMALL_SIZE_MAX) return lowbit; // small blocks start at a multiple of their size + if (mi_is_power_of_two(bsize) && bsize <= MI_PAGE_MAX_START_BLOCK_ALIGN2) return bsize; // power-of-two blocks up to 4KiB + if ((bsize % MI_PAGE_OSPAGE_BLOCK_ALIGN2) == 0) { // multiples of 4KiB are 4KiB aligned (or cache offset unit aligned) + return (mi_block_size_has_large_cache_offset(bsize) ? MI_PAGE_LARGE_CACHE_OFFSET_UNIT : MI_PAGE_OSPAGE_BLOCK_ALIGN2); + } + return (lowbit < MI_MAX_ALIGN_SIZE ? lowbit : MI_MAX_ALIGN_SIZE); // otherwise blocks start at least `MI_MAX_ALIGN_SIZE` aligned +} + +static inline bool mi_page_contains_address(const mi_page_t* page, const void* p) { + size_t psize; + const mi_addr_t start = mi_addr(mi_page_area(page, &psize)); + return (start <= mi_addr(p) && mi_addr(p) < start + psize); +} + +static inline bool mi_page_is_in_arena(const mi_page_t* page) { + return (page->memid.memkind == MI_MEM_ARENA); +} + +static inline bool mi_page_is_singleton(const mi_page_t* page) { + return (page->reserved == 1); +} + +// Get the usable block size of a page without fixed padding. +// This may still include internal padding due to alignment and rounding up size classes. +static inline size_t mi_page_usable_block_size(const mi_page_t* page) { + return mi_page_block_size(page) - MI_PADDING_SIZE; +} + +static inline bool mi_page_meta_is_separated(const mi_page_t* page) { + #if MI_PAGE_META_IS_ALIGNED + #if MI_PAGE_META_SMALL_IS_ALIGNED + return (mi_addr(page) != mi_align_down(mi_addr(mi_page_start(page)), MI_ARENA_SLICE_ALIGN)); + #else + MI_UNUSED_RELEASE(page); + mi_assert_internal(mi_addr(page) != mi_align_down(mi_addr(mi_page_start(page)), MI_ARENA_SLICE_ALIGN)); + return true; + #endif + #elif MI_PAGE_META_OS_IS_SEPARATED && !MI_PAGE_META_SMALL_IS_ALIGNED + MI_UNUSED_RELEASE(page); + mi_assert_internal(mi_addr(page) != mi_align_down(mi_addr(mi_page_start(page)), MI_ARENA_SLICE_ALIGN)); + return true; + #elif 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_SMALL_IS_ALIGNED + return (page->memid.memkind == MI_MEM_ARENA && mi_addr(page) != mi_align_down(mi_addr(mi_page_start(page)), MI_ARENA_SLICE_ALIGN)); + #else + MI_UNUSED(page); + return false; + #endif +} + +static inline uint8_t* mi_page_slice_start(const mi_page_t* page) { + #if MI_CHERI + // derive from the arena or OS memory as both the page meta data and the page start are bounded + if (page->memid.memkind == MI_MEM_ARENA) { + return mi_arena_start(mi_memid_arena(page->memid)) + ((size_t)page->memid.mem.arena.slice_index * MI_ARENA_SLICE_SIZE); + } + else { + void* const slice_start = (mi_page_meta_is_separated(page) ? mi_align_down_ptr(mi_page_start(page), MI_ARENA_SLICE_ALIGN) : (void*)page); + return (uint8_t*)mi_ptr_rederive(page->memid.mem.os.base, slice_start); + } + #else + 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(mi_page_start(page), MI_ARENA_SLICE_ALIGN); + } + else { + // page meta info is at the start of the page slices (without its memory tag) + return (uint8_t*)mi_ptr_memtag_meta(page); + } + #endif +} + +// Re-derive `p` in the page memory with the authority to change its protection +static inline void* mi_page_vmem_ptr(const mi_page_t* page, void* p) { + #if MI_CHERI + return mi_ptr_rederive(mi_page_slice_start(page), p); + #else + MI_UNUSED(page); + return p; + #endif +} + +// 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 (mi_page_start(page) - mi_page_slice_start(page)) + offset_relative_to_page_start; +} + +// The end of the blocks relative to the slice start rounded up to the OS page size. +// This is where the end guard page is if `page->memid.guard_end` is set. +static inline size_t mi_page_guard_end_offset(const mi_page_t* page) { + return mi_align_up(mi_page_slice_offset_of(page, mi_page_size(page)), _mi_os_page_size()); +} + +// How much of the page is committed relative to the slice start? (or 0 if fully committed already) +static inline size_t mi_page_slice_committed(const mi_page_t* page) { + return ((size_t)page->slice_pcommitted * _mi_os_page_size()); +} + +// Currently committed part of a page +static inline size_t mi_page_committed(const mi_page_t* page) { + const size_t slice_committed = mi_page_slice_committed(page); + return (slice_committed == 0 ? mi_page_size(page) : slice_committed - mi_page_slice_offset_of(page,0)); +} + +static inline size_t mi_page_used(const mi_page_t* page) { + mi_assert_internal(page != NULL); + return mi_xused_used_count(page->xused); +} + +static inline void mi_page_used_reset(mi_page_t* page) { + page->xused = mi_xused_used_reset(page->xused); +} + +static inline size_t mi_page_alloc_count(const mi_page_t* page) { + return mi_xused_alloc_count(page->xused); +} + +static inline size_t mi_page_last_used(const mi_page_t* page) { + #if MI_SIZE_SIZE >= 8 + return (page->xused.used_alloc >> 32) & 0xFFFF; + #else + return page->xlast_used; + #endif +} + +static inline size_t mi_page_last_alloc(const mi_page_t* page) { + #if MI_SIZE_SIZE >= 8 + return (page->xused.used_alloc >> 48) & 0xFFFF; + #else + return page->xlast_alloc; + #endif +} + + +// are all blocks in a page freed? +// note: needs up-to-date used count, (as the `xthread_free` list may not be empty). see `_mi_page_collect_free`. +static inline bool mi_page_all_free(const mi_page_t* page) { + mi_assert_internal(page != NULL); + return (mi_page_used(page)==0); +} + +// are there immediately available blocks, i.e. blocks available on the free list. +static inline bool mi_page_immediate_available(const mi_page_t* page) { + mi_assert_internal(page != NULL); + return (page->free != NULL); +} + + +// is the page not yet used up to its reserved space? +static inline bool mi_page_is_expandable(const mi_page_t* page) { + mi_assert_internal(page != NULL); + mi_assert_internal(page->capacity <= page->reserved); + return (page->capacity < page->reserved); +} + + +static inline bool mi_page_is_full(const mi_page_t* page) { + const bool full = (page->reserved == mi_page_used(page)); + mi_assert_internal(!full || page->free == NULL); + return full; +} + +// is more than (1 - 1/n)'th of a page in use? +static inline bool mi_page_is_used_at_frac(const mi_page_t* page, size_t n) { + if (page==NULL) return true; + const size_t frac = page->reserved / n; + return (page->reserved - mi_page_used(page) <= frac); +} + +// is more than 7/8th of a page in use? +static inline bool mi_page_is_mostly_used(const mi_page_t* page) { + return mi_page_is_used_at_frac(page, 8); +} + +// Is reuse of the freed blocks in this page delayed? (see `MI_SECURE_REUSE_DELAY`) +static inline bool mi_page_reuse_is_delayed(const mi_page_t* page) { + #if (MI_SECURE_REUSE_DELAY > 0) + const size_t capacity = page->capacity; + size_t delay = capacity / MI_SECURE_REUSE_DELAY; + const size_t delay_min = (capacity/2 < MI_SECURE_REUSE_DELAY_MIN ? capacity/2 : MI_SECURE_REUSE_DELAY_MIN); + if (delay < delay_min) { delay = delay_min; } + if (delay > MI_SECURE_REUSE_DELAY_MAX) { delay = MI_SECURE_REUSE_DELAY_MAX; } + return (capacity - mi_page_used(page) < delay); + #else + MI_UNUSED(page); + return false; + #endif +} + +static inline bool mi_page_is_small(const mi_page_t* page) { + return (page->block_size <= MI_SMALL_MAX_OBJ_SIZE && !mi_page_is_singleton(page)); +} + +static inline bool mi_page_is_huge(const mi_page_t* page) { + return page->memid.is_huge; +} + +static inline size_t mi_page_min_commit_size(void) { + const size_t psize = _mi_os_page_size(); + return (MI_PAGE_MIN_COMMIT_SIZE >= psize ? MI_PAGE_MIN_COMMIT_SIZE : psize); +} + +//----------------------------------------------------------- +// Page thread id and flags +//----------------------------------------------------------- + +// Thread id of thread that owns this page (with flags in the bottom 2 bits) +static inline mi_thread_id_t mi_page_xthread_id(const mi_page_t* page) { + return mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_id); +} + +// Plain thread id of the thread that owns this page +static inline mi_thread_id_t mi_page_thread_id(const mi_page_t* page) { + return (mi_page_xthread_id(page) & ~MI_PAGE_FLAG_MASK); +} + +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 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) { + return ((mi_page_flags(page) & MI_PAGE_IN_FULL_QUEUE) != 0); +} + +static inline void mi_page_set_in_full(mi_page_t* page, bool in_full) { + 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) { + mi_assert_internal(page->capacity==page->reserved); + const size_t size = page->reserved * 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) { + return ((mi_page_flags(page) & MI_PAGE_HAS_INTERIOR_POINTERS) != 0); +} + +static inline void mi_page_set_has_interior_pointers(mi_page_t* page, bool has_aligned) { + mi_page_flags_set(page, has_aligned, MI_PAGE_HAS_INTERIOR_POINTERS); +} + +// Are the blocks in this page memory tagged? (always false without `MI_MTE`) +static inline bool mi_page_is_memtag(const mi_page_t* page) { + return ((mi_page_flags(page) & MI_PAGE_IS_MEMTAGGED) != 0); +} + +// The tag class parity of the blocks in a memory tagged page: block `i` has the class of `i + parity` (see `prim-mte.h`). +// Adjacent pages must not share a tag class across their boundary, so a page starts with an even block (or a tag 0 gap) +// and ends with an odd block (or a tag 0 gap). When there is a (tag 0) cache offset gap in front of an odd number of +// blocks, we flip the parity such that the last block is odd. (A page without a front gap and an odd number of blocks +// that fills its slices exactly can only be a singleton (as regular page sizes are a power of two), which gets a tag 0 +// unit at the end, see `mi_arenas_page_singleton_alloc`.) +// (note: with page meta data in front of the slices, which happens only for OS-allocated pages, the meta data has the odd class) +static inline size_t mi_page_memtag_parity(const mi_page_t* page) { + return ((page->reserved & 1) != 0 && mi_page_meta_is_separated(page) && mi_page_start(page) != mi_page_slice_start(page) ? 1 : 0); +} + +// The tag exclusion mask for (re)tagging the `block` of size `bsize` in a memory tagged page, and the adjacent blocks in `*prev` +// and `*next` (or NULL) such that the new tag can differ from the tags of the adjacent blocks (see `prim-mte.h:mi_memtag_random_adjacent`). +// Only the first unit of the neighbours is read (as a guarded block may end in a guard page), and only for blocks below the capacity +// (as later blocks are not yet tagged and may not be committed). The first and the last block of the page use the tag class of `idx` +// (as the adjacent memory cannot be read). +// (note: the capacity is read concurrently by a non-owning thread (using the atomic `capacity_size`) but it only grows while the page +// has a used block; a stale capacity only means the next block is not considered, which is the same as a free just before an extension) +// (note: we branch on the (rare) edge case instead of selecting the mask as this keeps it off the critical path of the retagging) +static inline size_t mi_page_block_memtag_adjacent(const mi_page_t* page, const void* block, size_t bsize, size_t idx, const void** prev, const void** next) { + const uint8_t* const ublock = (const uint8_t*)mi_ptr_memtag_meta(block); + const size_t ofs = (size_t)(mi_addr(ublock) - mi_addr(mi_page_start(page))); + const size_t capacity_size = mi_page_capacity_size(page); + *prev = (ofs == 0 ? NULL : ublock - bsize); + *next = (ofs + bsize >= capacity_size ? NULL : ublock + bsize); + if mi_unlikely(ofs == 0 || ofs + bsize >= (size_t)page->reserved * bsize) { + return mi_memtag_exclude_base(idx, true); + } + return mi_memtag_exclude_base(idx, false); +} + +// Are freed blocks in this page zeroed (except for the free list link)? This holds for small blocks that are +// memory tagged or with `MI_SECURE>=3` (always false otherwise, or in debug mode as freed blocks are filled then) +static inline bool mi_page_is_zero_on_free(const mi_page_t* page) { + #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN + MI_UNUSED(page); + return false; + #else + return ((MI_SECURE>=3 || mi_page_is_memtag(page)) && mi_page_block_size(page) <= MI_ZERO_ON_FREE_MAX); + #endif +} + +#if MI_QSBR +// For qsbr, `qsbr_xthread_id` keeps the thread id of the last owning thread (so it is still available when a full page is abandoned) +// It is cleared when the owning theap abandons all its pages (e.g. on thread termination). +// The lowest bit is set if the page is in the qsbr queue of its theap. It is only written by the owning thread. +#define MI_PAGE_QSBR_IN_QUEUE MI_ZU(0x01) + +static inline mi_thread_id_t mi_page_qsbr_xthread_id(const mi_page_t* page) { + return mi_atomic_load_relaxed(&((mi_page_t*)page)->qsbr_xthread_id); +} + +static inline mi_thread_id_t mi_page_qsbr_thread_id(const mi_page_t* page) { + return (mi_page_qsbr_xthread_id(page) & ~MI_PAGE_FLAG_MASK); +} + +static inline void mi_page_qsbr_set_thread_id(mi_page_t* page, mi_thread_id_t tid) { + mi_assert_internal((tid & MI_PAGE_FLAG_MASK) == 0); + const mi_thread_id_t xtid = mi_page_qsbr_xthread_id(page); + mi_atomic_store_relaxed(&page->qsbr_xthread_id, tid | (xtid & MI_PAGE_QSBR_IN_QUEUE)); +} + +static inline bool mi_page_qsbr_is_in_queue(const mi_page_t* page) { + return ((mi_page_qsbr_xthread_id(page) & MI_PAGE_QSBR_IN_QUEUE) != 0); +} + +static inline void mi_page_qsbr_set_in_queue(mi_page_t* page, bool in_queue) { + const mi_thread_id_t xtid = mi_page_qsbr_xthread_id(page); + mi_atomic_store_relaxed(&page->qsbr_xthread_id, (in_queue ? (xtid | MI_PAGE_QSBR_IN_QUEUE) : (xtid & ~MI_PAGE_QSBR_IN_QUEUE))); +} +#endif + +static inline void mi_page_set_theap(mi_page_t* page, mi_theap_t* theap) { + // mi_assert_internal(!mi_page_is_in_full(page)); // can happen when destroying pages on theap_destroy + page->theap = theap; + const mi_thread_id_t tid = (theap == NULL ? MI_THREAD_ID_ABANDONED : theap->tld->thread_id); + mi_assert_internal((tid & MI_PAGE_FLAG_MASK) == 0); + + // Preserve flags set by concurrent aligned allocations. + if (theap == NULL) { + mi_atomic_and_release(&page->xthread_id, MI_PAGE_FLAG_MASK); + return; + } + mi_thread_id_t xtid_old = mi_page_xthread_id(page); + mi_thread_id_t xtid; + do { + xtid = tid | (xtid_old & MI_PAGE_FLAG_MASK); + } while (!mi_atomic_cas_weak_release(&page->xthread_id, &xtid_old, xtid)); + + #if MI_QSBR + // keep the last owning thread id around for `mi_thread_id_of` + if (tid > MI_THREAD_ID_DETACHED) { mi_page_qsbr_set_thread_id(page, tid); } + #endif +} + +static inline bool mi_page_is_abandoned(const mi_page_t* page) { + // note: the xtheap field of an abandoned theap is set to the subproc (for fast reclaim-on-free) + return (mi_page_thread_id(page) <= MI_THREAD_ID_ABANDONED_MAPPED); +} + +static inline bool mi_page_is_abandoned_mapped(const mi_page_t* page) { + return (mi_page_thread_id(page) == MI_THREAD_ID_ABANDONED_MAPPED); +} + +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_thread_id_t)MI_THREAD_ID_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_thread_id_t)MI_PAGE_FLAG_MASK); +} + + +static inline mi_theap_t* mi_page_theap(const mi_page_t* page) { + mi_assert_internal(!mi_page_is_abandoned(page)); + mi_assert_internal(page->theap != NULL && !_mi_is_empty_theap(page->theap)); + return page->theap; +} + +static inline mi_tld_t* mi_page_tld(const mi_page_t* page) { + mi_assert_internal(!mi_page_is_abandoned(page)); + mi_assert_internal(page->theap != NULL); + return page->theap->tld; +} + + +static inline mi_heap_t* mi_page_heap(const mi_page_t* page) { + mi_heap_t* heap = page->heap; + mi_assert_internal(heap != NULL); + return heap; +} + +// A page visitor may free or move pages, so we remember the page map entry of a live page +// to check later if it is still live (without accessing the page itself). +typedef struct mi_page_ref_s { + const void* start; + mi_page_t* entry; +} mi_page_ref_t; + +static inline mi_page_ref_t mi_page_ref(const mi_page_t* page) { + mi_page_ref_t ref = { NULL, NULL }; + if (page != NULL) { + ref.start = mi_page_start(page); + ref.entry = _mi_safe_ptr_page(ref.start); + } + return ref; +} + +static inline bool mi_page_ref_is_live(mi_page_ref_t ref) { + return (ref.start == NULL || _mi_safe_ptr_page(ref.start) == ref.entry); +} + +// Visit a page list where `fun` may free or move pages: we only continue at the next page if it +// is still live (and may miss pages that are freed or moved). Returns `false` if `fun` did. +typedef bool (mi_page_list_visit_fun)(mi_page_t* page, void* arg); + +static inline bool mi_page_list_visit(mi_page_t* page, mi_page_list_visit_fun* fun, void* arg) { + while (page != NULL) { + mi_page_t* const next = page->next; + const mi_page_ref_t next_ref = mi_page_ref(next); + if (!fun(page, arg)) return false; + if (!mi_page_ref_is_live(next_ref)) break; + page = next; + } + return true; +} + +static inline mi_subproc_t* mi_page_subproc(const mi_page_t* page) { + mi_heap_t* const heap = mi_page_heap(page); + return heap->subproc; +} + +//----------------------------------------------------------- +// Thread free list and ownership +//----------------------------------------------------------- + +// Thread free flag helpers +static inline mi_block_t* mi_tf_block(mi_thread_free_t tf) { + return (mi_block_t*)(tf & ~1); +} + +static inline bool mi_tf_is_owned(mi_thread_free_t tf) { + return ((tf & 1) == 1); +} + +static inline mi_thread_free_t mi_tf_create(mi_block_t* block, bool owned) { + const uintptr_t base = (uintptr_t)block | (owned ? 1 : 0); + return (mi_thread_free_t)base; +} + +static inline mi_thread_free_t mi_tf_set_owned(mi_thread_free_t tf, bool owned) { + return mi_tf_create(mi_tf_block(tf), owned); +} + +// Thread free access +static inline mi_block_t* mi_page_thread_free(const mi_page_t* page) { + return mi_tf_block(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free)); +} + +// are there any available blocks? +static inline bool mi_page_has_any_available(const mi_page_t* page) { + mi_assert_internal(page != NULL && page->reserved > 0); + return (mi_page_used(page) < page->reserved || (mi_page_thread_free(page) != NULL)); +} + +// Owned? +static inline bool mi_page_is_owned(const mi_page_t* page) { + return mi_tf_is_owned(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free)); +} + +// 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, (uintptr_t)1); + return ((old&1)==0); +} + +/* ----------------------------------------------------------- + Delayed page release +----------------------------------------------------------- */ + +static inline void mi_page_qsbr_unlink(mi_page_t* page) { +#if MI_QSBR + if (!mi_page_qsbr_is_in_queue(page)) { + mi_assert_internal(page->qsbr_next == NULL && page->qsbr_prev == NULL); + return; + } + mi_theap_t* theap = mi_page_theap(page); + if (page->qsbr_prev != NULL) { page->qsbr_prev->qsbr_next = page->qsbr_next; } + else { + mi_assert_internal(theap->qsbr_delayed == page); + theap->qsbr_delayed = page->qsbr_next; + } + if (page->qsbr_next != NULL) { page->qsbr_next->qsbr_prev = page->qsbr_prev; } + else { + mi_assert_internal(theap->qsbr_delayed_last == page); + theap->qsbr_delayed_last = page->qsbr_prev; + } + page->qsbr_next = page->qsbr_prev = NULL; + mi_page_qsbr_set_in_queue(page, false); +#else + MI_UNUSED(page); +#endif +} + +static inline void mi_page_qsbr_enqueue(mi_page_t* page, mi_theap_t* theap) { +#if MI_QSBR + mi_assert_internal(mi_page_theap(page) == theap); + mi_assert_internal(mi_page_all_free(page)); + mi_assert_internal(mi_heap_qsbr_is_enabled(mi_page_heap(page))); + mi_assert_internal(!mi_page_qsbr_is_clear(&page->qsbr)); + if (mi_page_qsbr_is_in_queue(page)) return; + mi_assert_internal(page->qsbr_next == NULL && page->qsbr_prev == NULL); + page->qsbr_prev = theap->qsbr_delayed_last; + if (theap->qsbr_delayed_last != NULL) { theap->qsbr_delayed_last->qsbr_next = page; } + else { theap->qsbr_delayed = page; } + theap->qsbr_delayed_last = page; + mi_page_qsbr_set_in_queue(page, true); +#else + MI_UNUSED(page); + MI_UNUSED(theap); +#endif +} + +static inline void _mi_page_qsbr_clear(mi_page_t* page) { +#if MI_QSBR + mi_page_qsbr_unlink(page); + mi_page_qsbr_clear(&page->qsbr); +#else + MI_UNUSED(page); +#endif +} + +static inline bool _mi_page_qsbr_is_clear(const mi_page_t* page) { +#if MI_QSBR + return (!mi_page_qsbr_is_in_queue(page) && page->qsbr_next == NULL && page->qsbr_prev == NULL && + mi_page_qsbr_is_clear(&page->qsbr)); +#else + MI_UNUSED(page); + return true; +#endif +} + +static inline bool _mi_page_qsbr_should_delay(mi_page_t* page) { +#if MI_QSBR + mi_assert_internal(mi_page_is_owned(page) && mi_page_all_free(page)); + mi_heap_t* heap = mi_page_heap(page); + if (!mi_heap_qsbr_is_enabled(heap)) return false; + const bool delayed = mi_page_qsbr_should_delay(&page->qsbr, &heap->qsbr, mi_page_capacity_size(page)); + mi_assert_internal(!delayed || !mi_page_qsbr_is_clear(&page->qsbr)); + return delayed; +#else + MI_UNUSED(page); + return false; +#endif +} + +/* ------------------------------------------------------------------- +Encoding/Decoding the free list next pointers + +This is to protect against buffer overflow exploits where the +free list is mutated. Many hardened allocators xor the next pointer `p` +with a secret key `k`, as `p^k`. This is weak: if the attacker can guess +`p` this reveals `k`, and xor-ing two entries cancels the key. A non-linear +encoding like `((p^k2)<<> 32) + + where `H` is as in the tagged offsets (the upper 32 bits, or with memory tagging all bits + outside the 24-bit offset), and `pacga` returns a 32-bit code in the upper 32 bits (and zeros + in the lower bits); the copy in the lower half provides the tag bits below bit 32 with memory tagging. + The integrity of the links does not depend on the page keys: `keys[0]` serves as a nonce + such that links from a previous use of the page do not validate, and a forged link validates + with probability 2^-32 even if the page keys are known. The mask `keys[1]` still hides the + (randomized) free list order (and the memory tags of the free blocks) from an attacker that + can only read freed memory. + +3. Xor-shift (the default on 32-bit, where we lack a cheap wide multiply). + We store the full next address `p` (with `NULL` encoded as the page address): + + x = L(p - t) <<< keys[0] + t = L(b ^ keys[0]) + keys[1] + L(y) = y ^ (y << (MI_SIZE_BITS/2)) (which is its own inverse) + + The tweak `t` binds the link to the block `b`, the xor-shift `L` diffuses + low bits into the high bits (such that partial overwrites decode outside + the page), and the secret rotation prevents linear combinations of + additions and xor's. Decoded links are validated by checking that they + are in the page. + +The padding canary encodes `NULL` at the unaligned address `b|1` (so it can +never be used as a valid free list link). +------------------------------------------------------------------- */ + +static inline bool mi_is_in_same_page(const void* p, const void* q) { + mi_page_t* page = mi_ptr_page(p); + return mi_page_contains_address(page,q); + // return (mi_ptr_page(p) == mi_ptr_page(q)); +} + +// The inputs to encode the free list links of a page; these can be loaded once before a loop +// (as in a CAS loop where the compiler cannot hoist the loads from the page). +typedef struct mi_page_codec_s { + const mi_page_t* page; + #if (MI_ENCODE_FREELIST || MI_PADDING) + uint8_t* page_start; + mi_addr_t keys[2]; + #endif +} mi_page_codec_t; + +static inline mi_page_codec_t mi_page_codec(const mi_page_t* page) { + mi_page_codec_t codec; + codec.page = page; + #if (MI_ENCODE_FREELIST || MI_PADDING) + codec.page_start = mi_page_start(page); + codec.keys[0] = page->keys[0]; + codec.keys[1] = page->keys[1]; + #endif + return codec; +} + +#if (MI_ENCODE_FREELIST || MI_PADDING) +#if MI_SIZE_BITS>=64 // tagged offsets + +// On 64-bit, a free list link stores the offset `d` of the next block (relative to the link address, or to the page start +// with memory tagging or CHERI), masked with +// a key, and a (keyed) MAC over `d` and the address of the link in all other bits (where the whole link is masked). With memory tagging, `d` includes +// the memory tag of the next block (at `MI_PTR_MEMTAG_MASK`, as the page start has tag 0) and we use a smaller +// offset to keep a longer MAC (pages with more than one block are at most `MI_LARGE_PAGE_SIZE`). Without memory +// tagging we use a 32-bit offset as that gives the best codegen (as the mask folds into the add, e.g. `uxtw` on arm64). +#define MI_BLOCK_OFS_BITS (MI_PTR_MEMTAG_MASK==0 ? 32 : 24) +#define MI_BLOCK_OFS_MASK (MI_PTR_MEMTAG_MASK | ((MI_ADDR(1) << MI_BLOCK_OFS_BITS) - 1)) +#define MI_BLOCK_OFS_NULL ((MI_ADDR(1) << MI_BLOCK_OFS_BITS) - 1) // odd, so never a block offset + +#if MI_LARGE_PAGE_SIZE >= (1UL<<24) +#error "the block offsets in a page with multiple blocks must fit in a free list link (see MI_BLOCK_OFS_BITS)" +#endif + +#if MI_PAC>=2 +static inline mi_addr_t mi_ptr_mac(const mi_page_codec_t* codec, mi_addr_t baddr, mi_addr_t d) { + return mi_keyed_mac(d, baddr ^ codec->keys[0]); +} +static inline mi_addr_t mi_ptr_ofs_key(const mi_page_codec_t* codec) { + return codec->keys[1]; +} +#else +static inline mi_addr_t mi_ptr_mac(const mi_page_codec_t* codec, mi_addr_t baddr, mi_addr_t d) { + #if MI_ENCODE_FREELIST==1 + return mi_keyed_mac_fast(d ^ codec->keys[0], baddr ^ codec->keys[1]); + #else + return mi_keyed_mac(d ^ codec->keys[0], baddr ^ codec->keys[1]); + #endif +} +static inline mi_addr_t mi_ptr_ofs_key(const mi_page_codec_t* codec) { + return mi_rotl(codec->keys[0], 32); +} +#endif + +// The offset is relative to the link address `baddr` (as a signed 32-bit value) such that decoding does not +// need the page start (but with memory tagging or CHERI we need the page start for the tag or capability). +#if !MI_MTE && !MI_CHERI +#define MI_BLOCK_OFS_RELATIVE 1 +#else +#define MI_BLOCK_OFS_RELATIVE 0 +#endif + +// Encode a pointer `p` (in the page, or NULL) to be stored at address `baddr` +static inline mi_encoded_t mi_ptr_encode(const mi_page_codec_t* codec, mi_addr_t baddr, const void* p) { + mi_assert_internal(p==NULL || mi_page_contains_address(codec->page,p)); + #if MI_BLOCK_OFS_RELATIVE + const mi_addr_t d = (p==NULL ? MI_BLOCK_OFS_NULL : (mi_addr(p) - baddr) & MI_BLOCK_OFS_MASK); + #else + const mi_addr_t d = (p==NULL ? MI_BLOCK_OFS_NULL : mi_ptr_pack(p) - mi_addr(codec->page_start)); + #endif + return (mi_encoded_t)(mi_ptr_ofs_key(codec) ^ (d | (mi_ptr_mac(codec,baddr,d) & ~MI_BLOCK_OFS_MASK))); +} + +// Decode a value `x` stored at address `baddr`; `valid` is false if `x` was not a valid encoding +static inline void* mi_ptr_decode(const mi_page_codec_t* codec, mi_addr_t baddr, mi_encoded_t x, bool* valid) { + const mi_addr_t y = (mi_addr_t)x ^ mi_ptr_ofs_key(codec); + const mi_addr_t d = y & MI_BLOCK_OFS_MASK; + *valid = (((y ^ mi_ptr_mac(codec,baddr,d)) & ~MI_BLOCK_OFS_MASK) == 0); + #if MI_BLOCK_OFS_RELATIVE + return (d == MI_BLOCK_OFS_NULL ? NULL : (void*)(baddr + (mi_addr_t)(intptr_t)(int32_t)(uint32_t)d)); + #else + return (d == MI_BLOCK_OFS_NULL ? NULL : codec->page_start + d); + #endif +} + +#else + +static inline mi_addr_t mi_xorshift_half(mi_addr_t y) { + return (y ^ (y << (MI_SIZE_BITS/2))); +} + +static inline mi_addr_t mi_ptr_tweak(const mi_page_codec_t* codec, mi_addr_t baddr) { + return (mi_xorshift_half(baddr ^ codec->keys[0]) + codec->keys[1]); +} + +// Encode a pointer `p` (in the page, or NULL) to be stored at address `baddr` +static inline mi_encoded_t mi_ptr_encode(const mi_page_codec_t* codec, mi_addr_t baddr, const void* p) { + mi_assert_internal(p==NULL || mi_page_contains_address(codec->page,p)); + const mi_addr_tagged_t addrt = (p==NULL ? (mi_addr_tagged_t)mi_addr(codec->page) : mi_ptr_pack(p)); + return (mi_encoded_t)mi_rotl(mi_xorshift_half(addrt - mi_ptr_tweak(codec,baddr)), codec->keys[0]); +} + +// Decode a value `x` stored at address `baddr`; `valid` is false if `x` was not a valid encoding +static inline void* mi_ptr_decode(const mi_page_codec_t* codec, mi_addr_t baddr, mi_encoded_t x, bool* valid) { + const mi_addr_tagged_t addrt = mi_xorshift_half(mi_rotr((mi_addr_t)x, codec->keys[0])) + mi_ptr_tweak(codec,baddr); + if (addrt == (mi_addr_tagged_t)mi_addr(codec->page)) { *valid = true; return NULL; } + void* const p = mi_ptr_unpack(codec->page_start, addrt); + *valid = mi_page_contains_address(codec->page, p); + return p; +} + +#endif + +static inline uint32_t mi_ptr_encode_canary(const mi_page_t* page, const mi_block_t* block) { + const mi_page_codec_t codec = mi_page_codec(page); + const mi_addr_t e = (mi_addr_t)mi_ptr_encode(&codec, mi_addr(block)|1, NULL); + const uint32_t x = (uint32_t)(e ^ (e >> (MI_SIZE_BITS/2))); + // make the lowest byte 0 to prevent spurious read overflows which could be a security issue (issue #951) + // also clear bit 9 which we set only when a block is freed. + #if MI_BIG_ENDIAN + return (x & 0x00FFFEFF); + #else + return (x & 0xFFFFFE00); + #endif +} + +static inline uint32_t mi_ptr_encode_canary_freed(void) { + return (0x00DEAD00); // set bit 9 so it is different from any valid canary +} + +static inline bool mi_ptr_decode_canary_is_freed(uint32_t canary) { + return (canary == mi_ptr_encode_canary_freed()); +} + +#endif // MI_ENCODE_FREELIST || MI_PADDING + +// Is `next` an aligned link inside the committed blocks of the page? (used to detect use-after-free writes in free lists +// that are not encoded, as encoded links are already validated by `mi_block_decode`) +static inline bool mi_block_next_is_valid(const mi_page_t* page, const mi_block_t* next, size_t capacity_size) { + const mi_addr_t ofs = mi_addr(next) - mi_addr(mi_page_start(page)); + return (ofs < capacity_size && ofs % MI_INTPTR_SIZE == 0); +} + +// Decode the free list link `x` stored in `block`; `valid` is false if the link was corrupted +static inline mi_block_t* mi_block_decode(const mi_page_t* page, const mi_block_t* block, mi_encoded_t x, bool* valid) { + #if MI_ENCODE_FREELIST + const mi_page_codec_t codec = mi_page_codec(page); + return (mi_block_t*)mi_ptr_decode(&codec, mi_addr(block), x, valid); + #else + MI_UNUSED(block); + *valid = true; + const mi_addr_tagged_t addrt = (mi_addr_tagged_t)x; + return (addrt==0 ? NULL : (mi_block_t*)mi_ptr_unpack(mi_page_start(page), addrt)); + #endif +} + +static inline mi_encoded_t mi_block_encode(const mi_page_codec_t* codec, const mi_block_t* block, const mi_block_t* next) { + #if MI_ENCODE_FREELIST + return mi_ptr_encode(codec, mi_addr(block), next); + #else + MI_UNUSED(codec); MI_UNUSED(block); + return (mi_encoded_t)mi_ptr_pack(next); // never store a capability in a (freed) block + #endif +} + +static inline mi_encoded_t mi_block_link(const mi_block_t* block) { + mi_track_mem_defined(block,sizeof(mi_block_t)); + const mi_encoded_t x = mi_atomic_load_relaxed(&block->next); + mi_track_mem_noaccess(block,sizeof(mi_block_t)); + return x; +} + +static inline mi_block_t* mi_block_next(const mi_page_t* page, const mi_block_t* block) { + const mi_encoded_t x = mi_block_link(block); + bool valid; + mi_block_t* const next = mi_block_decode(page, block, x, &valid); + if mi_unlikely(!valid) { + return _mi_error_block_next_is_corrupted(page, block, x); // returns NULL + } + return next; +} + +static inline void mi_block_set_next_ex(const mi_page_codec_t* codec, mi_block_t* block, const mi_block_t* next) { + mi_track_mem_undefined(block,sizeof(mi_block_t)); + mi_atomic_store_relaxed(&block->next, mi_block_encode(codec, block, next)); + mi_track_mem_noaccess(block,sizeof(mi_block_t)); +} + +static inline void mi_block_set_next(const mi_page_t* page, mi_block_t* block, const mi_block_t* next) { + const mi_page_codec_t codec = mi_page_codec(page); + mi_block_set_next_ex(&codec, block, next); +} + + +/* ----------------------------------------------------------- + Safe unlinking of doubly linked lists + + In secure mode, check that a `node` is properly linked through its `prev` and `next` + fields before unlinking it, such that corrupted links cannot be used for arbitrary writes. + `first` is the head of the list, and `last` the tail (or `NULL` if the list has no tail). + A corrupted list is a fatal error. +----------------------------------------------------------- */ + +static inline bool mi_list_link_is(const void* link, const void* node) { + return (mi_addr(link) == mi_addr(node)); // ignore memory tags +} + +#if MI_SECURE>=1 +#define mi_list_unlink_check(node,prev,next,first,last) \ + do { \ + if mi_unlikely(!((node)->prev==NULL ? mi_list_link_is(first,node) : mi_list_link_is((node)->prev->next,node)) || \ + !((node)->next==NULL ? ((last)==NULL || mi_list_link_is(last,node)) : mi_list_link_is((node)->next->prev,node))) \ + { _mi_error_list_corrupted(node); } \ + } while(0) +#else +#define mi_list_unlink_check(node,prev,next,first,last) do { } while(0) +#endif + +#endif diff --git a/Include/internal/mimalloc/mimalloc/arch.h b/Include/internal/mimalloc/mimalloc/arch.h new file mode 100644 index 00000000000000..d11f9bb0e47858 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/arch.h @@ -0,0 +1,695 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2019-2026 Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ + +/* ---------------------------------------------------------------------------- + Platform dependent definitions (MI_INTPTR_SIZE etc.), and bit operations. +---------------------------------------------------------------------------- */ + +#pragma once +#ifndef MI_ARCH_H +#define MI_ARCH_H + +#include // size_t +#include // int64_t etc +#include // bool +#include // LONG_MAX + +// Header availability for builds that do not use CMake. +#if !defined(MI_HAS_UNISTDH) && !defined(_WIN32) +#if defined(__has_include) +#if __has_include() +#define MI_HAS_UNISTDH 1 +#endif +#elif defined(__unix__) || defined(__APPLE__) || defined(__HAIKU__) +#define MI_HAS_UNISTDH 1 +#endif +#endif + +// C++ versus C +#if defined(__cplusplus) +#define mi_decl_externc extern "C" +#define mi_init_struct_zero { } +#else +#define mi_decl_externc +#define mi_init_struct_zero { 0 } +#endif + +#if defined(__CHERI_PURE_CAPABILITY__) +#define MI_CHERI 1 +#endif + +// ------------------------------------------------------ +// Size of a pointer. +// We assume that `sizeof(void*)==sizeof(intptr_t)` +// and it holds for all platforms we know of. +// +// However, the C standard only requires that: +// p == (void*)((intptr_t)p)) +// but we also need: +// i == (intptr_t)((void*)i) +// or otherwise one might define an intptr_t type that is larger than a pointer... +// +// On CHERI, pointers are 128-bit capabilities but `INTPTR_MAX` is `INT64_MAX` +// (as only the address is an integer value), so we use `__SIZEOF_POINTER__` if available. +// ------------------------------------------------------ + +#if defined(__SIZEOF_POINTER__) +#if (__SIZEOF_POINTER__ == 16) +# define MI_INTPTR_SHIFT (4) // 128-bit (as on CHERI for example) +#endif +#endif + +#if defined(MI_INTPTR_SHIFT) +// already defined +#elif INTPTR_MAX > INT64_MAX +# define MI_INTPTR_SHIFT (4) +#elif INTPTR_MAX == INT64_MAX +# define MI_INTPTR_SHIFT (3) +#elif INTPTR_MAX == INT32_MAX +# define MI_INTPTR_SHIFT (2) +#else +#error platform pointers must be 32, 64, or 128 bits +#endif + +#if (INTPTR_MAX) > LONG_MAX +# define MI_PU(x) x##ULL +#else +# define MI_PU(x) x##UL +#endif + +#if SIZE_MAX == UINT64_MAX +# define MI_SIZE_SHIFT (3) +typedef int64_t mi_ssize_t; +#define MI_SSIZE_MAX INT64_MAX +#elif SIZE_MAX == UINT32_MAX +# define MI_SIZE_SHIFT (2) +typedef int32_t mi_ssize_t; +#define MI_SSIZE_MAX INT32_MAX +#else +#error platform objects must be 32 or 64 bits in size +#endif + +#if (SIZE_MAX/2) > LONG_MAX +# define MI_ZU(x) x##ULL +#else +# define MI_ZU(x) x##UL +#endif + +#define MI_INTPTR_SIZE (1< +#elif MI_ARCH_ARM64 && MI_OPT_SIMD +#include +#endif +#if defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32) +#include +#endif + +#if MI_ARCH_X64 && defined(__AVX2__) && !defined(__BMI2__) // avx2 implies bmi2 +#define __BMI2__ 1 +#endif +#if MI_ARCH_X64 && (defined(__AVX2__) || defined(__BMI2__) || defined(__BMI__)) && !defined(__BMI1__) // bmi2 implies bmi1 +#define __BMI1__ 1 +#endif +#if MI_ARCH_X64 && defined(__AVX2__) && !defined(__LZCNT__) // avx2 implies lzcnt +#define __LZCNT__ 1 +#endif + +// maximum virtual address bits in a user-space pointer +#if MI_DEFAULT_VIRTUAL_ADDRESS_BITS > 0 +#define MI_MAX_VABITS MI_DEFAULT_VIRTUAL_ADDRESS_BITS +#elif MI_ARCH_X64 && (MI_INTPTR_SIZE > 4) // not on x32 +#define MI_MAX_VABITS (47) +#elif MI_INTPTR_SIZE > 4 +#define MI_MAX_VABITS (48) +#else +#define MI_MAX_VABITS (32) +#endif + +// the MI_MIN_VABITS determine how many bits of the address space are always committed in the page_map +#if MI_MAX_VABITS <= 32 +#define MI_MIN_VABITS (32) +#elif MI_MAX_VABITS <= 42 +#define MI_MIN_VABITS MI_MAX_VABITS +#else +#define MI_MIN_VABITS (43) /* 8 TiB */ +#endif + +// Always use the page map in `mi_free` on CHERI as we cannot derive the page meta-data from a (bounded) user pointer, +// and on WebAssembly as it cannot do large aligned allocations well (needed for aligned page meta-data). +#if (MI_CHERI || defined(__wasi__) || defined(__EMSCRIPTEN__)) && !defined(MI_FREE_USE_PAGEMAP) +#define MI_FREE_USE_PAGEMAP 1 +#endif + +// Probable OS page size (as statically known; the actual page size is determined at runtime with `_mi_os_page_size()`). +// Can be set explicitly, e.g. `-DMI_OS_PROBABLE_PAGE_SIZE=65536` for arm64 Linux kernels with 64 KiB pages. +#if !defined(MI_OS_PROBABLE_PAGE_SIZE) +#if defined(__APPLE__) // check first as `PAGE_SIZE` may be the runtime `vm_page_size` there +#if MI_ARCH_ARM64 +#define MI_OS_PROBABLE_PAGE_SIZE (16*MI_KiB) // macOS, iOS, etc. on Apple silicon +#else +#define MI_OS_PROBABLE_PAGE_SIZE (4*MI_KiB) +#endif +#elif defined(__wasm__) || defined(__EMSCRIPTEN__) || defined(__wasi__) +#define MI_OS_PROBABLE_PAGE_SIZE (64*MI_KiB) // fixed WebAssembly page size +#elif defined(PAGE_SIZE) // only defined if constant (FreeBSD, musl on x86, bionic without flexible page sizes, ...) +#define MI_OS_PROBABLE_PAGE_SIZE PAGE_SIZE +#elif defined(__linux__) && (defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__)) +#define MI_OS_PROBABLE_PAGE_SIZE (64*MI_KiB) // default for ppc64(le) distributions +#elif defined(__linux__) && defined(__loongarch__) +#define MI_OS_PROBABLE_PAGE_SIZE (16*MI_KiB) // default for LoongArch kernels +#elif defined(__ANDROID__) && defined(__BIONIC_NO_PAGE_SIZE_MACRO) +#define MI_OS_PROBABLE_PAGE_SIZE (16*MI_KiB) // built with flexible page size support (NDK r27+), so it can run with 16 KiB pages +#else +#define MI_OS_PROBABLE_PAGE_SIZE (4*MI_KiB) +#endif +#endif + +// Does the OS have guard pages? +#if !defined(MI_OS_HAS_GUARD_PAGES) +#if defined(__wasm__) || defined(__EMSCRIPTEN__) || defined(__wasi__) +#define MI_OS_HAS_GUARD_PAGES 0 +#elif defined(__uClinux__) // no MMU +#define MI_OS_HAS_GUARD_PAGES 0 +#else +#define MI_OS_HAS_GUARD_PAGES 1 +#endif +#endif + + +// ------------------------------------------------------ +// Signed pointers (see `prim/prim-pac.h`): with `MI_PAC` some internal pointers are stored signed +// (using ARM pointer authentication or a software keyed encoding); this is a `uintptr_t` so it can be atomic. +// ------------------------------------------------------ + +typedef uintptr_t mi_ptr_signed_t; +#define mi_ptr_signed(tp) mi_ptr_signed_t // a signed `tp*` (only documents the pointer type) + +#define mi_ptr_signed_from_ptr(tp,p) ((mi_ptr_signed(tp))(p)) +#define mi_ptr_signed_as_ptr(tp,p) ((tp*)(p)) +#define mi_ptr_signed_null(tp) mi_ptr_signed_from_ptr(tp,NULL) + +static inline bool mi_ptr_signed_is_null(mi_ptr_signed_t p) { + return (p == mi_ptr_signed_null(void)); +} + + +// Pointer signing (see `prim/prim-pac.h`): 0=off, 1=weak (using a software process key), 2=required (using the +// arm64 generic pointer authentication key (`pacga`), which must be supported at runtime). +// Only on 64-bit systems (and not on CHERI); `required` only on arm64 with GCC or clang. +// Defaults to `required` with `MI_MTE=2` as all MTE hardware supports PAC. +#if (MI_MTE >= 2) && !defined(MI_PAC) +#define MI_PAC 2 +#endif +#if (MI_PAC >= 2) && !(MI_ARCH_ARM64 && defined(__GNUC__)) +#error "pointer authentication (MI_PAC=ON) is only supported on arm64 with GCC or clang" +#elif (MI_PAC > 0) && (MI_CHERI || (MI_INTPTR_SIZE != 8)) +#warning "pointer authentication (MI_PAC=ON) is not supported on CHERI or non-64-bit systems" +#undef MI_PAC +#define MI_PAC 0 +#elif !defined(MI_PAC) +#define MI_PAC 0 +#endif + + +// ------------------------------------------------------ +// Capability bounds, permissions, and pointer provenance (only on CHERI at this point). +// Internally all blocks are derived from the page start which is bounded to the block area +// of the page, while pointers handed out to the user are bounded to their block and lose +// any non-data permissions. +// ------------------------------------------------------ + +#if MI_CHERI +#if defined(__has_include) +#if __has_include() +#include // CHERI_PERM_SW_VMEM on CheriBSD +#endif +#endif +#if defined(CHERI_PERM_SW_VMEM) +#define MI_CHERI_PERM_SW_VMEM CHERI_PERM_SW_VMEM // permission to (un)map memory +#elif defined(CHERI_PERM_CHERIABI_VMMAP) +#define MI_CHERI_PERM_SW_VMEM CHERI_PERM_CHERIABI_VMMAP // older CheriBSD +#else +#define MI_CHERI_PERM_SW_VMEM 0 +#endif +// permissions that data pointers (user blocks and internal meta data) never need +#define MI_CHERI_PERMS_NOT_DATA (__CHERI_CAP_PERMISSION_PERMIT_EXECUTE__ | __CHERI_CAP_PERMISSION_PERMIT_SEAL__ | \ + __CHERI_CAP_PERMISSION_PERMIT_UNSEAL__ | __CHERI_CAP_PERMISSION_ACCESS_SYSTEM_REGISTERS__ | \ + MI_CHERI_PERM_SW_VMEM) +// permissions a pointer passed to `mi_free` must have +#define MI_CHERI_PERMS_FREE (__CHERI_CAP_PERMISSION_PERMIT_LOAD__ | __CHERI_CAP_PERMISSION_PERMIT_STORE__ | \ + __CHERI_CAP_PERMISSION_PERMIT_LOAD_CAPABILITY__ | __CHERI_CAP_PERMISSION_PERMIT_STORE_CAPABILITY__) +#endif + +// The bounds size for a pointer to `size` bytes that is handed out to the user. On CHERI this is never zero: +// a zero-length capability can be validly derived at the end of a neighbouring block (which may be the start of +// another block), so `mi_free` rejects zero-length capabilities. +static inline size_t mi_bounds_user_size(size_t size) { + #if MI_CHERI + return (size==0 ? 1 : size); + #else + return size; + #endif +} + +// The alignment needed for exactly representable bounds of `size` bytes (always a power of 2, and 1 if not on CHERI) +static inline size_t mi_bounds_align(size_t size) { + #if MI_CHERI + return ~(size_t)__builtin_cheri_representable_alignment_mask(size) + 1; + #else + MI_UNUSED(size); + return 1; + #endif +} + +// Round `size` up such that bounds of that size can be exactly representable (`size` if not on CHERI) +static inline size_t mi_bounds_size(size_t size) { + #if MI_CHERI + return __builtin_cheri_round_representable_length(size); + #else + return size; + #endif +} + +// Restrict `p` to `size` bytes (rounded outward if that is not exactly representable) +static inline void* mi_ptr_bounded(void* p, size_t size) { + #if MI_CHERI + return __builtin_cheri_bounds_set(p, size); + #else + MI_UNUSED(size); + return p; + #endif +} + +// Restrict a (non-NULL) pointer to `size` bytes and data permissions only +static inline void* mi_ptr_bounded_data(void* p, size_t size) { + #if MI_CHERI + return mi_ptr_bounded(__builtin_cheri_perms_and(p, ~(size_t)MI_CHERI_PERMS_NOT_DATA), size); + #else + MI_UNUSED(size); + return p; + #endif +} + +// Keep the address and memory tag of `p`, taking capability authority from `auth` +static inline void* mi_ptr_rederive(const void* auth, const void* p) { + #if MI_CHERI + return mi_ptr_with_addr(auth, mi_addr(p)); + #else + MI_UNUSED(auth); + return (void*)p; + #endif +} + +// Limit `size` to the bytes accessible through `p` (`size` if not on a system with provenance) +static inline size_t mi_ptr_bounds_limit(const void* p, size_t size) { + #if MI_CHERI + const size_t len = (size_t)__builtin_cheri_length_get(p); + const size_t ofs = (size_t)__builtin_cheri_offset_get(p); + const size_t avail = (ofs <= len ? len - ofs : 0); + return (size <= avail ? size : avail); + #else + MI_UNUSED(p); + return size; + #endif +} + + +/* -------------------------------------------------------------------------------- + Builtin's +-------------------------------------------------------------------------------- */ + +#ifndef __has_builtin +#define __has_builtin(x) 0 +#endif + +#define mi_builtin(name) __builtin_##name +#define mi_has_builtin(name) __has_builtin(__builtin_##name) + +#if (LONG_MAX == INT32_MAX) +#define mi_builtin32(name) mi_builtin(name##l) +#define mi_has_builtin32(name) mi_has_builtin(name##l) +#else +#define mi_builtin32(name) mi_builtin(name) +#define mi_has_builtin32(name) mi_has_builtin(name) +#endif +#if (LONG_MAX == INT64_MAX) +#define mi_builtin64(name) mi_builtin(name##l) +#define mi_has_builtin64(name) mi_has_builtin(name##l) +#else +#define mi_builtin64(name) mi_builtin(name##ll) +#define mi_has_builtin64(name) mi_has_builtin(name##ll) +#endif + +#if (MI_SIZE_BITS == 32) +#define mi_builtinz(name) mi_builtin32(name) +#define mi_has_builtinz(name) mi_has_builtin32(name) +#define mi_msc_builtinz(name) name +#elif (MI_SIZE_BITS == 64) +#define mi_builtinz(name) mi_builtin64(name) +#define mi_has_builtinz(name) mi_has_builtin64(name) +#define mi_msc_builtinz(name) name##64 +#endif + +/* -------------------------------------------------------------------------------- + Popcount and count trailing/leading zero's +-------------------------------------------------------------------------------- */ + +size_t _mi_popcount_generic(size_t x); +extern bool _mi_cpu_has_popcnt; + +static inline size_t mi_popcount(size_t x) { + #if mi_has_builtinz(popcount) + return mi_builtinz(popcount)(x); + #elif defined(_MSC_VER) && (MI_ARCH_ARM64 || MI_ARCH_ARM32) + return mi_msc_builtinz(_CountOneBits)(x); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86) + if (_mi_cpu_has_popcnt) { return mi_msc_builtinz(__popcnt)(x); } + else { return _mi_popcount_generic(x); } // see issue #1291 + #elif MI_ARCH_X64 && defined(__BMI1__) + #if (MI_SIZE_BITS == 64) + return (size_t)_mm_popcnt_u64(x); + #else + return (size_t)_mm_popcnt_u32(x); // x32 + #endif + #else + #define MI_HAS_FAST_POPCOUNT 0 + return (x<=1 ? x : _mi_popcount_generic(x)); + #endif +} + +#ifndef MI_HAS_FAST_POPCOUNT +#define MI_HAS_FAST_POPCOUNT 1 +#endif + +size_t _mi_clz_generic(size_t x); +size_t _mi_ctz_generic(size_t x); + +static inline size_t mi_ctz(size_t x) { + #if defined(__GNUC__) && MI_ARCH_X64 && defined(__BMI1__) // on x64 tzcnt is defined for 0 + size_t r; + __asm ("tzcnt\t%1, %0" : "=r"(r) : "r"(x) : "cc"); + return r; + #elif defined(_MSC_VER) && MI_ARCH_X64 && defined(__BMI1__) + return _tzcnt_u64(x); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32) + unsigned long idx; + return (mi_msc_builtinz(_BitScanForward)(&idx, x) ? (size_t)idx : MI_SIZE_BITS); + #elif mi_has_builtinz(ctz) + return (x!=0 ? (size_t)mi_builtinz(ctz)(x) : MI_SIZE_BITS); + #elif defined(__GNUC__) && (MI_ARCH_X64 || MI_ARCH_X86) + size_t r = MI_SIZE_BITS; // bsf leaves destination unmodified if the argument is 0 (see ) + __asm ("bsf\t%1, %0" : "+r"(r) : "r"(x) : "cc"); + return r; + #elif MI_HAS_FAST_POPCOUNT + return (x!=0 ? (mi_popcount(x^(x-1))-1) : MI_SIZE_BITS); + #else + #define MI_HAS_FAST_BITSCAN 0 + return (x!=0 ? _mi_ctz_generic(x) : MI_SIZE_BITS); + #endif +} + +static inline size_t mi_clz(size_t x) { + #if defined(__GNUC__) && MI_ARCH_X64 && defined(__LZCNT__) // on x64 lzcnt is defined for 0 + size_t r; + __asm ("lzcnt\t%1, %0" : "=r"(r) : "r"(x) : "cc"); + return r; + #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; + return (mi_msc_builtinz(_BitScanReverse)(&idx, x) ? MI_SIZE_BITS - 1 - (size_t)idx : MI_SIZE_BITS); + #elif mi_has_builtinz(clz) + return (x!=0 ? (size_t)mi_builtinz(clz)(x) : MI_SIZE_BITS); + #elif defined(__GNUC__) && (MI_ARCH_X64 || MI_ARCH_X86) + if (x==0) return MI_SIZE_BITS; + size_t r; + __asm ("bsr\t%1, %0" : "=r"(r) : "r"(x) : "cc"); + return (MI_SIZE_BITS - 1 - r); + #else + #define MI_HAS_FAST_BITSCAN 0 + return (x!=0 ? _mi_clz_generic(x) : MI_SIZE_BITS); + #endif +} + +#ifndef MI_HAS_FAST_BITSCAN +#define MI_HAS_FAST_BITSCAN 1 +#endif + +/* -------------------------------------------------------------------------------- + find trailing/leading zero (bit scan forward/reverse) +-------------------------------------------------------------------------------- */ + +// Bit scan forward: find the least significant bit that is set (i.e. count trailing zero's) +// 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_bsf(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 ( "tzcnt\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) + unsigned long i; + return (mi_msc_builtinz(_BitScanForward)(&i, x) ? (*idx = (size_t)i, true) : false); + #else + return (x!=0 ? (*idx = mi_ctz(x), true) : false); + #endif +} + +// Bit scan reverse: find the most significant bit that is set +// 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 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); + #else + return (x!=0 ? (*idx = MI_SIZE_BITS - 1 - mi_clz(x), true) : false); + #endif +} + + +/* -------------------------------------------------------------------------------- + rotate +-------------------------------------------------------------------------------- */ + +static inline size_t mi_rotr(size_t x, size_t r) { + #if (mi_has_builtin(rotateright64) && MI_SIZE_BITS==64) + return mi_builtin(rotateright64)(x,r); + #elif (mi_has_builtin(rotateright32) && MI_SIZE_BITS==32) + return mi_builtin(rotateright32)(x,r); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_ARM64) + return _rotr64(x, (int)r); + #elif defined(_MSC_VER) && (MI_ARCH_X86 || MI_ARCH_ARM32) + return _lrotr(x,(int)r); + #else + // The term `(-rshift)&(BITS-1)` is written instead of `BITS - rshift` to + // avoid UB when `rshift==0`. See + const unsigned int rshift = (unsigned int)(r) & (MI_SIZE_BITS-1); + return ((x >> rshift) | (x << ((-rshift) & (MI_SIZE_BITS-1)))); + #endif +} + +static inline size_t mi_rotl(size_t x, size_t r) { + #if (mi_has_builtin(rotateleft64) && MI_SIZE_BITS==64) + return mi_builtin(rotateleft64)(x,r); + #elif (mi_has_builtin(rotateleft32) && MI_SIZE_BITS==32) + return mi_builtin(rotateleft32)(x,r); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_ARM64) + return _rotl64(x, (int)r); + #elif defined(_MSC_VER) && (MI_ARCH_X86 || MI_ARCH_ARM32) + return _lrotl(x, (int)r); + #else + // The term `(-rshift)&(BITS-1)` is written instead of `BITS - rshift` to + // avoid UB when `rshift==0`. See + const unsigned int rshift = (unsigned int)(r) & (MI_SIZE_BITS-1); + return ((x << rshift) | (x >> ((-rshift) & (MI_SIZE_BITS-1)))); + #endif +} + +static inline uint32_t mi_rotl32(uint32_t x, uint32_t r) { + #if mi_has_builtin(rotateleft32) + return mi_builtin(rotateleft32)(x,r); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32) + return _lrotl(x, (int)r); + #else + // The term `(-rshift)&(BITS-1)` is written instead of `BITS - rshift` to + // avoid UB when `rshift==0`. See + const unsigned int rshift = (unsigned int)(r) & 31; + return ((x << rshift) | (x >> ((-rshift) & 31))); + #endif +} + +/* -------------------------------------------------------------------------------- + multiply-xor: the xor of the low and high 64 bits of the full 128-bit product +-------------------------------------------------------------------------------- */ + +static inline uint64_t mi_mul_xor64(uint64_t x, uint64_t y) { + #if defined(__SIZEOF_INT128__) + const unsigned __int128 r = (unsigned __int128)x * y; + return ((uint64_t)r ^ (uint64_t)(r >> 64)); + #elif defined(_MSC_VER) && MI_ARCH_X64 + uint64_t hi; + const uint64_t lo = _umul128(x, y, &hi); + return (lo ^ hi); + #elif defined(_MSC_VER) && MI_ARCH_ARM64 + return ((x*y) ^ __umulh(x, y)); + #else + const uint64_t x0 = (uint32_t)x, x1 = (x >> 32); + const uint64_t y0 = (uint32_t)y, y1 = (y >> 32); + const uint64_t p00 = x0*y0, p01 = x0*y1, p10 = x1*y0, p11 = x1*y1; + const uint64_t mid = (p00 >> 32) + (uint32_t)p01 + (uint32_t)p10; // cannot overflow + const uint64_t lo = (mid << 32) | (uint32_t)p00; + const uint64_t hi = p11 + (p01 >> 32) + (p10 >> 32) + (mid >> 32); + return (lo ^ hi); + #endif +} + +// The high 64 bits of the 96-bit product `x*y` (with `x < 2^32`). +static inline uint64_t mi_mul_hi64_32(uint32_t x, uint64_t y) { + #if defined(__SIZEOF_INT128__) + return (uint64_t)(((unsigned __int128)x * y) >> 64); + #elif defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_ARM64) + return __umulh(x, y); + #else + // `x*(y>>32) <= (2^32-1)^2` so adding a 32-bit value cannot overflow + return ((uint64_t)x * (y >> 32) + (((uint64_t)x * (uint32_t)y) >> 32)) >> 32; + #endif +} + +#endif // MI_ARCH_H diff --git a/Include/internal/mimalloc/mimalloc/arena/arena-alloc.h b/Include/internal/mimalloc/mimalloc/arena/arena-alloc.h new file mode 100644 index 00000000000000..333c2cd4f5bf23 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/arena/arena-alloc.h @@ -0,0 +1,18 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ARENA_ARENA_ALLOC_H +#define MI_ARENA_ARENA_ALLOC_H + +#include "../types.h" + +void* _mi_arenas_alloc(mi_heap_t* heap, size_t size, bool commit, bool allow_pinned, mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid); +void* _mi_arenas_alloc_aligned(mi_heap_t* heap, size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_pinned, mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid); +void _mi_arenas_free(mi_subproc_t* subproc, void* p, size_t size, mi_memid_t memid); +void _mi_arenas_collect(bool force_purge, bool visit_all, mi_tld_t* tld); + +#endif diff --git a/Include/internal/mimalloc/mimalloc/arena/arena-page.h b/Include/internal/mimalloc/mimalloc/arena/arena-page.h new file mode 100644 index 00000000000000..9d9533bdd983fb --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/arena/arena-page.h @@ -0,0 +1,30 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ARENA_ARENA_PAGE_H +#define MI_ARENA_ARENA_PAGE_H + +#include "../types.h" + +mi_page_t* _mi_arenas_page_alloc(mi_theap_t* theap, size_t block_size, size_t page_alignment); +void _mi_arenas_page_free_direct(mi_page_t* page, mi_theap_t* current_theapx /* can be NULL */); +bool _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx /* can be NULL */); +void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap); +void _mi_arenas_page_unabandon(mi_page_t* page, mi_theap_t* current_theapx /* can be NULL */); +bool _mi_arenas_page_try_reabandon_to_mapped(mi_page_t* page); +void _mi_heap_move_pages(mi_heap_t* heap_from, mi_heap_t* heap_to); +void _mi_heap_destroy_pages(mi_heap_t* heap_from); + +// The caller must stop all allocation, freeing, and theap lifecycle operations on this heap. +void _mi_heap_collect_abandoned(mi_heap_t* heap); +void _mi_heap_qsbr_collect_delayed(mi_heap_t* heap); +#if MI_QSBR +void _mi_heap_qsbr_delayed_enqueue(mi_page_t* page); +#endif + + +#endif diff --git a/Include/internal/mimalloc/mimalloc/arena/arena.h b/Include/internal/mimalloc/mimalloc/arena/arena.h new file mode 100644 index 00000000000000..e0ca3b8c77408b --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/arena/arena.h @@ -0,0 +1,41 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026, Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_ARENA_ARENA_H +#define MI_ARENA_ARENA_H + +#include "../types.h" +#include "../prim/prim-pac.h" + +mi_arena_id_t _mi_arena_id_none(void); +mi_arena_t* _mi_arena_from_id(mi_arena_id_t id); +bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_t* request_arena); +void _mi_arenas_unsafe_destroy_all(mi_subproc_t* subproc); +mi_heap_t* _mi_arena_heap_main(const mi_arena_t* arena); +size_t _mi_slice_count_of_size(size_t size); +size_t _mi_size_of_slices(size_t bcount); + +// The arena of an arena memid (signed with the slice index as the salt since a memid is copied by value) +static inline mi_addr_t mi_memid_arena_salt(const mi_memid_arena_info_t* info) { + return mi_salt_of(info->slice_index); +} + +static inline mi_arena_t* mi_memid_arena(mi_memid_t memid) { + return (memid.memkind == MI_MEM_ARENA ? (mi_arena_t*)mi_ptr_auth(memid.mem.arena.arena, mi_memid_arena_salt(&memid.mem.arena)) : NULL); +} + +// Start of the arena memory area +static inline uint8_t* mi_arena_start(mi_arena_t* arena) { + return (uint8_t*)arena->start; +} + +// The parent of a sub-arena (or NULL) +static inline mi_arena_t* mi_arena_parent(mi_arena_t* arena) { + return arena->parent; +} + +#endif diff --git a/Include/internal/mimalloc/mimalloc/atomic.h b/Include/internal/mimalloc/mimalloc/atomic.h index 3d668fdca108c8..3c765beabfad72 100644 --- a/Include/internal/mimalloc/mimalloc/atomic.h +++ b/Include/internal/mimalloc/mimalloc/atomic.h @@ -1,15 +1,15 @@ /* ---------------------------------------------------------------------------- -Copyright (c) 2018-2024 Microsoft Research, Daan Leijen +Copyright (c) 2018-2026 Microsoft Research, Daan Leijen This is free software; you can redistribute it and/or modify it under the terms of the MIT license. A copy of the license can be found in the file "LICENSE" at the root of this distribution. -----------------------------------------------------------------------------*/ #pragma once -#ifndef MIMALLOC_ATOMIC_H -#define MIMALLOC_ATOMIC_H +#ifndef MI_ATOMIC_H +#define MI_ATOMIC_H // include windows.h or pthreads.h -#if defined(_WIN32) +#if defined(_WIN32) || defined(__CYGWIN__) // we use windows locks on cygwin, but otherwise treat it as unix #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -17,9 +17,7 @@ terms of the MIT license. A copy of the license can be found in the file #endif #if !defined(MI_USE_PTHREADS) #if !defined(_WIN32) && !defined(__wasi__) && (!defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)) -#define MI_USE_PTHREADS 1 -#else -#define MI_USE_PTHREADS 0 +#define MI_USE_PTHREADS 1 #endif #endif #if MI_USE_PTHREADS @@ -48,7 +46,7 @@ terms of the MIT license. A copy of the license can be found in the file #else #define MI_ATOMIC_VAR_INIT(x) ATOMIC_VAR_INIT(x) #endif -#elif defined(_MSC_VER) +#elif defined(_MSC_VER) && !defined(__clang__) // Use MSVC C wrapper for C11 atomics #define _Atomic(tp) tp #define MI_ATOMIC_VAR_INIT(x) x @@ -77,34 +75,46 @@ terms of the MIT license. A copy of the license can be found in the file #define mi_atomic_load_acquire(p) mi_atomic(load_explicit)(p,mi_memory_order(acquire)) #define mi_atomic_load_relaxed(p) mi_atomic(load_explicit)(p,mi_memory_order(relaxed)) +#define mi_atomic_load_seq_cst(p) mi_atomic(load_explicit)(p,mi_memory_order(seq_cst)) #define mi_atomic_store_release(p,x) mi_atomic(store_explicit)(p,x,mi_memory_order(release)) #define mi_atomic_store_relaxed(p,x) mi_atomic(store_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_exchange_relaxed(p,x) mi_atomic(exchange_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_exchange_release(p,x) mi_atomic(exchange_explicit)(p,x,mi_memory_order(release)) #define mi_atomic_exchange_acq_rel(p,x) mi_atomic(exchange_explicit)(p,x,mi_memory_order(acq_rel)) + +#define mi_atomic_cas_weak_relaxed(p,exp,des) mi_atomic_cas_weak(p,exp,des,mi_memory_order(relaxed),mi_memory_order(relaxed)) #define mi_atomic_cas_weak_release(p,exp,des) mi_atomic_cas_weak(p,exp,des,mi_memory_order(release),mi_memory_order(relaxed)) #define mi_atomic_cas_weak_acq_rel(p,exp,des) mi_atomic_cas_weak(p,exp,des,mi_memory_order(acq_rel),mi_memory_order(acquire)) +#define mi_atomic_cas_strong_relaxed(p,exp,des) mi_atomic_cas_strong(p,exp,des,mi_memory_order(relaxed),mi_memory_order(relaxed)) +#define mi_atomic_cas_strong_acquire(p,exp,des) mi_atomic_cas_strong(p,exp,des,mi_memory_order(acquire),mi_memory_order(relaxed)) #define mi_atomic_cas_strong_release(p,exp,des) mi_atomic_cas_strong(p,exp,des,mi_memory_order(release),mi_memory_order(relaxed)) #define mi_atomic_cas_strong_acq_rel(p,exp,des) mi_atomic_cas_strong(p,exp,des,mi_memory_order(acq_rel),mi_memory_order(acquire)) #define mi_atomic_add_relaxed(p,x) mi_atomic(fetch_add_explicit)(p,x,mi_memory_order(relaxed)) -#define mi_atomic_sub_relaxed(p,x) mi_atomic(fetch_sub_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_add_acq_rel(p,x) mi_atomic(fetch_add_explicit)(p,x,mi_memory_order(acq_rel)) +#define mi_atomic_sub_relaxed(p,x) mi_atomic(fetch_sub_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_sub_acq_rel(p,x) mi_atomic(fetch_sub_explicit)(p,x,mi_memory_order(acq_rel)) +#define mi_atomic_and_relaxed(p,x) mi_atomic(fetch_and_explicit)(p,x,mi_memory_order(relaxed)) +#define mi_atomic_and_acquire(p,x) mi_atomic(fetch_and_explicit)(p,x,mi_memory_order(acquire)) +#define mi_atomic_and_release(p,x) mi_atomic(fetch_and_explicit)(p,x,mi_memory_order(release)) #define mi_atomic_and_acq_rel(p,x) mi_atomic(fetch_and_explicit)(p,x,mi_memory_order(acq_rel)) +#define mi_atomic_or_relaxed(p,x) mi_atomic(fetch_or_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_or_acq_rel(p,x) mi_atomic(fetch_or_explicit)(p,x,mi_memory_order(acq_rel)) -#define mi_atomic_increment_relaxed(p) mi_atomic_add_relaxed(p,(uintptr_t)1) -#define mi_atomic_decrement_relaxed(p) mi_atomic_sub_relaxed(p,(uintptr_t)1) -#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) +#define mi_atomic_increment_relaxed(p) mi_atomic_add_relaxed(p,(size_t)1) +#define mi_atomic_decrement_relaxed(p) mi_atomic_sub_relaxed(p,(size_t)1) +#define mi_atomic_increment_acq_rel(p) mi_atomic_add_acq_rel(p,(size_t)1) +#define mi_atomic_decrement_acq_rel(p) mi_atomic_sub_acq_rel(p,(size_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); +static inline mi_ssize_t mi_atomic_addi_acq_rel(_Atomic(mi_ssize_t)*p, mi_ssize_t add); +static inline mi_ssize_t mi_atomic_subi_acq_rel(_Atomic(mi_ssize_t)*p, mi_ssize_t sub); +static inline mi_ssize_t mi_atomic_addi_relaxed(_Atomic(mi_ssize_t)*p, mi_ssize_t add); +static inline mi_ssize_t mi_atomic_subi_relaxed(_Atomic(mi_ssize_t)*p, mi_ssize_t sub); +static inline void mi_atomic_storess_relaxed(_Atomic(mi_ssize_t)* p, mi_ssize_t x); +static inline mi_ssize_t mi_atomic_loads_relaxed(_Atomic(mi_ssize_t)* p); -#if defined(__cplusplus) || !defined(_MSC_VER) +#if defined(__cplusplus) || !defined(_MSC_VER) || defined(__clang__) // In C++/C11 atomics we have polymorphic atomics so can use the typed `ptr` variants (where `tp` is the type of atomic value) // We use these macros so we can provide a typed wrapper in MSVC in C compilation mode as well @@ -135,18 +145,15 @@ static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub); #endif // These are used by the statistics -static inline int64_t mi_atomic_addi64_relaxed(volatile int64_t* p, int64_t add) { +static inline int64_t mi_atomic_volatile_addi64_relaxed(volatile int64_t* p, int64_t add) { return mi_atomic(fetch_add_explicit)((_Atomic(int64_t)*)p, add, mi_memory_order(relaxed)); } -static inline void mi_atomic_void_addi64_relaxed(volatile int64_t* p, const volatile int64_t* padd) { - const int64_t add = mi_atomic_load_relaxed((_Atomic(int64_t)*)padd); - if (add != 0) { - mi_atomic(fetch_add_explicit)((_Atomic(int64_t)*)p, add, mi_memory_order(relaxed)); - } +static inline int64_t mi_atomic_volatile_exchangei64_relaxed(volatile int64_t* p, int64_t x) { + return mi_atomic(exchange_explicit)((_Atomic(int64_t)*)p, x, mi_memory_order(relaxed)); } -static inline void mi_atomic_maxi64_relaxed(volatile int64_t* p, int64_t x) { +static inline void mi_atomic_volatile_maxi64_relaxed(volatile int64_t* p, int64_t x) { int64_t current = mi_atomic_load_relaxed((_Atomic(int64_t)*)p); - while (current < x && !mi_atomic_cas_weak_release((_Atomic(int64_t)*)p, ¤t, x)) { /* nothing */ }; + while (current < x && !mi_atomic_cas_weak_relaxed((_Atomic(int64_t)*)p, ¤t, x)) { /* nothing */ }; } // Used by timers @@ -156,10 +163,13 @@ static inline void mi_atomic_maxi64_relaxed(volatile int64_t* p, int64_t x) { #define mi_atomic_storei64_relaxed(p,x) mi_atomic(store_explicit)(p,x,mi_memory_order(relaxed)) #define mi_atomic_casi64_strong_acq_rel(p,e,d) mi_atomic_cas_strong_acq_rel(p,e,d) +#define mi_atomic_casi64_strong_relaxed(p,e,d) mi_atomic_cas_strong_relaxed(p,e,d) +#define mi_atomic_casi64_strong_release(p,e,d) mi_atomic_cas_strong_release(p,e,d) #define mi_atomic_addi64_acq_rel(p,i) mi_atomic_add_acq_rel(p,i) +#define mi_atomic_addi64_relaxed(p,i) mi_atomic_add_relaxed(p,i) -#elif defined(_MSC_VER) +#elif defined(_MSC_VER) && !defined(__clang__) // 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. @@ -223,6 +233,7 @@ static inline uintptr_t mi_atomic_load_explicit(_Atomic(uintptr_t) const* p, mi_ (void)(mo); // assert(mo<=mi_memory_order_acquire); // others are not used by mimalloc #if defined(_M_IX86) || defined(_M_X64) + // on x86/x64 we have a strong memory model so any load is acquire 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) { @@ -313,9 +324,9 @@ static inline void mi_atomic_storei64_explicit(_Atomic(int64_t)*p, int64_t x, mi } // These are used by the statistics -static inline int64_t mi_atomic_addi64_relaxed(volatile _Atomic(int64_t)*p, int64_t add) { +static inline int64_t mi_atomic_volatile_addi64_relaxed(volatile _Atomic(int64_t)*p, int64_t add) { #ifdef _WIN64 - return (int64_t)mi_atomic_addi((int64_t*)p, add); + return (int64_t)mi_atomic_addi_relaxed((_Atomic(int64_t)*)p, add); #elif defined(_M_ARM) return _InterlockedExchangeAdd64(p, add); #else @@ -329,14 +340,21 @@ static inline int64_t mi_atomic_addi64_relaxed(volatile _Atomic(int64_t)*p, int6 return current; #endif } -static inline void mi_atomic_void_addi64_relaxed(volatile int64_t* p, const volatile int64_t* padd) { - const int64_t add = *padd; - if (add != 0) { - mi_atomic_addi64_relaxed((volatile _Atomic(int64_t)*)p, add); - } + +static inline int64_t mi_atomic_volatile_exchangei64_relaxed(volatile int64_t* p, int64_t x) { + #if defined(_WIN64) || defined(_M_ARM) + return _InterlockedExchange64(p, x); + #else + // x86 + int64_t current; + do { + current = __iso_volatile_load64((volatile const int64_t*)p); + } while (_InterlockedCompareExchange64(p, x, current) != current); + return current; + #endif } -static inline void mi_atomic_maxi64_relaxed(volatile _Atomic(int64_t)* p, int64_t x) { +static inline void mi_atomic_volatile_maxi64_relaxed(volatile _Atomic(int64_t)* p, int64_t x) { int64_t current; do { current = *p; @@ -344,7 +362,11 @@ static inline void mi_atomic_maxi64_relaxed(volatile _Atomic(int64_t)* p, int64_ } static inline void mi_atomic_addi64_acq_rel(volatile _Atomic(int64_t)* p, int64_t i) { - mi_atomic_addi64_relaxed(p, i); + mi_atomic_volatile_addi64_relaxed(p, i); +} + +static inline int64_t mi_atomic_addi64_relaxed(volatile _Atomic(int64_t)* p, int64_t i) { + return mi_atomic_volatile_addi64_relaxed(p, i); } static inline bool mi_atomic_casi64_strong_acq_rel(volatile _Atomic(int64_t)* p, int64_t* exp, int64_t des) { @@ -358,18 +380,21 @@ static inline bool mi_atomic_casi64_strong_acq_rel(volatile _Atomic(int64_t)* p, } } +#define mi_atomic_casi64_strong_relaxed(p,e,d) mi_atomic_casi64_strong_acq_rel(p,e,d) +#define mi_atomic_casi64_strong_release(p,e,d) mi_atomic_casi64_strong_acq_rel(p,e,d) + // The pointer macros cast to `uintptr_t`. -#define mi_atomic_load_ptr_acquire(tp,p) (tp*)mi_atomic_load_acquire((_Atomic(uintptr_t)*)(p)) -#define mi_atomic_load_ptr_relaxed(tp,p) (tp*)mi_atomic_load_relaxed((_Atomic(uintptr_t)*)(p)) +#define mi_atomic_load_ptr_acquire(tp,p) ((tp*)mi_atomic_load_acquire((_Atomic(uintptr_t)*)(p))) +#define mi_atomic_load_ptr_relaxed(tp,p) ((tp*)mi_atomic_load_relaxed((_Atomic(uintptr_t)*)(p))) #define mi_atomic_store_ptr_release(tp,p,x) mi_atomic_store_release((_Atomic(uintptr_t)*)(p),(uintptr_t)(x)) #define mi_atomic_store_ptr_relaxed(tp,p,x) mi_atomic_store_relaxed((_Atomic(uintptr_t)*)(p),(uintptr_t)(x)) #define mi_atomic_cas_ptr_weak_release(tp,p,exp,des) mi_atomic_cas_weak_release((_Atomic(uintptr_t)*)(p),(uintptr_t*)exp,(uintptr_t)des) #define mi_atomic_cas_ptr_weak_acq_rel(tp,p,exp,des) mi_atomic_cas_weak_acq_rel((_Atomic(uintptr_t)*)(p),(uintptr_t*)exp,(uintptr_t)des) #define mi_atomic_cas_ptr_strong_release(tp,p,exp,des) mi_atomic_cas_strong_release((_Atomic(uintptr_t)*)(p),(uintptr_t*)exp,(uintptr_t)des) #define mi_atomic_cas_ptr_strong_acq_rel(tp,p,exp,des) mi_atomic_cas_strong_acq_rel((_Atomic(uintptr_t)*)(p),(uintptr_t*)exp,(uintptr_t)des) -#define mi_atomic_exchange_ptr_relaxed(tp,p,x) (tp*)mi_atomic_exchange_relaxed((_Atomic(uintptr_t)*)(p),(uintptr_t)x) -#define mi_atomic_exchange_ptr_release(tp,p,x) (tp*)mi_atomic_exchange_release((_Atomic(uintptr_t)*)(p),(uintptr_t)x) -#define mi_atomic_exchange_ptr_acq_rel(tp,p,x) (tp*)mi_atomic_exchange_acq_rel((_Atomic(uintptr_t)*)(p),(uintptr_t)x) +#define mi_atomic_exchange_ptr_relaxed(tp,p,x) ((tp*)mi_atomic_exchange_relaxed((_Atomic(uintptr_t)*)(p),(uintptr_t)x)) +#define mi_atomic_exchange_ptr_release(tp,p,x) ((tp*)mi_atomic_exchange_release((_Atomic(uintptr_t)*)(p),(uintptr_t)x)) +#define mi_atomic_exchange_ptr_acq_rel(tp,p,x) ((tp*)mi_atomic_exchange_acq_rel((_Atomic(uintptr_t)*)(p),(uintptr_t)x)) #define mi_atomic_loadi64_acquire(p) mi_atomic(loadi64_explicit)(p,mi_memory_order(acquire)) #define mi_atomic_loadi64_relaxed(p) mi_atomic(loadi64_explicit)(p,mi_memory_order(relaxed)) @@ -379,140 +404,57 @@ static inline bool mi_atomic_casi64_strong_acq_rel(volatile _Atomic(int64_t)* p, #endif - -// Atomically add a signed value; returns the previous value. -static inline intptr_t mi_atomic_addi(_Atomic(intptr_t)*p, intptr_t add) { - return (intptr_t)mi_atomic_add_acq_rel((_Atomic(uintptr_t)*)p, (uintptr_t)add); +// Atomic minimum where 0 means "not set" (and `x > 0`); returns the previous value. +// This always writes (even if the value is unchanged) so it is a read-modify-write that +// is ordered with other read-modify-writes on `p` (unlike a failed CAS which is just a read). +static inline int64_t mi_atomic_mini64_nonzero_acq_rel(_Atomic(int64_t)* p, int64_t x) { + int64_t current = mi_atomic_loadi64_relaxed(p); + int64_t desired; + do { + desired = (current == 0 || x < current ? x : current); + } while (!mi_atomic_casi64_strong_acq_rel(p, ¤t, desired)); + return current; } -// Atomically subtract a signed value; returns the previous value. -static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub) { - return (intptr_t)mi_atomic_addi(p, -sub); +static inline int64_t mi_atomic_exchangei64_acq_rel(_Atomic(int64_t)* p, int64_t x) { + int64_t current = mi_atomic_loadi64_relaxed(p); + while (!mi_atomic_casi64_strong_acq_rel(p, ¤t, x)) { /* nothing */ }; + return current; } +static inline mi_ssize_t mi_atomic_addi_acq_rel(_Atomic(mi_ssize_t)*p, mi_ssize_t add) { + return (mi_ssize_t)mi_atomic_add_acq_rel((_Atomic(size_t)*)p, (size_t)add); +} +static inline mi_ssize_t mi_atomic_subi_acq_rel(_Atomic(mi_ssize_t)*p, mi_ssize_t sub) { + return (mi_ssize_t)mi_atomic_addi_acq_rel(p, -sub); +} +static inline mi_ssize_t mi_atomic_addi_relaxed(_Atomic(mi_ssize_t)*p, mi_ssize_t add) { + return (mi_ssize_t)mi_atomic_add_relaxed((_Atomic(size_t)*)p, (size_t)add); +} +static inline mi_ssize_t mi_atomic_subi_relaxed(_Atomic(mi_ssize_t)*p, mi_ssize_t sub) { + return (mi_ssize_t)mi_atomic_addi_relaxed(p, -sub); +} +static inline void mi_atomic_storess_relaxed(_Atomic(mi_ssize_t)* p, mi_ssize_t x) { + mi_atomic_store_relaxed((_Atomic(size_t)*)p, (size_t)x); +} +static inline mi_ssize_t mi_atomic_loads_relaxed(_Atomic(mi_ssize_t)* p) { + return (mi_ssize_t)mi_atomic_load_relaxed((_Atomic(size_t)*)p); +} // ---------------------------------------------------------------------- -// Once and Guard +// Guard // ---------------------------------------------------------------------- -typedef _Atomic(uintptr_t) mi_atomic_guard_t; +typedef _Atomic(size_t) mi_atomic_guard_t; // Allows only one thread to execute at a time (without blocking anyone) #define mi_atomic_guard(guard) \ - uintptr_t _mi_guard_expected = 0; \ + size_t _mi_guard_expected = 0; \ for(bool _mi_guard_once = true; \ - _mi_guard_once && mi_atomic_cas_strong_acq_rel(guard,&_mi_guard_expected,(uintptr_t)1); \ - (mi_atomic_store_release(guard,(uintptr_t)0), _mi_guard_once = false) ) - + _mi_guard_once && mi_atomic_cas_strong_acquire(guard,&_mi_guard_expected,(size_t)1); \ + (mi_atomic_store_release(guard,(size_t)0), _mi_guard_once = false) ) -// ---------------------------------------------------------------------- -// Yield -// ---------------------------------------------------------------------- - -#if defined(_WIN32) -static inline void mi_atomic_yield(void) { - YieldProcessor(); // see issue #1215 and #1225 why this is preferred over __yield or SwitchToThread -} -#elif defined(__SSE2__) -#include -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__) || \ - defined(__riscv)) -#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("isb"); -} -#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 -#elif defined(__riscv) -#if defined(__riscv_zihintpause) -static inline void mi_atomic_yield(void) { - __asm__ volatile("pause" ::: "memory"); -} -#else -static inline void mi_atomic_yield(void) { - __asm__ volatile("nop" ::: "memory"); -} -#endif -#endif -#elif defined(__sun) -#include -static inline void mi_atomic_yield(void) { - smt_pause(); -} -#elif defined(__wasi__) -#include -static inline void mi_atomic_yield(void) { - sched_yield(); -} -// Fallback for other archs -#elif defined(__cplusplus) -#include -static inline void mi_atomic_yield(void) { - std::this_thread::yield(); -} -#else -#include -static inline void mi_atomic_yield(void) { - sleep(0); -} -#endif - -#if defined(_WIN32) -static inline void mi_sleep0(void) { - Sleep(0); -} -#else -#include -static inline void mi_sleep0(void) { - sleep(0); -} -#endif - -static inline void mi_atomic_yield_sleep( size_t* ticks, const size_t ticks_until_sleep ) { - const size_t n = *ticks; - if (n==0 || n > ticks_until_sleep) { - *ticks = ticks_until_sleep; // reset - } - else { - *ticks = n-1; - } - if (n>1) { - mi_atomic_yield(); - } - else { - mi_sleep0(); - } -} - // ---------------------------------------------------------------------- // Locks // These should be light-weight in-process only locks. @@ -522,31 +464,35 @@ static inline void mi_atomic_yield_sleep( size_t* ticks, const size_t ticks_unti #pragma warning(disable:26110) // unlock with holding lock #endif -#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) ) +// use a unique loop variable per line to avoid shadowing warnings for nested locks +#define mi_concat_(a,b) a##b +#define mi_concat(a,b) mi_concat_(a,b) +#define mi_unique(name) mi_concat(name,__LINE__) +#define mi_lock(lock) for(bool mi_unique(_mi_go) = (mi_lock_acquire(lock),true); mi_unique(_mi_go); (mi_lock_release(lock), mi_unique(_mi_go)=false) ) +#define mi_lock_maybe(lock,acquire) for(bool mi_unique(_mi_go) = ((acquire) ? (mi_lock_acquire(lock),true) : true); mi_unique(_mi_go); mi_unique(_mi_go) = ((acquire) ? (mi_lock_release(lock),false) : false) ) -#if defined(_WIN32) +#if defined(_WIN32) || defined(__CYGWIN__) -typedef struct mi_lock_s { +typedef struct mi_mutex_s { SRWLOCK mutex; // slim reader-writer lock -} mi_lock_t; +} mi_mutex_t; -#define MI_LOCK_INITIALIZER { SRWLOCK_INIT } +#define MI_MUTEX_INITIALIZER { SRWLOCK_INIT } -static inline bool mi_lock_try_acquire(mi_lock_t* lock) { +static inline bool mi_mutex_try_acquire(mi_mutex_t* lock) { return TryAcquireSRWLockExclusive(&lock->mutex); } -static inline void mi_lock_acquire(mi_lock_t* lock) { +static inline void mi_mutex_acquire(mi_mutex_t* lock) { AcquireSRWLockExclusive(&lock->mutex); } -static inline void mi_lock_release(mi_lock_t* lock) { +static inline void mi_mutex_release(mi_mutex_t* lock) { ReleaseSRWLockExclusive(&lock->mutex); } -static inline void mi_lock_init(mi_lock_t* lock) { +static inline void mi_mutex_init(mi_mutex_t* lock) { InitializeSRWLock(&lock->mutex); } -static inline void mi_lock_done(mi_lock_t* lock) { +static inline void mi_mutex_done(mi_mutex_t* lock) { (void)(lock); } @@ -555,31 +501,31 @@ static inline void mi_lock_done(mi_lock_t* lock) { #include // memcpy void _mi_error_message(int err, const char* fmt, ...); -typedef struct mi_lock_s { +typedef struct mi_mutex_s { pthread_mutex_t mutex; -} mi_lock_t; +} mi_mutex_t; -#define MI_LOCK_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } +#define MI_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } -static inline bool mi_lock_try_acquire(mi_lock_t* lock) { +static inline bool mi_mutex_try_acquire(mi_mutex_t* lock) { return (pthread_mutex_trylock(&lock->mutex) == 0); } -static inline void mi_lock_acquire(mi_lock_t* lock) { +static inline void mi_mutex_acquire(mi_mutex_t* 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) { +static inline void mi_mutex_release(mi_mutex_t* lock) { pthread_mutex_unlock(&lock->mutex); } -static inline void mi_lock_init(mi_lock_t* lock) { +static inline void mi_mutex_init(mi_mutex_t* lock) { if(lock==NULL) return; // 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) { +static inline void mi_mutex_done(mi_mutex_t* lock) { pthread_mutex_destroy(&lock->mutex); } @@ -589,26 +535,26 @@ static inline void mi_lock_done(mi_lock_t* lock) { #include #include -typedef struct mi_lock_s { +typedef struct mi_mutex_s { std::mutex mutex; -} mi_lock_t; +} mi_mutex_t; -#define MI_LOCK_INITIALIZER { } +#define MI_MUTEX_INITIALIZER { } -static inline bool mi_lock_try_acquire(mi_lock_t* lock) { +static inline bool mi_mutex_try_acquire(mi_mutex_t* lock) { return lock->mutex.try_lock(); } -static inline void mi_lock_acquire(mi_lock_t* lock) { +static inline void mi_mutex_acquire(mi_mutex_t* lock) { lock->mutex.lock(); } -static inline void mi_lock_release(mi_lock_t* lock) { +static inline void mi_mutex_release(mi_mutex_t* lock) { lock->mutex.unlock(); } -static inline void mi_lock_init(mi_lock_t* lock) { - new(&lock->mutex) std::mutex(); +static inline void mi_mutex_init(mi_mutex_t* lock) { + new(&lock->mutex) std::mutex(); // in-place constructor } -static inline void mi_lock_done(mi_lock_t* lock) { - (void)(lock); +static inline void mi_mutex_done(mi_mutex_t* lock) { + lock->mutex.~mutex(); // in-place destructor } #else @@ -620,52 +566,156 @@ static inline void mi_lock_done(mi_lock_t* lock) { #define EFAULT (14) #endif void _mi_error_message(int err, const char* fmt, ...); +void _mi_prim_thread_yield(void); + +typedef struct mi_mutex_s { + _Atomic(size_t) mutex; +} mi_mutex_t; + +#define MI_MUTEX_INITIALIZER { MI_ATOMIC_VAR_INIT(0) } + +static inline bool mi_mutex_try_acquire(mi_mutex_t* lock) { + size_t expected = 0; + return mi_atomic_cas_strong_acquire(&lock->mutex, &expected, (size_t)1); +} +static inline void mi_mutex_acquire(mi_mutex_t* lock) { + for (int i = 0; i < 10000; i++) { // for at most 10000 tries? + if (mi_mutex_try_acquire(lock)) return; + _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_mutex_release(mi_mutex_t* lock) { + mi_atomic_store_release(&lock->mutex, (size_t)0); +} +static inline void mi_mutex_init(mi_mutex_t* lock) { + mi_mutex_release(lock); +} +static inline void mi_mutex_done(mi_mutex_t* lock) { + (void)(lock); +} + +#endif + + + +// Locks are re-entrant for the owning thread so user callbacks (like an error handler or output +// function) that are invoked while holding a lock can call back into the allocator. +// `mi_lock_try_acquire` is not re-entrant though. +#define MI_MAX_REENTRY (8) // nested lock acquisitions or user callbacks beyond this are a runaway recursion +size_t _mi_thread_id(void) mi_attr_noexcept; +mi_decl_noreturn mi_decl_cold void _mi_reentry_fatal(const char* msg); typedef struct mi_lock_s { - _Atomic(uintptr_t) mutex; + mi_mutex_t mutex; + _Atomic(size_t) owner; // thread id of the owner (or 0) + size_t count; // recursive acquisitions by the owner } mi_lock_t; -#define MI_LOCK_INITIALIZER { MI_ATOMIC_VAR_INIT(0) } +#define MI_LOCK_INITIALIZER { MI_MUTEX_INITIALIZER, MI_ATOMIC_VAR_INIT(0), 0 } + +static inline void mi_lock_set_owner(mi_lock_t* lock, size_t tid) { + mi_atomic_store_relaxed(&lock->owner, tid); + lock->count = 1; +} static inline bool mi_lock_try_acquire(mi_lock_t* lock) { - uintptr_t expected = 0; - return mi_atomic_cas_strong_acq_rel(&lock->mutex, &expected, (uintptr_t)1); + const size_t tid = _mi_thread_id(); + if (mi_atomic_load_relaxed(&lock->owner) == tid) return false; + if (!mi_mutex_try_acquire(&lock->mutex)) return false; + mi_lock_set_owner(lock, tid); + return true; } static inline void mi_lock_acquire(mi_lock_t* lock) { - size_t ticks = 0; - for (int i = 0; i < 10000; i++) { // for at most 10000 tries? - if (mi_lock_try_acquire(lock)) return; - mi_atomic_yield_sleep(&ticks,100); + const size_t tid = _mi_thread_id(); + if (mi_atomic_load_relaxed(&lock->owner) == tid) { + if mi_unlikely(++lock->count > MI_MAX_REENTRY) { _mi_reentry_fatal("too many re-entrant lock acquisitions (recursion through a user callback?)"); } + return; } - _mi_error_message(EFAULT, "internal error: lock cannot be acquired (due to lack of native lock primitives)\n"); + mi_mutex_acquire(&lock->mutex); + mi_lock_set_owner(lock, tid); } static inline void mi_lock_release(mi_lock_t* lock) { - mi_atomic_store_release(&lock->mutex, (uintptr_t)0); + if mi_unlikely(lock->count == 0) { _mi_reentry_fatal("lock released without being acquired"); } + mi_assert_internal(mi_atomic_load_relaxed(&lock->owner) == _mi_thread_id()); + if (--lock->count > 0) return; + mi_atomic_store_relaxed(&lock->owner, (size_t)0); + mi_mutex_release(&lock->mutex); +} +static inline bool mi_lock_is_reentered(const mi_lock_t* lock) { + return (lock->count > 1); +} +static inline bool mi_lock_is_owned(mi_lock_t* lock) { // by the current thread + return (mi_atomic_load_relaxed(&lock->owner) == _mi_thread_id()); } static inline void mi_lock_init(mi_lock_t* lock) { - mi_lock_release(lock); + if (lock==NULL) return; + mi_mutex_init(&lock->mutex); + mi_atomic_store_relaxed(&lock->owner, (size_t)0); + lock->count = 0; } static inline void mi_lock_done(mi_lock_t* lock) { - (void)(lock); + mi_mutex_done(&lock->mutex); } -#endif - - typedef struct mi_atomic_once_s { - _Atomic(uintptr_t) tid; + _Atomic(size_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` +bool _mi_atomic_once_enter(mi_atomic_once_t* once); // defined in `util/libc.c` +void _mi_atomic_once_release(mi_atomic_once_t* once); // defined in `util/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_H + +/* ----------------------------------------------------------- + pthread thread locals +----------------------------------------------------------- */ + +#if MI_USE_PTHREADS + +#if defined(__APPLE__) && defined(__aarch64__) +#define MI_PTHREAD_KEY_INVALID ((pthread_key_t)(0)) // nicer codegen +#else +#define MI_PTHREAD_KEY_INVALID ((pthread_key_t)(-1)) +#endif + +#if defined(__linux__) && defined(__GLIBC__) +// pthread_getspecific returns NULL for invalid keys. +// see also: +#define MI_PTHREADS_GET_INVALID_KEY_IS_NULL 1 +#endif + +mi_decl_noinline bool _mi_pthread_key_create(pthread_key_t* pkey, void (*destruct)(void*), void* init); + +static inline void* mi_pthread_key_get(pthread_key_t key) { + #if !MI_PTHREADS_GET_INVALID_KEY_IS_NULL + if mi_unlikely(key==MI_PTHREAD_KEY_INVALID) return NULL; + #endif + return pthread_getspecific(key); +} + +static inline bool mi_pthread_key_set(pthread_key_t* pkey, void* val) { + if mi_likely(*pkey!=MI_PTHREAD_KEY_INVALID) { pthread_setspecific(*pkey,val); return true; } + else if (val!=NULL) { return _mi_pthread_key_create(pkey,NULL,val); } + else return true; +} + +static inline void mi_pthread_key_delete(pthread_key_t* pkey) { + const pthread_key_t key = *pkey; + if (key!=MI_PTHREAD_KEY_INVALID) { + *pkey = MI_PTHREAD_KEY_INVALID; + pthread_key_delete(key); + } +} +#endif + + +#endif // MI_ATOMIC_H diff --git a/Include/internal/mimalloc/mimalloc/config.h b/Include/internal/mimalloc/mimalloc/config.h new file mode 100644 index 00000000000000..b5dbff86d21551 --- /dev/null +++ b/Include/internal/mimalloc/mimalloc/config.h @@ -0,0 +1,391 @@ +/* ---------------------------------------------------------------------------- +Copyright (c) 2018-2026 Microsoft Research, Daan Leijen +This is free software; you can redistribute it and/or modify it under the +terms of the MIT license. A copy of the license can be found in the file +"LICENSE" at the root of this distribution. +-----------------------------------------------------------------------------*/ +#pragma once +#ifndef MI_CONFIG_H +#define MI_CONFIG_H + +// Minimal alignment necessary. On most platforms 16 bytes are needed +// due to SSE registers for example. This must be at least `sizeof(void*)` +#ifndef MI_MAX_ALIGN_SIZE +#define MI_MAX_ALIGN_SIZE 16 // sizeof(max_align_t) +#endif + +#if MI_MAX_ALIGN_SIZE < MI_INTPTR_SIZE +#error MI_MAX_ALIGN_SIZE must be at least MI_INTPTR_SIZE +#endif + +// ------------------------------------------------------ +// Build Variants +// ------------------------------------------------------ + +// Define NDEBUG in the release version to disable assertions. +// #define NDEBUG + +// Define MI_TRACK_ to enable tracking support +// #define MI_TRACK_VALGRIND 1 +// #define MI_TRACK_ASAN 1 +// #define MI_TRACK_ETW 1 +// #define MI_TRACK_CUSTOM 1 + +// Define MI_STATS as 1 to maintain statistics; set it to 2 to have detailed statistics (but costs some performance). +// #define MI_STATS 1 + +// Define MI_SECURE to enable security mitigations +// #define MI_SECURE 0 // no security mitigations +// #define MI_SECURE 1 // + guard pages around metadata (and separated metadata) and after singleton blocks, randomized arena/OS allocation addresses, + // abort on EFAULT (corrupted meta-data), encode free lists with a fast MAC (64-bit multiply), clear free list `next` on allocation + // (so double frees are detected on allocation, at an immediate double free, or when the page is freed) (`-DMI_SECURE=BASIC`) +// #define MI_SECURE 2 // + invalid-pointer check on free (checked lookup in page-map.h), encode free lists with a stronger MAC (128-bit multiply+xor), + // randomized free list (4-way) initialization and allocation addresses within mimalloc pages (`-DMI_SECURE=CHECKED`) +// #define MI_SECURE 3 // + zero blocks on free (up to the first 1KiB), check double free (slow, and only for thread-local frees; + // only at level 3 as padding is used at level 4) +// #define MI_SECURE 4 // + add padding to each block, check buffer overflow (using the padding), immediate double free check (using the padding), + // more randomized free lists (64-way), decommit with mprotect, reuse of freed blocks is delayed (until 1/8th of a page is free) + // and a random number of the most recently freed blocks is held back (`-DMI_SECURE=ON`) +// #define MI_SECURE 5 // + guard page at the end of each mimalloc page (expensive!), and byte-precise buffer overflow checks (`-DMI_SECURE=FULL`) + +// The default is 2 with MTE or PAC, and 3 on CHERI (where capabilities already provide spatial safety) +#if !defined(MI_SECURE) +#if MI_MTE || MI_PAC +#define MI_SECURE 2 +#elif MI_CHERI +#define MI_SECURE 3 +#else +#define MI_SECURE 0 +#endif +#endif + +// Restrict environment options by default in secure, PAC, and MTE builds. +#if !defined(MI_SECURE_ENV) +#if MI_SECURE >= 1 || MI_PAC || MI_MTE +#define MI_SECURE_ENV 1 +#else +#define MI_SECURE_ENV 0 +#endif +#endif + +// MTE, PAC, or secure level 2 and higher always check for invalid pointers in `mi_free` +#if (MI_MTE || MI_PAC || MI_SECURE>=2) && !MI_FREE_IS_CHECKED +#undef MI_FREE_IS_CHECKED +#define MI_FREE_IS_CHECKED 1 +#endif + +// Statistics (0=only essential, 1=detailed (fast, can be enabled always), 2=slightly more expensive tracking of precise requested bytes) +#ifndef MI_STATS +#if (MI_DEBUG>0) +#define MI_STATS 2 +#else +#define MI_STATS 1 +#endif +#endif + +// Enable profiling support (0=off, 1=fast, can be enabled always, 2=allow fine-grained sample rates(<64 KiB), a tad more expensive) +#ifndef MI_PROFILE +#define MI_PROFILE 1 +#endif + +// 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_OPT_FREE_SMALL +#define MI_GUARDED 1 +#endif + +// For profiling or guarded pages we need to sample every once in a while. (0=no sampling, 1=fast, 2=allow fine grained sample rates(<64 KiB), a tad more expensive) +#ifndef MI_SAMPLE +#if MI_PROFILE>1 || MI_GUARDED>1 + #define MI_SAMPLE 2 +#elif MI_PROFILE || MI_GUARDED + #define MI_SAMPLE 1 +#else + #define MI_SAMPLE 0 +#endif +#endif + +// Reserve extra padding at the end of each block to be more resilient against theap block overflows. +// The padding can detect heap-block overflow on free, and provides byte-precise `mi_usable_size`. +#if !defined(MI_PADDING) +#if (MI_SECURE>=4 || MI_DEBUG>=1 || (MI_TRACK_VALGRIND || MI_TRACK_ASAN || MI_TRACK_ETW)) +#define MI_PADDING 1 +#else +#define MI_PADDING 0 +#endif +#endif + +// Check for byte-precise buffer overflow? +#if !defined(MI_PADDING_CHECK_BYTES) && MI_PADDING && (MI_SECURE>=5 || MI_DEBUG>=1) +#define MI_PADDING_CHECK_BYTES 1 +#endif + + +// Encoded free lists allow detection of corrupted free lists +// and can detect buffer overflows, modify after free, and double `free`s. +// Level 1 uses a faster but weaker keyed MAC on 64-bit (the low product only), while level 2 uses the full `mulxor64` MAC. +#ifndef MI_ENCODE_FREELIST +#if (MI_SECURE>=2 || MI_DEBUG>=1) +#define MI_ENCODE_FREELIST 2 +#elif (MI_SECURE>=1) +#define MI_ENCODE_FREELIST 1 +#endif +#endif + + +// Use large pages for objects between 80KiB and 512KiB ? +// This is disabled by default as for many workloads the block sizes above 80 KiB +// are quite random which can lead to too many partially used large pages (but see issue #1104). +#ifndef MI_ENABLE_LARGE_PAGES +#define MI_ENABLE_LARGE_PAGES 0 +#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. +#if !defined(MI_PAGE_META_IS_SEPARATED) +#define MI_PAGE_META_IS_SEPARATED 1 +#endif + +// We can choose to page meta info aligned at the start of every MI_PAGE_META_ALIGNED_CHUNKS +// This can be used to have a faster `mi_free(_small)` as we can avoid a page_map lookup. +// This only works if valid pointers are passed to `mi_free` though. However, checked +// free `mi_cfree` can still use the page map to validate pointers. +#if !MI_FREE_IS_CHECKED && !MI_FREE_USE_PAGEMAP && !MI_CHERI +#if MI_PAGE_META_IS_SEPARATED +#define MI_PAGE_META_IS_ALIGNED 1 +#define MI_PAGE_META_ALIGNED_CHUNKS MI_SIZE_SIZE +#else +#warning "cannot optimize free with alignment since the page meta data is not separated" +#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_SMALL_IS_ALIGNED) +// guarded can put small allocations into big blocks in a medium page (which would make `mi_free_small` fail) +// on CHERI we cannot derive the page from a (bounded) user pointer +#if (defined(MI_OPT_FREE_SMALL) && MI_OPT_FREE_SMALL==0) || MI_SECURE || MI_GUARDED || MI_CHERI +#define MI_PAGE_META_SMALL_IS_ALIGNED 0 +#elif (MI_OPT_FREE_SMALL || MI_PAGE_META_IS_ALIGNED) +#define MI_PAGE_META_SMALL_IS_ALIGNED 1 +#else +#define MI_PAGE_META_SMALL_IS_ALIGNED 0 +#endif +#endif + +// -------------------------------------------------------------- +// Build configuration checks +// -------------------------------------------------------------- + +#if !MI_PAGE_META_IS_SEPARATED && MI_SECURE +#error "Secure mode should use separated page infos" +#endif +#if MI_PAGE_META_SMALL_IS_ALIGNED && (MI_SECURE || MI_GUARDED || MI_MTE) +#error "MTE, secure or guarded mode cannot use MI_OPT_FREE_SMALL (MI_PAGE_META_SMALL_IS_ALIGNED)" +#endif +#if (MI_PAGE_META_IS_ALIGNED || MI_PAGE_META_SMALL_IS_ALIGNED) && MI_CHERI +#error "Cannot have aligned page meta with CHERI" +#endif +#if MI_QSBR && MI_CHERI +#error "QSBR cannot be used with CHERI (as delayed concurrent reads would have the wrong capability)" +#endif + + +// -------------------------------------------------------------- +// Sizes of internal data-structures +// (comments specify sizes on 64-bit, usually 32-bit is halved) +// -------------------------------------------------------------- + +// Main size parameter; determines max arena sizes and max arena object sizes etc. +#ifndef MI_ARENA_SLICE_SHIFT + #ifdef MI_SMALL_PAGE_SHIFT // backward compatibility + #define MI_ARENA_SLICE_SHIFT MI_SMALL_PAGE_SHIFT + #elif MI_SECURE && MI_OS_PROBABLE_PAGE_SIZE >= 64*MI_KiB + #define MI_ARENA_SLICE_SHIFT (18) // 256 KiB as 64 KiB guard pages can be at most 1/4 of a slice (issue #1166) + #elif MI_SECURE>=5 && MI_OS_PROBABLE_PAGE_SIZE >= 16*MI_KiB + #define MI_ARENA_SLICE_SHIFT (17) // 128 KiB to not waste too much due to 16 KiB guard pages + #elif MI_OS_PROBABLE_PAGE_SIZE >= 64*MI_KiB + #define MI_ARENA_SLICE_SHIFT (16) // 64 KiB: at least the OS page size (e.g. on wasm32) + #else + #define MI_ARENA_SLICE_SHIFT (13 + MI_SIZE_SHIFT) // 64 KiB (32 KiB on 32-bit) + #endif +#endif +#if MI_ARENA_SLICE_SHIFT < 13 +#error Arena slices should be at least 8KiB +#endif + +#ifndef MI_BCHUNK_BITS_SHIFT + #if MI_ARENA_SLICE_SHIFT <= 13 // <= 8KiB + #define MI_BCHUNK_BITS_SHIFT (7) // 128 bits + #elif MI_ARENA_SLICE_SHIFT < 16 // <= 32KiB + #define MI_BCHUNK_BITS_SHIFT (8) // 256 bits + #else + #define MI_BCHUNK_BITS_SHIFT (6 + MI_SIZE_SHIFT) // 512 bits (or 256 on 32-bit) + #endif +#endif + +#define MI_BCHUNK_BITS (1 << MI_BCHUNK_BITS_SHIFT) // sub-bitmaps in arena's are "bchunks" of 512 bits +#define MI_ARENA_SLICE_SIZE (MI_ZU(1) << MI_ARENA_SLICE_SHIFT) // arena's allocate in slices of 64 KiB +#define MI_ARENA_SLICE_ALIGN (MI_ARENA_SLICE_SIZE) +#define MI_ARENA_CHUNK_SIZE (MI_BCHUNK_BITS * MI_ARENA_SLICE_SIZE) + +#define MI_ARENA_MIN_OBJ_SLICES (1) +#define MI_ARENA_MAX_CHUNK_OBJ_SLICES (MI_BCHUNK_BITS) // 32 MiB (or 8 MiB on 32-bit) + +#define MI_ARENA_MIN_OBJ_SIZE (MI_ARENA_MIN_OBJ_SLICES * MI_ARENA_SLICE_SIZE) +#define MI_ARENA_MAX_CHUNK_OBJ_SIZE (MI_ARENA_MAX_CHUNK_OBJ_SLICES * MI_ARENA_SLICE_SIZE) + +#if MI_ARENA_MAX_CHUNK_OBJ_SIZE < MI_SIZE_SIZE*1024 +#error maximum object size may be too small to hold local thread data +#endif + +#define MI_SMALL_PAGE_SIZE MI_ARENA_MIN_OBJ_SIZE // 64 KiB +#define MI_MEDIUM_PAGE_SIZE (8*MI_SMALL_PAGE_SIZE) // 512 KiB (=byte in the bchunk bitmap) +#define MI_LARGE_PAGE_SIZE (MI_SIZE_SIZE*MI_MEDIUM_PAGE_SIZE) // 4 MiB (=word in the bchunk bitmap) + + +// Maximum number of size classes. (spaced exponentially in 12.5% increments) +#if MI_BIN_HUGE != 73U +#error "mimalloc internal: expecting 73 bins" +#endif +#define MI_BIN_FULL (MI_BIN_HUGE+1) +#define MI_BIN_COUNT (MI_BIN_FULL+1) + +// We never allocate more than PTRDIFF_MAX (see also ) +#define MI_MAX_ALLOC_SIZE PTRDIFF_MAX + +// Minimal commit for a page on-demand commit +#define MI_PAGE_MIN_COMMIT_SIZE (16*MI_KiB) /* MI_ARENA_SLICE_SIZE */ + +// In secure mode, a guard slice is reserved in front of the arena info and around the separated page meta data +// of aligned areas and direct OS allocations (but not on WebAssembly as it cannot protect memory) +#if MI_SECURE && !defined(__wasi__) && !defined(__EMSCRIPTEN__) +#define MI_ARENA_GUARD_SLICES 1 +#else +#define MI_ARENA_GUARD_SLICES 0 +#endif + +// Is the page meta data of direct OS allocated pages separated in front of the page area? (between guard slices in secure mode) +// Otherwise it is placed at the start of the page area itself. +#if MI_PAGE_META_IS_ALIGNED || (MI_PAGE_META_IS_SEPARATED && MI_ARENA_GUARD_SLICES > 0) +#define MI_PAGE_META_OS_IS_SEPARATED 1 +#else +#define MI_PAGE_META_OS_IS_SEPARATED 0 +#endif + +#if MI_PAGE_META_IS_ALIGNED +#define MI_PAGE_META_ALIGNED_COUNT (MI_PAGE_META_ALIGNED_CHUNKS * MI_BCHUNK_BITS) +#define MI_PAGE_META_ALIGNMENT (MI_PAGE_META_ALIGNED_COUNT * MI_ARENA_SLICE_SIZE) // 256 MiB (32 MiB on 32-bit) +#define MI_PAGE_META_ALIGNED_OFFSET (MI_ARENA_GUARD_SLICES * MI_ARENA_SLICE_SIZE) // offset of the page meta data in an aligned area +#define MI_ARENA_ALIGNMENT MI_PAGE_META_ALIGNMENT +#else +#define MI_ARENA_ALIGNMENT MI_ARENA_SLICE_ALIGN +#endif + +// spread the page meta entries of adjacent slices over the cache lines (within aligned areas or arena bitmap chunks) +#if !defined(MI_PAGE_META_IDX_MUL) +#define MI_PAGE_META_IDX_MUL 5 // must be odd; use 1 for a direct mapping; 9 or 33 work also well. +#endif +#if (MI_PAGE_META_IDX_MUL % 2) == 0 // (gcd(MI_PAGE_META_ALIGNED_COUNT, MI_PAGE_META_IDX_MUL)==1) => one-to-one mapping +#error "MI_PAGE_META_IDX_MUL must be odd to map slices one-to-one onto the page meta entries" +#endif + + +// ------------------------------------------------------ +// Object sizes +// ------------------------------------------------------ + +#define MI_PAGE_ALIGN MI_ARENA_SLICE_ALIGN // page area's must be aligned on this for the page map. +#define MI_PAGE_MIN_START_BLOCK_ALIGN MI_MAX_ALIGN_SIZE // minimal block alignment for the first block in a page (16b) +#define MI_PAGE_MAX_START_BLOCK_ALIGN2 (4*MI_KiB) // maximal block alignment for "power of 2"-sized blocks (such that we guarantee natural alignment, i.e. aligned to their own size) +#define MI_PAGE_OSPAGE_BLOCK_ALIGN2 (4*MI_KiB) // alignment of blocks that are a multiple of this size. +#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 + +// Offset the first block in pages with larger blocks (using the unused space at the end of the page) spread across cache sets (issue #1121). +#if !defined(MI_PAGE_LARGE_CACHE_OFFSET) +#define MI_PAGE_LARGE_CACHE_OFFSET 1 +#endif +#define MI_PAGE_LARGE_CACHE_OFFSET_UNIT (128) // offset granularity (power of 2 between 16 and 4KiB) +#define MI_PAGE_LARGE_CACHE_OFFSET_MAX (MI_PAGE_OSPAGE_BLOCK_ALIGN2 - MI_PAGE_LARGE_CACHE_OFFSET_UNIT) // maximal offset (32 possible offsets) +// Offset the first block in pages with small blocks +#define MI_PAGE_SMALL_CACHE_OFFSET_UNIT (64) +#define MI_PAGE_SMALL_CACHE_OFFSET_MAX (7*MI_PAGE_SMALL_CACHE_OFFSET_UNIT) // up to 512B (7+1 offsets) (using 15+1 offsets upto 1KiB works well too) + +// 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 +#define MI_MEDIUM_MAX_OBJ_SIZE (5*(MI_MEDIUM_PAGE_SIZE/32)) // largest bin with 6 blocks/medium page (but see `alloc/page.h:mi_block_size_is_medium`) +#if MI_ENABLE_LARGE_PAGES +#define MI_LARGE_MAX_OBJ_SIZE (MI_LARGE_PAGE_SIZE/8) // <= 512 KiB. note: this must be a bin-size or we get rounding issues with `_mi_bin` +#else +#define MI_LARGE_MAX_OBJ_SIZE MI_MEDIUM_MAX_OBJ_SIZE // note: this must be a bin-size or we get rounding issues with `_mi_bin` +#endif +#define MI_LARGE_MAX_OBJ_WSIZE (MI_LARGE_MAX_OBJ_SIZE/MI_SIZE_SIZE) +#define MI_MAX_RECLAIM_OBJ_SIZE (MI_LARGE_MAX_OBJ_SIZE/4) // only reclaim abandoned pages on free up to this block size + +#if (MI_LARGE_MAX_OBJ_WSIZE >= 655360) +#error "mimalloc internal: define more bins" +#endif + +// static invariant: MI_MAX_SINGLETON_BIN >= _mi_bin(MI_LARGE_MAX_OBJ_SIZE) (See heap/process.c for the size bins) +#if (MI_LARGE_MAX_OBJ_WSIZE <= 8192) // 64 KiB +#define MI_MAX_SINGLETON_BIN (48) +#elif (MI_LARGE_MAX_OBJ_WSIZE <= 32768) // 256KiB +#define MI_MAX_SINGLETON_BIN (56) +#elif (MI_LARGE_MAX_OBJ_WSIZE <= 65536) // 512KiB +#define MI_MAX_SINGLETON_BIN (60) +#else +#define MI_MAX_SINGLETON_BIN MI_BIN_HUGE +#endif + +// The small object max size must be larger than twice the small size max minus one, +// such that any aligned allocation with `alignment <= size <= MI_SMALL_SIZE_MAX` will +// be allocated in a small page (so `mi_free_csize` can delegate correctly to `mi_free_small`. +#if MI_SMALL_MAX_OBJ_SIZE <= (2*(MI_SMALL_WSIZE_MAX * MI_SIZE_SIZE)-1) +#error "mimalloc internal: the small object max size is too small" +#endif + +// Environment options are named `MIMALLOC_