Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
Bump vendored deps: Mongoose 7.21, SQLite 3.51.3, mimalloc 3.2.8
Martin Vogel1d30971ff0f7
diff --git a/src/foundation/mem.c b/src/foundation/mem.cindex 1a5970ab4..79953ba31 100644--- a/src/foundation/mem.c+++ b/src/foundation/mem.c@@ -116,8 +116,8 @@ void cbm_mem_init(double ram_fraction) {ram_fraction = DEFAULT_RAM_FRACTION;}- /* Reduce upfront memory: don't eagerly commit segments */- mi_option_set(mi_option_eager_commit, 0);+ /* Reduce upfront memory: don't eagerly commit arenas */+ mi_option_set(mi_option_arena_eager_commit, 0);cbm_system_info_t info = cbm_system_info();g_budget = (size_t)((double)info.total_ram * ram_fraction);diff --git a/vendored/mimalloc/include/mimalloc-stats.h b/vendored/mimalloc/include/mimalloc-stats.hnew file mode 100644index 000000000..a714f41c7--- /dev/null+++ b/vendored/mimalloc/include/mimalloc-stats.h@@ -0,0 +1,156 @@+/* ----------------------------------------------------------------------------+Copyright (c) 2024-2025, 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_STATS_H+#define MIMALLOC_STATS_H++#include <mimalloc.h>+#include <stdint.h>++#define MI_STAT_VERSION 4 // 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 __cplusplus >= 201103L+#define mi_decl_align(a) alignas(a)+#else+#define mi_decl_align(a)+#endif+++// count allocation over time+typedef struct mi_stat_count_s {+ int64_t total; // total allocated+ int64_t peak; // peak allocation+ int64_t current; // current allocation+} mi_stat_count_t;++// counters only increase+typedef struct mi_stat_counter_s {+ int64_t total; // total count+} mi_stat_counter_t;++#define MI_STAT_FIELDS() \+ MI_STAT_COUNT(pages) /* count of mimalloc pages */ \+ MI_STAT_COUNT(reserved) /* reserved memory bytes */ \+ MI_STAT_COUNT(committed) /* committed bytes */ \+ MI_STAT_COUNTER(reset) /* reset bytes */ \+ MI_STAT_COUNTER(purged) /* purged bytes */ \+ MI_STAT_COUNT(page_committed) /* committed memory inside pages */ \+ MI_STAT_COUNT(pages_abandoned) /* abandonded pages count */ \+ MI_STAT_COUNT(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_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 */ \+ MI_STAT_COUNTER(arena_rollback_count) \+ MI_STAT_COUNTER(arena_purges) \+ MI_STAT_COUNTER(pages_extended) /* number of page extensions */ \+ MI_STAT_COUNTER(pages_retire) /* number of pages that are retired */ \+ MI_STAT_COUNTER(page_searches) /* total pages searched for a fresh page */ \+ MI_STAT_COUNTER(page_searches_count) /* searched count for a fresh page */ \+ /* only on v1 and v2 */ \+ MI_STAT_COUNT(segments) \+ MI_STAT_COUNT(segments_abandoned) \+ MI_STAT_COUNT(segments_cache) \+ MI_STAT_COUNT(_segments_reserved) \+ /* only on v3 */ \+ MI_STAT_COUNT(heaps) \+ 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)++// 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+#define MI_BIN_HUGE (73U) // see types.h+#define MI_STAT_COUNT(stat) mi_stat_count_t stat;+#define MI_STAT_COUNTER(stat) mi_stat_counter_t stat;++typedef struct mi_stats_s+{+ size_t size; // size of the mi_stats_t structure+ size_t version;++ mi_decl_align(8) MI_STAT_FIELDS()++ // future extension+ mi_stat_count_t _stat_reserved[4];+ mi_stat_counter_t _stat_counter_reserved[4];++ // 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;++// Exported definitions+#ifdef __cplusplus+extern "C" {+#endif++// 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;++#ifdef __cplusplus+}+#endif++#endif // MIMALLOC_STATS_Hdiff --git a/vendored/mimalloc/include/mimalloc.h b/vendored/mimalloc/include/mimalloc.hindex bd91db433..bf570d155 100644--- a/vendored/mimalloc/include/mimalloc.h+++ b/vendored/mimalloc/include/mimalloc.h@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2025, Microsoft Research, Daan Leijen+Copyright (c) 2018-2026, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -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 219 // major + 2 digits minor+#define MI_MALLOC_VERSION 3208 // major + minor + 2 digits patch// ------------------------------------------------------// Compiler specific attributes@@ -97,7 +97,6 @@ terms of the MIT license. A copy of the license can be found in the file#include <stddef.h> // size_t#include <stdbool.h> // bool-#include <stdint.h> // INTPTR_MAX#ifdef __cplusplusextern "C" {@@ -118,7 +117,7 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_strndup(const char* smi_decl_nodiscard mi_decl_export mi_decl_restrict char* mi_realpath(const char* fname, char* resolved_name) mi_attr_noexcept mi_attr_malloc;// -------------------------------------------------------// Extended functionality+// Extended allocation functions// ------------------------------------------------------#define MI_SMALL_WSIZE_MAX (128)#define MI_SMALL_SIZE_MAX (MI_SMALL_WSIZE_MAX*sizeof(void*))@@ -135,8 +134,44 @@ mi_decl_nodiscard mi_decl_export size_t mi_usable_size(const void* p) mi_attr_nomi_decl_nodiscard mi_decl_export size_t mi_good_size(size_t size) 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(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(tp,p,n) ((tp*)mi_reallocn(p,n,sizeof(tp)))+#define mi_recalloc_tp(tp,p,n) ((tp*)mi_recalloc(p,n,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,n) ((tp*)mi_heap_recalloc(hp,p,n,sizeof(tp)))++// ------------------------------------------------------// Internals+// See also `mimalloc-stats.h` for statistics// ------------------------------------------------------typedef void (mi_cdecl mi_deferred_free_fun)(bool force, unsigned long long heartbeat, void* arg);@@ -148,63 +183,70 @@ mi_decl_export void mi_register_output(mi_output_fun* out, void* arg) mi_attr_notypedef 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 void mi_collect_reduce(size_t target_thread_owned) 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_collect(bool force) mi_attr_noexcept;+mi_decl_export int mi_version(void) mi_attr_noexcept;+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 automaticallymi_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;-mi_decl_export void mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept;+mi_decl_export void mi_thread_set_in_threadpool(void) mi_attr_noexcept; // communicate that a thread is in a threadpool-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;-// --------------------------------------------------------------------------------------// Aligned allocation-// Note that `alignment` always follows `size` for consistency with unaligned-// allocation, but unfortunately this differs from `posix_memalign` and `aligned_alloc`.-// -------------------------------------------------------------------------------------+// -----------------------------------------------------------------+// Return allocated block size (if the return value is not NULL)+// ------------------------------------------------------------------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_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_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_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);// --------------------------------------------------------------------------------------// 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_heap_set_numa_affinity(mi_heap_t* heap, int numa_node);+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_malloc_small(mi_heap_t* theap, size_t size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2);mi_decl_nodiscard mi_decl_export 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;@@ -236,105 +278,149 @@ mi_decl_nodiscard mi_decl_export void* mi_recalloc_aligned(void* p, size_t newcomi_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_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_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);+// -------------------------------------------------------// 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 blockssize_t reserved; // bytes reserved for this area (virtual)size_t committed; // current available bytes for this areasize_t used; // number of allocated blockssize_t block_size; // size in bytes of each blocksize_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);+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(bool show_inuse) 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 size_t mi_arena_min_alignment(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 arenami_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 segments stay separated (and no reclamation between them)-// Used for example for separate interpreter's in one process.-typedef void* mi_subproc_id_t;+// ------------------------------------------------------+// 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;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 (from threads that have been terminated)-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);+-// 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);+// -------------------------------------------------------------------------------------+// 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).+// --------------------------------------------------------------------------------------// deprecated-mi_decl_export int mi_reserve_huge_os_pages(size_t pages, double max_secs, size_t* pages_reserved) mi_attr_noexcept;+struct mi_theap_s;+typedef struct mi_theap_s mi_theap_t;++mi_decl_export mi_theap_t* mi_heap_theap(mi_heap_t* heap);+mi_decl_export mi_theap_t* mi_theap_set_default(mi_theap_t* theap);+mi_decl_export mi_theap_t* mi_theap_get_default(void);+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_malloc_aligned(mi_theap_t* theap, size_t size, size_t alignment) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_size(2) mi_attr_alloc_align(3);+mi_decl_nodiscard mi_decl_export void* mi_theap_realloc(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept mi_attr_alloc_size(3);+++// ------------------------------------------------------+// 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);++// 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;++//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);// -------------------------------------------------------// 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_export bool mi_check_owned(const void* p);++mi_decl_export void mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept;+mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) 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;++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; // not deprecated but declared in `mimalloc-stats.h` now.-#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)))// ------------------------------------------------------@@ -347,46 +433,55 @@ typedef enum mi_option_e {mi_option_show_stats, // print statistics on terminationmi_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 large (2 or 4 MiB) OS pages, implies eager commit. If false, also disables THP for the process.+ mi_option_allow_large_os_pages, // allow use of large (2 or 4 MiB) OS pages, implies eager commit.mi_option_reserve_huge_os_pages, // reserve N huge OS pages (1GiB pages) at startupmi_option_reserve_huge_os_pages_at, // reserve huge OS pages at a specific NUMA nodemi_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 messagesmi_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, // max. percentage of the abandoned segments can be reclaimed per try (=10%)mi_option_destroy_on_exit, // if set, release all memory on exit; sometimes used for dynamic unloading but can be unsafemi_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_visit_abandoned, // allow visiting theap blocks from abandoned threads (=0)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_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 theaps every N (=10000) generic allocation calls+ mi_option_page_reclaim_on_free, // reclaim abandoned pages on a free (=0). -1 disallowr always, 0 allows if the page originated from the current theap, 1 allow always+ 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) (=16)+ mi_option_allow_thp, // allow transparent huge pages? (=1) (on Android =0 by default). Set to 0 to disable THP for the process.+ mi_option_minimal_purge_size, // set minimal purge size (in KiB) (=0). By default set to either 64 or 2048 if THP is enabled.+ mi_option_arena_max_object_size, // set maximal object size that can be allocated in an arena (in KiB) (=2GiB on 64-bit)._mi_option_last,// legacy option namesmi_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_t;@@ -407,7 +502,7 @@ 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;@@ -446,7 +541,7 @@ mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_new_n(size_t count, smi_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);#ifdef __cplusplus@@ -524,7 +619,7 @@ template<class T1,class T2> bool operator!=(const mi_stl_allocator<T1>& , const#include <memory> // std::shared_ptr-// Common base class for STL allocators in a specific heap+// Common base class for STL allocators in a specific theaptemplate<class T, bool _mi_destroy> struct _mi_heap_stl_allocator_common : public _mi_stl_allocator_common<T> {using typename _mi_stl_allocator_common<T>::size_type;using typename _mi_stl_allocator_common<T>::value_type;diff --git a/vendored/mimalloc/include/mimalloc/atomic.h b/vendored/mimalloc/include/mimalloc/atomic.hindex 0d7aaf789..699c78b45 100644--- a/vendored/mimalloc/include/mimalloc/atomic.h+++ b/vendored/mimalloc/include/mimalloc/atomic.h@@ -5,8 +5,8 @@ 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)@@ -31,33 +31,33 @@ terms of the MIT license. A copy of the license can be found in the file#if defined(__cplusplus)// Use C++ atomics#include <atomic>-#define _Atomic(tp) std::atomic<tp>-#define mi_atomic(name) std::atomic_##name-#define mi_memory_order(name) std::memory_order_##name-#if (__cplusplus >= 202002L) // c++20, see issue #571- #define MI_ATOMIC_VAR_INIT(x) x+#define _Atomic(tp) std::atomic<tp>+#define mi_atomic(name) std::atomic_##name+#define mi_memory_order(name) std::memory_order_##name+#if (__cplusplus >= 202002L) // c++20, see issue #571+ #define MI_ATOMIC_VAR_INIT(x) x#elif !defined(ATOMIC_VAR_INIT)- #define MI_ATOMIC_VAR_INIT(x) x+ #define MI_ATOMIC_VAR_INIT(x) x#else- #define MI_ATOMIC_VAR_INIT(x) ATOMIC_VAR_INIT(x)+ #define MI_ATOMIC_VAR_INIT(x) ATOMIC_VAR_INIT(x)#endif#elif defined(_MSC_VER)// Use MSVC C wrapper for C11 atomics-#define _Atomic(tp) tp-#define MI_ATOMIC_VAR_INIT(x) x-#define mi_atomic(name) mi_atomic_##name-#define mi_memory_order(name) mi_memory_order_##name+#define _Atomic(tp) tp+#define MI_ATOMIC_VAR_INIT(x) x+#define mi_atomic(name) mi_atomic_##name+#define mi_memory_order(name) mi_memory_order_##name#else// Use C11 atomics#include <stdatomic.h>-#define mi_atomic(name) atomic_##name-#define mi_memory_order(name) memory_order_##name+#define mi_atomic(name) atomic_##name+#define mi_memory_order(name) memory_order_##name#if (__STDC_VERSION__ >= 201710L) // c17, see issue #735- #define MI_ATOMIC_VAR_INIT(x) x+ #define MI_ATOMIC_VAR_INIT(x) x#elif !defined(ATOMIC_VAR_INIT)- #define MI_ATOMIC_VAR_INIT(x) x+ #define MI_ATOMIC_VAR_INIT(x) x#else- #define MI_ATOMIC_VAR_INIT(x) ATOMIC_VAR_INIT(x)+ #define MI_ATOMIC_VAR_INIT(x) ATOMIC_VAR_INIT(x)#endif#endif@@ -75,16 +75,21 @@ terms of the MIT license. A copy of the license can be found in the file#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_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_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)@@ -111,6 +116,7 @@ static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub);#define mi_atomic_cas_ptr_weak_release(tp,p,exp,des) mi_atomic_cas_weak_release(p,exp,(tp*)des)#define mi_atomic_cas_ptr_weak_acq_rel(tp,p,exp,des) mi_atomic_cas_weak_acq_rel(p,exp,(tp*)des)#define mi_atomic_cas_ptr_strong_release(tp,p,exp,des) mi_atomic_cas_strong_release(p,exp,(tp*)des)+#define mi_atomic_cas_ptr_strong_acq_rel(tp,p,exp,des) mi_atomic_cas_strong_acq_rel(p,exp,(tp*)des)#define mi_atomic_exchange_ptr_relaxed(tp,p,x) mi_atomic_exchange_relaxed(p,(tp*)x)#define mi_atomic_exchange_ptr_release(tp,p,x) mi_atomic_exchange_release(p,(tp*)x)#define mi_atomic_exchange_ptr_acq_rel(tp,p,x) mi_atomic_exchange_acq_rel(p,(tp*)x)@@ -120,6 +126,7 @@ static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub);#define mi_atomic_cas_ptr_weak_release(tp,p,exp,des) mi_atomic_cas_weak_release(p,exp,des)#define mi_atomic_cas_ptr_weak_acq_rel(tp,p,exp,des) mi_atomic_cas_weak_acq_rel(p,exp,des)#define mi_atomic_cas_ptr_strong_release(tp,p,exp,des) mi_atomic_cas_strong_release(p,exp,des)+#define mi_atomic_cas_ptr_strong_acq_rel(tp,p,exp,des) mi_atomic_cas_strong_acq_rel(p,exp,des)#define mi_atomic_exchange_ptr_relaxed(tp,p,x) mi_atomic_exchange_relaxed(p,x)#define mi_atomic_exchange_ptr_release(tp,p,x) mi_atomic_exchange_release(p,x)#define mi_atomic_exchange_ptr_acq_rel(tp,p,x) mi_atomic_exchange_acq_rel(p,x)@@ -129,6 +136,12 @@ static inline intptr_t mi_atomic_subi(_Atomic(intptr_t)*p, intptr_t sub);static inline int64_t mi_atomic_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 void mi_atomic_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 */ };@@ -260,6 +273,14 @@ static inline int64_t mi_atomic_addi64_relaxed(volatile _Atomic(int64_t)*p, int6return 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 void mi_atomic_maxi64_relaxed(volatile _Atomic(int64_t)*p, int64_t x) {int64_t current;do {@@ -290,6 +311,8 @@ static inline bool mi_atomic_casi64_strong_acq_rel(volatile _Atomic(int64_t*)p,#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)@@ -356,8 +379,9 @@ static inline void mi_atomic_yield(void) {_mm_pause();}#elif (defined(__GNUC__) || defined(__clang__)) && \- (defined(__x86_64__) || defined(__i386__) || defined(__arm__) || defined(__armel__) || defined(__ARMEL__) || \- defined(__aarch64__) || defined(__powerpc__) || defined(__ppc__) || defined(__PPC__)) || defined(__POWERPC__)+ (defined(__x86_64__) || defined(__i386__) || \+ defined(__aarch64__) || defined(__arm__) || \+ defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) || defined(__POWERPC__))#if defined(__x86_64__) || defined(__i386__)static inline void mi_atomic_yield(void) {__asm__ volatile ("pause" ::: "memory");@@ -366,10 +390,16 @@ static inline void mi_atomic_yield(void) {static inline void mi_atomic_yield(void) {__asm__ volatile("wfe");}-#elif (defined(__arm__) && __ARM_ARCH__ >= 7)+#elif defined(__arm__)+#if __ARM_ARCH >= 7static 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) {@@ -380,10 +410,6 @@ static inline void mi_atomic_yield(void) {__asm__ __volatile__ ("or 27,27,27" ::: "memory");}#endif-#elif defined(__armel__) || defined(__ARMEL__)-static inline void mi_atomic_yield(void) {- __asm__ volatile ("nop" ::: "memory");-}#endif#elif defined(__sun)// Fallback for other archs@@ -405,10 +431,9 @@ static inline void mi_atomic_yield(void) {// -----------------------------------------------------------------------// Locks-// These do not have to be recursive and should be light-weight-// in-process only locks. Only used for reserving arena's and to-// maintain the abandoned list.+// Locks+// These should be light-weight in-process only locks.+// Only used for reserving arena's and to maintain the abandoned list.// ----------------------------------------------------------------------#if _MSC_VER#pragma warning(disable:26110) // unlock with holding lock@@ -460,6 +485,7 @@ static inline void mi_lock_done(mi_lock_t* lock) {#elif defined(MI_USE_PTHREADS)+#include <string.h> // memcpyvoid _mi_error_message(int err, const char* fmt, ...);#define mi_lock_t pthread_mutex_t@@ -470,14 +496,17 @@ static inline bool mi_lock_try_acquire(mi_lock_t* lock) {static inline void mi_lock_acquire(mi_lock_t* lock) {const int err = pthread_mutex_lock(lock);if (err != 0) {- _mi_error_message(err, "internal error: lock cannot be acquired\n");+ _mi_error_message(err, "internal error: lock cannot be acquired (err %i)\n", err);}}static inline void mi_lock_release(mi_lock_t* lock) {pthread_mutex_unlock(lock);}static inline void mi_lock_init(mi_lock_t* lock) {- pthread_mutex_init(lock, NULL);+ if(lock==NULL) return;+ // use instead of pthread_mutex_init since that can cause allocation on some platforms (and recursively initialize)+ const mi_lock_t temp_lock = PTHREAD_MUTEX_INITIALIZER;+ memcpy(lock,&temp_lock,sizeof(temp_lock));}static inline void mi_lock_done(mi_lock_t* lock) {pthread_mutex_destroy(lock);@@ -534,4 +563,4 @@ static inline void mi_lock_done(mi_lock_t* lock) {#endif-#endif // __MIMALLOC_ATOMIC_H+#endif // MI_ATOMIC_Hdiff --git a/vendored/mimalloc/include/mimalloc/bits.h b/vendored/mimalloc/include/mimalloc/bits.hnew file mode 100644index 000000000..c40b32f6b--- /dev/null+++ b/vendored/mimalloc/include/mimalloc/bits.h@@ -0,0 +1,342 @@+/* ----------------------------------------------------------------------------+Copyright (c) 2019-2024 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.+-----------------------------------------------------------------------------*/++/* ----------------------------------------------------------------------------+ Bit operation, and platform dependent definition (MI_INTPTR_SIZE etc)+---------------------------------------------------------------------------- */++#pragma once+#ifndef MI_BITS_H+#define MI_BITS_H++#include <stddef.h> // size_t+#include <stdint.h> // int64_t etc+#include <stdbool.h> // bool++// ------------------------------------------------------+// 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...+// ------------------------------------------------------++#if INTPTR_MAX > INT64_MAX+# define MI_INTPTR_SHIFT (4) // assume 128-bit (as on arm CHERI for example)+#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;+#elif SIZE_MAX == UINT32_MAX+# define MI_SIZE_SHIFT (2)+typedef int32_t mi_ssize_t;+#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<<MI_INTPTR_SHIFT)+#define MI_INTPTR_BITS (MI_INTPTR_SIZE*8)++#define MI_SIZE_SIZE (1<<MI_SIZE_SHIFT)+#define MI_SIZE_BITS (MI_SIZE_SIZE*8)++#define MI_KiB (MI_ZU(1024))+#define MI_MiB (MI_KiB*MI_KiB)+#define MI_GiB (MI_MiB*MI_KiB)+++/* --------------------------------------------------------------------------------+ Architecture+-------------------------------------------------------------------------------- */++#if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_HYBRID_X86_ARM64) || defined(_M_ARM64EC) // consider arm64ec as arm64+#define MI_ARCH_ARM64 1+#elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)+#define MI_ARCH_X64 1+#elif defined(__i386__) || defined(__i386) || defined(_M_IX86) || defined(_X86_) || defined(__X86__)+#define MI_ARCH_X86 1+#elif defined(__arm__) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm)+#define MI_ARCH_ARM32 1+#elif defined(__riscv) || defined(_M_RISCV)+#define MI_ARCH_RISCV 1+#if (LONG_MAX == INT32_MAX)+#define MI_ARCH_RISCV32 1+#else+#define MI_ARCH_RISCV64 1+#endif+#endif++#if MI_ARCH_X64 && defined(__AVX2__)+#include <immintrin.h>+#elif MI_ARCH_ARM64 && MI_OPT_SIMD+#include <arm_neon.h>+#endif+#if defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)+#include <intrin.h>+#endif++#if MI_ARCH_X64 && defined(__AVX2__) && !defined(__BMI2__) // msvc+#define __BMI2__ 1+#endif+#if MI_ARCH_X64 && (defined(__AVX2__) || defined(__BMI2__)) && !defined(__BMI1__) // msvc+#define __BMI1__ 1+#endif++// Define big endian if needed+// #define MI_BIG_ENDIAN 1++// 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+#define MI_MAX_VABITS (47)+#elif MI_INTPTR_SIZE > 4+#define MI_MAX_VABITS (48)+#else+#define MI_MAX_VABITS (32)+#endif++// use a flat page-map (or a 2-level one)+#ifndef MI_PAGE_MAP_FLAT+#if MI_MAX_VABITS <= 40 && !defined(__APPLE__)+#define MI_PAGE_MAP_FLAT 1+#else+#define MI_PAGE_MAP_FLAT 0+#endif+#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);++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_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)+ return mi_msc_builtinz(__popcnt)(x);+ #elif MI_ARCH_X64 && defined(__BMI1__)+ return (size_t)_mm_popcnt_u64(x);+ #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 <https://github.com/llvm/llvm-project/pull/102885>)+ __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(__BMI1__) // 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(__BMI1__)+ 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 defined(__GNUC__) && MI_ARCH_X64 && defined(__BMI1__) && (!defined(__clang_major__) || __clang_major__ >= 9)+ // on x64 the carry flag is set on zero which gives better codegen+ bool is_zero;+ __asm ("lzcnt\t%2, %1" : "=@ccc"(is_zero), "=r"(*idx) : "r"(x) : "cc");+ return !is_zero;+ #elif 0 && defined(_MSC_VER) && (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64 || MI_ARCH_ARM32)+ 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 <https://blog.regehr.org/archives/1063>+ 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 <https://blog.regehr.org/archives/1063>+ 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 <https://blog.regehr.org/archives/1063>+ const unsigned int rshift = (unsigned int)(r) & 31;+ return ((x << rshift) | (x >> ((-rshift) & 31)));+ #endif+}+++#endif // MI_BITS_Hdiff --git a/vendored/mimalloc/include/mimalloc/internal.h b/vendored/mimalloc/include/mimalloc/internal.hindex e7e7b5083..bf0b6975a 100644--- a/vendored/mimalloc/include/mimalloc/internal.h+++ b/vendored/mimalloc/include/mimalloc/internal.h@@ -1,13 +1,12 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2023, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.-----------------------------------------------------------------------------*/#pragma once-#ifndef MIMALLOC_INTERNAL_H-#define MIMALLOC_INTERNAL_H-+#ifndef MI_INTERNAL_H+#define MI_INTERNAL_H// --------------------------------------------------------------------------// This file contains the internal API's of mimalloc and various utility@@ -16,6 +15,12 @@ terms of the MIT license. A copy of the license can be found in the file#include "types.h"#include "track.h"+#include "bits.h"+++// --------------------------------------------------------------------------+// Compiler defines+// --------------------------------------------------------------------------#if (MI_DEBUG>0)#define mi_trace_message(...) _mi_trace_message(__VA_ARGS__)@@ -23,284 +28,391 @@ terms of the MIT license. A copy of the license can be found in the file#define mi_trace_message(...)#endif-#define MI_CACHE_LINE 64+#define mi_decl_cache_align mi_decl_align(64)+#if defined(_MSC_VER)#pragma warning(disable:4127) // suppress constant conditional warning (due to MI_SECURE paths)#pragma warning(disable:26812) // unscoped enum warning+#define mi_decl_forceinline __forceinline#define mi_decl_noinline __declspec(noinline)#define mi_decl_thread __declspec(thread)-#define mi_decl_cache_align __declspec(align(MI_CACHE_LINE))+#define mi_decl_noreturn __declspec(noreturn)#define mi_decl_weak#define mi_decl_hidden+#define mi_decl_cold#elif (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__clang__) // includes clang and icc+#if !MI_TRACK_ASAN+#define mi_decl_forceinline __attribute__((always_inline)) inline+#else+#define mi_decl_forceinline inline+#endif#define mi_decl_noinline __attribute__((noinline))#define mi_decl_thread __thread-#define mi_decl_cache_align __attribute__((aligned(MI_CACHE_LINE)))+#define mi_decl_noreturn __attribute__((noreturn))#define mi_decl_weak __attribute__((weak))#define mi_decl_hidden __attribute__((visibility("hidden")))+#if (__GNUC__ >= 4) || defined(__clang__)+#define mi_decl_cold __attribute__((cold))+#else+#define mi_decl_cold+#endif#elif __cplusplus >= 201103L // c++11+#define mi_decl_forceinline inline#define mi_decl_noinline#define mi_decl_thread thread_local-#define mi_decl_cache_align alignas(MI_CACHE_LINE)+#define mi_decl_noreturn [[noreturn]]#define mi_decl_weak#define mi_decl_hidden+#define mi_decl_cold#else+#define mi_decl_forceinline inline#define mi_decl_noinline#define mi_decl_thread __thread // hope for the best :-)-#define mi_decl_cache_align+#define mi_decl_noreturn#define mi_decl_weak#define mi_decl_hidden+#define mi_decl_cold#endif-#if defined(__EMSCRIPTEN__) && !defined(__wasi__)-#define __wasi__+#if defined(__GNUC__) || defined(__clang__)+#define mi_unlikely(x) (__builtin_expect(!!(x),false))+#define mi_likely(x) (__builtin_expect(!!(x),true))+#elif (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)+#define mi_unlikely(x) (x) [[unlikely]]+#define mi_likely(x) (x) [[likely]]+#else+#define mi_unlikely(x) (x)+#define mi_likely(x) (x)+#endif++#ifndef __has_builtin+#define __has_builtin(x) 0+#endif++#if defined(__cplusplus)+#define mi_decl_externc extern "C"+#else+#define mi_decl_externc+#endif++#if (defined(__GNUC__) && (__GNUC__ >= 7)) || defined(__clang__) // includes clang and icc+#define mi_decl_maybe_unused __attribute__((unused))+#elif __cplusplus >= 201703L // c++17+#define mi_decl_maybe_unused [[maybe_unused]]+#else+#define mi_decl_maybe_unused#endif#if defined(__cplusplus)-#define mi_decl_externc extern "C"+#define mi_decl_externc extern "C"#else#define mi_decl_externc#endif++#if defined(__EMSCRIPTEN__) && !defined(__wasi__)+#define __wasi__+#endif+++// --------------------------------------------------------------------------+// Internal functions+// --------------------------------------------------------------------------++// "libc.c"-#include <stdarg.h>-void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args);-void _mi_snprintf(char* buf, size_t buflen, const char* fmt, ...);-char _mi_toupper(char c);-int _mi_strnicmp(const char* s, const char* t, size_t n);-void _mi_strlcpy(char* dest, const char* src, size_t dest_size);-void _mi_strlcat(char* dest, const char* src, size_t dest_size);-size_t _mi_strlen(const char* s);-size_t _mi_strnlen(const char* s, size_t max_len);-bool _mi_getenv(const char* name, char* result, size_t result_size);+#include <stdarg.h>+int _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args);+int _mi_snprintf(char* buf, size_t buflen, const char* fmt, ...);+char _mi_toupper(char c);+int _mi_strnicmp(const char* s, const char* t, size_t n);+void _mi_strlcpy(char* dest, const char* src, size_t dest_size);+void _mi_strlcat(char* dest, const char* src, size_t dest_size);+size_t _mi_strlen(const char* s);+size_t _mi_strnlen(const char* s, size_t max_len);+char* _mi_strnstr(char* s, size_t max_len, const char* pat);+bool _mi_getenv(const char* name, char* result, size_t result_size);// "options.c"-void _mi_fputs(mi_output_fun* out, void* arg, const char* prefix, const char* message);-void _mi_fprintf(mi_output_fun* out, void* arg, const char* fmt, ...);-void _mi_warning_message(const char* fmt, ...);-void _mi_verbose_message(const char* fmt, ...);-void _mi_trace_message(const char* fmt, ...);-void _mi_options_init(void);-long _mi_option_get_fast(mi_option_t option);-void _mi_error_message(int err, const char* fmt, ...);+void _mi_fputs(mi_output_fun* out, void* arg, const char* prefix, const char* message);+void _mi_fprintf(mi_output_fun* out, void* arg, const char* fmt, ...);+void _mi_raw_message(const char* fmt, ...);+void _mi_message(const char* fmt, ...);+void _mi_warning_message(const char* fmt, ...);+void _mi_verbose_message(const char* fmt, ...);+void _mi_trace_message(const char* fmt, ...);+void _mi_options_init(void);+void _mi_options_post_init(void);+long _mi_option_get_fast(mi_option_t option);+void _mi_error_message(int err, const char* fmt, ...);// random.c-void _mi_random_init(mi_random_ctx_t* ctx);-void _mi_random_init_weak(mi_random_ctx_t* ctx);-void _mi_random_reinit_if_weak(mi_random_ctx_t * ctx);-void _mi_random_split(mi_random_ctx_t* ctx, mi_random_ctx_t* new_ctx);-uintptr_t _mi_random_next(mi_random_ctx_t* ctx);-uintptr_t _mi_heap_random_next(mi_heap_t* heap);-uintptr_t _mi_os_random_weak(uintptr_t extra_seed);+void _mi_random_init(mi_random_ctx_t* ctx);+void _mi_random_init_weak(mi_random_ctx_t* ctx);+void _mi_random_reinit_if_weak(mi_random_ctx_t * ctx);+void _mi_random_split(mi_random_ctx_t* ctx, mi_random_ctx_t* new_ctx);+uintptr_t _mi_random_next(mi_random_ctx_t* ctx);+uintptr_t _mi_theap_random_next(mi_theap_t* theap);+uintptr_t _mi_os_random_weak(uintptr_t extra_seed);static inline uintptr_t _mi_random_shuffle(uintptr_t x);// init.c-extern mi_decl_cache_align mi_stats_t _mi_stats_main;extern mi_decl_hidden mi_decl_cache_align const mi_page_t _mi_page_empty;-void _mi_process_load(void);-void mi_cdecl _mi_process_done(void);-bool _mi_is_redirected(void);-bool _mi_allocator_init(const char** message);-void _mi_allocator_done(void);-bool _mi_is_main_thread(void);-size_t _mi_current_thread_count(void);-bool _mi_preloading(void); // true while the C runtime is not initialized yet-void _mi_thread_done(mi_heap_t* heap);-void _mi_thread_data_collect(void);-void _mi_tld_init(mi_tld_t* tld, mi_heap_t* bheap);-mi_threadid_t _mi_thread_id(void) mi_attr_noexcept;-mi_heap_t* _mi_heap_main_get(void); // statically allocated main backing heap+void _mi_auto_process_init(void);+void mi_cdecl _mi_auto_process_done(void) mi_attr_noexcept;+bool _mi_is_redirected(void);+bool _mi_allocator_init(const char** message);+void _mi_allocator_done(void);+bool _mi_is_main_thread(void);+bool _mi_preloading(void); // true while the C runtime is not initialized yet+void _mi_thread_done(mi_theap_t* theap);++mi_subproc_t* _mi_subproc(void);+mi_subproc_t* _mi_subproc_main(void);+mi_heap_t* _mi_subproc_heap_main(mi_subproc_t* subproc);mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id);-void _mi_heap_guarded_init(mi_heap_t* heap);--// os.c-void _mi_os_init(void); // called from process init-void* _mi_os_alloc(size_t size, mi_memid_t* memid);-void _mi_os_free(void* p, size_t size, mi_memid_t memid);-void _mi_os_free_ex(void* p, size_t size, bool still_committed, mi_memid_t memid);-size_t _mi_os_page_size(void);-size_t _mi_os_good_alloc_size(size_t size);-bool _mi_os_has_overcommit(void);-bool _mi_os_has_virtual_reserve(void);--bool _mi_os_reset(void* addr, size_t size);-bool _mi_os_commit(void* p, size_t size, bool* is_zero);-bool _mi_os_decommit(void* addr, size_t size);-bool _mi_os_protect(void* addr, size_t size);-bool _mi_os_unprotect(void* addr, size_t size);-bool _mi_os_purge(void* p, size_t size);-bool _mi_os_purge_ex(void* p, size_t size, bool allow_reset, size_t stat_size);--void* _mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, bool allow_large, mi_memid_t* memid);-void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_large, mi_memid_t* memid);--void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size);-bool _mi_os_use_large_page(size_t size, size_t alignment);-size_t _mi_os_large_page_size(void);+mi_threadid_t _mi_thread_id(void) mi_attr_noexcept;+size_t _mi_thread_seq_id(void) mi_attr_noexcept;+bool _mi_is_heap_main(const mi_heap_t* heap);+void _mi_theap_guarded_init(mi_theap_t* theap);+void _mi_theap_options_init(mi_theap_t* theap);+mi_theap_t* _mi_theap_default_safe(void); // ensure the returned theap is initialized-void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_secs, size_t* pages_reserved, size_t* psize, mi_memid_t* memid);+// os.c+void _mi_os_init(void); // called from process init+void* _mi_os_alloc(size_t size, mi_memid_t* memid);+void* _mi_os_zalloc(size_t size, mi_memid_t* memid);+void _mi_os_free(void* p, size_t size, mi_memid_t memid);+void _mi_os_free_ex(void* p, size_t size, bool still_committed, mi_memid_t memid, mi_subproc_t* subproc );++size_t _mi_os_page_size(void);+size_t _mi_os_guard_page_size(void);+size_t _mi_os_good_alloc_size(size_t size);+bool _mi_os_has_overcommit(void);+bool _mi_os_has_virtual_reserve(void);+size_t _mi_os_virtual_address_bits(void);+size_t _mi_os_minimal_purge_size(void);++bool _mi_os_reset(void* addr, size_t size);+bool _mi_os_decommit(void* addr, size_t size);+void _mi_os_reuse(void* p, size_t size);+mi_decl_nodiscard bool _mi_os_commit(void* p, size_t size, bool* is_zero);+mi_decl_nodiscard bool _mi_os_commit_ex(void* addr, size_t size, bool* is_zero, size_t stat_size);+mi_decl_nodiscard bool _mi_os_protect(void* addr, size_t size);+bool _mi_os_unprotect(void* addr, size_t size);+bool _mi_os_purge(void* p, size_t size);+bool _mi_os_purge_ex(void* p, size_t size, bool allow_reset, size_t stats_size, mi_commit_fun_t* commit_fun, void* commit_fun_arg);++size_t _mi_os_secure_guard_page_size(void);+bool _mi_os_secure_guard_page_set_at(void* addr, mi_memid_t memid);+bool _mi_os_secure_guard_page_set_before(void* addr, mi_memid_t memid);+bool _mi_os_secure_guard_page_reset_at(void* addr, mi_memid_t memid);+bool _mi_os_secure_guard_page_reset_before(void* addr, mi_memid_t memid);++int _mi_os_numa_node(void);+int _mi_os_numa_node_count(void);++void* _mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, bool allow_large, mi_memid_t* memid);+void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_large, mi_memid_t* memid);++void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size);+bool _mi_os_canuse_large_page(size_t size, size_t alignment);+size_t _mi_os_large_page_size(void);+void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_secs, size_t* pages_reserved, size_t* psize, mi_memid_t* memid);++// threadlocal.c++mi_thread_local_t _mi_thread_local_create(void);+void _mi_thread_local_free( mi_thread_local_t key );+bool _mi_thread_local_set( mi_thread_local_t key, void* val );+void* _mi_thread_local_get( mi_thread_local_t key );+void _mi_thread_locals_init(void);+void _mi_thread_locals_done(void);+void _mi_thread_locals_thread_done(void);// arena.cmi_arena_id_t _mi_arena_id_none(void);-void _mi_arena_free(void* p, size_t size, size_t still_committed_size, mi_memid_t memid);-void* _mi_arena_alloc(size_t size, bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid);-void* _mi_arena_alloc_aligned(size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid);-bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_id_t request_arena_id);-bool _mi_arena_contains(const void* p);-void _mi_arenas_collect(bool force_purge);-void _mi_arena_unsafe_destroy_all(void);--bool _mi_arena_segment_clear_abandoned(mi_segment_t* segment);-void _mi_arena_segment_mark_abandoned(mi_segment_t* segment);--void* _mi_arena_meta_zalloc(size_t size, mi_memid_t* memid);-void _mi_arena_meta_free(void* p, mi_memid_t memid, size_t size);--typedef struct mi_arena_field_cursor_s { // abstract struct- size_t os_list_count; // max entries to visit in the OS abandoned list- size_t start; // start arena idx (may need to be wrapped)- size_t end; // end arena idx (exclusive, may need to be wrapped)- size_t bitmap_idx; // current bit idx for an arena- mi_subproc_t* subproc; // only visit blocks in this sub-process- bool visit_all; // ensure all abandoned blocks are seen (blocking)- bool hold_visit_lock; // if the subproc->abandoned_os_visit_lock is held-} mi_arena_field_cursor_t;-void _mi_arena_field_cursor_init(mi_heap_t* heap, mi_subproc_t* subproc, bool visit_all, mi_arena_field_cursor_t* current);-mi_segment_t* _mi_arena_segment_clear_abandoned_next(mi_arena_field_cursor_t* previous);-void _mi_arena_field_cursor_done(mi_arena_field_cursor_t* current);--// "segment-map.c"-void _mi_segment_map_allocated_at(const mi_segment_t* segment);-void _mi_segment_map_freed_at(const mi_segment_t* segment);-void _mi_segment_map_unsafe_destroy(void);--// "segment.c"-mi_page_t* _mi_segment_page_alloc(mi_heap_t* heap, size_t block_size, size_t page_alignment, mi_segments_tld_t* tld);-void _mi_segment_page_free(mi_page_t* page, bool force, mi_segments_tld_t* tld);-void _mi_segment_page_abandon(mi_page_t* page, mi_segments_tld_t* tld);-bool _mi_segment_try_reclaim_abandoned( mi_heap_t* heap, bool try_all, mi_segments_tld_t* tld);-void _mi_segment_collect(mi_segment_t* segment, bool force);--#if MI_HUGE_PAGE_ABANDON-void _mi_segment_huge_page_free(mi_segment_t* segment, mi_page_t* page, mi_block_t* block);-#else-void _mi_segment_huge_page_reset(mi_segment_t* segment, mi_page_t* page, mi_block_t* block);-#endif--uint8_t* _mi_segment_page_start(const mi_segment_t* segment, const mi_page_t* page, size_t* page_size); // page start for any page-void _mi_abandoned_reclaim_all(mi_heap_t* heap, mi_segments_tld_t* tld);-void _mi_abandoned_collect(mi_heap_t* heap, bool force, mi_segments_tld_t* tld);-bool _mi_segment_attempt_reclaim(mi_heap_t* heap, mi_segment_t* segment);-bool _mi_segment_visit_blocks(mi_segment_t* segment, int heap_tag, bool visit_blocks, mi_block_visit_fun* visitor, void* arg);+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_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(void* p, size_t size, mi_memid_t memid);+bool _mi_arenas_contain(const void* p);+void _mi_arenas_collect(bool force_purge, bool visit_all, mi_tld_t* tld);+void _mi_arenas_unsafe_destroy_all(mi_subproc_t* subproc);++mi_page_t* _mi_arenas_page_alloc(mi_theap_t* theap, size_t block_size, size_t page_alignment);+void _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);++// arena-meta.c+void* _mi_meta_zalloc( size_t size, mi_memid_t* memid );+void _mi_meta_free(void* p, size_t size, mi_memid_t memid);+bool _mi_meta_is_meta_page(void* p);++// "page-map.c"+bool _mi_page_map_init(void);+mi_decl_nodiscard bool _mi_page_map_register(mi_page_t* page);+void _mi_page_map_unregister(mi_page_t* page);+void _mi_page_map_unregister_range(void* start, size_t size);+mi_page_t* _mi_safe_ptr_page(const void* p);+void _mi_page_map_unsafe_destroy(mi_subproc_t* subproc);// "page.c"-void* _mi_malloc_generic(mi_heap_t* heap, size_t size, bool zero, size_t huge_alignment) 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);-void _mi_page_free(mi_page_t* page, mi_page_queue_t* pq, bool force); // free the page-void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq); // abandon the page, to be picked up by another thread...-void _mi_page_force_abandon(mi_page_t* page);--void _mi_heap_delayed_free_all(mi_heap_t* heap);-bool _mi_heap_delayed_free_partial(mi_heap_t* heap);-void _mi_heap_collect_retired(mi_heap_t* heap, bool force);--void _mi_page_use_delayed_free(mi_page_t* page, mi_delayed_t delay, bool override_never);-bool _mi_page_try_use_delayed_free(mi_page_t* page, mi_delayed_t delay, bool override_never);-size_t _mi_page_queue_append(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_queue_t* append);-void _mi_deferred_free(mi_heap_t* heap, bool force);--void _mi_page_free_collect(mi_page_t* page,bool force);-void _mi_page_reclaim(mi_heap_t* heap, mi_page_t* page); // callback from segments--size_t _mi_bin_size(uint8_t bin); // for stats-uint8_t _mi_bin(size_t size); // for stats+void* _mi_malloc_generic(mi_theap_t* theap, size_t size, size_t zero_huge_alignment, size_t* usable) 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);+void _mi_page_free(mi_page_t* page, mi_page_queue_t* pq); // free the page+void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq); // abandon the page, to be picked up by another thread...++size_t _mi_page_queue_append(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_queue_t* append);+void _mi_deferred_free(mi_theap_t* theap, bool force);++void _mi_page_free_collect(mi_page_t* page, bool force);+void _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);+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++// "theap.c"+mi_theap_t* _mi_theap_create(mi_heap_t* heap, mi_tld_t* tld);+void _mi_theap_delete(mi_theap_t* theap);+void _mi_theap_default_set(mi_theap_t* theap);+void _mi_theap_cached_set(mi_theap_t* theap);+void _mi_theap_collect_retired(mi_theap_t* theap, bool force);+bool _mi_theap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg);+void _mi_theap_page_reclaim(mi_theap_t* theap, mi_page_t* page);+void _mi_theap_free(mi_theap_t* theap);// "heap.c"-void _mi_heap_init(mi_heap_t* heap, mi_tld_t* tld, mi_arena_id_t arena_id, bool noreclaim, uint8_t tag);-void _mi_heap_destroy_pages(mi_heap_t* heap);-void _mi_heap_collect_abandon(mi_heap_t* heap);-void _mi_heap_set_default_direct(mi_heap_t* heap);-bool _mi_heap_memid_is_suitable(mi_heap_t* heap, mi_memid_t memid);-void _mi_heap_unsafe_destroy_all(mi_heap_t* heap);-mi_heap_t* _mi_heap_by_tag(mi_heap_t* heap, uint8_t tag);-void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page);-bool _mi_heap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg);+void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page);+mi_decl_cold mi_theap_t* _mi_heap_theap_get_or_init(const mi_heap_t* heap); // get (and possible create) the theap belonging to a heap+mi_decl_cold mi_theap_t* _mi_heap_theap_get_peek(const mi_heap_t* heap); // get the theap for a heap without initializing (and return NULL in that case)+void _mi_heap_move_pages(mi_heap_t* heap_from, mi_heap_t* heap_to); // in "arena.c"+void _mi_heap_destroy_pages(mi_heap_t* heap_from); // in "arena.c"+// "stats.c"-void _mi_stats_done(mi_stats_t* stats);-mi_msecs_t _mi_clock_now(void);-mi_msecs_t _mi_clock_end(mi_msecs_t start);-mi_msecs_t _mi_clock_start(void);+void _mi_stats_init(void);+void _mi_stats_merge_into(mi_stats_t* to, mi_stats_t* from);++mi_msecs_t _mi_clock_now(void);+mi_msecs_t _mi_clock_end(mi_msecs_t start);+mi_msecs_t _mi_clock_start(void);// "alloc.c"-void* _mi_page_malloc_zero(mi_heap_t* heap, mi_page_t* page, size_t size, bool zero) mi_attr_noexcept; // called from `_mi_malloc_generic`-void* _mi_page_malloc(mi_heap_t* heap, mi_page_t* page, size_t size) mi_attr_noexcept; // called from `_mi_heap_malloc_aligned`-void* _mi_page_malloc_zeroed(mi_heap_t* heap, mi_page_t* page, size_t size) mi_attr_noexcept; // called from `_mi_heap_malloc_aligned`-void* _mi_heap_malloc_zero(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept;-void* _mi_heap_malloc_zero_ex(mi_heap_t* heap, size_t size, bool zero, size_t huge_alignment) mi_attr_noexcept; // called from `_mi_heap_malloc_aligned`-void* _mi_heap_realloc_zero(mi_heap_t* heap, void* p, size_t newsize, bool zero) mi_attr_noexcept;-mi_block_t* _mi_page_ptr_unalign(const mi_page_t* page, const void* p);-bool _mi_free_delayed_block(mi_block_t* block);-void _mi_free_generic(mi_segment_t* segment, mi_page_t* page, bool is_local, void* p) mi_attr_noexcept; // for runtime integration-void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const size_t min_size);+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`+void* _mi_theap_malloc_zero(mi_theap_t* theap, size_t size, bool zero, size_t* usable) mi_attr_noexcept;+void* _mi_theap_malloc_zero_ex(mi_theap_t* theap, size_t size, bool zero, size_t huge_alignment, size_t* usable) mi_attr_noexcept; // called from `_mi_theap_malloc_aligned`+void* _mi_theap_realloc_zero(mi_theap_t* theap, void* p, size_t newsize, bool zero, size_t* usable_pre, size_t* usable_post) mi_attr_noexcept;+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);#if MI_DEBUG>1-bool _mi_page_is_valid(mi_page_t* page);+bool _mi_page_is_valid(mi_page_t* page);#endif// -------------------------------------------------------// Branches+// Assertions// -------------------------------------------------------#if defined(__GNUC__) || defined(__clang__)-#define mi_unlikely(x) (__builtin_expect(!!(x),false))-#define mi_likely(x) (__builtin_expect(!!(x),true))-#elif (defined(__cplusplus) && (__cplusplus >= 202002L)) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)-#define mi_unlikely(x) (x) [[unlikely]]-#define mi_likely(x) (x) [[likely]]+#if (MI_DEBUG)+// use our own assertion to print without memory allocation+mi_decl_noreturn mi_decl_cold void _mi_assert_fail(const char* assertion, const char* fname, unsigned int line, const char* func) mi_attr_noexcept;+#define mi_assert(expr) ((expr) ? (void)0 : _mi_assert_fail(#expr,__FILE__,__LINE__,__func__))#else-#define mi_unlikely(x) (x)-#define mi_likely(x) (x)+#define mi_assert(x)#endif-#ifndef __has_builtin-#define __has_builtin(x) 0+#if (MI_DEBUG>1)+#define mi_assert_internal mi_assert+#else+#define mi_assert_internal(x)+#endif++#if (MI_DEBUG>2)+#define mi_assert_expensive mi_assert+#else+#define mi_assert_expensive(x)#endif/* ------------------------------------------------------------ Error codes passed to `_mi_fatal_error`- All are recoverable but EFAULT is a serious error and aborts by default in secure mode.- For portability define undefined error codes using common Unix codes:- <https://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html>+ Statistics (in `stats.c`)----------------------------------------------------------- */-#include <errno.h>-#ifndef EAGAIN // double free-#define EAGAIN (11)-#endif-#ifndef ENOMEM // out of memory-#define ENOMEM (12)-#endif-#ifndef EFAULT // corrupted free-list or meta-data-#define EFAULT (14)-#endif-#ifndef EINVAL // trying to free an invalid pointer-#define EINVAL (22)-#endif-#ifndef EOVERFLOW // count*size overflow-#define EOVERFLOW (75)-#endif++// add to stat keeping track of the peak+void __mi_stat_increase(mi_stat_count_t* stat, size_t amount);+void __mi_stat_decrease(mi_stat_count_t* stat, size_t amount);+void __mi_stat_increase_mt(mi_stat_count_t* stat, size_t amount);+void __mi_stat_decrease_mt(mi_stat_count_t* stat, size_t amount);++// adjust stat in special cases to compensate for double counting (and does not adjust peak values and can decrease the total)+void __mi_stat_adjust_increase(mi_stat_count_t* stat, size_t amount);+void __mi_stat_adjust_decrease(mi_stat_count_t* stat, size_t amount);+void __mi_stat_adjust_increase_mt(mi_stat_count_t* stat, size_t amount);+void __mi_stat_adjust_decrease_mt(mi_stat_count_t* stat, size_t amount);++// counters can just be increased+void __mi_stat_counter_increase(mi_stat_counter_t* stat, size_t amount);+void __mi_stat_counter_increase_mt(mi_stat_counter_t* stat, size_t amount);++#define mi_heap_stat_counter_increase(heap,stat,amount) __mi_stat_counter_increase_mt( &(heap)->stats.stat, amount)+#define mi_heap_stat_increase(heap,stat,amount) __mi_stat_increase_mt( &(heap)->stats.stat, amount)+#define mi_heap_stat_decrease(heap,stat,amount) __mi_stat_decrease_mt( &(heap)->stats.stat, amount)+#define mi_heap_stat_adjust_increase(heap,stat,amnt) __mi_stat_adjust_increase_mt( &(heap)->stats.stat, amnt)+#define mi_heap_stat_adjust_decrease(heap,stat,amnt) __mi_stat_adjust_decrease_mt( &(heap)->stats.stat, amnt)++#define mi_subproc_stat_counter_increase(subproc,stat,amount) __mi_stat_counter_increase_mt( &(subproc)->stats.stat, amount)+#define mi_subproc_stat_increase(subproc,stat,amount) __mi_stat_increase_mt( &(subproc)->stats.stat, amount)+#define mi_subproc_stat_decrease(subproc,stat,amount) __mi_stat_decrease_mt( &(subproc)->stats.stat, amount)+#define mi_subproc_stat_adjust_increase(subproc,stat,amount) __mi_stat_adjust_increase_mt( &(subproc)->stats.stat, amount)+#define mi_subproc_stat_adjust_decrease(subproc,stat,amount) __mi_stat_adjust_decrease_mt( &(subproc)->stats.stat, amount)++#define mi_os_stat_counter_increase(stat,amount) mi_subproc_stat_counter_increase(_mi_subproc(),stat,amount)+#define mi_os_stat_increase(stat,amount) mi_subproc_stat_increase(_mi_subproc(),stat,amount)+#define mi_os_stat_decrease(stat,amount) mi_subproc_stat_decrease(_mi_subproc(),stat,amount)++#define mi_theap_stat_counter_increase(theap,stat,amount) __mi_stat_counter_increase( &(theap)->stats.stat, amount)+#define mi_theap_stat_increase(theap,stat,amount) __mi_stat_increase( &(theap)->stats.stat, amount)+#define mi_theap_stat_decrease(theap,stat,amount) __mi_stat_decrease( &(theap)->stats.stat, amount)+#define mi_theap_stat_adjust_increase(theap,stat,amnt) __mi_stat_adjust_increase( &(theap)->stats.stat, amnt)+#define mi_theap_stat_adjust_decrease(theap,stat,amnt) __mi_stat_adjust_decrease( &(theap)->stats.stat, amnt)+++/* -----------------------------------------------------------+ Options (exposed for the debugger)+----------------------------------------------------------- */+typedef enum mi_option_init_e {+ MI_OPTION_UNINIT, // not yet initialized+ MI_OPTION_DEFAULTED, // not found in the environment, use default value+ MI_OPTION_INITIALIZED // found in environment or set explicitly+} mi_option_init_t;++typedef struct mi_option_desc_s {+ long value; // the value+ mi_option_init_t init; // is it initialized yet? (from the environment)+ mi_option_t option; // for debugging: the option index should match the option+ const char* name; // option name without `mimalloc_` prefix+ const char* legacy_name; // potential legacy option name+} mi_option_desc_t;+/* -----------------------------------------------------------Inlined definitions----------------------------------------------------------- */#define MI_UNUSED(x) (void)(x)-#if (MI_DEBUG>0)+#ifndef NDEBUG#define MI_UNUSED_RELEASE(x)#else#define MI_UNUSED_RELEASE(x) MI_UNUSED(x)@@ -314,6 +426,8 @@ bool _mi_page_is_valid(mi_page_t* page);#define MI_INIT128(x) MI_INIT64(x),MI_INIT64(x)#define MI_INIT256(x) MI_INIT128(x),MI_INIT128(x)+#define MI_INIT74(x) MI_INIT64(x),MI_INIT8(x),x(),x()+#define MI_INIT5(x) MI_INIT4(x),x()#include <string.h>// initialize a local variable to zero; use memset as compilers optimize constant sized memset's@@ -342,7 +456,13 @@ static inline uintptr_t _mi_align_up(uintptr_t sz, size_t alignment) {}}-// Align downwards++// Align a pointer upwards+static inline uint8_t* _mi_align_up_ptr(void* p, size_t alignment) {+ return (uint8_t*)_mi_align_up((uintptr_t)p, alignment);+}++static inline uintptr_t _mi_align_down(uintptr_t sz, size_t alignment) {mi_assert_internal(alignment != 0);uintptr_t mask = alignment - 1;@@ -354,17 +474,10 @@ static inline uintptr_t _mi_align_down(uintptr_t sz, size_t alignment) {}}-// Align a pointer upwards-static inline void* mi_align_up_ptr(void* p, size_t alignment) {- return (void*)_mi_align_up((uintptr_t)p, alignment);-}--// Align a pointer downwardsstatic inline void* mi_align_down_ptr(void* p, size_t alignment) {return (void*)_mi_align_down((uintptr_t)p, alignment);}-// Divide upwards: `s <= _mi_divide_up(s,d)*d < s+d`.static inline uintptr_t _mi_divide_up(uintptr_t size, size_t divider) {mi_assert_internal(divider != 0);@@ -387,7 +500,6 @@ static inline bool mi_mem_is_zero(const void* p, size_t size) {return true;}-// Align a byte size to a size in _machine words_,// i.e. byte size == `wsize*sizeof(void*)`.static inline size_t _mi_wsize_from_size(size_t size) {@@ -412,10 +524,13 @@ static inline bool mi_mul_overflow(size_t count, size_t size, size_t* total) {}#else /* __builtin_umul_overflow is unavailable */static inline bool mi_mul_overflow(size_t count, size_t size, size_t* total) {- #define MI_MUL_COULD_OVERFLOW ((size_t)1 << (4*sizeof(size_t))) // sqrt(SIZE_MAX)- *total = count * size;- // note: gcc/clang optimize this to directly check the overflow flag- return ((size >= MI_MUL_COULD_OVERFLOW || count >= MI_MUL_COULD_OVERFLOW) && size > 0 && (SIZE_MAX / size) < count);+ *total = count*size;+ if mi_likely(((size|count)>>(4*MI_SIZE_SIZE))==0) { // did size and count fit both in the lower half bits of a size_t?+ return false;+ }+ else {+ return (size!=0 && (SIZE_MAX / size) < count);+ }}#endif@@ -425,14 +540,16 @@ static inline bool mi_count_size_overflow(size_t count, size_t size, size_t* tot*total = size;return false;}- else if mi_unlikely(mi_mul_overflow(count, size, total)) {+ else if mi_likely(!mi_mul_overflow(count, size, total)) {+ return false;+ }+ else {#if MI_DEBUG > 0_mi_error_message(EOVERFLOW, "allocation request is too large (%zu * %zu bytes)\n", count, size);#endif*total = SIZE_MAX;return true;}- else return false;}@@ -440,163 +557,171 @@ static inline bool mi_count_size_overflow(size_t count, size_t size, size_t* totHeap functions------------------------------------------------------------------------------------------- */-extern mi_decl_hidden const mi_heap_t _mi_heap_empty; // read-only empty heap, initial value of the thread local default heap+extern mi_decl_hidden const mi_theap_t _mi_theap_empty; // read-only empty theap, initial value of the thread local default theap (in the MI_TLS_MODEL_THREAD_LOCAL)+extern mi_decl_hidden const mi_theap_t _mi_theap_empty_wrong; // read-only empty theap used to signal that a theap for a heap could not be allocated-static inline bool mi_heap_is_backing(const mi_heap_t* heap) {- return (heap->tld->heap_backing == heap);+static inline bool mi_theap_is_initialized(const mi_theap_t* theap) {+ return (theap != NULL && theap->heap != NULL);}-static inline bool mi_heap_is_initialized(mi_heap_t* heap) {- mi_assert_internal(heap != NULL);- return (heap != NULL && heap != &_mi_heap_empty);+static inline mi_page_t* _mi_theap_get_free_small_page(mi_theap_t* theap, size_t size) {+ mi_assert_internal(size <= (MI_SMALL_SIZE_MAX + MI_PADDING_SIZE));+ const size_t idx = _mi_wsize_from_size(size);+ mi_assert_internal(idx < MI_PAGES_DIRECT);+ return theap->pages_free_direct[idx];}-static inline uintptr_t _mi_ptr_cookie(const void* p) {- extern mi_decl_hidden mi_heap_t _mi_heap_main;- mi_assert_internal(_mi_heap_main.cookie != 0);- return ((uintptr_t)p ^ _mi_heap_main.cookie);-}++//static inline uintptr_t _mi_ptr_cookie(const void* p) {+// extern mi_theap_t _mi_theap_main;+// mi_assert_internal(_mi_theap_main.cookie != 0);+// return ((uintptr_t)p ^ _mi_theap_main.cookie);+//}+/* ------------------------------------------------------------ Pages+ The page map maps addresses to `mi_page_t` pointers----------------------------------------------------------- */-static inline mi_page_t* _mi_heap_get_free_small_page(mi_heap_t* heap, size_t size) {- mi_assert_internal(size <= (MI_SMALL_SIZE_MAX + MI_PADDING_SIZE));- const size_t idx = _mi_wsize_from_size(size);- mi_assert_internal(idx < MI_PAGES_DIRECT);- return heap->pages_free_direct[idx];-}--// Segment that contains the pointer-// Large aligned blocks may be aligned at N*MI_SEGMENT_SIZE (inside a huge segment > MI_SEGMENT_SIZE),-// and we need align "down" to the segment info which is `MI_SEGMENT_SIZE` bytes before it;-// therefore we align one byte before `p`.-// We check for NULL afterwards on 64-bit systems to improve codegen for `mi_free`.-static inline mi_segment_t* _mi_ptr_segment(const void* p) {- mi_segment_t* const segment = (mi_segment_t*)(((uintptr_t)p - 1) & ~MI_SEGMENT_MASK);- #if MI_INTPTR_SIZE <= 4- return (p==NULL ? NULL : segment);- #else- return ((intptr_t)segment <= 0 ? NULL : segment);- #endif+#if MI_PAGE_MAP_FLAT++// flat page-map committed on demand, using one byte per slice (64 KiB).+// single indirection and low commit, but large initial virtual reserve (4 GiB with 48 bit virtual addresses)+// used by default on <= 40 bit virtual address spaces.+extern mi_decl_hidden uint8_t* _mi_page_map;++static inline size_t _mi_page_map_index(const void* p) {+ return (size_t)((uintptr_t)p >> MI_ARENA_SLICE_SHIFT);}-static inline mi_page_t* mi_slice_to_page(mi_slice_t* s) {- mi_assert_internal(s->slice_offset== 0 && s->slice_count > 0);- return (mi_page_t*)(s);+static inline mi_page_t* _mi_ptr_page_ex(const void* p, bool* valid) {+ const size_t idx = _mi_page_map_index(p);+ const size_t ofs = _mi_page_map[idx];+ if (valid != NULL) { *valid = (ofs != 0); }+ return (mi_page_t*)((((uintptr_t)p >> MI_ARENA_SLICE_SHIFT) + 1 - ofs) << MI_ARENA_SLICE_SHIFT);}-static inline mi_slice_t* mi_page_to_slice(mi_page_t* p) {- mi_assert_internal(p->slice_offset== 0 && p->slice_count > 0);- return (mi_slice_t*)(p);+static inline mi_page_t* _mi_checked_ptr_page(const void* p) {+ bool valid;+ mi_page_t* const page = _mi_ptr_page_ex(p, &valid);+ return (valid ? page : NULL);}-// Segment belonging to a page-static inline mi_segment_t* _mi_page_segment(const mi_page_t* page) {- mi_assert_internal(page!=NULL);- mi_segment_t* segment = _mi_ptr_segment(page);- mi_assert_internal(segment == NULL || ((mi_slice_t*)page >= segment->slices && (mi_slice_t*)page < segment->slices + segment->slice_entries));- return segment;+static inline mi_page_t* _mi_unchecked_ptr_page(const void* p) {+ return _mi_ptr_page_ex(p, NULL);}-static inline mi_slice_t* mi_slice_first(const mi_slice_t* slice) {- mi_slice_t* start = (mi_slice_t*)((uint8_t*)slice - slice->slice_offset);- mi_assert_internal(start >= _mi_ptr_segment(slice)->slices);- mi_assert_internal(start->slice_offset == 0);- mi_assert_internal(start + start->slice_count > slice);- return start;+#else++// 2-level page map:+// double indirection, but low commit and low virtual reserve.+//+// the page-map is usually 4 MiB (for 48 bit virtual addresses) and points to sub maps of 64 KiB.+// the page-map is committed on-demand (in 64 KiB parts) (and sub-maps are committed on-demand as well)+// one sub page-map = 64 KiB => covers 2^(16-3) * 2^16 = 2^29 = 512 MiB address space+// the page-map needs 48-(16+13) = 19 bits => 2^19 sub map pointers = 2^22 bytes = 4 MiB reserved size.+#define MI_PAGE_MAP_SUB_SHIFT (13)+#define MI_PAGE_MAP_SUB_COUNT (MI_ZU(1) << MI_PAGE_MAP_SUB_SHIFT)+#define MI_PAGE_MAP_SHIFT (MI_MAX_VABITS - MI_PAGE_MAP_SUB_SHIFT - MI_ARENA_SLICE_SHIFT)+#define MI_PAGE_MAP_COUNT (MI_ZU(1) << MI_PAGE_MAP_SHIFT)++typedef mi_page_t** mi_submap_t;+extern mi_decl_hidden _Atomic(mi_submap_t)* _mi_page_map;++static inline size_t _mi_page_map_index(const void* p, size_t* sub_idx) {+ const size_t u = (size_t)((uintptr_t)p / MI_ARENA_SLICE_SIZE);+ if (sub_idx != NULL) { *sub_idx = u % MI_PAGE_MAP_SUB_COUNT; }+ return (u / MI_PAGE_MAP_SUB_COUNT);}-// Get the page containing the pointer (performance critical as it is called in mi_free)-static inline mi_page_t* _mi_segment_page_of(const mi_segment_t* segment, const void* p) {- mi_assert_internal(p > (void*)segment);- ptrdiff_t diff = (uint8_t*)p - (uint8_t*)segment;- mi_assert_internal(diff > 0 && diff <= (ptrdiff_t)MI_SEGMENT_SIZE);- size_t idx = (size_t)diff >> MI_SEGMENT_SLICE_SHIFT;- mi_assert_internal(idx <= segment->slice_entries);- mi_slice_t* slice0 = (mi_slice_t*)&segment->slices[idx];- mi_slice_t* slice = mi_slice_first(slice0); // adjust to the block that holds the page data- mi_assert_internal(slice->slice_offset == 0);- mi_assert_internal(slice >= segment->slices && slice < segment->slices + segment->slice_entries);- return mi_slice_to_page(slice);+static inline mi_submap_t _mi_page_map_at(size_t idx) {+ return mi_atomic_load_ptr_relaxed(mi_page_t*, &_mi_page_map[idx]);}-// Quick page start for initialized pages-static inline uint8_t* mi_page_start(const mi_page_t* page) {- mi_assert_internal(page->page_start != NULL);- mi_assert_expensive(_mi_segment_page_start(_mi_page_segment(page),page,NULL) == page->page_start);- return page->page_start;+static inline mi_page_t* _mi_unchecked_ptr_page(const void* p) {+ size_t sub_idx;+ const size_t idx = _mi_page_map_index(p, &sub_idx);+ return (_mi_page_map_at(idx))[sub_idx]; // NULL if p==NULL+}++static inline mi_page_t* _mi_checked_ptr_page(const void* p) {+ size_t sub_idx;+ const size_t idx = _mi_page_map_index(p, &sub_idx);+ mi_submap_t const sub = _mi_page_map_at(idx);+ if mi_unlikely(sub == NULL) return NULL;+ return sub[sub_idx];}-// Get the page containing the pointer-static inline mi_page_t* _mi_ptr_page(void* p) {- mi_assert_internal(p!=NULL);- return _mi_segment_page_of(_mi_ptr_segment(p), p);+#endif+++static inline mi_page_t* _mi_ptr_page(const void* p) {+ mi_assert_internal(p==NULL || mi_is_in_heap_region(p));+ #if MI_DEBUG || MI_SECURE || defined(__APPLE__)+ return _mi_checked_ptr_page(p);+ #else+ return _mi_unchecked_ptr_page(p);+ #endif}-// Get the block size of a page (special case for huge objects)++// Get the block size of a pagestatic inline size_t mi_page_block_size(const mi_page_t* page) {mi_assert_internal(page->block_size > 0);return page->block_size;}-static inline bool mi_page_is_huge(const mi_page_t* page) {- mi_assert_internal((page->is_huge && _mi_page_segment(page)->kind == MI_SEGMENT_HUGE) ||- (!page->is_huge && _mi_page_segment(page)->kind != MI_SEGMENT_HUGE));- return page->is_huge;+// Page start+static inline uint8_t* mi_page_start(const mi_page_t* page) {+ return page->page_start;}-// 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 size_t mi_page_size(const mi_page_t* page) {+ return mi_page_block_size(page) * page->reserved;}-// size of a segment-static inline size_t mi_segment_size(mi_segment_t* segment) {- return segment->segment_slices * MI_SEGMENT_SLICE_SIZE;+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 uint8_t* mi_segment_end(mi_segment_t* segment) {- return (uint8_t*)segment + mi_segment_size(segment);+static inline size_t mi_page_info_size(void) {+ return _mi_align_up(sizeof(mi_page_t), MI_MAX_ALIGN_SIZE);}-// Thread free access-static inline mi_block_t* mi_page_thread_free(const mi_page_t* page) {- return (mi_block_t*)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free) & ~3);+static inline bool mi_page_contains_address(const mi_page_t* page, const void* p) {+ size_t psize;+ uint8_t* start = mi_page_area(page, &psize);+ return (start <= (uint8_t*)p && (uint8_t*)p < start + psize);}-static inline mi_delayed_t mi_page_thread_free_flag(const mi_page_t* page) {- return (mi_delayed_t)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xthread_free) & 3);+static inline bool mi_page_is_in_arena(const mi_page_t* page) {+ return (page->memid.memkind == MI_MEM_ARENA);}-// Heap access-static inline mi_heap_t* mi_page_heap(const mi_page_t* page) {- return (mi_heap_t*)(mi_atomic_load_relaxed(&((mi_page_t*)page)->xheap));+static inline bool mi_page_is_singleton(const mi_page_t* page) {+ return (page->reserved == 1);}-static inline void mi_page_set_heap(mi_page_t* page, mi_heap_t* heap) {- mi_assert_internal(mi_page_thread_free_flag(page) != MI_DELAYED_FREEING);- mi_atomic_store_release(&page->xheap,(uintptr_t)heap);- if (heap != NULL) { page->heap_tag = heap->tag; }+// 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;}-// Thread free flag helpers-static inline mi_block_t* mi_tf_block(mi_thread_free_t tf) {- return (mi_block_t*)(tf & ~0x03);-}-static inline mi_delayed_t mi_tf_delayed(mi_thread_free_t tf) {- return (mi_delayed_t)(tf & 0x03);+// This may change if we locate page info outside the page data slices+static inline uint8_t* mi_page_slice_start(const mi_page_t* page) {+ return (uint8_t*)page;}-static inline mi_thread_free_t mi_tf_make(mi_block_t* block, mi_delayed_t delayed) {- return (mi_thread_free_t)((uintptr_t)block | (uintptr_t)delayed);-}-static inline mi_thread_free_t mi_tf_set_delayed(mi_thread_free_t tf, mi_delayed_t delayed) {- return mi_tf_make(mi_tf_block(tf),delayed);++// This gives the offset relative to the start slice of a page. This may change if we ever+// locate page info outside the page-data itself.+static inline size_t mi_page_slice_offset_of(const mi_page_t* page, size_t offset_relative_to_page_start) {+ return (page->page_start - mi_page_slice_start(page)) + offset_relative_to_page_start;}-static inline mi_thread_free_t mi_tf_set_block(mi_thread_free_t tf, mi_block_t* block) {- return mi_tf_make(block, mi_tf_delayed(tf));++static inline size_t mi_page_committed(const mi_page_t* page) {+ return (page->slice_committed == 0 ? mi_page_size(page) : page->slice_committed - (page->page_start - mi_page_slice_start(page)));}// are all blocks in a page freed?@@ -606,18 +731,27 @@ static inline bool mi_page_all_free(const mi_page_t* page) {return (page->used == 0);}-// 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 (page->used < page->reserved || (mi_page_thread_free(page) != NULL));-}-// 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(mi_page_t* page) {+ const bool full = (page->reserved == page->used);+ mi_assert_internal(!full || page->free == NULL);+ return full;+}+// is more than 7/8th of a page in use?static inline bool mi_page_is_mostly_used(const mi_page_t* page) {if (page==NULL) return true;@@ -625,61 +759,195 @@ static inline bool mi_page_is_mostly_used(const mi_page_t* page) {return (page->reserved - page->used <= frac);}-static inline mi_page_queue_t* mi_page_queue(const mi_heap_t* heap, size_t size) {- return &((mi_heap_t*)heap)->pages[_mi_bin(size)];+// is more than (n-1)/n'th of a page in use?+static inline bool mi_page_is_used_at_frac(const mi_page_t* page, uint16_t n) {+ if (page==NULL) return true;+ uint16_t frac = page->reserved / n;+ return (page->reserved - page->used <= frac);+}+++static inline bool mi_page_is_huge(const mi_page_t* page) {+ return (mi_page_is_singleton(page) &&+ (page->block_size > MI_LARGE_MAX_OBJ_SIZE ||+ (mi_memkind_is_os(page->memid.memkind) && page->memid.mem.os.base < (void*)page)));}+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;+}//------------------------------------------------------------// Page flags+// Page thread id and flags//-----------------------------------------------------------++// Thread id of thread that owns this page (with flags in the bottom 2 bits)+static inline mi_threadid_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_threadid_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 void mi_page_flags_set(mi_page_t* page, bool set, mi_page_flags_t newflag) {+ if (set) { mi_atomic_or_relaxed(&page->xthread_id, newflag); }+ else { mi_atomic_and_relaxed(&page->xthread_id, ~newflag); }+}+static inline bool mi_page_is_in_full(const mi_page_t* page) {- return page->flags.x.in_full;+ 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) {- page->flags.x.in_full = in_full;+ mi_page_flags_set(page, in_full, MI_PAGE_IN_FULL_QUEUE);+}++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);+}++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_threadid_t tid = (theap == NULL ? MI_THREADID_ABANDONED : theap->tld->thread_id);+ mi_assert_internal((tid & MI_PAGE_FLAG_MASK) == 0);++ // we need to use an atomic cas since a concurrent thread may still set the MI_PAGE_HAS_INTERIOR_POINTERS flag (see `alloc_aligned.c`).+ mi_threadid_t xtid_old = mi_page_xthread_id(page);+ mi_threadid_t xtid;+ do {+ xtid = tid | (xtid_old & MI_PAGE_FLAG_MASK);+ } while (!mi_atomic_cas_weak_release(&page->xthread_id, &xtid_old, xtid));}-static inline bool mi_page_has_aligned(const mi_page_t* page) {- return page->flags.x.has_aligned;+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_THREADID_ABANDONED_MAPPED);}-static inline void mi_page_set_has_aligned(mi_page_t* page, bool has_aligned) {- page->flags.x.has_aligned = has_aligned;+static inline bool mi_page_is_abandoned_mapped(const mi_page_t* page) {+ return (mi_page_thread_id(page) == MI_THREADID_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_THREADID_ABANDONED_MAPPED);+}++static inline void mi_page_clear_abandoned_mapped(mi_page_t* page) {+ mi_assert_internal(mi_page_is_abandoned_mapped(page));+ mi_atomic_and_relaxed(&page->xthread_id, MI_PAGE_FLAG_MASK);+}+++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);+ 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;+ // we use NULL for the main heap to make `_mi_page_get_associated_theap` fast in `free.c:mi_abandoned_page_try_reclaim`.+ if mi_likely(heap==NULL) heap = mi_heap_main();+ mi_assert_internal(heap != NULL);+ return heap;+}++//-----------------------------------------------------------+// 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) {+ return (mi_thread_free_t)((uintptr_t)block | (owned ? 1 : 0));+}++// 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 (page->used < 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, 1);+ return ((old&1)==0);+}++/* -------------------------------------------------------------------Guarded objects------------------------------------------------------------------- */#if MI_GUARDED++// we always align guarded pointers in a block at an offset+// the block `next` field is then used as a tag to distinguish regular offset aligned blocks from guarded ones+#define MI_BLOCK_TAG_ALIGNED ((mi_encoded_t)(0))+#define MI_BLOCK_TAG_GUARDED (~MI_BLOCK_TAG_ALIGNED)+static inline bool mi_block_ptr_is_guarded(const mi_block_t* block, const void* p) {const ptrdiff_t offset = (uint8_t*)p - (uint8_t*)block;return (offset >= (ptrdiff_t)(sizeof(mi_block_t)) && block->next == MI_BLOCK_TAG_GUARDED);}-static inline bool mi_heap_malloc_use_guarded(mi_heap_t* heap, size_t size) {+static inline bool mi_theap_malloc_use_guarded(mi_theap_t* theap, size_t size) {// this code is written to result in fast assembly as it is on the hot path for allocation- const size_t count = heap->guarded_sample_count - 1; // if the rate was 0, this will underflow and count for a long time..+ const size_t count = theap->guarded_sample_count - 1; // if the rate was 0, this will underflow and count for a long time..if mi_likely(count != 0) {// no sample- heap->guarded_sample_count = count;+ theap->guarded_sample_count = count;return false;}- else if (size >= heap->guarded_size_min && size <= heap->guarded_size_max) {+ else if (size >= theap->guarded_size_min && size <= theap->guarded_size_max) {// use guarded allocation- heap->guarded_sample_count = heap->guarded_sample_rate; // reset- return (heap->guarded_sample_rate != 0);+ theap->guarded_sample_count = theap->guarded_sample_rate; // reset+ return (theap->guarded_sample_rate != 0);}else {- // failed size criteria, rewind count (but don't write to an empty heap)- if (heap->guarded_sample_rate != 0) { heap->guarded_sample_count = 1; }+ // failed size criteria, rewind count (but don't write to an empty theap)+ if (theap->guarded_sample_rate != 0) { theap->guarded_sample_count = 1; }return false;}}-mi_decl_restrict void* _mi_heap_malloc_guarded(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept;+mi_decl_restrict void* _mi_theap_malloc_guarded(mi_theap_t* theap, size_t size, bool zero) mi_attr_noexcept;#endif@@ -709,27 +977,10 @@ We also pass a separate `null` value to be used as `NULL` or otherwise`(k2<<<k1)+k1` would appear (too) often as a sentinel value.------------------------------------------------------------------- */-static inline bool mi_is_in_same_segment(const void* p, const void* q) {- return (_mi_ptr_segment(p) == _mi_ptr_segment(q));-}-static inline bool mi_is_in_same_page(const void* p, const void* q) {- mi_segment_t* segment = _mi_ptr_segment(p);- if (_mi_ptr_segment(q) != segment) return false;- // assume q may be invalid // return (_mi_segment_page_of(segment, p) == _mi_segment_page_of(segment, q));- mi_page_t* page = _mi_segment_page_of(segment, p);- size_t psize;- uint8_t* start = _mi_segment_page_start(segment, page, &psize);- return (start <= (uint8_t*)q && (uint8_t*)q < start + psize);-}--static inline uintptr_t mi_rotl(uintptr_t x, uintptr_t shift) {- shift %= MI_INTPTR_BITS;- return (shift==0 ? x : ((x << shift) | (x >> (MI_INTPTR_BITS - shift))));-}-static inline uintptr_t mi_rotr(uintptr_t x, uintptr_t shift) {- shift %= MI_INTPTR_BITS;- return (shift==0 ? x : ((x >> shift) | (x << (MI_INTPTR_BITS - shift))));+ mi_page_t* page = _mi_ptr_page(p);+ return mi_page_contains_address(page,q);+ // return (_mi_ptr_page(p) == _mi_ptr_page(q));}static inline void* mi_ptr_decode(const void* null, const mi_encoded_t x, const uintptr_t* keys) {@@ -745,7 +996,7 @@ static inline mi_encoded_t mi_ptr_encode(const void* null, const void* p, conststatic inline uint32_t mi_ptr_encode_canary(const void* null, const void* p, const uintptr_t* keys) {const uint32_t x = (uint32_t)(mi_ptr_encode(null,p,keys));// make the lowest byte 0 to prevent spurious read overflows which could be a security issue (issue #951)- #ifdef MI_BIG_ENDIAN+ #if MI_BIG_ENDIANreturn (x & 0x00FFFFFF);#elsereturn (x & 0xFFFFFF00);@@ -801,50 +1052,20 @@ static inline void mi_block_set_next(const mi_page_t* page, mi_block_t* block, c#endif}+/* -----------------------------------------------------------+ arena blocks+----------------------------------------------------------- */-// --------------------------------------------------------------------// commit mask-// ---------------------------------------------------------------------static inline void mi_commit_mask_create_empty(mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- cm->mask[i] = 0;- }-}--static inline void mi_commit_mask_create_full(mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- cm->mask[i] = ~((size_t)0);- }-}--static inline bool mi_commit_mask_is_empty(const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- if (cm->mask[i] != 0) return false;- }- return true;+// Blocks needed for a given byte size+static inline size_t mi_slice_count_of_size(size_t size) {+ return _mi_divide_up(size, MI_ARENA_SLICE_SIZE);}-static inline bool mi_commit_mask_is_full(const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- if (cm->mask[i] != ~((size_t)0)) return false;- }- return true;+// Byte size of a number of blocks+static inline size_t mi_size_of_slices(size_t bcount) {+ return (bcount * MI_ARENA_SLICE_SIZE);}-// defined in `segment.c`:-size_t _mi_commit_mask_committed_size(const mi_commit_mask_t* cm, size_t total);-size_t _mi_commit_mask_next_run(const mi_commit_mask_t* cm, size_t* idx);--#define mi_commit_mask_foreach(cm,idx,count) \- idx = 0; \- while ((count = _mi_commit_mask_next_run(cm,&idx)) > 0) {--#define mi_commit_mask_foreach_end() \- idx += count; \- }--/* -----------------------------------------------------------memory id's@@ -861,14 +1082,27 @@ static inline mi_memid_t _mi_memid_none(void) {return _mi_memid_create(MI_MEM_NONE);}-static inline mi_memid_t _mi_memid_create_os(bool committed, bool is_zero, bool is_large) {+static inline mi_memid_t _mi_memid_create_os(void* base, size_t size, bool committed, bool is_zero, bool is_large) {mi_memid_t memid = _mi_memid_create(MI_MEM_OS);+ memid.mem.os.base = base;+ memid.mem.os.size = size;memid.initially_committed = committed;memid.initially_zero = is_zero;memid.is_pinned = is_large;return memid;}+static inline mi_memid_t _mi_memid_create_meta(void* mpage, size_t block_idx, size_t block_count) {+ mi_memid_t memid = _mi_memid_create(MI_MEM_META);+ memid.mem.meta.meta_page = mpage;+ memid.mem.meta.block_index = (uint32_t)block_idx;+ memid.mem.meta.block_count = (uint32_t)block_count;+ memid.initially_committed = true;+ memid.initially_zero = true;+ memid.is_pinned = true;+ return memid;+}+// -------------------------------------------------------------------// Fast "random" shuffle@@ -894,177 +1128,65 @@ static inline uintptr_t _mi_random_shuffle(uintptr_t x) {return x;}-// --------------------------------------------------------------------// Optimize numa node access for the common case (= one node)-// ---------------------------------------------------------------------int _mi_os_numa_node_get(void);-size_t _mi_os_numa_node_count_get(void);--extern mi_decl_hidden _Atomic(size_t) _mi_numa_node_count;-static inline int _mi_os_numa_node(void) {- if mi_likely(mi_atomic_load_relaxed(&_mi_numa_node_count) == 1) { return 0; }- else return _mi_os_numa_node_get();-}-static inline size_t _mi_os_numa_node_count(void) {- const size_t count = mi_atomic_load_relaxed(&_mi_numa_node_count);- if mi_likely(count > 0) { return count; }- else return _mi_os_numa_node_count_get();-}----// ------------------------------------------------------------------------// Count bits: trailing or leading zeros (with MI_INTPTR_BITS on all zero)-// -------------------------------------------------------------------------#if defined(__GNUC__)-#include <limits.h> // LONG_MAX-#define MI_HAVE_FAST_BITSCAN-static inline size_t mi_clz(uintptr_t x) {- if (x==0) return MI_INTPTR_BITS;-#if (INTPTR_MAX == LONG_MAX)- return __builtin_clzl(x);-#else- return __builtin_clzll(x);-#endif-}-static inline size_t mi_ctz(uintptr_t x) {- if (x==0) return MI_INTPTR_BITS;-#if (INTPTR_MAX == LONG_MAX)- return __builtin_ctzl(x);-#else- return __builtin_ctzll(x);-#endif-}--#elif defined(_MSC_VER)+// ---------------------------------------------------------------------------------+// Provide our own `_mi_memcpy/set` for potential performance optimizations.+//+// For now, only on x64/x86 we optimize to `rep movsb/stosb`.+// Generally, we check for "fast short rep movsb/stosb" (FSRM/FSRS) or "fast enhanced rep movsb" (ERMS) support+// (AMD Zen3+ (~2020) or Intel Ice Lake+ (~2017). See also issue #201 and pr #253.+// Todo: we see improvements on win32 but less with glibc; we might want to only enable this on windows.+// ----------------------------------------------------------------------------------#include <limits.h> // LONG_MAX-#include <intrin.h> // BitScanReverse64-#define MI_HAVE_FAST_BITSCAN-static inline size_t mi_clz(uintptr_t x) {- if (x==0) return MI_INTPTR_BITS;- unsigned long idx;-#if (INTPTR_MAX == LONG_MAX)- _BitScanReverse(&idx, x);-#else- _BitScanReverse64(&idx, x);-#endif- return ((MI_INTPTR_BITS - 1) - idx);-}-static inline size_t mi_ctz(uintptr_t x) {- if (x==0) return MI_INTPTR_BITS;- unsigned long idx;-#if (INTPTR_MAX == LONG_MAX)- _BitScanForward(&idx, x);-#else- _BitScanForward64(&idx, x);-#endif- return idx;-}+#if !MI_TRACK_ENABLED && (MI_ARCH_X64 || MI_ARCH_X86) && (defined(_WIN32) || defined(__GNUC__))-#else+extern mi_decl_hidden size_t _mi_cpu_movsb_max; // in init.c+extern mi_decl_hidden size_t _mi_cpu_stosb_max;-static inline size_t mi_ctz_generic32(uint32_t x) {- // de Bruijn multiplication, see <http://supertech.csail.mit.edu/papers/debruijn.pdf>- static const uint8_t debruijn[32] = {- 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,- 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9- };- if (x==0) return 32;- return debruijn[(uint32_t)((x & -(int32_t)x) * (uint32_t)(0x077CB531U)) >> 27];-}--static inline size_t mi_clz_generic32(uint32_t x) {- // de Bruijn multiplication, see <http://supertech.csail.mit.edu/papers/debruijn.pdf>- static const uint8_t debruijn[32] = {- 31, 22, 30, 21, 18, 10, 29, 2, 20, 17, 15, 13, 9, 6, 28, 1,- 23, 19, 11, 3, 16, 14, 7, 24, 12, 4, 8, 25, 5, 26, 27, 0- };- if (x==0) return 32;- x |= x >> 1;- x |= x >> 2;- x |= x >> 4;- x |= x >> 8;- x |= x >> 16;- return debruijn[(uint32_t)(x * (uint32_t)(0x07C4ACDDU)) >> 27];-}--static inline size_t mi_ctz(size_t x) {- if (x==0) return MI_SIZE_BITS;- #if (MI_SIZE_BITS <= 32)- return mi_ctz_generic32((uint32_t)x);+static inline void mi_rep_movsb(void* dst, const void* src, size_t n) {+ #if defined(__GNUC__)+ __asm volatile("rep movsb" : "+D"(dst), "+c"(n), "+S"(src) : : "memory");#else- const uint32_t lo = (uint32_t)x;- if (lo != 0) {- return mi_ctz_generic32(lo);- }- else {- return (32 + mi_ctz_generic32((uint32_t)(x>>32)));- }+ __movsb((unsigned char*)dst, (const unsigned char*)src, n);#endif}-static inline size_t mi_clz(size_t x) {- if (x==0) return MI_SIZE_BITS;- #if (MI_SIZE_BITS <= 32)- return mi_clz_generic32((uint32_t)x);+static inline void mi_rep_stosb(void* dst, uint8_t val, size_t n) {+ #if defined(__GNUC__)+ __asm volatile("rep stosb" : "+D"(dst), "+c"(n) : "a"(val) : "memory");#else- const uint32_t hi = (uint32_t)(x>>32);- if (hi != 0) {- return mi_clz_generic32(hi);- }- else {- return 32 + mi_clz_generic32((uint32_t)x);- }+ __stosb((unsigned char*)dst, val, n);#endif}-#endif--// "bit scan reverse": Return index of the highest bit (or MI_INTPTR_BITS if `x` is zero)-static inline size_t mi_bsr(uintptr_t x) {- return (x==0 ? MI_INTPTR_BITS : MI_INTPTR_BITS - 1 - mi_clz(x));-}---// ----------------------------------------------------------------------------------// Provide our own `_mi_memcpy` for potential performance optimizations.-//-// For now, only on Windows with msvc/clang-cl we optimize to `rep movsb` if-// we happen to run on x86/x64 cpu's that have "fast short rep movsb" (FSRM) support-// (AMD Zen3+ (~2020) or Intel Ice Lake+ (~2017). See also issue #201 and pr #253.-// -----------------------------------------------------------------------------------#if !MI_TRACK_ENABLED && defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))-#include <intrin.h>-extern bool _mi_cpu_has_fsrm;-extern bool _mi_cpu_has_erms;static inline void _mi_memcpy(void* dst, const void* src, size_t n) {- if ((_mi_cpu_has_fsrm && n <= 128) || (_mi_cpu_has_erms && n > 128)) {- __movsb((unsigned char*)dst, (const unsigned char*)src, n);+ if mi_likely(n <= _mi_cpu_movsb_max) { // has fsrm && n <= 127 (todo: and maybe has erms?)+ mi_rep_movsb(dst, src, n);}else {memcpy(dst, src, n);}}-static inline void _mi_memzero(void* dst, size_t n) {- if ((_mi_cpu_has_fsrm && n <= 128) || (_mi_cpu_has_erms && n > 128)) {- __stosb((unsigned char*)dst, 0, n);++static inline void _mi_memset(void* dst, int val, size_t n) {+ if mi_likely(n <= _mi_cpu_stosb_max) { // has fsrs && n <= 127+ mi_rep_stosb(dst, (uint8_t)val, n);}else {- memset(dst, 0, n);+ memset(dst, val, n);}}+#else+static inline void _mi_memcpy(void* dst, const void* src, size_t n) {memcpy(dst, src, n);}-static inline void _mi_memzero(void* dst, size_t n) {- memset(dst, 0, n);++static inline void _mi_memset(void* dst, int val, size_t n) {+ memset(dst, val, n);}+#endif// -------------------------------------------------------------------------------@@ -1073,6 +1195,7 @@ static inline void _mi_memzero(void* dst, size_t n) {// -------------------------------------------------------------------------------#if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__)+// On GCC/CLang we provide a hint that the pointers are word aligned.static inline void _mi_memcpy_aligned(void* dst, const void* src, size_t n) {mi_assert_internal(((uintptr_t)dst % MI_INTPTR_SIZE == 0) && ((uintptr_t)src % MI_INTPTR_SIZE == 0));@@ -1081,23 +1204,35 @@ static inline void _mi_memcpy_aligned(void* dst, const void* src, size_t n) {_mi_memcpy(adst, asrc, n);}-static inline void _mi_memzero_aligned(void* dst, size_t n) {+static inline void _mi_memset_aligned(void* dst, int val, size_t n) {mi_assert_internal((uintptr_t)dst % MI_INTPTR_SIZE == 0);void* adst = __builtin_assume_aligned(dst, MI_INTPTR_SIZE);- _mi_memzero(adst, n);+ _mi_memset(adst, val, n);}+#else+// Default fallback on `_mi_memcpy`static inline void _mi_memcpy_aligned(void* dst, const void* src, size_t n) {mi_assert_internal(((uintptr_t)dst % MI_INTPTR_SIZE == 0) && ((uintptr_t)src % MI_INTPTR_SIZE == 0));_mi_memcpy(dst, src, n);}-static inline void _mi_memzero_aligned(void* dst, size_t n) {+static inline void _mi_memset_aligned(void* dst, int val, size_t n) {mi_assert_internal((uintptr_t)dst % MI_INTPTR_SIZE == 0);- _mi_memzero(dst, n);+ _mi_memset(dst, val, n);}+#endif+static inline void _mi_memzero(void* dst, size_t n) {+ _mi_memset(dst, 0, n);+}-#endif+static inline void _mi_memzero_aligned(void* dst, size_t n) {+ _mi_memset_aligned(dst, 0, n);+}++++#endif // MI_INTERNAL_Hdiff --git a/vendored/mimalloc/include/mimalloc/prim.h b/vendored/mimalloc/include/mimalloc/prim.hindex 606b71994..75ad758e8 100644--- a/vendored/mimalloc/include/mimalloc/prim.h+++ b/vendored/mimalloc/include/mimalloc/prim.h@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2024, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -7,7 +7,7 @@ terms of the MIT license. A copy of the license can be found in the file#pragma once#ifndef MIMALLOC_PRIM_H#define MIMALLOC_PRIM_H-+#include "internal.h" // mi_decl_hidden// --------------------------------------------------------------------------// This file specifies the primitive portability API.@@ -22,14 +22,15 @@ terms of the MIT license. A copy of the license can be found in the file// OS memory configurationtypedef struct mi_os_mem_config_s {- size_t page_size; // default to 4KiB- size_t large_page_size; // 0 if not supported, usually 2MiB (4MiB on Windows)- size_t alloc_granularity; // smallest allocation size (usually 4KiB, on Windows 64KiB)- size_t physical_memory; // physical memory size- size_t virtual_address_bits; // usually 48 or 56 bits on 64-bit systems. (used to determine secure randomization)- bool has_overcommit; // can we reserve more memory than can be actually committed?- bool has_partial_free; // can allocated blocks be freed partially? (true for mmap, false for VirtualAlloc)- bool has_virtual_reserve; // supports virtual address space reservation? (if true we can reserve virtual address space without using commit or physical memory)+ size_t page_size; // default to 4KiB+ size_t large_page_size; // 0 if not supported, usually 2MiB (4MiB on Windows)+ size_t alloc_granularity; // smallest allocation size (usually 4KiB, on Windows 64KiB)+ size_t physical_memory_in_kib; // physical memory size in KiB+ size_t virtual_address_bits; // usually 48 or 56 bits on 64-bit systems. (used to determine secure randomization)+ bool has_overcommit; // can we reserve more memory than can be actually committed?+ bool has_partial_free; // can allocated blocks be freed partially? (true for mmap, false for VirtualAlloc)+ bool has_virtual_reserve; // supports virtual address space reservation? (if true we can reserve virtual address space without using commit or physical memory)+ bool has_transparent_huge_pages; // true if transparent huge pages are enabled (on Linux)} mi_os_mem_config_t;// Initialize@@ -59,10 +60,15 @@ int _mi_prim_commit(void* addr, size_t size, bool* is_zero);// pre: needs_recommit != NULLint _mi_prim_decommit(void* addr, size_t size, bool* needs_recommit);-// Reset memory. The range keeps being accessible but the content might be reset.+// Reset memory. The range keeps being accessible but the content might be reset to zero at any moment.// Returns error code or 0 on success.int _mi_prim_reset(void* addr, size_t size);+// Reuse memory. This is called for memory that is already committed but+// may have been reset (`_mi_prim_reset`) or decommitted (`_mi_prim_decommit`) where `needs_recommit` was false.+// Returns error code or 0 on success. On most platforms this is a no-op.+int _mi_prim_reuse(void* addr, size_t size);+// Protect memory. Returns error code or 0 on success.int _mi_prim_protect(void* addr, size_t size, bool protect);@@ -114,17 +120,17 @@ void _mi_prim_thread_init_auto_done(void);// Called on process exit and may take action to clean up resources associated with the thread auto done.void _mi_prim_thread_done_auto_done(void);-// Called when the default heap for a thread changes-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap);--+// Called when the default theap for a thread changes+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap);+// Is this thread part of a thread pool?+bool _mi_prim_thread_is_in_threadpool(void);//-------------------------------------------------------------------// Access to TLS (thread local storage) slots.// We need fast access to both a unique thread id (in `free.c:mi_free`) and-// to a thread-local heap pointer (in `alloc.c:mi_malloc`).+// to a thread-local theap pointer (in `alloc.c:mi_malloc`).// To achieve this we use specialized code for various platforms.//-------------------------------------------------------------------@@ -135,21 +141,28 @@ void _mi_prim_thread_associate_default_heap(mi_heap_t* heap);//// Note: we would like to prefer `__builtin_thread_pointer()` nowadays instead of using assembly,// but unfortunately we can not detect support reliably (see issue #883)-// We also use it on Apple OS as we use a TLS slot for the default heap there.-#if defined(__GNUC__) && ( \+// We also use it on Apple OS as we use a TLS slot for the default theap there.+#if (defined(_WIN32)) || \+ (defined(__GNUC__) && ( \(defined(__GLIBC__) && (defined(__x86_64__) || defined(__i386__) || (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__))) \|| (defined(__APPLE__) && (defined(__x86_64__) || defined(__aarch64__) || defined(__POWERPC__))) \|| (defined(__BIONIC__) && (defined(__x86_64__) || defined(__i386__) || (defined(__arm__) && __ARM_ARCH >= 7) || defined(__aarch64__))) \|| (defined(__FreeBSD__) && (defined(__x86_64__) || defined(__i386__) || defined(__aarch64__))) \|| (defined(__OpenBSD__) && (defined(__x86_64__) || defined(__i386__) || defined(__aarch64__))) \- )--#define MI_HAS_TLS_SLOT 1+ ))static inline void* mi_prim_tls_slot(size_t slot) mi_attr_noexcept {void* res;const size_t ofs = (slot*sizeof(void*));- #if defined(__i386__)+ #if defined(_WIN32)+ #if (_M_X64 || _M_AMD64) && !defined(_M_ARM64EC)+ res = (void*)__readgsqword((unsigned long)ofs); // direct load at offset from gs+ #elif _M_IX86 && !defined(_M_ARM64EC)+ res = (void*)__readfsdword((unsigned long)ofs); // direct load at offset from fs+ #else+ res = ((void**)NtCurrentTeb())[slot]; MI_UNUSED(ofs);+ #endif+ #elif defined(__i386__)__asm__("movl %%gs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // x86 32-bit always uses GS#elif defined(__APPLE__) && defined(__x86_64__)__asm__("movq %%gs:%1, %0" : "=r" (res) : "m" (*((void**)ofs)) : ); // x86_64 macOSX uses GS@@ -172,14 +185,24 @@ static inline void* mi_prim_tls_slot(size_t slot) mi_attr_noexcept {#elif defined(__APPLE__) && defined(__POWERPC__) // ppc, issue #781MI_UNUSED(ofs);res = pthread_getspecific(slot);+ #else+ #define MI_HAS_TLS_SLOT 0+ MI_UNUSED(ofs);+ res = NULL;#endifreturn res;}+#ifndef MI_HAS_TLS_SLOT+#define MI_HAS_TLS_SLOT 1+#endif+// setting a tls slot is only used on macOS for nowstatic inline void mi_prim_tls_slot_set(size_t slot, void* value) mi_attr_noexcept {const size_t ofs = (slot*sizeof(void*));- #if defined(__i386__)+ #if defined(_WIN32)+ ((void**)NtCurrentTeb())[slot] = value; MI_UNUSED(ofs);+ #elif defined(__i386__)__asm__("movl %1,%%gs:%0" : "=m" (*((void**)ofs)) : "rn" (value) : ); // 32-bit always uses GS#elif defined(__APPLE__) && defined(__x86_64__)__asm__("movq %1,%%gs:%0" : "=m" (*((void**)ofs)) : "rn" (value) : ); // x86_64 macOS uses GS@@ -202,43 +225,18 @@ static inline void mi_prim_tls_slot_set(size_t slot, void* value) mi_attr_noexce#elif defined(__APPLE__) && defined(__POWERPC__) // ppc, issue #781MI_UNUSED(ofs);pthread_setspecific(slot, value);- #endif-}--#elif _WIN32 && MI_WIN_USE_FIXED_TLS && !defined(MI_WIN_USE_FLS)--// On windows we can store the thread-local heap at a fixed TLS slot to avoid-// thread-local initialization checks in the fast path. This uses a fixed location-// in the TCB though (last user-reserved slot by default) which may clash with other applications.--#define MI_HAS_TLS_SLOT 2 // 2 = we can reliably initialize the slot (saving a test on each malloc)--#if MI_WIN_USE_FIXED_TLS > 1-#define MI_TLS_SLOT (MI_WIN_USE_FIXED_TLS)-#elif MI_SIZE_SIZE == 4-#define MI_TLS_SLOT (0x710) // Last user-reserved slot <https://en.wikipedia.org/wiki/Win32_Thread_Information_Block>-// #define MI_TLS_SLOT (0xF0C) // Last TlsSlot (might clash with other app reserved slot)-#else-#define MI_TLS_SLOT (0x888) // Last user-reserved slot <https://en.wikipedia.org/wiki/Win32_Thread_Information_Block>-// #define MI_TLS_SLOT (0x1678) // Last TlsSlot (might clash with other app reserved slot)-#endif--static inline void* mi_prim_tls_slot(size_t slot) mi_attr_noexcept {- #if (_M_X64 || _M_AMD64) && !defined(_M_ARM64EC)- return (void*)__readgsqword((unsigned long)slot); // direct load at offset from gs- #elif _M_IX86 && !defined(_M_ARM64EC)- return (void*)__readfsdword((unsigned long)slot); // direct load at offset from fs#else- return ((void**)NtCurrentTeb())[slot / sizeof(void*)];+ MI_UNUSED(ofs); MI_UNUSED(value);#endif}-static inline void mi_prim_tls_slot_set(size_t slot, void* value) mi_attr_noexcept {- ((void**)NtCurrentTeb())[slot / sizeof(void*)] = value;-}#endif+// defined in `init.c`; do not use these directly+extern mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_main; // theap belonging to the main heap+extern mi_decl_hidden bool _mi_process_is_initialized; // has mi_process_init been called?+//-------------------------------------------------------------------// Get a fast unique thread id.@@ -266,38 +264,39 @@ static inline void mi_prim_tls_slot_set(size_t slot, void* value) mi_attr_noexce#endif#endif+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept;--// defined in `init.c`; do not use these directly-extern mi_decl_thread mi_heap_t* _mi_heap_default; // default heap to allocate from-extern bool _mi_process_is_initialized; // has mi_process_init been called?--static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept;+static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+ const mi_threadid_t tid = __mi_prim_thread_id();+ mi_assert_internal(tid > 1);+ mi_assert_internal((tid & MI_PAGE_FLAG_MASK) == 0); // bottom 2 bits are clear?+ return tid;+}// Get a unique id for the current thread.#if defined(MI_PRIM_THREAD_ID)-static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {return MI_PRIM_THREAD_ID(); // used for example by CPython for a free threaded build (see python/cpython#115488)}#elif defined(_WIN32)-static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {// Windows: works on Intel and ARM in both 32- and 64-bitreturn (uintptr_t)NtCurrentTeb();}#elif MI_USE_BUILTIN_THREAD_POINTER-static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {// Works on most Unix based platforms with recent compilersreturn (uintptr_t)__builtin_thread_pointer();}#elif MI_HAS_TLS_SLOT-static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {#if defined(__BIONIC__)// issue #384, #495: on the Bionic libc (Android), slot 1 is the thread id// see: https://github.com/aosp-mirror/platform_bionic/blob/c44b1d0676ded732df4b3b21c5f798eacae93228/libc/platform/bionic/tls_defines.h#L86@@ -313,8 +312,8 @@ static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {#else// otherwise use portable C, taking the address of a thread local variable (this is still very fast on most platforms).-static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {- return (uintptr_t)&_mi_heap_default;+static inline mi_threadid_t __mi_prim_thread_id(void) mi_attr_noexcept {+ return (uintptr_t)&__mi_theap_main;}#endif@@ -322,98 +321,215 @@ static inline mi_threadid_t _mi_prim_thread_id(void) mi_attr_noexcept {/* -----------------------------------------------------------------------------------------Get the thread local default heap: `_mi_prim_get_default_heap()`+Get the thread local default theap: `_mi_theap_default()` (and the cached heap `_mi_theap_cached`).This is inlined here as it is on the fast path for allocation functions.--On most platforms (Windows, Linux, FreeBSD, NetBSD, etc), this just returns a-__thread local variable (`_mi_heap_default`). With the initial-exec TLS model this ensures-that the storage will always be available (allocated on the thread stacks).--On some platforms though we cannot use that when overriding `malloc` since the underlying-TLS implementation (or the loader) will call itself `malloc` on a first access and recurse.-We try to circumvent this in an efficient way:-- macOSX : we use an unused TLS slot from the OS allocated slots (MI_TLS_SLOT). On OSX, the- loader itself calls `malloc` even before the modules are initialized.-- OpenBSD: we use an unused slot from the pthread block (MI_TLS_PTHREAD_SLOT_OFS).-- DragonFly: defaults are working but seem slow compared to freeBSD (see PR #323)+We have 4 models:++- MI_TLS_MODEL_THREAD_LOCAL: use regular thread local (default on Linux, FreeBSD, etc)+ On most platforms (Linux, FreeBSD, NetBSD, etc), this just returns a+ thread local variable (`__mi_theap_default`). With the initial-exec TLS model this ensures+ that the storage will always be available and properly initialized (with an empty theap).++ On some platforms the underlying TLS implementation (or the loader) will call itself `malloc`+ on a first access to a thread local and recurse in the MI_TLS_MODEL_THREAD_LOCAL.+ A way around this is to define MI_TLS_RECURSE_GUARD which adds an extra check if the process+ is initialized before accessing the thread-local. This is a check in the fast path though+ so this should be avoided.++- MI_TLS_MODEL_FIXED_SLOT: use a fixed slot in the TLS block (default on macOS)+ This reserves an unused and fixed TLS slot. This is fast and avoids the problem+ where the underlying TLS implementation (or the loader) will call itself `malloc`+ on a first access to a thread local (and recurse in the MI_TLS_MODEL_THREAD_LOCAL).+ This goes wrong though if the OS or a library uses the same fixed slot.++- MI_TLS_MODEL_DYNAMIC_WIN32: use a dynamically allocated slot with TlsAlloc. (default on Windows)+ Windows has somewhat slow thread locals so by default we use TlsAlloc'd slots which+ can be more efficient. First tries to use one of the "direct" first 64 slots which+ are the fastest, but falls back to using "expansion" slots when needed (up to 1088 slots).+ (If the allocated slot happens to always be under 64 for a particular program,+ one might use cmake with `-DMI_WIN_DIRECT_TLS=ON` to skip the expansion slot test in the fast path.)++- MI_TLS_MODEL_DYNAMIC_PTHREADS: use `pthread_getspecific`. (default on OpenBSD, maybe good for Android as well?)+ Use pthread local storage. Somewhat slow but can work well depending on the platform.++Each model should define `MI_THEAP_INITASNULL` to signify that the initial value+returned from `_mi_theap_default()` can be `NULL` (instead of the address of the empty heap).+This incurs an extra check in the fast path (but can often be combined in an existing check).------------------------------------------------------------------------------------------- */-static inline mi_heap_t* mi_prim_get_default_heap(void);--#if defined(MI_MALLOC_OVERRIDE)-#if defined(__APPLE__) // macOS- #define MI_TLS_SLOT 89 // seems unused?- // other possible unused ones are 9, 29, __PTK_FRAMEWORK_JAVASCRIPTCORE_KEY4 (94), __PTK_FRAMEWORK_GC_KEY9 (112) and __PTK_FRAMEWORK_OLDGC_KEY9 (89)+static inline mi_theap_t* _mi_theap_default(void);+static inline mi_theap_t* _mi_theap_cached(void);++#if defined(_WIN32)+ #define MI_TLS_MODEL_DYNAMIC_WIN32 1+#elif defined(__APPLE__) // macOS+ // #define MI_TLS_MODEL_DYNAMIC_PTHREADS 1 // also works but a bit slower+ #define MI_TLS_MODEL_FIXED_SLOT 1+ #define MI_TLS_MODEL_FIXED_SLOT_DEFAULT 108 // seems unused. @apple: it would be great to get 2 official slots for custom allocators :-)+ #define MI_TLS_MODEL_FIXED_SLOT_CACHED 109+ // we used before __PTK_FRAMEWORK_OLDGC_KEY9 (89) but that seems used now.// see <https://github.com/rweichler/substrate/blob/master/include/pthread_machdep.h>-#elif defined(__OpenBSD__)- // use end bytes of a name; goes wrong if anyone uses names > 23 characters (ptrhread specifies 16)- // see <https://github.com/openbsd/src/blob/master/lib/libc/include/thread_private.h#L371>- #define MI_TLS_PTHREAD_SLOT_OFS (6*sizeof(int) + 4*sizeof(void*) + 24)- // #elif defined(__DragonFly__)- // #warning "mimalloc is not working correctly on DragonFly yet."- // #define MI_TLS_PTHREAD_SLOT_OFS (4 + 1*sizeof(void*)) // offset `uniqueid` (also used by gdb?) <https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/lib/libthread_xu/thread/thr_private.h#L458>-#elif defined(__ANDROID__)- // See issue #381- #define MI_TLS_PTHREAD-#endif+#elif defined(__OpenBSD__) || defined(__ANDROID__)+ #define MI_TLS_MODEL_DYNAMIC_PTHREADS 1+ // #define MI_TLS_MODEL_DYNAMIC_PTHREADS_DEFAULT_ENTRY_IS_NULL 1+#else+ #define MI_TLS_MODEL_THREAD_LOCAL 1#endif+// Declared this way to optimize register spills and branches+mi_decl_cold mi_decl_noinline mi_theap_t* _mi_theap_empty_get(void);-#if MI_TLS_SLOT-# if !defined(MI_HAS_TLS_SLOT)-# error "trying to use a TLS slot for the default heap, but the mi_prim_tls_slot primitives are not defined"-# endif+static inline mi_theap_t* __mi_theap_empty(void) {+ #if __GNUC__+ __asm(""); // prevent conditional load+ return (mi_theap_t*)&_mi_theap_empty;+ #else+ return _mi_theap_empty_get();+ #endif+}-static inline mi_heap_t* mi_prim_get_default_heap(void) {- mi_heap_t* heap = (mi_heap_t*)mi_prim_tls_slot(MI_TLS_SLOT);- #if MI_HAS_TLS_SLOT == 1 // check if the TLS slot is initialized- if mi_unlikely(heap == NULL) {- #ifdef __GNUC__- __asm(""); // prevent conditional load of the address of _mi_heap_empty- #endif- heap = (mi_heap_t*)&_mi_heap_empty;- }+#if MI_TLS_MODEL_THREAD_LOCAL+// Thread local with an initial value (default on Linux). Very efficient.++extern mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_default; // default theap to allocate from+extern mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_cached; // theap from the last used heap++static inline mi_theap_t* _mi_theap_default(void) {+ #if defined(MI_TLS_RECURSE_GUARD)+ if (mi_unlikely(!_mi_process_is_initialized)) return _mi_theap_empty_get();#endif- return heap;+ return __mi_theap_default;+}++static inline mi_theap_t* _mi_theap_cached(void) {+ return __mi_theap_cached;}-#elif defined(MI_TLS_PTHREAD_SLOT_OFS)+#elif MI_TLS_MODEL_FIXED_SLOT+// Fixed TLS slot (default on macOS).+#define MI_THEAP_INITASNULL 1-static inline mi_heap_t** mi_prim_tls_pthread_heap_slot(void) {- pthread_t self = pthread_self();- #if defined(__DragonFly__)- if (self==NULL) return NULL;+static inline mi_theap_t* _mi_theap_default(void) {+ return (mi_theap_t*)mi_prim_tls_slot(MI_TLS_MODEL_FIXED_SLOT_DEFAULT);+}++static inline mi_theap_t* _mi_theap_cached(void) {+ return (mi_theap_t*)mi_prim_tls_slot(MI_TLS_MODEL_FIXED_SLOT_CACHED);+}++#elif MI_TLS_MODEL_DYNAMIC_WIN32+// Dynamic TLS slot (default on Windows)+#define MI_THEAP_INITASNULL 1++// We try to use direct slots (64), but can also use the expansion slots (upto 1024 extra available)+// See <https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/pebteb/teb/index.htm> for the offsets.+#if MI_SIZE_SIZE==4+#define MI_TLS_EXPANSION_SLOT (0x0F94 / MI_SIZE_SIZE)+#else+#define MI_TLS_EXPANSION_SLOT (0x1780 / MI_SIZE_SIZE)+#endif++extern mi_decl_hidden size_t _mi_theap_default_slot;+extern mi_decl_hidden size_t _mi_theap_cached_slot;+extern mi_decl_hidden size_t _mi_theap_default_expansion_slot;+extern mi_decl_hidden size_t _mi_theap_cached_expansion_slot;++static inline mi_theap_t* _mi_theap_default(void) {+ const size_t slot = _mi_theap_default_slot;+ mi_theap_t* theap = (mi_theap_t*)mi_prim_tls_slot(slot);+ #if !MI_WIN_DIRECT_TLS+ if mi_unlikely(slot==MI_TLS_EXPANSION_SLOT) { // in TlsExpansionSlots ?+ if mi_likely(theap!=NULL) { // initialized (on this thread)?+ theap = ((mi_theap_t**)theap)[_mi_theap_default_expansion_slot];+ }+ }#endif- return (mi_heap_t**)((uint8_t*)self + MI_TLS_PTHREAD_SLOT_OFS);+ return theap;}-static inline mi_heap_t* mi_prim_get_default_heap(void) {- mi_heap_t** pheap = mi_prim_tls_pthread_heap_slot();- if mi_unlikely(pheap == NULL) return _mi_heap_main_get();- mi_heap_t* heap = *pheap;- if mi_unlikely(heap == NULL) return (mi_heap_t*)&_mi_heap_empty;- return heap;+static inline mi_theap_t* _mi_theap_cached(void) {+ const size_t slot = _mi_theap_cached_slot;+ mi_theap_t* theap = (mi_theap_t*)mi_prim_tls_slot(slot);+ #if !MI_WIN_DIRECT_TLS+ if mi_unlikely(slot==MI_TLS_EXPANSION_SLOT) { // in TlsExpansionSlots ?+ if mi_likely(theap!=NULL) { // initialized (on this thread)?+ theap = ((mi_theap_t**)theap)[_mi_theap_cached_expansion_slot];+ }+ }+ #endif+ return theap;}-#elif defined(MI_TLS_PTHREAD)+#elif MI_TLS_MODEL_DYNAMIC_PTHREADS+// Dynamic pthread slot on less common platforms. This is not too bad. (default on OpenBSD)+#define MI_THEAP_INITASNULL 1++extern mi_decl_hidden pthread_key_t _mi_theap_default_key;+extern mi_decl_hidden pthread_key_t _mi_theap_cached_key;++static inline mi_theap_t* _mi_theap_default(void) {+ #if !MI_TLS_MODEL_DYNAMIC_PTHREADS_DEFAULT_ENTRY_IS_NULL+ // we can skip this check if using the initial key will return NULL from pthread_getspecific+ if mi_unlikely(_mi_theap_default_key==0) { return NULL; }+ #endif+ return (mi_theap_t*)pthread_getspecific(_mi_theap_default_key);+}-extern pthread_key_t _mi_heap_default_key;-static inline mi_heap_t* mi_prim_get_default_heap(void) {- mi_heap_t* heap = (mi_unlikely(_mi_heap_default_key == (pthread_key_t)(-1)) ? _mi_heap_main_get() : (mi_heap_t*)pthread_getspecific(_mi_heap_default_key));- return (mi_unlikely(heap == NULL) ? (mi_heap_t*)&_mi_heap_empty : heap);+static inline mi_theap_t* _mi_theap_cached(void) {+ #if !MI_TLS_MODEL_DYNAMIC_PTHREADS_DEFAULT_ENTRY_IS_NULL+ // we can skip this check if using the initial key will return NULL from pthread_getspecific+ if mi_unlikely(_mi_theap_cached_key==0) { return NULL; }+ #endif+ return (mi_theap_t*)pthread_getspecific(_mi_theap_cached_key);}-#else // default using a thread local variable; used on most platforms.+#else+#error "no TLS model is defined for this platform?"+#endif-static inline mi_heap_t* mi_prim_get_default_heap(void) {- #if defined(MI_TLS_RECURSE_GUARD)- if (mi_unlikely(!_mi_process_is_initialized)) return _mi_heap_main_get();++// Check if a thread is initialized (without using a thread-local if using fixed slots)+static inline bool _mi_thread_is_initialized(void) {+ return (mi_theap_is_initialized(_mi_theap_default()));+}++// Get (and possible create) the theap belonging to a heap+// We cache the last accessed theap in `_mi_theap_cached` for better performance.+static inline mi_theap_t* _mi_heap_theap(const mi_heap_t* heap) {+ mi_theap_t* theap = _mi_theap_cached();+ #if MI_THEAP_INITASNULL+ if mi_likely(theap!=NULL && theap->heap==heap) return theap;+ #else+ if mi_likely(theap->heap==heap) return theap;#endif- return _mi_heap_default;+ return _mi_heap_theap_get_or_init(heap);}-#endif // mi_prim_get_default_heap()+// Get the theap belonging to a heap without creating in if it is not yet initialized.+static inline mi_theap_t* _mi_heap_theap_peek(const mi_heap_t* heap) {+ mi_theap_t* theap = _mi_theap_cached();+ #if MI_THEAP_INITASNULL+ if mi_unlikely(theap==NULL || theap->heap!=heap)+ #else+ if mi_unlikely(theap->heap!=heap)+ #endif+ {+ theap = _mi_heap_theap_get_peek(heap); // don't update the cache on a query (?)+ }+ mi_assert(theap==NULL || theap->heap==heap);+ return theap;+}+// Find the associated theap or NULL if it does not exist (during shutdown)+// Should be fast as it is called in `free.c:mi_free_try_collect`.+static inline mi_theap_t* _mi_page_associated_theap_peek(mi_page_t* page) {+ mi_heap_t* const heap = page->heap;+ mi_theap_t* theap;+ if mi_likely(heap==NULL) { theap = __mi_theap_main; } // note: on macOS accessing the thread_local can cause allocation during thread shutdown (and reinitialize the thread)!+ else { theap = _mi_heap_theap_peek(heap); }+ mi_assert_internal(theap==NULL || _mi_thread_id()==theap->tld->thread_id);+ return theap;+}-#endif // MIMALLOC_PRIM_H+#endif // MI_PRIM_Hdiff --git a/vendored/mimalloc/include/mimalloc/track.h b/vendored/mimalloc/include/mimalloc/track.hindex 4b5709e2b..8f8b93f9a 100644--- a/vendored/mimalloc/include/mimalloc/track.h+++ b/vendored/mimalloc/include/mimalloc/track.h@@ -5,8 +5,8 @@ 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_TRACK_H-#define MIMALLOC_TRACK_H+#ifndef MI_TRACK_H+#define MI_TRACK_H/* ------------------------------------------------------------------------------------------------------Track memory ranges with macros for tools like Valgrind address sanitizer, or other memory checkers.@@ -47,7 +47,7 @@ defined, undefined, or not accessible at all:// valgrind tool#define MI_TRACK_ENABLED 1-#define MI_TRACK_HEAP_DESTROY 1 // track free of individual blocks on heap_destroy+#define MI_TRACK_HEAP_DESTROY 1 // track free of individual blocks on theap_destroy#define MI_TRACK_TOOL "valgrind"#include <valgrind/valgrind.h>@@ -142,4 +142,4 @@ defined, undefined, or not accessible at all:}#endif-#endif+#endif // MI_TRACK_Hdiff --git a/vendored/mimalloc/include/mimalloc/types.h b/vendored/mimalloc/include/mimalloc/types.hindex df6ff26c4..52cb3fcc5 100644--- a/vendored/mimalloc/include/mimalloc/types.h+++ b/vendored/mimalloc/include/mimalloc/types.h@@ -1,34 +1,36 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2024, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.-----------------------------------------------------------------------------*/#pragma once-#ifndef MIMALLOC_TYPES_H-#define MIMALLOC_TYPES_H+#ifndef MI_TYPES_H+#define MI_TYPES_H// --------------------------------------------------------------------------// This file contains the main type definitions for mimalloc:-// mi_heap_t : all data for a thread-local heap, contains-// lists of all managed heap pages.-// mi_segment_t : a larger chunk of memory (32GiB) from where pages-// are allocated. A segment is divided in slices (64KiB) from-// which pages are allocated.-// mi_page_t : a "mimalloc" page (usually 64KiB or 512KiB) from-// where objects are allocated.+// mi_heap_t : all data for a heap; usually there is just one main default heap.+// mi_theap_t : a thread local heap belonging to a specific heap:+// maintains lists of thread-local heap pages that have free space.+// mi_page_t : a mimalloc page (usually 64KiB or 512KiB) from+// where objects of a single size are allocated.// Note: we write "OS page" for OS memory pages while// using plain "page" for mimalloc pages (`mi_page_t`).+// mi_arena_t : a large memory area where pages are allocated (process shared)+// mi_tld_t : thread local data+// mi_subproc_t : all heaps belong to a sub-process (usually just the main one)// --------------------------------------------------------------------------+#include <mimalloc-stats.h>#include <stddef.h> // ptrdiff_t#include <stdint.h> // uintptr_t, uint16_t, etc-#include "atomic.h" // _Atomic--#ifdef _MSC_VER-#pragma warning(disable:4214) // bitfield is not int-#endif+#include <stdbool.h> // bool+#include <limits.h> // SIZE_MAX etc.+#include <errno.h> // error codes+#include "bits.h" // size defines (MI_INTPTR_SIZE etc), bit operations+#include "atomic.h" // _Atomic primitives// Minimal alignment necessary. On most platforms 16 bytes are needed// due to SSE registers for example. This must be at least `sizeof(void*)`@@ -36,6 +38,7 @@ terms of the MIT license. A copy of the license can be found in the file#define MI_MAX_ALIGN_SIZE 16 // sizeof(max_align_t)#endif+// ------------------------------------------------------// Variants// ------------------------------------------------------@@ -51,36 +54,51 @@ terms of the MIT license. A copy of the license can be found in the file// Define MI_STAT as 1 to maintain statistics; set it to 2 to have detailed statistics (but costs some performance).// #define MI_STAT 1-// Define MI_SECURE to enable security mitigations-// #define MI_SECURE 1 // guard page around metadata-// #define MI_SECURE 2 // guard page around each mimalloc page-// #define MI_SECURE 3 // encode free lists (detect corrupted free list (buffer overflow), and invalid pointer free)-// #define MI_SECURE 4 // checks for double free. (may be more expensive)+// Define MI_SECURE to enable security mitigations. Level 1 has minimal performance impact,+// but protects most metadata with guard pages:+// #define MI_SECURE 1 // guard page around metadata; check pointer validity on free+//+// Level 2 has more performance impact but protect well against various buffer overflows+// by surrounding all mimalloc pages with guard pages:+// #define MI_SECURE 2 // guard page around each mimalloc page (can fragment VMA's with large theaps..)+//+// The next two levels can have more performance cost:+// #define MI_SECURE 3 // randomize allocations, encode free lists (detect corrupted free list (buffer overflow), and invalid pointer free)+// #define MI_SECURE 4 // checks for double free. (may be more expensive)#if !defined(MI_SECURE)#define MI_SECURE 0#endif-// Define MI_DEBUG for debug mode-// #define MI_DEBUG 1 // basic assertion checks and statistics, check double free, corrupted free list, and invalid pointer free.-// #define MI_DEBUG 2 // + internal assertion checks+// Define MI_DEBUG for assertion and invariant checking+// #define MI_DEBUG 1 // basic assertion checks and statistics, check double free, corrupted free list, and invalid pointer free. (cmake -DMI_DEBUG=ON)+// #define MI_DEBUG 2 // + internal assertion checks (cmake -DMI_DEBUG_INTERNAL=ON)// #define MI_DEBUG 3 // + extensive internal invariant checking (cmake -DMI_DEBUG_FULL=ON)#if !defined(MI_DEBUG)-#if !defined(NDEBUG) || defined(_DEBUG)+#if defined(MI_BUILD_RELEASE) || defined(NDEBUG)+#define MI_DEBUG 0+#else#define MI_DEBUG 2+#endif+#endif++// Statistics (0=only essential, 1=normal, 2=more fine-grained (expensive) tracking)+#ifndef MI_STAT+#if (MI_DEBUG>0)+#define MI_STAT 2#else-#define MI_DEBUG 0+#define MI_STAT 0#endif#endif// Use guard pages behind objects of a certain size (set by the MIMALLOC_DEBUG_GUARDED_MIN/MAX options)// Padding should be disabled when using guard pages// #define MI_GUARDED 1-#if defined(MI_GUARDED)+#if MI_GUARDED#define MI_PADDING 0#endif-// Reserve extra padding at the end of each block to be more resilient against heap block overflows.+// Reserve extra padding at the end of each block to be more resilient against theap block overflows.// The padding can detect buffer overflow on free.#if !defined(MI_PADDING) && (MI_SECURE>=3 || MI_DEBUG>=1 || (MI_TRACK_VALGRIND || MI_TRACK_ASAN || MI_TRACK_ETW))#define MI_PADDING 1@@ -98,134 +116,173 @@ terms of the MIT license. A copy of the license can be found in the file#define MI_ENCODE_FREELIST 1#endif+// Enable large pages for objects between 64KiB and 512KiB.+// This should perhaps be disabled by default as for many workloads the block sizes above 64 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 1+#endif-// We used to abandon huge pages in order to eagerly deallocate it if freed from another thread.-// Unfortunately, that makes it not possible to visit them during a heap walk or include them in a-// `mi_heap_destroy`. We therefore instead reset/decommit the huge blocks nowadays if freed from-// another thread so the memory becomes "virtually" available (and eventually gets properly freed by-// the owning thread).-// #define MI_HUGE_PAGE_ABANDON 1+// --------------------------------------------------------------+// 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 && __APPLE__ && MI_ARCH_ARM64+ #define MI_ARENA_SLICE_SHIFT (17) // 128 KiB to not waste too much due to 16 KiB guard pages+ #else+ #define MI_ARENA_SLICE_SHIFT (13 + MI_SIZE_SHIFT) // 64 KiB (32 KiB on 32-bit)+ #endif+#endif+#if MI_ARENA_SLICE_SHIFT < 12+#error Arena slices should be at least 4KiB+#endif-// -------------------------------------------------------// Platform specific values-// ------------------------------------------------------+#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-// -------------------------------------------------------// 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...-// ------------------------------------------------------+#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)-#if INTPTR_MAX > INT64_MAX-# define MI_INTPTR_SHIFT (4) // assume 128-bit (as on arm CHERI for example)-#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+#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)-#if SIZE_MAX == UINT64_MAX-# define MI_SIZE_SHIFT (3)-typedef int64_t mi_ssize_t;-#elif SIZE_MAX == UINT32_MAX-# define MI_SIZE_SHIFT (2)-typedef int32_t mi_ssize_t;-#else-#error platform objects must be 32 or 64 bits+#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-#if (SIZE_MAX/2) > LONG_MAX-# define MI_ZU(x) x##ULL-# define MI_ZI(x) x##LL-#else-# define MI_ZU(x) x##UL-# define MI_ZI(x) x##L+#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)-#define MI_INTPTR_SIZE (1<<MI_INTPTR_SHIFT)-#define MI_INTPTR_BITS (MI_INTPTR_SIZE*8)+// We never allocate more than PTRDIFF_MAX (see also <https://sourceware.org/ml/libc-announce/2019/msg00001.html>)+#define MI_MAX_ALLOC_SIZE PTRDIFF_MAX-#define MI_SIZE_SIZE (1<<MI_SIZE_SHIFT)-#define MI_SIZE_BITS (MI_SIZE_SIZE*8)+// Minimal commit for a page on-demand commit (should be >= OS page size)+#define MI_PAGE_MIN_COMMIT_SIZE MI_ARENA_SLICE_SIZE-#define MI_KiB (MI_ZU(1024))-#define MI_MiB (MI_KiB*MI_KiB)-#define MI_GiB (MI_MiB*MI_KiB)++// ------------------------------------------------------+// Arena's are large reserved areas of memory allocated from+// the OS that are managed by mimalloc to efficiently+// allocate MI_ARENA_SLICE_SIZE slices of memory for the+// mimalloc pages.+// ------------------------------------------------------++// A large memory arena where pages are allocated in.+typedef struct mi_arena_s mi_arena_t; // defined below// -------------------------------------------------------// Main internal data-structures+// Heaps contain allocated blocks. Heaps are self-contained+// but share the (sub-process) memory in the arena's.// -------------------------------------------------------// Main tuning parameters for segment and page sizes-// Sizes for 64-bit (usually divide by two for 32-bit)-#ifndef MI_SEGMENT_SLICE_SHIFT-#define MI_SEGMENT_SLICE_SHIFT (13 + MI_INTPTR_SHIFT) // 64KiB (32KiB on 32-bit)-#endif+// A first-class heap.+typedef struct mi_heap_s mi_heap_t; // heaps-#ifndef MI_SEGMENT_SHIFT-#if MI_INTPTR_SIZE > 4-#define MI_SEGMENT_SHIFT ( 9 + MI_SEGMENT_SLICE_SHIFT) // 32MiB-#else-#define MI_SEGMENT_SHIFT ( 7 + MI_SEGMENT_SLICE_SHIFT) // 4MiB on 32-bit-#endif-#endif+// ------------------------------------------------------+// We can have sub-processes that are fully separated+// from each other (for running multiple Python interpreters+// for example). A sub-process holds the memory arenas and heaps.+// -------------------------------------------------------#ifndef MI_SMALL_PAGE_SHIFT-#define MI_SMALL_PAGE_SHIFT (MI_SEGMENT_SLICE_SHIFT) // 64KiB-#endif-#ifndef MI_MEDIUM_PAGE_SHIFT-#define MI_MEDIUM_PAGE_SHIFT ( 3 + MI_SMALL_PAGE_SHIFT) // 512KiB-#endif+// A sub-process+typedef struct mi_subproc_s mi_subproc_t;-// Derived constants-#define MI_SEGMENT_SIZE (MI_ZU(1)<<MI_SEGMENT_SHIFT)-#define MI_SEGMENT_ALIGN MI_SEGMENT_SIZE-#define MI_SEGMENT_MASK ((uintptr_t)(MI_SEGMENT_ALIGN - 1))-#define MI_SEGMENT_SLICE_SIZE (MI_ZU(1)<< MI_SEGMENT_SLICE_SHIFT)-#define MI_SLICES_PER_SEGMENT (MI_SEGMENT_SIZE / MI_SEGMENT_SLICE_SIZE) // 1024-#define MI_SMALL_PAGE_SIZE (MI_ZU(1)<<MI_SMALL_PAGE_SHIFT)-#define MI_MEDIUM_PAGE_SIZE (MI_ZU(1)<<MI_MEDIUM_PAGE_SHIFT)+// ---------------------------------------------------------------+// a memory id tracks the provenance of arena/OS allocated memory+// ----------------------------------------------------------------#define MI_SMALL_OBJ_SIZE_MAX (MI_SMALL_PAGE_SIZE/4) // 8KiB on 64-bit-#define MI_MEDIUM_OBJ_SIZE_MAX (MI_MEDIUM_PAGE_SIZE/4) // 128KiB on 64-bit-#define MI_MEDIUM_OBJ_WSIZE_MAX (MI_MEDIUM_OBJ_SIZE_MAX/MI_INTPTR_SIZE)-#define MI_LARGE_OBJ_SIZE_MAX (MI_SEGMENT_SIZE/2) // 16MiB on 64-bit-#define MI_LARGE_OBJ_WSIZE_MAX (MI_LARGE_OBJ_SIZE_MAX/MI_INTPTR_SIZE)+// Memory can reside in arena's, direct OS allocated, meta-data pages, or statically allocated.+// The memid keeps track of this.+typedef enum mi_memkind_e {+ MI_MEM_NONE, // not allocated+ MI_MEM_EXTERNAL, // not owned by mimalloc but provided externally (via `mi_manage_os_memory` for example)+ MI_MEM_STATIC, // allocated in a static area and should not be freed (the initial main theap data for example (`init.c`))+ MI_MEM_META, // allocated with the meta data allocator (`arena-meta.c`)+ MI_MEM_OS, // allocated from the OS+ MI_MEM_OS_HUGE, // allocated as huge OS pages (usually 1GiB, pinned to physical memory)+ MI_MEM_OS_REMAP, // allocated in a remapable area (i.e. using `mremap`)+ MI_MEM_ARENA, // allocated from an arena (the usual case) (`arena.c`)+ MI_MEM_HEAP_MAIN // allocated in the main heap (for theaps)+} mi_memkind_t;-// Maximum number of size classes. (spaced exponentially in 12.5% increments)-#define MI_BIN_HUGE (73U)+static inline bool mi_memkind_is_os(mi_memkind_t memkind) {+ return (memkind >= MI_MEM_OS && memkind <= MI_MEM_OS_REMAP);+}-#if (MI_MEDIUM_OBJ_WSIZE_MAX >= 655360)-#error "mimalloc internal: define more bins"-#endif+static inline bool mi_memkind_needs_no_free(mi_memkind_t memkind) {+ return (memkind <= MI_MEM_STATIC);+}-// Maximum block size for which blocks are guaranteed to be block size aligned. (see `segment.c:_mi_segment_page_start`)-#define MI_MAX_ALIGN_GUARANTEE (MI_MEDIUM_OBJ_SIZE_MAX)-// Alignments over MI_BLOCK_ALIGNMENT_MAX are allocated in dedicated huge page segments-#define MI_BLOCK_ALIGNMENT_MAX (MI_SEGMENT_SIZE >> 1)+typedef struct mi_memid_os_info {+ void* base; // actual base address of the block (used for offset aligned allocations)+ size_t size; // allocated full size+ // size_t alignment; // alignment at allocation+} mi_memid_os_info_t;-// Maximum slice count (255) for which we can find the page for interior pointers-#define MI_MAX_SLICE_OFFSET_COUNT ((MI_BLOCK_ALIGNMENT_MAX / MI_SEGMENT_SLICE_SIZE) - 1)+typedef struct mi_memid_arena_info {+ mi_arena_t* arena; // arena that contains this memory+ uint32_t slice_index; // slice index in the arena+ uint32_t slice_count; // allocated slices+} mi_memid_arena_info_t;-// we never allocate more than PTRDIFF_MAX (see also <https://sourceware.org/ml/libc-announce/2019/msg00001.html>)-// on 64-bit+ systems we also limit the maximum allocation size such that the slice count fits in 32-bits. (issue #877)-#if (PTRDIFF_MAX > INT32_MAX) && (PTRDIFF_MAX >= (MI_SEGMENT_SLIZE_SIZE * UINT32_MAX))-#define MI_MAX_ALLOC_SIZE (MI_SEGMENT_SLICE_SIZE * (UINT32_MAX-1))-#else-#define MI_MAX_ALLOC_SIZE PTRDIFF_MAX-#endif+typedef struct mi_memid_meta_info {+ void* meta_page; // meta-page that contains the block+ uint32_t block_index; // block index in the meta-data page+ uint32_t block_count; // allocated blocks+} mi_memid_meta_info_t;++typedef struct mi_memid_s {+ union {+ mi_memid_os_info_t os; // only used for MI_MEM_OS+ mi_memid_arena_info_t arena; // only used for MI_MEM_ARENA+ mi_memid_meta_info_t meta; // only used for MI_MEM_META+ } mem;+ mi_memkind_t memkind;+ bool is_pinned; // `true` if we cannot decommit/reset/protect in this memory (e.g. when allocated using large (2Mib) or huge (1GiB) OS pages)+ bool initially_committed;// `true` if the memory was originally allocated as committed+ bool initially_zero; // `true` if the memory was originally zero initialized+} mi_memid_t;+++static inline bool mi_memid_is_os(mi_memid_t memid) {+ return mi_memkind_is_os(memid.memkind);+}++static inline bool mi_memid_needs_no_free(mi_memid_t memid) {+ return mi_memkind_needs_no_free(memid.memkind);+}++static inline mi_arena_t* mi_memid_arena(mi_memid_t memid) {+ return (memid.memkind == MI_MEM_ARENA ? memid.mem.arena.arena : NULL);+}// ------------------------------------------------------@@ -244,46 +301,27 @@ typedef struct mi_block_s {mi_encoded_t next;} mi_block_t;-#if MI_GUARDED-// we always align guarded pointers in a block at an offset-// the block `next` field is then used as a tag to distinguish regular offset aligned blocks from guarded ones-#define MI_BLOCK_TAG_ALIGNED ((mi_encoded_t)(0))-#define MI_BLOCK_TAG_GUARDED (~MI_BLOCK_TAG_ALIGNED)-#endif+// The page flags are put in the bottom 2 bits of the thread_id (for a fast test in `mi_free`)+// If `has_interior_pointers` is true if the page has pointers at an offset in a block (so we have to unalign to the block start before free-ing)+// `in_full_queue` is true if the page is full and resides in the full queue (so we move it to a regular queue on free-ing)+#define MI_PAGE_IN_FULL_QUEUE MI_ZU(0x01)+#define MI_PAGE_HAS_INTERIOR_POINTERS MI_ZU(0x02)+#define MI_PAGE_FLAG_MASK MI_ZU(0x03)+typedef size_t mi_page_flags_t;-// The delayed flags are used for efficient multi-threaded free-ing-typedef enum mi_delayed_e {- MI_USE_DELAYED_FREE = 0, // push on the owning heap thread delayed list- MI_DELAYED_FREEING = 1, // temporary: another thread is accessing the owning heap- MI_NO_DELAYED_FREE = 2, // optimize: push on page local thread free queue if another block is already in the heap thread delayed free list- MI_NEVER_DELAYED_FREE = 3 // sticky: used for abandoned pages without a owning heap; this only resets on page reclaim-} mi_delayed_t;---// The `in_full` and `has_aligned` page flags are put in a union to efficiently-// test if both are false (`full_aligned == 0`) in the `mi_free` routine.-#if !MI_TSAN-typedef union mi_page_flags_s {- uint8_t full_aligned;- struct {- uint8_t in_full : 1;- uint8_t has_aligned : 1;- } x;-} mi_page_flags_t;-#else-// under thread sanitizer, use a byte for each flag to suppress warning, issue #130-typedef union mi_page_flags_s {- uint32_t full_aligned;- struct {- uint8_t in_full;- uint8_t has_aligned;- } x;-} mi_page_flags_t;-#endif+// There are two special threadid's: 0 for pages that are abandoned (and not in a theap queue),+// and 4 for abandoned & mapped threads -- abandoned-mapped pages are abandoned but also mapped+// in an arena (in `mi_heap_t.arena_pages.pages_abandoned`) so these can be quickly found for reuse.+// Abondoning partially used pages allows for sharing of this memory between threads (in particular if threads are blocked)+#define MI_THREADID_ABANDONED MI_ZU(0)+#define MI_THREADID_ABANDONED_MAPPED (MI_PAGE_FLAG_MASK + 1)// Thread free list.-// We use the bottom 2 bits of the pointer for mi_delayed_t flags+// Points to a list of blocks that are freed by other threads.+// The least-bit is set if the page is owned by the current thread. (`mi_page_is_owned`).+// Ownership is required before we can read any non-atomic fields in the page.+// This way we can push a block on the thread free list and try to claim ownership atomically in `free.c:mi_free_block_mt`.typedef uintptr_t mi_thread_free_t;// A page contains blocks of one specific size (`block_size`).@@ -294,234 +332,128 @@ typedef uintptr_t mi_thread_free_t;// The `local_free` and `thread_free` lists are migrated to the `free` list// when it is exhausted. The separate `local_free` list is necessary to// implement a monotonic heartbeat. The `thread_free` list is needed for-// avoiding atomic operations in the common case.+// avoiding atomic operations when allocating from the owning thread.//// `used - |thread_free|` == actual blocks that are in use (alive)// `used - |thread_free| + |free| + |local_free| == capacity`//-// We don't count `freed` (as |free|) but use `used` to reduce+// We don't count "freed" (as |free|) but use only the `used` field to reduce// the number of memory accesses in the `mi_page_all_free` function(s).+// Use `_mi_page_free_collect` to collect the thread_free list and update the `used` count.//// Notes:-// - Access is optimized for `free.c:mi_free` and `alloc.c:mi_page_alloc`+// - Non-atomic fields can only be accessed if having _ownership_ (low bit of `xthread_free` is 1).+// Combining the `thread_free` list with an ownership bit allows a concurrent `free` to atomically+// free an object and (re)claim ownership if the page was abandoned.+// - If a page is not part of a theap it is called "abandoned" (`theap==NULL`) -- in+// that case the `xthreadid` is 0 or 4 (4 is for abandoned pages that+// are in the `pages_abandoned` lists of an arena, these are called "mapped" abandoned pages).+// - page flags are in the bottom 3 bits of `xthread_id` for the fast path in `mi_free`.+// - The layout is optimized for `free.c:mi_free` and `alloc.c:mi_page_alloc`// - Using `uint16_t` does not seem to slow things down-// - The size is 12 words on 64-bit which helps the page index calculations-// (and 14 words on 32-bit, and encoded free lists add 2 words)-// - `xthread_free` uses the bottom bits as a delayed-free flags to optimize-// concurrent frees where only the first concurrent free adds to the owning-// heap `thread_delayed_free` list (see `free.c:mi_free_block_mt`).-// The invariant is that no-delayed-free is only set if there is-// at least one block that will be added, or as already been added, to-// the owning heap `thread_delayed_free` list. This guarantees that pages-// will be freed correctly even if only other threads free blocks.-typedef struct mi_page_s {- // "owned" by the segment- uint32_t slice_count; // slices in this page (0 if not a page)- uint32_t slice_offset; // distance from the actual page data slice (0 if a page)- uint8_t is_committed:1; // `true` if the page virtual memory is committed- uint8_t is_zero_init:1; // `true` if the page was initially zero initialized- uint8_t is_huge:1; // `true` if the page is in a huge segment (`segment->kind == MI_SEGMENT_HUGE`)- // padding- // layout like this to optimize access in `mi_malloc` and `mi_free`- uint16_t capacity; // number of blocks committed, must be the first field, see `segment.c:page_clear`- uint16_t reserved; // number of blocks reserved in memory- mi_page_flags_t flags; // `in_full` and `has_aligned` flags (8 bits)- uint8_t free_is_zero:1; // `true` if the blocks in the free list are zero initialized- uint8_t retire_expire:7; // expiration count for retired blocks-- mi_block_t* free; // list of available free blocks (`malloc` allocates from this list)- mi_block_t* local_free; // list of deferred free blocks by this thread (migrates to `free`)- uint16_t used; // number of blocks in use (including blocks in `thread_free`)- uint8_t block_size_shift; // if not zero, then `(1 << block_size_shift) == block_size` (only used for fast path in `free.c:_mi_page_ptr_unalign`)- uint8_t heap_tag; // tag of the owning heap, used to separate heaps by object type- // padding- size_t block_size; // size available in each block (always `>0`)- uint8_t* page_start; // start of the page area containing the blocks- #if (MI_ENCODE_FREELIST || MI_PADDING)- uintptr_t keys[2]; // two random keys to encode the free lists (see `_mi_block_next`) or padding canary- #endif-- _Atomic(mi_thread_free_t) xthread_free; // list of deferred free blocks freed by other threads- _Atomic(uintptr_t) xheap;+typedef struct mi_page_s {+ _Atomic(mi_threadid_t) xthread_id; // thread this page belongs to. (= `theap->thread_id (or 0 or 4 if abandoned) | page_flags`)- struct mi_page_s* next; // next page owned by this thread with the same `block_size`- struct mi_page_s* prev; // previous page owned by this thread with the same `block_size`+ mi_block_t* free; // list of available free blocks (`malloc` allocates from this list)+ uint16_t used; // number of blocks in use (including blocks in `thread_free`)+ uint16_t capacity; // number of blocks committed+ uint16_t reserved; // number of blocks reserved in memory+ uint8_t retire_expire; // expiration count for retired blocks+ bool free_is_zero; // `true` if the blocks in the free list are zero initialized- // 64-bit 11 words, 32-bit 13 words, (+2 for secure)- void* padding[1];-} mi_page_t;+ mi_block_t* local_free; // list of deferred free blocks by this thread (migrates to `free`)+ _Atomic(mi_thread_free_t) xthread_free; // list of deferred free blocks freed by other threads (= `mi_block_t* | (1 if owned)`)+ size_t block_size; // const: size available in each block (always `>0`)+ uint8_t* page_start; // const: start of the blocks+ #if (MI_ENCODE_FREELIST || MI_PADDING)+ uintptr_t keys[2]; // const: two random keys to encode the free lists (see `_mi_block_next`) or padding canary+ #endif-// -------------------------------------------------------// Mimalloc segments contain mimalloc pages-// ------------------------------------------------------+ mi_theap_t* theap; // the theap owning this page (may not be valid or NULL for abandoned pages)+ mi_heap_t* heap; // const: the heap owning this page-typedef enum mi_page_kind_e {- MI_PAGE_SMALL, // small blocks go into 64KiB pages inside a segment- MI_PAGE_MEDIUM, // medium blocks go into 512KiB pages inside a segment- MI_PAGE_LARGE, // larger blocks go into a single page spanning a whole segment- MI_PAGE_HUGE // a huge page is a single page in a segment of variable size- // used for blocks `> MI_LARGE_OBJ_SIZE_MAX` or an aligment `> MI_BLOCK_ALIGNMENT_MAX`.-} mi_page_kind_t;+ struct mi_page_s* next; // next page owned by the theap with the same `block_size`+ struct mi_page_s* prev; // previous page owned by the theap with the same `block_size`+ size_t slice_committed; // committed size relative to the first arena slice of the page data (or 0 if the page is fully committed already)+ mi_memid_t memid; // const: provenance of the page memory+} mi_page_t;-typedef enum mi_segment_kind_e {- MI_SEGMENT_NORMAL, // MI_SEGMENT_SIZE size with pages inside.- MI_SEGMENT_HUGE, // segment with just one huge page inside.-} mi_segment_kind_t;// -------------------------------------------------------// A segment holds a commit mask where a bit is set if-// the corresponding MI_COMMIT_SIZE area is committed.-// The MI_COMMIT_SIZE must be a multiple of the slice-// size. If it is equal we have the most fine grained-// decommit (but setting it higher can be more efficient).-// The MI_MINIMAL_COMMIT_SIZE is the minimal amount that will-// be committed in one go which can be set higher than-// MI_COMMIT_SIZE for efficiency (while the decommit mask-// is still tracked in fine-grained MI_COMMIT_SIZE chunks)+// Object sizes// -------------------------------------------------------#define MI_MINIMAL_COMMIT_SIZE (1*MI_SEGMENT_SLICE_SIZE)-#define MI_COMMIT_SIZE (MI_SEGMENT_SLICE_SIZE) // 64KiB-#define MI_COMMIT_MASK_BITS (MI_SEGMENT_SIZE / MI_COMMIT_SIZE)-#define MI_COMMIT_MASK_FIELD_BITS MI_SIZE_BITS-#define MI_COMMIT_MASK_FIELD_COUNT (MI_COMMIT_MASK_BITS / MI_COMMIT_MASK_FIELD_BITS)+#define MI_PAGE_ALIGN MI_ARENA_SLICE_ALIGN // pages 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)+#define MI_PAGE_OSPAGE_BLOCK_ALIGN2 (4*MI_KiB) // also aligns any multiple of this size to avoid TLB misses.+#define MI_PAGE_MAX_OVERALLOC_ALIGN MI_ARENA_SLICE_SIZE // (64 KiB) limit for which we overallocate in arena pages, beyond this use OS allocation-#if (MI_COMMIT_MASK_BITS != (MI_COMMIT_MASK_FIELD_COUNT * MI_COMMIT_MASK_FIELD_BITS))-#error "the segment size must be exactly divisible by the (commit size * size_t bits)"+#if (MI_ENCODE_FREELIST || MI_PADDING) && MI_SIZE_SIZE == 8+#define MI_PAGE_INFO_SIZE ((MI_INTPTR_SHIFT+2)*32) // 160 >= sizeof(mi_page_t)+#else+#define MI_PAGE_INFO_SIZE ((MI_INTPTR_SHIFT+1)*32) // 128/96 >= sizeof(mi_page_t)#endif-typedef struct mi_commit_mask_s {- size_t mask[MI_COMMIT_MASK_FIELD_COUNT];-} mi_commit_mask_t;--typedef mi_page_t mi_slice_t;-typedef int64_t mi_msecs_t;---// ----------------------------------------------------------------// a memory id tracks the provenance of arena/OS allocated memory-// -----------------------------------------------------------------// Memory can reside in arena's, direct OS allocated, or statically allocated. The memid keeps track of this.-typedef enum mi_memkind_e {- MI_MEM_NONE, // not allocated- MI_MEM_EXTERNAL, // not owned by mimalloc but provided externally (via `mi_manage_os_memory` for example)- MI_MEM_STATIC, // allocated in a static area and should not be freed (for arena meta data for example)- MI_MEM_OS, // allocated from the OS- MI_MEM_OS_HUGE, // allocated as huge OS pages (usually 1GiB, pinned to physical memory)- MI_MEM_OS_REMAP, // allocated in a remapable area (i.e. using `mremap`)- MI_MEM_ARENA // allocated from an arena (the usual case)-} mi_memkind_t;--static inline bool mi_memkind_is_os(mi_memkind_t memkind) {- return (memkind >= MI_MEM_OS && memkind <= MI_MEM_OS_REMAP);-}--typedef struct mi_memid_os_info {- void* base; // actual base address of the block (used for offset aligned allocations)- size_t size; // full allocation size-} mi_memid_os_info_t;--typedef struct mi_memid_arena_info {- size_t block_index; // index in the arena- mi_arena_id_t id; // arena id (>= 1)- bool is_exclusive; // this arena can only be used for specific arena allocations-} mi_memid_arena_info_t;--typedef struct mi_memid_s {- union {- mi_memid_os_info_t os; // only used for MI_MEM_OS- mi_memid_arena_info_t arena; // only used for MI_MEM_ARENA- } mem;- bool is_pinned; // `true` if we cannot decommit/reset/protect in this memory (e.g. when allocated using large (2Mib) or huge (1GiB) OS pages)- bool initially_committed;// `true` if the memory was originally allocated as committed- bool initially_zero; // `true` if the memory was originally zero initialized- mi_memkind_t memkind;-} mi_memid_t;---// ------------------------------------------------------------------------------------------// Segments are large allocated memory blocks (32mb on 64 bit) from arenas or the OS.-//-// Inside segments we allocated fixed size mimalloc pages (`mi_page_t`) that contain blocks.-// The start of a segment is this structure with a fixed number of slice entries (`slices`)-// usually followed by a guard OS page and the actual allocation area with pages.-// While a page is not allocated, we view it's data as a `mi_slice_t` (instead of a `mi_page_t`).-// Of any free area, the first slice has the info and `slice_offset == 0`; for any subsequent-// slices part of the area, the `slice_offset` is the byte offset back to the first slice-// (so we can quickly find the page info on a free, `internal.h:_mi_segment_page_of`).-// For slices, the `block_size` field is repurposed to signify if a slice is used (`1`) or not (`0`).-// Small and medium pages use a fixed amount of slices to reduce slice fragmentation, while-// large and huge pages span a variable amount of slices.--typedef struct mi_subproc_s mi_subproc_t;--typedef struct mi_segment_s {- // constant fields- mi_memid_t memid; // memory id for arena/OS allocation- bool allow_decommit; // can we decommmit the memory- bool allow_purge; // can we purge the memory (reset or decommit)- size_t segment_size;- mi_subproc_t* subproc; // segment belongs to sub process-- // segment fields- mi_msecs_t purge_expire; // purge slices in the `purge_mask` after this time- mi_commit_mask_t purge_mask; // slices that can be purged- mi_commit_mask_t commit_mask; // slices that are currently committed-- // from here is zero initialized- struct mi_segment_s* next; // the list of freed segments in the cache (must be first field, see `segment.c:mi_segment_init`)- bool was_reclaimed; // true if it was reclaimed (used to limit on-free reclamation)- bool dont_free; // can be temporarily true to ensure the segment is not freed+// The max object sizes are intended to not waste more than ~ 12.5% internally over the page sizes.+#define MI_SMALL_MAX_OBJ_SIZE ((MI_SMALL_PAGE_SIZE-MI_PAGE_OSPAGE_BLOCK_ALIGN2)/6) // = 10 KiB+#if MI_ENABLE_LARGE_PAGES+#define MI_MEDIUM_MAX_OBJ_SIZE ((MI_MEDIUM_PAGE_SIZE-MI_PAGE_OSPAGE_BLOCK_ALIGN2)/6) // ~ 84 KiB+#define MI_LARGE_MAX_OBJ_SIZE (MI_LARGE_PAGE_SIZE/8) // <= 512 KiB // note: this must be a nice power of 2 or we get rounding issues with `_mi_bin`+#else+#define MI_MEDIUM_MAX_OBJ_SIZE (MI_MEDIUM_PAGE_SIZE/8) // <= 64 KiB+#define MI_LARGE_MAX_OBJ_SIZE MI_MEDIUM_MAX_OBJ_SIZE // note: this must be a nice power of 2 or we get rounding issues with `_mi_bin`+#endif+#define MI_LARGE_MAX_OBJ_WSIZE (MI_LARGE_MAX_OBJ_SIZE/MI_SIZE_SIZE)- size_t abandoned; // abandoned pages (i.e. the original owning thread stopped) (`abandoned <= used`)- size_t abandoned_visits; // count how often this segment is visited during abondoned reclamation (to force reclaim if it takes too long)- size_t used; // count of pages in use- uintptr_t cookie; // verify addresses in debug mode: `mi_ptr_cookie(segment) == segment->cookie`+#if (MI_LARGE_MAX_OBJ_WSIZE >= 655360)+#error "mimalloc internal: define more bins"+#endif- struct mi_segment_s* abandoned_os_next; // only used for abandoned segments outside arena's, and only if `mi_option_visit_abandoned` is enabled- struct mi_segment_s* abandoned_os_prev;- size_t segment_slices; // for huge segments this may be different from `MI_SLICES_PER_SEGMENT`- size_t segment_info_slices; // initial count of slices that we are using for segment info and possible guard pages.+// ------------------------------------------------------+// Page kinds+// ------------------------------------------------------- // layout like this to optimize access in `mi_free`- mi_segment_kind_t kind;- size_t slice_entries; // entries in the `slices` array, at most `MI_SLICES_PER_SEGMENT`- _Atomic(mi_threadid_t) thread_id; // unique id of the thread owning this segment+typedef enum mi_page_kind_e {+ MI_PAGE_SMALL, // small blocks go into 64KiB pages+ MI_PAGE_MEDIUM, // medium blocks go into 512KiB pages+ MI_PAGE_LARGE, // larger blocks go into 4MiB pages (if `MI_ENABLE_LARGE_PAGES==1`)+ MI_PAGE_SINGLETON // page containing a single block.+ // used for blocks `> MI_LARGE_MAX_OBJ_SIZE` or an aligment `> MI_PAGE_MAX_OVERALLOC_ALIGN`.+} mi_page_kind_t;- mi_slice_t slices[MI_SLICES_PER_SEGMENT+1]; // one extra final entry for huge blocks with large alignment-} mi_segment_t;// -------------------------------------------------------// Heaps-// Provide first-class heaps to allocate from.-// A heap just owns a set of pages for allocation and+// A "theap" is a thread local heap which owns pages.+// (making them thread-local avoids atomic operations)+//+// All theaps belong to a (non-thread-local) heap.+// A theap just owns a set of pages for allocation and// can only be allocate/reallocate from the thread that created it.// Freeing blocks can be done from any thread though.-// Per thread, the segments are shared among its heaps.-// Per thread, there is always a default heap that is-// used for allocation; it is initialized to statically-// point to an empty heap to avoid initialization checks-// in the fast path.+//+// Per thread, there is always a default theap that belongs+// to the default heap. It is initialized to statically+// point initially to an empty theap to avoid initialization+// checks in the fast path.// ------------------------------------------------------// Thread local data-typedef struct mi_tld_s mi_tld_t;+typedef struct mi_tld_s mi_tld_t; // defined below// Pages of a certain block size are held in a queue.typedef struct mi_page_queue_s {mi_page_t* first;mi_page_t* last;+ size_t count;size_t block_size;} mi_page_queue_t;-#define MI_BIN_FULL (MI_BIN_HUGE+1)-// Random contexttypedef struct mi_random_cxt_s {uint32_t input[16];@@ -532,7 +464,7 @@ typedef struct mi_random_cxt_s {// In debug mode there is a padding structure at the end of the blocks to check for buffer overflows-#if (MI_PADDING)+#if MI_PADDINGtypedef struct mi_padding_s {uint32_t canary; // encoded block value to check validity of the padding (in case of overflow)uint32_t delta; // padding bytes before the block. (mi_usable_size(p) - delta == exact allocated bytes)@@ -547,205 +479,226 @@ typedef struct mi_padding_s {#define MI_PAGES_DIRECT (MI_SMALL_WSIZE_MAX + MI_PADDING_WSIZE + 1)-// A heap owns a set of pages.-struct mi_heap_s {- mi_tld_t* tld;- _Atomic(mi_block_t*) thread_delayed_free;- mi_threadid_t thread_id; // thread this heap belongs too- mi_arena_id_t arena_id; // arena id if the heap belongs to a specific arena (or 0)+// A thread-local heap ("theap") owns a set of thread-local pages.+struct mi_theap_s {+ mi_tld_t* tld; // thread-local data+ mi_heap_t* heap; // the heap this theap belongs to.+ unsigned long long heartbeat; // monotonic heartbeat countuintptr_t cookie; // random cookie to verify pointers (see `_mi_ptr_cookie`)- uintptr_t keys[2]; // two random keys used to encode the `thread_delayed_free` listmi_random_ctx_t random; // random number context used for secure allocationsize_t page_count; // total number of pages in the `pages` queues.size_t page_retired_min; // smallest retired index (retired pages are fully free, but still in the page queues)size_t page_retired_max; // largest retired index into the `pages` array.- mi_heap_t* next; // list of heaps per thread- bool no_reclaim; // `true` if this heap should not reclaim abandoned pages- uint8_t tag; // custom tag, can be used for separating heaps based on the object types+ long generic_count; // how often is `_mi_malloc_generic` called?+ long generic_collect_count; // how often is `_mi_malloc_generic` called without collecting?++ mi_theap_t* tnext; // list of theaps in this thread+ mi_theap_t* tprev;+ mi_theap_t* hnext; // list of theaps of the owning `heap`+ mi_theap_t* hprev;++ long page_full_retain; // how many full pages can be retained per queue (before abandoning them)+ bool allow_page_reclaim; // `true` if this theap should not reclaim abandoned pages+ bool allow_page_abandon; // `true` if this theap can abandon pages to reduce memory footprint#if MI_GUARDEDsize_t guarded_size_min; // minimal size for guarded objectssize_t guarded_size_max; // maximal size for guarded objectssize_t guarded_sample_rate; // sample rate (set to 0 to disable guarded pages)- size_t guarded_sample_seed; // starting sample countsize_t guarded_sample_count; // current sample count (counting down to 0)#endifmi_page_t* pages_free_direct[MI_PAGES_DIRECT]; // optimize: array where every entry points a page with possibly free blocks in the corresponding queue for that size.- mi_page_queue_t pages[MI_BIN_FULL + 1]; // queue of pages for each size class (or "bin")+ mi_page_queue_t pages[MI_BIN_COUNT]; // queue of pages for each size class (or "bin")+ mi_memid_t memid; // provenance of the theap struct itself (meta or os)+ mi_stats_t stats; // thread-local statistics};+// -------------------------------------------------------// Debug+// Heaps contain allocated blocks. Heaps are self-contained+// but share the (sub-process) memory in the arena's.// -------------------------------------------------------#if !defined(MI_DEBUG_UNINIT)-#define MI_DEBUG_UNINIT (0xD0)-#endif-#if !defined(MI_DEBUG_FREED)-#define MI_DEBUG_FREED (0xDF)-#endif-#if !defined(MI_DEBUG_PADDING)-#define MI_DEBUG_PADDING (0xDE)-#endif+// Keep track of all owned and abandoned pages in the arena's+struct mi_arena_pages_s;+typedef struct mi_arena_pages_s mi_arena_pages_t;-#if (MI_DEBUG)-// use our own assertion to print without memory allocation-void _mi_assert_fail(const char* assertion, const char* fname, unsigned int line, const char* func );-#define mi_assert(expr) ((expr) ? (void)0 : _mi_assert_fail(#expr,__FILE__,__LINE__,__func__))-#else-#define mi_assert(x)-#endif+#define MI_MAX_ARENAS (160) // Limited for now (and takes up .bss).. but arena's scale up exponentially (see `mi_arena_reserve`)+ // 160 arenas is enough for ~2 TiB memory-#if (MI_DEBUG>1)-#define mi_assert_internal mi_assert-#else-#define mi_assert_internal(x)-#endif+// A dynamic thread-local variable; 0 for an invalid thread-local+typedef size_t mi_thread_local_t;-#if (MI_DEBUG>2)-#define mi_assert_expensive mi_assert-#else-#define mi_assert_expensive(x)-#endif+typedef struct mi_heap_s {+ mi_subproc_t* subproc; // a heap belongs to a subprocess+ size_t heap_seq; // unique sequence number for heaps in this subprocess+ mi_heap_t* next; // list of heaps in this subprocess+ mi_heap_t* prev;+ mi_thread_local_t theap; // dynamic thread local for the thread-local theaps of this heap-// -------------------------------------------------------// Statistics-// ------------------------------------------------------+ mi_arena_t* exclusive_arena; // if the heap should only allocate from a specific arena (or NULL)+ int numa_node; // if >=0, prefer this numa node for allocations-#ifndef MI_STAT-#if (MI_DEBUG>0)-#define MI_STAT 2-#else-#define MI_STAT 0-#endif-#endif+ mi_theap_t* theaps; // list of all thread-local theaps belonging to this heap (using the `hnext`/`hprev` fields)+ mi_lock_t theaps_lock; // lock for the theaps list operations-typedef struct mi_stat_count_s {- int64_t allocated;- int64_t freed;- int64_t peak;- int64_t current;-} mi_stat_count_t;--typedef struct mi_stat_counter_s {- int64_t total;- int64_t count;-} mi_stat_counter_t;--typedef struct mi_stats_s {- mi_stat_count_t segments;- mi_stat_count_t pages;- mi_stat_count_t reserved;- mi_stat_count_t committed;- mi_stat_count_t reset;- mi_stat_count_t purged;- mi_stat_count_t page_committed;- mi_stat_count_t segments_abandoned;- mi_stat_count_t pages_abandoned;- mi_stat_count_t threads;- mi_stat_count_t normal;- mi_stat_count_t huge;- mi_stat_count_t large;- mi_stat_count_t malloc;- mi_stat_count_t segments_cache;- mi_stat_counter_t pages_extended;- mi_stat_counter_t mmap_calls;- mi_stat_counter_t commit_calls;- mi_stat_counter_t reset_calls;- mi_stat_counter_t purge_calls;- mi_stat_counter_t page_no_retire;- mi_stat_counter_t searches;- mi_stat_counter_t normal_count;- mi_stat_counter_t huge_count;- mi_stat_counter_t large_count;- mi_stat_counter_t arena_count;- mi_stat_counter_t arena_crossover_count;- mi_stat_counter_t arena_rollback_count;- mi_stat_counter_t guarded_alloc_count;-#if MI_STAT>1- mi_stat_count_t normal_bins[MI_BIN_HUGE+1];-#endif-} mi_stats_t;---// add to stat keeping track of the peak-void _mi_stat_increase(mi_stat_count_t* stat, size_t amount);-void _mi_stat_decrease(mi_stat_count_t* stat, size_t amount);-// adjust stat in special cases to compensate for double counting-void _mi_stat_adjust_increase(mi_stat_count_t* stat, size_t amount);-void _mi_stat_adjust_decrease(mi_stat_count_t* stat, size_t amount);-// counters can just be increased-void _mi_stat_counter_increase(mi_stat_counter_t* stat, size_t amount);--#if (MI_STAT)-#define mi_stat_increase(stat,amount) _mi_stat_increase( &(stat), amount)-#define mi_stat_decrease(stat,amount) _mi_stat_decrease( &(stat), amount)-#define mi_stat_counter_increase(stat,amount) _mi_stat_counter_increase( &(stat), amount)-#define mi_stat_adjust_increase(stat,amount) _mi_stat_adjust_increase( &(stat), amount)-#define mi_stat_adjust_decrease(stat,amount) _mi_stat_adjust_decrease( &(stat), amount)-#else-#define mi_stat_increase(stat,amount) ((void)0)-#define mi_stat_decrease(stat,amount) ((void)0)-#define mi_stat_counter_increase(stat,amount) ((void)0)-#define mi_stat_adjuct_increase(stat,amount) ((void)0)-#define mi_stat_adjust_decrease(stat,amount) ((void)0)-#endif+ _Atomic(size_t) abandoned_count[MI_BIN_COUNT]; // total count of abandoned pages in this heap+ mi_page_t* os_abandoned_pages; // list of pages that are OS allocated and not in an arena+ mi_lock_t os_abandoned_pages_lock; // lock for the os abandoned pages list (this lock protects list operations)++ _Atomic(mi_arena_pages_t*) arena_pages[MI_MAX_ARENAS]; // track owned and abandoned pages in the arenas (entries can be NULL)+ mi_lock_t arena_pages_lock; // lock to update the arena_pages array-#define mi_heap_stat_counter_increase(heap,stat,amount) mi_stat_counter_increase( (heap)->tld->stats.stat, amount)-#define mi_heap_stat_increase(heap,stat,amount) mi_stat_increase( (heap)->tld->stats.stat, amount)-#define mi_heap_stat_decrease(heap,stat,amount) mi_stat_decrease( (heap)->tld->stats.stat, amount)+ mi_stats_t stats; // statistics for this heap; periodically updated by merging from each theap+} mi_heap_t;// -------------------------------------------------------// Sub processes do not reclaim or visit segments-// from other sub processes+// Sub processes do not reclaim or visit pages from other sub processes.+// These are essentially the static variables of a process, and+// usually there is only one subprocess. This can be used for example+// by CPython to have separate interpreters within one process.+// Each thread can only belong to one subprocess+// (and needs to call `mi_subproc_add_current_thread` before any allocations).// ------------------------------------------------------struct mi_subproc_s {- _Atomic(size_t) abandoned_count; // count of abandoned segments for this sub-process- _Atomic(size_t) abandoned_os_list_count; // count of abandoned segments in the os-list- mi_lock_t abandoned_os_lock; // lock for the abandoned os segment list (outside of arena's) (this lock protect list operations)- mi_lock_t abandoned_os_visit_lock; // ensure only one thread per subproc visits the abandoned os list- mi_segment_t* abandoned_os_list; // doubly-linked list of abandoned segments outside of arena's (in OS allocated memory)- mi_segment_t* abandoned_os_list_tail; // the tail-end of the list- mi_memid_t memid; // provenance of this memory block+ size_t subproc_seq; // unique id for sub-processes+ mi_subproc_t* next; // list of all sub-processes+ mi_subproc_t* prev;++ _Atomic(size_t) arena_count; // current count of arena's+ _Atomic(mi_arena_t*) arenas[MI_MAX_ARENAS]; // arena's of this sub-process+ mi_lock_t arena_reserve_lock; // lock to ensure arena's get reserved one at a time+ mi_decl_align(8) // needed on some 32-bit platforms+ _Atomic(int64_t) purge_expire; // expiration is set if any arenas can be purged++ _Atomic(mi_heap_t*) heap_main; // main heap for this sub process+ mi_heap_t* heaps; // heaps belonging to this sub-process+ mi_lock_t heaps_lock;++ _Atomic(size_t) thread_count; // current threads associated with this sub-process+ _Atomic(size_t) thread_total_count; // total created threads associated with this sub-process+ _Atomic(size_t) heap_count; // current heaps in this sub-process (== |heaps|)+ _Atomic(size_t) heap_total_count; // total created heaps in this sub-process++ mi_memid_t memid; // provenance of this memory block (meta or static)+ mi_decl_align(8) // needed on some 32-bit platforms+ mi_stats_t stats; // subprocess statistics; updated for arena/OS stats like committed,+ // and otherwise merged with heap stats when those are deleted};+// ------------------------------------------------------// Thread Local data// -------------------------------------------------------// A "span" is is an available range of slices. The span queues keep-// track of slice spans of at most the given `slice_count` (but more than the previous size class).-typedef struct mi_span_queue_s {- mi_slice_t* first;- mi_slice_t* last;- size_t slice_count;-} mi_span_queue_t;--#define MI_SEGMENT_BIN_MAX (35) // 35 == mi_segment_bin(MI_SLICES_PER_SEGMENT)--// Segments thread local data-typedef struct mi_segments_tld_s {- mi_span_queue_t spans[MI_SEGMENT_BIN_MAX+1]; // free slice spans inside segments- size_t count; // current number of segments;- size_t peak_count; // peak number of segments- size_t current_size; // current size of all segments- size_t peak_size; // peak size of all segments- size_t reclaim_count;// number of reclaimed (abandoned) segments- mi_subproc_t* subproc; // sub-process this thread belongs to.- mi_stats_t* stats; // points to tld stats-} mi_segments_tld_t;+// Milliseconds as in `int64_t` to avoid overflows+typedef int64_t mi_msecs_t;// Thread local datastruct mi_tld_s {- unsigned long long heartbeat; // monotonic heartbeat count- bool recurse; // true if deferred was called; used to prevent infinite recursion.- mi_heap_t* heap_backing; // backing heap of this thread (cannot be deleted)- mi_heap_t* heaps; // list of heaps in this thread (so we can abandon all when the thread terminates)- mi_segments_tld_t segments; // segment tld- mi_stats_t stats; // statistics+ mi_threadid_t thread_id; // thread id of this thread+ size_t thread_seq; // thread sequence id (linear count of created threads)+ int numa_node; // thread preferred numa node+ mi_subproc_t* subproc; // sub-process this thread belongs to.+ mi_theap_t* theaps; // list of theaps in this thread (so we can abandon all when the thread terminates)+ bool recurse; // true if deferred was called; used to prevent infinite recursion.+ bool is_in_threadpool; // true if this thread is part of a threadpool (and can run arbitrary tasks)+ mi_memid_t memid; // provenance of the tld memory itself (meta or OS)};++/* ----------------------------------------------------------------------------+ Arenas are fixed area's of OS memory from which we can allocate+ large blocks (>= MI_ARENA_MIN_BLOCK_SIZE).+ In contrast to the rest of mimalloc, the arenas are shared between+ threads and need to be accessed using atomic operations (using atomic `mi_bitmap_t`'s).++ Arenas are also used to for huge OS page (1GiB) reservations or for reserving+ OS memory upfront which can be improve performance or is sometimes needed+ on embedded devices. We can also employ this with WASI or `sbrk` systems+ to reserve large arenas upfront and be able to reuse the memory more effectively.+-----------------------------------------------------------------------------*/++#define MI_ARENA_BIN_COUNT (MI_BIN_COUNT)+#define MI_ARENA_MIN_SIZE (MI_BCHUNK_BITS * MI_ARENA_SLICE_SIZE) // 32 MiB (or 8 MiB on 32-bit)+#define MI_ARENA_MAX_SIZE (MI_BITMAP_MAX_BIT_COUNT * MI_ARENA_SLICE_SIZE)++typedef struct mi_bitmap_s mi_bitmap_t; // atomic bitmap (defined in `src/bitmap.h`)+typedef struct mi_bbitmap_s mi_bbitmap_t; // atomic binned bitmap (defined in `src/bitmap.h`)++typedef struct mi_arena_pages_s {+ mi_bitmap_t* pages; // all registered pages (abandoned and owned)+ mi_bitmap_t* pages_abandoned[MI_ARENA_BIN_COUNT]; // abandoned pages per size bin (a set bit means the start of the page)+ // followed by the bitmaps (whose sizes depend on the arena size)+} mi_arena_pages_t;+++// A memory arena+typedef struct mi_arena_s {+ mi_memid_t memid; // provenance of the memory area+ mi_subproc_t* subproc; // subprocess this arena belongs to (`this 'element-of' this->subproc->arenas`)+ size_t arena_idx; // index in the arenas array++ size_t slice_count; // total size of the area in arena slices (of `MI_ARENA_SLICE_SIZE`)+ size_t info_slices; // initial slices reserved for the arena bitmaps+ int numa_node; // associated NUMA node+ bool is_exclusive; // only allow allocations if specifically for this arena+ mi_decl_align(8) // needed on some 32-bit platforms+ _Atomic(mi_msecs_t) purge_expire; // expiration time when slices can be purged from `slices_purge`.+ mi_commit_fun_t* commit_fun; // custom commit/decommit memory+ void* commit_fun_arg; // user argument for a custom commit function++ mi_bbitmap_t* slices_free; // is the slice free? (a binned bitmap with size classes)+ mi_bitmap_t* slices_committed; // is the slice committed? (i.e. accessible)+ mi_bitmap_t* slices_dirty; // is the slice potentially non-zero?+ mi_bitmap_t* slices_purge; // slices that can be purged+ mi_arena_pages_t pages_main; // arena page bitmaps for the main heap are allocated up front as well++ // followed by the bitmaps (whose sizes depend on the arena size)+ // note: when adding bitmaps revise `mi_arena_info_slices_needed`+} mi_arena_t;++++/* -----------------------------------------------------------+ Error codes passed to `_mi_fatal_error`+ All are recoverable but EFAULT is a serious error and aborts by default in secure mode.+ For portability define undefined error codes using common Unix codes:+ <https://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html>+----------------------------------------------------------- */++#ifndef EAGAIN // double free+#define EAGAIN (11)+#endif+#ifndef ENOMEM // out of memory+#define ENOMEM (12)+#endif+#ifndef EFAULT // corrupted free-list or meta-data+#define EFAULT (14)+#endif+#ifndef EINVAL // trying to free an invalid pointer+#define EINVAL (22)#endif+#ifndef EOVERFLOW // count*size overflow+#define EOVERFLOW (75)+#endif++/* -----------------------------------------------------------+ Debug constants+----------------------------------------------------------- */++#if !defined(MI_DEBUG_UNINIT)+#define MI_DEBUG_UNINIT (0xD0)+#endif+#if !defined(MI_DEBUG_FREED)+#define MI_DEBUG_FREED (0xDF)+#endif+#if !defined(MI_DEBUG_PADDING)+#define MI_DEBUG_PADDING (0xDE)+#endif+++#endif // MI_TYPES_Hdiff --git a/vendored/mimalloc/src/alloc-aligned.c b/vendored/mimalloc/src/alloc-aligned.cindex 8bf0a38db..fe8ae1725 100644--- a/vendored/mimalloc/src/alloc-aligned.c+++ b/vendored/mimalloc/src/alloc-aligned.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2021, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -7,7 +7,7 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc.h"#include "mimalloc/internal.h"-#include "mimalloc/prim.h" // mi_prim_get_default_heap+#include "mimalloc/prim.h" // _mi_theap_default#include <string.h> // memset@@ -16,73 +16,80 @@ terms of the MIT license. A copy of the license can be found in the file// ------------------------------------------------------static bool mi_malloc_is_naturally_aligned( size_t size, size_t alignment ) {- // objects up to `MI_MAX_ALIGN_GUARANTEE` are allocated aligned to their size (see `segment.c:_mi_segment_page_start`).+ // certain blocks are always allocated at a certain natural alignment.+ // (see also `arena.c:mi_arenas_page_alloc_fresh`).mi_assert_internal(_mi_is_power_of_two(alignment) && (alignment > 0));if (alignment > size) return false;- if (alignment <= MI_MAX_ALIGN_SIZE) return true;const size_t bsize = mi_good_size(size);- return (bsize <= MI_MAX_ALIGN_GUARANTEE && (bsize & (alignment-1)) == 0);+ const bool ok = (bsize <= MI_PAGE_MAX_START_BLOCK_ALIGN2 && _mi_is_power_of_two(bsize)) || // power-of-two under N+ (alignment==MI_PAGE_OSPAGE_BLOCK_ALIGN2 && (bsize % MI_PAGE_OSPAGE_BLOCK_ALIGN2)==0); // or multiple of N+ if (ok) { mi_assert_internal((bsize & (alignment-1)) == 0); } // since both power of 2 and alignment <= size+ return ok;}#if MI_GUARDED-static mi_decl_restrict void* mi_heap_malloc_guarded_aligned(mi_heap_t* heap, size_t size, size_t alignment, bool zero) mi_attr_noexcept {+static mi_decl_restrict void* mi_theap_malloc_guarded_aligned(mi_theap_t* theap, size_t size, size_t alignment, bool zero) mi_attr_noexcept {// use over allocation for guarded blocksl- mi_assert_internal(alignment > 0 && alignment < MI_BLOCK_ALIGNMENT_MAX);+ #if MI_THEAP_INITASNULL+ if mi_unlikely(theap==NULL) { theap = _mi_theap_empty_get(); }+ #endif+ mi_assert_internal(alignment > 0 && alignment < MI_PAGE_MAX_OVERALLOC_ALIGN);const size_t oversize = size + alignment - 1;- void* base = _mi_heap_malloc_guarded(heap, oversize, zero);- void* p = mi_align_up_ptr(base, alignment);+ void* base = _mi_theap_malloc_guarded(theap, oversize, zero);+ void* p = _mi_align_up_ptr(base, alignment);mi_track_align(base, p, (uint8_t*)p - (uint8_t*)base, size);mi_assert_internal(mi_usable_size(p) >= size);mi_assert_internal(_mi_is_aligned(p, alignment));return p;}-static void* mi_heap_malloc_zero_no_guarded(mi_heap_t* heap, size_t size, bool zero) {- const size_t rate = heap->guarded_sample_rate;- // only write if `rate!=0` so we don't write to the constant `_mi_heap_empty`- if (rate != 0) { heap->guarded_sample_rate = 0; }- void* p = _mi_heap_malloc_zero(heap, size, zero);- if (rate != 0) { heap->guarded_sample_rate = rate; }+static void* mi_theap_malloc_zero_no_guarded(mi_theap_t* theap, size_t size, bool zero, size_t* usable) {+ #if MI_THEAP_INITASNULL+ if mi_unlikely(theap==NULL) { theap = _mi_theap_empty_get(); }+ #endif+ const size_t rate = theap->guarded_sample_rate;+ // only write if `rate!=0` so we don't write to the constant `_mi_theap_empty`+ if (rate != 0) { theap->guarded_sample_rate = 0; }+ void* p = _mi_theap_malloc_zero(theap, size, zero, usable);+ if (rate != 0) { theap->guarded_sample_rate = rate; }return p;}#else-static void* mi_heap_malloc_zero_no_guarded(mi_heap_t* heap, size_t size, bool zero) {- return _mi_heap_malloc_zero(heap, size, zero);+static void* mi_theap_malloc_zero_no_guarded(mi_theap_t* theap, size_t size, bool zero, size_t* usable) {+ return _mi_theap_malloc_zero(theap, size, zero, usable);}#endif// Fallback aligned allocation that over-allocates -- split out for better codegen-static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_overalloc(mi_heap_t* const heap, const size_t size, const size_t alignment, const size_t offset, const bool zero) mi_attr_noexcept+static mi_decl_noinline void* mi_theap_malloc_zero_aligned_at_overalloc(mi_theap_t* const theap, const size_t size, const size_t alignment, const size_t offset, const bool zero, size_t* usable) mi_attr_noexcept{mi_assert_internal(size <= (MI_MAX_ALLOC_SIZE - MI_PADDING_SIZE));mi_assert_internal(alignment != 0 && _mi_is_power_of_two(alignment));void* p;size_t oversize;- if mi_unlikely(alignment > MI_BLOCK_ALIGNMENT_MAX) {- // use OS allocation for very large alignment and allocate inside a huge page (dedicated segment with 1 page)- // This can support alignments >= MI_SEGMENT_SIZE by ensuring the object can be aligned at a point in the- // first (and single) page such that the segment info is `MI_SEGMENT_SIZE` bytes before it (so it can be found by aligning the pointer down)+ if mi_unlikely(alignment > MI_PAGE_MAX_OVERALLOC_ALIGN) {+ // use OS allocation for large alignments and allocate inside a singleton page (not in an arena)+ // This can support alignments >= MI_PAGE_ALIGN by ensuring the object can be aligned+ // in the first (and single) page such that the page info is `MI_PAGE_ALIGN` bytes before it (and can be found in the _mi_page_map).if mi_unlikely(offset != 0) {// todo: cannot support offset alignment for very large alignments yet-#if MI_DEBUG > 0- _mi_error_message(EOVERFLOW, "aligned allocation with a very large alignment cannot be used with an alignment offset (size %zu, alignment %zu, offset %zu)\n", size, alignment, offset);-#endif+ #if MI_DEBUG > 0+ _mi_error_message(EOVERFLOW, "aligned allocation with a large alignment cannot be used with an alignment offset (size %zu, alignment %zu, offset %zu)\n", size, alignment, offset);+ #endifreturn NULL;}oversize = (size <= MI_SMALL_SIZE_MAX ? MI_SMALL_SIZE_MAX + 1 /* ensure we use generic malloc path */ : size);// note: no guarded as alignment > 0- p = _mi_heap_malloc_zero_ex(heap, oversize, false, alignment); // the page block size should be large enough to align in the single huge page block- // zero afterwards as only the area from the aligned_p may be committed!+ p = _mi_theap_malloc_zero_ex(theap, oversize, zero, alignment, usable); // the page block size should be large enough to align in the single huge page blockif (p == NULL) return NULL;}else {// otherwise over-allocateoversize = (size < MI_MAX_ALIGN_SIZE ? MI_MAX_ALIGN_SIZE : size) + alignment - 1; // adjust for size <= 16; with size 0 and aligment 64k, we would allocate a 64k block and pointing just beyond that.- p = mi_heap_malloc_zero_no_guarded(heap, oversize, zero);+ p = mi_theap_malloc_zero_no_guarded(theap, oversize, zero, usable);if (p == NULL) return NULL;}- mi_page_t* page = _mi_ptr_page(p);// .. and align within the allocationconst uintptr_t align_mask = alignment - 1; // for any x, `(x & align_mask) == (x % alignment)`@@ -90,8 +97,14 @@ static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_overalloc(mi_heap_tconst uintptr_t adjust = (poffset == 0 ? 0 : alignment - poffset);mi_assert_internal(adjust < alignment);void* aligned_p = (void*)((uintptr_t)p + adjust);++ // note: after the above allocation, the page may be abandoned now (as it became full, see `page.c:_mi_malloc_generic`)+ // and we no longer own it. We should be careful to only read constant fields in the page,+ // or use safe atomic access as in `mi_page_set_has_interior_pointers`.+ // (we can access the page though since the just allocated pointer keeps it alive)+ mi_page_t* page = _mi_ptr_page(p);if (aligned_p != p) {- mi_page_set_has_aligned(page, true);+ mi_page_set_has_interior_pointers(page, true);#if MI_GUARDED// set tag to aligned so mi_usable_size works with guard pagesif (adjust >= sizeof(mi_block_t)) {@@ -114,13 +127,13 @@ static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_overalloc(mi_heap_t#endif// now zero the block if needed- if (alignment > MI_BLOCK_ALIGNMENT_MAX) {- // for the tracker, on huge aligned allocations only the memory from the start of the large block is defined- mi_track_mem_undefined(aligned_p, size);- if (zero) {- _mi_memzero_aligned(aligned_p, mi_usable_size(aligned_p));- }- }+ //if (alignment > MI_PAGE_MAX_OVERALLOC_ALIGN) {+ // // for the tracker, on huge aligned allocations only from the start of the large block is defined+ // mi_track_mem_undefined(aligned_p, size);+ // if (zero) {+ // _mi_memzero_aligned(aligned_p, mi_usable_size(aligned_p));+ // }+ //}if (p != aligned_p) {mi_track_align(p,aligned_p,adjust,mi_usable_size(aligned_p));@@ -132,7 +145,7 @@ static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_overalloc(mi_heap_t}// Generic primitive aligned allocation -- split out for better codegen-static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_generic(mi_heap_t* const heap, const size_t size, const size_t alignment, const size_t offset, const bool zero) mi_attr_noexcept+static mi_decl_noinline void* mi_theap_malloc_zero_aligned_at_generic(mi_theap_t* const theap, const size_t size, const size_t alignment, const size_t offset, const bool zero, size_t* usable) mi_attr_noexcept{mi_assert_internal(alignment != 0 && _mi_is_power_of_two(alignment));// we don't allocate more than MI_MAX_ALLOC_SIZE (see <https://sourceware.org/ml/libc-announce/2019/msg00001.html>)@@ -144,10 +157,10 @@ static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_generic(mi_heap_t*}// use regular allocation if it is guaranteed to fit the alignment constraints.- // this is important to try as the fast path in `mi_heap_malloc_zero_aligned` only works when there exist+ // this is important to try as the fast path in `mi_theap_malloc_zero_aligned` only works when there exist// a page with the right block size, and if we always use the over-alloc fallback that would never happen.if (offset == 0 && mi_malloc_is_naturally_aligned(size,alignment)) {- void* p = mi_heap_malloc_zero_no_guarded(heap, size, zero);+ void* p = mi_theap_malloc_zero_no_guarded(theap, size, zero, usable);mi_assert_internal(p == NULL || ((uintptr_t)p % alignment) == 0);const bool is_aligned_or_null = (((uintptr_t)p) & (alignment-1))==0;if mi_likely(is_aligned_or_null) {@@ -161,12 +174,12 @@ static mi_decl_noinline void* mi_heap_malloc_zero_aligned_at_generic(mi_heap_t*}// fall back to over-allocation- return mi_heap_malloc_zero_aligned_at_overalloc(heap,size,alignment,offset,zero);+ return mi_theap_malloc_zero_aligned_at_overalloc(theap,size,alignment,offset,zero,usable);}// Primitive aligned allocation-static void* mi_heap_malloc_zero_aligned_at(mi_heap_t* const heap, const size_t size, const size_t alignment, const size_t offset, const bool zero) mi_attr_noexcept+static inline void* mi_theap_malloc_zero_aligned_at(mi_theap_t* const theap, const size_t size, const size_t alignment, const size_t offset, const bool zero, size_t* usable) mi_attr_noexcept{// note: we don't require `size > offset`, we just guarantee that the address at offset is aligned regardless of the allocated size.if mi_unlikely(alignment == 0 || !_mi_is_power_of_two(alignment)) { // require power-of-two (see <https://en.cppreference.com/w/c/memory/aligned_alloc>)@@ -177,98 +190,135 @@ static void* mi_heap_malloc_zero_aligned_at(mi_heap_t* const heap, const size_t}#if MI_GUARDED- if (offset==0 && alignment < MI_BLOCK_ALIGNMENT_MAX && mi_heap_malloc_use_guarded(heap,size)) {- return mi_heap_malloc_guarded_aligned(heap, size, alignment, zero);+ #if MI_THEAP_INITASNULL+ if mi_likely(theap!=NULL)+ #endif+ if (offset==0 && alignment < MI_PAGE_MAX_OVERALLOC_ALIGN && mi_theap_malloc_use_guarded(theap,size)) {+ return mi_theap_malloc_guarded_aligned(theap, size, alignment, zero);}#endif// try first if there happens to be a small block available with just the right alignment- if mi_likely(size <= MI_SMALL_SIZE_MAX && alignment <= size) {- const uintptr_t align_mask = alignment-1; // for any x, `(x & align_mask) == (x % alignment)`- const size_t padsize = size + MI_PADDING_SIZE;- mi_page_t* page = _mi_heap_get_free_small_page(heap, padsize);- if mi_likely(page->free != NULL) {- const bool is_aligned = (((uintptr_t)page->free + offset) & align_mask)==0;- if mi_likely(is_aligned)- {- #if MI_STAT>1- mi_heap_stat_increase(heap, malloc, size);- #endif- void* p = (zero ? _mi_page_malloc_zeroed(heap,page,padsize) : _mi_page_malloc(heap,page,padsize)); // call specific page malloc for better codegen- mi_assert_internal(p != NULL);- mi_assert_internal(((uintptr_t)p + offset) % alignment == 0);- mi_track_malloc(p,size,zero);- return p;+ // since most small power-of-2 blocks (under MI_PAGE_MAX_BLOCK_START_ALIGN2) are already+ // naturally aligned this can be often the case.+ #if MI_THEAP_INITASNULL+ if mi_likely(theap!=NULL)+ #endif+ {+ if mi_likely(size <= MI_SMALL_SIZE_MAX && alignment <= size) {+ const uintptr_t align_mask = alignment-1; // for any x, `(x & align_mask) == (x % alignment)`+ const size_t padsize = size + MI_PADDING_SIZE;+ mi_page_t* page = _mi_theap_get_free_small_page(theap, padsize);+ if mi_likely(page->free != NULL) {+ const bool is_aligned = (((uintptr_t)page->free + offset) & align_mask)==0;+ if mi_likely(is_aligned)+ {+ if (usable!=NULL) { *usable = mi_page_usable_block_size(page); }+ void* p = _mi_page_malloc_zero(theap, page, padsize, zero);+ mi_assert_internal(p != NULL);+ mi_assert_internal(((uintptr_t)p + offset) % alignment == 0);+ mi_track_malloc(p, size, zero);+ return p;+ }}}}// fallback to generic aligned allocation- return mi_heap_malloc_zero_aligned_at_generic(heap, size, alignment, offset, zero);+ return mi_theap_malloc_zero_aligned_at_generic(theap, size, alignment, offset, zero, usable);}// -------------------------------------------------------// Optimized mi_heap_malloc_aligned / mi_malloc_aligned+// Internal mi_theap_malloc_aligned / mi_malloc_aligned// -------------------------------------------------------mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc_aligned_at(mi_heap_t* heap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_malloc_zero_aligned_at(heap, size, alignment, offset, false);+static mi_decl_restrict void* mi_theap_malloc_aligned_at(mi_theap_t* theap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_malloc_zero_aligned_at(theap, size, alignment, offset, false, NULL);}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc_aligned(mi_heap_t* heap, size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_malloc_aligned_at(heap, size, alignment, 0);+mi_decl_nodiscard mi_decl_restrict void* mi_theap_malloc_aligned(mi_theap_t* theap, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_malloc_aligned_at(theap, size, alignment, 0);}-// ensure a definition is emitted-#if defined(__cplusplus)-void* _mi_extern_heap_malloc_aligned = (void*)&mi_heap_malloc_aligned;-#endif--// -------------------------------------------------------// Aligned Allocation-// --------------------------------------------------------mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc_aligned_at(mi_heap_t* heap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_malloc_zero_aligned_at(heap, size, alignment, offset, true);+static mi_decl_restrict void* mi_theap_zalloc_aligned_at(mi_theap_t* theap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_malloc_zero_aligned_at(theap, size, alignment, offset, true, NULL);}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc_aligned(mi_heap_t* heap, size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_zalloc_aligned_at(heap, size, alignment, 0);+static mi_decl_restrict void* mi_theap_zalloc_aligned(mi_theap_t* theap, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_zalloc_aligned_at(theap, size, alignment, 0);}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc_aligned_at(mi_heap_t* heap, size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+static mi_decl_restrict void* mi_theap_calloc_aligned_at(mi_theap_t* theap, size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(count, size, &total)) return NULL;- return mi_heap_zalloc_aligned_at(heap, total, alignment, offset);+ return mi_theap_zalloc_aligned_at(theap, total, alignment, offset);}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc_aligned(mi_heap_t* heap, size_t count, size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_calloc_aligned_at(heap,count,size,alignment,0);+static mi_decl_restrict void* mi_theap_calloc_aligned(mi_theap_t* theap, size_t count, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_calloc_aligned_at(theap, count, size, alignment, 0);}++// ------------------------------------------------------+// Aligned Allocation+// ------------------------------------------------------+mi_decl_nodiscard mi_decl_restrict void* mi_malloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_malloc_aligned_at(mi_prim_get_default_heap(), size, alignment, offset);+ return mi_theap_malloc_aligned_at(_mi_theap_default(), size, alignment, offset);}mi_decl_nodiscard mi_decl_restrict void* mi_malloc_aligned(size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_malloc_aligned(mi_prim_get_default_heap(), size, alignment);+ return mi_theap_malloc_aligned(_mi_theap_default(), size, alignment);+}++mi_decl_nodiscard mi_decl_restrict void* mi_umalloc_aligned(size_t size, size_t alignment, size_t* block_size) mi_attr_noexcept {+ return mi_theap_malloc_zero_aligned_at(_mi_theap_default(), size, alignment, 0, false, block_size);}mi_decl_nodiscard mi_decl_restrict void* mi_zalloc_aligned_at(size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_zalloc_aligned_at(mi_prim_get_default_heap(), size, alignment, offset);+ return mi_theap_zalloc_aligned_at(_mi_theap_default(), size, alignment, offset);}mi_decl_nodiscard mi_decl_restrict void* mi_zalloc_aligned(size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_zalloc_aligned(mi_prim_get_default_heap(), size, alignment);+ return mi_theap_zalloc_aligned(_mi_theap_default(), size, alignment);+}++mi_decl_nodiscard mi_decl_restrict void* mi_uzalloc_aligned(size_t size, size_t alignment, size_t* block_size) mi_attr_noexcept {+ return mi_theap_malloc_zero_aligned_at(_mi_theap_default(), size, alignment, 0, true, block_size);}mi_decl_nodiscard mi_decl_restrict void* mi_calloc_aligned_at(size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_calloc_aligned_at(mi_prim_get_default_heap(), count, size, alignment, offset);+ return mi_theap_calloc_aligned_at(_mi_theap_default(), count, size, alignment, offset);}mi_decl_nodiscard mi_decl_restrict void* mi_calloc_aligned(size_t count, size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_calloc_aligned(mi_prim_get_default_heap(), count, size, alignment);+ return mi_theap_calloc_aligned(_mi_theap_default(), count, size, alignment);+}+++mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc_aligned_at(mi_heap_t* heap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_malloc_aligned_at(_mi_heap_theap(heap), size, alignment, offset);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc_aligned(mi_heap_t* heap, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_malloc_aligned(_mi_heap_theap(heap), size, alignment);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc_aligned_at(mi_heap_t* heap, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_zalloc_aligned_at(_mi_heap_theap(heap), size, alignment, offset);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc_aligned(mi_heap_t* heap, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_zalloc_aligned(_mi_heap_theap(heap), size, alignment);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc_aligned_at(mi_heap_t* heap, size_t count, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_calloc_aligned_at(_mi_heap_theap(heap), count, size, alignment, offset);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc_aligned(mi_heap_t* heap, size_t count, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_calloc_aligned(_mi_heap_theap(heap), count, size, alignment);}@@ -276,10 +326,10 @@ mi_decl_nodiscard mi_decl_restrict void* mi_calloc_aligned(size_t count, size_t// Aligned re-allocation// -------------------------------------------------------static void* mi_heap_realloc_zero_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset, bool zero) mi_attr_noexcept {+static void* mi_theap_realloc_zero_aligned_at(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, size_t offset, bool zero) mi_attr_noexcept {mi_assert(alignment > 0);- if (alignment <= sizeof(uintptr_t)) return _mi_heap_realloc_zero(heap,p,newsize,zero);- if (p == NULL) return mi_heap_malloc_zero_aligned_at(heap,newsize,alignment,offset,zero);+ if (alignment <= sizeof(uintptr_t)) return _mi_theap_realloc_zero(theap,p,newsize,zero,NULL,NULL);+ if (p == NULL) return mi_theap_malloc_zero_aligned_at(theap,newsize,alignment,offset,zero,NULL);size_t size = mi_usable_size(p);if (newsize <= size && newsize >= (size - (size / 2))&& (((uintptr_t)p + offset) % alignment) == 0) {@@ -287,7 +337,7 @@ static void* mi_heap_realloc_zero_aligned_at(mi_heap_t* heap, void* p, size_t ne}else {// note: we don't zero allocate upfront so we only zero initialize the expanded part- void* newp = mi_heap_malloc_aligned_at(heap,newsize,alignment,offset);+ void* newp = mi_theap_malloc_aligned_at(theap,newsize,alignment,offset);if (newp != NULL) {if (zero && newsize > size) {// also set last word in the previous allocation to zero to ensure any padding is zero-initialized@@ -301,63 +351,89 @@ static void* mi_heap_realloc_zero_aligned_at(mi_heap_t* heap, void* p, size_t ne}}-static void* mi_heap_realloc_zero_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, bool zero) mi_attr_noexcept {+static void* mi_theap_realloc_zero_aligned(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, bool zero) mi_attr_noexcept {mi_assert(alignment > 0);- if (alignment <= sizeof(uintptr_t)) return _mi_heap_realloc_zero(heap,p,newsize,zero);+ if (alignment <= sizeof(uintptr_t)) return _mi_theap_realloc_zero(theap,p,newsize,zero,NULL,NULL);size_t offset = ((uintptr_t)p % alignment); // use offset of previous allocation (p can be NULL)- return mi_heap_realloc_zero_aligned_at(heap,p,newsize,alignment,offset,zero);+ return mi_theap_realloc_zero_aligned_at(theap,p,newsize,alignment,offset,zero);}-mi_decl_nodiscard void* mi_heap_realloc_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_realloc_zero_aligned_at(heap,p,newsize,alignment,offset,false);+static void* mi_theap_realloc_aligned_at(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_realloc_zero_aligned_at(theap,p,newsize,alignment,offset,false);}-mi_decl_nodiscard void* mi_heap_realloc_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {- return mi_heap_realloc_zero_aligned(heap,p,newsize,alignment,false);+static void* mi_theap_realloc_aligned(mi_theap_t* theap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {+ return mi_theap_realloc_zero_aligned(theap,p,newsize,alignment,false);}-mi_decl_nodiscard void* mi_heap_rezalloc_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_realloc_zero_aligned_at(heap, p, newsize, alignment, offset, true);+static void* mi_theap_rezalloc_aligned_at(mi_theap_t* theap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_realloc_zero_aligned_at(theap, p, newsize, alignment, offset, true);}-mi_decl_nodiscard void* mi_heap_rezalloc_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {- return mi_heap_realloc_zero_aligned(heap, p, newsize, alignment, true);+static void* mi_theap_rezalloc_aligned(mi_theap_t* theap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {+ return mi_theap_realloc_zero_aligned(theap, p, newsize, alignment, true);}-mi_decl_nodiscard 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 {+static void* mi_theap_recalloc_aligned_at(mi_theap_t* theap, void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(newcount, size, &total)) return NULL;- return mi_heap_rezalloc_aligned_at(heap, p, total, alignment, offset);+ return mi_theap_rezalloc_aligned_at(theap, p, total, alignment, offset);}-mi_decl_nodiscard void* mi_heap_recalloc_aligned(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept {+static void* mi_theap_recalloc_aligned(mi_theap_t* theap, void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(newcount, size, &total)) return NULL;- return mi_heap_rezalloc_aligned(heap, p, total, alignment);+ return mi_theap_rezalloc_aligned(theap, p, total, alignment);}+mi_decl_nodiscard void* mi_realloc_aligned_at(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_realloc_aligned_at(mi_prim_get_default_heap(), p, newsize, alignment, offset);+ return mi_theap_realloc_aligned_at(_mi_theap_default(), p, newsize, alignment, offset);}mi_decl_nodiscard void* mi_realloc_aligned(void* p, size_t newsize, size_t alignment) mi_attr_noexcept {- return mi_heap_realloc_aligned(mi_prim_get_default_heap(), p, newsize, alignment);+ return mi_theap_realloc_aligned(_mi_theap_default(), p, newsize, alignment);}mi_decl_nodiscard void* mi_rezalloc_aligned_at(void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_rezalloc_aligned_at(mi_prim_get_default_heap(), p, newsize, alignment, offset);+ return mi_theap_rezalloc_aligned_at(_mi_theap_default(), p, newsize, alignment, offset);}mi_decl_nodiscard void* mi_rezalloc_aligned(void* p, size_t newsize, size_t alignment) mi_attr_noexcept {- return mi_heap_rezalloc_aligned(mi_prim_get_default_heap(), p, newsize, alignment);+ return mi_theap_rezalloc_aligned(_mi_theap_default(), p, newsize, alignment);}mi_decl_nodiscard void* mi_recalloc_aligned_at(void* p, size_t newcount, size_t size, size_t alignment, size_t offset) mi_attr_noexcept {- return mi_heap_recalloc_aligned_at(mi_prim_get_default_heap(), p, newcount, size, alignment, offset);+ return mi_theap_recalloc_aligned_at(_mi_theap_default(), p, newcount, size, alignment, offset);}mi_decl_nodiscard void* mi_recalloc_aligned(void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept {- return mi_heap_recalloc_aligned(mi_prim_get_default_heap(), p, newcount, size, alignment);+ return mi_theap_recalloc_aligned(_mi_theap_default(), p, newcount, size, alignment);+}+++mi_decl_nodiscard void* mi_heap_realloc_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_realloc_aligned_at(_mi_heap_theap(heap), p, newsize, alignment, offset);+}++mi_decl_nodiscard void* mi_heap_realloc_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {+ return mi_theap_realloc_aligned(_mi_heap_theap(heap), p, newsize, alignment);+}++mi_decl_nodiscard void* mi_heap_rezalloc_aligned_at(mi_heap_t* heap, void* p, size_t newsize, size_t alignment, size_t offset) mi_attr_noexcept {+ return mi_theap_rezalloc_aligned_at(_mi_heap_theap(heap), p, newsize, alignment, offset);+}++mi_decl_nodiscard void* mi_heap_rezalloc_aligned(mi_heap_t* heap, void* p, size_t newsize, size_t alignment) mi_attr_noexcept {+ return mi_theap_rezalloc_aligned(_mi_heap_theap(heap), p, newsize, alignment);+}++mi_decl_nodiscard 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 {+ return mi_theap_recalloc_aligned_at(_mi_heap_theap(heap), p, newcount, size, alignment, offset);+}++mi_decl_nodiscard void* mi_heap_recalloc_aligned(mi_heap_t* heap, void* p, size_t newcount, size_t size, size_t alignment) mi_attr_noexcept {+ return mi_theap_recalloc_aligned(_mi_heap_theap(heap), p, newcount, size, alignment);}diff --git a/vendored/mimalloc/src/alloc-override.c b/vendored/mimalloc/src/alloc-override.cindex b5109ded0..882e0607a 100644--- a/vendored/mimalloc/src/alloc-override.c+++ b/vendored/mimalloc/src/alloc-override.c@@ -71,24 +71,20 @@ typedef void* mi_nothrow_t;#define MI_INTERPOSE_FUN(oldfun,newfun) { (const void*)&newfun, (const void*)&oldfun }#define MI_INTERPOSE_MI(fun) MI_INTERPOSE_FUN(fun,mi_##fun)- __attribute__((used)) static struct mi_interpose_s _mi_interposes[] __attribute__((section("__DATA, __interpose"))) =+ #define MI_INTERPOSE_DECLS(name) __attribute__((used)) static struct mi_interpose_s name[] __attribute__((section("__DATA, __interpose")))++ MI_INTERPOSE_DECLS(_mi_interposes) ={MI_INTERPOSE_MI(malloc),MI_INTERPOSE_MI(calloc),MI_INTERPOSE_MI(realloc),MI_INTERPOSE_MI(strdup),- #if defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7- MI_INTERPOSE_MI(strndup),- #endifMI_INTERPOSE_MI(realpath),MI_INTERPOSE_MI(posix_memalign),MI_INTERPOSE_MI(reallocf),MI_INTERPOSE_MI(valloc),MI_INTERPOSE_FUN(malloc_size,mi_malloc_size_checked),MI_INTERPOSE_MI(malloc_good_size),- #if defined(MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15- MI_INTERPOSE_MI(aligned_alloc),- #endif#ifdef MI_OSX_ZONE// we interpose malloc_default_zone in alloc-override-osx.c so we can use mi_free safelyMI_INTERPOSE_MI(free),@@ -99,6 +95,12 @@ typedef void* mi_nothrow_t;MI_INTERPOSE_FUN(vfree,mi_cfree),#endif};+ MI_INTERPOSE_DECLS(_mi_interposes_10_7) __OSX_AVAILABLE(10.7) = {+ MI_INTERPOSE_MI(strndup),+ };+ MI_INTERPOSE_DECLS(_mi_interposes_10_15) __OSX_AVAILABLE(10.15) = {+ MI_INTERPOSE_MI(aligned_alloc),+ };#ifdef __cplusplusextern "C" {@@ -134,14 +136,14 @@ typedef void* mi_nothrow_t;mi_decl_export void* malloc(size_t size) MI_FORWARD1(mi_malloc, size)mi_decl_export void* calloc(size_t size, size_t n) MI_FORWARD2(mi_calloc, size, n)mi_decl_export void* realloc(void* p, size_t newsize) MI_FORWARD2(mi_realloc, p, newsize)- mi_decl_export void free(void* p) MI_FORWARD0(mi_free, p)+ mi_decl_export void free(void* p) MI_FORWARD0(mi_free, p)// In principle we do not need to forward `strdup`/`strndup` but on some systems these do not use `malloc` internally (but a more primitive call)// We only override if `strdup` is not a macro (as on some older libc's, see issue #885)#if !defined(strdup)mi_decl_export char* strdup(const char* str) MI_FORWARD1(mi_strdup, str)#endif#if !defined(strndup) && (!defined(__APPLE__) || (defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7))- mi_decl_export char* strndup(const char* str, size_t n) MI_FORWARD2(mi_strndup, str, n)+ mi_decl_export char* strndup(const char* str, size_t n) MI_FORWARD2(mi_strndup, str, n)#endif#endif@@ -202,17 +204,17 @@ typedef void* mi_nothrow_t;void _ZdaPv(void* p) MI_FORWARD0(mi_free,p) // delete[]void _ZdlPvm(void* p, size_t n) MI_FORWARD02(mi_free_size,p,n)void _ZdaPvm(void* p, size_t n) MI_FORWARD02(mi_free_size,p,n)-+void _ZdlPvSt11align_val_t(void* p, size_t al) { mi_free_aligned(p,al); }void _ZdaPvSt11align_val_t(void* p, size_t al) { mi_free_aligned(p,al); }void _ZdlPvmSt11align_val_t(void* p, size_t n, size_t al) { mi_free_size_aligned(p,n,al); }void _ZdaPvmSt11align_val_t(void* p, size_t n, size_t al) { mi_free_size_aligned(p,n,al); }- void _ZdlPvRKSt9nothrow_t(void* p, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free(p); } // operator delete(void*, std::nothrow_t const&)+ void _ZdlPvRKSt9nothrow_t(void* p, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free(p); } // operator delete(void*, std::nothrow_t const&)void _ZdaPvRKSt9nothrow_t(void* p, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free(p); } // operator delete[](void*, std::nothrow_t const&)- void _ZdlPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete(void*, std::align_val_t, std::nothrow_t const&)- void _ZdaPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete[](void*, std::align_val_t, std::nothrow_t const&)-+ void _ZdlPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete(void*, std::align_val_t, std::nothrow_t const&)+ void _ZdaPvSt11align_val_tRKSt9nothrow_t(void* p, size_t al, mi_nothrow_t tag) { MI_UNUSED(tag); mi_free_aligned(p,al); } // operator delete[](void*, std::align_val_t, std::nothrow_t const&)+#if (MI_INTPTR_SIZE==8)void* _Znwm(size_t n) MI_FORWARD1(mi_new,n) // new 64-bitvoid* _Znam(size_t n) MI_FORWARD1(mi_new,n) // new[] 64-bitdiff --git a/vendored/mimalloc/src/alloc.c b/vendored/mimalloc/src/alloc.cindex ffa7b8b70..d7b34e8cb 100644--- a/vendored/mimalloc/src/alloc.c+++ b/vendored/mimalloc/src/alloc.c@@ -1,5 +1,6 @@+/* -----------------------------------------------------------------------------Copyright (c) 2018-2024, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -28,16 +29,21 @@ terms of the MIT license. A copy of the license can be found in the file// Fast allocation in a page: just pop from the free list.// Fall back to generic allocation only if the list is empty.// Note: in release mode the (inlined) routine is about 7 instructions with a single test.-extern inline void* _mi_page_malloc_zero(mi_heap_t* heap, mi_page_t* page, size_t size, bool zero) mi_attr_noexcept+static mi_decl_forceinline void* mi_page_malloc_zero(mi_theap_t* theap, mi_page_t* page, size_t size, bool zero, size_t* usable) mi_attr_noexcept{- mi_assert_internal(page->block_size == 0 /* empty heap */ || mi_page_block_size(page) >= size);+ if (page->block_size != 0) { // not the empty theap+ mi_assert_internal(mi_page_block_size(page) >= size);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ }// check the free listmi_block_t* const block = page->free;if mi_unlikely(block == NULL) {- return _mi_malloc_generic(heap, size, zero, 0);+ return _mi_malloc_generic(theap, size, (zero ? 1 : 0), usable);}mi_assert_internal(block != NULL && _mi_ptr_page(block) == page);+ if (usable != NULL) { *usable = mi_page_usable_block_size(page); };// pop from the free listpage->free = mi_block_next(page, block);@@ -54,49 +60,45 @@ extern inline void* _mi_page_malloc_zero(mi_heap_t* heap, mi_page_t* page, size_// allow use of the block internally// note: when tracking we need to avoid ever touching the MI_PADDING since// that is tracked by valgrind etc. as non-accessible (through the red-zone, see `mimalloc/track.h`)- mi_track_mem_undefined(block, mi_page_usable_block_size(page));-- // zero the block? note: we need to zero the full block size (issue #63)- if mi_unlikely(zero) {- mi_assert_internal(page->block_size != 0); // do not call with zero'ing for huge blocks (see _mi_malloc_generic)- mi_assert_internal(!mi_page_is_huge(page));- #if MI_PADDING- mi_assert_internal(page->block_size >= MI_PADDING_SIZE);- #endif- if (page->free_is_zero) {- block->next = 0;- mi_track_mem_defined(block, page->block_size - MI_PADDING_SIZE);- }- else {- _mi_memzero_aligned(block, page->block_size - MI_PADDING_SIZE);- }- }-- #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN- if (!zero && !mi_page_is_huge(page)) {- memset(block, MI_DEBUG_UNINIT, mi_page_usable_block_size(page));- }- #elif (MI_SECURE!=0)- if (!zero) { block->next = 0; } // don't leak internal data- #endif+ const size_t bsize = mi_page_usable_block_size(page);+ mi_track_mem_undefined(block, bsize);#if (MI_STAT>0)- const size_t bsize = mi_page_usable_block_size(page);- if (bsize <= MI_MEDIUM_OBJ_SIZE_MAX) {- mi_heap_stat_increase(heap, normal, bsize);- mi_heap_stat_counter_increase(heap, normal_count, 1);+ if (bsize <= MI_LARGE_MAX_OBJ_SIZE) {+ mi_theap_stat_increase(theap, malloc_normal, bsize);#if (MI_STAT>1)+ mi_theap_stat_counter_increase(theap, malloc_normal_count, 1);const size_t bin = _mi_bin(bsize);- mi_heap_stat_increase(heap, normal_bins[bin], 1);+ mi_theap_stat_increase(theap, malloc_bins[bin], 1);+ mi_theap_stat_increase(theap, malloc_requested, size - MI_PADDING_SIZE);#endif}#endif+ // zero the block? note: we need to zero the full block size (issue #63)+ if mi_likely(!zero) {+ // #if MI_SECURE+ block->next = 0; // don't leak internal data+ // #endif+ #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN+ if (!mi_page_is_huge(page)) { memset(block, MI_DEBUG_UNINIT, bsize); }+ #endif+ }+ else {+ if (!page->free_is_zero) {+ _mi_memzero_aligned(block, bsize);+ }+ else {+ block->next = 0;+ mi_track_mem_defined(block, bsize);+ }+ }+#if MI_PADDING // && !MI_TRACK_ENABLED- mi_padding_t* const padding = (mi_padding_t*)((uint8_t*)block + mi_page_usable_block_size(page));+ mi_padding_t* const padding = (mi_padding_t*)((uint8_t*)block + bsize);ptrdiff_t delta = ((uint8_t*)padding - (uint8_t*)block - (size - MI_PADDING_SIZE));#if (MI_DEBUG>=2)- mi_assert_internal(delta >= 0 && mi_page_usable_block_size(page) >= (size - MI_PADDING_SIZE + delta));+ mi_assert_internal(delta >= 0 && bsize >= (size - MI_PADDING_SIZE + delta));#endifmi_track_mem_defined(padding,sizeof(mi_padding_t)); // note: re-enable since mi_page_usable_block_size may set noaccesspadding->canary = mi_ptr_encode_canary(page,block,page->keys);@@ -113,45 +115,67 @@ extern inline void* _mi_page_malloc_zero(mi_heap_t* heap, mi_page_t* page, size_return block;}-// extra entries for improved efficiency in `alloc-aligned.c`.-extern void* _mi_page_malloc(mi_heap_t* heap, mi_page_t* page, size_t size) mi_attr_noexcept {- return _mi_page_malloc_zero(heap,page,size,false);-}-extern void* _mi_page_malloc_zeroed(mi_heap_t* heap, mi_page_t* page, size_t size) mi_attr_noexcept {- return _mi_page_malloc_zero(heap,page,size,true);+// extra entries for improved efficiency in `alloc-aligned.c` (and in `page.c:mi_malloc_generic`.+extern void* _mi_page_malloc_zero(mi_theap_t* theap, mi_page_t* page, size_t size, bool zero) mi_attr_noexcept {+ return mi_page_malloc_zero(theap, page, size, zero, NULL);}#if MI_GUARDED-mi_decl_restrict void* _mi_heap_malloc_guarded(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept;+mi_decl_restrict void* _mi_theap_malloc_guarded(mi_theap_t* theap, size_t size, bool zero) mi_attr_noexcept;#endif-static inline mi_decl_restrict void* mi_heap_malloc_small_zero(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept {- mi_assert(heap != NULL);+// main allocation primitives for small and generic allocation++// internal small size allocation+static mi_decl_forceinline mi_decl_restrict void* mi_theap_malloc_small_zero_nonnull(mi_theap_t* theap, size_t size, bool zero, size_t* usable) mi_attr_noexcept+{+ mi_assert(theap != NULL);mi_assert(size <= MI_SMALL_SIZE_MAX);#if MI_DEBUGconst uintptr_t tid = _mi_thread_id();- mi_assert(heap->thread_id == 0 || heap->thread_id == tid); // heaps are thread local+ mi_assert(theap->tld->thread_id == 0 || theap->tld->thread_id == tid); // theaps are thread local#endif#if (MI_PADDING || MI_GUARDED)- if (size == 0) { size = sizeof(void*); }+ if mi_unlikely(size == 0) { size = sizeof(void*); }#endif#if MI_GUARDED- if (mi_heap_malloc_use_guarded(heap,size)) {- return _mi_heap_malloc_guarded(heap, size, zero);+ if mi_unlikely(mi_theap_malloc_use_guarded(theap,size)) {+ return _mi_theap_malloc_guarded(theap, size, zero);}#endif// get page in constant time, and allocate from it- mi_page_t* page = _mi_heap_get_free_small_page(heap, size + MI_PADDING_SIZE);- void* const p = _mi_page_malloc_zero(heap, page, size + MI_PADDING_SIZE, zero);+ mi_page_t* page = _mi_theap_get_free_small_page(theap, size + MI_PADDING_SIZE);+ void* const p = mi_page_malloc_zero(theap, page, size + MI_PADDING_SIZE, zero, usable);mi_track_malloc(p,size,zero);- #if MI_STAT>1- if (p != NULL) {- if (!mi_heap_is_initialized(heap)) { heap = mi_prim_get_default_heap(); }- mi_heap_stat_increase(heap, malloc, mi_usable_size(p));+ #if MI_DEBUG>3+ if (p != NULL && zero) {+ mi_assert_expensive(mi_mem_is_zero(p, size));+ }+ #endif+ return p;+}++// internal generic allocation+static mi_decl_forceinline void* mi_theap_malloc_generic(mi_theap_t* theap, size_t size, bool zero, size_t huge_alignment, size_t* usable) mi_attr_noexcept+{+ #if MI_GUARDED+ #if MI_THEAP_INITASNULL+ if (theap!=NULL)+ #endif+ if (huge_alignment==0 && mi_theap_malloc_use_guarded(theap, size)) {+ return _mi_theap_malloc_guarded(theap, size, zero);}#endif+ #if !MI_THEAP_INITASNULL+ mi_assert(theap!=NULL);+ #endif+ mi_assert(theap==NULL || theap->tld->thread_id == 0 || theap->tld->thread_id == _mi_thread_id()); // theaps are thread local+ mi_assert((huge_alignment & 1)==0);+ void* const p = _mi_malloc_generic(theap, size + MI_PADDING_SIZE, (zero ? 1 : 0) | huge_alignment, usable); // note: size can overflow but it is detected in malloc_generic+ mi_track_malloc(p, size, zero);+#if MI_DEBUG>3if (p != NULL && zero) {mi_assert_expensive(mi_mem_is_zero(p, size));@@ -160,96 +184,156 @@ static inline mi_decl_restrict void* mi_heap_malloc_small_zero(mi_heap_t* heap,return p;}+// internal small allocation+static mi_decl_forceinline mi_decl_restrict void* mi_theap_malloc_small_zero(mi_theap_t* theap, size_t size, bool zero, size_t* usable) mi_attr_noexcept {+ #if MI_THEAP_INITASNULL+ if (theap!=NULL) {+ return mi_theap_malloc_small_zero_nonnull(theap, size, zero, usable);+ }+ else {+ return mi_theap_malloc_generic(theap, size, zero, 0, usable); // tailcall+ }+ #else+ return mi_theap_malloc_small_zero_nonnull(theap, size, zero, usable);+ #endif+}++// allocate a small block-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_heap_malloc_small(mi_heap_t* heap, size_t size) mi_attr_noexcept {- return mi_heap_malloc_small_zero(heap, size, false);+mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_malloc_small(mi_theap_t* theap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_small_zero(theap, size, false, NULL);+}++mi_decl_nodiscard mi_decl_restrict void* mi_malloc_small(size_t size) mi_attr_noexcept {+ return mi_theap_malloc_small(_mi_theap_default(), size);}-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_malloc_small(size_t size) mi_attr_noexcept {- return mi_heap_malloc_small(mi_prim_get_default_heap(), size);+mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc_small(mi_heap_t* heap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_small_zero_nonnull(_mi_heap_theap(heap), size, false, NULL);}-// The main allocation function-extern inline void* _mi_heap_malloc_zero_ex(mi_heap_t* heap, size_t size, bool zero, size_t huge_alignment) mi_attr_noexcept {+// The main internal allocation functions+static mi_decl_forceinline void* mi_theap_malloc_zero_nonnull(mi_theap_t* theap, size_t size, bool zero, size_t huge_alignment, size_t* usable) mi_attr_noexcept {// fast path for small objectsif mi_likely(size <= MI_SMALL_SIZE_MAX) {mi_assert_internal(huge_alignment == 0);- return mi_heap_malloc_small_zero(heap, size, zero);+ return mi_theap_malloc_small_zero_nonnull(theap, size, zero, usable);}- #if MI_GUARDED- else if (huge_alignment==0 && mi_heap_malloc_use_guarded(heap,size)) {- return _mi_heap_malloc_guarded(heap, size, zero);+ else {+ return mi_theap_malloc_generic(theap, size, zero, huge_alignment, usable);}+}++extern mi_decl_forceinline void* _mi_theap_malloc_zero_ex(mi_theap_t* theap, size_t size, bool zero, size_t huge_alignment, size_t* usable) mi_attr_noexcept {+ // fast path for small objects+ #if MI_THEAP_INITASNULL+ if mi_likely(theap!=NULL && size <= MI_SMALL_SIZE_MAX)+ #else+ if mi_likely(size <= MI_SMALL_SIZE_MAX)#endif+ {+ mi_assert_internal(huge_alignment == 0);+ return mi_theap_malloc_small_zero_nonnull(theap, size, zero, usable);+ }else {- // regular allocation- mi_assert(heap!=NULL);- mi_assert(heap->thread_id == 0 || heap->thread_id == _mi_thread_id()); // heaps are thread local- void* const p = _mi_malloc_generic(heap, size + MI_PADDING_SIZE, zero, huge_alignment); // note: size can overflow but it is detected in malloc_generic- mi_track_malloc(p,size,zero);-- #if MI_STAT>1- if (p != NULL) {- if (!mi_heap_is_initialized(heap)) { heap = mi_prim_get_default_heap(); }- mi_heap_stat_increase(heap, malloc, mi_usable_size(p));- }- #endif- #if MI_DEBUG>3- if (p != NULL && zero) {- mi_assert_expensive(mi_mem_is_zero(p, size));- }- #endif- return p;+ return mi_theap_malloc_generic(theap, size, zero, huge_alignment, usable);}}-extern inline void* _mi_heap_malloc_zero(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept {- return _mi_heap_malloc_zero_ex(heap, size, zero, 0);+void* _mi_theap_malloc_zero(mi_theap_t* theap, size_t size, bool zero, size_t* usable) mi_attr_noexcept {+ return _mi_theap_malloc_zero_ex(theap, size, zero, 0, usable);}-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_heap_malloc(mi_heap_t* heap, size_t size) mi_attr_noexcept {- return _mi_heap_malloc_zero(heap, size, false);++// Main allocation functions++mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_malloc(mi_theap_t* theap, size_t size) mi_attr_noexcept {+ return _mi_theap_malloc_zero(theap, size, false, NULL);}-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_malloc(size_t size) mi_attr_noexcept {- return mi_heap_malloc(mi_prim_get_default_heap(), size);+mi_decl_nodiscard mi_decl_restrict void* mi_malloc(size_t size) mi_attr_noexcept {+ return mi_theap_malloc(_mi_theap_default(), size);}+mi_decl_nodiscard mi_decl_restrict void* mi_heap_malloc(mi_heap_t* heap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_zero_nonnull(_mi_heap_theap(heap), size, false, 0, NULL);+}++// zero initialized small blockmi_decl_nodiscard mi_decl_restrict void* mi_zalloc_small(size_t size) mi_attr_noexcept {- return mi_heap_malloc_small_zero(mi_prim_get_default_heap(), size, true);+ return mi_theap_malloc_small_zero(_mi_theap_default(), size, true, NULL);}-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_heap_zalloc(mi_heap_t* heap, size_t size) mi_attr_noexcept {- return _mi_heap_malloc_zero(heap, size, true);+mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_zalloc(mi_theap_t* theap, size_t size) mi_attr_noexcept {+ return _mi_theap_malloc_zero(theap, size, true, NULL);}mi_decl_nodiscard mi_decl_restrict void* mi_zalloc(size_t size) mi_attr_noexcept {- return mi_heap_zalloc(mi_prim_get_default_heap(),size);+ return _mi_theap_malloc_zero(_mi_theap_default(), size, true, NULL);}+mi_decl_nodiscard mi_decl_restrict void* mi_heap_zalloc(mi_heap_t* heap, size_t size) mi_attr_noexcept {+ return mi_theap_malloc_zero_nonnull(_mi_heap_theap(heap), size, true, 0, NULL);+}-mi_decl_nodiscard extern inline mi_decl_restrict void* mi_heap_calloc(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept {+mi_decl_nodiscard extern inline mi_decl_restrict void* mi_theap_calloc(mi_theap_t* theap, size_t count, size_t size) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(count,size,&total)) return NULL;- return mi_heap_zalloc(heap,total);+ return mi_theap_zalloc(theap,total);}mi_decl_nodiscard mi_decl_restrict void* mi_calloc(size_t count, size_t size) mi_attr_noexcept {- return mi_heap_calloc(mi_prim_get_default_heap(),count,size);+ return mi_theap_calloc(_mi_theap_default(),count,size);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_calloc(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept {+ size_t total;+ if (mi_count_size_overflow(count, size, &total)) return NULL;+ return mi_heap_zalloc(heap, total);+}++// Return usable size+mi_decl_nodiscard mi_decl_restrict void* mi_umalloc_small(size_t size, size_t* usable) mi_attr_noexcept {+ return mi_theap_malloc_small_zero(_mi_theap_default(), size, false, usable);+}++mi_decl_nodiscard mi_decl_restrict void* mi_theap_umalloc(mi_theap_t* theap, size_t size, size_t* usable) mi_attr_noexcept {+ return _mi_theap_malloc_zero_ex(theap, size, false, 0, usable);+}++mi_decl_nodiscard mi_decl_restrict void* mi_umalloc(size_t size, size_t* usable) mi_attr_noexcept {+ return mi_theap_umalloc(_mi_theap_default(), size, usable);+}++mi_decl_nodiscard mi_decl_restrict void* mi_uzalloc(size_t size, size_t* usable) mi_attr_noexcept {+ return _mi_theap_malloc_zero_ex(_mi_theap_default(), size, true, 0, usable);+}++mi_decl_nodiscard mi_decl_restrict void* mi_ucalloc(size_t count, size_t size, size_t* usable) mi_attr_noexcept {+ size_t total;+ if (mi_count_size_overflow(count,size,&total)) return NULL;+ return mi_uzalloc(total, usable);}// Uninitialized `calloc`-mi_decl_nodiscard extern mi_decl_restrict void* mi_heap_mallocn(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept {+static mi_decl_restrict void* mi_theap_mallocn(mi_theap_t* theap, size_t count, size_t size) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(count, size, &total)) return NULL;- return mi_heap_malloc(heap, total);+ return mi_theap_malloc(theap, total);}mi_decl_nodiscard mi_decl_restrict void* mi_mallocn(size_t count, size_t size) mi_attr_noexcept {- return mi_heap_mallocn(mi_prim_get_default_heap(),count,size);+ return mi_theap_mallocn(_mi_theap_default(),count,size);}+mi_decl_nodiscard mi_decl_restrict void* mi_heap_mallocn(mi_heap_t* heap, size_t count, size_t size) mi_attr_noexcept {+ size_t total;+ if (mi_count_size_overflow(count, size, &total)) return NULL;+ return mi_heap_malloc(heap, total);+}++// Expand (or shrink) in place (or fail)void* mi_expand(void* p, size_t newsize) mi_attr_noexcept {#if MI_PADDING@@ -258,25 +342,40 @@ void* mi_expand(void* p, size_t newsize) mi_attr_noexcept {return NULL;#elseif (p == NULL) return NULL;- const size_t size = _mi_usable_size(p,"mi_expand");+ const mi_page_t* const page = mi_validate_ptr_page(p,"mi_expand");+ const size_t size = _mi_usable_size(p,page);if (newsize > size) return NULL;return p; // it fits#endif}-void* _mi_heap_realloc_zero(mi_heap_t* heap, void* p, size_t newsize, bool zero) mi_attr_noexcept {+void* _mi_theap_realloc_zero(mi_theap_t* theap, void* p, size_t newsize, bool zero, size_t* usable_pre, size_t* usable_post) mi_attr_noexcept {// if p == NULL then behave as malloc.// else if size == 0 then reallocate to a zero-sized block (and don't return NULL, just as mi_malloc(0)).// (this means that returning NULL always indicates an error, and `p` will not have been freed in that case.)- const size_t size = _mi_usable_size(p,"mi_realloc"); // also works if p == NULL (with size 0)- if mi_unlikely(newsize <= size && newsize >= (size / 2) && newsize > 0) { // note: newsize must be > 0 or otherwise we return NULL for realloc(NULL,0)+ const mi_page_t* page;+ size_t size;+ if (p==NULL) {+ page = NULL;+ size = 0;+ if (usable_pre!=NULL) { *usable_pre = 0; }+ }+ else {+ page = mi_validate_ptr_page(p,"mi_realloc");+ size = _mi_usable_size(p,page);+ if (usable_pre!=NULL) { *usable_pre = mi_page_usable_block_size(page); }+ }+ if mi_unlikely(newsize<=size && newsize>=(size/2) && newsize>0 // note: newsize must be > 0 or otherwise we return NULL for realloc(NULL,0)+ && mi_page_heap(page)==theap->heap) // and within the same heap+ {mi_assert_internal(p!=NULL);// todo: do not track as the usable size is still the same in the free; adjust potential padding?// mi_track_resize(p,size,newsize)// if (newsize < size) { mi_track_mem_noaccess((uint8_t*)p + newsize, size - newsize); }+ if (usable_post!=NULL) { *usable_post = mi_page_usable_block_size(page); }return p; // reallocation still fits and not more than 50% waste}- void* newp = mi_heap_malloc(heap,newsize);+ void* newp = mi_theap_umalloc(theap,newsize,usable_post);if mi_likely(newp != NULL) {if (zero && newsize > size) {// also set last word in the previous allocation to zero to ensure any padding is zero-initialized@@ -290,60 +389,86 @@ void* _mi_heap_realloc_zero(mi_heap_t* heap, void* p, size_t newsize, bool zero)const size_t copysize = (newsize > size ? size : newsize);mi_track_mem_defined(p,copysize); // _mi_useable_size may be too large for byte precise memory tracking.._mi_memcpy(newp, p, copysize);- mi_free(p); // only free the original pointer if successful+ mi_free(p); // only free the original pointer if successful // todo: optimize since page is known?}}return newp;}-mi_decl_nodiscard void* mi_heap_realloc(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {- return _mi_heap_realloc_zero(heap, p, newsize, false);+mi_decl_nodiscard void* mi_theap_realloc(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept {+ return _mi_theap_realloc_zero(theap, p, newsize, false, NULL, NULL);}-mi_decl_nodiscard void* mi_heap_reallocn(mi_heap_t* heap, void* p, size_t count, size_t size) mi_attr_noexcept {+static void* mi_theap_reallocn(mi_theap_t* theap, void* p, size_t count, size_t size) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(count, size, &total)) return NULL;- return mi_heap_realloc(heap, p, total);+ return mi_theap_realloc(theap, p, total);}// Reallocate but free `p` on errors-mi_decl_nodiscard void* mi_heap_reallocf(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {- void* newp = mi_heap_realloc(heap, p, newsize);+static void* mi_theap_reallocf(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept {+ void* newp = mi_theap_realloc(theap, p, newsize);if (newp==NULL && p!=NULL) mi_free(p);return newp;}-mi_decl_nodiscard void* mi_heap_rezalloc(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {- return _mi_heap_realloc_zero(heap, p, newsize, true);+static void* mi_theap_rezalloc(mi_theap_t* theap, void* p, size_t newsize) mi_attr_noexcept {+ return _mi_theap_realloc_zero(theap, p, newsize, true, NULL, NULL);}-mi_decl_nodiscard void* mi_heap_recalloc(mi_heap_t* heap, void* p, size_t count, size_t size) mi_attr_noexcept {+static void* mi_theap_recalloc(mi_theap_t* theap, void* p, size_t count, size_t size) mi_attr_noexcept {size_t total;if (mi_count_size_overflow(count, size, &total)) return NULL;- return mi_heap_rezalloc(heap, p, total);+ return mi_theap_rezalloc(theap, p, total);}mi_decl_nodiscard void* mi_realloc(void* p, size_t newsize) mi_attr_noexcept {- return mi_heap_realloc(mi_prim_get_default_heap(),p,newsize);+ return mi_theap_realloc(_mi_theap_default(),p,newsize);}mi_decl_nodiscard void* mi_reallocn(void* p, size_t count, size_t size) mi_attr_noexcept {- return mi_heap_reallocn(mi_prim_get_default_heap(),p,count,size);+ return mi_theap_reallocn(_mi_theap_default(),p,count,size);+}++mi_decl_nodiscard void* mi_urealloc(void* p, size_t newsize, size_t* usable_pre, size_t* usable_post) mi_attr_noexcept {+ return _mi_theap_realloc_zero(_mi_theap_default(),p,newsize, false, usable_pre, usable_post);}// Reallocate but free `p` on errorsmi_decl_nodiscard void* mi_reallocf(void* p, size_t newsize) mi_attr_noexcept {- return mi_heap_reallocf(mi_prim_get_default_heap(),p,newsize);+ return mi_theap_reallocf(_mi_theap_default(),p,newsize);}mi_decl_nodiscard void* mi_rezalloc(void* p, size_t newsize) mi_attr_noexcept {- return mi_heap_rezalloc(mi_prim_get_default_heap(), p, newsize);+ return mi_theap_rezalloc(_mi_theap_default(), p, newsize);}mi_decl_nodiscard void* mi_recalloc(void* p, size_t count, size_t size) mi_attr_noexcept {- return mi_heap_recalloc(mi_prim_get_default_heap(), p, count, size);+ return mi_theap_recalloc(_mi_theap_default(), p, count, size);+}+++mi_decl_nodiscard void* mi_heap_realloc(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {+ return mi_theap_realloc(_mi_heap_theap(heap), p, newsize);+}++mi_decl_nodiscard void* mi_heap_reallocn(mi_heap_t* heap, void* p, size_t count, size_t size) mi_attr_noexcept {+ return mi_theap_reallocn(_mi_heap_theap(heap), p, count, size);+}++// Reallocate but free `p` on errors+mi_decl_nodiscard void* mi_heap_reallocf(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {+ return mi_theap_reallocf(_mi_heap_theap(heap), p, newsize);+}++mi_decl_nodiscard void* mi_heap_rezalloc(mi_heap_t* heap, void* p, size_t newsize) mi_attr_noexcept {+ return mi_theap_rezalloc(_mi_heap_theap(heap), p, newsize);+}++mi_decl_nodiscard void* mi_heap_recalloc(mi_heap_t* heap, void* p, size_t count, size_t size) mi_attr_noexcept {+ return mi_theap_recalloc(_mi_heap_theap(heap), p, count, size);}@@ -353,10 +478,10 @@ mi_decl_nodiscard void* mi_recalloc(void* p, size_t count, size_t size) mi_attr_// ------------------------------------------------------// `strdup` using mi_malloc-mi_decl_nodiscard mi_decl_restrict char* mi_heap_strdup(mi_heap_t* heap, const char* s) mi_attr_noexcept {+mi_decl_nodiscard static mi_decl_restrict char* mi_theap_strdup(mi_theap_t* theap, const char* s) mi_attr_noexcept {if (s == NULL) return NULL;size_t len = _mi_strlen(s);- char* t = (char*)mi_heap_malloc(heap,len+1);+ char* t = (char*)mi_theap_malloc(theap,len+1);if (t == NULL) return NULL;_mi_memcpy(t, s, len);t[len] = 0;@@ -364,14 +489,18 @@ mi_decl_nodiscard mi_decl_restrict char* mi_heap_strdup(mi_heap_t* heap, const c}mi_decl_nodiscard mi_decl_restrict char* mi_strdup(const char* s) mi_attr_noexcept {- return mi_heap_strdup(mi_prim_get_default_heap(), s);+ return mi_theap_strdup(_mi_theap_default(), s);+}++mi_decl_nodiscard mi_decl_restrict char* mi_heap_strdup(mi_heap_t* heap, const char* s) mi_attr_noexcept {+ return mi_theap_strdup(_mi_heap_theap(heap), s);}// `strndup` using mi_malloc-mi_decl_nodiscard mi_decl_restrict char* mi_heap_strndup(mi_heap_t* heap, const char* s, size_t n) mi_attr_noexcept {+mi_decl_nodiscard static mi_decl_restrict char* mi_theap_strndup(mi_theap_t* theap, const char* s, size_t n) mi_attr_noexcept {if (s == NULL) return NULL;const size_t len = _mi_strnlen(s,n); // len <= n- char* t = (char*)mi_heap_malloc(heap, len+1);+ char* t = (char*)mi_theap_malloc(theap, len+1);if (t == NULL) return NULL;_mi_memcpy(t, s, len);t[len] = 0;@@ -379,7 +508,11 @@ mi_decl_nodiscard mi_decl_restrict char* mi_heap_strndup(mi_heap_t* heap, const}mi_decl_nodiscard mi_decl_restrict char* mi_strndup(const char* s, size_t n) mi_attr_noexcept {- return mi_heap_strndup(mi_prim_get_default_heap(),s,n);+ return mi_theap_strndup(_mi_theap_default(),s,n);+}++mi_decl_nodiscard mi_decl_restrict char* mi_heap_strndup(mi_heap_t* heap, const char* s, size_t n) mi_attr_noexcept {+ return mi_theap_strndup(_mi_heap_theap(heap), s, n);}#ifndef __wasi__@@ -389,7 +522,7 @@ mi_decl_nodiscard mi_decl_restrict char* mi_strndup(const char* s, size_t n) mi_#define PATH_MAX MAX_PATH#endif-mi_decl_nodiscard mi_decl_restrict char* mi_heap_realpath(mi_heap_t* heap, const char* fname, char* resolved_name) mi_attr_noexcept {+mi_decl_nodiscard static mi_decl_restrict char* mi_theap_realpath(mi_theap_t* theap, const char* fname, char* resolved_name) mi_attr_noexcept {// todo: use GetFullPathNameW to allow longer file nameschar buf[PATH_MAX];DWORD res = GetFullPathNameA(fname, PATH_MAX, (resolved_name == NULL ? buf : resolved_name), NULL);@@ -403,53 +536,31 @@ mi_decl_nodiscard mi_decl_restrict char* mi_heap_realpath(mi_heap_t* heap, constreturn resolved_name;}else {- return mi_heap_strndup(heap, buf, PATH_MAX);+ return mi_theap_strndup(theap, buf, PATH_MAX);}}#else-/*-#include <unistd.h> // pathconf-static size_t mi_path_max(void) {- static size_t path_max = 0;- if (path_max <= 0) {- long m = pathconf("/",_PC_PATH_MAX);- if (m <= 0) path_max = 4096; // guess- else if (m < 256) path_max = 256; // at least 256- else path_max = m;- }- return path_max;-}-*/-char* mi_heap_realpath(mi_heap_t* heap, const char* fname, char* resolved_name) mi_attr_noexcept {+char* mi_theap_realpath(mi_theap_t* theap, const char* fname, char* resolved_name) mi_attr_noexcept {if (resolved_name != NULL) {return realpath(fname,resolved_name);}else {char* rname = realpath(fname, NULL);if (rname == NULL) return NULL;- char* result = mi_heap_strdup(heap, rname);+ char* result = mi_theap_strdup(theap, rname);mi_cfree(rname); // use checked free (which may be redirected to our free but that's ok)// note: with ASAN realpath is intercepted and mi_cfree may leak the returned pointer :-(return result;}- /*- const size_t n = mi_path_max();- char* buf = (char*)mi_malloc(n+1);- if (buf == NULL) {- errno = ENOMEM;- return NULL;- }- char* rname = realpath(fname,buf);- char* result = mi_heap_strndup(heap,rname,n); // ok if `rname==NULL`- mi_free(buf);- return result;- }- */}#endifmi_decl_nodiscard mi_decl_restrict char* mi_realpath(const char* fname, char* resolved_name) mi_attr_noexcept {- return mi_heap_realpath(mi_prim_get_default_heap(),fname,resolved_name);+ return mi_theap_realpath(_mi_theap_default(),fname,resolved_name);+}++mi_decl_nodiscard mi_decl_restrict char* mi_heap_realpath(mi_heap_t* heap, const char* fname, char* resolved_name) mi_attr_noexcept {+ return mi_theap_realpath(_mi_heap_theap(heap), fname, resolved_name);}#endif@@ -499,7 +610,7 @@ static std_new_handler_t mi_get_new_handler(void) {}#else// note: on windows we could dynamically link to `?get_new_handler@std@@YAP6AXXZXZ`.-static std_new_handler_t mi_get_new_handler() {+static std_new_handler_t mi_get_new_handler(void) {return NULL;}#endif@@ -520,43 +631,57 @@ static bool mi_try_new_handler(bool nothrow) {}#endif-mi_decl_export mi_decl_noinline void* mi_heap_try_new(mi_heap_t* heap, size_t size, bool nothrow ) {+static mi_decl_noinline void* mi_theap_try_new(mi_theap_t* theap, size_t size, bool nothrow ) {void* p = NULL;while(p == NULL && mi_try_new_handler(nothrow)) {- p = mi_heap_malloc(heap,size);+ p = mi_theap_malloc(theap,size);}return p;}static mi_decl_noinline void* mi_try_new(size_t size, bool nothrow) {- return mi_heap_try_new(mi_prim_get_default_heap(), size, nothrow);+ return mi_theap_try_new(_mi_theap_default(), size, nothrow);}+static mi_decl_noinline void* mi_heap_try_new(mi_heap_t* heap, size_t size, bool nothrow) {+ return mi_theap_try_new(_mi_heap_theap(heap), size, nothrow);+}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_alloc_new(mi_heap_t* heap, size_t size) {- void* p = mi_heap_malloc(heap,size);- if mi_unlikely(p == NULL) return mi_heap_try_new(heap, size, false);++mi_decl_nodiscard static mi_decl_restrict void* mi_theap_alloc_new(mi_theap_t* theap, size_t size) {+ void* p = mi_theap_malloc(theap,size);+ if mi_unlikely(p == NULL) return mi_theap_try_new(theap, size, false);return p;}mi_decl_nodiscard mi_decl_restrict void* mi_new(size_t size) {- return mi_heap_alloc_new(mi_prim_get_default_heap(), size);+ return mi_theap_alloc_new(_mi_theap_default(), size);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_alloc_new(mi_heap_t* heap, size_t size) {+ void* p = mi_heap_malloc(heap, size);+ if mi_unlikely(p == NULL) return mi_heap_try_new(heap, size, false);+ return p;}-mi_decl_nodiscard mi_decl_restrict void* mi_heap_alloc_new_n(mi_heap_t* heap, size_t count, size_t size) {+mi_decl_nodiscard static mi_decl_restrict void* mi_theap_alloc_new_n(mi_theap_t* theap, size_t count, size_t size) {size_t total;if mi_unlikely(mi_count_size_overflow(count, size, &total)) {mi_try_new_handler(false); // on overflow we invoke the try_new_handler once to potentially throw std::bad_allocreturn NULL;}else {- return mi_heap_alloc_new(heap,total);+ return mi_theap_alloc_new(theap,total);}}mi_decl_nodiscard mi_decl_restrict void* mi_new_n(size_t count, size_t size) {- return mi_heap_alloc_new_n(mi_prim_get_default_heap(), count, size);+ return mi_theap_alloc_new_n(_mi_theap_default(), count, size);+}++mi_decl_nodiscard mi_decl_restrict void* mi_heap_alloc_new_n(mi_heap_t* heap, size_t count, size_t size) {+ return mi_theap_alloc_new_n(_mi_heap_theap(heap), count, size);}@@ -604,18 +729,17 @@ mi_decl_nodiscard void* mi_new_reallocn(void* p, size_t newcount, size_t size) {}#if MI_GUARDED-// We always allocate a guarded allocation at an offset (`mi_page_has_aligned` will be true).+// We always allocate a guarded allocation at an offset (`mi_page_has_interior_pointers` will be true).// We then set the first word of the block to `0` for regular offset aligned allocations (in `alloc-aligned.c`)// and the first word to `~0` for guarded allocations to have a correct `mi_usable_size`static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {// TODO: we can still make padding work by moving it out of the guard page areami_page_t* const page = _mi_ptr_page(block);- mi_page_set_has_aligned(page, true);+ mi_page_set_has_interior_pointers(page, true);block->next = MI_BLOCK_TAG_GUARDED;// set guard page at the end of the block- mi_segment_t* const segment = _mi_page_segment(page);const size_t block_size = mi_page_block_size(page); // must use `block_size` to match `mi_free_local`const size_t os_page_size = _mi_os_page_size();mi_assert_internal(block_size >= obj_size + os_page_size + sizeof(mi_block_t));@@ -625,9 +749,15 @@ static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {return NULL;}uint8_t* guard_page = (uint8_t*)block + block_size - os_page_size;+ // note: the alignment of the guard page relies on blocks being os_page_size aligned which+ // is ensured in `mi_arena_page_alloc_fresh`.+ mi_assert_internal(_mi_is_aligned(block, os_page_size));mi_assert_internal(_mi_is_aligned(guard_page, os_page_size));- if (segment->allow_decommit && _mi_is_aligned(guard_page, os_page_size)) {- _mi_os_protect(guard_page, os_page_size);+ if (!page->memid.is_pinned && _mi_is_aligned(guard_page, os_page_size)) {+ const bool ok = _mi_os_protect(guard_page, os_page_size);+ if mi_unlikely(!ok) {+ _mi_warning_message("failed to set a guard page behind an object (object %p of size %zu)\n", block, block_size);+ }}else {_mi_warning_message("unable to set a guard page behind an object due to pinned memory (large OS pages?) (object %p of size %zu)\n", block, block_size);@@ -636,17 +766,17 @@ static void* mi_block_ptr_set_guarded(mi_block_t* block, size_t obj_size) {// align pointer just in front of the guard pagesize_t offset = block_size - os_page_size - obj_size;mi_assert_internal(offset > sizeof(mi_block_t));- if (offset > MI_BLOCK_ALIGNMENT_MAX) {+ if (offset > MI_PAGE_MAX_OVERALLOC_ALIGN) {// give up to place it right in front of the guard page if the offset is too large for unalignment- offset = MI_BLOCK_ALIGNMENT_MAX;+ offset = MI_PAGE_MAX_OVERALLOC_ALIGN;}- void* p = (uint8_t*)block + offset;+ void* p = (uint8_t*)block + offset;mi_track_align(block, p, offset, obj_size);mi_track_mem_defined(block, sizeof(mi_block_t));return p;}-mi_decl_restrict void* _mi_heap_malloc_guarded(mi_heap_t* heap, size_t size, bool zero) mi_attr_noexcept+mi_decl_restrict void* _mi_theap_malloc_guarded(mi_theap_t* theap, size_t size, bool zero) mi_attr_noexcept{#if defined(MI_PADDING_SIZE)mi_assert(MI_PADDING_SIZE==0);@@ -657,18 +787,19 @@ mi_decl_restrict void* _mi_heap_malloc_guarded(mi_heap_t* heap, size_t size, booconst size_t obj_size = (mi_option_is_enabled(mi_option_guarded_precise) ? size : _mi_align_up(size, MI_MAX_ALIGN_SIZE));const size_t bsize = _mi_align_up(_mi_align_up(obj_size, MI_MAX_ALIGN_SIZE) + sizeof(mi_block_t), MI_MAX_ALIGN_SIZE);const size_t req_size = _mi_align_up(bsize + os_page_size, os_page_size);- mi_block_t* const block = (mi_block_t*)_mi_malloc_generic(heap, req_size, zero, 0 /* huge_alignment */);+ mi_block_t* const block = (mi_block_t*)_mi_malloc_generic(theap, req_size, (zero ? 1 : 0), NULL);if (block==NULL) return NULL;- void* const p = mi_block_ptr_set_guarded(block, obj_size);+ void* const p = mi_block_ptr_set_guarded(block, obj_size);// stats- mi_track_malloc(p, size, zero);+ mi_track_malloc(p, size, zero);if (p != NULL) {- if (!mi_heap_is_initialized(heap)) { heap = mi_prim_get_default_heap(); }+ if (!mi_theap_is_initialized(theap)) { theap = _mi_theap_default(); }#if MI_STAT>1- mi_heap_stat_increase(heap, malloc, mi_usable_size(p));+ mi_theap_stat_adjust_decrease(theap, malloc_requested, req_size);+ mi_theap_stat_increase(theap, malloc_requested, size);#endif- _mi_stat_counter_increase(&heap->tld->stats.guarded_alloc_count, 1);+ mi_theap_stat_counter_increase(theap, malloc_guarded_count, 1);}#if MI_DEBUG>3if (p != NULL && zero) {@@ -685,17 +816,20 @@ mi_decl_restrict void* _mi_heap_malloc_guarded(mi_heap_t* heap, size_t size, boo#ifdef __cplusplusvoid* _mi_externs[] = {- (void*)&_mi_page_malloc,(void*)&_mi_page_malloc_zero,- (void*)&_mi_heap_malloc_zero,- (void*)&_mi_heap_malloc_zero_ex,+ (void*)&_mi_theap_malloc_zero,+ (void*)&_mi_theap_malloc_zero_ex,+ (void*)&mi_theap_malloc,+ (void*)&mi_theap_zalloc,+ (void*)&mi_theap_malloc_small,(void*)&mi_malloc,(void*)&mi_malloc_small,+ (void*)&mi_zalloc,(void*)&mi_zalloc_small,(void*)&mi_heap_malloc,- (void*)&mi_heap_zalloc,(void*)&mi_heap_malloc_small,- // (void*)&mi_heap_alloc_new,- // (void*)&mi_heap_alloc_new_n+ (void*)&mi_malloc_aligned+ // (void*)&mi_theap_alloc_new,+ // (void*)&mi_theap_alloc_new_n};#endifdiff --git a/vendored/mimalloc/src/arena-abandon.c b/vendored/mimalloc/src/arena-abandon.cdeleted file mode 100644index 460c80fc2..000000000--- a/vendored/mimalloc/src/arena-abandon.c+++ /dev/null@@ -1,346 +0,0 @@-/* -----------------------------------------------------------------------------Copyright (c) 2019-2024, 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.------------------------------------------------------------------------------*/--#if !defined(MI_IN_ARENA_C)-#error "this file should be included from 'arena.c' (so mi_arena_t is visible)"-// add includes help an IDE-#include "mimalloc.h"-#include "mimalloc/internal.h"-#include "bitmap.h"-#endif--// Minimal exports for arena-abandoned.-size_t mi_arena_id_index(mi_arena_id_t id);-mi_arena_t* mi_arena_from_index(size_t idx);-size_t mi_arena_get_count(void);-void* mi_arena_block_start(mi_arena_t* arena, mi_bitmap_index_t bindex);-bool mi_arena_memid_indices(mi_memid_t memid, size_t* arena_index, mi_bitmap_index_t* bitmap_index);--/* ------------------------------------------------------------ Abandoned blocks/segments:-- _mi_arena_segment_clear_abandoned- _mi_arena_segment_mark_abandoned-- This is used to atomically abandon/reclaim segments- (and crosses the arena API but it is convenient to have here).-- Abandoned segments still have live blocks; they get reclaimed- when a thread frees a block in it, or when a thread needs a fresh- segment.-- Abandoned segments are atomically marked in the `block_abandoned`- bitmap of arenas. Any segments allocated outside arenas are put- in the sub-process `abandoned_os_list`. This list is accessed- using locks but this should be uncommon and generally uncontended.- Reclaim and visiting either scan through the `block_abandoned`- bitmaps of the arena's, or visit the `abandoned_os_list`-- A potentially nicer design is to use arena's for everything- and perhaps have virtual arena's to map OS allocated memory- but this would lack the "density" of our current arena's. TBC.------------------------------------------------------------ */---// reclaim a specific OS abandoned segment; `true` on success.-// sets the thread_id.-static bool mi_arena_segment_os_clear_abandoned(mi_segment_t* segment, bool take_lock) {- mi_assert(segment->memid.memkind != MI_MEM_ARENA);- // not in an arena, remove from list of abandoned os segments- mi_subproc_t* const subproc = segment->subproc;- if (take_lock && !mi_lock_try_acquire(&subproc->abandoned_os_lock)) {- return false; // failed to acquire the lock, we just give up- }- // remove atomically from the abandoned os list (if possible!)- bool reclaimed = false;- mi_segment_t* const next = segment->abandoned_os_next;- mi_segment_t* const prev = segment->abandoned_os_prev;- if (next != NULL || prev != NULL || subproc->abandoned_os_list == segment) {- #if MI_DEBUG>3- // find ourselves in the abandoned list (and check the count)- bool found = false;- size_t count = 0;- for (mi_segment_t* current = subproc->abandoned_os_list; current != NULL; current = current->abandoned_os_next) {- if (current == segment) { found = true; }- count++;- }- mi_assert_internal(found);- mi_assert_internal(count == mi_atomic_load_relaxed(&subproc->abandoned_os_list_count));- #endif- // remove (atomically) from the list and reclaim- if (prev != NULL) { prev->abandoned_os_next = next; }- else { subproc->abandoned_os_list = next; }- if (next != NULL) { next->abandoned_os_prev = prev; }- else { subproc->abandoned_os_list_tail = prev; }- segment->abandoned_os_next = NULL;- segment->abandoned_os_prev = NULL;- mi_atomic_decrement_relaxed(&subproc->abandoned_count);- mi_atomic_decrement_relaxed(&subproc->abandoned_os_list_count);- if (take_lock) { // don't reset the thread_id when iterating- mi_atomic_store_release(&segment->thread_id, _mi_thread_id());- }- reclaimed = true;- }- if (take_lock) { mi_lock_release(&segment->subproc->abandoned_os_lock); }- return reclaimed;-}--// reclaim a specific abandoned segment; `true` on success.-// sets the thread_id.-bool _mi_arena_segment_clear_abandoned(mi_segment_t* segment) {- if mi_unlikely(segment->memid.memkind != MI_MEM_ARENA) {- return mi_arena_segment_os_clear_abandoned(segment, true /* take lock */);- }- // arena segment: use the blocks_abandoned bitmap.- size_t arena_idx;- size_t bitmap_idx;- mi_arena_memid_indices(segment->memid, &arena_idx, &bitmap_idx);- mi_arena_t* arena = mi_arena_from_index(arena_idx);- mi_assert_internal(arena != NULL);- // reclaim atomically- bool was_marked = _mi_bitmap_unclaim(arena->blocks_abandoned, arena->field_count, 1, bitmap_idx);- if (was_marked) {- mi_assert_internal(mi_atomic_load_acquire(&segment->thread_id) == 0);- mi_atomic_decrement_relaxed(&segment->subproc->abandoned_count);- mi_atomic_store_release(&segment->thread_id, _mi_thread_id());- }- // mi_assert_internal(was_marked);- mi_assert_internal(!was_marked || _mi_bitmap_is_claimed(arena->blocks_inuse, arena->field_count, 1, bitmap_idx));- //mi_assert_internal(arena->blocks_committed == NULL || _mi_bitmap_is_claimed(arena->blocks_committed, arena->field_count, 1, bitmap_idx));- return was_marked;-}---// mark a specific OS segment as abandoned-static void mi_arena_segment_os_mark_abandoned(mi_segment_t* segment) {- mi_assert(segment->memid.memkind != MI_MEM_ARENA);- // not in an arena; we use a list of abandoned segments- mi_subproc_t* const subproc = segment->subproc;- mi_lock(&subproc->abandoned_os_lock) {- // push on the tail of the list (important for the visitor)- mi_segment_t* prev = subproc->abandoned_os_list_tail;- mi_assert_internal(prev == NULL || prev->abandoned_os_next == NULL);- mi_assert_internal(segment->abandoned_os_prev == NULL);- mi_assert_internal(segment->abandoned_os_next == NULL);- if (prev != NULL) { prev->abandoned_os_next = segment; }- else { subproc->abandoned_os_list = segment; }- subproc->abandoned_os_list_tail = segment;- segment->abandoned_os_prev = prev;- segment->abandoned_os_next = NULL;- mi_atomic_increment_relaxed(&subproc->abandoned_os_list_count);- mi_atomic_increment_relaxed(&subproc->abandoned_count);- // and release the lock- }- return;-}--// mark a specific segment as abandoned-// clears the thread_id.-void _mi_arena_segment_mark_abandoned(mi_segment_t* segment)-{- mi_assert_internal(segment->used == segment->abandoned);- mi_atomic_store_release(&segment->thread_id, (uintptr_t)0); // mark as abandoned for multi-thread free's- if mi_unlikely(segment->memid.memkind != MI_MEM_ARENA) {- mi_arena_segment_os_mark_abandoned(segment);- return;- }- // segment is in an arena, mark it in the arena `blocks_abandoned` bitmap- size_t arena_idx;- size_t bitmap_idx;- mi_arena_memid_indices(segment->memid, &arena_idx, &bitmap_idx);- mi_arena_t* arena = mi_arena_from_index(arena_idx);- mi_assert_internal(arena != NULL);- // set abandonment atomically- mi_subproc_t* const subproc = segment->subproc; // don't access the segment after setting it abandoned- const bool was_unmarked = _mi_bitmap_claim(arena->blocks_abandoned, arena->field_count, 1, bitmap_idx, NULL);- if (was_unmarked) { mi_atomic_increment_relaxed(&subproc->abandoned_count); }- mi_assert_internal(was_unmarked);- mi_assert_internal(_mi_bitmap_is_claimed(arena->blocks_inuse, arena->field_count, 1, bitmap_idx));-}---/* ------------------------------------------------------------ Iterate through the abandoned blocks/segments using a cursor.- This is used for reclaiming and abandoned block visiting.------------------------------------------------------------ */--// start a cursor at a randomized arena-void _mi_arena_field_cursor_init(mi_heap_t* heap, mi_subproc_t* subproc, bool visit_all, mi_arena_field_cursor_t* current) {- mi_assert_internal(heap == NULL || heap->tld->segments.subproc == subproc);- current->bitmap_idx = 0;- current->subproc = subproc;- current->visit_all = visit_all;- current->hold_visit_lock = false;- const size_t abandoned_count = mi_atomic_load_relaxed(&subproc->abandoned_count);- const size_t abandoned_list_count = mi_atomic_load_relaxed(&subproc->abandoned_os_list_count);- const size_t max_arena = mi_arena_get_count();- if (heap != NULL && heap->arena_id != _mi_arena_id_none()) {- // for a heap that is bound to one arena, only visit that arena- current->start = mi_arena_id_index(heap->arena_id);- current->end = current->start + 1;- current->os_list_count = 0;- }- else {- // otherwise visit all starting at a random location- if (abandoned_count > abandoned_list_count && max_arena > 0) {- current->start = (heap == NULL || max_arena == 0 ? 0 : (mi_arena_id_t)(_mi_heap_random_next(heap) % max_arena));- current->end = current->start + max_arena;- }- else {- current->start = 0;- current->end = 0;- }- current->os_list_count = abandoned_list_count; // max entries to visit in the os abandoned list- }- mi_assert_internal(current->start <= max_arena);-}--void _mi_arena_field_cursor_done(mi_arena_field_cursor_t* current) {- if (current->hold_visit_lock) {- mi_lock_release(¤t->subproc->abandoned_os_visit_lock);- current->hold_visit_lock = false;- }-}--static mi_segment_t* mi_arena_segment_clear_abandoned_at(mi_arena_t* arena, mi_subproc_t* subproc, mi_bitmap_index_t bitmap_idx) {- // try to reclaim an abandoned segment in the arena atomically- if (!_mi_bitmap_unclaim(arena->blocks_abandoned, arena->field_count, 1, bitmap_idx)) return NULL;- mi_assert_internal(_mi_bitmap_is_claimed(arena->blocks_inuse, arena->field_count, 1, bitmap_idx));- mi_segment_t* segment = (mi_segment_t*)mi_arena_block_start(arena, bitmap_idx);- mi_assert_internal(mi_atomic_load_relaxed(&segment->thread_id) == 0);- // check that the segment belongs to our sub-process- // note: this is the reason we need the `abandoned_visit` lock in the case abandoned visiting is enabled.- // without the lock an abandoned visit may otherwise fail to visit all abandoned segments in the sub-process.- // for regular reclaim it is fine to miss one sometimes so without abandoned visiting we don't need the `abandoned_visit` lock.- if (segment->subproc != subproc) {- // it is from another sub-process, re-mark it and continue searching- const bool was_zero = _mi_bitmap_claim(arena->blocks_abandoned, arena->field_count, 1, bitmap_idx, NULL);- mi_assert_internal(was_zero); MI_UNUSED(was_zero);- return NULL;- }- else {- // success, we unabandoned a segment in our sub-process- mi_atomic_decrement_relaxed(&subproc->abandoned_count);- return segment;- }-}--static mi_segment_t* mi_arena_segment_clear_abandoned_next_field(mi_arena_field_cursor_t* previous) {- const size_t max_arena = mi_arena_get_count();- size_t field_idx = mi_bitmap_index_field(previous->bitmap_idx);- size_t bit_idx = mi_bitmap_index_bit_in_field(previous->bitmap_idx);- // visit arena's (from the previous cursor)- for (; previous->start < previous->end; previous->start++, field_idx = 0, bit_idx = 0) {- // index wraps around- size_t arena_idx = (previous->start >= max_arena ? previous->start % max_arena : previous->start);- mi_arena_t* arena = mi_arena_from_index(arena_idx);- if (arena != NULL) {- bool has_lock = false;- // visit the abandoned fields (starting at previous_idx)- for (; field_idx < arena->field_count; field_idx++, bit_idx = 0) {- size_t field = mi_atomic_load_relaxed(&arena->blocks_abandoned[field_idx]);- if mi_unlikely(field != 0) { // skip zero fields quickly- // we only take the arena lock if there are actually abandoned segments present- if (!has_lock && mi_option_is_enabled(mi_option_visit_abandoned)) {- has_lock = (previous->visit_all ? (mi_lock_acquire(&arena->abandoned_visit_lock),true) : mi_lock_try_acquire(&arena->abandoned_visit_lock));- if (!has_lock) {- if (previous->visit_all) {- _mi_error_message(EFAULT, "internal error: failed to visit all abandoned segments due to failure to acquire the visitor lock");- }- // skip to next arena- break;- }- }- mi_assert_internal(has_lock || !mi_option_is_enabled(mi_option_visit_abandoned));- // visit each set bit in the field (todo: maybe use `ctz` here?)- for (; bit_idx < MI_BITMAP_FIELD_BITS; bit_idx++) {- // pre-check if the bit is set- size_t mask = ((size_t)1 << bit_idx);- if mi_unlikely((field & mask) == mask) {- mi_bitmap_index_t bitmap_idx = mi_bitmap_index_create(field_idx, bit_idx);- mi_segment_t* const segment = mi_arena_segment_clear_abandoned_at(arena, previous->subproc, bitmap_idx);- if (segment != NULL) {- //mi_assert_internal(arena->blocks_committed == NULL || _mi_bitmap_is_claimed(arena->blocks_committed, arena->field_count, 1, bitmap_idx));- if (has_lock) { mi_lock_release(&arena->abandoned_visit_lock); }- previous->bitmap_idx = mi_bitmap_index_create_ex(field_idx, bit_idx + 1); // start at next one for the next iteration- return segment;- }- }- }- }- }- if (has_lock) { mi_lock_release(&arena->abandoned_visit_lock); }- }- }- return NULL;-}--static mi_segment_t* mi_arena_segment_clear_abandoned_next_list(mi_arena_field_cursor_t* previous) {- // go through the abandoned_os_list- // we only allow one thread per sub-process to do to visit guarded by the `abandoned_os_visit_lock`.- // The lock is released when the cursor is released.- if (!previous->hold_visit_lock) {- previous->hold_visit_lock = (previous->visit_all ? (mi_lock_acquire(&previous->subproc->abandoned_os_visit_lock),true)- : mi_lock_try_acquire(&previous->subproc->abandoned_os_visit_lock));- if (!previous->hold_visit_lock) {- if (previous->visit_all) {- _mi_error_message(EFAULT, "internal error: failed to visit all abandoned segments due to failure to acquire the OS visitor lock");- }- return NULL; // we cannot get the lock, give up- }- }- // One list entry at a time- while (previous->os_list_count > 0) {- previous->os_list_count--;- mi_lock_acquire(&previous->subproc->abandoned_os_lock); // this could contend with concurrent OS block abandonment and reclaim from `free`- mi_segment_t* segment = previous->subproc->abandoned_os_list;- // pop from head of the list, a subsequent mark will push at the end (and thus we iterate through os_list_count entries)- if (segment == NULL || mi_arena_segment_os_clear_abandoned(segment, false /* we already have the lock */)) {- mi_lock_release(&previous->subproc->abandoned_os_lock);- return segment;- }- // already abandoned, try again- mi_lock_release(&previous->subproc->abandoned_os_lock);- }- // done- mi_assert_internal(previous->os_list_count == 0);- return NULL;-}---// reclaim abandoned segments-// this does not set the thread id (so it appears as still abandoned)-mi_segment_t* _mi_arena_segment_clear_abandoned_next(mi_arena_field_cursor_t* previous) {- if (previous->start < previous->end) {- // walk the arena- mi_segment_t* segment = mi_arena_segment_clear_abandoned_next_field(previous);- if (segment != NULL) { return segment; }- }- // no entries in the arena's anymore, walk the abandoned OS list- mi_assert_internal(previous->start == previous->end);- return mi_arena_segment_clear_abandoned_next_list(previous);-}---bool mi_abandoned_visit_blocks(mi_subproc_id_t subproc_id, int heap_tag, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {- // (unfortunately) the visit_abandoned option must be enabled from the start.- // This is to avoid taking locks if abandoned list visiting is not required (as for most programs)- if (!mi_option_is_enabled(mi_option_visit_abandoned)) {- _mi_error_message(EFAULT, "internal error: can only visit abandoned blocks when MIMALLOC_VISIT_ABANDONED=ON");- return false;- }- mi_arena_field_cursor_t current;- _mi_arena_field_cursor_init(NULL, _mi_subproc_from_id(subproc_id), true /* visit all (blocking) */, ¤t);- mi_segment_t* segment;- bool ok = true;- while (ok && (segment = _mi_arena_segment_clear_abandoned_next(¤t)) != NULL) {- ok = _mi_segment_visit_blocks(segment, heap_tag, visit_blocks, visitor, arg);- _mi_arena_segment_mark_abandoned(segment);- }- _mi_arena_field_cursor_done(¤t);- return ok;-}diff --git a/vendored/mimalloc/src/arena-meta.c b/vendored/mimalloc/src/arena-meta.cnew file mode 100644index 000000000..7ff336e8c--- /dev/null+++ b/vendored/mimalloc/src/arena-meta.c@@ -0,0 +1,179 @@+/* ----------------------------------------------------------------------------+Copyright (c) 2019-2024, 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.+-----------------------------------------------------------------------------*/++/* ----------------------------------------------------------------------------+ We have a special "mini" allocator just for allocation of meta-data like+ the theap (`mi_theap_t`) or thread-local data (`mi_tld_t`).++ We reuse the bitmap of the arena's for allocation of 64b blocks inside+ an arena slice (64KiB).+ We always ensure that meta data is zero'd (we zero on `free`)+-----------------------------------------------------------------------------*/++#include "mimalloc.h"+#include "mimalloc/internal.h"+#include "bitmap.h"++/* -----------------------------------------------------------+ Meta data allocation+----------------------------------------------------------- */++#define MI_META_PAGE_SIZE MI_ARENA_SLICE_SIZE+#define MI_META_PAGE_ALIGN MI_ARENA_SLICE_ALIGN++// large enough such that META_MAX_SIZE > 4k (even on 32-bit)+#define MI_META_BLOCK_SIZE (1 << (16 - MI_BCHUNK_BITS_SHIFT)) // 128 on 64-bit+#define MI_META_BLOCK_ALIGN MI_META_BLOCK_SIZE+#define MI_META_BLOCKS_PER_PAGE (MI_META_PAGE_SIZE / MI_META_BLOCK_SIZE) // 512+#define MI_META_MAX_SIZE (MI_BCHUNK_SIZE * MI_META_BLOCK_SIZE)++#if MI_META_MAX_SIZE <= 4096+#error "max meta object size should be at least 4KiB"+#endif++typedef struct mi_meta_page_s {+ _Atomic(struct mi_meta_page_s*) next; // a linked list of meta-data pages (never released)+ mi_memid_t memid; // provenance of the meta-page memory itself+ mi_bbitmap_t blocks_free; // a small bitmap with 1 bit per block.+} mi_meta_page_t;++static mi_decl_cache_align _Atomic(mi_meta_page_t*) mi_meta_pages = MI_ATOMIC_VAR_INIT(NULL);+++#if MI_DEBUG > 1+static mi_meta_page_t* mi_meta_page_of_ptr(void* p, size_t* block_idx) {+ mi_meta_page_t* mpage = (mi_meta_page_t*)((uint8_t*)mi_align_down_ptr(p,MI_META_PAGE_ALIGN) + _mi_os_secure_guard_page_size());+ if (block_idx != NULL) {+ *block_idx = ((uint8_t*)p - (uint8_t*)mpage) / MI_META_BLOCK_SIZE;+ }+ return mpage;+}+#endif++static mi_meta_page_t* mi_meta_page_next( mi_meta_page_t* mpage ) {+ return mi_atomic_load_ptr_acquire(mi_meta_page_t, &mpage->next);+}++static void* mi_meta_block_start( mi_meta_page_t* mpage, size_t block_idx ) {+ mi_assert_internal(_mi_is_aligned((uint8_t*)mpage - _mi_os_secure_guard_page_size(), MI_META_PAGE_ALIGN));+ mi_assert_internal(block_idx < MI_META_BLOCKS_PER_PAGE);+ void* p = ((uint8_t*)mpage - _mi_os_secure_guard_page_size() + (block_idx * MI_META_BLOCK_SIZE));+ mi_assert_internal(mpage == mi_meta_page_of_ptr(p,NULL));+ return p;+}++// allocate a fresh meta page and add it to the global list.+static mi_meta_page_t* mi_meta_page_zalloc(void) {+ // allocate a fresh arena slice+ // note: careful with _mi_subproc as it may recurse into mi_tld and meta_page_zalloc again.. (same with _mi_os_numa_node()...)+ mi_memid_t memid;+ uint8_t* base = (uint8_t*)_mi_arenas_alloc_aligned(mi_heap_main(), MI_META_PAGE_SIZE, MI_META_PAGE_ALIGN, 0,+ true /* commit*/, (MI_SECURE==0) /* allow large? */,+ NULL /* req arena */, 0 /* thread_seq */, -1 /* numa node */, &memid);+ if (base == NULL) return NULL;+ mi_assert_internal(_mi_is_aligned(base,MI_META_PAGE_ALIGN));+ if (!memid.initially_zero) {+ _mi_memzero_aligned(base, MI_ARENA_SLICE_SIZE);+ }++ // guard pages+ #if MI_SECURE >= 1+ _mi_os_secure_guard_page_set_at(base, memid);+ _mi_os_secure_guard_page_set_before(base + MI_META_PAGE_SIZE, memid);+ #endif++ // initialize the page and free block bitmap+ mi_meta_page_t* mpage = (mi_meta_page_t*)(base + _mi_os_secure_guard_page_size());+ mpage->memid = memid;+ mi_bbitmap_init(&mpage->blocks_free, MI_META_BLOCKS_PER_PAGE, true /* already_zero */);+ const size_t mpage_size = offsetof(mi_meta_page_t,blocks_free) + mi_bbitmap_size(MI_META_BLOCKS_PER_PAGE, NULL);+ const size_t info_blocks = _mi_divide_up(mpage_size,MI_META_BLOCK_SIZE);+ const size_t guard_blocks = _mi_divide_up(_mi_os_secure_guard_page_size(), MI_META_BLOCK_SIZE);+ mi_assert_internal(info_blocks + 2*guard_blocks < MI_META_BLOCKS_PER_PAGE);+ mi_bbitmap_unsafe_setN(&mpage->blocks_free, info_blocks + guard_blocks, MI_META_BLOCKS_PER_PAGE - info_blocks - 2*guard_blocks);++ // push atomically in front of the meta page list+ // (note: there is no ABA issue since we never free meta-pages)+ mi_meta_page_t* old = mi_atomic_load_ptr_acquire(mi_meta_page_t,&mi_meta_pages);+ do {+ mi_atomic_store_ptr_release(mi_meta_page_t, &mpage->next, old);+ } while(!mi_atomic_cas_ptr_weak_acq_rel(mi_meta_page_t,&mi_meta_pages,&old,mpage));+ return mpage;+}+++// allocate meta-data+mi_decl_noinline void* _mi_meta_zalloc( size_t size, mi_memid_t* pmemid )+{+ mi_assert_internal(pmemid != NULL);+ size = _mi_align_up(size,MI_META_BLOCK_SIZE);+ if (size == 0 || size > MI_META_MAX_SIZE) return NULL;+ const size_t block_count = _mi_divide_up(size,MI_META_BLOCK_SIZE);+ mi_assert_internal(block_count > 0 && block_count < MI_BCHUNK_BITS);+ mi_meta_page_t* mpage0 = mi_atomic_load_ptr_acquire(mi_meta_page_t,&mi_meta_pages);+ mi_meta_page_t* mpage = mpage0;+ while (mpage != NULL) {+ size_t block_idx;+ if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, block_count, 0, &block_idx)) {+ // found and claimed `block_count` blocks+ *pmemid = _mi_memid_create_meta(mpage, block_idx, block_count);+ return mi_meta_block_start(mpage,block_idx);+ }+ else {+ mpage = mi_meta_page_next(mpage);+ }+ }+ // failed to find space in existing pages+ if (mi_atomic_load_ptr_acquire(mi_meta_page_t,&mi_meta_pages) != mpage0) {+ // the page list was updated by another thread in the meantime, retry+ return _mi_meta_zalloc(size,pmemid);+ }+ // otherwise, allocate a fresh metapage and try once more+ mpage = mi_meta_page_zalloc();+ if (mpage != NULL) {+ size_t block_idx;+ if (mi_bbitmap_try_find_and_clearN(&mpage->blocks_free, block_count, 0, &block_idx)) {+ // found and claimed `block_count` blocks+ *pmemid = _mi_memid_create_meta(mpage, block_idx, block_count);+ return mi_meta_block_start(mpage,block_idx);+ }+ }+ // if all this failed, allocate from the OS+ return _mi_os_alloc(size, pmemid);+}++// free meta-data+mi_decl_noinline void _mi_meta_free(void* p, size_t size, mi_memid_t memid) {+ if (p==NULL) return;+ if (memid.memkind == MI_MEM_META) {+ mi_assert_internal(_mi_divide_up(size, MI_META_BLOCK_SIZE) == memid.mem.meta.block_count);+ const size_t block_count = memid.mem.meta.block_count;+ const size_t block_idx = memid.mem.meta.block_index;+ mi_meta_page_t* mpage = (mi_meta_page_t*)memid.mem.meta.meta_page;+ mi_assert_internal(mi_meta_page_of_ptr(p,NULL) == mpage);+ mi_assert_internal(block_idx + block_count <= MI_META_BLOCKS_PER_PAGE);+ mi_assert_internal(mi_bbitmap_is_clearN(&mpage->blocks_free, block_idx, block_count));+ // we zero on free (and on the initial page allocation) so we don't need a "dirty" map+ _mi_memzero_aligned(mi_meta_block_start(mpage, block_idx), block_count*MI_META_BLOCK_SIZE);+ mi_bbitmap_setN(&mpage->blocks_free, block_idx, block_count);+ }+ else {+ _mi_arenas_free(p,size,memid);+ }+}++// used for debug output+bool _mi_meta_is_meta_page(void* p)+{+ mi_meta_page_t* mpage0 = mi_atomic_load_ptr_acquire(mi_meta_page_t, &mi_meta_pages);+ mi_meta_page_t* mpage = mpage0;+ while (mpage != NULL) {+ if ((void*)mpage == p) return true;+ mpage = mi_meta_page_next(mpage);+ }+ return false;+}diff --git a/vendored/mimalloc/src/arena.c b/vendored/mimalloc/src/arena.cindex a809b85f4..872ea4900 100644--- a/vendored/mimalloc/src/arena.c+++ b/vendored/mimalloc/src/arena.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2019-2024, Microsoft Research, Daan Leijen+Copyright (c) 2019-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -7,7 +7,7 @@ terms of the MIT license. A copy of the license can be found in the file/* ----------------------------------------------------------------------------"Arenas" are fixed area's of OS memory from which we can allocate-large blocks (>= MI_ARENA_MIN_BLOCK_SIZE, 4MiB).+large blocks (>= MI_ARENA_MIN_BLOCK_SIZE, 64KiB).In contrast to the rest of mimalloc, the arenas are shared betweenthreads and need to be accessed using atomic operations.@@ -21,215 +21,157 @@ The arena allocation needs to be thread safe and we use an atomic bitmap to allo#include "mimalloc.h"#include "mimalloc/internal.h"-#include "mimalloc/atomic.h"+#include "mimalloc/prim.h"#include "bitmap.h"--/* ------------------------------------------------------------ Arena allocation------------------------------------------------------------ */--// A memory arena descriptor-typedef struct mi_arena_s {- mi_arena_id_t id; // arena id; 0 for non-specific- mi_memid_t memid; // memid of the memory area- _Atomic(uint8_t*) start; // the start of the memory area- size_t block_count; // size of the area in arena blocks (of `MI_ARENA_BLOCK_SIZE`)- size_t field_count; // number of bitmap fields (where `field_count * MI_BITMAP_FIELD_BITS >= block_count`)- size_t meta_size; // size of the arena structure itself (including its bitmaps)- mi_memid_t meta_memid; // memid of the arena structure itself (OS or static allocation)- int numa_node; // associated NUMA node- bool exclusive; // only allow allocations if specifically for this arena- bool is_large; // memory area consists of large- or huge OS pages (always committed)- mi_lock_t abandoned_visit_lock; // lock is only used when abandoned segments are being visited- _Atomic(size_t) search_idx; // optimization to start the search for free blocks- _Atomic(mi_msecs_t) purge_expire; // expiration time when blocks should be purged from `blocks_purge`.-- mi_bitmap_field_t* blocks_dirty; // are the blocks potentially non-zero?- mi_bitmap_field_t* blocks_committed; // are the blocks committed? (can be NULL for memory that cannot be decommitted)- mi_bitmap_field_t* blocks_purge; // blocks that can be (reset) decommitted. (can be NULL for memory that cannot be (reset) decommitted)- mi_bitmap_field_t* blocks_abandoned; // blocks that start with an abandoned segment. (This crosses API's but it is convenient to have here)- mi_bitmap_field_t blocks_inuse[1]; // in-place bitmap of in-use blocks (of size `field_count`)- // do not add further fields here as the dirty, committed, purged, and abandoned bitmaps follow the inuse bitmap fields.-} mi_arena_t;---#define MI_ARENA_BLOCK_SIZE (MI_SEGMENT_SIZE) // 64MiB (must be at least MI_SEGMENT_ALIGN)-#define MI_ARENA_MIN_OBJ_SIZE (MI_ARENA_BLOCK_SIZE/2) // 32MiB-#define MI_MAX_ARENAS (132) // Limited as the reservation exponentially increases (and takes up .bss)--// The available arenas-static mi_decl_cache_align _Atomic(mi_arena_t*) mi_arenas[MI_MAX_ARENAS];-static mi_decl_cache_align _Atomic(size_t) mi_arena_count; // = 0-static mi_decl_cache_align _Atomic(int64_t) mi_arenas_purge_expire; // set if there exist purgeable arenas--#define MI_IN_ARENA_C-#include "arena-abandon.c"-#undef MI_IN_ARENA_C-/* -----------------------------------------------------------Arena id's- id = arena_index + 1----------------------------------------------------------- */-size_t mi_arena_id_index(mi_arena_id_t id) {- return (size_t)(id <= 0 ? MI_MAX_ARENAS : id - 1);+mi_arena_id_t _mi_arena_id_none(void) {+ return NULL;}-static mi_arena_id_t mi_arena_id_create(size_t arena_index) {- mi_assert_internal(arena_index < MI_MAX_ARENAS);- return (int)arena_index + 1;+mi_arena_t* _mi_arena_from_id(mi_arena_id_t id) {+ return (mi_arena_t*)id;}-mi_arena_id_t _mi_arena_id_none(void) {- return 0;-}-static bool mi_arena_id_is_suitable(mi_arena_id_t arena_id, bool arena_is_exclusive, mi_arena_id_t req_arena_id) {- return ((!arena_is_exclusive && req_arena_id == _mi_arena_id_none()) ||- (arena_id == req_arena_id));+static bool mi_arena_id_is_suitable(mi_arena_t* arena, mi_arena_t* req_arena) {+ return ((arena == req_arena) || // they match,+ (req_arena == NULL && !arena->is_exclusive)); // or the arena is not exclusive, and we didn't request a specific one}-bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_id_t request_arena_id) {+bool _mi_arena_memid_is_suitable(mi_memid_t memid, mi_arena_t* request_arena) {if (memid.memkind == MI_MEM_ARENA) {- return mi_arena_id_is_suitable(memid.mem.arena.id, memid.mem.arena.is_exclusive, request_arena_id);+ return mi_arena_id_is_suitable(memid.mem.arena.arena, request_arena);}else {- return mi_arena_id_is_suitable(_mi_arena_id_none(), false, request_arena_id);+ return mi_arena_id_is_suitable(NULL, request_arena);}}-bool _mi_arena_memid_is_os_allocated(mi_memid_t memid) {- return (memid.memkind == MI_MEM_OS);-}--size_t mi_arena_get_count(void) {- return mi_atomic_load_relaxed(&mi_arena_count);+size_t mi_arenas_get_count(mi_subproc_t* subproc) {+ return mi_atomic_load_relaxed(&subproc->arena_count);}-mi_arena_t* mi_arena_from_index(size_t idx) {- mi_assert_internal(idx < mi_arena_get_count());- return mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[idx]);+mi_arena_t* mi_arena_from_index(mi_subproc_t* subproc, size_t idx) {+ mi_assert_internal(idx < mi_arenas_get_count(subproc));+ return mi_atomic_load_ptr_relaxed(mi_arena_t, &subproc->arenas[idx]);}--/* ------------------------------------------------------------ Arena allocations get a (currently) 16-bit memory id where the- lower 8 bits are the arena id, and the upper bits the block index.------------------------------------------------------------ */--static size_t mi_block_count_of_size(size_t size) {- return _mi_divide_up(size, MI_ARENA_BLOCK_SIZE);+static size_t mi_arena_info_slices(mi_arena_t* arena) {+ return arena->info_slices;}-static size_t mi_arena_block_size(size_t bcount) {- return (bcount * MI_ARENA_BLOCK_SIZE);+#if MI_DEBUG > 1+static bool mi_heap_has_page(mi_heap_t* heap, mi_arena_t* arena, mi_page_t* page) {+ mi_assert(arena->arena_idx < MI_MAX_ARENAS);+ mi_arena_pages_t* arena_pages = heap->arena_pages[arena->arena_idx];+ return (page->memid.memkind == MI_MEM_ARENA &&+ page->memid.mem.arena.arena == arena &&+ arena_pages != NULL &&+ mi_bitmap_is_setN(arena_pages->pages, page->memid.mem.arena.slice_index, 1));}+#endif-static size_t mi_arena_size(mi_arena_t* arena) {- return mi_arena_block_size(arena->block_count);+size_t mi_arena_min_alignment(void) {+ return MI_ARENA_SLICE_ALIGN;}-static mi_memid_t mi_memid_create_arena(mi_arena_id_t id, bool is_exclusive, mi_bitmap_index_t bitmap_index) {- mi_memid_t memid = _mi_memid_create(MI_MEM_ARENA);- memid.mem.arena.id = id;- memid.mem.arena.block_index = bitmap_index;- memid.mem.arena.is_exclusive = is_exclusive;- return memid;+static size_t mi_arena_max_object_size(void) {+ size_t max_size = mi_option_get_size(mi_option_arena_max_object_size);+ max_size = _mi_align_up(max_size, MI_ARENA_SLICE_SIZE);+ if (max_size <= MI_ARENA_MIN_OBJ_SIZE) {+ return MI_ARENA_MIN_OBJ_SIZE;+ }+ else if (max_size >= MI_ARENA_MAX_SIZE - MI_BCHUNK_SIZE) { // minus a bchunk to accommodate meta info+ return (MI_ARENA_MAX_SIZE - MI_BCHUNK_SIZE);+ }+ else {+ return max_size;+ }}-bool mi_arena_memid_indices(mi_memid_t memid, size_t* arena_index, mi_bitmap_index_t* bitmap_index) {- mi_assert_internal(memid.memkind == MI_MEM_ARENA);- *arena_index = mi_arena_id_index(memid.mem.arena.id);- *bitmap_index = memid.mem.arena.block_index;- return memid.mem.arena.is_exclusive;+mi_decl_nodiscard static bool mi_arena_commit(mi_arena_t* arena, void* start, size_t size, bool* is_zero, size_t already_committed) {+ if (arena != NULL && arena->commit_fun != NULL) {+ return (*arena->commit_fun)(true, start, size, is_zero, arena->commit_fun_arg);+ }+ else if (already_committed > 0) {+ return _mi_os_commit_ex(start, size, is_zero, already_committed);+ }+ else {+ return _mi_os_commit(start, size, is_zero);+ }}/* ------------------------------------------------------------ Special static area for mimalloc internal structures- to avoid OS calls (for example, for the arena metadata (~= 256b))+ Util----------------------------------------------------------- */-#define MI_ARENA_STATIC_MAX ((MI_INTPTR_SIZE/2)*MI_KiB) // 4 KiB on 64-bit--static mi_decl_cache_align uint8_t mi_arena_static[MI_ARENA_STATIC_MAX]; // must be cache aligned, see issue #895-static mi_decl_cache_align _Atomic(size_t) mi_arena_static_top;--static void* mi_arena_static_zalloc(size_t size, size_t alignment, mi_memid_t* memid) {- *memid = _mi_memid_none();- if (size == 0 || size > MI_ARENA_STATIC_MAX) return NULL;- const size_t toplow = mi_atomic_load_relaxed(&mi_arena_static_top);- if ((toplow + size) > MI_ARENA_STATIC_MAX) return NULL;-- // try to claim space- if (alignment < MI_MAX_ALIGN_SIZE) { alignment = MI_MAX_ALIGN_SIZE; }- const size_t oversize = size + alignment - 1;- if (toplow + oversize > MI_ARENA_STATIC_MAX) return NULL;- const size_t oldtop = mi_atomic_add_acq_rel(&mi_arena_static_top, oversize);- size_t top = oldtop + oversize;- if (top > MI_ARENA_STATIC_MAX) {- // try to roll back, ok if this fails- mi_atomic_cas_strong_acq_rel(&mi_arena_static_top, &top, oldtop);- return NULL;- }- // success- *memid = _mi_memid_create(MI_MEM_STATIC);- memid->initially_zero = true;- const size_t start = _mi_align_up(oldtop, alignment);- uint8_t* const p = &mi_arena_static[start];- _mi_memzero_aligned(p, size);- return p;+// Size of an arena+static size_t mi_arena_size(mi_arena_t* arena) {+ return mi_size_of_slices(arena->slice_count);}-void* _mi_arena_meta_zalloc(size_t size, mi_memid_t* memid) {- *memid = _mi_memid_none();-- // try static- void* p = mi_arena_static_zalloc(size, MI_MAX_ALIGN_SIZE, memid);- if (p != NULL) return p;-- // or fall back to the OS- p = _mi_os_alloc(size, memid);- if (p == NULL) return NULL;-- // zero the OS memory if needed- if (!memid->initially_zero) {- _mi_memzero_aligned(p, size);- memid->initially_zero = true;- }- return p;+// Start of the arena memory area+static uint8_t* mi_arena_start(mi_arena_t* arena) {+ return ((uint8_t*)arena);}-void _mi_arena_meta_free(void* p, mi_memid_t memid, size_t size) {- if (mi_memkind_is_os(memid.memkind)) {- _mi_os_free(p, size, memid);- }- else {- mi_assert(memid.memkind == MI_MEM_STATIC);- }+// Start of a slice+uint8_t* mi_arena_slice_start(mi_arena_t* arena, size_t slice_index) {+ return (mi_arena_start(arena) + mi_size_of_slices(slice_index));}-void* mi_arena_block_start(mi_arena_t* arena, mi_bitmap_index_t bindex) {- return (arena->start + mi_arena_block_size(mi_bitmap_index_bit(bindex)));+// Arena area+void* mi_arena_area(mi_arena_id_t arena_id, size_t* size) {+ if (size != NULL) *size = 0;+ mi_arena_t* arena = _mi_arena_from_id(arena_id);+ if (arena == NULL) return NULL;+ if (size != NULL) { *size = mi_size_of_slices(arena->slice_count); }+ return mi_arena_start(arena);}-/* ------------------------------------------------------------ Thread safe allocation in an arena------------------------------------------------------------ */+// Create an arena memid+static mi_memid_t mi_memid_create_arena(mi_arena_t* arena, size_t slice_index, size_t slice_count) {+ mi_assert_internal(slice_index < UINT32_MAX);+ mi_assert_internal(slice_count < UINT32_MAX);+ mi_assert_internal(slice_count > 0);+ mi_assert_internal(slice_index < arena->slice_count);+ mi_memid_t memid = _mi_memid_create(MI_MEM_ARENA);+ memid.mem.arena.arena = arena;+ memid.mem.arena.slice_index = (uint32_t)slice_index;+ memid.mem.arena.slice_count = (uint32_t)slice_count;+ return memid;+}-// claim the `blocks_inuse` bits-static bool mi_arena_try_claim(mi_arena_t* arena, size_t blocks, mi_bitmap_index_t* bitmap_idx)-{- size_t idx = 0; // mi_atomic_load_relaxed(&arena->search_idx); // start from last search; ok to be relaxed as the exact start does not matter- if (_mi_bitmap_try_find_from_claim_across(arena->blocks_inuse, arena->field_count, idx, blocks, bitmap_idx)) {- mi_atomic_store_relaxed(&arena->search_idx, mi_bitmap_index_field(*bitmap_idx)); // start search from found location next time around- return true;- };- return false;+// get the arena and slice span+static mi_arena_t* mi_arena_from_memid(mi_memid_t memid, size_t* slice_index, size_t* slice_count) {+ mi_assert_internal(memid.memkind == MI_MEM_ARENA);+ mi_arena_t* arena = memid.mem.arena.arena;+ if (slice_index!=NULL) { *slice_index = memid.mem.arena.slice_index; }+ if (slice_count!=NULL) { *slice_count = memid.mem.arena.slice_count; }+ return arena;+}++static size_t mi_page_full_size(mi_page_t* page) {+ if (page->memid.memkind == MI_MEM_ARENA) {+ return page->memid.mem.arena.slice_count * MI_ARENA_SLICE_SIZE;+ }+ else if (mi_memid_is_os(page->memid) || page->memid.memkind == MI_MEM_EXTERNAL) {+ mi_assert_internal((uint8_t*)page->memid.mem.os.base <= (uint8_t*)page);+ const ptrdiff_t presize = (uint8_t*)page - (uint8_t*)page->memid.mem.os.base;+ mi_assert_internal((ptrdiff_t)page->memid.mem.os.size >= presize);+ return (presize > (ptrdiff_t)page->memid.mem.os.size ? 0 : page->memid.mem.os.size - presize);+ }+ else {+ return 0;+ }}@@ -237,194 +179,341 @@ static bool mi_arena_try_claim(mi_arena_t* arena, size_t blocks, mi_bitmap_indexArena Allocation----------------------------------------------------------- */-static mi_decl_noinline void* mi_arena_try_alloc_at(mi_arena_t* arena, size_t arena_index, size_t needed_bcount,- bool commit, mi_memid_t* memid)+static mi_decl_noinline void* mi_arena_try_alloc_at(+ mi_arena_t* arena, size_t slice_count, bool commit, size_t tseq, mi_memid_t* memid){- MI_UNUSED(arena_index);- mi_assert_internal(mi_arena_id_index(arena->id) == arena_index);-- mi_bitmap_index_t bitmap_index;- if (!mi_arena_try_claim(arena, needed_bcount, &bitmap_index)) return NULL;+ size_t slice_index;+ if (!mi_bbitmap_try_find_and_clearN(arena->slices_free, slice_count, tseq, &slice_index)) return NULL;// claimed it!- void* p = mi_arena_block_start(arena, bitmap_index);- *memid = mi_memid_create_arena(arena->id, arena->exclusive, bitmap_index);+ void* p = mi_arena_slice_start(arena, slice_index);+ *memid = mi_memid_create_arena(arena, slice_index, slice_count);memid->is_pinned = arena->memid.is_pinned;- // none of the claimed blocks should be scheduled for a decommit- if (arena->blocks_purge != NULL) {- // this is thread safe as a potential purge only decommits parts that are not yet claimed as used (in `blocks_inuse`).- _mi_bitmap_unclaim_across(arena->blocks_purge, arena->field_count, needed_bcount, bitmap_index);- }-- // set the dirty bits (todo: no need for an atomic op here?)- if (arena->memid.initially_zero && arena->blocks_dirty != NULL) {- memid->initially_zero = _mi_bitmap_claim_across(arena->blocks_dirty, arena->field_count, needed_bcount, bitmap_index, NULL);+ // set the dirty bits and track which slices become accessible+ size_t touched_slices = slice_count;+ if (arena->memid.initially_zero) {+ size_t already_dirty = 0;+ memid->initially_zero = mi_bitmap_setN(arena->slices_dirty, slice_index, slice_count, &already_dirty);+ mi_assert_internal(already_dirty <= touched_slices);+ touched_slices -= already_dirty;}// set commit state- if (arena->blocks_committed == NULL) {- // always committed- memid->initially_committed = true;- }- else if (commit) {+ if (commit) {// commit requested, but the range may not be committed as a whole: ensure it is committed now- memid->initially_committed = true;- bool any_uncommitted;- _mi_bitmap_claim_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index, &any_uncommitted);- if (any_uncommitted) {+ const size_t already_committed = mi_bitmap_popcountN(arena->slices_committed, slice_index, slice_count);+ if (already_committed < slice_count) {+ // not all committed, try to commit nowbool commit_zero = false;- if (!_mi_os_commit(p, mi_arena_block_size(needed_bcount), &commit_zero)) {- memid->initially_committed = false;+ if (!_mi_os_commit_ex(p, mi_size_of_slices(slice_count), &commit_zero, mi_size_of_slices(slice_count - already_committed))) {+ // if the commit fails, release ownership, and return NULL;+ // note: this does not roll back dirty bits but that is ok.+ mi_bbitmap_setN(arena->slices_free, slice_index, slice_count);+ return NULL;}- else {- if (commit_zero) { memid->initially_zero = true; }+ if (commit_zero) {+ memid->initially_zero = true;}- }- }- else {- // no need to commit, but check if already fully committed- memid->initially_committed = _mi_bitmap_is_claimed_across(arena->blocks_committed, arena->field_count, needed_bcount, bitmap_index);- }-- return p;-}--// allocate in a specific arena-static void* mi_arena_try_alloc_at_id(mi_arena_id_t arena_id, bool match_numa_node, int numa_node, size_t size, size_t alignment,- bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid )-{- MI_UNUSED_RELEASE(alignment);- mi_assert(alignment <= MI_SEGMENT_ALIGN);- const size_t bcount = mi_block_count_of_size(size);- const size_t arena_index = mi_arena_id_index(arena_id);- mi_assert_internal(arena_index < mi_atomic_load_relaxed(&mi_arena_count));- mi_assert_internal(size <= mi_arena_block_size(bcount));-- // Check arena suitability- mi_arena_t* arena = mi_arena_from_index(arena_index);- if (arena == NULL) return NULL;- if (!allow_large && arena->is_large) return NULL;- if (!mi_arena_id_is_suitable(arena->id, arena->exclusive, req_arena_id)) return NULL;- if (req_arena_id == _mi_arena_id_none()) { // in not specific, check numa affinity- const bool numa_suitable = (numa_node < 0 || arena->numa_node < 0 || arena->numa_node == numa_node);- if (match_numa_node) { if (!numa_suitable) return NULL; }- else { if (numa_suitable) return NULL; }- }- // try to allocate- void* p = mi_arena_try_alloc_at(arena, arena_index, bcount, commit, memid);- mi_assert_internal(p == NULL || _mi_is_aligned(p, alignment));- return p;-}+ // set the commit bits+ mi_bitmap_setN(arena->slices_committed, slice_index, slice_count, NULL);+ // committed+ #if MI_DEBUG > 1+ if (memid->initially_zero) {+ if (!mi_mem_is_zero(p, mi_size_of_slices(slice_count))) {+ _mi_error_message(EFAULT, "internal error: arena allocation was not zero-initialized!\n");+ memid->initially_zero = false;+ }+ }+ #endif+ }+ else {+ // already fully committed.+ _mi_os_reuse(p, mi_size_of_slices(slice_count));+ // if the OS has overcommit, and this is the first time we access these pages, then+ // count the commit now (as at arena reserve we didn't count those commits as these are on-demand)+ if (_mi_os_has_overcommit() && touched_slices > 0) {+ mi_subproc_stat_increase( arena->subproc, committed, mi_size_of_slices(touched_slices));+ }+ }-// allocate from an arena with fallback to the OS-static mi_decl_noinline void* mi_arena_try_alloc(int numa_node, size_t size, size_t alignment,- bool commit, bool allow_large,- mi_arena_id_t req_arena_id, mi_memid_t* memid )-{- MI_UNUSED(alignment);- mi_assert_internal(alignment <= MI_SEGMENT_ALIGN);- const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);- if mi_likely(max_arena == 0) return NULL;+ mi_assert_internal(mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));+ memid->initially_committed = true;- if (req_arena_id != _mi_arena_id_none()) {- // try a specific arena if requested- if (mi_arena_id_index(req_arena_id) < max_arena) {- void* p = mi_arena_try_alloc_at_id(req_arena_id, true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);- if (p != NULL) return p;+ // tool support+ if (memid->initially_zero) {+ mi_track_mem_defined(p, slice_count * MI_ARENA_SLICE_SIZE);+ }+ else {+ mi_track_mem_undefined(p, slice_count * MI_ARENA_SLICE_SIZE);}}else {- // try numa affine allocation- for (size_t i = 0; i < max_arena; i++) {- void* p = mi_arena_try_alloc_at_id(mi_arena_id_create(i), true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);- if (p != NULL) return p;- }-- // try from another numa node instead..- if (numa_node >= 0) { // if numa_node was < 0 (no specific affinity requested), all arena's have been tried already- for (size_t i = 0; i < max_arena; i++) {- void* p = mi_arena_try_alloc_at_id(mi_arena_id_create(i), false /* only proceed if not numa local */, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);- if (p != NULL) return p;- }+ // no need to commit, but check if it is already fully committed+ memid->initially_committed = mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count);+ if (!memid->initially_committed) {+ // partly committed.. adjust stats+ size_t already_committed_count = 0;+ mi_bitmap_setN(arena->slices_committed, slice_index, slice_count, &already_committed_count);+ mi_bitmap_clearN(arena->slices_committed, slice_index, slice_count);+ mi_subproc_stat_decrease(arena->subproc, committed, mi_size_of_slices(already_committed_count));}}- return NULL;++ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ if (commit) { mi_assert_internal(mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count)); }+ if (commit) { mi_assert_internal(memid->initially_committed); }+ mi_assert_internal(mi_bitmap_is_setN(arena->slices_dirty, slice_index, slice_count));++ return p;}++static int mi_reserve_os_memory_ex2(mi_subproc_t* subproc, size_t size, bool commit, bool allow_large, bool exclusive, mi_arena_id_t* arena_id);+// try to reserve a fresh arena space-static bool mi_arena_reserve(size_t req_size, bool allow_large, mi_arena_id_t *arena_id)+static bool mi_arena_reserve(mi_subproc_t* subproc, size_t req_size, bool allow_large, mi_arena_id_t* arena_id){- if (_mi_preloading()) return false; // use OS only while pre loading-- const size_t arena_count = mi_atomic_load_acquire(&mi_arena_count);+ const size_t arena_count = mi_arenas_get_count(subproc);if (arena_count > (MI_MAX_ARENAS - 4)) return false;+ // calc reservesize_t arena_reserve = mi_option_get_size(mi_option_arena_reserve);if (arena_reserve == 0) return false;if (!_mi_os_has_virtual_reserve()) {arena_reserve = arena_reserve/4; // be conservative if virtual reserve is not supported (for WASM for example)}- arena_reserve = _mi_align_up(arena_reserve, MI_ARENA_BLOCK_SIZE);- arena_reserve = _mi_align_up(arena_reserve, MI_SEGMENT_SIZE);- if (arena_count >= 8 && arena_count <= 128) {- // scale up the arena sizes exponentially every 8 entries (128 entries get to 589TiB)- const size_t multiplier = (size_t)1 << _mi_clamp(arena_count/8, 0, 16 );+ arena_reserve = _mi_align_up(arena_reserve, MI_ARENA_SLICE_SIZE);++ if (arena_count >= 1 && arena_count <= 128) {+ // scale up the arena sizes exponentially every 8 entries+ const size_t multiplier = (size_t)1 << _mi_clamp(arena_count/8, 0, 16);size_t reserve = 0;if (!mi_mul_overflow(multiplier, arena_reserve, &reserve)) {arena_reserve = reserve;}}- if (arena_reserve < req_size) return false; // should be able to at least handle the current allocation size++ // try to accommodate the requested size for huge allocations+ req_size = _mi_align_up(req_size + MI_ARENA_MAX_CHUNK_OBJ_SIZE, MI_ARENA_MAX_CHUNK_OBJ_SIZE); // over-reserve for meta-info+ if (arena_reserve < req_size) {+ arena_reserve = req_size;+ }++ // check arena bounds+ const size_t min_reserve = MI_ARENA_MIN_SIZE;+ const size_t max_reserve = MI_ARENA_MAX_SIZE; // 16 GiB+ if (arena_reserve < min_reserve) {+ arena_reserve = min_reserve;+ }+ else if (arena_reserve > max_reserve) {+ arena_reserve = max_reserve;+ }++ // should be able to at least handle the current allocation size+ if (arena_reserve < req_size) return false;// commit eagerly?bool arena_commit = false;- if (mi_option_get(mi_option_arena_eager_commit) == 2) { arena_commit = _mi_os_has_overcommit(); }+ const bool overcommit = _mi_os_has_overcommit();+ if (mi_option_get(mi_option_arena_eager_commit) == 2) { arena_commit = overcommit; }else if (mi_option_get(mi_option_arena_eager_commit) == 1) { arena_commit = true; }- return (mi_reserve_os_memory_ex(arena_reserve, arena_commit, allow_large, false /* exclusive? */, arena_id) == 0);+ // on an OS with overcommit (Linux) we don't count the commit yet as it is on-demand. Once a slice+ // is actually allocated for the first time it will be counted.+ const bool adjust = (overcommit && arena_commit);+ if (adjust) { mi_subproc_stat_adjust_decrease( subproc, committed, arena_reserve); }+ // and try to reserve the arena+ int err = mi_reserve_os_memory_ex2(subproc, arena_reserve, arena_commit, allow_large, false /* exclusive? */, arena_id);+ if (err != 0) {+ if (adjust) { mi_subproc_stat_adjust_increase( subproc, committed, arena_reserve); } // roll back+ // failed to allocate: try a smaller size arena as fallback?+ const size_t small_arena_reserve = 4 * MI_ARENA_MIN_SIZE; // 128 MiB (or 32 MiB on 32-bit)+ if (arena_reserve > small_arena_reserve && small_arena_reserve > req_size) {+ // try again+ if (adjust) { mi_subproc_stat_adjust_decrease(subproc, committed, small_arena_reserve); }+ err = mi_reserve_os_memory_ex2(subproc, small_arena_reserve, arena_commit, allow_large, false /* exclusive? */, arena_id);+ if (err != 0 && adjust) { mi_subproc_stat_adjust_increase( subproc, committed, small_arena_reserve); } // roll back+ }+ }+ return (err==0);}-void* _mi_arena_alloc_aligned(size_t size, size_t alignment, size_t align_offset, bool commit, bool allow_large,- mi_arena_id_t req_arena_id, mi_memid_t* memid)-{- mi_assert_internal(memid != NULL);- mi_assert_internal(size > 0);- *memid = _mi_memid_none();- const int numa_node = _mi_os_numa_node(); // current numa node- // try to allocate in an arena if the alignment is small enough and the object is not too small (as for heap meta data)- if (!mi_option_is_enabled(mi_option_disallow_arena_alloc)) { // is arena allocation allowed?- if (size >= MI_ARENA_MIN_OBJ_SIZE && alignment <= MI_SEGMENT_ALIGN && align_offset == 0)+/* -----------------------------------------------------------+ Arena iteration+----------------------------------------------------------- */++static inline bool mi_arena_is_suitable(mi_arena_t* arena, mi_arena_t* req_arena, bool match_numa, int numa_node, bool allow_pinned) {+ if (!allow_pinned && arena->memid.is_pinned) return false;+ if (!mi_arena_id_is_suitable(arena, req_arena)) return false;+ if (req_arena == NULL) { // if not specific, check numa affinity+ const bool numa_suitable = (numa_node < 0 || arena->numa_node < 0 || arena->numa_node == numa_node);+ if (match_numa) { if (!numa_suitable) return false; }+ else { if (numa_suitable) return false; }+ }+ return true;+}++// determine the start of search; important to keep heaps and threads+// into their own memory regions to reduce contention.+static size_t mi_arena_start_idx(mi_heap_t* heap, size_t tseq, size_t arena_cycle) {+ const size_t hseq = heap->heap_seq;+ const size_t hcount = mi_atomic_load_relaxed(&heap->subproc->heap_count);+ if (arena_cycle <= 1) return 0;+ if (hseq==0 || hcount<=1) return (tseq % arena_cycle); // common for single heap programs++ // spread heaps evenly among arena's, and then evenly for threads in their fraction+ size_t start;+ mi_assert_internal(arena_cycle <= 0x8FF); // prevent overflow on 32-bit+ const size_t frac = (arena_cycle * 256) / hcount; // fraction in the arena_cycle; at most: arena_cycle * 0x100+ if (frac==0) {+ // many heaps (> 256 per arena)+ start = (hseq % arena_cycle);+ }+ else {+ const size_t hspot = (hseq % hcount);+ start = (frac * hspot) / 256;+ if (frac >= 512) { // at least 2 arena's per heap?+ start = start + (tseq % (frac/256));+ }+ }+ mi_assert_internal(start < arena_cycle);+ return start;+}++#define mi_forall_arenas(heap, req_arena, tseq, name_arena) { \+ const size_t _arena_count = mi_arenas_get_count(heap->subproc); \+ const size_t _arena_cycle = (_arena_count == 0 ? 0 : _arena_count - 1); /* first search the arenas below the last one */ \+ /* always start searching in the arena's below the max */ \+ const size_t _start = mi_arena_start_idx(heap,tseq,_arena_cycle); \+ for (size_t _i = 0; _i < _arena_count; _i++) { \+ mi_arena_t* name_arena; \+ if (req_arena != NULL) { \+ name_arena = req_arena; /* if there is a specific req_arena, only search that one */\+ if (_i > 0) break; /* only once */ \+ } \+ else { \+ size_t _idx; \+ if (_i < _arena_cycle) { \+ _idx = _i + _start; \+ if (_idx >= _arena_cycle) { _idx -= _arena_cycle; } /* adjust so we rotate through the cycle */ \+ } \+ else { \+ _idx = _i; /* remaining arena's after the cycle */ \+ } \+ name_arena = mi_arena_from_index(heap->subproc,_idx); \+ } \+ if (name_arena != NULL) \{- void* p = mi_arena_try_alloc(numa_node, size, alignment, commit, allow_large, req_arena_id, memid);- if (p != NULL) return p;-- // otherwise, try to first eagerly reserve a new arena- if (req_arena_id == _mi_arena_id_none()) {- mi_arena_id_t arena_id = 0;- if (mi_arena_reserve(size, allow_large, &arena_id)) {- // and try allocate in there- mi_assert_internal(req_arena_id == _mi_arena_id_none());- p = mi_arena_try_alloc_at_id(arena_id, true, numa_node, size, alignment, commit, allow_large, req_arena_id, memid);- if (p != NULL) return p;- }- }++#define mi_forall_arenas_end() \+ } \+ } \+ }++#define mi_forall_suitable_arenas(heap, req_arena, tseq, match_numa, numa_node, allow_large, name_arena) \+ mi_forall_arenas(heap, req_arena,tseq,name_arena) { \+ if (mi_arena_is_suitable(name_arena, req_arena, match_numa, numa_node, allow_large)) { \++#define mi_forall_suitable_arenas_end() \+ }} \+ mi_forall_arenas_end()++/* -----------------------------------------------------------+ Arena allocation+----------------------------------------------------------- */++// allocate slices from the arenas+static mi_decl_noinline void* mi_arenas_try_find_free(+ mi_heap_t* heap, size_t slice_count, size_t alignment,+ bool commit, bool allow_large, mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid)+{+ // mi_assert_internal(slice_count <= mi_slice_count_of_size(MI_ARENA_MAX_CHUNK_OBJ_SIZE));+ mi_assert(alignment <= MI_ARENA_SLICE_ALIGN);+ if (alignment > MI_ARENA_SLICE_ALIGN) return NULL;++ // search arena's+ mi_forall_suitable_arenas(heap, req_arena, tseq, true /* only numa matching */, numa_node, allow_large, arena)+ {+ void* p = mi_arena_try_alloc_at(arena, slice_count, commit, tseq, memid);+ if (p != NULL) return p;+ }+ mi_forall_suitable_arenas_end();+ if (numa_node < 0) return NULL;++ // search again but now regardless of preferred numa affinity+ mi_forall_suitable_arenas(heap, req_arena, tseq, false /* numa non-matching now */, numa_node, allow_large, arena)+ {+ void* p = mi_arena_try_alloc_at(arena, slice_count, commit, tseq, memid);+ if (p != NULL) return p;+ }+ mi_forall_suitable_arenas_end();+ return NULL;+}++// Allocate slices from the arena's -- potentially allocating a fresh arena+static mi_decl_noinline void* mi_arenas_try_alloc(+ mi_heap_t* heap,+ size_t slice_count, size_t alignment,+ bool commit, bool allow_large,+ mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid)+{+ // mi_assert(slice_count <= MI_ARENA_MAX_CHUNK_OBJ_SLICES);+ mi_assert(alignment <= MI_ARENA_SLICE_ALIGN);+ void* p;++ // not too large?+ if (slice_count * MI_ARENA_SLICE_SIZE > MI_ARENA_MAX_SIZE) return NULL;++ // try to find free slices in the arena's+ p = mi_arenas_try_find_free(heap, slice_count, alignment, commit, allow_large, req_arena, tseq, numa_node, memid);+ if (p != NULL) return p;++ // did we need a specific arena?+ if (req_arena != NULL) return NULL;++ // don't create arena's while preloading (todo: or should we?)+ if (_mi_preloading()) return NULL;++ // otherwise, try to reserve a new arena -- but one thread at a time.. (todo: allow 2 or 4 to reduce contention?)+ mi_subproc_t* const subproc = heap->subproc;+ const size_t arena_count = mi_arenas_get_count(subproc);+ mi_lock(&subproc->arena_reserve_lock) {+ if (arena_count == mi_arenas_get_count(subproc)) {+ // we are the first to enter the lock, reserve a fresh arena+ mi_arena_id_t arena_id = 0;+ mi_arena_reserve(subproc, mi_size_of_slices(slice_count), allow_large, &arena_id);+ }+ else {+ // another thread already reserved a new arena}}+ // try once more to allocate in the new arena+ mi_assert_internal(req_arena == NULL);+ p = mi_arenas_try_find_free(heap, slice_count, alignment, commit, allow_large, req_arena, tseq, numa_node, memid);+ if (p != NULL) return p;++ return NULL;+}+// Allocate from the OS (if allowed)+static void* mi_arena_os_alloc_aligned(+ size_t size, size_t alignment, size_t align_offset,+ bool commit, bool allow_large,+ mi_arena_id_t req_arena_id, mi_memid_t* memid)+{// if we cannot use OS allocation, return NULLif (mi_option_is_enabled(mi_option_disallow_os_alloc) || req_arena_id != _mi_arena_id_none()) {errno = ENOMEM;return NULL;}- // finally, fall back to the OSif (align_offset > 0) {return _mi_os_alloc_aligned_at_offset(size, alignment, align_offset, commit, allow_large, memid);}@@ -433,383 +522,869 @@ void* _mi_arena_alloc_aligned(size_t size, size_t alignment, size_t align_offset}}-void* _mi_arena_alloc(size_t size, bool commit, bool allow_large, mi_arena_id_t req_arena_id, mi_memid_t* memid)++// Allocate large sized memory+void* _mi_arenas_alloc_aligned( mi_heap_t* heap,+ size_t size, size_t alignment, size_t align_offset,+ bool commit, bool allow_large,+ mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid){- return _mi_arena_alloc_aligned(size, MI_ARENA_BLOCK_SIZE, 0, commit, allow_large, req_arena_id, memid);-}+ mi_assert_internal(memid != NULL);+ mi_assert_internal(size > 0);++ // try to allocate in an arena if the alignment is small enough and the object is not too small (as for theap meta data)+ if (!mi_option_is_enabled(mi_option_disallow_arena_alloc) && // is arena allocation allowed?+ size >= MI_ARENA_MIN_OBJ_SIZE && size <= mi_arena_max_object_size() && // and not too small or too large+ alignment <= MI_ARENA_SLICE_ALIGN && align_offset == 0) // and good alignment+ {+ const size_t slice_count = mi_slice_count_of_size(size);+ void* p = mi_arenas_try_alloc(heap, slice_count, alignment, commit, allow_large, req_arena, tseq, numa_node, memid);+ if (p != NULL) return p;+ }+ // fall back to the OS+ void* p = mi_arena_os_alloc_aligned(size, alignment, align_offset, commit, allow_large, req_arena, memid);+ return p;+}-void* mi_arena_area(mi_arena_id_t arena_id, size_t* size) {- if (size != NULL) *size = 0;- size_t arena_index = mi_arena_id_index(arena_id);- if (arena_index >= MI_MAX_ARENAS) return NULL;- mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[arena_index]);- if (arena == NULL) return NULL;- if (size != NULL) { *size = mi_arena_block_size(arena->block_count); }- return arena->start;+void* _mi_arenas_alloc(mi_heap_t* heap, size_t size, bool commit, bool allow_large, mi_arena_t* req_arena, size_t tseq, int numa_node, mi_memid_t* memid)+{+ return _mi_arenas_alloc_aligned(heap, size, MI_ARENA_SLICE_SIZE, 0, commit, allow_large, req_arena, tseq, numa_node, memid);}+/* ------------------------------------------------------------ Arena purge+ Arena page allocation----------------------------------------------------------- */-static long mi_arena_purge_delay(void) {- // <0 = no purging allowed, 0=immediate purging, >0=milli-second delay- return (mi_option_get(mi_option_purge_delay) * mi_option_get(mi_option_arena_purge_mult));+// release ownership of a page. This may free the page if all blocks were concurrently+// freed in the meantime. Returns true if the page was freed.+static bool mi_abandoned_page_unown(mi_page_t* page, mi_theap_t* current_theap) {+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(_mi_thread_id()==current_theap->tld->thread_id);+ mi_thread_free_t tf_new;+ mi_thread_free_t tf_old = mi_atomic_load_relaxed(&page->xthread_free);+ do {+ mi_assert_internal(mi_tf_is_owned(tf_old));+ while mi_unlikely(mi_tf_block(tf_old) != NULL) {+ _mi_page_free_collect(page, false); // update used+ if (mi_page_all_free(page)) { // it may become free just before unowning it+ _mi_arenas_page_unabandon(page, current_theap);+ _mi_arenas_page_free(page, current_theap);+ return true;+ }+ tf_old = mi_atomic_load_relaxed(&page->xthread_free);+ }+ mi_assert_internal(mi_tf_block(tf_old)==NULL);+ tf_new = mi_tf_create(NULL, false);+ } while (!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tf_old, tf_new));+ return false;}-// reset or decommit in an arena and update the committed/decommit bitmaps-// assumes we own the area (i.e. blocks_in_use is claimed by us)-static void mi_arena_purge(mi_arena_t* arena, size_t bitmap_idx, size_t blocks) {- mi_assert_internal(arena->blocks_committed != NULL);- mi_assert_internal(arena->blocks_purge != NULL);- mi_assert_internal(!arena->memid.is_pinned);- const size_t size = mi_arena_block_size(blocks);- void* const p = mi_arena_block_start(arena, bitmap_idx);- bool needs_recommit;- if (_mi_bitmap_is_claimed_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx)) {- // all blocks are committed, we can purge freely- needs_recommit = _mi_os_purge(p, size);++static bool mi_arena_try_claim_abandoned(size_t slice_index, mi_arena_t* arena, bool* keep_abandoned) {+ // found an abandoned page of the right size+ mi_page_t* const page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ // can we claim ownership?+ if (!mi_page_claim_ownership(page)) {+ // there was a concurrent free that reclaims this page ..+ // we need to keep it in the abandoned map as the free will call `mi_arena_page_unabandon`,+ // and wait for readers (us!) to finish. This is why it is very important to set the abandoned+ // bit again (or otherwise the unabandon will never stop waiting).+ *keep_abandoned = true;+ return false;}else {- // some blocks are not committed -- this can happen when a partially committed block is freed- // in `_mi_arena_free` and it is conservatively marked as uncommitted but still scheduled for a purge- // we need to ensure we do not try to reset (as that may be invalid for uncommitted memory),- // and also undo the decommit stats (as it was already adjusted)- mi_assert_internal(mi_option_is_enabled(mi_option_purge_decommits));- needs_recommit = _mi_os_purge_ex(p, size, false /* allow reset? */, 0);- }-- // clear the purged blocks- _mi_bitmap_unclaim_across(arena->blocks_purge, arena->field_count, blocks, bitmap_idx);- // update committed bitmap- if (needs_recommit) {- _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx);+ // yes, we can reclaim it, keep the abandoned map entry clear+ *keep_abandoned = false;+ return true;}}-// Schedule a purge. This is usually delayed to avoid repeated decommit/commit calls.-// Note: assumes we (still) own the area as we may purge immediately-static void mi_arena_schedule_purge(mi_arena_t* arena, size_t bitmap_idx, size_t blocks) {- mi_assert_internal(arena->blocks_purge != NULL);- const long delay = mi_arena_purge_delay();- if (delay < 0) return; // is purging allowed at all?+// allocate initial arena_pages from the main heap+static mi_arena_pages_t* mi_arena_pages_alloc(mi_arena_t* arena);- if (_mi_preloading() || delay == 0) {- // decommit directly- mi_arena_purge(arena, bitmap_idx, blocks);- }- else {- // schedule purge- const mi_msecs_t expire = _mi_clock_now() + delay;- mi_msecs_t expire0 = 0;- if (mi_atomic_casi64_strong_acq_rel(&arena->purge_expire, &expire0, expire)) {- // expiration was not yet set- // maybe set the global arenas expire as well (if it wasn't set already)- mi_atomic_casi64_strong_acq_rel(&mi_arenas_purge_expire, &expire0, expire);- }- else {- // already an expiration was set- }- _mi_bitmap_claim_across(arena->blocks_purge, arena->field_count, blocks, bitmap_idx, NULL);- }-}--// purge a range of blocks-// return true if the full range was purged.-// assumes we own the area (i.e. blocks_in_use is claimed by us)-static bool mi_arena_purge_range(mi_arena_t* arena, size_t idx, size_t startidx, size_t bitlen, size_t purge) {- const size_t endidx = startidx + bitlen;- size_t bitidx = startidx;- bool all_purged = false;- while (bitidx < endidx) {- // count consecutive ones in the purge mask- size_t count = 0;- while (bitidx + count < endidx && (purge & ((size_t)1 << (bitidx + count))) != 0) {- count++;- }- if (count > 0) {- // found range to be purged- const mi_bitmap_index_t range_idx = mi_bitmap_index_create(idx, bitidx);- mi_arena_purge(arena, range_idx, count);- if (count == bitlen) {- all_purged = true;- }- }- bitidx += (count+1); // +1 to skip the zero bit (or end)- }- return all_purged;+static mi_arena_pages_t* mi_heap_arena_pages(mi_heap_t* heap, mi_arena_t* arena) {+ mi_assert_internal(arena!=NULL);+ mi_assert_internal(heap!=NULL);+ mi_assert(arena->arena_idx < MI_MAX_ARENAS);+ return mi_atomic_load_ptr_relaxed(mi_arena_pages_t, &heap->arena_pages[arena->arena_idx]);}-// returns true if anything was purged-static bool mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force)-{- // check pre-conditions- if (arena->memid.is_pinned) return false;-- // expired yet?- mi_msecs_t expire = mi_atomic_loadi64_relaxed(&arena->purge_expire);- if (!force && (expire == 0 || expire > now)) return false;+static mi_arena_t* mi_page_arena_pages(mi_page_t* page, size_t* slice_index, size_t* slice_count, mi_arena_pages_t** parena_pages) {+ // todo: maybe store the arena* directly in the page?+ mi_assert_internal(mi_page_is_owned(page));+ mi_arena_t* const arena = mi_arena_from_memid(page->memid, slice_index, slice_count);+ mi_assert_internal(arena != NULL);+ if (parena_pages != NULL) {+ mi_arena_pages_t* const arena_pages = mi_heap_arena_pages(mi_page_heap(page), arena);+ mi_assert_internal(arena_pages != NULL);+ mi_assert_internal(slice_index==NULL || mi_bitmap_is_set(arena_pages->pages, *slice_index));+ *parena_pages = arena_pages;+ }+ return arena;+}- // reset expire (if not already set concurrently)- mi_atomic_casi64_strong_acq_rel(&arena->purge_expire, &expire, (mi_msecs_t)0);-- // potential purges scheduled, walk through the bitmap- bool any_purged = false;- bool full_purge = true;- for (size_t i = 0; i < arena->field_count; i++) {- size_t purge = mi_atomic_load_relaxed(&arena->blocks_purge[i]);- if (purge != 0) {- size_t bitidx = 0;- while (bitidx < MI_BITMAP_FIELD_BITS) {- // find consecutive range of ones in the purge mask- size_t bitlen = 0;- while (bitidx + bitlen < MI_BITMAP_FIELD_BITS && (purge & ((size_t)1 << (bitidx + bitlen))) != 0) {- bitlen++;+static mi_arena_pages_t* mi_heap_ensure_arena_pages(mi_heap_t* heap, mi_arena_t* arena) {+ mi_assert_internal(arena!=NULL);+ mi_assert_internal(heap!=NULL);+ mi_assert(arena->arena_idx < MI_MAX_ARENAS);+ mi_arena_pages_t* arena_pages = mi_heap_arena_pages(heap, arena);+ if (arena_pages==NULL) {+ mi_lock(&heap->arena_pages_lock) {+ arena_pages = mi_atomic_load_ptr_acquire(mi_arena_pages_t, &heap->arena_pages[arena->arena_idx]);+ if (arena_pages == NULL) { // still NULL?+ if (_mi_is_heap_main(heap)) {+ // the page info for the main heap is always allocated as part of an arena+ arena_pages = &arena->pages_main;}- // temporarily claim the purge range as "in-use" to be thread-safe with allocation- // try to claim the longest range of corresponding in_use bits- const mi_bitmap_index_t bitmap_index = mi_bitmap_index_create(i, bitidx);- while( bitlen > 0 ) {- if (_mi_bitmap_try_claim(arena->blocks_inuse, arena->field_count, bitlen, bitmap_index)) {- break;- }- bitlen--;- }- // actual claimed bits at `in_use`- if (bitlen > 0) {- // read purge again now that we have the in_use bits- purge = mi_atomic_load_acquire(&arena->blocks_purge[i]);- if (!mi_arena_purge_range(arena, i, bitidx, bitlen, purge)) {- full_purge = false;- }- any_purged = true;- // release the claimed `in_use` bits again- _mi_bitmap_unclaim(arena->blocks_inuse, arena->field_count, bitlen, bitmap_index);+ else {+ // always allocate the arena pages info from the main heap+ // todo: allocate into the current arena?+ arena_pages = mi_arena_pages_alloc(arena);}- bitidx += (bitlen+1); // +1 to skip the zero (or end)- } // while bitidx- } // purge != 0- }- // if not fully purged, make sure to purge again in the future- if (!full_purge) {- const long delay = mi_arena_purge_delay();- mi_msecs_t expected = 0;- mi_atomic_casi64_strong_acq_rel(&arena->purge_expire,&expected,_mi_clock_now() + delay);+ mi_atomic_store_ptr_release(mi_arena_pages_t, &heap->arena_pages[arena->arena_idx], arena_pages);+ }+ }}- return any_purged;+ if (_mi_is_heap_main(heap)) { mi_assert(arena_pages != NULL); } // can never fail+ return arena_pages;}-static void mi_arenas_try_purge( bool force, bool visit_all )+static mi_page_t* mi_arenas_page_try_find_abandoned(mi_theap_t* theap, size_t slice_count, size_t block_size){- if (_mi_preloading() || mi_arena_purge_delay() <= 0) return; // nothing will be scheduled+ mi_heap_t* const heap = theap->heap;+ const size_t tseq = theap->tld->thread_seq;+ mi_arena_t* const req_arena = heap->exclusive_arena;- // check if any arena needs purging?- const mi_msecs_t now = _mi_clock_now();- mi_msecs_t arenas_expire = mi_atomic_load_acquire(&mi_arenas_purge_expire);- if (!force && (arenas_expire == 0 || arenas_expire < now)) return;+ MI_UNUSED(slice_count);+ const size_t bin = _mi_bin(block_size);+ mi_assert_internal(bin < MI_BIN_COUNT);- const size_t max_arena = mi_atomic_load_acquire(&mi_arena_count);- if (max_arena == 0) return;+ // any abandoned in our size class?+ mi_assert_internal(heap != NULL);+ if (mi_atomic_load_relaxed(&heap->abandoned_count[bin]) == 0) {+ return NULL;+ }- // allow only one thread to purge at a time- static mi_atomic_guard_t purge_guard;- mi_atomic_guard(&purge_guard)+ // search arena's+ const bool allow_large = true;+ const int any_numa = -1;+ const bool match_numa = true;+ mi_forall_suitable_arenas(heap, req_arena, tseq, match_numa, any_numa, allow_large, arena){- // increase global expire: at most one purge per delay cycle- mi_atomic_store_release(&mi_arenas_purge_expire, now + mi_arena_purge_delay());- size_t max_purge_count = (visit_all ? max_arena : 2);- bool all_visited = true;- for (size_t i = 0; i < max_arena; i++) {- mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[i]);- if (arena != NULL) {- if (mi_arena_try_purge(arena, now, force)) {- if (max_purge_count <= 1) {- all_visited = false;- break;- }- max_purge_count--;- }+ mi_arena_pages_t* const arena_pages = mi_heap_arena_pages(heap, arena);+ if (arena_pages != NULL) {+ size_t slice_index;+ mi_bitmap_t* const bitmap = arena_pages->pages_abandoned[bin];++ if (mi_bitmap_try_find_and_claim(bitmap, tseq, &slice_index, &mi_arena_try_claim_abandoned, arena)) {+ // found an abandoned page of the right size+ // and claimed ownership.+ mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(mi_heap_has_page(heap, arena, page));+ mi_atomic_decrement_relaxed(&heap->abandoned_count[bin]);+ mi_theap_stat_decrease(theap, pages_abandoned, 1);+ mi_theap_stat_counter_increase(theap, pages_reclaim_on_alloc, 1);++ _mi_page_free_collect(page, false); // update `used` count+ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ mi_assert_internal(page->slice_committed > 0 || mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));+ mi_assert_internal(mi_bitmap_is_setN(arena->slices_dirty, slice_index, slice_count));+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);+ mi_assert_internal(mi_page_block_size(page) == block_size);+ mi_assert_internal(!mi_page_is_full(page));+ return page;}}- if (all_visited) {- // all arena's were visited and purged: reset global expire- mi_atomic_store_release(&mi_arenas_purge_expire, 0);- }}+ mi_forall_suitable_arenas_end();+ return NULL;}-/* ------------------------------------------------------------ Arena free------------------------------------------------------------ */--void _mi_arena_free(void* p, size_t size, size_t committed_size, mi_memid_t memid) {- mi_assert_internal(size > 0);- mi_assert_internal(committed_size <= size);- if (p==NULL) return;- if (size==0) return;- const bool all_committed = (committed_size == size);-- // need to set all memory to undefined as some parts may still be marked as no_access (like padding etc.)- mi_track_mem_undefined(p,size);+// Allocate a fresh page+static mi_page_t* mi_arenas_page_alloc_fresh(mi_theap_t* theap, size_t slice_count, size_t block_size, size_t block_alignment, bool commit)+{+ const bool allow_large = (MI_SECURE < 2); // 2 = guard page at end of each arena page+ const bool os_align = (block_alignment > MI_PAGE_MAX_OVERALLOC_ALIGN);+ const size_t page_alignment = MI_ARENA_SLICE_ALIGN;++ mi_heap_t* const heap = theap->heap;+ mi_tld_t* const tld = theap->tld;+ mi_arena_t* const req_arena = heap->exclusive_arena;+ const int numa_node = (heap->numa_node >= 0 ? heap->numa_node : tld->numa_node);+++ // try to allocate from free space in arena's+ mi_memid_t memid = _mi_memid_none();+ mi_page_t* page = NULL;+ const size_t alloc_size = mi_size_of_slices(slice_count);+ if (!mi_option_is_enabled(mi_option_disallow_arena_alloc) && // allowed to allocate from arena's?+ !os_align && // not large alignment+ slice_count <= mi_arena_max_object_size()/MI_ARENA_SLICE_SIZE) // and not too large+ {+ page = (mi_page_t*)mi_arenas_try_alloc(heap, slice_count, page_alignment, commit, allow_large, req_arena, tld->thread_seq, numa_node, &memid);+ if (page != NULL) {+ mi_arena_pages_t* const arena_pages = mi_heap_ensure_arena_pages(heap, memid.mem.arena.arena);+ if (arena_pages==NULL) {+ _mi_arenas_free(page, mi_size_of_slices(slice_count), page->memid); // roll back+ page = NULL;+ }+ else {+ mi_assert_internal(mi_bitmap_is_clearN(arena_pages->pages, memid.mem.arena.slice_index, memid.mem.arena.slice_count));+ mi_bitmap_set(arena_pages->pages, memid.mem.arena.slice_index);+ }+ }+ }++ // otherwise fall back to the OS+ if (page == NULL) {+ if (os_align) {+ // note: slice_count already includes the page+ mi_assert_internal(slice_count >= mi_slice_count_of_size(block_size) + mi_slice_count_of_size(page_alignment));+ page = (mi_page_t*)mi_arena_os_alloc_aligned(alloc_size, block_alignment, page_alignment /* align offset */, commit, allow_large, req_arena, &memid);+ }+ else {+ page = (mi_page_t*)mi_arena_os_alloc_aligned(alloc_size, page_alignment, 0 /* align offset */, commit, allow_large, req_arena, &memid);+ }+ }++ if (page == NULL) return NULL;+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(!os_align || _mi_is_aligned((uint8_t*)page + page_alignment, block_alignment));++ // guard page at the end of mimalloc page?+ #if MI_SECURE < 2+ const size_t page_noguard_size = alloc_size;+ #else+ mi_assert(alloc_size > _mi_os_secure_guard_page_size());+ const size_t page_noguard_size = alloc_size - _mi_os_secure_guard_page_size();+ if (memid.initially_committed) {+ _mi_os_secure_guard_page_set_at((uint8_t*)page + page_noguard_size, memid);+ }+ #endif++ // claimed free slices: initialize the page partly+ if (!memid.initially_zero && memid.initially_committed) {+ mi_track_mem_undefined(page, slice_count * MI_ARENA_SLICE_SIZE);+ _mi_memzero_aligned(page, sizeof(*page));+ }+ else if (memid.initially_committed) {+ mi_track_mem_defined(page, slice_count * MI_ARENA_SLICE_SIZE);+ }+ #if MI_DEBUG > 1+ if (memid.initially_zero && memid.initially_committed) {+ if (!mi_mem_is_zero(page, page_noguard_size)) {+ _mi_error_message(EFAULT, "internal error: page memory was not zero initialized.\n");+ memid.initially_zero = false;+ _mi_memzero_aligned(page, sizeof(*page));+ }+ }+ #endif+ mi_assert(MI_PAGE_INFO_SIZE >= mi_page_info_size());++ size_t block_start;+ #if MI_GUARDED+ // in a guarded build, we align pages with blocks a multiple of an OS page size, to the OS page size+ // this ensures that all blocks in such pages are OS page size aligned (which is needed for the guard pages)+ const size_t os_page_size = _mi_os_page_size();+ mi_assert_internal(MI_PAGE_ALIGN >= os_page_size);+ if (!os_align && block_size % os_page_size == 0 && block_size > os_page_size /* at least 2 or more */ ) {+ block_start = _mi_align_up(mi_page_info_size(), os_page_size);+ }+ else+ #endif+ if (os_align) {+ block_start = MI_PAGE_ALIGN;+ }+ else if (_mi_is_power_of_two(block_size) && block_size <= MI_PAGE_MAX_START_BLOCK_ALIGN2) {+ // naturally align power-of-2 blocks up to MI_PAGE_MAX_START_BLOCK_ALIGN2 size (4KiB)+ block_start = _mi_align_up(mi_page_info_size(), block_size);+ }+ else if (block_size != 0 && (block_size % MI_PAGE_OSPAGE_BLOCK_ALIGN2) == 0) {+ // also align large pages that are a multiple of MI_PAGE_OSPAGE_BLOCK_ALIGN2 (4KiB)+ block_start = _mi_align_up(mi_page_info_size(), MI_PAGE_OSPAGE_BLOCK_ALIGN2);+ }+ else {+ // otherwise start after the info+ block_start = mi_page_info_size();+ }+ const size_t reserved = (os_align ? 1 : (page_noguard_size - block_start) / block_size);+ mi_assert_internal(reserved > 0 && reserved <= UINT16_MAX);++ // commit first block?+ size_t commit_size = 0;+ if (!memid.initially_committed) {+ commit_size = _mi_align_up(block_start + block_size, MI_PAGE_MIN_COMMIT_SIZE);+ if (commit_size > page_noguard_size) { commit_size = page_noguard_size; }+ bool is_zero;+ if mi_unlikely(!mi_arena_commit( mi_memid_arena(memid), page, commit_size, &is_zero, 0)) {+ _mi_arenas_free(page, alloc_size, memid);+ return NULL;+ }+ if (!memid.initially_zero && !is_zero) {+ _mi_memzero_aligned(page, commit_size);+ }+ }++ // initialize+ page->reserved = (uint16_t)reserved;+ page->page_start = (uint8_t*)page + block_start;+ page->block_size = block_size;+ page->slice_committed = commit_size;+ page->memid = memid;+ page->free_is_zero = memid.initially_zero;++ // and own it+ mi_page_claim_ownership(page);++ // register in the page map+ if mi_unlikely(!_mi_page_map_register(page)) {+ _mi_arenas_free( page, alloc_size, memid );+ return NULL;+ }++ // stats+ mi_theap_stat_increase(theap, pages, 1);+ mi_theap_stat_increase(theap, page_bins[_mi_page_stats_bin(page)], 1);++ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);+ mi_assert_internal(mi_page_block_size(page) == block_size);+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(mi_page_is_owned(page));++ return page;+}++// Allocate a regular small/medium/large page.+static mi_page_t* mi_arenas_page_regular_alloc(mi_theap_t* theap, size_t slice_count, size_t block_size)+{+ // 1. look for an abandoned page+ mi_page_t* page = mi_arenas_page_try_find_abandoned(theap, slice_count, block_size);+ if (page != NULL) {+ return page; // return as abandoned+ }++ // 2. find a free block, potentially allocating a new arena+ const long commit_on_demand = mi_option_get(mi_option_page_commit_on_demand);+ const bool commit = (slice_count <= mi_slice_count_of_size(MI_PAGE_MIN_COMMIT_SIZE) || // always commit small pages+ (commit_on_demand == 2 && _mi_os_has_overcommit()) || (commit_on_demand == 0));+ page = mi_arenas_page_alloc_fresh(theap, slice_count, block_size, 1, commit);+ if (page == NULL) return NULL;++ mi_assert_internal(page->memid.memkind != MI_MEM_ARENA || page->memid.mem.arena.slice_count == slice_count);+ if (!_mi_page_init(theap, page)) {+ _mi_arenas_free( page, mi_page_full_size(page), page->memid);+ return NULL;+ }++ return page;+}++// Allocate a page containing one block (very large, or with large alignment)+static mi_page_t* mi_arenas_page_singleton_alloc(mi_theap_t* theap, size_t block_size, size_t block_alignment)+{+ const bool os_align = (block_alignment > MI_PAGE_MAX_OVERALLOC_ALIGN);+ const size_t info_size = (os_align ? MI_PAGE_ALIGN : mi_page_info_size());+ #if MI_SECURE < 2+ const size_t slice_count = mi_slice_count_of_size(info_size + block_size);+ #else+ const size_t slice_count = mi_slice_count_of_size(_mi_align_up(info_size + block_size, _mi_os_secure_guard_page_size()) + _mi_os_secure_guard_page_size());+ #endif++ mi_page_t* page = mi_arenas_page_alloc_fresh(theap, slice_count, block_size, block_alignment, true /* commit singletons always */);+ if (page == NULL) return NULL;++ mi_assert(page->reserved == 1);+ if (!_mi_page_init(theap, page)) {+ _mi_arenas_free( page, mi_page_full_size(page), page->memid);+ return NULL;+ }++ return page;+}+++mi_page_t* _mi_arenas_page_alloc(mi_theap_t* theap, size_t block_size, size_t block_alignment) {+ mi_page_t* page;+ if mi_unlikely(block_alignment > MI_PAGE_MAX_OVERALLOC_ALIGN) {+ mi_assert_internal(_mi_is_power_of_two(block_alignment));+ page = mi_arenas_page_singleton_alloc(theap, block_size, block_alignment);+ }+ else if (block_size <= MI_SMALL_MAX_OBJ_SIZE) {+ page = mi_arenas_page_regular_alloc(theap, mi_slice_count_of_size(MI_SMALL_PAGE_SIZE), block_size);+ }+ else if (block_size <= MI_MEDIUM_MAX_OBJ_SIZE) {+ page = mi_arenas_page_regular_alloc(theap, mi_slice_count_of_size(MI_MEDIUM_PAGE_SIZE), block_size);+ }+ #if MI_ENABLE_LARGE_PAGES+ else if (block_size <= MI_LARGE_MAX_OBJ_SIZE) {+ page = mi_arenas_page_regular_alloc(theap, mi_slice_count_of_size(MI_LARGE_PAGE_SIZE), block_size);+ }+ #endif+ else {+ page = mi_arenas_page_singleton_alloc(theap, block_size, block_alignment);+ }+ if mi_unlikely(page == NULL) {+ return NULL;+ }+ // mi_assert_internal(page == NULL || _mi_page_segment(page)->subproc == tld->subproc);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(_mi_ptr_page(mi_page_start(page))==page);+ mi_assert_internal(block_alignment <= MI_PAGE_MAX_OVERALLOC_ALIGN || _mi_is_aligned(mi_page_start(page), block_alignment));++ return page;+}++void _mi_arenas_page_free(mi_page_t* page, mi_theap_t* current_theapx) {+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_all_free(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(page->next==NULL && page->prev==NULL);+ mi_assert_internal(current_theapx == NULL || _mi_thread_id()==current_theapx->tld->thread_id);++ if (current_theapx != NULL) {+ mi_theap_stat_decrease(current_theapx, page_bins[_mi_page_stats_bin(page)], 1);+ mi_theap_stat_decrease(current_theapx, pages, 1);+ }+ else {+ mi_heap_t* const heap = mi_page_heap(page);+ mi_heap_stat_decrease(heap, page_bins[_mi_page_stats_bin(page)], 1);+ mi_heap_stat_decrease(heap, pages, 1);+ }++ #if MI_DEBUG>1+ if (page->memid.memkind==MI_MEM_ARENA && !mi_page_is_full(page)) {+ size_t bin = _mi_bin(mi_page_block_size(page));+ size_t slice_index;+ size_t slice_count;+ mi_arena_pages_t* arena_pages = NULL;+ mi_arena_t* const arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages);+ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ mi_assert_internal(page->slice_committed > 0 || mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));+ mi_assert_internal(mi_bitmap_is_clearN(arena_pages->pages_abandoned[bin], slice_index, 1));+ mi_assert_internal(mi_bitmap_is_setN(arena_pages->pages, slice_index, 1));+ // note: we cannot check for `!mi_page_is_abandoned_and_mapped` since that may+ // be (temporarily) not true if the free happens while trying to reclaim+ // see `mi_arena_try_claim_abandoned`+ }+ #endif++ // recommit guard page at the end?+ // we must do this since we may later allocate large spans over this page and cannot have a guard page in between+ #if MI_SECURE >= 2+ if (!page->memid.is_pinned) {+ _mi_os_secure_guard_page_reset_before((uint8_t*)page + mi_page_full_size(page), page->memid);+ }+ #endif++ // unregister page+ _mi_page_map_unregister(page);+ if (page->memid.memkind == MI_MEM_ARENA) {+ mi_arena_pages_t* arena_pages;+ size_t slice_index;+ size_t slice_count; MI_UNUSED(slice_count);+ mi_arena_t* const arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages);+ mi_assert_internal(arena_pages!=NULL);+ mi_bitmap_clear(arena_pages->pages, slice_index);+ if (page->slice_committed > 0) {+ // if committed on-demand, set the commit bits to account commit properly+ mi_assert_internal(mi_page_full_size(page) >= page->slice_committed);+ const size_t total_slices = page->slice_committed / MI_ARENA_SLICE_SIZE; // conservative+ //mi_assert_internal(mi_bitmap_is_clearN(arena->slices_committed, slice_index, total_slices));+ mi_assert_internal(slice_count >= total_slices);+ if (total_slices > 0) {+ mi_bitmap_setN(arena->slices_committed, slice_index, total_slices, NULL);+ }+ // any left over?+ const size_t extra = page->slice_committed % MI_ARENA_SLICE_SIZE;+ if (extra > 0) {+ // pretend it was decommitted already+ mi_subproc_stat_decrease(arena->subproc, committed, extra);+ }+ }+ else {+ mi_assert_internal(mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));+ }+ }+ _mi_arenas_free(page, mi_page_full_size(page), page->memid);+}++/* -----------------------------------------------------------+ Arena abandon+----------------------------------------------------------- */++void _mi_arenas_page_abandon(mi_page_t* page, mi_theap_t* current_theap) {+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(!mi_page_all_free(page));+ mi_assert_internal(page->next==NULL && page->prev == NULL);+ mi_assert_internal(_mi_thread_id()==current_theap->tld->thread_id);+ // mi_assert_internal(current_theap == _mi_page_associated_theap(page));++ mi_heap_t* heap = mi_page_heap(page); mi_assert_internal(heap==current_theap->heap);+ if (page->memid.memkind==MI_MEM_ARENA && !mi_page_is_full(page)) {+ // make available for allocations+ size_t bin = _mi_bin(mi_page_block_size(page));+ size_t slice_index;+ size_t slice_count;+ mi_arena_pages_t* arena_pages = NULL;+ mi_arena_t* const arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages); MI_UNUSED(arena);++ mi_assert_internal(!mi_page_is_singleton(page));+ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ mi_assert_internal(page->slice_committed > 0 || mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));+ mi_assert_internal(mi_bitmap_is_setN(arena->slices_dirty, slice_index, slice_count));++ mi_page_set_abandoned_mapped(page);+ const bool was_clear = mi_bitmap_set(arena_pages->pages_abandoned[bin], slice_index);+ MI_UNUSED(was_clear); mi_assert_internal(was_clear);+ mi_atomic_increment_relaxed(&heap->abandoned_count[bin]);+ mi_theap_stat_increase(current_theap, pages_abandoned, 1);+ }+ else {+ // page is full (or a singleton), or the page is OS/externally allocated+ // leave as is; it will be reclaimed when an object is free'd in the page+ // but for non-arena pages, add to the subproc list so these can be visited+ if (page->memid.memkind != MI_MEM_ARENA && mi_option_is_enabled(mi_option_visit_abandoned)) {+ mi_lock(&heap->os_abandoned_pages_lock) {+ // push in front+ page->prev = NULL;+ page->next = heap->os_abandoned_pages;+ if (page->next != NULL) { page->next->prev = page; }+ heap->os_abandoned_pages = page;+ }+ }+ mi_theap_stat_increase(current_theap, pages_abandoned, 1);+ }+ mi_abandoned_page_unown(page, current_theap);+}+++// this is called from `free.c:mi_free_try_collect_mt` only.+bool _mi_arenas_page_try_reabandon_to_mapped(mi_page_t* page) {+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(!mi_page_is_abandoned_mapped(page));+ mi_assert_internal(!mi_page_is_full(page));+ mi_assert_internal(!mi_page_all_free(page));+ mi_assert_internal(!mi_page_is_singleton(page));+ if (mi_page_is_full(page) || mi_page_is_abandoned_mapped(page) || page->memid.memkind != MI_MEM_ARENA) {+ return false;+ }+ else {+ // do not use _mi_heap_theap as we may call this during shutdown of threads and don't want to reinitialize the theap+ mi_theap_t* const theap = _mi_page_associated_theap_peek(page);+ if (theap == NULL) {+ return false;+ }+ else {+ mi_theap_stat_counter_increase(theap, pages_reabandon_full, 1);+ mi_theap_stat_adjust_decrease(theap, pages_abandoned, 1); // adjust as we are not abandoning fresh+ _mi_arenas_page_abandon(page, theap);+ return true;+ }+ }+}++// called from `mi_free` if trying to unabandon an abandoned page+void _mi_arenas_page_unabandon(mi_page_t* page, mi_theap_t* current_theapx) {+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(current_theapx==NULL || _mi_thread_id()==current_theapx->tld->thread_id);++ mi_heap_t* const heap = mi_page_heap(page);+ if (mi_page_is_abandoned_mapped(page)) {+ mi_assert_internal(page->memid.memkind==MI_MEM_ARENA);+ // remove from the abandoned map+ size_t bin = _mi_bin(mi_page_block_size(page));+ size_t slice_index;+ size_t slice_count;+ mi_arena_pages_t* arena_pages;+ mi_arena_t* arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages); MI_UNUSED(arena);++ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ mi_assert_internal(page->slice_committed > 0 || mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count));++ // this busy waits until a concurrent reader (from alloc_abandoned) is done+ mi_bitmap_clear_once_set(arena_pages->pages_abandoned[bin], slice_index);+ mi_page_clear_abandoned_mapped(page);+ mi_atomic_decrement_relaxed(&heap->abandoned_count[bin]);+ }+ else {+ // page is full (or a singleton), page is OS allocated+ // if not an arena page, remove from the subproc os pages list+ if (page->memid.memkind != MI_MEM_ARENA && mi_option_is_enabled(mi_option_visit_abandoned)) {+ mi_lock(&heap->os_abandoned_pages_lock) {+ if (page->prev != NULL) { page->prev->next = page->next; }+ if (page->next != NULL) { page->next->prev = page->prev; }+ if (heap->os_abandoned_pages == page) { heap->os_abandoned_pages = page->next; }+ page->next = NULL;+ page->prev = NULL;+ }+ }+ }+ if (current_theapx!=NULL) {+ mi_theap_stat_decrease(current_theapx, pages_abandoned, 1);+ }+ else {+ mi_heap_stat_decrease(heap, pages_abandoned, 1);+ }+}+++/* -----------------------------------------------------------+ Arena free+----------------------------------------------------------- */+static void mi_arena_schedule_purge(mi_arena_t* arena, size_t slice_index, size_t slices);+static void mi_arenas_try_purge(bool force, bool visit_all, mi_subproc_t* subproc, size_t tseq);++void _mi_arenas_free(void* p, size_t size, mi_memid_t memid) {+ if (p==NULL) return;+ if (size==0) return;++ // need to set all memory to undefined as some parts may still be marked as no_access (like padding etc.)+ mi_track_mem_undefined(p, size);if (mi_memkind_is_os(memid.memkind)) {// was a direct OS allocation, pass through- if (!all_committed && committed_size > 0) {- // if partially committed, adjust the committed stats (as `_mi_os_free` will increase decommit by the full size)- _mi_stat_decrease(&_mi_stats_main.committed, committed_size);- }_mi_os_free(p, size, memid);}else if (memid.memkind == MI_MEM_ARENA) {// allocated in an arena- size_t arena_idx;- size_t bitmap_idx;- mi_arena_memid_indices(memid, &arena_idx, &bitmap_idx);- mi_assert_internal(arena_idx < MI_MAX_ARENAS);- mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t,&mi_arenas[arena_idx]);- mi_assert_internal(arena != NULL);- const size_t blocks = mi_block_count_of_size(size);-+ size_t slice_count;+ size_t slice_index;+ mi_arena_t* arena = mi_arena_from_memid(memid, &slice_index, &slice_count);+ mi_assert_internal((size%MI_ARENA_SLICE_SIZE)==0);+ mi_assert_internal((slice_count*MI_ARENA_SLICE_SIZE)==size);+ mi_assert_internal(mi_arena_slice_start(arena,slice_index) <= (uint8_t*)p);+ mi_assert_internal(mi_arena_slice_start(arena,slice_index) + mi_size_of_slices(slice_count) > (uint8_t*)p);// checksif (arena == NULL) {_mi_error_message(EINVAL, "trying to free from an invalid arena: %p, size %zu, memid: 0x%zx\n", p, size, memid);return;}- mi_assert_internal(arena->field_count > mi_bitmap_index_field(bitmap_idx));- if (arena->field_count <= mi_bitmap_index_field(bitmap_idx)) {+ mi_assert_internal(slice_index < arena->slice_count);+ mi_assert_internal(slice_index >= mi_arena_info_slices(arena));+ if (slice_index < mi_arena_info_slices(arena) || slice_index > arena->slice_count) {_mi_error_message(EINVAL, "trying to free from an invalid arena block: %p, size %zu, memid: 0x%zx\n", p, size, memid);return;}// potentially decommit- if (arena->memid.is_pinned || arena->blocks_committed == NULL) {- mi_assert_internal(all_committed);- }- else {- mi_assert_internal(arena->blocks_committed != NULL);- mi_assert_internal(arena->blocks_purge != NULL);-- if (!all_committed) {- // mark the entire range as no longer committed (so we recommit the full range when re-using)- _mi_bitmap_unclaim_across(arena->blocks_committed, arena->field_count, blocks, bitmap_idx);- mi_track_mem_noaccess(p,size);- if (committed_size > 0) {- // if partially committed, adjust the committed stats (is it will be recommitted when re-using)- // in the delayed purge, we now need to not count a decommit if the range is not marked as committed.- _mi_stat_decrease(&_mi_stats_main.committed, committed_size);- }- // note: if not all committed, it may be that the purge will reset/decommit the entire range- // that contains already decommitted parts. Since purge consistently uses reset or decommit that- // works (as we should never reset decommitted parts).- }- // (delay) purge the entire range- mi_arena_schedule_purge(arena, bitmap_idx, blocks);+ if (!arena->memid.is_pinned /* && !arena->memid.initially_committed */) { // todo: allow decommit even if initially committed?+ // (delay) purge the page+ mi_arena_schedule_purge(arena, slice_index, slice_count);}// and make it available to others again- bool all_inuse = _mi_bitmap_unclaim_across(arena->blocks_inuse, arena->field_count, blocks, bitmap_idx);+ bool all_inuse = mi_bbitmap_setN(arena->slices_free, slice_index, slice_count);if (!all_inuse) {- _mi_error_message(EAGAIN, "trying to free an already freed arena block: %p, size %zu\n", p, size);+ _mi_error_message(EAGAIN, "trying to free an already freed arena block: %p, size %zu\n", mi_arena_slice_start(arena,slice_index), mi_size_of_slices(slice_count));return;};}+ else if (memid.memkind == MI_MEM_META) {+ _mi_meta_free(p, size, memid);+ }else {// arena was none, external, or static; nothing to do- mi_assert_internal(memid.memkind < MI_MEM_OS);+ mi_assert_internal(mi_memid_needs_no_free(memid));}- // purge expired decommits- mi_arenas_try_purge(false, false);+ // try to purge expired decommits+ // mi_arenas_try_purge(false, false, NULL);}+// Purge the arenas; if `force_purge` is true, amenable parts are purged even if not yet expired+void _mi_arenas_collect(bool force_purge, bool visit_all, mi_tld_t* tld) {+ mi_arenas_try_purge(force_purge, visit_all, tld->subproc, tld->thread_seq);+}+++// Is a pointer contained in the given arena area?+bool mi_arena_contains(mi_arena_id_t arena_id, const void* p) {+ mi_arena_t* arena = _mi_arena_from_id(arena_id);+ return (mi_arena_start(arena) <= (const uint8_t*)p &&+ mi_arena_start(arena) + mi_size_of_slices(arena->slice_count) >(const uint8_t*)p);+}++// Is a pointer inside any of our arenas?+bool _mi_arenas_contain(const void* p) {+ mi_subproc_t* subproc = _mi_subproc();+ const size_t max_arena = mi_arenas_get_count(subproc);+ for (size_t i = 0; i < max_arena; i++) {+ mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &subproc->arenas[i]);+ if (arena != NULL && mi_arena_contains(arena,p)) {+ return true;+ }+ }+ return false;+}++++/* -----------------------------------------------------------+ Remove an arena.+----------------------------------------------------------- */+// destroy owned arenas; this is unsafe and should only be done using `mi_option_destroy_on_exit`// for dynamic libraries that are unloaded and need to release all their allocated memory.-static void mi_arenas_unsafe_destroy(void) {- const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);- size_t new_max_arena = 0;- for (size_t i = 0; i < max_arena; i++) {- mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &mi_arenas[i]);+static void mi_arenas_unsafe_destroy(mi_subproc_t* subproc) {+ mi_assert_internal(subproc != NULL);+ const size_t arena_count = mi_arenas_get_count(subproc);+ for (size_t i = 0; i < arena_count; i++) {+ mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &subproc->arenas[i]);if (arena != NULL) {- mi_lock_done(&arena->abandoned_visit_lock);- if (arena->start != NULL && mi_memkind_is_os(arena->memid.memkind)) {- mi_atomic_store_ptr_release(mi_arena_t, &mi_arenas[i], NULL);- _mi_os_free(arena->start, mi_arena_size(arena), arena->memid);+ // mi_lock_done(&arena->abandoned_visit_lock);+ mi_atomic_store_ptr_release(mi_arena_t, &subproc->arenas[i], NULL);+ if (mi_memkind_is_os(arena->memid.memkind)) {+ _mi_os_free_ex(mi_arena_start(arena), mi_arena_size(arena), true, arena->memid, subproc); // pass `subproc` to avoid accessing the theap pointer (in `_mi_subproc()`)}- else {- new_max_arena = i;- }- _mi_arena_meta_free(arena, arena->meta_memid, arena->meta_size);}}-// try to lower the max arena.- size_t expected = max_arena;- mi_atomic_cas_strong_acq_rel(&mi_arena_count, &expected, new_max_arena);+ size_t expected = arena_count;+ mi_atomic_cas_strong_acq_rel(&subproc->arena_count, &expected, 0);}-// Purge the arenas; if `force_purge` is true, amenable parts are purged even if not yet expired-void _mi_arenas_collect(bool force_purge) {- mi_arenas_try_purge(force_purge, force_purge /* visit all? */);-}// destroy owned arenas; this is unsafe and should only be done using `mi_option_destroy_on_exit`// for dynamic libraries that are unloaded and need to release all their allocated memory.-void _mi_arena_unsafe_destroy_all(void) {- mi_arenas_unsafe_destroy();- _mi_arenas_collect(true /* force purge */); // purge non-owned arenas+void _mi_arenas_unsafe_destroy_all(mi_subproc_t* subproc) {+ mi_arenas_unsafe_destroy(subproc);+ // mi_arenas_try_purge(true /* force purge */, true /* visit all*/, subproc, 0 /* thread seq */); // purge non-owned arenas}-// Is a pointer inside any of our arenas?-bool _mi_arena_contains(const void* p) {- const size_t max_arena = mi_atomic_load_relaxed(&mi_arena_count);- for (size_t i = 0; i < max_arena; i++) {- mi_arena_t* arena = mi_atomic_load_ptr_relaxed(mi_arena_t, &mi_arenas[i]);- if (arena != NULL && arena->start <= (const uint8_t*)p && arena->start + mi_arena_block_size(arena->block_count) > (const uint8_t*)p) {- return true;- }- }- return false;-}/* -----------------------------------------------------------Add an arena.----------------------------------------------------------- */-static bool mi_arena_add(mi_arena_t* arena, mi_arena_id_t* arena_id, mi_stats_t* stats) {+static bool mi_arenas_add(mi_subproc_t* subproc, mi_arena_t* arena, mi_arena_id_t* arena_id)+{mi_assert_internal(arena != NULL);- mi_assert_internal((uintptr_t)mi_atomic_load_ptr_relaxed(uint8_t,&arena->start) % MI_SEGMENT_ALIGN == 0);- mi_assert_internal(arena->block_count > 0);- if (arena_id != NULL) { *arena_id = -1; }+ mi_assert_internal(arena->slice_count > 0);+ if (arena_id != NULL) { *arena_id = NULL; }++ // try to find a NULL entry+ mi_arena_t* expected;+ size_t count = mi_arenas_get_count(subproc);+ for( size_t i = 0; i < count; i++) {+ if (mi_arena_from_index(subproc,i) == NULL) {+ arena->arena_idx = i;+ expected = NULL;+ if (mi_atomic_cas_ptr_strong_release(mi_arena_t, &subproc->arenas[i], &expected, arena)) {+ // success+ if (arena_id != NULL) { *arena_id = arena; }+ return true;+ }+ }+ }- size_t i = mi_atomic_increment_acq_rel(&mi_arena_count);- if (i >= MI_MAX_ARENAS) {- mi_atomic_decrement_acq_rel(&mi_arena_count);- return false;+ // otherwise, try to allocate a fresh slot+ while(count<MI_MAX_ARENAS) {+ if (mi_atomic_cas_strong_release(&subproc->arena_count, &count, count+1)) {+ arena->arena_idx = count;+ expected = NULL;+ if (mi_atomic_cas_ptr_strong_release(mi_arena_t, &subproc->arenas[count], &expected, arena)) {+ mi_subproc_stat_counter_increase(arena->subproc, arena_count, 1);+ if (arena_id != NULL) { *arena_id = arena; }+ return true;+ }+ }}- _mi_stat_counter_increase(&stats->arena_count,1);- arena->id = mi_arena_id_create(i);- mi_atomic_store_ptr_release(mi_arena_t,&mi_arenas[i], arena);- if (arena_id != NULL) { *arena_id = arena->id; }- return true;++ // failed+ arena->arena_idx = 0;+ arena->subproc = NULL;+ return false;}-static bool mi_manage_os_memory_ex2(void* start, size_t size, bool is_large, int numa_node, bool exclusive, mi_memid_t memid, mi_arena_id_t* arena_id) mi_attr_noexcept-{- if (arena_id != NULL) *arena_id = _mi_arena_id_none();- if (size < MI_ARENA_BLOCK_SIZE) {- _mi_warning_message("the arena size is too small (memory at %p with size %zu)\n", start, size);- return false;- }- if (is_large) {- mi_assert_internal(memid.initially_committed && memid.is_pinned);+static size_t mi_arena_pages_size(size_t slice_count, size_t* bitmap_base) {+ if (slice_count == 0) slice_count = MI_BCHUNK_BITS;+ mi_assert_internal((slice_count % MI_BCHUNK_BITS) == 0);+ const size_t base_size = _mi_align_up(sizeof(mi_arena_pages_t), MI_BCHUNK_SIZE);+ const size_t bitmaps_count = 1 + MI_ARENA_BIN_COUNT; // pages, and abandoned+ const size_t bitmaps_size = bitmaps_count * mi_bitmap_size(slice_count, NULL);+ const size_t size = base_size + bitmaps_size;+ if (bitmap_base != NULL) *bitmap_base = base_size;+ return size;+}++static size_t mi_arena_info_slices_needed(size_t slice_count, size_t* bitmap_base) {+ if (slice_count == 0) slice_count = MI_BCHUNK_BITS;+ mi_assert_internal((slice_count % MI_BCHUNK_BITS) == 0);+ const size_t base_size = _mi_align_up(sizeof(mi_arena_t), MI_BCHUNK_SIZE);+ const size_t bitmaps_count = 4 + MI_ARENA_BIN_COUNT; // commit, dirty, purge, pages, and abandoned+ const size_t bitmaps_size = bitmaps_count * mi_bitmap_size(slice_count, NULL) + mi_bbitmap_size(slice_count, NULL); // + free+ const size_t size = base_size + bitmaps_size;++ const size_t os_page_size = _mi_os_page_size();+ const size_t info_size = _mi_align_up(size, os_page_size) + _mi_os_secure_guard_page_size();+ const size_t info_slices = mi_slice_count_of_size(info_size);++ if (bitmap_base != NULL) *bitmap_base = base_size;+ return info_slices;+}++static mi_bitmap_t* mi_arena_bitmap_init(size_t slice_count, uint8_t** base) {+ mi_bitmap_t* bitmap = (mi_bitmap_t*)(*base);+ *base = (*base) + mi_bitmap_init(bitmap, slice_count, true /* already zero */);+ return bitmap;+}++static mi_bbitmap_t* mi_arena_bbitmap_init(size_t slice_count, uint8_t** base) {+ mi_bbitmap_t* bbitmap = (mi_bbitmap_t*)(*base);+ *base = (*base) + mi_bbitmap_init(bbitmap, slice_count, true /* already zero */);+ return bbitmap;+}++static mi_arena_pages_t* mi_arena_pages_alloc(mi_arena_t* arena) {+ const size_t slice_count = arena->slice_count;+ size_t bitmap_base = 0;+ const size_t size = mi_arena_pages_size(slice_count, &bitmap_base);+ mi_arena_pages_t* arena_pages = (mi_arena_pages_t*)mi_heap_zalloc_aligned(mi_heap_main(), size, MI_BCHUNK_SIZE);+ if (arena_pages==NULL) return NULL;+ uint8_t* base = (uint8_t*)arena_pages + bitmap_base;+ mi_assert_internal(_mi_is_aligned(base, MI_BCHUNK_SIZE));+ arena_pages->pages = mi_arena_bitmap_init(slice_count, &base);+ for (size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {+ arena_pages->pages_abandoned[i] = mi_arena_bitmap_init(slice_count, &base);}- if (!_mi_is_aligned(start, MI_SEGMENT_ALIGN)) {- void* const aligned_start = mi_align_up_ptr(start, MI_SEGMENT_ALIGN);+ return arena_pages;+}+++static bool mi_manage_os_memory_ex2(mi_subproc_t* subproc, void* start, size_t size, int numa_node, bool exclusive,+ mi_memid_t memid, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept+{+ mi_assert(_mi_is_aligned(start,MI_ARENA_SLICE_SIZE));+ mi_assert(start!=NULL);+ if (arena_id != NULL) { *arena_id = _mi_arena_id_none(); }+ if (start==NULL) return false;+ if (!_mi_is_aligned(start,MI_ARENA_SLICE_SIZE)) {+ // we can align the start since the memid tracks the real base of the memory.+ void* const aligned_start = _mi_align_up_ptr(start, MI_ARENA_SLICE_SIZE);const size_t diff = (uint8_t*)aligned_start - (uint8_t*)start;- if (diff >= size || (size - diff) < MI_ARENA_BLOCK_SIZE) {+ if (diff >= size || (size - diff) < MI_ARENA_SLICE_SIZE) {_mi_warning_message("after alignment, the size of the arena becomes too small (memory at %p with size %zu)\n", start, size);return false;}@@ -817,76 +1392,138 @@ static bool mi_manage_os_memory_ex2(void* start, size_t size, bool is_large, intsize = size - diff;}- const size_t bcount = size / MI_ARENA_BLOCK_SIZE;- const size_t fields = _mi_divide_up(bcount, MI_BITMAP_FIELD_BITS);- const size_t bitmaps = (memid.is_pinned ? 3 : 5);- const size_t asize = sizeof(mi_arena_t) + (bitmaps*fields*sizeof(mi_bitmap_field_t));- mi_memid_t meta_memid;- mi_arena_t* arena = (mi_arena_t*)_mi_arena_meta_zalloc(asize, &meta_memid);- if (arena == NULL) return false;-- // already zero'd due to zalloc- // _mi_memzero(arena, asize);- arena->id = _mi_arena_id_none();- arena->memid = memid;- arena->exclusive = exclusive;- arena->meta_size = asize;- arena->meta_memid = meta_memid;- arena->block_count = bcount;- arena->field_count = fields;- arena->start = (uint8_t*)start;+ const size_t slice_count = _mi_align_down(size / MI_ARENA_SLICE_SIZE, MI_BCHUNK_BITS);+ if (slice_count > MI_BITMAP_MAX_BIT_COUNT) { // 16 GiB for now+ // todo: allow larger areas (either by splitting it up in arena's or having larger arena's)+ _mi_warning_message("cannot use OS memory since it is too large (size %zu MiB, maximum is %zu MiB)", size/MI_MiB, mi_size_of_slices(MI_BITMAP_MAX_BIT_COUNT)/MI_MiB);+ return false;+ }+ size_t bitmap_base;+ const size_t info_slices = mi_arena_info_slices_needed(slice_count, &bitmap_base);+ if (slice_count < info_slices+1) {+ _mi_warning_message("cannot use OS memory since it is not large enough (size %zu KiB, minimum required is %zu KiB)", size/MI_KiB, mi_size_of_slices(info_slices+1)/MI_KiB);+ return false;+ }+ else if (info_slices >= MI_ARENA_MAX_CHUNK_OBJ_SLICES) {+ _mi_warning_message("cannot use OS memory since it is too large with respect to the maximum object size (size %zu MiB, meta-info slices %zu, maximum object slices are %zu)", size/MI_MiB, info_slices, MI_ARENA_MAX_CHUNK_OBJ_SLICES);+ return false;+ }++ mi_arena_t* arena = (mi_arena_t*)start;++ // commit & zero if needed+ if (!memid.initially_committed) {+ size_t commit_size = mi_size_of_slices(info_slices);+ // leave a guard OS page decommitted at the end?+ if (!memid.is_pinned) { commit_size -= _mi_os_secure_guard_page_size(); }+ bool ok = false;+ if (commit_fun != NULL) {+ ok = (*commit_fun)(true /* commit */, arena, commit_size, NULL, commit_fun_arg);+ }+ else {+ ok = _mi_os_commit(arena, commit_size, NULL);+ }+ if (!ok) {+ _mi_warning_message("unable to commit meta-data for OS memory");+ return false;+ }+ }+ else if (!memid.is_pinned) {+ // if MI_SECURE, set a guard page at the end+ // todo: this does not respect the commit_fun as the memid is of external memory+ _mi_os_secure_guard_page_set_before((uint8_t*)arena + mi_size_of_slices(info_slices), memid);+ }+ if (!memid.initially_zero) {+ _mi_memzero(arena, mi_size_of_slices(info_slices) - _mi_os_secure_guard_page_size());+ }++ // init+ arena->subproc = subproc;+ arena->memid = memid;+ arena->is_exclusive = exclusive;+ arena->slice_count = slice_count;+ arena->info_slices = info_slices;arena->numa_node = numa_node; // TODO: or get the current numa node if -1? (now it allows anyone to allocate on -1)- arena->is_large = is_large;arena->purge_expire = 0;- arena->search_idx = 0;- mi_lock_init(&arena->abandoned_visit_lock);- // consecutive bitmaps- arena->blocks_dirty = &arena->blocks_inuse[fields]; // just after inuse bitmap- arena->blocks_abandoned = &arena->blocks_inuse[2 * fields]; // just after dirty bitmap- arena->blocks_committed = (arena->memid.is_pinned ? NULL : &arena->blocks_inuse[3*fields]); // just after abandoned bitmap- arena->blocks_purge = (arena->memid.is_pinned ? NULL : &arena->blocks_inuse[4*fields]); // just after committed bitmap- // initialize committed bitmap?- if (arena->blocks_committed != NULL && arena->memid.initially_committed) {- memset((void*)arena->blocks_committed, 0xFF, fields*sizeof(mi_bitmap_field_t)); // cast to void* to avoid atomic warning+ arena->commit_fun = commit_fun;+ arena->commit_fun_arg = commit_fun_arg;+ // mi_lock_init(&arena->abandoned_visit_lock);++ // init bitmaps+ uint8_t* base = mi_arena_start(arena) + bitmap_base;+ arena->slices_free = mi_arena_bbitmap_init(slice_count,&base);+ arena->slices_committed = mi_arena_bitmap_init(slice_count,&base);+ arena->slices_dirty = mi_arena_bitmap_init(slice_count,&base);+ arena->slices_purge = mi_arena_bitmap_init(slice_count, &base);+ arena->pages_main.pages = mi_arena_bitmap_init(slice_count, &base);+ for( size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {+ arena->pages_main.pages_abandoned[i] = mi_arena_bitmap_init(slice_count,&base);}+ mi_assert_internal(mi_size_of_slices(info_slices) >= (size_t)(base - mi_arena_start(arena)));- // and claim leftover blocks if needed (so we never allocate there)- ptrdiff_t post = (fields * MI_BITMAP_FIELD_BITS) - bcount;- mi_assert_internal(post >= 0);- if (post > 0) {- // don't use leftover bits at the end- mi_bitmap_index_t postidx = mi_bitmap_index_create(fields - 1, MI_BITMAP_FIELD_BITS - post);- _mi_bitmap_claim(arena->blocks_inuse, fields, post, postidx, NULL);+ // reserve our meta info (and reserve slices outside the memory area)+ mi_bbitmap_unsafe_setN(arena->slices_free, info_slices /* start */, arena->slice_count - info_slices);+ if (memid.initially_committed) {+ mi_bitmap_unsafe_setN(arena->slices_committed, 0, arena->slice_count);+ }+ else {+ mi_bitmap_setN(arena->slices_committed, 0, info_slices, NULL);+ }+ if (!memid.initially_zero) {+ mi_bitmap_unsafe_setN(arena->slices_dirty, 0, arena->slice_count);}- return mi_arena_add(arena, arena_id, &_mi_stats_main);+ else {+ mi_bitmap_setN(arena->slices_dirty, 0, info_slices, NULL);+ }++ return mi_arenas_add(subproc, arena, arena_id);+}++bool mi_manage_os_memory_ex(void* start, size_t size, bool is_committed, bool is_pinned, bool is_zero, int numa_node, bool exclusive, mi_arena_id_t* arena_id) mi_attr_noexcept {+ mi_memid_t memid = _mi_memid_create(MI_MEM_EXTERNAL);+ memid.mem.os.base = start;+ memid.mem.os.size = size;+ memid.initially_committed = is_committed;+ memid.initially_zero = is_zero;+ memid.is_pinned = is_pinned;+ return mi_manage_os_memory_ex2(_mi_subproc(), start, size, numa_node, exclusive, memid, NULL, NULL, arena_id);}-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 {+bool mi_manage_memory(void* start, size_t size, bool is_committed, bool is_zero, bool is_pinned, int numa_node, bool exclusive, mi_commit_fun_t* commit_fun, void* commit_fun_arg, mi_arena_id_t* arena_id) mi_attr_noexcept+{mi_memid_t memid = _mi_memid_create(MI_MEM_EXTERNAL);+ memid.mem.os.base = start;+ memid.mem.os.size = size;memid.initially_committed = is_committed;memid.initially_zero = is_zero;- memid.is_pinned = is_large;- return mi_manage_os_memory_ex2(start,size,is_large,numa_node,exclusive,memid, arena_id);+ memid.is_pinned = is_pinned;+ return mi_manage_os_memory_ex2(_mi_subproc(), start, size, numa_node, exclusive, memid, commit_fun, commit_fun_arg, arena_id);}+// Reserve a range of regular OS memory-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 {+static int mi_reserve_os_memory_ex2(mi_subproc_t* subproc, size_t size, bool commit, bool allow_large, bool exclusive, mi_arena_id_t* arena_id) {if (arena_id != NULL) *arena_id = _mi_arena_id_none();- size = _mi_align_up(size, MI_ARENA_BLOCK_SIZE); // at least one block+ size = _mi_align_up(size, MI_ARENA_SLICE_SIZE); // at least one slicemi_memid_t memid;- void* start = _mi_os_alloc_aligned(size, MI_SEGMENT_ALIGN, commit, allow_large, &memid);+ void* start = _mi_os_alloc_aligned(size, MI_ARENA_SLICE_ALIGN, commit, allow_large, &memid);if (start == NULL) return ENOMEM;- const bool is_large = memid.is_pinned; // todo: use separate is_large field?- if (!mi_manage_os_memory_ex2(start, size, is_large, -1 /* numa node */, exclusive, memid, arena_id)) {- _mi_os_free_ex(start, size, commit, memid);+ if (!mi_manage_os_memory_ex2(subproc, start, size, -1 /* numa node */, exclusive, memid, NULL, NULL, arena_id)) {+ _mi_os_free_ex(start, size, commit, memid, NULL);_mi_verbose_message("failed to reserve %zu KiB memory\n", _mi_divide_up(size, 1024));return ENOMEM;}- _mi_verbose_message("reserved %zu KiB memory%s\n", _mi_divide_up(size, 1024), is_large ? " (in large os pages)" : "");+ _mi_verbose_message("reserved %zu KiB memory%s\n", _mi_divide_up(size, 1024), memid.is_pinned ? " (in large os pages)" : "");+ // mi_debug_show_arenas(true, true, false);+return 0;}+// Reserve a range of regular OS memory+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 {+ return mi_reserve_os_memory_ex2(_mi_subproc(), size, commit, allow_large, exclusive, arena_id);+}// Manage a range of regular OS memorybool mi_manage_os_memory(void* start, size_t size, bool is_committed, bool is_large, bool is_zero, int numa_node) mi_attr_noexcept {@@ -903,55 +1540,232 @@ int mi_reserve_os_memory(size_t size, bool commit, bool allow_large) mi_attr_noeDebugging----------------------------------------------------------- */-static size_t mi_debug_show_bitmap(const char* prefix, const char* header, size_t block_count, mi_bitmap_field_t* fields, size_t field_count ) {- _mi_verbose_message("%s%s:\n", prefix, header);- size_t bcount = 0;- size_t inuse_count = 0;- for (size_t i = 0; i < field_count; i++) {- char buf[MI_BITMAP_FIELD_BITS + 1];- uintptr_t field = mi_atomic_load_relaxed(&fields[i]);- for (size_t bit = 0; bit < MI_BITMAP_FIELD_BITS; bit++, bcount++) {- if (bcount < block_count) {- bool inuse = ((((uintptr_t)1 << bit) & field) != 0);- if (inuse) inuse_count++;- buf[bit] = (inuse ? 'x' : '.');+// Return idx of the slice past the last used slice+static size_t mi_arena_used_slices(mi_arena_t* arena) {+ size_t idx;+ if (mi_bitmap_bsr(arena->slices_dirty, &idx)) {+ return (idx + 1);+ }+ else {+ return mi_arena_info_slices(arena);+ }+}++static size_t mi_debug_show_bfield(mi_bfield_t field, char* buf, size_t* k) {+ size_t bit_set_count = 0;+ for (int bit = 0; bit < MI_BFIELD_BITS; bit++) {+ bool is_set = ((((mi_bfield_t)1 << bit) & field) != 0);+ if (is_set) bit_set_count++;+ buf[*k] = (is_set ? 'x' : '.');+ *k = *k + 1;+ }+ return bit_set_count;+}++typedef enum mi_ansi_color_e {+ MI_BLACK = 30,+ MI_MAROON,+ MI_DARKGREEN,+ MI_ORANGE,+ MI_NAVY,+ MI_PURPLE,+ MI_TEAL,+ MI_GRAY,+ MI_DARKGRAY = 90,+ MI_RED,+ MI_GREEN,+ MI_YELLOW,+ MI_BLUE,+ MI_MAGENTA,+ MI_CYAN,+ MI_WHITE+} mi_ansi_color_t;++static void mi_debug_color(char* buf, size_t* k, mi_ansi_color_t color) {+ *k += _mi_snprintf(buf + *k, 32, "\x1B[%dm", (int)color);+}++static int mi_page_commit_usage(mi_page_t* page) {+ // if (mi_page_size(page) <= MI_PAGE_MIN_COMMIT_SIZE) return 100;+ const size_t committed_size = mi_page_committed(page);+ const size_t used_size = page->used * mi_page_block_size(page);+ return (int)(used_size * 100 / committed_size);+}++static size_t mi_debug_show_page_bfield(char* buf, size_t* k, mi_arena_t* arena, size_t slice_index, long* pbit_of_page, mi_ansi_color_t* pcolor_of_page ) {+ size_t bit_set_count = 0;+ long bit_of_page = *pbit_of_page;+ mi_ansi_color_t color = *pcolor_of_page;+ mi_ansi_color_t prev_color = MI_GRAY;+ for (int bit = 0; bit < MI_BFIELD_BITS; bit++, bit_of_page--) {+ // bool is_set = ((((mi_bfield_t)1 << bit) & field) != 0);+ void* start = mi_arena_slice_start(arena, slice_index + bit);+ mi_page_t* page = _mi_safe_ptr_page(start);+ char c = ' ';+ if (start==page) {+ mi_assert_internal(bit_of_page <= 0);+ bit_set_count++;+ c = 'p';+ color = MI_GRAY;+ if (mi_page_is_singleton(page)) { c = 's'; }+ else if (mi_page_is_full(page)) { c = 'f'; }+ if (!mi_page_is_abandoned(page)) { c = _mi_toupper(c); }+ int commit_usage = mi_page_commit_usage(page);+ if (commit_usage < 25) { color = MI_MAROON; }+ else if (commit_usage < 50) { color = MI_ORANGE; }+ else if (commit_usage < 75) { color = MI_TEAL; }+ else color = MI_DARKGREEN;+ bit_of_page = (long)page->memid.mem.arena.slice_count;+ }+ else {+ c = '?';+ if (bit_of_page > 0) { c = '-'; }+ else if (_mi_meta_is_meta_page(start)) { c = 'm'; color = MI_GRAY; }+ else if (slice_index + bit < arena->info_slices) { c = 'i'; color = MI_GRAY; }+ // else if (mi_bitmap_is_setN(arena->pages_purge, slice_index + bit, NULL)) { c = '*'; }+ else if (mi_bbitmap_is_setN(arena->slices_free, slice_index+bit,1)) {+ if (mi_bitmap_is_set(arena->slices_purge, slice_index + bit)) { c = '~'; color = MI_ORANGE; }+ else if (mi_bitmap_is_setN(arena->slices_committed, slice_index + bit, 1)) { c = '_'; color = MI_GRAY; }+ else { c = '.'; color = MI_GRAY; }+ }+ if (bit==MI_BFIELD_BITS-1 && bit_of_page > 1) { c = '>'; }+ }+ if (color != prev_color) {+ mi_debug_color(buf, k, color);+ prev_color = color;+ }+ buf[*k] = c; *k += 1;+ }+ mi_debug_color(buf, k, MI_GRAY);+ *pbit_of_page = bit_of_page;+ *pcolor_of_page = color;+ return bit_set_count;+}++static size_t mi_debug_show_chunks(const char* header1, const char* header2, const char* header3,+ size_t slice_count, size_t chunk_count,+ mi_bchunk_t* chunks, mi_bchunkmap_t* chunk_bins, bool invert, mi_arena_t* arena, bool narrow)+{+ _mi_raw_message("\x1B[37m%s%s%s (use/commit: \x1B[31m0 - 25%%\x1B[33m - 50%%\x1B[36m - 75%%\x1B[32m - 100%%\x1B[0m)\n", header1, header2, header3);+ const size_t fields_per_line = (narrow ? 2 : 4);+ const size_t used_slice_count = mi_arena_used_slices(arena);+ size_t bit_count = 0;+ size_t bit_set_count = 0;+ long bit_of_page = 0;+ mi_ansi_color_t color_of_page = MI_GRAY;+ for (size_t i = 0; i < chunk_count && bit_count < slice_count; i++) {+ char buf[5*MI_BCHUNK_BITS + 64]; _mi_memzero(buf, sizeof(buf));+ if (bit_count > used_slice_count && i+2 < chunk_count) {+ const size_t diff = chunk_count - 1 - i;+ bit_count += diff*MI_BCHUNK_BITS;+ _mi_raw_message(" |\n");+ i = chunk_count-1;+ }++ size_t k = 0;++ if (i<10) { buf[k++] = ('0' + (char)i); buf[k++] = ' '; buf[k++] = ' '; }+ else if (i<100) { buf[k++] = ('0' + (char)(i/10)); buf[k++] = ('0' + (char)(i%10)); buf[k++] = ' '; }+ else if (i<1000) { buf[k++] = ('0' + (char)(i/100)); buf[k++] = ('0' + (char)((i%100)/10)); buf[k++] = ('0' + (char)(i%10)); }++ char chunk_kind = ' ';+ if (chunk_bins != NULL) {+ switch (mi_bbitmap_debug_get_bin(chunk_bins,i)) {+ case MI_CBIN_SMALL: chunk_kind = 'S'; break;+ case MI_CBIN_MEDIUM: chunk_kind = 'M'; break;+ case MI_CBIN_LARGE: chunk_kind = 'L'; break;+ case MI_CBIN_HUGE: chunk_kind = 'H'; break;+ case MI_CBIN_OTHER: chunk_kind = 'X'; break;+ default: chunk_kind = ' '; break; // suppress warning+ // case MI_CBIN_NONE: chunk_kind = 'N'; break;+ }+ }+ buf[k++] = chunk_kind;+ buf[k++] = ' ';++ for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {+ if (j > 0 && (j % fields_per_line) == 0) {+ // buf[k++] = '\n'; _mi_memset(buf+k,' ',7); k += 7;+ _mi_raw_message(" %s\n\x1B[37m", buf);+ _mi_memzero(buf, sizeof(buf));+ _mi_memset(buf, ' ', 5); k = 5;+ }+ if (bit_count < slice_count) {+ mi_bfield_t bfield = 0;+ if (chunks!=NULL) {+ bfield = chunks[i].bfields[j];+ }+ if (invert) bfield = ~bfield;+ size_t xcount = (chunks==NULL ? mi_debug_show_page_bfield(buf, &k, arena, bit_count, &bit_of_page, &color_of_page)+ : mi_debug_show_bfield(bfield, buf, &k));+ if (invert) xcount = MI_BFIELD_BITS - xcount;+ bit_set_count += xcount;+ buf[k++] = ' ';}else {- buf[bit] = ' ';+ _mi_memset(buf + k, 'o', MI_BFIELD_BITS);+ k += MI_BFIELD_BITS;}+ bit_count += MI_BFIELD_BITS;}- buf[MI_BITMAP_FIELD_BITS] = 0;- _mi_verbose_message("%s %s\n", prefix, buf);+ _mi_raw_message(" %s\n\x1B[37m", buf);}- _mi_verbose_message("%s total ('x'): %zu\n", prefix, inuse_count);- return inuse_count;+ _mi_raw_message("\x1B[0m total pages: %zu\n", bit_set_count);+ return bit_set_count;}-void mi_debug_show_arenas(bool show_inuse) mi_attr_noexcept {- size_t max_arenas = mi_atomic_load_relaxed(&mi_arena_count);- size_t inuse_total = 0;+//static size_t mi_debug_show_bitmap_binned(const char* header1, const char* header2, const char* header3, size_t slice_count,+// mi_bitmap_t* bitmap, mi_bchunkmap_t* chunk_bins, bool invert, mi_arena_t* arena, bool narrow) {+// return mi_debug_show_chunks(header1, header2, header3, slice_count, mi_bitmap_chunk_count(bitmap), &bitmap->chunks[0], chunk_bins, invert, arena, narrow);+//}++static void mi_debug_show_arenas_ex(mi_heap_t* heap, bool show_pages, bool narrow) mi_attr_noexcept {+ mi_subproc_t* subproc = heap->subproc;+ size_t max_arenas = mi_arenas_get_count(subproc);+ //size_t free_total = 0;+ //size_t slice_total = 0;//size_t abandoned_total = 0;- //size_t purge_total = 0;+ size_t page_total = 0;for (size_t i = 0; i < max_arenas; i++) {- mi_arena_t* arena = mi_atomic_load_ptr_relaxed(mi_arena_t, &mi_arenas[i]);+ mi_arena_t* arena = mi_atomic_load_ptr_acquire(mi_arena_t, &subproc->arenas[i]);if (arena == NULL) break;- _mi_verbose_message("arena %zu: %zu blocks of size %zuMiB (in %zu fields) %s\n", i, arena->block_count, MI_ARENA_BLOCK_SIZE / MI_MiB, arena->field_count, (arena->memid.is_pinned ? ", pinned" : ""));- if (show_inuse) {- inuse_total += mi_debug_show_bitmap(" ", "inuse blocks", arena->block_count, arena->blocks_inuse, arena->field_count);- }- if (arena->blocks_committed != NULL) {- mi_debug_show_bitmap(" ", "committed blocks", arena->block_count, arena->blocks_committed, arena->field_count);- }- //if (show_abandoned) {- // abandoned_total += mi_debug_show_bitmap(" ", "abandoned blocks", arena->block_count, arena->blocks_abandoned, arena->field_count);+ mi_assert(arena->subproc == subproc);+ // slice_total += arena->slice_count;+ _mi_raw_message("arena %zu at %p: %zu slices (%zu MiB)%s, subproc: %p\n", i, arena, arena->slice_count, (size_t)(mi_size_of_slices(arena->slice_count)/MI_MiB), (arena->memid.is_pinned ? ", pinned" : ""), arena->subproc);+ //if (show_inuse) {+ // free_total += mi_debug_show_bbitmap("in-use slices", arena->slice_count, arena->slices_free, true, NULL);//}- //if (show_purge && arena->blocks_purge != NULL) {- // purge_total += mi_debug_show_bitmap(" ", "purgeable blocks", arena->block_count, arena->blocks_purge, arena->field_count);+ //if (show_committed) {+ // mi_debug_show_bitmap("committed slices", arena->slice_count, arena->slices_committed, false, NULL);//}+ // todo: abandoned slices+ //if (show_purge) {+ // purge_total += mi_debug_show_bitmap("purgeable slices", arena->slice_count, arena->slices_purge, false, NULL);+ //}+ if (show_pages) {+ // mi_arena_pages_t* arena_pages = mi_heap_arena_pages(heap, arena);+ // if (arena_pages != NULL)+ {+ const char* header1 = "chunks (p:page, f:full, s:singleton, P,F,S:not abandoned, i:arena-info, m:meta-data, ~:free-purgable, _:free-committed, .:free-reserved)";+ const char* header2 = (narrow ? "\n " : " ");+ const char* header3 = "(chunk bin: S:small, M : medium, L : large, X : other)";+ page_total += mi_debug_show_chunks(header1, header2, header3, arena->slice_count,+ mi_bbitmap_chunk_count(arena->slices_free), NULL,+ arena->slices_free->chunkmap_bins, false, arena, narrow);+ }+ }}- if (show_inuse) _mi_verbose_message("total inuse blocks : %zu\n", inuse_total);- //if (show_abandoned) _mi_verbose_message("total abandoned blocks: %zu\n", abandoned_total);- //if (show_purge) _mi_verbose_message("total purgeable blocks: %zu\n", purge_total);+ // if (show_inuse) _mi_raw_message("total inuse slices : %zu\n", slice_total - free_total);+ // if (show_abandoned) _mi_raw_message("total abandoned slices: %zu\n", abandoned_total);+ if (show_pages) _mi_raw_message("total pages in arenas: %zu\n", page_total);+}++void mi_debug_show_arenas(void) mi_attr_noexcept {+ mi_debug_show_arenas_ex(mi_heap_main(), true /* show pages */, true /* narrow? */);+}++void mi_arenas_print(void) mi_attr_noexcept {+ mi_debug_show_arenas();}@@ -960,7 +1774,7 @@ void mi_debug_show_arenas(bool show_inuse) mi_attr_noexcept {----------------------------------------------------------- */// reserve at a specific numa nodeint 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 {- if (arena_id != NULL) *arena_id = -1;+ if (arena_id != NULL) *arena_id = NULL;if (pages==0) return 0;if (numa_node < -1) numa_node = -1;if (numa_node >= 0) numa_node = numa_node % _mi_os_numa_node_count();@@ -974,7 +1788,7 @@ int mi_reserve_huge_os_pages_at_ex(size_t pages, int numa_node, size_t timeout_m}_mi_verbose_message("numa node %i: reserved %zu GiB huge pages (of the %zu GiB requested)\n", numa_node, pages_reserved, pages);- if (!mi_manage_os_memory_ex2(p, hsize, true, numa_node, exclusive, memid, arena_id)) {+ if (!mi_manage_os_memory_ex2(_mi_subproc(), p, hsize, numa_node, exclusive, memid, NULL, NULL, arena_id)) {_mi_os_free(p, hsize, memid);return ENOMEM;}@@ -990,17 +1804,17 @@ int mi_reserve_huge_os_pages_interleave(size_t pages, size_t numa_nodes, size_tif (pages == 0) return 0;// pages per numa node- size_t numa_count = (numa_nodes > 0 ? numa_nodes : _mi_os_numa_node_count());- if (numa_count <= 0) numa_count = 1;+ int numa_count = (numa_nodes > 0 && numa_nodes <= INT_MAX ? (int)numa_nodes : _mi_os_numa_node_count());+ if (numa_count <= 0) { numa_count = 1; }const size_t pages_per = pages / numa_count;const size_t pages_mod = pages % numa_count;const size_t timeout_per = (timeout_msecs==0 ? 0 : (timeout_msecs / numa_count) + 50);// reserve evenly among numa nodes- for (size_t numa_node = 0; numa_node < numa_count && pages > 0; numa_node++) {+ for (int numa_node = 0; numa_node < numa_count && pages > 0; numa_node++) {size_t node_pages = pages_per; // can be 0- if (numa_node < pages_mod) node_pages++;- int err = mi_reserve_huge_os_pages_at(node_pages, (int)numa_node, timeout_per);+ if ((size_t)numa_node < pages_mod) { node_pages++; }+ int err = mi_reserve_huge_os_pages_at(node_pages, numa_node, timeout_per);if (err) return err;if (pages < node_pages) {pages = 0;@@ -1021,3 +1835,492 @@ int mi_reserve_huge_os_pages(size_t pages, double max_secs, size_t* pages_reservif (err==0 && pages_reserved!=NULL) *pages_reserved = pages;return err;}++++++/* -----------------------------------------------------------+ Arena purge+----------------------------------------------------------- */++static long mi_arena_purge_delay(void) {+ // <0 = no purging allowed, 0=immediate purging, >0=milli-second delay+ return (mi_option_get(mi_option_purge_delay) * mi_option_get(mi_option_arena_purge_mult));+}++// reset or decommit in an arena and update the commit bitmap+// assumes we own the area (i.e. slices_free is claimed by us)+// returns if the memory is no longer committed (versus reset which keeps the commit)+static bool mi_arena_purge(mi_arena_t* arena, size_t slice_index, size_t slice_count) {+ mi_assert_internal(!arena->memid.is_pinned);+ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));++ const size_t size = mi_size_of_slices(slice_count);+ void* const p = mi_arena_slice_start(arena, slice_index);+ //const bool all_committed = mi_bitmap_is_setN(arena->slices_committed, slice_index, slice_count);+ size_t already_committed;+ mi_bitmap_setN(arena->slices_committed, slice_index, slice_count, &already_committed); // pretend all committed.. (as we lack a clearN call that counts the already set bits..)+ const bool all_committed = (already_committed == slice_count);+ const bool needs_recommit = _mi_os_purge_ex(p, size, all_committed /* allow reset? */, mi_size_of_slices(already_committed), arena->commit_fun, arena->commit_fun_arg);++ if (needs_recommit) {+ // no longer committed+ mi_bitmap_clearN(arena->slices_committed, slice_index, slice_count);+ // we just counted in the purge to decommit all, but the some part was not committed so adjust that here+ // mi_subproc_stat_decrease(arena->subproc, committed, mi_size_of_slices(slice_count - already_committed));+ }+ else if (!all_committed) {+ // we cannot assume any of these are committed any longer (even with reset since we did setN and may have marked uncommitted slices as committed)+ mi_bitmap_clearN(arena->slices_committed, slice_index, slice_count);+ // we adjust the commit count as parts will be re-committed+ // mi_subproc_stat_decrease(arena->subproc, committed, mi_size_of_slices(already_committed));+ }++ return needs_recommit;+}+++// Schedule a purge. This is usually delayed to avoid repeated decommit/commit calls.+// Note: assumes we (still) own the area as we may purge immediately+static void mi_arena_schedule_purge(mi_arena_t* arena, size_t slice_index, size_t slice_count) {+ const long delay = mi_arena_purge_delay();+ if (arena->memid.is_pinned || delay < 0 || _mi_preloading()) return; // is purging allowed at all?++ mi_assert_internal(mi_bbitmap_is_clearN(arena->slices_free, slice_index, slice_count));+ if (delay == 0) {+ // purge directly+ mi_arena_purge(arena, slice_index, slice_count);+ }+ else {+ // schedule purge+ const mi_msecs_t expire = _mi_clock_now() + delay;+ mi_msecs_t expire0 = 0;+ if (mi_atomic_casi64_strong_acq_rel(&arena->purge_expire, &expire0, expire)) {+ // expiration was not yet set+ // maybe set the global arenas expire as well (if it wasn't set already)+ mi_assert_internal(expire0==0);+ mi_atomic_casi64_strong_acq_rel(&arena->subproc->purge_expire, &expire0, expire);+ }+ else {+ // already an expiration was set+ }+ mi_bitmap_setN(arena->slices_purge, slice_index, slice_count, NULL);+ }+}++typedef struct mi_purge_visit_info_s {+ mi_msecs_t now;+ mi_msecs_t delay;+ bool all_purged;+ bool any_purged;+} mi_purge_visit_info_t;++static bool mi_arena_try_purge_range(mi_arena_t* arena, size_t slice_index, size_t slice_count) {+ mi_assert(slice_count < MI_BCHUNK_BITS);+ if (mi_bbitmap_try_clearNC(arena->slices_free, slice_index, slice_count)) {+ // purge+ bool decommitted = mi_arena_purge(arena, slice_index, slice_count); MI_UNUSED(decommitted);+ mi_assert_internal(!decommitted || mi_bitmap_is_clearN(arena->slices_committed, slice_index, slice_count));+ // and reset the free range+ mi_bbitmap_setN(arena->slices_free, slice_index, slice_count);+ return true;+ }+ else {+ // was allocated again already+ return false;+ }+}++static bool mi_arena_try_purge_visitor(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {+ mi_purge_visit_info_t* vinfo = (mi_purge_visit_info_t*)arg;+ // try to purge: first claim the free blocks+ if (mi_arena_try_purge_range(arena, slice_index, slice_count)) {+ vinfo->any_purged = true;+ vinfo->all_purged = true;+ }+ else if (slice_count > 1)+ {+ // failed to claim the full range, try per slice instead+ for (size_t i = 0; i < slice_count; i++) {+ const bool purged = mi_arena_try_purge_range(arena, slice_index + i, 1);+ vinfo->any_purged = vinfo->any_purged || purged;+ vinfo->all_purged = vinfo->all_purged && purged;+ }+ }+ // don't clear the purge bits as that is done atomically be the _bitmap_forall_set_ranges+ // mi_bitmap_clearN(arena->slices_purge, slice_index, slice_count);+ return true; // continue+}++// returns true if anything was purged+static bool mi_arena_try_purge(mi_arena_t* arena, mi_msecs_t now, bool force)+{+ // check pre-conditions+ if (arena->memid.is_pinned) return false;++ // expired yet?+ mi_msecs_t expire = mi_atomic_loadi64_relaxed(&arena->purge_expire);+ if (!force && (expire == 0 || expire > now)) return false;++ // reset expire+ mi_atomic_storei64_release(&arena->purge_expire, (mi_msecs_t)0);+ mi_subproc_stat_counter_increase(arena->subproc, arena_purges, 1);++ // go through all purge info's (with max MI_BFIELD_BITS ranges at a time)+ // this also clears those ranges atomically (so any newly freed blocks will get purged next+ // time around)+ mi_purge_visit_info_t vinfo = { now, mi_arena_purge_delay(), true /*all?*/, false /*any?*/};++ // we purge by at least `minslices` to not fragment transparent huge pages for example+ const size_t minslices = mi_slice_count_of_size(_mi_os_minimal_purge_size());+ _mi_bitmap_forall_setc_rangesn(arena->slices_purge, minslices, &mi_arena_try_purge_visitor, arena, &vinfo);++ return vinfo.any_purged;+}+++static void mi_arenas_try_purge(bool force, bool visit_all, mi_subproc_t* subproc, size_t tseq)+{+ // try purge can be called often so try to only run when needed+ const long delay = mi_arena_purge_delay();+ if (_mi_preloading() || delay <= 0) return; // nothing will be scheduled++ // check if any arena needs purging?+ const mi_msecs_t now = _mi_clock_now();+ const mi_msecs_t arenas_expire = mi_atomic_loadi64_acquire(&subproc->purge_expire);+ if (!visit_all && !force && (arenas_expire == 0 || arenas_expire > now)) return;++ const size_t max_arena = mi_arenas_get_count(subproc);+ if (max_arena == 0) return;++ // allow only one thread to purge at a time (todo: allow concurrent purging?)+ static mi_atomic_guard_t purge_guard;+ mi_atomic_guard(&purge_guard)+ {+ // increase global expire: at most one purge per delay cycle+ if (arenas_expire > now) { mi_atomic_storei64_release(&subproc->purge_expire, now + (delay/10)); }+ const size_t arena_start = tseq % max_arena;+ size_t max_purge_count = (visit_all ? max_arena : (max_arena/4)+1);+ bool all_visited = true;+ bool any_purged = false;+ for (size_t _i = 0; _i < max_arena; _i++) {+ size_t i = _i + arena_start;+ if (i >= max_arena) { i -= max_arena; }+ mi_arena_t* arena = mi_arena_from_index(subproc,i);+ if (arena != NULL) {+ if (mi_arena_try_purge(arena, now, force)) {+ any_purged = true;+ if (max_purge_count <= 1) {+ all_visited = false;+ break;+ }+ max_purge_count--;+ }+ }+ }+ if (all_visited && !any_purged) {+ mi_atomic_storei64_release(&subproc->purge_expire, 0);+ }+ }+}+++/* -----------------------------------------------------------+ Visit all pages and blocks in a heap+----------------------------------------------------------- */++typedef struct mi_heap_visit_info_s {+ mi_heap_t* heap;+ mi_block_visit_fun* visitor;+ void* arg;+ bool visit_blocks;+} mi_heap_visit_info_t;++static bool mi_heap_visit_page(mi_page_t* page, mi_heap_visit_info_t* vinfo) {+ mi_heap_area_t area;+ _mi_heap_area_init(&area, page);+ mi_assert_internal(vinfo->heap == mi_page_heap(page));+ if (!vinfo->visitor(vinfo->heap, &area, NULL, area.block_size, vinfo->arg)) {+ return false;+ }+ if (vinfo->visit_blocks) {+ return _mi_theap_area_visit_blocks(&area, page, vinfo->visitor, vinfo->arg);+ }+ else {+ return true;+ }+}++static bool mi_heap_visit_page_at(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {+ MI_UNUSED(slice_count);+ mi_heap_visit_info_t* vinfo = (mi_heap_visit_info_t*)arg;+ mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ return mi_heap_visit_page(page, vinfo);+}++bool _mi_heap_visit_blocks(mi_heap_t* heap, bool abandoned_only, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {+ mi_assert(visitor!=NULL);+ if (visitor==NULL) return false;+ if (heap==NULL) { heap = mi_heap_main(); }+ // visit all pages in a heap+ // we don't have to claim because we assume we are the only thread running (with this heap).+ // (but we could atomically claim as well by first doing abandoned_reclaim and afterwards reabandoning).+ mi_heap_visit_info_t visit_info = { heap, visitor, arg, visit_blocks };+ bool ok = true;+ mi_forall_arenas(heap, NULL, 0, arena) {+ mi_arena_pages_t* arena_pages = mi_heap_arena_pages(heap, arena);+ if (ok && arena_pages != NULL) {+ if (abandoned_only) {+ for (size_t bin = 0; ok && bin < MI_BIN_COUNT; bin++) {+ // todo: if we had a single abandoned page map as well, this can be faster.+ if (mi_atomic_load_relaxed(&heap->abandoned_count[bin]) > 0) {+ ok = _mi_bitmap_forall_set(arena_pages->pages_abandoned[bin], &mi_heap_visit_page_at, arena, &visit_info);+ }+ }+ }+ else {+ ok = _mi_bitmap_forall_set(arena_pages->pages, &mi_heap_visit_page_at, arena, &visit_info);+ }+ }+ }+ mi_forall_arenas_end();+ if (!ok) return false;++ // visit abandoned pages in OS allocated memory+ // (technically we don't need the initial lock as we assume we are the only thread running in this subproc)+ mi_page_t* page = NULL;+ mi_lock(&heap->os_abandoned_pages_lock) {+ page = heap->os_abandoned_pages;+ }+ while (ok && page != NULL) {+ mi_page_t* next = page->next; // read upfront in case the visitor frees the page+ ok = mi_heap_visit_page(page, &visit_info);+ page = next;+ }++ return ok;+}++bool mi_heap_visit_blocks(mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {+ return _mi_heap_visit_blocks(heap, false, visit_blocks, visitor, arg);+}++bool mi_heap_visit_abandoned_blocks(mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {+ return _mi_heap_visit_blocks(heap, true, visit_blocks, visitor, arg);+}+++typedef struct mi_heap_delete_visit_info_s {+ mi_heap_t* heap_target;+ mi_theap_t* theap_target;+ mi_theap_t* theap;+} mi_heap_delete_visit_info_t;++static bool mi_heap_delete_page(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {+ MI_UNUSED(block); MI_UNUSED(block_size); MI_UNUSED(heap);+ mi_heap_delete_visit_info_t* info = (mi_heap_delete_visit_info_t*)arg;+ mi_heap_t* heap_target = info->heap_target;+ mi_theap_t* const theap = info->theap; mi_assert_internal(theap->heap == heap);+ mi_page_t* const page = (mi_page_t*)area->reserved1;++ mi_page_claim_ownership(page); // claim ownership+ if (mi_page_is_abandoned(page)) {+ _mi_arenas_page_unabandon(page,theap);+ }+ else {+ page->next = page->prev = NULL; // yikes.. better not to try to access this from a thread later on..+ mi_page_set_theap(page,NULL); // set threadid to abandoned+ }+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(mi_page_is_owned(page));++ if (page->used==0) {+ // free the page+ _mi_arenas_page_free(page, theap);+ }+ else if (heap_target==NULL) {+ // destroy the page+ page->used=0; // note: invariant `|local_free| + |free| == reserved - used` does not hold in this case+ _mi_arenas_page_free(page, theap);+ }+ else {+ // move the page to `heap_target` as an abandoned page+ // first remove it from the current heap+ const size_t sbin = _mi_page_stats_bin(page);+ size_t slice_index;+ size_t slice_count;+ mi_arena_pages_t* arena_pages = NULL;+ mi_arena_t* const arena = mi_page_arena_pages(page, &slice_index, &slice_count, &arena_pages);+ mi_assert_internal(mi_bitmap_is_set(arena_pages->pages, slice_index));+ mi_bitmap_clear(arena_pages->pages, slice_index);+ mi_theap_stat_decrease(theap, page_bins[sbin], 1);+ mi_theap_stat_decrease(theap, pages, 1);+ mi_theap_t* theap_target = info->theap_target;++ // and then add it to the new target heap+ mi_arena_pages_t* arena_pages_target = mi_heap_ensure_arena_pages(heap_target, arena);+ if mi_unlikely(arena_pages_target==NULL) {+ // if we cannot allocate this, we move it to the main heap instead (which does not require allocation)+ heap_target = mi_heap_main();+ theap_target = mi_heap_theap(heap_target);+ arena_pages_target = mi_heap_ensure_arena_pages(heap_target, arena);+ mi_assert_internal(arena_pages_target!=NULL);+ }+ mi_assert_internal(mi_bitmap_is_clear(arena_pages_target->pages, slice_index));+ mi_bitmap_set(arena_pages_target->pages, slice_index);+ page->heap = heap_target;+ mi_theap_stat_increase(theap_target, page_bins[sbin], 1);+ mi_theap_stat_increase(theap_target, pages, 1);++ // and abandon in the new heap+ _mi_arenas_page_abandon(page,theap_target);+ }+ return true;+}++static void mi_heap_delete_pages(mi_heap_t* heap, mi_heap_t* heap_target) {+ mi_theap_t* const theap_target = (heap_target != NULL ? _mi_heap_theap(heap_target) : NULL);+ mi_theap_t* const theap = _mi_heap_theap(heap);+ mi_heap_delete_visit_info_t info = { heap_target, theap_target, theap };+ _mi_heap_visit_blocks(heap, false, false, &mi_heap_delete_page, &info);+ #if MI_DEBUG>1+ // no more arena pages?+ for (size_t i = 0; i < MI_ARENA_BIN_COUNT; i++) {+ mi_arena_pages_t* const arena_pages = mi_atomic_load_relaxed(&heap->arena_pages[i]);+ if (arena_pages!=NULL) {+ mi_assert_internal(mi_bitmap_is_all_clear(arena_pages->pages));+ }+ }+ // nor os abandoned pages?+ mi_lock(&heap->os_abandoned_pages_lock) {++ mi_assert_internal(heap->os_abandoned_pages == NULL);+ }+ // nor arena abandoned pages?+ for (size_t i = 0; i < MI_BIN_COUNT; i++) {+ mi_assert_internal(mi_atomic_load_relaxed(&heap->abandoned_count[i])==0);+ }+ #endif+}++void _mi_heap_move_pages(mi_heap_t* heap_from, mi_heap_t* heap_to) {+ if (_mi_is_heap_main(heap_from)) return;+ if (heap_to==NULL) { heap_to = mi_heap_main(); }+ mi_heap_delete_pages(heap_from, heap_to);+}++void _mi_heap_destroy_pages(mi_heap_t* heap_from) {+ if (_mi_is_heap_main(heap_from)) return;+ mi_heap_delete_pages(heap_from, NULL);+}++/* -----------------------------------------------------------+ Unloading and reloading an arena.+----------------------------------------------------------- */+/*+static bool mi_arena_page_register(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg) {+ MI_UNUSED(arg); MI_UNUSED(slice_count);+ mi_assert_internal(slice_count == 1);+ mi_page_t* page = (mi_page_t*)mi_arena_slice_start(arena, slice_index);+ mi_assert_internal(mi_bitmap_is_setN(page->memid.mem.arena.arena->pages, page->memid.mem.arena.slice_index, 1));+ if (!_mi_page_map_register(page)) return false; // break+ mi_assert_internal(_mi_ptr_page(page)==page);+ return true;+}++mi_decl_nodiscard static bool mi_arena_pages_reregister(mi_arena_t* arena) {+ return _mi_bitmap_forall_set(arena->pages, &mi_arena_page_register, arena, NULL);+}++mi_decl_export bool mi_arena_unload(mi_arena_id_t arena_id, void** base, size_t* accessed_size, size_t* full_size) {+ mi_arena_t* arena = _mi_arena_from_id(arena_id);+ if (arena==NULL) {+ return false;+ }+ else if (!arena->is_exclusive) {+ _mi_warning_message("cannot unload a non-exclusive arena (id %zu at %p)\n", arena_id, arena);+ return false;+ }+ else if (arena->memid.memkind != MI_MEM_EXTERNAL) {+ _mi_warning_message("can only unload managed arena's for external memory (id %zu at %p)\n", arena_id, arena);+ return false;+ }++ // find accessed size+ const size_t asize = mi_size_of_slices(mi_arena_used_slices(arena));+ if (base != NULL) { *base = (void*)arena; }+ if (full_size != NULL) { *full_size = arena->memid.mem.os.size; }+ if (accessed_size != NULL) { *accessed_size = asize; }++ // adjust abandoned page count+ mi_subproc_t* const subproc = arena->subproc;+ for (size_t bin = 0; bin < MI_BIN_COUNT; bin++) {+ const size_t count = mi_bitmap_popcount(arena->pages_abandoned[bin]);+ if (count > 0) { mi_atomic_decrement_acq_rel(&subproc->abandoned_count[bin]); }+ }++ // unregister the pages+ _mi_page_map_unregister_range(arena, asize);++ // set arena entry to NULL+ const size_t count = mi_arenas_get_count(subproc);+ for(size_t i = 0; i < count; i++) {+ if (mi_arena_from_index(subproc, i) == arena) {+ mi_atomic_store_ptr_release(mi_arena_t, &subproc->arenas[i], NULL);+ if (i + 1 == count) { // try adjust the count?+ size_t expected = count;+ mi_atomic_cas_strong_acq_rel(&subproc->arena_count, &expected, count-1);+ }+ break;+ }+ }+ return true;+}++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) {+ // assume the memory area is already containing the arena+ if (arena_id != NULL) { *arena_id = _mi_arena_id_none(); }+ if (start == NULL || size == 0) return false;+ mi_arena_t* arena = (mi_arena_t*)start;+ mi_memid_t memid = arena->memid;+ if (memid.memkind != MI_MEM_EXTERNAL) {+ _mi_warning_message("can only reload arena's from external memory (%p)\n", arena);+ return false;+ }+ if (memid.mem.os.base != start) {+ _mi_warning_message("the reloaded arena base address differs from the external memory (arena: %p, external: %p)\n", arena, start);+ return false;+ }+ if (memid.mem.os.size != size) {+ _mi_warning_message("the reloaded arena size differs from the external memory (arena size: %zu, external size: %zu)\n", arena->memid.mem.os.size, size);+ return false;+ }+ if (!arena->is_exclusive) {+ _mi_warning_message("the reloaded arena is not exclusive\n");+ return false;+ }++ // re-initialize+ arena->is_exclusive = true;+ arena->commit_fun = commit_fun;+ arena->commit_fun_arg = commit_fun_arg;+ arena->subproc = _mi_subproc();+ if (!mi_arenas_add(arena->subproc, arena, arena_id)) {+ return false;+ }+ if (!mi_arena_pages_reregister(arena)) {+ // todo: clear arena entry in the subproc?+ return false;+ }++ // adjust abandoned page count+ for (size_t bin = 0; bin < MI_BIN_COUNT; bin++) {+ const size_t count = mi_bitmap_popcount(arena->pages_abandoned[bin]);+ if (count > 0) { mi_atomic_decrement_acq_rel(&arena->subproc->abandoned_count[bin]); }+ }++ return true;+}++*/diff --git a/vendored/mimalloc/src/bitmap.c b/vendored/mimalloc/src/bitmap.cindex 084082fb7..aa4d23619 100644--- a/vendored/mimalloc/src/bitmap.c+++ b/vendored/mimalloc/src/bitmap.c@@ -1,436 +1,1899 @@/* -----------------------------------------------------------------------------Copyright (c) 2019-2023 Microsoft Research, Daan Leijen+Copyright (c) 2019-2024 Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.-----------------------------------------------------------------------------*//* -----------------------------------------------------------------------------Concurrent bitmap that can set/reset sequences of bits atomically,-represented as an array of fields where each field is a machine word (`size_t`)--There are two api's; the standard one cannot have sequences that cross-between the bitmap fields (and a sequence must be <= MI_BITMAP_FIELD_BITS).--The `_across` postfixed functions do allow sequences that can cross over-between the fields. (This is used in arena allocation)+Concurrent bitmap that can set/reset sequences of bits atomically---------------------------------------------------------------------------- */#include "mimalloc.h"#include "mimalloc/internal.h"+#include "mimalloc/bits.h"#include "bitmap.h"-/* ------------------------------------------------------------ Bitmap definition------------------------------------------------------------ */+#ifndef MI_OPT_SIMD+#define MI_OPT_SIMD 0+#endif++/* --------------------------------------------------------------------------------+ bfields+-------------------------------------------------------------------------------- */-// The bit mask for a given number of blocks at a specified bit index.-static inline size_t mi_bitmap_mask_(size_t count, size_t bitidx) {- mi_assert_internal(count + bitidx <= MI_BITMAP_FIELD_BITS);- mi_assert_internal(count > 0);- if (count >= MI_BITMAP_FIELD_BITS) return MI_BITMAP_FIELD_FULL;- if (count == 0) return 0;- return ((((size_t)1 << count) - 1) << bitidx);+static inline size_t mi_bfield_ctz(mi_bfield_t x) {+ return mi_ctz(x);}+static inline size_t mi_bfield_clz(mi_bfield_t x) {+ return mi_clz(x);+}-/* ------------------------------------------------------------ Claim a bit sequence atomically------------------------------------------------------------ */+static inline size_t mi_bfield_popcount(mi_bfield_t x) {+ return mi_popcount(x);+}-// Try to atomically claim a sequence of `count` bits in a single-// field at `idx` in `bitmap`. Returns `true` on success.-inline bool _mi_bitmap_try_find_claim_field(mi_bitmap_t bitmap, size_t idx, const size_t count, mi_bitmap_index_t* bitmap_idx)-{- mi_assert_internal(bitmap_idx != NULL);- mi_assert_internal(count <= MI_BITMAP_FIELD_BITS);- mi_assert_internal(count > 0);- mi_bitmap_field_t* field = &bitmap[idx];- size_t map = mi_atomic_load_relaxed(field);- if (map==MI_BITMAP_FIELD_FULL) return false; // short cut-- // search for 0-bit sequence of length count- const size_t mask = mi_bitmap_mask_(count, 0);- const size_t bitidx_max = MI_BITMAP_FIELD_BITS - count;--#ifdef MI_HAVE_FAST_BITSCAN- size_t bitidx = mi_ctz(~map); // quickly find the first zero bit if possible-#else- size_t bitidx = 0; // otherwise start at 0-#endif- size_t m = (mask << bitidx); // invariant: m == mask shifted by bitidx-- // scan linearly for a free range of zero bits- while (bitidx <= bitidx_max) {- const size_t mapm = (map & m);- if (mapm == 0) { // are the mask bits free at bitidx?- mi_assert_internal((m >> bitidx) == mask); // no overflow?- const size_t newmap = (map | m);- mi_assert_internal((newmap^map) >> bitidx == mask);- if (!mi_atomic_cas_strong_acq_rel(field, &map, newmap)) { // TODO: use weak cas here?- // no success, another thread claimed concurrently.. keep going (with updated `map`)- continue;+static inline mi_bfield_t mi_bfield_clear_least_bit(mi_bfield_t x) {+ return (x & (x-1));+}++// 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_bfield_find_least_bit(mi_bfield_t x, size_t* idx) {+ return mi_bsf(x,idx);+}++// 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_bfield_find_highest_bit(mi_bfield_t x, size_t* idx) {+ return mi_bsr(x, idx);+}++++// find each set bit in a bit field `x` and clear it, until it becomes zero.+static inline bool mi_bfield_foreach_bit(mi_bfield_t* x, size_t* idx) {+ const bool found = mi_bfield_find_least_bit(*x, idx);+ *x = mi_bfield_clear_least_bit(*x);+ return found;+}++static inline mi_bfield_t mi_bfield_zero(void) {+ return 0;+}++static inline mi_bfield_t mi_bfield_one(void) {+ return 1;+}++static inline mi_bfield_t mi_bfield_all_set(void) {+ return ~((mi_bfield_t)0);+}++// mask of `bit_count` bits set shifted to the left by `shiftl`+static inline mi_bfield_t mi_bfield_mask(size_t bit_count, size_t shiftl) {+ mi_assert_internal(bit_count > 0);+ mi_assert_internal(bit_count + shiftl <= MI_BFIELD_BITS);+ mi_assert_internal(shiftl < MI_BFIELD_BITS);+ const mi_bfield_t mask0 = (bit_count < MI_BFIELD_BITS ? (mi_bfield_one() << bit_count)-1 : mi_bfield_all_set());+ return (mask0 << shiftl);+}+++// ------- mi_bfield_atomic_set ---------------------------------------+// the `_set` functions return also the count of bits that were already set (for commit statistics)+// the `_clear` functions return also whether the new bfield is all clear or not (for the chunk_map)++// Set a bit atomically. Returns `true` if the bit transitioned from 0 to 1+static inline bool mi_bfield_atomic_set(_Atomic(mi_bfield_t)*b, size_t idx) {+ mi_assert_internal(idx < MI_BFIELD_BITS);+ const mi_bfield_t mask = mi_bfield_mask(1, idx);;+ const mi_bfield_t old = mi_atomic_or_acq_rel(b, mask);+ return ((old&mask) == 0);+}++// Clear a bit atomically. Returns `true` if the bit transitioned from 1 to 0.+// `all_clear` is set if the new bfield is zero.+static inline bool mi_bfield_atomic_clear(_Atomic(mi_bfield_t)*b, size_t idx, bool* all_clear) {+ mi_assert_internal(idx < MI_BFIELD_BITS);+ const mi_bfield_t mask = mi_bfield_mask(1, idx);;+ mi_bfield_t old = mi_atomic_and_acq_rel(b, ~mask);+ if (all_clear != NULL) { *all_clear = ((old&~mask)==0); }+ return ((old&mask) == mask);+}++// Clear a bit but only when/once it is set. This is used by concurrent free's while+// the page is abandoned and mapped. This can incure a busy wait :-( but it should+// happen almost never (and is accounted for in the stats)+static inline void mi_bfield_atomic_clear_once_set(_Atomic(mi_bfield_t)*b, size_t idx) {+ mi_assert_internal(idx < MI_BFIELD_BITS);+ const mi_bfield_t mask = mi_bfield_mask(1, idx);;+ mi_bfield_t old = mi_atomic_load_relaxed(b);+ do {+ if mi_unlikely((old&mask) == 0) {+ old = mi_atomic_load_acquire(b);+ if ((old&mask)==0) {+ mi_subproc_stat_counter_increase(_mi_subproc(), pages_unabandon_busy_wait, 1);}- else {- // success, we claimed the bits!- *bitmap_idx = mi_bitmap_index_create(idx, bitidx);- return true;+ while ((old&mask)==0) { // busy wait+ mi_atomic_yield();+ old = mi_atomic_load_acquire(b);}}+ } while (!mi_atomic_cas_weak_acq_rel(b,&old, (old&~mask)));+ mi_assert_internal((old&mask)==mask); // we should only clear when it was set+}++// Set a mask set of bits atomically, and return true of the mask bits transitioned from all 0's to 1's.+// `already_set` contains the count of bits that were already set (used when committing ranges to account+// statistics correctly).+static inline bool mi_bfield_atomic_set_mask(_Atomic(mi_bfield_t)*b, mi_bfield_t mask, size_t* already_set) {+ mi_assert_internal(mask != 0);+ mi_bfield_t old = mi_atomic_load_relaxed(b);+ while (!mi_atomic_cas_weak_acq_rel(b, &old, old|mask)) {}; // try to atomically set the mask bits until success+ if (already_set!=NULL) { *already_set = mi_bfield_popcount(old&mask); }+ return ((old&mask) == 0);+}++// Clear a mask set of bits atomically, and return true of the mask bits transitioned from all 1's to 0's+// `all_clear` is set to `true` if the new bfield became zero.+static inline bool mi_bfield_atomic_clear_mask(_Atomic(mi_bfield_t)*b, mi_bfield_t mask, bool* all_clear) {+ mi_assert_internal(mask != 0);+ mi_bfield_t old = mi_atomic_load_relaxed(b);+ while (!mi_atomic_cas_weak_acq_rel(b, &old, old&~mask)) {}; // try to atomically clear the mask bits until success+ if (all_clear != NULL) { *all_clear = ((old&~mask)==0); }+ return ((old&mask) == mask);+}++static inline bool mi_bfield_atomic_setX(_Atomic(mi_bfield_t)*b, size_t* already_set) {+ const mi_bfield_t old = mi_atomic_exchange_release(b, mi_bfield_all_set());+ if (already_set!=NULL) { *already_set = mi_bfield_popcount(old); }+ return (old==0);+}++// static inline bool mi_bfield_atomic_clearX(_Atomic(mi_bfield_t)*b, bool* all_clear) {+// const mi_bfield_t old = mi_atomic_exchange_release(b, mi_bfield_zero());+// if (all_clear!=NULL) { *all_clear = true; }+// return (~old==0);+// }++// ------- mi_bfield_atomic_try_clear ---------------------------------------+++// Tries to clear a mask atomically, and returns true if the mask bits atomically transitioned from mask to 0+// and false otherwise (leaving the bit field as is).+// `all_clear` is set to `true` if the new bfield became zero.+static inline bool mi_bfield_atomic_try_clear_mask_of(_Atomic(mi_bfield_t)*b, mi_bfield_t mask, mi_bfield_t expect, bool* all_clear) {+ mi_assert_internal(mask != 0);+ // try to atomically clear the mask bits+ do {+ if ((expect & mask) != mask) { // are all bits still set?+ if (all_clear != NULL) { *all_clear = (expect == 0); }+ return false;+ }+ } while (!mi_atomic_cas_weak_acq_rel(b, &expect, expect & ~mask));+ if (all_clear != NULL) { *all_clear = ((expect & ~mask) == 0); }+ return true;+}++static inline bool mi_bfield_atomic_try_clear_mask(_Atomic(mi_bfield_t)* b, mi_bfield_t mask, bool* all_clear) {+ mi_assert_internal(mask != 0);+ const mi_bfield_t expect = mi_atomic_load_relaxed(b);+ return mi_bfield_atomic_try_clear_mask_of(b, mask, expect, all_clear);+}++// Tries to clear a bit atomically. Returns `true` if the bit transitioned from 1 to 0+// and `false` otherwise leaving the bfield `b` as-is.+// `all_clear` is set to true if the new bfield became zero (and false otherwise)+mi_decl_maybe_unused static inline bool mi_bfield_atomic_try_clear(_Atomic(mi_bfield_t)* b, size_t idx, bool* all_clear) {+ mi_assert_internal(idx < MI_BFIELD_BITS);+ const mi_bfield_t mask = mi_bfield_one()<<idx;+ return mi_bfield_atomic_try_clear_mask(b, mask, all_clear);+}++// Tries to clear a byte atomically, and returns true if the byte atomically transitioned from 0xFF to 0+// `all_clear` is set to true if the new bfield became zero (and false otherwise)+mi_decl_maybe_unused static inline bool mi_bfield_atomic_try_clear8(_Atomic(mi_bfield_t)*b, size_t idx, bool* all_clear) {+ mi_assert_internal(idx < MI_BFIELD_BITS);+ mi_assert_internal((idx%8)==0);+ const mi_bfield_t mask = ((mi_bfield_t)0xFF)<<idx;+ return mi_bfield_atomic_try_clear_mask(b, mask, all_clear);+}++// Try to clear a full field of bits atomically, and return true all bits transitioned from all 1's to 0's.+// and false otherwise leaving the bit field as-is.+// `all_clear` is set to true if the new bfield became zero (which is always the case if successful).+static inline bool mi_bfield_atomic_try_clearX(_Atomic(mi_bfield_t)*b, bool* all_clear) {+ mi_bfield_t old = mi_bfield_all_set();+ if (mi_atomic_cas_strong_acq_rel(b, &old, mi_bfield_zero())) {+ if (all_clear != NULL) { *all_clear = true; }+ return true;+ }+ else return false;+}+++// ------- mi_bfield_atomic_is_set ---------------------------------------++// Check if a bit is set+static inline bool mi_bfield_atomic_is_set(const _Atomic(mi_bfield_t)*b, const size_t idx) {+ const mi_bfield_t x = mi_atomic_load_relaxed(b);+ return ((x & mi_bfield_mask(1,idx)) != 0);+}++// Check if a bit is clear+static inline bool mi_bfield_atomic_is_clear(const _Atomic(mi_bfield_t)*b, const size_t idx) {+ const mi_bfield_t x = mi_atomic_load_relaxed(b);+ return ((x & mi_bfield_mask(1, idx)) == 0);+}++// Check if a bit is xset+static inline bool mi_bfield_atomic_is_xset(mi_xset_t set, const _Atomic(mi_bfield_t)*b, const size_t idx) {+ if (set) return mi_bfield_atomic_is_set(b, idx);+ else return mi_bfield_atomic_is_clear(b, idx);+}++// Check if all bits corresponding to a mask are set.+static inline bool mi_bfield_atomic_is_set_mask(const _Atomic(mi_bfield_t)* b, mi_bfield_t mask) {+ mi_assert_internal(mask != 0);+ const mi_bfield_t x = mi_atomic_load_relaxed(b);+ return ((x & mask) == mask);+}++// Check if all bits corresponding to a mask are clear.+static inline bool mi_bfield_atomic_is_clear_mask(const _Atomic(mi_bfield_t)* b, mi_bfield_t mask) {+ mi_assert_internal(mask != 0);+ const mi_bfield_t x = mi_atomic_load_relaxed(b);+ return ((x & mask) == 0);+}++// Check if all bits corresponding to a mask are set/cleared.+static inline bool mi_bfield_atomic_is_xset_mask(mi_xset_t set, const _Atomic(mi_bfield_t)* b, mi_bfield_t mask) {+ mi_assert_internal(mask != 0);+ if (set) return mi_bfield_atomic_is_set_mask(b, mask);+ else return mi_bfield_atomic_is_clear_mask(b, mask);+}++// Count bits in a mask+static inline size_t mi_bfield_atomic_popcount_mask(_Atomic(mi_bfield_t)*b, mi_bfield_t mask) {+ const mi_bfield_t x = mi_atomic_load_relaxed(b);+ return mi_bfield_popcount(x & mask);+}+++/* --------------------------------------------------------------------------------+ bitmap chunks+-------------------------------------------------------------------------------- */++// ------- mi_bchunk_set ---------------------------------------++// Set a single bit+static inline bool mi_bchunk_set(mi_bchunk_t* chunk, size_t cidx, size_t* already_set) {+ mi_assert_internal(cidx < MI_BCHUNK_BITS);+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ const bool was_clear = mi_bfield_atomic_set(&chunk->bfields[i], idx);+ if (already_set != NULL) { *already_set = (was_clear ? 0 : 1); }+ return was_clear;+}++// Set `0 < n <= MI_BFIELD_BITS`, and return true of the mask bits transitioned from all 0's to 1's.+// `already_set` contains the count of bits that were already set (used when committing ranges to account+// statistics correctly).+// Can cross over two bfields.+static inline bool mi_bchunk_setNX(mi_bchunk_t* chunk, size_t cidx, size_t n, size_t* already_set) {+ mi_assert_internal(cidx < MI_BCHUNK_BITS);+ mi_assert_internal(n > 0 && n <= MI_BFIELD_BITS);+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ if mi_likely(idx + n <= MI_BFIELD_BITS) {+ // within one field+ return mi_bfield_atomic_set_mask(&chunk->bfields[i], mi_bfield_mask(n,idx), already_set);+ }+ else {+ // spanning two fields+ const size_t m = MI_BFIELD_BITS - idx; // bits to clear in the first field+ mi_assert_internal(m < n);+ mi_assert_internal(i < MI_BCHUNK_FIELDS - 1);+ mi_assert_internal(idx + m <= MI_BFIELD_BITS);+ size_t already_set1;+ const bool all_set1 = mi_bfield_atomic_set_mask(&chunk->bfields[i], mi_bfield_mask(m, idx), &already_set1);+ mi_assert_internal(n - m > 0);+ mi_assert_internal(n - m < MI_BFIELD_BITS);+ size_t already_set2;+ const bool all_set2 = mi_bfield_atomic_set_mask(&chunk->bfields[i+1], mi_bfield_mask(n - m, 0), &already_set2);+ if (already_set != NULL) { *already_set = already_set1 + already_set2; }+ return (all_set1 && all_set2);+ }+}++// Set a sequence of `n` bits within a chunk.+// Returns true if all bits transitioned from 0 to 1 (or 1 to 0).+mi_decl_noinline static bool mi_bchunk_xsetNC(mi_xset_t set, mi_bchunk_t* chunk, size_t cidx, size_t n, size_t* palready_set, bool* pmaybe_all_clear) {+ mi_assert_internal(cidx + n <= MI_BCHUNK_BITS);+ mi_assert_internal(n>0);+ bool all_transition = true;+ bool maybe_all_clear = true;+ size_t total_already_set = 0;+ size_t idx = cidx % MI_BFIELD_BITS;+ size_t field = cidx / MI_BFIELD_BITS;+ while (n > 0) {+ size_t m = MI_BFIELD_BITS - idx; // m is the bits to xset in this field+ if (m > n) { m = n; }+ mi_assert_internal(idx + m <= MI_BFIELD_BITS);+ mi_assert_internal(field < MI_BCHUNK_FIELDS);+ const mi_bfield_t mask = mi_bfield_mask(m, idx);+ size_t already_set = 0;+ bool all_clear = false;+ const bool transition = (set ? mi_bfield_atomic_set_mask(&chunk->bfields[field], mask, &already_set)+ : mi_bfield_atomic_clear_mask(&chunk->bfields[field], mask, &all_clear));+ mi_assert_internal((transition && already_set == 0) || (!transition && already_set > 0));+ all_transition = all_transition && transition;+ total_already_set += already_set;+ maybe_all_clear = maybe_all_clear && all_clear;+ // next field+ field++;+ idx = 0;+ mi_assert_internal(m <= n);+ n -= m;+ }+ if (palready_set!=NULL) { *palready_set = total_already_set; }+ if (pmaybe_all_clear!=NULL) { *pmaybe_all_clear = maybe_all_clear; }+ return all_transition;+}++static inline bool mi_bchunk_setN(mi_bchunk_t* chunk, size_t cidx, size_t n, size_t* already_set) {+ mi_assert_internal(n>0 && n <= MI_BCHUNK_BITS);+ if (n==1) return mi_bchunk_set(chunk, cidx, already_set);+ // if (n==8 && (cidx%8) == 0) return mi_bchunk_set8(chunk, cidx, already_set);+ // if (n==MI_BFIELD_BITS) return mi_bchunk_setX(chunk, cidx, already_set);+ if (n<=MI_BFIELD_BITS) return mi_bchunk_setNX(chunk, cidx, n, already_set);+ return mi_bchunk_xsetNC(MI_BIT_SET, chunk, cidx, n, already_set, NULL);+}++// ------- mi_bchunk_clear ---------------------------------------++static inline bool mi_bchunk_clear(mi_bchunk_t* chunk, size_t cidx, bool* all_clear) {+ mi_assert_internal(cidx < MI_BCHUNK_BITS);+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ return mi_bfield_atomic_clear(&chunk->bfields[i], idx, all_clear);+}++static inline bool mi_bchunk_clearN(mi_bchunk_t* chunk, size_t cidx, size_t n, bool* maybe_all_clear) {+ mi_assert_internal(n>0 && n <= MI_BCHUNK_BITS);+ if (n==1) return mi_bchunk_clear(chunk, cidx, maybe_all_clear);+ // if (n==8) return mi_bchunk_clear8(chunk, cidx, maybe_all_clear);+ // if (n==MI_BFIELD_BITS) return mi_bchunk_clearX(chunk, cidx, maybe_all_clear);+ // TODO: implement mi_bchunk_xsetNX instead of setNX+ return mi_bchunk_xsetNC(MI_BIT_CLEAR, chunk, cidx, n, NULL, maybe_all_clear);+}++// Check if a sequence of `n` bits within a chunk are all set/cleared.+// This can cross bfield's+mi_decl_noinline static size_t mi_bchunk_popcountNC(mi_bchunk_t* chunk, size_t field_idx, size_t idx, size_t n) {+ mi_assert_internal((field_idx*MI_BFIELD_BITS) + idx + n <= MI_BCHUNK_BITS);+ size_t count = 0;+ while (n > 0) {+ size_t m = MI_BFIELD_BITS - idx; // m is the bits to xset in this field+ if (m > n) { m = n; }+ mi_assert_internal(idx + m <= MI_BFIELD_BITS);+ mi_assert_internal(field_idx < MI_BCHUNK_FIELDS);+ const size_t mask = mi_bfield_mask(m, idx);+ count += mi_bfield_atomic_popcount_mask(&chunk->bfields[field_idx], mask);+ // next field+ field_idx++;+ idx = 0;+ n -= m;+ }+ return count;+}++// Count set bits a sequence of `n` bits.+static inline size_t mi_bchunk_popcountN(mi_bchunk_t* chunk, size_t cidx, size_t n) {+ mi_assert_internal(cidx + n <= MI_BCHUNK_BITS);+ mi_assert_internal(n>0);+ if (n==0) return 0;+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ if (n==1) { return (mi_bfield_atomic_is_set(&chunk->bfields[i], idx) ? 1 : 0); }+ if (idx + n <= MI_BFIELD_BITS) { return mi_bfield_atomic_popcount_mask(&chunk->bfields[i], mi_bfield_mask(n, idx)); }+ return mi_bchunk_popcountNC(chunk, i, idx, n);+}+++// ------- mi_bchunk_is_xset ---------------------------------------++// Check if a sequence of `n` bits within a chunk are all set/cleared.+// This can cross bfield's+mi_decl_noinline static bool mi_bchunk_is_xsetNC(mi_xset_t set, const mi_bchunk_t* chunk, size_t field_idx, size_t idx, size_t n) {+ mi_assert_internal((field_idx*MI_BFIELD_BITS) + idx + n <= MI_BCHUNK_BITS);+ while (n > 0) {+ size_t m = MI_BFIELD_BITS - idx; // m is the bits to xset in this field+ if (m > n) { m = n; }+ mi_assert_internal(idx + m <= MI_BFIELD_BITS);+ mi_assert_internal(field_idx < MI_BCHUNK_FIELDS);+ const size_t mask = mi_bfield_mask(m, idx);+ if (!mi_bfield_atomic_is_xset_mask(set, &chunk->bfields[field_idx], mask)) {+ return false;+ }+ // next field+ field_idx++;+ idx = 0;+ n -= m;+ }+ return true;+}++// Check if a sequence of `n` bits within a chunk are all set/cleared.+static inline bool mi_bchunk_is_xsetN(mi_xset_t set, const mi_bchunk_t* chunk, size_t cidx, size_t n) {+ mi_assert_internal(cidx + n <= MI_BCHUNK_BITS);+ mi_assert_internal(n>0);+ if (n==0) return true;+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ if (n==1) { return mi_bfield_atomic_is_xset(set, &chunk->bfields[i], idx); }+ if (idx + n <= MI_BFIELD_BITS) { return mi_bfield_atomic_is_xset_mask(set, &chunk->bfields[i], mi_bfield_mask(n, idx)); }+ return mi_bchunk_is_xsetNC(set, chunk, i, idx, n);+}+++// ------- mi_bchunk_try_clear ---------------------------------------++// Clear `0 < n <= MI_BITFIELD_BITS`. Can cross over a bfield boundary.+static inline bool mi_bchunk_try_clearNX(mi_bchunk_t* chunk, size_t cidx, size_t n, bool* pmaybe_all_clear) {+ mi_assert_internal(cidx < MI_BCHUNK_BITS);+ mi_assert_internal(n <= MI_BFIELD_BITS);+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ if mi_likely(idx + n <= MI_BFIELD_BITS) {+ // within one field+ return mi_bfield_atomic_try_clear_mask(&chunk->bfields[i], mi_bfield_mask(n, idx), pmaybe_all_clear);+ }+ else {+ // spanning two fields (todo: use double-word atomic ops?)+ const size_t m = MI_BFIELD_BITS - idx; // bits to clear in the first field+ mi_assert_internal(m < n);+ mi_assert_internal(i < MI_BCHUNK_FIELDS - 1);+ bool field1_is_clear;+ if (!mi_bfield_atomic_try_clear_mask(&chunk->bfields[i], mi_bfield_mask(m, idx), &field1_is_clear)) return false;+ // try the second field as well+ mi_assert_internal(n - m > 0);+ mi_assert_internal(n - m < MI_BFIELD_BITS);+ bool field2_is_clear;+ if (!mi_bfield_atomic_try_clear_mask(&chunk->bfields[i+1], mi_bfield_mask(n - m, 0), &field2_is_clear)) {+ // we failed to clear the second field, restore the first one+ mi_bfield_atomic_set_mask(&chunk->bfields[i], mi_bfield_mask(m, idx), NULL);+ return false;+ }+ if (pmaybe_all_clear != NULL) { *pmaybe_all_clear = field1_is_clear && field2_is_clear; }+ return true;+ }+}++// Clear a full aligned bfield.+// static inline bool mi_bchunk_try_clearX(mi_bchunk_t* chunk, size_t cidx, bool* pmaybe_all_clear) {+// mi_assert_internal(cidx < MI_BCHUNK_BITS);+// mi_assert_internal((cidx%MI_BFIELD_BITS) == 0);+// const size_t i = cidx / MI_BFIELD_BITS;+// return mi_bfield_atomic_try_clearX(&chunk->bfields[i], pmaybe_all_clear);+// }++// Try to atomically clear a sequence of `n` bits within a chunk.+// Returns true if all bits transitioned from 1 to 0,+// and false otherwise leaving all bit fields as is.+// Note: this is the complex one as we need to unwind partial atomic operations if we fail halfway..+// `maybe_all_clear` is set to `true` if all the bfields involved become zero.+mi_decl_noinline static bool mi_bchunk_try_clearNC(mi_bchunk_t* chunk, size_t cidx, size_t n, bool* pmaybe_all_clear) {+ mi_assert_internal(cidx + n <= MI_BCHUNK_BITS);+ mi_assert_internal(n>0);+ if (pmaybe_all_clear != NULL) { *pmaybe_all_clear = true; }+ if (n==0) return true;++ // first field+ const size_t start_idx = cidx % MI_BFIELD_BITS;+ const size_t start_field = cidx / MI_BFIELD_BITS;+ size_t field = start_field;+ size_t m = MI_BFIELD_BITS - start_idx; // m are the bits to clear in this field+ if (m > n) { m = n; }+ mi_assert_internal(start_idx + m <= MI_BFIELD_BITS);+ mi_assert_internal(start_field < MI_BCHUNK_FIELDS);+ const mi_bfield_t mask_start = mi_bfield_mask(m, start_idx);+ bool maybe_all_clear;+ if (!mi_bfield_atomic_try_clear_mask(&chunk->bfields[field], mask_start, &maybe_all_clear)) return false;++ // done?+ mi_assert_internal(m <= n);+ n -= m;++ // continue with mid fields and last field: if these fail we need to recover by unsetting previous fields+ // mid fields?+ while (n >= MI_BFIELD_BITS) {+ field++;+ mi_assert_internal(field < MI_BCHUNK_FIELDS);+ bool field_is_clear;+ if (!mi_bfield_atomic_try_clearX(&chunk->bfields[field], &field_is_clear)) goto restore;+ maybe_all_clear = maybe_all_clear && field_is_clear;+ n -= MI_BFIELD_BITS;+ }++ // last field?+ if (n > 0) {+ mi_assert_internal(n < MI_BFIELD_BITS);+ field++;+ mi_assert_internal(field < MI_BCHUNK_FIELDS);+ const mi_bfield_t mask_end = mi_bfield_mask(n, 0);+ bool field_is_clear;+ if (!mi_bfield_atomic_try_clear_mask(&chunk->bfields[field], mask_end, &field_is_clear)) goto restore;+ maybe_all_clear = maybe_all_clear && field_is_clear;+ }++ if (pmaybe_all_clear != NULL) { *pmaybe_all_clear = maybe_all_clear; }+ return true;++restore:+ // `field` is the index of the field that failed to set atomically; we need to restore all previous fields+ mi_assert_internal(field > start_field);+ while( field > start_field) {+ field--;+ if (field == start_field) {+ mi_bfield_atomic_set_mask(&chunk->bfields[field], mask_start, NULL);+ }else {- // on to the next bit range-#ifdef MI_HAVE_FAST_BITSCAN- mi_assert_internal(mapm != 0);- const size_t shift = (count == 1 ? 1 : (MI_INTPTR_BITS - mi_clz(mapm) - bitidx));- mi_assert_internal(shift > 0 && shift <= count);-#else- const size_t shift = 1;+ mi_bfield_atomic_setX(&chunk->bfields[field], NULL); // mid-field: set all bits again+ }+ }+ return false;+}+++static inline bool mi_bchunk_try_clearN(mi_bchunk_t* chunk, size_t cidx, size_t n, bool* maybe_all_clear) {+ mi_assert_internal(n>0);+ // if (n==MI_BFIELD_BITS) return mi_bchunk_try_clearX(chunk, cidx, maybe_all_clear);+ if (n<=MI_BFIELD_BITS) return mi_bchunk_try_clearNX(chunk, cidx, n, maybe_all_clear);+ return mi_bchunk_try_clearNC(chunk, cidx, n, maybe_all_clear);+}+++// ------- mi_bchunk_try_find_and_clear ---------------------------------------++#if MI_OPT_SIMD && defined(__AVX2__)+mi_decl_maybe_unused static inline __m256i mi_mm256_zero(void) {+ return _mm256_setzero_si256();+}+mi_decl_maybe_unused static inline __m256i mi_mm256_ones(void) {+ return _mm256_set1_epi64x(~0);+}+mi_decl_maybe_unused static inline bool mi_mm256_is_ones(__m256i vec) {+ return _mm256_testc_si256(vec, _mm256_cmpeq_epi32(vec, vec));+}+mi_decl_maybe_unused static inline bool mi_mm256_is_zero( __m256i vec) {+ return _mm256_testz_si256(vec,vec);+}#endif- bitidx += shift;- m <<= shift;++static inline bool mi_bchunk_try_find_and_clear_at(mi_bchunk_t* chunk, size_t chunk_idx, size_t* pidx) {+ mi_assert_internal(chunk_idx < MI_BCHUNK_FIELDS);+ // note: this must be acquire (and not relaxed), or otherwise the AVX code below can loop forever+ // as the compiler won't reload the registers vec1 and vec2 from memory again.+ const mi_bfield_t b = mi_atomic_load_acquire(&chunk->bfields[chunk_idx]);+ size_t idx;+ if (mi_bfield_find_least_bit(b, &idx)) { // find the least bit+ if mi_likely(mi_bfield_atomic_try_clear_mask_of(&chunk->bfields[chunk_idx], mi_bfield_mask(1,idx), b, NULL)) { // clear it atomically+ *pidx = (chunk_idx*MI_BFIELD_BITS) + idx;+ mi_assert_internal(*pidx < MI_BCHUNK_BITS);+ return true;}}- // no bits foundreturn false;}-// Find `count` bits of 0 and set them to 1 atomically; returns `true` on success.-// Starts at idx, and wraps around to search in all `bitmap_fields` fields.-// `count` can be at most MI_BITMAP_FIELD_BITS and will never cross fields.-bool _mi_bitmap_try_find_from_claim(mi_bitmap_t bitmap, const size_t bitmap_fields, const size_t start_field_idx, const size_t count, mi_bitmap_index_t* bitmap_idx) {- size_t idx = start_field_idx;- for (size_t visited = 0; visited < bitmap_fields; visited++, idx++) {- if (idx >= bitmap_fields) { idx = 0; } // wrap- if (_mi_bitmap_try_find_claim_field(bitmap, idx, count, bitmap_idx)) {+// Find least 1-bit in a chunk and try to clear it atomically+// set `*pidx` to the bit index (0 <= *pidx < MI_BCHUNK_BITS) on success.+// This is used to find free slices and abandoned pages and should be efficient.+// todo: try neon version+static inline bool mi_bchunk_try_find_and_clear(mi_bchunk_t* chunk, size_t* pidx) {+ #if MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==256)+ for(int tries=0; tries<4; tries++) { // paranoia: at most 4 tries+ const __m256i vec = _mm256_load_si256((const __m256i*)chunk->bfields);+ const __m256i vcmp = _mm256_cmpeq_epi64(vec, mi_mm256_zero()); // (elem64 == 0 ? 0xFF : 0)+ const uint32_t mask = ~_mm256_movemask_epi8(vcmp); // mask of most significant bit of each byte (so each 8 bits are all set or clear)+ // mask is inverted, so each 8-bits is 0xFF iff the corresponding elem64 has a bit set (and thus can be cleared)+ if (mask==0) return false;+ mi_assert_internal((_tzcnt_u32(mask)%8) == 0); // tzcnt == 0, 8, 16, or 24+ const size_t chunk_idx = _tzcnt_u32(mask) / 8;+ if (mi_bchunk_try_find_and_clear_at(chunk, chunk_idx, pidx)) return true;+ // try again+ // note: there must be an atomic release/acquire in between or otherwise the registers may not be reloaded+ // we add an explicit memory barrier as older gcc compilers do not reload the registers even with an atomic acquire (issue #1206)+ #if defined(__GNUC__)+ __asm __volatile ("" : : "g"(chunk) : "memory");+ #endif+ }+ #elif MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==512)+ for(int tries=0; tries<4; tries++) { // paranoia: at most 4 tries+ size_t chunk_idx = 0;+ #if 0+ // one vector at a time+ __m256i vec = _mm256_load_si256((const __m256i*)chunk->bfields);+ if (mi_mm256_is_zero(vec)) {+ chunk_idx += 4;+ vec = _mm256_load_si256(((const __m256i*)chunk->bfields) + 1);+ }+ const __m256i vcmp = _mm256_cmpeq_epi64(vec, mi_mm256_zero()); // (elem64 == 0 ? 0xFF : 0)+ const uint32_t mask = ~_mm256_movemask_epi8(vcmp); // mask of most significant bit of each byte (so each 8 bits are all set or clear)+ // mask is inverted, so each 8-bits is 0xFF iff the corresponding elem64 has a bit set (and thus can be cleared)+ if (mask==0) return false;+ mi_assert_internal((_tzcnt_u32(mask)%8) == 0); // tzcnt == 0, 8, 16, or 24+ chunk_idx += _tzcnt_u32(mask) / 8;+ #else+ // a cache line is 64b so we can just as well load all at the same time+ const __m256i vec1 = _mm256_load_si256((const __m256i*)chunk->bfields);+ const __m256i vec2 = _mm256_load_si256(((const __m256i*)chunk->bfields)+1);+ const __m256i cmpv = mi_mm256_zero();+ const __m256i vcmp1 = _mm256_cmpeq_epi64(vec1, cmpv); // (elem64 == 0 ? 0xFF : 0)+ const __m256i vcmp2 = _mm256_cmpeq_epi64(vec2, cmpv); // (elem64 == 0 ? 0xFF : 0)+ const uint32_t mask1 = ~_mm256_movemask_epi8(vcmp1); // mask of most significant bit of each byte (so each 8 bits are all set or clear)+ const uint32_t mask2 = ~_mm256_movemask_epi8(vcmp2); // mask of most significant bit of each byte (so each 8 bits are all set or clear)+ const uint64_t mask = ((uint64_t)mask2 << 32) | mask1;+ // mask is inverted, so each 8-bits is 0xFF iff the corresponding elem64 has a bit set (and thus can be cleared)+ if (mask==0) return false;+ mi_assert_internal((_tzcnt_u64(mask)%8) == 0); // tzcnt == 0, 8, 16, 24 , ..+ chunk_idx = mi_ctz(mask) / 8;+ #endif+ if (mi_bchunk_try_find_and_clear_at(chunk, chunk_idx, pidx)) return true;+ // try again+ // note: there must be an atomic release/acquire in between or otherwise the registers may not be reloaded+ // we add an explicit memory barrier as older gcc compilers do not reload the registers even with an atomic acquire (issue #1206)+ #if defined(__GNUC__)+ __asm __volatile ("" : : "g"(chunk) : "memory");+ #endif+ }+ #elif MI_OPT_SIMD && (MI_BCHUNK_BITS==512) && MI_ARCH_ARM64+ for(int tries=0; tries<4; tries++) { // paranoia: at most 4 tries+ // a cache line is 64b so we can just as well load all at the same time (?)+ const uint64x2_t vzero1_lo = vceqzq_u64(vld1q_u64((uint64_t*)chunk->bfields)); // 2x64 bit is_zero+ const uint64x2_t vzero1_hi = vceqzq_u64(vld1q_u64((uint64_t*)chunk->bfields + 2)); // 2x64 bit is_zero+ const uint64x2_t vzero2_lo = vceqzq_u64(vld1q_u64((uint64_t*)chunk->bfields + 4)); // 2x64 bit is_zero+ const uint64x2_t vzero2_hi = vceqzq_u64(vld1q_u64((uint64_t*)chunk->bfields + 6)); // 2x64 bit is_zero+ const uint32x4_t vzero1 = vuzp1q_u32(vreinterpretq_u32_u64(vzero1_lo),vreinterpretq_u32_u64(vzero1_hi)); // unzip even elements: narrow to 4x32 bit is_zero ()+ const uint32x4_t vzero2 = vuzp1q_u32(vreinterpretq_u32_u64(vzero2_lo),vreinterpretq_u32_u64(vzero2_hi)); // unzip even elements: narrow to 4x32 bit is_zero ()+ const uint32x4_t vzero1x = vreinterpretq_u32_u64(vshrq_n_u64(vreinterpretq_u64_u32(vzero1), 24)); // shift-right 2x32bit elem by 24: lo 16 bits contain the 2 lo bytes+ const uint32x4_t vzero2x = vreinterpretq_u32_u64(vshrq_n_u64(vreinterpretq_u64_u32(vzero2), 24));+ const uint16x8_t vzero12 = vreinterpretq_u16_u32(vuzp1q_u32(vzero1x,vzero2x)); // unzip even 32-bit elements into one vector+ const uint8x8_t vzero = vmovn_u16(vzero12); // narrow the bottom 16-bits+ const uint64_t mask = ~vget_lane_u64(vreinterpret_u64_u8(vzero), 0); // 1 byte for each bfield (0xFF => bfield has a bit set)+ if (mask==0) return false;+ mi_assert_internal((mi_ctz(mask)%8) == 0); // tzcnt == 0, 8, 16, 24 , ..+ const size_t chunk_idx = mi_ctz(mask) / 8;+ if (mi_bchunk_try_find_and_clear_at(chunk, chunk_idx, pidx)) return true;+ // try again+ // note: there must be an atomic release/acquire in between or otherwise the registers may not be reloaded+ // we add an explicit memory barrier as older gcc compilers do not reload the registers even with an atomic acquire (issue #1206)+ #if defined(__GNUC__)+ __asm __volatile ("" : : "g"(chunk) : "memory");+ #endif+ }+ #else+ for (int i = 0; i < MI_BCHUNK_FIELDS; i++) {+ if (mi_bchunk_try_find_and_clear_at(chunk, i, pidx)) return true;+ }+ #endif+ return false;+}++static inline bool mi_bchunk_try_find_and_clear_1(mi_bchunk_t* chunk, size_t n, size_t* pidx) {+ mi_assert_internal(n==1); MI_UNUSED(n);+ return mi_bchunk_try_find_and_clear(chunk, pidx);+}++mi_decl_maybe_unused static inline bool mi_bchunk_try_find_and_clear8_at(mi_bchunk_t* chunk, size_t chunk_idx, size_t* pidx) {+ const mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[chunk_idx]);+ // has_set8 has low bit in each byte set if the byte in x == 0xFF+ const mi_bfield_t has_set8 =+ ((~b - MI_BFIELD_LO_BIT8) & // high bit set if byte in x is 0xFF or < 0x7F+ (b & MI_BFIELD_HI_BIT8)) // high bit set if byte in x is >= 0x80+ >> 7; // shift high bit to low bit+ size_t idx;+ if (mi_bfield_find_least_bit(has_set8, &idx)) { // find least 1-bit+ mi_assert_internal(idx <= (MI_BFIELD_BITS - 8));+ mi_assert_internal((idx%8)==0);+ if mi_likely(mi_bfield_atomic_try_clear_mask_of(&chunk->bfields[chunk_idx], (mi_bfield_t)0xFF << idx, b, NULL)) { // unset the byte atomically+ *pidx = (chunk_idx*MI_BFIELD_BITS) + idx;+ mi_assert_internal(*pidx + 8 <= MI_BCHUNK_BITS);return true;}}return false;}-// Like _mi_bitmap_try_find_from_claim but with an extra predicate that must be fullfilled-bool _mi_bitmap_try_find_from_claim_pred(mi_bitmap_t bitmap, const size_t bitmap_fields,- const size_t start_field_idx, const size_t count,- mi_bitmap_pred_fun_t pred_fun, void* pred_arg,- mi_bitmap_index_t* bitmap_idx) {- size_t idx = start_field_idx;- for (size_t visited = 0; visited < bitmap_fields; visited++, idx++) {- if (idx >= bitmap_fields) idx = 0; // wrap- if (_mi_bitmap_try_find_claim_field(bitmap, idx, count, bitmap_idx)) {- if (pred_fun == NULL || pred_fun(*bitmap_idx, pred_arg)) {+// find least aligned byte in a chunk with all bits set, and try unset it atomically+// set `*pidx` to its bit index (0 <= *pidx < MI_BCHUNK_BITS) on success.+// Used to find medium size pages in the free blocks.+// todo: try neon version+static mi_decl_noinline bool mi_bchunk_try_find_and_clear8(mi_bchunk_t* chunk, size_t* pidx) {+ #if MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==512)+ while (true) {+ // since a cache-line is 64b, load all at once+ const __m256i vec1 = _mm256_load_si256((const __m256i*)chunk->bfields);+ const __m256i vec2 = _mm256_load_si256((const __m256i*)chunk->bfields+1);+ const __m256i cmpv = mi_mm256_ones();+ const __m256i vcmp1 = _mm256_cmpeq_epi8(vec1, cmpv); // (byte == ~0 ? 0xFF : 0)+ const __m256i vcmp2 = _mm256_cmpeq_epi8(vec2, cmpv); // (byte == ~0 ? 0xFF : 0)+ const uint32_t mask1 = _mm256_movemask_epi8(vcmp1); // mask of most significant bit of each byte+ const uint32_t mask2 = _mm256_movemask_epi8(vcmp2); // mask of most significant bit of each byte+ const uint64_t mask = ((uint64_t)mask2 << 32) | mask1;+ // mask is inverted, so each bit is 0xFF iff the corresponding byte has a bit set (and thus can be cleared)+ if (mask==0) return false;+ const size_t bidx = _tzcnt_u64(mask); // byte-idx of the byte in the chunk+ const size_t chunk_idx = bidx / 8;+ const size_t idx = (bidx % 8)*8;+ mi_assert_internal(chunk_idx < MI_BCHUNK_FIELDS);+ if mi_likely(mi_bfield_atomic_try_clear8(&chunk->bfields[chunk_idx], idx, NULL)) { // clear it atomically+ *pidx = (chunk_idx*MI_BFIELD_BITS) + idx;+ mi_assert_internal(*pidx + 8 <= MI_BCHUNK_BITS);+ return true;+ }+ // try again+ // note: there must be an atomic release/acquire in between or otherwise the registers may not be reloaded }+ }+ #else+ for (int i = 0; i < MI_BCHUNK_FIELDS; i++) {+ if (mi_bchunk_try_find_and_clear8_at(chunk, i, pidx)) return true;+ }+ return false;+ #endif+}++static inline bool mi_bchunk_try_find_and_clear_8(mi_bchunk_t* chunk, size_t n, size_t* pidx) {+ mi_assert_internal(n==8); MI_UNUSED(n);+ return mi_bchunk_try_find_and_clear8(chunk, pidx);+}+++// find a sequence of `n` bits in a chunk with `0 < n <= MI_BFIELD_BITS` with all bits set,+// and try to clear them atomically.+// set `*pidx` to its bit index (0 <= *pidx <= MI_BCHUNK_BITS - n) on success.+// will cross bfield boundaries.+mi_decl_noinline static bool mi_bchunk_try_find_and_clearNX(mi_bchunk_t* chunk, size_t n, size_t* pidx) {+ if (n == 0 || n > MI_BFIELD_BITS) return false;+ const mi_bfield_t mask = mi_bfield_mask(n, 0);+ // for all fields in the chunk+ for (int i = 0; i < MI_BCHUNK_FIELDS; i++) {+ mi_bfield_t b0 = mi_atomic_load_relaxed(&chunk->bfields[i]);+ mi_bfield_t b = b0;+ size_t idx;++ // is there a range inside the field?+ while (mi_bfield_find_least_bit(b, &idx)) { // find least 1-bit+ if (idx + n > MI_BFIELD_BITS) break; // too short: maybe cross over, or continue with the next field++ const size_t bmask = mask<<idx;+ mi_assert_internal(bmask>>idx == mask);+ if ((b&bmask) == bmask) { // found a match with all bits set, try clearing atomically+ if mi_likely(mi_bfield_atomic_try_clear_mask_of(&chunk->bfields[i], bmask, b0, NULL)) {+ *pidx = (i*MI_BFIELD_BITS) + idx;+ mi_assert_internal(*pidx < MI_BCHUNK_BITS);+ mi_assert_internal(*pidx + n <= MI_BCHUNK_BITS);+ return true;+ }+ else {+ // if we failed to atomically commit, reload b and try again from the start+ b = b0 = mi_atomic_load_acquire(&chunk->bfields[i]);+ }+ }+ else {+ // advance by clearing the least run of ones, for example, with n>=4, idx=2:+ // b = 1111 1101 1010 1100+ // .. + (1<<idx) = 1111 1101 1011 0000+ // .. & b = 1111 1101 1010 0000+ b = b & (b + (mi_bfield_one() << idx));+ }+ }++ // check if we can cross into the next bfield+ if (b!=0 && i < MI_BCHUNK_FIELDS-1) {+ const size_t post = mi_bfield_clz(~b);+ if (post > 0) {+ const size_t pre = mi_bfield_ctz(~mi_atomic_load_relaxed(&chunk->bfields[i+1]));+ if (post + pre >= n) {+ // it fits -- try to claim it atomically+ const size_t cidx = (i*MI_BFIELD_BITS) + (MI_BFIELD_BITS - post);+ if (mi_bchunk_try_clearNX(chunk, cidx, n, NULL)) {+ // we cleared all atomically+ *pidx = cidx;+ mi_assert_internal(*pidx < MI_BCHUNK_BITS);+ mi_assert_internal(*pidx + n <= MI_BCHUNK_BITS);+ return true;+ }+ }+ }+ }+ }+ return false;+}++// find a sequence of `n` bits in a chunk with `n <= MI_BCHUNK_BITS` with all bits set,+// and try to clear them atomically.+// set `*pidx` to its bit index (0 <= *pidx <= MI_BCHUNK_BITS - n) on success.+// This can cross bfield boundaries.+static mi_decl_noinline bool mi_bchunk_try_find_and_clearNC(mi_bchunk_t* chunk, size_t n, size_t* pidx) {+ if (n == 0 || n > MI_BCHUNK_BITS) return false; // cannot be more than a chunk++ // we first scan ahead to see if there is a range of `n` set bits, and only then try to clear atomically+ mi_assert_internal(n>0);+ const size_t skip_count = (n-1)/MI_BFIELD_BITS;+ size_t cidx;+ for (size_t i = 0; i < MI_BCHUNK_FIELDS - skip_count; i++)+ {+ size_t m = n; // bits to go++ // first field+ mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[i]);+ size_t ones = mi_bfield_clz(~b);++ cidx = (i*MI_BFIELD_BITS) + (MI_BFIELD_BITS - ones); // start index+ if (ones >= m) {+ // we found enough bits already!+ m = 0;+ }+ else if (ones > 0) {+ // keep scanning further fields until we have enough bits+ m -= ones;+ size_t j = 1; // field count from i+ while (i+j < MI_BCHUNK_FIELDS) {+ mi_assert_internal(m > 0);+ b = mi_atomic_load_relaxed(&chunk->bfields[i+j]);+ ones = mi_bfield_ctz(~b);+ if (ones >= m) {+ // we found enough bits+ m = 0;+ break;+ }+ else if (ones == MI_BFIELD_BITS) {+ // not enough yet, proceed to the next field+ j++;+ m -= MI_BFIELD_BITS;+ }+ else {+ // the range was not enough, start from scratch+ i = i + j - 1; // no need to re-scan previous fields, except the last one (with clz this time)+ mi_assert_internal(m>0);+ break;+ }+ }+ }++ // did we find a range?+ if (m==0) {+ if (mi_bchunk_try_clearN(chunk, cidx, n, NULL)) {+ // we cleared all atomically+ *pidx = cidx;+ mi_assert_internal(*pidx < MI_BCHUNK_BITS);+ mi_assert_internal(*pidx + n <= MI_BCHUNK_BITS);return true;}- // predicate returned false, unclaim and look further- _mi_bitmap_unclaim(bitmap, bitmap_fields, count, *bitmap_idx);+ // note: if we fail for a small `n` on the first field, we don't rescan that field (as `i` is incremented)}+ // otherwise continue searching}return false;}-// Set `count` bits at `bitmap_idx` to 0 atomically-// Returns `true` if all `count` bits were 1 previously.-bool _mi_bitmap_unclaim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- const size_t idx = mi_bitmap_index_field(bitmap_idx);- const size_t bitidx = mi_bitmap_index_bit_in_field(bitmap_idx);- const size_t mask = mi_bitmap_mask_(count, bitidx);- mi_assert_internal(bitmap_fields > idx); MI_UNUSED(bitmap_fields);- // mi_assert_internal((bitmap[idx] & mask) == mask);- const size_t prev = mi_atomic_and_acq_rel(&bitmap[idx], ~mask);- return ((prev & mask) == mask);-}---// Set `count` bits at `bitmap_idx` to 1 atomically-// Returns `true` if all `count` bits were 0 previously. `any_zero` is `true` if there was at least one zero bit.-bool _mi_bitmap_claim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* any_zero) {- const size_t idx = mi_bitmap_index_field(bitmap_idx);- const size_t bitidx = mi_bitmap_index_bit_in_field(bitmap_idx);- const size_t mask = mi_bitmap_mask_(count, bitidx);- mi_assert_internal(bitmap_fields > idx); MI_UNUSED(bitmap_fields);- //mi_assert_internal(any_zero != NULL || (bitmap[idx] & mask) == 0);- size_t prev = mi_atomic_or_acq_rel(&bitmap[idx], mask);- if (any_zero != NULL) { *any_zero = ((prev & mask) != mask); }- return ((prev & mask) == 0);-}--// Returns `true` if all `count` bits were 1. `any_ones` is `true` if there was at least one bit set to one.-static bool mi_bitmap_is_claimedx(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* any_ones) {- const size_t idx = mi_bitmap_index_field(bitmap_idx);- const size_t bitidx = mi_bitmap_index_bit_in_field(bitmap_idx);- const size_t mask = mi_bitmap_mask_(count, bitidx);- mi_assert_internal(bitmap_fields > idx); MI_UNUSED(bitmap_fields);- const size_t field = mi_atomic_load_relaxed(&bitmap[idx]);- if (any_ones != NULL) { *any_ones = ((field & mask) != 0); }- return ((field & mask) == mask);-}--// Try to set `count` bits at `bitmap_idx` from 0 to 1 atomically.-// Returns `true` if successful when all previous `count` bits were 0.-bool _mi_bitmap_try_claim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- const size_t idx = mi_bitmap_index_field(bitmap_idx);- const size_t bitidx = mi_bitmap_index_bit_in_field(bitmap_idx);- const size_t mask = mi_bitmap_mask_(count, bitidx);- mi_assert_internal(bitmap_fields > idx); MI_UNUSED(bitmap_fields);- size_t expected = mi_atomic_load_relaxed(&bitmap[idx]);- do {- if ((expected & mask) != 0) return false;- }- while (!mi_atomic_cas_strong_acq_rel(&bitmap[idx], &expected, expected | mask));- mi_assert_internal((expected & mask) == 0);+++// ------- mi_bchunk_clear_once_set ---------------------------------------++static inline void mi_bchunk_clear_once_set(mi_bchunk_t* chunk, size_t cidx) {+ mi_assert_internal(cidx < MI_BCHUNK_BITS);+ const size_t i = cidx / MI_BFIELD_BITS;+ const size_t idx = cidx % MI_BFIELD_BITS;+ mi_bfield_atomic_clear_once_set(&chunk->bfields[i], idx);+}+++// ------- mi_bitmap_all_are_clear ---------------------------------------+++// are all bits in a bitmap chunk clear?+static inline bool mi_bchunk_all_are_clear_relaxed(mi_bchunk_t* chunk) {+ #if MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==256)+ const __m256i vec = _mm256_load_si256((const __m256i*)chunk->bfields);+ return mi_mm256_is_zero(vec);+ #elif MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==512)+ // a 64b cache-line contains the entire chunk anyway so load both at once+ const __m256i vec1 = _mm256_load_si256((const __m256i*)chunk->bfields);+ const __m256i vec2 = _mm256_load_si256(((const __m256i*)chunk->bfields)+1);+ return (mi_mm256_is_zero(_mm256_or_si256(vec1,vec2)));+ #elif MI_OPT_SIMD && (MI_BCHUNK_BITS==512) && MI_ARCH_ARM64+ const uint64x2_t v0 = vld1q_u64((uint64_t*)chunk->bfields);+ const uint64x2_t v1 = vld1q_u64((uint64_t*)chunk->bfields + 2);+ const uint64x2_t v2 = vld1q_u64((uint64_t*)chunk->bfields + 4);+ const uint64x2_t v3 = vld1q_u64((uint64_t*)chunk->bfields + 6);+ const uint64x2_t v = vorrq_u64(vorrq_u64(v0,v1),vorrq_u64(v2,v3));+ return (vmaxvq_u32(vreinterpretq_u32_u64(v)) == 0);+ #else+ for (int i = 0; i < MI_BCHUNK_FIELDS; i++) {+ if (mi_atomic_load_relaxed(&chunk->bfields[i]) != 0) return false;+ }+ return true;+ #endif+}++// are all bits in a bitmap chunk set?+static inline bool mi_bchunk_all_are_set_relaxed(mi_bchunk_t* chunk) {+#if MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==256)+ const __m256i vec = _mm256_load_si256((const __m256i*)chunk->bfields);+ return mi_mm256_is_ones(vec);+#elif MI_OPT_SIMD && defined(__AVX2__) && (MI_BCHUNK_BITS==512)+ // a 64b cache-line contains the entire chunk anyway so load both at once+ const __m256i vec1 = _mm256_load_si256((const __m256i*)chunk->bfields);+ const __m256i vec2 = _mm256_load_si256(((const __m256i*)chunk->bfields)+1);+ return (mi_mm256_is_ones(_mm256_and_si256(vec1, vec2)));+#elif MI_OPT_SIMD && (MI_BCHUNK_BITS==512) && MI_ARCH_ARM64+ const uint64x2_t v0 = vld1q_u64((uint64_t*)chunk->bfields);+ const uint64x2_t v1 = vld1q_u64((uint64_t*)chunk->bfields + 2);+ const uint64x2_t v2 = vld1q_u64((uint64_t*)chunk->bfields + 4);+ const uint64x2_t v3 = vld1q_u64((uint64_t*)chunk->bfields + 6);+ const uint64x2_t v = vandq_u64(vandq_u64(v0,v1),vandq_u64(v2,v3));+ return (vminvq_u32(vreinterpretq_u32_u64(v)) == 0xFFFFFFFFUL);+#else+ for (int i = 0; i < MI_BCHUNK_FIELDS; i++) {+ if (~mi_atomic_load_relaxed(&chunk->bfields[i]) != 0) return false;+ }return true;+#endif}-bool _mi_bitmap_is_claimed(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- return mi_bitmap_is_claimedx(bitmap, bitmap_fields, count, bitmap_idx, NULL);+static bool mi_bchunk_bsr(mi_bchunk_t* chunk, size_t* pidx) {+ for (size_t i = MI_BCHUNK_FIELDS; i > 0; ) {+ i--;+ mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[i]);+ size_t idx;+ if (mi_bsr(b, &idx)) {+ *pidx = (i*MI_BFIELD_BITS) + idx;+ return true;+ }+ }+ return false;}-bool _mi_bitmap_is_any_claimed(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- bool any_ones;- mi_bitmap_is_claimedx(bitmap, bitmap_fields, count, bitmap_idx, &any_ones);- return any_ones;+static size_t mi_bchunk_popcount(mi_bchunk_t* chunk) {+ size_t popcount = 0;+ for (size_t i = 0; i < MI_BCHUNK_FIELDS; i++) {+ const mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[i]);+ popcount += mi_bfield_popcount(b);+ }+ return popcount;}-//---------------------------------------------------------------------------// the `_across` functions work on bitmaps where sequences can cross over-// between the fields. This is used in arena allocation-//--------------------------------------------------------------------------+/* --------------------------------------------------------------------------------+ bitmap chunkmap+-------------------------------------------------------------------------------- */-// Try to atomically claim a sequence of `count` bits starting from the field-// at `idx` in `bitmap` and crossing into subsequent fields. Returns `true` on success.-// Only needs to consider crossing into the next fields (see `mi_bitmap_try_find_from_claim_across`)-static bool mi_bitmap_try_find_claim_field_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t idx, const size_t count, const size_t retries, mi_bitmap_index_t* bitmap_idx)+static void mi_bitmap_chunkmap_set(mi_bitmap_t* bitmap, size_t chunk_idx) {+ mi_assert(chunk_idx < mi_bitmap_chunk_count(bitmap));+ mi_bchunk_set(&bitmap->chunkmap, chunk_idx, NULL);+}++static bool mi_bitmap_chunkmap_try_clear(mi_bitmap_t* bitmap, size_t chunk_idx) {+ mi_assert(chunk_idx < mi_bitmap_chunk_count(bitmap));+ // check if the corresponding chunk is all clear+ if (!mi_bchunk_all_are_clear_relaxed(&bitmap->chunks[chunk_idx])) return false;+ // clear the chunkmap bit+ mi_bchunk_clear(&bitmap->chunkmap, chunk_idx, NULL);+ // .. but a concurrent set may have happened in between our all-clear test and the clearing of the+ // bit in the mask. We check again to catch this situation.+ if (!mi_bchunk_all_are_clear_relaxed(&bitmap->chunks[chunk_idx])) {+ mi_bchunk_set(&bitmap->chunkmap, chunk_idx, NULL);+ return false;+ }+ return true;+}+++/* --------------------------------------------------------------------------------+ bitmap+-------------------------------------------------------------------------------- */++size_t mi_bitmap_size(size_t bit_count, size_t* pchunk_count) {+ mi_assert_internal((bit_count % MI_BCHUNK_BITS) == 0);+ bit_count = _mi_align_up(bit_count, MI_BCHUNK_BITS);+ mi_assert_internal(bit_count <= MI_BITMAP_MAX_BIT_COUNT);+ mi_assert_internal(bit_count > 0);+ const size_t chunk_count = bit_count / MI_BCHUNK_BITS;+ mi_assert_internal(chunk_count >= 1);+ const size_t size = offsetof(mi_bitmap_t,chunks) + (chunk_count * MI_BCHUNK_SIZE);+ mi_assert_internal( (size%MI_BCHUNK_SIZE) == 0 );+ if (pchunk_count != NULL) { *pchunk_count = chunk_count; }+ return size;+}+++// initialize a bitmap to all unset; avoid a mem_zero if `already_zero` is true+// returns the size of the bitmap+size_t mi_bitmap_init(mi_bitmap_t* bitmap, size_t bit_count, bool already_zero) {+ size_t chunk_count;+ const size_t size = mi_bitmap_size(bit_count, &chunk_count);+ if (!already_zero) {+ _mi_memzero_aligned(bitmap, size);+ }+ mi_atomic_store_release(&bitmap->chunk_count, chunk_count);+ mi_assert_internal(mi_atomic_load_relaxed(&bitmap->chunk_count) <= MI_BITMAP_MAX_CHUNK_COUNT);+ return size;+}+++// Set a sequence of `n` bits in the bitmap (and can cross chunks). Not atomic so only use if local to a thread.+static void mi_bchunks_unsafe_setN(mi_bchunk_t* chunks, mi_bchunkmap_t* cmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);++ // start chunk and index+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ const size_t cidx = idx % MI_BCHUNK_BITS;+ const size_t ccount = _mi_divide_up(n, MI_BCHUNK_BITS);++ // first update the chunkmap+ mi_bchunk_setN(cmap, chunk_idx, ccount, NULL);++ // first chunk+ size_t m = MI_BCHUNK_BITS - cidx;+ if (m > n) { m = n; }+ mi_bchunk_setN(&chunks[chunk_idx], cidx, m, NULL);++ // n can be large so use memset for efficiency for all in-between chunks+ chunk_idx++;+ n -= m;+ const size_t mid_chunks = n / MI_BCHUNK_BITS;+ if (mid_chunks > 0) {+ _mi_memset(&chunks[chunk_idx], ~0, mid_chunks * MI_BCHUNK_SIZE);+ chunk_idx += mid_chunks;+ n -= (mid_chunks * MI_BCHUNK_BITS);+ }++ // last chunk+ if (n > 0) {+ mi_assert_internal(n < MI_BCHUNK_BITS);+ mi_assert_internal(chunk_idx < MI_BCHUNK_FIELDS);+ mi_bchunk_setN(&chunks[chunk_idx], 0, n, NULL);+ }+}++// Set a sequence of `n` bits in the bitmap (and can cross chunks). Not atomic so only use if local to a thread.+void mi_bitmap_unsafe_setN(mi_bitmap_t* bitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ mi_assert_internal(idx + n <= mi_bitmap_max_bits(bitmap));+ mi_bchunks_unsafe_setN(&bitmap->chunks[0], &bitmap->chunkmap, idx, n);+}+++++// ------- mi_bitmap_xset ---------------------------------------++// Set a sequence of `n` bits in the bitmap; returns `true` if atomically transitioned from 0's to 1's (or 1's to 0's).+bool mi_bitmap_setN(mi_bitmap_t* bitmap, size_t idx, size_t n, size_t* palready_set) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bitmap_max_bits(bitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return false;+ n = maxbits - idx;+ }++ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ bool were_allclear = true;+ size_t already_set = 0;+ while (n > 0) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ size_t _already_set = 0;+ were_allclear = mi_bchunk_setN(&bitmap->chunks[chunk_idx], cidx, m, &_already_set) && were_allclear;+ already_set += _already_set;+ mi_bitmap_chunkmap_set(bitmap, chunk_idx); // set afterwards+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ if (palready_set != NULL) { *palready_set = already_set; }+ return were_allclear;+}++// Clear a sequence of `n` bits in the bitmap; returns `true` if atomically transitioned from 1's to 0's.+bool mi_bitmap_clearN(mi_bitmap_t* bitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bitmap_max_bits(bitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return false;+ n = maxbits - idx;+ }++ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ bool were_allset = true;+ while (n > 0) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ bool maybe_all_clear = false;+ were_allset = mi_bchunk_clearN(&bitmap->chunks[chunk_idx], cidx, m, &maybe_all_clear) && were_allset;+ if (maybe_all_clear) { mi_bitmap_chunkmap_try_clear(bitmap, chunk_idx); }+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ return were_allset;+}++// Count bits set in a range of `n` bits.+size_t mi_bitmap_popcountN( mi_bitmap_t* bitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bitmap_max_bits(bitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return 0;+ n = maxbits - idx;+ }++ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ size_t popcount = 0;+ while (n > 0) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ popcount += mi_bchunk_popcountN(&bitmap->chunks[chunk_idx], cidx, m);+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ return popcount;+}+++// Set/clear a bit in the bitmap; returns `true` if atomically transitioned from 0 to 1 (or 1 to 0)+bool mi_bitmap_set(mi_bitmap_t* bitmap, size_t idx) {+ return mi_bitmap_setN(bitmap, idx, 1, NULL);+}++bool mi_bitmap_clear(mi_bitmap_t* bitmap, size_t idx) {+ return mi_bitmap_clearN(bitmap, idx, 1);+}++++// ------- mi_bitmap_is_xset ---------------------------------------++// Is a sequence of n bits already all set/cleared?+bool mi_bitmap_is_xsetN(mi_xset_t set, mi_bitmap_t* bitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bitmap_max_bits(bitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return false;+ n = maxbits - idx;+ }++ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ bool xset = true;+ while (n > 0 && xset) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ xset = mi_bchunk_is_xsetN(set, &bitmap->chunks[chunk_idx], cidx, m) && xset;+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ return xset;+}++bool mi_bitmap_is_all_clear(mi_bitmap_t* bitmap) {+ return mi_bitmap_is_xsetN(MI_BIT_CLEAR, bitmap, 0, mi_bitmap_max_bits(bitmap));+}++/* --------------------------------------------------------------------------------+ Iterate through a bfield+-------------------------------------------------------------------------------- */++// Cycle iteration through a bitfield. This is used to space out threads+// so there is less chance of contention. When searching for a free page we+// like to first search only the accessed part (so we reuse better). This+// high point is called the `cycle`.+//+// We then iterate through the bitfield as:+// first: [start, cycle>+// then : [0, start>+// then : [cycle, MI_BFIELD_BITS>+//+// The start is determined usually as `tseq % cycle` to have each thread+// start at a different spot.+// - We use `popcount` to improve branch prediction (maybe not needed? can we simplify?)+// - The `cycle_mask` is the part `[start, cycle>`.+#define mi_bfield_iterate(bfield,start,cycle,name_idx,SUF) { \+ mi_assert_internal(start <= cycle); \+ mi_assert_internal(start < MI_BFIELD_BITS); \+ mi_assert_internal(cycle <= MI_BFIELD_BITS); \+ const mi_bfield_t _cycle_mask##SUF = mi_bfield_mask(cycle - start, start); \+ size_t _bcount##SUF = mi_bfield_popcount(bfield); \+ mi_bfield_t _b##SUF = bfield & _cycle_mask##SUF; /* process [start, cycle> first*/\+ while(_bcount##SUF > 0) { \+ _bcount##SUF--;\+ if (_b##SUF==0) { _b##SUF = bfield & ~_cycle_mask##SUF; } /* process [0,start> + [cycle, MI_BFIELD_BITS> next */ \+ /* size_t name_idx; */ \+ const bool _found##SUF = mi_bfield_find_least_bit(_b##SUF,&name_idx); \+ _b##SUF = mi_bfield_clear_least_bit(_b##SUF); /* clear early so `continue` works */ \+ mi_assert_internal(_found##SUF); MI_UNUSED(_found##SUF); \+ { \++#define mi_bfield_iterate_end(SUF) \+ } \+ } \+}+++#define mi_bfield_cycle_iterate(bfield,tseq,cycle,name_idx,SUF) { \+ const size_t _start##SUF = (uint32_t)(tseq) % (uint32_t)(cycle); /* or: 0 to always search from the start? */\+ mi_bfield_iterate(bfield,_start##SUF,cycle,name_idx,SUF)++#define mi_bfield_cycle_iterate_end(SUF) \+ mi_bfield_iterate_end(SUF); \+}+++/* --------------------------------------------------------------------------------+ mi_bitmap_find+ (used to find free pages)+-------------------------------------------------------------------------------- */++typedef bool (mi_bitmap_visit_fun_t)(mi_bitmap_t* bitmap, size_t chunk_idx, size_t n, size_t* idx, void* arg1, void* arg2);++// Go through the bitmap and for every sequence of `n` set bits, call the visitor function.+// If it returns `true` stop the search.+static inline bool mi_bitmap_find(mi_bitmap_t* bitmap, size_t tseq, size_t n, size_t* pidx, mi_bitmap_visit_fun_t* on_find, void* arg1, void* arg2){- mi_assert_internal(bitmap_idx != NULL);-- // check initial trailing zeros- mi_bitmap_field_t* field = &bitmap[idx];- size_t map = mi_atomic_load_relaxed(field);- const size_t initial = mi_clz(map); // count of initial zeros starting at idx- mi_assert_internal(initial <= MI_BITMAP_FIELD_BITS);- if (initial == 0) return false;- if (initial >= count) return _mi_bitmap_try_find_claim_field(bitmap, idx, count, bitmap_idx); // no need to cross fields (this case won't happen for us)- if (_mi_divide_up(count - initial, MI_BITMAP_FIELD_BITS) >= (bitmap_fields - idx)) return false; // not enough entries-- // scan ahead- size_t found = initial;- size_t mask = 0; // mask bits for the final field- while(found < count) {- field++;- map = mi_atomic_load_relaxed(field);- const size_t mask_bits = (found + MI_BITMAP_FIELD_BITS <= count ? MI_BITMAP_FIELD_BITS : (count - found));- mi_assert_internal(mask_bits > 0 && mask_bits <= MI_BITMAP_FIELD_BITS);- mask = mi_bitmap_mask_(mask_bits, 0);- if ((map & mask) != 0) return false; // some part is already claimed- found += mask_bits;- }- mi_assert_internal(field < &bitmap[bitmap_fields]);-- // we found a range of contiguous zeros up to the final field; mask contains mask in the final field- // now try to claim the range atomically- mi_bitmap_field_t* const final_field = field;- const size_t final_mask = mask;- mi_bitmap_field_t* const initial_field = &bitmap[idx];- const size_t initial_idx = MI_BITMAP_FIELD_BITS - initial;- const size_t initial_mask = mi_bitmap_mask_(initial, initial_idx);-- // initial field- size_t newmap;- field = initial_field;- map = mi_atomic_load_relaxed(field);- do {- newmap = (map | initial_mask);- if ((map & initial_mask) != 0) { goto rollback; };- } while (!mi_atomic_cas_strong_acq_rel(field, &map, newmap));+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for (size_t i = 0; i < chunkmap_max; i++) {+ // and for each chunkmap entry we iterate over its bits to find the chunks+ const mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t hi;+ if (mi_bfield_find_highest_bit(cmap_entry, &hi)) {+ size_t eidx = 0;+ mi_bfield_cycle_iterate(cmap_entry, tseq%8, hi+1, eidx, Y) // reduce the tseq to 8 bins to reduce using extra memory (see `mstress`)+ {+ mi_assert_internal(eidx <= MI_BFIELD_BITS);+ const size_t chunk_idx = i*MI_BFIELD_BITS + eidx;+ mi_assert_internal(chunk_idx < mi_bitmap_chunk_count(bitmap));+ if ((*on_find)(bitmap, chunk_idx, n, pidx, arg1, arg2)) {+ return true;+ }+ }+ mi_bfield_cycle_iterate_end(Y);+ }+ }+ return false;+}+++/* --------------------------------------------------------------------------------+ Bitmap: try_find_and_claim -- used to allocate abandoned pages+ note: the compiler will fully inline the indirect function call+-------------------------------------------------------------------------------- */- // intermediate fields- while (++field < final_field) {- newmap = MI_BITMAP_FIELD_FULL;- map = 0;- if (!mi_atomic_cas_strong_acq_rel(field, &map, newmap)) { goto rollback; }+typedef struct mi_claim_fun_data_s {+ mi_arena_t* arena;+} mi_claim_fun_data_t;++static bool mi_bitmap_try_find_and_claim_visit(mi_bitmap_t* bitmap, size_t chunk_idx, size_t n, size_t* pidx, void* arg1, void* arg2)+{+ mi_assert_internal(n==1); MI_UNUSED(n);+ mi_claim_fun_t* claim_fun = (mi_claim_fun_t*)arg1;+ mi_claim_fun_data_t* claim_data = (mi_claim_fun_data_t*)arg2;+ size_t cidx;+ if mi_likely(mi_bchunk_try_find_and_clear(&bitmap->chunks[chunk_idx], &cidx)) {+ const size_t slice_index = (chunk_idx * MI_BCHUNK_BITS) + cidx;+ mi_assert_internal(slice_index < mi_bitmap_max_bits(bitmap));+ bool keep_set = true;+ if ((*claim_fun)(slice_index, claim_data->arena, &keep_set)) {+ // success!+ mi_assert_internal(!keep_set);+ *pidx = slice_index;+ return true;+ }+ else {+ // failed to claim it, set abandoned mapping again (unless the page was freed)+ if (keep_set) {+ const bool wasclear = mi_bchunk_set(&bitmap->chunks[chunk_idx], cidx, NULL);+ mi_assert_internal(wasclear); MI_UNUSED(wasclear);+ }+ }}+ else {+ // we may find that all are cleared only on a second iteration but that is ok as+ // the chunkmap is a conservative approximation.+ mi_bitmap_chunkmap_try_clear(bitmap, chunk_idx);+ }+ return false;+}- // final field- mi_assert_internal(field == final_field);- map = mi_atomic_load_relaxed(field);- do {- newmap = (map | final_mask);- if ((map & final_mask) != 0) { goto rollback; }- } while (!mi_atomic_cas_strong_acq_rel(field, &map, newmap));+// Find a set bit in the bitmap and try to atomically clear it and claim it.+// (Used to find pages in the pages_abandoned bitmaps.)+mi_decl_nodiscard bool mi_bitmap_try_find_and_claim(mi_bitmap_t* bitmap, size_t tseq, size_t* pidx,+ mi_claim_fun_t* claim, mi_arena_t* arena )+{+ mi_claim_fun_data_t claim_data = { arena };+ return mi_bitmap_find(bitmap, tseq, 1, pidx, &mi_bitmap_try_find_and_claim_visit, (void*)claim, &claim_data);+}- // claimed!- mi_stat_counter_increase(_mi_stats_main.arena_crossover_count,1);- *bitmap_idx = mi_bitmap_index_create(idx, initial_idx);++bool mi_bitmap_bsr(mi_bitmap_t* bitmap, size_t* idx) {+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for (size_t i = chunkmap_max; i > 0; ) {+ i--;+ mi_bfield_t cmap = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ if (mi_bsr(cmap,&cmap_idx)) {+ // highest chunk+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ size_t cidx;+ if (mi_bchunk_bsr(&bitmap->chunks[chunk_idx], &cidx)) {+ *idx = (chunk_idx * MI_BCHUNK_BITS) + cidx;+ return true;+ }+ }+ }+ return false;+}++// Return count of all set bits in a bitmap.+size_t mi_bitmap_popcount(mi_bitmap_t* bitmap) {+ // for all chunkmap entries+ size_t popcount = 0;+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for (size_t i = 0; i < chunkmap_max; i++) {+ mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ // for each chunk (corresponding to a set bit in a chunkmap entry)+ while (mi_bfield_foreach_bit(&cmap_entry, &cmap_idx)) {+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ // count bits in a chunk+ popcount += mi_bchunk_popcount(&bitmap->chunks[chunk_idx]);+ }+ }+ return popcount;+}++++// Clear a bit once it is set.+void mi_bitmap_clear_once_set(mi_bitmap_t* bitmap, size_t idx) {+ mi_assert_internal(idx < mi_bitmap_max_bits(bitmap));+ const size_t chunk_idx = idx / MI_BCHUNK_BITS;+ const size_t cidx = idx % MI_BCHUNK_BITS;+ mi_assert_internal(chunk_idx < mi_bitmap_chunk_count(bitmap));+ mi_bchunk_clear_once_set(&bitmap->chunks[chunk_idx], cidx);+}+++// Visit all set bits in a bitmap.+// todo: optimize further? maybe use avx512 to directly get all indices using a mask_compressstore?+bool _mi_bitmap_forall_set(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg) {+ // for all chunkmap entries+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for(size_t i = 0; i < chunkmap_max; i++) {+ mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ // for each chunk (corresponding to a set bit in a chunkmap entry)+ while (mi_bfield_foreach_bit(&cmap_entry, &cmap_idx)) {+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ // for each chunk field+ mi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];+ for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {+ const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);+ mi_bfield_t b = mi_atomic_load_relaxed(&chunk->bfields[j]);+ size_t bidx;+ while (mi_bfield_foreach_bit(&b, &bidx)) {+ const size_t idx = base_idx + bidx;+ if (!visit(idx, 1, arena, arg)) return false;+ }+ }+ }+ }return true;+}-rollback:- // roll back intermediate fields- // (we just failed to claim `field` so decrement first)- while (--field > initial_field) {- newmap = 0;- map = MI_BITMAP_FIELD_FULL;- mi_assert_internal(mi_atomic_load_relaxed(field) == map);- mi_atomic_store_release(field, newmap);- }- if (field == initial_field) { // (if we failed on the initial field, `field + 1 == initial_field`)- map = mi_atomic_load_relaxed(field);- do {- mi_assert_internal((map & initial_mask) == initial_mask);- newmap = (map & ~initial_mask);- } while (!mi_atomic_cas_strong_acq_rel(field, &map, newmap));+// Visit all set bits in a bitmap but try to return ranges (within bfields) if possible.+// Also clear those ranges atomically.+// Used by purging to purge larger ranges when possible+// todo: optimize further? maybe use avx512 to directly get all indices using a mask_compressstore?+bool _mi_bitmap_forall_setc_ranges(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg) {+ // for all chunkmap entries+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for (size_t i = 0; i < chunkmap_max; i++) {+ mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ // for each chunk (corresponding to a set bit in a chunkmap entry)+ while (mi_bfield_foreach_bit(&cmap_entry, &cmap_idx)) {+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ // for each chunk field+ mi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];+ for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {+ const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);+ mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], 0);+#if MI_DEBUG > 1+ const size_t bpopcount = mi_popcount(b);+ size_t rngcount = 0;+#endif+ size_t bidx;+ while (mi_bfield_find_least_bit(b, &bidx)) {+ size_t rng = mi_ctz(~(b>>bidx)); // all the set bits from bidx+#if MI_DEBUG > 1+ rngcount += rng;+#endif+ const size_t idx = base_idx + bidx;+ mi_assert_internal(rng>=1 && rng<=MI_BFIELD_BITS);+ mi_assert_internal((idx % MI_BFIELD_BITS) + rng <= MI_BFIELD_BITS);+ mi_assert_internal((idx / MI_BCHUNK_BITS) < mi_bitmap_chunk_count(bitmap));+ if (!visit(idx, rng, arena, arg)) return false;+ // clear rng bits in b+ b = b & ~mi_bfield_mask(rng, bidx);+ }+ mi_assert_internal(rngcount == bpopcount);+ }+ }+ }+ return true;+}++// Visit all set bits in a bitmap but try to return ranges (within bfields) if possible,+// but only in chunks of at least `rngslices` slices (that are also aligned at `rngslices`)+// and clear those ranges atomically.+// However, the `rngslices` are capped at `MI_BFIELD_BITS` at most.+// Used by purging to purge larger ranges when possible. With transparent huge pages we only+// want to purge whole huge pages (2 MiB) at a time which is what the `rngslices` parameter achieves.+bool _mi_bitmap_forall_setc_rangesn(mi_bitmap_t* bitmap, size_t rngslices, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg)+{+ // use the generic routine for `rngslices<=1` (as that one finds longest ranges at a time)+ if (rngslices<=1) {+ return _mi_bitmap_forall_setc_ranges(bitmap, visit, arena, arg);}- mi_stat_counter_increase(_mi_stats_main.arena_rollback_count,1);- // retry? (we make a recursive call instead of goto to be able to use const declarations)- if (retries <= 2) {- return mi_bitmap_try_find_claim_field_across(bitmap, bitmap_fields, idx, count, retries+1, bitmap_idx);+ // mi_assert_internal(rngslices <= MI_BFIELD_BITS);+ if (rngslices > MI_BFIELD_BITS) { rngslices = MI_BFIELD_BITS; } // cap at MI_BFIELD_BITS at most++ // for all chunkmap entries+ const size_t chunkmap_max = _mi_divide_up(mi_bitmap_chunk_count(bitmap), MI_BFIELD_BITS);+ for (size_t i = 0; i < chunkmap_max; i++) {+ mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bitmap->chunkmap.bfields[i]);+ size_t cmap_idx;+ // for each chunk (corresponding to a set bit in a chunkmap entry)+ while (mi_bfield_foreach_bit(&cmap_entry, &cmap_idx)) {+ const size_t chunk_idx = i*MI_BFIELD_BITS + cmap_idx;+ // for each chunk field+ mi_bchunk_t* const chunk = &bitmap->chunks[chunk_idx];+ for (size_t j = 0; j < MI_BCHUNK_FIELDS; j++) {+ const size_t base_idx = (chunk_idx*MI_BCHUNK_BITS) + (j*MI_BFIELD_BITS);+ mi_bfield_t b = mi_atomic_exchange_relaxed(&chunk->bfields[j], 0); // atomic clear+ mi_bfield_t skipped = 0; // but track which bits we skip so we can restore them+ for(size_t shift = 0; rngslices + shift <= MI_BFIELD_BITS; shift += rngslices) { // per `rngslices` to keep alignment+ const mi_bfield_t rngmask = mi_bfield_mask(rngslices, shift);+ if ((b & rngmask) == rngmask) {+ const size_t idx = base_idx + shift;+ if (!visit(idx, rngslices, arena, arg)) {+ // break early+ if (skipped != 0) {+ mi_atomic_or_relaxed(&chunk->bfields[j], skipped);+ return false;+ }+ }+ }+ else {+ skipped = skipped | (b & rngmask);+ }+ }++ if (skipped != 0) {+ mi_atomic_or_relaxed(&chunk->bfields[j], skipped);+ }+ }+ }}- else {+ return true;+}+++/* --------------------------------------------------------------------------------+ binned bitmap's+-------------------------------------------------------------------------------- */+++size_t mi_bbitmap_size(size_t bit_count, size_t* pchunk_count) {+ // mi_assert_internal((bit_count % MI_BCHUNK_BITS) == 0);+ bit_count = _mi_align_up(bit_count, MI_BCHUNK_BITS);+ mi_assert_internal(bit_count <= MI_BITMAP_MAX_BIT_COUNT);+ mi_assert_internal(bit_count > 0);+ const size_t chunk_count = bit_count / MI_BCHUNK_BITS;+ mi_assert_internal(chunk_count >= 1);+ const size_t size = offsetof(mi_bbitmap_t,chunks) + (chunk_count * MI_BCHUNK_SIZE);+ mi_assert_internal( (size%MI_BCHUNK_SIZE) == 0 );+ if (pchunk_count != NULL) { *pchunk_count = chunk_count; }+ return size;+}++// initialize a bitmap to all unset; avoid a mem_zero if `already_zero` is true+// returns the size of the bitmap+size_t mi_bbitmap_init(mi_bbitmap_t* bbitmap, size_t bit_count, bool already_zero) {+ size_t chunk_count;+ const size_t size = mi_bbitmap_size(bit_count, &chunk_count);+ if (!already_zero) {+ _mi_memzero_aligned(bbitmap, size);+ }+ mi_atomic_store_release(&bbitmap->chunk_count, chunk_count);+ mi_assert_internal(mi_atomic_load_relaxed(&bbitmap->chunk_count) <= MI_BITMAP_MAX_CHUNK_COUNT);+ return size;+}++void mi_bbitmap_unsafe_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ mi_assert_internal(idx + n <= mi_bbitmap_max_bits(bbitmap));+ mi_bchunks_unsafe_setN(&bbitmap->chunks[0], &bbitmap->chunkmap, idx, n);+}++++/* --------------------------------------------------------------------------------+ binned bitmap used to track free slices+-------------------------------------------------------------------------------- */++// Assign a specific size bin to a chunk+static void mi_bbitmap_set_chunk_bin(mi_bbitmap_t* bbitmap, size_t chunk_idx, mi_chunkbin_t bin) {+ mi_assert_internal(chunk_idx < mi_bbitmap_chunk_count(bbitmap));+ for (mi_chunkbin_t ibin = MI_CBIN_SMALL; ibin < MI_CBIN_NONE; ibin = mi_chunkbin_inc(ibin)) {+ if (ibin == bin) {+ const bool was_clear = mi_bchunk_set(& bbitmap->chunkmap_bins[ibin], chunk_idx, NULL);+ if (was_clear) { mi_os_stat_increase(chunk_bins[ibin],1); }+ }+ else {+ const bool was_set = mi_bchunk_clear(&bbitmap->chunkmap_bins[ibin], chunk_idx, NULL);+ if (was_set) { mi_os_stat_decrease(chunk_bins[ibin],1); }+ }+ }+}++mi_chunkbin_t mi_bbitmap_debug_get_bin(const mi_bchunkmap_t* chunkmap_bins, size_t chunk_idx) {+ for (mi_chunkbin_t ibin = MI_CBIN_SMALL; ibin < MI_CBIN_NONE; ibin = mi_chunkbin_inc(ibin)) {+ if (mi_bchunk_is_xsetN(MI_BIT_SET, &chunkmap_bins[ibin], chunk_idx, 1)) {+ return ibin;+ }+ }+ return MI_CBIN_NONE;+}++// Track the index of the highest chunk that is accessed.+static void mi_bbitmap_chunkmap_set_max(mi_bbitmap_t* bbitmap, size_t chunk_idx) {+ size_t oldmax = mi_atomic_load_relaxed(&bbitmap->chunk_max_accessed);+ if mi_unlikely(chunk_idx > oldmax) {+ mi_atomic_cas_strong_relaxed(&bbitmap->chunk_max_accessed, &oldmax, chunk_idx);+ }+}++// Set a bit in the chunkmap+static void mi_bbitmap_chunkmap_set(mi_bbitmap_t* bbitmap, size_t chunk_idx, bool check_all_set) {+ mi_assert(chunk_idx < mi_bbitmap_chunk_count(bbitmap));+ if (check_all_set) {+ if (mi_bchunk_all_are_set_relaxed(&bbitmap->chunks[chunk_idx])) {+ // all slices are free in this chunk: return back to the NONE bin+ mi_bbitmap_set_chunk_bin(bbitmap, chunk_idx, MI_CBIN_NONE);+ }+ }+ mi_bchunk_set(&bbitmap->chunkmap, chunk_idx, NULL);+ mi_bbitmap_chunkmap_set_max(bbitmap, chunk_idx);+}++static bool mi_bbitmap_chunkmap_try_clear(mi_bbitmap_t* bbitmap, size_t chunk_idx) {+ mi_assert(chunk_idx < mi_bbitmap_chunk_count(bbitmap));+ // check if the corresponding chunk is all clear+ if (!mi_bchunk_all_are_clear_relaxed(&bbitmap->chunks[chunk_idx])) return false;+ // clear the chunkmap bit+ mi_bchunk_clear(&bbitmap->chunkmap, chunk_idx, NULL);+ // .. but a concurrent set may have happened in between our all-clear test and the clearing of the+ // bit in the mask. We check again to catch this situation. (note: mi_bchunk_clear must be acq-rel)+ if (!mi_bchunk_all_are_clear_relaxed(&bbitmap->chunks[chunk_idx])) {+ mi_bchunk_set(&bbitmap->chunkmap, chunk_idx, NULL);return false;}+ mi_bbitmap_chunkmap_set_max(bbitmap, chunk_idx);+ return true;}-// Find `count` bits of zeros and set them to 1 atomically; returns `true` on success.-// Starts at idx, and wraps around to search in all `bitmap_fields` fields.-bool _mi_bitmap_try_find_from_claim_across(mi_bitmap_t bitmap, const size_t bitmap_fields, const size_t start_field_idx, const size_t count, mi_bitmap_index_t* bitmap_idx) {- mi_assert_internal(count > 0);- if (count <= 2) {- // we don't bother with crossover fields for small counts- return _mi_bitmap_try_find_from_claim(bitmap, bitmap_fields, start_field_idx, count, bitmap_idx);+/* --------------------------------------------------------------------------------+ mi_bbitmap_setN, try_clearN, and is_xsetN+ (used to find free pages)+-------------------------------------------------------------------------------- */++// Set a sequence of `n` bits in the bitmap; returns `true` if atomically transitioned from 0's to 1's (or 1's to 0's).+bool mi_bbitmap_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bbitmap_max_bits(bbitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return false;+ n = maxbits - idx;}- // visit the fields- size_t idx = start_field_idx;- for (size_t visited = 0; visited < bitmap_fields; visited++, idx++) {- if (idx >= bitmap_fields) { idx = 0; } // wrap- // first try to claim inside a field- /*- if (count <= MI_BITMAP_FIELD_BITS) {- if (_mi_bitmap_try_find_claim_field(bitmap, idx, count, bitmap_idx)) {- return true;+ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ bool were_allclear = true;+ while (n > 0) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ were_allclear = mi_bchunk_setN(&bbitmap->chunks[chunk_idx], cidx, m, NULL) && were_allclear;+ mi_bbitmap_chunkmap_set(bbitmap, chunk_idx, true); // set afterwards+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ return were_allclear;+}++// ------- mi_bbitmap_try_clearNC ---------------------------------------++// Try to clear `n` bits at `idx` where `n <= MI_BCHUNK_BITS`.+bool mi_bbitmap_try_clearNC(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ mi_assert_internal(n<=MI_BCHUNK_BITS);+ mi_assert_internal(idx + n <= mi_bbitmap_max_bits(bbitmap));++ const size_t chunk_idx = idx / MI_BCHUNK_BITS;+ const size_t cidx = idx % MI_BCHUNK_BITS;+ mi_assert_internal(cidx + n <= MI_BCHUNK_BITS); // don't cross chunks (for now)+ mi_assert_internal(chunk_idx < mi_bbitmap_chunk_count(bbitmap));+ if (cidx + n > MI_BCHUNK_BITS) return false;+ bool maybe_all_clear = false;+ const bool cleared = mi_bchunk_try_clearN(&bbitmap->chunks[chunk_idx], cidx, n, &maybe_all_clear);+ if (cleared && maybe_all_clear) { mi_bbitmap_chunkmap_try_clear(bbitmap, chunk_idx); }+ // note: we don't set the size class for an explicit try_clearN (only used by purging)+ return cleared;+}++++// ------- mi_bbitmap_is_xset ---------------------------------------++// Is a sequence of n bits already all set/cleared?+bool mi_bbitmap_is_xsetN(mi_xset_t set, mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ mi_assert_internal(n>0);+ const size_t maxbits = mi_bbitmap_max_bits(bbitmap);+ mi_assert_internal(idx + n <= maxbits);+ if (idx+n > maxbits) { // paranoia+ if (idx >= maxbits) return false;+ n = maxbits - idx;+ }++ // iterate through the chunks+ size_t chunk_idx = idx / MI_BCHUNK_BITS;+ size_t cidx = idx % MI_BCHUNK_BITS;+ bool xset = true;+ while (n > 0 && xset) {+ const size_t m = (cidx + n > MI_BCHUNK_BITS ? MI_BCHUNK_BITS - cidx : n);+ xset = mi_bchunk_is_xsetN(set, &bbitmap->chunks[chunk_idx], cidx, m) && xset;+ mi_assert_internal(m <= n);+ n -= m;+ cidx = 0;+ chunk_idx++;+ }+ return xset;+}+++++/* --------------------------------------------------------------------------------+ mi_bbitmap_find+ (used to find free pages)+-------------------------------------------------------------------------------- */++typedef bool (mi_bchunk_try_find_and_clear_fun_t)(mi_bchunk_t* chunk, size_t n, size_t* idx);++// Go through the bbitmap and for every sequence of `n` set bits, call the visitor function.+// If it returns `true` stop the search.+//+// This is used for finding free blocks and it is important to be efficient (with 2-level bitscan)+// but also reduce fragmentation (through size bins).+static inline bool mi_bbitmap_try_find_and_clear_generic(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx, mi_bchunk_try_find_and_clear_fun_t* on_find)+{+ // we space out threads to reduce contention+ const size_t cmap_max_count = _mi_divide_up(mi_bbitmap_chunk_count(bbitmap),MI_BFIELD_BITS);+ const size_t chunk_acc = mi_atomic_load_relaxed(&bbitmap->chunk_max_accessed);+ const size_t cmap_acc = chunk_acc / MI_BFIELD_BITS;+ const size_t cmap_acc_bits = 1 + (chunk_acc % MI_BFIELD_BITS);++ // create a mask over the chunkmap entries to iterate over them efficiently+ mi_assert_internal(MI_BFIELD_BITS >= MI_BCHUNK_FIELDS);+ const mi_bfield_t cmap_mask = mi_bfield_mask(cmap_max_count,0);+ const size_t cmap_cycle = cmap_acc+1;+ const mi_chunkbin_t bbin = mi_chunkbin_of(n);+ // visit each cmap entry+ size_t cmap_idx = 0;+ mi_bfield_cycle_iterate(cmap_mask, tseq, cmap_cycle, cmap_idx, X)+ {+ // and for each chunkmap entry we iterate over its bits to find the chunks+ const mi_bfield_t cmap_entry = mi_atomic_load_relaxed(&bbitmap->chunkmap.bfields[cmap_idx]);+ const size_t cmap_entry_cycle = (cmap_idx != cmap_acc ? MI_BFIELD_BITS : cmap_acc_bits);+ if (cmap_entry == 0) {+ continue;+ }++ // get size bin masks+ mi_bfield_t cmap_bins[MI_CBIN_COUNT] = { 0 };+ cmap_bins[MI_CBIN_NONE] = cmap_entry;+ for (mi_chunkbin_t ibin = MI_CBIN_SMALL; ibin < MI_CBIN_NONE; ibin = mi_chunkbin_inc(ibin)) {+ const mi_bfield_t cmap_bin = mi_atomic_load_relaxed(&bbitmap->chunkmap_bins[ibin].bfields[cmap_idx]);+ cmap_bins[ibin] = cmap_bin & cmap_entry;+ cmap_bins[MI_CBIN_NONE] &= ~cmap_bin; // clear bits that are in an assigned size bin+ }++ // consider only chunks for a particular size bin at a time+ // this picks the best bin only within a cmap entry (~ 1GiB address space), but avoids multiple+ // iterations through all entries.+ mi_assert_internal(bbin < MI_CBIN_NONE);+ for (mi_chunkbin_t ibin = MI_CBIN_SMALL; ibin <= MI_CBIN_NONE;+ // skip from bbin to NONE (so, say, a SMALL will never be placed in a OTHER, MEDIUM, or LARGE chunk to reduce fragmentation)+ ibin = (ibin == bbin ? MI_CBIN_NONE : mi_chunkbin_inc(ibin)))+ {+ mi_assert_internal(ibin < MI_CBIN_COUNT);+ const mi_bfield_t cmap_bin = cmap_bins[ibin];+ size_t eidx = 0;+ mi_bfield_cycle_iterate(cmap_bin, tseq, cmap_entry_cycle, eidx, Y)+ {+ // assertion doesn't quite hold as the max_accessed may be out-of-date+ // mi_assert_internal(cmap_entry_cycle > eidx || ibin == MI_CBIN_NONE);++ // get the chunk+ const size_t chunk_idx = cmap_idx*MI_BFIELD_BITS + eidx;+ mi_bchunk_t* chunk = &bbitmap->chunks[chunk_idx];++ size_t cidx;+ if ((*on_find)(chunk, n, &cidx)) {+ if (cidx==0 && ibin == MI_CBIN_NONE) { // only the first block determines the size bin+ // this chunk is now reserved for the `bbin` size class+ mi_bbitmap_set_chunk_bin(bbitmap, chunk_idx, bbin);+ }+ *pidx = (chunk_idx * MI_BCHUNK_BITS) + cidx;+ mi_assert_internal(*pidx + n <= mi_bbitmap_max_bits(bbitmap));+ return true;+ }+ else {+ // todo: should _on_find_ return a boolean if there is a chance all are clear to avoid calling `try_clear?`+ // we may find that all are cleared only on a second iteration but that is ok as the chunkmap is a conservative approximation.+ mi_bbitmap_chunkmap_try_clear(bbitmap, chunk_idx);+ }}+ mi_bfield_cycle_iterate_end(Y);}- */- // if that fails, then try to claim across fields- if (mi_bitmap_try_find_claim_field_across(bitmap, bitmap_fields, idx, count, 0, bitmap_idx)) {- return true;+ }+ mi_bfield_cycle_iterate_end(X);+ return false;+}++/* --------------------------------------------------------------------------------+ mi_bbitmap_try_find_and_clear -- used to find free pages+ note: the compiler will fully inline the indirect function calls+-------------------------------------------------------------------------------- */++bool mi_bbitmap_try_find_and_clear(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx) {+ return mi_bbitmap_try_find_and_clear_generic(bbitmap, tseq, 1, pidx, &mi_bchunk_try_find_and_clear_1);+}++bool mi_bbitmap_try_find_and_clear8(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx) {+ return mi_bbitmap_try_find_and_clear_generic(bbitmap, tseq, 8, pidx, &mi_bchunk_try_find_and_clear_8);+}++// bool mi_bbitmap_try_find_and_clearX(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx) {+// return mi_bbitmap_try_find_and_clear_generic(bbitmap, tseq, MI_BFIELD_BITS, pidx, &mi_bchunk_try_find_and_clear_X);+// }++bool mi_bbitmap_try_find_and_clearNX(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx) {+ mi_assert_internal(n<=MI_BFIELD_BITS);+ return mi_bbitmap_try_find_and_clear_generic(bbitmap, tseq, n, pidx, &mi_bchunk_try_find_and_clearNX);+}++bool mi_bbitmap_try_find_and_clearNC(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx) {+ mi_assert_internal(n<=MI_BCHUNK_BITS);+ return mi_bbitmap_try_find_and_clear_generic(bbitmap, tseq, n, pidx, &mi_bchunk_try_find_and_clearNC);+}+++/* --------------------------------------------------------------------------------+ mi_bbitmap_try_find_and_clear for huge objects spanning multiple chunks+-------------------------------------------------------------------------------- */++// Try to atomically clear `n` bits starting at `chunk_idx` where `n` can span over multiple chunks+static bool mi_bchunk_try_clearN_(mi_bbitmap_t* bbitmap, size_t chunk_idx, size_t n) {+ mi_assert_internal((chunk_idx * MI_BCHUNK_BITS) + n <= mi_bbitmap_max_bits(bbitmap));++ size_t m = n; // bits to go+ size_t count = 0; // chunk count+ while (m > 0) {+ mi_bchunk_t* chunk = &bbitmap->chunks[chunk_idx + count];+ if (!mi_bchunk_try_clearN(chunk, 0, (m > MI_BCHUNK_BITS ? MI_BCHUNK_BITS : m), NULL)) {+ goto rollback;}+ m = (m <= MI_BCHUNK_BITS ? 0 : m - MI_BCHUNK_BITS);+ count++;+ }+ return true;++rollback:+ // we only need to reset chunks the we just fully cleared+ while (count > 0) {+ count--;+ mi_bchunk_t* chunk = &bbitmap->chunks[chunk_idx + count];+ mi_bchunk_setN(chunk, 0, MI_BCHUNK_BITS, NULL);}return false;}-// Helper for masks across fields; returns the mid count, post_mask may be 0-static size_t mi_bitmap_mask_across(mi_bitmap_index_t bitmap_idx, size_t bitmap_fields, size_t count, size_t* pre_mask, size_t* mid_mask, size_t* post_mask) {- MI_UNUSED(bitmap_fields);- const size_t bitidx = mi_bitmap_index_bit_in_field(bitmap_idx);- if mi_likely(bitidx + count <= MI_BITMAP_FIELD_BITS) {- *pre_mask = mi_bitmap_mask_(count, bitidx);- *mid_mask = 0;- *post_mask = 0;- mi_assert_internal(mi_bitmap_index_field(bitmap_idx) < bitmap_fields);- return 0;+// Go through the bbitmap to find a sequence of `n` bits and clear them atomically where `n > MI_ARENA_MAX_CHUNK_OBJ_SIZE`+// Since these are very large object allocations we always search from the start and only consider starting at the start+// of a chunk (for fragmentation and efficiency).+// Todo: for now we try to find full empty chunks to cover `n` but we can allow a partial chunk at the end+// Todo: This scans directly through the chunks -- we might want to consult the cmap as well?+bool mi_bbitmap_try_find_and_clearN_(mi_bbitmap_t* bbitmap, size_t tseq, size_t n, size_t* pidx) {+ MI_UNUSED(tseq);+ mi_assert(n > 0); if (n==0) { return false; }++ const size_t chunk_max = mi_bbitmap_chunk_count(bbitmap);+ const size_t chunk_req = _mi_divide_up(n, MI_BCHUNK_BITS); // minimal number of chunks needed+ if (chunk_max < chunk_req) { return false; }++ // iterate through the chunks+ size_t chunk_idx = 0;+ while (chunk_idx <= chunk_max - chunk_req)+ {+ size_t count = 0; // chunk count+ do {+ mi_assert_internal(chunk_idx + count < chunk_max);+ mi_bchunk_t* const chunk = &bbitmap->chunks[chunk_idx + count];+ if (!mi_bchunk_all_are_set_relaxed(chunk)) {+ break;+ }+ else {+ count++;+ }+ }+ while (count < chunk_req);++ // did we find a suitable range?+ if (count == chunk_req) {+ // now try to claim it!+ if (mi_bchunk_try_clearN_(bbitmap, chunk_idx, n)) {+ *pidx = (chunk_idx * MI_BCHUNK_BITS);+ for (size_t i = 0; i < count; i++) {+ mi_bbitmap_set_chunk_bin(bbitmap, chunk_idx + i, MI_CBIN_HUGE);+ }+ mi_assert_internal(*pidx + n <= mi_bbitmap_max_bits(bbitmap));+ return true;+ }+ }++ // keep searching but skip the scanned range+ chunk_idx += count+1;}- else {- const size_t pre_bits = MI_BITMAP_FIELD_BITS - bitidx;- mi_assert_internal(pre_bits < count);- *pre_mask = mi_bitmap_mask_(pre_bits, bitidx);- count -= pre_bits;- const size_t mid_count = (count / MI_BITMAP_FIELD_BITS);- *mid_mask = MI_BITMAP_FIELD_FULL;- count %= MI_BITMAP_FIELD_BITS;- *post_mask = (count==0 ? 0 : mi_bitmap_mask_(count, 0));- mi_assert_internal(mi_bitmap_index_field(bitmap_idx) + mid_count + (count==0 ? 0 : 1) < bitmap_fields);- return mid_count;- }-}--// Set `count` bits at `bitmap_idx` to 0 atomically-// Returns `true` if all `count` bits were 1 previously.-bool _mi_bitmap_unclaim_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- size_t idx = mi_bitmap_index_field(bitmap_idx);- size_t pre_mask;- size_t mid_mask;- size_t post_mask;- size_t mid_count = mi_bitmap_mask_across(bitmap_idx, bitmap_fields, count, &pre_mask, &mid_mask, &post_mask);- bool all_one = true;- mi_bitmap_field_t* field = &bitmap[idx];- size_t prev = mi_atomic_and_acq_rel(field++, ~pre_mask); // clear first part- if ((prev & pre_mask) != pre_mask) all_one = false;- while(mid_count-- > 0) {- prev = mi_atomic_and_acq_rel(field++, ~mid_mask); // clear mid part- if ((prev & mid_mask) != mid_mask) all_one = false;- }- if (post_mask!=0) {- prev = mi_atomic_and_acq_rel(field, ~post_mask); // clear end part- if ((prev & post_mask) != post_mask) all_one = false;- }- return all_one;-}--// Set `count` bits at `bitmap_idx` to 1 atomically-// Returns `true` if all `count` bits were 0 previously. `any_zero` is `true` if there was at least one zero bit.-bool _mi_bitmap_claim_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* pany_zero) {- size_t idx = mi_bitmap_index_field(bitmap_idx);- size_t pre_mask;- size_t mid_mask;- size_t post_mask;- size_t mid_count = mi_bitmap_mask_across(bitmap_idx, bitmap_fields, count, &pre_mask, &mid_mask, &post_mask);- bool all_zero = true;- bool any_zero = false;- _Atomic(size_t)*field = &bitmap[idx];- size_t prev = mi_atomic_or_acq_rel(field++, pre_mask);- if ((prev & pre_mask) != 0) all_zero = false;- if ((prev & pre_mask) != pre_mask) any_zero = true;- while (mid_count-- > 0) {- prev = mi_atomic_or_acq_rel(field++, mid_mask);- if ((prev & mid_mask) != 0) all_zero = false;- if ((prev & mid_mask) != mid_mask) any_zero = true;- }- if (post_mask!=0) {- prev = mi_atomic_or_acq_rel(field, post_mask);- if ((prev & post_mask) != 0) all_zero = false;- if ((prev & post_mask) != post_mask) any_zero = true;- }- if (pany_zero != NULL) { *pany_zero = any_zero; }- return all_zero;-}---// Returns `true` if all `count` bits were 1.-// `any_ones` is `true` if there was at least one bit set to one.-static bool mi_bitmap_is_claimedx_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* pany_ones) {- size_t idx = mi_bitmap_index_field(bitmap_idx);- size_t pre_mask;- size_t mid_mask;- size_t post_mask;- size_t mid_count = mi_bitmap_mask_across(bitmap_idx, bitmap_fields, count, &pre_mask, &mid_mask, &post_mask);- bool all_ones = true;- bool any_ones = false;- mi_bitmap_field_t* field = &bitmap[idx];- size_t prev = mi_atomic_load_relaxed(field++);- if ((prev & pre_mask) != pre_mask) all_ones = false;- if ((prev & pre_mask) != 0) any_ones = true;- while (mid_count-- > 0) {- prev = mi_atomic_load_relaxed(field++);- if ((prev & mid_mask) != mid_mask) all_ones = false;- if ((prev & mid_mask) != 0) any_ones = true;- }- if (post_mask!=0) {- prev = mi_atomic_load_relaxed(field);- if ((prev & post_mask) != post_mask) all_ones = false;- if ((prev & post_mask) != 0) any_ones = true;- }- if (pany_ones != NULL) { *pany_ones = any_ones; }- return all_ones;-}--bool _mi_bitmap_is_claimed_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- return mi_bitmap_is_claimedx_across(bitmap, bitmap_fields, count, bitmap_idx, NULL);-}--bool _mi_bitmap_is_any_claimed_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx) {- bool any_ones;- mi_bitmap_is_claimedx_across(bitmap, bitmap_fields, count, bitmap_idx, &any_ones);- return any_ones;+ return false;}+++++diff --git a/vendored/mimalloc/src/bitmap.h b/vendored/mimalloc/src/bitmap.hindex f098dd8f1..6e9d2f1d8 100644--- a/vendored/mimalloc/src/bitmap.h+++ b/vendored/mimalloc/src/bitmap.h@@ -1,119 +1,339 @@/* -----------------------------------------------------------------------------Copyright (c) 2019-2023 Microsoft Research, Daan Leijen+Copyright (c) 2019-2024 Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.-----------------------------------------------------------------------------*//* -----------------------------------------------------------------------------Concurrent bitmap that can set/reset sequences of bits atomically,-represented as an array of fields where each field is a machine word (`size_t`)--There are two api's; the standard one cannot have sequences that cross-between the bitmap fields (and a sequence must be <= MI_BITMAP_FIELD_BITS).-(this is used in region allocation)--The `_across` postfixed functions do allow sequences that can cross over-between the fields. (This is used in arena allocation)+Concurrent bitmap that can set/reset sequences of bits atomically---------------------------------------------------------------------------- */#pragma once#ifndef MI_BITMAP_H#define MI_BITMAP_H-/* ------------------------------------------------------------ Bitmap definition------------------------------------------------------------ */+/* --------------------------------------------------------------------------------+ Atomic bitmaps with release/acquire guarantees:++ `mi_bfield_t`: is a single machine word that can efficiently be bit counted (usually `size_t`)+ each bit usually represents a single MI_ARENA_SLICE_SIZE in an arena (64 KiB).+ We need 16K bits to represent a 1GiB arena.++ `mi_bchunk_t`: a chunk of bfield's of a total of MI_BCHUNK_BITS (= 512 on 64-bit, 256 on 32-bit)+ allocations never span across chunks -- so MI_ARENA_MAX_OBJ_SIZE is the number+ of bits in a chunk times the MI_ARENA_SLICE_SIZE (512 * 64KiB = 32 MiB).+ These chunks are cache-aligned and we can use AVX2/AVX512/NEON/SVE/SVE2/etc. instructions+ to scan for bits (perhaps) more efficiently.++ We allocate byte-sized ranges aligned to bytes in the bfield, and bfield-sized+ ranges aligned to a bfield.++ Searching linearly through the chunks would be too slow (16K bits per GiB).+ Instead we add a "chunkmap" to do a two-level search (more or less a btree of depth 2).++ `mi_bchunkmap_t` (== `mi_bchunk_t`): for each chunk we track if it has (potentially) any bit set.+ The chunkmap has 1 bit per chunk that is set if the chunk potentially has a bit set.+ This is used to avoid scanning every chunk. (and thus strictly an optimization)+ It is conservative: it is fine to set a bit in the chunk map even if the chunk turns out+ to have no bits set. It is also allowed to briefly have a clear bit even if the+ chunk has bits set -- as long as we guarantee that the bit will be set later on;+ (this allows us to set the chunkmap bit right after we set a bit in the corresponding chunk).++ However, when we clear a bit in a chunk, and the chunk is indeed all clear, we+ cannot safely clear the bit corresponding to the chunk in the chunkmap since it+ may race with another thread setting a bit in the same chunk. Therefore, when+ clearing, we first test if a chunk is clear, then clear the chunkmap bit, and+ then test again to catch any set bits that we may have missed.++ Since the chunkmap may thus be briefly out-of-sync, this means that we may sometimes+ not find a free page even though it's there (but we accept this as we avoid taking+ full locks). (Another way to do this is to use an epoch but we like to avoid that complexity+ for now).++ `mi_bitmap_t`: a bitmap with N chunks. A bitmap has a chunkmap of MI_BCHUNK_BITS (512)+ and thus has at most 512 chunks (=2^18 bits x 64 KiB slices = 16 GiB max arena size).+ The minimum is 1 chunk which is a 32 MiB arena.-#define MI_BITMAP_FIELD_BITS (8*MI_SIZE_SIZE)-#define MI_BITMAP_FIELD_FULL (~((size_t)0)) // all bits set+ For now, the implementation assumes MI_HAS_FAST_BITSCAN and uses trailing-zero-count+ and pop-count (but we think it can be adapted work reasonably well on older hardware too)+--------------------------------------------------------------------------------------------- */-// An atomic bitmap of `size_t` fields-typedef _Atomic(size_t) mi_bitmap_field_t;-typedef mi_bitmap_field_t* mi_bitmap_t;+// A word-size bit field.+typedef size_t mi_bfield_t;-// A bitmap index is the index of the bit in a bitmap.-typedef size_t mi_bitmap_index_t;+#define MI_BFIELD_BITS_SHIFT (MI_SIZE_SHIFT+3)+#define MI_BFIELD_BITS (1 << MI_BFIELD_BITS_SHIFT)+#define MI_BFIELD_SIZE (MI_BFIELD_BITS/8)+#define MI_BFIELD_LO_BIT8 (((~(mi_bfield_t)0))/0xFF) // 0x01010101 ..+#define MI_BFIELD_HI_BIT8 (MI_BFIELD_LO_BIT8 << 7) // 0x80808080 ..-// Create a bit index.-static inline mi_bitmap_index_t mi_bitmap_index_create_ex(size_t idx, size_t bitidx) {- mi_assert_internal(bitidx <= MI_BITMAP_FIELD_BITS);- return (idx*MI_BITMAP_FIELD_BITS) + bitidx;+#define MI_BCHUNK_SIZE (MI_BCHUNK_BITS / 8)+#define MI_BCHUNK_FIELDS (MI_BCHUNK_BITS / MI_BFIELD_BITS) // 8 on both 64- and 32-bit+++// some compiler (msvc in C mode) cannot have expressions in the alignment attribute+#if MI_BCHUNK_SIZE==64+#define mi_decl_bchunk_align mi_decl_align(64)+#elif MI_BCHUNK_SIZE==32+#define mi_decl_bchunk_align mi_decl_align(32)+#else+#define mi_decl_bchunk_align mi_decl_align(MI_BCHUNK_SIZE)+#endif+++// A bitmap chunk contains 512 bits on 64-bit (256 on 32-bit)+typedef mi_decl_bchunk_align struct mi_bchunk_s {+ _Atomic(mi_bfield_t) bfields[MI_BCHUNK_FIELDS];+} mi_bchunk_t;+++// The chunkmap has one bit per corresponding chunk that is set if the chunk potentially has bits set.+// The chunkmap is itself a chunk.+typedef mi_bchunk_t mi_bchunkmap_t;++#define MI_BCHUNKMAP_BITS MI_BCHUNK_BITS++#define MI_BITMAP_MAX_CHUNK_COUNT (MI_BCHUNKMAP_BITS)+#define MI_BITMAP_MIN_CHUNK_COUNT (1)+#if MI_SIZE_BITS > 32+#define MI_BITMAP_DEFAULT_CHUNK_COUNT (64) // 2 GiB on 64-bit -- this is for the page map+#else+#define MI_BITMAP_DEFAULT_CHUNK_COUNT (1)+#endif+#define MI_BITMAP_MAX_BIT_COUNT (MI_BITMAP_MAX_CHUNK_COUNT * MI_BCHUNK_BITS) // 16 GiB arena+#define MI_BITMAP_MIN_BIT_COUNT (MI_BITMAP_MIN_CHUNK_COUNT * MI_BCHUNK_BITS) // 32 MiB arena+#define MI_BITMAP_DEFAULT_BIT_COUNT (MI_BITMAP_DEFAULT_CHUNK_COUNT * MI_BCHUNK_BITS) // 2 GiB arena+++// An atomic bitmap+typedef mi_decl_bchunk_align struct mi_bitmap_s {+ _Atomic(size_t) chunk_count; // total count of chunks (0 < N <= MI_BCHUNKMAP_BITS)+ size_t _padding[MI_BCHUNK_SIZE/MI_SIZE_SIZE - 1]; // suppress warning on msvc+ mi_bchunkmap_t chunkmap;+ mi_bchunk_t chunks[MI_BITMAP_DEFAULT_CHUNK_COUNT]; // usually dynamic MI_BITMAP_MAX_CHUNK_COUNT+} mi_bitmap_t;+++static inline size_t mi_bitmap_chunk_count(const mi_bitmap_t* bitmap) {+ return mi_atomic_load_relaxed(&((mi_bitmap_t*)bitmap)->chunk_count);}-static inline mi_bitmap_index_t mi_bitmap_index_create(size_t idx, size_t bitidx) {- mi_assert_internal(bitidx < MI_BITMAP_FIELD_BITS);- return mi_bitmap_index_create_ex(idx,bitidx);++static inline size_t mi_bitmap_max_bits(const mi_bitmap_t* bitmap) {+ return (mi_bitmap_chunk_count(bitmap) * MI_BCHUNK_BITS);}-// Create a bit index.-static inline mi_bitmap_index_t mi_bitmap_index_create_from_bit(size_t full_bitidx) {- return mi_bitmap_index_create(full_bitidx / MI_BITMAP_FIELD_BITS, full_bitidx % MI_BITMAP_FIELD_BITS);+++/* --------------------------------------------------------------------------------+ Atomic bitmap operations+-------------------------------------------------------------------------------- */++// Many operations are generic over setting or clearing the bit sequence: we use `mi_xset_t` for this (true if setting, false if clearing)+typedef bool mi_xset_t;+#define MI_BIT_SET (true)+#define MI_BIT_CLEAR (false)+++// Required size of a bitmap to represent `bit_count` bits.+size_t mi_bitmap_size(size_t bit_count, size_t* chunk_count);++// Initialize a bitmap to all clear; avoid a mem_zero if `already_zero` is true+// returns the size of the bitmap.+size_t mi_bitmap_init(mi_bitmap_t* bitmap, size_t bit_count, bool already_zero);++// Set/clear a sequence of `n` bits in the bitmap (and can cross chunks).+// Not atomic so only use if still local to a thread.+void mi_bitmap_unsafe_setN(mi_bitmap_t* bitmap, size_t idx, size_t n);+++// Set a bit in the bitmap; returns `true` if it atomically transitioned from 0 to 1+bool mi_bitmap_set(mi_bitmap_t* bitmap, size_t idx);++// Clear a bit in the bitmap; returns `true` if it atomically transitioned from 1 to 0+bool mi_bitmap_clear(mi_bitmap_t* bitmap, size_t idx);++// Set a sequence of `n` bits in the bitmap; returns `true` if atomically transitioned from all 0's to 1's+// If `already_set` is not NULL, it is set to count of bits were already all set.+// (this is used for correct statistics if commiting over a partially committed area)+bool mi_bitmap_setN(mi_bitmap_t* bitmap, size_t idx, size_t n, size_t* already_set);++// Clear a sequence of `n` bits in the bitmap; returns `true` if atomically transitioned from all 1's to 0's+bool mi_bitmap_clearN(mi_bitmap_t* bitmap, size_t idx, size_t n);+++// Is a sequence of n bits already all set/cleared?+bool mi_bitmap_is_xsetN(mi_xset_t set, mi_bitmap_t* bitmap, size_t idx, size_t n);++// Is the bitmap completely clear?+bool mi_bitmap_is_all_clear(mi_bitmap_t* bitmap);++// Is a sequence of n bits already set?+// (Used to check if a memory range is already committed)+static inline bool mi_bitmap_is_setN(mi_bitmap_t* bitmap, size_t idx, size_t n) {+ return mi_bitmap_is_xsetN(MI_BIT_SET, bitmap, idx, n);}-// Get the field index from a bit index.-static inline size_t mi_bitmap_index_field(mi_bitmap_index_t bitmap_idx) {- return (bitmap_idx / MI_BITMAP_FIELD_BITS);+// Is a sequence of n bits already clear?+static inline bool mi_bitmap_is_clearN(mi_bitmap_t* bitmap, size_t idx, size_t n) {+ return mi_bitmap_is_xsetN(MI_BIT_CLEAR, bitmap, idx, n);}-// Get the bit index in a bitmap field-static inline size_t mi_bitmap_index_bit_in_field(mi_bitmap_index_t bitmap_idx) {- return (bitmap_idx % MI_BITMAP_FIELD_BITS);+static inline bool mi_bitmap_is_set(mi_bitmap_t* bitmap, size_t idx) {+ return mi_bitmap_is_setN(bitmap, idx, 1);}-// Get the full bit index-static inline size_t mi_bitmap_index_bit(mi_bitmap_index_t bitmap_idx) {- return bitmap_idx;+static inline bool mi_bitmap_is_clear(mi_bitmap_t* bitmap, size_t idx) {+ return mi_bitmap_is_clearN(bitmap, idx, 1);}-/* ------------------------------------------------------------ Claim a bit sequence atomically------------------------------------------------------------ */+// Called once a bit is cleared to see if the memory slice can be claimed.+typedef bool (mi_claim_fun_t)(size_t slice_index, mi_arena_t* arena, bool* keep_set);-// Try to atomically claim a sequence of `count` bits in a single-// field at `idx` in `bitmap`. Returns `true` on success.-bool _mi_bitmap_try_find_claim_field(mi_bitmap_t bitmap, size_t idx, const size_t count, mi_bitmap_index_t* bitmap_idx);+// Find a set bits in the bitmap, atomically clear it, and check if `claim` returns true.+// If not claimed, continue on (potentially setting the bit again depending on `keep_set`).+// Returns true on success, and in that case sets the index: `0 <= *pidx <= MI_BITMAP_MAX_BITS-n`.+mi_decl_nodiscard bool mi_bitmap_try_find_and_claim(mi_bitmap_t* bitmap, size_t tseq, size_t* pidx,+ mi_claim_fun_t* claim, mi_arena_t* arena );-// Starts at idx, and wraps around to search in all `bitmap_fields` fields.-// For now, `count` can be at most MI_BITMAP_FIELD_BITS and will never cross fields.-bool _mi_bitmap_try_find_from_claim(mi_bitmap_t bitmap, const size_t bitmap_fields, const size_t start_field_idx, const size_t count, mi_bitmap_index_t* bitmap_idx);-// Like _mi_bitmap_try_find_from_claim but with an extra predicate that must be fullfilled-typedef bool (mi_cdecl *mi_bitmap_pred_fun_t)(mi_bitmap_index_t bitmap_idx, void* pred_arg);-bool _mi_bitmap_try_find_from_claim_pred(mi_bitmap_t bitmap, const size_t bitmap_fields, const size_t start_field_idx, const size_t count, mi_bitmap_pred_fun_t pred_fun, void* pred_arg, mi_bitmap_index_t* bitmap_idx);+// Atomically clear a bit but only if it is set. Will block otherwise until the bit is set.+// This is used to delay free-ing a page that it at the same time being considered to be+// allocated from `mi_arena_try_abandoned` (and is in the `claim` function of `mi_bitmap_try_find_and_claim`).+void mi_bitmap_clear_once_set(mi_bitmap_t* bitmap, size_t idx);-// Set `count` bits at `bitmap_idx` to 0 atomically-// Returns `true` if all `count` bits were 1 previously.-bool _mi_bitmap_unclaim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);-// Try to set `count` bits at `bitmap_idx` from 0 to 1 atomically.-// Returns `true` if successful when all previous `count` bits were 0.-bool _mi_bitmap_try_claim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);+// If a bit is set in the bitmap, return `true` and set `idx` to the index of the highest bit.+// Otherwise return `false` (and `*idx` is undefined).+// Used for unloading arena's+bool mi_bitmap_bsr(mi_bitmap_t* bitmap, size_t* idx);-// Set `count` bits at `bitmap_idx` to 1 atomically-// Returns `true` if all `count` bits were 0 previously. `any_zero` is `true` if there was at least one zero bit.-bool _mi_bitmap_claim(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* any_zero);+// Return count of all set bits in a bitmap.+size_t mi_bitmap_popcount(mi_bitmap_t* bitmap);-bool _mi_bitmap_is_claimed(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);-bool _mi_bitmap_is_any_claimed(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);+typedef bool (mi_forall_set_fun_t)(size_t slice_index, size_t slice_count, mi_arena_t* arena, void* arg2);-//---------------------------------------------------------------------------// the `_across` functions work on bitmaps where sequences can cross over-// between the fields. This is used in arena allocation-//--------------------------------------------------------------------------+// Visit all set bits in a bitmap (`slice_count == 1`)+bool _mi_bitmap_forall_set(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg);-// Find `count` bits of zeros and set them to 1 atomically; returns `true` on success.-// Starts at idx, and wraps around to search in all `bitmap_fields` fields.-bool _mi_bitmap_try_find_from_claim_across(mi_bitmap_t bitmap, const size_t bitmap_fields, const size_t start_field_idx, const size_t count, mi_bitmap_index_t* bitmap_idx);+// Visit all set bits in a bitmap with larger ranges if possible (`slice_count >= 1`)+// Ranges will never cross chunk boundaries though (and `slice_count <= MI_BCHUNK_BITS`)+bool _mi_bitmap_forall_setc_ranges(mi_bitmap_t* bitmap, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg);-// Set `count` bits at `bitmap_idx` to 0 atomically-// Returns `true` if all `count` bits were 1 previously.-bool _mi_bitmap_unclaim_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);+// Visit all set bits in a bitmap with at least `rngslices` at a time (and aligned to `rngslices`).+// This is used by purging to not break up transparent huge pages for example.+// Ranges will never cross chunk boundaries (and `slice_count <= MI_BCHUNK_BITS`).+bool _mi_bitmap_forall_setc_rangesn(mi_bitmap_t* bitmap, size_t rngslices, mi_forall_set_fun_t* visit, mi_arena_t* arena, void* arg);-// Set `count` bits at `bitmap_idx` to 1 atomically-// Returns `true` if all `count` bits were 0 previously. `any_zero` is `true` if there was at least one zero bit.-bool _mi_bitmap_claim_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx, bool* pany_zero);+// Count all set bits in given range in the bitmap.+size_t mi_bitmap_popcountN( mi_bitmap_t* bitmap, size_t idx, size_t n);-bool _mi_bitmap_is_claimed_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);-bool _mi_bitmap_is_any_claimed_across(mi_bitmap_t bitmap, size_t bitmap_fields, size_t count, mi_bitmap_index_t bitmap_idx);+/* ----------------------------------------------------------------------------+ Binned concurrent bitmap+ Assigns a size class to each chunk such that small blocks don't cause too+ much fragmentation since we keep chunks for larger blocks separate.+---------------------------------------------------------------------------- */-#endif+// mi_chunkbin_t is defined in mimalloc-stats.h++static inline mi_chunkbin_t mi_chunkbin_inc(mi_chunkbin_t bbin) {+ mi_assert_internal(bbin < MI_CBIN_COUNT);+ return (mi_chunkbin_t)((int)bbin + 1);+}++static inline mi_chunkbin_t mi_chunkbin_dec(mi_chunkbin_t bbin) {+ mi_assert_internal(bbin > MI_CBIN_NONE);+ return (mi_chunkbin_t)((int)bbin - 1);+}++static inline mi_chunkbin_t mi_chunkbin_of(size_t slice_count) {+ if (slice_count==1) return MI_CBIN_SMALL;+ if (slice_count==8) return MI_CBIN_MEDIUM;+ #if MI_ENABLE_LARGE_PAGES+ if (slice_count==MI_BFIELD_BITS) return MI_CBIN_LARGE;+ #endif+ if (slice_count > MI_BCHUNK_BITS) return MI_CBIN_HUGE;+ return MI_CBIN_OTHER;+}++// An atomic "binned" bitmap for the free slices where we keep chunks reserved for particular size classes+typedef mi_decl_bchunk_align struct mi_bbitmap_s {+ _Atomic(size_t) chunk_count; // total count of chunks (0 < N <= MI_BCHUNKMAP_BITS)+ _Atomic(size_t) chunk_max_accessed; // max chunk index that was once cleared or set+ #if (MI_BCHUNK_SIZE / MI_SIZE_SIZE) > 2+ size_t _padding[MI_BCHUNK_SIZE/MI_SIZE_SIZE - 2]; // suppress warning on msvc by aligning manually+ #endif+ mi_bchunkmap_t chunkmap;+ mi_bchunkmap_t chunkmap_bins[MI_CBIN_COUNT - 1]; // chunkmaps with bit set if the chunk is in that size class (excluding MI_CBIN_NONE)+ mi_bchunk_t chunks[MI_BITMAP_DEFAULT_CHUNK_COUNT]; // usually dynamic MI_BITMAP_MAX_CHUNK_COUNT+} mi_bbitmap_t;+++static inline size_t mi_bbitmap_chunk_count(const mi_bbitmap_t* bbitmap) {+ return mi_atomic_load_relaxed(&((mi_bbitmap_t*)bbitmap)->chunk_count);+}++static inline size_t mi_bbitmap_max_bits(const mi_bbitmap_t* bbitmap) {+ return (mi_bbitmap_chunk_count(bbitmap) * MI_BCHUNK_BITS);+}++mi_chunkbin_t mi_bbitmap_debug_get_bin(const mi_bchunk_t* chunkmap_bins, size_t chunk_idx);++size_t mi_bbitmap_size(size_t bit_count, size_t* chunk_count);+++// Initialize a bitmap to all clear; avoid a mem_zero if `already_zero` is true+// returns the size of the bitmap.+size_t mi_bbitmap_init(mi_bbitmap_t* bbitmap, size_t bit_count, bool already_zero);++// Set/clear a sequence of `n` bits in the bitmap (and can cross chunks).+// Not atomic so only use if still local to a thread.+void mi_bbitmap_unsafe_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n);+++// Set a sequence of `n` bits in the bbitmap; returns `true` if atomically transitioned from all 0's to 1's+bool mi_bbitmap_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n);+++// Is a sequence of n bits already all set/cleared?+bool mi_bbitmap_is_xsetN(mi_xset_t set, mi_bbitmap_t* bbitmap, size_t idx, size_t n);++// Is a sequence of n bits already set?+// (Used to check if a memory range is already committed)+static inline bool mi_bbitmap_is_setN(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ return mi_bbitmap_is_xsetN(MI_BIT_SET, bbitmap, idx, n);+}++// Is a sequence of n bits already clear?+static inline bool mi_bbitmap_is_clearN(mi_bbitmap_t* bbitmap, size_t idx, size_t n) {+ return mi_bbitmap_is_xsetN(MI_BIT_CLEAR, bbitmap, idx, n);+}+++// Try to atomically transition `n` bits from all set to all clear. Returns `true` on succes.+// `n` cannot cross chunk boundaries, where `n <= MI_CHUNK_BITS`.+bool mi_bbitmap_try_clearNC(mi_bbitmap_t* bbitmap, size_t idx, size_t n);+++// Specialized versions for common bit sequence sizes+bool mi_bbitmap_try_find_and_clear(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // 1-bit+bool mi_bbitmap_try_find_and_clear8(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // 8-bits+// bool mi_bbitmap_try_find_and_clearX(mi_bbitmap_t* bbitmap, size_t tseq, size_t* pidx); // MI_BFIELD_BITS+bool mi_bbitmap_try_find_and_clearNX(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // < MI_BFIELD_BITS+bool mi_bbitmap_try_find_and_clearNC(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // > MI_BFIELD_BITS <= MI_BCHUNK_BITS+bool mi_bbitmap_try_find_and_clearN_(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx); // > MI_BCHUNK_BITS++// Find a sequence of `n` bits in the bbitmap with all bits set, and try to atomically clear all.+// Returns true on success, and in that case sets the index: `0 <= *pidx <= MI_BITMAP_MAX_BITS-n`.+mi_decl_nodiscard static inline bool mi_bbitmap_try_find_and_clearN(mi_bbitmap_t* bbitmap, size_t n, size_t tseq, size_t* pidx) {+ if (n==1) return mi_bbitmap_try_find_and_clear(bbitmap, tseq, pidx); // small pages+ if (n==8) return mi_bbitmap_try_find_and_clear8(bbitmap, tseq, pidx); // medium pages+ // if (n==MI_BFIELD_BITS) return mi_bbitmap_try_find_and_clearX(bbitmap, tseq, pidx); // large pages+ if (n==0) return false;+ if (n<=MI_BFIELD_BITS) return mi_bbitmap_try_find_and_clearNX(bbitmap, tseq, n, pidx);+ if (n<=MI_BCHUNK_BITS) return mi_bbitmap_try_find_and_clearNC(bbitmap, tseq, n, pidx);+ return mi_bbitmap_try_find_and_clearN_(bbitmap, tseq, n, pidx);+}+++#endif // MI_BITMAP_Hdiff --git a/vendored/mimalloc/src/free.c b/vendored/mimalloc/src/free.cindex f856da77a..9be8f26c3 100644--- a/vendored/mimalloc/src/free.c+++ b/vendored/mimalloc/src/free.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2024, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -23,9 +23,6 @@ static void mi_stat_free(const mi_page_t* page, const mi_block_t* block);// Free// -------------------------------------------------------// forward declaration of multi-threaded free (`_mt`) (or free in huge block if compiled with MI_HUGE_PAGE_ABANDON)-static mi_decl_noinline void mi_free_block_mt(mi_page_t* page, mi_segment_t* segment, mi_block_t* block);-// regular free of a (thread local) block pointer// fast path written carefully to prevent spilling on the stackstatic inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, bool track_stats, bool check_full)@@ -35,9 +32,7 @@ static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, boolmi_check_padding(page, block);if (track_stats) { mi_stat_free(page, block); }#if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN && !MI_GUARDED- if (!mi_page_is_huge(page)) { // huge page content may be already decommitted- memset(block, MI_DEBUG_FREED, mi_page_block_size(page));- }+ memset(block, MI_DEBUG_FREED, mi_page_block_size(page));#endifif (track_stats) { mi_track_free_size(block, mi_page_usable_size_of(page, block)); } // faster then mi_usable_size as we already know the page and that p is unaligned@@ -45,13 +40,49 @@ static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, boolmi_block_set_next(page, block, page->local_free);page->local_free = block;if mi_unlikely(--page->used == 0) {- _mi_page_retire(page);+ if (page->retire_expire==0) { // no need to re-retire retired pages (happens when we alloc/free one block repeatedly in an empty page)+ _mi_page_retire(page);+ }}else if mi_unlikely(check_full && mi_page_is_in_full(page)) {_mi_page_unfull(page);}}+// Forward declaration for multi-threaded collect+static void mi_decl_noinline mi_free_try_collect_mt(mi_page_t* page, mi_block_t* mt_free) mi_attr_noexcept;++// Free a block multi-threaded+static inline void mi_free_block_mt(mi_page_t* page, mi_block_t* block) mi_attr_noexcept+{+ // adjust stats (after padding check and potentially recursive `mi_free` above)+ mi_stat_free(page, block); // stat_free may access the padding+ mi_track_free_size(block, mi_page_usable_size_of(page, block));++ // _mi_padding_shrink(page, block, sizeof(mi_block_t));+#if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN // note: when tracking, cannot use mi_usable_size with multi-threading+ size_t dbgsize = mi_usable_size(block);+ if (dbgsize > MI_MiB) { dbgsize = MI_MiB; }+ _mi_memset_aligned(block, MI_DEBUG_FREED, dbgsize);+#endif++ // push atomically on the page thread free list+ mi_thread_free_t tf_new;+ mi_thread_free_t tf_old = mi_atomic_load_relaxed(&page->xthread_free);+ do {+ mi_block_set_next(page, block, mi_tf_block(tf_old));+ tf_new = mi_tf_create(block, true /* always use owned: try to claim it if the page is abandoned */);+ } while (!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tf_old, tf_new)); // todo: release is enough?++ // and atomically try to collect the page if it was abandoned+ const bool is_owned_now = !mi_tf_is_owned(tf_old);+ if (is_owned_now) {+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_free_try_collect_mt(page,block);+ }+}++// Adjust a block that was allocated aligned, to the actual start of the block in the page.// note: this can be called from `mi_free_generic_mt` where a non-owning thread accesses the// `page_start` and `block_size` fields; however these are constant and the page won't be@@ -59,15 +90,9 @@ static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, boolmi_block_t* _mi_page_ptr_unalign(const mi_page_t* page, const void* p) {mi_assert_internal(page!=NULL && p!=NULL);- size_t diff = (uint8_t*)p - page->page_start;- size_t adjust;- if mi_likely(page->block_size_shift != 0) {- adjust = diff & (((size_t)1 << page->block_size_shift) - 1);- }- else {- adjust = diff % mi_page_block_size(page);- }-+ const size_t diff = (uint8_t*)p - mi_page_start(page);+ const size_t block_size = mi_page_block_size(page);+ const size_t adjust = (_mi_is_power_of_two(block_size) ? diff & (block_size - 1) : diff % block_size);return (mi_block_t*)((uintptr_t)p - adjust);}@@ -83,224 +108,249 @@ static inline void mi_block_check_unguard(mi_page_t* page, mi_block_t* block, vo}#endif+static inline mi_block_t* mi_validate_block_from_ptr( const mi_page_t* page, void* p ) {+ mi_assert(_mi_page_ptr_unalign(page,p) == (mi_block_t*)p); // should never be an interior pointer+ #if MI_SECURE > 0+ // in secure mode we always unalign to guard against free-ing interior pointers+ return _mi_page_ptr_unalign(page,p);+ #else+ MI_UNUSED(page);+ return (mi_block_t*)p;+ #endif+}++// free a local pointer (page parameter comes first for better codegen)-static void mi_decl_noinline mi_free_generic_local(mi_page_t* page, mi_segment_t* segment, void* p) mi_attr_noexcept {- MI_UNUSED(segment);- mi_block_t* const block = (mi_page_has_aligned(page) ? _mi_page_ptr_unalign(page, p) : (mi_block_t*)p);+static void mi_decl_noinline mi_free_generic_local(mi_page_t* page, void* p) mi_attr_noexcept {+ mi_assert_internal(p!=NULL && page != NULL);+ mi_block_t* const block = (mi_page_has_interior_pointers(page) ? _mi_page_ptr_unalign(page, p) : mi_validate_block_from_ptr(page,p));mi_block_check_unguard(page, block, p);mi_free_block_local(page, block, true /* track stats */, true /* check for a full page */);}// free a pointer owned by another thread (page parameter comes first for better codegen)-static void mi_decl_noinline mi_free_generic_mt(mi_page_t* page, mi_segment_t* segment, void* p) mi_attr_noexcept {- mi_block_t* const block = _mi_page_ptr_unalign(page, p); // don't check `has_aligned` flag to avoid a race (issue #865)+static void mi_decl_noinline mi_free_generic_mt(mi_page_t* page, void* p) mi_attr_noexcept {+ mi_assert_internal(p!=NULL && page != NULL);+ mi_block_t* const block = (mi_page_has_interior_pointers(page) ? _mi_page_ptr_unalign(page, p) : mi_validate_block_from_ptr(page,p));mi_block_check_unguard(page, block, p);- mi_free_block_mt(page, segment, block);+ mi_free_block_mt(page, block);}// generic free (for runtime integration)-void mi_decl_noinline _mi_free_generic(mi_segment_t* segment, mi_page_t* page, bool is_local, void* p) mi_attr_noexcept {- if (is_local) mi_free_generic_local(page,segment,p);- else mi_free_generic_mt(page,segment,p);+void mi_decl_noinline _mi_free_generic(mi_page_t* page, bool is_local, void* p) mi_attr_noexcept {+ if (is_local) mi_free_generic_local(page,p);+ else mi_free_generic_mt(page,p);}-// Get the segment data belonging to a pointer-// This is just a single `and` in release mode but does further checks in debug mode-// (and secure mode) to see if this was a valid pointer.-static inline mi_segment_t* mi_checked_ptr_segment(const void* p, const char* msg)-{- MI_UNUSED(msg);- #if (MI_DEBUG>0)+// Get the page belonging to a pointer+// Does further checks in debug mode to see if this was a valid pointer.+static inline mi_page_t* mi_validate_ptr_page(const void* p, const char* msg)+{+ MI_UNUSED_RELEASE(msg);+ #if MI_DEBUGif mi_unlikely(((uintptr_t)p & (MI_INTPTR_SIZE - 1)) != 0 && !mi_option_is_enabled(mi_option_guarded_precise)) {_mi_error_message(EINVAL, "%s: invalid (unaligned) pointer: %p\n", msg, p);return NULL;}- #endif-- mi_segment_t* const segment = _mi_ptr_segment(p);- if mi_unlikely(segment==NULL) return segment;-- #if (MI_DEBUG>0)- if mi_unlikely(!mi_is_in_heap_region(p)) {- #if (MI_INTPTR_SIZE == 8 && defined(__linux__))- if (((uintptr_t)p >> 40) != 0x7F) { // linux tends to align large blocks above 0x7F000000000 (issue #640)- #else- {- #endif- _mi_warning_message("%s: pointer might not point to a valid heap region: %p\n"- "(this may still be a valid very large allocation (over 64MiB))\n", msg, p);- if mi_likely(_mi_ptr_cookie(segment) == segment->cookie) {- _mi_warning_message("(yes, the previous pointer %p was valid after all)\n", p);- }- }- }- #endif- #if (MI_DEBUG>0 || MI_SECURE>=4)- if mi_unlikely(_mi_ptr_cookie(segment) != segment->cookie) {- _mi_error_message(EINVAL, "%s: pointer does not point to a valid heap space: %p\n", msg, p);- return NULL;+ mi_page_t* page = _mi_safe_ptr_page(p);+ if (p != NULL && page == NULL) {+ _mi_error_message(EINVAL, "%s: invalid pointer: %p\n", msg, p);}+ return page;+ #else+ return _mi_ptr_page(p);#endif-- return segment;}// Free a block// Fast path written carefully to prevent register spilling on the stack-void mi_free(void* p) mi_attr_noexcept+static mi_decl_forceinline void mi_free_ex(void* p, size_t* usable){- mi_segment_t* const segment = mi_checked_ptr_segment(p,"mi_free");- if mi_unlikely(segment==NULL) return;-- const bool is_local = (_mi_prim_thread_id() == mi_atomic_load_relaxed(&segment->thread_id));- mi_page_t* const page = _mi_segment_page_of(segment, p);-- if mi_likely(is_local) { // thread-local free?- if mi_likely(page->flags.full_aligned == 0) { // and it is not a full page (full pages need to move from the full bin), nor has aligned blocks (aligned blocks need to be unaligned)- // thread-local, aligned, and not a full page- mi_block_t* const block = (mi_block_t*)p;- mi_free_block_local(page, block, true /* track stats */, false /* no need to check if the page is full */);- }- else {- // page is full or contains (inner) aligned blocks; use generic path- mi_free_generic_local(page, segment, p);- }+ mi_page_t* const page = mi_validate_ptr_page(p,"mi_free");+ if mi_unlikely(page==NULL) return; // page will be NULL if p==NULL+ mi_assert_internal(p!=NULL && page!=NULL);+ if (usable!=NULL) { *usable = mi_page_usable_block_size(page); }++ const mi_threadid_t xtid = (_mi_prim_thread_id() ^ mi_page_xthread_id(page));+ if mi_likely(xtid == 0) { // `tid == mi_page_thread_id(page) && mi_page_flags(page) == 0`+ // thread-local, aligned, and not a full page+ mi_block_t* const block = mi_validate_block_from_ptr(page,p);+ mi_free_block_local(page, block, true /* track stats */, false /* no need to check if the page is full */);+ }+ else if (xtid <= MI_PAGE_FLAG_MASK) { // `tid == mi_page_thread_id(page) && mi_page_flags(page) != 0`+ // page is local, but is full or contains (inner) aligned blocks; use generic path+ mi_free_generic_local(page, p);+ }+ // free-ing in a page owned by a theap in another thread, or an abandoned page (not belonging to a theap)+ else if ((xtid & MI_PAGE_FLAG_MASK) == 0) { // `tid != mi_page_thread_id(page) && mi_page_flags(page) == 0`+ // blocks are aligned (and not a full page); push on the thread_free list+ mi_block_t* const block = mi_validate_block_from_ptr(page,p);+ mi_free_block_mt(page,block);}else {- // not thread-local; use generic path- mi_free_generic_mt(page, segment, p);+ // page is full or contains (inner) aligned blocks; use generic multi-thread path+ mi_free_generic_mt(page, p);}}-// return true if successful-bool _mi_free_delayed_block(mi_block_t* block) {- // get segment and page- mi_assert_internal(block!=NULL);- const mi_segment_t* const segment = _mi_ptr_segment(block);- mi_assert_internal(_mi_ptr_cookie(segment) == segment->cookie);- mi_assert_internal(_mi_thread_id() == segment->thread_id);- mi_page_t* const page = _mi_segment_page_of(segment, block);-- // Clear the no-delayed flag so delayed freeing is used again for this page.- // This must be done before collecting the free lists on this page -- otherwise- // some blocks may end up in the page `thread_free` list with no blocks in the- // heap `thread_delayed_free` list which may cause the page to be never freed!- // (it would only be freed if we happen to scan it in `mi_page_queue_find_free_ex`)- if (!_mi_page_try_use_delayed_free(page, MI_USE_DELAYED_FREE, false /* dont overwrite never delayed */)) {- return false;- }+void mi_free(void* p) mi_attr_noexcept {+ mi_free_ex(p, NULL);+}- // collect all other non-local frees (move from `thread_free` to `free`) to ensure up-to-date `used` count- _mi_page_free_collect(page, false);+void mi_ufree(void* p, size_t* usable) mi_attr_noexcept {+ mi_free_ex(p, usable);+}++// --------------------------------------------------------------------------------------------+// `mi_free_try_collect_mt`: Potentially collect a page in a free in an abandoned page.+// 1. if the page becomes empty, free it+// 2. if it can be reclaimed, reclaim it in our theap+// 3. if it went to < 7/8th used, re-abandon to be mapped (so it can be found by theaps looking for free pages)+// --------------------------------------------------------------------------------------------- // and free the block (possibly freeing the page as well since `used` is updated)- mi_free_block_local(page, block, false /* stats have already been adjusted */, true /* check for a full page */);+// Helper for mi_free_try_collect_mt: free if the page has no more used blocks (this is updated by `_mi_page_free_collect(_partly)`)+static bool mi_abandoned_page_try_free(mi_page_t* page)+{+ if (!mi_page_all_free(page)) return false;+ // first remove it from the abandoned pages in the arena (if mapped, this might wait for any readers to finish)+ _mi_arenas_page_unabandon(page,NULL);+ _mi_arenas_page_free(page,NULL); // we can now free the page directlyreturn true;}-// -------------------------------------------------------// Multi-threaded Free (`_mt`)-// --------------------------------------------------------// Push a block that is owned by another thread on its page-local thread free-// list or it's heap delayed free list. Such blocks are later collected by-// the owning thread in `_mi_free_delayed_block`.-static void mi_decl_noinline mi_free_block_delayed_mt( mi_page_t* page, mi_block_t* block )+// Helper for mi_free_try_collect_mt: try if we can reabandon a previously abandoned mostly full page to be mapped+static bool mi_abandoned_page_try_reabandon_to_mapped(mi_page_t* page){- // Try to put the block on either the page-local thread free list,- // or the heap delayed free list (if this is the first non-local free in that page)- mi_thread_free_t tfreex;- bool use_delayed;- mi_thread_free_t tfree = mi_atomic_load_relaxed(&page->xthread_free);- do {- use_delayed = (mi_tf_delayed(tfree) == MI_USE_DELAYED_FREE);- if mi_unlikely(use_delayed) {- // unlikely: this only happens on the first concurrent free in a page that is in the full list- tfreex = mi_tf_set_delayed(tfree,MI_DELAYED_FREEING);- }- else {- // usual: directly add to page thread_free list- mi_block_set_next(page, block, mi_tf_block(tfree));- tfreex = mi_tf_set_block(tfree,block);+ // if the page is unmapped, try to reabandon so it can possibly be mapped and found for allocations+ // We only reabandon if a full page starts to have enough blocks available to prevent immediate re-abandon of a full page+ if (mi_page_is_mostly_used(page)) return false; // not too full+ if (page->memid.memkind != MI_MEM_ARENA || mi_page_is_abandoned_mapped(page)) return false; // and not already mapped (or unmappable)++ mi_assert(!mi_page_is_full(page));+ return _mi_arenas_page_try_reabandon_to_mapped(page);+}++// Release ownership of a page. This may free or reabandond the page if other blocks are concurrently+// freed in the meantime. Returns `true` if the page was freed.+// By passing the captured `expected_thread_free`, we can often avoid calling `mi_page_free_collect`.+static void mi_abandoned_page_unown_from_free(mi_page_t* page, mi_block_t* expected_thread_free) {+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(!mi_page_all_free(page));+ // try to cas atomically the original free list (`mt_free`) back with the ownership cleared.+ mi_thread_free_t tf_expect = mi_tf_create(expected_thread_free, true);+ mi_thread_free_t tf_new = mi_tf_create(expected_thread_free, false);+ while mi_unlikely(!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tf_expect, tf_new)) {+ mi_assert_internal(mi_tf_is_owned(tf_expect));+ // while the xthread_free list is not empty..+ while (mi_tf_block(tf_expect) != NULL) {+ // if there were concurrent updates to the thread-free list, we retry to free or reabandon to mapped (if it became !mosty_used).+ _mi_page_free_collect(page,false); // update used count+ if (mi_abandoned_page_try_free(page)) return;+ if (mi_abandoned_page_try_reabandon_to_mapped(page)) return;+ // otherwise continue un-owning+ tf_expect = mi_atomic_load_relaxed(&page->xthread_free);}- } while (!mi_atomic_cas_weak_release(&page->xthread_free, &tfree, tfreex));-- // If this was the first non-local free, we need to push it on the heap delayed free list instead- if mi_unlikely(use_delayed) {- // racy read on `heap`, but ok because MI_DELAYED_FREEING is set (see `mi_heap_delete` and `mi_heap_collect_abandon`)- mi_heap_t* const heap = (mi_heap_t*)(mi_atomic_load_acquire(&page->xheap)); //mi_page_heap(page);- mi_assert_internal(heap != NULL);- if (heap != NULL) {- // add to the delayed free list of this heap. (do this atomically as the lock only protects heap memory validity)- mi_block_t* dfree = mi_atomic_load_ptr_relaxed(mi_block_t, &heap->thread_delayed_free);- do {- mi_block_set_nextx(heap,block,dfree, heap->keys);- } while (!mi_atomic_cas_ptr_weak_release(mi_block_t,&heap->thread_delayed_free, &dfree, block));- }-- // and reset the MI_DELAYED_FREEING flag- tfree = mi_atomic_load_relaxed(&page->xthread_free);- do {- tfreex = tfree;- mi_assert_internal(mi_tf_delayed(tfree) == MI_DELAYED_FREEING);- tfreex = mi_tf_set_delayed(tfree,MI_NO_DELAYED_FREE);- } while (!mi_atomic_cas_weak_release(&page->xthread_free, &tfree, tfreex));+ // and try again to release ownership+ mi_assert_internal(mi_tf_block(tf_expect)==NULL);+ tf_new = mi_tf_create(NULL, false);}}-// Multi-threaded free (`_mt`) (or free in huge block if compiled with MI_HUGE_PAGE_ABANDON)-static void mi_decl_noinline mi_free_block_mt(mi_page_t* page, mi_segment_t* segment, mi_block_t* block)+static inline bool mi_page_queue_len_is_atmost( mi_theap_t* theap, size_t block_size, long atmost) {+ if (atmost < 0) return false;+ mi_page_queue_t* const pq = mi_page_queue(theap,block_size);+ mi_assert_internal(pq!=NULL);+ return (pq->count <= (size_t)atmost);+}++// Helper for mi_free_try_collect_mt: try to reclaim the page for ourselves+static mi_decl_noinline bool mi_abandoned_page_try_reclaim(mi_page_t* page, long reclaim_on_free) mi_attr_noexcept{- // first see if the segment was abandoned and if we can reclaim it into our thread- if (_mi_option_get_fast(mi_option_abandoned_reclaim_on_free) != 0 &&- #if MI_HUGE_PAGE_ABANDON- segment->page_kind != MI_PAGE_HUGE &&- #endif- mi_atomic_load_relaxed(&segment->thread_id) == 0 && // segment is abandoned?- mi_prim_get_default_heap() != (mi_heap_t*)&_mi_heap_empty) // and we did not already exit this thread (without this check, a fresh heap will be initalized (issue #944))- {- // the segment is abandoned, try to reclaim it into our heap- if (_mi_segment_attempt_reclaim(mi_heap_get_default(), segment)) {- mi_assert_internal(_mi_thread_id() == mi_atomic_load_relaxed(&segment->thread_id));- mi_assert_internal(mi_heap_get_default()->tld->segments.subproc == segment->subproc);- mi_free(block); // recursively free as now it will be a local free in our heap- return;- }+ // note: reclaiming can improve benchmarks like `larson` or `rbtree-ck` a lot even in the single-threaded case,+ // since free-ing from an owned page avoids atomic operations. However, if we reclaim too eagerly in+ // a multi-threaded scenario we may start to hold on to too much memory and reduce reuse among threads.+ // If the current theap is where the page originally came from, we reclaim much more eagerly while+ // 'cross-thread' reclaiming on free is by default off (and we only 'reclaim' these by finding the abandoned+ // pages when we allocate a fresh page).+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(!mi_page_all_free(page));+ mi_assert_internal(page->block_size <= MI_SMALL_SIZE_MAX);+ mi_assert_internal(reclaim_on_free >= 0);++ // dont reclaim if we just have terminated this thread and we should+ // not reinitialize the theap for this thread. (can happen due to thread-local destructors for example -- issue #944)+ if (!_mi_thread_is_initialized()) return false;++ // get our theap+ mi_theap_t* const theap = _mi_page_associated_theap_peek(page);+ if (theap==NULL || !theap->allow_page_reclaim) return false;++ // todo: cache `is_in_threadpool` and `exclusive_arena` directly in the theap for performance?+ // set max_reclaim limit+ long max_reclaim = 0;+ if mi_likely(theap == page->theap) { // did this page originate from the current theap? (and thus allocated from this thread)+ // originating theap+ max_reclaim = _mi_option_get_fast(theap->tld->is_in_threadpool ? mi_option_page_cross_thread_max_reclaim : mi_option_page_max_reclaim);+ }+ else if (reclaim_on_free == 1 && // if cross-thread is allowed+ !theap->tld->is_in_threadpool && // and we are not part of a threadpool+ !mi_page_is_mostly_used(page) && // and the page is not too full+ _mi_arena_memid_is_suitable(page->memid, theap->heap->exclusive_arena)) { // and it fits our memory+ // across threads+ max_reclaim = _mi_option_get_fast(mi_option_page_cross_thread_max_reclaim);}- // The padding check may access the non-thread-owned page for the key values.- // that is safe as these are constant and the page won't be freed (as the block is not freed yet).- mi_check_padding(page, block);+ // are we within the reclaim limit?+ if (max_reclaim >= 0 && !mi_page_queue_len_is_atmost(theap, page->block_size, max_reclaim)) {+ return false;+ }- // adjust stats (after padding check and potentially recursive `mi_free` above)- mi_stat_free(page, block); // stat_free may access the padding- mi_track_free_size(block, mi_page_usable_size_of(page,block));-- // for small size, ensure we can fit the delayed thread pointers without triggering overflow detection- _mi_padding_shrink(page, block, sizeof(mi_block_t));-- if (segment->kind == MI_SEGMENT_HUGE) {- #if MI_HUGE_PAGE_ABANDON- // huge page segments are always abandoned and can be freed immediately- _mi_segment_huge_page_free(segment, page, block);- return;- #else- // huge pages are special as they occupy the entire segment- // as these are large we reset the memory occupied by the page so it is available to other threads- // (as the owning thread needs to actually free the memory later).- _mi_segment_huge_page_reset(segment, page, block);- #endif+ // reclaim the page into this theap+ // first remove it from the abandoned pages in the arena -- this might wait for any readers to finish+ _mi_arenas_page_unabandon(page, theap);+ _mi_theap_page_reclaim(theap, page);+ mi_theap_stat_counter_increase(theap, pages_reclaim_on_free, 1);+ return true;+}+++// We freed a block in an abandoned page (that was not owned). Try to collect+static void mi_decl_noinline mi_free_try_collect_mt(mi_page_t* page, mi_block_t* mt_free) mi_attr_noexcept+{+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_assert_internal(mt_free != NULL);+ // we own the page now, and it is safe to collect the thread atomic free list+ if (page->block_size <= MI_SMALL_SIZE_MAX) {+ // use the `_partly` version to avoid atomic operations since we already have the `mt_free` pointing into the thread free list+ // (after this the `used` count might be too high (as some blocks may have been concurrently added to the thread free list and are yet uncounted).+ // however, if the page became completely free, the used count is guaranteed to be 0.)+ mi_assert_internal(page->reserved>=16); // below this even one freed block goes from full to no longer mostly used.+ _mi_page_free_collect_partly(page, mt_free);}else {- #if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN // note: when tracking, cannot use mi_usable_size with multi-threading- memset(block, MI_DEBUG_FREED, mi_usable_size(block));- #endif+ // for larger blocks we use the regular collect+ _mi_page_free_collect(page,false /* no force */);+ mt_free = NULL; // expected page->xthread_free value after collection}+ const long reclaim_on_free = _mi_option_get_fast(mi_option_page_reclaim_on_free);+ #if MI_DEBUG > 1+ if (mi_page_is_singleton(page)) { mi_assert_internal(mi_page_all_free(page)); }+ if (mi_page_is_full(page)) { mi_assert(mi_page_is_mostly_used(page)); }+ #endif- // and finally free the actual block by pushing it on the owning heap- // thread_delayed free list (or heap delayed free list)- mi_free_block_delayed_mt(page,block);+ // try to: 1. free it, 2. reclaim it, or 3. reabandon it to be mapped+ if (mi_abandoned_page_try_free(page)) return;+ if (page->block_size <= MI_SMALL_SIZE_MAX && reclaim_on_free >= 0) { // early test for better codegen+ if (mi_abandoned_page_try_reclaim(page, reclaim_on_free)) return;+ }+ if (mi_abandoned_page_try_reabandon_to_mapped(page)) return;++ // otherwise unown the page again+ mi_abandoned_page_unown_from_free(page, mt_free);}@@ -323,11 +373,9 @@ static size_t mi_decl_noinline mi_page_usable_aligned_size_of(const mi_page_t* preturn aligned_size;}-static inline size_t _mi_usable_size(const void* p, const char* msg) mi_attr_noexcept {- const mi_segment_t* const segment = mi_checked_ptr_segment(p, msg);- if mi_unlikely(segment==NULL) return 0;- const mi_page_t* const page = _mi_segment_page_of(segment, p);- if mi_likely(!mi_page_has_aligned(page)) {+static inline size_t _mi_usable_size(const void* p, const mi_page_t* page) mi_attr_noexcept {+ if mi_unlikely(page==NULL) return 0;+ if mi_likely(!mi_page_has_interior_pointers(page)) {const mi_block_t* block = (const mi_block_t*)p;return mi_page_usable_size_of(page, block);}@@ -338,7 +386,8 @@ static inline size_t _mi_usable_size(const void* p, const char* msg) mi_attr_noe}mi_decl_nodiscard size_t mi_usable_size(const void* p) mi_attr_noexcept {- return _mi_usable_size(p, "mi_usable_size");+ const mi_page_t* const page = mi_validate_ptr_page(p,"mi_usable_size");+ return _mi_usable_size(p,page);}@@ -348,7 +397,11 @@ mi_decl_nodiscard size_t mi_usable_size(const void* p) mi_attr_noexcept {void mi_free_size(void* p, size_t size) mi_attr_noexcept {MI_UNUSED_RELEASE(size);- mi_assert(p == NULL || size <= _mi_usable_size(p,"mi_free_size"));+ #if MI_DEBUG+ const mi_page_t* const page = mi_validate_ptr_page(p,"mi_free_size");+ const size_t available = _mi_usable_size(p,page);+ mi_assert(p == NULL || size <= available || available == 0 /* invalid pointer */ );+ #endifmi_free(p);}@@ -417,7 +470,7 @@ static inline bool mi_check_is_double_free(const mi_page_t* page, const mi_block// ----------------------------------------------------------------------------// Check for heap block overflow by setting up padding at the end of the block+// Check for theap block overflow by setting up padding at the end of the block// ---------------------------------------------------------------------------#if MI_PADDING // && !MI_TRACK_ENABLED@@ -445,7 +498,7 @@ static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* bl}// When a non-thread-local block is freed, it becomes part of the thread delayed free-// list that is freed later by the owning heap. If the exact usable size is too small to+// list that is freed later by the owning theap. If the exact usable size is too small to// contain the pointer for the delayed list, then shrink the padding (by decreasing delta)// so it will later not trigger an overflow error in `mi_free_block`.void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const size_t min_size) {@@ -506,7 +559,7 @@ static void mi_check_padding(const mi_page_t* page, const mi_block_t* block) {size_t size;size_t wrong;if (!mi_verify_padding(page,block,&size,&wrong)) {- _mi_error_message(EFAULT, "buffer overflow in heap block %p of size %zu: write after %zu bytes\n", block, size, wrong );+ _mi_error_message(EFAULT, "buffer overflow in theap block %p of size %zu: write after %zu bytes\n", block, size, wrong );}}@@ -522,30 +575,28 @@ static void mi_check_padding(const mi_page_t* page, const mi_block_t* block) {// only maintain stats for smaller objects if requested#if (MI_STAT>0)static void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {- #if (MI_STAT < 2)MI_UNUSED(block);- #endif- mi_heap_t* const heap = mi_heap_get_default();+ mi_theap_t* const theap = _mi_theap_default();+ if (!mi_theap_is_initialized(theap)) return; // (for now) skip statistics if free'd after thread_done was called (usually a thread cleanup call by the OS)+const size_t bsize = mi_page_usable_block_size(page);- #if (MI_STAT>1)- const size_t usize = mi_page_usable_size_of(page, block);- mi_heap_stat_decrease(heap, malloc, usize);- #endif- if (bsize <= MI_MEDIUM_OBJ_SIZE_MAX) {- mi_heap_stat_decrease(heap, normal, bsize);+ // #if (MI_STAT>1)+ // const size_t usize = mi_page_usable_size_of(page, block);+ // mi_theap_stat_decrease(theap, malloc_requested, usize);+ // #endif+ if (bsize <= MI_LARGE_MAX_OBJ_SIZE) {+ mi_theap_stat_decrease(theap, malloc_normal, bsize);#if (MI_STAT > 1)- mi_heap_stat_decrease(heap, normal_bins[_mi_bin(bsize)], 1);+ mi_theap_stat_decrease(theap, malloc_bins[_mi_bin(bsize)], 1);#endif}- else if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {- mi_heap_stat_decrease(heap, large, bsize);- }else {- mi_heap_stat_decrease(heap, huge, bsize);+ const size_t bpsize = mi_page_block_size(page); // match stat in page.c:mi_huge_page_alloc+ mi_theap_stat_decrease(theap, malloc_huge, bpsize);}}#else-static void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {+void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {MI_UNUSED(page); MI_UNUSED(block);}#endif@@ -556,14 +607,14 @@ static void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {static void mi_block_unguard(mi_page_t* page, mi_block_t* block, void* p) {MI_UNUSED(p);mi_assert_internal(mi_block_ptr_is_guarded(block, p));- mi_assert_internal(mi_page_has_aligned(page));+ mi_assert_internal(mi_page_has_interior_pointers(page));mi_assert_internal((uint8_t*)p - (uint8_t*)block >= (ptrdiff_t)sizeof(mi_block_t));mi_assert_internal(block->next == MI_BLOCK_TAG_GUARDED);const size_t bsize = mi_page_block_size(page);const size_t psize = _mi_os_page_size();mi_assert_internal(bsize > psize);- mi_assert_internal(_mi_page_segment(page)->allow_decommit);+ mi_assert_internal(!page->memid.is_pinned);void* gpage = (uint8_t*)block + bsize - psize;mi_assert_internal(_mi_is_aligned(gpage, psize));_mi_os_unprotect(gpage, psize);diff --git a/vendored/mimalloc/src/heap.c b/vendored/mimalloc/src/heap.cindex f39dfb0ba..080cfd127 100644--- a/vendored/mimalloc/src/heap.c+++ b/vendored/mimalloc/src/heap.c@@ -1,5 +1,5 @@/*-----------------------------------------------------------------------------Copyright (c) 2018-2021, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -7,723 +7,213 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc.h"#include "mimalloc/internal.h"-#include "mimalloc/atomic.h"-#include "mimalloc/prim.h" // mi_prim_get_default_heap+#include "mimalloc/prim.h" // _mi_theap_default-#include <string.h> // memset, memcpy--#if defined(_MSC_VER) && (_MSC_VER < 1920)-#pragma warning(disable:4204) // non-constant aggregate initializer-#endif/* ------------------------------------------------------------ Helpers+ Heap's----------------------------------------------------------- */-// return `true` if ok, `false` to break-typedef bool (heap_page_visitor_fun)(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2);--// Visit all pages in a heap; returns `false` if break was called.-static bool mi_heap_visit_pages(mi_heap_t* heap, heap_page_visitor_fun* fn, void* arg1, void* arg2)-{- if (heap==NULL || heap->page_count==0) return 0;-- // visit all pages- #if MI_DEBUG>1- size_t total = heap->page_count;- size_t count = 0;- #endif-- for (size_t i = 0; i <= MI_BIN_FULL; i++) {- mi_page_queue_t* pq = &heap->pages[i];- mi_page_t* page = pq->first;- while(page != NULL) {- mi_page_t* next = page->next; // save next in case the page gets removed from the queue- mi_assert_internal(mi_page_heap(page) == heap);- #if MI_DEBUG>1- count++;- #endif- if (!fn(heap, pq, page, arg1, arg2)) return false;- page = next; // and continue- }- }- mi_assert_internal(count == total);- return true;+mi_theap_t* mi_heap_theap(mi_heap_t* heap) {+ return _mi_heap_theap(heap);}--#if MI_DEBUG>=2-static bool mi_heap_page_is_valid(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {- MI_UNUSED(arg1);- MI_UNUSED(arg2);- MI_UNUSED(pq);- mi_assert_internal(mi_page_heap(page) == heap);- mi_segment_t* segment = _mi_page_segment(page);- mi_assert_internal(mi_atomic_load_relaxed(&segment->thread_id) == heap->thread_id);- mi_assert_expensive(_mi_page_is_valid(page));- return true;+void mi_heap_set_numa_affinity(mi_heap_t* heap, int numa_node) {+ if (heap==NULL) { heap = mi_heap_main(); }+ heap->numa_node = (numa_node < 0 ? -1 : numa_node % _mi_os_numa_node_count());}-#endif-#if MI_DEBUG>=3-static bool mi_heap_is_valid(mi_heap_t* heap) {- mi_assert_internal(heap!=NULL);- mi_heap_visit_pages(heap, &mi_heap_page_is_valid, NULL, NULL);- return true;-}-#endif----/* ------------------------------------------------------------ "Collect" pages by migrating `local_free` and `thread_free`- lists and freeing empty pages. This is done when a thread- stops (and in that case abandons pages if there are still- blocks alive)------------------------------------------------------------ */--typedef enum mi_collect_e {- MI_NORMAL,- MI_FORCE,- MI_ABANDON-} mi_collect_t;---static bool mi_heap_page_collect(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg_collect, void* arg2 ) {- MI_UNUSED(arg2);- MI_UNUSED(heap);- mi_assert_internal(mi_heap_page_is_valid(heap, pq, page, NULL, NULL));- mi_collect_t collect = *((mi_collect_t*)arg_collect);- _mi_page_free_collect(page, collect >= MI_FORCE);- if (collect == MI_FORCE) {- // note: call before a potential `_mi_page_free` as the segment may be freed if this was the last used page in that segment.- mi_segment_t* segment = _mi_page_segment(page);- _mi_segment_collect(segment, true /* force? */);- }- if (mi_page_all_free(page)) {- // no more used blocks, free the page.- // note: this will free retired pages as well.- _mi_page_free(page, pq, collect >= MI_FORCE);- }- else if (collect == MI_ABANDON) {- // still used blocks but the thread is done; abandon the page- _mi_page_abandon(page, pq);- }- return true; // don't break+void mi_heap_stats_merge_to_subproc(mi_heap_t* heap) {+ if (heap==NULL) { heap = mi_heap_main(); }+ _mi_stats_merge_into(&heap->subproc->stats, &heap->stats);}-static bool mi_heap_page_never_delayed_free(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {- MI_UNUSED(arg1);- MI_UNUSED(arg2);- MI_UNUSED(heap);- MI_UNUSED(pq);- _mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);- return true; // don't break+void mi_heap_stats_merge_to_main(mi_heap_t* heap) {+ if (heap==NULL) return;+ _mi_stats_merge_into(&mi_heap_main()->stats, &heap->stats);}-static void mi_heap_collect_ex(mi_heap_t* heap, mi_collect_t collect)+static mi_theap_t* mi_heap_init_theap(const mi_heap_t* const_heap){- if (heap==NULL || !mi_heap_is_initialized(heap)) return;-- const bool force = (collect >= MI_FORCE);- _mi_deferred_free(heap, force);-- // python/cpython#112532: we may be called from a thread that is not the owner of the heap- const bool is_main_thread = (_mi_is_main_thread() && heap->thread_id == _mi_thread_id());-- // note: never reclaim on collect but leave it to threads that need storage to reclaim- const bool force_main =- #ifdef NDEBUG- collect == MI_FORCE- #else- collect >= MI_FORCE- #endif- && is_main_thread && mi_heap_is_backing(heap) && !heap->no_reclaim;+ mi_heap_t* heap = (mi_heap_t*)const_heap;+ mi_assert_internal(heap!=NULL);- if (force_main) {- // the main thread is abandoned (end-of-program), try to reclaim all abandoned segments.- // if all memory is freed by now, all segments should be freed.- // note: this only collects in the current subprocess- _mi_abandoned_reclaim_all(heap, &heap->tld->segments);+ if (_mi_is_heap_main(heap)) {+ // this can be called if the (main) thread is not yet initialized (as no allocation happened)+ mi_thread_init();+ mi_theap_t* theap = _mi_heap_theap(heap);+ mi_assert_internal(theap!=NULL);+ return theap;+ }++ // otherwise initialize the theap for this heap+ // get the thread local+ mi_theap_t* theap = NULL;+ if (heap->theap==0) {+ // initialize thread locals+ heap->theap = _mi_thread_local_create();+ if (heap->theap==0) {+ _mi_error_message(EFAULT, "unable to dynamically create a thread local for a heap\n");+ return NULL;+ }}-- // if abandoning, mark all pages to no longer add to delayed_free- if (collect == MI_ABANDON) {- mi_heap_visit_pages(heap, &mi_heap_page_never_delayed_free, NULL, NULL);+ else {+ // get current thread local+ theap = (mi_theap_t*)_mi_thread_local_get(heap->theap);}- // free all current thread delayed blocks.- // (if abandoning, after this there are no more thread-delayed references into the pages.)- _mi_heap_delayed_free_all(heap);-- // collect retired pages- _mi_heap_collect_retired(heap, force);-- // collect all pages owned by this thread- mi_heap_visit_pages(heap, &mi_heap_page_collect, &collect, NULL);- mi_assert_internal( collect != MI_ABANDON || mi_atomic_load_ptr_acquire(mi_block_t,&heap->thread_delayed_free) == NULL );-- // collect abandoned segments (in particular, purge expired parts of segments in the abandoned segment list)- // note: forced purge can be quite expensive if many threads are created/destroyed so we do not force on abandonment- _mi_abandoned_collect(heap, collect == MI_FORCE /* force? */, &heap->tld->segments);-- // if forced, collect thread data cache on program-exit (or shared library unload)- if (force && is_main_thread && mi_heap_is_backing(heap)) {- _mi_thread_data_collect(); // collect thread data cache+ // create a fresh theap?+ if (theap==NULL) {+ theap = _mi_theap_create(heap, _mi_theap_default_safe()->tld);+ if (theap==NULL) {+ _mi_error_message(EFAULT, "unable to allocate memory for a thread local heap\n");+ return NULL;+ }+ if (!_mi_thread_local_set(heap->theap, theap)) {+ _mi_error_message(EFAULT, "unable to allocate memory for a thread local storage\n");+ return NULL;+ }}-- // collect arenas (this is program wide so don't force purges on abandonment of threads)- _mi_arenas_collect(collect == MI_FORCE /* force purge? */);-}--void _mi_heap_collect_abandon(mi_heap_t* heap) {- mi_heap_collect_ex(heap, MI_ABANDON);-}--void mi_heap_collect(mi_heap_t* heap, bool force) mi_attr_noexcept {- mi_heap_collect_ex(heap, (force ? MI_FORCE : MI_NORMAL));+ return theap;}-void mi_collect(bool force) mi_attr_noexcept {- mi_heap_collect(mi_prim_get_default_heap(), force);-}---/* ------------------------------------------------------------ Heap new------------------------------------------------------------ */-mi_heap_t* mi_heap_get_default(void) {- mi_thread_init();- return mi_prim_get_default_heap();-}--static bool mi_heap_is_default(const mi_heap_t* heap) {- return (heap == mi_prim_get_default_heap());-}---mi_heap_t* mi_heap_get_backing(void) {- mi_heap_t* heap = mi_heap_get_default();- mi_assert_internal(heap!=NULL);- mi_heap_t* bheap = heap->tld->heap_backing;- mi_assert_internal(bheap!=NULL);- mi_assert_internal(bheap->thread_id == _mi_thread_id());- return bheap;-}--void _mi_heap_init(mi_heap_t* heap, mi_tld_t* tld, mi_arena_id_t arena_id, bool noreclaim, uint8_t tag) {- _mi_memcpy_aligned(heap, &_mi_heap_empty, sizeof(mi_heap_t));- heap->tld = tld;- heap->thread_id = _mi_thread_id();- heap->arena_id = arena_id;- heap->no_reclaim = noreclaim;- heap->tag = tag;- if (heap == tld->heap_backing) {- _mi_random_init(&heap->random);+// get the theap for a heap without initializing (and return NULL in that case)+mi_theap_t* _mi_heap_theap_get_peek(const mi_heap_t* heap) {+ if (heap==NULL || _mi_is_heap_main(heap)) {+ return __mi_theap_main; // don't call _mi_theap_main as it may still be NULL}else {- _mi_random_split(&tld->heap_backing->random, &heap->random);+ return (mi_theap_t*)_mi_thread_local_get(heap->theap);}- heap->cookie = _mi_heap_random_next(heap) | 1;- heap->keys[0] = _mi_heap_random_next(heap);- heap->keys[1] = _mi_heap_random_next(heap);- _mi_heap_guarded_init(heap);- // push on the thread local heaps list- heap->next = heap->tld->heaps;- heap->tld->heaps = heap;}-mi_decl_nodiscard mi_heap_t* mi_heap_new_ex(int heap_tag, bool allow_destroy, mi_arena_id_t arena_id) {- mi_heap_t* bheap = mi_heap_get_backing();- mi_heap_t* heap = mi_heap_malloc_tp(bheap, mi_heap_t); // todo: OS allocate in secure mode?- if (heap == NULL) return NULL;- mi_assert(heap_tag >= 0 && heap_tag < 256);- _mi_heap_init(heap, bheap->tld, arena_id, allow_destroy /* no reclaim? */, (uint8_t)heap_tag /* heap tag */);+// get (and possibly create) the theap belonging to a heap+mi_theap_t* _mi_heap_theap_get_or_init(const mi_heap_t* heap)+{+ mi_theap_t* theap = _mi_heap_theap_peek(heap);+ if mi_unlikely(theap==NULL) {+ theap = mi_heap_init_theap(heap);+ if (theap==NULL) { return (mi_theap_t*)&_mi_theap_empty_wrong; } // this will return NULL from page.c:_mi_malloc_generic+ }+ _mi_theap_cached_set(theap);+ return theap;+}+++mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t exclusive_arena_id) {+ // always allocate heap data in the (subprocess) main heap+ mi_heap_t* heap_main = mi_heap_main();+ // todo: allocate heap data in the exclusive arena ?+ mi_heap_t* heap = (mi_heap_t*)mi_heap_zalloc( heap_main, sizeof(mi_heap_t) );+ if (heap==NULL) return NULL;++ // init fields+ heap->subproc = heap_main->subproc;+ heap->heap_seq = mi_atomic_increment_relaxed(&heap_main->subproc->heap_total_count);+ heap->exclusive_arena = _mi_arena_from_id(exclusive_arena_id);+ heap->numa_node = -1; // no initial affinity++ mi_lock_init(&heap->theaps_lock);+ mi_lock_init(&heap->os_abandoned_pages_lock);+ mi_lock_init(&heap->arena_pages_lock);++ // push onto the subproc heaps+ mi_lock(&heap->subproc->heaps_lock) {+ mi_heap_t* head = heap->subproc->heaps;+ heap->prev = NULL;+ heap->next = head;+ if (head!=NULL) { head->prev = heap; }+ heap->subproc->heaps = heap;+ }+ mi_atomic_increment_relaxed(&heap_main->subproc->heap_count);+ mi_subproc_stat_increase(heap_main->subproc, heaps, 1);return heap;}-mi_decl_nodiscard mi_heap_t* mi_heap_new_in_arena(mi_arena_id_t arena_id) {- return mi_heap_new_ex(0 /* default heap tag */, false /* don't allow `mi_heap_destroy` */, arena_id);-}--mi_decl_nodiscard mi_heap_t* mi_heap_new(void) {- // don't reclaim abandoned memory or otherwise destroy is unsafe- return mi_heap_new_ex(0 /* default heap tag */, true /* no reclaim */, _mi_arena_id_none());+mi_heap_t* mi_heap_new(void) {+ return mi_heap_new_in_arena(0);}-bool _mi_heap_memid_is_suitable(mi_heap_t* heap, mi_memid_t memid) {- return _mi_arena_memid_is_suitable(memid, heap->arena_id);-}--uintptr_t _mi_heap_random_next(mi_heap_t* heap) {- return _mi_random_next(&heap->random);-}--// zero out the page queues-static void mi_heap_reset_pages(mi_heap_t* heap) {- mi_assert_internal(heap != NULL);- mi_assert_internal(mi_heap_is_initialized(heap));- // TODO: copy full empty heap instead?- memset(&heap->pages_free_direct, 0, sizeof(heap->pages_free_direct));- _mi_memcpy_aligned(&heap->pages, &_mi_heap_empty.pages, sizeof(heap->pages));- heap->thread_delayed_free = NULL;- heap->page_count = 0;-}--// called from `mi_heap_destroy` and `mi_heap_delete` to free the internal heap resources.+// free the heap resources (assuming the pages are already moved/destroyed)static void mi_heap_free(mi_heap_t* heap) {- mi_assert(heap != NULL);- mi_assert_internal(mi_heap_is_initialized(heap));- if (heap==NULL || !mi_heap_is_initialized(heap)) return;- if (mi_heap_is_backing(heap)) return; // dont free the backing heap-- // reset default- if (mi_heap_is_default(heap)) {- _mi_heap_set_default_direct(heap->tld->heap_backing);+ mi_assert_internal(heap!=NULL && !_mi_is_heap_main(heap));++ // free all theaps belonging to this heap+ mi_theap_t* theap = NULL;+ mi_lock(&heap->theaps_lock) { theap = heap->theaps; }+ while(theap != NULL) {+ mi_theap_t* next = NULL;+ mi_lock(&heap->theaps_lock) { next = theap->hnext; }+ _mi_theap_free(theap);+ theap = next;+ }+ mi_lock(&heap->theaps_lock) { theap = heap->theaps; }+ mi_assert_internal(theap==NULL);++ // free all arena pages infos+ mi_lock(&heap->arena_pages_lock) {+ for (size_t i = 0; i < MI_MAX_ARENAS; i++) {+ mi_arena_pages_t* arena_pages = mi_atomic_load_ptr_relaxed(mi_arena_pages_t, &heap->arena_pages[i]);+ if (arena_pages!=NULL) {+ mi_atomic_store_ptr_relaxed(mi_arena_pages_t, &heap->arena_pages[i], NULL);+ mi_free(arena_pages);+ }+ }}- // remove ourselves from the thread local heaps list- // linear search but we expect the number of heaps to be relatively small- mi_heap_t* prev = NULL;- mi_heap_t* curr = heap->tld->heaps;- while (curr != heap && curr != NULL) {- prev = curr;- curr = curr->next;- }- mi_assert_internal(curr == heap);- if (curr == heap) {- if (prev != NULL) { prev->next = heap->next; }- else { heap->tld->heaps = heap->next; }+ // remove the heap from the subproc+ mi_heap_stats_merge_to_main(heap);+ mi_atomic_decrement_relaxed(&heap->subproc->heap_count);+ mi_subproc_stat_decrease(heap->subproc, heaps, 1);+ mi_lock(&heap->subproc->heaps_lock) {+ if (heap->next!=NULL) { heap->next->prev = heap->prev; }+ if (heap->prev!=NULL) { heap->prev->next = heap->next; }+ else { heap->subproc->heaps = heap->next; }}- mi_assert_internal(heap->tld->heaps != NULL);- // and free the used memory+ _mi_thread_local_free(heap->theap);+ mi_lock_done(&heap->theaps_lock);+ mi_lock_done(&heap->os_abandoned_pages_lock);mi_free(heap);}-// return a heap on the same thread as `heap` specialized for the specified tag (if it exists)-mi_heap_t* _mi_heap_by_tag(mi_heap_t* heap, uint8_t tag) {- if (heap->tag == tag) {- return heap;+void mi_heap_delete(mi_heap_t* heap) {+ if (heap==NULL) return;+ if (_mi_is_heap_main(heap)) {+ _mi_warning_message("cannot delete the main heap\n");+ return;}- for (mi_heap_t *curr = heap->tld->heaps; curr != NULL; curr = curr->next) {- if (curr->tag == tag) {- return curr;- }- }- return NULL;-}--/* ------------------------------------------------------------ Heap destroy------------------------------------------------------------ */--static bool _mi_heap_page_destroy(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {- MI_UNUSED(arg1);- MI_UNUSED(arg2);- MI_UNUSED(heap);- MI_UNUSED(pq);-- // ensure no more thread_delayed_free will be added- _mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);-- // stats- const size_t bsize = mi_page_block_size(page);- if (bsize > MI_MEDIUM_OBJ_SIZE_MAX) {- if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {- mi_heap_stat_decrease(heap, large, bsize);- }- else {- mi_heap_stat_decrease(heap, huge, bsize);- }- }-#if (MI_STAT)- _mi_page_free_collect(page, false); // update used count- const size_t inuse = page->used;- if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {- mi_heap_stat_decrease(heap, normal, bsize * inuse);-#if (MI_STAT>1)- mi_heap_stat_decrease(heap, normal_bins[_mi_bin(bsize)], inuse);-#endif- }- mi_heap_stat_decrease(heap, malloc, bsize * inuse); // todo: off for aligned blocks...-#endif-- /// pretend it is all free now- mi_assert_internal(mi_page_thread_free(page) == NULL);- page->used = 0;-- // and free the page- // mi_page_free(page,false);- page->next = NULL;- page->prev = NULL;- _mi_segment_page_free(page,false /* no force? */, &heap->tld->segments);-- return true; // keep going-}--void _mi_heap_destroy_pages(mi_heap_t* heap) {- mi_heap_visit_pages(heap, &_mi_heap_page_destroy, NULL, NULL);- mi_heap_reset_pages(heap);-}--#if MI_TRACK_HEAP_DESTROY-static bool mi_cdecl mi_heap_track_block_free(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {- MI_UNUSED(heap); MI_UNUSED(area); MI_UNUSED(arg); MI_UNUSED(block_size);- mi_track_free_size(block,mi_usable_size(block));- return true;+ _mi_heap_move_pages(heap, mi_heap_main());+ mi_heap_free(heap);}-#endifvoid mi_heap_destroy(mi_heap_t* heap) {- mi_assert(heap != NULL);- mi_assert(mi_heap_is_initialized(heap));- mi_assert(heap->no_reclaim);- mi_assert_expensive(mi_heap_is_valid(heap));- if (heap==NULL || !mi_heap_is_initialized(heap)) return;- #if MI_GUARDED- // _mi_warning_message("'mi_heap_destroy' called but MI_GUARDED is enabled -- using `mi_heap_delete` instead (heap at %p)\n", heap);- mi_heap_delete(heap);- return;- #else- if (!heap->no_reclaim) {- _mi_warning_message("'mi_heap_destroy' called but ignored as the heap was not created with 'allow_destroy' (heap at %p)\n", heap);- // don't free in case it may contain reclaimed pages- mi_heap_delete(heap);+ if (heap==NULL) return;+ if (_mi_is_heap_main(heap)) {+ _mi_warning_message("cannot destroy the main heap\n");+ return;}- else {- // track all blocks as freed- #if MI_TRACK_HEAP_DESTROY- mi_heap_visit_blocks(heap, true, mi_heap_track_block_free, NULL);- #endif- // free all pages- _mi_heap_destroy_pages(heap);- mi_heap_free(heap);- }- #endif-}--// forcefully destroy all heaps in the current thread-void _mi_heap_unsafe_destroy_all(mi_heap_t* heap) {- mi_assert_internal(heap != NULL);- if (heap == NULL) return;- mi_heap_t* curr = heap->tld->heaps;- while (curr != NULL) {- mi_heap_t* next = curr->next;- if (curr->no_reclaim) {- mi_heap_destroy(curr);- }- else {- _mi_heap_destroy_pages(curr);- }- curr = next;- }-}--/* ------------------------------------------------------------ Safe Heap delete------------------------------------------------------------ */--// Transfer the pages from one heap to the other-static void mi_heap_absorb(mi_heap_t* heap, mi_heap_t* from) {- mi_assert_internal(heap!=NULL);- if (from==NULL || from->page_count == 0) return;-- // reduce the size of the delayed frees- _mi_heap_delayed_free_partial(from);-- // transfer all pages by appending the queues; this will set a new heap field- // so threads may do delayed frees in either heap for a while.- // note: appending waits for each page to not be in the `MI_DELAYED_FREEING` state- // so after this only the new heap will get delayed frees- for (size_t i = 0; i <= MI_BIN_FULL; i++) {- mi_page_queue_t* pq = &heap->pages[i];- mi_page_queue_t* append = &from->pages[i];- size_t pcount = _mi_page_queue_append(heap, pq, append);- heap->page_count += pcount;- from->page_count -= pcount;- }- mi_assert_internal(from->page_count == 0);-- // and do outstanding delayed frees in the `from` heap- // note: be careful here as the `heap` field in all those pages no longer point to `from`,- // turns out to be ok as `_mi_heap_delayed_free` only visits the list and calls a- // the regular `_mi_free_delayed_block` which is safe.- _mi_heap_delayed_free_all(from);- #if !defined(_MSC_VER) || (_MSC_VER > 1900) // somehow the following line gives an error in VS2015, issue #353- mi_assert_internal(mi_atomic_load_ptr_relaxed(mi_block_t,&from->thread_delayed_free) == NULL);- #endif-- // and reset the `from` heap- mi_heap_reset_pages(from);-}--// are two heaps compatible with respect to heap-tag, exclusive arena etc.-static bool mi_heaps_are_compatible(mi_heap_t* heap1, mi_heap_t* heap2) {- return (heap1->tag == heap2->tag && // store same kind of objects- heap1->arena_id == heap2->arena_id); // same arena preference-}--// Safe delete a heap without freeing any still allocated blocks in that heap.-void mi_heap_delete(mi_heap_t* heap)-{- mi_assert(heap != NULL);- mi_assert(mi_heap_is_initialized(heap));- mi_assert_expensive(mi_heap_is_valid(heap));- if (heap==NULL || !mi_heap_is_initialized(heap)) return;-- mi_heap_t* bheap = heap->tld->heap_backing;- if (bheap != heap && mi_heaps_are_compatible(bheap,heap)) {- // transfer still used pages to the backing heap- mi_heap_absorb(bheap, heap);- }- else {- // the backing heap abandons its pages- _mi_heap_collect_abandon(heap);- }- mi_assert_internal(heap->page_count==0);+ _mi_heap_destroy_pages(heap);mi_heap_free(heap);}-mi_heap_t* mi_heap_set_default(mi_heap_t* heap) {- mi_assert(heap != NULL);- mi_assert(mi_heap_is_initialized(heap));- if (heap==NULL || !mi_heap_is_initialized(heap)) return NULL;- mi_assert_expensive(mi_heap_is_valid(heap));- mi_heap_t* old = mi_prim_get_default_heap();- _mi_heap_set_default_direct(heap);- return old;+mi_heap_t* mi_heap_of(const void* p) {+ mi_page_t* page = _mi_safe_ptr_page(p);+ if (page==NULL) return NULL;+ return mi_page_heap(page);}----/* ------------------------------------------------------------ Analysis------------------------------------------------------------ */--// static since it is not thread safe to access heaps from other threads.-static mi_heap_t* mi_heap_of_block(const void* p) {- if (p == NULL) return NULL;- mi_segment_t* segment = _mi_ptr_segment(p);- bool valid = (_mi_ptr_cookie(segment) == segment->cookie);- mi_assert_internal(valid);- if mi_unlikely(!valid) return NULL;- return mi_page_heap(_mi_segment_page_of(segment,p));-}--bool mi_heap_contains_block(mi_heap_t* heap, const void* p) {- mi_assert(heap != NULL);- if (heap==NULL || !mi_heap_is_initialized(heap)) return false;- return (heap == mi_heap_of_block(p));-}---static bool mi_heap_page_check_owned(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* p, void* vfound) {- MI_UNUSED(heap);- MI_UNUSED(pq);- bool* found = (bool*)vfound;- void* start = mi_page_start(page);- void* end = (uint8_t*)start + (page->capacity * mi_page_block_size(page));- *found = (p >= start && p < end);- return (!*found); // continue if not found+bool mi_any_heap_contains(const void* p) {+ return (mi_heap_of(p)!=NULL);}-bool mi_heap_check_owned(mi_heap_t* heap, const void* p) {- mi_assert(heap != NULL);- if (heap==NULL || !mi_heap_is_initialized(heap)) return false;- if (((uintptr_t)p & (MI_INTPTR_SIZE - 1)) != 0) return false; // only aligned pointers- bool found = false;- mi_heap_visit_pages(heap, &mi_heap_page_check_owned, (void*)p, &found);- return found;+bool mi_heap_contains(const mi_heap_t* heap, const void* p) {+ if (heap==NULL) { heap = mi_heap_main(); }+ return (heap==mi_heap_of(p));}+// deprecatedbool mi_check_owned(const void* p) {- return mi_heap_check_owned(mi_prim_get_default_heap(), p);-}--/* ------------------------------------------------------------ Visit all heap blocks and areas- Todo: enable visiting abandoned pages, and- enable visiting all blocks of all heaps across threads------------------------------------------------------------ */--void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page) {- const size_t bsize = mi_page_block_size(page);- const size_t ubsize = mi_page_usable_block_size(page);- area->reserved = page->reserved * bsize;- area->committed = page->capacity * bsize;- area->blocks = mi_page_start(page);- area->used = page->used; // number of blocks in use (#553)- area->block_size = ubsize;- area->full_block_size = bsize;- area->heap_tag = page->heap_tag;-}---static void mi_get_fast_divisor(size_t divisor, uint64_t* magic, size_t* shift) {- mi_assert_internal(divisor > 0 && divisor <= UINT32_MAX);- *shift = MI_INTPTR_BITS - mi_clz(divisor - 1);- *magic = ((((uint64_t)1 << 32) * (((uint64_t)1 << *shift) - divisor)) / divisor + 1);-}--static size_t mi_fast_divide(size_t n, uint64_t magic, size_t shift) {- mi_assert_internal(n <= UINT32_MAX);- const uint64_t hi = ((uint64_t)n * magic) >> 32;- return (size_t)((hi + n) >> shift);-}--bool _mi_heap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg) {- mi_assert(area != NULL);- if (area==NULL) return true;- mi_assert(page != NULL);- if (page == NULL) return true;-- _mi_page_free_collect(page,true); // collect both thread_delayed and local_free- mi_assert_internal(page->local_free == NULL);- if (page->used == 0) return true;-- size_t psize;- uint8_t* const pstart = _mi_segment_page_start(_mi_page_segment(page), page, &psize);- mi_heap_t* const heap = mi_page_heap(page);- const size_t bsize = mi_page_block_size(page);- const size_t ubsize = mi_page_usable_block_size(page); // without padding-- // optimize page with one block- if (page->capacity == 1) {- mi_assert_internal(page->used == 1 && page->free == NULL);- return visitor(mi_page_heap(page), area, pstart, ubsize, arg);- }- mi_assert(bsize <= UINT32_MAX);-- // optimize full pages- if (page->used == page->capacity) {- uint8_t* block = pstart;- for (size_t i = 0; i < page->capacity; i++) {- if (!visitor(heap, area, block, ubsize, arg)) return false;- block += bsize;- }- return true;- }-- // create a bitmap of free blocks.- #define MI_MAX_BLOCKS (MI_SMALL_PAGE_SIZE / sizeof(void*))- uintptr_t free_map[MI_MAX_BLOCKS / MI_INTPTR_BITS];- const uintptr_t bmapsize = _mi_divide_up(page->capacity, MI_INTPTR_BITS);- memset(free_map, 0, bmapsize * sizeof(intptr_t));- if (page->capacity % MI_INTPTR_BITS != 0) {- // mark left-over bits at the end as free- size_t shift = (page->capacity % MI_INTPTR_BITS);- uintptr_t mask = (UINTPTR_MAX << shift);- free_map[bmapsize - 1] = mask;- }-- // fast repeated division by the block size- uint64_t magic;- size_t shift;- mi_get_fast_divisor(bsize, &magic, &shift);-- #if MI_DEBUG>1- size_t free_count = 0;- #endif- for (mi_block_t* block = page->free; block != NULL; block = mi_block_next(page, block)) {- #if MI_DEBUG>1- free_count++;- #endif- mi_assert_internal((uint8_t*)block >= pstart && (uint8_t*)block < (pstart + psize));- size_t offset = (uint8_t*)block - pstart;- mi_assert_internal(offset % bsize == 0);- mi_assert_internal(offset <= UINT32_MAX);- size_t blockidx = mi_fast_divide(offset, magic, shift);- mi_assert_internal(blockidx == offset / bsize);- mi_assert_internal(blockidx < MI_MAX_BLOCKS);- size_t bitidx = (blockidx / MI_INTPTR_BITS);- size_t bit = blockidx - (bitidx * MI_INTPTR_BITS);- free_map[bitidx] |= ((uintptr_t)1 << bit);- }- mi_assert_internal(page->capacity == (free_count + page->used));-- // walk through all blocks skipping the free ones- #if MI_DEBUG>1- size_t used_count = 0;- #endif- uint8_t* block = pstart;- for (size_t i = 0; i < bmapsize; i++) {- if (free_map[i] == 0) {- // every block is in use- for (size_t j = 0; j < MI_INTPTR_BITS; j++) {- #if MI_DEBUG>1- used_count++;- #endif- if (!visitor(heap, area, block, ubsize, arg)) return false;- block += bsize;- }- }- else {- // visit the used blocks in the mask- uintptr_t m = ~free_map[i];- while (m != 0) {- #if MI_DEBUG>1- used_count++;- #endif- size_t bitidx = mi_ctz(m);- if (!visitor(heap, area, block + (bitidx * bsize), ubsize, arg)) return false;- m &= m - 1; // clear least significant bit- }- block += bsize * MI_INTPTR_BITS;- }- }- mi_assert_internal(page->used == used_count);- return true;-}----// Separate struct to keep `mi_page_t` out of the public interface-typedef struct mi_heap_area_ex_s {- mi_heap_area_t area;- mi_page_t* page;-} mi_heap_area_ex_t;--typedef bool (mi_heap_area_visit_fun)(const mi_heap_t* heap, const mi_heap_area_ex_t* area, void* arg);--static bool mi_heap_visit_areas_page(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_t* page, void* vfun, void* arg) {- MI_UNUSED(heap);- MI_UNUSED(pq);- mi_heap_area_visit_fun* fun = (mi_heap_area_visit_fun*)vfun;- mi_heap_area_ex_t xarea;- xarea.page = page;- _mi_heap_area_init(&xarea.area, page);- return fun(heap, &xarea, arg);-}--// Visit all heap pages as areas-static bool mi_heap_visit_areas(const mi_heap_t* heap, mi_heap_area_visit_fun* visitor, void* arg) {- if (visitor == NULL) return false;- return mi_heap_visit_pages((mi_heap_t*)heap, &mi_heap_visit_areas_page, (void*)(visitor), arg); // note: function pointer to void* :-{-}--// Just to pass arguments-typedef struct mi_visit_blocks_args_s {- bool visit_blocks;- mi_block_visit_fun* visitor;- void* arg;-} mi_visit_blocks_args_t;--static bool mi_heap_area_visitor(const mi_heap_t* heap, const mi_heap_area_ex_t* xarea, void* arg) {- mi_visit_blocks_args_t* args = (mi_visit_blocks_args_t*)arg;- if (!args->visitor(heap, &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;- if (args->visit_blocks) {- return _mi_heap_area_visit_blocks(&xarea->area, xarea->page, args->visitor, args->arg);- }- else {- return true;- }-}--// Visit all blocks in a heap-bool mi_heap_visit_blocks(const mi_heap_t* heap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {- mi_visit_blocks_args_t args = { visit_blocks, visitor, arg };- return mi_heap_visit_areas(heap, &mi_heap_area_visitor, &args);+ return mi_any_heap_contains(p);}diff --git a/vendored/mimalloc/src/init.c b/vendored/mimalloc/src/init.cindex a2d01db1d..3161450fd 100644--- a/vendored/mimalloc/src/init.c+++ b/vendored/mimalloc/src/init.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2022, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -11,35 +11,34 @@ terms of the MIT license. A copy of the license can be found in the file#include <string.h> // memcpy, memset#include <stdlib.h> // atexit+#define MI_MEMID_INIT(kind) {{{NULL,0}}, kind, true /* pinned */, true /* committed */, false /* zero */ }+#define MI_MEMID_STATIC MI_MEMID_INIT(MI_MEM_STATIC)// Empty page used to initialize the small free pages arrayconst mi_page_t _mi_page_empty = {- 0,- false, false, false, false,- 0, // capacity- 0, // reserved capacity- { 0 }, // flags- false, // is_zero- 0, // retire_expire- NULL, // free- NULL, // local_free- 0, // used- 0, // block size shift- 0, // heap tag- 0, // block_size- NULL, // page_start+ MI_ATOMIC_VAR_INIT(0), // xthread_id+ NULL, // free+ 0, // used+ 0, // capacity+ 0, // reserved capacity+ 0, // retire_expire+ false, // is_zero+ NULL, // local_free+ MI_ATOMIC_VAR_INIT(0), // xthread_free+ 0, // block_size+ NULL, // page_start#if (MI_PADDING || MI_ENCODE_FREELIST)- { 0, 0 },+ { 0, 0 }, // keys#endif- MI_ATOMIC_VAR_INIT(0), // xthread_free- MI_ATOMIC_VAR_INIT(0), // xheap- NULL, NULL- , { 0 } // padding+ NULL, // theap+ NULL, // heap+ NULL, NULL, // next, prev+ MI_ARENA_SLICE_SIZE, // page_committed+ MI_MEMID_STATIC // memid};#define MI_PAGE_EMPTY() ((mi_page_t*)&_mi_page_empty)-#if (MI_SMALL_WSIZE_MAX==128)#if (MI_PADDING>0) && (MI_INTPTR_SIZE >= 8)#define MI_SMALL_PAGES_EMPTY { MI_INIT128(MI_PAGE_EMPTY), MI_PAGE_EMPTY(), MI_PAGE_EMPTY() }#elif (MI_PADDING>0)@@ -47,12 +46,10 @@ const mi_page_t _mi_page_empty = {#else#define MI_SMALL_PAGES_EMPTY { MI_INIT128(MI_PAGE_EMPTY), MI_PAGE_EMPTY() }#endif-#else-#error "define right initialization sizes corresponding to MI_SMALL_WSIZE_MAX"-#endif+// Empty page queues for every bin-#define QNULL(sz) { NULL, NULL, (sz)*sizeof(uintptr_t) }+#define QNULL(sz) { NULL, NULL, 0, (sz)*sizeof(uintptr_t) }#define MI_PAGE_QUEUES_EMPTY \{ QNULL(1), \QNULL( 1), QNULL( 2), QNULL( 3), QNULL( 4), QNULL( 5), QNULL( 6), QNULL( 7), QNULL( 8), /* 8 */ \@@ -64,410 +61,536 @@ const mi_page_t _mi_page_empty = {QNULL( 10240), QNULL( 12288), QNULL( 14336), QNULL( 16384), QNULL( 20480), QNULL( 24576), QNULL( 28672), QNULL( 32768), /* 56 */ \QNULL( 40960), QNULL( 49152), QNULL( 57344), QNULL( 65536), QNULL( 81920), QNULL( 98304), QNULL(114688), QNULL(131072), /* 64 */ \QNULL(163840), QNULL(196608), QNULL(229376), QNULL(262144), QNULL(327680), QNULL(393216), QNULL(458752), QNULL(524288), /* 72 */ \- QNULL(MI_MEDIUM_OBJ_WSIZE_MAX + 1 /* 655360, Huge queue */), \- QNULL(MI_MEDIUM_OBJ_WSIZE_MAX + 2) /* Full queue */ }+ QNULL(MI_LARGE_MAX_OBJ_WSIZE + 1 /* 655360, Huge queue */), \+ QNULL(MI_LARGE_MAX_OBJ_WSIZE + 2) /* Full queue */ }-#define MI_STAT_COUNT_NULL() {0,0,0,0}+#define MI_STAT_COUNT_NULL() {0,0,0}// Empty statistics-#if MI_STAT>1-#define MI_STAT_COUNT_END_NULL() , { MI_STAT_COUNT_NULL(), MI_INIT32(MI_STAT_COUNT_NULL) }-#else-#define MI_STAT_COUNT_END_NULL()-#endif-#define MI_STATS_NULL \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \- MI_STAT_COUNT_NULL(), \- { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, \- { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, \- { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, \- { 0, 0 }, { 0, 0 } \- MI_STAT_COUNT_END_NULL()---// Empty slice span queues for every bin-#define SQNULL(sz) { NULL, NULL, sz }-#define MI_SEGMENT_SPAN_QUEUES_EMPTY \- { SQNULL(1), \- SQNULL( 1), SQNULL( 2), SQNULL( 3), SQNULL( 4), SQNULL( 5), SQNULL( 6), SQNULL( 7), SQNULL( 10), /* 8 */ \- SQNULL( 12), SQNULL( 14), SQNULL( 16), SQNULL( 20), SQNULL( 24), SQNULL( 28), SQNULL( 32), SQNULL( 40), /* 16 */ \- SQNULL( 48), SQNULL( 56), SQNULL( 64), SQNULL( 80), SQNULL( 96), SQNULL( 112), SQNULL( 128), SQNULL( 160), /* 24 */ \- SQNULL( 192), SQNULL( 224), SQNULL( 256), SQNULL( 320), SQNULL( 384), SQNULL( 448), SQNULL( 512), SQNULL( 640), /* 32 */ \- SQNULL( 768), SQNULL( 896), SQNULL( 1024) /* 35 */ }-+ MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \+ { 0 }, { 0 }, \+ MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \+ MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), MI_STAT_COUNT_NULL(), \+ { 0 }, { 0 }, { 0 }, { 0 }, \+ { 0 }, { 0 }, { 0 }, { 0 }, \+ \+ { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, \+ MI_INIT5(MI_STAT_COUNT_NULL), \+ { 0 }, { 0 }, { 0 }, { 0 }, \+ \+ { MI_INIT4(MI_STAT_COUNT_NULL) }, \+ { { 0 }, { 0 }, { 0 }, { 0 } }, \+ \+ { MI_INIT74(MI_STAT_COUNT_NULL) }, \+ { MI_INIT74(MI_STAT_COUNT_NULL) }, \+ { MI_INIT5(MI_STAT_COUNT_NULL) }// ---------------------------------------------------------// Statically allocate an empty heap as the initial-// thread local value for the default heap,-// and statically allocate the backing heap for the main+// Statically allocate an empty theap as the initial+// thread local value for the default theap,+// and statically allocate the backing theap for the main// thread so it can function without doing any allocation// itself (as accessing a thread local for the first time// may lead to allocation itself on some platforms)// ---------------------------------------------------------mi_decl_cache_align const mi_heap_t _mi_heap_empty = {- NULL,- MI_ATOMIC_VAR_INIT(NULL),- 0, // tid- 0, // cookie- 0, // arena id- { 0, 0 }, // keys- { {0}, {0}, 0, true }, // random- 0, // page count- MI_BIN_FULL, 0, // page retired min/max- NULL, // next- false, // can reclaim- 0, // tag+static mi_decl_cache_align mi_subproc_t subproc_main+#if __cplusplus+= { }; // empty initializer to prevent running the constructor (with msvc)+#else+= { 0 }; // C zero initialize+#endif++static mi_subproc_t* subprocs = &subproc_main;+static mi_lock_t subprocs_lock;++static mi_decl_cache_align mi_tld_t tld_empty = {+ 0, // thread_id+ 0, // thread_seq+ 0, // default numa node+ &subproc_main, // subproc+ NULL, // theaps list+ false, // recurse+ false, // is_in_threadpool+ MI_MEMID_STATIC // memid+};++mi_decl_cache_align const mi_theap_t _mi_theap_empty = {+ &tld_empty, // tld+ NULL, // heap+ 0, // heartbeat+ 0, // cookie+ { {0}, {0}, 0, true }, // random+ 0, // page count+ MI_BIN_FULL, 0, // page retired min/max+ 0, 0, // generic count+ NULL, NULL, // tnext, tprev+ NULL, NULL, // hnext, hprev+ 0, // full page retain+ false, // allow reclaim+ true, // allow abandon#if MI_GUARDED- 0, 0, 0, 0, 1, // count is 1 so we never write to it (see `internal.h:mi_heap_malloc_use_guarded`)+ 0, 0, 0, 1, // sample count is 1 so we never write to it (see `internal.h:mi_theap_malloc_use_guarded`)#endifMI_SMALL_PAGES_EMPTY,- MI_PAGE_QUEUES_EMPTY+ MI_PAGE_QUEUES_EMPTY,+ MI_MEMID_STATIC,+ { sizeof(mi_stats_t), MI_STAT_VERSION, MI_STATS_NULL }, // stats};-static mi_decl_cache_align mi_subproc_t mi_subproc_default;--#define tld_empty_stats ((mi_stats_t*)((uint8_t*)&tld_empty + offsetof(mi_tld_t,stats)))--mi_decl_cache_align static const mi_tld_t tld_empty = {- 0,- false,- NULL, NULL,- { MI_SEGMENT_SPAN_QUEUES_EMPTY, 0, 0, 0, 0, 0, &mi_subproc_default, tld_empty_stats }, // segments- { MI_STATS_NULL } // stats+mi_decl_cache_align const mi_theap_t _mi_theap_empty_wrong = {+ &tld_empty, // tld+ NULL, // heap+ 0, // heartbeat+ 0, // cookie+ { {0}, {0}, 0, true }, // random+ 0, // page count+ MI_BIN_FULL, 0, // page retired min/max+ 0, 0, // generic count+ NULL, NULL, // tnext, tprev+ NULL, NULL, // hnext, hprev+ 0, // full page retain+ false, // allow reclaim+ true, // allow abandon+ #if MI_GUARDED+ 0, 0, 0, 1, // sample count is 1 so we never write to it (see `internal.h:mi_theap_malloc_use_guarded`)+ #endif+ MI_SMALL_PAGES_EMPTY,+ MI_PAGE_QUEUES_EMPTY,+ MI_MEMID_STATIC,+ { sizeof(mi_stats_t), MI_STAT_VERSION, MI_STATS_NULL }, // stats};-mi_threadid_t _mi_thread_id(void) mi_attr_noexcept {- return _mi_prim_thread_id();-}--// the thread-local default heap for allocation-mi_decl_thread mi_heap_t* _mi_heap_default = (mi_heap_t*)&_mi_heap_empty;+// Heap for the main thread-extern mi_heap_t _mi_heap_main;+extern mi_decl_hidden mi_decl_cache_align mi_theap_t theap_main;+extern mi_decl_hidden mi_decl_cache_align mi_heap_t heap_main;static mi_decl_cache_align mi_tld_t tld_main = {- 0, false,- &_mi_heap_main, & _mi_heap_main,- { MI_SEGMENT_SPAN_QUEUES_EMPTY, 0, 0, 0, 0, 0, &mi_subproc_default, &tld_main.stats }, // segments- { MI_STATS_NULL } // stats+ 0, // thread_id+ 0, // thread_seq+ 0, // numa node+ &subproc_main, // subproc+ &theap_main, // theaps list+ false, // recurse+ false, // is_in_threadpool+ MI_MEMID_STATIC // memid};-mi_decl_cache_align mi_heap_t _mi_heap_main = {- &tld_main,- MI_ATOMIC_VAR_INIT(NULL),- 0, // thread id- 0, // initial cookie- 0, // arena id- { 0, 0 }, // the key of the main heap can be fixed (unlike page keys that need to be secure!)+mi_decl_cache_align mi_theap_t theap_main = {+ &tld_main, // thread local data+ &heap_main, // main heap+ 0, // heartbeat+ 0, // initial cookie{ {0x846ca68b}, {0}, 0, true }, // random- 0, // page count- MI_BIN_FULL, 0, // page retired min/max- NULL, // next heap- false, // can reclaim- 0, // tag+ 0, // page count+ MI_BIN_FULL, 0, // page retired min/max+ 0, 0, // generic count+ NULL, NULL, // tnext, tprev+ NULL, NULL, // hnext, hprev+ 2, // full page retain+ true, // allow page reclaim+ true, // allow page abandon#if MI_GUARDED- 0, 0, 0, 0, 0,+ 0, 0, 0, 0,#endifMI_SMALL_PAGES_EMPTY,- MI_PAGE_QUEUES_EMPTY+ MI_PAGE_QUEUES_EMPTY,+ MI_MEMID_STATIC,+ { sizeof(mi_stats_t), MI_STAT_VERSION, MI_STATS_NULL }, // stats};+mi_decl_cache_align mi_heap_t heap_main+#if __cplusplus+ = { }; // empty initializer to prevent running the constructor (with msvc)+#else+ = { 0 }; // C zero initialize+#endif++mi_threadid_t _mi_thread_id(void) mi_attr_noexcept {+ return _mi_prim_thread_id();+}++// the theap belonging to the main heap+mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_main = NULL;++#if MI_TLS_MODEL_THREAD_LOCAL+// the thread-local main theap for allocation+mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_default = (mi_theap_t*)&_mi_theap_empty;+// the last used non-main theap+mi_decl_hidden mi_decl_thread mi_theap_t* __mi_theap_cached = (mi_theap_t*)&_mi_theap_empty;+#endif+bool _mi_process_is_initialized = false; // set to `true` in `mi_process_init`.-mi_stats_t _mi_stats_main = { MI_STATS_NULL };+mi_stats_t _mi_stats_main = { sizeof(mi_stats_t), MI_STAT_VERSION, MI_STATS_NULL };#if MI_GUARDED-mi_decl_export void mi_heap_guarded_set_sample_rate(mi_heap_t* heap, size_t sample_rate, size_t seed) {- heap->guarded_sample_seed = seed;- if (heap->guarded_sample_seed == 0) {- heap->guarded_sample_seed = _mi_heap_random_next(heap);- }- heap->guarded_sample_rate = sample_rate;- if (heap->guarded_sample_rate >= 1) {- heap->guarded_sample_seed = heap->guarded_sample_seed % heap->guarded_sample_rate;+mi_decl_export void mi_theap_guarded_set_sample_rate(mi_theap_t* theap, size_t sample_rate, size_t seed) {+ theap->guarded_sample_rate = sample_rate;+ theap->guarded_sample_count = sample_rate; // count down samples+ if (theap->guarded_sample_rate > 1) {+ if (seed == 0) {+ seed = _mi_theap_random_next(theap);+ }+ theap->guarded_sample_count = (seed % theap->guarded_sample_rate) + 1; // start at random count between 1 and `sample_rate`}- heap->guarded_sample_count = heap->guarded_sample_seed; // count down samples}-mi_decl_export void mi_heap_guarded_set_size_bound(mi_heap_t* heap, size_t min, size_t max) {- heap->guarded_size_min = min;- heap->guarded_size_max = (min > max ? min : max);+mi_decl_export void mi_theap_guarded_set_size_bound(mi_theap_t* theap, size_t min, size_t max) {+ theap->guarded_size_min = min;+ theap->guarded_size_max = (min > max ? min : max);}-void _mi_heap_guarded_init(mi_heap_t* heap) {- mi_heap_guarded_set_sample_rate(heap,+void _mi_theap_guarded_init(mi_theap_t* theap) {+ mi_theap_guarded_set_sample_rate(theap,(size_t)mi_option_get_clamp(mi_option_guarded_sample_rate, 0, LONG_MAX),(size_t)mi_option_get(mi_option_guarded_sample_seed));- mi_heap_guarded_set_size_bound(heap,+ mi_theap_guarded_set_size_bound(theap,(size_t)mi_option_get_clamp(mi_option_guarded_min, 0, LONG_MAX),(size_t)mi_option_get_clamp(mi_option_guarded_max, 0, LONG_MAX) );}#else-mi_decl_export void mi_heap_guarded_set_sample_rate(mi_heap_t* heap, size_t sample_rate, size_t seed) {- MI_UNUSED(heap); MI_UNUSED(sample_rate); MI_UNUSED(seed);+mi_decl_export void mi_theap_guarded_set_sample_rate(mi_theap_t* theap, size_t sample_rate, size_t seed) {+ MI_UNUSED(theap); MI_UNUSED(sample_rate); MI_UNUSED(seed);}-mi_decl_export void mi_heap_guarded_set_size_bound(mi_heap_t* heap, size_t min, size_t max) {- MI_UNUSED(heap); MI_UNUSED(min); MI_UNUSED(max);+mi_decl_export void mi_theap_guarded_set_size_bound(mi_theap_t* theap, size_t min, size_t max) {+ MI_UNUSED(theap); MI_UNUSED(min); MI_UNUSED(max);}-void _mi_heap_guarded_init(mi_heap_t* heap) {- MI_UNUSED(heap);+void _mi_theap_guarded_init(mi_theap_t* theap) {+ MI_UNUSED(theap);}#endif+/* -----------------------------------------------------------+ Initialization+ Note: on some platforms lock_init or just a thread local access+ can cause allocation and induce recursion during initialization.+----------------------------------------------------------- */+-static void mi_heap_main_init(void) {- if (_mi_heap_main.cookie == 0) {- _mi_heap_main.thread_id = _mi_thread_id();- _mi_heap_main.cookie = 1;- #if defined(_WIN32) && !defined(MI_SHARED_LIB)- _mi_random_init_weak(&_mi_heap_main.random); // prevent allocation failure during bcrypt dll initialization with static linking+// Initialize main subproc+static void mi_subproc_main_init(void) {+ if (subproc_main.memid.memkind != MI_MEM_STATIC) {+ subproc_main.memid = _mi_memid_create(MI_MEM_STATIC);+ subproc_main.heaps = &heap_main;+ subproc_main.heap_total_count = 1;+ subproc_main.heap_count = 1;+ mi_atomic_store_ptr_release(mi_heap_t, &subproc_main.heap_main, &heap_main);+ __mi_stat_increase_mt(&subproc_main.stats.heaps, 1);+ mi_lock_init(&subproc_main.arena_reserve_lock);+ mi_lock_init(&subproc_main.heaps_lock);+ mi_lock_init(&subprocs_lock);+ }+}++// Initialize main tld+static void mi_tld_main_init(void) {+ if (tld_main.thread_id == 0) {+ tld_main.thread_id = _mi_prim_thread_id();+ }+}++void _mi_theap_options_init(mi_theap_t* theap) {+ theap->allow_page_reclaim = (mi_option_get(mi_option_page_reclaim_on_free) >= 0);+ theap->allow_page_abandon = (mi_option_get(mi_option_page_full_retain) >= 0);+ theap->page_full_retain = mi_option_get_clamp(mi_option_page_full_retain, -1, 32);+}++// Initialization of the (statically allocated) main theap, and the main tld and subproc.+static void mi_theap_main_init(void) {+ if mi_unlikely(theap_main.memid.memkind != MI_MEM_STATIC) {+ // theap+ theap_main.memid = _mi_memid_create(MI_MEM_STATIC);+ #if defined(__APPLE__) || defined(_WIN32) && !defined(MI_SHARED_LIB)+ _mi_random_init_weak(&theap_main.random); // prevent allocation failure during bcrypt dll initialization with static linking (issue #1185)#else- _mi_random_init(&_mi_heap_main.random);+ _mi_random_init(&theap_main.random);#endif- _mi_heap_main.cookie = _mi_heap_random_next(&_mi_heap_main);- _mi_heap_main.keys[0] = _mi_heap_random_next(&_mi_heap_main);- _mi_heap_main.keys[1] = _mi_heap_random_next(&_mi_heap_main);- mi_lock_init(&mi_subproc_default.abandoned_os_lock);- mi_lock_init(&mi_subproc_default.abandoned_os_visit_lock);- _mi_heap_guarded_init(&_mi_heap_main);+ theap_main.cookie = _mi_theap_random_next(&theap_main);+ _mi_theap_options_init(&theap_main);+ _mi_theap_guarded_init(&theap_main);}}-mi_heap_t* _mi_heap_main_get(void) {- mi_heap_main_init();- return &_mi_heap_main;+// Initialize main heap+static void mi_heap_main_init(void) {+ if mi_unlikely(heap_main.subproc == NULL) {+ heap_main.subproc = &subproc_main;+ heap_main.theaps = &theap_main;++ mi_theap_main_init();+ mi_subproc_main_init();+ mi_tld_main_init();++ mi_lock_init(&heap_main.theaps_lock);+ mi_lock_init(&heap_main.os_abandoned_pages_lock);+ mi_lock_init(&heap_main.arena_pages_lock);+ }}/* ------------------------------------------------------------ Sub process+ Thread local data----------------------------------------------------------- */-mi_subproc_id_t mi_subproc_main(void) {- return NULL;+// Allocate fresh tld+static mi_tld_t* mi_tld_alloc(void) {+ if (_mi_is_main_thread()) {+ mi_atomic_increment_relaxed(&tld_main.subproc->thread_count);+ return &tld_main;+ }+ else {+ // allocate tld meta-data+ // note: we need to be careful to not access the tld from `_mi_meta_zalloc`+ // (and in turn from `_mi_arena_alloc_aligned` and `_mi_os_alloc_aligned`).+ mi_memid_t memid;+ mi_tld_t* tld = (mi_tld_t*)_mi_meta_zalloc(sizeof(mi_tld_t), &memid);+ if (tld==NULL) {+ _mi_error_message(ENOMEM, "unable to allocate memory for thread local data\n");+ return NULL;+ }+ tld->memid = memid;+ tld->theaps = NULL;+ tld->subproc = &subproc_main;+ tld->numa_node = _mi_os_numa_node();+ tld->thread_id = _mi_prim_thread_id();+ tld->thread_seq = mi_atomic_increment_relaxed(&tld->subproc->thread_total_count);+ tld->is_in_threadpool = _mi_prim_thread_is_in_threadpool();+ mi_atomic_increment_relaxed(&tld->subproc->thread_count);+ return tld;+ }}-mi_subproc_id_t mi_subproc_new(void) {- mi_memid_t memid = _mi_memid_none();- mi_subproc_t* subproc = (mi_subproc_t*)_mi_arena_meta_zalloc(sizeof(mi_subproc_t), &memid);- if (subproc == NULL) return NULL;- subproc->memid = memid;- subproc->abandoned_os_list = NULL;- mi_lock_init(&subproc->abandoned_os_lock);- mi_lock_init(&subproc->abandoned_os_visit_lock);- return subproc;+#define MI_TLD_INVALID ((mi_tld_t*)1)++mi_decl_noinline static void mi_tld_free(mi_tld_t* tld) {+ if (tld != NULL && tld != MI_TLD_INVALID) {+ mi_atomic_decrement_relaxed(&tld->subproc->thread_count);+ _mi_meta_free(tld, sizeof(mi_tld_t), tld->memid);+ }+ #if 0+ // do not read/write to `thread_tld` on older macOS <= 14 as that will re-initialize the thread local storage+ // (since we are calling this during pthread shutdown)+ // (and this could happen on other systems as well, so let's never do it)+ thread_tld = MI_TLD_INVALID;+ #endif}-mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id) {- return (subproc_id == NULL ? &mi_subproc_default : (mi_subproc_t*)subproc_id);+// return the thread local heap ensuring it is initialized (and not `NULL` or `&_mi_theap_empty`);+mi_theap_t* _mi_theap_default_safe(void) {+ mi_theap_t* theap = _mi_theap_default();+ if mi_likely(mi_theap_is_initialized(theap)) return theap;+ mi_thread_init();+ mi_assert_internal(mi_theap_is_initialized(_mi_theap_default()));+ return _mi_theap_default();}-void mi_subproc_delete(mi_subproc_id_t subproc_id) {- if (subproc_id == NULL) return;- mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);- // check if there are no abandoned segments still..- bool safe_to_delete = false;- mi_lock(&subproc->abandoned_os_lock) {- if (subproc->abandoned_os_list == NULL) {- safe_to_delete = true;- }++mi_subproc_t* _mi_subproc_main(void) {+ return &subproc_main;+}++mi_subproc_t* _mi_subproc(void) {+ // should work without doing initialization (as it may be called from `_mi_tld -> mi_tld_alloc ... -> os_alloc -> _mi_subproc()`+ // todo: this will still fail on OS systems where the first access to a thread-local causes allocation.+ // on such systems we can check for this with the _mi_prim_get_default_theap as those are protected (by being+ // stored in a TLS slot for example)+ mi_theap_t* theap = _mi_theap_default();+ if (theap == NULL) {+ return _mi_subproc_main();+ }+ else {+ return theap->tld->subproc; // avoid using thread local storage (`thread_tld`)}- if (!safe_to_delete) return;- // safe to release- // todo: should we refcount subprocesses?- mi_lock_done(&subproc->abandoned_os_lock);- mi_lock_done(&subproc->abandoned_os_visit_lock);- _mi_arena_meta_free(subproc, subproc->memid, sizeof(mi_subproc_t));}-void mi_subproc_add_current_thread(mi_subproc_id_t subproc_id) {- mi_heap_t* heap = mi_heap_get_default();- if (heap == NULL) return;- mi_assert(heap->tld->segments.subproc == &mi_subproc_default);- if (heap->tld->segments.subproc != &mi_subproc_default) return;- heap->tld->segments.subproc = _mi_subproc_from_id(subproc_id);+mi_heap_t* _mi_subproc_heap_main(mi_subproc_t* subproc) {+ mi_heap_t* heap = mi_atomic_load_ptr_relaxed(mi_heap_t,&subproc->heap_main);+ if mi_likely(heap!=NULL) {+ return heap;+ }+ else {+ mi_heap_main_init();+ mi_assert_internal(mi_atomic_load_relaxed(&subproc->heap_main) != NULL);+ return mi_atomic_load_ptr_relaxed(mi_heap_t,&subproc->heap_main);+ }}+mi_heap_t* mi_heap_main(void) {+ return _mi_subproc_heap_main(_mi_subproc()); // don't use _mi_theap_main() so this call works during process_init+}+bool _mi_is_heap_main(const mi_heap_t* heap) {+ mi_assert_internal(heap!=NULL);+ return (_mi_subproc_heap_main(heap->subproc) == heap);+}/* ------------------------------------------------------------ Initialization and freeing of the thread local heaps+ Sub process----------------------------------------------------------- */-// note: in x64 in release build `sizeof(mi_thread_data_t)` is under 4KiB (= OS page size).-typedef struct mi_thread_data_s {- mi_heap_t heap; // must come first due to cast in `_mi_heap_done`- mi_tld_t tld;- mi_memid_t memid; // must come last due to zero'ing-} mi_thread_data_t;---// Thread meta-data is allocated directly from the OS. For-// some programs that do not use thread pools and allocate and-// destroy many OS threads, this may causes too much overhead-// per thread so we maintain a small cache of recently freed metadata.--#define TD_CACHE_SIZE (32)-static _Atomic(mi_thread_data_t*) td_cache[TD_CACHE_SIZE];--static mi_thread_data_t* mi_thread_data_zalloc(void) {- // try to find thread metadata in the cache- bool is_zero = false;- mi_thread_data_t* td = NULL;- for (int i = 0; i < TD_CACHE_SIZE; i++) {- td = mi_atomic_load_ptr_relaxed(mi_thread_data_t, &td_cache[i]);- if (td != NULL) {- // found cached allocation, try use it- td = mi_atomic_exchange_ptr_acq_rel(mi_thread_data_t, &td_cache[i], NULL);- if (td != NULL) {- break;- }- }+mi_subproc_id_t mi_subproc_main(void) {+ return _mi_subproc_main();+}++mi_subproc_id_t mi_subproc_current(void) {+ return _mi_subproc();+}++mi_subproc_id_t mi_subproc_new(void) {+ static _Atomic(size_t) subproc_total_count;+ mi_memid_t memid;+ mi_subproc_t* subproc = (mi_subproc_t*)_mi_meta_zalloc(sizeof(mi_subproc_t),&memid);+ if (subproc == NULL) return NULL;+ subproc->memid = memid;+ subproc->subproc_seq = mi_atomic_increment_relaxed(&subproc_total_count) + 1;+ mi_lock_init(&subproc->arena_reserve_lock);+ mi_lock_init(&subproc->heaps_lock);+ mi_lock(&subprocs_lock) {+ // push on subproc list+ subproc->next = subprocs;+ if (subprocs!=NULL) { subprocs->prev = subproc; }+ subprocs = subproc;}+ return subproc;+}- // if that fails, allocate as meta data- if (td == NULL) {- mi_memid_t memid;- td = (mi_thread_data_t*)_mi_os_alloc(sizeof(mi_thread_data_t), &memid);- if (td == NULL) {- // if this fails, try once more. (issue #257)- td = (mi_thread_data_t*)_mi_os_alloc(sizeof(mi_thread_data_t), &memid);- if (td == NULL) {- // really out of memory- _mi_error_message(ENOMEM, "unable to allocate thread local heap metadata (%zu bytes)\n", sizeof(mi_thread_data_t));- }- }- if (td != NULL) {- td->memid = memid;- is_zero = memid.initially_zero;+mi_subproc_t* _mi_subproc_from_id(mi_subproc_id_t subproc_id) {+ return (subproc_id == NULL ? &subproc_main : (mi_subproc_t*)subproc_id);+}++// destroy all subproc resources including arena's, heap's etc.+static void mi_subproc_unsafe_destroy(mi_subproc_t* subproc)+{+ // remove from the subproc list+ mi_lock(&subprocs_lock) {+ if (subproc->next!=NULL) { subproc->next->prev = subproc->prev; }+ if (subproc->prev!=NULL) { subproc->prev->next = subproc->next; }+ else { mi_assert_internal(subprocs==subproc); subprocs = subproc->next; }+ }++ // destroy all subproc heaps+ mi_lock(&subproc->heaps_lock) {+ mi_heap_t* heap = subproc->heaps;+ while (heap != NULL) {+ mi_heap_t* next = heap->next;+ if (heap!=subproc->heap_main) {mi_heap_destroy(heap); }+ heap = next;}+ mi_assert_internal(subproc->heaps == subproc->heap_main);+ mi_heap_destroy(subproc->heap_main);}- if (td != NULL && !is_zero) {- _mi_memzero_aligned(td, offsetof(mi_thread_data_t,memid));+ // merge stats back into the main subproc?+ if (subproc!=&subproc_main) {+ _mi_arenas_unsafe_destroy_all(subproc);+ _mi_stats_merge_into(&subproc_main.stats, &subproc->stats);++ // safe to release+ // todo: should we refcount subprocesses?+ mi_lock_done(&subproc->arena_reserve_lock);+ mi_lock_done(&subproc->heaps_lock);+ _mi_meta_free(subproc, sizeof(mi_subproc_t), subproc->memid);}- return td;}-static void mi_thread_data_free( mi_thread_data_t* tdfree ) {- // try to add the thread metadata to the cache- for (int i = 0; i < TD_CACHE_SIZE; i++) {- mi_thread_data_t* td = mi_atomic_load_ptr_relaxed(mi_thread_data_t, &td_cache[i]);- if (td == NULL) {- mi_thread_data_t* expected = NULL;- if (mi_atomic_cas_ptr_weak_acq_rel(mi_thread_data_t, &td_cache[i], &expected, tdfree)) {- return;- }- }- }- // if that fails, just free it directly- _mi_os_free(tdfree, sizeof(mi_thread_data_t), tdfree->memid);+void mi_subproc_destroy(mi_subproc_id_t subproc_id) {+ if (subproc_id == NULL) return;+ mi_subproc_unsafe_destroy(_mi_subproc_from_id(subproc_id));}-void _mi_thread_data_collect(void) {- // free all thread metadata from the cache- for (int i = 0; i < TD_CACHE_SIZE; i++) {- mi_thread_data_t* td = mi_atomic_load_ptr_relaxed(mi_thread_data_t, &td_cache[i]);- if (td != NULL) {- td = mi_atomic_exchange_ptr_acq_rel(mi_thread_data_t, &td_cache[i], NULL);- if (td != NULL) {- _mi_os_free(td, sizeof(mi_thread_data_t), td->memid);+static void mi_subprocs_unsafe_destroy_all(void) {+ mi_lock(&subprocs_lock) {+ mi_subproc_t* subproc = subprocs;+ while (subproc!=NULL) {+ mi_subproc_t* next = subproc->next;+ if (subproc!=&subproc_main) {+ mi_subproc_unsafe_destroy(subproc);}+ subproc = next;}}+ mi_subproc_unsafe_destroy(&subproc_main);}-// Initialize the thread local default heap, called from `mi_thread_init`-static bool _mi_thread_heap_init(void) {- if (mi_heap_is_initialized(mi_prim_get_default_heap())) return true;- if (_mi_is_main_thread()) {- // mi_assert_internal(_mi_heap_main.thread_id != 0); // can happen on freeBSD where alloc is called before any initialization- // the main heap is statically allocated- mi_heap_main_init();- _mi_heap_set_default_direct(&_mi_heap_main);- //mi_assert_internal(_mi_heap_default->tld->heap_backing == mi_prim_get_default_heap());- }- else {- // use `_mi_os_alloc` to allocate directly from the OS- mi_thread_data_t* td = mi_thread_data_zalloc();- if (td == NULL) return false;- mi_tld_t* tld = &td->tld;- mi_heap_t* heap = &td->heap;- _mi_tld_init(tld, heap); // must be before `_mi_heap_init`- _mi_heap_init(heap, tld, _mi_arena_id_none(), false /* can reclaim */, 0 /* default tag */);- _mi_heap_set_default_direct(heap);+void mi_subproc_add_current_thread(mi_subproc_id_t subproc_id) {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ mi_tld_t* const tld = _mi_theap_default_safe()->tld;+ mi_assert(tld->subproc== &subproc_main);+ if (tld->subproc != &subproc_main) {+ _mi_warning_message("unable to add thread to the subprocess as it was already in another subprocess (id: %p)\n", subproc);+ return;}- return false;+ tld->subproc = subproc;+ tld->thread_seq = mi_atomic_increment_relaxed(&subproc->thread_total_count);+ mi_atomic_decrement_relaxed(&subproc_main.thread_count);+ mi_atomic_increment_relaxed(&subproc->thread_count);}-// initialize thread local data-void _mi_tld_init(mi_tld_t* tld, mi_heap_t* bheap) {- _mi_memcpy_aligned(tld, &tld_empty, sizeof(mi_tld_t));- tld->heap_backing = bheap;- tld->heaps = NULL;- tld->segments.subproc = &mi_subproc_default;- tld->segments.stats = &tld->stats;-}--// Free the thread local default heap (called from `mi_thread_done`)-static bool _mi_thread_heap_done(mi_heap_t* heap) {- if (!mi_heap_is_initialized(heap)) return true;-- // reset default heap- _mi_heap_set_default_direct(_mi_is_main_thread() ? &_mi_heap_main : (mi_heap_t*)&_mi_heap_empty);- // switch to backing heap- heap = heap->tld->heap_backing;- if (!mi_heap_is_initialized(heap)) return false;-- // delete all non-backing heaps in this thread- mi_heap_t* curr = heap->tld->heaps;- while (curr != NULL) {- mi_heap_t* next = curr->next; // save `next` as `curr` will be freed- if (curr != heap) {- mi_assert_internal(!mi_heap_is_backing(curr));- mi_heap_delete(curr);+bool mi_subproc_visit_heaps(mi_subproc_id_t subproc_id, mi_heap_visit_fun* visitor, void* arg) {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL) return false;+ bool ok = true;+ mi_lock(&subproc->heaps_lock) {+ for (mi_heap_t* heap = subproc->heaps; heap!=NULL && ok; heap = heap->next) {+ ok = (*visitor)(heap, arg);}- curr = next;}- mi_assert_internal(heap->tld->heaps == heap && heap->next == NULL);- mi_assert_internal(mi_heap_is_backing(heap));+ return ok;+}- // collect if not the main thread- if (heap != &_mi_heap_main) {- _mi_heap_collect_abandon(heap);- }- // merge stats- _mi_stats_done(&heap->tld->stats);+/* -----------------------------------------------------------+ Allocate theap data+----------------------------------------------------------- */- // free if not the main thread- if (heap != &_mi_heap_main) {- // the following assertion does not always hold for huge segments as those are always treated- // as abondened: one may allocate it in one thread, but deallocate in another in which case- // the count can be too large or negative. todo: perhaps not count huge segments? see issue #363- // mi_assert_internal(heap->tld->segments.count == 0 || heap->thread_id != _mi_thread_id());- mi_thread_data_free((mi_thread_data_t*)heap);+// Initialize the thread local default theap, called from `mi_thread_init`+static mi_theap_t* _mi_thread_init_theap_default(void) {+ mi_theap_t* theap = _mi_theap_default();+ if (mi_theap_is_initialized(theap)) return theap;+ if (_mi_is_main_thread()) {+ mi_heap_main_init();+ theap = &theap_main;}else {- #if 0- // never free the main thread even in debug mode; if a dll is linked statically with mimalloc,+ // allocates tld data+ // note: we cannot access thread-locals yet as that can cause (recursive) allocation+ // (on macOS <= 14 for example where the loader allocates thread-local data on demand).+ mi_tld_t* tld = mi_tld_alloc();+ // allocate and initialize the theap for the main heap+ theap = _mi_theap_create(mi_heap_main(), tld);+ }+ // associate the theap with this thread+ // (this is safe, on macOS for example, the theap is set in a dedicated TLS slot and thus does not cause recursive allocation)+ _mi_theap_default_set(theap);+ return theap;+}+++// Free the thread local theaps+static void mi_thread_theaps_done(mi_tld_t* tld)+{+ // reset the thread local theaps+ __mi_theap_main = NULL;+ _mi_theap_default_set((mi_theap_t*)&_mi_theap_empty);+ _mi_theap_cached_set((mi_theap_t*)&_mi_theap_empty);++ // delete all theaps in this thread+ mi_theap_t* curr = tld->theaps;+ while (curr != NULL) {+ mi_theap_t* next = curr->tnext; // save `tnext` as `curr` will be freed+ // never destroy theaps; if a dll is linked statically with mimalloc,// there may still be delete/free calls after the mi_fls_done is called. Issue #207- _mi_heap_destroy_pages(heap);- mi_assert_internal(heap->tld->heap_backing == &_mi_heap_main);- #endif+ _mi_theap_delete(curr);+ curr = next;}- return false;+ mi_assert(_mi_theap_default()==(mi_theap_t*)&_mi_theap_empty); // careful to not re-initialize the default theap during theap_delete+ mi_assert(!mi_theap_is_initialized(_mi_theap_default()));}@@ -480,7 +603,7 @@ static bool _mi_thread_heap_done(mi_heap_t* heap) {// 1. windows dynamic library:// call from DllMain on DLL_THREAD_DETACH// 2. windows static library:-// use `FlsAlloc` to call a destructor when the thread is done+// use special linker section to call a destructor when the thread is done// 3. unix, pthreads:// use a pthread key to call a destructor when a pthread is done//@@ -494,81 +617,204 @@ static void mi_process_setup_auto_thread_done(void) {if (tls_initialized) return;tls_initialized = true;_mi_prim_thread_init_auto_done();- _mi_heap_set_default_direct(&_mi_heap_main);+ _mi_theap_default_set(&theap_main);}bool _mi_is_main_thread(void) {- return (_mi_heap_main.thread_id==0 || _mi_heap_main.thread_id == _mi_thread_id());+ return (tld_main.thread_id==0 || tld_main.thread_id == _mi_thread_id());}-static _Atomic(size_t) thread_count = MI_ATOMIC_VAR_INIT(1);--size_t _mi_current_thread_count(void) {- return mi_atomic_load_relaxed(&thread_count);-}-// This is called from the `mi_malloc_generic`+// Initialize threadvoid mi_thread_init(void) mi_attr_noexcept{// ensure our process has started alreadymi_process_init();+ // if the theap_default is already set we have already initialized+ if (_mi_thread_is_initialized()) return;- // initialize the thread local default heap- // (this will call `_mi_heap_set_default_direct` and thus set the- // fiber/pthread key to a non-zero value, ensuring `_mi_thread_done` is called)- if (_mi_thread_heap_init()) return; // returns true if already initialized+ // initialize the default theap+ _mi_thread_init_theap_default();- _mi_stat_increase(&_mi_stats_main.threads, 1);- mi_atomic_increment_relaxed(&thread_count);- //_mi_verbose_message("thread init: 0x%zx\n", _mi_thread_id());+ mi_heap_stat_increase(mi_heap_main(), threads, 1);+ // _mi_verbose_message("thread init: 0x%zx\n", _mi_thread_id());}void mi_thread_done(void) mi_attr_noexcept {_mi_thread_done(NULL);}-void _mi_thread_done(mi_heap_t* heap)+void _mi_thread_done(mi_theap_t* _theap_main){- // calling with NULL implies using the default heap- if (heap == NULL) {- heap = mi_prim_get_default_heap();- if (heap == NULL) return;+ // NULL can be passed on some platforms+ if (_theap_main==NULL) {+ _theap_main = __mi_theap_main;}- // prevent re-entrancy through heap_done/heap_set_default_direct (issue #699)- if (!mi_heap_is_initialized(heap)) {+ // prevent re-entrancy through theap_done/theap_set_default_direct (issue #699)+ if (!mi_theap_is_initialized(_theap_main)) {return;}+ // release dynamic thread_local's+ _mi_thread_locals_thread_done();++ // note: we store the tld as we should avoid reading `thread_tld` at this point (to avoid reinitializing the thread local storage)+ mi_tld_t* const tld = _theap_main->tld;+// adjust stats- mi_atomic_decrement_relaxed(&thread_count);- _mi_stat_decrease(&_mi_stats_main.threads, 1);-- // check thread-id as on Windows shutdown with FLS the main (exit) thread may call this on thread-local heaps...- if (heap->thread_id != _mi_thread_id()) return;-- // abandon the thread local heap- if (_mi_thread_heap_done(heap)) return; // returns true if already ran-}--void _mi_heap_set_default_direct(mi_heap_t* heap) {- mi_assert_internal(heap != NULL);- #if defined(MI_TLS_SLOT)- mi_prim_tls_slot_set(MI_TLS_SLOT,heap);- #elif defined(MI_TLS_PTHREAD_SLOT_OFS)- *mi_prim_tls_pthread_heap_slot() = heap;- #elif defined(MI_TLS_PTHREAD)- // we use _mi_heap_default_key- #else- _mi_heap_default = heap;+ mi_heap_stat_decrease(_mi_subproc_heap_main(tld->subproc), threads, 1); // todo: or `_theap_main->heap`?++ // check thread-id as on Windows shutdown with FLS the main (exit) thread may call this on thread-local theaps...+ if (tld->thread_id != _mi_prim_thread_id()) return;++ // delete the thread local theaps+ mi_thread_theaps_done(tld);++ // free thread local data+ mi_tld_free(tld);+}+++mi_decl_cold mi_decl_noinline mi_theap_t* _mi_theap_empty_get(void) {+ return (mi_theap_t*)&_mi_theap_empty;+}++#if MI_TLS_MODEL_DYNAMIC_WIN32++// If we can, we use one of the 64 direct TLS slots (but fall back to expansion slots if needed)+// See <https://en.wikipedia.org/wiki/Win32_Thread_Information_Block> for the offsets.+#if MI_SIZE_SIZE==4+#define MI_TLS_DIRECT_FIRST (0x0E10 / MI_SIZE_SIZE)+#else+#define MI_TLS_DIRECT_FIRST (0x1480 / MI_SIZE_SIZE)+#endif+#define MI_TLS_DIRECT_SLOTS (64)+#define MI_TLS_EXPANSION_SLOTS (1024)++#if !MI_WIN_DIRECT_TLS+#define MI_TLS_INITIAL_SLOT MI_TLS_EXPANSION_SLOT+#define MI_TLS_INITIAL_EXPANSION_SLOT (MI_TLS_EXPANSION_SLOTS-1)+#else+// with only direct entries, use the "arbitrary user data" field+// and assume it is NULL (see also <http://www.nynaeve.net/?p=98>)+#define MI_TLS_INITIAL_EXPANSION_SLOT (0)+#define MI_TLS_INITIAL_SLOT (5)+#endif++// we initially use the last of the expansion slots as the default NULL.+// note: this will fail if the program allocates exactly 1024+64 slots with TlsAlloc (which is quite unlikely)+mi_decl_hidden mi_decl_cache_align size_t _mi_theap_default_slot = MI_TLS_INITIAL_SLOT;+mi_decl_hidden size_t _mi_theap_default_expansion_slot = MI_TLS_INITIAL_EXPANSION_SLOT;+mi_decl_hidden size_t _mi_theap_cached_slot = MI_TLS_INITIAL_SLOT;+mi_decl_hidden size_t _mi_theap_cached_expansion_slot = MI_TLS_INITIAL_EXPANSION_SLOT;++static size_t mi_win_tls_slot_alloc(size_t* extended) {+ const DWORD slot = TlsAlloc();+ if (slot==TLS_OUT_OF_INDEXES || slot >= MI_TLS_DIRECT_SLOTS + MI_TLS_EXPANSION_SLOTS - 1) {+ // note: we also fail if the program already allocated the maximum number of expansion slots (as we use the last one as the default)+ *extended = 0;+ return 0;+ }+ else if (slot<MI_TLS_DIRECT_SLOTS) {+ *extended = 0;+ return (slot + MI_TLS_DIRECT_FIRST);+ }+ else {+ #if MI_WIN_DIRECT_TLS+ *extended = 0;+ return 0;+ #else+ *extended = (slot - MI_TLS_DIRECT_SLOTS);+ return MI_TLS_EXPANSION_SLOT;+ #endif+ }+}++mi_decl_cold mi_theap_t* _mi_win_tls_slots_init(void) {+ static mi_atomic_once_t tls_slots_init;+ if (mi_atomic_once(&tls_slots_init)) {+ _mi_theap_default_slot = mi_win_tls_slot_alloc(&_mi_theap_default_expansion_slot);+ _mi_theap_cached_slot = mi_win_tls_slot_alloc(&_mi_theap_cached_expansion_slot);+ if (_mi_theap_cached_slot==0) {+ _mi_error_message(EFAULT, "unable to allocate fast TLS user slot (0x%zx)\n", _mi_theap_cached_slot);+ }+ }+ return (mi_theap_t*)&_mi_theap_empty;+}++static void mi_win_tls_slot_set(size_t slot, size_t extended_slot, void* value) {+ mi_assert_internal((slot >= MI_TLS_DIRECT_FIRST && slot < MI_TLS_DIRECT_FIRST + MI_TLS_DIRECT_SLOTS) || slot == MI_TLS_EXPANSION_SLOT);+ if (slot < MI_TLS_DIRECT_FIRST + MI_TLS_DIRECT_SLOTS) {+ mi_prim_tls_slot_set(slot, value);+ }+ else {+ mi_assert_internal(extended_slot < MI_TLS_EXPANSION_SLOTS);+ TlsSetValue((DWORD)(extended_slot + MI_TLS_DIRECT_SLOTS), value); // use TlsSetValue to initialize the TlsExpansion array if needed+ }+}++#elif MI_TLS_MODEL_DYNAMIC_PTHREADS++// only for pthreads for now+mi_decl_hidden pthread_key_t _mi_theap_default_key = 0;+mi_decl_hidden pthread_key_t _mi_theap_cached_key = 0;++mi_decl_cold mi_theap_t* _mi_tls_keys_init(void) {+ static mi_atomic_once_t tls_keys_init;+ if (mi_atomic_once(&tls_keys_init)) {+ pthread_key_create(&_mi_theap_default_key, NULL);+ pthread_key_create(&_mi_theap_cached_key, NULL);+ }+ return (mi_theap_t*)&_mi_theap_empty;+}++#endif++void _mi_theap_cached_set(mi_theap_t* theap) {+ #if MI_TLS_MODEL_THREAD_LOCAL+ __mi_theap_cached = theap;+ #elif MI_TLS_MODEL_FIXED_SLOT+ mi_prim_tls_slot_set(MI_TLS_MODEL_FIXED_SLOT_CACHED, theap);+ #elif MI_TLS_MODEL_DYNAMIC_WIN32+ _mi_win_tls_slots_init();+ mi_win_tls_slot_set(_mi_theap_cached_slot, _mi_theap_cached_expansion_slot, theap);+ #elif MI_TLS_MODEL_DYNAMIC_PTHREADS+ _mi_tls_keys_init();+ if (_mi_theap_cached_key!=0) pthread_setspecific(_mi_theap_cached_key, theap);+ #endif+}++void _mi_theap_default_set(mi_theap_t* theap) {+ mi_assert_internal(theap != NULL);+ mi_assert_internal(theap->tld->thread_id==0 || theap->tld->thread_id==_mi_thread_id());+ #if MI_TLS_MODEL_THREAD_LOCAL+ __mi_theap_default = theap;+ #elif MI_TLS_MODEL_FIXED_SLOT+ mi_prim_tls_slot_set(MI_TLS_MODEL_FIXED_SLOT_DEFAULT, theap);+ #elif MI_TLS_MODEL_DYNAMIC_WIN32+ _mi_win_tls_slots_init();+ mi_win_tls_slot_set(_mi_theap_default_slot, _mi_theap_default_expansion_slot, theap);+ #elif MI_TLS_MODEL_DYNAMIC_PTHREADS+ _mi_tls_keys_init();+ if (_mi_theap_default_key!=0) pthread_setspecific(_mi_theap_default_key, theap);#endif- // ensure the default heap is passed to `_mi_thread_done`- // setting to a non-NULL value also ensures `mi_thread_done` is called.- _mi_prim_thread_associate_default_heap(heap);+ // set theap main if needed+ if (mi_theap_is_initialized(theap)) {+ // ensure the default theap is passed to `_mi_thread_done` as on some platforms we cannot access TLS at thread termination (as it would allocate again)+ _mi_prim_thread_associate_default_theap(theap);+ if (_mi_is_heap_main(theap->heap)) {+ __mi_theap_main = theap;+ }+ }}+void mi_thread_set_in_threadpool(void) mi_attr_noexcept {+ mi_theap_t* theap = _mi_theap_default_safe();+ theap->tld->is_in_threadpool = true;+}// --------------------------------------------------------// Run functions on process init/done, and thread init/done@@ -580,18 +826,26 @@ bool mi_decl_noinline _mi_preloading(void) {return os_preloading;}+// Returns true if mimalloc was redirected+mi_decl_nodiscard bool mi_is_redirected(void) mi_attr_noexcept {+ return _mi_is_redirected();+}+// Called once by the process loader from `src/prim/prim.c`-void _mi_process_load(void) {- mi_heap_main_init();- #if defined(__APPLE__) || defined(MI_TLS_RECURSE_GUARD)- volatile mi_heap_t* dummy = _mi_heap_default; // access TLS to allocate it before setting tls_initialized to true;- if (dummy == NULL) return; // use dummy or otherwise the access may get optimized away (issue #697)- #endif+void _mi_auto_process_init(void) {+ // mi_heap_main_init();+ // #if defined(__APPLE__) || defined(MI_TLS_RECURSE_GUARD)+ // volatile mi_theap_t* dummy = __mi_theap_default; // access TLS to allocate it before setting tls_initialized to true;+ // if (dummy == NULL) return; // use dummy or otherwise the access may get optimized away (issue #697)+ // #endif+os_preloading = false;mi_assert_internal(_mi_is_main_thread());- _mi_options_init();- mi_process_setup_auto_thread_done();+mi_process_init();+ mi_process_setup_auto_thread_done();+ _mi_thread_locals_init();+ _mi_options_post_init(); // now we can print to stderrif (_mi_is_redirected()) _mi_verbose_message("malloc is redirected.\n");// show message from the redirector (if present)@@ -602,66 +856,114 @@ void _mi_process_load(void) {}// reseed random- _mi_random_reinit_if_weak(&_mi_heap_main.random);+ _mi_random_reinit_if_weak(&theap_main.random);}-#if defined(_WIN32) && (defined(_M_IX86) || defined(_M_X64))-#include <intrin.h>-mi_decl_cache_align bool _mi_cpu_has_fsrm = false;-mi_decl_cache_align bool _mi_cpu_has_erms = false;+// CPU features+mi_decl_cache_align size_t _mi_cpu_movsb_max = 0; // for size <= max, rep movsb is fast+mi_decl_cache_align size_t _mi_cpu_stosb_max = 0; // for size <= max, rep stosb is fast+mi_decl_cache_align bool _mi_cpu_has_popcnt = false;++#if (MI_ARCH_X64 || MI_ARCH_X86)+#if defined(__GNUC__)+// #include <cpuid.h>+static bool mi_cpuid(uint32_t* regs4, uint32_t level, uint32_t sublevel) {+ // note: use explicit assembly instead of __get_cpuid as we need the sublevel (in ecx)+ // (on Ubuntu 22 with WSL the __get_cpuid does not clear ecx for level 7 which is incorrect).+ uint32_t eax, ebx, ecx, edx;+ __asm __volatile("cpuid" : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : "a"(level), "c"(sublevel) : );+ regs4[0] = eax;+ regs4[1] = ebx;+ regs4[2] = ecx;+ regs4[3] = edx;+ return true;+}++#elif defined(_MSC_VER)+static bool mi_cpuid(uint32_t* regs4, uint32_t level, uint32_t sublevel) {+ __cpuidex((int32_t*)regs4, (int32_t)level, (int32_t)sublevel);+ return true;+}+#else+static bool mi_cpuid(uint32_t* regs4, uint32_t level, uint32_t sublevel) {+ MI_UNUSED(regs4); MI_UNUSED(level); MI_UNUSED(sublevel);+ return false;+}+#endifstatic void mi_detect_cpu_features(void) {- // FSRM for fast short rep movsb/stosb support (AMD Zen3+ (~2020) or Intel Ice Lake+ (~2017))- // EMRS for fast enhanced rep movsb/stosb support- int32_t cpu_info[4];- __cpuid(cpu_info, 7);- _mi_cpu_has_fsrm = ((cpu_info[3] & (1 << 4)) != 0); // bit 4 of EDX : see <https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features>- _mi_cpu_has_erms = ((cpu_info[2] & (1 << 9)) != 0); // bit 9 of ECX : see <https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features>+ // FSRM for fast short rep movsb support (AMD Zen3+ (~2020) or Intel Ice Lake+ (~2017))+ // EMRS for fast enhanced rep movsb/stosb support (not used at the moment, memcpy always seems faster?)+ // FSRS for fast short rep stosb+ bool amd = false;+ bool fsrm = false;+ // bool erms = false;+ bool fsrs = false;+ uint32_t cpu_info[4];+ if (mi_cpuid(cpu_info, 0, 0)) {+ amd = (cpu_info[2]==0x444d4163); // (Auth enti cAMD)+ }+ if (mi_cpuid(cpu_info, 7, 0)) {+ fsrm = ((cpu_info[3] & (1 << 4)) != 0); // bit 4 of EDX : see <https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features>+ // erms = ((cpu_info[1] & (1 << 9)) != 0); // bit 9 of EBX : see <https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features>+ }+ if (mi_cpuid(cpu_info, 7, 1)) {+ fsrs = ((cpu_info[1] & (1 << 11)) != 0); // bit 11 of EBX: see <https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=1:_Extended_Features>+ }+ if (mi_cpuid(cpu_info, 1, 0)) {+ _mi_cpu_has_popcnt = ((cpu_info[2] & (1 << 23)) != 0); // bit 23 of ECX : see <https://en.wikipedia.org/wiki/CPUID#EAX=1:_Processor_Info_and_Feature_Bits>+ }++ if (fsrm) {+ _mi_cpu_movsb_max = 127;+ }+ if (fsrs || (amd && fsrm)) { // fsrm on amd implies fsrs, see: https://marc.info/?l=git-commits-head&m=168186277717803+ _mi_cpu_stosb_max = 127;+ }}+#elsestatic void mi_detect_cpu_features(void) {- // nothing+ #if MI_ARCH_ARM64+ _mi_cpu_has_popcnt = true;+ #endif}#endif+// Initialize the process; called by thread_init or the process loadervoid mi_process_init(void) mi_attr_noexcept {// ensure we are called oncestatic mi_atomic_once_t process_init;- #if _MSC_VER < 1920- mi_heap_main_init(); // vs2017 can dynamically re-initialize _mi_heap_main- #endif+ // #if _MSC_VER < 1920+ // mi_heap_main_init(); // vs2017 can dynamically re-initialize theap_main+ // #endifif (!mi_atomic_once(&process_init)) return;- _mi_process_is_initialized = true;_mi_verbose_message("process init: 0x%zx\n", _mi_thread_id());- mi_process_setup_auto_thread_done();mi_detect_cpu_features();+ _mi_options_init();+ _mi_stats_init();_mi_os_init();- mi_heap_main_init();- #if MI_DEBUG- _mi_verbose_message("debug level : %d\n", MI_DEBUG);- #endif- _mi_verbose_message("secure level: %d\n", MI_SECURE);- _mi_verbose_message("mem tracking: %s\n", MI_TRACK_TOOL);- #if MI_TSAN- _mi_verbose_message("thread santizer enabled\n");- #endif+ // the following can potentially allocate (on freeBSD for pthread keys)+ // todo: do 2-phase so we can use stats at first, then later init the keys?+ mi_heap_main_init(); // before page_map_init so stats are working+ _mi_page_map_init(); // todo: this could fail.. should we abort in that case?mi_thread_init();+ _mi_process_is_initialized = true;- #if defined(_WIN32)+ #if defined(_WIN32) && defined(MI_WIN_USE_FLS)// On windows, when building as a static lib the FLS cleanup happens to early for the main thread.// To avoid this, set the FLS value for the main thread to NULL so the fls cleanup// will not call _mi_thread_done on the (still executing) main thread. See issue #508.- _mi_prim_thread_associate_default_heap(NULL);+ _mi_prim_thread_associate_default_theap(NULL);#endif- mi_stats_reset(); // only call stat reset *after* thread init (or the heap tld == NULL)+ // mi_stats_reset(); // only call stat reset *after* thread init (or the theap tld == NULL)mi_track_init();-if (mi_option_is_enabled(mi_option_reserve_huge_os_pages)) {size_t pages = mi_option_get_clamp(mi_option_reserve_huge_os_pages, 0, 128*1024);- long reserve_at = mi_option_get(mi_option_reserve_huge_os_pages_at);+ int reserve_at = (int)mi_option_get_clamp(mi_option_reserve_huge_os_pages_at, -1, INT_MAX);if (reserve_at != -1) {mi_reserve_huge_os_pages_at(pages, reserve_at, pages*500);} else {@@ -671,13 +973,13 @@ void mi_process_init(void) mi_attr_noexcept {if (mi_option_is_enabled(mi_option_reserve_os_memory)) {long ksize = mi_option_get(mi_option_reserve_os_memory);if (ksize > 0) {- mi_reserve_os_memory((size_t)ksize*MI_KiB, true /* commit? */, true /* allow large pages? */);+ mi_reserve_os_memory((size_t)ksize*MI_KiB, true, true);}}}-// Called when the process is done (through `at_exit`)-void mi_cdecl _mi_process_done(void) {+// Called when the process is done (cdecl as it is used with `at_exit` on some platforms)+void mi_cdecl mi_process_done(void) mi_attr_noexcept {// only shutdown if we were initializedif (!_mi_process_is_initialized) return;// ensure we are called once@@ -685,20 +987,18 @@ void mi_cdecl _mi_process_done(void) {if (process_done) return;process_done = true;- // get the default heap so we don't need to acces thread locals anymore- mi_heap_t* heap = mi_prim_get_default_heap(); // use prim to not initialize any heap- mi_assert_internal(heap != NULL);+ // free dynamic thread locals (if used at all)+ _mi_thread_locals_done();// release any thread specific resources and ensure _mi_thread_done is called on all but the main thread_mi_prim_thread_done_auto_done();-#ifndef MI_SKIP_COLLECT_ON_EXIT#if (MI_DEBUG || !defined(MI_SHARED_LIB))// free all memory if possible on process exit. This is not needed for a stand-alone process// but should be done if mimalloc is statically linked into another shared library which// is repeatedly loaded/unloaded, see issue #281.- mi_heap_collect(heap, true /* force */ );+ mi_theap_collect(_mi_theap_default(), true /* force */);#endif#endif@@ -706,17 +1006,23 @@ void mi_cdecl _mi_process_done(void) {// since after process_done there might still be other code running that calls `free` (like at_exit routines,// or C-runtime termination code.if (mi_option_is_enabled(mi_option_destroy_on_exit)) {- mi_heap_collect(heap, true /* force */);- _mi_heap_unsafe_destroy_all(heap); // forcefully release all memory held by all heaps (of this thread only!)- _mi_arena_unsafe_destroy_all();- _mi_segment_map_unsafe_destroy();+ mi_subprocs_unsafe_destroy_all();+ _mi_page_map_unsafe_destroy(_mi_subproc_main());+ }+ else {+ mi_heap_stats_merge_to_subproc(mi_heap_main());}if (mi_option_is_enabled(mi_option_show_stats) || mi_option_is_enabled(mi_option_verbose)) {- mi_stats_print(NULL);+ mi_subproc_stats_print_out(NULL, NULL, NULL);}+ mi_lock_done(&subprocs_lock);_mi_allocator_done();- _mi_verbose_message("process done: 0x%zx\n", _mi_heap_main.thread_id);+ _mi_verbose_message("process done: 0x%zx\n", tld_main.thread_id);os_preloading = true; // don't call the C runtime anymore}+void mi_cdecl _mi_auto_process_done(void) mi_attr_noexcept {+ if (_mi_option_get_fast(mi_option_destroy_on_exit)>1) return;+ mi_process_done();+}diff --git a/vendored/mimalloc/src/libc.c b/vendored/mimalloc/src/libc.cindex ce541f1b5..4c891c1e6 100644--- a/vendored/mimalloc/src/libc.c+++ b/vendored/mimalloc/src/libc.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2023, Microsoft Research, Daan Leijen+Copyright (c) 2018-2024, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -7,7 +7,7 @@ terms of the MIT license. A copy of the license can be found in the file// --------------------------------------------------------// This module defines various std libc functions to reduce-// the dependency on libc, and also prevent errors caused+// the dependency on libc, and also prevent errors caused// by some libc implementations when called before `main`// executes (due to malloc redirection)// --------------------------------------------------------@@ -65,6 +65,21 @@ size_t _mi_strnlen(const char* s, size_t max_len) {return len;}+char* _mi_strnstr(char* s, size_t max_len, const char* pat) {+ if (s==NULL) return NULL;+ if (pat==NULL) return s;+ const size_t m = _mi_strnlen(s, max_len);+ const size_t n = _mi_strlen(pat);+ for (size_t start = 0; start + n <= m; start++) {+ size_t i = 0;+ while (i<n && pat[i]==s[start+i]) {+ i++;+ }+ if (i==n) return &s[start];+ }+ return NULL;+}+#ifdef MI_NO_GETENVbool _mi_getenv(const char* name, char* result, size_t result_size) {MI_UNUSED(name);@@ -83,7 +98,7 @@ bool _mi_getenv(const char* name, char* result, size_t result_size) {// Define our own limited `_mi_vsnprintf` and `_mi_snprintf`// This is mostly to avoid calling these when libc is not yet// initialized (and to reduce dependencies)-//+//// format: d i, p x u, s// prec: z l ll L// width: 10@@ -130,7 +145,7 @@ static void mi_out_alignright(char fill, char* start, size_t len, size_t extra,}-static void mi_out_num(uintmax_t x, size_t base, char prefix, char** out, char* end)+static void mi_out_num(uintmax_t x, size_t base, char prefix, char** out, char* end){if (x == 0 || base == 0 || base > 16) {if (prefix != 0) { mi_outc(prefix, out, end); }@@ -144,8 +159,8 @@ static void mi_out_num(uintmax_t x, size_t base, char prefix, char** out, char*mi_outc((digit <= 9 ? '0' + digit : 'A' + digit - 10),out,end);x = x / base;}- if (prefix != 0) {- mi_outc(prefix, out, end);+ if (prefix != 0) {+ mi_outc(prefix, out, end);}size_t len = *out - start;// and reverse in-place@@ -160,8 +175,8 @@ static void mi_out_num(uintmax_t x, size_t base, char prefix, char** out, char*#define MI_NEXTC() c = *in; if (c==0) break; in++;-void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {- if (buf == NULL || bufsize == 0 || fmt == NULL) return;+int _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {+ if (buf == NULL || bufsize == 0 || fmt == NULL) return 0;buf[bufsize - 1] = 0;char* const end = buf + (bufsize - 1);const char* in = fmt;@@ -171,7 +186,18 @@ void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {char c;MI_NEXTC();if (c != '%') {- if ((c >= ' ' && c <= '~') || c=='\n' || c=='\r' || c=='\t') { // output visible ascii or standard control only+ if (c == '\\') {+ MI_NEXTC();+ switch (c) {+ case 'e': mi_outc('\x1B', &out, end); break;+ case 't': mi_outc('\t', &out, end); break;+ case 'n': mi_outc('\n', &out, end); break;+ case 'r': mi_outc('\r', &out, end); break;+ case '\\': mi_outc('\\', &out, end); break;+ default: /* ignore */ break;+ }+ }+ else if ((c >= ' ' && c <= '~') || c=='\n' || c=='\r' || c=='\t' || c=='\x1b') { // output visible ascii or standard control onlymi_outc(c, &out, end);}}@@ -181,7 +207,7 @@ void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {size_t width = 0;char numtype = 'd';char numplus = 0;- bool alignright = true;+ bool alignright = true;if (c == '+' || c == ' ') { numplus = c; MI_NEXTC(); }if (c == '-') { alignright = false; MI_NEXTC(); }if (c == '0') { fill = '0'; MI_NEXTC(); }@@ -191,7 +217,7 @@ void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {width = (10 * width) + (c - '0'); MI_NEXTC();}if (c == 0) break; // extra check due to while- }+ }if (c == 'z' || c == 't' || c == 'L') { numtype = c; MI_NEXTC(); }else if (c == 'l') {numtype = c; MI_NEXTC();@@ -199,7 +225,10 @@ void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {}char* start = out;- if (c == 's') {+ if (c == '%') {+ mi_outc('%', &out, end);+ }+ else if (c == 's') {// stringconst char* s = va_arg(args, const char*);mi_outs(s, &out, end);@@ -265,11 +294,139 @@ void _mi_vsnprintf(char* buf, size_t bufsize, const char* fmt, va_list args) {}mi_assert_internal(out <= end);*out = 0;+ return (int)(out - buf);}-void _mi_snprintf(char* buf, size_t buflen, const char* fmt, ...) {+int _mi_snprintf(char* buf, size_t buflen, const char* fmt, ...) {va_list args;va_start(args, fmt);- _mi_vsnprintf(buf, buflen, fmt, args);+ const int written = _mi_vsnprintf(buf, buflen, fmt, args);va_end(args);+ return written;+}++++// --------------------------------------------------------+// generic trailing and leading zero count, and popcount+// --------------------------------------------------------++#if !MI_HAS_FAST_BITSCAN++static size_t mi_ctz_generic32(uint32_t x) {+ // de Bruijn multiplication, see <http://keithandkatie.com/keith/papers/debruijn.html>+ static const uint8_t debruijn[32] = {+ 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,+ 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9+ };+ if (x==0) return 32;+ return debruijn[(uint32_t)((x & -(int32_t)x) * (uint32_t)(0x077CB531U)) >> 27];+}++static size_t mi_clz_generic32(uint32_t x) {+ // de Bruijn multiplication, see <http://keithandkatie.com/keith/papers/debruijn.html>+ static const uint8_t debruijn[32] = {+ 31, 22, 30, 21, 18, 10, 29, 2, 20, 17, 15, 13, 9, 6, 28, 1,+ 23, 19, 11, 3, 16, 14, 7, 24, 12, 4, 8, 25, 5, 26, 27, 0+ };+ if (x==0) return 32;+ x |= x >> 1;+ x |= x >> 2;+ x |= x >> 4;+ x |= x >> 8;+ x |= x >> 16;+ return debruijn[(uint32_t)(x * (uint32_t)(0x07C4ACDDU)) >> 27];+}++size_t _mi_ctz_generic(size_t x) {+ if (x==0) return MI_SIZE_BITS;+ #if (MI_SIZE_BITS <= 32)+ return mi_ctz_generic32((uint32_t)x);+ #else+ const uint32_t lo = (uint32_t)x;+ if (lo != 0) {+ return mi_ctz_generic32(lo);+ }+ else {+ return (32 + mi_ctz_generic32((uint32_t)(x>>32)));+ }+ #endif}++size_t _mi_clz_generic(size_t x) {+ if (x==0) return MI_SIZE_BITS;+ #if (MI_SIZE_BITS <= 32)+ return mi_clz_generic32((uint32_t)x);+ #else+ const uint32_t hi = (uint32_t)(x>>32);+ if (hi != 0) {+ return mi_clz_generic32(hi);+ }+ else {+ return 32 + mi_clz_generic32((uint32_t)x);+ }+ #endif+}++#endif // bit scan+++#if MI_SIZE_SIZE == 4+#define mi_mask_even_bits32 (0x55555555)+#define mi_mask_even_pairs32 (0x33333333)+#define mi_mask_even_nibbles32 (0x0F0F0F0F)++// sum of all the bytes in `x` if it is guaranteed that the sum < 256!+static size_t mi_byte_sum32(uint32_t x) {+ // perform `x * 0x01010101`: the highest byte contains the sum of all bytes.+ x += (x << 8);+ x += (x << 16);+ return (size_t)(x >> 24);+}++static size_t mi_popcount_generic32(uint32_t x) {+ // first count each 2-bit group `a`, where: a==0b00 -> 00, a==0b01 -> 01, a==0b10 -> 01, a==0b11 -> 10+ // in other words, `a - (a>>1)`; to do this in parallel, we need to mask to prevent spilling a bit pair+ // into the lower bit-pair:+ x = x - ((x >> 1) & mi_mask_even_bits32);+ // add the 2-bit pair results+ x = (x & mi_mask_even_pairs32) + ((x >> 2) & mi_mask_even_pairs32);+ // add the 4-bit nibble results+ x = (x + (x >> 4)) & mi_mask_even_nibbles32;+ // each byte now has a count of its bits, we can sum them now:+ return mi_byte_sum32(x);+}++mi_decl_noinline size_t _mi_popcount_generic(size_t x) {+ if (x<=1) return x;+ if (~x==0) return MI_SIZE_BITS;+ return mi_popcount_generic32(x);+}++#else+#define mi_mask_even_bits64 (0x5555555555555555)+#define mi_mask_even_pairs64 (0x3333333333333333)+#define mi_mask_even_nibbles64 (0x0F0F0F0F0F0F0F0F)++// sum of all the bytes in `x` if it is guaranteed that the sum < 256!+static size_t mi_byte_sum64(uint64_t x) {+ x += (x << 8);+ x += (x << 16);+ x += (x << 32);+ return (size_t)(x >> 56);+}++static size_t mi_popcount_generic64(uint64_t x) {+ x = x - ((x >> 1) & mi_mask_even_bits64);+ x = (x & mi_mask_even_pairs64) + ((x >> 2) & mi_mask_even_pairs64);+ x = (x + (x >> 4)) & mi_mask_even_nibbles64;+ return mi_byte_sum64(x);+}++mi_decl_noinline size_t _mi_popcount_generic(size_t x) {+ if (x<=1) return x;+ if (~x==0) return MI_SIZE_BITS;+ return mi_popcount_generic64(x);+}+#endif+diff --git a/vendored/mimalloc/src/options.c b/vendored/mimalloc/src/options.cindex d7fa66651..0b71ebbad 100644--- a/vendored/mimalloc/src/options.c+++ b/vendored/mimalloc/src/options.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2021, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -12,8 +12,6 @@ terms of the MIT license. A copy of the license can be found in the file#include <stdio.h> // stdin/stdout#include <stdlib.h> // abort--static long mi_max_error_count = 16; // stop outputting errors after this (use < 0 for no limit)static long mi_max_warning_count = 16; // stop outputting warnings after this (use < 0 for no limit)@@ -30,19 +28,7 @@ int mi_version(void) mi_attr_noexcept {// concurrently initialized, but an initializing data race// is ok since they resolve to the same value.// ---------------------------------------------------------typedef enum mi_init_e {- UNINIT, // not yet initialized- DEFAULTED, // not found in the environment, use default value- INITIALIZED // found in environment or set explicitly-} mi_init_t;--typedef struct mi_option_desc_s {- long value; // the value- mi_init_t init; // is it initialized yet? (from the environment)- mi_option_t option; // for debugging: the option index should match the option- const char* name; // option name without `mimalloc_` prefix- const char* legacy_name; // potential legacy option name-} mi_option_desc_t;+#define MI_OPTION(opt) mi_option_##opt, #opt, NULL#define MI_OPTION_LEGACY(opt,legacy) mi_option_##opt, #opt, #legacy@@ -57,10 +43,6 @@ typedef struct mi_option_desc_s {#define MI_DEFAULT_VERBOSE 0#endif-#ifndef MI_DEFAULT_EAGER_COMMIT-#define MI_DEFAULT_EAGER_COMMIT 1-#endif-#ifndef MI_DEFAULT_ARENA_EAGER_COMMIT#define MI_DEFAULT_ARENA_EAGER_COMMIT 2#endif@@ -74,17 +56,17 @@ typedef struct mi_option_desc_s {#endif#endif+#ifndef MI_DEFAULT_ARENA_MAX_OBJECT_SIZE+#define MI_DEFAULT_ARENA_MAX_OBJECT_SIZE ((MI_SIZE_BITS * MI_ARENA_MAX_CHUNK_OBJ_SIZE)/MI_KiB) /* 2 GiB (or 256 MiB on 32-bit), larger than this is alloc'd by the OS */+#endif+#ifndef MI_DEFAULT_DISALLOW_ARENA_ALLOC#define MI_DEFAULT_DISALLOW_ARENA_ALLOC 0#endif#ifndef MI_DEFAULT_ALLOW_LARGE_OS_PAGES-#if defined(__linux__) && !defined(__ANDROID__)-#define MI_DEFAULT_ALLOW_LARGE_OS_PAGES 2 // enabled, but only use transparent huge pages through madvise-#else#define MI_DEFAULT_ALLOW_LARGE_OS_PAGES 0#endif-#endif#ifndef MI_DEFAULT_RESERVE_HUGE_OS_PAGES#define MI_DEFAULT_RESERVE_HUGE_OS_PAGES 0@@ -102,85 +84,118 @@ typedef struct mi_option_desc_s {#endif#endif+#ifndef MI_DEFAULT_PAGEMAP_COMMIT+#if defined(__APPLE__) // when overloading malloc, we still get mixed pointers sometimes on macOS; this avoids a bad access+#define MI_DEFAULT_PAGEMAP_COMMIT 1+#else+#define MI_DEFAULT_PAGEMAP_COMMIT 0+#endif+#endif++#ifndef MI_DEFAULT_PAGE_MAX_RECLAIM+#define MI_DEFAULT_PAGE_MAX_RECLAIM (-1) // unlimited+#endif++#ifndef MI_DEFAULT_PAGE_CROSS_THREAD_MAX_RECLAIM+#define MI_DEFAULT_PAGE_CROSS_THREAD_MAX_RECLAIM 32+#endif++#ifndef MI_DEFAULT_ALLOW_THP+#if defined(__ANDROID__)+#define MI_DEFAULT_ALLOW_THP 0+#else+#define MI_DEFAULT_ALLOW_THP 1+#endif+#endif-static mi_option_desc_t options[_mi_option_last] =+// Static options+static mi_option_desc_t mi_options[_mi_option_last] ={// stable options- #if MI_DEBUG || defined(MI_SHOW_ERRORS)- { 1, UNINIT, MI_OPTION(show_errors) },- #else- { 0, UNINIT, MI_OPTION(show_errors) },- #endif- { 0, UNINIT, MI_OPTION(show_stats) },- { MI_DEFAULT_VERBOSE, UNINIT, MI_OPTION(verbose) },+#if MI_DEBUG || defined(MI_SHOW_ERRORS)+ { 1, MI_OPTION_UNINIT, MI_OPTION(show_errors) },+#else+ { 0, MI_OPTION_UNINIT, MI_OPTION(show_errors) },+#endif+ { 0, MI_OPTION_UNINIT, MI_OPTION(show_stats) },+ { MI_DEFAULT_VERBOSE, MI_OPTION_UNINIT, MI_OPTION(verbose) },// some of the following options are experimental and not all combinations are allowed.- { MI_DEFAULT_EAGER_COMMIT,- UNINIT, MI_OPTION(eager_commit) }, // commit per segment directly (4MiB) (but see also `eager_commit_delay`)+ { 1, MI_OPTION_UNINIT, MI_OPTION(deprecated_eager_commit) },{ MI_DEFAULT_ARENA_EAGER_COMMIT,- UNINIT, MI_OPTION_LEGACY(arena_eager_commit,eager_region_commit) }, // eager commit arena's? 2 is used to enable this only on an OS that has overcommit (i.e. linux)- { 1, UNINIT, MI_OPTION_LEGACY(purge_decommits,reset_decommits) }, // purge decommits memory (instead of reset) (note: on linux this uses MADV_DONTNEED for decommit)+ MI_OPTION_UNINIT, MI_OPTION_LEGACY(arena_eager_commit,eager_region_commit) }, // eager commit arena's? 2 is used to enable this only on an OS that has overcommit (i.e. linux)+ { 1, MI_OPTION_UNINIT, MI_OPTION_LEGACY(purge_decommits,reset_decommits) }, // purge decommits memory (instead of reset) (note: on linux this uses MADV_DONTNEED for decommit){ MI_DEFAULT_ALLOW_LARGE_OS_PAGES,- UNINIT, MI_OPTION_LEGACY(allow_large_os_pages,large_os_pages) }, // use large OS pages, use only with eager commit to prevent fragmentation of VMA's+ MI_OPTION_UNINIT, MI_OPTION_LEGACY(allow_large_os_pages,large_os_pages) }, // use large OS pages, use only with eager commit to prevent fragmentation of VMA's{ MI_DEFAULT_RESERVE_HUGE_OS_PAGES,- UNINIT, MI_OPTION(reserve_huge_os_pages) }, // per 1GiB huge pages- {-1, UNINIT, MI_OPTION(reserve_huge_os_pages_at) }, // reserve huge pages at node N+ MI_OPTION_UNINIT, MI_OPTION(reserve_huge_os_pages) }, // per 1GiB huge pages+ {-1, MI_OPTION_UNINIT, MI_OPTION(reserve_huge_os_pages_at) }, // reserve huge pages at node N{ MI_DEFAULT_RESERVE_OS_MEMORY,- UNINIT, MI_OPTION(reserve_os_memory) }, // reserve N KiB OS memory in advance (use `option_get_size`)- { 0, UNINIT, MI_OPTION(deprecated_segment_cache) }, // cache N segments per thread- { 0, UNINIT, MI_OPTION(deprecated_page_reset) }, // reset page memory on free- { 0, UNINIT, MI_OPTION_LEGACY(abandoned_page_purge,abandoned_page_reset) }, // reset free page memory when a thread terminates- { 0, UNINIT, MI_OPTION(deprecated_segment_reset) }, // reset segment memory on free (needs eager commit)+ MI_OPTION_UNINIT, MI_OPTION(reserve_os_memory) }, // reserve N KiB OS memory in advance (use `option_get_size`)+ { 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_segment_cache) }, // cache N segments per thread+ { 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_page_reset) }, // reset page memory on free+ { 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_abandoned_page_purge) },+ { 0, MI_OPTION_UNINIT, MI_OPTION(deprecated_segment_reset) }, // reset segment memory on free (needs eager commit)#if defined(__NetBSD__)- { 0, UNINIT, MI_OPTION(eager_commit_delay) }, // the first N segments per thread are not eagerly committed+ { 0, MI_OPTION_UNINIT, MI_OPTION(eager_commit_delay) }, // the first N segments per thread are not eagerly committed#else- { 1, UNINIT, MI_OPTION(eager_commit_delay) }, // the first N segments per thread are not eagerly committed (but per page in the segment on demand)+ { 1, MI_OPTION_UNINIT, MI_OPTION(deprecated_eager_commit_delay) },#endif- { 10, UNINIT, MI_OPTION_LEGACY(purge_delay,reset_delay) }, // purge delay in milli-seconds- { 0, UNINIT, MI_OPTION(use_numa_nodes) }, // 0 = use available numa nodes, otherwise use at most N nodes.- { 0, UNINIT, MI_OPTION_LEGACY(disallow_os_alloc,limit_os_alloc) }, // 1 = do not use OS memory for allocation (but only reserved arenas)- { 100, UNINIT, MI_OPTION(os_tag) }, // only apple specific for now but might serve more or less related purpose- { 32, UNINIT, MI_OPTION(max_errors) }, // maximum errors that are output- { 32, UNINIT, MI_OPTION(max_warnings) }, // maximum warnings that are output- { 10, UNINIT, MI_OPTION(max_segment_reclaim)}, // max. percentage of the abandoned segments to be reclaimed per try.- { 0, UNINIT, MI_OPTION(destroy_on_exit)}, // release all OS memory on process exit; careful with dangling pointer or after-exit frees!- { MI_DEFAULT_ARENA_RESERVE, UNINIT, MI_OPTION(arena_reserve) }, // reserve memory N KiB at a time (=1GiB) (use `option_get_size`)- { 10, UNINIT, MI_OPTION(arena_purge_mult) }, // purge delay multiplier for arena's- { 1, UNINIT, MI_OPTION_LEGACY(purge_extend_delay, decommit_extend_delay) },- { 0, UNINIT, MI_OPTION(abandoned_reclaim_on_free) },// reclaim an abandoned segment on a free- { MI_DEFAULT_DISALLOW_ARENA_ALLOC, UNINIT, MI_OPTION(disallow_arena_alloc) }, // 1 = do not use arena's for allocation (except if using specific arena id's)- { 400, UNINIT, MI_OPTION(retry_on_oom) }, // windows only: retry on out-of-memory for N milli seconds (=400), set to 0 to disable retries.+ { 1000,MI_OPTION_UNINIT, MI_OPTION_LEGACY(purge_delay,reset_delay) }, // purge delay in milli-seconds+ { 0, MI_OPTION_UNINIT, MI_OPTION(use_numa_nodes) }, // 0 = use available numa nodes, otherwise use at most N nodes.+ { 0, MI_OPTION_UNINIT, MI_OPTION_LEGACY(disallow_os_alloc,limit_os_alloc) }, // 1 = do not use OS memory for allocation (but only reserved arenas)+ { 100, MI_OPTION_UNINIT, MI_OPTION(os_tag) }, // only apple specific for now but might serve more or less related purpose+ { 32, MI_OPTION_UNINIT, MI_OPTION(max_errors) }, // maximum errors that are output+ { 32, MI_OPTION_UNINIT, MI_OPTION(max_warnings) }, // maximum warnings that are output+ { 10, MI_OPTION_UNINIT, MI_OPTION(deprecated_max_segment_reclaim)}, // max. percentage of the abandoned segments to be reclaimed per try.+ { 0, MI_OPTION_UNINIT, MI_OPTION(destroy_on_exit)}, // release all OS memory on process exit; careful with dangling pointer or after-exit frees!+ { MI_DEFAULT_ARENA_RESERVE, MI_OPTION_UNINIT, MI_OPTION(arena_reserve) }, // reserve memory N KiB at a time (=1GiB) (use `option_get_size`)+ { 1, MI_OPTION_UNINIT, MI_OPTION(arena_purge_mult) }, // purge delay multiplier for arena's+ { 1, MI_OPTION_UNINIT, MI_OPTION_LEGACY(deprecated_purge_extend_delay, decommit_extend_delay) },+ { MI_DEFAULT_DISALLOW_ARENA_ALLOC, MI_OPTION_UNINIT, MI_OPTION(disallow_arena_alloc) }, // 1 = do not use arena's for allocation (except if using specific arena id's)+ { 400, MI_OPTION_UNINIT, MI_OPTION(retry_on_oom) }, // windows only: retry on out-of-memory for N milli seconds (=400), set to 0 to disable retries.#if defined(MI_VISIT_ABANDONED)- { 1, INITIALIZED, MI_OPTION(visit_abandoned) }, // allow visiting heap blocks in abandoned segments; requires taking locks during reclaim.+ { 1, MI_OPTION_INITIALIZED, MI_OPTION(visit_abandoned) }, // allow visiting theap blocks in abandoned segments; requires taking locks during reclaim.#else- { 0, UNINIT, MI_OPTION(visit_abandoned) },+ { 0, MI_OPTION_UNINIT, MI_OPTION(visit_abandoned) },#endif- { 0, UNINIT, MI_OPTION(guarded_min) }, // only used when building with MI_GUARDED: minimal rounded object size for guarded objects- { MI_GiB, UNINIT, MI_OPTION(guarded_max) }, // only used when building with MI_GUARDED: maximal rounded object size for guarded objects- { 0, UNINIT, MI_OPTION(guarded_precise) }, // disregard minimal alignment requirement to always place guarded blocks exactly in front of a guard page (=0)+ { 0, MI_OPTION_UNINIT, MI_OPTION(guarded_min) }, // only used when building with MI_GUARDED: minimal rounded object size for guarded objects+ { MI_GiB, MI_OPTION_UNINIT, MI_OPTION(guarded_max) }, // only used when building with MI_GUARDED: maximal rounded object size for guarded objects+ { 0, MI_OPTION_UNINIT, MI_OPTION(guarded_precise) }, // disregard minimal alignment requirement to always place guarded blocks exactly in front of a guard page (=0){ MI_DEFAULT_GUARDED_SAMPLE_RATE,- UNINIT, MI_OPTION(guarded_sample_rate)}, // 1 out of N allocations in the min/max range will be guarded (=4000)- { 0, UNINIT, MI_OPTION(guarded_sample_seed)},- { 0, UNINIT, MI_OPTION(target_segments_per_thread) }, // abandon segments beyond this point, or 0 to disable.+ MI_OPTION_UNINIT, MI_OPTION(guarded_sample_rate)}, // 1 out of N allocations in the min/max range will be guarded (=4000)+ { 0, MI_OPTION_UNINIT, MI_OPTION(guarded_sample_seed)},+ { 10000, MI_OPTION_UNINIT, MI_OPTION(generic_collect) }, // collect theaps every N (=10000) generic allocation calls+ { 0, MI_OPTION_UNINIT, MI_OPTION_LEGACY(page_reclaim_on_free, abandoned_reclaim_on_free) },// reclaim abandoned (small) pages on a free: -1 = disable completely, 0 = only reclaim into the originating theap, 1 = reclaim on free across theaps+ { 2, MI_OPTION_UNINIT, MI_OPTION(page_full_retain) }, // number of (small) pages to retain in the free page queues+ { 4, MI_OPTION_UNINIT, MI_OPTION(page_max_candidates) }, // max search to find a best page candidate+ { 0, MI_OPTION_UNINIT, MI_OPTION(max_vabits) }, // max virtual address space bits+ { MI_DEFAULT_PAGEMAP_COMMIT,+ MI_OPTION_UNINIT, MI_OPTION(pagemap_commit) }, // commit the full pagemap upfront?+ { 0, MI_OPTION_UNINIT, MI_OPTION(page_commit_on_demand) }, // commit pages on-demand (2 disables this only on overcommit systems (like Linux))+ { MI_DEFAULT_PAGE_MAX_RECLAIM,+ MI_OPTION_UNINIT, MI_OPTION(page_max_reclaim) }, // don't reclaim (small) pages of the same originating theap if we already own N pages in that size class+ { MI_DEFAULT_PAGE_CROSS_THREAD_MAX_RECLAIM,+ MI_OPTION_UNINIT, MI_OPTION(page_cross_thread_max_reclaim) }, // don't reclaim (small) pages across threads if we already own N pages in that size class+ { MI_DEFAULT_ALLOW_THP,+ MI_OPTION_UNINIT, MI_OPTION(allow_thp) }, // allow transparent huge pages? (=1) (on Android =0 by default). Set to 0 to disable THP for the process.+ { 0, MI_OPTION_UNINIT, MI_OPTION(minimal_purge_size) }, // set minimal purge size (in KiB) (=0). By default set to either 64 or 2048 if THP is enabled.+ { MI_DEFAULT_ARENA_MAX_OBJECT_SIZE,+ MI_OPTION_UNINIT, MI_OPTION(arena_max_object_size) }, // set maximal object size that can be allocated in an arena (in KiB) (=2GiB on 64-bit).};static void mi_option_init(mi_option_desc_t* desc);static bool mi_option_has_size_in_kib(mi_option_t option) {- return (option == mi_option_reserve_os_memory || option == mi_option_arena_reserve);+ return (option == mi_option_reserve_os_memory || option == mi_option_arena_reserve ||+ option == mi_option_minimal_purge_size || option == mi_option_arena_max_object_size);}void _mi_options_init(void) {// called on process load- mi_add_stderr_output(); // now it safe to use stderr for outputfor(int i = 0; i < _mi_option_last; i++ ) {mi_option_t option = (mi_option_t)i;long l = mi_option_get(option); MI_UNUSED(l); // initialize- // if (option != mi_option_verbose)- {- mi_option_desc_t* desc = &options[option];- _mi_verbose_message("option '%s': %ld %s\n", desc->name, desc->value, (mi_option_has_size_in_kib(option) ? "KiB" : ""));- }}mi_max_error_count = mi_option_get(mi_option_max_errors);mi_max_warning_count = mi_option_get(mi_option_max_warnings);@@ -191,15 +206,67 @@ void _mi_options_init(void) {_mi_warning_message("option 'allow_large_os_pages' is disabled to allow for guarded objects\n");}}- _mi_verbose_message("guarded build: %s\n", mi_option_get(mi_option_guarded_sample_rate) != 0 ? "enabled" : "disabled");+ #endif+}++// called at actual process load, it should be safe to print now+void _mi_options_post_init(void) {+ mi_add_stderr_output(); // now it safe to use stderr for output+ if (mi_option_is_enabled(mi_option_verbose)) { mi_options_print(); }+}++#define mi_stringifyx(str) #str // and stringify+#define mi_stringify(str) mi_stringifyx(str) // expand++mi_decl_export void mi_options_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept+{+ // show version+ const int vermajor = MI_MALLOC_VERSION/1000;+ const int verminor = (MI_MALLOC_VERSION%1000)/100;+ const int verpatch = (MI_MALLOC_VERSION%100);+ _mi_fprintf(out, arg, "v%i.%i.%i%s%s (built on %s, %s)\n", vermajor, verminor, verpatch,+ #if defined(MI_CMAKE_BUILD_TYPE)+ ", " mi_stringify(MI_CMAKE_BUILD_TYPE)+ #else+ ""+ #endif+ ,+ #if defined(MI_GIT_DESCRIBE)+ ", git " mi_stringify(MI_GIT_DESCRIBE)+ #else+ ""+ #endif+ , __DATE__, __TIME__);++ // show options+ for (int i = 0; i < _mi_option_last; i++) {+ mi_option_t option = (mi_option_t)i;+ long l = mi_option_get(option); MI_UNUSED(l); // possibly initialize+ mi_option_desc_t* desc = &mi_options[option];+ _mi_fprintf(out, arg, "option '%s': %ld %s\n", desc->name, desc->value, (mi_option_has_size_in_kib(option) ? "KiB" : ""));+ }++ // show build configuration+ _mi_fprintf(out, arg, "debug level : %d\n", MI_DEBUG );+ _mi_fprintf(out, arg, "secure level: %d\n", MI_SECURE );+ _mi_fprintf(out, arg, "mem tracking: %s\n", MI_TRACK_TOOL);+ #if MI_GUARDED+ _mi_fprintf(out, arg, "guarded build: %s\n", mi_option_get(mi_option_guarded_sample_rate) != 0 ? "enabled" : "disabled");#endif+ #if MI_TSAN+ _mi_fprintf(out, arg, "thread santizer enabled\n");+ #endif+}++mi_decl_export void mi_options_print(void) mi_attr_noexcept {+ mi_options_print_out(NULL, NULL);}long _mi_option_get_fast(mi_option_t option) {mi_assert(option >= 0 && option < _mi_option_last);- mi_option_desc_t* desc = &options[option];+ mi_option_desc_t* desc = &mi_options[option];mi_assert(desc->option == option); // index should match the option- //mi_assert(desc->init != UNINIT);+ //mi_assert(desc->init != MI_OPTION_UNINIT);return desc->value;}@@ -207,9 +274,9 @@ long _mi_option_get_fast(mi_option_t option) {mi_decl_nodiscard long mi_option_get(mi_option_t option) {mi_assert(option >= 0 && option < _mi_option_last);if (option < 0 || option >= _mi_option_last) return 0;- mi_option_desc_t* desc = &options[option];+ mi_option_desc_t* desc = &mi_options[option];mi_assert(desc->option == option); // index should match the option- if mi_unlikely(desc->init == UNINIT) {+ if mi_unlikely(desc->init == MI_OPTION_UNINIT) {mi_option_init(desc);}return desc->value;@@ -232,10 +299,10 @@ mi_decl_nodiscard size_t mi_option_get_size(mi_option_t option) {void mi_option_set(mi_option_t option, long value) {mi_assert(option >= 0 && option < _mi_option_last);if (option < 0 || option >= _mi_option_last) return;- mi_option_desc_t* desc = &options[option];+ mi_option_desc_t* desc = &mi_options[option];mi_assert(desc->option == option); // index should match the optiondesc->value = value;- desc->init = INITIALIZED;+ desc->init = MI_OPTION_INITIALIZED;// ensure min/max range; be careful to not recurse.if (desc->option == mi_option_guarded_min && _mi_option_get_fast(mi_option_guarded_max) < value) {mi_option_set(mi_option_guarded_max, value);@@ -248,8 +315,8 @@ void mi_option_set(mi_option_t option, long value) {void mi_option_set_default(mi_option_t option, long value) {mi_assert(option >= 0 && option < _mi_option_last);if (option < 0 || option >= _mi_option_last) return;- mi_option_desc_t* desc = &options[option];- if (desc->init != INITIALIZED) {+ mi_option_desc_t* desc = &mi_options[option];+ if (desc->init != MI_OPTION_INITIALIZED) {desc->value = value;}}@@ -288,7 +355,7 @@ static void mi_cdecl mi_out_stderr(const char* msg, void* arg) {#ifndef MI_MAX_DELAY_OUTPUT#define MI_MAX_DELAY_OUTPUT ((size_t)(16*1024))#endif-static char out_buf[MI_MAX_DELAY_OUTPUT+1];+static char mi_output_buffer[MI_MAX_DELAY_OUTPUT+1];static _Atomic(size_t) out_len;static void mi_cdecl mi_out_buf(const char* msg, void* arg) {@@ -304,7 +371,8 @@ static void mi_cdecl mi_out_buf(const char* msg, void* arg) {if (start+n >= MI_MAX_DELAY_OUTPUT) {n = MI_MAX_DELAY_OUTPUT-start-1;}- _mi_memcpy(&out_buf[start], msg, n);+ mi_assert_internal(start + n <= MI_MAX_DELAY_OUTPUT);+ _mi_memcpy(&mi_output_buffer[start], msg, n);}static void mi_out_buf_flush(mi_output_fun* out, bool no_more_buf, void* arg) {@@ -313,10 +381,10 @@ static void mi_out_buf_flush(mi_output_fun* out, bool no_more_buf, void* arg) {size_t count = mi_atomic_add_acq_rel(&out_len, (no_more_buf ? MI_MAX_DELAY_OUTPUT : 1));// and output the current contentsif (count>MI_MAX_DELAY_OUTPUT) count = MI_MAX_DELAY_OUTPUT;- out_buf[count] = 0;- out(out_buf,arg);+ mi_output_buffer[count] = 0;+ out(mi_output_buffer,arg);if (!no_more_buf) {- out_buf[count] = '\n'; // if continue with the buffer, insert a newline+ mi_output_buffer[count] = '\n'; // if continue with the buffer, insert a newline}}@@ -354,8 +422,10 @@ void mi_register_output(mi_output_fun* out, void* arg) mi_attr_noexcept {// add stderr to the delayed output after the module is loadedstatic void mi_add_stderr_output(void) {mi_assert_internal(mi_out_default == NULL);- mi_out_buf_flush(&mi_out_stderr, false, NULL); // flush current contents to stderr- mi_out_default = &mi_out_buf_stderr; // and add stderr to the delayed output+ if (mi_out_default==NULL) {+ mi_out_buf_flush(&mi_out_stderr, false, NULL); // flush current contents to stderr+ mi_out_default = &mi_out_buf_stderr; // and add stderr to the delayed output+ }}// --------------------------------------------------------@@ -386,14 +456,14 @@ static mi_decl_noinline void mi_recurse_exit_prim(void) {}static bool mi_recurse_enter(void) {- #if defined(__APPLE__) || defined(MI_TLS_RECURSE_GUARD)+ #if defined(__APPLE__) || defined(__ANDROID__) || defined(MI_TLS_RECURSE_GUARD)if (_mi_preloading()) return false;#endifreturn mi_recurse_enter_prim();}static void mi_recurse_exit(void) {- #if defined(__APPLE__) || defined(MI_TLS_RECURSE_GUARD)+ #if defined(__APPLE__) || defined(__ANDROID__) || defined(MI_TLS_RECURSE_GUARD)if (_mi_preloading()) return;#endifmi_recurse_exit_prim();@@ -416,7 +486,7 @@ void _mi_fputs(mi_output_fun* out, void* arg, const char* prefix, const char* me// Define our own limited `fprintf` that avoids memory allocation.// We do this using `_mi_vsnprintf` with a limited buffer.static void mi_vfprintf( mi_output_fun* out, void* arg, const char* prefix, const char* fmt, va_list args ) {- char buf[512];+ char buf[992];if (fmt==NULL) return;if (!mi_recurse_enter()) return;_mi_vsnprintf(buf, sizeof(buf)-1, fmt, args);@@ -442,6 +512,20 @@ static void mi_vfprintf_thread(mi_output_fun* out, void* arg, const char* prefix}}+void _mi_raw_message(const char* fmt, ...) {+ va_list args;+ va_start(args, fmt);+ mi_vfprintf(NULL, NULL, NULL, fmt, args);+ va_end(args);+}++void _mi_message(const char* fmt, ...) {+ va_list args;+ va_start(args, fmt);+ mi_vfprintf_thread(NULL, NULL, "mimalloc: ", fmt, args);+ va_end(args);+}+void _mi_trace_message(const char* fmt, ...) {if (mi_option_get(mi_option_verbose) <= 1) return; // only with verbose level 2 or higherva_list args;@@ -479,7 +563,7 @@ void _mi_warning_message(const char* fmt, ...) {#if MI_DEBUG-void _mi_assert_fail(const char* assertion, const char* fname, unsigned line, const char* func ) {+mi_decl_noreturn mi_decl_cold void _mi_assert_fail(const char* assertion, const char* fname, unsigned line, const char* func ) mi_attr_noexcept {_mi_fprintf(NULL, NULL, "mimalloc: assertion failed: at \"%s\":%u, %s\n assertion: \"%s\"\n", fname, line, (func==NULL?"":func), assertion);abort();}@@ -567,11 +651,11 @@ static void mi_option_init(mi_option_desc_t* desc) {buf[len] = 0;if (buf[0] == 0 || strstr("1;TRUE;YES;ON", buf) != NULL) {desc->value = 1;- desc->init = INITIALIZED;+ desc->init = MI_OPTION_INITIALIZED;}else if (strstr("0;FALSE;NO;OFF", buf) != NULL) {desc->value = 0;- desc->init = INITIALIZED;+ desc->init = MI_OPTION_INITIALIZED;}else {char* end = buf;@@ -596,7 +680,7 @@ static void mi_option_init(mi_option_desc_t* desc) {}else {// set `init` first to avoid recursion through _mi_warning_message on mimalloc_verbose.- desc->init = DEFAULTED;+ desc->init = MI_OPTION_DEFAULTED;if (desc->option == mi_option_verbose && desc->value == 0) {// if the 'mimalloc_verbose' env var has a bogus value we'd never know// (since the value defaults to 'off') so in that case briefly enable verbose@@ -609,9 +693,9 @@ static void mi_option_init(mi_option_desc_t* desc) {}}}- mi_assert_internal(desc->init != UNINIT);+ mi_assert_internal(desc->init != MI_OPTION_UNINIT);}else if (!_mi_preloading()) {- desc->init = DEFAULTED;+ desc->init = MI_OPTION_DEFAULTED;}}diff --git a/vendored/mimalloc/src/os.c b/vendored/mimalloc/src/os.cindex 61c9eebfe..45d1d8ea7 100644--- a/vendored/mimalloc/src/os.c+++ b/vendored/mimalloc/src/os.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2023, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -9,26 +9,14 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc/atomic.h"#include "mimalloc/prim.h"-#define mi_os_stat_increase(stat,amount) _mi_stat_increase(&_mi_stats_main.stat, amount)-#define mi_os_stat_decrease(stat,amount) _mi_stat_decrease(&_mi_stats_main.stat, amount)-#define mi_os_stat_counter_increase(stat,inc) _mi_stat_counter_increase(&_mi_stats_main.stat, inc)-/* -----------------------------------------------------------Initialization.----------------------------------------------------------- */-#ifndef MI_DEFAULT_VIRTUAL_ADDRESS_BITS+#ifndef MI_DEFAULT_PHYSICAL_MEMORY_IN_KIB#if MI_INTPTR_SIZE < 8-#define MI_DEFAULT_VIRTUAL_ADDRESS_BITS 32+#define MI_DEFAULT_PHYSICAL_MEMORY_IN_KIB 4*MI_MiB // 4 GiB#else-#define MI_DEFAULT_VIRTUAL_ADDRESS_BITS 48-#endif-#endif--#ifndef MI_DEFAULT_PHYSICAL_MEMORY-#if MI_INTPTR_SIZE < 8-#define MI_DEFAULT_PHYSICAL_MEMORY 4*MI_GiB-#else-#define MI_DEFAULT_PHYSICAL_MEMORY 32*MI_GiB+#define MI_DEFAULT_PHYSICAL_MEMORY_IN_KIB 32*MI_MiB // 32 GiB#endif#endif@@ -36,11 +24,12 @@ static mi_os_mem_config_t mi_os_mem_config = {4096, // page size0, // large page size (usually 2MiB)4096, // allocation granularity- MI_DEFAULT_PHYSICAL_MEMORY,- MI_DEFAULT_VIRTUAL_ADDRESS_BITS,+ MI_DEFAULT_PHYSICAL_MEMORY_IN_KIB,+ MI_MAX_VABITS, // in `bits.h`true, // has overcommit? (if true we use MAP_NORESERVE on mmap systems)false, // can we partially free allocated blocks? (on mmap systems we can free anywhere in a mapped range, but on Windows we must free the entire span)- true // has virtual reserve? (if true we can reserve virtual address space without using commit or physical memory)+ true, // has virtual reserve? (if true we can reserve virtual address space without using commit or physical memory)+ false // has transparent huge pages? (if true we purge in (aligned) large page size chunks only to not fragment such pages)};bool _mi_os_has_overcommit(void) {@@ -62,9 +51,35 @@ size_t _mi_os_large_page_size(void) {return (mi_os_mem_config.large_page_size != 0 ? mi_os_mem_config.large_page_size : _mi_os_page_size());}-bool _mi_os_use_large_page(size_t size, size_t alignment) {+// minimal purge size. Can be larger than the page size if transparent huge pages are enabled.+size_t _mi_os_minimal_purge_size(void) {+ size_t minsize = mi_option_get_size(mi_option_minimal_purge_size);+ if (minsize != 0) {+ return _mi_align_up(minsize, _mi_os_page_size());+ }+ else if (mi_os_mem_config.has_transparent_huge_pages && mi_option_is_enabled(mi_option_allow_thp)) {+ return _mi_os_large_page_size();+ }+ else {+ return _mi_os_page_size();+ }+}++size_t _mi_os_guard_page_size(void) {+ const size_t gsize = _mi_os_page_size();+ mi_assert(gsize <= (MI_ARENA_SLICE_SIZE/4)); // issue #1166+ return gsize;+}++size_t _mi_os_virtual_address_bits(void) {+ const size_t vbits = mi_os_mem_config.virtual_address_bits;+ mi_assert(vbits <= MI_MAX_VABITS);+ return vbits;+}++bool _mi_os_canuse_large_page(size_t size, size_t alignment) {// if we have access, check the size and alignment requirements- if (mi_os_mem_config.large_page_size == 0 || !mi_option_is_enabled(mi_option_allow_large_os_pages)) return false;+ if (mi_os_mem_config.large_page_size == 0) return false;return ((size % mi_os_mem_config.large_page_size) == 0 && (alignment % mi_os_mem_config.large_page_size) == 0);}@@ -91,90 +106,112 @@ void _mi_os_init(void) {bool _mi_os_decommit(void* addr, size_t size);bool _mi_os_commit(void* addr, size_t size, bool* is_zero);+void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size) {+ MI_UNUSED(try_alignment); MI_UNUSED(size);+ return NULL;+}-/* ------------------------------------------------------------ aligned hinting--------------------------------------------------------------- */--// On systems with enough virtual address bits, we can do efficient aligned allocation by using-// the 2TiB to 30TiB area to allocate those. If we have at least 46 bits of virtual address-// space (64TiB) we use this technique. (but see issue #939)-#if (MI_INTPTR_SIZE >= 8) && !defined(MI_NO_ALIGNED_HINT)-static mi_decl_cache_align _Atomic(uintptr_t)aligned_base;-// Return a MI_SEGMENT_SIZE aligned address that is probably available.-// If this returns NULL, the OS will determine the address but on some OS's that may not be-// properly aligned which can be more costly as it needs to be adjusted afterwards.-// For a size > 1GiB this always returns NULL in order to guarantee good ASLR randomization;-// (otherwise an initial large allocation of say 2TiB has a 50% chance to include (known) addresses-// in the middle of the 2TiB - 6TiB address range (see issue #372))+/* -----------------------------------------------------------+ Guard page allocation+----------------------------------------------------------- */-#define MI_HINT_BASE ((uintptr_t)2 << 40) // 2TiB start-#define MI_HINT_AREA ((uintptr_t)4 << 40) // upto 6TiB (since before win8 there is "only" 8TiB available to processes)-#define MI_HINT_MAX ((uintptr_t)30 << 40) // wrap after 30TiB (area after 32TiB is used for huge OS pages)+// In secure mode, return the size of a guard page, otherwise 0+size_t _mi_os_secure_guard_page_size(void) {+ #if MI_SECURE > 0+ return _mi_os_guard_page_size();+ #else+ return 0;+ #endif+}-void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size)-{- if (try_alignment <= 1 || try_alignment > MI_SEGMENT_SIZE) return NULL;- if (mi_os_mem_config.virtual_address_bits < 46) return NULL; // < 64TiB virtual address space- size = _mi_align_up(size, MI_SEGMENT_SIZE);- if (size > 1*MI_GiB) return NULL; // guarantee the chance of fixed valid address is at most 1/(MI_HINT_AREA / 1<<30) = 1/4096.- #if (MI_SECURE>0)- size += MI_SEGMENT_SIZE; // put in `MI_SEGMENT_SIZE` virtual gaps between hinted blocks; this splits VLA's but increases guarded areas.+// In secure mode, try to decommit an area and output a warning if this fails.+bool _mi_os_secure_guard_page_set_at(void* addr, mi_memid_t memid) {+ if (addr == NULL) return true;+ #if MI_SECURE > 0+ bool ok = false;+ if (!memid.is_pinned) {+ mi_arena_t* const arena = mi_memid_arena(memid);+ if (arena != NULL && arena->commit_fun != NULL) {+ ok = (*(arena->commit_fun))(false /* decommit */, addr, _mi_os_secure_guard_page_size(), NULL, arena->commit_fun_arg);+ }+ else {+ ok = _mi_os_decommit(addr, _mi_os_secure_guard_page_size());+ }+ }+ if (!ok) {+ _mi_error_message(EINVAL, "secure level %d, but failed to commit guard page (at %p of size %zu)\n", MI_SECURE, addr, _mi_os_secure_guard_page_size());+ }+ return ok;+ #else+ MI_UNUSED(memid);+ return true;#endif+}- uintptr_t hint = mi_atomic_add_acq_rel(&aligned_base, size);- if (hint == 0 || hint > MI_HINT_MAX) { // wrap or initialize- uintptr_t init = MI_HINT_BASE;- #if (MI_SECURE>0 || MI_DEBUG==0) // security: randomize start of aligned allocations unless in debug mode- uintptr_t r = _mi_heap_random_next(mi_prim_get_default_heap());- init = init + ((MI_SEGMENT_SIZE * ((r>>17) & 0xFFFFF)) % MI_HINT_AREA); // (randomly 20 bits)*4MiB == 0 to 4TiB- #endif- uintptr_t expected = hint + size;- mi_atomic_cas_strong_acq_rel(&aligned_base, &expected, init);- hint = mi_atomic_add_acq_rel(&aligned_base, size); // this may still give 0 or > MI_HINT_MAX but that is ok, it is a hint after all+// In secure mode, try to decommit an area and output a warning if this fails.+bool _mi_os_secure_guard_page_set_before(void* addr, mi_memid_t memid) {+ return _mi_os_secure_guard_page_set_at((uint8_t*)addr - _mi_os_secure_guard_page_size(), memid);+}++// In secure mode, try to recommit an area+bool _mi_os_secure_guard_page_reset_at(void* addr, mi_memid_t memid) {+ if (addr == NULL) return true;+ #if MI_SECURE > 0+ if (!memid.is_pinned) {+ mi_arena_t* const arena = mi_memid_arena(memid);+ if (arena != NULL && arena->commit_fun != NULL) {+ return (*(arena->commit_fun))(true, addr, _mi_os_secure_guard_page_size(), NULL, arena->commit_fun_arg);+ }+ else {+ return _mi_os_commit(addr, _mi_os_secure_guard_page_size(), NULL);+ }}- if (hint%try_alignment != 0) return NULL;- return (void*)hint;+ #else+ MI_UNUSED(memid);+ #endif+ return true;}-#else-void* _mi_os_get_aligned_hint(size_t try_alignment, size_t size) {- MI_UNUSED(try_alignment); MI_UNUSED(size);- return NULL;++// In secure mode, try to recommit an area+bool _mi_os_secure_guard_page_reset_before(void* addr, mi_memid_t memid) {+ return _mi_os_secure_guard_page_reset_at((uint8_t*)addr - _mi_os_secure_guard_page_size(), memid);}-#endif+/* -----------------------------------------------------------Free memory-------------------------------------------------------------- */-static void mi_os_free_huge_os_pages(void* p, size_t size);+static void mi_os_free_huge_os_pages(void* p, size_t size, mi_subproc_t* subproc);-static void mi_os_prim_free(void* addr, size_t size, size_t commit_size) {+static void mi_os_prim_free(void* addr, size_t size, size_t commit_size, mi_subproc_t* subproc) {mi_assert_internal((size % _mi_os_page_size()) == 0);- if (addr == NULL || size == 0) return; // || _mi_os_is_huge_reserved(addr)- int err = _mi_prim_free(addr, size);+ if (addr == NULL) return; // || _mi_os_is_huge_reserved(addr)+ int err = _mi_prim_free(addr, size); // allow size==0 (issue #1041)if (err != 0) {_mi_warning_message("unable to free OS memory (error: %d (0x%x), size: 0x%zx bytes, address: %p)\n", err, err, size, addr);}+ if (subproc == NULL) { subproc = _mi_subproc(); } // from `mi_arenas_unsafe_destroy` we pass subproc_main explicitly as we can no longer use the theap pointerif (commit_size > 0) {- mi_os_stat_decrease(committed, commit_size);+ mi_subproc_stat_decrease(subproc, committed, commit_size);}- mi_os_stat_decrease(reserved, size);+ mi_subproc_stat_decrease(subproc, reserved, size);}-void _mi_os_free_ex(void* addr, size_t size, bool still_committed, mi_memid_t memid) {+void _mi_os_free_ex(void* addr, size_t size, bool still_committed, mi_memid_t memid, mi_subproc_t* subproc /* can be NULL */) {if (mi_memkind_is_os(memid.memkind)) {size_t csize = memid.mem.os.size;- if (csize==0) { _mi_os_good_alloc_size(size); }+ if (csize==0) { csize = _mi_os_good_alloc_size(size); }+ mi_assert_internal(csize >= size);size_t commit_size = (still_committed ? csize : 0);void* base = addr;// different base? (due to alignment)if (memid.mem.os.base != base) {- mi_assert(memid.mem.os.base <= addr);+ mi_assert(memid.mem.os.base <= addr);base = memid.mem.os.base;const size_t diff = (uint8_t*)addr - (uint8_t*)memid.mem.os.base;- if (memid.mem.os.size==0) {+ if (memid.mem.os.size==0) {csize += diff;}if (still_committed) {@@ -184,10 +221,10 @@ void _mi_os_free_ex(void* addr, size_t size, bool still_committed, mi_memid_t me// free itif (memid.memkind == MI_MEM_OS_HUGE) {mi_assert(memid.is_pinned);- mi_os_free_huge_os_pages(base, csize);+ mi_os_free_huge_os_pages(base, csize, subproc);}else {- mi_os_prim_free(base, csize, (still_committed ? commit_size : 0));+ mi_os_prim_free(base, csize, (still_committed ? commit_size : 0), subproc);}}else {@@ -197,7 +234,7 @@ void _mi_os_free_ex(void* addr, size_t size, bool still_committed, mi_memid_t me}void _mi_os_free(void* p, size_t size, mi_memid_t memid) {- _mi_os_free_ex(p, size, true, memid);+ _mi_os_free_ex(p, size, true, memid, NULL);}@@ -221,8 +258,6 @@ static void* mi_os_prim_alloc_at(void* hint_addr, size_t size, size_t try_alignm_mi_warning_message("unable to allocate OS memory (error: %d (0x%x), addr: %p, size: 0x%zx bytes, align: 0x%zx, commit: %d, allow large: %d)\n", err, err, hint_addr, size, try_alignment, commit, allow_large);}--mi_os_stat_counter_increase(mmap_calls, 1);if (p != NULL) {mi_os_stat_increase(reserved, size);@@ -255,20 +290,26 @@ static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commitif (!(alignment >= _mi_os_page_size() && ((alignment & (alignment - 1)) == 0))) return NULL;size = _mi_align_up(size, _mi_os_page_size());- // try first with a requested alignment hint (this will usually be aligned directly on Win 10+ or BSD)- void* p = mi_os_prim_alloc(size, alignment, commit, allow_large, is_large, is_zero);- if (p == NULL) return NULL;+ // try a direct allocation if the alignment is below the default, or if larger than 1/8 fraction of the size.+ const bool try_direct_alloc = (alignment <= mi_os_mem_config.alloc_granularity || alignment > size/8);++ void* p = NULL;+ if (try_direct_alloc) {+ p = mi_os_prim_alloc(size, alignment, commit, allow_large, is_large, is_zero);+ }// aligned already?- if (((uintptr_t)p % alignment) == 0) {+ if (p != NULL && ((uintptr_t)p % alignment) == 0) {*base = p;}else {// if not aligned, free it, overallocate, and unmap around it#if !MI_TRACK_ASAN- _mi_warning_message("unable to allocate aligned OS memory directly, fall back to over-allocation (size: 0x%zx bytes, address: %p, alignment: 0x%zx, commit: %d)\n", size, p, alignment, commit);+ if (try_direct_alloc) {+ _mi_warning_message("unable to allocate aligned OS memory directly, fall back to over-allocation (size: 0x%zx bytes, address: %p, alignment: 0x%zx, commit: %d)\n", size, p, alignment, commit);+ }#endif- if (p != NULL) { mi_os_prim_free(p, size, (commit ? size : 0)); }+ if (p != NULL) { mi_os_prim_free(p, size, (commit ? size : 0), NULL); }if (size >= (SIZE_MAX - alignment)) return NULL; // overflowconst size_t over_size = size + alignment;@@ -278,14 +319,17 @@ static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commitif (p == NULL) return NULL;// set p to the aligned part in the full region- // note: this is dangerous on Windows as VirtualFree needs the actual base pointer- // this is handled though by having the `base` field in the memid's+ // note: on Windows VirtualFree needs the actual base pointer+ // this is handledby having the `base` field in the memid.*base = p; // remember the base- p = mi_align_up_ptr(p, alignment);+ p = _mi_align_up_ptr(p, alignment);// explicitly commit only the aligned partif (commit) {- _mi_os_commit(p, size, NULL);+ if (!_mi_os_commit(p, size, NULL)) {+ mi_os_prim_free(*base, over_size, 0, NULL);+ return NULL;+ }}}else { // mmap can free inside an allocation@@ -294,13 +338,13 @@ static void* mi_os_prim_alloc_aligned(size_t size, size_t alignment, bool commitif (p == NULL) return NULL;// and selectively unmap parts around the over-allocated area.- void* aligned_p = mi_align_up_ptr(p, alignment);+ void* aligned_p = _mi_align_up_ptr(p, alignment);size_t pre_size = (uint8_t*)aligned_p - (uint8_t*)p;size_t mid_size = _mi_align_up(size, _mi_os_page_size());size_t post_size = over_size - pre_size - mid_size;mi_assert_internal(pre_size < over_size&& post_size < over_size&& mid_size >= size);- if (pre_size > 0) { mi_os_prim_free(p, pre_size, (commit ? pre_size : 0)); }- if (post_size > 0) { mi_os_prim_free((uint8_t*)aligned_p + mid_size, post_size, (commit ? post_size : 0)); }+ if (pre_size > 0) { mi_os_prim_free(p, pre_size, (commit ? pre_size : 0), NULL); }+ if (post_size > 0) { mi_os_prim_free((uint8_t*)aligned_p + mid_size, post_size, (commit ? post_size : 0), NULL); }// we can return the aligned pointer on `mmap` systemsp = aligned_p;*base = aligned_p; // since we freed the pre part, `*base == p`.@@ -323,9 +367,11 @@ void* _mi_os_alloc(size_t size, mi_memid_t* memid) {bool os_is_large = false;bool os_is_zero = false;void* p = mi_os_prim_alloc(size, 0, true, false, &os_is_large, &os_is_zero);- if (p != NULL) {- *memid = _mi_memid_create_os(true, os_is_zero, os_is_large);- }+ if (p == NULL) return NULL;++ *memid = _mi_memid_create_os(p, size, true, os_is_zero, os_is_large);+ mi_assert_internal(memid->mem.os.size >= size);+ mi_assert_internal(memid->initially_committed);return p;}@@ -341,15 +387,42 @@ void* _mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, bool allobool os_is_zero = false;void* os_base = NULL;void* p = mi_os_prim_alloc_aligned(size, alignment, commit, allow_large, &os_is_large, &os_is_zero, &os_base );- if (p != NULL) {- *memid = _mi_memid_create_os(commit, os_is_zero, os_is_large);- memid->mem.os.base = os_base;- // memid->mem.os.alignment = alignment;- memid->mem.os.size += ((uint8_t*)p - (uint8_t*)os_base); // todo: return from prim_alloc_aligned+ if (p == NULL) return NULL;++ *memid = _mi_memid_create_os(p, size, commit, os_is_zero, os_is_large);+ memid->mem.os.base = os_base;+ memid->mem.os.size += ((uint8_t*)p - (uint8_t*)os_base); // todo: return from prim_alloc_aligned?++ mi_assert_internal(memid->mem.os.size >= size);+ mi_assert_internal(_mi_is_aligned(p,alignment));+ if (commit) { mi_assert_internal(memid->initially_committed); }+ return p;+}+++mi_decl_nodiscard static void* mi_os_ensure_zero(void* p, size_t size, mi_memid_t* memid) {+ if (p==NULL || size==0) return p;+ // ensure committed+ if (!memid->initially_committed) {+ bool is_zero = false;+ if (!_mi_os_commit(p, size, &is_zero)) {+ _mi_os_free(p, size, *memid);+ return NULL;+ }+ memid->initially_committed = true;}+ // ensure zero'd+ if (memid->initially_zero) return p;+ _mi_memzero_aligned(p,size);+ memid->initially_zero = true;return p;}+void* _mi_os_zalloc(size_t size, mi_memid_t* memid) {+ void* p = _mi_os_alloc(size,memid);+ return mi_os_ensure_zero(p, size, memid);+}+/* -----------------------------------------------------------OS aligned allocation with an offset. This is usedfor large alignments > MI_BLOCK_ALIGNMENT_MAX. We use a large mimalloc@@ -359,11 +432,9 @@ void* _mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, bool allo----------------------------------------------------------- */void* _mi_os_alloc_aligned_at_offset(size_t size, size_t alignment, size_t offset, bool commit, bool allow_large, mi_memid_t* memid) {- mi_assert(offset <= MI_SEGMENT_SIZE);mi_assert(offset <= size);mi_assert((alignment % _mi_os_page_size()) == 0);*memid = _mi_memid_none();- if (offset > MI_SEGMENT_SIZE) return NULL;if (offset == 0) {// regular aligned allocationreturn _mi_os_alloc_aligned(size, alignment, commit, allow_large, memid);@@ -396,11 +467,11 @@ static void* mi_os_page_align_areax(bool conservative, void* addr, size_t size,if (newsize != NULL) *newsize = 0;if (size == 0 || addr == NULL) return NULL;- // page align conservatively within the range- void* start = (conservative ? mi_align_up_ptr(addr, _mi_os_page_size())+ // page align conservatively within the range, or liberally straddling pages outside the range+ void* start = (conservative ? _mi_align_up_ptr(addr, _mi_os_page_size()): mi_align_down_ptr(addr, _mi_os_page_size()));void* end = (conservative ? mi_align_down_ptr((uint8_t*)addr + size, _mi_os_page_size())- : mi_align_up_ptr((uint8_t*)addr + size, _mi_os_page_size()));+ : _mi_align_up_ptr((uint8_t*)addr + size, _mi_os_page_size()));ptrdiff_t diff = (uint8_t*)end - (uint8_t*)start;if (diff <= 0) return NULL;@@ -415,7 +486,6 @@ static void* mi_os_page_align_area_conservative(void* addr, size_t size, size_t*bool _mi_os_commit_ex(void* addr, size_t size, bool* is_zero, size_t stat_size) {if (is_zero != NULL) { *is_zero = false; }- mi_os_stat_increase(committed, stat_size); // use size for precise commit vs. decommitmi_os_stat_counter_increase(commit_calls, 1);// page align range@@ -439,6 +509,7 @@ bool _mi_os_commit_ex(void* addr, size_t size, bool* is_zero, size_t stat_size)if (os_is_zero) { mi_track_mem_defined(start,csize); }else { mi_track_mem_undefined(start,csize); }#endif+ mi_os_stat_increase(committed, stat_size); // use size for precise commit vs. decommitreturn true;}@@ -480,7 +551,7 @@ bool _mi_os_reset(void* addr, size_t size) {size_t csize;void* start = mi_os_page_align_area_conservative(addr, size, &csize);if (csize == 0) return true; // || _mi_os_is_huge_reserved(addr)- mi_os_stat_increase(reset, csize);+ mi_os_stat_counter_increase(reset, csize);mi_os_stat_counter_increase(reset_calls, 1);#if (MI_DEBUG>1) && !MI_SECURE && !MI_TRACK_ENABLED // && !MI_TSAN@@ -495,23 +566,38 @@ bool _mi_os_reset(void* addr, size_t size) {}+void _mi_os_reuse( void* addr, size_t size ) {+ // page align conservatively within the range+ size_t csize = 0;+ void* const start = mi_os_page_align_area_conservative(addr, size, &csize);+ if (csize == 0) return;+ const int err = _mi_prim_reuse(start, csize);+ if (err != 0) {+ _mi_warning_message("cannot reuse OS memory (error: %d (0x%x), address: %p, size: 0x%zx bytes)\n", err, err, start, csize);+ }+}+// either resets or decommits memory, returns true if the memory needs// to be recommitted if it is to be re-used later on.-bool _mi_os_purge_ex(void* p, size_t size, bool allow_reset, size_t stat_size)+bool _mi_os_purge_ex(void* p, size_t size, bool allow_reset, size_t stat_size, mi_commit_fun_t* commit_fun, void* commit_fun_arg){if (mi_option_get(mi_option_purge_delay) < 0) return false; // is purging allowed?mi_os_stat_counter_increase(purge_calls, 1);- mi_os_stat_increase(purged, size);+ mi_os_stat_counter_increase(purged, size);- if (mi_option_is_enabled(mi_option_purge_decommits) && // should decommit?- !_mi_preloading()) // don't decommit during preloading (unsafe)+ if (commit_fun != NULL) {+ bool decommitted = (*commit_fun)(false, p, size, NULL, commit_fun_arg);+ return decommitted; // needs_recommit?+ }+ else if (mi_option_is_enabled(mi_option_purge_decommits) && // should decommit?+ !_mi_preloading()) // don't decommit during preloading (unsafe){bool needs_recommit = true;mi_os_decommit_ex(p, size, &needs_recommit, stat_size);return needs_recommit;}else {- if (allow_reset) { // this can sometimes be not allowed if the range is not fully committed+ if (allow_reset) { // this can sometimes be not allowed if the range is not fully committed (on Windows, we cannot reset uncommitted memory)_mi_os_reset(p, size);}return false; // needs no recommit@@ -521,9 +607,10 @@ bool _mi_os_purge_ex(void* p, size_t size, bool allow_reset, size_t stat_size)// either resets or decommits memory, returns true if the memory needs// to be recommitted if it is to be re-used later on.bool _mi_os_purge(void* p, size_t size) {- return _mi_os_purge_ex(p, size, true, size);+ return _mi_os_purge_ex(p, size, true, size, NULL, NULL);}+// Protect a region in memory to be not accessible.static bool mi_os_protectx(void* addr, size_t size, bool protect) {// page align conservatively within the range@@ -575,15 +662,14 @@ static uint8_t* mi_os_claim_huge_pages(size_t pages, size_t* total_size) {start = huge_start;if (start == 0) {// Initialize the start address after the 32TiB area- start = ((uintptr_t)32 << 40); // 32TiB virtual start address- #if (MI_SECURE>0 || MI_DEBUG==0) // security: randomize start of huge pages unless in debug mode- uintptr_t r = _mi_heap_random_next(mi_prim_get_default_heap());+ start = ((uintptr_t)8 << 40); // 8TiB virtual start address+ #if (MI_SECURE>0 || MI_DEBUG==0) // security: randomize start of huge pages unless in debug mode+ uintptr_t r = _mi_theap_random_next(_mi_theap_default());start = start + ((uintptr_t)MI_HUGE_OS_PAGE_SIZE * ((r>>17) & 0x0FFF)); // (randomly 12bits)*1GiB == between 0 to 4TiB#endif}end = start + size;- mi_assert_internal(end % MI_SEGMENT_SIZE == 0);- } while (!mi_atomic_cas_strong_acq_rel(&mi_huge_start, &huge_start, end));+ } while (!mi_atomic_cas_weak_acq_rel(&mi_huge_start, &huge_start, end));if (total_size != NULL) *total_size = size;return (uint8_t*)start;@@ -596,13 +682,13 @@ static uint8_t* mi_os_claim_huge_pages(size_t pages, size_t* total_size) {}#endif-// Allocate MI_SEGMENT_SIZE aligned huge pages+// Allocate MI_ARENA_SLICE_ALIGN aligned huge pagesvoid* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_msecs, size_t* pages_reserved, size_t* psize, mi_memid_t* memid) {*memid = _mi_memid_none();if (psize != NULL) *psize = 0;if (pages_reserved != NULL) *pages_reserved = 0;size_t size = 0;- uint8_t* start = mi_os_claim_huge_pages(pages, &size);+ uint8_t* const start = mi_os_claim_huge_pages(pages, &size);if (start == NULL) return NULL; // or 32-bit systems// Allocate one page at the time but try to place them contiguously@@ -628,7 +714,7 @@ void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_mse// no success, issue a warning and breakif (p != NULL) {_mi_warning_message("could not allocate contiguous huge OS page %zu at %p\n", page, addr);- mi_os_prim_free(p, MI_HUGE_OS_PAGE_SIZE, MI_HUGE_OS_PAGE_SIZE);+ mi_os_prim_free(p, MI_HUGE_OS_PAGE_SIZE, MI_HUGE_OS_PAGE_SIZE, NULL);}break;}@@ -658,7 +744,7 @@ void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_mseif (psize != NULL) { *psize = page * MI_HUGE_OS_PAGE_SIZE; }if (page != 0) {mi_assert(start != NULL);- *memid = _mi_memid_create_os(true /* is committed */, all_zero, true /* is_large */);+ *memid = _mi_memid_create_os(start, size, true /* is committed */, all_zero, true /* is_large */);memid->memkind = MI_MEM_OS_HUGE;mi_assert(memid->is_pinned);#ifdef MI_TRACK_ASAN@@ -670,44 +756,103 @@ void* _mi_os_alloc_huge_os_pages(size_t pages, int numa_node, mi_msecs_t max_mse// free every huge page in a range individually (as we allocated per page)// note: needed with VirtualAlloc but could potentially be done in one go on mmap'd systems.-static void mi_os_free_huge_os_pages(void* p, size_t size) {+static void mi_os_free_huge_os_pages(void* p, size_t size, mi_subproc_t* subproc) {if (p==NULL || size==0) return;uint8_t* base = (uint8_t*)p;while (size >= MI_HUGE_OS_PAGE_SIZE) {- mi_os_prim_free(base, MI_HUGE_OS_PAGE_SIZE, MI_HUGE_OS_PAGE_SIZE);+ mi_os_prim_free(base, MI_HUGE_OS_PAGE_SIZE, MI_HUGE_OS_PAGE_SIZE, subproc);size -= MI_HUGE_OS_PAGE_SIZE;base += MI_HUGE_OS_PAGE_SIZE;}}+/* ----------------------------------------------------------------------------Support NUMA aware allocation-----------------------------------------------------------------------------*/-_Atomic(size_t) _mi_numa_node_count; // = 0 // cache the node count+static _Atomic(size_t) mi_numa_node_count; // = 0 // cache the node count-size_t _mi_os_numa_node_count_get(void) {- size_t count = mi_atomic_load_acquire(&_mi_numa_node_count);- if (count <= 0) {+int _mi_os_numa_node_count(void) {+ size_t count = mi_atomic_load_acquire(&mi_numa_node_count);+ if mi_unlikely(count == 0) {long ncount = mi_option_get(mi_option_use_numa_nodes); // given explicitly?- if (ncount > 0) {+ if (ncount > 0 && ncount < INT_MAX) {count = (size_t)ncount;}else {- count = _mi_prim_numa_node_count(); // or detect dynamically- if (count == 0) count = 1;+ const size_t n = _mi_prim_numa_node_count(); // or detect dynamically+ if (n == 0 || n > INT_MAX) { count = 1; }+ else { count = n; }}- mi_atomic_store_release(&_mi_numa_node_count, count); // save it- _mi_verbose_message("using %zd numa regions\n", count);+ mi_atomic_store_release(&mi_numa_node_count, count); // save it+ if (count>1) { _mi_verbose_message("using %zd numa regions\n", count); }}- return count;+ mi_assert_internal(count > 0 && count <= INT_MAX);+ return (int)count;}-int _mi_os_numa_node_get(void) {- size_t numa_count = _mi_os_numa_node_count();+static int mi_os_numa_node_get(void) {+ int numa_count = _mi_os_numa_node_count();if (numa_count<=1) return 0; // optimize on single numa node systems: always node 0// never more than the node count and >= 0- size_t numa_node = _mi_prim_numa_node();+ const size_t n = _mi_prim_numa_node();+ int numa_node = (n < INT_MAX ? (int)n : 0);if (numa_node >= numa_count) { numa_node = numa_node % numa_count; }- return (int)numa_node;+ return numa_node;+}++int _mi_os_numa_node(void) {+ if mi_likely(mi_atomic_load_relaxed(&mi_numa_node_count) == 1) {+ return 0;+ }+ else {+ return mi_os_numa_node_get();+ }}+++/* ----------------------------------------------------------------------------+ Public API+-----------------------------------------------------------------------------*/+#if 0+mi_decl_export void* mi_os_alloc(size_t size, bool commit, size_t* full_size) {+ return mi_os_alloc_aligned(size, mi_os_mem_config.alloc_granularity, commit, NULL, full_size);+}++static void* mi_os_alloc_aligned_ex(size_t size, size_t alignment, bool commit, bool allow_large, bool* is_committed, bool* is_pinned, void** base, size_t* full_size) {+ mi_memid_t memid = _mi_memid_none();+ void* p = _mi_os_alloc_aligned(size, alignment, commit, allow_large, &memid);+ if (p == NULL) return p;+ if (is_committed != NULL) { *is_committed = memid.initially_committed; }+ if (is_pinned != NULL) { *is_pinned = memid.is_pinned; }+ if (base != NULL) { *base = memid.mem.os.base; }+ if (full_size != NULL) { *full_size = memid.mem.os.size; }+ if (!memid.initially_zero && memid.initially_committed) {+ _mi_memzero_aligned(memid.mem.os.base, memid.mem.os.size);+ }+ return p;+}++mi_decl_export void* mi_os_alloc_aligned(size_t size, size_t alignment, bool commit, void** base, size_t* full_size) {+ return mi_os_alloc_aligned_ex(size, alignment, commit, false, NULL, NULL, base, full_size);+}++mi_decl_export void* mi_os_alloc_aligned_allow_large(size_t size, size_t alignment, bool commit, bool* is_committed, bool* is_pinned, void** base, size_t* full_size) {+ return mi_os_alloc_aligned_ex(size, alignment, commit, true, is_committed, is_pinned, base, full_size);+}++mi_decl_export void mi_os_free(void* p, size_t size) {+ if (p==NULL || size == 0) return;+ mi_memid_t memid = _mi_memid_create_os(p, size, true, false, false);+ _mi_os_free(p, size, memid);+}++mi_decl_export void mi_os_commit(void* p, size_t size) {+ _mi_os_commit(p, size, NULL);+}++mi_decl_export void mi_os_decommit(void* p, size_t size) {+ _mi_os_decommit(p, size);+}+#endifdiff --git a/vendored/mimalloc/src/page-map.c b/vendored/mimalloc/src/page-map.cnew file mode 100644index 000000000..d8393e72b--- /dev/null+++ b/vendored/mimalloc/src/page-map.c@@ -0,0 +1,441 @@+/*----------------------------------------------------------------------------+Copyright (c) 2023-2025, 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.+-----------------------------------------------------------------------------*/++#include "mimalloc.h"+#include "mimalloc/internal.h"+#include "bitmap.h"++static void mi_page_map_cannot_commit(void) {+ _mi_warning_message("unable to commit the allocation page-map on-demand\n" );+}++#if MI_PAGE_MAP_FLAT++// The page-map contains a byte for each 64kb slice in the address space.+// For an address `a` where `ofs = _mi_page_map[a >> 16]`:+// 0 = unused+// 1 = the slice at `a & ~0xFFFF` is a mimalloc page.+// 1 < ofs <= 127 = the slice is part of a page, starting at `(((a>>16) - ofs - 1) << 16)`.+//+// 1 byte per slice => 1 TiB address space needs a 2^14 * 2^16 = 16 MiB page map.+// A full 256 TiB address space (48 bit) needs a 4 GiB page map.+// A full 4 GiB address space (32 bit) needs only a 64 KiB page map.++mi_decl_cache_align uint8_t* _mi_page_map = NULL;+static void* mi_page_map_max_address = NULL;+static mi_memid_t mi_page_map_memid;++#define MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT MI_ARENA_SLICE_SIZE+static mi_bitmap_t* mi_page_map_commit; // one bit per committed 64 KiB entries++mi_decl_nodiscard static bool mi_page_map_ensure_committed(size_t idx, size_t slice_count);++bool _mi_page_map_init(void) {+ size_t vbits = (size_t)mi_option_get_clamp(mi_option_max_vabits, 0, MI_SIZE_BITS);+ if (vbits == 0) {+ vbits = _mi_os_virtual_address_bits();+ #if MI_ARCH_X64 // canonical address is limited to the first 128 TiB+ if (vbits >= 48) { vbits = 47; }+ #endif+ }++ // Allocate the page map and commit bits+ mi_page_map_max_address = (void*)(vbits >= MI_SIZE_BITS ? (SIZE_MAX - MI_ARENA_SLICE_SIZE + 1) : (MI_PU(1) << vbits));+ const size_t page_map_size = (MI_ZU(1) << (vbits - MI_ARENA_SLICE_SHIFT));+ const bool commit = (page_map_size <= 1*MI_MiB || mi_option_is_enabled(mi_option_pagemap_commit)); // _mi_os_has_overcommit(); // commit on-access on Linux systems?+ const size_t commit_bits = _mi_divide_up(page_map_size, MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT);+ const size_t bitmap_size = (commit ? 0 : mi_bitmap_size(commit_bits, NULL));+ const size_t reserve_size = bitmap_size + page_map_size;+ uint8_t* const base = (uint8_t*)_mi_os_alloc_aligned(reserve_size, 1, commit, true /* allow large */, &mi_page_map_memid);+ if (base==NULL) {+ _mi_error_message(ENOMEM, "unable to reserve virtual memory for the page map (%zu KiB)\n", page_map_size / MI_KiB);+ return false;+ }+ if (mi_page_map_memid.initially_committed && !mi_page_map_memid.initially_zero) {+ _mi_warning_message("internal: the page map was committed but not zero initialized!\n");+ _mi_memzero_aligned(base, reserve_size);+ }+ if (bitmap_size > 0) {+ mi_page_map_commit = (mi_bitmap_t*)base;+ if (!_mi_os_commit(mi_page_map_commit, bitmap_size, NULL)) {+ mi_page_map_cannot_commit();+ return false;+ }+ mi_bitmap_init(mi_page_map_commit, commit_bits, true);+ }+ _mi_page_map = base + bitmap_size;++ // commit the first part so NULL pointers get resolved without an access violation+ if (!commit) {+ if (!mi_page_map_ensure_committed(0, 1)) {+ mi_page_map_cannot_commit();+ return false;+ }+ }+ _mi_page_map[0] = 1; // so _mi_ptr_page(NULL) == NULL+ mi_assert_internal(_mi_ptr_page(NULL)==NULL);+ return true;+}++void _mi_page_map_unsafe_destroy(mi_subproc_t* subproc) {+ mi_assert_internal(subproc != NULL);+ mi_assert_internal(_mi_page_map != NULL);+ if (_mi_page_map == NULL) return;+ _mi_os_free_ex(mi_page_map_memid.mem.os.base, mi_page_map_memid.mem.os.size, true, mi_page_map_memid, subproc);+ _mi_page_map = NULL;+ mi_page_map_commit = NULL;+ mi_page_map_max_address = NULL;+ mi_page_map_memid = _mi_memid_none();+}+++static bool mi_page_map_ensure_committed(size_t idx, size_t slice_count) {+ // is the page map area that contains the page address committed?+ // we always set the commit bits so we can track what ranges are in-use.+ // we only actually commit if the map wasn't committed fully already.+ if (mi_page_map_commit != NULL) {+ const size_t commit_idx = idx / MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT;+ const size_t commit_idx_hi = (idx + slice_count - 1) / MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT;+ for (size_t i = commit_idx; i <= commit_idx_hi; i++) { // per bit to avoid crossing over bitmap chunks+ if (mi_bitmap_is_clear(mi_page_map_commit, i)) {+ // this may race, in which case we do multiple commits (which is ok)+ bool is_zero;+ uint8_t* const start = _mi_page_map + (i * MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT);+ const size_t size = MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT;+ if (!_mi_os_commit(start, size, &is_zero)) {+ mi_page_map_cannot_commit();+ return false;+ }+ if (!is_zero && !mi_page_map_memid.initially_zero) { _mi_memzero(start, size); }+ mi_bitmap_set(mi_page_map_commit, i);+ }+ }+ }+ #if MI_DEBUG > 0+ _mi_page_map[idx] = 0;+ _mi_page_map[idx+slice_count-1] = 0;+ #endif+ return true;+}+++static size_t mi_page_map_get_idx(mi_page_t* page, uint8_t** page_start, size_t* slice_count) {+ size_t page_size;+ *page_start = mi_page_area(page, &page_size);+ if (page_size > MI_LARGE_PAGE_SIZE) { page_size = MI_LARGE_PAGE_SIZE - MI_ARENA_SLICE_SIZE; } // furthest interior pointer+ *slice_count = mi_slice_count_of_size(page_size) + (((uint8_t*)*page_start - (uint8_t*)page)/MI_ARENA_SLICE_SIZE); // add for large aligned blocks+ return _mi_page_map_index(page);+}++bool _mi_page_map_register(mi_page_t* page) {+ mi_assert_internal(page != NULL);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_page_map != NULL); // should be initialized before multi-thread access!+ if mi_unlikely(_mi_page_map == NULL) {+ if (!_mi_page_map_init()) return false;+ }+ mi_assert(_mi_page_map!=NULL);+ uint8_t* page_start;+ size_t slice_count;+ const size_t idx = mi_page_map_get_idx(page, &page_start, &slice_count);++ if (!mi_page_map_ensure_committed(idx, slice_count)) {+ return false;+ }++ // set the offsets+ for (size_t i = 0; i < slice_count; i++) {+ mi_assert_internal(i < 128);+ _mi_page_map[idx + i] = (uint8_t)(i+1);+ }+ return true;+}++void _mi_page_map_unregister(mi_page_t* page) {+ mi_assert_internal(_mi_page_map != NULL);+ // get index and count+ uint8_t* page_start;+ size_t slice_count;+ const size_t idx = mi_page_map_get_idx(page, &page_start, &slice_count);+ // unset the offsets+ _mi_memzero(_mi_page_map + idx, slice_count);+}++void _mi_page_map_unregister_range(void* start, size_t size) {+ const size_t slice_count = _mi_divide_up(size, MI_ARENA_SLICE_SIZE);+ const uintptr_t index = _mi_page_map_index(start);+ // todo: scan the commit bits and clear only those ranges?+ if (!mi_page_map_ensure_committed(index, slice_count)) { // we commit the range in total;+ return;+ }+ _mi_memzero(&_mi_page_map[index], slice_count);+}+++mi_page_t* _mi_safe_ptr_page(const void* p) {+ if mi_unlikely(p >= mi_page_map_max_address) return NULL;+ const uintptr_t idx = _mi_page_map_index(p);+ if mi_unlikely(mi_page_map_commit != NULL && !mi_bitmap_is_set(mi_page_map_commit, idx/MI_PAGE_MAP_ENTRIES_PER_COMMIT_BIT)) return NULL;+ const uintptr_t ofs = _mi_page_map[idx];+ if mi_unlikely(ofs == 0) return NULL;+ return (mi_page_t*)((((uintptr_t)p >> MI_ARENA_SLICE_SHIFT) - ofs + 1) << MI_ARENA_SLICE_SHIFT);+}++mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_attr_noexcept {+ return (_mi_safe_ptr_page(p) != NULL);+}++#else++// A 2-level page map+#define MI_PAGE_MAP_SUB_SIZE (MI_PAGE_MAP_SUB_COUNT * sizeof(mi_page_t*))+#define MI_PAGE_MAP_ENTRIES_PER_CBIT (MI_PAGE_MAP_COUNT / MI_BFIELD_BITS)++mi_decl_cache_align _Atomic(mi_submap_t)* _mi_page_map;+static size_t mi_page_map_count;+static void* mi_page_map_max_address;+static mi_memid_t mi_page_map_memid;+static mi_lock_t mi_page_map_lock;++// divide the main map in 64 (`MI_BFIELD_BITS`) parts commit those parts on demand+static _Atomic(mi_bfield_t) mi_page_map_commit;++mi_decl_nodiscard static inline bool mi_page_map_is_committed(size_t idx, size_t* pbit_idx) {+ mi_bfield_t commit = mi_atomic_load_relaxed(&mi_page_map_commit);+ const size_t bit_idx = idx/MI_PAGE_MAP_ENTRIES_PER_CBIT;+ mi_assert_internal(bit_idx < MI_BFIELD_BITS);+ if (pbit_idx != NULL) { *pbit_idx = bit_idx; }+ return ((commit & (MI_ZU(1) << bit_idx)) != 0);+}++mi_decl_nodiscard static bool mi_page_map_ensure_committed(size_t idx, mi_submap_t* submap) {+ mi_assert_internal(submap!=NULL && *submap==NULL);+ size_t bit_idx;+ if mi_unlikely(!mi_page_map_is_committed(idx, &bit_idx)) {+ uint8_t* start = (uint8_t*)&_mi_page_map[bit_idx * MI_PAGE_MAP_ENTRIES_PER_CBIT];+ if (!_mi_os_commit(start, MI_PAGE_MAP_ENTRIES_PER_CBIT * sizeof(mi_submap_t), NULL)) {+ mi_page_map_cannot_commit();+ return false;+ }+ mi_atomic_or_acq_rel(&mi_page_map_commit, MI_ZU(1) << bit_idx);+ }+ *submap = mi_atomic_load_ptr_acquire(mi_page_t*, &_mi_page_map[idx]); // acquire _mi_page_map_at(idx);+ return true;+}++// initialize the page map+bool _mi_page_map_init(void) {+ size_t vbits = (size_t)mi_option_get_clamp(mi_option_max_vabits, 0, MI_SIZE_BITS);+ if (vbits == 0) {+ vbits = _mi_os_virtual_address_bits();+ #if MI_ARCH_X64 // canonical address is limited to the first 128 TiB+ if (vbits >= 48) { vbits = 47; }+ #endif+ }++ // Allocate the page map and commit bits+ mi_assert(MI_MAX_VABITS >= vbits);+ mi_page_map_max_address = (void*)(vbits >= MI_SIZE_BITS ? (SIZE_MAX - MI_ARENA_SLICE_SIZE + 1) : (MI_PU(1) << vbits));+ mi_page_map_count = (MI_ZU(1) << (vbits - MI_PAGE_MAP_SUB_SHIFT - MI_ARENA_SLICE_SHIFT));+ mi_assert(mi_page_map_count <= MI_PAGE_MAP_COUNT);+ const size_t os_page_size = _mi_os_page_size();+ const size_t page_map_size = _mi_align_up( mi_page_map_count * sizeof(mi_page_t**), os_page_size);+ const size_t submap_size = MI_PAGE_MAP_SUB_SIZE;+ const size_t reserve_size = page_map_size + submap_size;+ #if MI_SECURE+ const bool commit = true; // the whole page map is valid and we can reliably check any pointer+ #else+ const bool commit = page_map_size <= 64*MI_KiB ||+ mi_option_is_enabled(mi_option_pagemap_commit) || _mi_os_has_overcommit();+ #endif+ _mi_page_map = (_Atomic(mi_page_t**)*)_mi_os_alloc_aligned(reserve_size, 1, commit, true /* allow large */, &mi_page_map_memid);+ if (_mi_page_map==NULL) {+ _mi_error_message(ENOMEM, "unable to reserve virtual memory for the page map (%zu KiB)\n", page_map_size / MI_KiB);+ return false;+ }+ if (mi_page_map_memid.initially_committed && !mi_page_map_memid.initially_zero) {+ _mi_warning_message("internal: the page map was committed but not zero initialized!\n");+ _mi_memzero_aligned(_mi_page_map, page_map_size);+ }+ mi_atomic_store_release(&mi_page_map_commit, (mi_page_map_memid.initially_committed ? ~MI_ZU(0) : MI_ZU(0)));++ // ensure there is a submap for the NULL address+ mi_page_t** const sub0 = (mi_page_t**)((uint8_t*)_mi_page_map + page_map_size); // we reserved a submap part at the end already+ if (!mi_page_map_memid.initially_committed) {+ if (!_mi_os_commit(sub0, submap_size, NULL)) { // commit full submap (issue #1087)+ mi_page_map_cannot_commit();+ return false;+ }+ }+ if (!mi_page_map_memid.initially_zero) { // initialize low addresses with NULL+ _mi_memzero_aligned(sub0, submap_size);+ }+ mi_submap_t nullsub = NULL;+ if (!mi_page_map_ensure_committed(0,&nullsub)) {+ mi_page_map_cannot_commit();+ return false;+ }+ mi_atomic_store_ptr_release(mi_page_t*, &_mi_page_map[0], sub0);+ mi_lock_init(&mi_page_map_lock); // initialize late in case the lock init causes allocation++ mi_assert_internal(_mi_ptr_page(NULL)==NULL);+ return true;+}+++void _mi_page_map_unsafe_destroy(mi_subproc_t* subproc) {+ mi_assert_internal(subproc != NULL);+ mi_assert_internal(_mi_page_map != NULL);+ if (_mi_page_map == NULL) return;+ mi_lock_done(&mi_page_map_lock);+ for (size_t idx = 1; idx < mi_page_map_count; idx++) { // skip entry 0 (as we allocate that submap at the end of the page_map)+ // free all sub-maps+ if (mi_page_map_is_committed(idx, NULL)) {+ mi_submap_t sub = _mi_page_map_at(idx);+ if (sub != NULL) {+ mi_memid_t memid = _mi_memid_create_os(sub, MI_PAGE_MAP_SUB_SIZE, true, false, false);+ _mi_os_free_ex(memid.mem.os.base, memid.mem.os.size, true, memid, subproc);+ mi_atomic_store_ptr_release(mi_page_t*, &_mi_page_map[idx], NULL);+ }+ }+ }+ _mi_os_free_ex(_mi_page_map, mi_page_map_memid.mem.os.size, true, mi_page_map_memid, subproc);+ _mi_page_map = NULL;+ mi_page_map_count = 0;+ mi_page_map_memid = _mi_memid_none();+ mi_page_map_max_address = NULL;+ mi_atomic_store_release(&mi_page_map_commit, 0);+}+++mi_decl_nodiscard static bool mi_page_map_ensure_submap_at(size_t idx, mi_submap_t* submap) {+ mi_assert_internal(submap!=NULL && *submap==NULL);+ mi_submap_t sub = NULL;+ if (!mi_page_map_ensure_committed(idx, &sub)) {+ return false;+ }+ if mi_unlikely(sub == NULL) {+ // sub map not yet allocated, alloc now+ mi_lock(&mi_page_map_lock)+ {+ sub = mi_atomic_load_ptr_acquire(mi_page_t*, &_mi_page_map[idx]); // reload+ if (sub==NULL) // not yet allocated by another thread?+ {+ mi_memid_t memid;+ const size_t submap_size = MI_PAGE_MAP_SUB_SIZE;+ sub = (mi_submap_t)_mi_os_zalloc(submap_size, &memid);+ if (sub==NULL) {+ _mi_warning_message("internal error: unable to extend the page map\n");+ }+ else {+ mi_submap_t expect = NULL;+ if (!mi_atomic_cas_ptr_strong_acq_rel(mi_page_t*, &_mi_page_map[idx], &expect, sub)) {+ // another thread already allocated it.. free and continue+ _mi_os_free(sub, submap_size, memid);+ sub = expect;+ }+ }+ }+ }+ if (sub==NULL) return false; // unable to allocate the submap..+ }+ mi_assert_internal(sub!=NULL);+ *submap = sub;+ return true;+}++static bool mi_page_map_set_range_prim(mi_page_t* page, size_t idx, size_t sub_idx, size_t slice_count) {+ // is the page map area that contains the page address committed?+ while (slice_count > 0) {+ mi_submap_t sub = NULL;+ if (!mi_page_map_ensure_submap_at(idx, &sub)) {+ return false;+ };+ mi_assert_internal(sub!=NULL);+ // set the offsets for the page+ while (slice_count > 0 && sub_idx < MI_PAGE_MAP_SUB_COUNT) {+ sub[sub_idx] = page;+ slice_count--;+ sub_idx++;+ }+ idx++; // potentially wrap around to the next idx+ sub_idx = 0;+ }+ return true;+}++static bool mi_page_map_set_range(mi_page_t* page, size_t idx, size_t sub_idx, size_t slice_count) {+ if mi_unlikely(!mi_page_map_set_range_prim(page,idx,sub_idx,slice_count)) {+ // failed to commit, call again to reset the page pointer if needed+ if (page!=NULL) {+ mi_page_map_set_range_prim(NULL,idx,sub_idx,slice_count);+ }+ return false;+ }+ return true;+}++static size_t mi_page_map_get_idx(mi_page_t* page, size_t* sub_idx, size_t* slice_count) {+ size_t page_size;+ uint8_t* page_start = mi_page_area(page, &page_size);+ if (page_size > MI_LARGE_PAGE_SIZE) { page_size = MI_LARGE_PAGE_SIZE - MI_ARENA_SLICE_SIZE; } // furthest interior pointer+ *slice_count = mi_slice_count_of_size(page_size) + ((page_start - (uint8_t*)page)/MI_ARENA_SLICE_SIZE); // add for large aligned blocks+ return _mi_page_map_index(page, sub_idx);+}++bool _mi_page_map_register(mi_page_t* page) {+ mi_assert_internal(page != NULL);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_page_map != NULL); // should be initialized before multi-thread access!+ if mi_unlikely(_mi_page_map == NULL) {+ if (!_mi_page_map_init()) return false;+ }+ mi_assert(_mi_page_map!=NULL);+ size_t slice_count;+ size_t sub_idx;+ const size_t idx = mi_page_map_get_idx(page, &sub_idx, &slice_count);+ return mi_page_map_set_range(page, idx, sub_idx, slice_count);+}++void _mi_page_map_unregister(mi_page_t* page) {+ mi_assert_internal(_mi_page_map != NULL);+ mi_assert_internal(page != NULL);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ if mi_unlikely(_mi_page_map == NULL) return;+ // get index and count+ size_t slice_count;+ size_t sub_idx;+ const size_t idx = mi_page_map_get_idx(page, &sub_idx, &slice_count);+ // unset the offsets+ mi_page_map_set_range(NULL, idx, sub_idx, slice_count);+}++void _mi_page_map_unregister_range(void* start, size_t size) {+ if mi_unlikely(_mi_page_map == NULL) return;+ const size_t slice_count = _mi_divide_up(size, MI_ARENA_SLICE_SIZE);+ size_t sub_idx;+ const uintptr_t idx = _mi_page_map_index(start, &sub_idx);+ mi_page_map_set_range(NULL, idx, sub_idx, slice_count); // todo: avoid committing if not already committed?+}++// Return NULL for invalid pointers+mi_page_t* _mi_safe_ptr_page(const void* p) {+ if (p==NULL) return NULL;+ if mi_unlikely(p >= mi_page_map_max_address) return NULL;+ size_t sub_idx;+ const size_t idx = _mi_page_map_index(p,&sub_idx);+ if mi_unlikely(!mi_page_map_is_committed(idx,NULL)) return NULL;+ mi_page_t** const sub = _mi_page_map[idx];+ if mi_unlikely(sub==NULL) return NULL;+ return sub[sub_idx];+}++mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_attr_noexcept {+ return (_mi_safe_ptr_page(p) != NULL);+}++#endifdiff --git a/vendored/mimalloc/src/page-queue.c b/vendored/mimalloc/src/page-queue.cindex 83b60e931..4c54cb9a2 100644--- a/vendored/mimalloc/src/page-queue.c+++ b/vendored/mimalloc/src/page-queue.c@@ -38,15 +38,19 @@ terms of the MIT license. A copy of the license can be found in the filestatic inline bool mi_page_queue_is_huge(const mi_page_queue_t* pq) {- return (pq->block_size == (MI_MEDIUM_OBJ_SIZE_MAX+sizeof(uintptr_t)));+ return (pq->block_size == (MI_LARGE_MAX_OBJ_SIZE+sizeof(uintptr_t)));}static inline bool mi_page_queue_is_full(const mi_page_queue_t* pq) {- return (pq->block_size == (MI_MEDIUM_OBJ_SIZE_MAX+(2*sizeof(uintptr_t))));+ return (pq->block_size == (MI_LARGE_MAX_OBJ_SIZE+(2*sizeof(uintptr_t))));}static inline bool mi_page_queue_is_special(const mi_page_queue_t* pq) {- return (pq->block_size > MI_MEDIUM_OBJ_SIZE_MAX);+ return (pq->block_size > MI_LARGE_MAX_OBJ_SIZE);+}++static inline size_t mi_page_queue_count(const mi_page_queue_t* pq) {+ return pq->count;}/* -----------------------------------------------------------@@ -57,27 +61,23 @@ static inline bool mi_page_queue_is_special(const mi_page_queue_t* pq) {// Returns MI_BIN_HUGE if the size is too large.// We use `wsize` for the size in "machine word sizes",// i.e. byte size == `wsize*sizeof(void*)`.-static inline uint8_t mi_bin(size_t size) {+static mi_decl_noinline size_t mi_bin(size_t size) {size_t wsize = _mi_wsize_from_size(size);- uint8_t bin;- if (wsize <= 1) {- bin = 1;- }- #if defined(MI_ALIGN4W)- else if (wsize <= 4) {- bin = (uint8_t)((wsize+1)&~1); // round to double word sizes+#if defined(MI_ALIGN4W)+ if mi_likely(wsize <= 4) {+ return (wsize <= 1 ? 1 : (wsize+1)&~1); // round to double word sizes}- #elif defined(MI_ALIGN2W)- else if (wsize <= 8) {- bin = (uint8_t)((wsize+1)&~1); // round to double word sizes+#elif defined(MI_ALIGN2W)+ if mi_likely(wsize <= 8) {+ return (wsize <= 1 ? 1 : (wsize+1)&~1); // round to double word sizes}- #else- else if (wsize <= 8) {- bin = (uint8_t)wsize;+#else+ if mi_likely(wsize <= 8) {+ return (wsize == 0 ? 1 : wsize);}- #endif- else if (wsize > MI_MEDIUM_OBJ_WSIZE_MAX) {- bin = MI_BIN_HUGE;+#endif+ else if mi_unlikely(wsize > MI_LARGE_MAX_OBJ_WSIZE) {+ return MI_BIN_HUGE;}else {#if defined(MI_ALIGN4W)@@ -85,15 +85,14 @@ static inline uint8_t mi_bin(size_t size) {#endifwsize--;// find the highest bit- uint8_t b = (uint8_t)mi_bsr(wsize); // note: wsize != 0+ const size_t b = (MI_SIZE_BITS - 1 - mi_clz(wsize)); // note: wsize != 0// and use the top 3 bits to determine the bin (~12.5% worst internal fragmentation).// - adjust with 3 because we use do not round the first 8 sizes// which each get an exact bin- bin = ((b << 2) + (uint8_t)((wsize >> (b - 2)) & 0x03)) - 3;- mi_assert_internal(bin < MI_BIN_HUGE);+ const size_t bin = ((b << 2) + ((wsize >> (b - 2)) & 0x03)) - 3;+ mi_assert_internal(bin > 0 && bin < MI_BIN_HUGE);+ return bin;}- mi_assert_internal(bin > 0 && bin <= MI_BIN_HUGE);- return bin;}@@ -102,17 +101,18 @@ static inline uint8_t mi_bin(size_t size) {Queue of pages with free blocks----------------------------------------------------------- */-uint8_t _mi_bin(size_t size) {+size_t _mi_bin(size_t size) {return mi_bin(size);}-size_t _mi_bin_size(uint8_t bin) {- return _mi_heap_empty.pages[bin].block_size;+size_t _mi_bin_size(size_t bin) {+ mi_assert_internal(bin <= MI_BIN_HUGE);+ return _mi_theap_empty.pages[bin].block_size;}// Good size for allocation-size_t mi_good_size(size_t size) mi_attr_noexcept {- if (size <= MI_MEDIUM_OBJ_SIZE_MAX) {+mi_decl_nodiscard mi_decl_export size_t mi_good_size(size_t size) mi_attr_noexcept {+ if (size <= MI_LARGE_MAX_OBJ_SIZE) {return _mi_bin_size(mi_bin(size + MI_PADDING_SIZE));}else {@@ -136,29 +136,64 @@ static bool mi_page_queue_contains(mi_page_queue_t* queue, const mi_page_t* page#endif#if (MI_DEBUG>1)-static bool mi_heap_contains_queue(const mi_heap_t* heap, const mi_page_queue_t* pq) {- return (pq >= &heap->pages[0] && pq <= &heap->pages[MI_BIN_FULL]);+static bool mi_theap_contains_queue(const mi_theap_t* theap, const mi_page_queue_t* pq) {+ return (pq >= &theap->pages[0] && pq <= &theap->pages[MI_BIN_FULL]);}#endif-static inline bool mi_page_is_large_or_huge(const mi_page_t* page) {- return (mi_page_block_size(page) > MI_MEDIUM_OBJ_SIZE_MAX || mi_page_is_huge(page));+bool _mi_page_queue_is_valid(mi_theap_t* theap, const mi_page_queue_t* pq) {+ MI_UNUSED_RELEASE(theap);+ if (pq==NULL) return false;+ size_t count = 0; MI_UNUSED_RELEASE(count);+ mi_page_t* prev = NULL; MI_UNUSED_RELEASE(prev);+ for (mi_page_t* page = pq->first; page != NULL; page = page->next) {+ mi_assert_internal(page->prev == prev);+ if (mi_page_is_in_full(page)) {+ mi_assert_internal(_mi_wsize_from_size(pq->block_size) == MI_LARGE_MAX_OBJ_WSIZE + 2);+ }+ else if (mi_page_is_huge(page)) {+ mi_assert_internal(_mi_wsize_from_size(pq->block_size) == MI_LARGE_MAX_OBJ_WSIZE + 1);+ }+ else {+ mi_assert_internal(mi_page_block_size(page) == pq->block_size);+ }+ mi_assert_internal(page->theap == theap);+ if (page->next == NULL) {+ mi_assert_internal(pq->last == page);+ }+ count++;+ prev = page;+ }+ mi_assert_internal(pq->count == count);+ return true;}-static mi_page_queue_t* mi_heap_page_queue_of(mi_heap_t* heap, const mi_page_t* page) {- mi_assert_internal(heap!=NULL);- uint8_t bin = (mi_page_is_in_full(page) ? MI_BIN_FULL : (mi_page_is_huge(page) ? MI_BIN_HUGE : mi_bin(mi_page_block_size(page))));+static size_t mi_page_bin(const mi_page_t* page) {+ const size_t bin = (mi_page_is_in_full(page) ? MI_BIN_FULL : (mi_page_is_huge(page) ? MI_BIN_HUGE : mi_bin(mi_page_block_size(page))));mi_assert_internal(bin <= MI_BIN_FULL);- mi_page_queue_t* pq = &heap->pages[bin];+ return bin;+}++// returns the page bin without using MI_BIN_FULL for statistics+size_t _mi_page_stats_bin(const mi_page_t* page) {+ const size_t bin = (mi_page_is_huge(page) ? MI_BIN_HUGE : mi_bin(mi_page_block_size(page)));+ mi_assert_internal(bin <= MI_BIN_HUGE);+ return bin;+}++static mi_page_queue_t* mi_theap_page_queue_of(mi_theap_t* theap, const mi_page_t* page) {+ mi_assert_internal(theap!=NULL);+ const size_t bin = mi_page_bin(page);+ mi_page_queue_t* pq = &theap->pages[bin];mi_assert_internal((mi_page_block_size(page) == pq->block_size) ||- (mi_page_is_large_or_huge(page) && mi_page_queue_is_huge(pq)) ||+ (mi_page_is_huge(page) && mi_page_queue_is_huge(pq)) ||(mi_page_is_in_full(page) && mi_page_queue_is_full(pq)));return pq;}static mi_page_queue_t* mi_page_queue_of(const mi_page_t* page) {- mi_heap_t* heap = mi_page_heap(page);- mi_page_queue_t* pq = mi_heap_page_queue_of(heap, page);+ mi_theap_t* theap = mi_page_theap(page);+ mi_page_queue_t* pq = mi_theap_page_queue_of(theap, page);mi_assert_expensive(mi_page_queue_contains(pq, page));return pq;}@@ -168,8 +203,8 @@ static mi_page_queue_t* mi_page_queue_of(const mi_page_t* page) {// size without having to compute the bin. This means when the// current free page queue is updated for a small bin, we need to update a// range of entries in `_mi_page_small_free`.-static inline void mi_heap_queue_first_update(mi_heap_t* heap, const mi_page_queue_t* pq) {- mi_assert_internal(mi_heap_contains_queue(heap,pq));+static inline void mi_theap_queue_first_update(mi_theap_t* theap, const mi_page_queue_t* pq) {+ mi_assert_internal(mi_theap_contains_queue(theap,pq));size_t size = pq->block_size;if (size > MI_SMALL_SIZE_MAX) return;@@ -179,7 +214,7 @@ static inline void mi_heap_queue_first_update(mi_heap_t* heap, const mi_page_que// find index in the right direct page arraysize_t start;size_t idx = _mi_wsize_from_size(size);- mi_page_t** pages_free = heap->pages_free_direct;+ mi_page_t** pages_free = theap->pages_free_direct;if (pages_free[idx] == page) return; // already set@@ -189,9 +224,9 @@ static inline void mi_heap_queue_first_update(mi_heap_t* heap, const mi_page_que}else {// find previous size; due to minimal alignment upto 3 previous bins may need to be skipped- uint8_t bin = mi_bin(size);+ size_t bin = mi_bin(size);const mi_page_queue_t* prev = pq - 1;- while( bin == mi_bin(prev->block_size) && prev > &heap->pages[0]) {+ while( bin == mi_bin(prev->block_size) && prev > &theap->pages[0]) {prev--;}start = 1 + _mi_wsize_from_size(prev->block_size);@@ -214,40 +249,40 @@ static bool mi_page_queue_is_empty(mi_page_queue_t* queue) {static void mi_page_queue_remove(mi_page_queue_t* queue, mi_page_t* page) {mi_assert_internal(page != NULL);mi_assert_expensive(mi_page_queue_contains(queue, page));+ mi_assert_internal(queue->count >= 1);mi_assert_internal(mi_page_block_size(page) == queue->block_size ||- (mi_page_is_large_or_huge(page) && mi_page_queue_is_huge(queue)) ||+ (mi_page_is_huge(page) && mi_page_queue_is_huge(queue)) ||(mi_page_is_in_full(page) && mi_page_queue_is_full(queue)));- mi_heap_t* heap = mi_page_heap(page);-+ mi_theap_t* theap = mi_page_theap(page);if (page->prev != NULL) page->prev->next = page->next;if (page->next != NULL) page->next->prev = page->prev;if (page == queue->last) queue->last = page->prev;if (page == queue->first) {queue->first = page->next;// update first- mi_assert_internal(mi_heap_contains_queue(heap, queue));- mi_heap_queue_first_update(heap,queue);+ mi_assert_internal(mi_theap_contains_queue(theap, queue));+ mi_theap_queue_first_update(theap,queue);}- heap->page_count--;+ theap->page_count--;+ queue->count--;page->next = NULL;page->prev = NULL;- // mi_atomic_store_ptr_release(mi_atomic_cast(void*, &page->heap), NULL);mi_page_set_in_full(page,false);}-static void mi_page_queue_push(mi_heap_t* heap, mi_page_queue_t* queue, mi_page_t* page) {- mi_assert_internal(mi_page_heap(page) == heap);+static void mi_page_queue_push(mi_theap_t* theap, mi_page_queue_t* queue, mi_page_t* page) {+ mi_assert_internal(mi_page_theap(page) == theap);mi_assert_internal(!mi_page_queue_contains(queue, page));#if MI_HUGE_PAGE_ABANDON- mi_assert_internal(_mi_page_segment(page)->kind != MI_SEGMENT_HUGE);+ mi_assert_internal(_mi_page_segment(page)->page_kind != MI_PAGE_HUGE);#endifmi_assert_internal(mi_page_block_size(page) == queue->block_size ||- (mi_page_is_large_or_huge(page) && mi_page_queue_is_huge(queue)) ||+ (mi_page_is_huge(page) && mi_page_queue_is_huge(queue)) ||(mi_page_is_in_full(page) && mi_page_queue_is_full(queue)));mi_page_set_in_full(page, mi_page_queue_is_full(queue));- // mi_atomic_store_ptr_release(mi_atomic_cast(void*, &page->heap), heap);+page->next = queue->first;page->prev = NULL;if (queue->first != NULL) {@@ -258,23 +293,54 @@ static void mi_page_queue_push(mi_heap_t* heap, mi_page_queue_t* queue, mi_page_else {queue->first = queue->last = page;}+ queue->count++;// update direct- mi_heap_queue_first_update(heap, queue);- heap->page_count++;+ mi_theap_queue_first_update(theap, queue);+ theap->page_count++;}-static void mi_page_queue_move_to_front(mi_heap_t* heap, mi_page_queue_t* queue, mi_page_t* page) {- mi_assert_internal(mi_page_heap(page) == heap);+static void mi_page_queue_push_at_end(mi_theap_t* theap, mi_page_queue_t* queue, mi_page_t* page) {+ mi_assert_internal(mi_page_theap(page) == theap);+ mi_assert_internal(!mi_page_queue_contains(queue, page));++ mi_assert_internal(mi_page_block_size(page) == queue->block_size ||+ (mi_page_is_huge(page) && mi_page_queue_is_huge(queue)) ||+ (mi_page_is_in_full(page) && mi_page_queue_is_full(queue)));++ mi_page_set_in_full(page, mi_page_queue_is_full(queue));++ page->prev = queue->last;+ page->next = NULL;+ if (queue->last != NULL) {+ mi_assert_internal(queue->last->next == NULL);+ queue->last->next = page;+ queue->last = page;+ }+ else {+ queue->first = queue->last = page;+ }+ queue->count++;++ // update direct+ if (queue->first == page) {+ mi_theap_queue_first_update(theap, queue);+ }+ theap->page_count++;+}++static void mi_page_queue_move_to_front(mi_theap_t* theap, mi_page_queue_t* queue, mi_page_t* page) {+ mi_assert_internal(mi_page_theap(page) == theap);mi_assert_internal(mi_page_queue_contains(queue, page));if (queue->first == page) return;mi_page_queue_remove(queue, page);- mi_page_queue_push(heap, queue, page);+ mi_page_queue_push(theap, queue, page);mi_assert_internal(queue->first == page);}static void mi_page_queue_enqueue_from_ex(mi_page_queue_t* to, mi_page_queue_t* from, bool enqueue_at_end, mi_page_t* page) {mi_assert_internal(page != NULL);+ mi_assert_internal(from->count >= 1);mi_assert_expensive(mi_page_queue_contains(from, page));mi_assert_expensive(!mi_page_queue_contains(to, page));const size_t bsize = mi_page_block_size(page);@@ -282,10 +348,10 @@ static void mi_page_queue_enqueue_from_ex(mi_page_queue_t* to, mi_page_queue_t*mi_assert_internal((bsize == to->block_size && bsize == from->block_size) ||(bsize == to->block_size && mi_page_queue_is_full(from)) ||(bsize == from->block_size && mi_page_queue_is_full(to)) ||- (mi_page_is_large_or_huge(page) && mi_page_queue_is_huge(to)) ||- (mi_page_is_large_or_huge(page) && mi_page_queue_is_full(to)));+ (mi_page_is_huge(page) && mi_page_queue_is_huge(to)) ||+ (mi_page_is_huge(page) && mi_page_queue_is_full(to)));- mi_heap_t* heap = mi_page_heap(page);+ mi_theap_t* theap = mi_page_theap(page);// delete from `from`if (page->prev != NULL) page->prev->next = page->next;@@ -294,36 +360,38 @@ static void mi_page_queue_enqueue_from_ex(mi_page_queue_t* to, mi_page_queue_t*if (page == from->first) {from->first = page->next;// update first- mi_assert_internal(mi_heap_contains_queue(heap, from));- mi_heap_queue_first_update(heap, from);+ mi_assert_internal(mi_theap_contains_queue(theap, from));+ mi_theap_queue_first_update(theap, from);}+ from->count--;// insert into `to`+ to->count++;if (enqueue_at_end) {// enqueue at the endpage->prev = to->last;page->next = NULL;if (to->last != NULL) {- mi_assert_internal(heap == mi_page_heap(to->last));+ mi_assert_internal(theap == mi_page_theap(to->last));to->last->next = page;to->last = page;}else {to->first = page;to->last = page;- mi_heap_queue_first_update(heap, to);+ mi_theap_queue_first_update(theap, to);}}else {if (to->first != NULL) {// enqueue at 2nd place- mi_assert_internal(heap == mi_page_heap(to->first));+ mi_assert_internal(theap == mi_page_theap(to->first));mi_page_t* next = to->first->next;page->prev = to->first;page->next = next;to->first->next = page;- if (next != NULL) {- next->prev = page;+ if (next != NULL) {+ next->prev = page;}else {to->last = page;@@ -335,7 +403,7 @@ static void mi_page_queue_enqueue_from_ex(mi_page_queue_t* to, mi_page_queue_t*page->next = NULL;to->first = page;to->last = page;- mi_heap_queue_first_update(heap, to);+ mi_theap_queue_first_update(theap, to);}}@@ -351,32 +419,27 @@ static void mi_page_queue_enqueue_from_full(mi_page_queue_t* to, mi_page_queue_tmi_page_queue_enqueue_from_ex(to, from, true /* enqueue at the end of the `to` queue? */, page);}-// Only called from `mi_heap_absorb`.-size_t _mi_page_queue_append(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_queue_t* append) {- mi_assert_internal(mi_heap_contains_queue(heap,pq));+// Only called from `mi_theap_absorb`.+size_t _mi_page_queue_append(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_queue_t* append) {+ mi_assert_internal(mi_theap_contains_queue(theap,pq));mi_assert_internal(pq->block_size == append->block_size);if (append->first==NULL) return 0;- // set append pages to new heap and count+ // set append pages to new theap and countsize_t count = 0;for (mi_page_t* page = append->first; page != NULL; page = page->next) {- // inline `mi_page_set_heap` to avoid wrong assertion during absorption;- // in this case it is ok to be delayed freeing since both "to" and "from" heap are still alive.- mi_atomic_store_release(&page->xheap, (uintptr_t)heap);- // set the flag to delayed free (not overriding NEVER_DELAYED_FREE) which has as a- // side effect that it spins until any DELAYED_FREEING is finished. This ensures- // that after appending only the new heap will be used for delayed free operations.- _mi_page_use_delayed_free(page, MI_USE_DELAYED_FREE, false);+ mi_page_set_theap(page, theap);count++;}+ mi_assert_internal(count == append->count);if (pq->last==NULL) {// take over afreshmi_assert_internal(pq->first==NULL);pq->first = append->first;pq->last = append->last;- mi_heap_queue_first_update(heap, pq);+ mi_theap_queue_first_update(theap, pq);}else {// append to end@@ -386,5 +449,7 @@ size_t _mi_page_queue_append(mi_heap_t* heap, mi_page_queue_t* pq, mi_page_queueappend->first->prev = pq->last;pq->last = append->last;}+ pq->count += append->count;+return count;}diff --git a/vendored/mimalloc/src/page.c b/vendored/mimalloc/src/page.cindex 6a559af03..8f9fbab28 100644--- a/vendored/mimalloc/src/page.c+++ b/vendored/mimalloc/src/page.c@@ -14,6 +14,7 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc.h"#include "mimalloc/internal.h"#include "mimalloc/atomic.h"+#include "mimalloc/prim.h"/* -----------------------------------------------------------Definition of page queues for each block size@@ -36,14 +37,14 @@ static inline mi_block_t* mi_page_block_at(const mi_page_t* page, void* page_stareturn (mi_block_t*)((uint8_t*)page_start + (i * block_size));}-static void mi_page_init(mi_heap_t* heap, mi_page_t* page, size_t size, mi_tld_t* tld);-static void mi_page_extend_free(mi_heap_t* heap, mi_page_t* page, mi_tld_t* tld);+static bool mi_page_extend_free(mi_theap_t* theap, mi_page_t* page);#if (MI_DEBUG>=3)static size_t mi_page_list_count(mi_page_t* page, mi_block_t* head) {+ mi_assert_internal(_mi_ptr_page(page) == page);size_t count = 0;while (head != NULL) {- mi_assert_internal(page == _mi_ptr_page(head));+ mi_assert_internal((uint8_t*)head - (uint8_t*)page > (ptrdiff_t)MI_LARGE_PAGE_SIZE || page == _mi_ptr_page(head));count++;head = mi_block_next(page, head);}@@ -59,7 +60,7 @@ static inline uint8_t* mi_page_area(const mi_page_t* page) {static bool mi_page_list_is_valid(mi_page_t* page, mi_block_t* p) {size_t psize;- uint8_t* page_area = _mi_segment_page_start(_mi_page_segment(page), page, &psize);+ uint8_t* page_area = mi_page_area(page, &psize);mi_block_t* start = (mi_block_t*)page_area;mi_block_t* end = (mi_block_t*)(page_area + psize);while(p != NULL) {@@ -82,9 +83,8 @@ static bool mi_page_is_valid_init(mi_page_t* page) {mi_assert_internal(page->used <= page->capacity);mi_assert_internal(page->capacity <= page->reserved);- uint8_t* start = mi_page_start(page);- mi_assert_internal(start == _mi_segment_page_start(_mi_page_segment(page), page, NULL));- mi_assert_internal(page->is_huge == (_mi_page_segment(page)->kind == MI_SEGMENT_HUGE));+ // const size_t bsize = mi_page_block_size(page);+ // uint8_t* start = mi_page_start(page);//mi_assert_internal(start + page->capacity*page->block_size == page->top);mi_assert_internal(mi_page_list_is_valid(page,page->free));@@ -112,94 +112,45 @@ static bool mi_page_is_valid_init(mi_page_t* page) {return true;}-extern bool _mi_process_is_initialized; // has mi_process_init been called?+extern mi_decl_hidden bool _mi_process_is_initialized; // has mi_process_init been called?bool _mi_page_is_valid(mi_page_t* page) {mi_assert_internal(mi_page_is_valid_init(page));#if MI_SECUREmi_assert_internal(page->keys[0] != 0);#endif- if (mi_page_heap(page)!=NULL) {- mi_segment_t* segment = _mi_page_segment(page);-- mi_assert_internal(!_mi_process_is_initialized || segment->thread_id==0 || segment->thread_id == mi_page_heap(page)->thread_id);- #if MI_HUGE_PAGE_ABANDON- if (segment->kind != MI_SEGMENT_HUGE)- #endif+ if (!mi_page_is_abandoned(page)) {+ //mi_assert_internal(!_mi_process_is_initialized);{mi_page_queue_t* pq = mi_page_queue_of(page);mi_assert_internal(mi_page_queue_contains(pq, page));- mi_assert_internal(pq->block_size==mi_page_block_size(page) || mi_page_block_size(page) > MI_MEDIUM_OBJ_SIZE_MAX || mi_page_is_in_full(page));- mi_assert_internal(mi_heap_contains_queue(mi_page_heap(page),pq));+ mi_assert_internal(pq->block_size==mi_page_block_size(page) || mi_page_is_huge(page) || mi_page_is_in_full(page));+ // mi_assert_internal(mi_theap_contains_queue(mi_page_theap(page),pq));}}return true;}#endif-void _mi_page_use_delayed_free(mi_page_t* page, mi_delayed_t delay, bool override_never) {- while (!_mi_page_try_use_delayed_free(page, delay, override_never)) {- mi_atomic_yield();- }-}--bool _mi_page_try_use_delayed_free(mi_page_t* page, mi_delayed_t delay, bool override_never) {- mi_thread_free_t tfreex;- mi_delayed_t old_delay;- mi_thread_free_t tfree;- size_t yield_count = 0;- do {- tfree = mi_atomic_load_acquire(&page->xthread_free); // note: must acquire as we can break/repeat this loop and not do a CAS;- tfreex = mi_tf_set_delayed(tfree, delay);- old_delay = mi_tf_delayed(tfree);- if mi_unlikely(old_delay == MI_DELAYED_FREEING) {- if (yield_count >= 4) return false; // give up after 4 tries- yield_count++;- mi_atomic_yield(); // delay until outstanding MI_DELAYED_FREEING are done.- // tfree = mi_tf_set_delayed(tfree, MI_NO_DELAYED_FREE); // will cause CAS to busy fail- }- else if (delay == old_delay) {- break; // avoid atomic operation if already equal- }- else if (!override_never && old_delay == MI_NEVER_DELAYED_FREE) {- break; // leave never-delayed flag set- }- } while ((old_delay == MI_DELAYED_FREEING) ||- !mi_atomic_cas_weak_release(&page->xthread_free, &tfree, tfreex));-- return true; // success-}/* -----------------------------------------------------------Page collect the `local_free` and `thread_free` lists----------------------------------------------------------- */-// Collect the local `thread_free` list using an atomic exchange.-// Note: The exchange must be done atomically as this is used right after-// moving to the full list in `mi_page_collect_ex` and we need to-// ensure that there was no race where the page became unfull just before the move.-static void _mi_page_thread_free_collect(mi_page_t* page)+static void mi_page_thread_collect_to_local(mi_page_t* page, mi_block_t* head){- mi_block_t* head;- mi_thread_free_t tfreex;- mi_thread_free_t tfree = mi_atomic_load_relaxed(&page->xthread_free);- do {- head = mi_tf_block(tfree);- tfreex = mi_tf_set_block(tfree,NULL);- } while (!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tfree, tfreex));-- // return if the list is emptyif (head == NULL) return;- // find the tail -- also to get a proper count (without data races)+ // find the last block in the list -- also to get a proper use count (without data races)size_t max_count = page->capacity; // cannot collect more than capacitysize_t count = 1;- mi_block_t* tail = head;+ mi_block_t* last = head;mi_block_t* next;- while ((next = mi_block_next(page,tail)) != NULL && count <= max_count) {+ while ((next = mi_block_next(page, last)) != NULL && count <= max_count) {count++;- tail = next;+ last = next;}+// if `count > max_count` there was a memory corruption (possibly infinite list due to double multi-threaded free)if (count > max_count) {_mi_error_message(EFAULT, "corrupted thread-free list\n");@@ -207,20 +158,49 @@ static void _mi_page_thread_free_collect(mi_page_t* page)}// and append the current local free list- mi_block_set_next(page,tail, page->local_free);+ mi_block_set_next(page, last, page->local_free);page->local_free = head;// update counts now- page->used -= (uint16_t)count;+ mi_assert_internal(count <= UINT16_MAX);+ mi_assert_internal(page->used >= (uint16_t)count);+ page->used = page->used - (uint16_t)count;+}++// Collect the local `thread_free` list using an atomic exchange.+static void mi_page_thread_free_collect(mi_page_t* page)+{+ // atomically capture the thread free list+ mi_block_t* head;+ mi_thread_free_t tfreex;+ mi_thread_free_t tfree = mi_atomic_load_relaxed(&page->xthread_free);+ do {+ head = mi_tf_block(tfree);+ if mi_likely(head == NULL) return; // return if the list is empty+ tfreex = mi_tf_create(NULL,mi_tf_is_owned(tfree)); // set the thread free list to NULL+ } while (!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tfree, tfreex)); // release is enough?+ mi_assert_internal(head != NULL);++ // and move it to the local list+ mi_page_thread_collect_to_local(page, head);+}++// returns `true` if after collection `mi_page_immediate_available` is true.+static bool mi_page_free_quick_collect(mi_page_t* page) {+ if (page->free != NULL) return true;+ if (page->local_free == NULL) return false;+ // move local_free to free+ page->free = page->local_free;+ page->local_free = NULL;+ page->free_is_zero = false;+ return true;}void _mi_page_free_collect(mi_page_t* page, bool force) {mi_assert_internal(page!=NULL);// collect the thread free list- if (force || mi_page_thread_free(page) != NULL) { // quick test to avoid an atomic operation- _mi_page_thread_free_collect(page);- }+ mi_page_thread_free_collect(page);// and the local free listif (page->local_free != NULL) {@@ -247,116 +227,147 @@ void _mi_page_free_collect(mi_page_t* page, bool force) {mi_assert_internal(!force || page->local_free == NULL);}+// Collect elements in the thread-free list starting at `head`. This is an optimized+// version of `_mi_page_free_collect` to be used from `free.c:_mi_free_collect_mt` that avoids atomic access to `xthread_free`.+//+// `head` must be in the `xthread_free` list. It will not collect `head` itself+// so the `used` count is not fully updated in general. However, if the `head` is+// the last remaining element, it will be collected and the used count will become `0` (so `mi_page_all_free` becomes true).+void _mi_page_free_collect_partly(mi_page_t* page, mi_block_t* head) {+ if (head == NULL) return;+ mi_block_t* next = mi_block_next(page,head); // we cannot collect the head element itself as `page->thread_free` may point to it (and we want to avoid atomic ops)+ if (next != NULL) {+ mi_block_set_next(page, head, NULL);+ mi_page_thread_collect_to_local(page, next);+ if (page->local_free != NULL && page->free == NULL) {+ page->free = page->local_free;+ page->local_free = NULL;+ page->free_is_zero = false;+ }+ }+ if (page->used == 1) {+ // all elements are free'd since we skipped the `head` element itself+ mi_assert_internal(mi_tf_block(mi_atomic_load_relaxed(&page->xthread_free)) == head);+ mi_assert_internal(mi_block_next(page,head) == NULL);+ _mi_page_free_collect(page, false); // collect the final element+ }+}/* -----------------------------------------------------------Page fresh and retire----------------------------------------------------------- */+/*// called from segments when reclaiming abandoned pages-void _mi_page_reclaim(mi_heap_t* heap, mi_page_t* page) {- mi_assert_expensive(mi_page_is_valid_init(page));+void _mi_page_reclaim(mi_theap_t* theap, mi_page_t* page) {+ // mi_page_set_theap(page, theap);+ // _mi_page_use_delayed_free(page, MI_USE_DELAYED_FREE, true); // override never (after theap is set)+ _mi_page_free_collect(page, false); // ensure used count is up to date- mi_assert_internal(mi_page_heap(page) == heap);- mi_assert_internal(mi_page_thread_free_flag(page) != MI_NEVER_DELAYED_FREE);- #if MI_HUGE_PAGE_ABANDON- mi_assert_internal(_mi_page_segment(page)->kind != MI_SEGMENT_HUGE);- #endif+ mi_assert_expensive(mi_page_is_valid_init(page));+ // mi_assert_internal(mi_page_theap(page) == theap);+ // mi_assert_internal(mi_page_thread_free_flag(page) != MI_NEVER_DELAYED_FREE);// TODO: push on full queue immediately if it is full?- mi_page_queue_t* pq = mi_page_queue(heap, mi_page_block_size(page));- mi_page_queue_push(heap, pq, page);+ mi_page_queue_t* pq = mi_theap_page_queue_of(theap, page);+ mi_page_queue_push(theap, pq, page);+ mi_assert_expensive(_mi_page_is_valid(page));+}+*/++// called from `mi_free` on a reclaim, and fresh_alloc if we get an abandoned page+void _mi_theap_page_reclaim(mi_theap_t* theap, mi_page_t* page)+{+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(mi_page_is_abandoned(page));++ mi_page_set_theap(page,theap);+ _mi_page_free_collect(page, false); // ensure used count is up to date+ mi_page_queue_t* pq = mi_theap_page_queue_of(theap, page);+ mi_page_queue_push_at_end(theap, pq, page);mi_assert_expensive(_mi_page_is_valid(page));}-// allocate a fresh page from a segment-static mi_page_t* mi_page_fresh_alloc(mi_heap_t* heap, mi_page_queue_t* pq, size_t block_size, size_t page_alignment) {+void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq) {+ _mi_page_free_collect(page, false); // ensure used count is up to date+ if (mi_page_all_free(page)) {+ _mi_page_free(page, pq);+ }+ else {+ mi_page_queue_remove(pq, page);+ mi_theap_t* theap = page->theap;+ mi_page_set_theap(page, NULL);+ page->theap = theap; // don't actually set theap to NULL so we can reclaim_on_free within the same theap+ _mi_arenas_page_abandon(page, theap);+ _mi_arenas_collect(false, false, theap->tld); // allow purging+ }+}+++// allocate a fresh page from an arena+static mi_page_t* mi_page_fresh_alloc(mi_theap_t* theap, mi_page_queue_t* pq, size_t block_size, size_t page_alignment) {#if !MI_HUGE_PAGE_ABANDONmi_assert_internal(pq != NULL);- mi_assert_internal(mi_heap_contains_queue(heap, pq));- mi_assert_internal(page_alignment > 0 || block_size > MI_MEDIUM_OBJ_SIZE_MAX || block_size == pq->block_size);+ mi_assert_internal(mi_theap_contains_queue(theap, pq));+ mi_assert_internal(page_alignment > 0 || block_size > MI_LARGE_MAX_OBJ_SIZE || block_size == pq->block_size);#endif- mi_page_t* page = _mi_segment_page_alloc(heap, block_size, page_alignment, &heap->tld->segments);+ mi_page_t* page = _mi_arenas_page_alloc(theap, block_size, page_alignment);if (page == NULL) {- // this may be out-of-memory, or an abandoned page was reclaimed (and in our queue)+ // out-of-memoryreturn NULL;}- #if MI_HUGE_PAGE_ABANDON- mi_assert_internal(pq==NULL || _mi_page_segment(page)->page_kind != MI_PAGE_HUGE);- #endif- mi_assert_internal(page_alignment >0 || block_size > MI_MEDIUM_OBJ_SIZE_MAX || _mi_page_segment(page)->kind != MI_SEGMENT_HUGE);+ if (mi_page_is_abandoned(page)) {+ _mi_theap_page_reclaim(theap, page);+ if (!mi_page_immediate_available(page)) {+ if (mi_page_is_expandable(page)) {+ if (!mi_page_extend_free(theap, page)) {+ return NULL; // cannot commit+ };+ }+ else {+ mi_assert(false); // should not happen?+ return NULL;+ }+ }+ }+ else if (pq != NULL) {+ mi_page_queue_push(theap, pq, page);+ }mi_assert_internal(pq!=NULL || mi_page_block_size(page) >= block_size);- // a fresh page was found, initialize it- const size_t full_block_size = (pq == NULL || mi_page_is_huge(page) ? mi_page_block_size(page) : block_size); // see also: mi_segment_huge_page_alloc- mi_assert_internal(full_block_size >= block_size);- mi_page_init(heap, page, full_block_size, heap->tld);- mi_heap_stat_increase(heap, pages, 1);- if (pq != NULL) { mi_page_queue_push(heap, pq, page); }mi_assert_expensive(_mi_page_is_valid(page));return page;}// Get a fresh page to use-static mi_page_t* mi_page_fresh(mi_heap_t* heap, mi_page_queue_t* pq) {- mi_assert_internal(mi_heap_contains_queue(heap, pq));- mi_page_t* page = mi_page_fresh_alloc(heap, pq, pq->block_size, 0);+static mi_page_t* mi_page_fresh(mi_theap_t* theap, mi_page_queue_t* pq) {+ mi_assert_internal(mi_theap_contains_queue(theap, pq));+ mi_page_t* page = mi_page_fresh_alloc(theap, pq, pq->block_size, 0);if (page==NULL) return NULL;mi_assert_internal(pq->block_size==mi_page_block_size(page));- mi_assert_internal(pq==mi_page_queue(heap, mi_page_block_size(page)));+ mi_assert_internal(pq==mi_theap_page_queue_of(theap, page));return page;}-/* ------------------------------------------------------------ Do any delayed frees- (put there by other threads if they deallocated in a full page)------------------------------------------------------------ */-void _mi_heap_delayed_free_all(mi_heap_t* heap) {- while (!_mi_heap_delayed_free_partial(heap)) {- mi_atomic_yield();- }-}--// returns true if all delayed frees were processed-bool _mi_heap_delayed_free_partial(mi_heap_t* heap) {- // take over the list (note: no atomic exchange since it is often NULL)- mi_block_t* block = mi_atomic_load_ptr_relaxed(mi_block_t, &heap->thread_delayed_free);- while (block != NULL && !mi_atomic_cas_ptr_weak_acq_rel(mi_block_t, &heap->thread_delayed_free, &block, NULL)) { /* nothing */ };- bool all_freed = true;-- // and free them all- while(block != NULL) {- mi_block_t* next = mi_block_nextx(heap,block, heap->keys);- // use internal free instead of regular one to keep stats etc correct- if (!_mi_free_delayed_block(block)) {- // we might already start delayed freeing while another thread has not yet- // reset the delayed_freeing flag; in that case delay it further by reinserting the current block- // into the delayed free list- all_freed = false;- mi_block_t* dfree = mi_atomic_load_ptr_relaxed(mi_block_t, &heap->thread_delayed_free);- do {- mi_block_set_nextx(heap, block, dfree, heap->keys);- } while (!mi_atomic_cas_ptr_weak_release(mi_block_t,&heap->thread_delayed_free, &dfree, block));- }- block = next;- }- return all_freed;-}/* -----------------------------------------------------------Unfull, abandon, free and retire----------------------------------------------------------- */-// Move a page from the full list back to a regular list+// Move a page from the full list back to a regular list (called from thread-local mi_free)void _mi_page_unfull(mi_page_t* page) {mi_assert_internal(page != NULL);mi_assert_expensive(_mi_page_is_valid(page));mi_assert_internal(mi_page_is_in_full(page));+ mi_assert_internal(!mi_page_theap(page)->allow_page_abandon);if (!mi_page_is_in_full(page)) return;- mi_heap_t* heap = mi_page_heap(page);- mi_page_queue_t* pqfull = &heap->pages[MI_BIN_FULL];+ mi_theap_t* theap = mi_page_theap(page);+ mi_page_queue_t* pqfull = &theap->pages[MI_BIN_FULL];mi_page_set_in_full(page, false); // to get the right queue- mi_page_queue_t* pq = mi_heap_page_queue_of(heap, page);+ mi_page_queue_t* pq = mi_theap_page_queue_of(theap, page);mi_page_set_in_full(page, true);mi_page_queue_enqueue_from_full(pq, pqfull, page);}@@ -366,96 +377,48 @@ static void mi_page_to_full(mi_page_t* page, mi_page_queue_t* pq) {mi_assert_internal(!mi_page_immediate_available(page));mi_assert_internal(!mi_page_is_in_full(page));- if (mi_page_is_in_full(page)) return;- mi_page_queue_enqueue_from(&mi_page_heap(page)->pages[MI_BIN_FULL], pq, page);- _mi_page_free_collect(page,false); // try to collect right away in case another thread freed just before MI_USE_DELAYED_FREE was set-}---// Abandon a page with used blocks at the end of a thread.-// Note: only call if it is ensured that no references exist from-// the `page->heap->thread_delayed_free` into this page.-// Currently only called through `mi_heap_collect_ex` which ensures this.-void _mi_page_abandon(mi_page_t* page, mi_page_queue_t* pq) {- mi_assert_internal(page != NULL);- mi_assert_expensive(_mi_page_is_valid(page));- mi_assert_internal(pq == mi_page_queue_of(page));- mi_assert_internal(mi_page_heap(page) != NULL);-- mi_heap_t* pheap = mi_page_heap(page);-- // remove from our page list- mi_segments_tld_t* segments_tld = &pheap->tld->segments;- mi_page_queue_remove(pq, page);-- // page is no longer associated with our heap- mi_assert_internal(mi_page_thread_free_flag(page)==MI_NEVER_DELAYED_FREE);- mi_page_set_heap(page, NULL);--#if (MI_DEBUG>1) && !MI_TRACK_ENABLED- // check there are no references left..- for (mi_block_t* block = (mi_block_t*)pheap->thread_delayed_free; block != NULL; block = mi_block_nextx(pheap, block, pheap->keys)) {- mi_assert_internal(_mi_ptr_page(block) != page);- }-#endif-- // and abandon it- mi_assert_internal(mi_page_heap(page) == NULL);- _mi_segment_page_abandon(page,segments_tld);-}--// force abandon a page-void _mi_page_force_abandon(mi_page_t* page) {- mi_heap_t* heap = mi_page_heap(page);- // mark page as not using delayed free- _mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);-- // ensure this page is no longer in the heap delayed free list- _mi_heap_delayed_free_all(heap);- // We can still access the page meta-info even if it is freed as we ensure- // in `mi_segment_force_abandon` that the segment is not freed (yet)- if (page->capacity == 0) return; // it may have been freed now-- // and now unlink it from the page queue and abandon (or free)- mi_page_queue_t* pq = mi_heap_page_queue_of(heap, page);- if (mi_page_all_free(page)) {- _mi_page_free(page, pq, false);- }- else {+ mi_theap_t* theap = mi_page_theap(page);+ if (theap->allow_page_abandon) {+ // abandon full pages (this is the usual case in order to allow for sharing of memory between theaps)_mi_page_abandon(page, pq);}+ else if (!mi_page_is_in_full(page)) {+ // put full pages in a theap local queue (this is for theaps that cannot abandon, for example, if the theap can be destroyed)+ mi_page_queue_enqueue_from(&mi_page_theap(page)->pages[MI_BIN_FULL], pq, page);+ _mi_page_free_collect(page, false); // try to collect right away in case another thread freed just before MI_USE_DELAYED_FREE was set+ }}// Free a page with no more free blocks-void _mi_page_free(mi_page_t* page, mi_page_queue_t* pq, bool force) {+void _mi_page_free(mi_page_t* page, mi_page_queue_t* pq) {mi_assert_internal(page != NULL);mi_assert_expensive(_mi_page_is_valid(page));mi_assert_internal(pq == mi_page_queue_of(page));mi_assert_internal(mi_page_all_free(page));- mi_assert_internal(mi_page_thread_free_flag(page)!=MI_DELAYED_FREEING);+ // mi_assert_internal(mi_page_thread_free_flag(page)!=MI_DELAYED_FREEING);// no more aligned blocks in here- mi_page_set_has_aligned(page, false);-- mi_heap_t* heap = mi_page_heap(page);+ mi_page_set_has_interior_pointers(page, false);// remove from the page list- // (no need to do _mi_heap_delayed_free first as all blocks are already free)- mi_segments_tld_t* segments_tld = &heap->tld->segments;+ // (no need to do _mi_theap_delayed_free first as all blocks are already free)mi_page_queue_remove(pq, page);// and free it- mi_page_set_heap(page,NULL);- _mi_segment_page_free(page, force, segments_tld);+ mi_theap_t* theap = mi_page_theap(page); mi_assert_internal(theap!=NULL);+ mi_page_set_theap(page,NULL);+ _mi_arenas_page_free(page, theap);+ _mi_arenas_collect(false, false, theap->tld); // allow purging}-#define MI_MAX_RETIRE_SIZE MI_MEDIUM_OBJ_SIZE_MAX // should be less than size for MI_BIN_HUGE+#define MI_MAX_RETIRE_SIZE MI_LARGE_OBJ_SIZE_MAX // should be less than size for MI_BIN_HUGE#define MI_RETIRE_CYCLES (16)// Retire a page with no more used blocks// Important to not retire too quickly though as new// allocations might coming.+//// Note: called from `mi_free` and benchmarks often// trigger this due to freeing everything and then// allocating again so careful when changing this.@@ -464,7 +427,8 @@ void _mi_page_retire(mi_page_t* page) mi_attr_noexcept {mi_assert_expensive(_mi_page_is_valid(page));mi_assert_internal(mi_page_all_free(page));- mi_page_set_has_aligned(page, false);+ if (page->retire_expire!=0) return; // already retired, just keep it retired+ mi_page_set_has_interior_pointers(page, false);// don't retire too often..// (or we end up retiring and re-allocating most of the time)@@ -477,35 +441,37 @@ void _mi_page_retire(mi_page_t* page) mi_attr_noexcept {const size_t bsize = mi_page_block_size(page);if mi_likely( /* bsize < MI_MAX_RETIRE_SIZE && */ !mi_page_queue_is_special(pq)) { // not full or huge queue?if (pq->last==page && pq->first==page) { // the only page in the queue?- mi_stat_counter_increase(_mi_stats_main.page_no_retire,1);- page->retire_expire = (bsize <= MI_SMALL_OBJ_SIZE_MAX ? MI_RETIRE_CYCLES : MI_RETIRE_CYCLES/4);- mi_heap_t* heap = mi_page_heap(page);- mi_assert_internal(pq >= heap->pages);- const size_t index = pq - heap->pages;+ mi_theap_t* theap = mi_page_theap(page);+ #if MI_STAT>0+ mi_theap_stat_counter_increase(theap, pages_retire, 1);+ #endif+ page->retire_expire = (bsize <= MI_SMALL_MAX_OBJ_SIZE ? MI_RETIRE_CYCLES : MI_RETIRE_CYCLES/4);+ mi_assert_internal(pq >= theap->pages);+ const size_t index = pq - theap->pages;mi_assert_internal(index < MI_BIN_FULL && index < MI_BIN_HUGE);- if (index < heap->page_retired_min) heap->page_retired_min = index;- if (index > heap->page_retired_max) heap->page_retired_max = index;+ if (index < theap->page_retired_min) theap->page_retired_min = index;+ if (index > theap->page_retired_max) theap->page_retired_max = index;mi_assert_internal(mi_page_all_free(page));return; // don't free after all}}#endif- _mi_page_free(page, pq, false);+ _mi_page_free(page, pq);}// free retired pages: we don't need to look at the entire queues// since we only retire pages that are at the head position in a queue.-void _mi_heap_collect_retired(mi_heap_t* heap, bool force) {+void _mi_theap_collect_retired(mi_theap_t* theap, bool force) {size_t min = MI_BIN_FULL;size_t max = 0;- for(size_t bin = heap->page_retired_min; bin <= heap->page_retired_max; bin++) {- mi_page_queue_t* pq = &heap->pages[bin];+ for(size_t bin = theap->page_retired_min; bin <= theap->page_retired_max; bin++) {+ mi_page_queue_t* pq = &theap->pages[bin];mi_page_t* page = pq->first;if (page != NULL && page->retire_expire != 0) {if (mi_page_all_free(page)) {page->retire_expire--;- if (force || page->retire_expire == 0) {- _mi_page_free(pq->first, pq, force);+ if (page->retire_expire == 0 || force) {+ _mi_page_free(page, pq);}else {// keep retired, update min/max@@ -518,10 +484,33 @@ void _mi_heap_collect_retired(mi_heap_t* heap, bool force) {}}}- heap->page_retired_min = min;- heap->page_retired_max = max;+ theap->page_retired_min = min;+ theap->page_retired_max = max;}+/*+static void mi_theap_collect_full_pages(mi_theap_t* theap) {+ // note: normally full pages get immediately abandoned and the full queue is always empty+ // this path is only used if abandoning is disabled due to a destroy-able theap or options+ // set by the user.+ mi_page_queue_t* pq = &theap->pages[MI_BIN_FULL];+ for (mi_page_t* page = pq->first; page != NULL; ) {+ mi_page_t* next = page->next; // get next in case we free the page+ _mi_page_free_collect(page, false); // register concurrent free's+ // no longer full?+ if (!mi_page_is_full(page)) {+ if (mi_page_all_free(page)) {+ _mi_page_free(page, pq);+ }+ else {+ _mi_page_unfull(page);+ }+ }+ page = next;+ }+}+*/+/* -----------------------------------------------------------Initialize the initial free list in a page.@@ -533,9 +522,8 @@ void _mi_heap_collect_retired(mi_heap_t* heap, bool force) {#define MI_MAX_SLICES (1UL << MI_MAX_SLICE_SHIFT)#define MI_MIN_SLICES (2)-static void mi_page_free_list_extend_secure(mi_heap_t* const heap, mi_page_t* const page, const size_t bsize, const size_t extend, mi_stats_t* const stats) {- MI_UNUSED(stats);- #if (MI_SECURE<=2)+static void mi_page_free_list_extend_secure(mi_theap_t* const theap, mi_page_t* const page, const size_t bsize, const size_t extend) {+ #if (MI_SECURE<3)mi_assert_internal(page->free == NULL);mi_assert_internal(page->local_free == NULL);#endif@@ -562,7 +550,7 @@ static void mi_page_free_list_extend_secure(mi_heap_t* const heap, mi_page_t* co// and initialize the free list by randomly threading through them// set up first element- const uintptr_t r = _mi_heap_random_next(heap);+ const uintptr_t r = _mi_theap_random_next(theap);size_t current = r % slice_count;counts[current]--;mi_block_t* const free_start = blocks[current];@@ -590,10 +578,9 @@ static void mi_page_free_list_extend_secure(mi_heap_t* const heap, mi_page_t* copage->free = free_start;}-static mi_decl_noinline void mi_page_free_list_extend( mi_page_t* const page, const size_t bsize, const size_t extend, mi_stats_t* const stats)+static mi_decl_noinline void mi_page_free_list_extend( mi_page_t* const page, const size_t bsize, const size_t extend){- MI_UNUSED(stats);- #if (MI_SECURE <= 2)+ #if (MI_SECURE<3)mi_assert_internal(page->free == NULL);mi_assert_internal(page->local_free == NULL);#endif@@ -621,10 +608,10 @@ static mi_decl_noinline void mi_page_free_list_extend( mi_page_t* const page, co----------------------------------------------------------- */#define MI_MAX_EXTEND_SIZE (4*1024) // heuristic, one OS page seems to work well.-#if (MI_SECURE>0)+#if (MI_SECURE>=3)#define MI_MIN_EXTEND (8*MI_SECURE) // extend at least by this many#else-#define MI_MIN_EXTEND (4)+#define MI_MIN_EXTEND (1)#endif// Extend the capacity (up to reserved) by initializing a free list@@ -632,21 +619,25 @@ static mi_decl_noinline void mi_page_free_list_extend( mi_page_t* const page, co// Note: we also experimented with "bump" allocation on the first// allocations but this did not speed up any benchmark (due to an// extra test in malloc? or cache effects?)-static void mi_page_extend_free(mi_heap_t* heap, mi_page_t* page, mi_tld_t* tld) {- MI_UNUSED(tld);+static bool mi_page_extend_free(mi_theap_t* theap, mi_page_t* page) {mi_assert_expensive(mi_page_is_valid_init(page));- #if (MI_SECURE<=2)+ #if (MI_SECURE<3)mi_assert(page->free == NULL);mi_assert(page->local_free == NULL);- if (page->free != NULL) return;+ if (page->free != NULL) return true;#endif- if (page->capacity >= page->reserved) return;+ if (page->capacity >= page->reserved) return true;- mi_stat_counter_increase(tld->stats.pages_extended, 1);+ size_t page_size;+ //uint8_t* page_start =+ mi_page_area(page, &page_size);+ #if MI_STAT>0+ mi_theap_stat_counter_increase(theap, pages_extended, 1);+ #endif// calculate the extend countconst size_t bsize = mi_page_block_size(page);- size_t extend = page->reserved - page->capacity;+ size_t extend = (size_t)page->reserved - page->capacity;mi_assert_internal(extend > 0);size_t max_extend = (bsize >= MI_MAX_EXTEND_SIZE ? MI_MIN_EXTEND : MI_MAX_EXTEND_SIZE/bsize);@@ -662,73 +653,79 @@ static void mi_page_extend_free(mi_heap_t* heap, mi_page_t* page, mi_tld_t* tld)mi_assert_internal(extend > 0 && extend + page->capacity <= page->reserved);mi_assert_internal(extend < (1UL<<16));+ // commit on demand?+ if (page->slice_committed > 0) {+ const size_t needed_size = (page->capacity + extend)*bsize;+ const size_t needed_commit = _mi_align_up( mi_page_slice_offset_of(page, needed_size), MI_PAGE_MIN_COMMIT_SIZE );+ if (needed_commit > page->slice_committed) {+ mi_assert_internal(((needed_commit - page->slice_committed) % _mi_os_page_size()) == 0);+ if (!_mi_os_commit(mi_page_slice_start(page) + page->slice_committed, needed_commit - page->slice_committed, NULL)) {+ return false;+ }+ page->slice_committed = needed_commit;+ }+ }+// and append the extend the free list- if (extend < MI_MIN_SLICES || MI_SECURE==0) { //!mi_option_is_enabled(mi_option_secure)) {- mi_page_free_list_extend(page, bsize, extend, &tld->stats );+ if (extend < MI_MIN_SLICES || MI_SECURE<3) { //!mi_option_is_enabled(mi_option_secure)) {+ mi_page_free_list_extend(page, bsize, extend );}else {- mi_page_free_list_extend_secure(heap, page, bsize, extend, &tld->stats);+ mi_page_free_list_extend_secure(theap, page, bsize, extend);}// enable the new free listpage->capacity += (uint16_t)extend;- mi_stat_increase(tld->stats.page_committed, extend * bsize);+ #if MI_STAT>0+ mi_theap_stat_increase(theap, page_committed, extend * bsize);+ #endifmi_assert_expensive(mi_page_is_valid_init(page));+ return true;}-// Initialize a fresh page-static void mi_page_init(mi_heap_t* heap, mi_page_t* page, size_t block_size, mi_tld_t* tld) {+// Initialize a fresh page (that is already partially initialized)+mi_decl_nodiscard bool _mi_page_init(mi_theap_t* theap, mi_page_t* page) {mi_assert(page != NULL);- mi_segment_t* segment = _mi_page_segment(page);- mi_assert(segment != NULL);- mi_assert_internal(block_size > 0);- // set fields- mi_page_set_heap(page, heap);- page->block_size = block_size;+ mi_assert(theap!=NULL);+ page->heap = (_mi_is_heap_main(theap->heap) ? NULL : theap->heap); // faster for `mi_page_associated_theap`+ mi_page_set_theap(page, theap);+size_t page_size;- page->page_start = _mi_segment_page_start(segment, page, &page_size);- mi_track_mem_noaccess(page->page_start,page_size);- mi_assert_internal(mi_page_block_size(page) <= page_size);- mi_assert_internal(page_size <= page->slice_count*MI_SEGMENT_SLICE_SIZE);- mi_assert_internal(page_size / block_size < (1L<<16));- page->reserved = (uint16_t)(page_size / block_size);+ uint8_t* page_start = mi_page_area(page, &page_size); MI_UNUSED(page_start);+ mi_track_mem_noaccess(page_start,page_size);+ mi_assert_internal(page_size / mi_page_block_size(page) < (1L<<16));mi_assert_internal(page->reserved > 0);#if (MI_PADDING || MI_ENCODE_FREELIST)- page->keys[0] = _mi_heap_random_next(heap);- page->keys[1] = _mi_heap_random_next(heap);+ page->keys[0] = _mi_theap_random_next(theap);+ page->keys[1] = _mi_theap_random_next(theap);#endif- page->free_is_zero = page->is_zero_init;#if MI_DEBUG>2- if (page->is_zero_init) {- mi_track_mem_defined(page->page_start, page_size);- mi_assert_expensive(mi_mem_is_zero(page->page_start, page_size));+ if (page->memid.initially_zero) {+ mi_track_mem_defined(page->page_start, mi_page_committed(page));+ mi_assert_expensive(mi_mem_is_zero(page_start, mi_page_committed(page)));}#endif- mi_assert_internal(page->is_committed);- if (block_size > 0 && _mi_is_power_of_two(block_size)) {- page->block_size_shift = (uint8_t)(mi_ctz((uintptr_t)block_size));- }- else {- page->block_size_shift = 0;- }+ mi_assert_internal(page->theap!=NULL);+ mi_assert_internal(page->theap == mi_page_theap(page));mi_assert_internal(page->capacity == 0);mi_assert_internal(page->free == NULL);mi_assert_internal(page->used == 0);- mi_assert_internal(page->xthread_free == 0);+ mi_assert_internal(mi_page_is_owned(page));+ mi_assert_internal(page->xthread_free == 1);mi_assert_internal(page->next == NULL);mi_assert_internal(page->prev == NULL);mi_assert_internal(page->retire_expire == 0);- mi_assert_internal(!mi_page_has_aligned(page));+ mi_assert_internal(!mi_page_has_interior_pointers(page));#if (MI_PADDING || MI_ENCODE_FREELIST)mi_assert_internal(page->keys[0] != 0);mi_assert_internal(page->keys[1] != 0);#endif- mi_assert_internal(page->block_size_shift == 0 || (block_size == ((size_t)1 << page->block_size_shift)));mi_assert_expensive(mi_page_is_valid_init(page));// initialize an initial free list- mi_page_extend_free(heap,page,tld);+ if (!mi_page_extend_free(theap,page)) return false;mi_assert(mi_page_immediate_available(page));+ return true;}@@ -736,70 +733,65 @@ static void mi_page_init(mi_heap_t* heap, mi_page_t* page, size_t block_size, miFind pages with free blocks-------------------------------------------------------------*/-// search for a best next page to use for at most N pages (often cut short if immediate blocks are available)-#define MI_MAX_CANDIDATE_SEARCH (4)--// is the page not yet used up to its reserved space?-static 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);-}--// Find a page with free blocks of `page->block_size`.-static mi_page_t* mi_page_queue_find_free_ex(mi_heap_t* heap, mi_page_queue_t* pq, bool first_try)+static mi_decl_noinline mi_page_t* mi_page_queue_find_free_ex(mi_theap_t* theap, mi_page_queue_t* pq, bool first_try){// search through the pages in "next fit" order- #if MI_STATsize_t count = 0;- #endif- size_t candidate_count = 0; // we reset this on the first candidate to limit the search+ long candidate_limit = 0; // we reset this on the first candidate to limit the search+ long page_full_retain = (pq->block_size > MI_SMALL_MAX_OBJ_SIZE ? 0 : theap->page_full_retain); // only retain small pagesmi_page_t* page_candidate = NULL; // a page with free spacemi_page_t* page = pq->first;while (page != NULL){- mi_page_t* next = page->next; // remember next- #if MI_STAT+ mi_page_t* next = page->next; // remember next (as this page can move to another queue)count++;- #endif- candidate_count++;-- // collect freed blocks by us and other threads- _mi_page_free_collect(page, false);+ candidate_limit--;- #if MI_MAX_CANDIDATE_SEARCH > 1// search up to N pages for a best candidate// is the local free list non-empty?- const bool immediate_available = mi_page_immediate_available(page);+ bool immediate_available = mi_page_immediate_available(page);+ if (!immediate_available) {+ // collect freed blocks by us and other threads to we get a proper use count+ _mi_page_free_collect(page, false);+ immediate_available = mi_page_immediate_available(page);+ }// if the page is completely full, move it to the `mi_pages_full`// queue so we don't visit long-lived pages too often.if (!immediate_available && !mi_page_is_expandable(page)) {- mi_assert_internal(!mi_page_is_in_full(page) && !mi_page_immediate_available(page));- mi_page_to_full(page, pq);+ page_full_retain--;+ if (page_full_retain < 0) {+ mi_assert_internal(!mi_page_is_in_full(page) && !mi_page_immediate_available(page));+ mi_page_to_full(page, pq);+ }}else {// the page has free space, make it a candidate// we prefer non-expandable pages with high usage as candidates (to reduce commit, and increase chances of free-ing up pages)if (page_candidate == NULL) {page_candidate = page;- candidate_count = 0;+ candidate_limit = _mi_option_get_fast(mi_option_page_max_candidates);+ }+ else if (mi_page_all_free(page_candidate)) {+ _mi_page_free(page_candidate, pq);+ page_candidate = page;}// prefer to reuse fuller pages (in the hope the less used page gets freed)- else if (page->used >= page_candidate->used && !mi_page_is_mostly_used(page) && !mi_page_is_expandable(page)) {+ else if (page->used >= page_candidate->used && !mi_page_is_mostly_used(page)) { // && !mi_page_is_expandable(page)) {page_candidate = page;}// if we find a non-expandable candidate, or searched for N pages, return with the best candidate- if (immediate_available || candidate_count > MI_MAX_CANDIDATE_SEARCH) {+ if (immediate_available || candidate_limit <= 0) {mi_assert_internal(page_candidate!=NULL);break;}}- #else- // first-fit algorithm++ #if 0+ // first-fit algorithm without candidates// If the page contains free blocks, we are doneif (mi_page_immediate_available(page) || mi_page_is_expandable(page)) {break; // pick this one@@ -814,30 +806,39 @@ static mi_page_t* mi_page_queue_find_free_ex(mi_heap_t* heap, mi_page_queue_t* ppage = next;} // for each page- mi_heap_stat_counter_increase(heap, searches, count);+ mi_theap_stat_counter_increase(theap, page_searches, count);+ mi_theap_stat_counter_increase(theap, page_searches_count, 1);// set the page to the best candidateif (page_candidate != NULL) {page = page_candidate;}- if (page != NULL && !mi_page_immediate_available(page)) {- mi_assert_internal(mi_page_is_expandable(page));- mi_page_extend_free(heap, page, heap->tld);+ if (page != NULL) {+ if (!mi_page_immediate_available(page)) {+ mi_assert_internal(mi_page_is_expandable(page));+ if (!mi_page_extend_free(theap, page)) {+ page = NULL; // failed to extend+ }+ }+ mi_assert_internal(page == NULL || mi_page_immediate_available(page));}if (page == NULL) {- _mi_heap_collect_retired(heap, false); // perhaps make a page available?- page = mi_page_fresh(heap, pq);+ _mi_theap_collect_retired(theap, false); // perhaps make a page available+ page = mi_page_fresh(theap, pq);+ mi_assert_internal(page == NULL || mi_page_immediate_available(page));if (page == NULL && first_try) {// out-of-memory _or_ an abandoned page with free blocks was reclaimed, try once again- page = mi_page_queue_find_free_ex(heap, pq, false);+ page = mi_page_queue_find_free_ex(theap, pq, false);+ mi_assert_internal(page == NULL || mi_page_immediate_available(page));}}else {+ mi_assert_internal(page == NULL || mi_page_immediate_available(page));// move the page to the front of the queue- mi_page_queue_move_to_front(heap, pq, page);+ mi_page_queue_move_to_front(theap, pq, page);page->retire_expire = 0;- // _mi_heap_collect_retired(heap, false); // update retire counts; note: increases rss on MemoryLoad bench so don't do this+ // _mi_theap_collect_retired(theap, false); // update retire counts; note: increases rss on MemoryLoad bench so don't do this}mi_assert_internal(page == NULL || mi_page_immediate_available(page));@@ -848,30 +849,25 @@ static mi_page_t* mi_page_queue_find_free_ex(mi_heap_t* heap, mi_page_queue_t* p// Find a page with free blocks of `size`.-static inline mi_page_t* mi_find_free_page(mi_heap_t* heap, size_t size) {- mi_page_queue_t* pq = mi_page_queue(heap, size);+static mi_page_t* mi_find_free_page(mi_theap_t* theap, mi_page_queue_t* pq) {+ // mi_page_queue_t* pq = mi_page_queue(theap, size);+ mi_assert_internal(!mi_page_queue_is_huge(pq));// check the first page: we even do this with candidate search or otherwise we re-search every timemi_page_t* page = pq->first;- if (page != NULL) {- #if (MI_SECURE>=3) // in secure mode, we extend half the time to increase randomness- if (page->capacity < page->reserved && ((_mi_heap_random_next(heap) & 1) == 1)) {- mi_page_extend_free(heap, page, heap->tld);+ if mi_likely(page != NULL && mi_page_free_quick_collect(page)) {+ #if (MI_SECURE>=3) // in secure mode, we extend half the time to increase randomness+ if (page->capacity < page->reserved && ((_mi_theap_random_next(theap) & 1) == 1)) {+ (void)mi_page_extend_free(theap, page); // ok if this failsmi_assert_internal(mi_page_immediate_available(page));}- else- #endif- {- _mi_page_free_collect(page,false);- }-- if (mi_page_immediate_available(page)) {- page->retire_expire = 0;- return page; // fast path- }+ #endif+ page->retire_expire = 0;+ return page; // fast path+ }+ else {+ return mi_page_queue_find_free_ex(theap, pq, true);}-- return mi_page_queue_find_free_ex(heap, pq, true);}@@ -885,12 +881,12 @@ static inline mi_page_t* mi_find_free_page(mi_heap_t* heap, size_t size) {static mi_deferred_free_fun* volatile deferred_free = NULL;static _Atomic(void*) deferred_arg; // = NULL-void _mi_deferred_free(mi_heap_t* heap, bool force) {- heap->tld->heartbeat++;- if (deferred_free != NULL && !heap->tld->recurse) {- heap->tld->recurse = true;- deferred_free(force, heap->tld->heartbeat, mi_atomic_load_ptr_relaxed(void,&deferred_arg));- heap->tld->recurse = false;+void _mi_deferred_free(mi_theap_t* theap, bool force) {+ theap->heartbeat++;+ if (deferred_free != NULL && !theap->tld->recurse) {+ theap->tld->recurse = true;+ deferred_free(force, theap->heartbeat, mi_atomic_load_ptr_relaxed(void,&deferred_arg));+ theap->tld->recurse = false;}}@@ -904,46 +900,30 @@ void mi_register_deferred_free(mi_deferred_free_fun* fn, void* arg) mi_attr_noexGeneral allocation----------------------------------------------------------- */-// Large and huge page allocation.-// Huge pages contain just one block, and the segment contains just that page (as `MI_SEGMENT_HUGE`).+// Huge pages contain just one block, and the segment contains just that page.// Huge pages are also use if the requested alignment is very large (> MI_BLOCK_ALIGNMENT_MAX)// so their size is not always `> MI_LARGE_OBJ_SIZE_MAX`.-static mi_page_t* mi_large_huge_page_alloc(mi_heap_t* heap, size_t size, size_t page_alignment) {- size_t block_size = _mi_os_good_alloc_size(size);- mi_assert_internal(mi_bin(block_size) == MI_BIN_HUGE || page_alignment > 0);- bool is_huge = (block_size > MI_LARGE_OBJ_SIZE_MAX || page_alignment > 0);+static mi_page_t* mi_huge_page_alloc(mi_theap_t* theap, size_t size, size_t page_alignment, mi_page_queue_t* pq) {+ const size_t block_size = _mi_os_good_alloc_size(size);+ // mi_assert_internal(mi_bin(block_size) == MI_BIN_HUGE || page_alignment > 0);#if MI_HUGE_PAGE_ABANDON- mi_page_queue_t* pq = (is_huge ? NULL : mi_page_queue(heap, block_size));+ #error todo.#else- mi_page_queue_t* pq = mi_page_queue(heap, is_huge ? MI_LARGE_OBJ_SIZE_MAX+1 : block_size);- mi_assert_internal(!is_huge || mi_page_queue_is_huge(pq));+ // mi_page_queue_t* pq = mi_page_queue(theap, MI_LARGE_MAX_OBJ_SIZE+1); // always in the huge queue regardless of the block size+ mi_assert_internal(mi_page_queue_is_huge(pq));#endif- mi_page_t* page = mi_page_fresh_alloc(heap, pq, block_size, page_alignment);+ mi_page_t* page = mi_page_fresh_alloc(theap, pq, block_size, page_alignment);if (page != NULL) {+ mi_assert_internal(mi_page_block_size(page) >= size);mi_assert_internal(mi_page_immediate_available(page));-- if (is_huge) {- mi_assert_internal(mi_page_is_huge(page));- mi_assert_internal(_mi_page_segment(page)->kind == MI_SEGMENT_HUGE);- mi_assert_internal(_mi_page_segment(page)->used==1);- #if MI_HUGE_PAGE_ABANDON- mi_assert_internal(_mi_page_segment(page)->thread_id==0); // abandoned, not in the huge queue- mi_page_set_heap(page, NULL);- #endif- }- else {- mi_assert_internal(!mi_page_is_huge(page));- }-- const size_t bsize = mi_page_usable_block_size(page); // note: not `mi_page_block_size` to account for padding- if (bsize <= MI_LARGE_OBJ_SIZE_MAX) {- mi_heap_stat_increase(heap, large, bsize);- mi_heap_stat_counter_increase(heap, large_count, 1);- }- else {- mi_heap_stat_increase(heap, huge, bsize);- mi_heap_stat_counter_increase(heap, huge_count, 1);- }+ mi_assert_internal(mi_page_is_huge(page));+ mi_assert_internal(mi_page_is_singleton(page));+ #if MI_HUGE_PAGE_ABANDON+ mi_assert_internal(mi_page_is_abandoned(page));+ mi_page_set_theap(page, NULL);+ #endif+ mi_theap_stat_increase(theap, malloc_huge, mi_page_block_size(page));+ mi_theap_stat_counter_increase(theap, malloc_huge_count, 1);}return page;}@@ -951,53 +931,78 @@ static mi_page_t* mi_large_huge_page_alloc(mi_heap_t* heap, size_t size, size_t// Allocate a page// Note: in debug mode the size includes MI_PADDING_SIZE and might have overflowed.-static mi_page_t* mi_find_page(mi_heap_t* heap, size_t size, size_t huge_alignment) mi_attr_noexcept {- // huge allocation?+static mi_page_t* mi_find_page(mi_theap_t* theap, size_t size, size_t huge_alignment) mi_attr_noexcept {const size_t req_size = size - MI_PADDING_SIZE; // correct for padding_size in case of an overflow on `size`- if mi_unlikely(req_size > (MI_MEDIUM_OBJ_SIZE_MAX - MI_PADDING_SIZE) || huge_alignment > 0) {- if mi_unlikely(req_size > MI_MAX_ALLOC_SIZE) {- _mi_error_message(EOVERFLOW, "allocation request is too large (%zu bytes)\n", req_size);- return NULL;- }- else {- return mi_large_huge_page_alloc(heap,size,huge_alignment);- }+ if mi_unlikely(req_size > MI_MAX_ALLOC_SIZE) {+ _mi_error_message(EOVERFLOW, "allocation request is too large (%zu bytes)\n", req_size);+ return NULL;+ }+ mi_page_queue_t* pq = mi_page_queue(theap, (huge_alignment > 0 ? MI_LARGE_MAX_OBJ_SIZE+1 : size));+ // huge allocation?+ if mi_unlikely(mi_page_queue_is_huge(pq) || req_size > MI_MAX_ALLOC_SIZE) {+ return mi_huge_page_alloc(theap,size,huge_alignment,pq);}else {// otherwise find a page with free blocks in our size segregated queues#if MI_PADDINGmi_assert_internal(size >= MI_PADDING_SIZE);#endif- return mi_find_free_page(heap, size);+ return mi_find_free_page(theap, pq);}}+// Generic allocation routine if the fast path (`alloc.c:mi_page_malloc`) does not succeed.// Note: in debug mode the size includes MI_PADDING_SIZE and might have overflowed.-// The `huge_alignment` is normally 0 but is set to a multiple of MI_SEGMENT_SIZE for-// very large requested alignments in which case we use a huge segment.-void* _mi_malloc_generic(mi_heap_t* heap, size_t size, bool zero, size_t huge_alignment) mi_attr_noexcept+// The `huge_alignment` is normally 0 but is set to a multiple of MI_SLICE_SIZE for+// very large requested alignments in which case we use a huge singleton page.+// Note: we put `bool zero, size_t huge_alignment` into one parameter (with zero in the low bit)+// to use 4 parameters which compiles better on msvc for the malloc fast path.+void* _mi_malloc_generic(mi_theap_t* theap, size_t size, size_t zero_huge_alignment, size_t* usable) mi_attr_noexcept{- mi_assert_internal(heap != NULL);+ const bool zero = ((zero_huge_alignment & 1) != 0);+ const size_t huge_alignment = (zero_huge_alignment & ~1);++ #if !MI_THEAP_INITASNULL+ mi_assert_internal(theap != NULL);+ #endif// initialize if necessary- if mi_unlikely(!mi_heap_is_initialized(heap)) {- heap = mi_heap_get_default(); // calls mi_thread_init- if mi_unlikely(!mi_heap_is_initialized(heap)) { return NULL; }+ if mi_unlikely(!mi_theap_is_initialized(theap)) {+ if (theap==&_mi_theap_empty_wrong) {+ // we were unable to allocate a theap for a first-class heap+ return NULL;+ }+ // otherwise we initialize the thread and its default theap+ mi_thread_init();+ theap = _mi_theap_default();+ if mi_unlikely(!mi_theap_is_initialized(theap)) { return NULL; }+ mi_assert_internal(_mi_theap_default()==theap);+ }+ mi_assert_internal(mi_theap_is_initialized(theap));++ // do administrative tasks every N generic mallocs+ if mi_unlikely(++theap->generic_count >= 1000) {+ theap->generic_collect_count += theap->generic_count;+ theap->generic_count = 0;+ // call potential deferred free routines+ _mi_deferred_free(theap, false);+ // free retired pages+ _mi_theap_collect_retired(theap, false);++ // collect every once in a while (10000 by default)+ const long generic_collect = mi_option_get_clamp(mi_option_generic_collect, 1, 1000000L);+ if (theap->generic_collect_count >= generic_collect) {+ theap->generic_collect_count = 0;+ mi_theap_collect(theap, false /* force? */);+ }}- mi_assert_internal(mi_heap_is_initialized(heap));-- // call potential deferred free routines- _mi_deferred_free(heap, false);-- // free delayed frees from other threads (but skip contended ones)- _mi_heap_delayed_free_partial(heap);// find (or allocate) a page of the right size- mi_page_t* page = mi_find_page(heap, size, huge_alignment);+ mi_page_t* page = mi_find_page(theap, size, huge_alignment);if mi_unlikely(page == NULL) { // first time out of memory, try to collect and retry the allocation once more- mi_heap_collect(heap, true /* force */);- page = mi_find_page(heap, size, huge_alignment);+ mi_theap_collect(theap, true /* force? */);+ page = mi_find_page(theap, size, huge_alignment);}if mi_unlikely(page == NULL) { // out of memory@@ -1008,16 +1013,17 @@ void* _mi_malloc_generic(mi_heap_t* heap, size_t size, bool zero, size_t huge_almi_assert_internal(mi_page_immediate_available(page));mi_assert_internal(mi_page_block_size(page) >= size);+ mi_assert_internal(_mi_is_aligned(page, MI_PAGE_ALIGN));+ mi_assert_internal(_mi_ptr_page(page)==page);// and try again, this time succeeding! (i.e. this should never recurse through _mi_page_malloc)- if mi_unlikely(zero && mi_page_is_huge(page)) {- // note: we cannot call _mi_page_malloc with zeroing for huge blocks; we zero it afterwards in that case.- void* p = _mi_page_malloc(heap, page, size);- mi_assert_internal(p != NULL);- _mi_memzero_aligned(p, mi_page_usable_block_size(page));- return p;- }- else {- return _mi_page_malloc_zero(heap, page, size, zero);+ if (usable!=NULL) { *usable = mi_page_usable_block_size(page); }+ void* const p = _mi_page_malloc_zero(theap,page,size,zero);+ mi_assert_internal(p != NULL);++ // move full pages to the full queue+ if (mi_page_block_size(page) > MI_SMALL_MAX_OBJ_SIZE && mi_page_is_full(page)) {+ mi_page_to_full(page, mi_page_queue_of(page));}+ return p;}diff --git a/vendored/mimalloc/src/prim/emscripten/prim.c b/vendored/mimalloc/src/prim/emscripten/prim.cindex 82147de79..ab3d59eed 100644--- a/vendored/mimalloc/src/prim/emscripten/prim.c+++ b/vendored/mimalloc/src/prim/emscripten/prim.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2023, Microsoft Research, Daan Leijen, Alon Zakai+Copyright (c) 2018-2025, Microsoft Research, Daan Leijen, Alon ZakaiThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -58,7 +58,7 @@ void _mi_prim_mem_init( mi_os_mem_config_t* config) {extern void emmalloc_free(void*);int _mi_prim_free(void* addr, size_t size) {- MI_UNUSED(size);+ if (size==0) return 0;emmalloc_free(addr);return 0;}@@ -114,6 +114,11 @@ int _mi_prim_reset(void* addr, size_t size) {return 0;}+int _mi_prim_reuse(void* addr, size_t size) {+ MI_UNUSED(addr); MI_UNUSED(size);+ return 0;+}+int _mi_prim_protect(void* addr, size_t size, bool protect) {MI_UNUSED(addr); MI_UNUSED(size); MI_UNUSED(protect);return 0;@@ -203,12 +208,12 @@ bool _mi_prim_random_buf(void* buf, size_t buf_len) {#if defined(MI_USE_PTHREADS)// use pthread local storage keys to detect thread ending-// (and used with MI_TLS_PTHREADS for the default heap)+// (and used with MI_TLS_PTHREADS for the default theap)pthread_key_t _mi_heap_default_key = (pthread_key_t)(-1);static void mi_pthread_done(void* value) {if (value!=NULL) {- _mi_thread_done((mi_heap_t*)value);+ _mi_thread_done((mi_theap_t*)value);}}@@ -221,9 +226,9 @@ void _mi_prim_thread_done_auto_done(void) {// nothing to do}-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {if (_mi_heap_default_key != (pthread_key_t)(-1)) { // can happen during recursive invocation on freeBSD- pthread_setspecific(_mi_heap_default_key, heap);+ pthread_setspecific(_mi_heap_default_key, theap);}}@@ -237,8 +242,11 @@ void _mi_prim_thread_done_auto_done(void) {// nothing}-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {- MI_UNUSED(heap);-+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);}#endif++bool _mi_prim_thread_is_in_threadpool(void) {+ return false;+}diff --git a/vendored/mimalloc/src/prim/osx/alloc-override-zone.c b/vendored/mimalloc/src/prim/osx/alloc-override-zone.cindex d3af170de..aa971c39f 100644--- a/vendored/mimalloc/src/prim/osx/alloc-override-zone.c+++ b/vendored/mimalloc/src/prim/osx/alloc-override-zone.c@@ -64,7 +64,8 @@ static void* zone_valloc(malloc_zone_t* zone, size_t size) {static void zone_free(malloc_zone_t* zone, void* p) {MI_UNUSED(zone);- mi_cfree(p);+ // mi_cfree(p); // checked free as `zone_free` may be called with invalid pointers+ mi_free(p); // with the page_map and pagemap_commit=1 we can use the regular free}static void* zone_realloc(malloc_zone_t* zone, void* p, size_t newsize) {@@ -83,7 +84,7 @@ static void zone_destroy(malloc_zone_t* zone) {}static unsigned zone_batch_malloc(malloc_zone_t* zone, size_t size, void** ps, unsigned count) {- size_t i;+ unsigned i;for (i = 0; i < count; i++) {ps[i] = zone_malloc(zone, size);if (ps[i] == NULL) break;diff --git a/vendored/mimalloc/src/prim/prim.c b/vendored/mimalloc/src/prim/prim.cindex 2002853f2..5147bae81 100644--- a/vendored/mimalloc/src/prim/prim.c+++ b/vendored/mimalloc/src/prim/prim.c@@ -39,29 +39,29 @@ terms of the MIT license. A copy of the license can be found in the file#define mi_attr_destructor __attribute__((destructor))#endifstatic void mi_attr_constructor mi_process_attach(void) {- _mi_process_load();+ _mi_auto_process_init();}static void mi_attr_destructor mi_process_detach(void) {- _mi_process_done();+ _mi_auto_process_done();}#elif defined(__cplusplus)// C++: use static initialization to detect process start/end// This is not guaranteed to be first/last but the best we can generally do?struct mi_init_done_t {mi_init_done_t() {- _mi_process_load();+ _mi_auto_process_init();}~mi_init_done_t() {- _mi_process_done();+ _mi_auto_process_done();}};static mi_init_done_t mi_init_done;#else- #pragma message("define a way to call _mi_process_load/done on your platform")+ #pragma message("define a way to call _mi_auto_process_init/done on your platform")#endif#endif-// Generic allocator init/done callback+// Generic allocator init/done callback#ifndef MI_PRIM_HAS_ALLOCATOR_INITbool _mi_is_redirected(void) {return false;diff --git a/vendored/mimalloc/src/prim/unix/prim.c b/vendored/mimalloc/src/prim/unix/prim.cindex 46869c861..ba8dfb1f8 100644--- a/vendored/mimalloc/src/prim/unix/prim.c+++ b/vendored/mimalloc/src/prim/unix/prim.c@@ -1,5 +1,5 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2023, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.@@ -31,11 +31,13 @@ terms of the MIT license. A copy of the license can be found in the file#if defined(__linux__)#include <features.h>- //#if defined(MI_NO_THP)- #include <sys/prctl.h> // THP disable- //#endif+ #include <sys/prctl.h> // THP disable, PR_SET_VMA+ #include <sys/sysinfo.h> // sysinfo+ #if defined(__GLIBC__) && !defined(PR_SET_VMA)+ #include <linux/prctl.h>+ #endif#if defined(__GLIBC__)- #include <linux/mman.h> // linux mmap flags+ #include <linux/mman.h> // linux mmap flags#else#include <sys/mman.h>#endif@@ -48,6 +50,7 @@ terms of the MIT license. A copy of the license can be found in the file#if !defined(MAC_OS_X_VERSION_10_7)#define MAC_OS_X_VERSION_10_7 1070#endif+ #include <sys/sysctl.h>#elif defined(__FreeBSD__) || defined(__DragonFly__)#include <sys/param.h>#if __FreeBSD_version >= 1200000@@ -57,11 +60,19 @@ terms of the MIT license. A copy of the license can be found in the file#include <sys/sysctl.h>#endif-#if defined(__linux__) || defined(__FreeBSD__)+#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__)#define MI_HAS_SYSCALL_H#include <sys/syscall.h>#endif+#if !defined(MADV_DONTNEED) && defined(POSIX_MADV_DONTNEED) // QNX+#define MADV_DONTNEED POSIX_MADV_DONTNEED+#endif+#if !defined(MADV_FREE) && defined(POSIX_MADV_FREE) // QNX+#define MADV_FREE POSIX_MADV_FREE+#endif++#define MI_UNIX_LARGE_PAGE_SIZE (2*MI_MiB) // TODO: can we query the OS for this?//------------------------------------------------------------------------------------// Use syscalls for some primitives to allow for libraries that override open/read/close etc.@@ -110,56 +121,105 @@ static inline int mi_prim_access(const char *fpath, int mode) {static bool unix_detect_overcommit(void) {bool os_overcommit = true;-#if defined(__linux__)- int fd = mi_prim_open("/proc/sys/vm/overcommit_memory", O_RDONLY);- if (fd >= 0) {+ #if defined(__linux__)+ int fd = mi_prim_open("/proc/sys/vm/overcommit_memory", O_RDONLY);+ if (fd >= 0) {+ char buf[32];+ ssize_t nread = mi_prim_read(fd, &buf, sizeof(buf));+ mi_prim_close(fd);+ // <https://www.kernel.org/doc/Documentation/vm/overcommit-accounting>+ // 0: heuristic overcommit, 1: always overcommit, 2: never overcommit (ignore NORESERVE)+ if (nread >= 1) {+ os_overcommit = (buf[0] == '0' || buf[0] == '1');+ }+ }+ #elif defined(__FreeBSD__)+ int val = 0;+ size_t olen = sizeof(val);+ if (sysctlbyname("vm.overcommit", &val, &olen, NULL, 0) == 0) {+ os_overcommit = (val != 0);+ }+ #else+ // default: overcommit is true+ #endif+ return os_overcommit;+}++static bool unix_detect_thp(void) {+ bool thp_enabled = false;+ #if defined(__linux__)+ int fd = mi_prim_open("/sys/kernel/mm/transparent_hugepage/enabled", O_RDONLY);+ if (fd >= 0) {char buf[32];ssize_t nread = mi_prim_read(fd, &buf, sizeof(buf));mi_prim_close(fd);- // <https://www.kernel.org/doc/Documentation/vm/overcommit-accounting>- // 0: heuristic overcommit, 1: always overcommit, 2: never overcommit (ignore NORESERVE)+ // <https://www.kernel.org/doc/html/latest/admin-guide/mm/transhuge.html>+ // between brackets is the current value, for example: always [madvise] neverif (nread >= 1) {- os_overcommit = (buf[0] == '0' || buf[0] == '1');+ thp_enabled = (_mi_strnstr(buf,32,"[never]") == NULL);}}-#elif defined(__FreeBSD__)- int val = 0;- size_t olen = sizeof(val);- if (sysctlbyname("vm.overcommit", &val, &olen, NULL, 0) == 0) {- os_overcommit = (val != 0);- }-#else- // default: overcommit is true-#endif- return os_overcommit;+ #endif+ return thp_enabled;+}++// try to detect the physical memory dynamically (if possible)+static void unix_detect_physical_memory( size_t page_size, size_t* physical_memory_in_kib ) {+ #if defined(CTL_HW) && (defined(HW_PHYSMEM64) || defined(HW_MEMSIZE)) // freeBSD, macOS+ MI_UNUSED(page_size);+ int64_t physical_memory = 0;+ size_t length = sizeof(int64_t);+ #if defined(HW_PHYSMEM64)+ int mib[2] = { CTL_HW, HW_PHYSMEM64 };+ #else+ int mib[2] = { CTL_HW, HW_MEMSIZE };+ #endif+ const int err = sysctl(mib, 2, &physical_memory, &length, NULL, 0);+ if (err==0 && physical_memory > 0) {+ const int64_t phys_in_kib = physical_memory / MI_KiB;+ if (phys_in_kib > 0 && (uint64_t)phys_in_kib <= SIZE_MAX) {+ *physical_memory_in_kib = (size_t)phys_in_kib;+ }+ }+ #elif defined(__linux__)+ MI_UNUSED(page_size);+ struct sysinfo info; _mi_memzero_var(info);+ const int err = sysinfo(&info);+ if (err==0 && info.totalram > 0 && info.totalram <= SIZE_MAX) {+ *physical_memory_in_kib = (size_t)info.totalram / MI_KiB;+ }+ #elif defined(_SC_PHYS_PAGES) // do not use by default as it might cause allocation (by using `fopen` to parse /proc/meminfo) (issue #1100)+ const long pphys = sysconf(_SC_PHYS_PAGES);+ const size_t psize_in_kib = page_size / MI_KiB;+ if (psize_in_kib > 0 && pphys > 0 && (unsigned long)pphys <= SIZE_MAX && (size_t)pphys <= (SIZE_MAX/psize_in_kib)) {+ *physical_memory_in_kib = (size_t)pphys * psize_in_kib;+ }+ #endif}void _mi_prim_mem_init( mi_os_mem_config_t* config ){long psize = sysconf(_SC_PAGESIZE);- if (psize > 0) {+ if (psize > 0 && (unsigned long)psize < SIZE_MAX) {config->page_size = (size_t)psize;config->alloc_granularity = (size_t)psize;- #if defined(_SC_PHYS_PAGES)- long pphys = sysconf(_SC_PHYS_PAGES);- if (pphys > 0 && (size_t)pphys < (SIZE_MAX/(size_t)psize)) {- config->physical_memory = (size_t)pphys * (size_t)psize;- }- #endif+ unix_detect_physical_memory(config->page_size, &config->physical_memory_in_kib);}- config->large_page_size = 2*MI_MiB; // TODO: can we query the OS for this?+ config->large_page_size = MI_UNIX_LARGE_PAGE_SIZE;config->has_overcommit = unix_detect_overcommit();config->has_partial_free = true; // mmap can free in partsconfig->has_virtual_reserve = true; // todo: check if this true for NetBSD? (for anonymous mmap with PROT_NONE)+ config->has_transparent_huge_pages = unix_detect_thp();// disable transparent huge pages for this process?#if (defined(__linux__) || defined(__ANDROID__)) && defined(PR_GET_THP_DISABLE)#if defined(MI_NO_THP)if (true)#else- if (!mi_option_is_enabled(mi_option_allow_large_os_pages)) // disable THP also if large OS pages are not allowed in the options+ if (!mi_option_is_enabled(mi_option_allow_thp)) // disable THP if requested through an option#endif{+ config->has_transparent_huge_pages = false;int val = 0;if (prctl(PR_GET_THP_DISABLE, &val, 0, 0, 0) != 0) {// Most likely since distros often come with always/madvise settings.@@ -177,6 +237,7 @@ void _mi_prim_mem_init( mi_os_mem_config_t* config )//---------------------------------------------int _mi_prim_free(void* addr, size_t size ) {+ if (size==0) return 0;bool err = (munmap(addr, size) == -1);return (err ? errno : 0);}@@ -189,20 +250,33 @@ int _mi_prim_free(void* addr, size_t size ) {static int unix_madvise(void* addr, size_t size, int advice) {#if defined(__sun)int res = madvise((caddr_t)addr, size, advice); // Solaris needs cast (issue #520)+ #elif defined(__QNX__)+ int res = posix_madvise(addr, size, advice);#elseint res = madvise(addr, size, advice);#endifreturn (res==0 ? 0 : errno);}-static void* unix_mmap_prim(void* addr, size_t size, size_t try_alignment, int protect_flags, int flags, int fd) {+static void* unix_mmap_prim(void* addr, size_t size, int protect_flags, int flags, int fd) {+ void* p = mmap(addr, size, protect_flags, flags, fd, 0 /* offset */);+ #if defined(__linux__) && defined(PR_SET_VMA)+ if (p!=MAP_FAILED && p!=NULL) {+ prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, p, size, "mimalloc");+ }+ #endif+ return p;+}++static void* unix_mmap_prim_aligned(void* addr, size_t size, size_t try_alignment, int protect_flags, int flags, int fd) {MI_UNUSED(try_alignment);void* p = NULL;#if defined(MAP_ALIGNED) // BSDif (addr == NULL && try_alignment > 1 && (try_alignment % _mi_os_page_size()) == 0) {- size_t n = mi_bsr(try_alignment);+ size_t n = 0;+ mi_bsr(try_alignment, &n);if (((size_t)1 << n) == try_alignment && n >= 12 && n <= 30) { // alignment is a power of 2 and 4096 <= alignment <= 1GiB- p = mmap(addr, size, protect_flags, flags | MAP_ALIGNED(n), fd, 0);+ p = unix_mmap_prim(addr, size, protect_flags, flags | MAP_ALIGNED(n), fd);if (p==MAP_FAILED || !_mi_is_aligned(p,try_alignment)) {int err = errno;_mi_trace_message("unable to directly request aligned OS memory (error: %d (0x%x), size: 0x%zx bytes, alignment: 0x%zx, hint address: %p)\n", err, err, size, try_alignment, addr);@@ -213,7 +287,7 @@ static void* unix_mmap_prim(void* addr, size_t size, size_t try_alignment, int p}#elif defined(MAP_ALIGN) // Solarisif (addr == NULL && try_alignment > 1 && (try_alignment % _mi_os_page_size()) == 0) {- p = mmap((void*)try_alignment, size, protect_flags, flags | MAP_ALIGN, fd, 0); // addr parameter is the required alignment+ p = unix_mmap_prim((void*)try_alignment, size, protect_flags, flags | MAP_ALIGN, fd); // addr parameter is the required alignmentif (p!=MAP_FAILED) return p;// fall back to regular mmap}@@ -223,7 +297,7 @@ static void* unix_mmap_prim(void* addr, size_t size, size_t try_alignment, int pif (addr == NULL) {void* hint = _mi_os_get_aligned_hint(try_alignment, size);if (hint != NULL) {- p = mmap(hint, size, protect_flags, flags, fd, 0);+ p = unix_mmap_prim(hint, size, protect_flags, flags, fd);if (p==MAP_FAILED || !_mi_is_aligned(p,try_alignment)) {#if MI_TRACK_ENABLED // asan sometimes does not instrument errno correctly?int err = 0;@@ -238,7 +312,7 @@ static void* unix_mmap_prim(void* addr, size_t size, size_t try_alignment, int p}#endif// regular mmap- p = mmap(addr, size, protect_flags, flags, fd, 0);+ p = unix_mmap_prim(addr, size, protect_flags, flags, fd);if (p!=MAP_FAILED) return p;// failed to allocatereturn NULL;@@ -272,7 +346,7 @@ static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protecprotect_flags |= PROT_MAX(PROT_READ | PROT_WRITE); // BSD#endif// huge page allocation- if (allow_large && (large_only || (_mi_os_use_large_page(size, try_alignment) && mi_option_get(mi_option_allow_large_os_pages) == 1))) {+ if (allow_large && (large_only || (_mi_os_canuse_large_page(size, try_alignment) && mi_option_is_enabled(mi_option_allow_large_os_pages)))) {static _Atomic(size_t) large_page_try_ok; // = 0;size_t try_ok = mi_atomic_load_acquire(&large_page_try_ok);if (!large_only && try_ok > 0) {@@ -309,7 +383,7 @@ static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protecif (large_only || lflags != flags) {// try large OS page allocation*is_large = true;- p = unix_mmap_prim(addr, size, try_alignment, protect_flags, lflags, lfd);+ p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, lflags, lfd);#ifdef MAP_HUGE_1GBif (p == NULL && (lflags & MAP_HUGE_1GB) == MAP_HUGE_1GB) {mi_huge_pages_available = false; // don't try huge 1GiB pages again@@ -317,7 +391,7 @@ static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protec_mi_warning_message("unable to allocate huge (1GiB) page, trying large (2MiB) pages instead (errno: %i)\n", errno);}lflags = ((lflags & ~MAP_HUGE_1GB) | MAP_HUGE_2MB);- p = unix_mmap_prim(addr, size, try_alignment, protect_flags, lflags, lfd);+ p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, lflags, lfd);}#endifif (large_only) return p;@@ -330,8 +404,9 @@ static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protec// regular allocationif (p == NULL) {*is_large = false;- p = unix_mmap_prim(addr, size, try_alignment, protect_flags, flags, fd);- if (p != NULL) {+ p = unix_mmap_prim_aligned(addr, size, try_alignment, protect_flags, flags, fd);+ #if !defined(MI_NO_THP)+ if (p != NULL && allow_large && mi_option_is_enabled(mi_option_allow_thp) && _mi_os_canuse_large_page(size, try_alignment)) {#if defined(MADV_HUGEPAGE)// Many Linux systems don't allow MAP_HUGETLB but they support instead// transparent huge pages (THP). Generally, it is not required to call `madvise` with MADV_HUGE@@ -339,22 +414,19 @@ static void* unix_mmap(void* addr, size_t size, size_t try_alignment, int protec// in that case -- in particular for our large regions (in `memory.c`).// However, some systems only allow THP if called with explicit `madvise`, so// when large OS pages are enabled for mimalloc, we call `madvise` anyways.- if (allow_large && _mi_os_use_large_page(size, try_alignment)) {- if (unix_madvise(p, size, MADV_HUGEPAGE) == 0) {- // *is_large = true; // possibly- };- }+ if (unix_madvise(p, size, MADV_HUGEPAGE) == 0) {+ // *is_large = true; // possibly+ };#elif defined(__sun)- if (allow_large && _mi_os_use_large_page(size, try_alignment)) {- struct memcntl_mha cmd = {0};- cmd.mha_pagesize = _mi_os_large_page_size();- cmd.mha_cmd = MHA_MAPSIZE_VA;- if (memcntl((caddr_t)p, size, MC_HAT_ADVISE, (caddr_t)&cmd, 0, 0) == 0) {- // *is_large = true; // possibly- }+ struct memcntl_mha cmd = {0};+ cmd.mha_pagesize = _mi_os_large_page_size();+ cmd.mha_cmd = MHA_MAPSIZE_VA;+ if (memcntl((caddr_t)p, size, MC_HAT_ADVISE, (caddr_t)&cmd, 0, 0) == 0) {+ // *is_large = true; // possibly}#endif}+ #endif}return p;}@@ -364,6 +436,9 @@ int _mi_prim_alloc(void* hint_addr, size_t size, size_t try_alignment, bool commmi_assert_internal(size > 0 && (size % _mi_os_page_size()) == 0);mi_assert_internal(commit || !allow_large);mi_assert_internal(try_alignment > 0);+ if (hint_addr == NULL && size >= 8*MI_UNIX_LARGE_PAGE_SIZE && try_alignment > 1 && _mi_is_power_of_two(try_alignment) && try_alignment < MI_UNIX_LARGE_PAGE_SIZE) {+ try_alignment = MI_UNIX_LARGE_PAGE_SIZE; // try to align along large page size for larger allocations+ }*is_zero = true;int protect_flags = (commit ? (PROT_WRITE | PROT_READ) : PROT_NONE);@@ -388,6 +463,10 @@ static void unix_mprotect_hint(int err) {#endif}++++int _mi_prim_commit(void* start, size_t size, bool* is_zero) {// commit: ensure we can access the area// note: we may think that *is_zero can be true since the memory@@ -403,11 +482,25 @@ int _mi_prim_commit(void* start, size_t size, bool* is_zero) {return err;}+int _mi_prim_reuse(void* start, size_t size) {+ MI_UNUSED(start); MI_UNUSED(size);+ #if defined(__APPLE__) && defined(MADV_FREE_REUSE)+ return unix_madvise(start, size, MADV_FREE_REUSE);+ #endif+ return 0;+}+int _mi_prim_decommit(void* start, size_t size, bool* needs_recommit) {int err = 0;- // decommit: use MADV_DONTNEED as it decreases rss immediately (unlike MADV_FREE)- err = unix_madvise(start, size, MADV_DONTNEED);- #if !MI_DEBUG && !MI_SECURE+ #if defined(__APPLE__) && defined(MADV_FREE_REUSABLE)+ // decommit on macOS: use MADV_FREE_REUSABLE as it does immediate rss accounting (issue #1097)+ err = unix_madvise(start, size, MADV_FREE_REUSABLE);+ if (err) { err = unix_madvise(start, size, MADV_DONTNEED); }+ #else+ // decommit: use MADV_DONTNEED as it decreases rss immediately (unlike MADV_FREE)+ err = unix_madvise(start, size, MADV_DONTNEED);+ #endif+ #if !MI_DEBUG && MI_SECURE<=2*needs_recommit = false;#else*needs_recommit = true;@@ -424,14 +517,22 @@ int _mi_prim_decommit(void* start, size_t size, bool* needs_recommit) {}int _mi_prim_reset(void* start, size_t size) {- // We try to use `MADV_FREE` as that is the fastest. A drawback though is that it+ int err = 0;++ // on macOS can use MADV_FREE_REUSABLE (but we disable this for now as it seems slower)+ #if 0 && defined(__APPLE__) && defined(MADV_FREE_REUSABLE)+ err = unix_madvise(start, size, MADV_FREE_REUSABLE);+ if (err==0) return 0;+ // fall through+ #endif++ #if defined(MADV_FREE)+ // Otherwise, we try to use `MADV_FREE` as that is the fastest. A drawback though is that it// will not reduce the `rss` stats in tools like `top` even though the memory is available// to other processes. With the default `MIMALLOC_PURGE_DECOMMITS=1` we ensure that by// default `MADV_DONTNEED` is used though.- #if defined(MADV_FREE)static _Atomic(size_t) advice = MI_ATOMIC_VAR_INIT(MADV_FREE);int oadvice = (int)mi_atomic_load_relaxed(&advice);- int err;while ((err = unix_madvise(start, size, oadvice)) != 0 && errno == EAGAIN) { errno = 0; };if (err != 0 && errno == EINVAL && oadvice == MADV_FREE) {// if MADV_FREE is not supported, fall back to MADV_DONTNEED from now on@@ -439,7 +540,7 @@ int _mi_prim_reset(void* start, size_t size) {err = unix_madvise(start, size, MADV_DONTNEED);}#else- int err = unix_madvise(start, size, MADV_DONTNEED);+ err = unix_madvise(start, size, MADV_DONTNEED);#endifreturn err;}@@ -477,7 +578,7 @@ static long mi_prim_mbind(void* start, unsigned long len, unsigned long mode, coint _mi_prim_alloc_huge_os_pages(void* hint_addr, size_t size, int numa_node, bool* is_zero, void** addr) {bool is_large = true;*is_zero = true;- *addr = unix_mmap(hint_addr, size, MI_SEGMENT_SIZE, PROT_READ | PROT_WRITE, true, true, &is_large);+ *addr = unix_mmap(hint_addr, size, MI_ARENA_SLICE_ALIGN, PROT_READ | PROT_WRITE, true, true, &is_large);if (*addr != NULL && numa_node >= 0 && numa_node < 8*MI_INTPTR_SIZE) { // at most 64 nodesunsigned long numa_mask = (1UL << numa_node);// TODO: does `mbind` work correctly for huge OS pages? should we@@ -843,12 +944,12 @@ bool _mi_prim_random_buf(void* buf, size_t buf_len) {#if defined(MI_USE_PTHREADS)// use pthread local storage keys to detect thread ending-// (and used with MI_TLS_PTHREADS for the default heap)+// (and used with MI_TLS_PTHREADS for the default theap)pthread_key_t _mi_heap_default_key = (pthread_key_t)(-1);static void mi_pthread_done(void* value) {if (value!=NULL) {- _mi_thread_done((mi_heap_t*)value);+ _mi_thread_done((mi_theap_t*)value);}}@@ -863,9 +964,9 @@ void _mi_prim_thread_done_auto_done(void) {}}-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {if (_mi_heap_default_key != (pthread_key_t)(-1)) { // can happen during recursive invocation on freeBSD- pthread_setspecific(_mi_heap_default_key, heap);+ pthread_setspecific(_mi_heap_default_key, theap);}}@@ -879,8 +980,12 @@ void _mi_prim_thread_done_auto_done(void) {// nothing}-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {- MI_UNUSED(heap);+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);}#endif++bool _mi_prim_thread_is_in_threadpool(void) {+ return false;+}diff --git a/vendored/mimalloc/src/prim/wasi/prim.c b/vendored/mimalloc/src/prim/wasi/prim.cindex e1e7de5ef..4e6270dde 100644--- a/vendored/mimalloc/src/prim/wasi/prim.c+++ b/vendored/mimalloc/src/prim/wasi/prim.c@@ -32,7 +32,7 @@ void _mi_prim_mem_init( mi_os_mem_config_t* config ) {int _mi_prim_free(void* addr, size_t size ) {MI_UNUSED(addr); MI_UNUSED(size);- // wasi heap cannot be shrunk+ // wasi theap cannot be shrunkreturn 0;}@@ -62,7 +62,7 @@ int _mi_prim_free(void* addr, size_t size ) {#endif#if defined(MI_USE_PTHREADS)-static pthread_mutex_t mi_heap_grow_mutex = PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t mi_theap_grow_mutex = PTHREAD_MUTEX_INITIALIZER;#endifstatic void* mi_prim_mem_grow(size_t size, size_t try_alignment) {@@ -70,11 +70,11 @@ static void* mi_prim_mem_grow(size_t size, size_t try_alignment) {if (try_alignment <= 1) {// `sbrk` is not thread safe in general so try to protect it (we could skip this on WASM but leave it in for now)#if defined(MI_USE_PTHREADS)- pthread_mutex_lock(&mi_heap_grow_mutex);+ pthread_mutex_lock(&mi_theap_grow_mutex);#endifp = mi_memory_grow(size);#if defined(MI_USE_PTHREADS)- pthread_mutex_unlock(&mi_heap_grow_mutex);+ pthread_mutex_unlock(&mi_theap_grow_mutex);#endif}else {@@ -84,7 +84,7 @@ static void* mi_prim_mem_grow(size_t size, size_t try_alignment) {// between getting the current size and actual allocation// (also, `sbrk` is not thread safe in general)#if defined(MI_USE_PTHREADS)- pthread_mutex_lock(&mi_heap_grow_mutex);+ pthread_mutex_lock(&mi_theap_grow_mutex);#endif{void* current = mi_memory_grow(0); // get current size@@ -95,7 +95,7 @@ static void* mi_prim_mem_grow(size_t size, size_t try_alignment) {}}#if defined(MI_USE_PTHREADS)- pthread_mutex_unlock(&mi_heap_grow_mutex);+ pthread_mutex_unlock(&mi_theap_grow_mutex);#endifif (base != NULL) {p = mi_align_up_ptr(base, try_alignment);@@ -149,6 +149,11 @@ int _mi_prim_reset(void* addr, size_t size) {return 0;}+int _mi_prim_reuse(void* addr, size_t size) {+ MI_UNUSED(addr); MI_UNUSED(size);+ return 0;+}+int _mi_prim_protect(void* addr, size_t size, bool protect) {MI_UNUSED(addr); MI_UNUSED(size); MI_UNUSED(protect);return 0;@@ -274,6 +279,10 @@ void _mi_prim_thread_done_auto_done(void) {// nothing}-void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {- MI_UNUSED(heap);+void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);+}++bool _mi_prim_thread_is_in_threadpool(void) {+ return false;}diff --git a/vendored/mimalloc/src/prim/windows/prim.c b/vendored/mimalloc/src/prim/windows/prim.cindex 745224c27..27d0a38ed 100644--- a/vendored/mimalloc/src/prim/windows/prim.c+++ b/vendored/mimalloc/src/prim/windows/prim.c@@ -12,11 +12,22 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc/prim.h"#include <stdio.h> // fputs, stderr+// xbox has no console IO+#if !defined(WINAPI_FAMILY_PARTITION) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM)+#define MI_HAS_CONSOLE_IO+#endif//---------------------------------------------// Dynamically bind Windows API points for portability//---------------------------------------------+#if defined(_MSC_VER)+#pragma warning(disable:4996) // don't use GetVersionExW+#endif++static DWORD win_major_version = 6;+static DWORD win_minor_version = 0;+// We use VirtualAlloc2 for aligned allocation, but it is only supported on Windows 10 and Windows Server 2016.// So, we need to look it up dynamically to run on older systems. (use __stdcall for 32-bit compatibility)// NtAllocateVirtualAllocEx is used for huge OS page allocation (1GiB)@@ -45,22 +56,35 @@ typedef struct MI_MEM_ADDRESS_REQUIREMENTS_S {#define MI_MEM_EXTENDED_PARAMETER_NONPAGED_HUGE 0x00000010#include <winternl.h>-typedef PVOID (__stdcall *PVirtualAlloc2)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MI_MEM_EXTENDED_PARAMETER*, ULONG);-typedef NTSTATUS (__stdcall *PNtAllocateVirtualMemoryEx)(HANDLE, PVOID*, SIZE_T*, ULONG, ULONG, MI_MEM_EXTENDED_PARAMETER*, ULONG);+typedef PVOID (__stdcall *PVirtualAlloc2)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MI_MEM_EXTENDED_PARAMETER*, ULONG);+typedef LONG (__stdcall *PNtAllocateVirtualMemoryEx)(HANDLE, PVOID*, SIZE_T*, ULONG, ULONG, MI_MEM_EXTENDED_PARAMETER*, ULONG); // avoid NTSTATUS as it is not defined on xbox (pr #1084)static PVirtualAlloc2 pVirtualAlloc2 = NULL;static PNtAllocateVirtualMemoryEx pNtAllocateVirtualMemoryEx = NULL;-// Similarly, GetNumaProcessorNodeEx is only supported since Windows 7+// Similarly, GetNumaProcessorNodeEx is only supported since Windows 7 (and GetNumaNodeProcessorMask is not supported on xbox)typedef struct MI_PROCESSOR_NUMBER_S { WORD Group; BYTE Number; BYTE Reserved; } MI_PROCESSOR_NUMBER;typedef VOID (__stdcall *PGetCurrentProcessorNumberEx)(MI_PROCESSOR_NUMBER* ProcNumber);typedef BOOL (__stdcall *PGetNumaProcessorNodeEx)(MI_PROCESSOR_NUMBER* Processor, PUSHORT NodeNumber);typedef BOOL (__stdcall* PGetNumaNodeProcessorMaskEx)(USHORT Node, PGROUP_AFFINITY ProcessorMask);typedef BOOL (__stdcall *PGetNumaProcessorNode)(UCHAR Processor, PUCHAR NodeNumber);+typedef BOOL (__stdcall* PGetNumaNodeProcessorMask)(UCHAR Node, PULONGLONG ProcessorMask);+typedef BOOL (__stdcall* PGetNumaHighestNodeNumber)(PULONG Node);static PGetCurrentProcessorNumberEx pGetCurrentProcessorNumberEx = NULL;static PGetNumaProcessorNodeEx pGetNumaProcessorNodeEx = NULL;static PGetNumaNodeProcessorMaskEx pGetNumaNodeProcessorMaskEx = NULL;static PGetNumaProcessorNode pGetNumaProcessorNode = NULL;+static PGetNumaNodeProcessorMask pGetNumaNodeProcessorMask = NULL;+static PGetNumaHighestNodeNumber pGetNumaHighestNodeNumber = NULL;++// Not available on xbox+typedef SIZE_T(__stdcall* PGetLargePageMinimum)(VOID);+static PGetLargePageMinimum pGetLargePageMinimum = NULL;++// Available after Windows XP+typedef BOOL (__stdcall *PGetPhysicallyInstalledSystemMemory)( PULONGLONG TotalMemoryInKilobytes );+typedef BOOL (__stdcall* PGetVersionExW)(LPOSVERSIONINFOW lpVersionInformation);+//---------------------------------------------// Enable large page support dynamically (if possible)@@ -71,6 +95,7 @@ static bool win_enable_large_os_pages(size_t* large_page_size)static bool large_initialized = false;if (large_initialized) return (_mi_os_large_page_size() > 0);large_initialized = true;+ if (pGetLargePageMinimum==NULL) return false; // no large page support (xbox etc.)// Try to see if large OS pages are supported// To use large pages on Windows, we first need access permission@@ -89,8 +114,8 @@ static bool win_enable_large_os_pages(size_t* large_page_size)if (ok) {err = GetLastError();ok = (err == ERROR_SUCCESS);- if (ok && large_page_size != NULL) {- *large_page_size = GetLargePageMinimum();+ if (ok && large_page_size != NULL && pGetLargePageMinimum != NULL) {+ *large_page_size = (*pGetLargePageMinimum)();}}}@@ -108,31 +133,30 @@ static bool win_enable_large_os_pages(size_t* large_page_size)// Initialize//---------------------------------------------+static DWORD win_allocation_granularity = 64*MI_KiB;+void _mi_prim_mem_init( mi_os_mem_config_t* config ){config->has_overcommit = false;config->has_partial_free = false;config->has_virtual_reserve = true;+// get the page size- SYSTEM_INFO si;+ SYSTEM_INFO si; _mi_memzero_var(si);GetSystemInfo(&si);if (si.dwPageSize > 0) { config->page_size = si.dwPageSize; }- if (si.dwAllocationGranularity > 0) { config->alloc_granularity = si.dwAllocationGranularity; }+ if (si.dwAllocationGranularity > 0) {+ config->alloc_granularity = si.dwAllocationGranularity;+ win_allocation_granularity = si.dwAllocationGranularity;+ }// get virtual address bitsif ((uintptr_t)si.lpMaximumApplicationAddress > 0) {- const size_t vbits = MI_INTPTR_BITS - mi_clz((uintptr_t)si.lpMaximumApplicationAddress);+ const size_t vbits = MI_SIZE_BITS - mi_clz((uintptr_t)si.lpMaximumApplicationAddress);config->virtual_address_bits = vbits;}- // get physical memory- ULONGLONG memInKiB = 0;- if (GetPhysicallyInstalledSystemMemory(&memInKiB)) {- if (memInKiB > 0 && memInKiB < (SIZE_MAX / MI_KiB)) {- config->physical_memory = memInKiB * MI_KiB;- }- }+// get the VirtualAlloc2 function- HINSTANCE hDll;- hDll = LoadLibrary(TEXT("kernelbase.dll"));+ HINSTANCE hDll = LoadLibrary(TEXT("kernelbase.dll"));if (hDll != NULL) {// use VirtualAlloc2FromApp if possible as it is available to Windows store appspVirtualAlloc2 = (PVirtualAlloc2)(void (*)(void))GetProcAddress(hDll, "VirtualAlloc2FromApp");@@ -152,8 +176,32 @@ void _mi_prim_mem_init( mi_os_mem_config_t* config )pGetNumaProcessorNodeEx = (PGetNumaProcessorNodeEx)(void (*)(void))GetProcAddress(hDll, "GetNumaProcessorNodeEx");pGetNumaNodeProcessorMaskEx = (PGetNumaNodeProcessorMaskEx)(void (*)(void))GetProcAddress(hDll, "GetNumaNodeProcessorMaskEx");pGetNumaProcessorNode = (PGetNumaProcessorNode)(void (*)(void))GetProcAddress(hDll, "GetNumaProcessorNode");+ pGetNumaNodeProcessorMask = (PGetNumaNodeProcessorMask)(void (*)(void))GetProcAddress(hDll, "GetNumaNodeProcessorMask");+ pGetNumaHighestNodeNumber = (PGetNumaHighestNodeNumber)(void (*)(void))GetProcAddress(hDll, "GetNumaHighestNodeNumber");+ pGetLargePageMinimum = (PGetLargePageMinimum)(void (*)(void))GetProcAddress(hDll, "GetLargePageMinimum");+ // Get physical memory (not available on XP, so check dynamically)+ PGetPhysicallyInstalledSystemMemory pGetPhysicallyInstalledSystemMemory = (PGetPhysicallyInstalledSystemMemory)(void (*)(void))GetProcAddress(hDll,"GetPhysicallyInstalledSystemMemory");+ if (pGetPhysicallyInstalledSystemMemory != NULL) {+ ULONGLONG memInKiB = 0;+ if ((*pGetPhysicallyInstalledSystemMemory)(&memInKiB)) {+ if (memInKiB > 0 && memInKiB <= SIZE_MAX) {+ config->physical_memory_in_kib = (size_t)memInKiB;+ }+ }+ }+ // Get Windows version+ PGetVersionExW pGetVersionExW = (PGetVersionExW)(void (*)(void))GetProcAddress(hDll, "GetVersionExW");+ if (pGetVersionExW != NULL) {+ OSVERSIONINFOW version; _mi_memzero_var(version);+ version.dwOSVersionInfoSize = sizeof(version);+ if ((*pGetVersionExW)(&version)) {+ win_major_version = version.dwMajorVersion;+ win_minor_version = version.dwMinorVersion;+ }+ }FreeLibrary(hDll);}+ // Enable large/huge OS page support?if (mi_option_is_enabled(mi_option_allow_large_os_pages) || mi_option_is_enabled(mi_option_reserve_huge_os_pages)) {win_enable_large_os_pages(&config->large_page_size);}@@ -173,9 +221,9 @@ int _mi_prim_free(void* addr, size_t size ) {// In mi_os_mem_alloc_aligned the fallback path may have returned a pointer inside// the memory region returned by VirtualAlloc; in that case we need to free using// the start of the region.- MEMORY_BASIC_INFORMATION info = { 0 };+ MEMORY_BASIC_INFORMATION info; _mi_memzero_var(info);VirtualQuery(addr, &info, sizeof(info));- if (info.AllocationBase < addr && ((uint8_t*)addr - (uint8_t*)info.AllocationBase) < (ptrdiff_t)MI_SEGMENT_SIZE) {+ if (info.AllocationBase < addr && ((uint8_t*)addr - (uint8_t*)info.AllocationBase) < (ptrdiff_t)(4*MI_MiB)) {errcode = 0;err = (VirtualFree(info.AllocationBase, 0, MEM_RELEASE) == 0);if (err) { errcode = GetLastError(); }@@ -203,7 +251,7 @@ static void* win_virtual_alloc_prim_once(void* addr, size_t size, size_t try_ali}#endif// on modern Windows try use VirtualAlloc2 for aligned allocation- if (addr == NULL && try_alignment > 1 && (try_alignment % _mi_os_page_size()) == 0 && pVirtualAlloc2 != NULL) {+ if (addr == NULL && try_alignment > win_allocation_granularity && (try_alignment % _mi_os_page_size()) == 0 && pVirtualAlloc2 != NULL) {MI_MEM_ADDRESS_REQUIREMENTS reqs = { 0, 0, 0 };reqs.Alignment = try_alignment;MI_MEM_EXTENDED_PARAMETER param = { {0, 0}, {0} };@@ -239,7 +287,7 @@ static void* win_virtual_alloc_prim(void* addr, size_t size, size_t try_alignmen// success, return the addressreturn p;}- else if (max_retry_msecs > 0 && (try_alignment <= 2*MI_SEGMENT_ALIGN) &&+ else if (max_retry_msecs > 0 && (try_alignment <= 8*MI_MiB) &&(flags&MEM_COMMIT) != 0 && (flags&MEM_LARGE_PAGES) == 0 &&win_is_out_of_memory_error(GetLastError())) {// if committing regular memory and being out-of-memory,@@ -263,8 +311,9 @@ static void* win_virtual_alloc(void* addr, size_t size, size_t try_alignment, DWstatic _Atomic(size_t) large_page_try_ok; // = 0;void* p = NULL;// Try to allocate large OS pages (2MiB) if allowed or required.- if ((large_only || _mi_os_use_large_page(size, try_alignment))- && allow_large && (flags&MEM_COMMIT)!=0 && (flags&MEM_RESERVE)!=0) {+ if ((large_only || (_mi_os_canuse_large_page(size, try_alignment) && mi_option_is_enabled(mi_option_allow_large_os_pages)))+ && allow_large && (flags&MEM_COMMIT)!=0 && (flags&MEM_RESERVE)!=0)+ {size_t try_ok = mi_atomic_load_acquire(&large_page_try_ok);if (!large_only && try_ok > 0) {// if a large page allocation fails, it seems the calls to VirtualAlloc get very expensive.@@ -344,6 +393,11 @@ int _mi_prim_reset(void* addr, size_t size) {return (p != NULL ? 0 : (int)GetLastError());}+int _mi_prim_reuse(void* addr, size_t size) {+ MI_UNUSED(addr); MI_UNUSED(size);+ return 0;+}+int _mi_prim_protect(void* addr, size_t size, bool protect) {DWORD oldprotect = 0;BOOL ok = VirtualProtect(addr, size, protect ? PAGE_NOACCESS : PAGE_READWRITE, &oldprotect);@@ -375,7 +429,7 @@ static void* _mi_prim_alloc_huge_os_pagesx(void* hint_addr, size_t size, int num}SIZE_T psize = size;void* base = hint_addr;- NTSTATUS err = (*pNtAllocateVirtualMemoryEx)(GetCurrentProcess(), &base, &psize, flags, PAGE_READWRITE, params, param_count);+ LONG err = (*pNtAllocateVirtualMemoryEx)(GetCurrentProcess(), &base, &psize, flags, PAGE_READWRITE, params, param_count);if (err == 0 && base != NULL) {return base;}@@ -429,9 +483,11 @@ size_t _mi_prim_numa_node(void) {size_t _mi_prim_numa_node_count(void) {ULONG numa_max = 0;- GetNumaHighestNodeNumber(&numa_max);+ if (pGetNumaHighestNodeNumber!=NULL) {+ (*pGetNumaHighestNodeNumber)(&numa_max);+ }// find the highest node number that has actual processors assigned to it. Issue #282- while(numa_max > 0) {+ while (numa_max > 0) {if (pGetNumaNodeProcessorMaskEx != NULL) {// Extended API is supportedGROUP_AFFINITY affinity;@@ -442,8 +498,10 @@ size_t _mi_prim_numa_node_count(void) {else {// Vista or earlier, use older API that is limited to 64 processors.ULONGLONG mask;- if (GetNumaNodeProcessorMask((UCHAR)numa_max, &mask)) {- if (mask != 0) break; // found the maximum non-empty node+ if (pGetNumaNodeProcessorMask != NULL) {+ if ((*pGetNumaNodeProcessorMask)((UCHAR)numa_max, &mask)) {+ if (mask != 0) break; // found the maximum non-empty node+ }};}// max node was invalid or had no processor assigned, try again@@ -533,17 +591,21 @@ void _mi_prim_out_stderr( const char* msg )if (!_mi_preloading()) {// _cputs(msg); // _cputs cannot be used as it aborts when failing to lock the consolestatic HANDLE hcon = INVALID_HANDLE_VALUE;- static bool hconIsConsole;+ static bool hconIsConsole = false;if (hcon == INVALID_HANDLE_VALUE) {- CONSOLE_SCREEN_BUFFER_INFO sbi;hcon = GetStdHandle(STD_ERROR_HANDLE);+ #ifdef MI_HAS_CONSOLE_IO+ CONSOLE_SCREEN_BUFFER_INFO sbi;hconIsConsole = ((hcon != INVALID_HANDLE_VALUE) && GetConsoleScreenBufferInfo(hcon, &sbi));+ #endif}const size_t len = _mi_strlen(msg);if (len > 0 && len < UINT32_MAX) {DWORD written = 0;if (hconIsConsole) {+ #ifdef MI_HAS_CONSOLE_IOWriteConsoleA(hcon, msg, (DWORD)len, &written, NULL);+ #endif}else if (hcon != INVALID_HANDLE_VALUE) {// use direct write if stderr was redirected@@ -614,28 +676,73 @@ bool _mi_prim_random_buf(void* buf, size_t buf_len) {#endif // MI_USE_RTLGENRANDOM+//----------------------------------------------------------------+// Thread pool?+//----------------------------------------------------------------++bool _mi_prim_thread_is_in_threadpool(void) {+#if (MI_ARCH_X64 || MI_ARCH_X86 || MI_ARCH_ARM64)+ if (win_major_version >= 6) {+ // check if this thread belongs to a windows threadpool+ // see: <https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/pebteb/teb/index.htm>+ struct _TEB* const teb = NtCurrentTeb();+ void* const pool_data = *((void**)((uint8_t*)teb + (MI_SIZE_BITS == 32 ? 0x0F90 : 0x1778)));+ return (pool_data != NULL);+ }+#endif+ return false;+}+//----------------------------------------------------------------// Process & Thread Init/Done//----------------------------------------------------------------+#if MI_WIN_USE_FIXED_TLS==1+mi_decl_cache_align size_t _mi_win_tls_offset = 0;+#endif++//static void mi_debug_out(const char* s) {+// HANDLE h = GetStdHandle(STD_ERROR_HANDLE);+// WriteConsole(h, s, (DWORD)_mi_strlen(s), NULL, NULL);+//}++static void mi_win_tls_init(DWORD reason) {+ if (reason==DLL_PROCESS_ATTACH || reason==DLL_THREAD_ATTACH) {+ #if MI_WIN_USE_FIXED_TLS==1 // we must allocate a TLS slot dynamically+ if (_mi_win_tls_offset == 0 && reason == DLL_PROCESS_ATTACH) {+ const DWORD tls_slot = TlsAlloc(); // usually returns slot 1+ if (tls_slot == TLS_OUT_OF_INDEXES) {+ _mi_error_message(EFAULT, "unable to allocate the a TLS slot (rebuild without MI_WIN_USE_FIXED_TLS?)\n");+ }+ _mi_win_tls_offset = (size_t)tls_slot * sizeof(void*);+ }+ #endif+ #if MI_HAS_TLS_SLOT >= 2 // we must initialize the TLS slot before any allocation+ if (_mi_theap_default() == NULL) {+ _mi_theap_default_set((mi_theap_t*)&_mi_theap_empty);+ #if MI_DEBUG && MI_WIN_USE_FIXED_TLS==1+ void* const p = TlsGetValue((DWORD)(_mi_win_tls_offset / sizeof(void*)));+ mi_assert_internal(p == (void*)&_mi_theap_empty);+ #endif+ }+ #endif+ }+}+static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {MI_UNUSED(reserved);MI_UNUSED(module);- #if MI_TLS_SLOT >= 2- if ((reason==DLL_PROCESS_ATTACH || reason==DLL_THREAD_ATTACH) && mi_prim_get_default_heap() == NULL) {- _mi_heap_set_default_direct((mi_heap_t*)&_mi_heap_empty);- }- #endif+ mi_win_tls_init(reason);if (reason==DLL_PROCESS_ATTACH) {- _mi_process_load();+ _mi_auto_process_init();}else if (reason==DLL_PROCESS_DETACH) {- _mi_process_done();+ _mi_auto_process_done();}else if (reason==DLL_THREAD_DETACH && !_mi_is_redirected()) {_mi_thread_done(NULL);- }+ }}@@ -643,7 +750,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {#define MI_PRIM_HAS_PROCESS_ATTACH 1// Windows DLL: easy to hook into process_init and thread_done- __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID reserved) {+ BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID reserved) {mi_win_main((PVOID)inst,reason,reserved);return TRUE;}@@ -651,8 +758,8 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {// nothing to do since `_mi_thread_done` is handled through the DLL_THREAD_DETACH event.void _mi_prim_thread_init_auto_done(void) { }void _mi_prim_thread_done_auto_done(void) { }- void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {- MI_UNUSED(heap);+ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);}#elif !defined(MI_WIN_USE_FLS)@@ -708,8 +815,8 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {// nothing to do since `_mi_thread_done` is handled through the DLL_THREAD_DETACH event.void _mi_prim_thread_init_auto_done(void) { }void _mi_prim_thread_done_auto_done(void) { }- void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {- MI_UNUSED(heap);+ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {+ MI_UNUSED(theap);}#else // deprecated: statically linked, use fiber api@@ -721,7 +828,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {static int mi_process_attach(void) {mi_win_main(NULL,DLL_PROCESS_ATTACH,NULL);- atexit(&_mi_process_done);+ atexit(&_mi_auto_process_done);return 0;}typedef int(*mi_crt_callback_t)(void);@@ -748,10 +855,10 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {static DWORD mi_fls_key = (DWORD)(-1);static void NTAPI mi_fls_done(PVOID value) {- mi_heap_t* heap = (mi_heap_t*)value;- if (heap != NULL) {- _mi_thread_done(heap);- FlsSetValue(mi_fls_key, NULL); // prevent recursion as _mi_thread_done may set it back to the main heap, issue #672+ mi_theap_t* theap = (mi_theap_t*)value;+ if (theap != NULL) {+ _mi_thread_done(theap);+ FlsSetValue(mi_fls_key, NULL); // prevent recursion as _mi_thread_done may set it back to the main theap, issue #672}}@@ -765,9 +872,9 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {FlsFree(mi_fls_key);}- void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {+ void _mi_prim_thread_associate_default_theap(mi_theap_t* theap) {mi_assert_internal(mi_fls_key != (DWORD)(-1));- FlsSetValue(mi_fls_key, heap);+ FlsSetValue(mi_fls_key, theap);}#endif@@ -788,11 +895,7 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {#endifmi_decl_export void _mi_redirect_entry(DWORD reason) {// called on redirection; careful as this may be called before DllMain- #if MI_TLS_SLOT >= 2- if ((reason==DLL_PROCESS_ATTACH || reason==DLL_THREAD_ATTACH) && mi_prim_get_default_heap() == NULL) {- _mi_heap_set_default_direct((mi_heap_t*)&_mi_heap_empty);- }- #endif+ mi_win_tls_init(reason);if (reason == DLL_PROCESS_ATTACH) {mi_redirected = true;}@@ -815,3 +918,4 @@ static void NTAPI mi_win_main(PVOID module, DWORD reason, LPVOID reserved) {mi_allocator_done();}#endif+diff --git a/vendored/mimalloc/src/random.c b/vendored/mimalloc/src/random.cindex 4fc8b2f8f..990e4894f 100644--- a/vendored/mimalloc/src/random.c+++ b/vendored/mimalloc/src/random.c@@ -7,7 +7,6 @@ terms of the MIT license. A copy of the license can be found in the file#include "mimalloc.h"#include "mimalloc/internal.h"#include "mimalloc/prim.h" // _mi_prim_random_buf-#include <string.h> // memset/* ----------------------------------------------------------------------------We use our own PRNG to keep predictable performance of random number generation@@ -33,15 +32,11 @@ The implementation uses regular C code which compiles very well on modern compil(gcc x64 has no register spills, and clang 6+ uses SSE instructions)-----------------------------------------------------------------------------*/-static inline uint32_t rotl(uint32_t x, uint32_t shift) {- return (x << shift) | (x >> (32 - shift));-}-static inline void qround(uint32_t x[16], size_t a, size_t b, size_t c, size_t d) {- x[a] += x[b]; x[d] = rotl(x[d] ^ x[a], 16);- x[c] += x[d]; x[b] = rotl(x[b] ^ x[c], 12);- x[a] += x[b]; x[d] = rotl(x[d] ^ x[a], 8);- x[c] += x[d]; x[b] = rotl(x[b] ^ x[c], 7);+ x[a] += x[b]; x[d] = mi_rotl32(x[d] ^ x[a], 16);+ x[c] += x[d]; x[b] = mi_rotl32(x[b] ^ x[c], 12);+ x[a] += x[b]; x[d] = mi_rotl32(x[d] ^ x[a], 8);+ x[c] += x[d]; x[b] = mi_rotl32(x[b] ^ x[c], 7);}static void chacha_block(mi_random_ctx_t* ctx)@@ -99,7 +94,7 @@ static void chacha_init(mi_random_ctx_t* ctx, const uint8_t key[32], uint64_t no// since we only use chacha for randomness (and not encryption) we// do not _need_ to read 32-bit values as little endian but we do anyways// just for being compatible :-)- memset(ctx, 0, sizeof(*ctx));+ _mi_memzero(ctx, sizeof(*ctx));for (size_t i = 0; i < 4; i++) {const uint8_t* sigma = (uint8_t*)"expand 32-byte k";ctx->input[i] = read32(sigma,i);@@ -114,7 +109,7 @@ static void chacha_init(mi_random_ctx_t* ctx, const uint8_t key[32], uint64_t no}static void chacha_split(mi_random_ctx_t* ctx, uint64_t nonce, mi_random_ctx_t* ctx_new) {- memset(ctx_new, 0, sizeof(*ctx_new));+ _mi_memzero(ctx_new, sizeof(*ctx_new));_mi_memcpy(ctx_new->input, ctx->input, sizeof(ctx_new->input));ctx_new->input[12] = 0;ctx_new->input[13] = 0;@@ -143,13 +138,17 @@ void _mi_random_split(mi_random_ctx_t* ctx, mi_random_ctx_t* ctx_new) {uintptr_t _mi_random_next(mi_random_ctx_t* ctx) {mi_assert_internal(mi_random_is_initialized(ctx));- #if MI_INTPTR_SIZE <= 4- return chacha_next32(ctx);- #elif MI_INTPTR_SIZE == 8- return (((uintptr_t)chacha_next32(ctx) << 32) | chacha_next32(ctx));- #else- # error "define mi_random_next for this platform"- #endif+ uintptr_t r;+ do {+ #if MI_INTPTR_SIZE <= 4+ r = chacha_next32(ctx);+ #elif MI_INTPTR_SIZE == 8+ r = (((uintptr_t)chacha_next32(ctx) << 32) | chacha_next32(ctx));+ #else+ # error "define mi_random_next for this platform"+ #endif+ } while (r==0);+ return r;}@@ -160,10 +159,10 @@ If we cannot get good randomness, we fall back to weak randomness based on a timuintptr_t _mi_os_random_weak(uintptr_t extra_seed) {uintptr_t x = (uintptr_t)&_mi_os_random_weak ^ extra_seed; // ASLR makes the address random- x ^= _mi_prim_clock_now();+ x ^= _mi_prim_clock_now();// and do a few randomization stepsuintptr_t max = ((x ^ (x >> 17)) & 0x0F) + 1;- for (uintptr_t i = 0; i < max; i++) {+ for (uintptr_t i = 0; i < max || x==0; i++, x++) {x = _mi_random_shuffle(x);}mi_assert_internal(x != 0);@@ -179,7 +178,7 @@ static void mi_random_init_ex(mi_random_ctx_t* ctx, bool use_weak) {if (!use_weak) { _mi_warning_message("unable to use secure randomness\n"); }#endifuintptr_t x = _mi_os_random_weak(0);- for (size_t i = 0; i < 8; i++) { // key is eight 32-bit words.+ for (size_t i = 0; i < 8; i++, x++) { // key is eight 32-bit words.x = _mi_random_shuffle(x);((uint32_t*)key)[i] = (uint32_t)x;}diff --git a/vendored/mimalloc/src/segment-map.c b/vendored/mimalloc/src/segment-map.cdeleted file mode 100644index 5809342cf..000000000--- a/vendored/mimalloc/src/segment-map.c+++ /dev/null@@ -1,136 +0,0 @@-/* -----------------------------------------------------------------------------Copyright (c) 2019-2023, 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.------------------------------------------------------------------------------*/--/* ------------------------------------------------------------ The following functions are to reliably find the segment or- block that encompasses any pointer p (or NULL if it is not- in any of our segments).- We maintain a bitmap of all memory with 1 bit per MI_SEGMENT_SIZE (64MiB)- set to 1 if it contains the segment meta data.------------------------------------------------------------ */-#include "mimalloc.h"-#include "mimalloc/internal.h"-#include "mimalloc/atomic.h"--// Reduce total address space to reduce .bss (due to the `mi_segment_map`)-#if (MI_INTPTR_SIZE > 4) && MI_TRACK_ASAN-#define MI_SEGMENT_MAP_MAX_ADDRESS (128*1024ULL*MI_GiB) // 128 TiB (see issue #881)-#elif (MI_INTPTR_SIZE > 4)-#define MI_SEGMENT_MAP_MAX_ADDRESS (48*1024ULL*MI_GiB) // 48 TiB-#else-#define MI_SEGMENT_MAP_MAX_ADDRESS (UINT32_MAX)-#endif--#define MI_SEGMENT_MAP_PART_SIZE (MI_INTPTR_SIZE*MI_KiB - 128) // 128 > sizeof(mi_memid_t) !-#define MI_SEGMENT_MAP_PART_BITS (8*MI_SEGMENT_MAP_PART_SIZE)-#define MI_SEGMENT_MAP_PART_ENTRIES (MI_SEGMENT_MAP_PART_SIZE / MI_INTPTR_SIZE)-#define MI_SEGMENT_MAP_PART_BIT_SPAN (MI_SEGMENT_ALIGN)-#define MI_SEGMENT_MAP_PART_SPAN (MI_SEGMENT_MAP_PART_BITS * MI_SEGMENT_MAP_PART_BIT_SPAN)-#define MI_SEGMENT_MAP_MAX_PARTS ((MI_SEGMENT_MAP_MAX_ADDRESS / MI_SEGMENT_MAP_PART_SPAN) + 1)--// A part of the segment map.-typedef struct mi_segmap_part_s {- mi_memid_t memid;- _Atomic(uintptr_t) map[MI_SEGMENT_MAP_PART_ENTRIES];-} mi_segmap_part_t;--// Allocate parts on-demand to reduce .bss footprint-static _Atomic(mi_segmap_part_t*) mi_segment_map[MI_SEGMENT_MAP_MAX_PARTS]; // = { NULL, .. }--static mi_segmap_part_t* mi_segment_map_index_of(const mi_segment_t* segment, bool create_on_demand, size_t* idx, size_t* bitidx) {- // note: segment can be invalid or NULL.- mi_assert_internal(_mi_ptr_segment(segment + 1) == segment); // is it aligned on MI_SEGMENT_SIZE?- *idx = 0;- *bitidx = 0;- if ((uintptr_t)segment >= MI_SEGMENT_MAP_MAX_ADDRESS) return NULL;- const uintptr_t segindex = ((uintptr_t)segment) / MI_SEGMENT_MAP_PART_SPAN;- if (segindex >= MI_SEGMENT_MAP_MAX_PARTS) return NULL;- mi_segmap_part_t* part = mi_atomic_load_ptr_relaxed(mi_segmap_part_t, &mi_segment_map[segindex]);-- // allocate on demand to reduce .bss footprint- if (part == NULL) {- if (!create_on_demand) return NULL;- mi_memid_t memid;- part = (mi_segmap_part_t*)_mi_os_alloc(sizeof(mi_segmap_part_t), &memid);- if (part == NULL) return NULL;- part->memid = memid;- mi_segmap_part_t* expected = NULL;- if (!mi_atomic_cas_ptr_strong_release(mi_segmap_part_t, &mi_segment_map[segindex], &expected, part)) {- _mi_os_free(part, sizeof(mi_segmap_part_t), memid);- part = expected;- if (part == NULL) return NULL;- }- }- mi_assert(part != NULL);- const uintptr_t offset = ((uintptr_t)segment) % MI_SEGMENT_MAP_PART_SPAN;- const uintptr_t bitofs = offset / MI_SEGMENT_MAP_PART_BIT_SPAN;- *idx = bitofs / MI_INTPTR_BITS;- *bitidx = bitofs % MI_INTPTR_BITS;- return part;-}--void _mi_segment_map_allocated_at(const mi_segment_t* segment) {- if (segment->memid.memkind == MI_MEM_ARENA) return; // we lookup segments first in the arena's and don't need the segment map- size_t index;- size_t bitidx;- mi_segmap_part_t* part = mi_segment_map_index_of(segment, true /* alloc map if needed */, &index, &bitidx);- if (part == NULL) return; // outside our address range..- uintptr_t mask = mi_atomic_load_relaxed(&part->map[index]);- uintptr_t newmask;- do {- newmask = (mask | ((uintptr_t)1 << bitidx));- } while (!mi_atomic_cas_weak_release(&part->map[index], &mask, newmask));-}--void _mi_segment_map_freed_at(const mi_segment_t* segment) {- if (segment->memid.memkind == MI_MEM_ARENA) return;- size_t index;- size_t bitidx;- mi_segmap_part_t* part = mi_segment_map_index_of(segment, false /* don't alloc if not present */, &index, &bitidx);- if (part == NULL) return; // outside our address range..- uintptr_t mask = mi_atomic_load_relaxed(&part->map[index]);- uintptr_t newmask;- do {- newmask = (mask & ~((uintptr_t)1 << bitidx));- } while (!mi_atomic_cas_weak_release(&part->map[index], &mask, newmask));-}--// Determine the segment belonging to a pointer or NULL if it is not in a valid segment.-static mi_segment_t* _mi_segment_of(const void* p) {- if (p == NULL) return NULL;- mi_segment_t* segment = _mi_ptr_segment(p); // segment can be NULL- size_t index;- size_t bitidx;- mi_segmap_part_t* part = mi_segment_map_index_of(segment, false /* dont alloc if not present */, &index, &bitidx);- if (part == NULL) return NULL;- const uintptr_t mask = mi_atomic_load_relaxed(&part->map[index]);- if mi_likely((mask & ((uintptr_t)1 << bitidx)) != 0) {- bool cookie_ok = (_mi_ptr_cookie(segment) == segment->cookie);- mi_assert_internal(cookie_ok); MI_UNUSED(cookie_ok);- return segment; // yes, allocated by us- }- return NULL;-}--// Is this a valid pointer in our heap?-static bool mi_is_valid_pointer(const void* p) {- // first check if it is in an arena, then check if it is OS allocated- return (_mi_arena_contains(p) || _mi_segment_of(p) != NULL);-}--mi_decl_nodiscard mi_decl_export bool mi_is_in_heap_region(const void* p) mi_attr_noexcept {- return mi_is_valid_pointer(p);-}--void _mi_segment_map_unsafe_destroy(void) {- for (size_t i = 0; i < MI_SEGMENT_MAP_MAX_PARTS; i++) {- mi_segmap_part_t* part = mi_atomic_exchange_ptr_relaxed(mi_segmap_part_t, &mi_segment_map[i], NULL);- if (part != NULL) {- _mi_os_free(part, sizeof(mi_segmap_part_t), part->memid);- }- }-}diff --git a/vendored/mimalloc/src/segment.c b/vendored/mimalloc/src/segment.cdeleted file mode 100644index 2c0b9ec31..000000000--- a/vendored/mimalloc/src/segment.c+++ /dev/null@@ -1,1700 +0,0 @@-/* -----------------------------------------------------------------------------Copyright (c) 2018-2024, 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.------------------------------------------------------------------------------*/-#include "mimalloc.h"-#include "mimalloc/internal.h"-#include "mimalloc/atomic.h"--#include <string.h> // memset-#include <stdio.h>--// --------------------------------------------------------------------// Segments-// mimalloc pages reside in segments. See `mi_segment_valid` for invariants.-// ----------------------------------------------------------------------static void mi_segment_try_purge(mi_segment_t* segment, bool force);---// --------------------------------------------------------------------// commit mask-// ---------------------------------------------------------------------static bool mi_commit_mask_all_set(const mi_commit_mask_t* commit, const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- if ((commit->mask[i] & cm->mask[i]) != cm->mask[i]) return false;- }- return true;-}--static bool mi_commit_mask_any_set(const mi_commit_mask_t* commit, const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- if ((commit->mask[i] & cm->mask[i]) != 0) return true;- }- return false;-}--static void mi_commit_mask_create_intersect(const mi_commit_mask_t* commit, const mi_commit_mask_t* cm, mi_commit_mask_t* res) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- res->mask[i] = (commit->mask[i] & cm->mask[i]);- }-}--static void mi_commit_mask_clear(mi_commit_mask_t* res, const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- res->mask[i] &= ~(cm->mask[i]);- }-}--static void mi_commit_mask_set(mi_commit_mask_t* res, const mi_commit_mask_t* cm) {- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- res->mask[i] |= cm->mask[i];- }-}--static void mi_commit_mask_create(size_t bitidx, size_t bitcount, mi_commit_mask_t* cm) {- mi_assert_internal(bitidx < MI_COMMIT_MASK_BITS);- mi_assert_internal((bitidx + bitcount) <= MI_COMMIT_MASK_BITS);- if (bitcount == MI_COMMIT_MASK_BITS) {- mi_assert_internal(bitidx==0);- mi_commit_mask_create_full(cm);- }- else if (bitcount == 0) {- mi_commit_mask_create_empty(cm);- }- else {- mi_commit_mask_create_empty(cm);- size_t i = bitidx / MI_COMMIT_MASK_FIELD_BITS;- size_t ofs = bitidx % MI_COMMIT_MASK_FIELD_BITS;- while (bitcount > 0) {- mi_assert_internal(i < MI_COMMIT_MASK_FIELD_COUNT);- size_t avail = MI_COMMIT_MASK_FIELD_BITS - ofs;- size_t count = (bitcount > avail ? avail : bitcount);- size_t mask = (count >= MI_COMMIT_MASK_FIELD_BITS ? ~((size_t)0) : (((size_t)1 << count) - 1) << ofs);- cm->mask[i] = mask;- bitcount -= count;- ofs = 0;- i++;- }- }-}--size_t _mi_commit_mask_committed_size(const mi_commit_mask_t* cm, size_t total) {- mi_assert_internal((total%MI_COMMIT_MASK_BITS)==0);- size_t count = 0;- for (size_t i = 0; i < MI_COMMIT_MASK_FIELD_COUNT; i++) {- size_t mask = cm->mask[i];- if (~mask == 0) {- count += MI_COMMIT_MASK_FIELD_BITS;- }- else {- for (; mask != 0; mask >>= 1) { // todo: use popcount- if ((mask&1)!=0) count++;- }- }- }- // we use total since for huge segments each commit bit may represent a larger size- return ((total / MI_COMMIT_MASK_BITS) * count);-}---size_t _mi_commit_mask_next_run(const mi_commit_mask_t* cm, size_t* idx) {- size_t i = (*idx) / MI_COMMIT_MASK_FIELD_BITS;- size_t ofs = (*idx) % MI_COMMIT_MASK_FIELD_BITS;- size_t mask = 0;- // find first ones- while (i < MI_COMMIT_MASK_FIELD_COUNT) {- mask = cm->mask[i];- mask >>= ofs;- if (mask != 0) {- while ((mask&1) == 0) {- mask >>= 1;- ofs++;- }- break;- }- i++;- ofs = 0;- }- if (i >= MI_COMMIT_MASK_FIELD_COUNT) {- // not found- *idx = MI_COMMIT_MASK_BITS;- return 0;- }- else {- // found, count ones- size_t count = 0;- *idx = (i*MI_COMMIT_MASK_FIELD_BITS) + ofs;- do {- mi_assert_internal(ofs < MI_COMMIT_MASK_FIELD_BITS && (mask&1) == 1);- do {- count++;- mask >>= 1;- } while ((mask&1) == 1);- if ((((*idx + count) % MI_COMMIT_MASK_FIELD_BITS) == 0)) {- i++;- if (i >= MI_COMMIT_MASK_FIELD_COUNT) break;- mask = cm->mask[i];- ofs = 0;- }- } while ((mask&1) == 1);- mi_assert_internal(count > 0);- return count;- }-}---/* --------------------------------------------------------------------------------- Segment allocation- We allocate pages inside bigger "segments" (32 MiB on 64-bit). This is to avoid- splitting VMA's on Linux and reduce fragmentation on other OS's.- Each thread owns its own segments.-- Currently we have:- - small pages (64KiB)- - medium pages (512KiB)- - large pages (4MiB),- - huge segments have 1 page in one segment that can be larger than `MI_SEGMENT_SIZE`.- it is used for blocks `> MI_LARGE_OBJ_SIZE_MAX` or with alignment `> MI_BLOCK_ALIGNMENT_MAX`.-- The memory for a segment is usually committed on demand.- (i.e. we are careful to not touch the memory until we actually allocate a block there)-- If a thread ends, it "abandons" pages that still contain live blocks.- Such segments are abandoned and these can be reclaimed by still running threads,- (much like work-stealing).--------------------------------------------------------------------------------- */---/* ------------------------------------------------------------ Slices------------------------------------------------------------ */---static const mi_slice_t* mi_segment_slices_end(const mi_segment_t* segment) {- return &segment->slices[segment->slice_entries];-}--static uint8_t* mi_slice_start(const mi_slice_t* slice) {- mi_segment_t* segment = _mi_ptr_segment(slice);- mi_assert_internal(slice >= segment->slices && slice < mi_segment_slices_end(segment));- return ((uint8_t*)segment + ((slice - segment->slices)*MI_SEGMENT_SLICE_SIZE));-}---/* ------------------------------------------------------------ Bins------------------------------------------------------------ */-// Use bit scan forward to quickly find the first zero bit if it is available--static inline size_t mi_slice_bin8(size_t slice_count) {- if (slice_count<=1) return slice_count;- mi_assert_internal(slice_count <= MI_SLICES_PER_SEGMENT);- slice_count--;- size_t s = mi_bsr(slice_count); // slice_count > 1- if (s <= 2) return slice_count + 1;- size_t bin = ((s << 2) | ((slice_count >> (s - 2))&0x03)) - 4;- return bin;-}--static inline size_t mi_slice_bin(size_t slice_count) {- mi_assert_internal(slice_count*MI_SEGMENT_SLICE_SIZE <= MI_SEGMENT_SIZE);- mi_assert_internal(mi_slice_bin8(MI_SLICES_PER_SEGMENT) <= MI_SEGMENT_BIN_MAX);- size_t bin = mi_slice_bin8(slice_count);- mi_assert_internal(bin <= MI_SEGMENT_BIN_MAX);- return bin;-}--static inline size_t mi_slice_index(const mi_slice_t* slice) {- mi_segment_t* segment = _mi_ptr_segment(slice);- ptrdiff_t index = slice - segment->slices;- mi_assert_internal(index >= 0 && index < (ptrdiff_t)segment->slice_entries);- return index;-}---/* ------------------------------------------------------------ Slice span queues------------------------------------------------------------ */--static void mi_span_queue_push(mi_span_queue_t* sq, mi_slice_t* slice) {- // todo: or push to the end?- mi_assert_internal(slice->prev == NULL && slice->next==NULL);- slice->prev = NULL; // paranoia- slice->next = sq->first;- sq->first = slice;- if (slice->next != NULL) slice->next->prev = slice;- else sq->last = slice;- slice->block_size = 0; // free-}--static mi_span_queue_t* mi_span_queue_for(size_t slice_count, mi_segments_tld_t* tld) {- size_t bin = mi_slice_bin(slice_count);- mi_span_queue_t* sq = &tld->spans[bin];- mi_assert_internal(sq->slice_count >= slice_count);- return sq;-}--static void mi_span_queue_delete(mi_span_queue_t* sq, mi_slice_t* slice) {- mi_assert_internal(slice->block_size==0 && slice->slice_count>0 && slice->slice_offset==0);- // should work too if the queue does not contain slice (which can happen during reclaim)- if (slice->prev != NULL) slice->prev->next = slice->next;- if (slice == sq->first) sq->first = slice->next;- if (slice->next != NULL) slice->next->prev = slice->prev;- if (slice == sq->last) sq->last = slice->prev;- slice->prev = NULL;- slice->next = NULL;- slice->block_size = 1; // no more free-}---/* ------------------------------------------------------------ Invariant checking------------------------------------------------------------ */--static bool mi_slice_is_used(const mi_slice_t* slice) {- return (slice->block_size > 0);-}---#if (MI_DEBUG>=3)-static bool mi_span_queue_contains(mi_span_queue_t* sq, mi_slice_t* slice) {- for (mi_slice_t* s = sq->first; s != NULL; s = s->next) {- if (s==slice) return true;- }- return false;-}--static bool mi_segment_is_valid(mi_segment_t* segment, mi_segments_tld_t* tld) {- mi_assert_internal(segment != NULL);- mi_assert_internal(_mi_ptr_cookie(segment) == segment->cookie);- mi_assert_internal(segment->abandoned <= segment->used);- mi_assert_internal(segment->thread_id == 0 || segment->thread_id == _mi_thread_id());- mi_assert_internal(mi_commit_mask_all_set(&segment->commit_mask, &segment->purge_mask)); // can only decommit committed blocks- //mi_assert_internal(segment->segment_info_size % MI_SEGMENT_SLICE_SIZE == 0);- mi_slice_t* slice = &segment->slices[0];- const mi_slice_t* end = mi_segment_slices_end(segment);- size_t used_count = 0;- mi_span_queue_t* sq;- while(slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- size_t index = mi_slice_index(slice);- size_t maxindex = (index + slice->slice_count >= segment->slice_entries ? segment->slice_entries : index + slice->slice_count) - 1;- if (mi_slice_is_used(slice)) { // a page in use, we need at least MAX_SLICE_OFFSET_COUNT valid back offsets- used_count++;- mi_assert_internal(slice->is_huge == (segment->kind == MI_SEGMENT_HUGE));- for (size_t i = 0; i <= MI_MAX_SLICE_OFFSET_COUNT && index + i <= maxindex; i++) {- mi_assert_internal(segment->slices[index + i].slice_offset == i*sizeof(mi_slice_t));- mi_assert_internal(i==0 || segment->slices[index + i].slice_count == 0);- mi_assert_internal(i==0 || segment->slices[index + i].block_size == 1);- }- // and the last entry as well (for coalescing)- const mi_slice_t* last = slice + slice->slice_count - 1;- if (last > slice && last < mi_segment_slices_end(segment)) {- mi_assert_internal(last->slice_offset == (slice->slice_count-1)*sizeof(mi_slice_t));- mi_assert_internal(last->slice_count == 0);- mi_assert_internal(last->block_size == 1);- }- }- else { // free range of slices; only last slice needs a valid back offset- mi_slice_t* last = &segment->slices[maxindex];- if (segment->kind != MI_SEGMENT_HUGE || slice->slice_count <= (segment->slice_entries - segment->segment_info_slices)) {- mi_assert_internal((uint8_t*)slice == (uint8_t*)last - last->slice_offset);- }- mi_assert_internal(slice == last || last->slice_count == 0 );- mi_assert_internal(last->block_size == 0 || (segment->kind==MI_SEGMENT_HUGE && last->block_size==1));- if (segment->kind != MI_SEGMENT_HUGE && segment->thread_id != 0) { // segment is not huge or abandoned- sq = mi_span_queue_for(slice->slice_count,tld);- mi_assert_internal(mi_span_queue_contains(sq,slice));- }- }- slice = &segment->slices[maxindex+1];- }- mi_assert_internal(slice == end);- mi_assert_internal(used_count == segment->used + 1);- return true;-}-#endif--/* ------------------------------------------------------------ Segment size calculations------------------------------------------------------------ */--static size_t mi_segment_info_size(mi_segment_t* segment) {- return segment->segment_info_slices * MI_SEGMENT_SLICE_SIZE;-}--static uint8_t* _mi_segment_page_start_from_slice(const mi_segment_t* segment, const mi_slice_t* slice, size_t block_size, size_t* page_size)-{- const ptrdiff_t idx = slice - segment->slices;- const size_t psize = (size_t)slice->slice_count * MI_SEGMENT_SLICE_SIZE;- uint8_t* const pstart = (uint8_t*)segment + (idx*MI_SEGMENT_SLICE_SIZE);- // make the start not OS page aligned for smaller blocks to avoid page/cache effects- // note: the offset must always be a block_size multiple since we assume small allocations- // are aligned (see `mi_heap_malloc_aligned`).- size_t start_offset = 0;- if (block_size > 0 && block_size <= MI_MAX_ALIGN_GUARANTEE) {- // for small objects, ensure the page start is aligned with the block size (PR#66 by kickunderscore)- const size_t adjust = block_size - ((uintptr_t)pstart % block_size);- if (adjust < block_size && psize >= block_size + adjust) {- start_offset += adjust;- }- }- if (block_size >= MI_INTPTR_SIZE) {- if (block_size <= 64) { start_offset += 3*block_size; }- else if (block_size <= 512) { start_offset += block_size; }- }- start_offset = _mi_align_up(start_offset, MI_MAX_ALIGN_SIZE);- mi_assert_internal(_mi_is_aligned(pstart + start_offset, MI_MAX_ALIGN_SIZE));- mi_assert_internal(block_size == 0 || block_size > MI_MAX_ALIGN_GUARANTEE || _mi_is_aligned(pstart + start_offset,block_size));- if (page_size != NULL) { *page_size = psize - start_offset; }- return (pstart + start_offset);-}--// Start of the page available memory; can be used on uninitialized pages-uint8_t* _mi_segment_page_start(const mi_segment_t* segment, const mi_page_t* page, size_t* page_size)-{- const mi_slice_t* slice = mi_page_to_slice((mi_page_t*)page);- uint8_t* p = _mi_segment_page_start_from_slice(segment, slice, mi_page_block_size(page), page_size);- mi_assert_internal(mi_page_block_size(page) > 0 || _mi_ptr_page(p) == page);- mi_assert_internal(_mi_ptr_segment(p) == segment);- return p;-}---static size_t mi_segment_calculate_slices(size_t required, size_t* info_slices) {- size_t page_size = _mi_os_page_size();- size_t isize = _mi_align_up(sizeof(mi_segment_t), page_size);- size_t guardsize = 0;-- if (MI_SECURE>0) {- // in secure mode, we set up a protected page in between the segment info- // and the page data (and one at the end of the segment)- guardsize = page_size;- if (required > 0) {- required = _mi_align_up(required, MI_SEGMENT_SLICE_SIZE) + page_size;- }- }-- isize = _mi_align_up(isize + guardsize, MI_SEGMENT_SLICE_SIZE);- if (info_slices != NULL) *info_slices = isize / MI_SEGMENT_SLICE_SIZE;- size_t segment_size = (required==0 ? MI_SEGMENT_SIZE : _mi_align_up( required + isize + guardsize, MI_SEGMENT_SLICE_SIZE) );- mi_assert_internal(segment_size % MI_SEGMENT_SLICE_SIZE == 0);- return (segment_size / MI_SEGMENT_SLICE_SIZE);-}---/* -----------------------------------------------------------------------------Segment caches-We keep a small segment cache per thread to increase local-reuse and avoid setting/clearing guard pages in secure mode.-------------------------------------------------------------------------------- */--static void mi_segments_track_size(long segment_size, mi_segments_tld_t* tld) {- if (segment_size>=0) _mi_stat_increase(&tld->stats->segments,1);- else _mi_stat_decrease(&tld->stats->segments,1);- tld->count += (segment_size >= 0 ? 1 : -1);- if (tld->count > tld->peak_count) tld->peak_count = tld->count;- tld->current_size += segment_size;- if (tld->current_size > tld->peak_size) tld->peak_size = tld->current_size;-}--static void mi_segment_os_free(mi_segment_t* segment, mi_segments_tld_t* tld) {- segment->thread_id = 0;- _mi_segment_map_freed_at(segment);- mi_segments_track_size(-((long)mi_segment_size(segment)),tld);- if (segment->was_reclaimed) {- tld->reclaim_count--;- segment->was_reclaimed = false;- }- if (MI_SECURE>0) {- // _mi_os_unprotect(segment, mi_segment_size(segment)); // ensure no more guard pages are set- // unprotect the guard pages; we cannot just unprotect the whole segment size as part may be decommitted- size_t os_pagesize = _mi_os_page_size();- _mi_os_unprotect((uint8_t*)segment + mi_segment_info_size(segment) - os_pagesize, os_pagesize);- uint8_t* end = (uint8_t*)segment + mi_segment_size(segment) - os_pagesize;- _mi_os_unprotect(end, os_pagesize);- }-- // purge delayed decommits now? (no, leave it to the arena)- // mi_segment_try_purge(segment,true,tld->stats);-- const size_t size = mi_segment_size(segment);- const size_t csize = _mi_commit_mask_committed_size(&segment->commit_mask, size);-- _mi_arena_free(segment, mi_segment_size(segment), csize, segment->memid);-}--/* ------------------------------------------------------------ Commit/Decommit ranges------------------------------------------------------------ */--static void mi_segment_commit_mask(mi_segment_t* segment, bool conservative, uint8_t* p, size_t size, uint8_t** start_p, size_t* full_size, mi_commit_mask_t* cm) {- mi_assert_internal(_mi_ptr_segment(p + 1) == segment);- mi_assert_internal(segment->kind != MI_SEGMENT_HUGE);- mi_commit_mask_create_empty(cm);- if (size == 0 || size > MI_SEGMENT_SIZE || segment->kind == MI_SEGMENT_HUGE) return;- const size_t segstart = mi_segment_info_size(segment);- const size_t segsize = mi_segment_size(segment);- if (p >= (uint8_t*)segment + segsize) return;-- size_t pstart = (p - (uint8_t*)segment);- mi_assert_internal(pstart + size <= segsize);-- size_t start;- size_t end;- if (conservative) {- // decommit conservative- start = _mi_align_up(pstart, MI_COMMIT_SIZE);- end = _mi_align_down(pstart + size, MI_COMMIT_SIZE);- mi_assert_internal(start >= segstart);- mi_assert_internal(end <= segsize);- }- else {- // commit liberal- start = _mi_align_down(pstart, MI_MINIMAL_COMMIT_SIZE);- end = _mi_align_up(pstart + size, MI_MINIMAL_COMMIT_SIZE);- }- if (pstart >= segstart && start < segstart) { // note: the mask is also calculated for an initial commit of the info area- start = segstart;- }- if (end > segsize) {- end = segsize;- }-- mi_assert_internal(start <= pstart && (pstart + size) <= end);- mi_assert_internal(start % MI_COMMIT_SIZE==0 && end % MI_COMMIT_SIZE == 0);- *start_p = (uint8_t*)segment + start;- *full_size = (end > start ? end - start : 0);- if (*full_size == 0) return;-- size_t bitidx = start / MI_COMMIT_SIZE;- mi_assert_internal(bitidx < MI_COMMIT_MASK_BITS);-- size_t bitcount = *full_size / MI_COMMIT_SIZE; // can be 0- if (bitidx + bitcount > MI_COMMIT_MASK_BITS) {- _mi_warning_message("commit mask overflow: idx=%zu count=%zu start=%zx end=%zx p=0x%p size=%zu fullsize=%zu\n", bitidx, bitcount, start, end, p, size, *full_size);- }- mi_assert_internal((bitidx + bitcount) <= MI_COMMIT_MASK_BITS);- mi_commit_mask_create(bitidx, bitcount, cm);-}--static bool mi_segment_commit(mi_segment_t* segment, uint8_t* p, size_t size) {- mi_assert_internal(mi_commit_mask_all_set(&segment->commit_mask, &segment->purge_mask));-- // commit liberal- uint8_t* start = NULL;- size_t full_size = 0;- mi_commit_mask_t mask;- mi_segment_commit_mask(segment, false /* conservative? */, p, size, &start, &full_size, &mask);- if (mi_commit_mask_is_empty(&mask) || full_size == 0) return true;-- if (!mi_commit_mask_all_set(&segment->commit_mask, &mask)) {- // committing- bool is_zero = false;- mi_commit_mask_t cmask;- mi_commit_mask_create_intersect(&segment->commit_mask, &mask, &cmask);- _mi_stat_decrease(&_mi_stats_main.committed, _mi_commit_mask_committed_size(&cmask, MI_SEGMENT_SIZE)); // adjust for overlap- if (!_mi_os_commit(start, full_size, &is_zero)) return false;- mi_commit_mask_set(&segment->commit_mask, &mask);- }-- // increase purge expiration when using part of delayed purges -- we assume more allocations are coming soon.- if (mi_commit_mask_any_set(&segment->purge_mask, &mask)) {- segment->purge_expire = _mi_clock_now() + mi_option_get(mi_option_purge_delay);- }-- // always clear any delayed purges in our range (as they are either committed now)- mi_commit_mask_clear(&segment->purge_mask, &mask);- return true;-}--static bool mi_segment_ensure_committed(mi_segment_t* segment, uint8_t* p, size_t size) {- mi_assert_internal(mi_commit_mask_all_set(&segment->commit_mask, &segment->purge_mask));- // note: assumes commit_mask is always full for huge segments as otherwise the commit mask bits can overflow- if (mi_commit_mask_is_full(&segment->commit_mask) && mi_commit_mask_is_empty(&segment->purge_mask)) return true; // fully committed- mi_assert_internal(segment->kind != MI_SEGMENT_HUGE);- return mi_segment_commit(segment, p, size);-}--static bool mi_segment_purge(mi_segment_t* segment, uint8_t* p, size_t size) {- mi_assert_internal(mi_commit_mask_all_set(&segment->commit_mask, &segment->purge_mask));- if (!segment->allow_purge) return true;-- // purge conservative- uint8_t* start = NULL;- size_t full_size = 0;- mi_commit_mask_t mask;- mi_segment_commit_mask(segment, true /* conservative? */, p, size, &start, &full_size, &mask);- if (mi_commit_mask_is_empty(&mask) || full_size==0) return true;-- if (mi_commit_mask_any_set(&segment->commit_mask, &mask)) {- // purging- mi_assert_internal((void*)start != (void*)segment);- mi_assert_internal(segment->allow_decommit);- const bool decommitted = _mi_os_purge(start, full_size); // reset or decommit- if (decommitted) {- mi_commit_mask_t cmask;- mi_commit_mask_create_intersect(&segment->commit_mask, &mask, &cmask);- _mi_stat_increase(&_mi_stats_main.committed, full_size - _mi_commit_mask_committed_size(&cmask, MI_SEGMENT_SIZE)); // adjust for double counting- mi_commit_mask_clear(&segment->commit_mask, &mask);- }- }-- // always clear any scheduled purges in our range- mi_commit_mask_clear(&segment->purge_mask, &mask);- return true;-}--static void mi_segment_schedule_purge(mi_segment_t* segment, uint8_t* p, size_t size) {- if (!segment->allow_purge) return;-- if (mi_option_get(mi_option_purge_delay) == 0) {- mi_segment_purge(segment, p, size);- }- else {- // register for future purge in the purge mask- uint8_t* start = NULL;- size_t full_size = 0;- mi_commit_mask_t mask;- mi_segment_commit_mask(segment, true /*conservative*/, p, size, &start, &full_size, &mask);- if (mi_commit_mask_is_empty(&mask) || full_size==0) return;-- // update delayed commit- mi_assert_internal(segment->purge_expire > 0 || mi_commit_mask_is_empty(&segment->purge_mask));- mi_commit_mask_t cmask;- mi_commit_mask_create_intersect(&segment->commit_mask, &mask, &cmask); // only purge what is committed; span_free may try to decommit more- mi_commit_mask_set(&segment->purge_mask, &cmask);- mi_msecs_t now = _mi_clock_now();- if (segment->purge_expire == 0) {- // no previous purgess, initialize now- segment->purge_expire = now + mi_option_get(mi_option_purge_delay);- }- else if (segment->purge_expire <= now) {- // previous purge mask already expired- if (segment->purge_expire + mi_option_get(mi_option_purge_extend_delay) <= now) {- mi_segment_try_purge(segment, true);- }- else {- segment->purge_expire = now + mi_option_get(mi_option_purge_extend_delay); // (mi_option_get(mi_option_purge_delay) / 8); // wait a tiny bit longer in case there is a series of free's- }- }- else {- // previous purge mask is not yet expired, increase the expiration by a bit.- segment->purge_expire += mi_option_get(mi_option_purge_extend_delay);- }- }-}--static void mi_segment_try_purge(mi_segment_t* segment, bool force) {- if (!segment->allow_purge || segment->purge_expire == 0 || mi_commit_mask_is_empty(&segment->purge_mask)) return;- mi_msecs_t now = _mi_clock_now();- if (!force && now < segment->purge_expire) return;-- mi_commit_mask_t mask = segment->purge_mask;- segment->purge_expire = 0;- mi_commit_mask_create_empty(&segment->purge_mask);-- size_t idx;- size_t count;- mi_commit_mask_foreach(&mask, idx, count) {- // if found, decommit that sequence- if (count > 0) {- uint8_t* p = (uint8_t*)segment + (idx*MI_COMMIT_SIZE);- size_t size = count * MI_COMMIT_SIZE;- mi_segment_purge(segment, p, size);- }- }- mi_commit_mask_foreach_end()- mi_assert_internal(mi_commit_mask_is_empty(&segment->purge_mask));-}--// called from `mi_heap_collect_ex`-// this can be called per-page so it is important that try_purge has fast exit path-void _mi_segment_collect(mi_segment_t* segment, bool force) {- mi_segment_try_purge(segment, force);-}--/* ------------------------------------------------------------ Span free------------------------------------------------------------ */--static bool mi_segment_is_abandoned(mi_segment_t* segment) {- return (mi_atomic_load_relaxed(&segment->thread_id) == 0);-}--// note: can be called on abandoned segments-static void mi_segment_span_free(mi_segment_t* segment, size_t slice_index, size_t slice_count, bool allow_purge, mi_segments_tld_t* tld) {- mi_assert_internal(slice_index < segment->slice_entries);- mi_span_queue_t* sq = (segment->kind == MI_SEGMENT_HUGE || mi_segment_is_abandoned(segment)- ? NULL : mi_span_queue_for(slice_count,tld));- if (slice_count==0) slice_count = 1;- mi_assert_internal(slice_index + slice_count - 1 < segment->slice_entries);-- // set first and last slice (the intermediates can be undetermined)- mi_slice_t* slice = &segment->slices[slice_index];- slice->slice_count = (uint32_t)slice_count;- mi_assert_internal(slice->slice_count == slice_count); // no overflow?- slice->slice_offset = 0;- if (slice_count > 1) {- mi_slice_t* last = slice + slice_count - 1;- mi_slice_t* end = (mi_slice_t*)mi_segment_slices_end(segment);- if (last > end) { last = end; }- last->slice_count = 0;- last->slice_offset = (uint32_t)(sizeof(mi_page_t)*(slice_count - 1));- last->block_size = 0;- }-- // perhaps decommit- if (allow_purge) {- mi_segment_schedule_purge(segment, mi_slice_start(slice), slice_count * MI_SEGMENT_SLICE_SIZE);- }-- // and push it on the free page queue (if it was not a huge page)- if (sq != NULL) mi_span_queue_push( sq, slice );- else slice->block_size = 0; // mark huge page as free anyways-}--/*-// called from reclaim to add existing free spans-static void mi_segment_span_add_free(mi_slice_t* slice, mi_segments_tld_t* tld) {- mi_segment_t* segment = _mi_ptr_segment(slice);- mi_assert_internal(slice->xblock_size==0 && slice->slice_count>0 && slice->slice_offset==0);- size_t slice_index = mi_slice_index(slice);- mi_segment_span_free(segment,slice_index,slice->slice_count,tld);-}-*/--static void mi_segment_span_remove_from_queue(mi_slice_t* slice, mi_segments_tld_t* tld) {- mi_assert_internal(slice->slice_count > 0 && slice->slice_offset==0 && slice->block_size==0);- mi_assert_internal(_mi_ptr_segment(slice)->kind != MI_SEGMENT_HUGE);- mi_span_queue_t* sq = mi_span_queue_for(slice->slice_count, tld);- mi_span_queue_delete(sq, slice);-}--// note: can be called on abandoned segments-static mi_slice_t* mi_segment_span_free_coalesce(mi_slice_t* slice, mi_segments_tld_t* tld) {- mi_assert_internal(slice != NULL && slice->slice_count > 0 && slice->slice_offset == 0);- mi_segment_t* const segment = _mi_ptr_segment(slice);-- // for huge pages, just mark as free but don't add to the queues- if (segment->kind == MI_SEGMENT_HUGE) {- // issue #691: segment->used can be 0 if the huge page block was freed while abandoned (reclaim will get here in that case)- mi_assert_internal((segment->used==0 && slice->block_size==0) || segment->used == 1); // decreased right after this call in `mi_segment_page_clear`- slice->block_size = 0; // mark as free anyways- // we should mark the last slice `xblock_size=0` now to maintain invariants but we skip it to- // avoid a possible cache miss (and the segment is about to be freed)- return slice;- }-- // otherwise coalesce the span and add to the free span queues- const bool is_abandoned = (segment->thread_id == 0); // mi_segment_is_abandoned(segment);- size_t slice_count = slice->slice_count;- mi_slice_t* next = slice + slice->slice_count;- mi_assert_internal(next <= mi_segment_slices_end(segment));- if (next < mi_segment_slices_end(segment) && next->block_size==0) {- // free next block -- remove it from free and merge- mi_assert_internal(next->slice_count > 0 && next->slice_offset==0);- slice_count += next->slice_count; // extend- if (!is_abandoned) { mi_segment_span_remove_from_queue(next, tld); }- }- if (slice > segment->slices) {- mi_slice_t* prev = mi_slice_first(slice - 1);- mi_assert_internal(prev >= segment->slices);- if (prev->block_size==0) {- // free previous slice -- remove it from free and merge- mi_assert_internal(prev->slice_count > 0 && prev->slice_offset==0);- slice_count += prev->slice_count;- slice->slice_count = 0;- slice->slice_offset = (uint32_t)((uint8_t*)slice - (uint8_t*)prev); // set the slice offset for `segment_force_abandon` (in case the previous free block is very large).- if (!is_abandoned) { mi_segment_span_remove_from_queue(prev, tld); }- slice = prev;- }- }-- // and add the new free page- mi_segment_span_free(segment, mi_slice_index(slice), slice_count, true, tld);- return slice;-}----/* ------------------------------------------------------------ Page allocation------------------------------------------------------------ */--// Note: may still return NULL if committing the memory failed-static mi_page_t* mi_segment_span_allocate(mi_segment_t* segment, size_t slice_index, size_t slice_count) {- mi_assert_internal(slice_index < segment->slice_entries);- mi_slice_t* const slice = &segment->slices[slice_index];- mi_assert_internal(slice->block_size==0 || slice->block_size==1);-- // commit before changing the slice data- if (!mi_segment_ensure_committed(segment, _mi_segment_page_start_from_slice(segment, slice, 0, NULL), slice_count * MI_SEGMENT_SLICE_SIZE)) {- return NULL; // commit failed!- }-- // convert the slices to a page- slice->slice_offset = 0;- slice->slice_count = (uint32_t)slice_count;- mi_assert_internal(slice->slice_count == slice_count);- const size_t bsize = slice_count * MI_SEGMENT_SLICE_SIZE;- slice->block_size = bsize;- mi_page_t* page = mi_slice_to_page(slice);- mi_assert_internal(mi_page_block_size(page) == bsize);-- // set slice back pointers for the first MI_MAX_SLICE_OFFSET_COUNT entries- size_t extra = slice_count-1;- if (extra > MI_MAX_SLICE_OFFSET_COUNT) extra = MI_MAX_SLICE_OFFSET_COUNT;- if (slice_index + extra >= segment->slice_entries) extra = segment->slice_entries - slice_index - 1; // huge objects may have more slices than avaiable entries in the segment->slices-- mi_slice_t* slice_next = slice + 1;- for (size_t i = 1; i <= extra; i++, slice_next++) {- slice_next->slice_offset = (uint32_t)(sizeof(mi_slice_t)*i);- slice_next->slice_count = 0;- slice_next->block_size = 1;- }-- // and also for the last one (if not set already) (the last one is needed for coalescing and for large alignments)- // note: the cast is needed for ubsan since the index can be larger than MI_SLICES_PER_SEGMENT for huge allocations (see #543)- mi_slice_t* last = slice + slice_count - 1;- mi_slice_t* end = (mi_slice_t*)mi_segment_slices_end(segment);- if (last > end) last = end;- if (last > slice) {- last->slice_offset = (uint32_t)(sizeof(mi_slice_t) * (last - slice));- last->slice_count = 0;- last->block_size = 1;- }-- // and initialize the page- page->is_committed = true;- page->is_huge = (segment->kind == MI_SEGMENT_HUGE);- segment->used++;- return page;-}--static void mi_segment_slice_split(mi_segment_t* segment, mi_slice_t* slice, size_t slice_count, mi_segments_tld_t* tld) {- mi_assert_internal(_mi_ptr_segment(slice) == segment);- mi_assert_internal(slice->slice_count >= slice_count);- mi_assert_internal(slice->block_size > 0); // no more in free queue- if (slice->slice_count <= slice_count) return;- mi_assert_internal(segment->kind != MI_SEGMENT_HUGE);- size_t next_index = mi_slice_index(slice) + slice_count;- size_t next_count = slice->slice_count - slice_count;- mi_segment_span_free(segment, next_index, next_count, false /* don't purge left-over part */, tld);- slice->slice_count = (uint32_t)slice_count;-}--static mi_page_t* mi_segments_page_find_and_allocate(size_t slice_count, mi_arena_id_t req_arena_id, mi_segments_tld_t* tld) {- mi_assert_internal(slice_count*MI_SEGMENT_SLICE_SIZE <= MI_LARGE_OBJ_SIZE_MAX);- // search from best fit up- mi_span_queue_t* sq = mi_span_queue_for(slice_count, tld);- if (slice_count == 0) slice_count = 1;- while (sq <= &tld->spans[MI_SEGMENT_BIN_MAX]) {- for (mi_slice_t* slice = sq->first; slice != NULL; slice = slice->next) {- if (slice->slice_count >= slice_count) {- // found one- mi_segment_t* segment = _mi_ptr_segment(slice);- if (_mi_arena_memid_is_suitable(segment->memid, req_arena_id)) {- // found a suitable page span- mi_span_queue_delete(sq, slice);-- if (slice->slice_count > slice_count) {- mi_segment_slice_split(segment, slice, slice_count, tld);- }- mi_assert_internal(slice != NULL && slice->slice_count == slice_count && slice->block_size > 0);- mi_page_t* page = mi_segment_span_allocate(segment, mi_slice_index(slice), slice->slice_count);- if (page == NULL) {- // commit failed; return NULL but first restore the slice- mi_segment_span_free_coalesce(slice, tld);- return NULL;- }- return page;- }- }- }- sq++;- }- // could not find a page..- return NULL;-}---/* ------------------------------------------------------------ Segment allocation------------------------------------------------------------ */--static mi_segment_t* mi_segment_os_alloc( size_t required, size_t page_alignment, bool eager_delayed, mi_arena_id_t req_arena_id,- size_t* psegment_slices, size_t* pinfo_slices,- bool commit, mi_segments_tld_t* tld)--{- mi_memid_t memid;- bool allow_large = (!eager_delayed && (MI_SECURE == 0)); // only allow large OS pages once we are no longer lazy- size_t align_offset = 0;- size_t alignment = MI_SEGMENT_ALIGN;-- if (page_alignment > 0) {- // mi_assert_internal(huge_page != NULL);- mi_assert_internal(page_alignment >= MI_SEGMENT_ALIGN);- alignment = page_alignment;- const size_t info_size = (*pinfo_slices) * MI_SEGMENT_SLICE_SIZE;- align_offset = _mi_align_up( info_size, MI_SEGMENT_ALIGN );- const size_t extra = align_offset - info_size;- // recalculate due to potential guard pages- *psegment_slices = mi_segment_calculate_slices(required + extra, pinfo_slices);- mi_assert_internal(*psegment_slices > 0 && *psegment_slices <= UINT32_MAX);- }-- const size_t segment_size = (*psegment_slices) * MI_SEGMENT_SLICE_SIZE;- mi_segment_t* segment = (mi_segment_t*)_mi_arena_alloc_aligned(segment_size, alignment, align_offset, commit, allow_large, req_arena_id, &memid);- if (segment == NULL) {- return NULL; // failed to allocate- }-- // ensure metadata part of the segment is committed- mi_commit_mask_t commit_mask;- if (memid.initially_committed) {- mi_commit_mask_create_full(&commit_mask);- }- else {- // at least commit the info slices- const size_t commit_needed = _mi_divide_up((*pinfo_slices)*MI_SEGMENT_SLICE_SIZE, MI_COMMIT_SIZE);- mi_assert_internal(commit_needed>0);- mi_commit_mask_create(0, commit_needed, &commit_mask);- mi_assert_internal(commit_needed*MI_COMMIT_SIZE >= (*pinfo_slices)*MI_SEGMENT_SLICE_SIZE);- if (!_mi_os_commit(segment, commit_needed*MI_COMMIT_SIZE, NULL)) {- _mi_arena_free(segment,segment_size,0,memid);- return NULL;- }- }- mi_assert_internal(segment != NULL && (uintptr_t)segment % MI_SEGMENT_SIZE == 0);-- segment->memid = memid;- segment->allow_decommit = !memid.is_pinned;- segment->allow_purge = segment->allow_decommit && (mi_option_get(mi_option_purge_delay) >= 0);- segment->segment_size = segment_size;- segment->subproc = tld->subproc;- segment->commit_mask = commit_mask;- segment->purge_expire = 0;- mi_commit_mask_create_empty(&segment->purge_mask);-- mi_segments_track_size((long)(segment_size), tld);- _mi_segment_map_allocated_at(segment);- return segment;-}---// Allocate a segment from the OS aligned to `MI_SEGMENT_SIZE` .-static mi_segment_t* mi_segment_alloc(size_t required, size_t page_alignment, mi_arena_id_t req_arena_id, mi_segments_tld_t* tld, mi_page_t** huge_page)-{- mi_assert_internal((required==0 && huge_page==NULL) || (required>0 && huge_page != NULL));-- // calculate needed sizes first- size_t info_slices;- size_t segment_slices = mi_segment_calculate_slices(required, &info_slices);- mi_assert_internal(segment_slices > 0 && segment_slices <= UINT32_MAX);-- // Commit eagerly only if not the first N lazy segments (to reduce impact of many threads that allocate just a little)- const bool eager_delay = (// !_mi_os_has_overcommit() && // never delay on overcommit systems- _mi_current_thread_count() > 1 && // do not delay for the first N threads- tld->peak_count < (size_t)mi_option_get(mi_option_eager_commit_delay));- const bool eager = !eager_delay && mi_option_is_enabled(mi_option_eager_commit);- bool commit = eager || (required > 0);-- // Allocate the segment from the OS- mi_segment_t* segment = mi_segment_os_alloc(required, page_alignment, eager_delay, req_arena_id,- &segment_slices, &info_slices, commit, tld);- if (segment == NULL) return NULL;-- // zero the segment info? -- not always needed as it may be zero initialized from the OS- if (!segment->memid.initially_zero) {- ptrdiff_t ofs = offsetof(mi_segment_t, next);- size_t prefix = offsetof(mi_segment_t, slices) - ofs;- size_t zsize = prefix + (sizeof(mi_slice_t) * (segment_slices + 1)); // one more- _mi_memzero((uint8_t*)segment + ofs, zsize);- }-- // initialize the rest of the segment info- const size_t slice_entries = (segment_slices > MI_SLICES_PER_SEGMENT ? MI_SLICES_PER_SEGMENT : segment_slices);- segment->segment_slices = segment_slices;- segment->segment_info_slices = info_slices;- segment->thread_id = _mi_thread_id();- segment->cookie = _mi_ptr_cookie(segment);- segment->slice_entries = slice_entries;- segment->kind = (required == 0 ? MI_SEGMENT_NORMAL : MI_SEGMENT_HUGE);-- // _mi_memzero(segment->slices, sizeof(mi_slice_t)*(info_slices+1));- _mi_stat_increase(&tld->stats->page_committed, mi_segment_info_size(segment));-- // set up guard pages- size_t guard_slices = 0;- if (MI_SECURE>0) {- // in secure mode, we set up a protected page in between the segment info- // and the page data, and at the end of the segment.- size_t os_pagesize = _mi_os_page_size();- _mi_os_protect((uint8_t*)segment + mi_segment_info_size(segment) - os_pagesize, os_pagesize);- uint8_t* end = (uint8_t*)segment + mi_segment_size(segment) - os_pagesize;- mi_segment_ensure_committed(segment, end, os_pagesize);- _mi_os_protect(end, os_pagesize);- if (slice_entries == segment_slices) segment->slice_entries--; // don't use the last slice :-(- guard_slices = 1;- }-- // reserve first slices for segment info- mi_page_t* page0 = mi_segment_span_allocate(segment, 0, info_slices);- mi_assert_internal(page0!=NULL); if (page0==NULL) return NULL; // cannot fail as we always commit in advance- mi_assert_internal(segment->used == 1);- segment->used = 0; // don't count our internal slices towards usage-- // initialize initial free pages- if (segment->kind == MI_SEGMENT_NORMAL) { // not a huge page- mi_assert_internal(huge_page==NULL);- mi_segment_span_free(segment, info_slices, segment->slice_entries - info_slices, false /* don't purge */, tld);- }- else {- mi_assert_internal(huge_page!=NULL);- mi_assert_internal(mi_commit_mask_is_empty(&segment->purge_mask));- mi_assert_internal(mi_commit_mask_is_full(&segment->commit_mask));- *huge_page = mi_segment_span_allocate(segment, info_slices, segment_slices - info_slices - guard_slices);- mi_assert_internal(*huge_page != NULL); // cannot fail as we commit in advance- }-- mi_assert_expensive(mi_segment_is_valid(segment,tld));- return segment;-}---static void mi_segment_free(mi_segment_t* segment, bool force, mi_segments_tld_t* tld) {- MI_UNUSED(force);- mi_assert_internal(segment != NULL);- mi_assert_internal(segment->next == NULL);- mi_assert_internal(segment->used == 0);-- // in `mi_segment_force_abandon` we set this to true to ensure the segment's memory stays valid- if (segment->dont_free) return;-- // Remove the free pages- mi_slice_t* slice = &segment->slices[0];- const mi_slice_t* end = mi_segment_slices_end(segment);- #if MI_DEBUG>1- size_t page_count = 0;- #endif- while (slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- mi_assert_internal(mi_slice_index(slice)==0 || slice->block_size == 0); // no more used pages ..- if (slice->block_size == 0 && segment->kind != MI_SEGMENT_HUGE) {- mi_segment_span_remove_from_queue(slice, tld);- }- #if MI_DEBUG>1- page_count++;- #endif- slice = slice + slice->slice_count;- }- mi_assert_internal(page_count == 2); // first page is allocated by the segment itself-- // stats- _mi_stat_decrease(&tld->stats->page_committed, mi_segment_info_size(segment));-- // return it to the OS- mi_segment_os_free(segment, tld);-}---/* ------------------------------------------------------------ Page Free------------------------------------------------------------ */--static void mi_segment_abandon(mi_segment_t* segment, mi_segments_tld_t* tld);--// note: can be called on abandoned pages-static mi_slice_t* mi_segment_page_clear(mi_page_t* page, mi_segments_tld_t* tld) {- mi_assert_internal(page->block_size > 0);- mi_assert_internal(mi_page_all_free(page));- mi_segment_t* segment = _mi_ptr_segment(page);- mi_assert_internal(segment->used > 0);-- size_t inuse = page->capacity * mi_page_block_size(page);- _mi_stat_decrease(&tld->stats->page_committed, inuse);- _mi_stat_decrease(&tld->stats->pages, 1);-- // reset the page memory to reduce memory pressure?- if (segment->allow_decommit && mi_option_is_enabled(mi_option_deprecated_page_reset)) {- size_t psize;- uint8_t* start = _mi_segment_page_start(segment, page, &psize);- _mi_os_reset(start, psize);- }-- // zero the page data, but not the segment fields and heap tag- page->is_zero_init = false;- uint8_t heap_tag = page->heap_tag;- ptrdiff_t ofs = offsetof(mi_page_t, capacity);- _mi_memzero((uint8_t*)page + ofs, sizeof(*page) - ofs);- page->block_size = 1;- page->heap_tag = heap_tag;-- // and free it- mi_slice_t* slice = mi_segment_span_free_coalesce(mi_page_to_slice(page), tld);- segment->used--;- // cannot assert segment valid as it is called during reclaim- // mi_assert_expensive(mi_segment_is_valid(segment, tld));- return slice;-}--void _mi_segment_page_free(mi_page_t* page, bool force, mi_segments_tld_t* tld)-{- mi_assert(page != NULL);- mi_segment_t* segment = _mi_page_segment(page);- mi_assert_expensive(mi_segment_is_valid(segment,tld));-- // mark it as free now- mi_segment_page_clear(page, tld);- mi_assert_expensive(mi_segment_is_valid(segment, tld));-- if (segment->used == 0) {- // no more used pages; remove from the free list and free the segment- mi_segment_free(segment, force, tld);- }- else if (segment->used == segment->abandoned) {- // only abandoned pages; remove from free list and abandon- mi_segment_abandon(segment,tld);- }- else {- // perform delayed purges- mi_segment_try_purge(segment, false /* force? */);- }-}---/* ------------------------------------------------------------Abandonment--When threads terminate, they can leave segments with-live blocks (reachable through other threads). Such segments-are "abandoned" and will be reclaimed by other threads to-reuse their pages and/or free them eventually. The-`thread_id` of such segments is 0.--When a block is freed in an abandoned segment, the segment-is reclaimed into that thread.--Moreover, if threads are looking for a fresh segment, they-will first consider abandoned segments -- these can be found-by scanning the arena memory-(segments outside arena memoryare only reclaimed by a free).------------------------------------------------------------ */--/* ------------------------------------------------------------ Abandon segment/page------------------------------------------------------------ */--static void mi_segment_abandon(mi_segment_t* segment, mi_segments_tld_t* tld) {- mi_assert_internal(segment->used == segment->abandoned);- mi_assert_internal(segment->used > 0);- mi_assert_internal(segment->abandoned_visits == 0);- mi_assert_expensive(mi_segment_is_valid(segment,tld));-- // remove the free pages from the free page queues- mi_slice_t* slice = &segment->slices[0];- const mi_slice_t* end = mi_segment_slices_end(segment);- while (slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- if (slice->block_size == 0) { // a free page- mi_segment_span_remove_from_queue(slice,tld);- slice->block_size = 0; // but keep it free- }- slice = slice + slice->slice_count;- }-- // perform delayed decommits (forcing is much slower on mstress)- // Only abandoned segments in arena memory can be reclaimed without a free- // so if a segment is not from an arena we force purge here to be conservative.- const bool force_purge = (segment->memid.memkind != MI_MEM_ARENA) || mi_option_is_enabled(mi_option_abandoned_page_purge);- mi_segment_try_purge(segment, force_purge);-- // all pages in the segment are abandoned; add it to the abandoned list- _mi_stat_increase(&tld->stats->segments_abandoned, 1);- mi_segments_track_size(-((long)mi_segment_size(segment)), tld);- segment->thread_id = 0;- segment->abandoned_visits = 1; // from 0 to 1 to signify it is abandoned- if (segment->was_reclaimed) {- tld->reclaim_count--;- segment->was_reclaimed = false;- }- _mi_arena_segment_mark_abandoned(segment);-}--void _mi_segment_page_abandon(mi_page_t* page, mi_segments_tld_t* tld) {- mi_assert(page != NULL);- mi_assert_internal(mi_page_thread_free_flag(page)==MI_NEVER_DELAYED_FREE);- mi_assert_internal(mi_page_heap(page) == NULL);- mi_segment_t* segment = _mi_page_segment(page);-- mi_assert_expensive(mi_segment_is_valid(segment,tld));- segment->abandoned++;-- _mi_stat_increase(&tld->stats->pages_abandoned, 1);- mi_assert_internal(segment->abandoned <= segment->used);- if (segment->used == segment->abandoned) {- // all pages are abandoned, abandon the entire segment- mi_segment_abandon(segment, tld);- }-}--/* ------------------------------------------------------------ Reclaim abandoned pages------------------------------------------------------------ */--static mi_slice_t* mi_slices_start_iterate(mi_segment_t* segment, const mi_slice_t** end) {- mi_slice_t* slice = &segment->slices[0];- *end = mi_segment_slices_end(segment);- mi_assert_internal(slice->slice_count>0 && slice->block_size>0); // segment allocated page- slice = slice + slice->slice_count; // skip the first segment allocated page- return slice;-}--// Possibly free pages and check if free space is available-static bool mi_segment_check_free(mi_segment_t* segment, size_t slices_needed, size_t block_size, mi_segments_tld_t* tld)-{- mi_assert_internal(mi_segment_is_abandoned(segment));- bool has_page = false;-- // for all slices- const mi_slice_t* end;- mi_slice_t* slice = mi_slices_start_iterate(segment, &end);- while (slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- if (mi_slice_is_used(slice)) { // used page- // ensure used count is up to date and collect potential concurrent frees- mi_page_t* const page = mi_slice_to_page(slice);- _mi_page_free_collect(page, false);- if (mi_page_all_free(page)) {- // if this page is all free now, free it without adding to any queues (yet)- mi_assert_internal(page->next == NULL && page->prev==NULL);- _mi_stat_decrease(&tld->stats->pages_abandoned, 1);- segment->abandoned--;- slice = mi_segment_page_clear(page, tld); // re-assign slice due to coalesce!- mi_assert_internal(!mi_slice_is_used(slice));- if (slice->slice_count >= slices_needed) {- has_page = true;- }- }- else if (mi_page_block_size(page) == block_size && mi_page_has_any_available(page)) {- // a page has available free blocks of the right size- has_page = true;- }- }- else {- // empty span- if (slice->slice_count >= slices_needed) {- has_page = true;- }- }- slice = slice + slice->slice_count;- }- return has_page;-}--// Reclaim an abandoned segment; returns NULL if the segment was freed-// set `right_page_reclaimed` to `true` if it reclaimed a page of the right `block_size` that was not full.-static mi_segment_t* mi_segment_reclaim(mi_segment_t* segment, mi_heap_t* heap, size_t requested_block_size, bool* right_page_reclaimed, mi_segments_tld_t* tld) {- if (right_page_reclaimed != NULL) { *right_page_reclaimed = false; }- // can be 0 still with abandoned_next, or already a thread id for segments outside an arena that are reclaimed on a free.- mi_assert_internal(mi_atomic_load_relaxed(&segment->thread_id) == 0 || mi_atomic_load_relaxed(&segment->thread_id) == _mi_thread_id());- mi_assert_internal(segment->subproc == heap->tld->segments.subproc); // only reclaim within the same subprocess- mi_atomic_store_release(&segment->thread_id, _mi_thread_id());- segment->abandoned_visits = 0;- segment->was_reclaimed = true;- tld->reclaim_count++;- mi_segments_track_size((long)mi_segment_size(segment), tld);- mi_assert_internal(segment->next == NULL);- _mi_stat_decrease(&tld->stats->segments_abandoned, 1);-- // for all slices- const mi_slice_t* end;- mi_slice_t* slice = mi_slices_start_iterate(segment, &end);- while (slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- if (mi_slice_is_used(slice)) {- // in use: reclaim the page in our heap- mi_page_t* page = mi_slice_to_page(slice);- mi_assert_internal(page->is_committed);- mi_assert_internal(mi_page_thread_free_flag(page)==MI_NEVER_DELAYED_FREE);- mi_assert_internal(mi_page_heap(page) == NULL);- mi_assert_internal(page->next == NULL && page->prev==NULL);- _mi_stat_decrease(&tld->stats->pages_abandoned, 1);- segment->abandoned--;- // get the target heap for this thread which has a matching heap tag (so we reclaim into a matching heap)- mi_heap_t* target_heap = _mi_heap_by_tag(heap, page->heap_tag); // allow custom heaps to separate objects- if (target_heap == NULL) {- target_heap = heap;- _mi_error_message(EFAULT, "page with tag %u cannot be reclaimed by a heap with the same tag (using heap tag %u instead)\n", page->heap_tag, heap->tag );- }- // associate the heap with this page, and allow heap thread delayed free again.- mi_page_set_heap(page, target_heap);- _mi_page_use_delayed_free(page, MI_USE_DELAYED_FREE, true); // override never (after heap is set)- _mi_page_free_collect(page, false); // ensure used count is up to date- if (mi_page_all_free(page)) {- // if everything free by now, free the page- slice = mi_segment_page_clear(page, tld); // set slice again due to coalesceing- }- else {- // otherwise reclaim it into the heap- _mi_page_reclaim(target_heap, page);- if (requested_block_size == mi_page_block_size(page) && mi_page_has_any_available(page) && heap == target_heap) {- if (right_page_reclaimed != NULL) { *right_page_reclaimed = true; }- }- }- }- else {- // the span is free, add it to our page queues- slice = mi_segment_span_free_coalesce(slice, tld); // set slice again due to coalesceing- }- mi_assert_internal(slice->slice_count>0 && slice->slice_offset==0);- slice = slice + slice->slice_count;- }-- mi_assert(segment->abandoned == 0);- mi_assert_expensive(mi_segment_is_valid(segment, tld));- if (segment->used == 0) { // due to page_clear- mi_assert_internal(right_page_reclaimed == NULL || !(*right_page_reclaimed));- mi_segment_free(segment, false, tld);- return NULL;- }- else {- return segment;- }-}---// attempt to reclaim a particular segment (called from multi threaded free `alloc.c:mi_free_block_mt`)-bool _mi_segment_attempt_reclaim(mi_heap_t* heap, mi_segment_t* segment) {- if (mi_atomic_load_relaxed(&segment->thread_id) != 0) return false; // it is not abandoned- if (segment->subproc != heap->tld->segments.subproc) return false; // only reclaim within the same subprocess- if (!_mi_heap_memid_is_suitable(heap,segment->memid)) return false; // don't reclaim between exclusive and non-exclusive arena's- const long target = _mi_option_get_fast(mi_option_target_segments_per_thread);- if (target > 0 && (size_t)target <= heap->tld->segments.count) return false; // don't reclaim if going above the target count-- // don't reclaim more from a `free` call than half the current segments- // this is to prevent a pure free-ing thread to start owning too many segments- // (but not for out-of-arena segments as that is the main way to be reclaimed for those)- if (segment->memid.memkind == MI_MEM_ARENA && heap->tld->segments.reclaim_count * 2 > heap->tld->segments.count) {- return false;- }- if (_mi_arena_segment_clear_abandoned(segment)) { // atomically unabandon- mi_segment_t* res = mi_segment_reclaim(segment, heap, 0, NULL, &heap->tld->segments);- mi_assert_internal(res == segment);- return (res != NULL);- }- return false;-}--void _mi_abandoned_reclaim_all(mi_heap_t* heap, mi_segments_tld_t* tld) {- mi_segment_t* segment;- mi_arena_field_cursor_t current;- _mi_arena_field_cursor_init(heap, tld->subproc, true /* visit all, blocking */, ¤t);- while ((segment = _mi_arena_segment_clear_abandoned_next(¤t)) != NULL) {- mi_segment_reclaim(segment, heap, 0, NULL, tld);- }- _mi_arena_field_cursor_done(¤t);-}---static bool segment_count_is_within_target(mi_segments_tld_t* tld, size_t* ptarget) {- const size_t target = (size_t)mi_option_get_clamp(mi_option_target_segments_per_thread, 0, 1024);- if (ptarget != NULL) { *ptarget = target; }- return (target == 0 || tld->count < target);-}--static long mi_segment_get_reclaim_tries(mi_segments_tld_t* tld) {- // limit the tries to 10% (default) of the abandoned segments with at least 8 and at most 1024 tries.- const size_t perc = (size_t)mi_option_get_clamp(mi_option_max_segment_reclaim, 0, 100);- if (perc <= 0) return 0;- const size_t total_count = mi_atomic_load_relaxed(&tld->subproc->abandoned_count);- if (total_count == 0) return 0;- const size_t relative_count = (total_count > 10000 ? (total_count / 100) * perc : (total_count * perc) / 100); // avoid overflow- long max_tries = (long)(relative_count <= 1 ? 1 : (relative_count > 1024 ? 1024 : relative_count));- if (max_tries < 8 && total_count > 8) { max_tries = 8; }- return max_tries;-}--static mi_segment_t* mi_segment_try_reclaim(mi_heap_t* heap, size_t needed_slices, size_t block_size, bool* reclaimed, mi_segments_tld_t* tld)-{- *reclaimed = false;- long max_tries = mi_segment_get_reclaim_tries(tld);- if (max_tries <= 0) return NULL;-- mi_segment_t* result = NULL;- mi_segment_t* segment = NULL;- mi_arena_field_cursor_t current;- _mi_arena_field_cursor_init(heap, tld->subproc, false /* non-blocking */, ¤t);- while (segment_count_is_within_target(tld,NULL) && (max_tries-- > 0) && ((segment = _mi_arena_segment_clear_abandoned_next(¤t)) != NULL))- {- mi_assert(segment->subproc == heap->tld->segments.subproc); // cursor only visits segments in our sub-process- segment->abandoned_visits++;- // todo: should we respect numa affinity for abandoned reclaim? perhaps only for the first visit?- // todo: an arena exclusive heap will potentially visit many abandoned unsuitable segments and use many tries- // Perhaps we can skip non-suitable ones in a better way?- bool is_suitable = _mi_heap_memid_is_suitable(heap, segment->memid);- bool has_page = mi_segment_check_free(segment,needed_slices,block_size,tld); // try to free up pages (due to concurrent frees)- if (segment->used == 0) {- // free the segment (by forced reclaim) to make it available to other threads.- // note1: we prefer to free a segment as that might lead to reclaiming another- // segment that is still partially used.- // note2: we could in principle optimize this by skipping reclaim and directly- // freeing but that would violate some invariants temporarily)- mi_segment_reclaim(segment, heap, 0, NULL, tld);- }- else if (has_page && is_suitable) {- // found a large enough free span, or a page of the right block_size with free space- // we return the result of reclaim (which is usually `segment`) as it might free- // the segment due to concurrent frees (in which case `NULL` is returned).- result = mi_segment_reclaim(segment, heap, block_size, reclaimed, tld);- break;- }- else if (segment->abandoned_visits > 3 && is_suitable) {- // always reclaim on 3rd visit to limit the abandoned segment count.- mi_segment_reclaim(segment, heap, 0, NULL, tld);- }- else {- // otherwise, push on the visited list so it gets not looked at too quickly again- mi_segment_try_purge(segment, false /* true force? */); // force purge if needed as we may not visit soon again- _mi_arena_segment_mark_abandoned(segment);- }- }- _mi_arena_field_cursor_done(¤t);- return result;-}--// collect abandoned segments-void _mi_abandoned_collect(mi_heap_t* heap, bool force, mi_segments_tld_t* tld)-{- mi_segment_t* segment;- mi_arena_field_cursor_t current; _mi_arena_field_cursor_init(heap, tld->subproc, force /* blocking? */, ¤t);- long max_tries = (force ? (long)mi_atomic_load_relaxed(&tld->subproc->abandoned_count) : 1024); // limit latency- while ((max_tries-- > 0) && ((segment = _mi_arena_segment_clear_abandoned_next(¤t)) != NULL)) {- mi_segment_check_free(segment,0,0,tld); // try to free up pages (due to concurrent frees)- if (segment->used == 0) {- // free the segment (by forced reclaim) to make it available to other threads.- // note: we could in principle optimize this by skipping reclaim and directly- // freeing but that would violate some invariants temporarily)- mi_segment_reclaim(segment, heap, 0, NULL, tld);- }- else {- // otherwise, purge if needed and push on the visited list- // note: forced purge can be expensive if many threads are destroyed/created as in mstress.- mi_segment_try_purge(segment, force);- _mi_arena_segment_mark_abandoned(segment);- }- }- _mi_arena_field_cursor_done(¤t);-}--/* ------------------------------------------------------------ Force abandon a segment that is in use by our thread------------------------------------------------------------ */--// force abandon a segment-static void mi_segment_force_abandon(mi_segment_t* segment, mi_segments_tld_t* tld)-{- mi_assert_internal(!mi_segment_is_abandoned(segment));- mi_assert_internal(!segment->dont_free);-- // ensure the segment does not get free'd underneath us (so we can check if a page has been freed in `mi_page_force_abandon`)- segment->dont_free = true;-- // for all slices- const mi_slice_t* end;- mi_slice_t* slice = mi_slices_start_iterate(segment, &end);- while (slice < end) {- mi_assert_internal(slice->slice_count > 0);- mi_assert_internal(slice->slice_offset == 0);- if (mi_slice_is_used(slice)) {- // ensure used count is up to date and collect potential concurrent frees- mi_page_t* const page = mi_slice_to_page(slice);- _mi_page_free_collect(page, false);- {- // abandon the page if it is still in-use (this will free it if possible as well)- mi_assert_internal(segment->used > 0);- if (segment->used == segment->abandoned+1) {- // the last page.. abandon and return as the segment will be abandoned after this- // and we should no longer access it.- segment->dont_free = false;- _mi_page_force_abandon(page);- return;- }- else {- // abandon and continue- _mi_page_force_abandon(page);- // it might be freed, reset the slice (note: relies on coalesce setting the slice_offset)- slice = mi_slice_first(slice);- }- }- }- slice = slice + slice->slice_count;- }- segment->dont_free = false;- mi_assert(segment->used == segment->abandoned);- mi_assert(segment->used == 0);- if (segment->used == 0) { // paranoia- // all free now- mi_segment_free(segment, false, tld);- }- else {- // perform delayed purges- mi_segment_try_purge(segment, false /* force? */);- }-}---// try abandon segments.-// this should be called from `reclaim_or_alloc` so we know all segments are (about) fully in use.-static void mi_segments_try_abandon_to_target(mi_heap_t* heap, size_t target, mi_segments_tld_t* tld) {- if (target <= 1) return;- const size_t min_target = (target > 4 ? (target*3)/4 : target); // 75%- // todo: we should maintain a list of segments per thread; for now, only consider segments from the heap full pages- for (int i = 0; i < 64 && tld->count >= min_target; i++) {- mi_page_t* page = heap->pages[MI_BIN_FULL].first;- while (page != NULL && mi_page_block_size(page) > MI_LARGE_OBJ_SIZE_MAX) {- page = page->next;- }- if (page==NULL) {- break;- }- mi_segment_t* segment = _mi_page_segment(page);- mi_segment_force_abandon(segment, tld);- mi_assert_internal(page != heap->pages[MI_BIN_FULL].first); // as it is just abandoned- }-}--// try abandon segments.-// this should be called from `reclaim_or_alloc` so we know all segments are (about) fully in use.-static void mi_segments_try_abandon(mi_heap_t* heap, mi_segments_tld_t* tld) {- // we call this when we are about to add a fresh segment so we should be under our target segment count.- size_t target = 0;- if (segment_count_is_within_target(tld, &target)) return;- mi_segments_try_abandon_to_target(heap, target, tld);-}--void mi_collect_reduce(size_t target_size) mi_attr_noexcept {- mi_collect(true);- mi_heap_t* heap = mi_heap_get_default();- mi_segments_tld_t* tld = &heap->tld->segments;- size_t target = target_size / MI_SEGMENT_SIZE;- if (target == 0) {- target = (size_t)mi_option_get_clamp(mi_option_target_segments_per_thread, 1, 1024);- }- mi_segments_try_abandon_to_target(heap, target, tld);-}--/* ------------------------------------------------------------ Reclaim or allocate------------------------------------------------------------ */--static mi_segment_t* mi_segment_reclaim_or_alloc(mi_heap_t* heap, size_t needed_slices, size_t block_size, mi_segments_tld_t* tld)-{- mi_assert_internal(block_size <= MI_LARGE_OBJ_SIZE_MAX);-- // try to abandon some segments to increase reuse between threads- mi_segments_try_abandon(heap,tld);-- // 1. try to reclaim an abandoned segment- bool reclaimed;- mi_segment_t* segment = mi_segment_try_reclaim(heap, needed_slices, block_size, &reclaimed, tld);- if (reclaimed) {- // reclaimed the right page right into the heap- mi_assert_internal(segment != NULL);- return NULL; // pretend out-of-memory as the page will be in the page queue of the heap with available blocks- }- else if (segment != NULL) {- // reclaimed a segment with a large enough empty span in it- return segment;- }- // 2. otherwise allocate a fresh segment- return mi_segment_alloc(0, 0, heap->arena_id, tld, NULL);-}---/* ------------------------------------------------------------ Page allocation------------------------------------------------------------ */--static mi_page_t* mi_segments_page_alloc(mi_heap_t* heap, mi_page_kind_t page_kind, size_t required, size_t block_size, mi_segments_tld_t* tld)-{- mi_assert_internal(required <= MI_LARGE_OBJ_SIZE_MAX && page_kind <= MI_PAGE_LARGE);-- // find a free page- size_t page_size = _mi_align_up(required, (required > MI_MEDIUM_PAGE_SIZE ? MI_MEDIUM_PAGE_SIZE : MI_SEGMENT_SLICE_SIZE));- size_t slices_needed = page_size / MI_SEGMENT_SLICE_SIZE;- mi_assert_internal(slices_needed * MI_SEGMENT_SLICE_SIZE == page_size);- mi_page_t* page = mi_segments_page_find_and_allocate(slices_needed, heap->arena_id, tld); //(required <= MI_SMALL_SIZE_MAX ? 0 : slices_needed), tld);- if (page==NULL) {- // no free page, allocate a new segment and try again- if (mi_segment_reclaim_or_alloc(heap, slices_needed, block_size, tld) == NULL) {- // OOM or reclaimed a good page in the heap- return NULL;- }- else {- // otherwise try again- return mi_segments_page_alloc(heap, page_kind, required, block_size, tld);- }- }- mi_assert_internal(page != NULL && page->slice_count*MI_SEGMENT_SLICE_SIZE == page_size);- mi_assert_internal(_mi_ptr_segment(page)->thread_id == _mi_thread_id());- mi_segment_try_purge(_mi_ptr_segment(page), false);- return page;-}----/* ------------------------------------------------------------ Huge page allocation------------------------------------------------------------ */--static mi_page_t* mi_segment_huge_page_alloc(size_t size, size_t page_alignment, mi_arena_id_t req_arena_id, mi_segments_tld_t* tld)-{- mi_page_t* page = NULL;- mi_segment_t* segment = mi_segment_alloc(size,page_alignment,req_arena_id,tld,&page);- if (segment == NULL || page==NULL) return NULL;- mi_assert_internal(segment->used==1);- mi_assert_internal(mi_page_block_size(page) >= size);- #if MI_HUGE_PAGE_ABANDON- segment->thread_id = 0; // huge segments are immediately abandoned- #endif-- // for huge pages we initialize the block_size as we may- // overallocate to accommodate large alignments.- size_t psize;- uint8_t* start = _mi_segment_page_start(segment, page, &psize);- page->block_size = psize;- mi_assert_internal(page->is_huge);-- // decommit the part of the prefix of a page that will not be used; this can be quite large (close to MI_SEGMENT_SIZE)- if (page_alignment > 0 && segment->allow_decommit) {- uint8_t* aligned_p = (uint8_t*)_mi_align_up((uintptr_t)start, page_alignment);- mi_assert_internal(_mi_is_aligned(aligned_p, page_alignment));- mi_assert_internal(psize - (aligned_p - start) >= size);- uint8_t* decommit_start = start + sizeof(mi_block_t); // for the free list- ptrdiff_t decommit_size = aligned_p - decommit_start;- _mi_os_reset(decommit_start, decommit_size); // note: cannot use segment_decommit on huge segments- }-- return page;-}--#if MI_HUGE_PAGE_ABANDON-// free huge block from another thread-void _mi_segment_huge_page_free(mi_segment_t* segment, mi_page_t* page, mi_block_t* block) {- // huge page segments are always abandoned and can be freed immediately by any thread- mi_assert_internal(segment->kind==MI_SEGMENT_HUGE);- mi_assert_internal(segment == _mi_page_segment(page));- mi_assert_internal(mi_atomic_load_relaxed(&segment->thread_id)==0);-- // claim it and free- mi_heap_t* heap = mi_heap_get_default(); // issue #221; don't use the internal get_default_heap as we need to ensure the thread is initialized.- // paranoia: if this it the last reference, the cas should always succeed- size_t expected_tid = 0;- if (mi_atomic_cas_strong_acq_rel(&segment->thread_id, &expected_tid, heap->thread_id)) {- mi_block_set_next(page, block, page->free);- page->free = block;- page->used--;- page->is_zero_init = false;- mi_assert(page->used == 0);- mi_tld_t* tld = heap->tld;- _mi_segment_page_free(page, true, &tld->segments);- }-#if (MI_DEBUG!=0)- else {- mi_assert_internal(false);- }-#endif-}--#else-// reset memory of a huge block from another thread-void _mi_segment_huge_page_reset(mi_segment_t* segment, mi_page_t* page, mi_block_t* block) {- MI_UNUSED(page);- mi_assert_internal(segment->kind == MI_SEGMENT_HUGE);- mi_assert_internal(segment == _mi_page_segment(page));- mi_assert_internal(page->used == 1); // this is called just before the free- mi_assert_internal(page->free == NULL);- if (segment->allow_decommit) {- size_t csize = mi_usable_size(block);- if (csize > sizeof(mi_block_t)) {- csize = csize - sizeof(mi_block_t);- uint8_t* p = (uint8_t*)block + sizeof(mi_block_t);- _mi_os_reset(p, csize); // note: cannot use segment_decommit on huge segments- }- }-}-#endif--/* ------------------------------------------------------------ Page allocation and free------------------------------------------------------------ */-mi_page_t* _mi_segment_page_alloc(mi_heap_t* heap, size_t block_size, size_t page_alignment, mi_segments_tld_t* tld) {- mi_page_t* page;- if mi_unlikely(page_alignment > MI_BLOCK_ALIGNMENT_MAX) {- mi_assert_internal(_mi_is_power_of_two(page_alignment));- mi_assert_internal(page_alignment >= MI_SEGMENT_SIZE);- if (page_alignment < MI_SEGMENT_SIZE) { page_alignment = MI_SEGMENT_SIZE; }- page = mi_segment_huge_page_alloc(block_size,page_alignment,heap->arena_id,tld);- }- else if (block_size <= MI_SMALL_OBJ_SIZE_MAX) {- page = mi_segments_page_alloc(heap,MI_PAGE_SMALL,block_size,block_size,tld);- }- else if (block_size <= MI_MEDIUM_OBJ_SIZE_MAX) {- page = mi_segments_page_alloc(heap,MI_PAGE_MEDIUM,MI_MEDIUM_PAGE_SIZE,block_size,tld);- }- else if (block_size <= MI_LARGE_OBJ_SIZE_MAX) {- page = mi_segments_page_alloc(heap,MI_PAGE_LARGE,block_size,block_size,tld);- }- else {- page = mi_segment_huge_page_alloc(block_size,page_alignment,heap->arena_id,tld);- }- mi_assert_internal(page == NULL || _mi_heap_memid_is_suitable(heap, _mi_page_segment(page)->memid));- mi_assert_expensive(page == NULL || mi_segment_is_valid(_mi_page_segment(page),tld));- mi_assert_internal(page == NULL || _mi_page_segment(page)->subproc == tld->subproc);- return page;-}---/* ------------------------------------------------------------ Visit blocks in a segment (only used for abandoned segments)------------------------------------------------------------ */--static bool mi_segment_visit_page(mi_page_t* page, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {- mi_heap_area_t area;- _mi_heap_area_init(&area, page);- if (!visitor(NULL, &area, NULL, area.block_size, arg)) return false;- if (visit_blocks) {- return _mi_heap_area_visit_blocks(&area, page, visitor, arg);- }- else {- return true;- }-}--bool _mi_segment_visit_blocks(mi_segment_t* segment, int heap_tag, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {- const mi_slice_t* end;- mi_slice_t* slice = mi_slices_start_iterate(segment, &end);- while (slice < end) {- if (mi_slice_is_used(slice)) {- mi_page_t* const page = mi_slice_to_page(slice);- if (heap_tag < 0 || (int)page->heap_tag == heap_tag) {- if (!mi_segment_visit_page(page, visit_blocks, visitor, arg)) return false;- }- }- slice = slice + slice->slice_count;- }- return true;-}diff --git a/vendored/mimalloc/src/static.c b/vendored/mimalloc/src/static.cindex 9e06ce05a..2383f6596 100644--- a/vendored/mimalloc/src/static.c+++ b/vendored/mimalloc/src/static.c@@ -20,10 +20,11 @@ terms of the MIT license. A copy of the license can be found in the file// containing the whole library. If it is linked first// it will override all the standard library allocation// functions (on Unix's).-#include "alloc.c" // includes alloc-override.c+#include "alloc.c" // includes alloc-override.c and free.c#include "alloc-aligned.c"#include "alloc-posix.c"#include "arena.c"+#include "arena-meta.c"#include "bitmap.c"#include "heap.c"#include "init.c"@@ -31,10 +32,11 @@ terms of the MIT license. A copy of the license can be found in the file#include "options.c"#include "os.c"#include "page.c" // includes page-queue.c+#include "page-map.c"#include "random.c"-#include "segment.c"-#include "segment-map.c"#include "stats.c"+#include "theap.c"+#include "threadlocal.c"#include "prim/prim.c"#if MI_OSX_ZONE#include "prim/osx/alloc-override-zone.c"diff --git a/vendored/mimalloc/src/stats.c b/vendored/mimalloc/src/stats.cindex f82055938..877266c79 100644--- a/vendored/mimalloc/src/stats.c+++ b/vendored/mimalloc/src/stats.c@@ -1,10 +1,11 @@/* -----------------------------------------------------------------------------Copyright (c) 2018-2021, Microsoft Research, Daan Leijen+Copyright (c) 2018-2025, Microsoft Research, Daan LeijenThis is free software; you can redistribute it and/or modify it under theterms of the MIT license. A copy of the license can be found in the file"LICENSE" at the root of this distribution.-----------------------------------------------------------------------------*/#include "mimalloc.h"+#include "mimalloc-stats.h"#include "mimalloc/internal.h"#include "mimalloc/atomic.h"#include "mimalloc/prim.h"@@ -19,145 +20,121 @@ terms of the MIT license. A copy of the license can be found in the fileStatistics operations----------------------------------------------------------- */-static bool mi_is_in_main(void* stat) {- return ((uint8_t*)stat >= (uint8_t*)&_mi_stats_main- && (uint8_t*)stat < ((uint8_t*)&_mi_stats_main + sizeof(mi_stats_t)));+static void mi_stat_update_mt(mi_stat_count_t* stat, int64_t amount) {+ if (amount == 0) return;+ // add atomically+ int64_t current = mi_atomic_addi64_relaxed(&stat->current, amount);+ mi_atomic_maxi64_relaxed(&stat->peak, current + amount);+ if (amount > 0) {+ mi_atomic_addi64_relaxed(&stat->total, amount);+ }}static void mi_stat_update(mi_stat_count_t* stat, int64_t amount) {if (amount == 0) return;- if mi_unlikely(mi_is_in_main(stat))- {- // add atomically (for abandoned pages)- int64_t current = mi_atomic_addi64_relaxed(&stat->current, amount);- mi_atomic_maxi64_relaxed(&stat->peak, current + amount);- if (amount > 0) {- mi_atomic_addi64_relaxed(&stat->allocated,amount);- }- else {- mi_atomic_addi64_relaxed(&stat->freed, -amount);- }- }- else {- // add thread local- stat->current += amount;- if (stat->current > stat->peak) stat->peak = stat->current;- if (amount > 0) {- stat->allocated += amount;- }- else {- stat->freed += -amount;- }- }+ // add thread local+ stat->current += amount;+ if (stat->current > stat->peak) { stat->peak = stat->current; }+ if (amount > 0) { stat->total += amount; }}-// Adjust stats to compensate; for example before committing a range,-// first adjust downwards with parts that were already committed so-// we avoid double counting.-static void mi_stat_adjust(mi_stat_count_t* stat, int64_t amount) {- if (amount == 0) return;- if mi_unlikely(mi_is_in_main(stat))- {- // adjust atomically- mi_atomic_addi64_relaxed(&stat->current, amount);- mi_atomic_addi64_relaxed(&stat->allocated, amount);- mi_atomic_addi64_relaxed(&stat->freed, amount);- }- else {- // don't affect the peak- stat->current += amount;- // add to both- stat->allocated += amount;- stat->freed += amount;- }++void __mi_stat_counter_increase_mt(mi_stat_counter_t* stat, size_t amount) {+ mi_atomic_addi64_relaxed(&stat->total, (int64_t)amount);}-void _mi_stat_counter_increase(mi_stat_counter_t* stat, size_t amount) {- if (mi_is_in_main(stat)) {- mi_atomic_addi64_relaxed( &stat->count, 1 );- mi_atomic_addi64_relaxed( &stat->total, (int64_t)amount );- }- else {- stat->count++;- stat->total += amount;- }+void __mi_stat_counter_increase(mi_stat_counter_t* stat, size_t amount) {+ stat->total += amount;}-void _mi_stat_increase(mi_stat_count_t* stat, size_t amount) {+void __mi_stat_increase_mt(mi_stat_count_t* stat, size_t amount) {+ mi_stat_update_mt(stat, (int64_t)amount);+}+void __mi_stat_increase(mi_stat_count_t* stat, size_t amount) {mi_stat_update(stat, (int64_t)amount);}-void _mi_stat_decrease(mi_stat_count_t* stat, size_t amount) {+void __mi_stat_decrease_mt(mi_stat_count_t* stat, size_t amount) {+ mi_stat_update_mt(stat, -((int64_t)amount));+}+void __mi_stat_decrease(mi_stat_count_t* stat, size_t amount) {mi_stat_update(stat, -((int64_t)amount));}-void _mi_stat_adjust_increase(mi_stat_count_t* stat, size_t amount) {- mi_stat_adjust(stat, (int64_t)amount);++// Adjust stats to compensate; for example before committing a range,+// first adjust downwards with parts that were already committed so+// we avoid double counting.+static void mi_stat_adjust_mt(mi_stat_count_t* stat, int64_t amount) {+ if (amount == 0) return;+ // adjust atomically+ mi_atomic_addi64_relaxed(&stat->current, amount);+ mi_atomic_addi64_relaxed(&stat->total, amount);}-void _mi_stat_adjust_decrease(mi_stat_count_t* stat, size_t amount) {+static void mi_stat_adjust(mi_stat_count_t* stat, int64_t amount) {+ if (amount == 0) return;+ stat->current += amount;+ stat->total += amount;+}++void __mi_stat_adjust_increase_mt(mi_stat_count_t* stat, size_t amount) {+ mi_stat_adjust_mt(stat, (int64_t)amount);+}+void __mi_stat_adjust_increase(mi_stat_count_t* stat, size_t amount) {+ mi_stat_adjust(stat, (int64_t)amount);+}+void __mi_stat_adjust_decrease_mt(mi_stat_count_t* stat, size_t amount) {+ mi_stat_adjust_mt(stat, -((int64_t)amount));+}+void __mi_stat_adjust_decrease(mi_stat_count_t* stat, size_t amount) {mi_stat_adjust(stat, -((int64_t)amount));}+// must be thread safe as it is called from stats_merge-static void mi_stat_add(mi_stat_count_t* stat, const mi_stat_count_t* src, int64_t unit) {+static void mi_stat_count_add_mt(mi_stat_count_t* stat, const mi_stat_count_t* src) {if (stat==src) return;- if (src->allocated==0 && src->freed==0) return;- mi_atomic_addi64_relaxed( &stat->allocated, src->allocated * unit);- mi_atomic_addi64_relaxed( &stat->current, src->current * unit);- mi_atomic_addi64_relaxed( &stat->freed, src->freed * unit);- // peak scores do not work across threads..- mi_atomic_addi64_relaxed( &stat->peak, src->peak * unit);+ mi_atomic_void_addi64_relaxed(&stat->total, &src->total);+ const int64_t prev_current = mi_atomic_addi64_relaxed(&stat->current, src->current);++ // Global current plus thread peak approximates new global peak+ // note: peak scores do really not work across threads.+ // we used to just add them together but that often overestimates in practice.+ // similarly, max does not seem to work well. The current approach+ // by Artem Kharytoniuk (@artem-lunarg) seems to work better, see PR#1112+ // for a longer description.+ mi_atomic_maxi64_relaxed(&stat->peak, prev_current + src->peak);}-static void mi_stat_counter_add(mi_stat_counter_t* stat, const mi_stat_counter_t* src, int64_t unit) {+static void mi_stat_counter_add_mt(mi_stat_counter_t* stat, const mi_stat_counter_t* src) {if (stat==src) return;- mi_atomic_addi64_relaxed( &stat->total, src->total * unit);- mi_atomic_addi64_relaxed( &stat->count, src->count * unit);+ mi_atomic_void_addi64_relaxed(&stat->total, &src->total);}+#define MI_STAT_COUNT(stat) mi_stat_count_add_mt(&stats->stat, &src->stat);+#define MI_STAT_COUNTER(stat) mi_stat_counter_add_mt(&stats->stat, &src->stat);+// must be thread safe as it is called from stats_mergestatic void mi_stats_add(mi_stats_t* stats, const mi_stats_t* src) {if (stats==src) return;- mi_stat_add(&stats->segments, &src->segments,1);- mi_stat_add(&stats->pages, &src->pages,1);- mi_stat_add(&stats->reserved, &src->reserved, 1);- mi_stat_add(&stats->committed, &src->committed, 1);- mi_stat_add(&stats->reset, &src->reset, 1);- mi_stat_add(&stats->purged, &src->purged, 1);- mi_stat_add(&stats->page_committed, &src->page_committed, 1);-- mi_stat_add(&stats->pages_abandoned, &src->pages_abandoned, 1);- mi_stat_add(&stats->segments_abandoned, &src->segments_abandoned, 1);- mi_stat_add(&stats->threads, &src->threads, 1);-- mi_stat_add(&stats->malloc, &src->malloc, 1);- mi_stat_add(&stats->segments_cache, &src->segments_cache, 1);- mi_stat_add(&stats->normal, &src->normal, 1);- mi_stat_add(&stats->huge, &src->huge, 1);- mi_stat_add(&stats->large, &src->large, 1);-- mi_stat_counter_add(&stats->pages_extended, &src->pages_extended, 1);- mi_stat_counter_add(&stats->mmap_calls, &src->mmap_calls, 1);- mi_stat_counter_add(&stats->commit_calls, &src->commit_calls, 1);- mi_stat_counter_add(&stats->reset_calls, &src->reset_calls, 1);- mi_stat_counter_add(&stats->purge_calls, &src->purge_calls, 1);-- mi_stat_counter_add(&stats->page_no_retire, &src->page_no_retire, 1);- mi_stat_counter_add(&stats->searches, &src->searches, 1);- mi_stat_counter_add(&stats->normal_count, &src->normal_count, 1);- mi_stat_counter_add(&stats->huge_count, &src->huge_count, 1);- mi_stat_counter_add(&stats->large_count, &src->large_count, 1);- mi_stat_counter_add(&stats->guarded_alloc_count, &src->guarded_alloc_count, 1);-#if MI_STAT>1++ // copy all fields+ MI_STAT_FIELDS()++ #if MI_STAT>1for (size_t i = 0; i <= MI_BIN_HUGE; i++) {- if (src->normal_bins[i].allocated > 0 || src->normal_bins[i].freed > 0) {- mi_stat_add(&stats->normal_bins[i], &src->normal_bins[i], 1);- }+ mi_stat_count_add_mt(&stats->malloc_bins[i], &src->malloc_bins[i]);+ }+ #endif+ for (size_t i = 0; i <= MI_BIN_HUGE; i++) {+ mi_stat_count_add_mt(&stats->page_bins[i], &src->page_bins[i]);}-#endif}+#undef MI_STAT_COUNT+#undef MI_STAT_COUNTER+/* -----------------------------------------------------------Display statistics----------------------------------------------------------- */@@ -166,7 +143,7 @@ static void mi_stats_add(mi_stats_t* stats, const mi_stats_t* src) {// unit == 0: count as decimal// unit < 0 : count in binarystatic void mi_printf_amount(int64_t n, int64_t unit, mi_output_fun* out, void* arg, const char* fmt) {- char buf[32]; buf[0] = 0;+ char buf[32]; _mi_memzero_var(buf);int len = 32;const char* suffix = (unit <= 0 ? " " : "B");const int64_t base = (unit == 0 ? 1000 : 1024);@@ -204,30 +181,30 @@ static void mi_print_count(int64_t n, int64_t unit, mi_output_fun* out, void* ar}static void mi_stat_print_ex(const mi_stat_count_t* stat, const char* msg, int64_t unit, mi_output_fun* out, void* arg, const char* notok ) {- _mi_fprintf(out, arg,"%10s:", msg);+ _mi_fprintf(out, arg," %-10s:", msg);if (unit != 0) {if (unit > 0) {mi_print_amount(stat->peak, unit, out, arg);- mi_print_amount(stat->allocated, unit, out, arg);- mi_print_amount(stat->freed, unit, out, arg);+ mi_print_amount(stat->total, unit, out, arg);+ // mi_print_amount(stat->freed, unit, out, arg);mi_print_amount(stat->current, unit, out, arg);mi_print_amount(unit, 1, out, arg);- mi_print_count(stat->allocated, unit, out, arg);+ mi_print_count(stat->total, unit, out, arg);}else {mi_print_amount(stat->peak, -1, out, arg);- mi_print_amount(stat->allocated, -1, out, arg);- mi_print_amount(stat->freed, -1, out, arg);+ mi_print_amount(stat->total, -1, out, arg);+ // mi_print_amount(stat->freed, -1, out, arg);mi_print_amount(stat->current, -1, out, arg);if (unit == -1) {_mi_fprintf(out, arg, "%24s", "");}else {mi_print_amount(-unit, 1, out, arg);- mi_print_count((stat->allocated / -unit), 0, out, arg);+ mi_print_count((stat->total / -unit), 0, out, arg);}}- if (stat->allocated > stat->freed) {+ if (stat->current != 0) {_mi_fprintf(out, arg, " ");_mi_fprintf(out, arg, (notok == NULL ? "not all freed" : notok));_mi_fprintf(out, arg, "\n");@@ -238,7 +215,7 @@ static void mi_stat_print_ex(const mi_stat_count_t* stat, const char* msg, int64}else {mi_print_amount(stat->peak, 1, out, arg);- mi_print_amount(stat->allocated, 1, out, arg);+ mi_print_amount(stat->total, 1, out, arg);_mi_fprintf(out, arg, "%11s", " "); // no freedmi_print_amount(stat->current, 1, out, arg);_mi_fprintf(out, arg, "\n");@@ -249,47 +226,54 @@ static void mi_stat_print(const mi_stat_count_t* stat, const char* msg, int64_tmi_stat_print_ex(stat, msg, unit, out, arg, NULL);}-static void mi_stat_peak_print(const mi_stat_count_t* stat, const char* msg, int64_t unit, mi_output_fun* out, void* arg) {- _mi_fprintf(out, arg, "%10s:", msg);- mi_print_amount(stat->peak, unit, out, arg);+#if MI_STAT>1+static void mi_stat_total_print(const mi_stat_count_t* stat, const char* msg, int64_t unit, mi_output_fun* out, void* arg) {+ _mi_fprintf(out, arg, " %-10s:", msg);+ _mi_fprintf(out, arg, "%12s", " "); // no peak+ mi_print_amount(stat->total, unit, out, arg);_mi_fprintf(out, arg, "\n");}+#endifstatic void mi_stat_counter_print(const mi_stat_counter_t* stat, const char* msg, mi_output_fun* out, void* arg ) {- _mi_fprintf(out, arg, "%10s:", msg);+ _mi_fprintf(out, arg, " %-10s:", msg);mi_print_amount(stat->total, -1, out, arg);_mi_fprintf(out, arg, "\n");}-static void mi_stat_counter_print_avg(const mi_stat_counter_t* stat, const char* msg, mi_output_fun* out, void* arg) {- const int64_t avg_tens = (stat->count == 0 ? 0 : (stat->total*10 / stat->count));+static void mi_stat_average_print(size_t count, size_t total, const char* msg, mi_output_fun* out, void* arg) {+ const int64_t avg_tens = (count == 0 ? 0 : (total*10 / count));const long avg_whole = (long)(avg_tens/10);const long avg_frac1 = (long)(avg_tens%10);- _mi_fprintf(out, arg, "%10s: %5ld.%ld avg\n", msg, avg_whole, avg_frac1);+ _mi_fprintf(out, arg, " %-10s: %5ld.%ld avg\n", msg, avg_whole, avg_frac1);}-static void mi_print_header(mi_output_fun* out, void* arg ) {- _mi_fprintf(out, arg, "%10s: %11s %11s %11s %11s %11s %11s\n", "heap stats", "peak ", "total ", "freed ", "current ", "unit ", "count ");+static void mi_print_header(const char* name,mi_output_fun* out, void* arg ) {+ _mi_fprintf(out, arg, " %-11s %11s %11s %11s %11s %11s\n",+ name, "peak ", "total ", "current ", "block ", "total# ");}#if MI_STAT>1-static void mi_stats_print_bins(const mi_stat_count_t* bins, size_t max, const char* fmt, mi_output_fun* out, void* arg) {+static bool mi_stats_print_bins(const mi_stat_count_t* bins, size_t max, mi_output_fun* out, void* arg) {bool found = false;char buf[64];for (size_t i = 0; i <= max; i++) {- if (bins[i].allocated > 0) {+ if (bins[i].total > 0) {found = true;- int64_t unit = _mi_bin_size((uint8_t)i);- _mi_snprintf(buf, 64, "%s %3lu", fmt, (long)i);- mi_stat_print(&bins[i], buf, unit, out, arg);+ const size_t unit = _mi_bin_size((uint8_t)i);+ const char* pagekind = (unit <= MI_SMALL_MAX_OBJ_SIZE ? "S" :+ (unit <= MI_MEDIUM_MAX_OBJ_SIZE ? "M" :+ (unit <= MI_LARGE_MAX_OBJ_SIZE ? "L" : "H")));+ _mi_snprintf(buf, 64, "bin%2s %3lu", pagekind, (long)i);+ mi_stat_print(&bins[i], buf, (int64_t)unit, out, arg);}}if (found) {_mi_fprintf(out, arg, "\n");- mi_print_header(out, arg);}+ return found;}#endif@@ -329,57 +313,8 @@ static void mi_cdecl mi_buffered_out(const char* msg, void* arg) {// Print statistics//-------------------------------------------------------------static void _mi_stats_print(mi_stats_t* stats, mi_output_fun* out0, void* arg0) mi_attr_noexcept {- // wrap the output function to be line buffered- char buf[256];- buffered_t buffer = { out0, arg0, NULL, 0, 255 };- buffer.buf = buf;- mi_output_fun* out = &mi_buffered_out;- void* arg = &buffer;-- // and print using that- mi_print_header(out,arg);- #if MI_STAT>1- mi_stats_print_bins(stats->normal_bins, MI_BIN_HUGE, "normal",out,arg);- #endif- #if MI_STAT- mi_stat_print(&stats->normal, "normal", (stats->normal_count.count == 0 ? 1 : -(stats->normal.allocated / stats->normal_count.count)), out, arg);- mi_stat_print(&stats->large, "large", (stats->large_count.count == 0 ? 1 : -(stats->large.allocated / stats->large_count.count)), out, arg);- mi_stat_print(&stats->huge, "huge", (stats->huge_count.count == 0 ? 1 : -(stats->huge.allocated / stats->huge_count.count)), out, arg);- mi_stat_count_t total = { 0,0,0,0 };- mi_stat_add(&total, &stats->normal, 1);- mi_stat_add(&total, &stats->large, 1);- mi_stat_add(&total, &stats->huge, 1);- mi_stat_print(&total, "total", 1, out, arg);- #endif- #if MI_STAT>1- mi_stat_print(&stats->malloc, "malloc req", 1, out, arg);- _mi_fprintf(out, arg, "\n");- #endif- mi_stat_print_ex(&stats->reserved, "reserved", 1, out, arg, "");- mi_stat_print_ex(&stats->committed, "committed", 1, out, arg, "");- mi_stat_peak_print(&stats->reset, "reset", 1, out, arg );- mi_stat_peak_print(&stats->purged, "purged", 1, out, arg );- mi_stat_print(&stats->page_committed, "touched", 1, out, arg);- mi_stat_print(&stats->segments, "segments", -1, out, arg);- mi_stat_print(&stats->segments_abandoned, "-abandoned", -1, out, arg);- mi_stat_print(&stats->segments_cache, "-cached", -1, out, arg);- mi_stat_print(&stats->pages, "pages", -1, out, arg);- mi_stat_print(&stats->pages_abandoned, "-abandoned", -1, out, arg);- mi_stat_counter_print(&stats->pages_extended, "-extended", out, arg);- mi_stat_counter_print(&stats->page_no_retire, "-noretire", out, arg);- mi_stat_counter_print(&stats->arena_count, "arenas", out, arg);- mi_stat_counter_print(&stats->arena_crossover_count, "-crossover", out, arg);- mi_stat_counter_print(&stats->arena_rollback_count, "-rollback", out, arg);- mi_stat_counter_print(&stats->mmap_calls, "mmaps", out, arg);- mi_stat_counter_print(&stats->commit_calls, "commits", out, arg);- mi_stat_counter_print(&stats->reset_calls, "resets", out, arg);- mi_stat_counter_print(&stats->purge_calls, "purges", out, arg);- mi_stat_counter_print(&stats->guarded_alloc_count, "guarded", out, arg);- mi_stat_print(&stats->threads, "threads", -1, out, arg);- mi_stat_counter_print_avg(&stats->searches, "searches", out, arg);- _mi_fprintf(out, arg, "%10s: %5zu\n", "numa nodes", _mi_os_numa_node_count());-+mi_decl_export void mi_process_info_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept+{size_t elapsed;size_t user_time;size_t sys_time;@@ -389,58 +324,186 @@ static void _mi_stats_print(mi_stats_t* stats, mi_output_fun* out0, void* arg0)size_t peak_commit;size_t page_faults;mi_process_info(&elapsed, &user_time, &sys_time, ¤t_rss, &peak_rss, ¤t_commit, &peak_commit, &page_faults);- _mi_fprintf(out, arg, "%10s: %5ld.%03ld s\n", "elapsed", elapsed/1000, elapsed%1000);- _mi_fprintf(out, arg, "%10s: user: %ld.%03ld s, system: %ld.%03ld s, faults: %lu, rss: ", "process",- user_time/1000, user_time%1000, sys_time/1000, sys_time%1000, (unsigned long)page_faults );+ _mi_fprintf(out, arg, " %-10s: %5zu.%03zu s\n", "elapsed", elapsed/1000, elapsed%1000);+ _mi_fprintf(out, arg, " %-10s: user: %zu.%03zu s, system: %zu.%03zu s, faults: %zu, peak rss: ", "process",+ user_time/1000, user_time%1000, sys_time/1000, sys_time%1000, page_faults);mi_printf_amount((int64_t)peak_rss, 1, out, arg, "%s");if (peak_commit > 0) {- _mi_fprintf(out, arg, ", commit: ");+ _mi_fprintf(out, arg, ", peak commit: ");mi_printf_amount((int64_t)peak_commit, 1, out, arg, "%s");}_mi_fprintf(out, arg, "\n");}+void _mi_stats_print(const char* name, size_t id, mi_stats_t* stats, mi_output_fun* out0, void* arg0) mi_attr_noexcept {+ // wrap the output function to be line buffered+ char buf[256]; _mi_memzero_var(buf);+ buffered_t buffer = { out0, arg0, NULL, 0, 255 };+ buffer.buf = buf;+ mi_output_fun* out = &mi_buffered_out;+ void* arg = &buffer;++ // and print using that+ _mi_fprintf(out, arg, "%s %zu\n", name, id);++ if (stats->malloc_normal.total + stats->malloc_huge.total != 0) {+ #if MI_STAT>1+ mi_print_header("blocks", out, arg);+ mi_stats_print_bins(stats->malloc_bins, MI_BIN_HUGE, out, arg);+ #endif+ #if MI_STAT+ mi_stat_print(&stats->malloc_normal, "binned", (stats->malloc_normal_count.total == 0 ? 1 : -1), out, arg);+ mi_stat_print(&stats->malloc_huge, "huge", (stats->malloc_huge_count.total == 0 ? 1 : -1), out, arg);+ mi_stat_count_t total = { 0,0,0 };+ mi_stat_count_add_mt(&total, &stats->malloc_normal);+ mi_stat_count_add_mt(&total, &stats->malloc_huge);+ mi_stat_print_ex(&total, "total", 1, out, arg, "");+ #if MI_STAT>1+ mi_stat_total_print(&stats->malloc_requested, "malloc req", 1, out, arg);+ #endif+ _mi_fprintf(out, arg, "\n");+ #endif+ }++ if (stats->pages.total != 0) {+ mi_print_header("pages", out, arg);+ mi_stat_print_ex(&stats->page_committed, "touched", 1, out, arg, "");+ // mi_stat_print(&stats->segments, "segments", -1, out, arg);+ // mi_stat_print(&stats->segments_abandoned, "-abandoned", -1, out, arg);+ // mi_stat_print(&stats->segments_cache, "-cached", -1, out, arg);+ mi_stat_print(&stats->pages, "pages", -1, out, arg);+ mi_stat_print(&stats->pages_abandoned, "abandoned", -1, out, arg);+ mi_stat_counter_print(&stats->pages_reclaim_on_alloc, "reclaima", out, arg);+ mi_stat_counter_print(&stats->pages_reclaim_on_free, "reclaimf", out, arg);+ mi_stat_counter_print(&stats->pages_reabandon_full, "reabandon", out, arg);+ mi_stat_counter_print(&stats->pages_unabandon_busy_wait, "waits", out, arg);+ mi_stat_counter_print(&stats->pages_extended, "extended", out, arg);+ mi_stat_counter_print(&stats->pages_retire, "retire", out, arg);+ mi_stat_average_print(stats->page_searches_count.total, stats->page_searches.total, "searches", out, arg);+ _mi_fprintf(out, arg, "\n");+ }++ if (stats->arena_count.total > 0) {+ mi_print_header("arenas", out, arg);+ mi_stat_print_ex(&stats->reserved, "reserved", 1, out, arg, "");+ mi_stat_print_ex(&stats->committed, "committed", 1, out, arg, "");+ mi_stat_counter_print(&stats->reset, "reset", out, arg);+ mi_stat_counter_print(&stats->purged, "purged", out, arg);++ mi_stat_counter_print(&stats->arena_count, "arenas", out, arg);+ mi_stat_counter_print(&stats->arena_rollback_count, "rollback", out, arg);+ mi_stat_counter_print(&stats->mmap_calls, "mmaps", out, arg);+ mi_stat_counter_print(&stats->commit_calls, "commits", out, arg);+ mi_stat_counter_print(&stats->reset_calls, "resets", out, arg);+ mi_stat_counter_print(&stats->purge_calls, "purges", out, arg);+ mi_stat_counter_print(&stats->malloc_guarded_count, "guarded", out, arg);+ mi_stat_print_ex(&stats->heaps, "heaps", -1, out, arg, "");+ _mi_fprintf(out, arg, "\n");++ mi_print_header("process", out, arg);+ mi_stat_print_ex(&stats->threads, "threads", -1, out, arg, "");+ _mi_fprintf(out, arg, " %-10s: %5i\n", "numa nodes", _mi_os_numa_node_count());+ mi_process_info_print_out(out, arg);+ }+ _mi_fprintf(out, arg, "\n");+}++static mi_msecs_t mi_process_start; // = 0-static mi_stats_t* mi_stats_get_default(void) {- mi_heap_t* heap = mi_heap_get_default();- return &heap->tld->stats;+// called on process init+void _mi_stats_init(void) {+ if (mi_process_start == 0) { mi_process_start = _mi_clock_start(); };}-static void mi_stats_merge_from(mi_stats_t* stats) {- if (stats != &_mi_stats_main) {- mi_stats_add(&_mi_stats_main, stats);- memset(stats, 0, sizeof(mi_stats_t));- }+static void mi_stats_add_into(mi_stats_t* to, mi_stats_t* from) {+ mi_assert_internal(to != NULL && from != NULL);+ if (to == from) return;+ mi_stats_add(to, from);+}++void _mi_stats_merge_into(mi_stats_t* to, mi_stats_t* from) {+ mi_assert_internal(to != NULL && from != NULL);+ if (to == from) return;+ mi_stats_add(to, from);+ _mi_memzero(from, sizeof(mi_stats_t));+}++static mi_stats_t* mi_stats_merge_theap_to_heap(mi_theap_t* theap) mi_attr_noexcept {+ mi_stats_t* stats = &theap->stats;+ mi_stats_t* heap_stats = &theap->heap->stats;+ _mi_stats_merge_into( heap_stats, stats );+ return heap_stats;}+static mi_stats_t* mi_heap_get_stats(mi_heap_t* heap) {+ if (heap==NULL) { heap = mi_heap_main(); }+ mi_theap_t* theap = _mi_heap_theap_peek(heap);+ if (theap==NULL) return &heap->stats;+ else return mi_stats_merge_theap_to_heap(theap);+}++// deprecatedvoid mi_stats_reset(void) mi_attr_noexcept {- mi_stats_t* stats = mi_stats_get_default();- if (stats != &_mi_stats_main) { memset(stats, 0, sizeof(mi_stats_t)); }- memset(&_mi_stats_main, 0, sizeof(mi_stats_t));- if (mi_process_start == 0) { mi_process_start = _mi_clock_start(); };+ if (!mi_theap_is_initialized(_mi_theap_default())) return;+ mi_heap_get_stats(mi_heap_main());+ mi_heap_stats_merge_to_subproc(mi_heap_main());}-void mi_stats_merge(void) mi_attr_noexcept {- mi_stats_merge_from( mi_stats_get_default() );++void mi_heap_stats_print_out(mi_heap_t* heap, mi_output_fun* out, void* arg) mi_attr_noexcept {+ if (heap==NULL) { heap = mi_heap_main(); }+ _mi_stats_print("heap", heap->heap_seq, mi_heap_get_stats(heap), out, arg);+}++typedef struct mi_heap_print_visit_info_s {+ mi_output_fun* out;+ void* out_arg;+} mi_heap_print_visit_info_t;++static bool mi_cdecl mi_heap_print_visitor(mi_heap_t* heap, void* arg) {+ mi_heap_print_visit_info_t* vinfo = (mi_heap_print_visit_info_t*)(arg);+ mi_heap_stats_print_out(heap, vinfo->out, vinfo->out_arg);+ return true;}-void _mi_stats_done(mi_stats_t* stats) { // called from `mi_thread_done`- mi_stats_merge_from(stats);++// show each heap and then the subproc+void mi_subproc_heap_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun* out, void* arg) mi_attr_noexcept {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL) return;+ mi_heap_print_visit_info_t vinfo = { out, arg };+ mi_subproc_visit_heaps(subproc, &mi_heap_print_visitor, &vinfo);+ _mi_stats_print("subproc", subproc->subproc_seq, &subproc->stats, out, arg);+}+++// aggregate all stats from the heaps and subproc and print those+void mi_subproc_stats_print_out(mi_subproc_id_t subproc_id, mi_output_fun* out, void* arg) mi_attr_noexcept {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL) return;+ mi_stats_t_decl(stats);+ if (mi_subproc_stats_get(subproc_id, &stats)) {+ _mi_stats_print("subproc", subproc->subproc_seq, &stats, out, arg);+ }}void mi_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept {- mi_stats_merge_from(mi_stats_get_default());- _mi_stats_print(&_mi_stats_main, out, arg);+ mi_subproc_stats_print_out(mi_subproc_current(),out, arg);}+// deprecatedvoid mi_stats_print(void* out) mi_attr_noexcept {// for compatibility there is an `out` parameter (which can be `stdout` or `stderr`)mi_stats_print_out((mi_output_fun*)out, NULL);}+// deprecatedvoid mi_thread_stats_print_out(mi_output_fun* out, void* arg) mi_attr_noexcept {- _mi_stats_print(mi_stats_get_default(), out, arg);+ mi_theap_t* theap = _mi_theap_default();+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;+ _mi_stats_print("heap", theap->heap->heap_seq, &theap->stats, out, arg);+ mi_stats_merge_theap_to_heap(_mi_theap_default());}@@ -474,11 +537,12 @@ mi_msecs_t _mi_clock_end(mi_msecs_t start) {mi_decl_export void mi_process_info(size_t* elapsed_msecs, size_t* user_msecs, size_t* system_msecs, size_t* current_rss, size_t* peak_rss, size_t* current_commit, size_t* peak_commit, size_t* page_faults) mi_attr_noexcept{+ mi_subproc_t* subproc = _mi_subproc_main();mi_process_info_t pinfo;_mi_memzero_var(pinfo);pinfo.elapsed = _mi_clock_end(mi_process_start);- pinfo.current_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)&_mi_stats_main.committed.current));- pinfo.peak_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)&_mi_stats_main.committed.peak));+ pinfo.current_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.current)));+ pinfo.peak_commit = (size_t)(mi_atomic_loadi64_relaxed((_Atomic(int64_t)*)(&subproc->stats.committed.peak)));pinfo.current_rss = pinfo.current_commit;pinfo.peak_rss = pinfo.peak_commit;pinfo.utime = 0;@@ -496,3 +560,243 @@ mi_decl_export void mi_process_info(size_t* elapsed_msecs, size_t* user_msecs, sif (peak_commit!=NULL) *peak_commit = pinfo.peak_commit;if (page_faults!=NULL) *page_faults = pinfo.page_faults;}++mi_decl_export void mi_process_info_print(void) mi_attr_noexcept {+ mi_process_info_print_out(NULL, NULL);+}+++// --------------------------------------------------------+// Return statistics+// --------------------------------------------------------++size_t mi_stats_get_bin_size(size_t bin) mi_attr_noexcept {+ if (bin > MI_BIN_HUGE) return 0;+ return _mi_bin_size(bin);+}++static bool _mi_stats_get(mi_stats_t* stats_in, mi_stats_t* stats_out) mi_attr_noexcept {+ if (stats_out == NULL || stats_out->size != sizeof(mi_stats_t) || stats_out->version != MI_STAT_VERSION) return false;+ if (stats_in == NULL || stats_in->size != stats_out->size) return false;+ _mi_memcpy(stats_out, stats_in, stats_out->size);+ return true;+}++bool mi_subproc_stats_get_exclusive(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept {+ return _mi_stats_get(&_mi_subproc_from_id(subproc_id)->stats, stats);+}++bool mi_heap_stats_get(mi_heap_t* heap, mi_stats_t* stats) mi_attr_noexcept {+ return _mi_stats_get(mi_heap_get_stats(heap), stats);+}+++static bool mi_cdecl mi_heap_aggregate_visitor(mi_heap_t* heap, void* arg) {+ mi_stats_t* stats = (mi_stats_t*)arg;+ mi_stats_add_into(stats, &heap->stats);+ return true;+}++bool mi_subproc_stats_get(mi_subproc_id_t subproc_id, mi_stats_t* stats) mi_attr_noexcept {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (stats == NULL || stats->size != sizeof(mi_stats_t) || stats->version != MI_STAT_VERSION) return false;+ _mi_memzero(stats,stats->size);+ mi_subproc_visit_heaps(subproc, &mi_heap_aggregate_visitor, stats);+ mi_stats_add_into(stats, &subproc->stats);+ return true;+}++bool mi_stats_get(mi_stats_t* stats) mi_attr_noexcept {+ return mi_subproc_stats_get(mi_subproc_current(), stats);+}+++// --------------------------------------------------------+// Statics in json format+// --------------------------------------------------------++typedef struct mi_json_buf_s {+ char* buf;+ size_t size;+ size_t used;+ bool can_realloc;+} mi_json_buf_t;++static bool mi_json_buf_expand(mi_json_buf_t* hbuf) {+ if (hbuf==NULL) return false;+ if (hbuf->buf != NULL && hbuf->size>0) {+ hbuf->buf[hbuf->size-1] = 0;+ }+ if (hbuf->size > SIZE_MAX/2 || !hbuf->can_realloc) return false;+ const size_t newsize = (hbuf->size == 0 ? mi_good_size(12*MI_KiB) : 2*hbuf->size);+ char* const newbuf = (char*)mi_rezalloc(hbuf->buf, newsize);+ if (newbuf == NULL) return false;+ hbuf->buf = newbuf;+ hbuf->size = newsize;+ return true;+}++static void mi_json_buf_print(mi_json_buf_t* hbuf, const char* msg) {+ if (msg==NULL || hbuf==NULL) return;+ if (hbuf->used + 1 >= hbuf->size && !hbuf->can_realloc) return;+ for (const char* src = msg; *src != 0; src++) {+ char c = *src;+ if (hbuf->used + 1 >= hbuf->size) {+ if (!mi_json_buf_expand(hbuf)) return;+ }+ mi_assert_internal(hbuf->used < hbuf->size);+ hbuf->buf[hbuf->used++] = c;+ }+ mi_assert_internal(hbuf->used < hbuf->size);+ hbuf->buf[hbuf->used] = 0;+}++static void mi_json_buf_print_count_bin(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, size_t bin, bool add_comma) {+ const size_t binsize = mi_stats_get_bin_size(bin);+ const size_t pagesize = (binsize <= MI_SMALL_MAX_OBJ_SIZE ? MI_SMALL_PAGE_SIZE :+ (binsize <= MI_MEDIUM_MAX_OBJ_SIZE ? MI_MEDIUM_PAGE_SIZE :+ (binsize <= MI_LARGE_MAX_OBJ_SIZE ? MI_LARGE_PAGE_SIZE : 0)));+ char buf[128];+ _mi_snprintf(buf, 128, "%s{ \"total\": %lld, \"peak\": %lld, \"current\": %lld, \"block_size\": %zu, \"page_size\": %zu }%s\n", prefix, stat->total, stat->peak, stat->current, binsize, pagesize, (add_comma ? "," : ""));+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+}++static void mi_json_buf_print_count_cbin(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, mi_chunkbin_t bin, bool add_comma) {+ const char* cbin = " ";+ switch(bin) {+ case MI_CBIN_SMALL: cbin = "S"; break;+ case MI_CBIN_MEDIUM: cbin = "M"; break;+ case MI_CBIN_LARGE: cbin = "L"; break;+ case MI_CBIN_HUGE: cbin = "H"; break;+ case MI_CBIN_OTHER: cbin = "X"; break;+ default: cbin = " "; break;+ }+ char buf[128];+ _mi_snprintf(buf, 128, "%s{ \"total\": %lld, \"peak\": %lld, \"current\": %lld, \"bin\": \"%s\" }%s\n", prefix, stat->total, stat->peak, stat->current, cbin, (add_comma ? "," : ""));+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+}++static void mi_json_buf_print_count(mi_json_buf_t* hbuf, const char* prefix, mi_stat_count_t* stat, bool add_comma) {+ char buf[128];+ _mi_snprintf(buf, 128, "%s{ \"total\": %lld, \"peak\": %lld, \"current\": %lld }%s\n", prefix, stat->total, stat->peak, stat->current, (add_comma ? "," : ""));+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+}++static void mi_json_buf_print_count_value(mi_json_buf_t* hbuf, const char* name, mi_stat_count_t* stat) {+ char buf[128];+ _mi_snprintf(buf, 128, " \"%s\": ", name);+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+ mi_json_buf_print_count(hbuf, "", stat, true);+}++static void mi_json_buf_print_value(mi_json_buf_t* hbuf, const char* name, int64_t val) {+ char buf[128];+ _mi_snprintf(buf, 128, " \"%s\": %lld,\n", name, val);+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+}++static void mi_json_buf_print_size(mi_json_buf_t* hbuf, const char* name, size_t val, bool add_comma) {+ char buf[128];+ _mi_snprintf(buf, 128, " \"%s\": %zu%s\n", name, val, (add_comma ? "," : ""));+ buf[127] = 0;+ mi_json_buf_print(hbuf, buf);+}++static void mi_json_buf_print_counter_value(mi_json_buf_t* hbuf, const char* name, mi_stat_counter_t* stat) {+ mi_json_buf_print_value(hbuf, name, stat->total);+}++#define MI_STAT_COUNT(stat) mi_json_buf_print_count_value(&hbuf, #stat, &stats->stat);+#define MI_STAT_COUNTER(stat) mi_json_buf_print_counter_value(&hbuf, #stat, &stats->stat);++static char* mi_stats_get_json_from(mi_stats_t* stats, size_t output_size, char* output_buf) mi_attr_noexcept {+ if (stats==NULL || stats->size!=sizeof(mi_stats_t) || stats->version!=MI_STAT_VERSION) return NULL;+ mi_json_buf_t hbuf = { NULL, 0, 0, true };+ if (output_size > 0 && output_buf != NULL) {+ _mi_memzero(output_buf, output_size);+ hbuf.buf = output_buf;+ hbuf.size = output_size;+ hbuf.can_realloc = false;+ }+ else {+ if (!mi_json_buf_expand(&hbuf)) return NULL;+ }+ mi_json_buf_print(&hbuf, "{\n");+ mi_json_buf_print_value(&hbuf, "stat_version", MI_STAT_VERSION);+ mi_json_buf_print_value(&hbuf, "mimalloc_version", MI_MALLOC_VERSION);++ // process info+ mi_json_buf_print(&hbuf, " \"process\": {\n");+ size_t elapsed;+ size_t user_time;+ size_t sys_time;+ size_t current_rss;+ size_t peak_rss;+ size_t current_commit;+ size_t peak_commit;+ size_t page_faults;+ mi_process_info(&elapsed, &user_time, &sys_time, ¤t_rss, &peak_rss, ¤t_commit, &peak_commit, &page_faults);+ mi_json_buf_print_size(&hbuf, "elapsed_msecs", elapsed, true);+ mi_json_buf_print_size(&hbuf, "user_msecs", user_time, true);+ mi_json_buf_print_size(&hbuf, "system_msecs", sys_time, true);+ mi_json_buf_print_size(&hbuf, "page_faults", page_faults, true);+ mi_json_buf_print_size(&hbuf, "rss_current", current_rss, true);+ mi_json_buf_print_size(&hbuf, "rss_peak", peak_rss, true);+ mi_json_buf_print_size(&hbuf, "commit_current", current_commit, true);+ mi_json_buf_print_size(&hbuf, "commit_peak", peak_commit, false);+ mi_json_buf_print(&hbuf, " },\n");++ // statistics+ MI_STAT_FIELDS()++ // size bins+ mi_json_buf_print(&hbuf, " \"malloc_bins\": [\n");+ for (size_t i = 0; i <= MI_BIN_HUGE; i++) {+ mi_json_buf_print_count_bin(&hbuf, " ", &stats->malloc_bins[i], i, i!=MI_BIN_HUGE);+ }+ mi_json_buf_print(&hbuf, " ],\n");+ mi_json_buf_print(&hbuf, " \"page_bins\": [\n");+ for (size_t i = 0; i <= MI_BIN_HUGE; i++) {+ mi_json_buf_print_count_bin(&hbuf, " ", &stats->page_bins[i], i, i!=MI_BIN_HUGE);+ }+ mi_json_buf_print(&hbuf, " ],\n");+ mi_json_buf_print(&hbuf, " \"chunk_bins\": [\n");+ for (size_t i = 0; i < MI_CBIN_COUNT; i++) {+ mi_json_buf_print_count_cbin(&hbuf, " ", &stats->chunk_bins[i], (mi_chunkbin_t)i, i!=MI_CBIN_COUNT-1);+ }+ mi_json_buf_print(&hbuf, " ]\n");+ mi_json_buf_print(&hbuf, "}\n");+ if (hbuf.used >= hbuf.size) {+ // failed+ if (hbuf.can_realloc) { mi_free(hbuf.buf); }+ return NULL;+ }+ else {+ return hbuf.buf;+ }+}++char* mi_subproc_stats_get_json(mi_subproc_id_t subproc_id, size_t buf_size, char* buf) mi_attr_noexcept {+ mi_subproc_t* subproc = _mi_subproc_from_id(subproc_id);+ if (subproc==NULL) return NULL;+ mi_stats_t_decl(stats);+ if (!mi_subproc_stats_get(subproc_id,&stats)) return NULL;+ return mi_stats_get_json_from(&subproc->stats, buf_size, buf);+}++char* mi_heap_stats_get_json(mi_heap_t* heap, size_t buf_size, char* buf) mi_attr_noexcept {+ return mi_stats_get_json_from(mi_heap_get_stats(heap), buf_size, buf);+}++char* mi_stats_get_json(size_t buf_size, char* buf) mi_attr_noexcept {+ return mi_subproc_stats_get_json(mi_subproc_current(), buf_size, buf);+}++char* mi_stats_as_json(mi_stats_t* stats, size_t buf_size, char* buf) mi_attr_noexcept {+ return mi_stats_get_json_from(stats, buf_size, buf);+}diff --git a/vendored/mimalloc/src/theap.c b/vendored/mimalloc/src/theap.cnew file mode 100644index 000000000..47961afd3--- /dev/null+++ b/vendored/mimalloc/src/theap.c@@ -0,0 +1,674 @@+/*----------------------------------------------------------------------------+Copyright (c) 2018-2025, 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.+-----------------------------------------------------------------------------*/++#include "mimalloc.h"+#include "mimalloc/internal.h"+#include "mimalloc/prim.h" // _mi_theap_default++#if defined(_MSC_VER) && (_MSC_VER < 1920)+#pragma warning(disable:4204) // non-constant aggregate initializer+#endif++/* -----------------------------------------------------------+ Helpers+----------------------------------------------------------- */++// return `true` if ok, `false` to break+typedef bool (theap_page_visitor_fun)(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2);++// Visit all pages in a theap; returns `false` if break was called.+static bool mi_theap_visit_pages(mi_theap_t* theap, theap_page_visitor_fun* fn, void* arg1, void* arg2)+{+ if (theap==NULL || theap->page_count==0) return 0;++ // visit all pages+ #if MI_DEBUG>1+ size_t total = theap->page_count;+ size_t count = 0;+ #endif++ for (size_t i = 0; i <= MI_BIN_FULL; i++) {+ mi_page_queue_t* pq = &theap->pages[i];+ mi_page_t* page = pq->first;+ while(page != NULL) {+ mi_page_t* next = page->next; // save next in case the page gets removed from the queue+ mi_assert_internal(mi_page_theap(page) == theap);+ #if MI_DEBUG>1+ count++;+ #endif+ if (!fn(theap, pq, page, arg1, arg2)) return false;+ page = next; // and continue+ }+ }+ mi_assert_internal(count == total);+ return true;+}+++#if MI_DEBUG>=2+static bool mi_theap_page_is_valid(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {+ MI_UNUSED(arg1);+ MI_UNUSED(arg2);+ MI_UNUSED(pq);+ mi_assert_internal(mi_page_theap(page) == theap);+ mi_assert_expensive(_mi_page_is_valid(page));+ return true;+}+#endif+#if MI_DEBUG>=3+static bool mi_theap_is_valid(mi_theap_t* theap) {+ mi_assert_internal(theap!=NULL);+ mi_theap_visit_pages(theap, &mi_theap_page_is_valid, NULL, NULL);+ for (size_t bin = 0; bin < MI_BIN_COUNT; bin++) {+ mi_assert_internal(_mi_page_queue_is_valid(theap, &theap->pages[bin]));+ }+ return true;+}+#endif+++++/* -----------------------------------------------------------+ "Collect" pages by migrating `local_free` and `thread_free`+ lists and freeing empty pages. This is done when a thread+ stops (and in that case abandons pages if there are still+ blocks alive)+----------------------------------------------------------- */++typedef enum mi_collect_e {+ MI_NORMAL,+ MI_FORCE,+ MI_ABANDON+} mi_collect_t;+++static bool mi_theap_page_collect(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg_collect, void* arg2 ) {+ MI_UNUSED(arg2);+ MI_UNUSED(theap);+ mi_assert_internal(mi_theap_page_is_valid(theap, pq, page, NULL, NULL));+ mi_collect_t collect = *((mi_collect_t*)arg_collect);+ _mi_page_free_collect(page, collect >= MI_FORCE);+ if (mi_page_all_free(page)) {+ // no more used blocks, possibly free the page.+ if (collect >= MI_FORCE || page->retire_expire == 0) { // either forced/abandon, or not already retired+ // note: this will potentially free retired pages as well.+ _mi_page_free(page, pq);+ }+ }+ else if (collect == MI_ABANDON) {+ // still used blocks but the thread is done; abandon the page+ _mi_page_abandon(page, pq);+ }+ return true; // don't break+}++static void mi_theap_merge_stats(mi_theap_t* theap) {+ mi_assert_internal(mi_theap_is_initialized(theap));+ _mi_stats_merge_into(&theap->heap->stats, &theap->stats);+}++static void mi_theap_collect_ex(mi_theap_t* theap, mi_collect_t collect)+{+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;+ mi_assert_expensive(mi_theap_is_valid(theap));++ const bool force = (collect >= MI_FORCE);+ _mi_deferred_free(theap, force);++ // python/cpython#112532: we may be called from a thread that is not the owner of the theap+ // const bool is_main_thread = (_mi_is_main_thread() && theap->thread_id == _mi_thread_id());++ // collect retired pages+ _mi_theap_collect_retired(theap, force);++ // collect all pages owned by this thread+ mi_theap_visit_pages(theap, &mi_theap_page_collect, &collect, NULL);++ // collect arenas (this is program wide so don't force purges on abandonment of threads)+ //mi_atomic_storei64_release(&theap->tld->subproc->purge_expire, 1);+ _mi_arenas_collect(collect == MI_FORCE /* force purge? */, collect >= MI_FORCE /* visit all? */, theap->tld);++ // merge statistics+ mi_theap_merge_stats(theap);+}++void _mi_theap_collect_abandon(mi_theap_t* theap) {+ mi_theap_collect_ex(theap, MI_ABANDON);+}++void mi_theap_collect(mi_theap_t* theap, bool force) mi_attr_noexcept {+ mi_theap_collect_ex(theap, (force ? MI_FORCE : MI_NORMAL));+}++void mi_collect(bool force) mi_attr_noexcept {+ // cannot really collect process wide, just a theap..+ mi_theap_collect(_mi_theap_default(), force);+}++void mi_heap_collect(mi_heap_t* heap, bool force) {+ // cannot really collect a heap, just a theap..+ mi_theap_collect(mi_heap_theap(heap), force);+}++/* -----------------------------------------------------------+ Heap new+----------------------------------------------------------- */++mi_theap_t* mi_theap_get_default(void) {+ mi_theap_t* theap = _mi_theap_default();+ if mi_unlikely(!mi_theap_is_initialized(theap)) {+ mi_thread_init();+ theap = _mi_theap_default();+ mi_assert_internal(mi_theap_is_initialized(theap));+ }+ return theap;+}++// todo: make order of parameters consistent (but would that break compat with CPython?)+void _mi_theap_init(mi_theap_t* theap, mi_heap_t* heap, mi_tld_t* tld)+{+ mi_assert_internal(theap!=NULL);+ mi_memid_t memid = theap->memid;+ _mi_memcpy_aligned(theap, &_mi_theap_empty, sizeof(mi_theap_t));+ theap->memid = memid;+ theap->heap = heap;+ theap->tld = tld; // avoid reading the thread-local tld during initialization++ _mi_theap_options_init(theap);+ if (theap->tld->is_in_threadpool) {+ // if we run as part of a thread pool it is better to not arbitrarily reclaim abandoned pages into our theap.+ // this is checked in `free.c:mi_free_try_collect_mt`+ // .. but abandoning is good in this case: halve the full page retain (possibly to 0)+ // (so blocked threads do not hold on to too much memory)+ if (theap->page_full_retain > 0) {+ theap->page_full_retain = theap->page_full_retain / 4;+ }+ }++ // push on the thread local theaps list+ mi_theap_t* head = theap->tld->theaps;+ theap->tprev = NULL;+ theap->tnext = head;+ if (head!=NULL) { head->tprev = theap; }+ theap->tld->theaps = theap;++ // initialize random+ if (head == NULL) { // first theap in this thread?+ #if defined(_WIN32) && !defined(MI_SHARED_LIB)+ _mi_random_init_weak(&theap->random); // prevent allocation failure during bcrypt dll initialization with static linking (issue #1185)+ #else+ _mi_random_init(&theap->random);+ #endif+ }+ else {+ _mi_random_split(&head->random, &theap->random);+ }+ theap->cookie = _mi_theap_random_next(theap) | 1;+ _mi_theap_guarded_init(theap);++ // push on the heap's theap list+ mi_lock(&heap->theaps_lock) {+ head = heap->theaps;+ theap->hprev = NULL;+ theap->hnext = head;+ if (head!=NULL) { head->hprev = theap; }+ heap->theaps = theap;+ }+}++mi_theap_t* _mi_theap_create(mi_heap_t* heap, mi_tld_t* tld) {+ mi_assert_internal(tld!=NULL);+ mi_assert_internal(heap!=NULL);+ // allocate and initialize a theap+ mi_memid_t memid;+ mi_theap_t* theap;+ //if (!_mi_is_heap_main(heap)) {+ // theap = (mi_theap_t*)mi_heap_zalloc(mi_heap_main(),sizeof(mi_theap_t));+ // memid = _mi_memid_create(MI_MEM_HEAP_MAIN);+ // memid.initially_zero = memid.initially_committed = true;+ //}+ //else+ if (heap->exclusive_arena == NULL) {+ theap = (mi_theap_t*)_mi_meta_zalloc(sizeof(mi_theap_t), &memid);+ }+ else {+ // theaps associated with a specific arena are allocated in that arena+ // note: takes up at least one slice which is quite wasteful...+ const size_t size = _mi_align_up(sizeof(mi_theap_t),MI_ARENA_MIN_OBJ_SIZE);+ theap = (mi_theap_t*)_mi_arenas_alloc(heap, size, true, true, heap->exclusive_arena, tld->thread_seq, tld->numa_node, &memid);+ mi_assert_internal(memid.mem.os.size >= size);+ }+ if (theap==NULL) {+ _mi_error_message(ENOMEM, "unable to allocate theap meta-data\n");+ return NULL;+ }+ theap->memid = memid;+ _mi_theap_init(theap, heap, tld);+ return theap;+}++uintptr_t _mi_theap_random_next(mi_theap_t* theap) {+ return _mi_random_next(&theap->random);+}++// called from `mi_theap_delete` to free the internal theap resources.+void _mi_theap_free(mi_theap_t* theap) {+ mi_assert(theap != NULL);+ mi_assert_internal(mi_theap_is_initialized(theap));+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;++ // merge stats to the owning heap+ mi_theap_merge_stats(theap);++ // remove ourselves from the heap theaps list+ mi_lock(&theap->heap->theaps_lock) {+ if (theap->hnext != NULL) { theap->hnext->hprev = theap->hprev; }+ if (theap->hprev != NULL) { theap->hprev->hnext = theap->hnext; }+ else { mi_assert_internal(theap->heap->theaps == theap); theap->heap->theaps = theap->hnext; }+ }++ // remove ourselves from the thread local theaps list+ if (theap->tnext != NULL) { theap->tnext->tprev = theap->tprev; }+ if (theap->tprev != NULL) { theap->tprev->tnext = theap->tnext; }+ else { mi_assert_internal(theap->tld->theaps == theap); theap->tld->theaps = theap->tnext; }++ // and free the used memory+ if (theap->memid.memkind == MI_MEM_HEAP_MAIN) { // note: for now unused as it would access theap_default stats in mi_free of the current theap+ mi_assert_internal(_mi_is_heap_main(mi_heap_of(theap)));+ mi_free(theap);+ }+ else if (theap->memid.memkind == MI_MEM_META) {+ _mi_meta_free(theap, sizeof(*theap), theap->memid);+ }+ else {+ _mi_arenas_free(theap, _mi_align_up(sizeof(*theap),MI_ARENA_MIN_OBJ_SIZE), theap->memid ); // issue #1168, avoid assertion failure+ }+}+++/* -----------------------------------------------------------+ Heap destroy+----------------------------------------------------------- */+/*++// zero out the page queues+static void mi_theap_reset_pages(mi_theap_t* theap) {+ mi_assert_internal(theap != NULL);+ mi_assert_internal(mi_theap_is_initialized(theap));+ // TODO: copy full empty theap instead?+ _mi_memset(&theap->pages_free_direct, 0, sizeof(theap->pages_free_direct));+ _mi_memcpy_aligned(&theap->pages, &_mi_theap_empty.pages, sizeof(theap->pages));+ // theap->thread_delayed_free = NULL;+ theap->page_count = 0;+}++static bool _mi_theap_page_destroy(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* arg1, void* arg2) {+ MI_UNUSED(arg1);+ MI_UNUSED(arg2);+ MI_UNUSED(pq);++ // ensure no more thread_delayed_free will be added+ //_mi_page_use_delayed_free(page, MI_NEVER_DELAYED_FREE, false);++ // stats+ const size_t bsize = mi_page_block_size(page);+ if (bsize > MI_LARGE_MAX_OBJ_SIZE) {+ mi_theap_stat_decrease(theap, malloc_huge, bsize);+ }+ #if (MI_STAT>0)+ _mi_page_free_collect(page, false); // update used count+ const size_t inuse = page->used;+ if (bsize <= MI_LARGE_MAX_OBJ_SIZE) {+ mi_theap_stat_decrease(theap, malloc_normal, bsize * inuse);+ #if (MI_STAT>1)+ mi_theap_stat_decrease(theap, malloc_bins[_mi_bin(bsize)], inuse);+ #endif+ }+ // mi_theap_stat_decrease(theap, malloc_requested, bsize * inuse); // todo: off for aligned blocks...+ #endif++ /// pretend it is all free now+ mi_assert_internal(mi_page_thread_free(page) == NULL);+ page->used = 0;++ // and free the page+ // mi_page_free(page,false);+ page->next = NULL;+ page->prev = NULL;+ mi_page_set_theap(page, NULL);+ _mi_arenas_page_free(page, theap);++ return true; // keep going+}++void _mi_theap_destroy_pages(mi_theap_t* theap) {+ mi_theap_visit_pages(theap, &_mi_theap_page_destroy, NULL, NULL);+ mi_theap_reset_pages(theap);+}++#if MI_TRACK_HEAP_DESTROY+static bool mi_cdecl mi_theap_track_block_free(const mi_theap_t* theap, const mi_theap_area_t* area, void* block, size_t block_size, void* arg) {+ MI_UNUSED(theap); MI_UNUSED(area); MI_UNUSED(arg); MI_UNUSED(block_size);+ mi_track_free_size(block,mi_usable_size(block));+ return true;+}+#endif++void mi_theap_destroy(mi_theap_t* theap) {+ mi_assert(theap != NULL);+ mi_assert(mi_theap_is_initialized(theap));+ mi_assert(!theap->allow_page_reclaim);+ mi_assert(!theap->allow_page_abandon);+ mi_assert_expensive(mi_theap_is_valid(theap));+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;+ #if MI_GUARDED+ // _mi_warning_message("'mi_theap_destroy' called but MI_GUARDED is enabled -- using `mi_theap_delete` instead (theap at %p)\n", theap);+ mi_theap_delete(theap);+ return;+ #else+ if (theap->allow_page_reclaim) {+ _mi_warning_message("'mi_theap_destroy' called but ignored as the theap was not created with 'allow_destroy' (theap at %p)\n", theap);+ // don't free in case it may contain reclaimed pages,+ mi_theap_delete(theap);+ }+ else {+ // track all blocks as freed+ #if MI_TRACK_HEAP_DESTROY+ mi_theap_visit_blocks(theap, true, mi_theap_track_block_free, NULL);+ #endif+ // free all pages+ _mi_theap_destroy_pages(theap);+ mi_theap_free(theap,true);+ }+ #endif+}++// forcefully destroy all theaps in the current thread+void _mi_theap_unsafe_destroy_all(mi_theap_t* theap) {+ mi_assert_internal(theap != NULL);+ if (theap == NULL) return;+ mi_theap_t* curr = theap->tld->theaps;+ while (curr != NULL) {+ mi_theap_t* next = curr->next;+ if (!curr->allow_page_reclaim) {+ mi_theap_destroy(curr);+ }+ else {+ _mi_theap_destroy_pages(curr);+ }+ curr = next;+ }+}+*/++/* -----------------------------------------------------------+ Safe Heap delete+----------------------------------------------------------- */++// Safe delete a theap without freeing any still allocated blocks in that theap.+void _mi_theap_delete(mi_theap_t* theap)+{+ mi_assert(theap != NULL);+ mi_assert(mi_theap_is_initialized(theap));+ mi_assert_expensive(mi_theap_is_valid(theap));+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;++ // abandon all pages+ _mi_theap_collect_abandon(theap);++ mi_assert_internal(theap->page_count==0);+ _mi_theap_free(theap);+}++++/* -----------------------------------------------------------+ Load/unload theaps+----------------------------------------------------------- */+/*+void mi_theap_unload(mi_theap_t* theap) {+ mi_assert(mi_theap_is_initialized(theap));+ mi_assert_expensive(mi_theap_is_valid(theap));+ if (theap==NULL || !mi_theap_is_initialized(theap)) return;+ if (theap->heap->exclusive_arena == NULL) {+ _mi_warning_message("cannot unload theaps that are not associated with an exclusive arena\n");+ return;+ }++ // abandon all pages so all thread'id in the pages are cleared+ _mi_theap_collect_abandon(theap);+ mi_assert_internal(theap->page_count==0);++ // remove from theap list+ mi_theap_free(theap, false); // but don't actually free the memory++ // disassociate from the current thread-local and static state+ theap->tld = NULL;+ return;+}++bool mi_theap_reload(mi_theap_t* theap, mi_arena_id_t arena_id) {+ mi_assert(mi_theap_is_initialized(theap));+ if (theap==NULL || !mi_theap_is_initialized(theap)) return false;+ if (theap->heap->exclusive_arena == NULL) {+ _mi_warning_message("cannot reload theaps that were not associated with an exclusive arena\n");+ return false;+ }+ if (theap->tld != NULL) {+ _mi_warning_message("cannot reload theaps that were not unloaded first\n");+ return false;+ }+ mi_arena_t* arena = _mi_arena_from_id(arena_id);+ if (theap->heap->exclusive_arena != arena) {+ _mi_warning_message("trying to reload a theap at a different arena address: %p vs %p\n", theap->heap->exclusive_arena, arena);+ return false;+ }++ mi_assert_internal(theap->page_count==0);++ // re-associate with the current thread-local and static state+ theap->tld = mi_theap_get_default()->tld;++ // reinit direct pages (as we may be in a different process)+ mi_assert_internal(theap->page_count == 0);+ for (size_t i = 0; i < MI_PAGES_DIRECT; i++) {+ theap->pages_free_direct[i] = (mi_page_t*)&_mi_page_empty;+ }++ // push on the thread local theaps list+ theap->tnext = theap->tld->theaps;+ theap->tld->theaps = theap;+ return true;+}+*/+++/* -----------------------------------------------------------+ Visit all theap blocks and areas+ Todo: enable visiting abandoned pages, and+ enable visiting all blocks of all theaps across threads+----------------------------------------------------------- */++void _mi_heap_area_init(mi_heap_area_t* area, mi_page_t* page) {+ const size_t bsize = mi_page_block_size(page);+ const size_t ubsize = mi_page_usable_block_size(page);+ area->reserved = page->reserved * bsize;+ area->committed = page->capacity * bsize;+ area->blocks = mi_page_start(page);+ area->used = page->used; // number of blocks in use (#553)+ area->block_size = ubsize;+ area->full_block_size = bsize;+ area->reserved1 = page;+}++static void mi_get_fast_divisor(size_t divisor, uint64_t* magic, size_t* shift) {+ mi_assert_internal(divisor > 0 && divisor <= UINT32_MAX);+ *shift = MI_SIZE_BITS - mi_clz(divisor - 1);+ *magic = ((((uint64_t)1 << 32) * (((uint64_t)1 << *shift) - divisor)) / divisor + 1);+}++static size_t mi_fast_divide(size_t n, uint64_t magic, size_t shift) {+ mi_assert_internal(n <= UINT32_MAX);+ const uint64_t hi = ((uint64_t)n * magic) >> 32;+ return (size_t)((hi + n) >> shift);+}++bool _mi_theap_area_visit_blocks(const mi_heap_area_t* area, mi_page_t* page, mi_block_visit_fun* visitor, void* arg) {+ mi_assert(area != NULL);+ if (area==NULL) return true;+ mi_assert(page != NULL);+ if (page == NULL) return true;++ _mi_page_free_collect(page,true); // collect both thread_delayed and local_free+ mi_assert_internal(page->local_free == NULL);+ if (page->used == 0) return true;++ size_t psize;+ uint8_t* const pstart = mi_page_area(page, &psize);+ mi_heap_t* const heap = mi_page_heap(page);+ const size_t bsize = mi_page_block_size(page);+ const size_t ubsize = mi_page_usable_block_size(page); // without padding++ // optimize page with one block+ if (page->capacity == 1) {+ mi_assert_internal(page->used == 1 && page->free == NULL);+ return visitor(heap, area, pstart, ubsize, arg);+ }+ mi_assert(bsize <= UINT32_MAX);++ // optimize full pages+ if (page->used == page->capacity) {+ uint8_t* block = pstart;+ for (size_t i = 0; i < page->capacity; i++) {+ if (!visitor(heap, area, block, ubsize, arg)) return false;+ block += bsize;+ }+ return true;+ }++ // create a bitmap of free blocks.+ #define MI_MAX_BLOCKS (MI_SMALL_PAGE_SIZE / sizeof(void*))+ uintptr_t free_map[MI_MAX_BLOCKS / MI_INTPTR_BITS];+ const uintptr_t bmapsize = _mi_divide_up(page->capacity, MI_INTPTR_BITS);+ memset(free_map, 0, bmapsize * sizeof(intptr_t));+ if (page->capacity % MI_INTPTR_BITS != 0) {+ // mark left-over bits at the end as free+ size_t shift = (page->capacity % MI_INTPTR_BITS);+ uintptr_t mask = (UINTPTR_MAX << shift);+ free_map[bmapsize - 1] = mask;+ }++ // fast repeated division by the block size+ uint64_t magic;+ size_t shift;+ mi_get_fast_divisor(bsize, &magic, &shift);++ #if MI_DEBUG>1+ size_t free_count = 0;+ #endif+ for (mi_block_t* block = page->free; block != NULL; block = mi_block_next(page, block)) {+ #if MI_DEBUG>1+ free_count++;+ #endif+ mi_assert_internal((uint8_t*)block >= pstart && (uint8_t*)block < (pstart + psize));+ size_t offset = (uint8_t*)block - pstart;+ mi_assert_internal(offset % bsize == 0);+ mi_assert_internal(offset <= UINT32_MAX);+ size_t blockidx = mi_fast_divide(offset, magic, shift);+ mi_assert_internal(blockidx == offset / bsize);+ mi_assert_internal(blockidx < MI_MAX_BLOCKS);+ size_t bitidx = (blockidx / MI_INTPTR_BITS);+ size_t bit = blockidx - (bitidx * MI_INTPTR_BITS);+ free_map[bitidx] |= ((uintptr_t)1 << bit);+ }+ mi_assert_internal(page->capacity == (free_count + page->used));++ // walk through all blocks skipping the free ones+ #if MI_DEBUG>1+ size_t used_count = 0;+ #endif+ uint8_t* block = pstart;+ for (size_t i = 0; i < bmapsize; i++) {+ if (free_map[i] == 0) {+ // every block is in use+ for (size_t j = 0; j < MI_INTPTR_BITS; j++) {+ #if MI_DEBUG>1+ used_count++;+ #endif+ if (!visitor(heap, area, block, ubsize, arg)) return false;+ block += bsize;+ }+ }+ else {+ // visit the used blocks in the mask+ uintptr_t m = ~free_map[i];+ while (m != 0) {+ #if MI_DEBUG>1+ used_count++;+ #endif+ size_t bitidx = mi_ctz(m);+ if (!visitor(heap, area, block + (bitidx * bsize), ubsize, arg)) return false;+ m &= m - 1; // clear least significant bit+ }+ block += bsize * MI_INTPTR_BITS;+ }+ }+ mi_assert_internal(page->used == used_count);+ return true;+}++++// Separate struct to keep `mi_page_t` out of the public interface+typedef struct mi_theap_area_ex_s {+ mi_heap_area_t area;+ mi_page_t* page;+} mi_theap_area_ex_t;++typedef bool (mi_theap_area_visit_fun)(const mi_theap_t* theap, const mi_theap_area_ex_t* area, void* arg);++static bool mi_theap_visit_areas_page(mi_theap_t* theap, mi_page_queue_t* pq, mi_page_t* page, void* vfun, void* arg) {+ MI_UNUSED(theap);+ MI_UNUSED(pq);+ mi_theap_area_visit_fun* fun = (mi_theap_area_visit_fun*)vfun;+ mi_theap_area_ex_t xarea;+ xarea.page = page;+ _mi_heap_area_init(&xarea.area, page);+ return fun(theap, &xarea, arg);+}++// Visit all theap pages as areas+static bool mi_theap_visit_areas(const mi_theap_t* theap, mi_theap_area_visit_fun* visitor, void* arg) {+ if (visitor == NULL) return false;+ return mi_theap_visit_pages((mi_theap_t*)theap, &mi_theap_visit_areas_page, (void*)(visitor), arg); // note: function pointer to void* :-{+}++// Just to pass arguments+typedef struct mi_visit_blocks_args_s {+ bool visit_blocks;+ mi_block_visit_fun* visitor;+ void* arg;+} mi_visit_blocks_args_t;++static bool mi_theap_area_visitor(const mi_theap_t* theap, const mi_theap_area_ex_t* xarea, void* arg) {+ mi_visit_blocks_args_t* args = (mi_visit_blocks_args_t*)arg;+ if (!args->visitor(theap->heap, &xarea->area, NULL, xarea->area.block_size, args->arg)) return false;+ if (args->visit_blocks) {+ return _mi_theap_area_visit_blocks(&xarea->area, xarea->page, args->visitor, args->arg);+ }+ else {+ return true;+ }+}++// Visit all blocks in a theap+bool mi_theap_visit_blocks(const mi_theap_t* theap, bool visit_blocks, mi_block_visit_fun* visitor, void* arg) {+ mi_visit_blocks_args_t args = { visit_blocks, visitor, arg };+ return mi_theap_visit_areas(theap, &mi_theap_area_visitor, &args);+}+diff --git a/vendored/mimalloc/src/threadlocal.c b/vendored/mimalloc/src/threadlocal.cnew file mode 100644index 000000000..8e7c92b9f--- /dev/null+++ b/vendored/mimalloc/src/threadlocal.c@@ -0,0 +1,175 @@+/* ----------------------------------------------------------------------------+Copyright (c) 2019-2025, 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.+-----------------------------------------------------------------------------*/++/* ----------------------------------------------------------------------------+Implement dynamic thread local variables (for heap's).+Unlike most OS native implementations there is no limit on the number+that can be allocated.+-----------------------------------------------------------------------------*/++#include "mimalloc.h"+#include "mimalloc/internal.h"+#include "mimalloc/prim.h"++/* -----------------------------------------------------------+Each thread can have (a dynamically expanding) array of+thread-local values.+----------------------------------------------------------- */++typedef struct mi_thread_locals_s {+ size_t count;+ void* slots[1];+} mi_thread_locals_t;++static mi_thread_locals_t mi_thread_locals_empty = { 0, {NULL} };++mi_decl_thread mi_thread_locals_t* mi_thread_locals = &mi_thread_locals_empty; // always point to a valid `mi_thread_locals_t`++// dynamically reallocate the thread local slots when needed+static mi_thread_locals_t* mi_thread_locals_expand(mi_thread_local_t atleast) {+ mi_thread_locals_t* tls_old = mi_thread_locals;+ const size_t count_old = tls_old->count;+ size_t count;+ if (count_old==0) {+ tls_old = NULL; // so we allocate fresh from mi_thread_locals_empty+ count = 16; // start with 16 slots+ }+ else if (count_old >= 1024) {+ count = count_old + 1024; // at some point increase linearly+ }+ else {+ count = 2*count_old; // and double initially+ }+ if (count <= atleast) {+ count = atleast + 1;+ }+ mi_thread_locals_t* tls = (mi_thread_locals_t*)mi_rezalloc(tls_old, sizeof(mi_thread_locals_t) + count*sizeof(void*));+ if mi_unlikely(tls==NULL) return NULL;+ tls->count = count;+ mi_thread_locals = tls;+ return tls;+}++static mi_decl_noinline bool mi_thread_local_set_expand( mi_thread_local_t key, void* val ) {+ if (val==NULL) return true;+ mi_thread_locals_t* tls = mi_thread_locals_expand(key);+ if (tls==NULL) return false;+ mi_assert_internal(key < tls->count);+ mi_assert_internal(tls == mi_thread_locals);+ tls->slots[key] = val;+ return true;+}++// set a tls slot; returns `true` if successful.+// Can return `false` if we could not reallocate the slots array.+bool _mi_thread_local_set( mi_thread_local_t key, void* val ) {+ mi_thread_locals_t* tls = mi_thread_locals;+ mi_assert_internal(tls!=NULL);+ if mi_likely(key < tls->count) {+ tls->slots[key] = val;+ return true;+ }+ else {+ return mi_thread_local_set_expand( key, val ); // tailcall+ }+}++// get a tls slot value+void* _mi_thread_local_get( mi_thread_local_t key ) {+ const mi_thread_locals_t* const tls = mi_thread_locals;+ mi_assert_internal(tls!=NULL);+ if mi_likely(key < tls->count) {+ return tls->slots[key];+ }+ else {+ return NULL;+ }+}++void _mi_thread_locals_thread_done(void) {+ mi_thread_locals_t* const tls = mi_thread_locals;+ if (tls!=NULL && tls->count > 0) {+ mi_free(tls);+ mi_thread_locals = &mi_thread_locals_empty;+ }+}++/* -----------------------------------------------------------+Create and free fresh TLS key's+----------------------------------------------------------- */+#include "bitmap.h"++static mi_lock_t mi_thread_locals_lock; // we need a lock in order to re-allocate the slot bits+static mi_bitmap_t* mi_thread_locals_free; // reuse an arena bitmap to track which slots were assigned (1=free, 0=in-use)++void _mi_thread_locals_init(void) {+ mi_lock_init(&mi_thread_locals_lock);+}++void _mi_thread_locals_done(void) {+ mi_lock(&mi_thread_locals_lock) {+ mi_bitmap_t* const slots = mi_thread_locals_free;+ mi_free(slots);+ }+ mi_lock_done(&mi_thread_locals_lock);+}++// strange signature but allows us to reuse the arena code for claiming free pages+static bool mi_thread_local_claim(size_t _slice_index, mi_arena_t* _arena, bool* keep_set) {+ MI_UNUSED(_slice_index); MI_UNUSED(_arena);+ *keep_set = false;+ return true;+}++static mi_thread_local_t mi_thread_local_create_expand(void) {+ size_t key = 0;+ mi_bitmap_t* slots = mi_thread_locals_free;+ // 1024 bits at a time+ const size_t oldcount = (slots==NULL ? 0 : mi_bitmap_max_bits(slots));+ const size_t newcount = 1024 + oldcount;+ const size_t newsize = mi_bitmap_size( newcount, NULL );+ slots = (mi_bitmap_t*)mi_realloc_aligned(slots, newsize, MI_BCHUNK_SIZE);+ if (slots != NULL) {+ mi_bitmap_init(slots, newcount, true /* or otherwise we would zero all old entries */);+ mi_bitmap_unsafe_setN(slots, oldcount, newcount - oldcount);+ mi_thread_locals_free = slots;+ size_t idx = 0;+ if mi_likely(slots!=NULL && mi_bitmap_try_find_and_claim(slots,0,&idx,&mi_thread_local_claim,NULL)) {+ key = idx+1;+ }+ }+ return key;+}++// create a fresh key+mi_thread_local_t _mi_thread_local_create(void) {+ mi_thread_local_t key = 0;+ mi_lock(&mi_thread_locals_lock) {+ mi_bitmap_t* slots = mi_thread_locals_free;+ size_t idx = 0;+ if mi_likely(slots!=NULL && mi_bitmap_try_find_and_claim(slots,0,&idx,&mi_thread_local_claim,NULL)) {+ key = idx+1;+ }+ else {+ key = mi_thread_local_create_expand();+ }+ }+ return key;+}++// free a key+void _mi_thread_local_free(mi_thread_local_t key) {+ if (key==0) return;+ const size_t idx = key-1;+ mi_lock(&mi_thread_locals_lock) {+ mi_bitmap_t* const slots = mi_thread_locals_free;+ if (slots!=NULL && idx < mi_bitmap_max_bits(slots)) {+ mi_bitmap_set(slots,key-1);+ }+ }+}+diff --git a/vendored/mongoose/mongoose.c b/vendored/mongoose/mongoose.cindex 1d3087409..df80dfc39 100644--- a/vendored/mongoose/mongoose.c+++ b/vendored/mongoose/mongoose.c@@ -408,6 +408,7 @@ void mg_resolve(struct mg_connection *c, const char *url) {}}+// Response header length is 10 bytesstatic const uint8_t mdns_answer[] = {0, 1, // 2 bytes - record type, A0, 1, // 2 bytes - address class, INET@@ -415,6 +416,7 @@ static const uint8_t mdns_answer[] = {0, 4 // 2 bytes - address length};+// A name length is name->len + '.local' + 2 = name->len + 8static uint8_t *build_name(struct mg_str *name, uint8_t *p) {*p++ = (uint8_t) name->len; // label 1memcpy(p, name->buf, name->len), p += name->len;@@ -426,6 +428,7 @@ static uint8_t *build_name(struct mg_str *name, uint8_t *p) {void mg_getlocaddr(struct mg_connection *, struct mg_addr *, struct mg_addr *);+// An A record length is 10 + 4 = 14 bytesstatic uint8_t *build_a_record(struct mg_connection *c, uint8_t *p,struct mg_addr *addr) {memcpy(p, mdns_answer, sizeof(mdns_answer)), p += sizeof(mdns_answer);@@ -447,6 +450,7 @@ static uint8_t *build_a_record(struct mg_connection *c, uint8_t *p,return p;}+// A srv name length is r->srvcproto.len + '.local' + 2 = r->srvcproto.len + 8static uint8_t *build_srv_name(uint8_t *p, struct mg_dnssd_record *r) {*p++ = (uint8_t) r->srvcproto.len - 5; // label 1, up to '._tcp'memcpy(p, r->srvcproto.buf, r->srvcproto.len), p += r->srvcproto.len;@@ -467,6 +471,7 @@ static uint8_t *build_mysrv_name(struct mg_str *name, uint8_t *p,}#endif+// A PTR record length is 10 + name->len + 3 = name->len + 13static uint8_t *build_ptr_record(struct mg_str *name, uint8_t *p, uint16_t o) {uint16_t offset = mg_htons(o);memcpy(p, mdns_answer, sizeof(mdns_answer));@@ -481,6 +486,7 @@ static uint8_t *build_ptr_record(struct mg_str *name, uint8_t *p, uint16_t o) {return p;}+// An SRV record length is 10 + name->len + 9 = name->len + 19static uint8_t *build_srv_record(struct mg_str *name, uint8_t *p,struct mg_dnssd_record *r, uint16_t o) {uint16_t port = mg_htons(r->port);@@ -501,6 +507,7 @@ static uint8_t *build_srv_record(struct mg_str *name, uint8_t *p,return p;}+// A TXT record length is r->txt.len (txt contents) + 10static uint8_t *build_txt_record(uint8_t *p, struct mg_dnssd_record *r) {uint16_t len = mg_htons((uint16_t) r->txt.len);memcpy(p, mdns_answer, sizeof(mdns_answer));@@ -511,6 +518,8 @@ static uint8_t *build_txt_record(uint8_t *p, struct mg_dnssd_record *r) {return p;}+// Each additional record has a 2-byte field pointing to the name label+// RFC-6762 16: case-insensitivity --> RFC-1034, 1035static void handle_mdns_query(struct mg_connection *c) {@@ -599,6 +608,10 @@ static void handle_mdns_query(struct mg_connection *c) {uint8_t *o = p, *aux;uint16_t offset;if (respname->buf == NULL || respname->len == 0) return;+ if ((sizeof(*h) + req.r->srvcproto.len + 8 + respname->len + 13 + 2 ++ respname->len + 19 + 2 + req.r->txt.len + 10 + 2 + 14) >+ sizeof(buf)) // srv name + PTR + 2 + SRV + 2 + TXT + 2 + A+ return;h->num_other_prs = mg_htons(3); // 3 additional recordsp = build_srv_name(p, req.r);aux = build_ptr_record(respname, p, (uint16_t) (o - buf));@@ -619,12 +632,18 @@ static void handle_mdns_query(struct mg_connection *c) {*p |= 0xC0, p += 2;p = build_a_record(c, p, req.addr);} else if (rr.atype == MG_DNS_RTYPE_TXT) {+ if ((sizeof(*h) + req.r->srvcproto.len + 8 + req.r->txt.len + 10) >+ sizeof(buf)) // srv name + TXT+ return;p = build_srv_name(p, req.r);p = build_txt_record(p, req.r);} else if (rr.atype == MG_DNS_RTYPE_SRV) { // serve SRV + Auint8_t *o, *aux;uint16_t offset;if (respname->buf == NULL || respname->len == 0) return;+ if ((sizeof(*h) + req.r->srvcproto.len + 8 + respname->len + 19 + 2 ++ 14) > sizeof(buf)) // srv name + SRV + 2 + A+ return;h->num_other_prs = mg_htons(1); // 1 additional recordp = build_srv_name(p, req.r);o = p - 7; // point to '.local' label (\x05local\x00)@@ -638,6 +657,8 @@ static void handle_mdns_query(struct mg_connection *c) {} else { // A requested// RFC-6762 6: 0 Auth, 0 Additional RRsif (respname->buf == NULL || respname->len == 0) return;+ if ((sizeof(*h) + respname->len + 8 + 14) > sizeof(buf)) // name + A+ return;p = build_name(respname, p);p = build_a_record(c, p, req.addr);}@@ -1941,6 +1962,8 @@ static const char *skiptorn(const char *s, const char *end, struct mg_str *v) {static bool mg_http_parse_headers(const char *s, const char *end,struct mg_http_header *h, size_t max_hdrs) {size_t i, n;+ int cl_count = 0, te_count = 0, auth_count = 0;+ int conn_count = 0, cookie_count = 0;for (i = 0; i < max_hdrs; i++) {struct mg_str k = {NULL, 0}, v = {NULL, 0};if (s >= end) return false;@@ -1956,6 +1979,13 @@ static bool mg_http_parse_headers(const char *s, const char *end,while (v.len > 0 && (v.buf[v.len - 1] == ' ' || v.buf[v.len - 1] == '\t')) {v.len--; // Trim spaces}+ // detect duplicated headers -> discard+ if (((mg_strcasecmp(k, mg_str("Content-Length")) == 0) && (++cl_count > 1)) ||+ ((mg_strcasecmp(k, mg_str("Transfer-Encoding")) == 0) && (++te_count > 1)) ||+ ((mg_strcasecmp(k, mg_str("Authorization")) == 0) && (++auth_count > 1)) ||+ ((mg_strcasecmp(k, mg_str("Cookie")) == 0) && (++cookie_count > 1)) ||+ ((mg_strcasecmp(k, mg_str("Connection")) == 0) && (++conn_count > 1)))+ return false;// MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf));h[i].name = k, h[i].value = v; // Success. Assign values}@@ -1990,6 +2020,8 @@ int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {// If we're given a version, check that it is HTTP/x.xversion_prefix_valid =hm->proto.len > 5 && (mg_ncasecmp(hm->proto.buf, "HTTP/", 5) == 0);+ if (!is_response && !version_prefix_valid)+ return -1; // no version detected in requestif (!is_response && hm->proto.len > 0 &&(!version_prefix_valid || hm->proto.len != 8 ||(hm->proto.buf[5] < '0' || hm->proto.buf[5] > '9') ||@@ -2716,7 +2748,7 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {const char *buf = (char *) c->recv.buf + ofs;int n = mg_http_parse(buf, c->recv.len - ofs, &hm);struct mg_str *te; // Transfer - encoding header- bool is_chunked = false;+ bool is_chunked = false, is_http_1_0 = false;size_t old_len = c->recv.len;if (n < 0) {// We don't use mg_error() here, to avoid closing pipelined requests@@ -2739,7 +2771,11 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {hm.message.len = c->recv.len - ofs; // and closes now, deliver MSGhm.body.len = hm.message.len - (size_t) (hm.body.buf - hm.message.buf);}- if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {+ is_http_1_0 =+ hm.proto.len > 8 && mg_ncasecmp(hm.proto.buf, "HTTP/1.0", 8) == 0;+ // HTTP/1.0 does not use "Transfer-Encoding: chunked"+ if (!is_http_1_0 &&+ (te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {if (mg_strcasecmp(*te, mg_str("chunked")) == 0) {is_chunked = true;} else {@@ -2963,15 +2999,28 @@ static double mg_atod(const char *p, int len, int *numlen) {// Exponentialif (i < len && (p[i] == 'e' || p[i] == 'E')) {- int j, exp = 0, minus = 0;+ int exp = 0, minus = 0;i++;if (i < len && p[i] == '-') minus = 1, i++;if (i < len && p[i] == '+') i++;while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)exp = exp * 10 + (p[i++] - '0');- if (minus) exp = -exp;- for (j = 0; j < exp; j++) d *= 10.0;- for (j = 0; j < -exp; j++) d /= 10.0;+ // use fast exponentiation+ // https://en.wikipedia.org/wiki/Exponentiation_by_squaring+ if (exp != 0) {+ double x = 10, y = 1;+ if (exp > 308) exp = 308;+ if (minus) x = 0.1;+ while (exp > 1) {+ if (exp & 1) {+ y *= x;+ --exp;+ }+ x *= x;+ exp >>= 1;+ }+ d *= x * y;+ }}if (numlen != NULL) *numlen = i;@@ -5462,9 +5511,13 @@ static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,!(c->loc.is_ip6 ^ (pkt->ip6 != NULL))) // IP or IPv6 to same destbreak;if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&- !(c->loc.is_ip6 ^ (pkt->ip6 != NULL)) &&- lsn == (bool) c->is_listening &&- (lsn || c->rem.port == pkt->tcp->sport))+ ((lsn && c->is_listening && !(c->loc.is_ip6 ^ (pkt->ip6 != NULL))) ||+ (!lsn && !c->is_listening && c->rem.port == pkt->tcp->sport &&+ ((!c->loc.is_ip6 && c->rem.addr.ip4 == pkt->ip->src)+#if MG_ENABLE_IPV6+ || (c->loc.is_ip6 && MG_IP6MATCH(c->rem.addr.ip6, pkt->ip6->src))+#endif+ )))) // validate addr for established (not listening) connsbreak;}return c;@@ -6408,7 +6461,7 @@ static void backlog_poll(struct mg_mgr *mgr) {}// process options (MSS)-static void handle_opt(struct connstate *s, struct tcp *tcp, bool ip6) {+static bool handle_opt(struct connstate *s, struct tcp *tcp, bool ip6) {uint8_t *opts = (uint8_t *) (tcp + 1);int len = 4 * ((int) (tcp->off >> 4) - ((int) sizeof(*tcp) / 4));s->dmss = ip6 ? 1220 : 536; // assume default, RFC-9293 3.7.1@@ -6416,6 +6469,7 @@ static void handle_opt(struct connstate *s, struct tcp *tcp, bool ip6) {uint8_t kind = opts[0], optlen = 1;if (kind != 1) { // No-Operationif (kind == 0) break; // End of Option List+ if (len < 2 || opts[1] == 0) return false; // Malformed optionsoptlen = opts[1];if (kind == 2 && optlen == 4) // set received MSSs->dmss = (uint16_t) (((uint16_t) opts[2] << 8) + opts[3]);@@ -6424,6 +6478,7 @@ static void handle_opt(struct connstate *s, struct tcp *tcp, bool ip6) {opts += optlen;len -= optlen;}+ return true;}static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {@@ -6438,7 +6493,7 @@ static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {// - check clients (Group 1) and established connections (Group 3)if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {// client got a server connection accept- handle_opt(s, pkt->tcp, pkt->ip6 != NULL); // process options (MSS)+ if (!handle_opt(s, pkt->tcp, pkt->ip6 != NULL)) return; // process options (MSS)s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;tx_tcp_ctrlresp(ifp, pkt, TH_ACK, pkt->tcp->ack);c->is_connecting = 0; // Client connected@@ -6449,8 +6504,9 @@ static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {} else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {mg_error(c, "connection refused");} else if (c != NULL && pkt->tcp->flags & TH_RST) {- // TODO(): validate RST is within window (and optional with proper ACK)- mg_error(c, "peer RST"); // RFC-1122 4.2.2.13+ uint32_t seqno = mg_ntohl(pkt->tcp->seq);+ if (seqno >= s->ack && seqno < (s->ack + MG_TCPIP_WIN)) // RFC-9293 3.5.3+ mg_error(c, "peer RST"); // RFC-1122 4.2.2.13} else if (c != NULL) {// process segments->tmiss = 0; // Reset missed keep-alive counter@@ -6472,7 +6528,7 @@ static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {int key;uint32_t isn;if (pkt->tcp->sport != 0) {- handle_opt(&cs, pkt->tcp, pkt->ip6 != NULL); // process options (MSS)+ if (!handle_opt(&cs, pkt->tcp, pkt->ip6 != NULL)) return; // process options (MSS)key = backlog_insert(c, pkt->tcp->sport,cs.dmss); // backlog options (MSS)if (key < 0) return; // no room in backlog, discard SYN, client retries@@ -11365,7 +11421,9 @@ bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {} else if (i < p.len && (p.buf[i] == '*' || p.buf[i] == '#')) {if (caps && !caps->buf) caps->len = 0, caps->buf = &s.buf[j]; // Init capni = i++, nj = j + 1;- } else if (nj > 0 && nj <= s.len && ((ni < p.len && p.buf[ni] == '#') || s.buf[j] != '/')) {+ } else if (nj > 0 && nj <= s.len &&+ ((ni < p.len && p.buf[ni] == '#') ||+ (j < s.len && s.buf[j] != '/'))) {i = ni, j = nj;if (caps && caps->buf == NULL && caps->len == 0) {caps--, caps->len = 0; // Restart previous cap@@ -11446,8 +11504,7 @@ bool mg_str_to_num(struct mg_str str, int base, void *val, size_t val_len) {i++, ndigits++;}break;- default:- return false;+ default: return false;}if (ndigits == 0) return false;if (i != str.len) return false;@@ -11557,45 +11614,47 @@ static void aes_init_keygen_tables(void);/******************************************************************************* AES_SETKEY : called to expand the key for encryption or decryption******************************************************************************/-static int aes_setkey(aes_context *ctx, // pointer to context- int mode, // 1 or 0 for Encrypt/Decrypt- const unsigned char *key, // AES input key- unsigned int keysize); // size in bytes (must be 16, 24, 32 for- // 128, 192 or 256-bit keys respectively)- // returns 0 for success+static int aes_setkey(+ aes_context *ctx, // pointer to context+ int mode, // 1 or 0 for Encrypt/Decrypt+ const unsigned char *key, // AES input key+ unsigned int keysize); // size in bytes (must be 16, 24, 32 for+ // 128, 192 or 256-bit keys respectively)+ // returns 0 for success/******************************************************************************* AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data******************************************************************************/-static int aes_cipher(aes_context *ctx, // pointer to context- const unsigned char input[16], // 128-bit block to en/decipher- unsigned char output[16]); // 128-bit output result block- // returns 0 for success+static int aes_cipher(+ aes_context *ctx, // pointer to context+ const unsigned char input[16], // 128-bit block to en/decipher+ unsigned char output[16]); // 128-bit output result block+ // returns 0 for success/******************************************************************************* GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx******************************************************************************/typedef struct {- int mode; // cipher direction: encrypt/decrypt- uint64_t len; // cipher data length processed so far- uint64_t add_len; // total add data length- uint64_t HL[16]; // precalculated lo-half HTable- uint64_t HH[16]; // precalculated hi-half HTable+ int mode; // cipher direction: encrypt/decrypt+ uint64_t len; // cipher data length processed so far+ uint64_t add_len; // total add data length+ uint64_t HL[16]; // precalculated lo-half HTable+ uint64_t HH[16]; // precalculated hi-half HTableunsigned char base_ectr[16]; // first counter-mode cipher output for tagunsigned char y[16]; // the current cipher-input IV|Counter valueunsigned char buf[16]; // buf working value- aes_context aes_ctx; // cipher context used+ aes_context aes_ctx; // cipher context used} gcm_context;/******************************************************************************* GCM_SETKEY : sets the GCM (and AES) keying material for use******************************************************************************/static int gcm_setkey(- gcm_context *ctx, // caller-provided context ptr+ gcm_context *ctx, // caller-provided context ptrconst unsigned char *key, // pointer to cipher keyconst unsigned int keysize // size in bytes (must be 16, 24, 32 for- // 128, 192 or 256-bit keys respectively)-); // returns 0 for success+ // 128, 192 or 256-bit keys respectively)+); // returns 0 for success/*******************************************************************************@@ -11615,17 +11674,17 @@ static int gcm_setkey(*******************************************************************************/static int gcm_crypt_and_tag(- gcm_context *ctx, // gcm context with key already setup- int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)+ gcm_context *ctx, // gcm context with key already setup+ int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)const unsigned char *iv, // pointer to the 12-byte initialization vector- size_t iv_len, // byte length if the IV. should always be 12+ size_t iv_len, // byte length if the IV. should always be 12const unsigned char *add, // pointer to the non-ciphered additional data- size_t add_len, // byte length of the additional AEAD data+ size_t add_len, // byte length of the additional AEAD dataconst unsigned char *input, // pointer to the cipher data sourceunsigned char *output, // pointer to the cipher data destination- size_t length, // byte length of the cipher data+ size_t length, // byte length of the cipher dataunsigned char *tag, // pointer to the tag to be generated- size_t tag_len); // byte length of the tag to be generated+ size_t tag_len); // byte length of the tag to be generated/*******************************************************************************@@ -11636,12 +11695,12 @@ static int gcm_crypt_and_tag(*******************************************************************************/static int gcm_start(- gcm_context *ctx, // pointer to user-provided GCM context- int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)+ gcm_context *ctx, // pointer to user-provided GCM context+ int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)const unsigned char *iv, // pointer to initialization vector- size_t iv_len, // IV length in bytes (should == 12)+ size_t iv_len, // IV length in bytes (should == 12)const unsigned char *add, // pointer to additional AEAD data (NULL if none)- size_t add_len); // length of additional AEAD data (bytes)+ size_t add_len); // length of additional AEAD data (bytes)/*******************************************************************************@@ -11657,7 +11716,7 @@ static int gcm_start(static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM contextsize_t length, // length, in bytes, of data to processconst unsigned char *input, // pointer to source data- unsigned char *output); // pointer to destination data+ unsigned char *output); // pointer to destination data/*******************************************************************************@@ -11668,9 +11727,9 @@ static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context*******************************************************************************/static int gcm_finish(- gcm_context *ctx, // pointer to user-provided GCM context- unsigned char *tag, // ptr to tag buffer - NULL if tag_len = 0- size_t tag_len); // length, in bytes, of the tag-receiving buf+ gcm_context *ctx, // pointer to user-provided GCM context+ unsigned char *tag, // ptr to tag buffer - NULL if tag_len = 0+ size_t tag_len); // length, in bytes, of the tag-receiving buf/*******************************************************************************@@ -11721,15 +11780,15 @@ static int aes_tables_inited = 0; // run-once flag for performing key* decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.*/// We always need our forward tables-static unsigned char FSb[256]; // Forward substitution box (FSb)-static uint32_t FT0[256]; // Forward key schedule assembly tables+static unsigned char FSb[256]; // Forward substitution box (FSb)+static uint32_t FT0[256]; // Forward key schedule assembly tablesstatic uint32_t FT1[256];static uint32_t FT2[256];static uint32_t FT3[256];-#if AES_DECRYPTION // We ONLY need reverse for decryption-static unsigned char RSb[256]; // Reverse substitution box (RSb)-static uint32_t RT0[256]; // Reverse key schedule assembly tables+#if AES_DECRYPTION // We ONLY need reverse for decryption+static unsigned char RSb[256]; // Reverse substitution box (RSb)+static uint32_t RT0[256]; // Reverse key schedule assembly tablesstatic uint32_t RT1[256];static uint32_t RT2[256];static uint32_t RT3[256];@@ -11747,8 +11806,8 @@ static uint32_t RCON[10]; // AES round constants((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \}-#define PUT_UINT32_LE(n, b, i) \- { \+#define PUT_UINT32_LE(n, b, i) \+ { \(b)[(i)] = (unsigned char) ((n)); \(b)[(i) + 1] = (unsigned char) ((n) >> 8); \(b)[(i) + 2] = (unsigned char) ((n) >> 16); \@@ -11893,7 +11952,7 @@ void aes_init_keygen_tables(void) {******************************************************************************/static int aes_set_encryption_key(aes_context *ctx, const unsigned char *key,unsigned int keysize) {- unsigned int i; // general purpose iteration local+ unsigned int i; // general purpose iteration localuint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointerfor (i = 0; i < (keysize >> 2); i++) {@@ -12228,8 +12287,8 @@ static const uint64_t last4[16] = {((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \}-#define PUT_UINT32_BE(n, b, i) \- { \+#define PUT_UINT32_BE(n, b, i) \+ { \(b)[(i)] = (unsigned char) ((n) >> 24); \(b)[(i) + 1] = (unsigned char) ((n) >> 16); \(b)[(i) + 2] = (unsigned char) ((n) >> 8); \@@ -12262,9 +12321,10 @@ int mg_gcm_initialize(void) {* 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.*******************************************************************************/-static void gcm_mult(gcm_context *ctx, // pointer to established context- const unsigned char x[16], // pointer to 128-bit input vector- unsigned char output[16]) // pointer to 128-bit output vector+static void gcm_mult(+ gcm_context *ctx, // pointer to established context+ const unsigned char x[16], // pointer to 128-bit input vector+ unsigned char output[16]) // pointer to 128-bit output vector{int i;unsigned char lo, hi, rem;@@ -12309,10 +12369,10 @@ static void gcm_mult(gcm_context *ctx, // pointer to established context*******************************************************************************/static int gcm_setkey(- gcm_context *ctx, // pointer to caller-provided gcm context+ gcm_context *ctx, // pointer to caller-provided gcm contextconst unsigned char *key, // pointer to the AES encryption keyconst unsigned int keysize) // size in bytes (must be 16, 24, 32 for- // 128, 192 or 256-bit keys respectively)+ // 128, 192 or 256-bit keys respectively){int ret, i, j;uint64_t hi, lo;@@ -12381,18 +12441,19 @@ static int gcm_setkey(* mode, and preprocesses the initialization vector and additional AEAD data.*******************************************************************************/-int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context- int mode, // GCM_ENCRYPT or GCM_DECRYPT- const unsigned char *iv, // pointer to initialization vector- size_t iv_len, // IV length in bytes (should == 12)- const unsigned char *add, // ptr to additional AEAD data (NULL if none)- size_t add_len) // length of additional AEAD data (bytes)+int gcm_start(+ gcm_context *ctx, // pointer to user-provided GCM context+ int mode, // GCM_ENCRYPT or GCM_DECRYPT+ const unsigned char *iv, // pointer to initialization vector+ size_t iv_len, // IV length in bytes (should == 12)+ const unsigned char *add, // ptr to additional AEAD data (NULL if none)+ size_t add_len) // length of additional AEAD data (bytes){- int ret; // our error return if the AES encrypt fails+ int ret; // our error return if the AES encrypt failsunsigned char work_buf[16]; // XOR source built from provided IV if len != 16const unsigned char *p; // general purpose array pointer- size_t use_len; // byte count to process, up to 16 bytes- size_t i; // local loop iterator+ size_t use_len; // byte count to process, up to 16 bytes+ size_t i; // local loop iterator// since the context might be reused under the same key// we zero the working buffers for this next new process@@ -12449,15 +12510,15 @@ int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context* have a partial block length of < 128 bits.)*******************************************************************************/-int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context- size_t length, // length, in bytes, of data to process+int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context+ size_t length, // length, in bytes, of data to processconst unsigned char *input, // pointer to source dataunsigned char *output) // pointer to destination data{- int ret; // our error return if the AES encrypt fails+ int ret; // our error return if the AES encrypt failsunsigned char ectr[16]; // counter-mode cipher output for XORing- size_t use_len; // byte count to process, up to 16 bytes- size_t i; // local loop iterator+ size_t use_len; // byte count to process, up to 16 bytes+ size_t i; // local loop iteratorctx->len += length; // bump the GCM context's running length count@@ -12513,9 +12574,9 @@ int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context* It performs the final GHASH to produce the resulting authentication TAG.*******************************************************************************/-int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context- unsigned char *tag, // pointer to buffer which receives the tag- size_t tag_len) // length, in bytes, of the tag-receiving buf+int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context+ unsigned char *tag, // pointer to buffer which receives the tag+ size_t tag_len) // length, in bytes, of the tag-receiving buf{unsigned char work_buf[16];uint64_t orig_len = ctx->len * 8;@@ -12557,22 +12618,22 @@ int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context*******************************************************************************/int gcm_crypt_and_tag(- gcm_context *ctx, // gcm context with key already setup- int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT+ gcm_context *ctx, // gcm context with key already setup+ int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPTconst unsigned char *iv, // pointer to the 12-byte initialization vector- size_t iv_len, // byte length if the IV. should always be 12+ size_t iv_len, // byte length if the IV. should always be 12const unsigned char *add, // pointer to the non-ciphered additional data- size_t add_len, // byte length of the additional AEAD data+ size_t add_len, // byte length of the additional AEAD dataconst unsigned char *input, // pointer to the cipher data sourceunsigned char *output, // pointer to the cipher data destination- size_t length, // byte length of the cipher data+ size_t length, // byte length of the cipher dataunsigned char *tag, // pointer to the tag to be generated- size_t tag_len) // byte length of the tag to be generated-{ /*- assuming that the caller has already invoked gcm_setkey to- prepare the gcm context with the keying material, we simply- invoke each of the three GCM sub-functions in turn...- */+ size_t tag_len) // byte length of the tag to be generated+{ /*+ assuming that the caller has already invoked gcm_setkey to+ prepare the gcm context with the keying material, we simply+ invoke each of the three GCM sub-functions in turn...+ */gcm_start(ctx, mode, iv, iv_len, add, add_len);gcm_update(ctx, length, input, output);gcm_finish(ctx, tag, tag_len);@@ -12622,20 +12683,28 @@ int mg_aes_gcm_encrypt(unsigned char *output, //int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,size_t input_length, const unsigned char *key,const size_t key_len, const unsigned char *iv,- const size_t iv_len) {+ const size_t iv_len, unsigned char *aead,+ size_t aead_len, const unsigned char *tag,+ const size_t tag_len) {int ret = 0; // our return valuegcm_context ctx; // includes the AES context structure+ unsigned char computed_tag[16];+ size_t i;+ int diff = 0;- size_t tag_len = 0;- unsigned char *tag_buf = NULL;+ if (tag_len > sizeof(computed_tag)) return -1;gcm_setkey(&ctx, key, (unsigned int) key_len);- ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, NULL, 0, input, output,- input_length, tag_buf, tag_len);+ ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, aead, aead_len, input,+ output, input_length, computed_tag, tag_len);gcm_zero_ctx(&ctx);+ // compare tags+ for (i = 0; i < tag_len; i++) diff |= computed_tag[i] ^ tag[i];+ if (diff != 0) ret = -1;+return (ret);}#endif@@ -13201,14 +13270,19 @@ static int mg_tls_recv_record(struct mg_connection *c) {nonce[11] ^= (uint8_t) ((seq) & 255U);#if MG_ENABLE_CHACHA20{+ uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,+ (uint8_t) ((msgsz >> 8) & 0xff),+ (uint8_t) (msgsz & 0xff)};uint8_t *dec = (uint8_t *) mg_calloc(1, msgsz);size_t n;if (dec == NULL) {mg_error(c, "TLS OOM");return -1;}- n = mg_chacha20_poly1305_decrypt(dec, key, nonce, msg, msgsz);+ n = mg_chacha20_poly1305_decrypt(dec, key, nonce, associated_data,+ sizeof(associated_data), msg, msgsz);if (n == (size_t) -1) {+ mg_free(dec);mg_error(c, "decryption error");return -1;}@@ -13216,8 +13290,18 @@ static int mg_tls_recv_record(struct mg_connection *c) {mg_free(dec);}#else- mg_gcm_initialize();- mg_aes_gcm_decrypt(msg, msg, msgsz - 16, key, 16, nonce, sizeof(nonce));+ {+ uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,+ (uint8_t) ((msgsz >> 8) & 0xff),+ (uint8_t) (msgsz & 0xff)};+ mg_gcm_initialize();+ if (mg_aes_gcm_decrypt(msg, msg, msgsz - 16, key, 16, nonce, sizeof(nonce),+ associated_data, sizeof(associated_data),+ msg + msgsz - 16, 16) != 0) {+ mg_error(c, "GCM tag verify failed");+ return -1;+ }+ }#endifr = msgsz - 16 - 1;@@ -14143,7 +14227,7 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,if (mg_match(mg_str(server_name), mg_str_n((char *) name.value, name.len),NULL))return 1; // and matches the host name- } // TODO(): add IPv6 comparison, more items ?+ } // TODO(): add IPv6 comparison, more items ?}return -1;}@@ -14170,8 +14254,8 @@ static int mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,(unsigned) cert->tbshashsz, sig,mg_uecc_secp256r1());} else if (issuer->pubkey.len == 96) {- MG_VERBOSE(("ignore secp386 for now"));- return 1;+ MG_ERROR(("reject secp386 for now"));+ return 0;} else {MG_ERROR(("unsupported public key length: %d", issuer->pubkey.len));return 0;@@ -14288,6 +14372,14 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {mg_error(c, "failed to verify hostname");return -1;}+ if (ci->pubkey.len > sizeof(tls->pubkey)) {+ mg_error(c, "invalid certificate length");+ return -1;+ }+ if (ci->pubkey.len > sizeof(tls->pubkey)) {+ mg_error(c, "peer public key too large");+ return -1;+ }memmove(tls->pubkey, ci->pubkey.buf, ci->pubkey.len);tls->pubkeysz = ci->pubkey.len;} else {@@ -14635,7 +14727,7 @@ static int mg_rsa_parse_der_int(const uint8_t **p, const uint8_t *end,*p = value_end;MG_VERBOSE(("DER INT: parsed %u bytes (skipped zero=%d)", len,- (size_t)(value_end - value_start) != (size_t) len ? 1 : 0));+ (size_t) (value_end - value_start) != (size_t) len ? 1 : 0));return 0;}@@ -15145,7 +15237,7 @@ long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {if (!mg_tls_encrypt(c, (const uint8_t *) buf, len, MG_TLS_APP_DATA))return 0; // returning 0 means an OOM condition (iobuf couldn't resize),// yet this is so far recoverable, let the caller decide- } // else, resend outstanding encrypted data in tls->send+ } // else, resend outstanding encrypted data in tls->sendwhile (tls->send.len > 0 &&(n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {mg_iobuf_del(&tls->send, 0, (size_t) n);@@ -15292,7 +15384,8 @@ static PORTABLE_8439_DECL void poly1305_finish(poly1305_context *ctx,defined(__AVR__)#define __HAVE_LITTLE_ENDIAN 1#endif-// DO NOT test for LITTLE_ENDIAN, as it is defined as 1234 when including sys/types.h in GCC+// DO NOT test for LITTLE_ENDIAN, as it is defined as 1234 when including+// sys/types.h in GCC#ifndef TEST_SLOW_PATH#if defined(__HAVE_LITTLE_ENDIAN)@@ -15388,7 +15481,7 @@ static void core_block(const uint32_t *restrict start,TIMES16(__FIN)}-#define U8(x) ((uint8_t) ((x) &0xFF))+#define U8(x) ((uint8_t) ((x) & 0xFF))#ifdef FAST_PATH#define xor32_le(dst, src, pad) \@@ -15713,7 +15806,7 @@ static unsigned short U8TO16(const unsigned char *p) {/* store a 16 bit unsigned integer as two 8 bit unsigned integers in little* endian */static void U16TO8(unsigned char *p, unsigned short v) {- p[0] = (v) &0xff;+ p[0] = (v) & 0xff;p[1] = (v >> 8) & 0xff;}@@ -15724,7 +15817,7 @@ static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {/* r &= 0xffffffc0ffffffc0ffffffc0fffffff */t0 = U8TO16(&key[0]);- st->r[0] = (t0) &0x1fff;+ st->r[0] = (t0) & 0x1fff;t1 = U8TO16(&key[2]);st->r[1] = ((t0 >> 13) | (t1 << 3)) & 0x1fff;t2 = U8TO16(&key[4]);@@ -15764,7 +15857,7 @@ static void poly1305_blocks(poly1305_state_internal_t *st,/* h += m[i] */t0 = U8TO16(&m[0]);- st->h[0] += (t0) &0x1fff;+ st->h[0] += (t0) & 0x1fff;t1 = U8TO16(&m[2]);st->h[1] += ((t0 >> 13) | (t1 << 3)) & 0x1fff;t2 = U8TO16(&m[4]);@@ -15926,7 +16019,7 @@ static unsigned long U8TO32(const unsigned char *p) {/* store a 32 bit unsigned integer as four 8 bit unsigned integers in little* endian */static void U32TO8(unsigned char *p, unsigned long v) {- p[0] = (unsigned char) ((v) &0xff);+ p[0] = (unsigned char) ((v) & 0xff);p[1] = (unsigned char) ((v >> 8) & 0xff);p[2] = (unsigned char) ((v >> 16) & 0xff);p[3] = (unsigned char) ((v >> 24) & 0xff);@@ -16190,8 +16283,8 @@ typedef unsigned uint128_t __attribute__((mode(TI)));#define MUL128(out, x, y) out = ((uint128_t) x * y)#define ADD(out, in) out += in#define ADDLO(out, in) out += in-#define SHR(in, shift) (uint64_t)(in >> (shift))-#define LO(in) (uint64_t)(in)+#define SHR(in, shift) (uint64_t) (in >> (shift))+#define LO(in) (uint64_t) (in)#define POLY1305_NOINLINE __attribute__((noinline))#endif@@ -16220,7 +16313,7 @@ static uint64_t U8TO64(const unsigned char *p) {/* store a 64 bit unsigned integer as eight 8 bit unsigned integers in little* endian */static void U64TO8(unsigned char *p, uint64_t v) {- p[0] = (unsigned char) ((v) &0xff);+ p[0] = (unsigned char) ((v) & 0xff);p[1] = (unsigned char) ((v >> 8) & 0xff);p[2] = (unsigned char) ((v >> 16) & 0xff);p[3] = (unsigned char) ((v >> 24) & 0xff);@@ -16238,7 +16331,7 @@ static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {t0 = U8TO64(&key[0]);t1 = U8TO64(&key[8]);- st->r[0] = (t0) &0xffc0fffffff;+ st->r[0] = (t0) & 0xffc0fffffff;st->r[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff;st->r[2] = ((t1 >> 24)) & 0x00ffffffc0f;@@ -16282,7 +16375,7 @@ static void poly1305_blocks(poly1305_state_internal_t *st,t0 = U8TO64(&m[0]);t1 = U8TO64(&m[8]);- h0 += ((t0) &0xfffffffffff);+ h0 += ((t0) & 0xfffffffffff);h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff);h2 += (((t1 >> 24)) & 0x3ffffffffff) | hibit;@@ -16389,7 +16482,7 @@ static POLY1305_NOINLINE void poly1305_finish(poly1305_context *ctx,t0 = st->pad[0];t1 = st->pad[1];- h0 += ((t0) &0xfffffffffff);+ h0 += ((t0) & 0xfffffffffff);c = (h0 >> 44);h0 &= 0xfffffffffff;h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff) + c;@@ -16466,7 +16559,7 @@ static PORTABLE_8439_DECL void pad_if_needed(poly1305_context *ctx,}}-#define __u8(v) ((uint8_t) ((v) &0xFF))+#define __u8(v) ((uint8_t) ((v) & 0xFF))// TODO: make this depending on the unaligned/native read size possiblestatic PORTABLE_8439_DECL void write_64bit_int(poly1305_context *ctx,@@ -16539,14 +16632,26 @@ PORTABLE_8439_DECL size_t mg_chacha20_poly1305_encrypt(PORTABLE_8439_DECL size_t mg_chacha20_poly1305_decrypt(uint8_t *restrict plain_text, const uint8_t key[RFC_8439_KEY_SIZE],- const uint8_t nonce[RFC_8439_NONCE_SIZE],- const uint8_t *restrict cipher_text, size_t cipher_text_size) {+ const uint8_t nonce[RFC_8439_NONCE_SIZE], const uint8_t *restrict ad,+ size_t ad_size, const uint8_t *restrict cipher_text,+ size_t cipher_text_size) {// first we calculate the mac and see if it lines up, only then do we decryptsize_t actual_size = cipher_text_size - RFC_8439_TAG_SIZE;+ uint8_t computed_mac[RFC_8439_TAG_SIZE];+ int diff = 0;+ size_t i;if (MG_OVERLAPPING(plain_text, actual_size, cipher_text, cipher_text_size)) {return (size_t) -1;}+ poly1305_calculate_mac(computed_mac, cipher_text, actual_size, key, nonce, ad,+ ad_size);++ // compare tags+ for (i = 0; i < RFC_8439_TAG_SIZE; i++)+ diff |= computed_mac[i] ^ cipher_text[actual_size + i];+ if (diff != 0) return (size_t) -1;+chacha20_xor_stream(plain_text, cipher_text, actual_size, key, nonce, 1);return actual_size;}@@ -26733,14 +26838,11 @@ static void st67w6_handle_scan_result(char *data, size_t len) {!mg_str_to_num(fields[0], 10, &val, 1))return;bss.security =- (val == 0)- ? MG_WIFI_SECURITY_OPEN- : MG_WIFI_SECURITY_WEP |- ((val == 2 || val == 4 || val == 5) ? MG_WIFI_SECURITY_WPA- : 0) |- ((val == 3 || val == 4 || val == 7) ? MG_WIFI_SECURITY_WPA2- : 0) |- ((val == 6 || val == 7) ? MG_WIFI_SECURITY_WPA3 : 0);+ (val == 0) ? MG_WIFI_SECURITY_OPEN : (uint8_t) MG_WIFI_SECURITY_WEP;+ if (val == 2 || val == 4) bss.security |= MG_WIFI_SECURITY_WPA;+ if (val == 3 || val == 4 || val == 7) bss.security |= MG_WIFI_SECURITY_WPA2;+ if (val == 6 || val == 7) bss.security |= MG_WIFI_SECURITY_WPA3;+ if (val == 5) bss.security |= MG_WIFI_SECURITY_WPA_ENTERPRISE;if (!mg_span(fields[1], &fields[0], &fields[1], ',')) return;bss.SSID.buf = fields[0].buf + 1, bss.SSID.len = fields[0].len - 2;if (!mg_span(fields[1], &fields[0], &fields[1], ',')) return;@@ -26770,7 +26872,7 @@ static void st67w6_handle_scan_result(char *data, size_t len) {!mg_str_to_num(fields[0], 10, &val, 1))return;bss.has_n = (val & 4) != 0;- // bss.has_ax = (val & 8) != 0;+ bss.has_ax = (val & 8) != 0;bss.band = MG_WIFI_BAND_2G; // NOT INFORMED with default options, no docsMG_VERBOSE(("BSS: %.*s (%u) (%M) %d dBm %u", bss.SSID.len, bss.SSID.buf,bss.channel, mg_print_mac, bss.BSSID, (int) bss.RSSI,diff --git a/vendored/mongoose/mongoose.h b/vendored/mongoose/mongoose.hindex 4c7297779..0f17fae85 100644--- a/vendored/mongoose/mongoose.h+++ b/vendored/mongoose/mongoose.h@@ -20,7 +20,7 @@#ifndef MONGOOSE_H#define MONGOOSE_H-#define MG_VERSION "7.20"+#define MG_VERSION "7.21"#ifdef __cplusplusextern "C" {@@ -1961,7 +1961,9 @@ int mg_aes_gcm_encrypt(unsigned char *output, const unsigned char *input,int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,size_t input_length, const unsigned char *key,const size_t key_len, const unsigned char *iv,- const size_t iv_len);+ const size_t iv_len, unsigned char *aead,+ size_t aead_len, const unsigned char *tag,+ const size_t tag_len);#endif /* TLS_AES128_H */@@ -2727,6 +2729,7 @@ PORTABLE_8439_DECL size_t mg_chacha20_poly1305_encrypt(PORTABLE_8439_DECL size_t mg_chacha20_poly1305_decrypt(uint8_t *restrict plain_text, const uint8_t key[RFC_8439_KEY_SIZE],const uint8_t nonce[RFC_8439_NONCE_SIZE],+ const uint8_t *restrict ad, size_t ad_size,const uint8_t *restrict cipher_text, size_t cipher_text_size);#if defined(__cplusplus)}@@ -3164,11 +3167,16 @@ struct mg_wifi_scan_bss_data {#define MG_WIFI_SECURITY_WPA MG_BIT(1)#define MG_WIFI_SECURITY_WPA2 MG_BIT(2)#define MG_WIFI_SECURITY_WPA3 MG_BIT(3)+#define MG_WIFI_SECURITY_WPA_ENTERPRISE MG_BIT(4)+#define MG_WIFI_SECURITY_WPA2_ENTERPRISE MG_BIT(5)+#define MG_WIFI_SECURITY_WPA3_ENTERPRISE MG_BIT(6)uint8_t channel;unsigned band : 2;#define MG_WIFI_BAND_2G 0#define MG_WIFI_BAND_5G 1unsigned has_n : 1;+ unsigned has_ac : 1;+ unsigned has_ax : 1;};bool mg_wifi_scan(void);diff --git a/vendored/sqlite3/sqlite3.c b/vendored/sqlite3/sqlite3.cindex 37b534afb..851a2504c 100644--- a/vendored/sqlite3/sqlite3.c+++ b/vendored/sqlite3/sqlite3.c@@ -1,6 +1,6 @@/******************************************************************************** This file is an amalgamation of many separate C source files from SQLite-** version 3.49.1. By combining all the individual C code files into this+** version 3.51.3. By combining all the individual C code files into this** single large file, the entire code can be compiled as a single translation** unit. This allows many compilers to do optimizations that would not be** possible if the files were compiled separately. Performance improvements@@ -18,7 +18,7 @@** separate file. This file contains only code for the core SQLite library.**** The content in this amalgamation comes from Fossil check-in-** 873d4e274b4988d260ba8354a9718324a1c2 with changes in files:+** 737ae4a34738ffa0c3ff7f9bb18df914dd1c with changes in files:*****/@@ -170,7 +170,9 @@#define HAVE_UTIME 1#else/* This is not VxWorks. */-#define OS_VXWORKS 0+#ifndef OS_VXWORKS+# define OS_VXWORKS 0+#endif#define HAVE_FCHOWN 1#define HAVE_READLINK 1#define HAVE_LSTAT 1@@ -452,7 +454,7 @@ extern "C" {**** Since [version 3.6.18] ([dateof:3.6.18]),** SQLite source code has been stored in the-** <a href="http://www.fossil-scm.org/">Fossil configuration management+** <a href="http://fossil-scm.org/">Fossil configuration management** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to** a string which identifies a particular check-in of SQLite** within its configuration management system. ^The SQLITE_SOURCE_ID@@ -465,9 +467,12 @@ extern "C" {** [sqlite3_libversion_number()], [sqlite3_sourceid()],** [sqlite_version()] and [sqlite_source_id()].*/-#define SQLITE_VERSION "3.49.1"-#define SQLITE_VERSION_NUMBER 3049001-#define SQLITE_SOURCE_ID "2025-02-18 13:38:58 873d4e274b4988d260ba8354a9718324a1c26187a4ab4c1cc0227c03d0f10e70"+#define SQLITE_VERSION "3.51.3"+#define SQLITE_VERSION_NUMBER 3051003+#define SQLITE_SOURCE_ID "2026-03-13 10:38:09 737ae4a34738ffa0c3ff7f9bb18df914dd1cad163f28fd6b6e114a344fe6d618"+#define SQLITE_SCM_BRANCH "branch-3.51"+#define SQLITE_SCM_TAGS "release version-3.51.3"+#define SQLITE_SCM_DATETIME "2026-03-13T10:38:09.694Z"/*** CAPI3REF: Run-Time Library Version Numbers@@ -487,9 +492,9 @@ extern "C" {** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );** </pre></blockquote>)^**-** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]-** macro. ^The sqlite3_libversion() function returns a pointer to the-** to the sqlite3_version[] string constant. The sqlite3_libversion()+** ^The sqlite3_version[] string constant contains the text of the+** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a+** pointer to the sqlite3_version[] string constant. The sqlite3_libversion()** function is provided for use in DLLs since DLL users usually do not have** direct access to string constants within the DLL. ^The** sqlite3_libversion_number() function returns an integer equal to@@ -689,7 +694,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);** without having to use a lot of C code.**** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,-** semicolon-separate SQL statements passed into its 2nd argument,+** semicolon-separated SQL statements passed into its 2nd argument,** in the context of the [database connection] passed in as its 1st** argument. ^If the callback function of the 3rd argument to** sqlite3_exec() is not NULL, then it is invoked for each result row@@ -722,7 +727,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);** result row is NULL then the corresponding string pointer for the** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the** sqlite3_exec() callback is an array of pointers to strings where each-** entry represents the name of corresponding result column as obtained+** entry represents the name of a corresponding result column as obtained** from [sqlite3_column_name()].**** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer@@ -816,6 +821,9 @@ SQLITE_API int sqlite3_exec(#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))+#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8))+#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8))+#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8))#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))@@ -850,6 +858,8 @@ SQLITE_API int sqlite3_exec(#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8))#define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8))+#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8))+#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8))#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))@@ -908,7 +918,7 @@ SQLITE_API int sqlite3_exec(** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into** [sqlite3_open_v2()] does *not* cause the underlying database file** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into-** [sqlite3_open_v2()] has historically be a no-op and might become an+** [sqlite3_open_v2()] has historically been a no-op and might become an** error in future versions of SQLite.*/#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */@@ -1002,7 +1012,7 @@ SQLITE_API int sqlite3_exec(** SQLite uses one of these integer values as the second** argument to calls it makes to the xLock() and xUnlock() methods** of an [sqlite3_io_methods] object. These values are ordered from-** lest restrictive to most restrictive.+** least restrictive to most restrictive.**** The argument to xLock() is always SHARED or higher. The argument to** xUnlock is either SHARED or NONE.@@ -1243,7 +1253,7 @@ struct sqlite3_io_methods {** connection. See also [SQLITE_FCNTL_FILE_POINTER].**** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]-** No longer in use.+** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used.**** <li>[[SQLITE_FCNTL_SYNC]]** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and@@ -1318,7 +1328,7 @@ struct sqlite3_io_methods {**** <li>[[SQLITE_FCNTL_VFSNAME]]** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of-** all [VFSes] in the VFS stack. The names are of all VFS shims and the+** all [VFSes] in the VFS stack. The names of all VFS shims and the** final bottom-level VFS are written into memory obtained from** [sqlite3_malloc()] and the result is stored in the char* variable** that the fourth parameter of [sqlite3_file_control()] points to.@@ -1332,7 +1342,7 @@ struct sqlite3_io_methods {** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level** [VFSes] currently in use. ^(The argument X in** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be-** of type "[sqlite3_vfs] **". This opcodes will set *X+** of type "[sqlite3_vfs] **". This opcode will set *X** to a pointer to the top-level VFS.)^** ^When there are multiple VFS shims in the stack, this opcode finds the** upper-most shim only.@@ -1482,6 +1492,12 @@ struct sqlite3_io_methods {** the value that M is to be set to. Before returning, the 32-bit signed** integer is overwritten with the previous value of M.**+** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]+** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the+** VFS to block when taking a SHARED lock to connect to a wal mode database.+** This is used to implement the functionality associated with+** SQLITE_SETLK_BLOCK_ON_CONNECT.+**** <li>[[SQLITE_FCNTL_DATA_VERSION]]** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to** a database file. The argument is a pointer to a 32-bit unsigned integer.@@ -1516,7 +1532,7 @@ struct sqlite3_io_methods {** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect** whether or not there is a database client in another process with a wal-mode-** transaction open on the database or not. It is only available on unix.The+** transaction open on the database or not. It is only available on unix. The** (void*) argument passed with this file-control should be a pointer to a** value of type (int). The integer value is set to 1 if the database is a wal** mode database and there exists at least one client in another process that@@ -1534,6 +1550,15 @@ struct sqlite3_io_methods {** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control** purges the contents of the in-memory page cache. If there is an open** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.+**+** <li>[[SQLITE_FCNTL_FILESTAT]]+** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information+** about the [sqlite3_file] objects used access the database and journal files+** for the given schema. The fourth parameter to [sqlite3_file_control()]+** should be an initialized [sqlite3_str] pointer. JSON text describing+** various aspects of the sqlite3_file object is appended to the sqlite3_str.+** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time+** options are used to enable it.** </ul>*/#define SQLITE_FCNTL_LOCKSTATE 1@@ -1578,6 +1603,8 @@ struct sqlite3_io_methods {#define SQLITE_FCNTL_CKSM_FILE 41#define SQLITE_FCNTL_RESET_CACHE 42#define SQLITE_FCNTL_NULL_IO 43+#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44+#define SQLITE_FCNTL_FILESTAT 45/* deprecated names */#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE@@ -1940,7 +1967,7 @@ struct sqlite3_vfs {** SQLite interfaces so that an application usually does not need to** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]** calls sqlite3_initialize() so the SQLite library will be automatically-** initialized when [sqlite3_open()] is called if it has not be initialized+** initialized when [sqlite3_open()] is called if it has not been initialized** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]** compile-time option, then the automatic calls to sqlite3_initialize()** are omitted and the application must call sqlite3_initialize() directly@@ -2197,21 +2224,21 @@ struct sqlite3_mem_methods {** The [sqlite3_mem_methods]** structure is filled with the currently defined memory allocation routines.)^** This option can be used to overload the default memory allocation-** routines with a wrapper that simulations memory allocation failure or+** routines with a wrapper that simulates memory allocation failure or** tracks memory usage, for example. </dd>**** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>-** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of+** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes a single argument of** type int, interpreted as a boolean, which if true provides a hint to** SQLite that it should avoid large memory allocations if possible.** SQLite will run faster if it is free to make large memory allocations,-** but some application might prefer to run slower in exchange for+** but some applications might prefer to run slower in exchange for** guarantees about memory fragmentation that are possible if large** allocations are avoided. This hint is normally off.** </dd>**** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>-** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,+** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes a single argument of type int,** interpreted as a boolean, which enables or disables the collection of** memory allocation statistics. ^(When memory allocation statistics are** disabled, the following SQLite interfaces become non-operational:@@ -2256,7 +2283,7 @@ struct sqlite3_mem_methods {** ^If pMem is NULL and N is non-zero, then each database connection** does an initial bulk allocation for page cache memory** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or-** of -1024*N bytes if N is negative, . ^If additional+** of -1024*N bytes if N is negative. ^If additional** page cache memory is needed beyond what is provided by the initial** allocation, then SQLite goes to [sqlite3_malloc()] separately for each** additional cache line. </dd>@@ -2285,7 +2312,7 @@ struct sqlite3_mem_methods {** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a** pointer to an instance of the [sqlite3_mutex_methods] structure.** The argument specifies alternative low-level mutex routines to be used-** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of+** in place of the mutex routines built into SQLite.)^ ^SQLite makes a copy of** the content of the [sqlite3_mutex_methods] structure before the call to** [sqlite3_config()] returns. ^If SQLite is compiled with** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then@@ -2308,13 +2335,16 @@ struct sqlite3_mem_methods {**** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine-** the default size of lookaside memory on each [database connection].+** the default size of [lookaside memory] on each [database connection].** The first argument is the-** size of each lookaside buffer slot and the second is the number of-** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE-** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]-** option to [sqlite3_db_config()] can be used to change the lookaside-** configuration on individual connections.)^ </dd>+** size of each lookaside buffer slot ("sz") and the second is the number of+** slots allocated to each database connection ("cnt").)^+** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size.+** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can+** be used to change the lookaside configuration on individual connections.)^+** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the+** default lookaside configuration at compile-time.+** </dd>**** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is@@ -2324,7 +2354,7 @@ struct sqlite3_mem_methods {**** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which-** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of+** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies off** the current page cache implementation into that object.)^ </dd>**** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>@@ -2341,7 +2371,7 @@ struct sqlite3_mem_methods {** the logger function is a copy of the first parameter to the corresponding** [sqlite3_log()] call and is intended to be a [result code] or an** [extended result code]. ^The third parameter passed to the logger is-** log message after formatting via [sqlite3_snprintf()].+** a log message after formatting via [sqlite3_snprintf()].** The SQLite logging interface is not reentrant; the logger function** supplied by the application must not invoke any SQLite interface.** In a multi-threaded application, the application-defined logger@@ -2532,7 +2562,7 @@ struct sqlite3_mem_methods {** These constants are the available integer configuration options that** can be passed as the second parameter to the [sqlite3_db_config()] interface.**-** The [sqlite3_db_config()] interface is a var-args functions. It takes a+** The [sqlite3_db_config()] interface is a var-args function. It takes a** variable number of parameters, though always at least two. The number of** parameters passed into sqlite3_db_config() depends on which of these** constants is given as the second parameter. This documentation page@@ -2551,31 +2581,50 @@ struct sqlite3_mem_methods {** [[SQLITE_DBCONFIG_LOOKASIDE]]** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the-** configuration of the lookaside memory allocator within a database+** configuration of the [lookaside memory allocator] within a database** connection.** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i>** in the [DBCONFIG arguments|usual format].** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two,** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE** should have a total of five parameters.-** ^The first argument (the third parameter to [sqlite3_db_config()] is a+** <ol>+** <li><p>The first argument ("buf") is a** pointer to a memory buffer to use for lookaside memory.-** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb-** may be NULL in which case SQLite will allocate the-** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the-** size of each lookaside buffer slot. ^The third argument is the number of-** slots. The size of the buffer in the first argument must be greater than-** or equal to the product of the second and third arguments. The buffer-** must be aligned to an 8-byte boundary. ^If the second argument to-** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally-** rounded down to the next smaller multiple of 8. ^(The lookaside memory+** The first argument may be NULL in which case SQLite will allocate the+** lookaside buffer itself using [sqlite3_malloc()].+** <li><P>The second argument ("sz") is the+** size of each lookaside buffer slot. Lookaside is disabled if "sz"+** is less than 8. The "sz" argument should be a multiple of 8 less than+** 65536. If "sz" does not meet this constraint, it is reduced in size until+** it does.+** <li><p>The third argument ("cnt") is the number of slots. Lookaside is disabled+** if "cnt"is less than 1. The "cnt" value will be reduced, if necessary, so+** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt"+** parameter is usually chosen so that the product of "sz" and "cnt" is less+** than 1,000,000.+** </ol>+** <p>If the "buf" argument is not NULL, then it must+** point to a memory buffer with a size that is greater than+** or equal to the product of "sz" and "cnt".+** The buffer must be aligned to an 8-byte boundary.+** The lookaside memory** configuration for a database connection can only be changed when that** connection is not currently using lookaside memory, or in other words-** when the "current value" returned by-** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero.+** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero.** Any attempt to change the lookaside memory configuration when lookaside** memory is in use leaves the configuration unchanged and returns-** [SQLITE_BUSY].)^</dd>+** [SQLITE_BUSY].+** If the "buf" argument is NULL and an attempt+** to allocate memory based on "sz" and "cnt" fails, then+** lookaside is silently disabled.+** <p>+** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the+** default lookaside configuration at initialization. The+** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside+** configuration at compile-time. Typical values for lookaside are 1200 for+** "sz" and 40 to 100 for "cnt".+** </dd>**** [[SQLITE_DBCONFIG_ENABLE_FKEY]]** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>@@ -2625,17 +2674,20 @@ struct sqlite3_mem_methods {**** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>-** <dd> ^This option is used to enable or disable the-** [fts3_tokenizer()] function which is part of the-** [FTS3] full-text search engine extension.-** There must be two additional arguments.-** The first argument is an integer which is 0 to disable fts3_tokenizer() or-** positive to enable fts3_tokenizer() or negative to leave the setting-** unchanged.-** The second parameter is a pointer to an integer into which-** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled-** following this call. The second parameter may be a NULL pointer, in-** which case the new setting is not reported back. </dd>+** <dd> ^This option is used to enable or disable using the+** [fts3_tokenizer()] function - part of the [FTS3] full-text search engine+** extension - without using bound parameters as the parameters. Doing so+** is disabled by default. There must be two additional arguments. The first+** argument is an integer. If it is passed 0, then using fts3_tokenizer()+** without bound parameters is disabled. If it is passed a positive value,+** then calling fts3_tokenizer without bound parameters is enabled. If it+** is passed a negative value, this setting is not modified - this can be+** used to query for the current setting. The second parameter is a pointer+** to an integer into which is written 0 or 1 to indicate the current value+** of this setting (after it is modified, if applicable). The second+** parameter may be a NULL pointer, in which case the value of the setting+** is not reported back. Refer to [FTS3] documentation for further details.+** </dd>**** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>@@ -2647,8 +2699,8 @@ struct sqlite3_mem_methods {** When the first argument to this interface is 1, then only the C-API is** enabled and the SQL function remains disabled. If the first argument to** this interface is 0, then both the C-API and the SQL function are disabled.-** If the first argument is -1, then no changes are made to state of either the-** C-API or the SQL function.+** If the first argument is -1, then no changes are made to the state of either+** the C-API or the SQL function.** The second parameter is a pointer to an integer into which** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface** is disabled or enabled following this call. The second parameter may@@ -2766,7 +2818,7 @@ struct sqlite3_mem_methods {** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates-** the legacy behavior of the [ALTER TABLE RENAME] command such it+** the legacy behavior of the [ALTER TABLE RENAME] command such that it** behaves as it did prior to [version 3.24.0] (2018-06-04). See the** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for** additional information. This feature can also be turned on and off@@ -2815,7 +2867,7 @@ struct sqlite3_mem_methods {** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates** the legacy file format flag. When activated, this flag causes all newly-** created database file to have a schema format version number (the 4-byte+** created database files to have a schema format version number (the 4-byte** integer found at offset 44 into the database header) of 1. This in turn** means that the resulting database file will be readable and writable by** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,@@ -2842,7 +2894,7 @@ struct sqlite3_mem_methods {** the database handle both when the SQL statement is prepared and when it** is stepped. The flag is set (collection of statistics is enabled)** by default. <p>This option takes two arguments: an integer and a pointer to-** an integer.. The first argument is 1, 0, or -1 to enable, disable, or+** an integer. The first argument is 1, 0, or -1 to enable, disable, or** leave unchanged the statement scanstatus option. If the second argument** is not NULL, then the value of the statement scanstatus setting after** processing the first argument is written into the integer that the second@@ -2885,8 +2937,8 @@ struct sqlite3_mem_methods {** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the** ability of the [ATTACH DATABASE] SQL command to open a database for writing.** This capability is enabled by default. Applications can disable or-** reenable this capability using the current DBCONFIG option. If the-** the this capability is disabled, the [ATTACH] command will still work,+** reenable this capability using the current DBCONFIG option. If+** this capability is disabled, the [ATTACH] command will still work,** but the database will be opened read-only. If this option is disabled,** then the ability to create a new database using [ATTACH] is also disabled,** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]@@ -2920,7 +2972,7 @@ struct sqlite3_mem_methods {**** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the** overall call to [sqlite3_db_config()] has a total of four parameters.-** The first argument (the third parameter to sqlite3_db_config()) is a integer.+** The first argument (the third parameter to sqlite3_db_config()) is an integer.** The second argument is a pointer to an integer. If the first argument is 1,** then the option becomes enabled. If the first integer argument is 0, then the** option is disabled. If the first argument is -1, then the option setting@@ -3210,7 +3262,7 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*);** ^These routines return 0 if the statement is incomplete. ^If a** memory allocation fails, then SQLITE_NOMEM is returned.**-** ^These routines do not parse the SQL statements thus+** ^These routines do not parse the SQL statements and thus** will not detect syntactically incorrect SQL.**** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior@@ -3312,6 +3364,44 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);*/SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);+/*+** CAPI3REF: Set the Setlk Timeout+** METHOD: sqlite3+**+** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If+** the VFS supports blocking locks, it sets the timeout in ms used by+** eligible locks taken on wal mode databases by the specified database+** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does+** not support blocking locks, this function is a no-op.+**+** Passing 0 to this function disables blocking locks altogether. Passing+** -1 to this function requests that the VFS blocks for a long time -+** indefinitely if possible. The results of passing any other negative value+** are undefined.+**+** Internally, each SQLite database handle stores two timeout values - the+** busy-timeout (used for rollback mode databases, or if the VFS does not+** support blocking locks) and the setlk-timeout (used for blocking locks+** on wal-mode databases). The sqlite3_busy_timeout() method sets both+** values, this function sets only the setlk-timeout value. Therefore,+** to configure separate busy-timeout and setlk-timeout values for a single+** database handle, call sqlite3_busy_timeout() followed by this function.+**+** Whenever the number of connections to a wal mode database falls from+** 1 to 0, the last connection takes an exclusive lock on the database,+** then checkpoints and deletes the wal file. While it is doing this, any+** new connection that tries to read from the database fails with an+** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is+** passed to this API, the new connection blocks until the exclusive lock+** has been released.+*/+SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags);++/*+** CAPI3REF: Flags for sqlite3_setlk_timeout()+*/+#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01+/*** CAPI3REF: Convenience Routines For Running Queries** METHOD: sqlite3@@ -3319,7 +3409,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);** This is a legacy interface that is preserved for backwards compatibility.** Use of this interface is not recommended.**-** Definition: A <b>result table</b> is memory data structure created by the+** Definition: A <b>result table</b> is a memory data structure created by the** [sqlite3_get_table()] interface. A result table records the** complete query results from one or more queries.**@@ -3462,7 +3552,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);** ^Calling sqlite3_free() with a pointer previously returned** by sqlite3_malloc() or sqlite3_realloc() releases that memory so** that it might be reused. ^The sqlite3_free() routine is-** a no-op if is called with a NULL pointer. Passing a NULL pointer+** a no-op if it is called with a NULL pointer. Passing a NULL pointer** to sqlite3_free() is harmless. After being freed, memory** should neither be read nor written. Even reading previously freed** memory might result in a segmentation fault or other severe error.@@ -3480,13 +3570,13 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);** sqlite3_free(X).** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation** of at least N bytes in size or NULL if insufficient memory is available.-** ^If M is the size of the prior allocation, then min(N,M) bytes-** of the prior allocation are copied into the beginning of buffer returned+** ^If M is the size of the prior allocation, then min(N,M) bytes of the+** prior allocation are copied into the beginning of the buffer returned** by sqlite3_realloc(X,N) and the prior allocation is freed.** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the** prior allocation is not freed.**-** ^The sqlite3_realloc64(X,N) interfaces works the same as+** ^The sqlite3_realloc64(X,N) interface works the same as** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead** of a 32-bit signed integer.**@@ -3536,7 +3626,7 @@ SQLITE_API sqlite3_uint64 sqlite3_msize(void*);** was last reset. ^The values returned by [sqlite3_memory_used()] and** [sqlite3_memory_highwater()] include any overhead** added by SQLite in its implementation of [sqlite3_malloc()],-** but not overhead added by the any underlying system library+** but not overhead added by any underlying system library** routines that [sqlite3_malloc()] may call.**** ^The memory high-water mark is reset to the current value of@@ -3988,7 +4078,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);** there is no harm in trying.)**** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>-** <dd>The database is opened [shared cache] enabled, overriding+** <dd>The database is opened with [shared cache] enabled, overriding** the default shared cache setting provided by** [sqlite3_enable_shared_cache()].)^** The [use of shared cache mode is discouraged] and hence shared cache@@ -3996,7 +4086,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);** this option is a no-op.**** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>-** <dd>The database is opened [shared cache] disabled, overriding+** <dd>The database is opened with [shared cache] disabled, overriding** the default shared cache setting provided by** [sqlite3_enable_shared_cache()].)^**@@ -4331,7 +4421,7 @@ SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);**** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of** database filename D with corresponding journal file J and WAL file W and-** with N URI parameters key/values pairs in the array P. The result from+** an array P of N URI Key/Value pairs. The result from** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that** is safe to pass to routines like:** <ul>@@ -4414,7 +4504,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);** subsequent calls to other SQLite interface functions.)^**** ^The sqlite3_errstr(E) interface returns the English-language text-** that describes the [result code] E, as UTF-8, or NULL if E is not an+** that describes the [result code] E, as UTF-8, or NULL if E is not a** result code for which a text error message is available.** ^(Memory to hold the error message string is managed internally** and must not be freed by the application)^.@@ -4422,7 +4512,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);** ^If the most recent error references a specific token in the input** SQL, the sqlite3_error_offset() interface returns the byte offset** of the start of that token. ^The byte offset returned by-** sqlite3_error_offset() assumes that the input SQL is UTF8.+** sqlite3_error_offset() assumes that the input SQL is UTF-8.** ^If the most recent error does not reference a specific token in the input** SQL, then the sqlite3_error_offset() function returns -1.**@@ -4447,6 +4537,34 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*);SQLITE_API const char *sqlite3_errstr(int);SQLITE_API int sqlite3_error_offset(sqlite3 *db);+/*+** CAPI3REF: Set Error Codes And Message+** METHOD: sqlite3+**+** Set the error code of the database handle passed as the first argument+** to errcode, and the error message to a copy of nul-terminated string+** zErrMsg. If zErrMsg is passed NULL, then the error message is set to+** the default message associated with the supplied error code. Subsequent+** calls to [sqlite3_errcode()] and [sqlite3_errmsg()] and similar will+** return the values set by this routine in place of what was previously+** set by SQLite itself.+**+** This function returns SQLITE_OK if the error code and error message are+** successfully set, SQLITE_NOMEM if an OOM occurs, and SQLITE_MISUSE if+** the database handle is NULL or invalid.+**+** The error code and message set by this routine remains in effect until+** they are changed, either by another call to this routine or until they are+** changed to by SQLite itself to reflect the result of some subsquent+** API call.+**+** This function is intended for use by SQLite extensions or wrappers. The+** idea is that an extension or wrapper can use this routine to set error+** messages and error codes and thus behave more like a core SQLite+** feature from the point of view of an application.+*/+SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zErrMsg);+/*** CAPI3REF: Prepared Statement Object** KEYWORDS: {prepared statement} {prepared statements}@@ -4521,8 +4639,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);**** These constants define various performance limits** that can be lowered at run-time using [sqlite3_limit()].-** The synopsis of the meanings of the various limits is shown below.-** Additional information is available at [limits | Limits in SQLite].+** A concise description of these limits follows, and additional information+** is available at [limits | Limits in SQLite].**** <dl>** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>@@ -4587,7 +4705,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);/*** CAPI3REF: Prepare Flags**-** These constants define various flags that can be passed into+** These constants define various flags that can be passed into the** "prepFlags" parameter of the [sqlite3_prepare_v3()] and** [sqlite3_prepare16_v3()] interfaces.**@@ -4674,7 +4792,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);** there is a small performance advantage to passing an nByte parameter that** is the number of bytes in the input string <i>including</i>** the nul-terminator.-** Note that nByte measure the length of the input in bytes, not+** Note that nByte measures the length of the input in bytes, not** characters, even for the UTF-16 interfaces.**** ^If pzTail is not NULL then *pzTail is made to point to the first byte@@ -4808,7 +4926,7 @@ SQLITE_API int sqlite3_prepare16_v3(**** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory** is available to hold the result, or if the result would exceed the-** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].+** maximum string length determined by the [SQLITE_LIMIT_LENGTH].**** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time@@ -4996,7 +5114,7 @@ typedef struct sqlite3_value sqlite3_value;**** The context in which an SQL function executes is stored in an** sqlite3_context object. ^A pointer to an sqlite3_context object-** is always first parameter to [application-defined SQL functions].+** is always the first parameter to [application-defined SQL functions].** The application-defined SQL function implementation will pass this** pointer through into calls to [sqlite3_result_int | sqlite3_result()],** [sqlite3_aggregate_context()], [sqlite3_user_data()],@@ -5012,7 +5130,7 @@ typedef struct sqlite3_context sqlite3_context;** METHOD: sqlite3_stmt**** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,-** literals may be replaced by a [parameter] that matches one of following+** literals may be replaced by a [parameter] that matches one of the following** templates:**** <ul>@@ -5057,7 +5175,7 @@ typedef struct sqlite3_context sqlite3_context;**** [[byte-order determination rules]] ^The byte-order of** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)-** found in first character, which is removed, or in the absence of a BOM+** found in the first character, which is removed, or in the absence of a BOM** the byte order is the native byte order of the host** machine for sqlite3_bind_text16() or the byte order specified in** the 6th parameter for sqlite3_bind_text64().)^@@ -5077,7 +5195,7 @@ typedef struct sqlite3_context sqlite3_context;** or sqlite3_bind_text16() or sqlite3_bind_text64() then** that parameter must be the byte offset** where the NUL terminator would occur assuming the string were NUL-** terminated. If any NUL characters occurs at byte offsets less than+** terminated. If any NUL characters occur at byte offsets less than** the value of the fourth parameter then the resulting string value will** contain embedded NULs. The result of expressions involving strings** with embedded NULs is undefined.@@ -5120,9 +5238,11 @@ typedef struct sqlite3_context sqlite3_context;** associated with the pointer P of type T. ^D is either a NULL pointer or** a pointer to a destructor function for P. ^SQLite will invoke the** destructor D with a single argument of P when it is finished using-** P. The T parameter should be a static string, preferably a string-** literal. The sqlite3_bind_pointer() routine is part of the-** [pointer passing interface] added for SQLite 3.20.0.+** P, even if the call to sqlite3_bind_pointer() fails. Due to a+** historical design quirk, results are undefined if D is+** SQLITE_TRANSIENT. The T parameter should be a static string,+** preferably a string literal. The sqlite3_bind_pointer() routine is+** part of the [pointer passing interface] added for SQLite 3.20.0.**** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer** for the [prepared statement] or with a prepared statement for which@@ -5289,7 +5409,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);** METHOD: sqlite3_stmt**** ^These routines provide a means to determine the database, table, and-** table column that is the origin of a particular result column in+** table column that is the origin of a particular result column in a** [SELECT] statement.** ^The name of the database or table or column can be returned as** either a UTF-8 or UTF-16 string. ^The _database_ routines return@@ -5427,7 +5547,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);** other than [SQLITE_ROW] before any subsequent invocation of** sqlite3_step(). Failure to reset the prepared statement using** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from-** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],+** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]),** sqlite3_step() began** calling [sqlite3_reset()] automatically in this circumstance rather** than returning [SQLITE_MISUSE]. This is not considered a compatibility@@ -5733,7 +5853,7 @@ SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);**** ^The sqlite3_finalize() function is called to delete a [prepared statement].** ^If the most recent evaluation of the statement encountered no errors-** or if the statement is never been evaluated, then sqlite3_finalize() returns+** or if the statement has never been evaluated, then sqlite3_finalize() returns** SQLITE_OK. ^If the most recent evaluation of statement S failed, then** sqlite3_finalize(S) returns the appropriate [error code] or** [extended error code].@@ -5858,8 +5978,8 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);**** For best security, the [SQLITE_DIRECTONLY] flag is recommended for** all application-defined SQL functions that do not need to be-** used inside of triggers, view, CHECK constraints, or other elements of-** the database schema. This flags is especially recommended for SQL+** used inside of triggers, views, CHECK constraints, or other elements of+** the database schema. This flag is especially recommended for SQL** functions that have side effects or reveal internal application state.** Without this flag, an attacker might be able to modify the schema of** a database file to include invocations of the function with parameters@@ -5890,7 +6010,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);** [user-defined window functions|available here].**** ^(If the final parameter to sqlite3_create_function_v2() or-** sqlite3_create_window_function() is not NULL, then it is destructor for+** sqlite3_create_window_function() is not NULL, then it is the destructor for** the application data pointer. The destructor is invoked when the function** is deleted, either by being overloaded or when the database connection** closes.)^ ^The destructor is also invoked if the call to@@ -5965,7 +6085,7 @@ SQLITE_API int sqlite3_create_window_function(/*** CAPI3REF: Text Encodings**-** These constant define integer codes that represent the various+** These constants define integer codes that represent the various** text encodings supported by SQLite.*/#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */@@ -6057,7 +6177,7 @@ SQLITE_API int sqlite3_create_window_function(** result.** Every function that invokes [sqlite3_result_subtype()] should have this** property. If it does not, then the call to [sqlite3_result_subtype()]-** might become a no-op if the function is used as term in an+** might become a no-op if the function is used as a term in an** [expression index]. On the other hand, SQL functions that never invoke** [sqlite3_result_subtype()] should avoid setting this property, as the** purpose of this property is to disable certain optimizations that are@@ -6184,7 +6304,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6** sqlite3_value_nochange(X) interface returns true if and only if** the column corresponding to X is unchanged by the UPDATE operation** that the xUpdate method call was invoked to implement and if-** and the prior [xColumn] method call that was invoked to extracted+** the prior [xColumn] method call that was invoked to extract** the value for that column returned without setting a result (probably** because it queried [sqlite3_vtab_nochange()] and found that the column** was unchanging). ^Within an [xUpdate] method, any value for which@@ -6290,7 +6410,7 @@ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);** METHOD: sqlite3_value**** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]-** object D and returns a pointer to that copy. ^The [sqlite3_value] returned+** object V and returns a pointer to that copy. ^The [sqlite3_value] returned** is a [protected sqlite3_value] object even if the input is not.** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a** memory allocation fails. ^If V is a [pointer value], then the result@@ -6328,7 +6448,7 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);** allocation error occurs.**** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is-** determined by the N parameter on first successful call. Changing the+** determined by the N parameter on the first successful call. Changing the** value of N in any subsequent call to sqlite3_aggregate_context() within** the same aggregate function instance will not resize the memory** allocation.)^ Within the xFinal callback, it is customary to set@@ -6457,6 +6577,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi** or a NULL pointer if there were no prior calls to** sqlite3_set_clientdata() with the same values of D and N.** Names are compared using strcmp() and are thus case sensitive.+** It returns 0 on success and SQLITE_NOMEM on allocation failure.**** If P and X are both non-NULL, then the destructor X is invoked with** argument P on the first of the following occurrences:@@ -6490,7 +6611,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi**** Security Warning: These interfaces should not be exposed in scripting** languages or in other circumstances where it might be possible for an-** an attacker to invoke them. Any agent that can invoke these interfaces+** attacker to invoke them. Any agent that can invoke these interfaces** can probably also take control of the process.**** Database connection client data is only available for SQLite@@ -6604,7 +6725,7 @@ typedef void (*sqlite3_destructor_type)(void*);** pointed to by the 2nd parameter are taken as the application-defined** function result. If the 3rd parameter is non-negative, then it** must be the byte offset into the string where the NUL terminator would-** appear if the string where NUL terminated. If any NUL characters occur+** appear if the string were NUL terminated. If any NUL characters occur** in the string at a byte offset that is less than the value of the 3rd** parameter, then the resulting string will contain embedded NULs and the** result of expressions operating on strings with embedded NULs is undefined.@@ -6662,7 +6783,7 @@ typedef void (*sqlite3_destructor_type)(void*);** string and preferably a string literal. The sqlite3_result_pointer()** routine is part of the [pointer passing interface] added for SQLite 3.20.0.**-** If these routines are called from within the different thread+** If these routines are called from within a different thread** than the one containing the application-defined function that received** the [sqlite3_context] pointer, the results are undefined.*/@@ -7068,7 +7189,7 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);** METHOD: sqlite3**** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name-** for the N-th database on database connection D, or a NULL pointer of N is+** for the N-th database on database connection D, or a NULL pointer if N is** out of range. An N value of 0 means the main database file. An N of 1 is** the "temp" schema. Larger values of N correspond to various ATTACH-ed** databases.@@ -7163,7 +7284,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);** <dd>The SQLITE_TXN_READ state means that the database is currently** in a read transaction. Content has been read from the database file** but nothing in the database file has changed. The transaction state-** will advanced to SQLITE_TXN_WRITE if any changes occur and there are+** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are** no other conflicting concurrent write transactions. The transaction** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or** [COMMIT].</dd>@@ -7172,7 +7293,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);** <dd>The SQLITE_TXN_WRITE state means that the database is currently** in a write transaction. Content has been written to the database file** but has not yet committed. The transaction state will change to-** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>+** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>*/#define SQLITE_TXN_NONE 0#define SQLITE_TXN_READ 1@@ -7323,6 +7444,8 @@ SQLITE_API int sqlite3_autovacuum_pages(**** ^The second argument is a pointer to the function to invoke when a** row is updated, inserted or deleted in a rowid table.+** ^The update hook is disabled by invoking sqlite3_update_hook()+** with a NULL pointer as the second parameter.** ^The first argument to the callback is a copy of the third argument** to sqlite3_update_hook().** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],@@ -7451,7 +7574,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);** CAPI3REF: Impose A Limit On Heap Size**** These interfaces impose limits on the amount of heap memory that will be-** by all database connections within a single process.+** used by all database connections within a single process.**** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the** soft limit on the amount of heap memory that may be allocated by SQLite.@@ -7509,7 +7632,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);** </ul>)^**** The circumstances under which SQLite will enforce the heap limits may-** changes in future releases of SQLite.+** change in future releases of SQLite.*/SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);@@ -7624,8 +7747,8 @@ SQLITE_API int sqlite3_table_column_metadata(** ^The entry point is zProc.** ^(zProc may be 0, in which case SQLite will try to come up with an** entry point name on its own. It first tries "sqlite3_extension_init".-** If that does not work, it constructs a name "sqlite3_X_init" where the-** X is consists of the lower-case equivalent of all ASCII alphabetic+** If that does not work, it constructs a name "sqlite3_X_init" where+** X consists of the lower-case equivalent of all ASCII alphabetic** characters in the filename from the last "/" to the first following** "." and omitting any initial "lib".)^** ^The sqlite3_load_extension() interface returns@@ -7696,7 +7819,7 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);** ^(Even though the function prototype shows that xEntryPoint() takes** no arguments and returns void, SQLite invokes xEntryPoint() with three** arguments and expects an integer result as if the signature of the-** entry point where as follows:+** entry point were as follows:**** <blockquote><pre>** int xEntryPoint(@@ -7860,7 +7983,7 @@ struct sqlite3_module {** virtual table and might not be checked again by the byte code.)^ ^(The** aConstraintUsage[].omit flag is an optimization hint. When the omit flag** is left in its default setting of false, the constraint will always be-** checked separately in byte code. If the omit flag is change to true, then+** checked separately in byte code. If the omit flag is changed to true, then** the constraint may or may not be checked in byte code. In other words,** when the omit flag is true there is no guarantee that the constraint will** not be checked again using byte code.)^@@ -7886,7 +8009,7 @@ struct sqlite3_module {** The xBestIndex method may optionally populate the idxFlags field with a** mask of SQLITE_INDEX_SCAN_* flags. One such flag is** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN]-** output to show the idxNum has hex instead of as decimal. Another flag is+** output to show the idxNum as hex instead of as decimal. Another flag is** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will** return at most one row.**@@ -8027,7 +8150,7 @@ struct sqlite3_index_info {** the implementation of the [virtual table module]. ^The fourth** parameter is an arbitrary client data pointer that is passed through** into the [xCreate] and [xConnect] methods of the virtual table module-** when a new virtual table is be being created or reinitialized.+** when a new virtual table is being created or reinitialized.**** ^The sqlite3_create_module_v2() interface has a fifth parameter which** is a pointer to a destructor for the pClientData. ^SQLite will@@ -8192,7 +8315,7 @@ typedef struct sqlite3_blob sqlite3_blob;** in *ppBlob. Otherwise an [error code] is returned and, unless the error** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided** the API is not misused, it is always safe to call [sqlite3_blob_close()]-** on *ppBlob after this function it returns.+** on *ppBlob after this function returns.**** This function fails with SQLITE_ERROR if any of the following are true:** <ul>@@ -8312,7 +8435,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *);**** ^Returns the size in bytes of the BLOB accessible via the** successfully opened [BLOB handle] in its only argument. ^The-** incremental blob I/O routines can only read or overwriting existing+** incremental blob I/O routines can only read or overwrite existing** blob content; they cannot change the size of a blob.**** This routine only works on a [BLOB handle] which has been created@@ -8462,7 +8585,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);** ^The sqlite3_mutex_alloc() routine allocates a new** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()** routine returns NULL if it is unable to allocate the requested-** mutex. The argument to sqlite3_mutex_alloc() must one of these+** mutex. The argument to sqlite3_mutex_alloc() must be one of these** integer constants:**** <ul>@@ -8695,7 +8818,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);** CAPI3REF: Retrieve the mutex for a database connection** METHOD: sqlite3**-** ^This interface returns a pointer the [sqlite3_mutex] object that+** ^This interface returns a pointer to the [sqlite3_mutex] object that** serializes access to the [database connection] given in the argument** when the [threading mode] is Serialized.** ^If the [threading mode] is Single-thread or Multi-thread then this@@ -8818,7 +8941,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);** CAPI3REF: SQL Keyword Checking**** These routines provide access to the set of SQL language keywords-** recognized by SQLite. Applications can uses these routines to determine+** recognized by SQLite. Applications can use these routines to determine** whether or not a specific identifier needs to be escaped (for example,** by enclosing in double-quotes) so as not to confuse the parser.**@@ -8986,7 +9109,7 @@ SQLITE_API void sqlite3_str_reset(sqlite3_str*);** content of the dynamic string under construction in X. The value** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X** and might be freed or altered by any subsequent method on the same-** [sqlite3_str] object. Applications must not used the pointer returned+** [sqlite3_str] object. Applications must not use the pointer returned by** [sqlite3_str_value(X)] after any subsequent method call on the same** object. ^Applications may change the content of the string returned** by [sqlite3_str_value(X)] as long as they do not write into any bytes@@ -9072,7 +9195,7 @@ SQLITE_API int sqlite3_status64(** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]** buffer and where forced to overflow to [sqlite3_malloc()]. The** returned value includes allocations that overflowed because they-** where too large (they were larger than the "sz" parameter to+** were too large (they were larger than the "sz" parameter to** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because** no space was left in the page cache.</dd>)^**@@ -9131,9 +9254,18 @@ SQLITE_API int sqlite3_status64(** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a** non-zero [error code] on failure.**+** ^The sqlite3_db_status64(D,O,C,H,R) routine works exactly the same+** way as sqlite3_db_status(D,O,C,H,R) routine except that the C and H+** parameters are pointer to 64-bit integers (type: sqlite3_int64) instead+** of pointers to 32-bit integers, which allows larger status values+** to be returned. If a status value exceeds 2,147,483,647 then+** sqlite3_db_status() will truncate the value whereas sqlite3_db_status64()+** will return the full value.+**** See also: [sqlite3_status()] and [sqlite3_stmt_status()].*/SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);+SQLITE_API int sqlite3_db_status64(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int);/*** CAPI3REF: Status Parameters for database connections@@ -9156,28 +9288,29 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>** <dd>This parameter returns the number of malloc attempts that were** satisfied using lookaside memory. Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>-** <dd>This parameter returns the number malloc attempts that might have+** <dd>This parameter returns the number of malloc attempts that might have** been satisfied using lookaside memory but failed due to the amount of** memory requested being larger than the lookaside slot size.** Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>-** <dd>This parameter returns the number malloc attempts that might have+** <dd>This parameter returns the number of malloc attempts that might have** been satisfied using lookaside memory but failed due to all lookaside** memory already being in use.** Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap** memory used by all pager caches associated with the database connection.)^** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.+** </dd>**** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>@@ -9186,10 +9319,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** memory used by that pager cache is divided evenly between the attached** connections.)^ In other words, if none of the pager caches associated** with the database connection are shared, this request returns the same-** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are+** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are** shared, the value returned by this call will be smaller than that returned** by DBSTATUS_CACHE_USED. ^The highwater mark associated with-** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.+** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd>**** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap@@ -9199,6 +9332,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** schema memory is shared with other database connections due to** [shared cache mode] being enabled.** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.+** </dd>**** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap@@ -9228,6 +9362,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** If an IO or other error occurs while writing a page to disk, the effect** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.+** <p>+** ^(There is overlap between the quantities measured by this parameter+** (SQLITE_DBSTATUS_CACHE_WRITE) and SQLITE_DBSTATUS_TEMPBUF_SPILL.+** Resetting one will reduce the other.)^** </dd>**** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>@@ -9235,7 +9373,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** been written to disk in the middle of a transaction due to the page** cache overflowing. Transactions are more efficient if they are written** to disk all at once. When pages spill mid-transaction, that introduces-** additional overhead. This parameter can be used help identify+** additional overhead. This parameter can be used to help identify** inefficiencies that can be resolved by increasing the cache size.** </dd>**@@ -9243,6 +9381,18 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** <dd>This parameter returns zero for the current value if and only if** all foreign key constraints (deferred or immediate) have been** resolved.)^ ^The highwater mark is always 0.+**+** [[SQLITE_DBSTATUS_TEMPBUF_SPILL] ^(<dt>SQLITE_DBSTATUS_TEMPBUF_SPILL</dt>+** <dd>^(This parameter returns the number of bytes written to temporary+** files on disk that could have been kept in memory had sufficient memory+** been available. This value includes writes to intermediate tables that+** are part of complex queries, external sorts that spill to disk, and+** writes to TEMP tables.)^+** ^The highwater mark is always 0.+** <p>+** ^(There is overlap between the quantities measured by this parameter+** (SQLITE_DBSTATUS_TEMPBUF_SPILL) and SQLITE_DBSTATUS_CACHE_WRITE.+** Resetting one will reduce the other.)^** </dd>** </dl>*/@@ -9259,7 +9409,8 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r#define SQLITE_DBSTATUS_DEFERRED_FKS 10#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11#define SQLITE_DBSTATUS_CACHE_SPILL 12-#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */+#define SQLITE_DBSTATUS_TEMPBUF_SPILL 13+#define SQLITE_DBSTATUS_MAX 13 /* Largest defined DBSTATUS *//*@@ -9306,13 +9457,13 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>** <dd>^This is the number of sort operations that have occurred.** A non-zero value in this counter may indicate an opportunity to-** improvement performance through careful use of indices.</dd>+** improve performance through careful use of indices.</dd>**** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>** <dd>^This is the number of rows inserted into transient indices that** were created automatically in order to help joins run faster.** A non-zero value in this counter may indicate an opportunity to-** improvement performance by adding permanent indices that do not+** improve performance by adding permanent indices that do not** need to be reinitialized each time the statement is run.</dd>**** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>@@ -9321,19 +9472,19 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** to 2147483647. The number of virtual machine operations can be** used as a proxy for the total work done by the prepared statement.** If the number of virtual machine operations exceeds 2147483647-** then the value returned by this statement status code is undefined.+** then the value returned by this statement status code is undefined.</dd>**** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>** <dd>^This is the number of times that the prepare statement has been** automatically regenerated due to schema changes or changes to-** [bound parameters] that might affect the query plan.+** [bound parameters] that might affect the query plan.</dd>**** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>** <dd>^This is the number of times that the prepared statement has** been run. A single "run" for the purposes of this counter is one** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].** The counter is incremented on the first [sqlite3_step()] call of each-** cycle.+** cycle.</dd>**** [[SQLITE_STMTSTATUS_FILTER_MISS]]** [[SQLITE_STMTSTATUS_FILTER HIT]]@@ -9343,7 +9494,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** step was bypassed because a Bloom filter returned not-found. The** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of** times that the Bloom filter returned a find, and thus the join step-** had to be processed as normal.+** had to be processed as normal.</dd>**** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>** <dd>^This is the approximate number of bytes of heap memory@@ -9448,9 +9599,9 @@ struct sqlite3_pcache_page {** SQLite will typically create one cache instance for each open database file,** though this is not guaranteed. ^The** first parameter, szPage, is the size in bytes of the pages that must-** be allocated by the cache. ^szPage will always a power of two. ^The+** be allocated by the cache. ^szPage will always be a power of two. ^The** second parameter szExtra is a number of bytes of extra storage-** associated with each page cache entry. ^The szExtra parameter will+** associated with each page cache entry. ^The szExtra parameter will be** a number less than 250. SQLite will use the** extra szExtra bytes on each page to store metadata about the underlying** database page on disk. The value passed into szExtra depends@@ -9458,17 +9609,17 @@ struct sqlite3_pcache_page {** ^The third argument to xCreate(), bPurgeable, is true if the cache being** created will be used to cache database pages of a file stored on disk, or** false if it is used for an in-memory database. The cache implementation-** does not have to do anything special based with the value of bPurgeable;+** does not have to do anything special based upon the value of bPurgeable;** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will** never invoke xUnpin() except to deliberately delete a page.** ^In other words, calls to xUnpin() on a cache with bPurgeable set to** false will always have the "discard" flag set to true.-** ^Hence, a cache created with bPurgeable false will+** ^Hence, a cache created with bPurgeable set to false will** never contain any unpinned pages.**** [[the xCachesize() page cache method]]** ^(The xCachesize() method may be called at any time by SQLite to set the-** suggested maximum cache-size (number of pages stored by) the cache+** suggested maximum cache-size (number of pages stored) for the cache** instance passed as the first argument. This is the value configured using** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable** parameter, the implementation is not required to do anything with this@@ -9495,12 +9646,12 @@ struct sqlite3_pcache_page {** implementation must return a pointer to the page buffer with its content** intact. If the requested page is not already in the cache, then the** cache implementation should use the value of the createFlag-** parameter to help it determined what action to take:+** parameter to help it determine what action to take:**** <table border=1 width=85% align=center>** <tr><th> createFlag <th> Behavior when page is not already in cache** <tr><td> 0 <td> Do not allocate a new page. Return NULL.-** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.+** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so.** Otherwise return NULL.** <tr><td> 2 <td> Make every effort to allocate a new page. Only return** NULL if allocating a new page is effectively impossible.@@ -9517,7 +9668,7 @@ struct sqlite3_pcache_page {** as its second argument. If the third parameter, discard, is non-zero,** then the page must be evicted from the cache.** ^If the discard parameter is-** zero, then the page may be discarded or retained at the discretion of+** zero, then the page may be discarded or retained at the discretion of the** page cache implementation. ^The page cache implementation** may choose to evict unpinned pages at any time.**@@ -9535,7 +9686,7 @@ struct sqlite3_pcache_page {** When SQLite calls the xTruncate() method, the cache must discard all** existing cache entries with page numbers (keys) greater than or equal** to the value of the iLimit parameter passed to xTruncate(). If any-** of these pages are pinned, they are implicitly unpinned, meaning that+** of these pages are pinned, they become implicitly unpinned, meaning that** they can be safely discarded.**** [[the xDestroy() page cache method]]@@ -9715,7 +9866,7 @@ typedef struct sqlite3_backup sqlite3_backup;** external process or via a database connection other than the one being** used by the backup operation, then the backup will be automatically** restarted by the next call to sqlite3_backup_step(). ^If the source-** database is modified by the using the same database connection as is used+** database is modified by using the same database connection as is used** by the backup operation, then the backup database is automatically** updated at the same time.**@@ -9732,7 +9883,7 @@ typedef struct sqlite3_backup sqlite3_backup;** and may not be used following a call to sqlite3_backup_finish().**** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no-** sqlite3_backup_step() errors occurred, regardless or whether or not+** sqlite3_backup_step() errors occurred, regardless of whether or not** sqlite3_backup_step() completed.** ^If an out-of-memory condition or IO error occurred during any prior** sqlite3_backup_step() call on the same [sqlite3_backup] object, then@@ -9834,7 +9985,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);** application receives an SQLITE_LOCKED error, it may call the** sqlite3_unlock_notify() method with the blocked connection handle as** the first argument to register for a callback that will be invoked-** when the blocking connections current transaction is concluded. ^The+** when the blocking connection's current transaction is concluded. ^The** callback is invoked from within the [sqlite3_step] or [sqlite3_close]** call that concludes the blocking connection's transaction.**@@ -9854,7 +10005,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);** blocked connection already has a registered unlock-notify callback,** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is** called with a NULL pointer as its second argument, then any existing-** unlock-notify callback is canceled. ^The blocked connections+** unlock-notify callback is canceled. ^The blocked connection's** unlock-notify callback may also be canceled by closing the blocked** connection using [sqlite3_close()].**@@ -10024,7 +10175,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);** is the number of pages currently in the write-ahead log file,** including those that were just committed.**-** The callback function should normally return [SQLITE_OK]. ^If an error+** ^The callback function should normally return [SQLITE_OK]. ^If an error** code is returned, that error will propagate back up through the** SQLite code base to cause the statement that provoked the callback** to report an error, though the commit will have still occurred. If the@@ -10032,13 +10183,26 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);** that does not correspond to any valid SQLite error code, the results** are undefined.**-** A single database handle may have at most a single write-ahead log callback-** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any-** previously registered write-ahead log callback. ^The return value is-** a copy of the third parameter from the previous call, if any, or 0.-** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the-** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will-** overwrite any prior [sqlite3_wal_hook()] settings.+** ^A single database handle may have at most a single write-ahead log+** callback registered at one time. ^Calling [sqlite3_wal_hook()]+** replaces the default behavior or previously registered write-ahead+** log callback.+**+** ^The return value is a copy of the third parameter from the+** previous call, if any, or 0.+**+** ^The [sqlite3_wal_autocheckpoint()] interface and the+** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and+** will overwrite any prior [sqlite3_wal_hook()] settings.+**+** ^If a write-ahead log callback is set using this function then+** [sqlite3_wal_checkpoint_v2()] or [PRAGMA wal_checkpoint]+** should be invoked periodically to keep the write-ahead log file+** from growing without bound.+**+** ^Passing a NULL pointer for the callback disables automatic+** checkpointing entirely. To re-enable the default behavior, call+** sqlite3_wal_autocheckpoint(db,1000) or use [PRAGMA wal_checkpoint].*/SQLITE_API void *sqlite3_wal_hook(sqlite3*,@@ -10055,7 +10219,7 @@ SQLITE_API void *sqlite3_wal_hook(** to automatically [checkpoint]** after committing a transaction if there are N or** more frames in the [write-ahead log] file. ^Passing zero or-** a negative value as the nFrame parameter disables automatic+** a negative value as the N parameter disables automatic** checkpoints entirely.**** ^The callback registered by this function replaces any existing callback@@ -10071,9 +10235,10 @@ SQLITE_API void *sqlite3_wal_hook(**** ^Every new [database connection] defaults to having the auto-checkpoint** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]-** pages. The use of this interface-** is only necessary if the default setting is found to be suboptimal-** for a particular application.+** pages.+**+** ^The use of this interface is only necessary if the default setting+** is found to be suboptimal for a particular application.*/SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);@@ -10138,6 +10303,11 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the** addition that it also truncates the log file to zero bytes just prior** to a successful return.+**+** <dt>SQLITE_CHECKPOINT_NOOP<dd>+** ^This mode always checkpoints zero frames. The only reason to invoke+** a NOOP checkpoint is to access the values returned by+** sqlite3_wal_checkpoint_v2() via output parameters *pnLog and *pnCkpt.** </dl>**** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in@@ -10208,6 +10378,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the** meaning of each of these checkpoint modes.*/+#define SQLITE_CHECKPOINT_NOOP -1 /* Do no work at all */#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */@@ -10252,7 +10423,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);** support constraints. In this configuration (which is the default) if** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire** statement is rolled back as if [ON CONFLICT | OR ABORT] had been-** specified as part of the users SQL statement, regardless of the actual+** specified as part of the user's SQL statement, regardless of the actual** ON CONFLICT mode specified.**** If X is non-zero, then the virtual table implementation guarantees@@ -10286,7 +10457,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>** <dd>Calls of the form** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the-** the [xConnect] or [xCreate] methods of a [virtual table] implementation+** [xConnect] or [xCreate] methods of a [virtual table] implementation** identify that virtual table as being safe to use from within triggers** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the** virtual table can do no serious harm even if it is controlled by a@@ -10454,7 +10625,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);** </table>**** ^For the purposes of comparing virtual table output values to see if the-** values are same value for sorting purposes, two NULL values are considered+** values are the same value for sorting purposes, two NULL values are considered** to be the same. In other words, the comparison operator is "IS"** (or "IS NOT DISTINCT FROM") and not "==".**@@ -10464,7 +10635,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);**** ^A virtual table implementation is always free to return rows in any order** it wants, as long as the "orderByConsumed" flag is not set. ^When the-** the "orderByConsumed" flag is unset, the query planner will add extra+** "orderByConsumed" flag is unset, the query planner will add extra** [bytecode] to ensure that the final results returned by the SQL query are** ordered correctly. The use of the "orderByConsumed" flag and the** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful@@ -10561,7 +10732,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);** sqlite3_vtab_in_next(X,P) should be one of the parameters to the** xFilter method which invokes these routines, and specifically** a parameter that was previously selected for all-at-once IN constraint-** processing use the [sqlite3_vtab_in()] interface in the+** processing using the [sqlite3_vtab_in()] interface in the** [xBestIndex|xBestIndex method]. ^(If the X parameter is not** an xFilter argument that was selected for all-at-once IN constraint** processing, then these routines return [SQLITE_ERROR].)^@@ -10576,7 +10747,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);** ){** // do something with pVal** }-** if( rc!=SQLITE_OK ){+** if( rc!=SQLITE_DONE ){** // an error has occurred** }** </pre></blockquote>)^@@ -10616,7 +10787,7 @@ SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V)** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th** constraint is not available. ^The sqlite3_vtab_rhs_value() interface-** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if+** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if** something goes wrong.**** The sqlite3_vtab_rhs_value() interface is usually only successful if@@ -10644,8 +10815,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** KEYWORDS: {conflict resolution mode}**** These constants are returned by [sqlite3_vtab_on_conflict()] to-** inform a [virtual table] implementation what the [ON CONFLICT] mode-** is for the SQL statement being evaluated.+** inform a [virtual table] implementation of the [ON CONFLICT] mode+** for the SQL statement being evaluated.**** Note that the [SQLITE_IGNORE] constant is also used as a potential** return value from the [sqlite3_set_authorizer()] callback and that@@ -10685,39 +10856,39 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>** <dd>^The "double" variable pointed to by the V parameter will be set to the** query planner's estimate for the average number of rows output from each-** iteration of the X-th loop. If the query planner's estimates was accurate,+** iteration of the X-th loop. If the query planner's estimate was accurate,** then this value will approximate the quotient NVISIT/NLOOP and the** product of this value for all prior loops with the same SELECTID will-** be the NLOOP value for the current loop.+** be the NLOOP value for the current loop.</dd>**** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>** <dd>^The "const char *" variable pointed to by the V parameter will be set** to a zero-terminated UTF-8 string containing the name of the index or table-** used for the X-th loop.+** used for the X-th loop.</dd>**** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>** <dd>^The "const char *" variable pointed to by the V parameter will be set** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]-** description for the X-th loop.+** description for the X-th loop.</dd>**** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt>** <dd>^The "int" variable pointed to by the V parameter will be set to the** id for the X-th query plan element. The id value is unique within the** statement. The select-id is the same value as is output in the first-** column of an [EXPLAIN QUERY PLAN] query.+** column of an [EXPLAIN QUERY PLAN] query.</dd>**** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt>** <dd>The "int" variable pointed to by the V parameter will be set to the-** the id of the parent of the current query element, if applicable, or+** id of the parent of the current query element, if applicable, or** to zero if the query element has no parent. This is the same value as-** returned in the second column of an [EXPLAIN QUERY PLAN] query.+** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd>**** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt>** <dd>The sqlite3_int64 output value is set to the number of cycles,** according to the processor time-stamp counter, that elapsed while the** query element was being processed. This value is not available for** all query elements - if it is unavailable the output variable is-** set to -1.+** set to -1.</dd>** </dl>*/#define SQLITE_SCANSTAT_NLOOP 0@@ -10758,8 +10929,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter.**** Parameter "idx" identifies the specific query element to retrieve statistics-** for. Query elements are numbered starting from zero. A value of -1 may be-** to query for statistics regarding the entire query. ^If idx is out of range+** for. Query elements are numbered starting from zero. A value of -1 may+** retrieve statistics for the entire query. ^If idx is out of range** - less than -1 or greater than or equal to the total number of query** elements used to implement the statement - a non-zero value is returned and** the variable that pOut points to is unchanged.@@ -10802,7 +10973,7 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);** METHOD: sqlite3**** ^If a write-transaction is open on [database connection] D when the-** [sqlite3_db_cacheflush(D)] interface invoked, any dirty+** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty** pages in the pager-cache that are not currently in use are written out** to disk. A dirty page may be in use if a database cursor created by an** active SQL statement is reading from it, or if it is page 1 of a database@@ -10916,8 +11087,8 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);** triggers; and so forth.**** When the [sqlite3_blob_write()] API is used to update a blob column,-** the pre-update hook is invoked with SQLITE_DELETE. This is because the-** in this case the new values are not available. In this case, when a+** the pre-update hook is invoked with SQLITE_DELETE, because+** the new values are not yet available. In this case, when a** callback made with op==SQLITE_DELETE is actually a write using the** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns** the index of the column being written. In other cases, where the@@ -11035,7 +11206,7 @@ typedef struct sqlite3_snapshot {** The [sqlite3_snapshot_get()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(+SQLITE_API int sqlite3_snapshot_get(sqlite3 *db,const char *zSchema,sqlite3_snapshot **ppSnapshot@@ -11084,7 +11255,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(** The [sqlite3_snapshot_open()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(+SQLITE_API int sqlite3_snapshot_open(sqlite3 *db,const char *zSchema,sqlite3_snapshot *pSnapshot@@ -11101,7 +11272,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(** The [sqlite3_snapshot_free()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);+SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot*);/*** CAPI3REF: Compare the ages of two snapshot handles.@@ -11128,7 +11299,7 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);** This interface is only available if SQLite is compiled with the** [SQLITE_ENABLE_SNAPSHOT] option.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(+SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1,sqlite3_snapshot *p2);@@ -11156,7 +11327,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(** This interface is only available if SQLite is compiled with the** [SQLITE_ENABLE_SNAPSHOT] option.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);+SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);/*** CAPI3REF: Serialize a database@@ -11170,7 +11341,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c** For an ordinary on-disk database file, the serialization is just a** copy of the disk file. For an in-memory database or a "TEMP" database,** the serialization is the same sequence of bytes which would be written-** to disk if that database where backed up to disk.+** to disk if that database were backed up to disk.**** The usual case is that sqlite3_serialize() copies the serialization of** the database into memory obtained from [sqlite3_malloc64()] and returns@@ -11179,7 +11350,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations** are made, and the sqlite3_serialize() function will return a pointer** to the contiguous memory representation of the database that SQLite-** is currently using for that database, or NULL if the no such contiguous+** is currently using for that database, or NULL if no such contiguous** memory representation of the database exists. A contiguous memory** representation of the database will usually only exist if there has** been a prior call to [sqlite3_deserialize(D,S,...)] with the same@@ -11230,12 +11401,13 @@ SQLITE_API unsigned char *sqlite3_serialize(**** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the** [database connection] D to disconnect from database S and then-** reopen S as an in-memory database based on the serialization contained-** in P. The serialized database P is N bytes in size. M is the size of-** the buffer P, which might be larger than N. If M is larger than N, and-** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is-** permitted to add content to the in-memory database as long as the total-** size does not exceed M bytes.+** reopen S as an in-memory database based on the serialization+** contained in P. If S is a NULL pointer, the main database is+** used. The serialized database P is N bytes in size. M is the size+** of the buffer P, which might be larger than N. If M is larger than+** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then+** SQLite is permitted to add content to the in-memory database as+** long as the total size does not exceed M bytes.**** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will** invoke sqlite3_free() on the serialization buffer when the database@@ -11250,7 +11422,7 @@ SQLITE_API unsigned char *sqlite3_serialize(** database is currently in a read transaction or is involved in a backup** operation.**-** It is not possible to deserialized into the TEMP database. If the+** It is not possible to deserialize into the TEMP database. If the** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the** function returns SQLITE_ERROR.**@@ -11272,7 +11444,7 @@ SQLITE_API int sqlite3_deserialize(sqlite3 *db, /* The database connection */const char *zSchema, /* Which DB to reopen with the deserialization */unsigned char *pData, /* The serialized database content */- sqlite3_int64 szDb, /* Number bytes in the deserialization */+ sqlite3_int64 szDb, /* Number of bytes in the deserialization */sqlite3_int64 szBuf, /* Total size of buffer pData[] */unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */);@@ -11280,7 +11452,7 @@ SQLITE_API int sqlite3_deserialize(/*** CAPI3REF: Flags for sqlite3_deserialize()**-** The following are allowed values for 6th argument (the F argument) to+** The following are allowed values for the 6th argument (the F argument) to** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.**** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization@@ -11302,6 +11474,54 @@ SQLITE_API int sqlite3_deserialize(#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */+/*+** CAPI3REF: Bind array values to the CARRAY table-valued function+**+** The sqlite3_carray_bind(S,I,P,N,F,X) interface binds an array value to+** one of the first argument of the [carray() table-valued function]. The+** S parameter is a pointer to the [prepared statement] that uses the carray()+** functions. I is the parameter index to be bound. P is a pointer to the+** array to be bound, and N is the number of eements in the array. The+** F argument is one of constants [SQLITE_CARRAY_INT32], [SQLITE_CARRAY_INT64],+** [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT], or [SQLITE_CARRAY_BLOB] to+** indicate the datatype of the array being bound. The X argument is not a+** NULL pointer, then SQLite will invoke the function X on the P parameter+** after it has finished using P, even if the call to+** sqlite3_carray_bind() fails. The special-case finalizer+** SQLITE_TRANSIENT has no effect here.+*/+SQLITE_API int sqlite3_carray_bind(+ sqlite3_stmt *pStmt, /* Statement to be bound */+ int i, /* Parameter index */+ void *aData, /* Pointer to array data */+ int nData, /* Number of data elements */+ int mFlags, /* CARRAY flags */+ void (*xDel)(void*) /* Destructor for aData */+);++/*+** CAPI3REF: Datatypes for the CARRAY table-valued function+**+** The fifth argument to the [sqlite3_carray_bind()] interface musts be+** one of the following constants, to specify the datatype of the array+** that is being bound into the [carray table-valued function].+*/+#define SQLITE_CARRAY_INT32 0 /* Data is 32-bit signed integers */+#define SQLITE_CARRAY_INT64 1 /* Data is 64-bit signed integers */+#define SQLITE_CARRAY_DOUBLE 2 /* Data is doubles */+#define SQLITE_CARRAY_TEXT 3 /* Data is char* */+#define SQLITE_CARRAY_BLOB 4 /* Data is struct iovec */++/*+** Versions of the above #defines that omit the initial SQLITE_, for+** legacy compatibility.+*/+#define CARRAY_INT32 0 /* Data is 32-bit signed integers */+#define CARRAY_INT64 1 /* Data is 64-bit signed integers */+#define CARRAY_DOUBLE 2 /* Data is doubles */+#define CARRAY_TEXT 3 /* Data is char* */+#define CARRAY_BLOB 4 /* Data is struct iovec */+/*** Undo the hack that converts floating point types to integer for** builds on processors without floating point support.@@ -11805,9 +12025,10 @@ SQLITE_API void sqlite3session_table_filter(** is inserted while a session object is enabled, then later deleted while** the same session object is disabled, no INSERT record will appear in the** changeset, even though the delete took place while the session was disabled.-** Or, if one field of a row is updated while a session is disabled, and-** another field of the same row is updated while the session is enabled, the-** resulting changeset will contain an UPDATE change that updates both fields.+** Or, if one field of a row is updated while a session is enabled, and+** then another field of the same row is updated while the session is disabled,+** the resulting changeset will contain an UPDATE change that updates both+** fields.*/SQLITE_API int sqlite3session_changeset(sqlite3_session *pSession, /* Session object */@@ -11879,8 +12100,9 @@ SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession** database zFrom the contents of the two compatible tables would be** identical.**-** It an error if database zFrom does not exist or does not contain the-** required compatible table.+** Unless the call to this function is a no-op as described above, it is an+** error if database zFrom does not exist or does not contain the required+** compatible table.**** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg@@ -12015,7 +12237,7 @@ SQLITE_API int sqlite3changeset_start_v2(** The following flags may passed via the 4th parameter to** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:**-** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>+** <dt>SQLITE_CHANGESETSTART_INVERT <dd>** Invert the changeset while iterating through it. This is equivalent to** inverting a changeset using sqlite3changeset_invert() before applying it.** It is an error to specify this flag with a patchset.@@ -12330,19 +12552,6 @@ SQLITE_API int sqlite3changeset_concat(void **ppOut /* OUT: Buffer containing output changeset */);--/*-** CAPI3REF: Upgrade the Schema of a Changeset/Patchset-*/-SQLITE_API int sqlite3changeset_upgrade(- sqlite3 *db,- const char *zDb,- int nIn, const void *pIn, /* Input changeset */- int *pnOut, void **ppOut /* OUT: Inverse of input */-);---/*** CAPI3REF: Changegroup Handle**@@ -12572,14 +12781,32 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** update the "main" database attached to handle db with the changes found in** the changeset passed via the second and third arguments.**+** All changes made by these functions are enclosed in a savepoint transaction.+** If any other error (aside from a constraint failure when attempting to+** write to the target database) occurs, then the savepoint transaction is+** rolled back, restoring the target database to its original state, and an+** SQLite error code returned. Additionally, starting with version 3.51.0,+** an error code and error message that may be accessed using the+** [sqlite3_errcode()] and [sqlite3_errmsg()] APIs are left in the database+** handle.+**** The fourth argument (xFilter) passed to these functions is the "filter-** callback". If it is not NULL, then for each table affected by at least one-** change in the changeset, the filter callback is invoked with-** the table name as the second argument, and a copy of the context pointer-** passed as the sixth argument as the first. If the "filter callback"-** returns zero, then no attempt is made to apply any changes to the table.-** Otherwise, if the return value is non-zero or the xFilter argument to-** is NULL, all changes related to the table are attempted.+** callback". This may be passed NULL, in which case all changes in the+** changeset are applied to the database. For sqlite3changeset_apply() and+** sqlite3_changeset_apply_v2(), if it is not NULL, then it is invoked once+** for each table affected by at least one change in the changeset. In this+** case the table name is passed as the second argument, and a copy of+** the context pointer passed as the sixth argument to apply() or apply_v2()+** as the first. If the "filter callback" returns zero, then no attempt is+** made to apply any changes to the table. Otherwise, if the return value is+** non-zero, all changes related to the table are attempted.+**+** For sqlite3_changeset_apply_v3(), the xFilter callback is invoked once+** per change. The second argument in this case is an sqlite3_changeset_iter+** that may be queried using the usual APIs for the details of the current+** change. If the "filter callback" returns zero in this case, then no attempt+** is made to apply the current change. If it returns non-zero, the change+** is applied.**** For each table that is not excluded by the filter callback, this function** tests that the target database contains a compatible table. A table is@@ -12600,11 +12827,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** one such warning is issued for each table in the changeset.**** For each change for which there is a compatible table, an attempt is made-** to modify the table contents according to the UPDATE, INSERT or DELETE-** change. If a change cannot be applied cleanly, the conflict handler-** function passed as the fifth argument to sqlite3changeset_apply() may be-** invoked. A description of exactly when the conflict handler is invoked for-** each type of change is below.+** to modify the table contents according to each UPDATE, INSERT or DELETE+** change that is not excluded by a filter callback. If a change cannot be+** applied cleanly, the conflict handler function passed as the fifth argument+** to sqlite3changeset_apply() may be invoked. A description of exactly when+** the conflict handler is invoked for each type of change is below.**** Unlike the xFilter argument, xConflict may not be passed NULL. The results** of passing anything other than a valid function pointer as the xConflict@@ -12700,12 +12927,6 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** This can be used to further customize the application's conflict** resolution strategy.**-** All changes made by these functions are enclosed in a savepoint transaction.-** If any other error (aside from a constraint failure when attempting to-** write to the target database) occurs, then the savepoint transaction is-** rolled back, restoring the target database to its original state, and an-** SQLite error code returned.-**** If the output parameters (ppRebase) and (pnRebase) are non-NULL and** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()** may set (*ppRebase) to point to a "rebase" that may be used with the@@ -12755,6 +12976,23 @@ SQLITE_API int sqlite3changeset_apply_v2(void **ppRebase, int *pnRebase, /* OUT: Rebase data */int flags /* SESSION_CHANGESETAPPLY_* flags */);+SQLITE_API int sqlite3changeset_apply_v3(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int nChangeset, /* Size of changeset in bytes */+ void *pChangeset, /* Changeset blob */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p /* Handle describing change */+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase, /* OUT: Rebase data */+ int flags /* SESSION_CHANGESETAPPLY_* flags */+);/*** CAPI3REF: Flags for sqlite3changeset_apply_v2@@ -13174,6 +13412,23 @@ SQLITE_API int sqlite3changeset_apply_v2_strm(void **ppRebase, int *pnRebase,int flags);+SQLITE_API int sqlite3changeset_apply_v3_strm(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */+ void *pIn, /* First arg for xInput */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase,+ int flags+);SQLITE_API int sqlite3changeset_concat_strm(int (*xInputA)(void *pIn, void *pData, int *pnData),void *pInA,@@ -14079,6 +14334,27 @@ struct fts5_api {#endif#define SQLITE_MIN_LENGTH 30 /* Minimum value for the length limit */+/*+** Maximum size of any single memory allocation.+**+** This is not a limit on the total amount of memory used. This is+** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc().+**+** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391+** This provides a 256-byte safety margin for defense against 32-bit+** signed integer overflow bugs when computing memory allocation sizes.+** Paranoid applications might want to reduce the maximum allocation size+** further for an even larger safety margin. 0x3fffffff or 0x0fffffff+** or even smaller would be reasonable upper bounds on the size of a memory+** allocations for most applications.+*/+#ifndef SQLITE_MAX_ALLOCATION_SIZE+# define SQLITE_MAX_ALLOCATION_SIZE 2147483391+#endif+#if SQLITE_MAX_ALLOCATION_SIZE>2147483391+# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391+#endif+/*** This is the maximum number of**@@ -14090,14 +14366,22 @@ struct fts5_api {** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.** * Terms in the VALUES clause of an INSERT statement**-** The hard upper limit here is 32676. Most database people will+** The hard upper limit here is 32767. Most database people will** tell you that in a well-normalized database, you usually should** not have more than a dozen or so columns in any table. And if** that is the case, there is no point in having more than a few** dozen values in any of the other situations described above.+**+** An index can only have SQLITE_MAX_COLUMN columns from the user+** point of view, but the underlying b-tree that implements the index+** might have up to twice as many columns in a WITHOUT ROWID table,+** since must also store the primary key at the end. Hence the+** column count for Index is u16 instead of i16.*/-#ifndef SQLITE_MAX_COLUMN+#if !defined(SQLITE_MAX_COLUMN)# define SQLITE_MAX_COLUMN 2000+#elif SQLITE_MAX_COLUMN>32767+# error SQLITE_MAX_COLUMN may not exceed 32767#endif/*@@ -14242,7 +14526,7 @@ struct fts5_api {** Maximum number of pages in one database file.**** This is really just the default value for the max_page_count pragma.-** This value can be lowered (or raised) at run-time using that the+** This value can be lowered (or raised) at run-time using the** max_page_count macro.*/#ifndef SQLITE_MAX_PAGE_COUNT@@ -14749,6 +15033,7 @@ struct HashElem {HashElem *next, *prev; /* Next and previous elements in the table */void *data; /* Data associated with this element */const char *pKey; /* Key associated with this element */+ unsigned int h; /* hash for pKey */};/*@@ -15109,7 +15394,17 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);** ourselves.*/#ifndef offsetof-#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))+# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))+#endif++/*+** Work around C99 "flex-array" syntax for pre-C99 compilers, so as+** to avoid complaints from -fsanitize=strict-bounds.+*/+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)+# define FLEXARRAY+#else+# define FLEXARRAY 1#endif/*@@ -15187,6 +15482,11 @@ typedef INT16_TYPE i16; /* 2-byte signed integer */typedef UINT8_TYPE u8; /* 1-byte unsigned integer */typedef INT8_TYPE i8; /* 1-byte signed integer */+/* A bitfield type for use inside of structures. Always follow with :N where+** N is the number of bits.+*/+typedef unsigned bft; /* Bit Field Type */+/*** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value** that can be stored in a u32 without loss of data. The value@@ -15355,6 +15655,14 @@ typedef INT16_TYPE LogEst;#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)+/*+** Macro SMXV(n) return the maximum value that can be held in variable n,+** assuming n is a signed integer type. UMXV(n) is similar for unsigned+** integer types.+*/+#define SMXV(n) ((((i64)1)<<(sizeof(n)*8-1))-1)+#define UMXV(n) ((((i64)1)<<(sizeof(n)*8))-1)+/*** Round up a number to the next larger multiple of 8. This is used** to force 8-byte alignment on 64-bit architectures.@@ -15474,6 +15782,8 @@ SQLITE_PRIVATE u32 sqlite3TreeTrace;** 0x00020000 Transform DISTINCT into GROUP BY** 0x00040000 SELECT tree dump after all code has been generated** 0x00080000 NOT NULL strength reduction+** 0x00100000 Pointers are all shown as zero+** 0x00200000 EXISTS-to-JOIN optimization*//*@@ -15518,6 +15828,7 @@ SQLITE_PRIVATE u32 sqlite3WhereTrace;** 0x00020000 Show WHERE terms returned from whereScanNext()** 0x00040000 Solver overview messages** 0x00080000 Star-query heuristic+** 0x00100000 Pointers are all shown as zero*/@@ -15590,7 +15901,7 @@ struct BusyHandler {** pointer will work here as long as it is distinct from SQLITE_STATIC** and SQLITE_TRANSIENT.*/-#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3OomClear)+#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3RowSetClear)/*** When SQLITE_OMIT_WSD is defined, it means that the target platform does@@ -15811,8 +16122,8 @@ typedef int VList;** must provide its own VFS implementation together with sqlite3_os_init()** and sqlite3_os_end() routines.*/-#if !defined(SQLITE_OS_KV) && !defined(SQLITE_OS_OTHER) && \- !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_WIN)+#if SQLITE_OS_KV+1<=1 && SQLITE_OS_OTHER+1<=1 && \+ SQLITE_OS_WIN+1<=1 && SQLITE_OS_UNIX+1<=1# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \defined(__MINGW32__) || defined(__BORLANDC__)# define SQLITE_OS_WIN 1@@ -16658,6 +16969,7 @@ struct BtreePayload {SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,int flags, int seekResult);SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);+SQLITE_PRIVATE int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes);SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);@@ -16991,20 +17303,20 @@ typedef struct VdbeOpList VdbeOpList;#define OP_SorterSort 34 /* jump */#define OP_Sort 35 /* jump */#define OP_Rewind 36 /* jump0 */-#define OP_SorterNext 37 /* jump */-#define OP_Prev 38 /* jump */-#define OP_Next 39 /* jump */-#define OP_IdxLE 40 /* jump, synopsis: key=r[P3@P4] */-#define OP_IdxGT 41 /* jump, synopsis: key=r[P3@P4] */-#define OP_IdxLT 42 /* jump, synopsis: key=r[P3@P4] */+#define OP_IfEmpty 37 /* jump, synopsis: if( empty(P1) ) goto P2 */+#define OP_SorterNext 38 /* jump */+#define OP_Prev 39 /* jump */+#define OP_Next 40 /* jump */+#define OP_IdxLE 41 /* jump, synopsis: key=r[P3@P4] */+#define OP_IdxGT 42 /* jump, synopsis: key=r[P3@P4] */#define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */#define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */-#define OP_IdxGE 45 /* jump, synopsis: key=r[P3@P4] */-#define OP_RowSetRead 46 /* jump, synopsis: r[P3]=rowset(P1) */-#define OP_RowSetTest 47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */-#define OP_Program 48 /* jump0 */-#define OP_FkIfZero 49 /* jump, synopsis: if fkctr[P1]==0 goto P2 */-#define OP_IfPos 50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */+#define OP_IdxLT 45 /* jump, synopsis: key=r[P3@P4] */+#define OP_IdxGE 46 /* jump, synopsis: key=r[P3@P4] */+#define OP_RowSetRead 47 /* jump, synopsis: r[P3]=rowset(P1) */+#define OP_RowSetTest 48 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */+#define OP_Program 49 /* jump0 */+#define OP_FkIfZero 50 /* jump, synopsis: if fkctr[P1]==0 goto P2 */#define OP_IsNull 51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */#define OP_NotNull 52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */#define OP_Ne 53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */@@ -17014,49 +17326,49 @@ typedef struct VdbeOpList VdbeOpList;#define OP_Lt 57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */#define OP_Ge 58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */#define OP_ElseEq 59 /* jump, same as TK_ESCAPE */-#define OP_IfNotZero 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */-#define OP_DecrJumpZero 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */-#define OP_IncrVacuum 62 /* jump */-#define OP_VNext 63 /* jump */-#define OP_Filter 64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */-#define OP_PureFunc 65 /* synopsis: r[P3]=func(r[P2@NP]) */-#define OP_Function 66 /* synopsis: r[P3]=func(r[P2@NP]) */-#define OP_Return 67-#define OP_EndCoroutine 68-#define OP_HaltIfNull 69 /* synopsis: if r[P3]=null halt */-#define OP_Halt 70-#define OP_Integer 71 /* synopsis: r[P2]=P1 */-#define OP_Int64 72 /* synopsis: r[P2]=P4 */-#define OP_String 73 /* synopsis: r[P2]='P4' (len=P1) */-#define OP_BeginSubrtn 74 /* synopsis: r[P2]=NULL */-#define OP_Null 75 /* synopsis: r[P2..P3]=NULL */-#define OP_SoftNull 76 /* synopsis: r[P1]=NULL */-#define OP_Blob 77 /* synopsis: r[P2]=P4 (len=P1) */-#define OP_Variable 78 /* synopsis: r[P2]=parameter(P1) */-#define OP_Move 79 /* synopsis: r[P2@P3]=r[P1@P3] */-#define OP_Copy 80 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */-#define OP_SCopy 81 /* synopsis: r[P2]=r[P1] */-#define OP_IntCopy 82 /* synopsis: r[P2]=r[P1] */-#define OP_FkCheck 83-#define OP_ResultRow 84 /* synopsis: output=r[P1@P2] */-#define OP_CollSeq 85-#define OP_AddImm 86 /* synopsis: r[P1]=r[P1]+P2 */-#define OP_RealAffinity 87-#define OP_Cast 88 /* synopsis: affinity(r[P1]) */-#define OP_Permutation 89-#define OP_Compare 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */-#define OP_IsTrue 91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */-#define OP_ZeroOrNull 92 /* synopsis: r[P2] = 0 OR NULL */-#define OP_Offset 93 /* synopsis: r[P3] = sqlite_offset(P1) */-#define OP_Column 94 /* synopsis: r[P3]=PX cursor P1 column P2 */-#define OP_TypeCheck 95 /* synopsis: typecheck(r[P1@P2]) */-#define OP_Affinity 96 /* synopsis: affinity(r[P1@P2]) */-#define OP_MakeRecord 97 /* synopsis: r[P3]=mkrec(r[P1@P2]) */-#define OP_Count 98 /* synopsis: r[P2]=count() */-#define OP_ReadCookie 99-#define OP_SetCookie 100-#define OP_ReopenIdx 101 /* synopsis: root=P2 iDb=P3 */-#define OP_OpenRead 102 /* synopsis: root=P2 iDb=P3 */+#define OP_IfPos 60 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */+#define OP_IfNotZero 61 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */+#define OP_DecrJumpZero 62 /* jump, synopsis: if (--r[P1])==0 goto P2 */+#define OP_IncrVacuum 63 /* jump */+#define OP_VNext 64 /* jump */+#define OP_Filter 65 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */+#define OP_PureFunc 66 /* synopsis: r[P3]=func(r[P2@NP]) */+#define OP_Function 67 /* synopsis: r[P3]=func(r[P2@NP]) */+#define OP_Return 68+#define OP_EndCoroutine 69+#define OP_HaltIfNull 70 /* synopsis: if r[P3]=null halt */+#define OP_Halt 71+#define OP_Integer 72 /* synopsis: r[P2]=P1 */+#define OP_Int64 73 /* synopsis: r[P2]=P4 */+#define OP_String 74 /* synopsis: r[P2]='P4' (len=P1) */+#define OP_BeginSubrtn 75 /* synopsis: r[P2]=NULL */+#define OP_Null 76 /* synopsis: r[P2..P3]=NULL */+#define OP_SoftNull 77 /* synopsis: r[P1]=NULL */+#define OP_Blob 78 /* synopsis: r[P2]=P4 (len=P1) */+#define OP_Variable 79 /* synopsis: r[P2]=parameter(P1) */+#define OP_Move 80 /* synopsis: r[P2@P3]=r[P1@P3] */+#define OP_Copy 81 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */+#define OP_SCopy 82 /* synopsis: r[P2]=r[P1] */+#define OP_IntCopy 83 /* synopsis: r[P2]=r[P1] */+#define OP_FkCheck 84+#define OP_ResultRow 85 /* synopsis: output=r[P1@P2] */+#define OP_CollSeq 86+#define OP_AddImm 87 /* synopsis: r[P1]=r[P1]+P2 */+#define OP_RealAffinity 88+#define OP_Cast 89 /* synopsis: affinity(r[P1]) */+#define OP_Permutation 90+#define OP_Compare 91 /* synopsis: r[P1@P3] <-> r[P2@P3] */+#define OP_IsTrue 92 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */+#define OP_ZeroOrNull 93 /* synopsis: r[P2] = 0 OR NULL */+#define OP_Offset 94 /* synopsis: r[P3] = sqlite_offset(P1) */+#define OP_Column 95 /* synopsis: r[P3]=PX cursor P1 column P2 */+#define OP_TypeCheck 96 /* synopsis: typecheck(r[P1@P2]) */+#define OP_Affinity 97 /* synopsis: affinity(r[P1@P2]) */+#define OP_MakeRecord 98 /* synopsis: r[P3]=mkrec(r[P1@P2]) */+#define OP_Count 99 /* synopsis: r[P2]=count() */+#define OP_ReadCookie 100+#define OP_SetCookie 101+#define OP_ReopenIdx 102 /* synopsis: root=P2 iDb=P3 */#define OP_BitAnd 103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */#define OP_BitOr 104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */#define OP_ShiftLeft 105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */@@ -17067,83 +17379,84 @@ typedef struct VdbeOpList VdbeOpList;#define OP_Divide 110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */#define OP_Remainder 111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */#define OP_Concat 112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */-#define OP_OpenWrite 113 /* synopsis: root=P2 iDb=P3 */-#define OP_OpenDup 114+#define OP_OpenRead 113 /* synopsis: root=P2 iDb=P3 */+#define OP_OpenWrite 114 /* synopsis: root=P2 iDb=P3 */#define OP_BitNot 115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */-#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2 */-#define OP_OpenEphemeral 117 /* synopsis: nColumn=P2 */+#define OP_OpenDup 116+#define OP_OpenAutoindex 117 /* synopsis: nColumn=P2 */#define OP_String8 118 /* same as TK_STRING, synopsis: r[P2]='P4' */-#define OP_SorterOpen 119-#define OP_SequenceTest 120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */-#define OP_OpenPseudo 121 /* synopsis: P3 columns in r[P2] */-#define OP_Close 122-#define OP_ColumnsUsed 123-#define OP_SeekScan 124 /* synopsis: Scan-ahead up to P1 rows */-#define OP_SeekHit 125 /* synopsis: set P2<=seekHit<=P3 */-#define OP_Sequence 126 /* synopsis: r[P2]=cursor[P1].ctr++ */-#define OP_NewRowid 127 /* synopsis: r[P2]=rowid */-#define OP_Insert 128 /* synopsis: intkey=r[P3] data=r[P2] */-#define OP_RowCell 129-#define OP_Delete 130-#define OP_ResetCount 131-#define OP_SorterCompare 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */-#define OP_SorterData 133 /* synopsis: r[P2]=data */-#define OP_RowData 134 /* synopsis: r[P2]=data */-#define OP_Rowid 135 /* synopsis: r[P2]=PX rowid of P1 */-#define OP_NullRow 136-#define OP_SeekEnd 137-#define OP_IdxInsert 138 /* synopsis: key=r[P2] */-#define OP_SorterInsert 139 /* synopsis: key=r[P2] */-#define OP_IdxDelete 140 /* synopsis: key=r[P2@P3] */-#define OP_DeferredSeek 141 /* synopsis: Move P3 to P1.rowid if needed */-#define OP_IdxRowid 142 /* synopsis: r[P2]=rowid */-#define OP_FinishSeek 143-#define OP_Destroy 144-#define OP_Clear 145-#define OP_ResetSorter 146-#define OP_CreateBtree 147 /* synopsis: r[P2]=root iDb=P1 flags=P3 */-#define OP_SqlExec 148-#define OP_ParseSchema 149-#define OP_LoadAnalysis 150-#define OP_DropTable 151-#define OP_DropIndex 152-#define OP_DropTrigger 153+#define OP_OpenEphemeral 119 /* synopsis: nColumn=P2 */+#define OP_SorterOpen 120+#define OP_SequenceTest 121 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */+#define OP_OpenPseudo 122 /* synopsis: P3 columns in r[P2] */+#define OP_Close 123+#define OP_ColumnsUsed 124+#define OP_SeekScan 125 /* synopsis: Scan-ahead up to P1 rows */+#define OP_SeekHit 126 /* synopsis: set P2<=seekHit<=P3 */+#define OP_Sequence 127 /* synopsis: r[P2]=cursor[P1].ctr++ */+#define OP_NewRowid 128 /* synopsis: r[P2]=rowid */+#define OP_Insert 129 /* synopsis: intkey=r[P3] data=r[P2] */+#define OP_RowCell 130+#define OP_Delete 131+#define OP_ResetCount 132+#define OP_SorterCompare 133 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */+#define OP_SorterData 134 /* synopsis: r[P2]=data */+#define OP_RowData 135 /* synopsis: r[P2]=data */+#define OP_Rowid 136 /* synopsis: r[P2]=PX rowid of P1 */+#define OP_NullRow 137+#define OP_SeekEnd 138+#define OP_IdxInsert 139 /* synopsis: key=r[P2] */+#define OP_SorterInsert 140 /* synopsis: key=r[P2] */+#define OP_IdxDelete 141 /* synopsis: key=r[P2@P3] */+#define OP_DeferredSeek 142 /* synopsis: Move P3 to P1.rowid if needed */+#define OP_IdxRowid 143 /* synopsis: r[P2]=rowid */+#define OP_FinishSeek 144+#define OP_Destroy 145+#define OP_Clear 146+#define OP_ResetSorter 147+#define OP_CreateBtree 148 /* synopsis: r[P2]=root iDb=P1 flags=P3 */+#define OP_SqlExec 149+#define OP_ParseSchema 150+#define OP_LoadAnalysis 151+#define OP_DropTable 152+#define OP_DropIndex 153#define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=P4 */-#define OP_IntegrityCk 155-#define OP_RowSetAdd 156 /* synopsis: rowset(P1)=r[P2] */-#define OP_Param 157-#define OP_FkCounter 158 /* synopsis: fkctr[P1]+=P2 */-#define OP_MemMax 159 /* synopsis: r[P1]=max(r[P1],r[P2]) */-#define OP_OffsetLimit 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */-#define OP_AggInverse 161 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */-#define OP_AggStep 162 /* synopsis: accum=r[P3] step(r[P2@P5]) */-#define OP_AggStep1 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */-#define OP_AggValue 164 /* synopsis: r[P3]=value N=P2 */-#define OP_AggFinal 165 /* synopsis: accum=r[P1] N=P2 */-#define OP_Expire 166-#define OP_CursorLock 167-#define OP_CursorUnlock 168-#define OP_TableLock 169 /* synopsis: iDb=P1 root=P2 write=P3 */-#define OP_VBegin 170-#define OP_VCreate 171-#define OP_VDestroy 172-#define OP_VOpen 173-#define OP_VCheck 174-#define OP_VInitIn 175 /* synopsis: r[P2]=ValueList(P1,P3) */-#define OP_VColumn 176 /* synopsis: r[P3]=vcolumn(P2) */-#define OP_VRename 177-#define OP_Pagecount 178-#define OP_MaxPgcnt 179-#define OP_ClrSubtype 180 /* synopsis: r[P1].subtype = 0 */-#define OP_GetSubtype 181 /* synopsis: r[P2] = r[P1].subtype */-#define OP_SetSubtype 182 /* synopsis: r[P2].subtype = r[P1] */-#define OP_FilterAdd 183 /* synopsis: filter(P1) += key(P3@P4) */-#define OP_Trace 184-#define OP_CursorHint 185-#define OP_ReleaseReg 186 /* synopsis: release r[P1@P2] mask P3 */-#define OP_Noop 187-#define OP_Explain 188-#define OP_Abortable 189+#define OP_DropTrigger 155+#define OP_IntegrityCk 156+#define OP_RowSetAdd 157 /* synopsis: rowset(P1)=r[P2] */+#define OP_Param 158+#define OP_FkCounter 159 /* synopsis: fkctr[P1]+=P2 */+#define OP_MemMax 160 /* synopsis: r[P1]=max(r[P1],r[P2]) */+#define OP_OffsetLimit 161 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */+#define OP_AggInverse 162 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */+#define OP_AggStep 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */+#define OP_AggStep1 164 /* synopsis: accum=r[P3] step(r[P2@P5]) */+#define OP_AggValue 165 /* synopsis: r[P3]=value N=P2 */+#define OP_AggFinal 166 /* synopsis: accum=r[P1] N=P2 */+#define OP_Expire 167+#define OP_CursorLock 168+#define OP_CursorUnlock 169+#define OP_TableLock 170 /* synopsis: iDb=P1 root=P2 write=P3 */+#define OP_VBegin 171+#define OP_VCreate 172+#define OP_VDestroy 173+#define OP_VOpen 174+#define OP_VCheck 175+#define OP_VInitIn 176 /* synopsis: r[P2]=ValueList(P1,P3) */+#define OP_VColumn 177 /* synopsis: r[P3]=vcolumn(P2) */+#define OP_VRename 178+#define OP_Pagecount 179+#define OP_MaxPgcnt 180+#define OP_ClrSubtype 181 /* synopsis: r[P1].subtype = 0 */+#define OP_GetSubtype 182 /* synopsis: r[P2] = r[P1].subtype */+#define OP_SetSubtype 183 /* synopsis: r[P2].subtype = r[P1] */+#define OP_FilterAdd 184 /* synopsis: filter(P1) += key(P3@P4) */+#define OP_Trace 185+#define OP_CursorHint 186+#define OP_ReleaseReg 187 /* synopsis: release r[P1@P2] mask P3 */+#define OP_Noop 188+#define OP_Explain 189+#define OP_Abortable 190/* Properties such as "out2" or "jump" that are specified in** comments following the "case" for each opcode in the vdbe.c@@ -17162,26 +17475,26 @@ typedef struct VdbeOpList VdbeOpList;/* 8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\/* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\/* 24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\-/* 32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\-/* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\-/* 48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\-/* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\-/* 64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\-/* 72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\-/* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\-/* 88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\-/* 96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\+/* 32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x01, 0x41,\+/* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x41, 0x23,\+/* 48 */ 0x0b, 0x81, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\+/* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x03, 0x01,\+/* 64 */ 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00,\+/* 72 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\+/* 80 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02,\+/* 88 */ 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40,\+/* 96 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26,\/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\-/* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\-/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\-/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\-/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\-/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\-/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\-/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\-/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\-/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\-/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}+/* 112 */ 0x26, 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40,\+/* 120 */ 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10,\+/* 128 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\+/* 136 */ 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50,\+/* 144 */ 0x40, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\+/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00,\+/* 160 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\+/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10,\+/* 176 */ 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12,\+/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}/* The resolve3P2Values() routine is able to run faster if it knows** the value of the largest JUMP opcode. The smaller the maximum@@ -17189,7 +17502,7 @@ typedef struct VdbeOpList VdbeOpList;** generated this include file strives to group all JUMP opcodes** together near the beginning of the list.*/-#define SQLITE_MX_JUMP_OPCODE 64 /* Maximum JUMP opcode */+#define SQLITE_MX_JUMP_OPCODE 65 /* Maximum JUMP opcode *//************** End of opcodes.h *********************************************//************** Continuing where we left off in vdbe.h ***********************/@@ -17312,8 +17625,11 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);#endifSQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);+#ifdef SQLITE_ENABLE_PERCENTILE+SQLITE_PRIVATE const char *sqlite3VdbeFuncName(const sqlite3_context*);+#endif-SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);+SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(int,const void*,UnpackedRecord*);SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);@@ -17326,13 +17642,15 @@ SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);SQLITE_PRIVATE void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val);+#ifndef SQLITE_OMIT_DATETIME_FUNCSSQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);+#endif#ifdef SQLITE_ENABLE_BYTECODE_VTABSQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);#endif-/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on-** each VDBE opcode.+/* Use SQLITE_ENABLE_EXPLAIN_COMMENTS to enable generation of extra+** comments on each VDBE opcode.**** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op** comments in VDBE programs that show key decision points in the code@@ -17982,7 +18300,7 @@ struct sqlite3 {u8 iDb; /* Which db file is being initialized */u8 busy; /* TRUE if currently initializing */unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */- unsigned imposterTable : 1; /* Building an imposter table */+ unsigned imposterTable : 2; /* Building an imposter table */unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */const char **azInit; /* "type", "name", and "tbl_name" columns */} init;@@ -18055,12 +18373,17 @@ struct sqlite3 {Savepoint *pSavepoint; /* List of active savepoints */int nAnalysisLimit; /* Number of index rows to ANALYZE */int busyTimeout; /* Busy handler timeout, in msec */+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ int setlkTimeout; /* Blocking lock timeout, in msec. -1 -> inf. */+ int setlkFlags; /* Flags passed to setlk_timeout() */+#endifint nSavepoint; /* Number of non-transaction savepoints */int nStatement; /* Number of nested statement-transactions */i64 nDeferredCons; /* Net deferred constraints this transaction. */i64 nDeferredImmCons; /* Net deferred immediate constraints */int *pnBytesFreed; /* If not NULL, increment this in DbFree() */DbClientData *pDbData; /* sqlite3_set_clientdata() content */+ u64 nSpill; /* TEMP content spilled to disk */#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY/* The following variables are all protected by the STATIC_MAIN** mutex, not by sqlite3.mutex. They are used by code in notify.c.@@ -18204,6 +18527,7 @@ struct sqlite3 {#define SQLITE_OnePass 0x08000000 /* Single-pass DELETE and UPDATE */#define SQLITE_OrderBySubq 0x10000000 /* ORDER BY in subquery helps outer */#define SQLITE_StarQuery 0x20000000 /* Heurists for star queries */+#define SQLITE_ExistsToJoin 0x40000000 /* The EXISTS-to-JOIN optimization */#define SQLITE_AllOpts 0xffffffff /* All optimizations *//*@@ -18442,7 +18766,7 @@ struct FuncDestructor {#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \{nArg, SQLITE_FUNC_BUILTIN|\SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \- pArg, 0, xFunc, 0, 0, 0, #zName, }+ pArg, 0, xFunc, 0, 0, 0, #zName, {0} }#define LIKEFUNC(zName, nArg, arg, flags) \{nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \(void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }@@ -18609,6 +18933,7 @@ struct CollSeq {#define SQLITE_AFF_INTEGER 0x44 /* 'D' */#define SQLITE_AFF_REAL 0x45 /* 'E' */#define SQLITE_AFF_FLEXNUM 0x46 /* 'F' */+#define SQLITE_AFF_DEFER 0x58 /* 'X' - defer computation until later */#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)@@ -18733,6 +19058,7 @@ struct Table {} u;Trigger *pTrigger; /* List of triggers on this object */Schema *pSchema; /* Schema that contains this table */+ u8 aHx[16]; /* Column aHt[K%sizeof(aHt)] might have hash K */};/*@@ -18768,6 +19094,7 @@ struct Table {#define TF_Ephemeral 0x00004000 /* An ephemeral table */#define TF_Eponymous 0x00008000 /* An eponymous virtual table */#define TF_Strict 0x00010000 /* STRICT mode */+#define TF_Imposter 0x00020000 /* An imposter table *//*** Allowed values for Table.eTabType@@ -18866,9 +19193,13 @@ struct FKey {struct sColMap { /* Mapping of columns in pFrom to columns in zTo */int iFrom; /* Index of column in pFrom */char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */- } aCol[1]; /* One entry for each of nCol columns */+ } aCol[FLEXARRAY]; /* One entry for each of nCol columns */};+/* The size (in bytes) of an FKey object holding N columns. The answer+** does NOT include space to hold the zTo name. */+#define SZ_FKEY(N) (offsetof(FKey,aCol)+(N)*sizeof(struct sColMap))+/*** SQLite supports many different ways to resolve a constraint** error. ROLLBACK processing means that a constraint violation@@ -18919,9 +19250,15 @@ struct FKey {** argument to sqlite3VdbeKeyCompare and is used to control the** comparison of the two index keys.**-** Note that aSortOrder[] and aColl[] have nField+1 slots. There-** are nField slots for the columns of an index then one extra slot-** for the rowid at the end.+** The aSortOrder[] and aColl[] arrays have nAllField slots each. There+** are nKeyField slots for the columns of an index then extra slots+** for the rowid or key at the end. The aSortOrder array is located after+** the aColl[] array.+**+** If SQLITE_ENABLE_PREUPDATE_HOOK is defined, then aSortFlags might be NULL+** to indicate that this object is for use by a preupdate hook. When aSortFlags+** is NULL, then nAllField is uninitialized and no space is allocated for+** aColl[], so those fields may not be used.*/struct KeyInfo {u32 nRef; /* Number of references to this KeyInfo object */@@ -18930,9 +19267,21 @@ struct KeyInfo {u16 nAllField; /* Total columns, including key plus others */sqlite3 *db; /* The database connection */u8 *aSortFlags; /* Sort order for each column. */- CollSeq *aColl[1]; /* Collating sequence for each term of the key */+ CollSeq *aColl[FLEXARRAY]; /* Collating sequence for each term of the key */};+/* The size (in bytes) of a KeyInfo object with up to N fields. This includes+** the main body of the KeyInfo object and the aColl[] array of N elements,+** but does not count the memory used to hold aSortFlags[]. */+#define SZ_KEYINFO(N) (offsetof(KeyInfo,aColl) + (N)*sizeof(CollSeq*))++/* The size of a bare KeyInfo with no aColl[] entries */+#if FLEXARRAY+1 > 1+# define SZ_KEYINFO_0 offsetof(KeyInfo,aColl)+#else+# define SZ_KEYINFO_0 sizeof(KeyInfo)+#endif+/*** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.*/@@ -18951,9 +19300,8 @@ struct KeyInfo {**** An instance of this object serves as a "key" for doing a search on** an index b+tree. The goal of the search is to find the entry that-** is closed to the key described by this object. This object might hold-** just a prefix of the key. The number of fields is given by-** pKeyInfo->nField.+** is closest to the key described by this object. This object might hold+** just a prefix of the key. The number of fields is given by nField.**** The r1 and r2 fields are the values to return if this key is less than** or greater than a key in the btree, respectively. These are normally@@ -18963,7 +19311,7 @@ struct KeyInfo {** The key comparison functions actually return default_rc when they find** an equals comparison. default_rc can be -1, 0, or +1. If there are** multiple entries in the b-tree with the same key (when only looking-** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to+** at the first nField elements) then default_rc can be set to -1 to** cause the search to find the last match, or +1 to cause the search to** find the first match.**@@ -18975,8 +19323,8 @@ struct KeyInfo {** b-tree.*/struct UnpackedRecord {- KeyInfo *pKeyInfo; /* Collation and sort-order information */- Mem *aMem; /* Values */+ KeyInfo *pKeyInfo; /* Comparison info for the index that is unpacked */+ Mem *aMem; /* Values for columns of the index */union {char *z; /* Cache of aMem[0].z for vdbeRecordCompareString() */i64 i; /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */@@ -19052,7 +19400,7 @@ struct Index {Pgno tnum; /* DB Page containing root of this index */LogEst szIdxRow; /* Estimated average row size in bytes */u16 nKeyCol; /* Number of columns forming the key */- u16 nColumn; /* Number of columns stored in the index */+ u16 nColumn; /* Nr columns in btree. Can be 2*Table.nCol */u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */unsigned bUnordered:1; /* Use this index for == or IN queries only */@@ -19061,7 +19409,6 @@ struct Index {unsigned isCovering:1; /* True if this is a covering index */unsigned noSkipScan:1; /* Do not try to use skip-scan if true */unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */- unsigned bLowQual:1; /* sqlite_stat1 says this is a low-quality index */unsigned bNoQuery:1; /* Do not use this index to optimize queries */unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */@@ -19151,7 +19498,7 @@ struct AggInfo {** from source tables rather than from accumulators */u8 useSortingIdx; /* In direct mode, reference the sorting index rather** than the source table */- u16 nSortingColumn; /* Number of columns in the sorting index */+ u32 nSortingColumn; /* Number of columns in the sorting index */int sortingIdx; /* Cursor number of the sorting index */int sortingIdxPTab; /* Cursor number of pseudo-table */int iFirstReg; /* First register in range for aCol[] and aFunc[] */@@ -19160,8 +19507,8 @@ struct AggInfo {Table *pTab; /* Source table */Expr *pCExpr; /* The original expression */int iTable; /* Cursor number of the source table */- i16 iColumn; /* Column number within the source table */- i16 iSorterColumn; /* Column number in the sorting index */+ int iColumn; /* Column number within the source table */+ int iSorterColumn; /* Column number in the sorting index */} *aCol;int nColumn; /* Number of used entries in aCol[] */int nAccumulator; /* Number of columns that show through to the output.@@ -19336,6 +19683,7 @@ struct Expr {Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL** for a column of an index on an expression */Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */+ int nReg; /* TK_NULLS: Number of registers to NULL out */struct { /* TK_IN, TK_SELECT, and TK_EXISTS */int iAddr; /* Subroutine entry address */int regReturn; /* Register used to hold return address */@@ -19390,10 +19738,10 @@ struct Expr {/* Macros can be used to test, set, or clear bits in the** Expr.flags field.*/-#define ExprHasProperty(E,P) (((E)->flags&(P))!=0)-#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))-#define ExprSetProperty(E,P) (E)->flags|=(P)-#define ExprClearProperty(E,P) (E)->flags&=~(P)+#define ExprHasProperty(E,P) (((E)->flags&(u32)(P))!=0)+#define ExprHasAllProperty(E,P) (((E)->flags&(u32)(P))==(u32)(P))+#define ExprSetProperty(E,P) (E)->flags|=(u32)(P)+#define ExprClearProperty(E,P) (E)->flags&=~(u32)(P)#define ExprAlwaysTrue(E) (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)#define ExprAlwaysFalse(E) (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)#define ExprIsFullSize(E) (((E)->flags&(EP_Reduced|EP_TokenOnly))==0)@@ -19505,9 +19853,14 @@ struct ExprList {int iConstExprReg; /* Register in which Expr value is cached. Used only** by Parse.pConstExpr */} u;- } a[1]; /* One slot for each expression in the list */+ } a[FLEXARRAY]; /* One slot for each expression in the list */};+/* The size (in bytes) of an ExprList object that is big enough to hold+** as many as N expressions. */+#define SZ_EXPRLIST(N) \+ (offsetof(ExprList,a) + (N)*sizeof(struct ExprList_item))+/*** Allowed values for Expr.a.eEName*/@@ -19535,9 +19888,12 @@ struct IdList {int nId; /* Number of identifiers on the list */struct IdList_item {char *zName; /* Name of the identifier */- } a[1];+ } a[FLEXARRAY];};+/* The size (in bytes) of an IdList object that can hold up to N IDs. */+#define SZ_IDLIST(N) (offsetof(IdList,a)+(N)*sizeof(struct IdList_item))+/*** Allowed values for IdList.eType, which determines which value of the a.u4** is valid.@@ -19617,6 +19973,7 @@ struct SrcItem {unsigned rowidUsed :1; /* The ROWID of this table is referenced */unsigned fixedSchema :1; /* Uses u4.pSchema, not u4.zDatabase */unsigned hadSchema :1; /* Had u4.zDatabase before u4.pSchema */+ unsigned fromExists :1; /* Comes from WHERE EXISTS(...) */} fg;int iCursor; /* The VDBE cursor number used to access this table */Bitmask colUsed; /* Bit N set if column N used. Details above for N>62 */@@ -19657,11 +20014,19 @@ struct OnOrUsing {***/struct SrcList {- int nSrc; /* Number of tables or subqueries in the FROM clause */- u32 nAlloc; /* Number of entries allocated in a[] below */- SrcItem a[1]; /* One entry for each identifier on the list */+ int nSrc; /* Number of tables or subqueries in the FROM clause */+ u32 nAlloc; /* Number of entries allocated in a[] below */+ SrcItem a[FLEXARRAY]; /* One entry for each identifier on the list */};+/* Size (in bytes) of a SrcList object that can hold as many as N+** SrcItem objects. */+#define SZ_SRCLIST(N) (offsetof(SrcList,a)+(N)*sizeof(SrcItem))++/* Size (in bytes( of a SrcList object that holds 1 SrcItem. This is a+** special case of SZ_SRCITEM(1) that comes up often. */+#define SZ_SRCLIST_1 (offsetof(SrcList,a)+sizeof(SrcItem))+/*** Permitted values of the SrcList.a.jointype field*/@@ -19896,6 +20261,7 @@ struct Select {#define SF_OrderByReqd 0x8000000 /* The ORDER BY clause may not be omitted */#define SF_UpdateFrom 0x10000000 /* Query originates with UPDATE FROM */#define SF_Correlated 0x20000000 /* True if references the outer context */+#define SF_OnToWhere 0x40000000 /* One or more ON clauses moved to WHERE *//* True if SrcItem X is a subquery that has SF_NestedFrom */#define IsNestedFrom(X) \@@ -20130,25 +20496,33 @@ struct Parse {char *zErrMsg; /* An error message */Vdbe *pVdbe; /* An engine for executing database bytecode */int rc; /* Return code from execution */- u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */- u8 checkSchema; /* Causes schema cookie check after an error */+ LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */u8 nested; /* Number of nested calls to the parser/code generator */u8 nTempReg; /* Number of temporary registers in aTempReg[] */u8 isMultiWrite; /* True if statement may modify/insert multiple rows */u8 mayAbort; /* True if statement may throw an ABORT exception */u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */- u8 okConstFactor; /* OK to factor out constants */u8 disableLookaside; /* Number of times lookaside has been disabled */u8 prepFlags; /* SQLITE_PREPARE_* flags */u8 withinRJSubrtn; /* Nesting level for RIGHT JOIN body subroutines */- u8 bHasWith; /* True if statement contains WITH */+ u8 bHasExists; /* Has a correlated "EXISTS (SELECT ....)" expression */u8 mSubrtnSig; /* mini Bloom filter on available SubrtnSig.selId */+ u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */+ u8 bReturning; /* Coding a RETURNING trigger */+ u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */+ u8 disableTriggers; /* True to disable triggers */#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */#endif#ifdef SQLITE_DEBUGu8 ifNotExists; /* Might be true if IF NOT EXISTS. Assert()s only */+ u8 isCreate; /* CREATE TABLE, INDEX, or VIEW (but not TRIGGER)+ ** and ALTER TABLE ADD COLUMN. */#endif+ bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */+ bft bHasWith :1; /* True if statement contains WITH */+ bft okConstFactor :1; /* OK to factor out constants */+ bft checkSchema :1; /* Causes schema cookie check after an error */int nRangeReg; /* Size of the temporary register block */int iRangeReg; /* First register in temporary register block */int nErr; /* Number of errors seen */@@ -20163,12 +20537,9 @@ struct Parse {ExprList *pConstExpr;/* Constant expressions */IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */- Token constraintName;/* Name of the constraint currently being parsed */yDbMask writeMask; /* Start a write transaction on these databases */yDbMask cookieMask; /* Bitmask of schema verified databases */- int regRowid; /* Register holding rowid of CREATE TABLE entry */- int regRoot; /* Register holding root page number for new objects */- int nMaxArg; /* Max args passed to user function by sub-program */+ int nMaxArg; /* Max args to xUpdate and xFilter vtab methods */int nSelect; /* Number of SELECT stmts. Counter for Select.selId */#ifndef SQLITE_OMIT_PROGRESS_CALLBACKu32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */@@ -20182,17 +20553,6 @@ struct Parse {Table *pTriggerTab; /* Table triggers are being coded for */TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */- union {- int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */- Returning *pReturning; /* The RETURNING clause */- } u1;- u32 oldmask; /* Mask of old.* columns referenced */- u32 newmask; /* Mask of new.* columns referenced */- LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */- u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */- u8 bReturning; /* Coding a RETURNING trigger */- u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */- u8 disableTriggers; /* True to disable triggers *//**************************************************************************** Fields above must be initialized to zero. The fields that follow,@@ -20204,6 +20564,19 @@ struct Parse {int aTempReg[8]; /* Holding area for temporary registers */Parse *pOuterParse; /* Outer Parse object when nested */Token sNameToken; /* Token with unqualified schema object name */+ u32 oldmask; /* Mask of old.* columns referenced */+ u32 newmask; /* Mask of new.* columns referenced */+ union {+ struct { /* These fields available when isCreate is true */+ int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */+ int regRowid; /* Register holding rowid of CREATE TABLE entry */+ int regRoot; /* Register holding root page for new objects */+ Token constraintName; /* Name of the constraint currently being parsed */+ } cr;+ struct { /* These fields available to all other statements */+ Returning *pReturning; /* The RETURNING clause */+ } d;+ } u1;/************************************************************************** Above is constant between recursions. Below is reset before and after@@ -20642,6 +21015,7 @@ struct Walker {SrcItem *pSrcItem; /* A single FROM clause item */DbFixer *pFix; /* See sqlite3FixSelect() */Mem *aMem; /* See sqlite3BtreeCursorHint() */+ struct CheckOnCtx *pCheckOnCtx; /* See selectCheckOnClauses() */} u;};@@ -20719,9 +21093,13 @@ struct With {int nCte; /* Number of CTEs in the WITH clause */int bView; /* Belongs to the outermost Select of a view */With *pOuter; /* Containing WITH clause, or NULL */- Cte a[1]; /* For each CTE in the WITH clause.... */+ Cte a[FLEXARRAY]; /* For each CTE in the WITH clause.... */};+/* The size (in bytes) of a With object that can hold as many+** as N different CTEs. */+#define SZ_WITH(N) (offsetof(With,a) + (N)*sizeof(Cte))+/*** The Cte object is not guaranteed to persist for the entire duration** of code generation. (The query flattener or other parser tree@@ -20750,9 +21128,13 @@ struct DbClientData {DbClientData *pNext; /* Next in a linked list */void *pData; /* The data */void (*xDestructor)(void*); /* Destructor. Might be NULL */- char zName[1]; /* Name of this client data. MUST BE LAST */+ char zName[FLEXARRAY]; /* Name of this client data. MUST BE LAST */};+/* The size (in bytes) of a DbClientData object that can has a name+** that is N bytes long, including the zero-terminator. */+#define SZ_DBCLIENTDATA(N) (offsetof(DbClientData,zName)+(N))+#ifdef SQLITE_DEBUG/*** An instance of the TreeView object is used for printing the content of@@ -21121,6 +21503,7 @@ SQLITE_PRIVATE void sqlite3ShowTriggerList(const Trigger*);SQLITE_PRIVATE void sqlite3ShowWindow(const Window*);SQLITE_PRIVATE void sqlite3ShowWinFunc(const Window*);#endif+SQLITE_PRIVATE void sqlite3ShowBitvec(Bitvec*);#endifSQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);@@ -21195,7 +21578,7 @@ SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char);SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);-SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);+SQLITE_PRIVATE int sqlite3TableColumnToIndex(Index*, int);#ifdef SQLITE_OMIT_GENERATED_COLUMNS# define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */# define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */@@ -21293,7 +21676,7 @@ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*);SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);-SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);+SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**);SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,Expr*, int, int, u8);SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);@@ -21302,6 +21685,7 @@ SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprListExpr*,ExprList*,u32,Expr*);SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3*,void*);+SQLITE_PRIVATE void sqlite3SelectCheckOnClauses(Parse *pParse, Select *pSelect);SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*);SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);@@ -21340,6 +21724,7 @@ SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int)SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);+SQLITE_PRIVATE void sqlite3ExprNullRegisterRange(Parse*, int, int);SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);@@ -21429,19 +21814,24 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int);SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);-SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*);+SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*,int);+SQLITE_PRIVATE int sqlite3AppendOneUtf8Character(char*, u32);SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void);SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)-SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3*);+SQLITE_PRIVATE Module *sqlite3JsonVtabRegister(sqlite3*,const char*);#endifSQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p);+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY)+SQLITE_PRIVATE Module *sqlite3CarrayRegister(sqlite3*);+#endif+#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);#endif@@ -21662,7 +22052,7 @@ SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);SQLITE_PRIVATE void sqlite3AlterFunctions(void);SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);-SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);+SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *);SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);@@ -22294,6 +22684,9 @@ static const char * const sqlite3azCompileOpt[] = {#ifdef SQLITE_BUG_COMPATIBLE_20160819"BUG_COMPATIBLE_20160819",#endif+#ifdef SQLITE_BUG_COMPATIBLE_20250510+ "BUG_COMPATIBLE_20250510",+#endif#ifdef SQLITE_CASE_SENSITIVE_LIKE"CASE_SENSITIVE_LIKE",#endif@@ -22425,6 +22818,9 @@ static const char * const sqlite3azCompileOpt[] = {#ifdef SQLITE_ENABLE_BYTECODE_VTAB"ENABLE_BYTECODE_VTAB",#endif+#ifdef SQLITE_ENABLE_CARRAY+ "ENABLE_CARRAY",+#endif#ifdef SQLITE_ENABLE_CEROD"ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),#endif@@ -22515,6 +22911,9 @@ static const char * const sqlite3azCompileOpt[] = {#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK"ENABLE_OVERSIZE_CELL_CHECK",#endif+#ifdef SQLITE_ENABLE_PERCENTILE+ "ENABLE_PERCENTILE",+#endif#ifdef SQLITE_ENABLE_PREUPDATE_HOOK"ENABLE_PREUPDATE_HOOK",#endif@@ -22530,6 +22929,9 @@ static const char * const sqlite3azCompileOpt[] = {#ifdef SQLITE_ENABLE_SESSION"ENABLE_SESSION",#endif+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ "ENABLE_SETLK_TIMEOUT",+#endif#ifdef SQLITE_ENABLE_SNAPSHOT"ENABLE_SNAPSHOT",#endif@@ -22584,6 +22986,9 @@ static const char * const sqlite3azCompileOpt[] = {#ifdef SQLITE_EXTRA_INIT"EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),#endif+#ifdef SQLITE_EXTRA_INIT_MUTEXED+ "EXTRA_INIT_MUTEXED=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT_MUTEXED),+#endif#ifdef SQLITE_EXTRA_SHUTDOWN"EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),#endif@@ -23568,12 +23973,19 @@ struct VdbeCursor {#endifVdbeTxtBlbCache *pCache; /* Cache of large TEXT or BLOB values */- /* 2*nField extra array elements allocated for aType[], beyond the one- ** static element declared in the structure. nField total array slots for- ** aType[] and nField+1 array slots for aOffset[] */- u32 aType[1]; /* Type values record decode. MUST BE LAST */+ /* Space is allocated for aType to hold at least 2*nField+1 entries:+ ** nField slots for aType[] and nField+1 array slots for aOffset[] */+ u32 aType[FLEXARRAY]; /* Type values record decode. MUST BE LAST */};+/*+** The size (in bytes) of a VdbeCursor object that has an nField value of N+** or less. The value of SZ_VDBECURSOR(n) is guaranteed to be a multiple+** of 8.+*/+#define SZ_VDBECURSOR(N) \+ (ROUND8(offsetof(VdbeCursor,aType)) + ((N)+1)*sizeof(u64))+/* Return true if P is a null-only cursor*/#define IsNullCursor(P) \@@ -23716,7 +24128,7 @@ struct sqlite3_value {** MEM_Int, MEM_Real, and MEM_IntReal.**** * MEM_Blob|MEM_Zero A blob in Mem.z of length Mem.n plus-** MEM.u.i extra 0x00 bytes at the end.+** Mem.u.nZero extra 0x00 bytes at the end.**** * MEM_Int Integer stored in Mem.u.i.**@@ -23830,13 +24242,16 @@ struct sqlite3_context {u8 enc; /* Encoding to use for results */u8 skipFlag; /* Skip accumulator loading if true */u16 argc; /* Number of arguments */- sqlite3_value *argv[1]; /* Argument set */+ sqlite3_value *argv[FLEXARRAY]; /* Argument set */};-/* A bitfield type for use inside of structures. Always follow with :N where-** N is the number of bits.+/*+** The size (in bytes) of an sqlite3_context object that holds N+** argv[] arguments.*/-typedef unsigned bft; /* Bit Field Type */+#define SZ_CONTEXT(N) \+ (offsetof(sqlite3_context,argv)+(N)*sizeof(sqlite3_value*))+/* The ScanStatus object holds a single value for the** sqlite3_stmt_scanstatus() interface.@@ -23897,7 +24312,7 @@ struct Vdbe {i64 nStmtDefCons; /* Number of def. constraints when stmt started */i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */Mem *aMem; /* The memory locations */- Mem **apArg; /* Arguments to currently executing user function */+ Mem **apArg; /* Arguments xUpdate and xFilter vtab methods */VdbeCursor **apCsr; /* One element of this array for each open cursor */Mem *aVar; /* Values for the OP_Variable opcode. */@@ -23917,6 +24332,7 @@ struct Vdbe {#ifdef SQLITE_DEBUGint rcApp; /* errcode set by sqlite3_result_error_code() */u32 nWrite; /* Number of write operations that have occurred */+ int napArg; /* Size of the apArg[] array */#endifu16 nResColumn; /* Number of columns in one row of the result set */u16 nResAlloc; /* Column slots allocated to aColName[] */@@ -23969,7 +24385,7 @@ struct PreUpdate {VdbeCursor *pCsr; /* Cursor to read old values from */int op; /* One of SQLITE_INSERT, UPDATE, DELETE */u8 *aRecord; /* old.* database record */- KeyInfo keyinfo;+ KeyInfo *pKeyinfo; /* Key information */UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */int iNewReg; /* Register for new.* values */@@ -23981,6 +24397,9 @@ struct PreUpdate {Table *pTab; /* Schema object being updated */Index *pPk; /* PK index if pTab is WITHOUT ROWID */sqlite3_value **apDflt; /* Array of default values, if required */+ struct {+ u8 keyinfoSpace[SZ_KEYINFO_0]; /* Space to hold pKeyinfo[0] content */+ } uKey;};/*@@ -24144,9 +24563,11 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);#endif#ifndef SQLITE_OMIT_FOREIGN_KEY-SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);+SQLITE_PRIVATE int sqlite3VdbeCheckFkImmediate(Vdbe*);+SQLITE_PRIVATE int sqlite3VdbeCheckFkDeferred(Vdbe*);#else-# define sqlite3VdbeCheckFk(p,i) 0+# define sqlite3VdbeCheckFkImmediate(p) 0+# define sqlite3VdbeCheckFkDeferred(p) 0#endif#ifdef SQLITE_DEBUG@@ -24347,30 +24768,33 @@ SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){nInit += countLookasideSlots(db->lookaside.pSmallInit);nFree += countLookasideSlots(db->lookaside.pSmallFree);#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */- if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;- return db->lookaside.nSlot - (nInit+nFree);+ assert( db->lookaside.nSlot >= nInit+nFree );+ if( pHighwater ) *pHighwater = (int)(db->lookaside.nSlot - nInit);+ return (int)(db->lookaside.nSlot - (nInit+nFree));}/*** Query status information for a single database connection*/-SQLITE_API int sqlite3_db_status(- sqlite3 *db, /* The database connection whose status is desired */- int op, /* Status verb */- int *pCurrent, /* Write current value here */- int *pHighwater, /* Write high-water mark here */- int resetFlag /* Reset high-water mark if true */+SQLITE_API int sqlite3_db_status64(+ sqlite3 *db, /* The database connection whose status is desired */+ int op, /* Status verb */+ sqlite3_int64 *pCurrent, /* Write current value here */+ sqlite3_int64 *pHighwtr, /* Write high-water mark here */+ int resetFlag /* Reset high-water mark if true */){int rc = SQLITE_OK; /* Return code */#ifdef SQLITE_ENABLE_API_ARMOR- if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){+ if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwtr==0 ){return SQLITE_MISUSE_BKPT;}#endifsqlite3_mutex_enter(db->mutex);switch( op ){case SQLITE_DBSTATUS_LOOKASIDE_USED: {- *pCurrent = sqlite3LookasideUsed(db, pHighwater);+ int H = 0;+ *pCurrent = sqlite3LookasideUsed(db, &H);+ *pHighwtr = H;if( resetFlag ){LookasideSlot *p = db->lookaside.pFree;if( p ){@@ -24401,7 +24825,7 @@ SQLITE_API int sqlite3_db_status(assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );*pCurrent = 0;- *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];+ *pHighwtr = db->lookaside.anStat[op-SQLITE_DBSTATUS_LOOKASIDE_HIT];if( resetFlag ){db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;}@@ -24415,7 +24839,7 @@ SQLITE_API int sqlite3_db_status(*/case SQLITE_DBSTATUS_CACHE_USED_SHARED:case SQLITE_DBSTATUS_CACHE_USED: {- int totalUsed = 0;+ sqlite3_int64 totalUsed = 0;int i;sqlite3BtreeEnterAll(db);for(i=0; i<db->nDb; i++){@@ -24431,18 +24855,18 @@ SQLITE_API int sqlite3_db_status(}sqlite3BtreeLeaveAll(db);*pCurrent = totalUsed;- *pHighwater = 0;+ *pHighwtr = 0;break;}/*** *pCurrent gets an accurate estimate of the amount of memory used** to store the schema for all databases (main, temp, and any ATTACHed- ** databases. *pHighwater is set to zero.+ ** databases. *pHighwtr is set to zero.*/case SQLITE_DBSTATUS_SCHEMA_USED: {- int i; /* Used to iterate through schemas */- int nByte = 0; /* Used to accumulate return value */+ int i; /* Used to iterate through schemas */+ int nByte = 0; /* Used to accumulate return value */sqlite3BtreeEnterAll(db);db->pnBytesFreed = &nByte;@@ -24476,7 +24900,7 @@ SQLITE_API int sqlite3_db_status(db->lookaside.pEnd = db->lookaside.pTrueEnd;sqlite3BtreeLeaveAll(db);- *pHighwater = 0;+ *pHighwtr = 0;*pCurrent = nByte;break;}@@ -24484,7 +24908,7 @@ SQLITE_API int sqlite3_db_status(/*** *pCurrent gets an accurate estimate of the amount of memory used** to store all prepared statements.- ** *pHighwater is set to zero.+ ** *pHighwtr is set to zero.*/case SQLITE_DBSTATUS_STMT_USED: {struct Vdbe *pVdbe; /* Used to iterate through VMs */@@ -24499,7 +24923,7 @@ SQLITE_API int sqlite3_db_status(db->lookaside.pEnd = db->lookaside.pTrueEnd;db->pnBytesFreed = 0;- *pHighwater = 0; /* IMP: R-64479-57858 */+ *pHighwtr = 0; /* IMP: R-64479-57858 */*pCurrent = nByte;break;@@ -24507,7 +24931,7 @@ SQLITE_API int sqlite3_db_status(/*** Set *pCurrent to the total cache hits or misses encountered by all- ** pagers the database handle is connected to. *pHighwater is always set+ ** pagers the database handle is connected to. *pHighwtr is always set** to zero.*/case SQLITE_DBSTATUS_CACHE_SPILL:@@ -24527,19 +24951,39 @@ SQLITE_API int sqlite3_db_status(sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);}}- *pHighwater = 0; /* IMP: R-42420-56072 */+ *pHighwtr = 0; /* IMP: R-42420-56072 *//* IMP: R-54100-20147 *//* IMP: R-29431-39229 */- *pCurrent = (int)nRet & 0x7fffffff;+ *pCurrent = nRet;+ break;+ }++ /* Set *pCurrent to the number of bytes that the db database connection+ ** has spilled to the filesystem in temporary files that could have been+ ** stored in memory, had sufficient memory been available.+ ** The *pHighwater is always set to zero.+ */+ case SQLITE_DBSTATUS_TEMPBUF_SPILL: {+ u64 nRet = 0;+ if( db->aDb[1].pBt ){+ Pager *pPager = sqlite3BtreePager(db->aDb[1].pBt);+ sqlite3PagerCacheStat(pPager, SQLITE_DBSTATUS_CACHE_WRITE,+ resetFlag, &nRet);+ nRet *= sqlite3BtreeGetPageSize(db->aDb[1].pBt);+ }+ nRet += db->nSpill;+ if( resetFlag ) db->nSpill = 0;+ *pHighwtr = 0;+ *pCurrent = nRet;break;}/* Set *pCurrent to non-zero if there are unresolved deferred foreign** key constraints. Set *pCurrent to zero if all foreign key constraints- ** have been satisfied. The *pHighwater is always set to zero.+ ** have been satisfied. The *pHighwtr is always set to zero.*/case SQLITE_DBSTATUS_DEFERRED_FKS: {- *pHighwater = 0; /* IMP: R-11967-56545 */+ *pHighwtr = 0; /* IMP: R-11967-56545 */*pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;break;}@@ -24552,6 +24996,31 @@ SQLITE_API int sqlite3_db_status(return rc;}+/*+** 32-bit variant of sqlite3_db_status64()+*/+SQLITE_API int sqlite3_db_status(+ sqlite3 *db, /* The database connection whose status is desired */+ int op, /* Status verb */+ int *pCurrent, /* Write current value here */+ int *pHighwtr, /* Write high-water mark here */+ int resetFlag /* Reset high-water mark if true */+){+ sqlite3_int64 C = 0, H = 0;+ int rc;+#ifdef SQLITE_ENABLE_API_ARMOR+ if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwtr==0 ){+ return SQLITE_MISUSE_BKPT;+ }+#endif+ rc = sqlite3_db_status64(db, op, &C, &H, resetFlag);+ if( rc==0 ){+ *pCurrent = C & 0x7fffffff;+ *pHighwtr = H & 0x7fffffff;+ }+ return rc;+}+/************** End of status.c **********************************************//************** Begin file date.c ********************************************//*@@ -24744,6 +25213,10 @@ static int parseTimezone(const char *zDate, DateTime *p){}zDate += 5;p->tz = sgn*(nMn + nHr*60);+ if( p->tz==0 ){ /* Forum post 2025-09-17T10:12:14z */+ p->isLocal = 0;+ p->isUtc = 1;+ }zulu_time:while( sqlite3Isspace(*zDate) ){ zDate++; }return *zDate!=0;@@ -25913,7 +26386,7 @@ static int daysAfterMonday(DateTime *pDate){** In other words, return the day of the week according** to this code:**-** 0=Sunday, 1=Monday, 2=Tues, ..., 6=Saturday+** 0=Sunday, 1=Monday, 2=Tuesday, ..., 6=Saturday*/static int daysAfterSunday(DateTime *pDate){assert( pDate->validJD );@@ -25939,8 +26412,8 @@ static int daysAfterSunday(DateTime *pDate){** %l hour 1-12 (leading zero converted to space)** %m month 01-12** %M minute 00-59-** %p "am" or "pm"-** %P "AM" or "PM"+** %p "AM" or "PM"+** %P "am" or "pm"** %R time as HH:MM** %s seconds since 1970-01-01** %S seconds 00-59@@ -30122,6 +30595,8 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){#ifdef __CYGWIN__# include <sys/cygwin.h>+# include <sys/stat.h> /* amalgamator: dontcache */+# include <unistd.h> /* amalgamator: dontcache */# include <errno.h> /* amalgamator: dontcache */#endif@@ -30857,27 +31332,6 @@ static void mallocWithAlarm(int n, void **pp){*pp = p;}-/*-** Maximum size of any single memory allocation.-**-** This is not a limit on the total amount of memory used. This is-** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc().-**-** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391-** This provides a 256-byte safety margin for defense against 32-bit-** signed integer overflow bugs when computing memory allocation sizes.-** Paranoid applications might want to reduce the maximum allocation size-** further for an even larger safety margin. 0x3fffffff or 0x0fffffff-** or even smaller would be reasonable upper bounds on the size of a memory-** allocations for most applications.-*/-#ifndef SQLITE_MAX_ALLOCATION_SIZE-# define SQLITE_MAX_ALLOCATION_SIZE 2147483391-#endif-#if SQLITE_MAX_ALLOCATION_SIZE>2147483391-# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391-#endif-/*** Allocate memory. This routine is like sqlite3_malloc() except that it** assumes the memory subsystem has already been initialized.@@ -31101,8 +31555,7 @@ SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){sqlite3_free(pOld); /* IMP: R-26507-47431 */return 0;}- if( nBytes>=0x7fffff00 ){- /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */+ if( nBytes>SQLITE_MAX_ALLOCATION_SIZE ){return 0;}nOld = sqlite3MallocSize(pOld);@@ -31516,17 +31969,17 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){#define etPERCENT 7 /* Percent symbol. %% */#define etCHARX 8 /* Characters. %c *//* The rest are extensions, not normally found in printf() */-#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */-#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',- NULL pointers replaced by SQL NULL. %Q */-#define etTOKEN 11 /* a pointer to a Token structure */-#define etSRCITEM 12 /* a pointer to a SrcItem */-#define etPOINTER 13 /* The %p conversion */-#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */-#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */-#define etDECIMAL 16 /* %d or %u, but not %x, %o */+#define etESCAPE_q 9 /* Strings with '\'' doubled. %q */+#define etESCAPE_Q 10 /* Strings with '\'' doubled and enclosed in '',+ NULL pointers replaced by SQL NULL. %Q */+#define etTOKEN 11 /* a pointer to a Token structure */+#define etSRCITEM 12 /* a pointer to a SrcItem */+#define etPOINTER 13 /* The %p conversion */+#define etESCAPE_w 14 /* %w -> Strings with '\"' doubled */+#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */+#define etDECIMAL 16 /* %d or %u, but not %x, %o */-#define etINVALID 17 /* Any unrecognized conversion type */+#define etINVALID 17 /* Any unrecognized conversion type *//*@@ -31545,6 +31998,7 @@ typedef struct et_info { /* Information about each format field */etByte type; /* Conversion paradigm */etByte charset; /* Offset into aDigits[] of the digits string */etByte prefix; /* Offset into aPrefix[] of the prefix string */+ char iNxt; /* Next with same hash, or 0 for end of chain */} et_info;/*@@ -31553,44 +32007,61 @@ typedef struct et_info { /* Information about each format field */#define FLAG_SIGNED 1 /* True if the value to convert is signed */#define FLAG_STRING 4 /* Allow infinite precision */-/*-** The following table is searched linearly, so it is good to put the-** most frequently used conversion types first.+** The table is searched by hash. In the case of %C where C is the character+** and that character has ASCII value j, then the hash is j%23.+**+** The order of the entries in fmtinfo[] and the hash chain was entered+** manually, but based on the output of the following TCL script:*/+#if 0 /***** Beginning of script ******/+foreach c {d s g z q Q w c o u x X f e E G i n % p T S r} {+ scan $c %c x+ set n($c) $x+}+set mx [llength [array names n]]+puts "count: $mx"++set mx 27+puts "*********** mx=$mx ************"+for {set r 0} {$r<$mx} {incr r} {+ puts -nonewline [format %2d: $r]+ foreach c [array names n] {+ if {($n($c))%$mx==$r} {puts -nonewline " $c"}+ }+ puts ""+}+#endif /***** End of script ********/+static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";static const char aPrefix[] = "-x0\000X0";-static const et_info fmtinfo[] = {- { 'd', 10, 1, etDECIMAL, 0, 0 },- { 's', 0, 4, etSTRING, 0, 0 },- { 'g', 0, 1, etGENERIC, 30, 0 },- { 'z', 0, 4, etDYNSTRING, 0, 0 },- { 'q', 0, 4, etSQLESCAPE, 0, 0 },- { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },- { 'w', 0, 4, etSQLESCAPE3, 0, 0 },- { 'c', 0, 0, etCHARX, 0, 0 },- { 'o', 8, 0, etRADIX, 0, 2 },- { 'u', 10, 0, etDECIMAL, 0, 0 },- { 'x', 16, 0, etRADIX, 16, 1 },- { 'X', 16, 0, etRADIX, 0, 4 },-#ifndef SQLITE_OMIT_FLOATING_POINT- { 'f', 0, 1, etFLOAT, 0, 0 },- { 'e', 0, 1, etEXP, 30, 0 },- { 'E', 0, 1, etEXP, 14, 0 },- { 'G', 0, 1, etGENERIC, 14, 0 },-#endif- { 'i', 10, 1, etDECIMAL, 0, 0 },- { 'n', 0, 0, etSIZE, 0, 0 },- { '%', 0, 0, etPERCENT, 0, 0 },- { 'p', 16, 0, etPOINTER, 0, 1 },-- /* All the rest are undocumented and are for internal use only */- { 'T', 0, 0, etTOKEN, 0, 0 },- { 'S', 0, 0, etSRCITEM, 0, 0 },- { 'r', 10, 1, etORDINAL, 0, 0 },+static const et_info fmtinfo[23] = {+ /* 0 */ { 's', 0, 4, etSTRING, 0, 0, 1 },+ /* 1 */ { 'E', 0, 1, etEXP, 14, 0, 0 }, /* Hash: 0 */+ /* 2 */ { 'u', 10, 0, etDECIMAL, 0, 0, 3 },+ /* 3 */ { 'G', 0, 1, etGENERIC, 14, 0, 0 }, /* Hash: 2 */+ /* 4 */ { 'w', 0, 4, etESCAPE_w, 0, 0, 0 },+ /* 5 */ { 'x', 16, 0, etRADIX, 16, 1, 0 },+ /* 6 */ { 'c', 0, 0, etCHARX, 0, 0, 0 }, /* Hash: 7 */+ /* 7 */ { 'z', 0, 4, etDYNSTRING, 0, 0, 6 },+ /* 8 */ { 'd', 10, 1, etDECIMAL, 0, 0, 0 },+ /* 9 */ { 'e', 0, 1, etEXP, 30, 0, 0 },+ /* 10 */ { 'f', 0, 1, etFLOAT, 0, 0, 0 },+ /* 11 */ { 'g', 0, 1, etGENERIC, 30, 0, 0 },+ /* 12 */ { 'Q', 0, 4, etESCAPE_Q, 0, 0, 0 },+ /* 13 */ { 'i', 10, 1, etDECIMAL, 0, 0, 0 },+ /* 14 */ { '%', 0, 0, etPERCENT, 0, 0, 16 },+ /* 15 */ { 'T', 0, 0, etTOKEN, 0, 0, 0 },+ /* 16 */ { 'S', 0, 0, etSRCITEM, 0, 0, 0 }, /* Hash: 14 */+ /* 17 */ { 'X', 16, 0, etRADIX, 0, 4, 0 }, /* Hash: 19 */+ /* 18 */ { 'n', 0, 0, etSIZE, 0, 0, 0 },+ /* 19 */ { 'o', 8, 0, etRADIX, 0, 2, 17 },+ /* 20 */ { 'p', 16, 0, etPOINTER, 0, 1, 0 },+ /* 21 */ { 'q', 0, 4, etESCAPE_q, 0, 0, 0 },+ /* 22 */ { 'r', 10, 1, etORDINAL, 0, 0, 0 }};-/* Notes:+/* Additional Notes:**** %S Takes a pointer to SrcItem. Shows name or database.name** %!S Like %S but prefer the zName over the zAlias@@ -31717,7 +32188,10 @@ SQLITE_API void sqlite3_str_vappendf(#if HAVE_STRCHRNULfmt = strchrnul(fmt, '%');#else- do{ fmt++; }while( *fmt && *fmt != '%' );+ fmt = strchr(fmt, '%');+ if( fmt==0 ){+ fmt = bufpt + strlen(bufpt);+ }#endifsqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));if( *fmt==0 ) break;@@ -31831,6 +32305,9 @@ SQLITE_API void sqlite3_str_vappendf(}while( !done && (c=(*++fmt))!=0 );/* Fetch the info entry for the field */+#ifdef SQLITE_EBCDIC+ /* The hash table only works for ASCII. For EBCDIC, we need to do+ ** a linear search of the table */infop = &fmtinfo[0];xtype = etINVALID;for(idx=0; idx<ArraySize(fmtinfo); idx++){@@ -31840,6 +32317,20 @@ SQLITE_API void sqlite3_str_vappendf(break;}}+#else+ /* Fast hash-table lookup */+ assert( ArraySize(fmtinfo)==23 );+ idx = ((unsigned)c) % 23;+ if( fmtinfo[idx].fmttype==c+ || fmtinfo[idx = fmtinfo[idx].iNxt].fmttype==c+ ){+ infop = &fmtinfo[idx];+ xtype = infop->type;+ }else{+ infop = &fmtinfo[0];+ xtype = etINVALID;+ }+#endif/*** At this point, variables are initialized as follows:@@ -31907,6 +32398,14 @@ SQLITE_API void sqlite3_str_vappendf(}prefix = 0;}++#if WHERETRACE_ENABLED+ if( xtype==etPOINTER && sqlite3WhereTrace & 0x100000 ) longvalue = 0;+#endif+#if TREETRACE_ENABLED+ if( xtype==etPOINTER && sqlite3TreeTrace & 0x100000 ) longvalue = 0;+#endif+if( longvalue==0 ) flag_alternateform = 0;if( flag_zeropad && precision<width-(prefix!=0) ){precision = width-(prefix!=0);@@ -32019,7 +32518,21 @@ SQLITE_API void sqlite3_str_vappendf(}}if( s.sign=='-' ){- prefix = '-';+ if( flag_alternateform+ && !flag_prefix+ && xtype==etFLOAT+ && s.iDP<=iRound+ ){+ /* Suppress the minus sign if all of the following are true:+ ** * The value displayed is zero+ ** * The '#' flag is used+ ** * The '+' flag is not used, and+ ** * The format is %f+ */+ prefix = 0;+ }else{+ prefix = '-';+ }}else{prefix = flag_prefix;}@@ -32164,25 +32677,7 @@ SQLITE_API void sqlite3_str_vappendf(}}else{unsigned int ch = va_arg(ap,unsigned int);- if( ch<0x00080 ){- buf[0] = ch & 0xff;- length = 1;- }else if( ch<0x00800 ){- buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);- buf[1] = 0x80 + (u8)(ch & 0x3f);- length = 2;- }else if( ch<0x10000 ){- buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);- buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);- buf[2] = 0x80 + (u8)(ch & 0x3f);- length = 3;- }else{- buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);- buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);- buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);- buf[3] = 0x80 + (u8)(ch & 0x3f);- length = 4;- }+ length = sqlite3AppendOneUtf8Character(buf, ch);}if( precision>1 ){i64 nPrior = 1;@@ -32262,22 +32757,31 @@ SQLITE_API void sqlite3_str_vappendf(while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;}break;- case etSQLESCAPE: /* %q: Escape ' characters */- case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */- case etSQLESCAPE3: { /* %w: Escape " characters */+ case etESCAPE_q: /* %q: Escape ' characters */+ case etESCAPE_Q: /* %Q: Escape ' and enclose in '...' */+ case etESCAPE_w: { /* %w: Escape " characters */i64 i, j, k, n;- int needQuote, isnull;+ int needQuote = 0;char ch;- char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */char *escarg;+ char q;if( bArgList ){escarg = getTextArg(pArgList);}else{escarg = va_arg(ap,char*);}- isnull = escarg==0;- if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");+ if( escarg==0 ){+ escarg = (xtype==etESCAPE_Q ? "NULL" : "(NULL)");+ }else if( xtype==etESCAPE_Q ){+ needQuote = 1;+ }+ if( xtype==etESCAPE_w ){+ q = '"';+ flag_alternateform = 0;+ }else{+ q = '\'';+ }/* For %q, %Q, and %w, the precision is the number of bytes (or** characters if the ! flags is present) to use from the input.** Because of the extra quoting characters inserted, the number@@ -32290,7 +32794,30 @@ SQLITE_API void sqlite3_str_vappendf(while( (escarg[i+1]&0xc0)==0x80 ){ i++; }}}- needQuote = !isnull && xtype==etSQLESCAPE2;+ if( flag_alternateform ){+ /* For %#q, do unistr()-style backslash escapes for+ ** all control characters, and for backslash itself.+ ** For %#Q, do the same but only if there is at least+ ** one control character. */+ u32 nBack = 0;+ u32 nCtrl = 0;+ for(k=0; k<i; k++){+ if( escarg[k]=='\\' ){+ nBack++;+ }else if( ((u8*)escarg)[k]<=0x1f ){+ nCtrl++;+ }+ }+ if( nCtrl || xtype==etESCAPE_q ){+ n += nBack + 5*nCtrl;+ if( xtype==etESCAPE_Q ){+ n += 10;+ needQuote = 2;+ }+ }else{+ flag_alternateform = 0;+ }+ }n += i + 3;if( n>etBUFSIZE ){bufpt = zExtra = printfTempBuf(pAccum, n);@@ -32299,13 +32826,41 @@ SQLITE_API void sqlite3_str_vappendf(bufpt = buf;}j = 0;- if( needQuote ) bufpt[j++] = q;+ if( needQuote ){+ if( needQuote==2 ){+ memcpy(&bufpt[j], "unistr('", 8);+ j += 8;+ }else{+ bufpt[j++] = '\'';+ }+ }k = i;- for(i=0; i<k; i++){- bufpt[j++] = ch = escarg[i];- if( ch==q ) bufpt[j++] = ch;+ if( flag_alternateform ){+ for(i=0; i<k; i++){+ bufpt[j++] = ch = escarg[i];+ if( ch==q ){+ bufpt[j++] = ch;+ }else if( ch=='\\' ){+ bufpt[j++] = '\\';+ }else if( ((unsigned char)ch)<=0x1f ){+ bufpt[j-1] = '\\';+ bufpt[j++] = 'u';+ bufpt[j++] = '0';+ bufpt[j++] = '0';+ bufpt[j++] = ch>=0x10 ? '1' : '0';+ bufpt[j++] = "0123456789abcdef"[ch&0xf];+ }+ }+ }else{+ for(i=0; i<k; i++){+ bufpt[j++] = ch = escarg[i];+ if( ch==q ) bufpt[j++] = ch;+ }+ }+ if( needQuote ){+ bufpt[j++] = '\'';+ if( needQuote==2 ) bufpt[j++] = ')';}- if( needQuote ) bufpt[j++] = q;bufpt[j] = 0;length = j;goto adjust_width_for_utf8;@@ -32548,7 +33103,7 @@ SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){char *zText;assert( p->mxAlloc>0 && !isMalloced(p) );- zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );+ zText = sqlite3DbMallocRaw(p->db, 1+(u64)p->nChar );if( zText ){memcpy(zText, p->zText, p->nChar+1);p->printfFlags |= SQLITE_PRINTF_MALLOCED;@@ -32793,6 +33348,15 @@ SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){return zBuf;}+/* Maximum size of an sqlite3_log() message. */+#if defined(SQLITE_MAX_LOG_MESSAGE)+ /* Leave the definition as supplied */+#elif SQLITE_PRINT_BUF_SIZE*10>10000+# define SQLITE_MAX_LOG_MESSAGE 10000+#else+# define SQLITE_MAX_LOG_MESSAGE (SQLITE_PRINT_BUF_SIZE*10)+#endif+/*** This is the routine that actually formats the sqlite3_log() message.** We house it in a separate routine from sqlite3_log() to avoid using@@ -32809,7 +33373,7 @@ SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){*/static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){StrAccum acc; /* String accumulator */- char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */+ char zMsg[SQLITE_MAX_LOG_MESSAGE]; /* Complete log message */sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);sqlite3_str_vappendf(&acc, zFormat, ap);@@ -33179,9 +33743,13 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc)n = 0;if( pItem->fg.isSubquery ) n++;if( pItem->fg.isTabFunc ) n++;- if( pItem->fg.isUsing ) n++;+ if( pItem->fg.isUsing || pItem->u3.pOn!=0 ) n++;if( pItem->fg.isUsing ){sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING");+ }else if( pItem->u3.pOn!=0 ){+ sqlite3TreeViewItem(pView, "ON", (--n)>0);+ sqlite3TreeViewExpr(pView, pItem->u3.pOn, 0);+ sqlite3TreeViewPop(&pView);}if( pItem->fg.isSubquery ){assert( n==1 );@@ -34804,6 +35372,35 @@ static const unsigned char sqlite3Utf8Trans1[] = {} \}+/*+** Write a single UTF8 character whose value is v into the+** buffer starting at zOut. zOut must be sized to hold at+** least four bytes. Return the number of bytes needed+** to encode the new character.+*/+SQLITE_PRIVATE int sqlite3AppendOneUtf8Character(char *zOut, u32 v){+ if( v<0x00080 ){+ zOut[0] = (u8)(v & 0xff);+ return 1;+ }+ if( v<0x00800 ){+ zOut[0] = 0xc0 + (u8)((v>>6) & 0x1f);+ zOut[1] = 0x80 + (u8)(v & 0x3f);+ return 2;+ }+ if( v<0x10000 ){+ zOut[0] = 0xe0 + (u8)((v>>12) & 0x0f);+ zOut[1] = 0x80 + (u8)((v>>6) & 0x3f);+ zOut[2] = 0x80 + (u8)(v & 0x3f);+ return 3;+ }+ zOut[0] = 0xf0 + (u8)((v>>18) & 0x07);+ zOut[1] = 0x80 + (u8)((v>>12) & 0x3f);+ zOut[2] = 0x80 + (u8)((v>>6) & 0x3f);+ zOut[3] = 0x80 + (u8)(v & 0x3f);+ return 4;+}+/*** Translate a single UTF-8 character. Return the unicode value.**@@ -35225,7 +35822,7 @@ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nByte, int nChar){int n = 0;if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;- while( n<nChar && ALWAYS(z<=zEnd) ){+ while( n<nChar && z<=zEnd ){c = z[0];z += 2;if( c>=0xd8 && c<0xdc && z<=zEnd && z[0]>=0xdc && z[0]<0xe0 ) z += 2;@@ -36400,7 +36997,11 @@ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRou}p->z = &p->zBuf[i+1];assert( i+p->n < sizeof(p->zBuf) );- while( ALWAYS(p->n>0) && p->z[p->n-1]=='0' ){ p->n--; }+ assert( p->n>0 );+ while( p->z[p->n-1]=='0' ){+ p->n--;+ assert( p->n>0 );+ }}/*@@ -36905,7 +37506,7 @@ SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){}/*-** Compute the absolute value of a 32-bit signed integer, of possible. Or+** Compute the absolute value of a 32-bit signed integer, if possible. Or** if the integer has a value of -2147483648, return +2147483647*/SQLITE_PRIVATE int sqlite3AbsInt32(int x){@@ -37186,12 +37787,19 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){*/static unsigned int strHash(const char *z){unsigned int h = 0;- unsigned char c;- while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/+ while( z[0] ){ /*OPTIMIZATION-IF-TRUE*//* Knuth multiplicative hashing. (Sorting & Searching, p. 510).** 0x9e3779b1 is 2654435761 which is the closest prime number to- ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */- h += sqlite3UpperToLower[c];+ ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2.+ **+ ** Only bits 0xdf for ASCII and bits 0xbf for EBCDIC each octet are+ ** hashed since the omitted bits determine the upper/lower case difference.+ */+#ifdef SQLITE_EBCDIC+ h += 0xbf & (unsigned char)*(z++);+#else+ h += 0xdf & (unsigned char)*(z++);+#endifh *= 0x9e3779b1;}return h;@@ -37264,9 +37872,8 @@ static int rehash(Hash *pH, unsigned int new_size){pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);memset(new_ht, 0, new_size*sizeof(struct _ht));for(elem=pH->first, pH->first=0; elem; elem = next_elem){- unsigned int h = strHash(elem->pKey) % new_size;next_elem = elem->next;- insertElement(pH, &new_ht[h], elem);+ insertElement(pH, &new_ht[elem->h % new_size], elem);}return 1;}@@ -37284,23 +37891,22 @@ static HashElem *findElementWithHash(HashElem *elem; /* Used to loop thru the element list */unsigned int count; /* Number of elements left to test */unsigned int h; /* The computed hash */- static HashElem nullElement = { 0, 0, 0, 0 };+ static HashElem nullElement = { 0, 0, 0, 0, 0 };+ h = strHash(pKey);if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/struct _ht *pEntry;- h = strHash(pKey) % pH->htsize;- pEntry = &pH->ht[h];+ pEntry = &pH->ht[h % pH->htsize];elem = pEntry->chain;count = pEntry->count;}else{- h = 0;elem = pH->first;count = pH->count;}if( pHash ) *pHash = h;while( count ){assert( elem!=0 );- if( sqlite3StrICmp(elem->pKey,pKey)==0 ){+ if( h==elem->h && sqlite3StrICmp(elem->pKey,pKey)==0 ){return elem;}elem = elem->next;@@ -37312,10 +37918,9 @@ static HashElem *findElementWithHash(/* Remove a single entry from the hash table given a pointer to that** element and a hash on the element's key.*/-static void removeElementGivenHash(+static void removeElement(Hash *pH, /* The pH containing "elem" */- HashElem* elem, /* The element to be removed from the pH */- unsigned int h /* Hash value for the element */+ HashElem *elem /* The element to be removed from the pH */){struct _ht *pEntry;if( elem->prev ){@@ -37327,7 +37932,7 @@ static void removeElementGivenHash(elem->next->prev = elem->prev;}if( pH->ht ){- pEntry = &pH->ht[h];+ pEntry = &pH->ht[elem->h % pH->htsize];if( pEntry->chain==elem ){pEntry->chain = elem->next;}@@ -37378,7 +37983,7 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){if( elem->data ){void *old_data = elem->data;if( data==0 ){- removeElementGivenHash(pH,elem,h);+ removeElement(pH,elem);}else{elem->data = data;elem->pKey = pKey;@@ -37389,18 +37994,17 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );if( new_elem==0 ) return data;new_elem->pKey = pKey;+ new_elem->h = h;new_elem->data = data;pH->count++;- if( pH->count>=10 && pH->count > 2*pH->htsize ){- if( rehash(pH, pH->count*2) ){- assert( pH->htsize>0 );- h = strHash(pKey) % pH->htsize;- }+ if( pH->count>=5 && pH->count > 2*pH->htsize ){+ rehash(pH, pH->count*3);}- insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);+ insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem);return 0;}+/************** End of hash.c ************************************************//************** Begin file opcodes.c *****************************************//* Automatically generated. Do not edit */@@ -37452,20 +38056,20 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){/* 34 */ "SorterSort" OpHelp(""),/* 35 */ "Sort" OpHelp(""),/* 36 */ "Rewind" OpHelp(""),- /* 37 */ "SorterNext" OpHelp(""),- /* 38 */ "Prev" OpHelp(""),- /* 39 */ "Next" OpHelp(""),- /* 40 */ "IdxLE" OpHelp("key=r[P3@P4]"),- /* 41 */ "IdxGT" OpHelp("key=r[P3@P4]"),- /* 42 */ "IdxLT" OpHelp("key=r[P3@P4]"),+ /* 37 */ "IfEmpty" OpHelp("if( empty(P1) ) goto P2"),+ /* 38 */ "SorterNext" OpHelp(""),+ /* 39 */ "Prev" OpHelp(""),+ /* 40 */ "Next" OpHelp(""),+ /* 41 */ "IdxLE" OpHelp("key=r[P3@P4]"),+ /* 42 */ "IdxGT" OpHelp("key=r[P3@P4]"),/* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),/* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),- /* 45 */ "IdxGE" OpHelp("key=r[P3@P4]"),- /* 46 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),- /* 47 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),- /* 48 */ "Program" OpHelp(""),- /* 49 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),- /* 50 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),+ /* 45 */ "IdxLT" OpHelp("key=r[P3@P4]"),+ /* 46 */ "IdxGE" OpHelp("key=r[P3@P4]"),+ /* 47 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),+ /* 48 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),+ /* 49 */ "Program" OpHelp(""),+ /* 50 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),/* 51 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),/* 52 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),/* 53 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),@@ -37475,49 +38079,49 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){/* 57 */ "Lt" OpHelp("IF r[P3]<r[P1]"),/* 58 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),/* 59 */ "ElseEq" OpHelp(""),- /* 60 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),- /* 61 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),- /* 62 */ "IncrVacuum" OpHelp(""),- /* 63 */ "VNext" OpHelp(""),- /* 64 */ "Filter" OpHelp("if key(P3@P4) not in filter(P1) goto P2"),- /* 65 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"),- /* 66 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"),- /* 67 */ "Return" OpHelp(""),- /* 68 */ "EndCoroutine" OpHelp(""),- /* 69 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),- /* 70 */ "Halt" OpHelp(""),- /* 71 */ "Integer" OpHelp("r[P2]=P1"),- /* 72 */ "Int64" OpHelp("r[P2]=P4"),- /* 73 */ "String" OpHelp("r[P2]='P4' (len=P1)"),- /* 74 */ "BeginSubrtn" OpHelp("r[P2]=NULL"),- /* 75 */ "Null" OpHelp("r[P2..P3]=NULL"),- /* 76 */ "SoftNull" OpHelp("r[P1]=NULL"),- /* 77 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),- /* 78 */ "Variable" OpHelp("r[P2]=parameter(P1)"),- /* 79 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),- /* 80 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),- /* 81 */ "SCopy" OpHelp("r[P2]=r[P1]"),- /* 82 */ "IntCopy" OpHelp("r[P2]=r[P1]"),- /* 83 */ "FkCheck" OpHelp(""),- /* 84 */ "ResultRow" OpHelp("output=r[P1@P2]"),- /* 85 */ "CollSeq" OpHelp(""),- /* 86 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),- /* 87 */ "RealAffinity" OpHelp(""),- /* 88 */ "Cast" OpHelp("affinity(r[P1])"),- /* 89 */ "Permutation" OpHelp(""),- /* 90 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),- /* 91 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),- /* 92 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"),- /* 93 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),- /* 94 */ "Column" OpHelp("r[P3]=PX cursor P1 column P2"),- /* 95 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"),- /* 96 */ "Affinity" OpHelp("affinity(r[P1@P2])"),- /* 97 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),- /* 98 */ "Count" OpHelp("r[P2]=count()"),- /* 99 */ "ReadCookie" OpHelp(""),- /* 100 */ "SetCookie" OpHelp(""),- /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),- /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"),+ /* 60 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),+ /* 61 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),+ /* 62 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),+ /* 63 */ "IncrVacuum" OpHelp(""),+ /* 64 */ "VNext" OpHelp(""),+ /* 65 */ "Filter" OpHelp("if key(P3@P4) not in filter(P1) goto P2"),+ /* 66 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"),+ /* 67 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"),+ /* 68 */ "Return" OpHelp(""),+ /* 69 */ "EndCoroutine" OpHelp(""),+ /* 70 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),+ /* 71 */ "Halt" OpHelp(""),+ /* 72 */ "Integer" OpHelp("r[P2]=P1"),+ /* 73 */ "Int64" OpHelp("r[P2]=P4"),+ /* 74 */ "String" OpHelp("r[P2]='P4' (len=P1)"),+ /* 75 */ "BeginSubrtn" OpHelp("r[P2]=NULL"),+ /* 76 */ "Null" OpHelp("r[P2..P3]=NULL"),+ /* 77 */ "SoftNull" OpHelp("r[P1]=NULL"),+ /* 78 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),+ /* 79 */ "Variable" OpHelp("r[P2]=parameter(P1)"),+ /* 80 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),+ /* 81 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),+ /* 82 */ "SCopy" OpHelp("r[P2]=r[P1]"),+ /* 83 */ "IntCopy" OpHelp("r[P2]=r[P1]"),+ /* 84 */ "FkCheck" OpHelp(""),+ /* 85 */ "ResultRow" OpHelp("output=r[P1@P2]"),+ /* 86 */ "CollSeq" OpHelp(""),+ /* 87 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),+ /* 88 */ "RealAffinity" OpHelp(""),+ /* 89 */ "Cast" OpHelp("affinity(r[P1])"),+ /* 90 */ "Permutation" OpHelp(""),+ /* 91 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),+ /* 92 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),+ /* 93 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"),+ /* 94 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),+ /* 95 */ "Column" OpHelp("r[P3]=PX cursor P1 column P2"),+ /* 96 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"),+ /* 97 */ "Affinity" OpHelp("affinity(r[P1@P2])"),+ /* 98 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),+ /* 99 */ "Count" OpHelp("r[P2]=count()"),+ /* 100 */ "ReadCookie" OpHelp(""),+ /* 101 */ "SetCookie" OpHelp(""),+ /* 102 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),/* 103 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),/* 104 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),/* 105 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),@@ -37528,83 +38132,84 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){/* 110 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),/* 111 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),/* 112 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),- /* 113 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),- /* 114 */ "OpenDup" OpHelp(""),+ /* 113 */ "OpenRead" OpHelp("root=P2 iDb=P3"),+ /* 114 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),/* 115 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),- /* 116 */ "OpenAutoindex" OpHelp("nColumn=P2"),- /* 117 */ "OpenEphemeral" OpHelp("nColumn=P2"),+ /* 116 */ "OpenDup" OpHelp(""),+ /* 117 */ "OpenAutoindex" OpHelp("nColumn=P2"),/* 118 */ "String8" OpHelp("r[P2]='P4'"),- /* 119 */ "SorterOpen" OpHelp(""),- /* 120 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),- /* 121 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),- /* 122 */ "Close" OpHelp(""),- /* 123 */ "ColumnsUsed" OpHelp(""),- /* 124 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"),- /* 125 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"),- /* 126 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),- /* 127 */ "NewRowid" OpHelp("r[P2]=rowid"),- /* 128 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),- /* 129 */ "RowCell" OpHelp(""),- /* 130 */ "Delete" OpHelp(""),- /* 131 */ "ResetCount" OpHelp(""),- /* 132 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),- /* 133 */ "SorterData" OpHelp("r[P2]=data"),- /* 134 */ "RowData" OpHelp("r[P2]=data"),- /* 135 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"),- /* 136 */ "NullRow" OpHelp(""),- /* 137 */ "SeekEnd" OpHelp(""),- /* 138 */ "IdxInsert" OpHelp("key=r[P2]"),- /* 139 */ "SorterInsert" OpHelp("key=r[P2]"),- /* 140 */ "IdxDelete" OpHelp("key=r[P2@P3]"),- /* 141 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),- /* 142 */ "IdxRowid" OpHelp("r[P2]=rowid"),- /* 143 */ "FinishSeek" OpHelp(""),- /* 144 */ "Destroy" OpHelp(""),- /* 145 */ "Clear" OpHelp(""),- /* 146 */ "ResetSorter" OpHelp(""),- /* 147 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),- /* 148 */ "SqlExec" OpHelp(""),- /* 149 */ "ParseSchema" OpHelp(""),- /* 150 */ "LoadAnalysis" OpHelp(""),- /* 151 */ "DropTable" OpHelp(""),- /* 152 */ "DropIndex" OpHelp(""),- /* 153 */ "DropTrigger" OpHelp(""),+ /* 119 */ "OpenEphemeral" OpHelp("nColumn=P2"),+ /* 120 */ "SorterOpen" OpHelp(""),+ /* 121 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),+ /* 122 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),+ /* 123 */ "Close" OpHelp(""),+ /* 124 */ "ColumnsUsed" OpHelp(""),+ /* 125 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"),+ /* 126 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"),+ /* 127 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),+ /* 128 */ "NewRowid" OpHelp("r[P2]=rowid"),+ /* 129 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),+ /* 130 */ "RowCell" OpHelp(""),+ /* 131 */ "Delete" OpHelp(""),+ /* 132 */ "ResetCount" OpHelp(""),+ /* 133 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),+ /* 134 */ "SorterData" OpHelp("r[P2]=data"),+ /* 135 */ "RowData" OpHelp("r[P2]=data"),+ /* 136 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"),+ /* 137 */ "NullRow" OpHelp(""),+ /* 138 */ "SeekEnd" OpHelp(""),+ /* 139 */ "IdxInsert" OpHelp("key=r[P2]"),+ /* 140 */ "SorterInsert" OpHelp("key=r[P2]"),+ /* 141 */ "IdxDelete" OpHelp("key=r[P2@P3]"),+ /* 142 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),+ /* 143 */ "IdxRowid" OpHelp("r[P2]=rowid"),+ /* 144 */ "FinishSeek" OpHelp(""),+ /* 145 */ "Destroy" OpHelp(""),+ /* 146 */ "Clear" OpHelp(""),+ /* 147 */ "ResetSorter" OpHelp(""),+ /* 148 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),+ /* 149 */ "SqlExec" OpHelp(""),+ /* 150 */ "ParseSchema" OpHelp(""),+ /* 151 */ "LoadAnalysis" OpHelp(""),+ /* 152 */ "DropTable" OpHelp(""),+ /* 153 */ "DropIndex" OpHelp(""),/* 154 */ "Real" OpHelp("r[P2]=P4"),- /* 155 */ "IntegrityCk" OpHelp(""),- /* 156 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),- /* 157 */ "Param" OpHelp(""),- /* 158 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),- /* 159 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),- /* 160 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),- /* 161 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),- /* 162 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),- /* 163 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),- /* 164 */ "AggValue" OpHelp("r[P3]=value N=P2"),- /* 165 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),- /* 166 */ "Expire" OpHelp(""),- /* 167 */ "CursorLock" OpHelp(""),- /* 168 */ "CursorUnlock" OpHelp(""),- /* 169 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),- /* 170 */ "VBegin" OpHelp(""),- /* 171 */ "VCreate" OpHelp(""),- /* 172 */ "VDestroy" OpHelp(""),- /* 173 */ "VOpen" OpHelp(""),- /* 174 */ "VCheck" OpHelp(""),- /* 175 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),- /* 176 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),- /* 177 */ "VRename" OpHelp(""),- /* 178 */ "Pagecount" OpHelp(""),- /* 179 */ "MaxPgcnt" OpHelp(""),- /* 180 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),- /* 181 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),- /* 182 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),- /* 183 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),- /* 184 */ "Trace" OpHelp(""),- /* 185 */ "CursorHint" OpHelp(""),- /* 186 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),- /* 187 */ "Noop" OpHelp(""),- /* 188 */ "Explain" OpHelp(""),- /* 189 */ "Abortable" OpHelp(""),+ /* 155 */ "DropTrigger" OpHelp(""),+ /* 156 */ "IntegrityCk" OpHelp(""),+ /* 157 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),+ /* 158 */ "Param" OpHelp(""),+ /* 159 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),+ /* 160 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),+ /* 161 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),+ /* 162 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),+ /* 163 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),+ /* 164 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),+ /* 165 */ "AggValue" OpHelp("r[P3]=value N=P2"),+ /* 166 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),+ /* 167 */ "Expire" OpHelp(""),+ /* 168 */ "CursorLock" OpHelp(""),+ /* 169 */ "CursorUnlock" OpHelp(""),+ /* 170 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),+ /* 171 */ "VBegin" OpHelp(""),+ /* 172 */ "VCreate" OpHelp(""),+ /* 173 */ "VDestroy" OpHelp(""),+ /* 174 */ "VOpen" OpHelp(""),+ /* 175 */ "VCheck" OpHelp(""),+ /* 176 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"),+ /* 177 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),+ /* 178 */ "VRename" OpHelp(""),+ /* 179 */ "Pagecount" OpHelp(""),+ /* 180 */ "MaxPgcnt" OpHelp(""),+ /* 181 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"),+ /* 182 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"),+ /* 183 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"),+ /* 184 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"),+ /* 185 */ "Trace" OpHelp(""),+ /* 186 */ "CursorHint" OpHelp(""),+ /* 187 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),+ /* 188 */ "Noop" OpHelp(""),+ /* 189 */ "Explain" OpHelp(""),+ /* 190 */ "Abortable" OpHelp(""),};return azName[i];}@@ -37788,7 +38393,7 @@ static int kvstorageRead(const char*, const char *zKey, char *zBuf, int nBuf);#define KVSTORAGE_KEY_SZ 32/* Expand the key name with an appropriate prefix and put the result-** zKeyOut[]. The zKeyOut[] buffer is assumed to hold at least+** in zKeyOut[]. The zKeyOut[] buffer is assumed to hold at least** KVSTORAGE_KEY_SZ bytes.*/static void kvstorageMakeKey(@@ -37847,10 +38452,12 @@ static int kvstorageDelete(const char *zClass, const char *zKey){**** Return the total number of bytes in the data, without truncation, and** not counting the final zero terminator. Return -1 if the key does-** not exist.+** not exist or its key cannot be read.**-** If nBuf<=0 then this routine simply returns the size of the data without-** actually reading it.+** If nBuf<=0 then this routine simply returns the size of the data+** without actually reading it. Similarly, if nBuf==1 then it+** zero-terminates zBuf at zBuf[0] and returns the size of the data+** without reading it.*/static int kvstorageRead(const char *zClass,@@ -37899,11 +38506,9 @@ static int kvstorageRead(** kvvfs i/o methods with JavaScript implementations in WASM builds.** Maintenance reminder: if this struct changes in any way, the JSON** rendering of its structure must be updated in-** sqlite3_wasm_enum_json(). There are no binary compatibility-** concerns, so it does not need an iVersion member. This file is-** necessarily always compiled together with sqlite3_wasm_enum_json(),-** and JS code dynamically creates the mapping of members based on-** that JSON description.+** sqlite3-wasm.c:sqlite3__wasm_enum_json(). There are no binary+** compatibility concerns, so it does not need an iVersion+** member.*/typedef struct sqlite3_kvvfs_methods sqlite3_kvvfs_methods;struct sqlite3_kvvfs_methods {@@ -37920,8 +38525,8 @@ struct sqlite3_kvvfs_methods {** the compiler can hopefully optimize this level of indirection out.** That said, kvvfs is intended primarily for use in WASM builds.**-** Note that this is not explicitly flagged as static because the-** amalgamation build will tag it with SQLITE_PRIVATE.+** This is not explicitly flagged as static because the amalgamation+** build will tag it with SQLITE_PRIVATE.*/#ifndef SQLITE_WASMconst@@ -38880,6 +39485,7 @@ struct unixFile {#endif#ifdef SQLITE_ENABLE_SETLK_TIMEOUTunsigned iBusyTimeout; /* Wait this many millisec on locks */+ int bBlockOnConnect; /* True to block for SHARED locks */#endif#if OS_VXWORKSstruct vxworksFileId *pId; /* Unique file ID */@@ -39093,10 +39699,11 @@ static struct unix_syscall {#if defined(HAVE_FCHMOD){ "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },+#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)#else{ "fchmod", (sqlite3_syscall_ptr)0, 0 },+#define osFchmod(FID,MODE) 0#endif-#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE{ "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },@@ -39190,6 +39797,119 @@ static struct unix_syscall {}; /* End of the overrideable system calls */+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+/*+** Extract Posix Advisory Locking information about file description fd+** from the /proc/PID/fdinfo/FD pseudo-file. Fill the string buffer a[16]+** with characters to indicate which SQLite-relevant locks are held.+** a[16] will be a 15-character zero-terminated string with the following+** schema:+**+** AAA/B.DDD.DDDDD+**+** Each of character A-D will be "w" or "r" or "-" to indicate either a+** write-lock, a read-lock, or no-lock, respectively. The "." and "/"+** characters are delimiters intended to make the string more easily+** readable by humans. Here are the meaning of the specific letters:+**+** AAA -> The main database locks. PENDING_BYTE, RESERVED_BYTE,+** and SHARED_FIRST, respectively.+**+** B -> The deadman switch lock. Offset 128 of the -shm file.+**+** CCC -> WAL locks: WRITE, CKPT, RECOVER+**+** DDDDD -> WAL read-locks 0 through 5+**+** Note that elements before the "/" apply to the main database file and+** elements after the "/" apply to the -shm file in WAL mode.+**+** Here is another way of thinking about the meaning of the result string:+**+** AAA/B.CCC.DDDDD+** ||| | ||| \___/+** PENDING--'|| | ||| `----- READ 0-5+** RESERVED--'| | ||`---- RECOVER+** SHARED ----' | |`----- CKPT+** DMS ------' `------ WRITE+**+** Return SQLITE_OK on success and SQLITE_ERROR_UNABLE if the /proc+** pseudo-filesystem is unavailable.+*/+static int unixPosixAdvisoryLocks(+ int fd, /* The file descriptor to analyze */+ char a[16] /* Write a text description of PALs here */+){+ int in;+ ssize_t n;+ char *p, *pNext, *x;+ char z[2000];++ /* 1 */+ /* 012 4 678 01234 */+ memcpy(a, "---/-.---.-----", 16);+ sqlite3_snprintf(sizeof(z), z, "/proc/%d/fdinfo/%d", getpid(), fd);+ in = osOpen(z, O_RDONLY, 0);+ if( in<0 ){+ return SQLITE_ERROR_UNABLE;+ }+ n = osRead(in, z, sizeof(z)-1);+ osClose(in);+ if( n<=0 ) return SQLITE_ERROR_UNABLE;+ z[n] = 0;++ /* We are looking for lines that begin with "lock:\t". Examples:+ **+ ** lock: 1: POSIX ADVISORY READ 494716 08:02:5277597 1073741826 1073742335+ ** lock: 1: POSIX ADVISORY WRITE 494716 08:02:5282282 120 120+ ** lock: 2: POSIX ADVISORY READ 494716 08:02:5282282 123 123+ ** lock: 3: POSIX ADVISORY READ 494716 08:02:5282282 128 128+ */+ pNext = strstr(z, "lock:\t");+ while( pNext ){+ char cType = 0;+ sqlite3_int64 iFirst, iLast;+ p = pNext+6;+ pNext = strstr(p, "lock:\t");+ if( pNext ) pNext[-1] = 0;+ if( (x = strstr(p, " READ "))!=0 ){+ cType = 'r';+ x += 6;+ }else if( (x = strstr(p, " WRITE "))!=0 ){+ cType = 'w';+ x += 7;+ }else{+ continue;+ }+ x = strrchr(x, ' ');+ if( x==0 ) continue;+ iLast = strtoll(x+1, 0, 10);+ *x = 0;+ x = strrchr(p, ' ');+ if( x==0 ) continue;+ iFirst = strtoll(x+1, 0, 10);+ if( iLast>=PENDING_BYTE ){+ if( iFirst<=PENDING_BYTE && iLast>=PENDING_BYTE ) a[0] = cType;+ if( iFirst<=PENDING_BYTE+1 && iLast>=PENDING_BYTE+1 ) a[1] = cType;+ if( iFirst<=PENDING_BYTE+2 && iLast>=PENDING_BYTE+510 ) a[2] = cType;+ }else if( iLast<=128 ){+ if( iFirst<=128 && iLast>=128 ) a[4] = cType;+ if( iFirst<=120 && iLast>=120 ) a[6] = cType;+ if( iFirst<=121 && iLast>=121 ) a[7] = cType;+ if( iFirst<=122 && iLast>=122 ) a[8] = cType;+ if( iFirst<=123 && iLast>=123 ) a[10] = cType;+ if( iFirst<=124 && iLast>=124 ) a[11] = cType;+ if( iFirst<=125 && iLast>=125 ) a[12] = cType;+ if( iFirst<=126 && iLast>=126 ) a[13] = cType;+ if( iFirst<=127 && iLast>=127 ) a[14] = cType;+ }+ }+ return SQLITE_OK;+}+#else+# define unixPosixAdvisoryLocks(A,B) SQLITE_ERROR_UNABLE+#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */+/*** On some systems, calls to fchown() will trigger a message in a security** log if they come from non-root processes. So avoid calling fchown() if@@ -39354,9 +40074,8 @@ static int robust_open(const char *z, int f, mode_t m){/*** Helper functions to obtain and relinquish the global mutex. The-** global mutex is used to protect the unixInodeInfo and-** vxworksFileId objects used by this file, all of which may be-** shared by multiple threads.+** global mutex is used to protect the unixInodeInfo objects used by+** this file, all of which may be shared by multiple threads.**** Function unixMutexHeld() is used to assert() that the global mutex** is held when required. This function is only used as part of assert()@@ -39558,6 +40277,7 @@ struct vxworksFileId {** variable:*/static struct vxworksFileId *vxworksFileList = 0;+static sqlite3_mutex *vxworksMutex = 0;/*** Simplify a filename into its canonical form@@ -39623,14 +40343,14 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){** If found, increment the reference count and return a pointer to** the existing file ID.*/- unixEnterMutex();+ sqlite3_mutex_enter(vxworksMutex);for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){if( pCandidate->nName==n&& memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0){sqlite3_free(pNew);pCandidate->nRef++;- unixLeaveMutex();+ sqlite3_mutex_leave(vxworksMutex);return pCandidate;}}@@ -39640,7 +40360,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){pNew->nName = n;pNew->pNext = vxworksFileList;vxworksFileList = pNew;- unixLeaveMutex();+ sqlite3_mutex_leave(vxworksMutex);return pNew;}@@ -39649,7 +40369,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){** the object when the reference count reaches zero.*/static void vxworksReleaseFileId(struct vxworksFileId *pId){- unixEnterMutex();+ sqlite3_mutex_enter(vxworksMutex);assert( pId->nRef>0 );pId->nRef--;if( pId->nRef==0 ){@@ -39659,7 +40379,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){*pp = pId->pNext;sqlite3_free(pId);}- unixLeaveMutex();+ sqlite3_mutex_leave(vxworksMutex);}#endif /* OS_VXWORKS *//*************** End of Unique File ID Utility Used By VxWorks ****************@@ -40047,6 +40767,10 @@ static int findInodeInfo(storeLastErrno(pFile, errno);return SQLITE_IOERR;}+ if( fsync(fd) ){+ storeLastErrno(pFile, errno);+ return SQLITE_IOERR_FSYNC;+ }rc = osFstat(fd, &statbuf);if( rc!=0 ){storeLastErrno(pFile, errno);@@ -40216,18 +40940,42 @@ static int osSetPosixAdvisoryLock(struct flock *pLock, /* The description of the lock */unixFile *pFile /* Structure holding timeout value */){- int tm = pFile->iBusyTimeout;- int rc = osFcntl(h,F_SETLK,pLock);- while( rc<0 && tm>0 ){- /* On systems that support some kind of blocking file lock with a timeout,- ** make appropriate changes here to invoke that blocking file lock. On- ** generic posix, however, there is no such API. So we simply try the- ** lock once every millisecond until either the timeout expires, or until- ** the lock is obtained. */- unixSleep(0,1000);+ int rc = 0;++ if( pFile->iBusyTimeout==0 ){+ /* unixFile->iBusyTimeout is set to 0. In this case, attempt a+ ** non-blocking lock. */+ rc = osFcntl(h,F_SETLK,pLock);+ }else{+ /* unixFile->iBusyTimeout is set to greater than zero. In this case,+ ** attempt a blocking-lock with a unixFile->iBusyTimeout ms timeout.+ **+ ** On systems that support some kind of blocking file lock operation,+ ** this block should be replaced by code to attempt a blocking lock+ ** with a timeout of unixFile->iBusyTimeout ms. The code below is+ ** placeholder code. If SQLITE_TEST is defined, the placeholder code+ ** retries the lock once every 1ms until it succeeds or the timeout+ ** is reached. Or, if SQLITE_TEST is not defined, the placeholder+ ** code attempts a non-blocking lock and sets unixFile->iBusyTimeout+ ** to 0. This causes the caller to return SQLITE_BUSY, instead of+ ** SQLITE_BUSY_TIMEOUT to SQLite - as required by a VFS that does not+ ** support blocking locks.+ */+#ifdef SQLITE_TEST+ int tm = pFile->iBusyTimeout;+ while( tm>0 ){+ rc = osFcntl(h,F_SETLK,pLock);+ if( rc==0 ) break;+ unixSleep(0,1000);+ tm--;+ }+#elserc = osFcntl(h,F_SETLK,pLock);- tm--;+ pFile->iBusyTimeout = 0;+#endif+ /* End of code to replace with real blocking-locks code. */}+return rc;}#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */@@ -40273,11 +41021,25 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){rc = 0;}}else{+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK+ && pLock->l_start==SHARED_FIRST && pLock->l_len==SHARED_SIZE+ ){+ rc = osFcntl(pFile->h, F_SETLKW, pLock);+ }else+#endifrc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);}return rc;}+#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL)+/* Forward reference */+static int unixIsSharingShmNode(unixFile*);+#else+#define unixIsSharingShmNode(pFile) (0)+#endif+/*** Lock the file with the lock specified by parameter eFileLock - one** of the following:@@ -40470,6 +41232,14 @@ static int unixLock(sqlite3_file *id, int eFileLock){/* We are trying for an exclusive lock but another thread in this** same process is still holding a shared lock. */rc = SQLITE_BUSY;+ }else if( unixIsSharingShmNode(pFile) ){+ /* We are in WAL mode and attempting to delete the SHM and WAL+ ** files due to closing the connection or changing out of WAL mode,+ ** but another process still holds locks on the SHM file, thus+ ** indicating that database locks have been broken, perhaps due+ ** to a rogue close(open(dbFile)) or similar.+ */+ rc = SQLITE_BUSY;}else{/* The request was for a RESERVED or EXCLUSIVE lock. It is** assumed that there is a SHARED or greater lock on the file@@ -42561,6 +43331,10 @@ static int unixGetTempname(int nBuf, char *zBuf);#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL)static int unixFcntlExternalReader(unixFile*, int*);#endif+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+ static void unixDescribeShm(sqlite3_str*,unixShm*);+#endif+/*** Information and control of an open file handle.@@ -42634,8 +43408,9 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){#ifdef SQLITE_ENABLE_SETLK_TIMEOUTcase SQLITE_FCNTL_LOCK_TIMEOUT: {int iOld = pFile->iBusyTimeout;+ int iNew = *(int*)pArg;#if SQLITE_ENABLE_SETLK_TIMEOUT==1- pFile->iBusyTimeout = *(int*)pArg;+ pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew;#elif SQLITE_ENABLE_SETLK_TIMEOUT==2pFile->iBusyTimeout = !!(*(int*)pArg);#else@@ -42644,7 +43419,12 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){*(int*)pArg = iOld;return SQLITE_OK;}-#endif+ case SQLITE_FCNTL_BLOCK_ON_CONNECT: {+ int iNew = *(int*)pArg;+ pFile->bBlockOnConnect = iNew;+ return SQLITE_OK;+ }+#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */#if SQLITE_MAX_MMAP_SIZE>0case SQLITE_FCNTL_MMAP_SIZE: {i64 newLimit = *(i64*)pArg;@@ -42697,6 +43477,66 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){return SQLITE_OK;#endif}++#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+ case SQLITE_FCNTL_FILESTAT: {+ sqlite3_str *pStr = (sqlite3_str*)pArg;+ char aLck[16];+ unixInodeInfo *pInode;+ static const char *azLock[] = { "SHARED", "RESERVED",+ "PENDING", "EXCLUSIVE" };+ sqlite3_str_appendf(pStr, "{\"h\":%d", pFile->h);+ sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName);+ if( pFile->eFileLock ){+ sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"",+ azLock[pFile->eFileLock-1]);+ if( unixPosixAdvisoryLocks(pFile->h, aLck)==SQLITE_OK ){+ sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck);+ }+ }+ unixEnterMutex();+ if( pFile->pShm ){+ sqlite3_str_appendall(pStr, ",\"shm\":");+ unixDescribeShm(pStr, pFile->pShm);+ }+#if SQLITE_MAX_MMAP_SIZE>0+ if( pFile->mmapSize ){+ sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize);+ sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut);+ }+#endif+ if( (pInode = pFile->pInode)!=0 ){+ sqlite3_str_appendf(pStr, ",\"inode\":{\"nRef\":%d",pInode->nRef);+ sqlite3_mutex_enter(pInode->pLockMutex);+ sqlite3_str_appendf(pStr, ",\"nShared\":%d", pInode->nShared);+ if( pInode->eFileLock ){+ sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"",+ azLock[pInode->eFileLock-1]);+ }+ if( pInode->pUnused ){+ char cSep = '[';+ UnixUnusedFd *pUFd = pFile->pInode->pUnused;+ sqlite3_str_appendall(pStr, ",\"unusedFd\":");+ while( pUFd ){+ sqlite3_str_appendf(pStr, "%c{\"fd\":%d,\"flags\":%d",+ cSep, pUFd->fd, pUFd->flags);+ cSep = ',';+ if( unixPosixAdvisoryLocks(pUFd->fd, aLck)==SQLITE_OK ){+ sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck);+ }+ sqlite3_str_append(pStr, "}", 1);+ pUFd = pUFd->pNext;+ }+ sqlite3_str_append(pStr, "]", 1);+ }+ sqlite3_mutex_leave(pInode->pLockMutex);+ sqlite3_str_append(pStr, "}", 1);+ }+ unixLeaveMutex();+ sqlite3_str_append(pStr, "}", 1);+ return SQLITE_OK;+ }+#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */}return SQLITE_NOTFOUND;}@@ -42963,6 +43803,26 @@ struct unixShm {#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+/*+** Describe the pShm object using JSON. Used for diagnostics only.+*/+static void unixDescribeShm(sqlite3_str *pStr, unixShm *pShm){+ unixShmNode *pNode = pShm->pShmNode;+ char aLck[16];+ sqlite3_str_appendf(pStr, "{\"h\":%d", pNode->hShm);+ assert( unixMutexHeld() );+ sqlite3_str_appendf(pStr, ",\"nRef\":%d", pNode->nRef);+ sqlite3_str_appendf(pStr, ",\"id\":%d", pShm->id);+ sqlite3_str_appendf(pStr, ",\"sharedMask\":%d", pShm->sharedMask);+ sqlite3_str_appendf(pStr, ",\"exclMask\":%d", pShm->exclMask);+ if( unixPosixAdvisoryLocks(pNode->hShm, aLck)==SQLITE_OK ){+ sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck);+ }+ sqlite3_str_append(pStr, "}", 1);+}+#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */+/*** Use F_GETLK to check whether or not there are any readers with open** wal-mode transactions in other processes on database file pFile. If@@ -42996,6 +43856,44 @@ static int unixFcntlExternalReader(unixFile *pFile, int *piOut){return rc;}+/*+** If pFile has a -shm file open and it is sharing that file with some+** other connection, either in the same process or in a separate process,+** then return true. Return false if either pFile does not have a -shm+** file open or if it is the only connection to that -shm file across the+** entire system.+**+** This routine is not required for correct operation. It can always return+** false and SQLite will continue to operate according to spec. However,+** when this routine does its job, it adds extra robustness in cases+** where database file locks have been erroneously deleted in a WAL-mode+** database by doing close(open(DATABASE_PATHNAME)) or similar.+**+** With false negatives, SQLite still operates to spec, though with less+** robustness. With false positives, the last database connection on a+** WAL-mode database will fail to unlink the -wal and -shm files, which+** is annoying but harmless. False positives will also prevent a database+** connection from running "PRAGMA journal_mode=DELETE" in order to take+** the database out of WAL mode, which is perhaps more serious, but is+** still not a disaster.+*/+static int unixIsSharingShmNode(unixFile *pFile){+ unixShmNode *pShmNode;+ struct flock lock;+ if( pFile->pShm==0 ) return 0;+ if( pFile->ctrlFlags & UNIXFILE_EXCL ) return 0;+ pShmNode = pFile->pShm->pShmNode;+#if SQLITE_ATOMIC_INTRINSICS+ assert( AtomicLoad(&pShmNode->nRef)==1 );+#endif+ memset(&lock, 0, sizeof(lock));+ lock.l_whence = SEEK_SET;+ lock.l_start = UNIX_SHM_DMS;+ lock.l_len = 1;+ lock.l_type = F_WRLCK;+ osFcntl(pShmNode->hShm, F_GETLK, &lock);+ return (lock.l_type!=F_UNLCK);+}/*** Apply posix advisory locks for all bytes from ofst through ofst+n-1.@@ -43041,7 +43939,8 @@ static int unixShmSystemLock(/* Locks are within range */assert( n>=1 && n<=SQLITE_SHM_NLOCK );- assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) );+ assert( ofst>=UNIX_SHM_BASE && ofst<=UNIX_SHM_DMS );+ assert( ofst+n-1<=UNIX_SHM_DMS );if( pShmNode->hShm>=0 ){int res;@@ -43573,7 +44472,7 @@ static int assertLockingArrayOk(unixShmNode *pShmNode){return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);#endif}-#endif+#endif /* !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) *//*** Change the lock state for a shared-memory segment.@@ -43617,21 +44516,20 @@ static int unixShmLock(/* Check that, if this to be a blocking lock, no locks that occur later** in the following list than the lock being obtained are already held:**- ** 1. Checkpointer lock (ofst==1).- ** 2. Write lock (ofst==0).- ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).+ ** 1. Recovery lock (ofst==2).+ ** 2. Checkpointer lock (ofst==1).+ ** 3. Write lock (ofst==0).+ ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).**** In other words, if this is a blocking lock, none of the locks that** occur later in the above list than the lock being obtained may be** held.- **- ** It is not permitted to block on the RECOVER lock.*/-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG){u16 lockMask = (p->exclMask|p->sharedMask);assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (- (ofst!=2) /* not RECOVER */+ (ofst!=2 || lockMask==0)&& (ofst!=1 || lockMask==0 || lockMask==2)&& (ofst!=0 || lockMask<3)&& (ofst<3 || lockMask<(1<<ofst))@@ -44536,10 +45434,17 @@ static int fillInUnixFile(storeLastErrno(pNew, 0);#if OS_VXWORKSif( rc!=SQLITE_OK ){- if( h>=0 ) robust_close(pNew, h, __LINE__);- h = -1;- osUnlink(zFilename);- pNew->ctrlFlags |= UNIXFILE_DELETE;+ if( h>=0 ){+ robust_close(pNew, h, __LINE__);+ h = -1;+ }+ if( pNew->ctrlFlags & UNIXFILE_DELETE ){+ osUnlink(zFilename);+ }+ if( pNew->pId ){+ vxworksReleaseFileId(pNew->pId);+ pNew->pId = 0;+ }}#endifif( rc!=SQLITE_OK ){@@ -44583,6 +45488,9 @@ static const char *unixTempFileDir(void){while(1){if( zDir!=0+#if OS_VXWORKS+ && zDir[0]=='/'+#endif&& osStat(zDir, &buf)==0&& S_ISDIR(buf.st_mode)&& osAccess(zDir, 03)==0@@ -44897,6 +45805,12 @@ static int unixOpen(|| eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL);+#if OS_VXWORKS+ /* The file-ID mechanism used in Vxworks requires that all pathnames+ ** provided to unixOpen must be absolute pathnames. */+ if( zPath!=0 && zPath[0]!='/' ){ return SQLITE_CANTOPEN; }+#endif+/* Detect a pid change and reset the PRNG. There is a race condition** here such that two or more threads all trying to open databases at** the same instant might all reset the PRNG. But multiple resets@@ -45097,8 +46011,11 @@ static int unixOpen(}#endif- assert( zPath==0 || zPath[0]=='/'- || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL+ assert( zPath==0+ || zPath[0]=='/'+ || eType==SQLITE_OPEN_SUPER_JOURNAL+ || eType==SQLITE_OPEN_MAIN_JOURNAL+ || eType==SQLITE_OPEN_TEMP_JOURNAL);rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);@@ -45436,7 +46353,7 @@ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){/* Almost all modern unix systems support nanosleep(). But if you are** compiling for one of the rare exceptions, you can use- ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if+ ** -DHAVE_NANOSLEEP=0 (perhaps in conjunction with -DHAVE_USLEEP if** usleep() is available) in order to bypass the use of nanosleep() */nanosleep(&sp, NULL);@@ -46827,6 +47744,9 @@ SQLITE_API int sqlite3_os_init(void){sqlite3KvvfsInit();#endifunixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);+#if OS_VXWORKS+ vxworksMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS2);+#endif#ifndef SQLITE_OMIT_WAL/* Validate lock assumptions */@@ -46861,6 +47781,9 @@ SQLITE_API int sqlite3_os_init(void){*/SQLITE_API int sqlite3_os_end(void){unixBigLock = 0;+#if OS_VXWORKS+ vxworksMutex = 0;+#endifreturn SQLITE_OK;}@@ -47157,8 +48080,18 @@ struct winFile {sqlite3_int64 mmapSize; /* Size of mapped region */sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */#endif+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ DWORD iBusyTimeout; /* Wait this many millisec on locks */+ int bBlockOnConnect;+#endif};+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+# define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout+#else+# define winFileBusyTimeout(pDbFd) 0+#endif+/*** The winVfsAppData structure is used for the pAppData member for all of the** Win32 VFS variants.@@ -47477,7 +48410,7 @@ static struct win_syscall {{ "FileTimeToLocalFileTime", (SYSCALL)0, 0 },#endif-#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \+#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(const FILETIME*, \LPFILETIME))aSyscall[11].pCurrent)#if SQLITE_OS_WINCE@@ -47486,7 +48419,7 @@ static struct win_syscall {{ "FileTimeToSystemTime", (SYSCALL)0, 0 },#endif-#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \+#define osFileTimeToSystemTime ((BOOL(WINAPI*)(const FILETIME*, \LPSYSTEMTIME))aSyscall[12].pCurrent){ "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },@@ -47592,6 +48525,12 @@ static struct win_syscall {#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \LPWSTR*))aSyscall[25].pCurrent)+/*+** For GetLastError(), MSDN says:+**+** Minimum supported client: Windows XP [desktop apps | UWP apps]+** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]+*/{ "GetLastError", (SYSCALL)GetLastError, 0 },#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)@@ -47760,7 +48699,7 @@ static struct win_syscall {{ "LockFile", (SYSCALL)0, 0 },#endif-#ifndef osLockFile+#if !defined(osLockFile) && defined(SQLITE_WIN32_HAS_ANSI)#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \DWORD))aSyscall[47].pCurrent)#endif@@ -47824,7 +48763,7 @@ static struct win_syscall {{ "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },-#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \+#define osSystemTimeToFileTime ((BOOL(WINAPI*)(const SYSTEMTIME*, \LPFILETIME))aSyscall[56].pCurrent)#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT@@ -47833,7 +48772,7 @@ static struct win_syscall {{ "UnlockFile", (SYSCALL)0, 0 },#endif-#ifndef osUnlockFile+#if !defined(osUnlockFile) && defined(SQLITE_WIN32_HAS_ANSI)#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \DWORD))aSyscall[57].pCurrent)#endif@@ -47874,11 +48813,13 @@ static struct win_syscall {#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \DWORD,DWORD))aSyscall[62].pCurrent)-#if !SQLITE_OS_WINRT+/*+** For WaitForSingleObject(), MSDN says:+**+** Minimum supported client: Windows XP [desktop apps | UWP apps]+** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]+*/{ "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },-#else- { "WaitForSingleObject", (SYSCALL)0, 0 },-#endif#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \DWORD))aSyscall[63].pCurrent)@@ -48025,6 +48966,97 @@ static struct win_syscall {#define osFlushViewOfFile \((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)+/*+** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CreateEvent()+** to implement blocking locks with timeouts. MSDN says:+**+** Minimum supported client: Windows XP [desktop apps | UWP apps]+** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]+*/+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ { "CreateEvent", (SYSCALL)CreateEvent, 0 },+#else+ { "CreateEvent", (SYSCALL)0, 0 },+#endif++#define osCreateEvent ( \+ (HANDLE(WINAPI*) (LPSECURITY_ATTRIBUTES,BOOL,BOOL,LPCSTR)) \+ aSyscall[80].pCurrent \+)++/*+** If SQLITE_ENABLE_SETLK_TIMEOUT is defined, we require CancelIo()+** for the case where a timeout expires and a lock request must be+** cancelled.+**+** Minimum supported client: Windows XP [desktop apps | UWP apps]+** Minimum supported server: Windows Server 2003 [desktop apps | UWP apps]+*/+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ { "CancelIo", (SYSCALL)CancelIo, 0 },+#else+ { "CancelIo", (SYSCALL)0, 0 },+#endif++#define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[81].pCurrent)++#if defined(SQLITE_WIN32_HAS_WIDE) && defined(_WIN32)+ { "GetModuleHandleW", (SYSCALL)GetModuleHandleW, 0 },+#else+ { "GetModuleHandleW", (SYSCALL)0, 0 },+#endif++#define osGetModuleHandleW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[82].pCurrent)++#ifndef _WIN32+ { "getenv", (SYSCALL)getenv, 0 },+#else+ { "getenv", (SYSCALL)0, 0 },+#endif++#define osGetenv ((const char *(*)(const char *))aSyscall[83].pCurrent)++#ifndef _WIN32+ { "getcwd", (SYSCALL)getcwd, 0 },+#else+ { "getcwd", (SYSCALL)0, 0 },+#endif++#define osGetcwd ((char*(*)(char*,size_t))aSyscall[84].pCurrent)++#ifndef _WIN32+ { "readlink", (SYSCALL)readlink, 0 },+#else+ { "readlink", (SYSCALL)0, 0 },+#endif++#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[85].pCurrent)++#ifndef _WIN32+ { "lstat", (SYSCALL)lstat, 0 },+#else+ { "lstat", (SYSCALL)0, 0 },+#endif++#define osLstat ((int(*)(const char*,struct stat*))aSyscall[86].pCurrent)++#ifndef _WIN32+ { "__errno", (SYSCALL)__errno, 0 },+#else+ { "__errno", (SYSCALL)0, 0 },+#endif++#define osErrno (*((int*(*)(void))aSyscall[87].pCurrent)())++#ifndef _WIN32+ { "cygwin_conv_path", (SYSCALL)cygwin_conv_path, 0 },+#else+ { "cygwin_conv_path", (SYSCALL)0, 0 },+#endif++#define osCygwin_conv_path ((size_t(*)(unsigned int, \+ const void *, void *, size_t))aSyscall[88].pCurrent)+}; /* End of the overrideable system calls *//*@@ -48198,6 +49230,7 @@ SQLITE_API int sqlite3_win32_reset_heap(){}#endif /* SQLITE_WIN32_MALLOC */+#ifdef _WIN32/*** This function outputs the specified (ANSI) string to the Win32 debugger** (if available).@@ -48240,6 +49273,7 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){}#endif}+#endif /* _WIN32 *//*** The following routine suspends the current thread for at least ms@@ -48323,7 +49357,9 @@ SQLITE_API int sqlite3_win32_is_nt(void){}return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;#elif SQLITE_TEST- return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;+ return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2+ || osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0+ ;#else/*** NOTE: All sub-platforms where the GetVersionEx[AW] functions are@@ -48538,6 +49574,7 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){}#endif /* SQLITE_WIN32_MALLOC */+#ifdef _WIN32/*** Convert a UTF-8 string to Microsoft Unicode.**@@ -48563,6 +49600,7 @@ static LPWSTR winUtf8ToUnicode(const char *zText){}return zWideText;}+#endif /* _WIN32 *//*** Convert a Microsoft Unicode string to UTF-8.@@ -48597,28 +49635,29 @@ static char *winUnicodeToUtf8(LPCWSTR zWideText){** Space to hold the returned string is obtained from sqlite3_malloc().*/static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){- int nByte;+ int nWideChar;LPWSTR zMbcsText;int codepage = useAnsi ? CP_ACP : CP_OEMCP;- nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,- 0)*sizeof(WCHAR);- if( nByte==0 ){+ nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,+ 0);+ if( nWideChar==0 ){return 0;}- zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );+ zMbcsText = sqlite3MallocZero( nWideChar*sizeof(WCHAR) );if( zMbcsText==0 ){return 0;}- nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,- nByte);- if( nByte==0 ){+ nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,+ nWideChar);+ if( nWideChar==0 ){sqlite3_free(zMbcsText);zMbcsText = 0;}return zMbcsText;}+#ifdef _WIN32/*** Convert a Microsoft Unicode string to a multi-byte character string,** using the ANSI or OEM code page.@@ -48646,6 +49685,7 @@ static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){}return zText;}+#endif /* _WIN32 *//*** Convert a multi-byte character string to UTF-8.@@ -48665,6 +49705,7 @@ static char *winMbcsToUtf8(const char *zText, int useAnsi){return zTextUtf8;}+#ifdef _WIN32/*** Convert a UTF-8 string to a multi-byte character string.**@@ -48714,6 +49755,7 @@ SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){#endifreturn winUnicodeToUtf8(zWideText);}+#endif /* _WIN32 *//*** This is a public wrapper for the winMbcsToUtf8() function.@@ -48731,6 +49773,7 @@ SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){return winMbcsToUtf8(zText, osAreFileApisANSI());}+#ifdef _WIN32/*** This is a public wrapper for the winMbcsToUtf8() function.*/@@ -48855,6 +49898,7 @@ SQLITE_API int sqlite3_win32_set_directory(){return sqlite3_win32_set_directory16(type, zValue);}+#endif /* _WIN32 *//*** The return value of winGetLastErrorMsg@@ -49403,13 +50447,100 @@ static BOOL winLockFile(ovlp.Offset = offsetLow;ovlp.OffsetHigh = offsetHigh;return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);+#ifdef SQLITE_WIN32_HAS_ANSI}else{return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,numBytesHigh);+#endif}#endif}+#ifndef SQLITE_OMIT_WAL+/*+** Lock a region of nByte bytes starting at offset offset of file hFile.+** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock+** otherwise. If nMs is greater than zero and the lock cannot be obtained+** immediately, block for that many ms before giving up.+**+** This function returns SQLITE_OK if the lock is obtained successfully. If+** some other process holds the lock, SQLITE_BUSY is returned if nMs==0, or+** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR.+*/+static int winHandleLockTimeout(+ HANDLE hFile,+ DWORD offset,+ DWORD nByte,+ int bExcl,+ DWORD nMs+){+ DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (bExcl?LOCKFILE_EXCLUSIVE_LOCK:0);+ int rc = SQLITE_OK;+ BOOL ret;++ if( !osIsNT() ){+ ret = winLockFile(&hFile, flags, offset, 0, nByte, 0);+ }else{+ OVERLAPPED ovlp;+ memset(&ovlp, 0, sizeof(OVERLAPPED));+ ovlp.Offset = offset;++#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ if( nMs!=0 ){+ flags &= ~LOCKFILE_FAIL_IMMEDIATELY;+ }+ ovlp.hEvent = osCreateEvent(NULL, TRUE, FALSE, NULL);+ if( ovlp.hEvent==NULL ){+ return SQLITE_IOERR_LOCK;+ }+#endif++ ret = osLockFileEx(hFile, flags, 0, nByte, 0, &ovlp);++#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was+ ** opened with FILE_FLAG_OVERHEAD specified. In this case, the call to+ ** LockFileEx() may fail because the request is still pending. This can+ ** happen even if LOCKFILE_FAIL_IMMEDIATELY was specified.+ **+ ** If nMs is 0, then LOCKFILE_FAIL_IMMEDIATELY was set in the flags+ ** passed to LockFileEx(). In this case, if the operation is pending,+ ** block indefinitely until it is finished.+ **+ ** Otherwise, wait for up to nMs ms for the operation to finish. nMs+ ** may be set to INFINITE.+ */+ if( !ret && GetLastError()==ERROR_IO_PENDING ){+ DWORD nDelay = (nMs==0 ? INFINITE : nMs);+ DWORD res = osWaitForSingleObject(ovlp.hEvent, nDelay);+ if( res==WAIT_OBJECT_0 ){+ ret = TRUE;+ }else if( res==WAIT_TIMEOUT ){+#if SQLITE_ENABLE_SETLK_TIMEOUT==1+ rc = SQLITE_BUSY_TIMEOUT;+#else+ rc = SQLITE_BUSY;+#endif+ }else{+ /* Some other error has occurred */+ rc = SQLITE_IOERR_LOCK;+ }++ /* If it is still pending, cancel the LockFileEx() call. */+ osCancelIo(hFile);+ }++ osCloseHandle(ovlp.hEvent);+#endif+ }++ if( rc==SQLITE_OK && !ret ){+ rc = SQLITE_BUSY;+ }+ return rc;+}+#endif /* #ifndef SQLITE_OMIT_WAL */+/*** Unlock a file region.*/@@ -49434,13 +50565,25 @@ static BOOL winUnlockFile(ovlp.Offset = offsetLow;ovlp.OffsetHigh = offsetHigh;return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);+#ifdef SQLITE_WIN32_HAS_ANSI}else{return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,numBytesHigh);+#endif}#endif}+#ifndef SQLITE_OMIT_WAL+/*+** Remove an nByte lock starting at offset iOff from HANDLE h.+*/+static int winHandleUnlock(HANDLE h, int iOff, int nByte){+ BOOL ret = winUnlockFile(&h, iOff, 0, nByte, 0);+ return (ret ? SQLITE_OK : SQLITE_IOERR_UNLOCK);+}+#endif+/******************************************************************************* The next group of routines implement the I/O methods specified** by the sqlite3_io_methods object.@@ -49454,66 +50597,70 @@ static BOOL winUnlockFile(#endif/*-** Move the current position of the file handle passed as the first-** argument to offset iOffset within the file. If successful, return 0.-** Otherwise, set pFile->lastErrno and return non-zero.+** Seek the file handle h to offset nByte of the file.+**+** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite+** error code.*/-static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){+static int winHandleSeek(HANDLE h, sqlite3_int64 iOffset){+ int rc = SQLITE_OK; /* Return value */+#if !SQLITE_OS_WINRTLONG upperBits; /* Most sig. 32 bits of new offset */LONG lowerBits; /* Least sig. 32 bits of new offset */DWORD dwRet; /* Value returned by SetFilePointer() */- DWORD lastErrno; /* Value returned by GetLastError() */-- OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));upperBits = (LONG)((iOffset>>32) & 0x7fffffff);lowerBits = (LONG)(iOffset & 0xffffffff);+ dwRet = osSetFilePointer(h, lowerBits, &upperBits, FILE_BEGIN);+/* API oddity: If successful, SetFilePointer() returns a dword** containing the lower 32-bits of the new file-offset. Or, if it fails,** it returns INVALID_SET_FILE_POINTER. However according to MSDN,** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine** whether an error has actually occurred, it is also necessary to call- ** GetLastError().- */- dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);-- if( (dwRet==INVALID_SET_FILE_POINTER- && ((lastErrno = osGetLastError())!=NO_ERROR)) ){- pFile->lastErrno = lastErrno;- winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,- "winSeekFile", pFile->zPath);- OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));- return 1;+ ** GetLastError(). */+ if( dwRet==INVALID_SET_FILE_POINTER ){+ DWORD lastErrno = osGetLastError();+ if( lastErrno!=NO_ERROR ){+ rc = SQLITE_IOERR_SEEK;+ }}-- OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));- return 0;#else- /*- ** Same as above, except that this implementation works for WinRT.- */-+ /* This implementation works for WinRT. */LARGE_INTEGER x; /* The new offset */BOOL bRet; /* Value returned by SetFilePointerEx() */x.QuadPart = iOffset;- bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);+ bRet = osSetFilePointerEx(h, x, 0, FILE_BEGIN);if(!bRet){- pFile->lastErrno = osGetLastError();- winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,- "winSeekFile", pFile->zPath);- OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));- return 1;+ rc = SQLITE_IOERR_SEEK;}-- OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));- return 0;#endif++ OSTRACE(("SEEK file=%p, offset=%lld rc=%s\n", h, iOffset, sqlite3ErrName(rc)));+ return rc;+}++/*+** Move the current position of the file handle passed as the first+** argument to offset iOffset within the file. If successful, return 0.+** Otherwise, set pFile->lastErrno and return non-zero.+*/+static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){+ int rc;++ rc = winHandleSeek(pFile->h, iOffset);+ if( rc!=SQLITE_OK ){+ pFile->lastErrno = osGetLastError();+ winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath);+ }+ return rc;}+#if SQLITE_MAX_MMAP_SIZE>0/* Forward references to VFS helper methods used for memory mapped files */static int winMapfile(winFile*, sqlite3_int64);@@ -49773,6 +50920,62 @@ static int winWrite(return SQLITE_OK;}+#ifndef SQLITE_OMIT_WAL+/*+** Truncate the file opened by handle h to nByte bytes in size.+*/+static int winHandleTruncate(HANDLE h, sqlite3_int64 nByte){+ int rc = SQLITE_OK; /* Return code */+ rc = winHandleSeek(h, nByte);+ if( rc==SQLITE_OK ){+ if( 0==osSetEndOfFile(h) ){+ rc = SQLITE_IOERR_TRUNCATE;+ }+ }+ return rc;+}++/*+** Determine the size in bytes of the file opened by the handle passed as+** the first argument.+*/+static int winHandleSize(HANDLE h, sqlite3_int64 *pnByte){+ int rc = SQLITE_OK;++#if SQLITE_OS_WINRT+ FILE_STANDARD_INFO info;+ BOOL b;+ b = osGetFileInformationByHandleEx(h, FileStandardInfo, &info, sizeof(info));+ if( b ){+ *pnByte = info.EndOfFile.QuadPart;+ }else{+ rc = SQLITE_IOERR_FSTAT;+ }+#else+ DWORD upperBits = 0;+ DWORD lowerBits = 0;++ assert( pnByte );+ lowerBits = osGetFileSize(h, &upperBits);+ *pnByte = (((sqlite3_int64)upperBits)<<32) + lowerBits;+ if( lowerBits==INVALID_FILE_SIZE && osGetLastError()!=NO_ERROR ){+ rc = SQLITE_IOERR_FSTAT;+ }+#endif++ return rc;+}++/*+** Close the handle passed as the only argument.+*/+static void winHandleClose(HANDLE h){+ if( h!=INVALID_HANDLE_VALUE ){+ osCloseHandle(h);+ }+}+#endif /* #ifndef SQLITE_OMIT_WAL */+/*** Truncate an open file to a specified size*/@@ -50028,8 +51231,9 @@ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){** Different API routines are called depending on whether or not this** is Win9x or WinNT.*/-static int winGetReadLock(winFile *pFile){+static int winGetReadLock(winFile *pFile, int bBlock){int res;+ DWORD mask = ~(bBlock ? LOCKFILE_FAIL_IMMEDIATELY : 0);OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));if( osIsNT() ){#if SQLITE_OS_WINCE@@ -50039,7 +51243,7 @@ static int winGetReadLock(winFile *pFile){*/res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);#else- res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,+ res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST, 0,SHARED_SIZE, 0);#endif}@@ -50048,7 +51252,7 @@ static int winGetReadLock(winFile *pFile){int lk;sqlite3_randomness(sizeof(lk), &lk);pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));- res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,+ res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS&mask,SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);}#endif@@ -50143,46 +51347,62 @@ static int winLock(sqlite3_file *id, int locktype){assert( locktype!=PENDING_LOCK );assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );- /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or+ /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of** the PENDING_LOCK byte is temporary.*/newLocktype = pFile->locktype;- if( pFile->locktype==NO_LOCK- || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)+ if( locktype==SHARED_LOCK+ || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)){int cnt = 3;- while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,- PENDING_BYTE, 0, 1, 0))==0 ){++ /* Flags for the LockFileEx() call. This should be an exclusive lock if+ ** this call is to obtain EXCLUSIVE, or a shared lock if this call is to+ ** obtain SHARED. */+ int flags = LOCKFILE_FAIL_IMMEDIATELY;+ if( locktype==EXCLUSIVE_LOCK ){+ flags |= LOCKFILE_EXCLUSIVE_LOCK;+ }+ while( cnt>0 ){/* Try 3 times to get the pending lock. This is needed to work** around problems caused by indexing and/or anti-virus software on** Windows systems.+ **** If you are using this code as a model for alternative VFSes, do not- ** copy this retry logic. It is a hack intended for Windows only.- */+ ** copy this retry logic. It is a hack intended for Windows only. */+ res = winLockFile(&pFile->h, flags, PENDING_BYTE, 0, 1, 0);+ if( res ) break;+lastErrno = osGetLastError();OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",- pFile->h, cnt, res));+ pFile->h, cnt, res+ ));+if( lastErrno==ERROR_INVALID_HANDLE ){pFile->lastErrno = lastErrno;rc = SQLITE_IOERR_LOCK;OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",- pFile->h, cnt, sqlite3ErrName(rc)));+ pFile->h, cnt, sqlite3ErrName(rc)+ ));return rc;}- if( cnt ) sqlite3_win32_sleep(1);++ cnt--;+ if( cnt>0 ) sqlite3_win32_sleep(1);}gotPendingLock = res;- if( !res ){- lastErrno = osGetLastError();- }}/* Acquire a shared lock*/if( locktype==SHARED_LOCK && res ){assert( pFile->locktype==NO_LOCK );- res = winGetReadLock(pFile);+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ res = winGetReadLock(pFile, pFile->bBlockOnConnect);+#else+ res = winGetReadLock(pFile, 0);+#endifif( res ){newLocktype = SHARED_LOCK;}else{@@ -50220,7 +51440,7 @@ static int winLock(sqlite3_file *id, int locktype){newLocktype = EXCLUSIVE_LOCK;}else{lastErrno = osGetLastError();- winGetReadLock(pFile);+ winGetReadLock(pFile, 0);}}@@ -50300,7 +51520,7 @@ static int winUnlock(sqlite3_file *id, int locktype){type = pFile->locktype;if( type>=EXCLUSIVE_LOCK ){winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);- if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){+ if( locktype==SHARED_LOCK && !winGetReadLock(pFile, 0) ){/* This should never happen. We should always be able to** reacquire the read lock */rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),@@ -50510,6 +51730,50 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){return rc;}#endif++#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ case SQLITE_FCNTL_LOCK_TIMEOUT: {+ int iOld = pFile->iBusyTimeout;+ int iNew = *(int*)pArg;+#if SQLITE_ENABLE_SETLK_TIMEOUT==1+ pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew;+#elif SQLITE_ENABLE_SETLK_TIMEOUT==2+ pFile->iBusyTimeout = (DWORD)(!!iNew);+#else+# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2"+#endif+ *(int*)pArg = iOld;+ return SQLITE_OK;+ }+ case SQLITE_FCNTL_BLOCK_ON_CONNECT: {+ int iNew = *(int*)pArg;+ pFile->bBlockOnConnect = iNew;+ return SQLITE_OK;+ }+#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */++#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+ case SQLITE_FCNTL_FILESTAT: {+ sqlite3_str *pStr = (sqlite3_str*)pArg;+ sqlite3_str_appendf(pStr, "{\"h\":%llu", (sqlite3_uint64)pFile->h);+ sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName);+ if( pFile->locktype ){+ static const char *azLock[] = { "SHARED", "RESERVED",+ "PENDING", "EXCLUSIVE" };+ sqlite3_str_appendf(pStr, ",\"locktype\":\"%s\"",+ azLock[pFile->locktype-1]);+ }+#if SQLITE_MAX_MMAP_SIZE>0+ if( pFile->mmapSize ){+ sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize);+ sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut);+ }+#endif+ sqlite3_str_append(pStr, "}", 1);+ return SQLITE_OK;+ }+#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */+}OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));return SQLITE_NOTFOUND;@@ -50547,6 +51811,103 @@ static int winDeviceCharacteristics(sqlite3_file *id){*/static SYSTEM_INFO winSysInfo;+/*+** Convert a UTF-8 filename into whatever form the underlying+** operating system wants filenames in. Space to hold the result+** is obtained from malloc and must be freed by the calling+** function+**+** On Cygwin, 3 possible input forms are accepted:+** - If the filename starts with "<drive>:/" or "<drive>:\",+** it is converted to UTF-16 as-is.+** - If the filename contains '/', it is assumed to be a+** Cygwin absolute path, it is converted to a win32+** absolute path in UTF-16.+** - Otherwise it must be a filename only, the win32 filename+** is returned in UTF-16.+** Note: If the function cygwin_conv_path() fails, only+** UTF-8 -> UTF-16 conversion will be done. This can only+** happen when the file path >32k, in which case winUtf8ToUnicode()+** will fail too.+*/+static void *winConvertFromUtf8Filename(const char *zFilename){+ void *zConverted = 0;+ if( osIsNT() ){+#ifdef __CYGWIN__+ int nChar;+ LPWSTR zWideFilename;++ if( osCygwin_conv_path && !(winIsDriveLetterAndColon(zFilename)+ && winIsDirSep(zFilename[2])) ){+ i64 nByte;+ int convertflag = CCP_POSIX_TO_WIN_W;+ if( !strchr(zFilename, '/') ) convertflag |= CCP_RELATIVE;+ nByte = (i64)osCygwin_conv_path(convertflag,+ zFilename, 0, 0);+ if( nByte>0 ){+ zConverted = sqlite3MallocZero(12+(u64)nByte);+ if ( zConverted==0 ){+ return zConverted;+ }+ zWideFilename = zConverted;+ /* Filenames should be prefixed, except when converted+ * full path already starts with "\\?\". */+ if( osCygwin_conv_path(convertflag, zFilename,+ zWideFilename+4, nByte)==0 ){+ if( (convertflag&CCP_RELATIVE) ){+ memmove(zWideFilename, zWideFilename+4, nByte);+ }else if( memcmp(zWideFilename+4, L"\\\\", 4) ){+ memcpy(zWideFilename, L"\\\\?\\", 8);+ }else if( zWideFilename[6]!='?' ){+ memmove(zWideFilename+6, zWideFilename+4, nByte);+ memcpy(zWideFilename, L"\\\\?\\UNC", 14);+ }else{+ memmove(zWideFilename, zWideFilename+4, nByte);+ }+ return zConverted;+ }+ sqlite3_free(zConverted);+ }+ }+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);+ if( nChar==0 ){+ return 0;+ }+ zWideFilename = sqlite3MallocZero( nChar*sizeof(WCHAR)+12 );+ if( zWideFilename==0 ){+ return 0;+ }+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1,+ zWideFilename, nChar);+ if( nChar==0 ){+ sqlite3_free(zWideFilename);+ zWideFilename = 0;+ }else if( nChar>MAX_PATH+ && winIsDriveLetterAndColon(zFilename)+ && winIsDirSep(zFilename[2]) ){+ memmove(zWideFilename+4, zWideFilename, nChar*sizeof(WCHAR));+ zWideFilename[2] = '\\';+ memcpy(zWideFilename, L"\\\\?\\", 8);+ }else if( nChar>MAX_PATH+ && winIsDirSep(zFilename[0]) && winIsDirSep(zFilename[1])+ && zFilename[2] != '?' ){+ memmove(zWideFilename+6, zWideFilename, nChar*sizeof(WCHAR));+ memcpy(zWideFilename, L"\\\\?\\UNC", 14);+ }+ zConverted = zWideFilename;+#else+ zConverted = winUtf8ToUnicode(zFilename);+#endif /* __CYGWIN__ */+ }+#if defined(SQLITE_WIN32_HAS_ANSI) && defined(_WIN32)+ else{+ zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());+ }+#endif+ /* caller will handle out of memory */+ return zConverted;+}+#ifndef SQLITE_OMIT_WAL/*@@ -50583,30 +51944,40 @@ static int winShmMutexHeld(void) {** log-summary is opened only once per process.**** winShmMutexHeld() must be true when creating or destroying-** this object or while reading or writing the following fields:+** this object, or while editing the global linked list that starts+** at winShmNodeList.**-** nRef-** pNext+** When reading or writing the linked list starting at winShmNode.pWinShmList,+** pShmNode->mutex must be held.**-** The following fields are read-only after the object is created:+** The following fields are constant after the object is created:**-** fid** zFilename+** hSharedShm+** mutex+** bUseSharedLockHandle**-** Either winShmNode.mutex must be held or winShmNode.nRef==0 and+** Either winShmNode.mutex must be held or winShmNode.pWinShmList==0 and** winShmMutexHeld() is true when reading or writing any other field** in this structure.**+** File-handle hSharedShm is always used to (a) take the DMS lock, (b)+** truncate the *-shm file if the DMS-locking protocol demands it, and+** (c) map regions of the *-shm file into memory using MapViewOfFile()+** or similar. If bUseSharedLockHandle is true, then other locks are also+** taken on hSharedShm. Or, if bUseSharedLockHandle is false, then other+** locks are taken using each connection's winShm.hShm handles.*/struct winShmNode {sqlite3_mutex *mutex; /* Mutex to access this object */char *zFilename; /* Name of the file */- winFile hFile; /* File handle from winOpen */+ HANDLE hSharedShm; /* File handle open on zFilename */+ int bUseSharedLockHandle; /* True to use hSharedShm for everything */+ int isUnlocked; /* DMS lock has not yet been obtained */+ int isReadonly; /* True if read-only */int szRegion; /* Size of shared-memory regions */int nRegion; /* Size of array apRegion */- u8 isReadonly; /* True if read-only */- u8 isUnlocked; /* True if no DMS lock held */struct ShmRegion {HANDLE hMap; /* File handle from CreateFileMapping */@@ -50614,8 +51985,8 @@ struct winShmNode {} *aRegion;DWORD lastErrno; /* The Windows errno from the last I/O error */- int nRef; /* Number of winShm objects pointing to this */- winShm *pFirst; /* All winShm objects pointing to this */+ winShm *pWinShmList; /* List of winShm objects with ptrs to this */+winShmNode *pNext; /* Next in list of all winShmNode objects */#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)u8 nextShmId; /* Next available winShm.id value */@@ -50631,26 +52002,19 @@ static winShmNode *winShmNodeList = 0;/*** Structure used internally by this VFS to record the state of an-** open shared memory connection.-**-** The following fields are initialized when this object is created and-** are read-only thereafter:-**-** winShm.pShmNode-** winShm.id-**-** All other fields are read/write. The winShm.pShmNode->mutex must be held-** while accessing any read/write fields.+** open shared memory connection. There is one such structure for each+** winFile open on a wal mode database.*/struct winShm {winShmNode *pShmNode; /* The underlying winShmNode object */- winShm *pNext; /* Next winShm with the same winShmNode */- u8 hasMutex; /* True if holding the winShmNode mutex */u16 sharedMask; /* Mask of shared locks held */u16 exclMask; /* Mask of exclusive locks held */+ HANDLE hShm; /* File-handle on *-shm file. For locking. */+ int bReadonly; /* True if hShm is opened read-only */#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)u8 id; /* Id of this connection with its winShmNode */#endif+ winShm *pWinShmNext; /* Next winShm object on same winShmNode */};/*@@ -50659,56 +52023,12 @@ struct winShm {#define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */#define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */-/*-** Apply advisory locks for all n bytes beginning at ofst.-*/-#define WINSHM_UNLCK 1-#define WINSHM_RDLCK 2-#define WINSHM_WRLCK 3-static int winShmSystemLock(- winShmNode *pFile, /* Apply locks to this open shared-memory segment */- int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */- int ofst, /* Offset to first byte to be locked/unlocked */- int nByte /* Number of bytes to lock or unlock */-){- int rc = 0; /* Result code form Lock/UnlockFileEx() */-- /* Access to the winShmNode object is serialized by the caller */- assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );-- OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",- pFile->hFile.h, lockType, ofst, nByte));-- /* Release/Acquire the system-level lock */- if( lockType==WINSHM_UNLCK ){- rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);- }else{- /* Initialize the locking parameters */- DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;- if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;- rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);- }-- if( rc!= 0 ){- rc = SQLITE_OK;- }else{- pFile->lastErrno = osGetLastError();- rc = SQLITE_BUSY;- }-- OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",- pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :- "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));-- return rc;-}-/* Forward references to VFS methods */static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);static int winDelete(sqlite3_vfs *,const char*,int);/*-** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.+** Purge the winShmNodeList list of all entries with winShmNode.pWinShmList==0.**** This is not a VFS shared-memory method; it is a utility function called** by VFS shared-memory methods.@@ -50721,7 +52041,7 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){osGetCurrentProcessId(), deleteFlag));pp = &winShmNodeList;while( (p = *pp)!=0 ){- if( p->nRef==0 ){+ if( p->pWinShmList==0 ){int i;if( p->mutex ){ sqlite3_mutex_free(p->mutex); }for(i=0; i<p->nRegion; i++){@@ -50734,11 +52054,7 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));UNUSED_VARIABLE_VALUE(bRc);}- if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){- SimulateIOErrorBenign(1);- winClose((sqlite3_file *)&p->hFile);- SimulateIOErrorBenign(0);- }+ winHandleClose(p->hSharedShm);if( deleteFlag ){SimulateIOErrorBenign(1);sqlite3BeginBenignMalloc();@@ -50756,42 +52072,196 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){}/*-** The DMS lock has not yet been taken on shm file pShmNode. Attempt to-** take it now. Return SQLITE_OK if successful, or an SQLite error-** code otherwise.-**-** If the DMS cannot be locked because this is a readonly_shm=1-** connection and no other process already holds a lock, return-** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.+** The DMS lock has not yet been taken on the shm file associated with+** pShmNode. Take the lock. Truncate the *-shm file if required.+** Return SQLITE_OK if successful, or an SQLite error code otherwise.*/-static int winLockSharedMemory(winShmNode *pShmNode){- int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);+static int winLockSharedMemory(winShmNode *pShmNode, DWORD nMs){+ HANDLE h = pShmNode->hSharedShm;+ int rc = SQLITE_OK;+ assert( sqlite3_mutex_held(pShmNode->mutex) );+ rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 1, 0);if( rc==SQLITE_OK ){+ /* We have an EXCLUSIVE lock on the DMS byte. This means that this+ ** is the first process to open the file. Truncate it to zero bytes+ ** in this case. */if( pShmNode->isReadonly ){- pShmNode->isUnlocked = 1;- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);- return SQLITE_READONLY_CANTINIT;- }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);- return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),- "winLockSharedMemory", pShmNode->zFilename);+ rc = SQLITE_READONLY_CANTINIT;+ }else{+ rc = winHandleTruncate(h, 0);}++ /* Release the EXCLUSIVE lock acquired above. */+ winUnlockFile(&h, WIN_SHM_DMS, 0, 1, 0);+ }else if( (rc & 0xFF)==SQLITE_BUSY ){+ rc = SQLITE_OK;}if( rc==SQLITE_OK ){- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);+ /* Take a SHARED lock on the DMS byte. */+ rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 0, nMs);+ if( rc==SQLITE_OK ){+ pShmNode->isUnlocked = 0;+ }}- return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);+ return rc;}+/*-** Open the shared-memory area associated with database file pDbFd.+** This function is used to open a handle on a *-shm file.**-** When opening a new shared-memory file, if no other instances of that-** file are currently open, in this process or in other processes, then-** the file must be truncated to zero length or have its header cleared.+** If SQLITE_ENABLE_SETLK_TIMEOUT is defined at build time, then the file+** is opened with FILE_FLAG_OVERLAPPED specified. If not, it is not.+*/+static int winHandleOpen(+ const char *zUtf8, /* File to open */+ int *pbReadonly, /* IN/OUT: True for readonly handle */+ HANDLE *ph /* OUT: New HANDLE for file */+){+ int rc = SQLITE_OK;+ void *zConverted = 0;+ int bReadonly = *pbReadonly;+ HANDLE h = INVALID_HANDLE_VALUE;++#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ const DWORD flag_overlapped = FILE_FLAG_OVERLAPPED;+#else+ const DWORD flag_overlapped = 0;+#endif++ /* Convert the filename to the system encoding. */+ zConverted = winConvertFromUtf8Filename(zUtf8);+ if( zConverted==0 ){+ OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8));+ rc = SQLITE_IOERR_NOMEM_BKPT;+ goto winopenfile_out;+ }++ /* Ensure the file we are trying to open is not actually a directory. */+ if( winIsDir(zConverted) ){+ OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8));+ rc = SQLITE_CANTOPEN_ISDIR;+ goto winopenfile_out;+ }++ /* TODO: platforms.+ ** TODO: retry-on-ioerr.+ */+ if( osIsNT() ){+#if SQLITE_OS_WINRT+ CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;+ memset(&extendedParameters, 0, sizeof(extendedParameters));+ extendedParameters.dwSize = sizeof(extendedParameters);+ extendedParameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;+ extendedParameters.dwFileFlags = flag_overlapped;+ extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;+ h = osCreateFile2((LPCWSTR)zConverted,+ (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)),/* dwDesiredAccess */+ FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */+ OPEN_ALWAYS, /* dwCreationDisposition */+ &extendedParameters+ );+#else+ h = osCreateFileW((LPCWSTR)zConverted, /* lpFileName */+ (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */+ FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */+ NULL, /* lpSecurityAttributes */+ OPEN_ALWAYS, /* dwCreationDisposition */+ FILE_ATTRIBUTE_NORMAL|flag_overlapped,+ NULL+ );+#endif+ }else{+ /* Due to pre-processor directives earlier in this file,+ ** SQLITE_WIN32_HAS_ANSI is always defined if osIsNT() is false. */+#ifdef SQLITE_WIN32_HAS_ANSI+ h = osCreateFileA((LPCSTR)zConverted,+ (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */+ FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */+ NULL, /* lpSecurityAttributes */+ OPEN_ALWAYS, /* dwCreationDisposition */+ FILE_ATTRIBUTE_NORMAL|flag_overlapped,+ NULL+ );+#endif+ }++ if( h==INVALID_HANDLE_VALUE ){+ if( bReadonly==0 ){+ bReadonly = 1;+ rc = winHandleOpen(zUtf8, &bReadonly, &h);+ }else{+ rc = SQLITE_CANTOPEN_BKPT;+ }+ }++ winopenfile_out:+ sqlite3_free(zConverted);+ *pbReadonly = bReadonly;+ *ph = h;+ return rc;+}++/*+** Close pDbFd's connection to shared-memory. Delete the underlying+** *-shm file if deleteFlag is true.+*/+static int winCloseSharedMemory(winFile *pDbFd, int deleteFlag){+ winShm *p; /* The connection to be closed */+ winShm **pp; /* Iterator for pShmNode->pWinShmList */+ winShmNode *pShmNode; /* The underlying shared-memory file */++ p = pDbFd->pShm;+ if( p==0 ) return SQLITE_OK;+ if( p->hShm!=INVALID_HANDLE_VALUE ){+ osCloseHandle(p->hShm);+ }++ winShmEnterMutex();+ pShmNode = p->pShmNode;++ /* Remove this connection from the winShmNode.pWinShmList list */+ sqlite3_mutex_enter(pShmNode->mutex);+ for(pp=&pShmNode->pWinShmList; *pp!=p; pp=&(*pp)->pWinShmNext){}+ *pp = p->pWinShmNext;+ sqlite3_mutex_leave(pShmNode->mutex);++ winShmPurge(pDbFd->pVfs, deleteFlag);+ winShmLeaveMutex();++ /* Free the connection p */+ sqlite3_free(p);+ pDbFd->pShm = 0;+ return SQLITE_OK;+}++/*+** testfixture builds may set this global variable to true via a+** Tcl interface. This forces the VFS to use the locking normally+** only used for UNC paths for all files.+*/+#ifdef SQLITE_TEST+SQLITE_API int sqlite3_win_test_unc_locking = 0;+#else+# define sqlite3_win_test_unc_locking 0+#endif++/*+** Return true if the string passed as the only argument is likely+** to be a UNC path. In other words, if it starts with "\\".+*/+static int winIsUNCPath(const char *zFile){+ if( zFile[0]=='\\' && zFile[1]=='\\' ){+ return 1;+ }+ return sqlite3_win_test_unc_locking;+}++/*+** Open the shared-memory area associated with database file pDbFd.*/static int winOpenSharedMemory(winFile *pDbFd){struct winShm *p; /* The connection to be opened */@@ -50803,98 +52273,93 @@ static int winOpenSharedMemory(winFile *pDbFd){assert( pDbFd->pShm==0 ); /* Not previously opened *//* Allocate space for the new sqlite3_shm object. Also speculatively- ** allocate space for a new winShmNode and filename.- */+ ** allocate space for a new winShmNode and filename. */p = sqlite3MallocZero( sizeof(*p) );if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;nName = sqlite3Strlen30(pDbFd->zPath);- pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );+ pNew = sqlite3MallocZero( sizeof(*pShmNode) + (i64)nName + 17 );if( pNew==0 ){sqlite3_free(p);return SQLITE_IOERR_NOMEM_BKPT;}pNew->zFilename = (char*)&pNew[1];+ pNew->hSharedShm = INVALID_HANDLE_VALUE;+ pNew->isUnlocked = 1;+ pNew->bUseSharedLockHandle = winIsUNCPath(pDbFd->zPath);sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);/* Look to see if there is an existing winShmNode that can be used.- ** If no matching winShmNode currently exists, create a new one.- */+ ** If no matching winShmNode currently exists, then create a new one. */winShmEnterMutex();for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){/* TBD need to come up with better match here. Perhaps- ** use FILE_ID_BOTH_DIR_INFO Structure.- */+ ** use FILE_ID_BOTH_DIR_INFO Structure. */if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;}- if( pShmNode ){- sqlite3_free(pNew);- }else{- int inFlags = SQLITE_OPEN_WAL;- int outFlags = 0;-+ if( pShmNode==0 ){pShmNode = pNew;- pNew = 0;- ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;- pShmNode->pNext = winShmNodeList;- winShmNodeList = pShmNode;+ /* Allocate a mutex for this winShmNode object, if one is required. */if( sqlite3GlobalConfig.bCoreMutex ){pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);- if( pShmNode->mutex==0 ){- rc = SQLITE_IOERR_NOMEM_BKPT;- goto shm_open_err;- }+ if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT;}- if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){- inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;- }else{- inFlags |= SQLITE_OPEN_READONLY;- }- rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,- (sqlite3_file*)&pShmNode->hFile,- inFlags, &outFlags);- if( rc!=SQLITE_OK ){- rc = winLogError(rc, osGetLastError(), "winOpenShm",- pShmNode->zFilename);- goto shm_open_err;+ /* Open a file-handle to use for mappings, and for the DMS lock. */+ if( rc==SQLITE_OK ){+ HANDLE h = INVALID_HANDLE_VALUE;+ pShmNode->isReadonly = sqlite3_uri_boolean(pDbFd->zPath,"readonly_shm",0);+ rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h);+ pShmNode->hSharedShm = h;}- if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;- rc = winLockSharedMemory(pShmNode);- if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;+ /* If successful, link the new winShmNode into the global list. If an+ ** error occurred, free the object. */+ if( rc==SQLITE_OK ){+ pShmNode->pNext = winShmNodeList;+ winShmNodeList = pShmNode;+ pNew = 0;+ }else{+ sqlite3_mutex_free(pShmNode->mutex);+ if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){+ osCloseHandle(pShmNode->hSharedShm);+ }+ }}- /* Make the new connection a child of the winShmNode */- p->pShmNode = pShmNode;+ /* If no error has occurred, link the winShm object to the winShmNode and+ ** the winShm to pDbFd. */+ if( rc==SQLITE_OK ){+ sqlite3_mutex_enter(pShmNode->mutex);+ p->pShmNode = pShmNode;+ p->pWinShmNext = pShmNode->pWinShmList;+ pShmNode->pWinShmList = p;#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)- p->id = pShmNode->nextShmId++;+ p->id = pShmNode->nextShmId++;#endif- pShmNode->nRef++;- pDbFd->pShm = p;+ pDbFd->pShm = p;+ sqlite3_mutex_leave(pShmNode->mutex);+ }else if( p ){+ sqlite3_free(p);+ }++ assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 );winShmLeaveMutex();+ sqlite3_free(pNew);- /* The reference count on pShmNode has already been incremented under- ** the cover of the winShmEnterMutex() mutex and the pointer from the- ** new (struct winShm) object to the pShmNode has been set. All that is- ** left to do is to link the new object into the linked list starting- ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex- ** mutex.- */- sqlite3_mutex_enter(pShmNode->mutex);- p->pNext = pShmNode->pFirst;- pShmNode->pFirst = p;- sqlite3_mutex_leave(pShmNode->mutex);- return rc;+ /* Open a file-handle on the *-shm file for this connection. This file-handle+ ** is only used for locking. The mapping of the *-shm file is created using+ ** the shared file handle in winShmNode.hSharedShm. */+ if( rc==SQLITE_OK && pShmNode->bUseSharedLockHandle==0 ){+ p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0);+ rc = winHandleOpen(pShmNode->zFilename, &p->bReadonly, &p->hShm);+ if( rc!=SQLITE_OK ){+ assert( p->hShm==INVALID_HANDLE_VALUE );+ winCloseSharedMemory(pDbFd, 0);+ }+ }- /* Jump here on any error */-shm_open_err:- winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);- winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */- sqlite3_free(p);- sqlite3_free(pNew);- winShmLeaveMutex();return rc;}@@ -50906,38 +52371,7 @@ static int winShmUnmap(sqlite3_file *fd, /* Database holding shared memory */int deleteFlag /* Delete after closing if true */){- winFile *pDbFd; /* Database holding shared-memory */- winShm *p; /* The connection to be closed */- winShmNode *pShmNode; /* The underlying shared-memory file */- winShm **pp; /* For looping over sibling connections */-- pDbFd = (winFile*)fd;- p = pDbFd->pShm;- if( p==0 ) return SQLITE_OK;- pShmNode = p->pShmNode;-- /* Remove connection p from the set of connections associated- ** with pShmNode */- sqlite3_mutex_enter(pShmNode->mutex);- for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}- *pp = p->pNext;-- /* Free the connection p */- sqlite3_free(p);- pDbFd->pShm = 0;- sqlite3_mutex_leave(pShmNode->mutex);-- /* If pShmNode->nRef has reached 0, then close the underlying- ** shared-memory file, too */- winShmEnterMutex();- assert( pShmNode->nRef>0 );- pShmNode->nRef--;- if( pShmNode->nRef==0 ){- winShmPurge(pDbFd->pVfs, deleteFlag);- }- winShmLeaveMutex();-- return SQLITE_OK;+ return winCloseSharedMemory((winFile*)fd, deleteFlag);}/*@@ -50951,10 +52385,9 @@ static int winShmLock(){winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */winShm *p = pDbFd->pShm; /* The shared memory being locked */- winShm *pX; /* For looping over all siblings */winShmNode *pShmNode;int rc = SQLITE_OK; /* Result code */- u16 mask; /* Mask of locks to take or release */+ u16 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); /* Mask of locks to [un]take */if( p==0 ) return SQLITE_IOERR_SHMLOCK;pShmNode = p->pShmNode;@@ -50968,85 +52401,127 @@ static int winShmLock(|| flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );- mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));- assert( n>1 || mask==(1<<ofst) );- sqlite3_mutex_enter(pShmNode->mutex);- if( flags & SQLITE_SHM_UNLOCK ){- u16 allMask = 0; /* Mask of locks held by siblings */+ /* Check that, if this to be a blocking lock, no locks that occur later+ ** in the following list than the lock being obtained are already held:+ **+ ** 1. Recovery lock (ofst==2).+ ** 2. Checkpointer lock (ofst==1).+ ** 3. Write lock (ofst==0).+ ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).+ **+ ** In other words, if this is a blocking lock, none of the locks that+ ** occur later in the above list than the lock being obtained may be+ ** held.+ */+#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG)+ {+ u16 lockMask = (p->exclMask|p->sharedMask);+ assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (+ (ofst!=2 || lockMask==0)+ && (ofst!=1 || lockMask==0 || lockMask==2)+ && (ofst!=0 || lockMask<3)+ && (ofst<3 || lockMask<(1<<ofst))+ ));+ }+#endif- /* See if any siblings hold this same lock */- for(pX=pShmNode->pFirst; pX; pX=pX->pNext){- if( pX==p ) continue;- assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );- allMask |= pX->sharedMask;- }+ /* Check if there is any work to do. There are three cases:+ **+ ** a) An unlock operation where there are locks to unlock,+ ** b) An shared lock where the requested lock is not already held+ ** c) An exclusive lock where the requested lock is not already held+ **+ ** The SQLite core never requests an exclusive lock that it already holds.+ ** This is assert()ed immediately below. */+ assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)+ || 0==(p->exclMask & mask)+ );+ if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))+ || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))+ || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK))+ ){+ HANDLE h = p->hShm;- /* Unlock the system-level locks */- if( (mask & allMask)==0 ){- rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);- }else{- rc = SQLITE_OK;- }+ if( flags & SQLITE_SHM_UNLOCK ){+ /* Case (a) - unlock. */- /* Undo the local locks */- if( rc==SQLITE_OK ){- p->exclMask &= ~mask;- p->sharedMask &= ~mask;- }- }else if( flags & SQLITE_SHM_SHARED ){- u16 allShared = 0; /* Union of locks held by connections other than "p" */+ assert( (p->exclMask & p->sharedMask)==0 );+ assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );+ assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );- /* Find out which shared locks are already held by sibling connections.- ** If any sibling already holds an exclusive lock, go ahead and return- ** SQLITE_BUSY.- */- for(pX=pShmNode->pFirst; pX; pX=pX->pNext){- if( (pX->exclMask & mask)!=0 ){- rc = SQLITE_BUSY;- break;+ assert( !(flags & SQLITE_SHM_SHARED) || n==1 );+ if( pShmNode->bUseSharedLockHandle ){+ h = pShmNode->hSharedShm;+ if( flags & SQLITE_SHM_SHARED ){+ winShm *pShm;+ sqlite3_mutex_enter(pShmNode->mutex);+ for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){+ if( pShm!=p && (pShm->sharedMask & mask) ){+ /* Another connection within this process is also holding this+ ** SHARED lock. So do not actually release the OS lock. */+ h = INVALID_HANDLE_VALUE;+ break;+ }+ }+ sqlite3_mutex_leave(pShmNode->mutex);+ }}- allShared |= pX->sharedMask;- }- /* Get shared locks at the system level, if necessary */- if( rc==SQLITE_OK ){- if( (allShared & mask)==0 ){- rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);- }else{- rc = SQLITE_OK;+ if( h!=INVALID_HANDLE_VALUE ){+ rc = winHandleUnlock(h, ofst+WIN_SHM_BASE, n);}- }- /* Get the local shared locks */- if( rc==SQLITE_OK ){- p->sharedMask |= mask;- }- }else{- /* Make sure no sibling connections hold locks that will block this- ** lock. If any do, return SQLITE_BUSY right away.- */- for(pX=pShmNode->pFirst; pX; pX=pX->pNext){- if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){- rc = SQLITE_BUSY;- break;+ /* If successful, also clear the bits in sharedMask/exclMask */+ if( rc==SQLITE_OK ){+ p->exclMask = (p->exclMask & ~mask);+ p->sharedMask = (p->sharedMask & ~mask);+ }+ }else{+ int bExcl = ((flags & SQLITE_SHM_EXCLUSIVE) ? 1 : 0);+ DWORD nMs = winFileBusyTimeout(pDbFd);++ if( pShmNode->bUseSharedLockHandle ){+ winShm *pShm;+ h = pShmNode->hSharedShm;+ sqlite3_mutex_enter(pShmNode->mutex);+ for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){+ if( bExcl ){+ if( (pShm->sharedMask|pShm->exclMask) & mask ){+ rc = SQLITE_BUSY;+ h = INVALID_HANDLE_VALUE;+ }+ }else{+ if( pShm->sharedMask & mask ){+ h = INVALID_HANDLE_VALUE;+ }else if( pShm->exclMask & mask ){+ rc = SQLITE_BUSY;+ h = INVALID_HANDLE_VALUE;+ }+ }+ }+ sqlite3_mutex_leave(pShmNode->mutex);}- }- /* Get the exclusive locks at the system level. Then if successful- ** also mark the local connection as being locked.- */- if( rc==SQLITE_OK ){- rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);+ if( h!=INVALID_HANDLE_VALUE ){+ rc = winHandleLockTimeout(h, ofst+WIN_SHM_BASE, n, bExcl, nMs);+ }if( rc==SQLITE_OK ){- assert( (p->sharedMask & mask)==0 );- p->exclMask |= mask;+ if( bExcl ){+ p->exclMask = (p->exclMask | mask);+ }else{+ p->sharedMask = (p->sharedMask | mask);+ }}}}- sqlite3_mutex_leave(pShmNode->mutex);- OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",- osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,- sqlite3ErrName(rc)));++ OSTRACE((+ "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x,"+ " rc=%s\n",+ ofst, n, flags,+ osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,+ sqlite3ErrName(rc))+ );return rc;}@@ -51108,13 +52583,15 @@ static int winShmMap(sqlite3_mutex_enter(pShmNode->mutex);if( pShmNode->isUnlocked ){- rc = winLockSharedMemory(pShmNode);+ /* Take the DMS lock. */+ assert( pShmNode->nRegion==0 );+ rc = winLockSharedMemory(pShmNode, winFileBusyTimeout(pDbFd));if( rc!=SQLITE_OK ) goto shmpage_out;- pShmNode->isUnlocked = 0;}- assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );+ assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );if( pShmNode->nRegion<=iRegion ){+ HANDLE hShared = pShmNode->hSharedShm;struct ShmRegion *apNew; /* New aRegion[] array */int nByte = (iRegion+1)*szRegion; /* Minimum required file size */sqlite3_int64 sz; /* Current size of wal-index file */@@ -51125,10 +52602,9 @@ static int winShmMap(** Check to see if it has been allocated (i.e. if the wal-index file is** large enough to contain the requested region).*/- rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);+ rc = winHandleSize(hShared, &sz);if( rc!=SQLITE_OK ){- rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),- "winShmMap1", pDbFd->zPath);+ rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath);goto shmpage_out;}@@ -51137,19 +52613,17 @@ static int winShmMap(** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.**** Alternatively, if isWrite is non-zero, use ftruncate() to allocate- ** the requested memory region.- */+ ** the requested memory region. */if( !isWrite ) goto shmpage_out;- rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);+ rc = winHandleTruncate(hShared, nByte);if( rc!=SQLITE_OK ){- rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),- "winShmMap2", pDbFd->zPath);+ rc = winLogError(rc, osGetLastError(), "winShmMap2", pDbFd->zPath);goto shmpage_out;}}/* Map the requested memory region into this processes address space. */- apNew = (struct ShmRegion *)sqlite3_realloc64(+ apNew = (struct ShmRegion*)sqlite3_realloc64(pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]));if( !apNew ){@@ -51168,18 +52642,13 @@ static int winShmMap(void *pMap = 0; /* Mapped memory region */#if SQLITE_OS_WINRT- hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,- NULL, protect, nByte, NULL- );+ hMap = osCreateFileMappingFromApp(hShared, NULL, protect, nByte, NULL);#elif defined(SQLITE_WIN32_HAS_WIDE)- hMap = osCreateFileMappingW(pShmNode->hFile.h,- NULL, protect, 0, nByte, NULL- );+ hMap = osCreateFileMappingW(hShared, NULL, protect, 0, nByte, NULL);#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA- hMap = osCreateFileMappingA(pShmNode->hFile.h,- NULL, protect, 0, nByte, NULL- );+ hMap = osCreateFileMappingA(hShared, NULL, protect, 0, nByte, NULL);#endif+OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",osGetCurrentProcessId(), pShmNode->nRegion, nByte,hMap ? "ok" : "failed"));@@ -51222,7 +52691,9 @@ shmpage_out:}else{*pp = 0;}- if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;+ if( pShmNode->isReadonly && rc==SQLITE_OK ){+ rc = SQLITE_READONLY;+ }sqlite3_mutex_leave(pShmNode->mutex);return rc;}@@ -51542,47 +53013,6 @@ static winVfsAppData winNolockAppData = {** sqlite3_vfs object.*/-#if defined(__CYGWIN__)-/*-** Convert a filename from whatever the underlying operating system-** supports for filenames into UTF-8. Space to hold the result is-** obtained from malloc and must be freed by the calling function.-*/-static char *winConvertToUtf8Filename(const void *zFilename){- char *zConverted = 0;- if( osIsNT() ){- zConverted = winUnicodeToUtf8(zFilename);- }-#ifdef SQLITE_WIN32_HAS_ANSI- else{- zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());- }-#endif- /* caller will handle out of memory */- return zConverted;-}-#endif--/*-** Convert a UTF-8 filename into whatever form the underlying-** operating system wants filenames in. Space to hold the result-** is obtained from malloc and must be freed by the calling-** function.-*/-static void *winConvertFromUtf8Filename(const char *zFilename){- void *zConverted = 0;- if( osIsNT() ){- zConverted = winUtf8ToUnicode(zFilename);- }-#ifdef SQLITE_WIN32_HAS_ANSI- else{- zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());- }-#endif- /* caller will handle out of memory */- return zConverted;-}-/*** This function returns non-zero if the specified UTF-8 string buffer** ends with a directory separator character or one was successfully@@ -51595,7 +53025,14 @@ static int winMakeEndInDirSep(int nBuf, char *zBuf){if( winIsDirSep(zBuf[nLen-1]) ){return 1;}else if( nLen+1<nBuf ){- zBuf[nLen] = winGetDirSep();+ if( !osGetenv ){+ zBuf[nLen] = winGetDirSep();+ }else if( winIsDriveLetterAndColon(zBuf) && winIsDirSep(zBuf[2]) ){+ zBuf[nLen] = '\\';+ zBuf[2]='\\';+ }else{+ zBuf[nLen] = '/';+ }zBuf[nLen+1] = '\0';return 1;}@@ -51622,14 +53059,14 @@ static int winTempDirDefined(void){** The pointer returned in pzBuf must be freed via sqlite3_free().*/static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){- static char zChars[] =+ static const char zChars[] ="abcdefghijklmnopqrstuvwxyz""ABCDEFGHIJKLMNOPQRSTUVWXYZ""0123456789";size_t i, j;DWORD pid;int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);- int nMax, nBuf, nDir, nLen;+ i64 nMax, nBuf, nDir, nLen;char *zBuf;/* It's odd to simulate an io-error here, but really this is just@@ -51641,7 +53078,8 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){/* Allocate a temporary buffer to store the fully qualified file** name for the temporary file. If this fails, we cannot continue.*/- nMax = pVfs->mxPathname; nBuf = nMax + 2;+ nMax = pVfs->mxPathname;+ nBuf = 2 + (i64)nMax;zBuf = sqlite3MallocZero( nBuf );if( !zBuf ){OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));@@ -51672,7 +53110,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){}#if defined(__CYGWIN__)- else{+ else if( osGetenv!=NULL ){static const char *azDirs[] = {0, /* getenv("SQLITE_TMPDIR") */0, /* getenv("TMPDIR") */@@ -51688,11 +53126,11 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){unsigned int i;const char *zDir = 0;- if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");- if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");- if( !azDirs[2] ) azDirs[2] = getenv("TMP");- if( !azDirs[3] ) azDirs[3] = getenv("TEMP");- if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");+ if( !azDirs[0] ) azDirs[0] = osGetenv("SQLITE_TMPDIR");+ if( !azDirs[1] ) azDirs[1] = osGetenv("TMPDIR");+ if( !azDirs[2] ) azDirs[2] = osGetenv("TMP");+ if( !azDirs[3] ) azDirs[3] = osGetenv("TEMP");+ if( !azDirs[4] ) azDirs[4] = osGetenv("USERPROFILE");for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){void *zConverted;if( zDir==0 ) continue;@@ -51701,7 +53139,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){** it must be converted to a native Win32 path via the Cygwin API** prior to using it.*/- if( winIsDriveLetterAndColon(zDir) ){+ {zConverted = winConvertFromUtf8Filename(zDir);if( !zConverted ){sqlite3_free(zBuf);@@ -51714,44 +53152,12 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){break;}sqlite3_free(zConverted);- }else{- zConverted = sqlite3MallocZero( nMax+1 );- if( !zConverted ){- sqlite3_free(zBuf);- OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));- return SQLITE_IOERR_NOMEM_BKPT;- }- if( cygwin_conv_path(- osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,- zConverted, nMax+1)<0 ){- sqlite3_free(zConverted);- sqlite3_free(zBuf);- OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));- return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,- "winGetTempname2", zDir);- }- if( winIsDir(zConverted) ){- /* At this point, we know the candidate directory exists and should- ** be used. However, we may need to convert the string containing- ** its name into UTF-8 (i.e. if it is UTF-16 right now).- */- char *zUtf8 = winConvertToUtf8Filename(zConverted);- if( !zUtf8 ){- sqlite3_free(zConverted);- sqlite3_free(zBuf);- OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));- return SQLITE_IOERR_NOMEM_BKPT;- }- sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);- sqlite3_free(zUtf8);- sqlite3_free(zConverted);- break;- }- sqlite3_free(zConverted);}}}-#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)+#endif++#if !SQLITE_OS_WINRT && defined(_WIN32)else if( osIsNT() ){char *zMulti;LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );@@ -51875,7 +53281,7 @@ static int winIsDir(const void *zConverted){return 0; /* Invalid name? */}attr = sAttrData.dwFileAttributes;-#if SQLITE_OS_WINCE==0+#if SQLITE_OS_WINCE==0 && defined(SQLITE_WIN32_HAS_ANSI)}else{attr = osGetFileAttributesA((char*)zConverted);#endif@@ -51891,6 +53297,12 @@ static int winAccess(int *pResOut /* OUT: Result */);+/*+** The Windows version of xAccess() accepts an extra bit in the flags+** parameter that prevents an anti-virus retry loop.+*/+#define NORETRY 0x4000+/*** Open a file.*/@@ -51915,6 +53327,7 @@ static int winOpen(void *zConverted; /* Filename in OS encoding */const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */int cnt = 0;+ int isRO = 0; /* file is known to be accessible readonly *//* If argument zPath is a NULL pointer, this function is required to open** a temporary file. Use this buffer to store the file name in.@@ -52079,9 +53492,9 @@ static int winOpen(&extendedParameters);if( h!=INVALID_HANDLE_VALUE ) break;if( isReadWrite ){- int rc2, isRO = 0;+ int rc2;sqlite3BeginBenignMalloc();- rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);+ rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ|NORETRY, &isRO);sqlite3EndBenignMalloc();if( rc2==SQLITE_OK && isRO ) break;}@@ -52096,9 +53509,9 @@ static int winOpen(NULL);if( h!=INVALID_HANDLE_VALUE ) break;if( isReadWrite ){- int rc2, isRO = 0;+ int rc2;sqlite3BeginBenignMalloc();- rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);+ rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ|NORETRY, &isRO);sqlite3EndBenignMalloc();if( rc2==SQLITE_OK && isRO ) break;}@@ -52116,9 +53529,9 @@ static int winOpen(NULL);if( h!=INVALID_HANDLE_VALUE ) break;if( isReadWrite ){- int rc2, isRO = 0;+ int rc2;sqlite3BeginBenignMalloc();- rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO);+ rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ|NORETRY, &isRO);sqlite3EndBenignMalloc();if( rc2==SQLITE_OK && isRO ) break;}@@ -52133,7 +53546,7 @@ static int winOpen(if( h==INVALID_HANDLE_VALUE ){sqlite3_free(zConverted);sqlite3_free(zTmpname);- if( isReadWrite && !isExclusive ){+ if( isReadWrite && isRO && !isExclusive ){return winOpen(pVfs, zName, id,((flags|SQLITE_OPEN_READONLY) &~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),@@ -52335,8 +53748,14 @@ static int winAccess(int rc = 0;DWORD lastErrno = 0;void *zConverted;+ int noRetry = 0; /* Do not use winRetryIoerr() */UNUSED_PARAMETER(pVfs);+ if( (flags & NORETRY)!=0 ){+ noRetry = 1;+ flags &= ~NORETRY;+ }+SimulateIOError( return SQLITE_IOERR_ACCESS; );OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",zFilename, flags, pResOut));@@ -52359,7 +53778,10 @@ static int winAccess(memset(&sAttrData, 0, sizeof(sAttrData));while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,GetFileExInfoStandard,- &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}+ &sAttrData))+ && !noRetry+ && winRetryIoerr(&cnt, &lastErrno)+ ){ /* Loop until true */}if( rc ){/* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file** as if it does not exist.@@ -52427,6 +53849,7 @@ static BOOL winIsDriveLetterAndColon(return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );}+#ifdef _WIN32/*** Returns non-zero if the specified path name should be used verbatim. If** non-zero is returned from this function, the calling function must simply@@ -52463,6 +53886,70 @@ static BOOL winIsVerbatimPathname(*/return FALSE;}+#endif /* _WIN32 */++#ifdef __CYGWIN__+/*+** Simplify a filename into its canonical form+** by making the following changes:+**+** * convert any '/' to '\' (win32) or reverse (Cygwin)+** * removing any trailing and duplicate / (except for UNC paths)+** * convert /./ into just /+**+** Changes are made in-place. Return the new name length.+**+** The original filename is in z[0..]. If the path is shortened,+** no-longer used bytes will be written by '\0'.+*/+static void winSimplifyName(char *z){+ int i, j;+ for(i=j=0; z[i]; ++i){+ if( winIsDirSep(z[i]) ){+#if !defined(SQLITE_TEST)+ /* Some test-cases assume that "./foo" and "foo" are different */+ if( z[i+1]=='.' && winIsDirSep(z[i+2]) ){+ ++i;+ continue;+ }+#endif+ if( !z[i+1] || (winIsDirSep(z[i+1]) && (i!=0)) ){+ continue;+ }+ z[j++] = osGetenv?'/':'\\';+ }else{+ z[j++] = z[i];+ }+ }+ while(j<i) z[j++] = '\0';+}++#define SQLITE_MAX_SYMLINKS 100++static int mkFullPathname(+ const char *zPath, /* Input path */+ char *zOut, /* Output buffer */+ int nOut /* Allocated size of buffer zOut */+){+ int nPath = sqlite3Strlen30(zPath);+ int iOff = 0;+ if( zPath[0]!='/' ){+ if( osGetcwd(zOut, nOut-2)==0 ){+ return winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)osErrno, "getcwd", zPath);+ }+ iOff = sqlite3Strlen30(zOut);+ zOut[iOff++] = '/';+ }+ if( (iOff+nPath+1)>nOut ){+ /* SQLite assumes that xFullPathname() nul-terminates the output buffer+ ** even if it returns an error. */+ zOut[iOff] = '\0';+ return SQLITE_CANTOPEN_BKPT;+ }+ sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);+ return SQLITE_OK;+}+#endif /* __CYGWIN__ *//*** Turn a relative pathname into a full pathname. Write the full@@ -52475,8 +53962,8 @@ static int winFullPathnameNoMutex(int nFull, /* Size of output buffer in bytes */char *zFull /* Output buffer */){-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)- DWORD nByte;+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT+ int nByte;void *zConverted;char *zOut;#endif@@ -52489,64 +53976,82 @@ static int winFullPathnameNoMutex(zRelative++;}-#if defined(__CYGWIN__)SimulateIOError( return SQLITE_ERROR );- UNUSED_PARAMETER(nFull);- assert( nFull>=pVfs->mxPathname );- if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){- /*- ** NOTE: We are dealing with a relative path name and the data- ** directory has been set. Therefore, use it as the basis- ** for converting the relative path name to an absolute- ** one by prepending the data directory and a slash.- */- char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );- if( !zOut ){- return SQLITE_IOERR_NOMEM_BKPT;- }- if( cygwin_conv_path(- (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |- CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){- sqlite3_free(zOut);- return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,- "winFullPathname1", zRelative);- }else{- char *zUtf8 = winConvertToUtf8Filename(zOut);- if( !zUtf8 ){- sqlite3_free(zOut);- return SQLITE_IOERR_NOMEM_BKPT;- }- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",- sqlite3_data_directory, winGetDirSep(), zUtf8);- sqlite3_free(zUtf8);- sqlite3_free(zOut);- }- }else{- char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );- if( !zOut ){- return SQLITE_IOERR_NOMEM_BKPT;- }- if( cygwin_conv_path(- (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),- zRelative, zOut, pVfs->mxPathname+1)<0 ){- sqlite3_free(zOut);- return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,- "winFullPathname2", zRelative);- }else{- char *zUtf8 = winConvertToUtf8Filename(zOut);- if( !zUtf8 ){- sqlite3_free(zOut);- return SQLITE_IOERR_NOMEM_BKPT;- }- sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);- sqlite3_free(zUtf8);- sqlite3_free(zOut);++#ifdef __CYGWIN__+ if( osGetcwd ){+ zFull[nFull-1] = '\0';+ if( !winIsDriveLetterAndColon(zRelative) || !winIsDirSep(zRelative[2]) ){+ int rc = SQLITE_OK;+ int nLink = 1; /* Number of symbolic links followed so far */+ const char *zIn = zRelative; /* Input path for each iteration of loop */+ char *zDel = 0;+ struct stat buf;++ UNUSED_PARAMETER(pVfs);++ do {+ /* Call lstat() on path zIn. Set bLink to true if the path is a symbolic+ ** link, or false otherwise. */+ int bLink = 0;+ if( osLstat && osReadlink ) {+ if( osLstat(zIn, &buf)!=0 ){+ int myErrno = osErrno;+ if( myErrno!=ENOENT ){+ rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)myErrno, "lstat", zIn);+ }+ }else{+ bLink = ((buf.st_mode & 0170000) == 0120000);+ }++ if( bLink ){+ if( zDel==0 ){+ zDel = sqlite3MallocZero(nFull);+ if( zDel==0 ) rc = SQLITE_NOMEM;+ }else if( ++nLink>SQLITE_MAX_SYMLINKS ){+ rc = SQLITE_CANTOPEN_BKPT;+ }++ if( rc==SQLITE_OK ){+ nByte = osReadlink(zIn, zDel, nFull-1);+ if( nByte ==(DWORD)-1 ){+ rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)osErrno, "readlink", zIn);+ }else{+ if( zDel[0]!='/' ){+ int n;+ for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);+ if( nByte+n+1>nFull ){+ rc = SQLITE_CANTOPEN_BKPT;+ }else{+ memmove(&zDel[n], zDel, nByte+1);+ memcpy(zDel, zIn, n);+ nByte += n;+ }+ }+ zDel[nByte] = '\0';+ }+ }++ zIn = zDel;+ }+ }++ assert( rc!=SQLITE_OK || zIn!=zFull || zIn[0]=='/' );+ if( rc==SQLITE_OK && zIn!=zFull ){+ rc = mkFullPathname(zIn, zFull, nFull);+ }+ if( bLink==0 ) break;+ zIn = zFull;+ }while( rc==SQLITE_OK );++ sqlite3_free(zDel);+ winSimplifyName(zFull);+ return rc;}}- return SQLITE_OK;-#endif+#endif /* __CYGWIN__ */-#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)+#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && defined(_WIN32)SimulateIOError( return SQLITE_ERROR );/* WinCE has no concept of a relative pathname, or so I am told. *//* WinRT has no way to convert a relative path to an absolute one. */@@ -52565,7 +54070,8 @@ static int winFullPathnameNoMutex(return SQLITE_OK;#endif-#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)+#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT+#if defined(_WIN32)/* It's odd to simulate an io-error here, but really this is just** using the io-error infrastructure to test that SQLite handles this** function failing. This function could fail if, for example, the@@ -52583,6 +54089,7 @@ static int winFullPathnameNoMutex(sqlite3_data_directory, winGetDirSep(), zRelative);return SQLITE_OK;}+#endifzConverted = winConvertFromUtf8Filename(zRelative);if( zConverted==0 ){return SQLITE_IOERR_NOMEM_BKPT;@@ -52621,13 +54128,12 @@ static int winFullPathnameNoMutex(return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),"winFullPathname3", zRelative);}- nByte += 3;- zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );+ zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) + 3*sizeof(zTemp[0]) );if( zTemp==0 ){sqlite3_free(zConverted);return SQLITE_IOERR_NOMEM_BKPT;}- nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);+ nByte = osGetFullPathNameA((char*)zConverted, nByte+3, zTemp, 0);if( nByte==0 ){sqlite3_free(zConverted);sqlite3_free(zTemp);@@ -52640,7 +54146,26 @@ static int winFullPathnameNoMutex(}#endifif( zOut ){+#ifdef __CYGWIN__+ if( memcmp(zOut, "\\\\?\\", 4) ){+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);+ }else if( memcmp(zOut+4, "UNC\\", 4) ){+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+4);+ }else{+ char *p = zOut+6;+ *p = '\\';+ if( osGetcwd ){+ /* On Cygwin, UNC paths use forward slashes */+ while( *p ){+ if( *p=='\\' ) *p = '/';+ ++p;+ }+ }+ sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+6);+ }+#elsesqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);+#endif /* __CYGWIN__ */sqlite3_free(zOut);return SQLITE_OK;}else{@@ -52670,25 +54195,8 @@ static int winFullPathname(*/static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){HANDLE h;-#if defined(__CYGWIN__)- int nFull = pVfs->mxPathname+1;- char *zFull = sqlite3MallocZero( nFull );- void *zConverted = 0;- if( zFull==0 ){- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));- return 0;- }- if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){- sqlite3_free(zFull);- OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));- return 0;- }- zConverted = winConvertFromUtf8Filename(zFull);- sqlite3_free(zFull);-#elsevoid *zConverted = winConvertFromUtf8Filename(zFilename);UNUSED_PARAMETER(pVfs);-#endifif( zConverted==0 ){OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));return 0;@@ -53037,7 +54545,7 @@ SQLITE_API int sqlite3_os_init(void){/* Double-check that the aSyscall[] array has been constructed** correctly. See ticket [bb3a86e890c8e96ab] */- assert( ArraySize(aSyscall)==80 );+ assert( ArraySize(aSyscall)==89 );/* get memory map allocation granularity */memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));@@ -53656,13 +55164,13 @@ static int memdbOpen(}if( p==0 ){MemStore **apNew;- p = sqlite3Malloc( sizeof(*p) + szName + 3 );+ p = sqlite3Malloc( sizeof(*p) + (i64)szName + 3 );if( p==0 ){sqlite3_mutex_leave(pVfsMutex);return SQLITE_NOMEM;}apNew = sqlite3Realloc(memdb_g.apMemStore,- sizeof(apNew[0])*(memdb_g.nMemStore+1) );+ sizeof(apNew[0])*(1+(i64)memdb_g.nMemStore) );if( apNew==0 ){sqlite3_free(p);sqlite3_mutex_leave(pVfsMutex);@@ -54095,7 +55603,7 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){** no fewer collisions than the no-op *1. */#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)-#define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))+#define BITVEC_NPTR ((u32)(BITVEC_USIZE/sizeof(Bitvec *)))/*@@ -54135,6 +55643,7 @@ struct Bitvec {} u;};+/*** Create a new bitmap object able to handle bits between 0 and iSize,** inclusive. Return a pointer to the new object. Return NULL if@@ -54244,7 +55753,9 @@ bitvec_set_rehash:}else{memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));memset(p->u.apSub, 0, sizeof(p->u.apSub));- p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;+ p->iDivisor = p->iSize/BITVEC_NPTR;+ if( (p->iSize%BITVEC_NPTR)!=0 ) p->iDivisor++;+ if( p->iDivisor<BITVEC_NBIT ) p->iDivisor = BITVEC_NBIT;rc = sqlite3BitvecSet(p, i);for(j=0; j<BITVEC_NINT; j++){if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);@@ -54278,7 +55789,7 @@ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){}}if( p->iSize<=BITVEC_NBIT ){- p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));+ p->u.aBitmap[i/BITVEC_SZELEM] &= ~(BITVEC_TELEM)(1<<(i&(BITVEC_SZELEM-1)));}else{unsigned int j;u32 *aiValues = pBuf;@@ -54321,6 +55832,52 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){return p->iSize;}+#ifdef SQLITE_DEBUG+/*+** Show the content of a Bitvec option and its children. Indent+** everything by n spaces. Add x to each bitvec value.+**+** From a debugger such as gdb, one can type:+**+** call sqlite3ShowBitvec(p)+**+** For some Bitvec p and see a recursive view of the Bitvec's content.+*/+static void showBitvec(Bitvec *p, int n, unsigned x){+ int i;+ if( p==0 ){+ printf("NULL\n");+ return;+ }+ printf("Bitvec 0x%p iSize=%u", p, p->iSize);+ if( p->iSize<=BITVEC_NBIT ){+ printf(" bitmap\n");+ printf("%*s bits:", n, "");+ for(i=1; i<=BITVEC_NBIT; i++){+ if( sqlite3BitvecTest(p,i) ) printf(" %u", x+(unsigned)i);+ }+ printf("\n");+ }else if( p->iDivisor==0 ){+ printf(" hash with %u entries\n", p->nSet);+ printf("%*s bits:", n, "");+ for(i=0; i<BITVEC_NINT; i++){+ if( p->u.aHash[i] ) printf(" %u", x+(unsigned)p->u.aHash[i]);+ }+ printf("\n");+ }else{+ printf(" sub-bitvec with iDivisor=%u\n", p->iDivisor);+ for(i=0; i<BITVEC_NPTR; i++){+ if( p->u.apSub[i]==0 ) continue;+ printf("%*s apSub[%d]=", n, "", i);+ showBitvec(p->u.apSub[i], n+4, i*p->iDivisor);+ }+ }+}+SQLITE_PRIVATE void sqlite3ShowBitvec(Bitvec *p){+ showBitvec(p, 0, 0);+}+#endif+#ifndef SQLITE_UNTESTABLE/*** Let V[] be an array of unsigned characters sufficient to hold@@ -54329,9 +55886,10 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){** individual bits within V.*/#define SETBIT(V,I) V[I>>3] |= (1<<(I&7))-#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))+#define CLEARBIT(V,I) V[I>>3] &= ~(BITVEC_TELEM)(1<<(I&7))#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0+/*** This routine runs an extensive test of the Bitvec code.**@@ -54340,7 +55898,7 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){** by 0, 1, or 3 operands, depending on the opcode. Another** opcode follows immediately after the last operand.**-** There are 6 opcodes numbered from 0 through 5. 0 is the+** There are opcodes numbered starting with 0. 0 is the** "halt" opcode and causes the test to end.**** 0 Halt and return the number of errors@@ -54349,18 +55907,25 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){** 3 N Set N randomly chosen bits** 4 N Clear N randomly chosen bits** 5 N S X Set N bits from S increment X in array only, not in bitvec+** 6 Invoice sqlite3ShowBitvec() on the Bitvec object so far+** 7 X Show compile-time parameters and the hash of X**** The opcodes 1 through 4 perform set and clear operations are performed** on both a Bitvec object and on a linear array of bits obtained from malloc.** Opcode 5 works on the linear array only, not on the Bitvec.** Opcode 5 is used to deliberately induce a fault in order to-** confirm that error detection works.+** confirm that error detection works. Opcodes 6 and greater are+** state output opcodes. Opcodes 6 and greater are no-ops unless+** SQLite has been compiled with SQLITE_DEBUG.**** At the conclusion of the test the linear array is compared** against the Bitvec object. If there are any differences,** an error is returned. If they are the same, zero is returned.**** If a memory allocation error occurs, return -1.+**+** sz is the size of the Bitvec. Or if sz is negative, make the size+** 2*(unsigned)(-sz) and disabled the linear vector check.*/SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){Bitvec *pBitvec = 0;@@ -54371,10 +55936,15 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){/* Allocate the Bitvec to be tested and a linear array of** bits to act as the reference */- pBitvec = sqlite3BitvecCreate( sz );- pV = sqlite3MallocZero( (sz+7)/8 + 1 );+ if( sz<=0 ){+ pBitvec = sqlite3BitvecCreate( 2*(unsigned)(-sz) );+ pV = 0;+ }else{+ pBitvec = sqlite3BitvecCreate( sz );+ pV = sqlite3MallocZero( (7+(i64)sz)/8 + 1 );+ }pTmpSpace = sqlite3_malloc64(BITVEC_SZ);- if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;+ if( pBitvec==0 || pTmpSpace==0 || (pV==0 && sz>0) ) goto bitvec_end;/* NULL pBitvec tests */sqlite3BitvecSet(0, 1);@@ -54383,6 +55953,24 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){/* Run the program */pc = i = 0;while( (op = aOp[pc])!=0 ){+ if( op>=6 ){+#ifdef SQLITE_DEBUG+ if( op==6 ){+ sqlite3ShowBitvec(pBitvec);+ }else if( op==7 ){+ printf("BITVEC_SZ = %d (%d by sizeof)\n",+ BITVEC_SZ, (int)sizeof(Bitvec));+ printf("BITVEC_USIZE = %d\n", (int)BITVEC_USIZE);+ printf("BITVEC_NELEM = %d\n", (int)BITVEC_NELEM);+ printf("BITVEC_NBIT = %d\n", (int)BITVEC_NBIT);+ printf("BITVEC_NINT = %d\n", (int)BITVEC_NINT);+ printf("BITVEC_MXHASH = %d\n", (int)BITVEC_MXHASH);+ printf("BITVEC_NPTR = %d\n", (int)BITVEC_NPTR);+ }+#endif+ pc++;+ continue;+ }switch( op ){case 1:case 2:@@ -54404,12 +55992,12 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){pc += nx;i = (i & 0x7fffffff)%sz;if( (op & 1)!=0 ){- SETBIT(pV, (i+1));+ if( pV ) SETBIT(pV, (i+1));if( op!=5 ){if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;}}else{- CLEARBIT(pV, (i+1));+ if( pV ) CLEARBIT(pV, (i+1));sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);}}@@ -54419,14 +56007,18 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){** match (rc==0). Change rc to non-zero if a discrepancy** is found.*/- rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)- + sqlite3BitvecTest(pBitvec, 0)- + (sqlite3BitvecSize(pBitvec) - sz);- for(i=1; i<=sz; i++){- if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){- rc = i;- break;+ if( pV ){+ rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)+ + sqlite3BitvecTest(pBitvec, 0)+ + (sqlite3BitvecSize(pBitvec) - sz);+ for(i=1; i<=sz; i++){+ if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){+ rc = i;+ break;+ }}+ }else{+ rc = 0;}/* Free allocated structure */@@ -55613,10 +57205,6 @@ static SQLITE_WSD struct PCacheGlobal {sqlite3_mutex *mutex; /* Mutex for accessing the following: */PgFreeslot *pFree; /* Free page blocks */int nFreeSlot; /* Number of unused pcache slots */- /* The following value requires a mutex to change. We skip the mutex on- ** reading because (1) most platforms read a 32-bit integer atomically and- ** (2) even if an incorrect value is read, no great harm is done since this- ** is really just an optimization. */int bUnderPressure; /* True if low on PAGECACHE memory */} pcache1_g;@@ -55664,7 +57252,7 @@ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){pcache1.nReserve = n>90 ? 10 : (n/10 + 1);pcache1.pStart = pBuf;pcache1.pFree = 0;- pcache1.bUnderPressure = 0;+ AtomicStore(&pcache1.bUnderPressure,0);while( n-- ){p = (PgFreeslot*)pBuf;p->pNext = pcache1.pFree;@@ -55732,7 +57320,7 @@ static void *pcache1Alloc(int nByte){if( p ){pcache1.pFree = pcache1.pFree->pNext;pcache1.nFreeSlot--;- pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;+ AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve);assert( pcache1.nFreeSlot>=0 );sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);@@ -55771,7 +57359,7 @@ static void pcache1Free(void *p){pSlot->pNext = pcache1.pFree;pcache1.pFree = pSlot;pcache1.nFreeSlot++;- pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;+ AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve);assert( pcache1.nFreeSlot<=pcache1.nSlot );sqlite3_mutex_leave(pcache1.mutex);}else{@@ -55902,7 +57490,7 @@ SQLITE_PRIVATE void sqlite3PageFree(void *p){*/static int pcache1UnderMemoryPressure(PCache1 *pCache){if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){- return pcache1.bUnderPressure;+ return AtomicLoad(&pcache1.bUnderPressure);}else{return sqlite3HeapNearlyFull();}@@ -55919,12 +57507,12 @@ static int pcache1UnderMemoryPressure(PCache1 *pCache){*/static void pcache1ResizeHash(PCache1 *p){PgHdr1 **apNew;- unsigned int nNew;- unsigned int i;+ u64 nNew;+ u32 i;assert( sqlite3_mutex_held(p->pGroup->mutex) );- nNew = p->nHash*2;+ nNew = 2*(u64)p->nHash;if( nNew<256 ){nNew = 256;}@@ -56147,7 +57735,7 @@ static void pcache1Destroy(sqlite3_pcache *p);static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){PCache1 *pCache; /* The newly created page cache */PGroup *pGroup; /* The group the new page cache will belong to */- int sz; /* Bytes of memory required to allocate the new cache */+ i64 sz; /* Bytes of memory required to allocate the new cache */assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );assert( szExtra < 300 );@@ -58035,6 +59623,9 @@ struct Pager {Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */char *zWal; /* File name for write-ahead log */#endif+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ sqlite3 *dbWal;+#endif};/*@@ -58626,7 +60217,7 @@ static void checkPage(PgHdr *pPg){** If an error occurs while reading from the journal file, an SQLite** error code is returned.*/-static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){+static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u64 nSuper){int rc; /* Return code */u32 len; /* Length in bytes of super-journal name */i64 szJ; /* Total size in bytes of journal file pJrnl */@@ -59181,6 +60772,15 @@ static void pager_unlock(Pager *pPager){if( pagerUseWal(pPager) ){assert( !isOpen(pPager->jfd) );+ if( pPager->eState==PAGER_ERROR ){+ /* If an IO error occurs in wal.c while attempting to wrap the wal file,+ ** then the Wal object may be holding a write-lock but no read-lock.+ ** This call ensures that the write-lock is dropped as well. We cannot+ ** have sqlite3WalEndReadTransaction() drop the write-lock, as it once+ ** did, because this would break "BEGIN EXCLUSIVE" handling for+ ** SQLITE_ENABLE_SETLK_TIMEOUT builds. */+ (void)sqlite3WalEndWriteTransaction(pPager->pWal);+ }sqlite3WalEndReadTransaction(pPager->pWal);pPager->eState = PAGER_OPEN;}else if( !pPager->exclusiveMode ){@@ -59862,12 +61462,12 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){char *zJournal; /* Pointer to one journal within MJ file */char *zSuperPtr; /* Space to hold super-journal filename */char *zFree = 0; /* Free this buffer */- int nSuperPtr; /* Amount of space allocated to zSuperPtr[] */+ i64 nSuperPtr; /* Amount of space allocated to zSuperPtr[] *//* Allocate space for both the pJournal and pSuper file descriptors.** If successful, open the super-journal file for reading.*/- pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);+ pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);if( !pSuper ){rc = SQLITE_NOMEM_BKPT;pJournal = 0;@@ -59885,11 +61485,14 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){*/rc = sqlite3OsFileSize(pSuper, &nSuperJournal);if( rc!=SQLITE_OK ) goto delsuper_out;- nSuperPtr = pVfs->mxPathname+1;+ nSuperPtr = 1 + (i64)pVfs->mxPathname;+ assert( nSuperJournal>=0 && nSuperPtr>0 );zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2);if( !zFree ){rc = SQLITE_NOMEM_BKPT;goto delsuper_out;+ }else{+ assert( nSuperJournal<=0x7fffffff );}zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;zSuperJournal = &zFree[4];@@ -60150,7 +61753,7 @@ static int pager_playback(Pager *pPager, int isHot){** for pageSize.*/zSuper = pPager->pTmpSpace;- rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);+ rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);if( rc==SQLITE_OK && zSuper[0] ){rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);}@@ -60289,7 +61892,7 @@ end_playback:** which case it requires 4 0x00 bytes in memory immediately before** the filename. */zSuper = &pPager->pTmpSpace[4];- rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);+ rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);testcase( rc!=SQLITE_OK );}if( rc==SQLITE_OK@@ -60932,14 +62535,27 @@ SQLITE_PRIVATE void sqlite3PagerSetFlags(unsigned pgFlags /* Various flags */){unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;- if( pPager->tempFile ){+ if( pPager->tempFile || level==PAGER_SYNCHRONOUS_OFF ){pPager->noSync = 1;pPager->fullSync = 0;pPager->extraSync = 0;}else{- pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;+ pPager->noSync = 0;pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;- pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;++ /* Set Pager.extraSync if "PRAGMA synchronous=EXTRA" is requested, or+ ** if the file-system supports F2FS style atomic writes. If this flag+ ** is set, SQLite syncs the directory to disk immediately after deleting+ ** a journal file in "PRAGMA journal_mode=DELETE" mode. */+ if( level==PAGER_SYNCHRONOUS_EXTRA+#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE+ || (sqlite3OsDeviceCharacteristics(pPager->fd) & SQLITE_IOCAP_BATCH_ATOMIC)+#endif+ ){+ pPager->extraSync = 1;+ }else{+ pPager->extraSync = 0;+ }}if( pPager->noSync ){pPager->syncFlags = 0;@@ -62060,6 +63676,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen(const char *zUri = 0; /* URI args to copy */int nUriByte = 1; /* Number of bytes of URI args at *zUri */+/* Figure out how much space is required for each journal file-handle** (there are two of them, the main journal and the sub-journal). */journalFileSize = ROUND8(sqlite3JournalSize(pVfs));@@ -62085,8 +63702,8 @@ SQLITE_PRIVATE int sqlite3PagerOpen(*/if( zFilename && zFilename[0] ){const char *z;- nPathname = pVfs->mxPathname+1;- zPathname = sqlite3DbMallocRaw(0, nPathname*2);+ nPathname = pVfs->mxPathname + 1;+ zPathname = sqlite3DbMallocRaw(0, 2*(i64)nPathname);if( zPathname==0 ){return SQLITE_NOMEM_BKPT;}@@ -62173,14 +63790,14 @@ SQLITE_PRIVATE int sqlite3PagerOpen(ROUND8(sizeof(*pPager)) + /* Pager structure */ROUND8(pcacheSize) + /* PCache object */ROUND8(pVfs->szOsFile) + /* The main db file */- journalFileSize * 2 + /* The two journal files */+ (u64)journalFileSize * 2 + /* The two journal files */SQLITE_PTRSIZE + /* Space to hold a pointer */4 + /* Database prefix */- nPathname + 1 + /* database filename */- nUriByte + /* query parameters */- nPathname + 8 + 1 + /* Journal filename */+ (u64)nPathname + 1 + /* database filename */+ (u64)nUriByte + /* query parameters */+ (u64)nPathname + 8 + 1 + /* Journal filename */#ifndef SQLITE_OMIT_WAL- nPathname + 4 + 1 + /* WAL filename */+ (u64)nPathname + 4 + 1 + /* WAL filename */#endif3 /* Terminator */);@@ -64831,7 +66448,7 @@ SQLITE_PRIVATE int sqlite3PagerCheckpoint(}if( pPager->pWal ){rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,- (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),+ (eMode<=SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),pPager->pBusyHandlerArg,pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,pnLog, pnCkpt@@ -64903,6 +66520,11 @@ static int pagerOpenWal(Pager *pPager){pPager->fd, pPager->zWal, pPager->exclusiveMode,pPager->journalSizeLimit, &pPager->pWal);+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ if( rc==SQLITE_OK ){+ sqlite3WalDb(pPager->pWal, pPager->dbWal);+ }+#endif}pagerFixMaplimit(pPager);@@ -65022,6 +66644,7 @@ SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){** blocking locks are required.*/SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){+ pPager->dbWal = db;if( pagerUseWal(pPager) ){sqlite3WalDb(pPager->pWal, db);}@@ -65635,6 +67258,11 @@ struct WalCkptInfo {/*** An open write-ahead log file is represented by an instance of the** following object.+**+** writeLock:+** This is usually set to 1 whenever the WRITER lock is held. However,+** if it is set to 2, then the WRITER lock is held but must be released+** by walHandleException() if a SEH exception is thrown.*/struct Wal {sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */@@ -65725,9 +67353,13 @@ struct WalIterator {u32 *aPgno; /* Array of page numbers. */int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */int iZero; /* Frame number associated with aPgno[0] */- } aSegment[1]; /* One for every 32KB page in the wal-index */+ } aSegment[FLEXARRAY]; /* One for every 32KB page in the wal-index */};+/* Size (in bytes) of a WalIterator object suitable for N or fewer segments */+#define SZ_WALITERATOR(N) \+ (offsetof(WalIterator,aSegment)+(N)*sizeof(struct WalSegment))+/*** Define the parameters of the hash tables in the wal-index file. There** is a hash-table following every HASHTABLE_NPAGE page numbers in the@@ -65886,7 +67518,7 @@ static SQLITE_NOINLINE int walIndexPageRealloc(/* Enlarge the pWal->apWiData[] array if required */if( pWal->nWiData<=iPage ){- sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);+ sqlite3_int64 nByte = sizeof(u32*)*(1+(i64)iPage);volatile u32 **apNew;apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);if( !apNew ){@@ -65995,10 +67627,8 @@ static void walChecksumBytes(s1 = s2 = 0;}- assert( nByte>=8 );- assert( (nByte&0x00000007)==0 );- assert( nByte<=65536 );- assert( nByte%4==0 );+ /* nByte is a multiple of 8 between 8 and 65536 */+ assert( nByte>=8 && (nByte&7)==0 && nByte<=65536 );if( !nativeCksum ){do {@@ -67088,8 +68718,7 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){/* Allocate space for the WalIterator object. */nSegment = walFramePage(iLast) + 1;- nByte = sizeof(WalIterator)- + (nSegment-1)*sizeof(struct WalSegment)+ nByte = SZ_WALITERATOR(nSegment)+ iLast*sizeof(ht_slot);p = (WalIterator *)sqlite3_malloc64(nByte+ sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)@@ -67160,7 +68789,7 @@ static int walEnableBlockingMs(Wal *pWal, int nMs){static int walEnableBlocking(Wal *pWal){int res = 0;if( pWal->db ){- int tmout = pWal->db->busyTimeout;+ int tmout = pWal->db->setlkTimeout;if( tmout ){res = walEnableBlockingMs(pWal, tmout);}@@ -67381,68 +69010,82 @@ static int walCheckpoint(&& (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK){u32 nBackfill = pInfo->nBackfill;- pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;-- /* Sync the WAL to disk */- rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));-- /* If the database may grow as a result of this checkpoint, hint- ** about the eventual size of the db file to the VFS layer.- */- if( rc==SQLITE_OK ){- i64 nReq = ((i64)mxPage * szPage);- i64 nSize; /* Current size of database file */- sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);- rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);- if( rc==SQLITE_OK && nSize<nReq ){- if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){- /* If the size of the final database is larger than the current- ** database plus the amount of data in the wal file, plus the- ** maximum size of the pending-byte page (65536 bytes), then- ** must be corruption somewhere. */- rc = SQLITE_CORRUPT_BKPT;- }else{- sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);+ WalIndexHdr *pLive = (WalIndexHdr*)walIndexHdr(pWal);++ /* Now that read-lock slot 0 is locked, check that the wal has not been+ ** wrapped since the header was read for this checkpoint. If it was, then+ ** there was no work to do anyway. In this case the+ ** (pInfo->nBackfill<pWal->hdr.mxFrame) test above only passed because+ ** pInfo->nBackfill had already been set to 0 by the writer that wrapped+ ** the wal file. It would also be dangerous to proceed, as there may be+ ** fewer than pWal->hdr.mxFrame valid frames in the wal file. */+ int bChg = memcmp(pLive->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt));+ if( 0==bChg ){+ pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;++ /* Sync the WAL to disk */+ rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));++ /* If the database may grow as a result of this checkpoint, hint+ ** about the eventual size of the db file to the VFS layer.+ */+ if( rc==SQLITE_OK ){+ i64 nReq = ((i64)mxPage * szPage);+ i64 nSize; /* Current size of database file */+ sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);+ rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);+ if( rc==SQLITE_OK && nSize<nReq ){+ if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){+ /* If the size of the final database is larger than the current+ ** database plus the amount of data in the wal file, plus the+ ** maximum size of the pending-byte page (65536 bytes), then+ ** must be corruption somewhere. */+ rc = SQLITE_CORRUPT_BKPT;+ }else{+ sqlite3OsFileControlHint(+ pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);+ }}- }-- }- /* Iterate through the contents of the WAL, copying data to the db file */- while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){- i64 iOffset;- assert( walFramePgno(pWal, iFrame)==iDbpage );- SEH_INJECT_FAULT;- if( AtomicLoad(&db->u1.isInterrupted) ){- rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;- break;- }- if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){- continue;}- iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;- /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */- rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);- if( rc!=SQLITE_OK ) break;- iOffset = (iDbpage-1)*(i64)szPage;- testcase( IS_BIG_INT(iOffset) );- rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);- if( rc!=SQLITE_OK ) break;- }- sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);- /* If work was actually accomplished... */- if( rc==SQLITE_OK ){- if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){- i64 szDb = pWal->hdr.nPage*(i64)szPage;- testcase( IS_BIG_INT(szDb) );- rc = sqlite3OsTruncate(pWal->pDbFd, szDb);- if( rc==SQLITE_OK ){- rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));+ /* Iterate through the contents of the WAL, copying data to the+ ** db file */+ while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){+ i64 iOffset;+ assert( walFramePgno(pWal, iFrame)==iDbpage );+ SEH_INJECT_FAULT;+ if( AtomicLoad(&db->u1.isInterrupted) ){+ rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;+ break;+ }+ if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){+ continue;}+ iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;+ /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */+ rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);+ if( rc!=SQLITE_OK ) break;+ iOffset = (iDbpage-1)*(i64)szPage;+ testcase( IS_BIG_INT(iOffset) );+ rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);+ if( rc!=SQLITE_OK ) break;}+ sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);++ /* If work was actually accomplished... */if( rc==SQLITE_OK ){- AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;+ if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){+ i64 szDb = pWal->hdr.nPage*(i64)szPage;+ testcase( IS_BIG_INT(szDb) );+ rc = sqlite3OsTruncate(pWal->pDbFd, szDb);+ if( rc==SQLITE_OK ){+ rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));+ }+ }+ if( rc==SQLITE_OK ){+ AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;+ }}}@@ -67546,7 +69189,9 @@ static int walHandleException(Wal *pWal){static const int S = 1;static const int E = (1<<SQLITE_SHM_NLOCK);int ii;- u32 mUnlock = pWal->lockMask & ~(+ u32 mUnlock;+ if( pWal->writeLock==2 ) pWal->writeLock = 0;+ mUnlock = pWal->lockMask & ~((pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))| (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)| (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)@@ -67818,7 +69463,12 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){if( bWriteLock|| SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1))){- pWal->writeLock = 1;+ /* If the write-lock was just obtained, set writeLock to 2 instead of+ ** the usual 1. This causes walIndexPage() to behave as if the+ ** write-lock were held (so that it allocates new pages as required),+ ** and walHandleException() to unlock the write-lock if a SEH exception+ ** is thrown. */+ if( !bWriteLock ) pWal->writeLock = 2;if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){badHdr = walIndexTryHdr(pWal, pChanged);if( badHdr ){@@ -68182,7 +69832,6 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){rc = walIndexReadHdr(pWal, pChanged);}#ifdef SQLITE_ENABLE_SETLK_TIMEOUT- walDisableBlocking(pWal);if( rc==SQLITE_BUSY_TIMEOUT ){rc = SQLITE_BUSY;*pCnt |= WAL_RETRY_BLOCKED_MASK;@@ -68197,6 +69846,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){** WAL_RETRY this routine will be called again and will probably be** right on the second iteration.*/+ (void)walEnableBlocking(pWal);if( pWal->apWiData[0]==0 ){/* This branch is taken when the xShmMap() method returns SQLITE_BUSY.** We assume this is a transient condition, so return WAL_RETRY. The@@ -68213,6 +69863,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){rc = SQLITE_BUSY_RECOVERY;}}+ walDisableBlocking(pWal);if( rc!=SQLITE_OK ){return rc;}@@ -68603,8 +70254,11 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){** read-lock.*/SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){- sqlite3WalEndWriteTransaction(pWal);+#ifndef SQLITE_ENABLE_SETLK_TIMEOUT+ assert( pWal->writeLock==0 || pWal->readLock<0 );+#endifif( pWal->readLock>=0 ){+ (void)sqlite3WalEndWriteTransaction(pWal);walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));pWal->readLock = -1;}@@ -68797,7 +70451,7 @@ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){** read-transaction was even opened, making this call a no-op.** Return early. */if( pWal->writeLock ){- assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );+ assert( !memcmp(&pWal->hdr,(void*)pWal->apWiData[0],sizeof(WalIndexHdr)) );return SQLITE_OK;}#endif@@ -68897,6 +70551,7 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pif( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);}SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )+ pWal->iReCksum = 0;}return rc;}@@ -68944,6 +70599,9 @@ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){walCleanupHash(pWal);}SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; )+ if( pWal->iReCksum>pWal->hdr.mxFrame ){+ pWal->iReCksum = 0;+ }}return rc;@@ -69409,7 +71067,8 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(/* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked** in the SQLITE_CHECKPOINT_PASSIVE mode. */- assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );+ assert( SQLITE_CHECKPOINT_NOOP<SQLITE_CHECKPOINT_PASSIVE );+ assert( eMode>SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );if( pWal->readOnly ) return SQLITE_READONLY;WALTRACE(("WAL%p: checkpoint begins\n", pWal));@@ -69426,31 +71085,35 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,** it will not be invoked in this case.*/- rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);- testcase( rc==SQLITE_BUSY );- testcase( rc!=SQLITE_OK && xBusy2!=0 );- if( rc==SQLITE_OK ){- pWal->ckptLock = 1;+ if( eMode!=SQLITE_CHECKPOINT_NOOP ){+ rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);+ testcase( rc==SQLITE_BUSY );+ testcase( rc!=SQLITE_OK && xBusy2!=0 );+ if( rc==SQLITE_OK ){+ pWal->ckptLock = 1;- /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and- ** TRUNCATE modes also obtain the exclusive "writer" lock on the database- ** file.- **- ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained- ** immediately, and a busy-handler is configured, it is invoked and the- ** writer lock retried until either the busy-handler returns 0 or the- ** lock is successfully obtained.- */- if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){- rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);- if( rc==SQLITE_OK ){- pWal->writeLock = 1;- }else if( rc==SQLITE_BUSY ){- eMode2 = SQLITE_CHECKPOINT_PASSIVE;- xBusy2 = 0;- rc = SQLITE_OK;+ /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART+ ** and TRUNCATE modes also obtain the exclusive "writer" lock on the+ ** database file.+ **+ ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained+ ** immediately, and a busy-handler is configured, it is invoked and the+ ** writer lock retried until either the busy-handler returns 0 or the+ ** lock is successfully obtained.+ */+ if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){+ rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);+ if( rc==SQLITE_OK ){+ pWal->writeLock = 1;+ }else if( rc==SQLITE_BUSY ){+ eMode2 = SQLITE_CHECKPOINT_PASSIVE;+ xBusy2 = 0;+ rc = SQLITE_OK;+ }}}+ }else{+ rc = SQLITE_OK;}@@ -69464,7 +71127,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(** immediately and do a partial checkpoint if it cannot obtain it. */walDisableBlocking(pWal);rc = walIndexReadHdr(pWal, &isChanged);- if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);+ if( eMode2>SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal);if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){sqlite3OsUnfetch(pWal->pDbFd, 0, 0);}@@ -69472,9 +71135,10 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(/* Copy data from the log to the database file. */if( rc==SQLITE_OK ){+ sqlite3FaultSim(660);if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){rc = SQLITE_CORRUPT_BKPT;- }else{+ }else if( eMode2!=SQLITE_CHECKPOINT_NOOP ){rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf);}@@ -69502,7 +71166,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(sqlite3WalDb(pWal, 0);/* Release the locks. */- sqlite3WalEndWriteTransaction(pWal);+ (void)sqlite3WalEndWriteTransaction(pWal);if( pWal->ckptLock ){walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);pWal->ckptLock = 0;@@ -70246,6 +71910,12 @@ struct CellInfo {*/#define BTCURSOR_MAX_DEPTH 20+/*+** Maximum amount of storage local to a database page, regardless of+** page size.+*/+#define BT_MAX_LOCAL 65501 /* 65536 - 35 */+/*** A cursor is a pointer to a particular entry within a particular** b-tree within a database file.@@ -70654,7 +72324,7 @@ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){*/static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){int i;- int skipOk = 1;+ u8 skipOk = 1;Btree *p;assert( sqlite3_mutex_held(db->mutex) );for(i=0; i<db->nDb; i++){@@ -71510,7 +73180,7 @@ static int saveCursorKey(BtCursor *pCur){** below. */void *pKey;pCur->nKey = sqlite3BtreePayloadSize(pCur);- pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );+ pKey = sqlite3Malloc( ((i64)pCur->nKey) + 9 + 8 );if( pKey ){rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);if( rc==SQLITE_OK ){@@ -71653,7 +73323,7 @@ static int btreeMoveto(assert( nKey==(i64)(int)nKey );pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;- sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);+ sqlite3VdbeRecordUnpack((int)nKey, pKey, pIdxKey);if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){rc = SQLITE_CORRUPT_BKPT;}else{@@ -71800,7 +73470,7 @@ SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){*/SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );- pCur->hints = x;+ pCur->hints = (u8)x;}@@ -71994,14 +73664,15 @@ static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){int maxLocal; /* Maximum amount of payload held locally */maxLocal = pPage->maxLocal;+ assert( nPayload>=0 );if( nPayload<=maxLocal ){- return nPayload;+ return (int)nPayload;}else{int minLocal; /* Minimum amount of payload held locally */int surplus; /* Overflow payload available for local storage */minLocal = pPage->minLocal;- surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);- return ( surplus <= maxLocal ) ? surplus : minLocal;+ surplus = (int)(minLocal +(nPayload - minLocal)%(pPage->pBt->usableSize-4));+ return (surplus <= maxLocal) ? surplus : minLocal;}}@@ -72111,11 +73782,13 @@ static void btreeParseCellPtr(pInfo->pPayload = pIter;testcase( nPayload==pPage->maxLocal );testcase( nPayload==(u32)pPage->maxLocal+1 );+ assert( nPayload>=0 );+ assert( pPage->maxLocal <= BT_MAX_LOCAL );if( nPayload<=pPage->maxLocal ){/* This is the (easy) common case where the entire payload fits** on the local page. No overflow is required.*/- pInfo->nSize = nPayload + (u16)(pIter - pCell);+ pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);if( pInfo->nSize<4 ) pInfo->nSize = 4;pInfo->nLocal = (u16)nPayload;}else{@@ -72148,11 +73821,13 @@ static void btreeParseCellPtrIndex(pInfo->pPayload = pIter;testcase( nPayload==pPage->maxLocal );testcase( nPayload==(u32)pPage->maxLocal+1 );+ assert( nPayload>=0 );+ assert( pPage->maxLocal <= BT_MAX_LOCAL );if( nPayload<=pPage->maxLocal ){/* This is the (easy) common case where the entire payload fits** on the local page. No overflow is required.*/- pInfo->nSize = nPayload + (u16)(pIter - pCell);+ pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);if( pInfo->nSize<4 ) pInfo->nSize = 4;pInfo->nLocal = (u16)nPayload;}else{@@ -72691,24 +74366,24 @@ static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){** at the end of the page. So do additional corruption checks inside this** routine and return SQLITE_CORRUPT if any problems are found.*/-static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){- u16 iPtr; /* Address of ptr to next freeblock */- u16 iFreeBlk; /* Address of the next freeblock */+static int freeSpace(MemPage *pPage, int iStart, int iSize){+ int iPtr; /* Address of ptr to next freeblock */+ int iFreeBlk; /* Address of the next freeblock */u8 hdr; /* Page header size. 0 or 100 */- u8 nFrag = 0; /* Reduction in fragmentation */- u16 iOrigSize = iSize; /* Original value of iSize */- u16 x; /* Offset to cell content area */- u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */+ int nFrag = 0; /* Reduction in fragmentation */+ int iOrigSize = iSize; /* Original value of iSize */+ int x; /* Offset to cell content area */+ int iEnd = iStart + iSize; /* First byte past the iStart buffer */unsigned char *data = pPage->aData; /* Page content */u8 *pTmp; /* Temporary ptr into data[] */assert( pPage->pBt!=0 );assert( sqlite3PagerIswriteable(pPage->pDbPage) );assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );- assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );+ assert( CORRUPT_DB || iEnd <= (int)pPage->pBt->usableSize );assert( sqlite3_mutex_held(pPage->pBt->mutex) );assert( iSize>=4 ); /* Minimum cell size is 4 */- assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );+ assert( CORRUPT_DB || iStart<=(int)pPage->pBt->usableSize-4 );/* The list of freeblocks must be in ascending order. Find the** spot on the list where iStart should be inserted.@@ -72725,7 +74400,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){}iPtr = iFreeBlk;}- if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */+ if( iFreeBlk>(int)pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */return SQLITE_CORRUPT_PAGE(pPage);}assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );@@ -72740,7 +74415,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){nFrag = iFreeBlk - iEnd;if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);- if( iEnd > pPage->pBt->usableSize ){+ if( iEnd > (int)pPage->pBt->usableSize ){return SQLITE_CORRUPT_PAGE(pPage);}iSize = iEnd - iStart;@@ -72761,7 +74436,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){}}if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);- data[hdr+7] -= nFrag;+ data[hdr+7] -= (u8)nFrag;}pTmp = &data[hdr+5];x = get2byte(pTmp);@@ -72782,7 +74457,8 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){/* Insert the new freeblock into the freelist */put2byte(&data[iPtr], iStart);put2byte(&data[iStart], iFreeBlk);- put2byte(&data[iStart+2], iSize);+ assert( iSize>=0 && iSize<=0xffff );+ put2byte(&data[iStart+2], (u16)iSize);}pPage->nFree += iOrigSize;return SQLITE_OK;@@ -73008,7 +74684,7 @@ static int btreeInitPage(MemPage *pPage){assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );pPage->maskPage = (u16)(pBt->pageSize - 1);pPage->nOverflow = 0;- pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;+ pPage->cellOffset = (u16)(pPage->hdrOffset + 8 + pPage->childPtrSize);pPage->aCellIdx = data + pPage->childPtrSize + 8;pPage->aDataEnd = pPage->aData + pBt->pageSize;pPage->aDataOfst = pPage->aData + pPage->childPtrSize;@@ -73042,8 +74718,8 @@ static int btreeInitPage(MemPage *pPage){static void zeroPage(MemPage *pPage, int flags){unsigned char *data = pPage->aData;BtShared *pBt = pPage->pBt;- u8 hdr = pPage->hdrOffset;- u16 first;+ int hdr = pPage->hdrOffset;+ int first;assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );@@ -73060,7 +74736,7 @@ static void zeroPage(MemPage *pPage, int flags){put2byte(&data[hdr+5], pBt->usableSize);pPage->nFree = (u16)(pBt->usableSize - first);decodeFlags(pPage, flags);- pPage->cellOffset = first;+ pPage->cellOffset = (u16)first;pPage->aDataEnd = &data[pBt->pageSize];pPage->aCellIdx = &data[first];pPage->aDataOfst = &data[pPage->childPtrSize];@@ -73631,6 +75307,7 @@ static int removeFromSharingList(BtShared *pBt){sqlite3_mutex_leave(pMainMtx);return removed;#else+ UNUSED_PARAMETER( pBt );return 1;#endif}@@ -73846,8 +75523,12 @@ SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve,BtShared *pBt = p->pBt;assert( nReserve>=0 && nReserve<=255 );sqlite3BtreeEnter(p);- pBt->nReserveWanted = nReserve;+ pBt->nReserveWanted = (u8)nReserve;x = pBt->pageSize - pBt->usableSize;+ if( x==nReserve && (pageSize==0 || (u32)pageSize==pBt->pageSize) ){+ sqlite3BtreeLeave(p);+ return SQLITE_OK;+ }if( nReserve<x ) nReserve = x;if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){sqlite3BtreeLeave(p);@@ -73952,7 +75633,7 @@ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );if( newFlag>=0 ){p->pBt->btsFlags &= ~BTS_FAST_SECURE;- p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;+ p->pBt->btsFlags |= (u16)(BTS_SECURE_DELETE*newFlag);}b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;sqlite3BtreeLeave(p);@@ -74472,6 +76153,13 @@ static SQLITE_NOINLINE int btreeBeginTrans((void)sqlite3PagerWalWriteLock(pPager, 0);unlockBtreeIfUnused(pBt);}+#if defined(SQLITE_ENABLE_SETLK_TIMEOUT)+ if( rc==SQLITE_BUSY_TIMEOUT ){+ /* If a blocking lock timed out, break out of the loop here so that+ ** the busy-handler is not invoked. */+ break;+ }+#endif}while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&btreeInvokeBusyHandler(pBt) );sqlite3PagerWalDb(pPager, 0);@@ -75883,7 +77571,7 @@ static int accessPayload(getCellInfo(pCur);aPayload = pCur->info.pPayload;- assert( offset+amt <= pCur->info.nPayload );+ assert( (u64)offset+(u64)amt <= (u64)pCur->info.nPayload );assert( aPayload > pPage->aData );if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){@@ -76430,6 +78118,30 @@ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){return rc;}+/* Set *pRes to 1 (true) if the BTree pointed to by cursor pCur contains zero+** rows of content. Set *pRes to 0 (false) if the table contains content.+** Return SQLITE_OK on success or some error code (ex: SQLITE_NOMEM) if+** something goes wrong.+*/+SQLITE_PRIVATE int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes){+ int rc;++ assert( cursorOwnsBtShared(pCur) );+ assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );+ if( pCur->eState==CURSOR_VALID ){+ *pRes = 0;+ return SQLITE_OK;+ }+ rc = moveToRoot(pCur);+ if( rc==SQLITE_EMPTY ){+ *pRes = 1;+ rc = SQLITE_OK;+ }else{+ *pRes = 0;+ }+ return rc;+}+#ifdef SQLITE_DEBUG/* The cursors is CURSOR_VALID and has BTCF_AtLast set. Verify that** this flags are true for a consistent database.@@ -76649,8 +78361,8 @@ moveto_table_finish:}/*-** Compare the "idx"-th cell on the page the cursor pCur is currently-** pointing to to pIdxKey using xRecordCompare. Return negative or+** Compare the "idx"-th cell on the page pPage against the key+** pointing to by pIdxKey using xRecordCompare. Return negative or** zero if the cell is less than or equal pIdxKey. Return positive** if unknown.**@@ -76665,12 +78377,11 @@ moveto_table_finish:** a positive value as that will cause the optimization to be skipped.*/static int indexCellCompare(- BtCursor *pCur,+ MemPage *pPage,int idx,UnpackedRecord *pIdxKey,RecordCompare xRecordCompare){- MemPage *pPage = pCur->pPage;int c;int nCell; /* Size of the pCell cell in bytes */u8 *pCell = findCellPastPtr(pPage, idx);@@ -76779,14 +78490,14 @@ SQLITE_PRIVATE int sqlite3BtreeIndexMoveto(){int c;if( pCur->ix==pCur->pPage->nCell-1- && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0+ && (c = indexCellCompare(pCur->pPage,pCur->ix,pIdxKey,xRecordCompare))<=0&& pIdxKey->errCode==SQLITE_OK){*pRes = c;return SQLITE_OK; /* Cursor already pointing at the correct spot */}if( pCur->iPage>0- && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0+ && indexCellCompare(pCur->pPage, 0, pIdxKey, xRecordCompare)<=0&& pIdxKey->errCode==SQLITE_OK){pCur->curFlags &= ~(BTCF_ValidOvfl|BTCF_AtLast);@@ -76881,7 +78592,7 @@ bypass_moveto_root:rc = SQLITE_CORRUPT_PAGE(pPage);goto moveto_index_finish;}- pCellKey = sqlite3Malloc( nCell+nOverrun );+ pCellKey = sqlite3Malloc( (u64)nCell+(u64)nOverrun );if( pCellKey==0 ){rc = SQLITE_NOMEM_BKPT;goto moveto_index_finish;@@ -77003,7 +78714,7 @@ SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){n = pCur->pPage->nCell;for(i=0; i<pCur->iPage; i++){- n *= pCur->apPage[i]->nCell;+ n *= pCur->apPage[i]->nCell+1;}return n;}@@ -78400,7 +80111,8 @@ static int rebuildPage(}/* The pPg->nFree field is now set incorrectly. The caller will fix it. */- pPg->nCell = nCell;+ assert( nCell < 10922 );+ pPg->nCell = (u16)nCell;pPg->nOverflow = 0;put2byte(&aData[hdr+1], 0);@@ -78647,9 +80359,13 @@ static int editPage(if( pageInsertArray(pPg, pBegin, &pData, pCellptr,iNew+nCell, nNew-nCell, pCArray- ) ) goto editpage_fail;+ )+ ){+ goto editpage_fail;+ }- pPg->nCell = nNew;+ assert( nNew < 10922 );+ pPg->nCell = (u16)nNew;pPg->nOverflow = 0;put2byte(&aData[hdr+3], pPg->nCell);@@ -78958,7 +80674,7 @@ static int balance_nonroot(int pageFlags; /* Value of pPage->aData[0] */int iSpace1 = 0; /* First unused byte of aSpace1[] */int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */- int szScratch; /* Size of scratch memory requested */+ u64 szScratch; /* Size of scratch memory requested */MemPage *apOld[NB]; /* pPage and up to two siblings */MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */u8 *pRight; /* Location in parent of right-sibling pointer */@@ -79455,7 +81171,12 @@ static int balance_nonroot(** of the right-most new sibling page is set to the value that was** originally in the same field of the right-most old sibling page. */if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){- MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];+ MemPage *pOld;+ if( nNew>nOld ){+ pOld = apNew[nOld-1];+ }else{+ pOld = apOld[nOld-1];+ }memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);}@@ -80243,7 +81964,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(if( pCur->info.nKey==pX->nKey ){BtreePayload x2;x2.pData = pX->pKey;- x2.nData = pX->nKey;+ x2.nData = (int)pX->nKey; assert( pX->nKey<=0x7fffffff );x2.nZero = 0;return btreeOverwriteCell(pCur, &x2);}@@ -80424,7 +82145,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64getCellInfo(pSrc);if( pSrc->info.nPayload<0x80 ){- *(aOut++) = pSrc->info.nPayload;+ *(aOut++) = (u8)pSrc->info.nPayload;}else{aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);}@@ -80437,7 +82158,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64nRem = pSrc->info.nPayload;if( nIn==nRem && nIn<pDest->pPage->maxLocal ){memcpy(aOut, aIn, nIn);- pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);+ pBt->nPreformatSize = nIn + (int)(aOut - pBt->pTmpSpace);return SQLITE_OK;}else{int rc = SQLITE_OK;@@ -80449,7 +82170,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64u32 nOut; /* Size of output buffer aOut[] */nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);- pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);+ pBt->nPreformatSize = (int)nOut + (int)(aOut - pBt->pTmpSpace);if( nOut<pSrc->info.nPayload ){pPgnoOut = &aOut[nOut];pBt->nPreformatSize += 4;@@ -82070,6 +83791,7 @@ SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){*/SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){BtShared *pBt = p->pBt;+ assert( nBytes==0 || nBytes==sizeof(Schema) );sqlite3BtreeEnter(p);if( !pBt->pSchema && nBytes ){pBt->pSchema = sqlite3DbMallocZero(0, nBytes);@@ -82086,6 +83808,7 @@ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void*/SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){int rc;+ UNUSED_PARAMETER(p); /* only used in DEBUG builds */assert( sqlite3_mutex_held(p->db->mutex) );sqlite3BtreeEnter(p);rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);@@ -83186,7 +84909,7 @@ static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){** corresponding string value, then it is important that the string be** derived from the numeric value, not the other way around, to ensure** that the index and table are consistent. See ticket-** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for+** https://sqlite.org/src/info/343634942dd54ab (2018-01-31) for** an example.**** This routine looks at pMem to verify that if it has both a numeric@@ -83372,7 +85095,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){return;}if( pMem->enc!=SQLITE_UTF8 ) return;- if( NEVER(pMem->z==0) ) return;+ assert( pMem->z!=0 );if( pMem->flags & MEM_Dyn ){if( pMem->xDel==sqlite3_free&& sqlite3_msize(pMem->z) >= (u64)(pMem->n+1)@@ -84271,6 +85994,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){return SQLITE_NOMEM_BKPT;}+ assert( pMem->z!=0 );memcpy(pMem->z, z, nAlloc);}else{sqlite3VdbeMemRelease(pMem);@@ -84321,7 +86045,12 @@ SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(){int rc;pMem->flags = MEM_Null;- if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){+ testcase( amt==SQLITE_MAX_ALLOCATION_SIZE-1 );+ testcase( amt==SQLITE_MAX_ALLOCATION_SIZE );+ if( amt>=SQLITE_MAX_ALLOCATION_SIZE ){+ return SQLITE_NOMEM_BKPT;+ }+ if( (u64)amt + (u64)offset > (u64)sqlite3BtreeMaxRecordSize(pCur) ){return SQLITE_CORRUPT_BKPT;}if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){@@ -84485,7 +86214,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){if( pRec==0 ){Index *pIdx = p->pIdx; /* Index being probed */- int nByte; /* Bytes of space to allocate */+ i64 nByte; /* Bytes of space to allocate */int i; /* Counter variable */int nCol = pIdx->nColumn; /* Number of index columns including rowid */@@ -84551,7 +86280,7 @@ static int valueFromFunction(){sqlite3_context ctx; /* Context object for function invocation */sqlite3_value **apVal = 0; /* Function arguments */- int nVal = 0; /* Size of apVal[] array */+ int nVal = 0; /* Number of function arguments */FuncDef *pFunc = 0; /* Function definition */sqlite3_value *pVal = 0; /* New value */int rc = SQLITE_OK; /* Return code */@@ -85549,12 +87278,10 @@ SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(int eCallCtx /* Calling context */){Vdbe *v = pParse->pVdbe;- int nByte;int addr;sqlite3_context *pCtx;assert( v );- nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);- pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);+ pCtx = sqlite3DbMallocRawNN(pParse->db, SZ_CONTEXT(nArg));if( pCtx==0 ){assert( pParse->db->mallocFailed );freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);@@ -85830,7 +87557,7 @@ static Op *opIterNext(VdbeOpIter *p){}if( pRet->p4type==P4_SUBPROGRAM ){- int nByte = (p->nSub+1)*sizeof(SubProgram*);+ i64 nByte = (1+(u64)p->nSub)*sizeof(SubProgram*);int j;for(j=0; j<p->nSub; j++){if( p->apSub[j]==pRet->p4.pProgram ) break;@@ -85960,8 +87687,8 @@ SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){** (1) For each jump instruction with a negative P2 value (a label)** resolve the P2 value to an actual address.**-** (2) Compute the maximum number of arguments used by any SQL function-** and store that value in *pMaxFuncArgs.+** (2) Compute the maximum number of arguments used by the xUpdate/xFilter+** methods of any virtual table and store that value in *pMaxVtabArgs.**** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately** indicate what the prepared statement actually does.@@ -85974,8 +87701,8 @@ SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){** script numbers the opcodes correctly. Changes to this routine must be** coordinated with changes to mkopcodeh.tcl.*/-static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){- int nMaxArgs = *pMaxFuncArgs;+static void resolveP2Values(Vdbe *p, int *pMaxVtabArgs){+ int nMaxVtabArgs = *pMaxVtabArgs;Op *pOp;Parse *pParse = p->pParse;int *aLabel = pParse->aLabel;@@ -86020,15 +87747,19 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){}#ifndef SQLITE_OMIT_VIRTUALTABLEcase OP_VUpdate: {- if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;+ if( pOp->p2>nMaxVtabArgs ) nMaxVtabArgs = pOp->p2;break;}case OP_VFilter: {int n;+ /* The instruction immediately prior to VFilter will be an+ ** OP_Integer that sets the "argc" value for the VFilter. See+ ** the code where OP_VFilter is generated at tag-20250207a. */assert( (pOp - p->aOp) >= 3 );assert( pOp[-1].opcode==OP_Integer );+ assert( pOp[-1].p2==pOp->p3+1 );n = pOp[-1].p1;- if( n>nMaxArgs ) nMaxArgs = n;+ if( n>nMaxVtabArgs ) nMaxVtabArgs = n;/* Fall through into the default case *//* no break */ deliberate_fall_through}@@ -86069,7 +87800,7 @@ resolve_p2_values_loop_exit:pParse->aLabel = 0;}pParse->nLabel = 0;- *pMaxFuncArgs = nMaxArgs;+ *pMaxVtabArgs = nMaxVtabArgs;assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );}@@ -86298,7 +88029,7 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus(const char *zName /* Name of table or index being scanned */){if( IS_STMT_SCANSTATUS(p->db) ){- sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);+ i64 nByte = (1+(i64)p->nScan) * sizeof(ScanStatus);ScanStatus *aNew;aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);if( aNew ){@@ -86408,6 +88139,9 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){*/SQLITE_PRIVATE void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){VdbeOp *pOp = sqlite3VdbeGetLastOp(p);+#ifdef SQLITE_DEBUG+ while( pOp->opcode==OP_ReleaseReg ) pOp--;+#endifif( pOp->p3==iDest && pOp->opcode==OP_Column ){pOp->p5 |= OPFLAG_TYPEOFARG;}@@ -87747,7 +89481,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(int nVar; /* Number of parameters */int nMem; /* Number of VM memory registers */int nCursor; /* Number of cursors required */- int nArg; /* Number of arguments in subprograms */+ int nArg; /* Max number args to xFilter or xUpdate */int n; /* Loop counter */struct ReusableSpace x; /* Reusable bulk memory */@@ -87819,6 +89553,9 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));}}+#ifdef SQLITE_DEBUG+ p->napArg = nArg;+#endifif( db->mallocFailed ){p->nVar = 0;@@ -88090,10 +89827,12 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))|| nTrans<=1){- for(i=0; rc==SQLITE_OK && i<db->nDb; i++){- Btree *pBt = db->aDb[i].pBt;- if( pBt ){- rc = sqlite3BtreeCommitPhaseOne(pBt, 0);+ if( needXcommit ){+ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){+ Btree *pBt = db->aDb[i].pBt;+ if( sqlite3BtreeTxnState(pBt)>=SQLITE_TXN_WRITE ){+ rc = sqlite3BtreeCommitPhaseOne(pBt, 0);+ }}}@@ -88104,7 +89843,9 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){*/for(i=0; rc==SQLITE_OK && i<db->nDb; i++){Btree *pBt = db->aDb[i].pBt;- if( pBt ){+ int txn = sqlite3BtreeTxnState(pBt);+ if( txn!=SQLITE_TXN_NONE ){+ assert( needXcommit || txn==SQLITE_TXN_READ );rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);}}@@ -88359,28 +90100,31 @@ SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){/*-** This function is called when a transaction opened by the database+** These functions are called when a transaction opened by the database** handle associated with the VM passed as an argument is about to be-** committed. If there are outstanding deferred foreign key constraint-** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.+** committed. If there are outstanding foreign key constraint violations+** return an error code. Otherwise, SQLITE_OK.**** If there are outstanding FK violations and this function returns-** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY-** and write an error message to it. Then return SQLITE_ERROR.+** non-zero, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY+** and write an error message to it.*/#ifndef SQLITE_OMIT_FOREIGN_KEY-SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){+static SQLITE_NOINLINE int vdbeFkError(Vdbe *p){+ p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;+ p->errorAction = OE_Abort;+ sqlite3VdbeError(p, "FOREIGN KEY constraint failed");+ if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;+ return SQLITE_CONSTRAINT_FOREIGNKEY;+}+SQLITE_PRIVATE int sqlite3VdbeCheckFkImmediate(Vdbe *p){+ if( p->nFkConstraint==0 ) return SQLITE_OK;+ return vdbeFkError(p);+}+SQLITE_PRIVATE int sqlite3VdbeCheckFkDeferred(Vdbe *p){sqlite3 *db = p->db;- if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)- || (!deferred && p->nFkConstraint>0)- ){- p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;- p->errorAction = OE_Abort;- sqlite3VdbeError(p, "FOREIGN KEY constraint failed");- if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;- return SQLITE_CONSTRAINT_FOREIGNKEY;- }- return SQLITE_OK;+ if( (db->nDeferredCons+db->nDeferredImmCons)==0 ) return SQLITE_OK;+ return vdbeFkError(p);}#endif@@ -88474,7 +90218,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){/* Check for immediate foreign key violations. */if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){- (void)sqlite3VdbeCheckFk(p, 0);+ (void)sqlite3VdbeCheckFkImmediate(p);}/* If the auto-commit flag is set and this is the only active writer@@ -88488,7 +90232,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){&& db->nVdbeWrite==(p->readOnly==0)){if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){- rc = sqlite3VdbeCheckFk(p, 1);+ rc = sqlite3VdbeCheckFkDeferred(p);if( rc!=SQLITE_OK ){if( NEVER(p->readOnly) ){sqlite3VdbeLeave(p);@@ -89298,29 +91042,22 @@ SQLITE_PRIVATE void sqlite3VdbeSerialGet(return;}/*-** This routine is used to allocate sufficient space for an UnpackedRecord-** structure large enough to be used with sqlite3VdbeRecordUnpack() if-** the first argument is a pointer to KeyInfo structure pKeyInfo.-**-** The space is either allocated using sqlite3DbMallocRaw() or from within-** the unaligned buffer passed via the second and third arguments (presumably-** stack space). If the former, then *ppFree is set to a pointer that should-** be eventually freed by the caller using sqlite3DbFree(). Or, if the-** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL-** before returning.+** Allocate sufficient space for an UnpackedRecord structure large enough+** to hold a decoded index record for pKeyInfo.**-** If an OOM error occurs, NULL is returned.+** The space is allocated using sqlite3DbMallocRaw(). If an OOM error+** occurs, NULL is returned.*/SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *pKeyInfo /* Description of the record */){UnpackedRecord *p; /* Unpacked record to return */- int nByte; /* Number of bytes required for *p */+ u64 nByte; /* Number of bytes required for *p */+ assert( sizeof(UnpackedRecord) + sizeof(Mem)*65536 < 0x7fffffff );nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);if( !p ) return 0;p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];- assert( pKeyInfo->aSortFlags!=0 );p->pKeyInfo = pKeyInfo;p->nField = pKeyInfo->nKeyField + 1;return p;@@ -89332,7 +91069,6 @@ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(** contents of the decoded record.*/SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(- KeyInfo *pKeyInfo, /* Information about the record format */int nKey, /* Size of the binary record */const void *pKey, /* The binary record */UnpackedRecord *p /* Populate this structure before returning. */@@ -89343,6 +91079,7 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(u16 u; /* Unsigned loop counter */u32 szHdr;Mem *pMem = p->aMem;+ KeyInfo *pKeyInfo = p->pKeyInfo;p->default_rc = 0;assert( EIGHT_BYTE_ALIGNMENT(pMem) );@@ -89360,16 +91097,18 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(pMem->z = 0;sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);d += sqlite3VdbeSerialTypeLen(serial_type);- pMem++;if( (++u)>=p->nField ) break;+ pMem++;}if( d>(u32)nKey && u ){assert( CORRUPT_DB );/* In a corrupt record entry, the last pMem might have been set up using** uninitialized memory. Overwrite its value with NULL, to prevent** warnings from MSAN. */- sqlite3VdbeMemSetNull(pMem-1);+ sqlite3VdbeMemSetNull(pMem-(u<p->nField));}+ testcase( u == pKeyInfo->nKeyField + 1 );+ testcase( u < pKeyInfo->nKeyField + 1 );assert( u<=pKeyInfo->nKeyField + 1 );p->nField = u;}@@ -89537,6 +91276,32 @@ static void vdbeAssertFieldCountWithinLimits(** or positive value if *pMem1 is less than, equal to or greater than** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".*/+static SQLITE_NOINLINE int vdbeCompareMemStringWithEncodingChange(+ const Mem *pMem1,+ const Mem *pMem2,+ const CollSeq *pColl,+ u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */+){+ int rc;+ const void *v1, *v2;+ Mem c1;+ Mem c2;+ sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);+ sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);+ sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);+ sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);+ v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);+ v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);+ if( (v1==0 || v2==0) ){+ if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;+ rc = 0;+ }else{+ rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);+ }+ sqlite3VdbeMemReleaseMalloc(&c1);+ sqlite3VdbeMemReleaseMalloc(&c2);+ return rc;+}static int vdbeCompareMemString(const Mem *pMem1,const Mem *pMem2,@@ -89548,25 +91313,7 @@ static int vdbeCompareMemString(** comparison function directly */return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);}else{- int rc;- const void *v1, *v2;- Mem c1;- Mem c2;- sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);- sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);- sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);- sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);- v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);- v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);- if( (v1==0 || v2==0) ){- if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;- rc = 0;- }else{- rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);- }- sqlite3VdbeMemReleaseMalloc(&c1);- sqlite3VdbeMemReleaseMalloc(&c2);- return rc;+ return vdbeCompareMemStringWithEncodingChange(pMem1,pMem2,pColl,prcErr);}}@@ -90229,6 +91976,7 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){** The easiest way to enforce this limit is to consider only records with** 13 fields or less. If the first field is an integer, the maximum legal** header size is (12*5 + 1 + 1) bytes. */+ assert( p->pKeyInfo->aSortFlags!=0 );if( p->pKeyInfo->nAllField<=13 ){int flags = p->aMem[0].flags;if( p->pKeyInfo->aSortFlags[0] ){@@ -90478,6 +92226,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){}}+#ifndef SQLITE_OMIT_DATETIME_FUNCS/*** Cause a function to throw an error if it was call from OP_PureFunc** rather than OP_Function.@@ -90511,6 +92260,7 @@ SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){}return 1;}+#endif /* SQLITE_OMIT_DATETIME_FUNCS */#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)/*@@ -90587,7 +92337,6 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(i64 iKey2;PreUpdate preupdate;const char *zTbl = pTab->zName;- static const u8 fakeSortOrder = 0;#ifdef SQLITE_DEBUGint nRealCol;if( pTab->tabFlags & TF_WithoutRowid ){@@ -90622,10 +92371,11 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(preupdate.pCsr = pCsr;preupdate.op = op;preupdate.iNewReg = iReg;- preupdate.keyinfo.db = db;- preupdate.keyinfo.enc = ENC(db);- preupdate.keyinfo.nKeyField = pTab->nCol;- preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;+ preupdate.pKeyinfo = (KeyInfo*)&preupdate.uKey;+ preupdate.pKeyinfo->db = db;+ preupdate.pKeyinfo->enc = ENC(db);+ preupdate.pKeyinfo->nKeyField = pTab->nCol;+ preupdate.pKeyinfo->aSortFlags = 0; /* Indicate .aColl, .nAllField uninit */preupdate.iKey1 = iKey1;preupdate.iKey2 = iKey2;preupdate.pTab = pTab;@@ -90635,8 +92385,8 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);db->pPreUpdate = 0;sqlite3DbFree(db, preupdate.aRecord);- vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);- vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);+ vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pUnpacked);+ vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pNewUnpacked);sqlite3VdbeMemRelease(&preupdate.oldipk);if( preupdate.aNew ){int i;@@ -90655,6 +92405,17 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(}#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */+#ifdef SQLITE_ENABLE_PERCENTILE+/*+** Return the name of an SQL function associated with the sqlite3_context.+*/+SQLITE_PRIVATE const char *sqlite3VdbeFuncName(const sqlite3_context *pCtx){+ assert( pCtx!=0 );+ assert( pCtx->pFunc!=0 );+ return pCtx->pFunc->zName;+}+#endif /* SQLITE_ENABLE_PERCENTILE */+/************** End of vdbeaux.c *********************************************//************** Begin file vdbeapi.c *****************************************//*@@ -91702,7 +93463,7 @@ static int valueFromValueList(Mem sMem; /* Raw content of current row */memset(&sMem, 0, sizeof(sMem));sz = sqlite3BtreePayloadSize(pRhs->pCsr);- rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);+ rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,sz,&sMem);if( rc==SQLITE_OK ){u8 *zBuf = (u8*)sMem.z;u32 iSerial;@@ -92352,8 +94113,12 @@ static int bindText(if( zData!=0 ){pVar = &p->aVar[i-1];rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);- if( rc==SQLITE_OK && encoding!=0 ){- rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));+ if( rc==SQLITE_OK ){+ if( encoding==0 ){+ pVar->enc = ENC(p->db);+ }else{+ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));+ }}if( rc ){sqlite3Error(p->db, rc);@@ -92467,7 +94232,7 @@ SQLITE_API int sqlite3_bind_text64(assert( xDel!=SQLITE_DYNAMIC );if( enc!=SQLITE_UTF8 ){if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;- nData &= ~(u16)1;+ nData &= ~(u64)1;}return bindText(pStmt, i, zData, nData, xDel, enc);}@@ -92822,7 +94587,7 @@ static UnpackedRecord *vdbeUnpackRecord(pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);if( pRet ){memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));- sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);+ sqlite3VdbeRecordUnpack(nKey, pKey, pRet);}return pRet;}@@ -92851,6 +94616,9 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa}if( p->pPk ){iStore = sqlite3TableColumnToIndex(p->pPk, iIdx);+ }else if( iIdx >= p->pTab->nCol ){+ rc = SQLITE_MISUSE_BKPT;+ goto preupdate_old_out;}else{iStore = sqlite3TableColumnToStorage(p->pTab, iIdx);}@@ -92875,7 +94643,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVaif( !aRec ) goto preupdate_old_out;rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);if( rc==SQLITE_OK ){- p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);+ p->pUnpacked = vdbeUnpackRecord(p->pKeyinfo, nRec, aRec);if( !p->pUnpacked ) rc = SQLITE_NOMEM;}if( rc!=SQLITE_OK ){@@ -92892,7 +94660,9 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVaColumn *pCol = &p->pTab->aCol[iIdx];if( pCol->iDflt>0 ){if( p->apDflt==0 ){- int nByte = sizeof(sqlite3_value*)*p->pTab->nCol;+ int nByte;+ assert( sizeof(sqlite3_value*)*UMXV(p->pTab->nCol) < 0x7fffffff );+ nByte = sizeof(sqlite3_value*)*p->pTab->nCol;p->apDflt = (sqlite3_value**)sqlite3DbMallocZero(db, nByte);if( p->apDflt==0 ) goto preupdate_old_out;}@@ -92938,7 +94708,7 @@ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){#elsep = db->pPreUpdate;#endif- return (p ? p->keyinfo.nKeyField : 0);+ return (p ? p->pKeyinfo->nKeyField : 0);}#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */@@ -93004,6 +94774,8 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa}if( p->pPk && p->op!=SQLITE_UPDATE ){iStore = sqlite3TableColumnToIndex(p->pPk, iIdx);+ }else if( iIdx >= p->pTab->nCol ){+ return SQLITE_MISUSE_BKPT;}else{iStore = sqlite3TableColumnToStorage(p->pTab, iIdx);}@@ -93021,7 +94793,7 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVaMem *pData = &p->v->aMem[p->iNewReg];rc = ExpandBlob(pData);if( rc!=SQLITE_OK ) goto preupdate_new_out;- pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);+ pUnpack = vdbeUnpackRecord(p->pKeyinfo, pData->n, pData->z);if( !pUnpack ){rc = SQLITE_NOMEM;goto preupdate_new_out;@@ -93042,7 +94814,8 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa*/assert( p->op==SQLITE_UPDATE );if( !p->aNew ){- p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);+ assert( sizeof(Mem)*UMXV(p->pCsr->nField) < 0x7fffffff );+ p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem)*p->pCsr->nField);if( !p->aNew ){rc = SQLITE_NOMEM;goto preupdate_new_out;@@ -93278,10 +95051,10 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){** a host parameter. If the text contains no host parameters, return** the total number of bytes in the text.*/-static int findNextHostParameter(const char *zSql, int *pnToken){+static i64 findNextHostParameter(const char *zSql, i64 *pnToken){int tokenType;- int nTotal = 0;- int n;+ i64 nTotal = 0;+ i64 n;*pnToken = 0;while( zSql[0] ){@@ -93328,8 +95101,8 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql(sqlite3 *db; /* The database connection */int idx = 0; /* Index of a host parameter */int nextIndex = 1; /* Index of next ? host parameter */- int n; /* Length of a token prefix */- int nToken; /* Length of the parameter token */+ i64 n; /* Length of a token prefix */+ i64 nToken; /* Length of the parameter token */int i; /* Loop counter */Mem *pVar; /* Value of a host parameter */StrAccum out; /* Accumulate the output here */@@ -93812,11 +95585,11 @@ static VdbeCursor *allocateCursor(*/Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;- int nByte;+ i64 nByte;VdbeCursor *pCx = 0;- nByte =- ROUND8P(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +- (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);+ nByte = SZ_VDBECURSOR(nField);+ assert( ROUND8(nByte)==nByte );+ if( eCurType==CURTYPE_BTREE ) nByte += sqlite3BtreeCursorSize();assert( iCur>=0 && iCur<p->nCursor );if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/@@ -93840,7 +95613,7 @@ static VdbeCursor *allocateCursor(pMem->szMalloc = 0;return 0;}- pMem->szMalloc = nByte;+ pMem->szMalloc = (int)nByte;}p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;@@ -93849,8 +95622,8 @@ static VdbeCursor *allocateCursor(pCx->nField = nField;pCx->aOffset = &pCx->aType[nField];if( eCurType==CURTYPE_BTREE ){- pCx->uc.pCursor = (BtCursor*)- &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField];+ assert( ROUND8(SZ_VDBECURSOR(nField))==SZ_VDBECURSOR(nField) );+ pCx->uc.pCursor = (BtCursor*)&pMem->z[SZ_VDBECURSOR(nField)];sqlite3BtreeCursorZero(pCx->uc.pCursor);}return pCx;@@ -94253,7 +96026,7 @@ static u64 filterHash(const Mem *aMem, const Op *pOp){static SQLITE_NOINLINE int vdbeColumnFromOverflow(VdbeCursor *pC, /* The BTree cursor from which we are reading */int iCol, /* The column to read */- int t, /* The serial-type code for the column value */+ u32 t, /* The serial-type code for the column value */i64 iOffset, /* Offset to the start of the content value */u32 cacheStatus, /* Current Vdbe.cacheCtr value */u32 colCacheCtr, /* Current value of the column cache counter */@@ -94328,6 +96101,36 @@ static SQLITE_NOINLINE int vdbeColumnFromOverflow(return rc;}+/*+** Send a "statement aborts" message to the error log.+*/+static SQLITE_NOINLINE void sqlite3VdbeLogAbort(+ Vdbe *p, /* The statement that is running at the time of failure */+ int rc, /* Error code */+ Op *pOp, /* Opcode that filed */+ Op *aOp /* All opcodes */+){+ const char *zSql = p->zSql; /* Original SQL text */+ const char *zPrefix = ""; /* Prefix added to SQL text */+ int pc; /* Opcode address */+ char zXtra[100]; /* Buffer space to store zPrefix */++ if( p->pFrame ){+ assert( aOp[0].opcode==OP_Init );+ if( aOp[0].p4.z!=0 ){+ assert( aOp[0].p4.z[0]=='-'+ && aOp[0].p4.z[1]=='-'+ && aOp[0].p4.z[2]==' ' );+ sqlite3_snprintf(sizeof(zXtra), zXtra,"/* %s */ ",aOp[0].p4.z+3);+ zPrefix = zXtra;+ }else{+ zPrefix = "/* unknown trigger */ ";+ }+ }+ pc = (int)(pOp - aOp);+ sqlite3_log(rc, "statement aborts at %d: %s; [%s%s]",+ pc, p->zErrMsg, zPrefix, zSql);+}/*** Return the symbolic name for the data type of a pMem@@ -94853,8 +96656,7 @@ case OP_Halt: {}else{sqlite3VdbeError(p, "%s", pOp->p4.z);}- pcx = (int)(pOp - aOp);- sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);+ sqlite3VdbeLogAbort(p, pOp->p1, pOp, aOp);}rc = sqlite3VdbeHalt(p);assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );@@ -95233,7 +97035,7 @@ case OP_IntCopy: { /* out2 */** RETURNING clause.*/case OP_FkCheck: {- if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){+ if( (rc = sqlite3VdbeCheckFkImmediate(p))!=SQLITE_OK ){goto abort_due_to_error;}break;@@ -95325,10 +97127,14 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;flags2 = pIn2->flags & ~MEM_Str;}- nByte = pIn1->n + pIn2->n;+ nByte = pIn1->n;+ nByte += pIn2->n;if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){goto too_big;}+#if SQLITE_MAX_LENGTH>2147483645+ if( nByte>2147483645 ){ goto too_big; }+#endifif( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){goto no_mem;}@@ -96012,6 +97818,7 @@ case OP_Compare: {pKeyInfo = pOp->p4.pKeyInfo;assert( n>0 );assert( pKeyInfo!=0 );+ assert( pKeyInfo->aSortFlags!=0 );p1 = pOp->p1;p2 = pOp->p2;#ifdef SQLITE_DEBUG@@ -96180,7 +97987,7 @@ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */break;}-/* Opcode: Once P1 P2 * * *+/* Opcode: Once P1 P2 P3 * ***** Fall through to the next instruction the first time this opcode is** encountered on each invocation of the byte-code program. Jump to P2@@ -96196,6 +98003,12 @@ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */** whether or not the jump should be taken. The bitmask is necessary** because the self-altering code trick does not work for recursive** triggers.+**+** The P3 operand is not used directly by this opcode. However P3 is+** used by the code generator as follows: If this opcode is the start+** of a subroutine and that subroutine uses a Bloom filter, then P3 will+** be the register that holds that Bloom filter. See tag-202407032019+** in the source code for implementation details.*/case OP_Once: { /* jump */u32 iAddr; /* Address of this instruction */@@ -96768,6 +98581,15 @@ op_column_corrupt:** Take the affinities from the Table object in P4. If any value** cannot be coerced into the correct type, then raise an error.**+** If P3==0, then omit checking of VIRTUAL columns.+**+** If P3==1, then omit checking of all generated column, both VIRTUAL+** and STORED.+**+** If P3>=2, then only check column number P3-2 in the table (which will+** be a VIRTUAL column) against the value in reg[P1]. In this case,+** P2 will be 1.+**** This opcode is similar to OP_Affinity except that this opcode** forces the register type to the Table column type. This is used** to implement "strict affinity".@@ -96781,8 +98603,8 @@ op_column_corrupt:**** <ul>** <li> P2 should be the number of non-virtual columns in the-** table of P4.-** <li> Table P4 should be a STRICT table.+** table of P4 unless P3>1, in which case P2 will be 1.+** <li> Table P4 is a STRICT table.** </ul>**** If any precondition is false, an assertion fault occurs.@@ -96791,16 +98613,28 @@ case OP_TypeCheck: {Table *pTab;Column *aCol;int i;+ int nCol;assert( pOp->p4type==P4_TABLE );pTab = pOp->p4.pTab;assert( pTab->tabFlags & TF_Strict );- assert( pTab->nNVCol==pOp->p2 );+ assert( pOp->p3>=0 && pOp->p3<pTab->nCol+2 );aCol = pTab->aCol;pIn1 = &aMem[pOp->p1];- for(i=0; i<pTab->nCol; i++){- if( aCol[i].colFlags & COLFLAG_GENERATED ){- if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue;+ if( pOp->p3<2 ){+ assert( pTab->nNVCol==pOp->p2 );+ i = 0;+ nCol = pTab->nCol;+ }else{+ i = pOp->p3-2;+ nCol = i+1;+ assert( i<pTab->nCol );+ assert( aCol[i].colFlags & COLFLAG_VIRTUAL );+ assert( pOp->p2==1 );+ }+ for(; i<nCol; i++){+ if( (aCol[i].colFlags & COLFLAG_GENERATED)!=0 && pOp->p3<2 ){+ if( (aCol[i].colFlags & COLFLAG_VIRTUAL)!=0 ) continue;if( pOp->p3 ){ pIn1++; continue; }}assert( pIn1 < &aMem[pOp->p1+pOp->p2] );@@ -97122,7 +98956,7 @@ case OP_MakeRecord: {len = (u32)pRec->n;serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);if( pRec->flags & MEM_Zero ){- serial_type += pRec->u.nZero*2;+ serial_type += (u32)pRec->u.nZero*2;if( nData ){if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;len += pRec->u.nZero;@@ -97241,6 +99075,7 @@ case OP_MakeRecord: {zHdr += sqlite3PutVarint(zHdr, serial_type);if( pRec->n ){assert( pRec->z!=0 );+ assert( pRec->z!=(const char*)sqlite3CtypeMap );memcpy(zPayload, pRec->z, pRec->n);zPayload += pRec->n;}@@ -97388,7 +99223,7 @@ case OP_Savepoint: {*/int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;if( isTransaction && p1==SAVEPOINT_RELEASE ){- if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){+ if( (rc = sqlite3VdbeCheckFkDeferred(p))!=SQLITE_OK ){goto vdbe_return;}db->autoCommit = 1;@@ -97506,7 +99341,7 @@ case OP_AutoCommit: {"SQL statements in progress");rc = SQLITE_BUSY;goto abort_due_to_error;- }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){+ }else if( (rc = sqlite3VdbeCheckFkDeferred(p))!=SQLITE_OK ){goto vdbe_return;}else{db->autoCommit = (u8)desiredAutoCommit;@@ -98878,7 +100713,7 @@ case OP_Found: { /* jump, in3, ncycle */if( rc ) goto no_mem;pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);if( pIdxKey==0 ) goto no_mem;- sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);+ sqlite3VdbeRecordUnpack(r.aMem->n, r.aMem->z, pIdxKey);pIdxKey->default_rc = 0;rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);sqlite3DbFreeNN(db, pIdxKey);@@ -99592,7 +101427,7 @@ case OP_RowData: {/* The OP_RowData opcodes always follow OP_NotExists or** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions** that might invalidate the cursor.- ** If this where not the case, on of the following assert()s+ ** If this were not the case, one of the following assert()s** would fail. Should this ever change (because of changes in the code** generator) then the fix would be to insert a call to** sqlite3VdbeCursorMoveto().@@ -99876,6 +101711,32 @@ case OP_Rewind: { /* jump0, ncycle */break;}+/* Opcode: IfEmpty P1 P2 * * *+** Synopsis: if( empty(P1) ) goto P2+**+** Check to see if the b-tree table that cursor P1 references is empty+** and jump to P2 if it is.+*/+case OP_IfEmpty: { /* jump */+ VdbeCursor *pC;+ BtCursor *pCrsr;+ int res;++ assert( pOp->p1>=0 && pOp->p1<p->nCursor );+ assert( pOp->p2>=0 && pOp->p2<p->nOp );++ pC = p->apCsr[pOp->p1];+ assert( pC!=0 );+ assert( pC->eCurType==CURTYPE_BTREE );+ pCrsr = pC->uc.pCursor;+ assert( pCrsr );+ rc = sqlite3BtreeIsEmpty(pCrsr, &res);+ if( rc ) goto abort_due_to_error;+ VdbeBranchTaken(res!=0,2);+ if( res ) goto jump_to_p2;+ break;+}+/* Opcode: Next P1 P2 P3 * P5**** Advance cursor P1 so that it points to the next key/data pair in its@@ -100861,7 +102722,7 @@ case OP_RowSetTest: { /* jump, in1, in3 */*/case OP_Program: { /* jump0 */int nMem; /* Number of memory registers for sub-program */- int nByte; /* Bytes of runtime space required for sub-program */+ i64 nByte; /* Bytes of runtime space required for sub-program */Mem *pRt; /* Register to allocate runtime space */Mem *pMem; /* Used to iterate through memory cells */Mem *pEnd; /* Last memory cell in new array */@@ -100912,7 +102773,7 @@ case OP_Program: { /* jump0 */nByte = ROUND8(sizeof(VdbeFrame))+ nMem * sizeof(Mem)+ pProgram->nCsr * sizeof(VdbeCursor*)- + (pProgram->nOp + 7)/8;+ + (7 + (i64)pProgram->nOp)/8;pFrame = sqlite3DbMallocZero(db, nByte);if( !pFrame ){goto no_mem;@@ -100920,7 +102781,7 @@ case OP_Program: { /* jump0 */sqlite3VdbeMemRelease(pRt);pRt->flags = MEM_Blob|MEM_Dyn;pRt->z = (char*)pFrame;- pRt->n = nByte;+ pRt->n = (int)nByte;pRt->xDel = sqlite3VdbeFrameMemDel;pFrame->v = p;@@ -101019,12 +102880,14 @@ case OP_Param: { /* out2 */** statement counter is incremented (immediate foreign key constraints).*/case OP_FkCounter: {- if( db->flags & SQLITE_DeferFKs ){- db->nDeferredImmCons += pOp->p2;- }else if( pOp->p1 ){+ if( pOp->p1 ){db->nDeferredCons += pOp->p2;}else{- p->nFkConstraint += pOp->p2;+ if( db->flags & SQLITE_DeferFKs ){+ db->nDeferredImmCons += pOp->p2;+ }else{+ p->nFkConstraint += pOp->p2;+ }}break;}@@ -101239,7 +103102,7 @@ case OP_AggStep: {**** Note: We could avoid this by using a regular memory cell from aMem[] for** the accumulator, instead of allocating one here. */- nAlloc = ROUND8P( sizeof(pCtx[0]) + (n-1)*sizeof(sqlite3_value*) );+ nAlloc = ROUND8P( SZ_CONTEXT(n) );pCtx = sqlite3DbMallocRawNN(db, nAlloc + sizeof(Mem));if( pCtx==0 ) goto no_mem;pCtx->pOut = (Mem*)((u8*)pCtx + nAlloc);@@ -101410,6 +103273,7 @@ case OP_Checkpoint: {|| pOp->p2==SQLITE_CHECKPOINT_FULL|| pOp->p2==SQLITE_CHECKPOINT_RESTART|| pOp->p2==SQLITE_CHECKPOINT_TRUNCATE+ || pOp->p2==SQLITE_CHECKPOINT_NOOP);rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);if( rc ){@@ -101745,7 +103609,14 @@ case OP_VOpen: { /* ncycle */const sqlite3_module *pModule;assert( p->bIsReader );- pCur = 0;+ pCur = p->apCsr[pOp->p1];+ if( pCur!=0+ && ALWAYS( pCur->eCurType==CURTYPE_VTAB )+ && ALWAYS( pCur->uc.pVCur->pVtab==pOp->p4.pVtab->pVtab )+ ){+ /* This opcode is a no-op if the cursor is already open */+ break;+ }pVCur = 0;pVtab = pOp->p4.pVtab->pVtab;if( pVtab==0 || NEVER(pVtab->pModule==0) ){@@ -101899,6 +103770,7 @@ case OP_VFilter: { /* jump, ncycle *//* Invoke the xFilter method */apArg = p->apArg;+ assert( nArg<=p->napArg );for(i = 0; i<nArg; i++){apArg[i] = &pArgc[i+1];}@@ -102109,6 +103981,7 @@ case OP_VUpdate: {u8 vtabOnConflict = db->vtabOnConflict;apArg = p->apArg;pX = &aMem[pOp->p3];+ assert( nArg<=p->napArg );for(i=0; i<nArg; i++){assert( memIsValid(pX) );memAboutToChange(p, pX);@@ -102685,8 +104558,7 @@ abort_due_to_error:p->rc = rc;sqlite3SystemError(db, rc);testcase( sqlite3GlobalConfig.xLog!=0 );- sqlite3_log(rc, "statement aborts at %d: [%s] %s",- (int)(pOp - aOp), p->zSql, p->zErrMsg);+ sqlite3VdbeLogAbort(p, rc, pOp, aOp);if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){@@ -102895,6 +104767,7 @@ SQLITE_API int sqlite3_blob_open(char *zErr = 0;Table *pTab;Incrblob *pBlob = 0;+ int iDb;Parse sParse;#ifdef SQLITE_ENABLE_API_ARMOR@@ -102940,7 +104813,10 @@ SQLITE_API int sqlite3_blob_open(sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);}#endif- if( !pTab ){+ if( pTab==0+ || ((iDb = sqlite3SchemaToIndex(db, pTab->pSchema))==1 &&+ sqlite3OpenTempDatabase(&sParse))+ ){if( sParse.zErrMsg ){sqlite3DbFree(db, zErr);zErr = sParse.zErrMsg;@@ -102951,15 +104827,11 @@ SQLITE_API int sqlite3_blob_open(goto blob_open_out;}pBlob->pTab = pTab;- pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;+ pBlob->zDb = db->aDb[iDb].zDbSName;/* Now search pTab for the exact column. */- for(iCol=0; iCol<pTab->nCol; iCol++) {- if( sqlite3StrICmp(pTab->aCol[iCol].zCnName, zColumn)==0 ){- break;- }- }- if( iCol==pTab->nCol ){+ iCol = sqlite3ColumnIndex(pTab, zColumn);+ if( iCol<0 ){sqlite3DbFree(db, zErr);zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);rc = SQLITE_ERROR;@@ -103039,7 +104911,6 @@ SQLITE_API int sqlite3_blob_open({OP_Halt, 0, 0, 0}, /* 5 */};Vdbe *v = (Vdbe *)pBlob->pStmt;- int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);VdbeOp *aOp;sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,@@ -103148,7 +105019,7 @@ static int blobReadWrite(int iOffset,int (*xCall)(BtCursor*, u32, u32, void*)){- int rc;+ int rc = SQLITE_OK;Incrblob *p = (Incrblob *)pBlob;Vdbe *v;sqlite3 *db;@@ -103188,17 +105059,32 @@ static int blobReadWrite(** using the incremental-blob API, this works. For the sessions module** anyhow.*/- sqlite3_int64 iKey;- iKey = sqlite3BtreeIntegerKey(p->pCsr);- assert( v->apCsr[0]!=0 );- assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );- sqlite3VdbePreUpdateHook(- v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol- );+ if( sqlite3BtreeCursorIsValidNN(p->pCsr)==0 ){+ /* If the cursor is not currently valid, try to reseek it. This+ ** always either fails or finds the correct row - the cursor will+ ** have been marked permanently CURSOR_INVALID if the open row has+ ** been deleted. */+ int bDiff = 0;+ rc = sqlite3BtreeCursorRestore(p->pCsr, &bDiff);+ assert( bDiff==0 || sqlite3BtreeCursorIsValidNN(p->pCsr)==0 );+ }+ if( sqlite3BtreeCursorIsValidNN(p->pCsr) ){+ sqlite3_int64 iKey;+ iKey = sqlite3BtreeIntegerKey(p->pCsr);+ assert( v->apCsr[0]!=0 );+ assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );+ sqlite3VdbePreUpdateHook(+ v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol+ );+ }+ }+ if( rc==SQLITE_OK ){+ rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);}+#else+ rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);#endif- rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);sqlite3BtreeLeaveCursor(p->pCsr);if( rc==SQLITE_ABORT ){sqlite3VdbeFinalize(v);@@ -103587,6 +105473,7 @@ struct SortSubtask {SorterCompare xCompare; /* Compare function to use */SorterFile file; /* Temp file for level-0 PMAs */SorterFile file2; /* Space for other PMAs */+ u64 nSpill; /* Total bytes written by this task */};@@ -103617,9 +105504,12 @@ struct VdbeSorter {u8 iPrev; /* Previous thread used to flush PMA */u8 nTask; /* Size of aTask[] array */u8 typeMask;- SortSubtask aTask[1]; /* One or more subtasks */+ SortSubtask aTask[FLEXARRAY]; /* One or more subtasks */};+/* Size (in bytes) of a VdbeSorter object that works with N or fewer subtasks */+#define SZ_VDBESORTER(N) (offsetof(VdbeSorter,aTask)+(N)*sizeof(SortSubtask))+#define SORTER_TYPE_INTEGER 0x01#define SORTER_TYPE_TEXT 0x02@@ -103704,6 +105594,7 @@ struct PmaWriter {int iBufEnd; /* Last byte of buffer to write */i64 iWriteOff; /* Offset of start of buffer in file */sqlite3_file *pFd; /* File handle to write to */+ u64 nPmaSpill; /* Total number of bytes written */};/*@@ -104048,7 +105939,7 @@ static int vdbeSorterCompareTail(){UnpackedRecord *r2 = pTask->pUnpacked;if( *pbKey2Cached==0 ){- sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);+ sqlite3VdbeRecordUnpack(nKey2, pKey2, r2);*pbKey2Cached = 1;}return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);@@ -104075,7 +105966,7 @@ static int vdbeSorterCompare(){UnpackedRecord *r2 = pTask->pUnpacked;if( !*pbKey2Cached ){- sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);+ sqlite3VdbeRecordUnpack(nKey2, pKey2, r2);*pbKey2Cached = 1;}return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);@@ -104115,6 +106006,7 @@ static int vdbeSorterCompareText();}}else{+ assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 );assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){res = res * -1;@@ -104178,6 +106070,7 @@ static int vdbeSorterCompareInt(}}+ assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 );if( res==0 ){if( pTask->pSorter->pKeyInfo->nKeyField>1 ){res = vdbeSorterCompareTail(@@ -104221,7 +106114,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(VdbeSorter *pSorter; /* The new sorter */KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */- int sz; /* Size of pSorter in bytes */+ i64 sz; /* Size of pSorter in bytes */int rc = SQLITE_OK;#if SQLITE_MAX_WORKER_THREADS==0# define nWorker 0@@ -104249,8 +106142,11 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(assert( pCsr->pKeyInfo );assert( !pCsr->isEphemeral );assert( pCsr->eCurType==CURTYPE_SORTER );- szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);- sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);+ assert( sizeof(KeyInfo) + UMXV(pCsr->pKeyInfo->nKeyField)*sizeof(CollSeq*)+ < 0x7fffffff );+ assert( pCsr->pKeyInfo->nKeyField<=pCsr->pKeyInfo->nAllField );+ szKeyInfo = SZ_KEYINFO(pCsr->pKeyInfo->nAllField);+ sz = SZ_VDBESORTER(nWorker+1);pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);pCsr->uc.pSorter = pSorter;@@ -104263,7 +106159,12 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(pKeyInfo->db = 0;if( nField && nWorker==0 ){pKeyInfo->nKeyField = nField;+ assert( nField<=pCsr->pKeyInfo->nAllField );}+ /* It is OK that pKeyInfo reuses the aSortFlags field from pCsr->pKeyInfo,+ ** since the pCsr->pKeyInfo->aSortFlags[] array is invariant and lives+ ** longer that pSorter. */+ assert( pKeyInfo->aSortFlags==pCsr->pKeyInfo->aSortFlags );sqlite3BtreeEnter(pBt);pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);sqlite3BtreeLeave(pBt);@@ -104462,7 +106363,7 @@ static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){*/static MergeEngine *vdbeMergeEngineNew(int nReader){int N = 2; /* Smallest power of two >= nReader */- int nByte; /* Total bytes of space to allocate */+ i64 nByte; /* Total bytes of space to allocate */MergeEngine *pNew; /* Pointer to allocated object to return */assert( nReader<=SORTER_MAX_MERGE_COUNT );@@ -104552,6 +106453,12 @@ SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){assert( pCsr->eCurType==CURTYPE_SORTER );pSorter = pCsr->uc.pSorter;if( pSorter ){+ /* Increment db->nSpill by the total number of bytes of data written+ ** to temp files by this sort operation. */+ int ii;+ for(ii=0; ii<pSorter->nTask; ii++){+ db->nSpill += pSorter->aTask[ii].nSpill;+ }sqlite3VdbeSorterReset(db, pSorter);sqlite3_free(pSorter->list.aMemory);sqlite3DbFree(db, pSorter);@@ -104714,6 +106621,10 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){p->u.pNext = 0;for(i=0; aSlot[i]; i++){p = vdbeSorterMerge(pTask, p, aSlot[i]);+ /* ,--Each aSlot[] holds twice as much as the previous. So we cannot use+ ** | up all 64 aSlots[] with only a 64-bit address space.+ ** v */+ assert( i<ArraySize(aSlot) );aSlot[i] = 0;}aSlot[i] = p;@@ -104773,6 +106684,7 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){&p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,p->iWriteOff + p->iBufStart);+ p->nPmaSpill += (p->iBufEnd - p->iBufStart);p->iBufStart = p->iBufEnd = 0;p->iWriteOff += p->nBuffer;}@@ -104789,17 +106701,20 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){** required. Otherwise, return an SQLite error code.**** Before returning, set *piEof to the offset immediately following the-** last byte written to the file.+** last byte written to the file. Also, increment (*pnSpill) by the total+** number of bytes written to the file.*/-static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){+static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof, u64 *pnSpill){int rc;if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){p->eFWErr = sqlite3OsWrite(p->pFd,&p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,p->iWriteOff + p->iBufStart);+ p->nPmaSpill += (p->iBufEnd - p->iBufStart);}*piEof = (p->iWriteOff + p->iBufEnd);+ *pnSpill += p->nPmaSpill;sqlite3_free(p->aBuffer);rc = p->eFWErr;memset(p, 0, sizeof(PmaWriter));@@ -104879,7 +106794,7 @@ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){if( pList->aMemory==0 ) sqlite3_free(p);}pList->pList = p;- rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);+ rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof, &pTask->nSpill);}vdbeSorterWorkDebug(pTask, "exit");@@ -105193,7 +107108,7 @@ static int vdbeIncrPopulate(IncrMerger *pIncr){rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);}- rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);+ rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof, &pTask->nSpill);if( rc==SQLITE_OK ) rc = rc2;vdbeSorterPopulateDebug(pTask, "exit");return rc;@@ -106039,7 +107954,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterCompare(assert( r2->nField==nKeyCol );pKey = vdbeSorterRowkey(pSorter, &nKey);- sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);+ sqlite3VdbeRecordUnpack(nKey, pKey, r2);for(i=0; i<nKeyCol; i++){if( r2->aMem[i].flags & MEM_Null ){*pRes = -1;@@ -107505,7 +109420,6 @@ static int lookupName(Schema *pSchema = 0; /* Schema of the expression */int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */Table *pTab = 0; /* Table holding the row */- Column *pCol; /* A column of pTab */ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */const char *zCol = pRight->u.zToken;@@ -107556,7 +109470,6 @@ static int lookupName(if( pSrcList ){for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){- u8 hCol;pTab = pItem->pSTab;assert( pTab!=0 && pTab->zName!=0 );assert( pTab->nCol>0 || pParse->nErr );@@ -107586,10 +109499,13 @@ static int lookupName(if( cnt>0 ){if( pItem->fg.isUsing==0|| sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0+ || pMatch==pItem){/* Two or more tables have the same column name which is- ** not joined by USING. This is an error. Signal as much- ** by clearing pFJMatch and letting cnt go above 1. */+ ** not joined by USING. Or, a single table has two columns+ ** that match a USING term (if pMatch==pItem). These are both+ ** "ambiguous column name" errors. Signal as much by clearing+ ** pFJMatch and letting cnt go above 1. */sqlite3ExprListDelete(db, pFJMatch);pFJMatch = 0;}else@@ -107644,43 +109560,38 @@ static int lookupName(sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);}}- hCol = sqlite3StrIHash(zCol);- for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){- if( pCol->hName==hCol- && sqlite3StrICmp(pCol->zCnName, zCol)==0- ){- if( cnt>0 ){- if( pItem->fg.isUsing==0- || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0- ){- /* Two or more tables have the same column name which is- ** not joined by USING. This is an error. Signal as much- ** by clearing pFJMatch and letting cnt go above 1. */- sqlite3ExprListDelete(db, pFJMatch);- pFJMatch = 0;- }else- if( (pItem->fg.jointype & JT_RIGHT)==0 ){- /* An INNER or LEFT JOIN. Use the left-most table */- continue;- }else- if( (pItem->fg.jointype & JT_LEFT)==0 ){- /* A RIGHT JOIN. Use the right-most table */- cnt = 0;- sqlite3ExprListDelete(db, pFJMatch);- pFJMatch = 0;- }else{- /* For a FULL JOIN, we must construct a coalesce() func */- extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);- }- }- cnt++;- pMatch = pItem;- /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */- pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;- if( pItem->fg.isNestedFrom ){- sqlite3SrcItemColumnUsed(pItem, j);+ j = sqlite3ColumnIndex(pTab, zCol);+ if( j>=0 ){+ if( cnt>0 ){+ if( pItem->fg.isUsing==0+ || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0+ ){+ /* Two or more tables have the same column name which is+ ** not joined by USING. This is an error. Signal as much+ ** by clearing pFJMatch and letting cnt go above 1. */+ sqlite3ExprListDelete(db, pFJMatch);+ pFJMatch = 0;+ }else+ if( (pItem->fg.jointype & JT_RIGHT)==0 ){+ /* An INNER or LEFT JOIN. Use the left-most table */+ continue;+ }else+ if( (pItem->fg.jointype & JT_LEFT)==0 ){+ /* A RIGHT JOIN. Use the right-most table */+ cnt = 0;+ sqlite3ExprListDelete(db, pFJMatch);+ pFJMatch = 0;+ }else{+ /* For a FULL JOIN, we must construct a coalesce() func */+ extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);}- break;+ }+ cnt++;+ pMatch = pItem;+ /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */+ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;+ if( pItem->fg.isNestedFrom ){+ sqlite3SrcItemColumnUsed(pItem, j);}}if( 0==cnt && VisibleRowid(pTab) ){@@ -107770,23 +109681,18 @@ static int lookupName(if( pTab ){int iCol;- u8 hCol = sqlite3StrIHash(zCol);pSchema = pTab->pSchema;cntTab++;- for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){- if( pCol->hName==hCol- && sqlite3StrICmp(pCol->zCnName, zCol)==0- ){- if( iCol==pTab->iPKey ){- iCol = -1;- }- break;+ iCol = sqlite3ColumnIndex(pTab, zCol);+ if( iCol>=0 ){+ if( pTab->iPKey==iCol ) iCol = -1;+ }else{+ if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){+ iCol = -1;+ }else{+ iCol = pTab->nCol;}}- if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){- /* IMP: R-51414-32910 */- iCol = -1;- }if( iCol<pTab->nCol ){cnt++;pMatch = 0;@@ -108149,8 +110055,8 @@ static void notValidImpl(/*** Expression p should encode a floating point value between 1.0 and 0.0.-** Return 1024 times this value. Or return -1 if p is not a floating point-** value between 1.0 and 0.0.+** Return 134,217,728 (2^27) times this value. Or return -1 if p is not+** a floating point value between 1.0 and 0.0.*/static int exprProbability(Expr *p){double r = -1.0;@@ -108425,13 +110331,12 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){** sqlite_version() that might change over time cannot be used** in an index or generated column. Curiously, they can be used** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all- ** all this. */+ ** allow this. */sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);}else{assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */pExpr->op2 = pNC->ncFlags & NC_SelfRef;- if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);}if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0&& pParse->nested==0@@ -108447,6 +110352,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0&& !IN_RENAME_OBJECT){+ if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);sqlite3ExprFunctionUsable(pParse, pExpr, pDef);}}@@ -108581,11 +110487,13 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){return WRC_Prune;}#ifndef SQLITE_OMIT_SUBQUERY+ case TK_EXISTS:case TK_SELECT:- case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );#endifcase TK_IN: {testcase( pExpr->op==TK_IN );+ testcase( pExpr->op==TK_EXISTS );+ testcase( pExpr->op==TK_SELECT );if( ExprUseXSelect(pExpr) ){int nRef = pNC->nRef;testcase( pNC->ncFlags & NC_IsCheck );@@ -108593,6 +110501,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){testcase( pNC->ncFlags & NC_IdxExpr );testcase( pNC->ncFlags & NC_GenCol );assert( pExpr->x.pSelect );+ if( pExpr->op==TK_EXISTS ) pParse->bHasExists = 1;if( pNC->ncFlags & NC_SelfRef ){notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);}else{@@ -109296,6 +111205,14 @@ static int resolveSelectStep(Walker *pWalker, Select *p){return WRC_Abort;}+ /* If the SELECT statement contains ON clauses that were moved into+ ** the WHERE clause, go through and verify that none of the terms+ ** in the ON clauses reference tables to the right of the ON clause. */+ if( (p->selFlags & SF_OnToWhere) ){+ sqlite3SelectCheckOnClauses(pParse, p);+ if( pParse->nErr ) return WRC_Abort;+ }+/* Advance to the next term of the compound*/p = p->pPrior;@@ -109500,20 +111417,25 @@ SQLITE_PRIVATE int sqlite3ResolveSelfReference(Expr *pExpr, /* Expression to resolve. May be NULL. */ExprList *pList /* Expression list to resolve. May be NULL. */){- SrcList sSrc; /* Fake SrcList for pParse->pNewTable */+ SrcList *pSrc; /* Fake SrcList for pParse->pNewTable */NameContext sNC; /* Name context for pParse->pNewTable */int rc;+ union {+ SrcList sSrc;+ u8 srcSpace[SZ_SRCLIST_1]; /* Memory space for the fake SrcList */+ } uSrc;assert( type==0 || pTab!=0 );assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr|| type==NC_GenCol || pTab==0 );memset(&sNC, 0, sizeof(sNC));- memset(&sSrc, 0, sizeof(sSrc));+ memset(&uSrc, 0, sizeof(uSrc));+ pSrc = &uSrc.sSrc;if( pTab ){- sSrc.nSrc = 1;- sSrc.a[0].zName = pTab->zName;- sSrc.a[0].pSTab = pTab;- sSrc.a[0].iCursor = -1;+ pSrc->nSrc = 1;+ pSrc->a[0].zName = pTab->zName;+ pSrc->a[0].pSTab = pTab;+ pSrc->a[0].iCursor = -1;if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){/* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP** schema elements */@@ -109521,7 +111443,7 @@ SQLITE_PRIVATE int sqlite3ResolveSelfReference(}}sNC.pParse = pParse;- sNC.pSrcList = &sSrc;+ sNC.pSrcList = pSrc;sNC.ncFlags = type | NC_IsDDL;if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);@@ -109605,7 +111527,9 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr);}- if( op==TK_VECTOR ){+ if( op==TK_VECTOR+ || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER)+ ){assert( ExprUseXList(pExpr) );return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);}@@ -109798,7 +111722,9 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){p = p->pLeft;continue;}- if( op==TK_VECTOR ){+ if( op==TK_VECTOR+ || (op==TK_FUNCTION && p->affExpr==SQLITE_AFF_DEFER)+ ){assert( ExprUseXList(p) );p = p->x.pList->a[0].pExpr;continue;@@ -110672,7 +112598,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){return pLeft;}else{u32 f = pLeft->flags | pRight->flags;- if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse+ if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse|EP_HasFunc))==EP_IsFalse&& !IN_RENAME_OBJECT){sqlite3ExprDeferredDelete(pParse, pLeft);@@ -110767,6 +112693,11 @@ SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy(sqlite3ExprListDelete(db, pOrderBy);return;}+ if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){+ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");+ sqlite3ExprListDelete(db, pOrderBy);+ return;+ }pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);if( pOB==0 ){@@ -111270,7 +113201,7 @@ static Expr *exprDup(SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p){With *pRet = 0;if( p ){- sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);+ sqlite3_int64 nByte = SZ_WITH(p->nCte);pRet = sqlite3DbMallocZero(db, nByte);if( pRet ){int i;@@ -111381,7 +113312,6 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int}pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);pItem->fg = pOldItem->fg;- pItem->fg.done = 0;pItem->u = pOldItem->u;}return pNew;@@ -111398,11 +113328,9 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, intSQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){SrcList *pNew;int i;- int nByte;assert( db!=0 );if( p==0 ) return 0;- nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);- pNew = sqlite3DbMallocRawNN(db, nByte );+ pNew = sqlite3DbMallocRawNN(db, SZ_SRCLIST(p->nSrc) );if( pNew==0 ) return 0;pNew->nSrc = pNew->nAlloc = p->nSrc;for(i=0; i<p->nSrc; i++){@@ -111464,7 +113392,7 @@ SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){int i;assert( db!=0 );if( p==0 ) return 0;- pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );+ pNew = sqlite3DbMallocRawNN(db, SZ_IDLIST(p->nId));if( pNew==0 ) return 0;pNew->nId = p->nId;for(i=0; i<p->nId; i++){@@ -111496,7 +113424,7 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flapNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);pNew->iLimit = 0;pNew->iOffset = 0;- pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;+ pNew->selFlags = p->selFlags & ~(u32)SF_UsesEphemeral;pNew->addrOpenEphm[0] = -1;pNew->addrOpenEphm[1] = -1;pNew->nSelectRow = p->nSelectRow;@@ -111548,7 +113476,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(struct ExprList_item *pItem;ExprList *pList;- pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );+ pList = sqlite3DbMallocRawNN(db, SZ_EXPRLIST(4));if( pList==0 ){sqlite3ExprDelete(db, pExpr);return 0;@@ -111568,8 +113496,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(struct ExprList_item *pItem;ExprList *pNew;pList->nAlloc *= 2;- pNew = sqlite3DbRealloc(db, pList,- sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));+ pNew = sqlite3DbRealloc(db, pList, SZ_EXPRLIST(pList->nAlloc));if( pNew==0 ){sqlite3ExprListDelete(db, pList);sqlite3ExprDelete(db, pExpr);@@ -111905,6 +113832,85 @@ SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){return pExpr;}+/*+** Return true if it might be advantageous to compute the right operand+** of expression pExpr first, before the left operand.+**+** Normally the left operand is computed before the right operand. But if+** the left operand contains a subquery and the right does not, then it+** might be more efficient to compute the right operand first.+*/+static int exprEvalRhsFirst(Expr *pExpr){+ if( ExprHasProperty(pExpr->pLeft, EP_Subquery)+ && !ExprHasProperty(pExpr->pRight, EP_Subquery)+ ){+ return 1;+ }else{+ return 0;+ }+}++/*+** Compute the two operands of a binary operator.+**+** If either operand contains a subquery, then the code strives to+** compute the operand containing the subquery second. If the other+** operand evalutes to NULL, then a jump is made. The address of the+** IsNull operand that does this jump is returned. The caller can use+** this to optimize the computation so as to avoid doing the potentially+** expensive subquery.+**+** If no optimization opportunities exist, return 0.+*/+static int exprComputeOperands(+ Parse *pParse, /* Parsing context */+ Expr *pExpr, /* The comparison expression */+ int *pR1, /* OUT: Register holding the left operand */+ int *pR2, /* OUT: Register holding the right operand */+ int *pFree1, /* OUT: Temp register to free if not zero */+ int *pFree2 /* OUT: Another temp register to free if not zero */+){+ int addrIsNull;+ int r1, r2;+ Vdbe *v = pParse->pVdbe;++ assert( v!=0 );+ /*+ ** If the left operand contains a (possibly expensive) subquery and the+ ** right operand does not and the right operation might be NULL,+ ** then compute the right operand first and do an IsNull jump if the+ ** right operand evalutes to NULL.+ */+ if( exprEvalRhsFirst(pExpr) && sqlite3ExprCanBeNull(pExpr->pRight) ){+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2);+ addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r2);+ VdbeComment((v, "skip left operand"));+ VdbeCoverage(v);+ }else{+ r2 = 0; /* Silence a false-positive uninit-var warning in MSVC */+ addrIsNull = 0;+ }+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pFree1);+ if( addrIsNull==0 ){+ /*+ ** If the right operand contains a subquery and the left operand does not+ ** and the left operand might be NULL, then do an IsNull check+ ** check on the left operand before computing the right operand.+ */+ if( ExprHasProperty(pExpr->pRight, EP_Subquery)+ && sqlite3ExprCanBeNull(pExpr->pLeft)+ ){+ addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r1);+ VdbeComment((v, "skip right operand"));+ VdbeCoverage(v);+ }+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2);+ }+ *pR1 = r1;+ *pR2 = r2;+ return addrIsNull;+}+/*** pExpr is a TK_FUNCTION node. Try to determine whether or not the** function is a constant function. A function is constant if all of@@ -112498,13 +114504,7 @@ SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab){int ii;assert( VisibleRowid(pTab) );for(ii=0; ii<ArraySize(azOpt); ii++){- int iCol;- for(iCol=0; iCol<pTab->nCol; iCol++){- if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;- }- if( iCol==pTab->nCol ){- return azOpt[ii];- }+ if( sqlite3ColumnIndex(pTab, azOpt[ii])<0 ) return azOpt[ii];}return 0;}@@ -112908,7 +114908,7 @@ static char *exprINAffinity(Parse *pParse, const Expr *pExpr){char *zRet;assert( pExpr->op==TK_IN );- zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);+ zRet = sqlite3DbMallocRaw(pParse->db, 1+(i64)nVal);if( zRet ){int i;for(i=0; i<nVal; i++){@@ -113168,11 +115168,12 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(sqlite3SelectDelete(pParse->db, pCopy);sqlite3DbFree(pParse->db, dest.zAffSdst);if( addrBloom ){+ /* Remember that location of the Bloom filter in the P3 operand+ ** of the OP_Once that began this subroutine. tag-202407032019 */sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2;if( dest.iSDParm2==0 ){- sqlite3VdbeChangeToNoop(v, addrBloom);- }else{- sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2;+ /* If the Bloom filter won't actually be used, keep it small */+ sqlite3VdbeGetOp(v, addrBloom)->p1 = 10;}}if( rc ){@@ -113344,9 +115345,22 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){pParse->nMem += nReg;if( pExpr->op==TK_SELECT ){dest.eDest = SRT_Mem;- dest.iSdst = dest.iSDParm;+ if( (pSel->selFlags&SF_Distinct) && pSel->pLimit && pSel->pLimit->pRight ){+ /* If there is both a DISTINCT and an OFFSET clause, then allocate+ ** a separate dest.iSdst array for sqlite3Select() and other+ ** routines to populate. In this case results will be copied over+ ** into the dest.iSDParm array only after OFFSET processing. This+ ** ensures that in the case where OFFSET excludes all rows, the+ ** dest.iSDParm array is not left populated with the contents of the+ ** last row visited - it should be all NULLs if all rows were+ ** excluded by OFFSET. */+ dest.iSdst = pParse->nMem+1;+ pParse->nMem += nReg;+ }else{+ dest.iSdst = dest.iSDParm;+ }dest.nSdst = nReg;- sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);+ sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, pParse->nMem);VdbeComment((v, "Init subquery result"));}else{dest.eDest = SRT_Exists;@@ -113354,17 +115368,23 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){VdbeComment((v, "Init EXISTS result"));}if( pSel->pLimit ){- /* The subquery already has a limit. If the pre-existing limit is X- ** then make the new limit X<>0 so that the new limit is either 1 or 0 */- sqlite3 *db = pParse->db;- pLimit = sqlite3Expr(db, TK_INTEGER, "0");- if( pLimit ){- pLimit->affExpr = SQLITE_AFF_NUMERIC;- pLimit = sqlite3PExpr(pParse, TK_NE,- sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);+ /* The subquery already has a limit. If the pre-existing limit X is+ ** not already integer value 1 or 0, then make the new limit X<>0 so that+ ** the new limit is either 1 or 0 */+ Expr *pLeft = pSel->pLimit->pLeft;+ if( ExprHasProperty(pLeft, EP_IntValue)==0+ || (pLeft->u.iValue!=1 && pLeft->u.iValue!=0)+ ){+ sqlite3 *db = pParse->db;+ pLimit = sqlite3Expr(db, TK_INTEGER, "0");+ if( pLimit ){+ pLimit->affExpr = SQLITE_AFF_NUMERIC;+ pLimit = sqlite3PExpr(pParse, TK_NE,+ sqlite3ExprDup(db, pLeft, 0), pLimit);+ }+ sqlite3ExprDeferredDelete(pParse, pLeft);+ pSel->pLimit->pLeft = pLimit;}- sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);- pSel->pLimit->pLeft = pLimit;}else{/* If there is no pre-existing limit add a limit of 1 */pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");@@ -113452,7 +115472,6 @@ static void sqlite3ExprCodeIN(int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */int eType; /* Type of the RHS */int rLhs; /* Register(s) holding the LHS values */- int rLhsOrig; /* LHS values prior to reordering by aiMap[] */Vdbe *v; /* Statement under construction */int *aiMap = 0; /* Map from vector field to index column */char *zAff = 0; /* Affinity string for comparisons */@@ -113515,19 +115534,8 @@ static void sqlite3ExprCodeIN(** by code generated below. */assert( pParse->okConstFactor==okConstFactor );pParse->okConstFactor = 0;- rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);+ rLhs = exprCodeVector(pParse, pLeft, &iDummy);pParse->okConstFactor = okConstFactor;- for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */- if( i==nVector ){- /* LHS fields are not reordered */- rLhs = rLhsOrig;- }else{- /* Need to reorder the LHS fields according to aiMap */- rLhs = sqlite3GetTempRange(pParse, nVector);- for(i=0; i<nVector; i++){- sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);- }- }/* If sqlite3FindInIndex() did not find or create an index that is** suitable for evaluating the IN operator, then evaluate using a@@ -113542,6 +115550,7 @@ static void sqlite3ExprCodeIN(int r2, regToFree;int regCkNull = 0;int ii;+ assert( nVector==1 );assert( ExprUseXList(pExpr) );pList = pExpr->x.pList;pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);@@ -113583,6 +115592,26 @@ static void sqlite3ExprCodeIN(goto sqlite3ExprCodeIN_finished;}+ if( eType!=IN_INDEX_ROWID ){+ /* If this IN operator will use an index, then the order of columns in the+ ** vector might be different from the order in the index. In that case,+ ** we need to reorder the LHS values to be in index order. Run Affinity+ ** before reordering the columns, so that the affinity is correct.+ */+ sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);+ for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */+ if( i!=nVector ){+ /* Need to reorder the LHS fields according to aiMap */+ int rLhsOrig = rLhs;+ rLhs = sqlite3GetTempRange(pParse, nVector);+ for(i=0; i<nVector; i++){+ sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);+ }+ sqlite3ReleaseTempReg(pParse, rLhsOrig);+ }+ }++/* Step 2: Check to see if the LHS contains any NULL columns. If the** LHS does contain NULLs then the result must be either FALSE or NULL.** We will then skip the binary search of the RHS.@@ -113609,17 +115638,17 @@ static void sqlite3ExprCodeIN(/* In this case, the RHS is the ROWID of table b-tree and so we also** know that the RHS is non-NULL. Hence, we combine steps 3 and 4** into a single opcode. */+ assert( nVector==1 );sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);VdbeCoverage(v);addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */}else{- sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);if( destIfFalse==destIfNull ){/* Combine Step 3 and Step 5 into a single opcode */if( ExprHasProperty(pExpr, EP_Subrtn) ){const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr);assert( pOp->opcode==OP_Once || pParse->nErr );- if( pOp->opcode==OP_Once && pOp->p3>0 ){+ if( pOp->opcode==OP_Once && pOp->p3>0 ){ /* tag-202407032019 */assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) );sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse,rLhs, nVector); VdbeCoverage(v);@@ -113691,7 +115720,6 @@ static void sqlite3ExprCodeIN(sqlite3VdbeJumpHere(v, addrTruthOp);sqlite3ExprCodeIN_finished:- if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);VdbeComment((v, "end IN expr"));sqlite3ExprCodeIN_oom_error:sqlite3DbFree(pParse->db, aiMap);@@ -113806,7 +115834,12 @@ SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(iAddr = 0;}sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);- if( pCol->affinity>=SQLITE_AFF_TEXT ){+ if( (pCol->colFlags & COLFLAG_VIRTUAL)!=0+ && (pTab->tabFlags & TF_Strict)!=0+ ){+ int p3 = 2+(int)(pCol - pTab->aCol);+ sqlite3VdbeAddOp4(v, OP_TypeCheck, regOut, 1, p3, (char*)pTab, P4_TABLE);+ }else if( pCol->affinity>=SQLITE_AFF_TEXT ){sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);}if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);@@ -114211,7 +116244,7 @@ static SQLITE_NOINLINE int sqlite3IndexedExprLookup(/*-** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This+** Expression pExpr is guaranteed to be a TK_COLUMN or equivalent. This** function checks the Parse.pIdxPartExpr list to see if this column** can be replaced with a constant value. If so, it generates code to** put the constant value in a register (ideally, but not necessarily,@@ -114244,6 +116277,80 @@ static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){return 0;}+/*+** Generate code that evaluates an AND or OR operator leaving a+** boolean result in a register. pExpr is the AND/OR expression.+** Store the result in the "target" register. Use short-circuit+** evaluation to avoid computing both operands, if possible.+**+** The code generated might require the use of a temporary register.+** If it does, then write the number of that temporary register+** into *pTmpReg. If not, leave *pTmpReg unchanged.+*/+static SQLITE_NOINLINE int exprCodeTargetAndOr(+ Parse *pParse, /* Parsing context */+ Expr *pExpr, /* AND or OR expression to be coded */+ int target, /* Put result in this register, guaranteed */+ int *pTmpReg /* Write a temporary register here */+){+ int op; /* The opcode. TK_AND or TK_OR */+ int skipOp; /* Opcode for the branch that skips one operand */+ int addrSkip; /* Branch instruction that skips one of the operands */+ int regSS = 0; /* Register holding computed operand when other omitted */+ int r1, r2; /* Registers for left and right operands, respectively */+ Expr *pAlt; /* Alternative, simplified expression */+ Vdbe *v; /* statement being coded */++ assert( pExpr!=0 );+ op = pExpr->op;+ assert( op==TK_AND || op==TK_OR );+ assert( TK_AND==OP_And ); testcase( op==TK_AND );+ assert( TK_OR==OP_Or ); testcase( op==TK_OR );+ assert( pParse->pVdbe!=0 );+ v = pParse->pVdbe;+ pAlt = sqlite3ExprSimplifiedAndOr(pExpr);+ if( pAlt!=pExpr ){+ r1 = sqlite3ExprCodeTarget(pParse, pAlt, target);+ sqlite3VdbeAddOp3(v, OP_And, r1, r1, target);+ return target;+ }+ skipOp = op==TK_AND ? OP_IfNot : OP_If;+ if( exprEvalRhsFirst(pExpr) ){+ /* Compute the right operand first. Skip the computation of the left+ ** operand if the right operand fully determines the result */+ r2 = regSS = sqlite3ExprCodeTarget(pParse, pExpr->pRight, target);+ addrSkip = sqlite3VdbeAddOp1(v, skipOp, r2);+ VdbeComment((v, "skip left operand"));+ VdbeCoverage(v);+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pTmpReg);+ }else{+ /* Compute the left operand first */+ r1 = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);+ if( ExprHasProperty(pExpr->pRight, EP_Subquery) ){+ /* Skip over the computation of the right operand if the right+ ** operand is a subquery and the left operand completely determines+ ** the result */+ regSS = r1;+ addrSkip = sqlite3VdbeAddOp1(v, skipOp, r1);+ VdbeComment((v, "skip right operand"));+ VdbeCoverage(v);+ }else{+ addrSkip = regSS = 0;+ }+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pTmpReg);+ }+ sqlite3VdbeAddOp3(v, op, r2, r1, target);+ testcase( (*pTmpReg)==0 );+ if( addrSkip ){+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);+ sqlite3VdbeJumpHere(v, addrSkip);+ sqlite3VdbeAddOp3(v, OP_Or, regSS, regSS, target);+ VdbeComment((v, "short-circut value"));+ }+ return target;+}++/*** Generate code into the current Vdbe to evaluate the given@@ -114435,6 +116542,12 @@ expr_code_doover:sqlite3VdbeLoadString(v, target, pExpr->u.zToken);return target;}+ case TK_NULLS: {+ /* Set a range of registers to NULL. pExpr->y.nReg registers starting+ ** with target */+ sqlite3VdbeAddOp3(v, OP_Null, 0, target, target + pExpr->y.nReg - 1);+ return target;+ }default: {/* Make NULL the default case so that if a bug causes an illegal** Expr node to be passed into this function, it will be handled@@ -114493,11 +116606,17 @@ expr_code_doover:case TK_NE:case TK_EQ: {Expr *pLeft = pExpr->pLeft;+ int addrIsNull = 0;if( sqlite3ExprIsVector(pLeft) ){codeVectorCompare(pParse, pExpr, target, op, p5);}else{- r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1);- r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ if( ExprHasProperty(pExpr, EP_Subquery) && p5!=SQLITE_NULLEQ ){+ addrIsNull = exprComputeOperands(pParse, pExpr,+ &r1, &r2, ®Free1, ®Free2);+ }else{+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ }sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,sqlite3VdbeCurrentAddr(v)+2, p5,@@ -114512,6 +116631,11 @@ expr_code_doover:sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);}else{sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);+ if( addrIsNull ){+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);+ sqlite3VdbeJumpHere(v, addrIsNull);+ sqlite3VdbeAddOp2(v, OP_Null, 0, inReg);+ }}testcase( regFree1==0 );testcase( regFree2==0 );@@ -114519,7 +116643,10 @@ expr_code_doover:break;}case TK_AND:- case TK_OR:+ case TK_OR: {+ inReg = exprCodeTargetAndOr(pParse, pExpr, target, ®Free1);+ break;+ }case TK_PLUS:case TK_STAR:case TK_MINUS:@@ -114530,8 +116657,7 @@ expr_code_doover:case TK_LSHIFT:case TK_RSHIFT:case TK_CONCAT: {- assert( TK_AND==OP_And ); testcase( op==TK_AND );- assert( TK_OR==OP_Or ); testcase( op==TK_OR );+ int addrIsNull;assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );@@ -114541,11 +116667,23 @@ expr_code_doover:assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );- r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);- r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ if( ExprHasProperty(pExpr, EP_Subquery) ){+ addrIsNull = exprComputeOperands(pParse, pExpr,+ &r1, &r2, ®Free1, ®Free2);+ }else{+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ addrIsNull = 0;+ }sqlite3VdbeAddOp3(v, op, r2, r1, target);testcase( regFree1==0 );testcase( regFree2==0 );+ if( addrIsNull ){+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);+ sqlite3VdbeJumpHere(v, addrIsNull);+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);+ VdbeComment((v, "short-circut value"));+ }break;}case TK_UMINUS: {@@ -115119,6 +117257,25 @@ SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(return regDest;}+/*+** Make arrangements to invoke OP_Null on a range of registers+** during initialization.+*/+SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3ExprNullRegisterRange(+ Parse *pParse, /* Parsing context */+ int iReg, /* First register to set to NULL */+ int nReg /* Number of sequential registers to NULL out */+){+ u8 okConstFactor = pParse->okConstFactor;+ Expr t;+ memset(&t, 0, sizeof(t));+ t.op = TK_NULLS;+ t.y.nReg = nReg;+ pParse->okConstFactor = 1;+ sqlite3ExprCodeRunJustOnce(pParse, &t, iReg);+ pParse->okConstFactor = okConstFactor;+}+/*** Generate code to evaluate an expression and store the results** into a register. Return the register number where the results@@ -115394,17 +117551,27 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, intExpr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);if( pAlt!=pExpr ){sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);- }else if( op==TK_AND ){- int d2 = sqlite3VdbeMakeLabel(pParse);- testcase( jumpIfNull==0 );- sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,- jumpIfNull^SQLITE_JUMPIFNULL);- sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);- sqlite3VdbeResolveLabel(v, d2);}else{- testcase( jumpIfNull==0 );- sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);- sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);+ Expr *pFirst, *pSecond;+ if( exprEvalRhsFirst(pExpr) ){+ pFirst = pExpr->pRight;+ pSecond = pExpr->pLeft;+ }else{+ pFirst = pExpr->pLeft;+ pSecond = pExpr->pRight;+ }+ if( op==TK_AND ){+ int d2 = sqlite3VdbeMakeLabel(pParse);+ testcase( jumpIfNull==0 );+ sqlite3ExprIfFalse(pParse, pFirst, d2,+ jumpIfNull^SQLITE_JUMPIFNULL);+ sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull);+ sqlite3VdbeResolveLabel(v, d2);+ }else{+ testcase( jumpIfNull==0 );+ sqlite3ExprIfTrue(pParse, pFirst, dest, jumpIfNull);+ sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull);+ }}break;}@@ -115443,10 +117610,16 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, intcase TK_GE:case TK_NE:case TK_EQ: {+ int addrIsNull;if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;- testcase( jumpIfNull==0 );- r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);- r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){+ addrIsNull = exprComputeOperands(pParse, pExpr,+ &r1, &r2, ®Free1, ®Free2);+ }else{+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ addrIsNull = 0;+ }codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);@@ -115461,6 +117634,13 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, intVdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);testcase( regFree1==0 );testcase( regFree2==0 );+ if( addrIsNull ){+ if( jumpIfNull ){+ sqlite3VdbeChangeP2(v, addrIsNull, dest);+ }else{+ sqlite3VdbeJumpHere(v, addrIsNull);+ }+ }break;}case TK_ISNULL:@@ -115468,11 +117648,11 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, intassert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);- sqlite3VdbeTypeofColumn(v, r1);+ assert( regFree1==0 || regFree1==r1 );+ if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1);sqlite3VdbeAddOp2(v, op, r1, dest);VdbeCoverageIf(v, op==TK_ISNULL);VdbeCoverageIf(v, op==TK_NOTNULL);- testcase( regFree1==0 );break;}case TK_BETWEEN: {@@ -115568,17 +117748,27 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, intExpr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);if( pAlt!=pExpr ){sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);- }else if( pExpr->op==TK_AND ){- testcase( jumpIfNull==0 );- sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);- sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);}else{- int d2 = sqlite3VdbeMakeLabel(pParse);- testcase( jumpIfNull==0 );- sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,- jumpIfNull^SQLITE_JUMPIFNULL);- sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);- sqlite3VdbeResolveLabel(v, d2);+ Expr *pFirst, *pSecond;+ if( exprEvalRhsFirst(pExpr) ){+ pFirst = pExpr->pRight;+ pSecond = pExpr->pLeft;+ }else{+ pFirst = pExpr->pLeft;+ pSecond = pExpr->pRight;+ }+ if( pExpr->op==TK_AND ){+ testcase( jumpIfNull==0 );+ sqlite3ExprIfFalse(pParse, pFirst, dest, jumpIfNull);+ sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull);+ }else{+ int d2 = sqlite3VdbeMakeLabel(pParse);+ testcase( jumpIfNull==0 );+ sqlite3ExprIfTrue(pParse, pFirst, d2,+ jumpIfNull^SQLITE_JUMPIFNULL);+ sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull);+ sqlite3VdbeResolveLabel(v, d2);+ }}break;}@@ -115620,10 +117810,16 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, intcase TK_GE:case TK_NE:case TK_EQ: {+ int addrIsNull;if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;- testcase( jumpIfNull==0 );- r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);- r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){+ addrIsNull = exprComputeOperands(pParse, pExpr,+ &r1, &r2, ®Free1, ®Free2);+ }else{+ r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);+ r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);+ addrIsNull = 0;+ }codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);@@ -115638,16 +117834,23 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, intVdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);testcase( regFree1==0 );testcase( regFree2==0 );+ if( addrIsNull ){+ if( jumpIfNull ){+ sqlite3VdbeChangeP2(v, addrIsNull, dest);+ }else{+ sqlite3VdbeJumpHere(v, addrIsNull);+ }+ }break;}case TK_ISNULL:case TK_NOTNULL: {r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);- sqlite3VdbeTypeofColumn(v, r1);+ assert( regFree1==0 || regFree1==r1 );+ if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1);sqlite3VdbeAddOp2(v, op, r1, dest);testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);- testcase( regFree1==0 );break;}case TK_BETWEEN: {@@ -116547,7 +118750,9 @@ static void findOrCreateAggInfoColumn(){struct AggInfo_col *pCol;int k;+ int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];+ assert( mxTerm <= SMXV(i16) );assert( pAggInfo->iFirstReg==0 );pCol = pAggInfo->aCol;for(k=0; k<pAggInfo->nColumn; k++, pCol++){@@ -116565,6 +118770,10 @@ static void findOrCreateAggInfoColumn(assert( pParse->db->mallocFailed );return;}+ if( k>mxTerm ){+ sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm);+ k = mxTerm;+ }pCol = &pAggInfo->aCol[k];assert( ExprUseYTab(pExpr) );pCol->pTab = pExpr->y.pTab;@@ -116598,6 +118807,7 @@ fix_up_expr:if( pExpr->op==TK_COLUMN ){pExpr->op = TK_AGG_COLUMN;}+ assert( k <= SMXV(pExpr->iAgg) );pExpr->iAgg = (i16)k;}@@ -116682,13 +118892,19 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){** function that is already in the pAggInfo structure*/struct AggInfo_func *pItem = pAggInfo->aFunc;+ int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];+ assert( mxTerm <= SMXV(i16) );for(i=0; i<pAggInfo->nFunc; i++, pItem++){if( NEVER(pItem->pFExpr==pExpr) ) break;if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){break;}}- if( i>=pAggInfo->nFunc ){+ if( i>mxTerm ){+ sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm);+ i = mxTerm;+ assert( i<pAggInfo->nFunc );+ }else if( i>=pAggInfo->nFunc ){/* pExpr is original. Make a new entry in pAggInfo->aFunc[]*/u8 enc = ENC(pParse->db);@@ -116742,6 +118958,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){*/assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );ExprSetVVAProperty(pExpr, EP_NoReduce);+ assert( i <= SMXV(pExpr->iAgg) );pExpr->iAgg = (i16)i;pExpr->pAggInfo = pAggInfo;return WRC_Prune;@@ -117452,13 +119669,13 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){assert( pNew->nCol>0 );nAlloc = (((pNew->nCol-1)/8)*8)+8;assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );- pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);+ pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*(u32)nAlloc);pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);if( !pNew->aCol || !pNew->zName ){assert( db->mallocFailed );goto exit_begin_add_column;}- memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);+ memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*(size_t)pNew->nCol);for(i=0; i<pNew->nCol; i++){Column *pCol = &pNew->aCol[i];pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);@@ -117553,10 +119770,8 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(** altered. Set iCol to be the index of the column being renamed */zOld = sqlite3NameFromToken(db, pOld);if( !zOld ) goto exit_rename_column;- for(iCol=0; iCol<pTab->nCol; iCol++){- if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;- }- if( iCol==pTab->nCol ){+ iCol = sqlite3ColumnIndex(pTab, zOld);+ if( iCol<0 ){sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld);goto exit_rename_column;}@@ -118059,6 +120274,7 @@ static int renameParseSql(int bTemp /* True if SQL is from temp schema */){int rc;+ u64 flags;sqlite3ParseObjectInit(p, db);if( zSql==0 ){@@ -118067,11 +120283,21 @@ static int renameParseSql(if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){return SQLITE_CORRUPT_BKPT;}- db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);+ if( bTemp ){+ db->init.iDb = 1;+ }else{+ int iDb = sqlite3FindDbName(db, zDb);+ assert( iDb>=0 && iDb<=0xff );+ db->init.iDb = (u8)iDb;+ }p->eParseMode = PARSE_MODE_RENAME;p->db = db;p->nQueryLoop = 1;+ flags = db->flags;+ testcase( (db->flags & SQLITE_Comments)==0 && strstr(zSql," /* ")!=0 );+ db->flags |= SQLITE_Comments;rc = sqlite3RunParser(p, zSql);+ db->flags = flags;if( db->mallocFailed ) rc = SQLITE_NOMEM;if( rc==SQLITE_OK&& NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)@@ -118134,10 +120360,11 @@ static int renameEditSql(nQuot = sqlite3Strlen30(zQuot)-1;}- assert( nQuot>=nNew );- zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);+ assert( nQuot>=nNew && nSql>=0 && nNew>=0 );+ zOut = sqlite3DbMallocZero(db, (u64)nSql + pRename->nList*(u64)nQuot + 1);}else{- zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);+ assert( nSql>0 );+ zOut = (char*)sqlite3DbMallocZero(db, (2*(u64)nSql + 1) * 3);if( zOut ){zBuf1 = &zOut[nSql*2+1];zBuf2 = &zOut[nSql*4+2];@@ -118149,16 +120376,17 @@ static int renameEditSql(** with the new column name, or with single-quoted versions of themselves.** All that remains is to construct and return the edited SQL string. */if( zOut ){- int nOut = nSql;- memcpy(zOut, zSql, nSql);+ i64 nOut = nSql;+ assert( nSql>0 );+ memcpy(zOut, zSql, (size_t)nSql);while( pRename->pList ){int iOff; /* Offset of token to replace in zOut */- u32 nReplace;+ i64 nReplace;const char *zReplace;RenameToken *pBest = renameColumnTokenNext(pRename);if( zNew ){- if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){+ if( bQuote==0 && sqlite3IsIdChar(*(u8*)pBest->t.z) ){nReplace = nNew;zReplace = zNew;}else{@@ -118176,14 +120404,15 @@ static int renameEditSql(memcpy(zBuf1, pBest->t.z, pBest->t.n);zBuf1[pBest->t.n] = 0;sqlite3Dequote(zBuf1);- sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,+ assert( nSql < 0x15555554 /* otherwise malloc would have failed */ );+ sqlite3_snprintf((int)(nSql*2), zBuf2, "%Q%s", zBuf1,pBest->t.z[pBest->t.n]=='\'' ? " " : "");zReplace = zBuf2;nReplace = sqlite3Strlen30(zReplace);}- iOff = pBest->t.z - zSql;+ iOff = (int)(pBest->t.z - zSql);if( pBest->t.n!=nReplace ){memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],nOut - (iOff + pBest->t.n)@@ -118209,11 +120438,12 @@ static int renameEditSql(** Set all pEList->a[].fg.eEName fields in the expression-list to val.*/static void renameSetENames(ExprList *pEList, int val){+ assert( val==ENAME_NAME || val==ENAME_TAB || val==ENAME_SPAN );if( pEList ){int i;for(i=0; i<pEList->nExpr; i++){assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME );- pEList->a[i].fg.eEName = val;+ pEList->a[i].fg.eEName = val&0x3;}}}@@ -118470,7 +120700,7 @@ static void renameColumnFunc(if( sParse.pNewTable ){if( IsView(sParse.pNewTable) ){Select *pSelect = sParse.pNewTable->u.view.pSelect;- pSelect->selFlags &= ~SF_View;+ pSelect->selFlags &= ~(u32)SF_View;sParse.rc = SQLITE_OK;sqlite3SelectPrep(&sParse, pSelect, 0);rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);@@ -118688,7 +120918,7 @@ static void renameTableFunc(sNC.pParse = &sParse;assert( pSelect->selFlags & SF_View );- pSelect->selFlags &= ~SF_View;+ pSelect->selFlags &= ~(u32)SF_View;sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);if( sParse.nErr ){rc = sParse.rc;@@ -118861,7 +121091,7 @@ static void renameQuotefixFunc(if( sParse.pNewTable ){if( IsView(sParse.pNewTable) ){Select *pSelect = sParse.pNewTable->u.view.pSelect;- pSelect->selFlags &= ~SF_View;+ pSelect->selFlags &= ~(u32)SF_View;sParse.rc = SQLITE_OK;sqlite3SelectPrep(&sParse, pSelect, 0);rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);@@ -118960,10 +121190,10 @@ static void renameTableTest(if( zDb && zInput ){int rc;Parse sParse;- int flags = db->flags;+ u64 flags = db->flags;if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);- db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));+ db->flags = flags;if( rc==SQLITE_OK ){if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){NameContext sNC;@@ -119455,7 +121685,8 @@ static void openStatTable(sqlite3NestedParse(pParse,"CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols);- aRoot[i] = (u32)pParse->regRoot;+ assert( pParse->isCreate || pParse->nErr );+ aRoot[i] = (u32)pParse->u1.cr.regRoot;aCreateTbl[i] = OPFLAG_P2ISREG;}}else{@@ -119646,7 +121877,7 @@ static void statInit(int nCol; /* Number of columns in index being sampled */int nKeyCol; /* Number of key columns */int nColUp; /* nCol rounded up for alignment */- int n; /* Bytes of space to allocate */+ i64 n; /* Bytes of space to allocate */sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */#ifdef SQLITE_ENABLE_STAT4/* Maximum number of samples. 0 if STAT4 data is not collected */@@ -119682,7 +121913,7 @@ static void statInit(p->db = db;p->nEst = sqlite3_value_int64(argv[2]);p->nRow = 0;- p->nLimit = sqlite3_value_int64(argv[3]);+ p->nLimit = sqlite3_value_int(argv[3]);p->nCol = nCol;p->nKeyCol = nKeyCol;p->nSkipAhead = 0;@@ -120815,16 +123046,6 @@ static void decodeIntArray(while( z[0]!=0 && z[0]!=' ' ) z++;while( z[0]==' ' ) z++;}-- /* Set the bLowQual flag if the peak number of rows obtained- ** from a full equality match is so large that a full table scan- ** seems likely to be faster than using the index.- */- if( aLog[0] > 66 /* Index has more than 100 rows */- && aLog[0] <= aLog[nOut-1] /* And only a single value seen */- ){- pIndex->bLowQual = 1;- }}}@@ -121420,7 +123641,7 @@ static void attachFunc(if( aNew==0 ) return;memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);}else{- aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );+ aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(1+(i64)db->nDb));if( aNew==0 ) return;}db->aDb = aNew;@@ -121491,6 +123712,13 @@ static void attachFunc(sqlite3BtreeEnterAll(db);db->init.iDb = 0;db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ if( db->setlkFlags & SQLITE_SETLK_BLOCK_ON_CONNECT ){+ int val = 1;+ sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pNew->pBt));+ sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, &val);+ }+#endifif( !REOPEN_AS_MEMDB(db) ){rc = sqlite3Init(db, &zErrDyn);}@@ -122213,6 +124441,7 @@ static SQLITE_NOINLINE void lockTable(}}+ assert( pToplevel->nTableLock < 0x7fff0000 );nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);pToplevel->aTableLock =sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);@@ -122313,10 +124542,12 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){|| sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));if( v ){if( pParse->bReturning ){- Returning *pReturning = pParse->u1.pReturning;+ Returning *pReturning;int addrRewind;int reg;+ assert( !pParse->isCreate );+ pReturning = pParse->u1.d.pReturning;if( pReturning->nRetCol ){sqlite3VdbeAddOp0(v, OP_FkCheck);addrRewind =@@ -122392,7 +124623,9 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){}if( pParse->bReturning ){- Returning *pRet = pParse->u1.pReturning;+ Returning *pRet;+ assert( !pParse->isCreate );+ pRet = pParse->u1.d.pReturning;if( pRet->nRetCol ){sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);}@@ -122573,6 +124806,16 @@ SQLITE_PRIVATE Table *sqlite3LocateTable(if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){pMod = sqlite3PragmaVtabRegister(db, zName);}+#ifndef SQLITE_OMIT_JSON+ if( pMod==0 && sqlite3_strnicmp(zName, "json", 4)==0 ){+ pMod = sqlite3JsonVtabRegister(db, zName);+ }+#endif+#ifdef SQLITE_ENABLE_CARRAY+ if( pMod==0 && sqlite3_stricmp(zName, "carray")==0 ){+ pMod = sqlite3CarrayRegister(db);+ }+#endifif( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){testcase( pMod->pEpoTab==0 );return pMod->pEpoTab;@@ -123207,10 +125450,16 @@ SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){** find the (first) offset of that column in index pIdx. Or return -1** if column iCol is not used in index pIdx.*/-SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){+SQLITE_PRIVATE int sqlite3TableColumnToIndex(Index *pIdx, int iCol){int i;+ i16 iCol16;+ assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN );+ assert( pIdx->nColumn<=SQLITE_MAX_COLUMN*2 );+ iCol16 = iCol;for(i=0; i<pIdx->nColumn; i++){- if( iCol==pIdx->aiColumn[i] ) return i;+ if( iCol16==pIdx->aiColumn[i] ){+ return i;+ }}return -1;}@@ -123464,8 +125713,9 @@ SQLITE_PRIVATE void sqlite3StartTable(/* If the file format and encoding in the database have not been set,** set them now.*/- reg1 = pParse->regRowid = ++pParse->nMem;- reg2 = pParse->regRoot = ++pParse->nMem;+ assert( pParse->isCreate );+ reg1 = pParse->u1.cr.regRowid = ++pParse->nMem;+ reg2 = pParse->u1.cr.regRoot = ++pParse->nMem;reg3 = ++pParse->nMem;sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);sqlite3VdbeUsesBtree(v, iDb);@@ -123480,8 +125730,8 @@ SQLITE_PRIVATE void sqlite3StartTable(** The record created does not contain anything yet. It will be replaced** by the real entry in code generated at sqlite3EndTable().**- ** The rowid for the new entry is left in register pParse->regRowid.- ** The root page number of the new table is left in reg pParse->regRoot.+ ** The rowid for the new entry is left in register pParse->u1.cr.regRowid.+ ** The root page of the new table is left in reg pParse->u1.cr.regRoot.** The rowid and root page number values are needed by the code that** sqlite3EndTable will generate.*/@@ -123492,7 +125742,7 @@ SQLITE_PRIVATE void sqlite3StartTable(#endif{assert( !pParse->bReturning );- pParse->u1.addrCrTab =+ pParse->u1.cr.addrCrTab =sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);}sqlite3OpenSchemaTable(pParse, iDb);@@ -123501,6 +125751,9 @@ SQLITE_PRIVATE void sqlite3StartTable(sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);sqlite3VdbeChangeP5(v, OPFLAG_APPEND);sqlite3VdbeAddOp0(v, OP_Close);+ }else if( db->init.imposterTable ){+ pTable->tabFlags |= TF_Imposter;+ if( db->init.imposterTable>=2 ) pTable->tabFlags |= TF_Readonly;}/* Normal (non-error) return. */@@ -123570,7 +125823,8 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){sqlite3ExprListDelete(db, pList);return;}- pParse->u1.pReturning = pRet;+ assert( !pParse->isCreate );+ pParse->u1.d.pReturning = pRet;pRet->pParse = pParse;pRet->pReturnEL = pList;sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);@@ -123612,7 +125866,6 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){char *zType;Column *pCol;sqlite3 *db = pParse->db;- u8 hName;Column *aNew;u8 eType = COLTYPE_CUSTOM;u8 szEst = 1;@@ -123666,13 +125919,10 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){memcpy(z, sName.z, sName.n);z[sName.n] = 0;sqlite3Dequote(z);- hName = sqlite3StrIHash(z);- for(i=0; i<p->nCol; i++){- if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){- sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);- sqlite3DbFree(db, z);- return;- }+ if( p->nCol && sqlite3ColumnIndex(p, z)>=0 ){+ sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);+ sqlite3DbFree(db, z);+ return;}aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));if( aNew==0 ){@@ -123683,7 +125933,7 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){pCol = &p->aCol[p->nCol];memset(pCol, 0, sizeof(p->aCol[0]));pCol->zCnName = z;- pCol->hName = hName;+ pCol->hName = sqlite3StrIHash(z);sqlite3ColumnPropertiesFromName(p, pCol);if( sType.n==0 ){@@ -123707,9 +125957,14 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){pCol->affinity = sqlite3AffinityType(zType, pCol);pCol->colFlags |= COLFLAG_HASTYPE;}+ if( p->nCol<=0xff ){+ u8 h = pCol->hName % sizeof(p->aHx);+ p->aHx[h] = p->nCol;+ }p->nCol++;p->nNVCol++;- pParse->constraintName.n = 0;+ assert( pParse->isCreate );+ pParse->u1.cr.constraintName.n = 0;}/*@@ -123973,15 +126228,11 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(assert( pCExpr!=0 );sqlite3StringToId(pCExpr);if( pCExpr->op==TK_ID ){- const char *zCName;assert( !ExprHasProperty(pCExpr, EP_IntValue) );- zCName = pCExpr->u.zToken;- for(iCol=0; iCol<pTab->nCol; iCol++){- if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){- pCol = &pTab->aCol[iCol];- makeColumnPartOfPrimaryKey(pParse, pCol);- break;- }+ iCol = sqlite3ColumnIndex(pTab, pCExpr->u.zToken);+ if( iCol>=0 ){+ pCol = &pTab->aCol[iCol];+ makeColumnPartOfPrimaryKey(pParse, pCol);}}}@@ -124033,8 +126284,10 @@ SQLITE_PRIVATE void sqlite3AddCheckConstraint(&& !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)){pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);- if( pParse->constraintName.n ){- sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);+ assert( pParse->isCreate );+ if( pParse->u1.cr.constraintName.n ){+ sqlite3ExprListSetName(pParse, pTab->pCheck,+ &pParse->u1.cr.constraintName, 1);}else{Token t;for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}@@ -124229,7 +126482,8 @@ static void identPut(char *z, int *pIdx, char *zSignedIdent){** from sqliteMalloc() and must be freed by the calling function.*/static char *createTableStmt(sqlite3 *db, Table *p){- int i, k, n;+ int i, k, len;+ i64 n;char *zStmt;char *zSep, *zSep2, *zEnd;Column *pCol;@@ -124253,8 +126507,9 @@ static char *createTableStmt(sqlite3 *db, Table *p){sqlite3OomFault(db);return 0;}- sqlite3_snprintf(n, zStmt, "CREATE TABLE ");- k = sqlite3Strlen30(zStmt);+ assert( n>14 && n<=0x7fffffff );+ memcpy(zStmt, "CREATE TABLE ", 13);+ k = 13;identPut(zStmt, &k, p->zName);zStmt[k++] = '(';for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){@@ -124266,13 +126521,15 @@ static char *createTableStmt(sqlite3 *db, Table *p){/* SQLITE_AFF_REAL */ " REAL",/* SQLITE_AFF_FLEXNUM */ " NUM",};- int len;const char *zType;- sqlite3_snprintf(n-k, &zStmt[k], zSep);- k += sqlite3Strlen30(&zStmt[k]);+ len = sqlite3Strlen30(zSep);+ assert( k+len<n );+ memcpy(&zStmt[k], zSep, len);+ k += len;zSep = zSep2;identPut(zStmt, &k, pCol->zCnName);+ assert( k<n );assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );testcase( pCol->affinity==SQLITE_AFF_BLOB );@@ -124287,11 +126544,14 @@ static char *createTableStmt(sqlite3 *db, Table *p){assert( pCol->affinity==SQLITE_AFF_BLOB|| pCol->affinity==SQLITE_AFF_FLEXNUM|| pCol->affinity==sqlite3AffinityType(zType, 0) );+ assert( k+len<n );memcpy(&zStmt[k], zType, len);k += len;assert( k<=n );}- sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);+ len = sqlite3Strlen30(zEnd);+ assert( k+len<n );+ memcpy(&zStmt[k], zEnd, len+1);return zStmt;}@@ -124299,12 +126559,17 @@ static char *createTableStmt(sqlite3 *db, Table *p){** Resize an Index object to hold N columns total. Return SQLITE_OK** on success and SQLITE_NOMEM on an OOM error.*/-static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){+static int resizeIndexObject(Parse *pParse, Index *pIdx, int N){char *zExtra;- int nByte;+ u64 nByte;+ sqlite3 *db;if( pIdx->nColumn>=N ) return SQLITE_OK;+ db = pParse->db;+ assert( N>0 );+ assert( N <= SQLITE_MAX_COLUMN*2 /* tag-20250221-1 */ );+ testcase( N==2*pParse->db->aLimit[SQLITE_LIMIT_COLUMN] );assert( pIdx->isResized==0 );- nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;+ nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*(u64)N;zExtra = sqlite3DbMallocZero(db, nByte);if( zExtra==0 ) return SQLITE_NOMEM_BKPT;memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);@@ -124318,7 +126583,7 @@ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){zExtra += sizeof(i16)*N;memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);pIdx->aSortOrder = (u8*)zExtra;- pIdx->nColumn = N;+ pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */pIdx->isResized = 1;return SQLITE_OK;}@@ -124484,9 +126749,9 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){** into BTREE_BLOBKEY.*/assert( !pParse->bReturning );- if( pParse->u1.addrCrTab ){+ if( pParse->u1.cr.addrCrTab ){assert( v );- sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);+ sqlite3VdbeChangeP3(v, pParse->u1.cr.addrCrTab, BTREE_BLOBKEY);}/* Locate the PRIMARY KEY index. Or, if this table was originally@@ -124572,14 +126837,14 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){pIdx->nColumn = pIdx->nKeyCol;continue;}- if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;+ if( resizeIndexObject(pParse, pIdx, pIdx->nKeyCol+n) ) return;for(i=0, j=pIdx->nKeyCol; i<nPk; i++){if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );pIdx->aiColumn[j] = pPk->aiColumn[i];pIdx->azColl[j] = pPk->azColl[i];if( pPk->aSortOrder[i] ){- /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */+ /* See ticket https://sqlite.org/src/info/bba7b69f9849b5bf */pIdx->bAscKeyBug = 1;}j++;@@ -124596,7 +126861,7 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){if( !hasColumn(pPk->aiColumn, nPk, i)&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;}- if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;+ if( resizeIndexObject(pParse, pPk, nPk+nExtra) ) return;for(i=0, j=nPk; i<pTab->nCol; i++){if( !hasColumn(pPk->aiColumn, j, i)&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0@@ -124926,7 +127191,7 @@ SQLITE_PRIVATE void sqlite3EndTable(/* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT** statement to populate the new table. The root-page number for the- ** new table is in register pParse->regRoot.+ ** new table is in register pParse->u1.cr.regRoot.**** Once the SELECT has been coded by sqlite3Select(), it is in a** suitable state to query for the column names and types to be used@@ -124957,7 +127222,8 @@ SQLITE_PRIVATE void sqlite3EndTable(regRec = ++pParse->nMem;regRowid = ++pParse->nMem;sqlite3MayAbort(pParse);- sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->regRoot, iDb);+ assert( pParse->isCreate );+ sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->u1.cr.regRoot, iDb);sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);addrTop = sqlite3VdbeCurrentAddr(v) + 1;sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);@@ -125002,6 +127268,7 @@ SQLITE_PRIVATE void sqlite3EndTable(** schema table. We just need to update that slot with all** the information we've collected.*/+ assert( pParse->isCreate );sqlite3NestedParse(pParse,"UPDATE %Q." LEGACY_SCHEMA_TABLE" SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"@@ -125010,9 +127277,9 @@ SQLITE_PRIVATE void sqlite3EndTable(zType,p->zName,p->zName,- pParse->regRoot,+ pParse->u1.cr.regRoot,zStmt,- pParse->regRowid+ pParse->u1.cr.regRowid);sqlite3DbFree(db, zStmt);sqlite3ChangeCookie(pParse, iDb);@@ -125752,7 +128019,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(}else{nCol = pFromCol->nExpr;}- nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;+ nByte = SZ_FKEY(nCol) + pTo->n + 1;if( pToCol ){for(i=0; i<pToCol->nExpr; i++){nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;@@ -125954,7 +128221,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){** not work for UNIQUE constraint indexes on WITHOUT ROWID tables** with DESC primary keys, since those indexes have there keys in** a different order from the main table.- ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf+ ** See ticket: https://sqlite.org/src/info/bba7b69f9849b5bf*/sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);}@@ -125978,13 +128245,14 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){*/SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3 *db, /* Database connection */- i16 nCol, /* Total number of columns in the index */+ int nCol, /* Total number of columns in the index */int nExtra, /* Number of bytes of extra space to alloc */char **ppExtra /* Pointer to the "extra" space */){Index *p; /* Allocated index object */- int nByte; /* Bytes of space for Index object + arrays */+ i64 nByte; /* Bytes of space for Index object + arrays */+ assert( nCol <= 2*db->aLimit[SQLITE_LIMIT_COLUMN] );nByte = ROUND8(sizeof(Index)) + /* Index structure */ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */@@ -125997,8 +128265,9 @@ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;p->aSortOrder = (u8*)pExtra;- p->nColumn = nCol;- p->nKeyCol = nCol - 1;+ assert( nCol>0 );+ p->nColumn = (u16)nCol;+ p->nKeyCol = (u16)(nCol - 1);*ppExtra = ((char*)p) + nByte;}return p;@@ -126809,12 +129078,11 @@ SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *sqlite3 *db = pParse->db;int i;if( pList==0 ){- pList = sqlite3DbMallocZero(db, sizeof(IdList) );+ pList = sqlite3DbMallocZero(db, SZ_IDLIST(1));if( pList==0 ) return 0;}else{IdList *pNew;- pNew = sqlite3DbRealloc(db, pList,- sizeof(IdList) + pList->nId*sizeof(pList->a));+ pNew = sqlite3DbRealloc(db, pList, SZ_IDLIST(pList->nId+1));if( pNew==0 ){sqlite3IdListDelete(db, pList);return 0;@@ -126913,8 +129181,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(return 0;}if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;- pNew = sqlite3DbRealloc(db, pSrc,- sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );+ pNew = sqlite3DbRealloc(db, pSrc, SZ_SRCLIST(nAlloc));if( pNew==0 ){assert( db->mallocFailed );return 0;@@ -126989,7 +129256,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(assert( pParse->db!=0 );db = pParse->db;if( pList==0 ){- pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );+ pList = sqlite3DbMallocRawNN(pParse->db, SZ_SRCLIST(1));if( pList==0 ) return 0;pList->nAlloc = 1;pList->nSrc = 1;@@ -127256,16 +129523,22 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI** are deleted by this function.*/SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){- assert( p1 && p1->nSrc==1 );+ assert( p1 );+ assert( p2 || pParse->nErr );+ assert( p2==0 || p2->nSrc>=1 );+ testcase( p1->nSrc==0 );if( p2 ){- SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);+ int nOld = p1->nSrc;+ SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, nOld);if( pNew==0 ){sqlite3SrcListDelete(pParse->db, p2);}else{p1 = pNew;- memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));+ memcpy(&p1->a[nOld], p2->a, p2->nSrc*sizeof(SrcItem));+ assert( nOld==1 || (p2->a[0].fg.jointype & JT_LTORJ)==0 );+ assert( p1->nSrc>=1 );+ p1->a[0].fg.jointype |= (JT_LTORJ & p2->a[0].fg.jointype);sqlite3DbFree(pParse->db, p2);- p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);}}return p1;@@ -127776,14 +130049,19 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){}if( pParse->nErr ){assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );- if( pIdx->bNoQuery==0 ){+ if( pIdx->bNoQuery==0+ && sqlite3HashFind(&pIdx->pSchema->idxHash, pIdx->zName)+ ){/* Deactivate the index because it contains an unknown collating** sequence. The only way to reactive the index is to reload the** schema. Adding the missing collating sequence later does not** reactive the index. The application had the chance to register** the missing index using the collation-needed callback. For** simplicity, SQLite will not give the application a second chance.- */+ **+ ** Except, do not do this if the index is not in the schema hash+ ** table. In this case the index is currently being constructed+ ** by a CREATE INDEX statement, and retrying will not help. */pIdx->bNoQuery = 1;pParse->rc = SQLITE_ERROR_RETRY;}@@ -127875,10 +130153,9 @@ SQLITE_PRIVATE With *sqlite3WithAdd(}if( pWith ){- sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);- pNew = sqlite3DbRealloc(db, pWith, nByte);+ pNew = sqlite3DbRealloc(db, pWith, SZ_WITH(pWith->nCte+1));}else{- pNew = sqlite3DbMallocZero(db, sizeof(*pWith));+ pNew = sqlite3DbMallocZero(db, SZ_WITH(1));}assert( (pNew!=0 && zName!=0) || db->mallocFailed );@@ -128421,6 +130698,7 @@ SQLITE_PRIVATE void sqlite3SchemaClear(void *p){for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){sqlite3DeleteTrigger(&xdb, (Trigger*)sqliteHashData(pElem));}+sqlite3HashClear(&temp2);sqlite3HashInit(&pSchema->tblHash);for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){@@ -129852,11 +132130,6 @@ static void substrFunc(i64 p1, p2;assert( argc==3 || argc==2 );- if( sqlite3_value_type(argv[1])==SQLITE_NULL- || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)- ){- return;- }p0type = sqlite3_value_type(argv[0]);p1 = sqlite3_value_int64(argv[1]);if( p0type==SQLITE_BLOB ){@@ -129874,19 +132147,23 @@ static void substrFunc(}}}-#ifdef SQLITE_SUBSTR_COMPATIBILITY- /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as- ** as substr(X,1,N) - it returns the first N characters of X. This- ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]- ** from 2009-02-02 for compatibility of applications that exploited the- ** old buggy behavior. */- if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */-#endifif( argc==3 ){p2 = sqlite3_value_int64(argv[2]);+ if( p2==0 && sqlite3_value_type(argv[2])==SQLITE_NULL ) return;}else{p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];}+ if( p1==0 ){+#ifdef SQLITE_SUBSTR_COMPATIBILITY+ /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as+ ** as substr(X,1,N) - it returns the first N characters of X. This+ ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]+ ** from 2009-02-02 for compatibility of applications that exploited the+ ** old buggy behavior. */+ p1 = 1; /* <rdar://problem/6778339> */+#endif+ if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return;+ }if( p1<0 ){p1 += len;if( p1<0 ){@@ -129982,7 +132259,7 @@ static void *contextMalloc(sqlite3_context *context, i64 nByte){sqlite3 *db = sqlite3_context_db_handle(context);assert( nByte>0 );testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );- testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );+ testcase( nByte==(i64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){sqlite3_result_error_toobig(context);z = 0;@@ -130587,7 +132864,7 @@ static const char hexdigits[] = {** Append to pStr text that is the SQL literal representation of the** value contained in pValue.*/-SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){+SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue, int bEscape){/* As currently implemented, the string must be initially empty.** we might relax this requirement in the future, but that will** require enhancements to the implementation. */@@ -130635,7 +132912,7 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){}case SQLITE_TEXT: {const unsigned char *zArg = sqlite3_value_text(pValue);- sqlite3_str_appendf(pStr, "%Q", zArg);+ sqlite3_str_appendf(pStr, bEscape ? "%#Q" : "%Q", zArg);break;}default: {@@ -130646,6 +132923,105 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){}}+/*+** Return true if z[] begins with N hexadecimal digits, and write+** a decoding of those digits into *pVal. Or return false if any+** one of the first N characters in z[] is not a hexadecimal digit.+*/+static int isNHex(const char *z, int N, u32 *pVal){+ int i;+ u32 v = 0;+ for(i=0; i<N; i++){+ if( !sqlite3Isxdigit(z[i]) ) return 0;+ v = (v<<4) + sqlite3HexToInt(z[i]);+ }+ *pVal = v;+ return 1;+}++/*+** Implementation of the UNISTR() function.+**+** This is intended to be a work-alike of the UNISTR() function in+** PostgreSQL. Quoting from the PG documentation (PostgreSQL 17 -+** scraped on 2025-02-22):+**+** Evaluate escaped Unicode characters in the argument. Unicode+** characters can be specified as \XXXX (4 hexadecimal digits),+** \+XXXXXX (6 hexadecimal digits), \uXXXX (4 hexadecimal digits),+** or \UXXXXXXXX (8 hexadecimal digits). To specify a backslash,+** write two backslashes. All other characters are taken literally.+*/+static void unistrFunc(+ sqlite3_context *context,+ int argc,+ sqlite3_value **argv+){+ char *zOut;+ const char *zIn;+ int nIn;+ int i, j, n;+ u32 v;++ assert( argc==1 );+ UNUSED_PARAMETER( argc );+ zIn = (const char*)sqlite3_value_text(argv[0]);+ if( zIn==0 ) return;+ nIn = sqlite3_value_bytes(argv[0]);+ zOut = sqlite3_malloc64(nIn+1);+ if( zOut==0 ){+ sqlite3_result_error_nomem(context);+ return;+ }+ i = j = 0;+ while( i<nIn ){+ char *z = strchr(&zIn[i],'\\');+ if( z==0 ){+ n = nIn - i;+ memmove(&zOut[j], &zIn[i], n);+ j += n;+ break;+ }+ n = z - &zIn[i];+ if( n>0 ){+ memmove(&zOut[j], &zIn[i], n);+ j += n;+ i += n;+ }+ if( zIn[i+1]=='\\' ){+ i += 2;+ zOut[j++] = '\\';+ }else if( sqlite3Isxdigit(zIn[i+1]) ){+ if( !isNHex(&zIn[i+1], 4, &v) ) goto unistr_error;+ i += 5;+ j += sqlite3AppendOneUtf8Character(&zOut[j], v);+ }else if( zIn[i+1]=='+' ){+ if( !isNHex(&zIn[i+2], 6, &v) ) goto unistr_error;+ i += 8;+ j += sqlite3AppendOneUtf8Character(&zOut[j], v);+ }else if( zIn[i+1]=='u' ){+ if( !isNHex(&zIn[i+2], 4, &v) ) goto unistr_error;+ i += 6;+ j += sqlite3AppendOneUtf8Character(&zOut[j], v);+ }else if( zIn[i+1]=='U' ){+ if( !isNHex(&zIn[i+2], 8, &v) ) goto unistr_error;+ i += 10;+ j += sqlite3AppendOneUtf8Character(&zOut[j], v);+ }else{+ goto unistr_error;+ }+ }+ zOut[j] = 0;+ sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8);+ return;++unistr_error:+ sqlite3_free(zOut);+ sqlite3_result_error(context, "invalid Unicode escape", -1);+ return;+}++/*** Implementation of the QUOTE() function.**@@ -130655,6 +133031,10 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){** as needed. BLOBs are encoded as hexadecimal literals. Strings with** embedded NUL characters cannot be represented as string literals in SQL** and hence the returned string literal is truncated prior to the first NUL.+**+** If sqlite3_user_data() is non-zero, then the UNISTR_QUOTE() function is+** implemented instead. The difference is that UNISTR_QUOTE() uses the+** UNISTR() function to escape control characters.*/static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){sqlite3_str str;@@ -130662,7 +133042,7 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){assert( argc==1 );UNUSED_PARAMETER(argc);sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);- sqlite3QuoteValue(&str,argv[0]);+ sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context)));sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar,SQLITE_DYNAMIC);if( str.accError!=SQLITE_OK ){@@ -130917,7 +133297,7 @@ static void replaceFunc(assert( zRep==sqlite3_value_text(argv[2]) );nOut = nStr + 1;assert( nOut<SQLITE_MAX_LENGTH );- zOut = contextMalloc(context, (i64)nOut);+ zOut = contextMalloc(context, nOut);if( zOut==0 ){return;}@@ -131061,8 +133441,9 @@ static void concatFuncCore(int nSep,const char *zSep){- i64 j, k, n = 0;+ i64 j, n = 0;int i;+ int bNotNull = 0; /* True after at least NOT NULL argument seen */char *z;for(i=0; i<argc; i++){n += sqlite3_value_bytes(argv[i]);@@ -131075,16 +133456,17 @@ static void concatFuncCore(}j = 0;for(i=0; i<argc; i++){- k = sqlite3_value_bytes(argv[i]);- if( k>0 ){+ if( sqlite3_value_type(argv[i])!=SQLITE_NULL ){+ int k = sqlite3_value_bytes(argv[i]);const char *v = (const char*)sqlite3_value_text(argv[i]);if( v!=0 ){- if( j>0 && nSep>0 ){+ if( bNotNull && nSep>0 ){memcpy(&z[j], zSep, nSep);j += nSep;}memcpy(&z[j], v, k);j += k;+ bNotNull = 1;}}}@@ -131313,7 +133695,7 @@ static void kahanBabuskaNeumaierInit(** that it returns NULL if it sums over no inputs. TOTAL returns** 0.0 in that case. In addition, TOTAL always returns a float where** SUM might return an integer if it never encounters a floating point-** value. TOTAL never fails, but SUM might through an exception if+** value. TOTAL never fails, but SUM might throw an exception if** it overflows an integer.*/static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){@@ -132030,6 +134412,502 @@ static void signFunc(sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);}+#if defined(SQLITE_ENABLE_PERCENTILE)+/***********************************************************************+** This section implements the percentile(Y,P) SQL function and similar.+** Requirements:+**+** (1) The percentile(Y,P) function is an aggregate function taking+** exactly two arguments.+**+** (2) If the P argument to percentile(Y,P) is not the same for every+** row in the aggregate then an error is thrown. The word "same"+** in the previous sentence means that the value differ by less+** than 0.001.+**+** (3) If the P argument to percentile(Y,P) evaluates to anything other+** than a number in the range of 0.0 to 100.0 inclusive then an+** error is thrown.+**+** (4) If any Y argument to percentile(Y,P) evaluates to a value that+** is not NULL and is not numeric then an error is thrown.+**+** (5) If any Y argument to percentile(Y,P) evaluates to plus or minus+** infinity then an error is thrown. (SQLite always interprets NaN+** values as NULL.)+**+** (6) Both Y and P in percentile(Y,P) can be arbitrary expressions,+** including CASE WHEN expressions.+**+** (7) The percentile(Y,P) aggregate is able to handle inputs of at least+** one million (1,000,000) rows.+**+** (8) If there are no non-NULL values for Y, then percentile(Y,P)+** returns NULL.+**+** (9) If there is exactly one non-NULL value for Y, the percentile(Y,P)+** returns the one Y value.+**+** (10) If there N non-NULL values of Y where N is two or more and+** the Y values are ordered from least to greatest and a graph is+** drawn from 0 to N-1 such that the height of the graph at J is+** the J-th Y value and such that straight lines are drawn between+** adjacent Y values, then the percentile(Y,P) function returns+** the height of the graph at P*(N-1)/100.+**+** (11) The percentile(Y,P) function always returns either a floating+** point number or NULL.+**+** (12) The percentile(Y,P) is implemented as a single C99 source-code+** file that compiles into a shared-library or DLL that can be loaded+** into SQLite using the sqlite3_load_extension() interface.+**+** (13) A separate median(Y) function is the equivalent percentile(Y,50).+**+** (14) A separate percentile_cont(Y,P) function is equivalent to+** percentile(Y,P/100.0). In other words, the fraction value in+** the second argument is in the range of 0 to 1 instead of 0 to 100.+**+** (15) A separate percentile_disc(Y,P) function is like+** percentile_cont(Y,P) except that instead of returning the weighted+** average of the nearest two input values, it returns the next lower+** value. So the percentile_disc(Y,P) will always return a value+** that was one of the inputs.+**+** (16) All of median(), percentile(Y,P), percentile_cont(Y,P) and+** percentile_disc(Y,P) can be used as window functions.+**+** Differences from standard SQL:+**+** * The percentile_cont(X,P) function is equivalent to the following in+** standard SQL:+**+** (percentile_cont(P) WITHIN GROUP (ORDER BY X))+**+** The SQLite syntax is much more compact. The standard SQL syntax+** is also supported if SQLite is compiled with the+** -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option.+**+** * No median(X) function exists in the SQL standard. App developers+** are expected to write "percentile_cont(0.5)WITHIN GROUP(ORDER BY X)".+**+** * No percentile(Y,P) function exists in the SQL standard. Instead of+** percential(Y,P), developers must write this:+** "percentile_cont(P/100.0) WITHIN GROUP (ORDER BY Y)". Note that+** the fraction parameter to percentile() goes from 0 to 100 whereas+** the fraction parameter in SQL standard percentile_cont() goes from+** 0 to 1.+**+** Implementation notes as of 2024-08-31:+**+** * The regular aggregate-function versions of these routines work+** by accumulating all values in an array of doubles, then sorting+** that array using quicksort before computing the answer. Thus+** the runtime is O(NlogN) where N is the number of rows of input.+**+** * For the window-function versions of these routines, the array of+** inputs is sorted as soon as the first value is computed. Thereafter,+** the array is kept in sorted order using an insert-sort. This+** results in O(N*K) performance where K is the size of the window.+** One can imagine alternative implementations that give O(N*logN*logK)+** performance, but they require more complex logic and data structures.+** The developers have elected to keep the asymptotically slower+** algorithm for now, for simplicity, under the theory that window+** functions are seldom used and when they are, the window size K is+** often small. The developers might revisit that decision later,+** should the need arise.+*/++/* The following object is the group context for a single percentile()+** aggregate. Remember all input Y values until the very end.+** Those values are accumulated in the Percentile.a[] array.+*/+typedef struct Percentile Percentile;+struct Percentile {+ u64 nAlloc; /* Number of slots allocated for a[] */+ u64 nUsed; /* Number of slots actually used in a[] */+ char bSorted; /* True if a[] is already in sorted order */+ char bKeepSorted; /* True if advantageous to keep a[] sorted */+ char bPctValid; /* True if rPct is valid */+ double rPct; /* Fraction. 0.0 to 1.0 */+ double *a; /* Array of Y values */+};++/*+** Return TRUE if the input floating-point number is an infinity.+*/+static int percentIsInfinity(double r){+ sqlite3_uint64 u;+ assert( sizeof(u)==sizeof(r) );+ memcpy(&u, &r, sizeof(u));+ return ((u>>52)&0x7ff)==0x7ff;+}++/*+** Return TRUE if two doubles differ by 0.001 or less.+*/+static int percentSameValue(double a, double b){+ a -= b;+ return a>=-0.001 && a<=0.001;+}++/*+** Search p (which must have p->bSorted) looking for an entry with+** value y. Return the index of that entry.+**+** If bExact is true, return -1 if the entry is not found.+**+** If bExact is false, return the index at which a new entry with+** value y should be insert in order to keep the values in sorted+** order. The smallest return value in this case will be 0, and+** the largest return value will be p->nUsed.+*/+static i64 percentBinarySearch(Percentile *p, double y, int bExact){+ i64 iFirst = 0; /* First element of search range */+ i64 iLast = (i64)p->nUsed - 1; /* Last element of search range */+ while( iLast>=iFirst ){+ i64 iMid = (iFirst+iLast)/2;+ double x = p->a[iMid];+ if( x<y ){+ iFirst = iMid + 1;+ }else if( x>y ){+ iLast = iMid - 1;+ }else{+ return iMid;+ }+ }+ if( bExact ) return -1;+ return iFirst;+}++/*+** Generate an error for a percentile function.+**+** The error format string must have exactly one occurrence of "%%s()"+** (with two '%' characters). That substring will be replaced by the name+** of the function.+*/+static void percentError(sqlite3_context *pCtx, const char *zFormat, ...){+ char *zMsg1;+ char *zMsg2;+ va_list ap;++ va_start(ap, zFormat);+ zMsg1 = sqlite3_vmprintf(zFormat, ap);+ va_end(ap);+ zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, sqlite3VdbeFuncName(pCtx)) : 0;+ sqlite3_result_error(pCtx, zMsg2, -1);+ sqlite3_free(zMsg1);+ sqlite3_free(zMsg2);+}++/*+** The "step" function for percentile(Y,P) is called once for each+** input row.+*/+static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){+ Percentile *p;+ double rPct;+ int eType;+ double y;+ assert( argc==2 || argc==1 );++ if( argc==1 ){+ /* Requirement 13: median(Y) is the same as percentile(Y,50). */+ rPct = 0.5;+ }else{+ /* P must be a number between 0 and 100 for percentile() or between+ ** 0.0 and 1.0 for percentile_cont() and percentile_disc().+ **+ ** The user-data is an integer which is 10 times the upper bound.+ */+ double mxFrac = (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&2)? 100.0 : 1.0;+ eType = sqlite3_value_numeric_type(argv[1]);+ rPct = sqlite3_value_double(argv[1])/mxFrac;+ if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT)+ || rPct<0.0 || rPct>1.0+ ){+ percentError(pCtx, "the fraction argument to %%s()"+ " is not between 0.0 and %.1f",+ (double)mxFrac);+ return;+ }+ }++ /* Allocate the session context. */+ p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p));+ if( p==0 ) return;++ /* Remember the P value. Throw an error if the P value is different+ ** from any prior row, per Requirement (2). */+ if( !p->bPctValid ){+ p->rPct = rPct;+ p->bPctValid = 1;+ }else if( !percentSameValue(p->rPct,rPct) ){+ percentError(pCtx, "the fraction argument to %%s()"+ " is not the same for all input rows");+ return;+ }++ /* Ignore rows for which Y is NULL */+ eType = sqlite3_value_type(argv[0]);+ if( eType==SQLITE_NULL ) return;++ /* If not NULL, then Y must be numeric. Otherwise throw an error.+ ** Requirement 4 */+ if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){+ percentError(pCtx, "input to %%s() is not numeric");+ return;+ }++ /* Throw an error if the Y value is infinity or NaN */+ y = sqlite3_value_double(argv[0]);+ if( percentIsInfinity(y) ){+ percentError(pCtx, "Inf input to %%s()");+ return;+ }++ /* Allocate and store the Y */+ if( p->nUsed>=p->nAlloc ){+ u64 n = p->nAlloc*2 + 250;+ double *a = sqlite3_realloc64(p->a, sizeof(double)*n);+ if( a==0 ){+ sqlite3_free(p->a);+ memset(p, 0, sizeof(*p));+ sqlite3_result_error_nomem(pCtx);+ return;+ }+ p->nAlloc = n;+ p->a = a;+ }+ if( p->nUsed==0 ){+ p->a[p->nUsed++] = y;+ p->bSorted = 1;+ }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){+ p->a[p->nUsed++] = y;+ }else if( p->bKeepSorted ){+ i64 i;+ i = percentBinarySearch(p, y, 0);+ if( i<(int)p->nUsed ){+ memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0]));+ }+ p->a[i] = y;+ p->nUsed++;+ }else{+ p->a[p->nUsed++] = y;+ p->bSorted = 0;+ }+}++/*+** Interchange two doubles.+*/+#define SWAP_DOUBLE(X,Y) {double ttt=(X);(X)=(Y);(Y)=ttt;}++/*+** Sort an array of doubles.+**+** Algorithm: quicksort+**+** This is implemented separately rather than using the qsort() routine+** from the standard library because:+**+** (1) To avoid a dependency on qsort()+** (2) To avoid the function call to the comparison routine for each+** comparison.+*/+static void percentSort(double *a, unsigned int n){+ int iLt; /* Entries before a[iLt] are less than rPivot */+ int iGt; /* Entries at or after a[iGt] are greater than rPivot */+ int i; /* Loop counter */+ double rPivot; /* The pivot value */++ assert( n>=2 );+ if( a[0]>a[n-1] ){+ SWAP_DOUBLE(a[0],a[n-1])+ }+ if( n==2 ) return;+ iGt = n-1;+ i = n/2;+ if( a[0]>a[i] ){+ SWAP_DOUBLE(a[0],a[i])+ }else if( a[i]>a[iGt] ){+ SWAP_DOUBLE(a[i],a[iGt])+ }+ if( n==3 ) return;+ rPivot = a[i];+ iLt = i = 1;+ do{+ if( a[i]<rPivot ){+ if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt])+ iLt++;+ i++;+ }else if( a[i]>rPivot ){+ do{+ iGt--;+ }while( iGt>i && a[iGt]>rPivot );+ SWAP_DOUBLE(a[i],a[iGt])+ }else{+ i++;+ }+ }while( i<iGt );+ if( iLt>=2 ) percentSort(a, iLt);+ if( n-iGt>=2 ) percentSort(a+iGt, n-iGt);++/* Uncomment for testing */+#if 0+ for(i=0; i<n-1; i++){+ assert( a[i]<=a[i+1] );+ }+#endif+}+++/*+** The "inverse" function for percentile(Y,P) is called to remove a+** row that was previously inserted by "step".+*/+static void percentInverse(sqlite3_context *pCtx,int argc,sqlite3_value **argv){+ Percentile *p;+ int eType;+ double y;+ i64 i;+ assert( argc==2 || argc==1 );++ /* Allocate the session context. */+ p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p));+ assert( p!=0 );++ /* Ignore rows for which Y is NULL */+ eType = sqlite3_value_type(argv[0]);+ if( eType==SQLITE_NULL ) return;++ /* If not NULL, then Y must be numeric. Otherwise throw an error.+ ** Requirement 4 */+ if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){+ return;+ }++ /* Ignore the Y value if it is infinity or NaN */+ y = sqlite3_value_double(argv[0]);+ if( percentIsInfinity(y) ){+ return;+ }+ if( p->bSorted==0 ){+ assert( p->nUsed>1 );+ percentSort(p->a, p->nUsed);+ p->bSorted = 1;+ }+ p->bKeepSorted = 1;++ /* Find and remove the row */+ i = percentBinarySearch(p, y, 1);+ if( i>=0 ){+ p->nUsed--;+ if( i<(int)p->nUsed ){+ memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0]));+ }+ }+}++/*+** Compute the final output of percentile(). Clean up all allocated+** memory if and only if bIsFinal is true.+*/+static void percentCompute(sqlite3_context *pCtx, int bIsFinal){+ Percentile *p;+ int settings = SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&1; /* Discrete? */+ unsigned i1, i2;+ double v1, v2;+ double ix, vx;+ p = (Percentile*)sqlite3_aggregate_context(pCtx, 0);+ if( p==0 ) return;+ if( p->a==0 ) return;+ if( p->nUsed ){+ if( p->bSorted==0 ){+ assert( p->nUsed>1 );+ percentSort(p->a, p->nUsed);+ p->bSorted = 1;+ }+ ix = p->rPct*(p->nUsed-1);+ i1 = (unsigned)ix;+ if( settings & 1 ){+ vx = p->a[i1];+ }else{+ i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1;+ v1 = p->a[i1];+ v2 = p->a[i2];+ vx = v1 + (v2-v1)*(ix-i1);+ }+ sqlite3_result_double(pCtx, vx);+ }+ if( bIsFinal ){+ sqlite3_free(p->a);+ memset(p, 0, sizeof(*p));+ }else{+ p->bKeepSorted = 1;+ }+}+static void percentFinal(sqlite3_context *pCtx){+ percentCompute(pCtx, 1);+}+static void percentValue(sqlite3_context *pCtx){+ percentCompute(pCtx, 0);+}+/****** End of percentile family of functions ******/+#endif /* SQLITE_ENABLE_PERCENTILE */++#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+/*+** Implementation of sqlite_filestat(SCHEMA).+**+** Return JSON text that describes low-level debug/diagnostic information+** about the sqlite3_file object associated with SCHEMA.+*/+static void filestatFunc(+ sqlite3_context *context,+ int argc,+ sqlite3_value **argv+){+ sqlite3 *db = sqlite3_context_db_handle(context);+ const char *zDbName;+ sqlite3_str *pStr;+ Btree *pBtree;++ zDbName = (const char*)sqlite3_value_text(argv[0]);+ pBtree = sqlite3DbNameToBtree(db, zDbName);+ if( pBtree ){+ Pager *pPager;+ sqlite3_file *fd;+ int rc;+ sqlite3BtreeEnter(pBtree);+ pPager = sqlite3BtreePager(pBtree);+ assert( pPager!=0 );+ fd = sqlite3PagerFile(pPager);+ pStr = sqlite3_str_new(db);+ if( pStr==0 ){+ sqlite3_result_error_nomem(context);+ }else{+ sqlite3_str_append(pStr, "{\"db\":", 6);+ rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr);+ if( rc ) sqlite3_str_append(pStr, "null", 4);+ fd = sqlite3PagerJrnlFile(pPager);+ if( fd && fd->pMethods!=0 ){+ sqlite3_str_appendall(pStr, ",\"journal\":");+ rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr);+ if( rc ) sqlite3_str_append(pStr, "null", 4);+ }+ sqlite3_str_append(pStr, "}", 1);+ sqlite3_result_text(context, sqlite3_str_finish(pStr), -1,+ sqlite3_free);+ }+ sqlite3BtreeLeave(pBtree);+ }else{+ sqlite3_result_text(context, "{}", 2, SQLITE_STATIC);+ }+}+#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */+#ifdef SQLITE_DEBUG/*** Implementation of fpdecode(x,y,z) function.@@ -132187,6 +135065,9 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNCINLINE_FUNC(sqlite_offset, 1, INLINEFUNC_sqlite_offset, 0 ),+#endif+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT)+ FUNCTION(sqlite_filestat, 1, 0, 0, filestatFunc ),#endifFUNCTION(ltrim, 1, 1, 0, trimFunc ),FUNCTION(ltrim, 2, 1, 0, trimFunc ),@@ -132233,7 +135114,9 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),+ FUNCTION(unistr, 1, 0, 0, unistrFunc ),FUNCTION(quote, 1, 0, 0, quoteFunc ),+ FUNCTION(unistr_quote, 1, 1, 0, quoteFunc ),VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),VFUNCTION(changes, 0, 0, 0, changes ),VFUNCTION(total_changes, 0, 0, 0, total_changes ),@@ -132258,6 +135141,21 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){WAGGREGATE(string_agg, 2, 0, 0, groupConcatStep,groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),+#ifdef SQLITE_ENABLE_PERCENTILE+ WAGGREGATE(median, 1, 0,0, percentStep,+ percentFinal, percentValue, percentInverse,+ SQLITE_INNOCUOUS|SQLITE_SELFORDER1),+ WAGGREGATE(percentile, 2, 0x2,0, percentStep,+ percentFinal, percentValue, percentInverse,+ SQLITE_INNOCUOUS|SQLITE_SELFORDER1),+ WAGGREGATE(percentile_cont, 2, 0,0, percentStep,+ percentFinal, percentValue, percentInverse,+ SQLITE_INNOCUOUS|SQLITE_SELFORDER1),+ WAGGREGATE(percentile_disc, 2, 0x1,0, percentStep,+ percentFinal, percentValue, percentInverse,+ SQLITE_INNOCUOUS|SQLITE_SELFORDER1),+#endif /* SQLITE_ENABLE_PERCENTILE */+LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),#ifdef SQLITE_CASE_SENSITIVE_LIKELIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),@@ -134012,12 +136910,15 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){** by one slot and insert a new OP_TypeCheck where the current** OP_MakeRecord is found */VdbeOp *pPrev;+ int p3;sqlite3VdbeAppendP4(v, pTab, P4_TABLE);pPrev = sqlite3VdbeGetLastOp(v);assert( pPrev!=0 );assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );pPrev->opcode = OP_TypeCheck;- sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);+ p3 = pPrev->p3;+ pPrev->p3 = 0;+ sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, p3);}else{/* Insert an isolated OP_Typecheck */sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);@@ -134520,7 +137421,7 @@ SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprListf = (f & pLeft->selFlags);}pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0);- pLeft->selFlags &= ~SF_MultiValue;+ pLeft->selFlags &= ~(u32)SF_MultiValue;if( pSelect ){pSelect->op = TK_ALL;pSelect->pPrior = pLeft;@@ -134902,28 +137803,22 @@ SQLITE_PRIVATE void sqlite3Insert(aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int));if( aTabColMap==0 ) goto insert_cleanup;for(i=0; i<pColumn->nId; i++){- const char *zCName = pColumn->a[i].zName;- u8 hName = sqlite3StrIHash(zCName);- for(j=0; j<pTab->nCol; j++){- if( pTab->aCol[j].hName!=hName ) continue;- if( sqlite3StrICmp(zCName, pTab->aCol[j].zCnName)==0 ){- if( aTabColMap[j]==0 ) aTabColMap[j] = i+1;- if( i!=j ) bIdListInOrder = 0;- if( j==pTab->iPKey ){- ipkColumn = i; assert( !withoutRowid );- }+ j = sqlite3ColumnIndex(pTab, pColumn->a[i].zName);+ if( j>=0 ){+ if( aTabColMap[j]==0 ) aTabColMap[j] = i+1;+ if( i!=j ) bIdListInOrder = 0;+ if( j==pTab->iPKey ){+ ipkColumn = i; assert( !withoutRowid );+ }#ifndef SQLITE_OMIT_GENERATED_COLUMNS- if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){- sqlite3ErrorMsg(pParse,- "cannot INSERT into generated column \"%s\"",- pTab->aCol[j].zCnName);- goto insert_cleanup;- }-#endif- break;+ if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){+ sqlite3ErrorMsg(pParse,+ "cannot INSERT into generated column \"%s\"",+ pTab->aCol[j].zCnName);+ goto insert_cleanup;}- }- if( j>=pTab->nCol ){+#endif+ }else{if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ipkColumn = i;bIdListInOrder = 0;@@ -135221,7 +138116,7 @@ SQLITE_PRIVATE void sqlite3Insert(continue;}else if( pColumn==0 ){/* Hidden columns that are not explicitly named in the INSERT- ** get there default value */+ ** get their default value */sqlite3ExprCodeFactorable(pParse,sqlite3ColumnExpr(pTab, &pTab->aCol[i]),iRegStore);@@ -135946,7 +138841,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(** could happen in any order, but they are grouped up front for** convenience.**- ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43+ ** 2018-08-14: Ticket https://sqlite.org/src/info/908f001483982c43** The order of constraints used to have OE_Update as (2) and OE_Abort** and so forth as (1). But apparently PostgreSQL checks the OE_Update** constraint before any others, so it had to be moved.@@ -137756,6 +140651,12 @@ struct sqlite3_api_routines {/* Version 3.44.0 and later */void *(*get_clientdata)(sqlite3*,const char*);int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));+ /* Version 3.50.0 and later */+ int (*setlk_timeout)(sqlite3*,int,int);+ /* Version 3.51.0 and later */+ int (*set_errmsg)(sqlite3*,int,const char*);+ int (*db_status64)(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int);+};/*@@ -138089,6 +140990,11 @@ typedef int (*sqlite3_loadext_entry)(/* Version 3.44.0 and later */#define sqlite3_get_clientdata sqlite3_api->get_clientdata#define sqlite3_set_clientdata sqlite3_api->set_clientdata+/* Version 3.50.0 and later */+#define sqlite3_setlk_timeout sqlite3_api->setlk_timeout+/* Version 3.51.0 and later */+#define sqlite3_set_errmsg sqlite3_api->set_errmsg+#define sqlite3_db_status64 sqlite3_api->db_status64#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)@@ -138610,7 +141516,12 @@ static const sqlite3_api_routines sqlite3Apis = {sqlite3_stmt_explain,/* Version 3.44.0 and later */sqlite3_get_clientdata,- sqlite3_set_clientdata+ sqlite3_set_clientdata,+ /* Version 3.50.0 and later */+ sqlite3_setlk_timeout,+ /* Version 3.51.0 and later */+ sqlite3_set_errmsg,+ sqlite3_db_status64};/* True if x is the directory separator character@@ -139132,48 +142043,48 @@ static const char *const pragCName[] = {/* 13 */ "pk",/* 14 */ "hidden",/* table_info reuses 8 */- /* 15 */ "schema", /* Used by: table_list */- /* 16 */ "name",+ /* 15 */ "name", /* Used by: function_list */+ /* 16 */ "builtin",/* 17 */ "type",- /* 18 */ "ncol",- /* 19 */ "wr",- /* 20 */ "strict",- /* 21 */ "seqno", /* Used by: index_xinfo */- /* 22 */ "cid",- /* 23 */ "name",- /* 24 */ "desc",- /* 25 */ "coll",- /* 26 */ "key",- /* 27 */ "name", /* Used by: function_list */- /* 28 */ "builtin",- /* 29 */ "type",- /* 30 */ "enc",- /* 31 */ "narg",- /* 32 */ "flags",- /* 33 */ "tbl", /* Used by: stats */- /* 34 */ "idx",- /* 35 */ "wdth",- /* 36 */ "hght",- /* 37 */ "flgs",- /* 38 */ "seq", /* Used by: index_list */- /* 39 */ "name",- /* 40 */ "unique",- /* 41 */ "origin",- /* 42 */ "partial",+ /* 18 */ "enc",+ /* 19 */ "narg",+ /* 20 */ "flags",+ /* 21 */ "schema", /* Used by: table_list */+ /* 22 */ "name",+ /* 23 */ "type",+ /* 24 */ "ncol",+ /* 25 */ "wr",+ /* 26 */ "strict",+ /* 27 */ "seqno", /* Used by: index_xinfo */+ /* 28 */ "cid",+ /* 29 */ "name",+ /* 30 */ "desc",+ /* 31 */ "coll",+ /* 32 */ "key",+ /* 33 */ "seq", /* Used by: index_list */+ /* 34 */ "name",+ /* 35 */ "unique",+ /* 36 */ "origin",+ /* 37 */ "partial",+ /* 38 */ "tbl", /* Used by: stats */+ /* 39 */ "idx",+ /* 40 */ "wdth",+ /* 41 */ "hght",+ /* 42 */ "flgs",/* 43 */ "table", /* Used by: foreign_key_check *//* 44 */ "rowid",/* 45 */ "parent",/* 46 */ "fkid",- /* index_info reuses 21 */- /* 47 */ "seq", /* Used by: database_list */- /* 48 */ "name",- /* 49 */ "file",- /* 50 */ "busy", /* Used by: wal_checkpoint */- /* 51 */ "log",- /* 52 */ "checkpointed",- /* collation_list reuses 38 */+ /* 47 */ "busy", /* Used by: wal_checkpoint */+ /* 48 */ "log",+ /* 49 */ "checkpointed",+ /* 50 */ "seq", /* Used by: database_list */+ /* 51 */ "name",+ /* 52 */ "file",+ /* index_info reuses 27 *//* 53 */ "database", /* Used by: lock_status *//* 54 */ "status",+ /* collation_list reuses 33 *//* 55 */ "cache_size", /* Used by: default_cache_size *//* module_list pragma_list reuses 9 *//* 56 */ "timeout", /* Used by: busy_timeout */@@ -139266,7 +142177,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "collation_list",/* ePragTyp: */ PragTyp_COLLATION_LIST,/* ePragFlg: */ PragFlg_Result0,- /* ColNames: */ 38, 2,+ /* ColNames: */ 33, 2,/* iArg: */ 0 },#endif#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)@@ -139301,7 +142212,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "database_list",/* ePragTyp: */ PragTyp_DATABASE_LIST,/* ePragFlg: */ PragFlg_Result0,- /* ColNames: */ 47, 3,+ /* ColNames: */ 50, 3,/* iArg: */ 0 },#endif#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)@@ -139381,7 +142292,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "function_list",/* ePragTyp: */ PragTyp_FUNCTION_LIST,/* ePragFlg: */ PragFlg_Result0,- /* ColNames: */ 27, 6,+ /* ColNames: */ 15, 6,/* iArg: */ 0 },#endif#endif@@ -139410,17 +142321,17 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "index_info",/* ePragTyp: */ PragTyp_INDEX_INFO,/* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,- /* ColNames: */ 21, 3,+ /* ColNames: */ 27, 3,/* iArg: */ 0 },{/* zName: */ "index_list",/* ePragTyp: */ PragTyp_INDEX_LIST,/* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,- /* ColNames: */ 38, 5,+ /* ColNames: */ 33, 5,/* iArg: */ 0 },{/* zName: */ "index_xinfo",/* ePragTyp: */ PragTyp_INDEX_INFO,/* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,- /* ColNames: */ 21, 6,+ /* ColNames: */ 27, 6,/* iArg: */ 1 },#endif#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)@@ -139599,7 +142510,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "stats",/* ePragTyp: */ PragTyp_STATS,/* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,- /* ColNames: */ 33, 5,+ /* ColNames: */ 38, 5,/* iArg: */ 0 },#endif#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)@@ -139618,7 +142529,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "table_list",/* ePragTyp: */ PragTyp_TABLE_LIST,/* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1,- /* ColNames: */ 15, 6,+ /* ColNames: */ 21, 6,/* iArg: */ 0 },{/* zName: */ "table_xinfo",/* ePragTyp: */ PragTyp_TABLE_INFO,@@ -139695,7 +142606,7 @@ static const PragmaName aPragmaName[] = {{/* zName: */ "wal_checkpoint",/* ePragTyp: */ PragTyp_WAL_CHECKPOINT,/* ePragFlg: */ PragFlg_NeedSchema,- /* ColNames: */ 50, 3,+ /* ColNames: */ 47, 3,/* iArg: */ 0 },#endif#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)@@ -139717,7 +142628,7 @@ static const PragmaName aPragmaName[] = {** the following macro or to the actual analysis_limit if it is non-zero,** in order to prevent PRAGMA optimize from running for too long.**-** The value of 2000 is chosen emperically so that the worst-case run-time+** The value of 2000 is chosen empirically so that the worst-case run-time** for PRAGMA optimize does not exceed 100 milliseconds against a variety** of test databases on a RaspberryPI-4 compiled using -Os and without** -DSQLITE_DEBUG. Of course, your mileage may vary. For the purpose of@@ -140072,6 +142983,22 @@ static int integrityCheckResultRow(Vdbe *v){return addr;}+/*+** Should table pTab be skipped when doing an integrity_check?+** Return true or false.+**+** If pObjTab is not null, the return true if pTab matches pObjTab.+**+** If pObjTab is null, then return true only if pTab is an imposter table.+*/+static int tableSkipIntegrityCheck(const Table *pTab, const Table *pObjTab){+ if( pObjTab ){+ return pTab!=pObjTab;+ }else{+ return (pTab->tabFlags & TF_Imposter)!=0;+ }+}+/*** Process a pragma statement.**@@ -140834,7 +143761,10 @@ SQLITE_PRIVATE void sqlite3Pragma(}}else{db->flags &= ~mask;- if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;+ if( mask==SQLITE_DeferFKs ){+ db->nDeferredImmCons = 0;+ db->nDeferredCons = 0;+ }if( (mask & SQLITE_WriteSchema)!=0&& sqlite3_stricmp(zRight, "reset")==0){@@ -141414,7 +144344,7 @@ SQLITE_PRIVATE void sqlite3Pragma(Table *pTab = sqliteHashData(x); /* Current table */Index *pIdx; /* An index on pTab */int nIdx; /* Number of indexes on pTab */- if( pObjTab && pObjTab!=pTab ) continue;+ if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;if( HasRowid(pTab) ) cnt++;for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }}@@ -141427,7 +144357,7 @@ SQLITE_PRIVATE void sqlite3Pragma(for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){Table *pTab = sqliteHashData(x);Index *pIdx;- if( pObjTab && pObjTab!=pTab ) continue;+ if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){aRoot[++cnt] = pIdx->tnum;@@ -141458,7 +144388,7 @@ SQLITE_PRIVATE void sqlite3Pragma(int iTab = 0;Table *pTab = sqliteHashData(x);Index *pIdx;- if( pObjTab && pObjTab!=pTab ) continue;+ if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;if( HasRowid(pTab) ){iTab = cnt++;}else{@@ -141494,7 +144424,7 @@ SQLITE_PRIVATE void sqlite3Pragma(int r2; /* Previous key for WITHOUT ROWID tables */int mxCol; /* Maximum non-virtual column number */- if( pObjTab && pObjTab!=pTab ) continue;+ if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;if( !IsOrdinaryTable(pTab) ) continue;if( isQuick || HasRowid(pTab) ){pPk = 0;@@ -141818,7 +144748,7 @@ SQLITE_PRIVATE void sqlite3Pragma(Table *pTab = sqliteHashData(x);sqlite3_vtab *pVTab;int a1;- if( pObjTab && pObjTab!=pTab ) continue;+ if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue;if( IsOrdinaryTable(pTab) ) continue;if( !IsVirtual(pTab) ) continue;if( pTab->nCol<=0 ){@@ -142050,6 +144980,8 @@ SQLITE_PRIVATE void sqlite3Pragma(eMode = SQLITE_CHECKPOINT_RESTART;}else if( sqlite3StrICmp(zRight, "truncate")==0 ){eMode = SQLITE_CHECKPOINT_TRUNCATE;+ }else if( sqlite3StrICmp(zRight, "noop")==0 ){+ eMode = SQLITE_CHECKPOINT_NOOP;}}pParse->nMem = 3;@@ -143616,9 +146548,11 @@ static int sqlite3LockAndPrepare(rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);assert( rc==SQLITE_OK || *ppStmt==0 );if( rc==SQLITE_OK || db->mallocFailed ) break;- }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY)- || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );+ cnt++;+ }while( (rc==SQLITE_ERROR_RETRY && ALWAYS(cnt<=SQLITE_MAX_PREPARE_RETRY))+ || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt)==1) );sqlite3BtreeLeaveAll(db);+ assert( rc!=SQLITE_ERROR_RETRY );rc = sqlite3ApiExit(db, rc);assert( (rc&db->errMask)==rc );db->busyHandler.nBusy = 0;@@ -144003,7 +146937,7 @@ SQLITE_PRIVATE Select *sqlite3SelectNew(pNew->addrOpenEphm[0] = -1;pNew->addrOpenEphm[1] = -1;pNew->nSelectRow = 0;- if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));+ if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);pNew->pSrc = pSrc;pNew->pWhere = pWhere;pNew->pGroupBy = pGroupBy;@@ -144168,10 +147102,33 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p*/SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol){int i;- u8 h = sqlite3StrIHash(zCol);- Column *pCol;- for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){- if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;+ u8 h;+ const Column *aCol;+ int nCol;++ h = sqlite3StrIHash(zCol);+ aCol = pTab->aCol;+ nCol = pTab->nCol;++ /* See if the aHx gives us a lucky match */+ i = pTab->aHx[h % sizeof(pTab->aHx)];+ assert( i<nCol );+ if( aCol[i].hName==h+ && sqlite3StrICmp(aCol[i].zCnName, zCol)==0+ ){+ return i;+ }++ /* No lucky match from the hash table. Do a full search. */+ i = 0;+ while( 1 /*exit-by-break*/ ){+ if( aCol[i].hName==h+ && sqlite3StrICmp(aCol[i].zCnName, zCol)==0+ ){+ return i;+ }+ i++;+ if( i>=nCol ) break;}return -1;}@@ -144210,7 +147167,7 @@ static int tableAndColumnIndex(int iEnd, /* Last member of pSrc->a[] to check */const char *zCol, /* Name of the column we are looking for */int *piTab, /* Write index of pSrc->a[] here */- int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */+ int *piCol, /* Write index of pSrc->a[*piTab].pSTab->aCol[] here */int bIgnoreHidden /* Ignore hidden columns */){int i; /* For looping over tables in pSrc */@@ -144269,8 +147226,7 @@ SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );ExprSetVVAProperty(p, EP_NoReduce);p->w.iJoin = iTable;- if( p->op==TK_FUNCTION ){- assert( ExprUseXList(p) );+ if( ExprUseXList(p) ){if( p->x.pList ){int i;for(i=0; i<p->x.pList->nExpr; i++){@@ -144422,7 +147378,7 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){}pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);- if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){+ if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 && pParse->nErr==0 ){/* This branch runs if the query contains one or more RIGHT or FULL** JOINs. If only a single table on the left side of this join** contains the zName column, then this branch is a no-op.@@ -144438,6 +147394,8 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){*/ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */static const Token tkCoalesce = { "coalesce", 8 };+ assert( pE1!=0 );+ ExprSetProperty(pE1, EP_CanBeNull);while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,pRight->fg.isSynthUsing)!=0 ){if( pSrc->a[iLeft].fg.isUsing==0@@ -144454,7 +147412,13 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){if( pFuncArgs ){pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);+ if( pE1 ){+ pE1->affExpr = SQLITE_AFF_DEFER;+ }}+ }else if( (pSrc->a[i+1].fg.jointype & JT_LEFT)!=0 && pParse->nErr==0 ){+ assert( pE1!=0 );+ ExprSetProperty(pE1, EP_CanBeNull);}pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);sqlite3SrcItemColumnUsed(pRight, iRightCol);@@ -144478,6 +147442,7 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);pRight->u3.pOn = 0;pRight->fg.isOn = 1;+ p->selFlags |= SF_OnToWhere;}}return 0;@@ -145263,9 +148228,14 @@ static void selectInnerLoop(assert( nResultCol<=pDest->nSdst );pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);+ pDest->iSDParm = regResult;}else{assert( nResultCol==pDest->nSdst );- assert( regResult==iParm );+ if( regResult!=iParm ){+ /* This occurs in cases where the SELECT had both a DISTINCT and+ ** an OFFSET clause. */+ sqlite3VdbeAddOp3(v, OP_Copy, regResult, iParm, nResultCol-1);+ }/* The LIMIT clause will jump out of the loop for us */}break;@@ -145363,8 +148333,11 @@ static void selectInnerLoop(** X extra columns.*/SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){- int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);- KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);+ int nExtra = (N+X)*(sizeof(CollSeq*)+1);+ KeyInfo *p;+ assert( X>=0 );+ if( NEVER(N+X>0xffff) ) return (KeyInfo*)sqlite3OomFault(db);+ p = sqlite3DbMallocRawNN(db, SZ_KEYINFO(0) + nExtra);if( p ){p->aSortFlags = (u8*)&p->aColl[N+X];p->nKeyField = (u16)N;@@ -145372,7 +148345,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){p->enc = ENC(db);p->db = db;p->nRef = 1;- memset(&p[1], 0, nExtra);+ memset(p->aColl, 0, nExtra);}else{return (KeyInfo*)sqlite3OomFault(db);}@@ -145931,6 +148904,10 @@ static void generateColumnTypes(#endifsqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);}+#else+ UNUSED_PARAMETER(pParse);+ UNUSED_PARAMETER(pTabList);+ UNUSED_PARAMETER(pEList);#endif /* !defined(SQLITE_OMIT_DECLTYPE) */}@@ -146850,8 +149827,10 @@ static int multiSelect(int priorOp; /* The SRT_ operation to apply to prior selects */Expr *pLimit; /* Saved values of p->nLimit */int addr;+ int emptyBypass = 0; /* IfEmpty opcode to bypass RHS */SelectDest uniondest;+testcase( p->op==TK_EXCEPT );testcase( p->op==TK_UNION );priorOp = SRT_Union;@@ -146889,6 +149868,8 @@ static int multiSelect(*/if( p->op==TK_EXCEPT ){op = SRT_Except;+ emptyBypass = sqlite3VdbeAddOp1(v, OP_IfEmpty, unionTab);+ VdbeCoverage(v);}else{assert( p->op==TK_UNION );op = SRT_Union;@@ -146909,6 +149890,7 @@ static int multiSelect(if( p->op==TK_UNION ){p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);}+ if( emptyBypass ) sqlite3VdbeJumpHere(v, emptyBypass);sqlite3ExprDelete(db, p->pLimit);p->pLimit = pLimit;p->iLimit = 0;@@ -146939,9 +149921,10 @@ static int multiSelect(int tab1, tab2;int iCont, iBreak, iStart;Expr *pLimit;- int addr;+ int addr, iLimit, iOffset;SelectDest intersectdest;int r1;+ int emptyBypass;/* INTERSECT is different from the others since it requires** two temporary tables. Hence it has its own case. Begin@@ -146966,14 +149949,28 @@ static int multiSelect(goto multi_select_end;}+ /* Initialize LIMIT counters before checking to see if the LHS+ ** is empty, in case the jump is taken */+ iBreak = sqlite3VdbeMakeLabel(pParse);+ computeLimitRegisters(pParse, p, iBreak);+ emptyBypass = sqlite3VdbeAddOp1(v, OP_IfEmpty, tab1); VdbeCoverage(v);+/* Code the current SELECT into temporary table "tab2"*/addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);assert( p->addrOpenEphm[1] == -1 );p->addrOpenEphm[1] = addr;- p->pPrior = 0;++ /* Disable prior SELECTs and the LIMIT counters during the computation+ ** of the RHS select */pLimit = p->pLimit;+ iLimit = p->iLimit;+ iOffset = p->iOffset;+ p->pPrior = 0;p->pLimit = 0;+ p->iLimit = 0;+ p->iOffset = 0;+intersectdest.iSDParm = tab2;ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",sqlite3SelectOpName(p->op)));@@ -146986,19 +149983,21 @@ static int multiSelect(p->nSelectRow = pPrior->nSelectRow;}sqlite3ExprDelete(db, p->pLimit);++ /* Reinstate the LIMIT counters prior to running the final intersect */p->pLimit = pLimit;+ p->iLimit = iLimit;+ p->iOffset = iOffset;/* Generate code to take the intersection of the two temporary** tables.*/if( rc ) break;assert( p->pEList );- iBreak = sqlite3VdbeMakeLabel(pParse);- iCont = sqlite3VdbeMakeLabel(pParse);- computeLimitRegisters(pParse, p, iBreak);- sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);+ sqlite3VdbeAddOp1(v, OP_Rewind, tab1);r1 = sqlite3GetTempReg(pParse);iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);+ iCont = sqlite3VdbeMakeLabel(pParse);sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);VdbeCoverage(v);sqlite3ReleaseTempReg(pParse, r1);@@ -147008,6 +150007,7 @@ static int multiSelect(sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);sqlite3VdbeResolveLabel(v, iBreak);sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);+ sqlite3VdbeJumpHere(v, emptyBypass);sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);break;}@@ -147073,6 +150073,7 @@ static int multiSelect(multi_select_end:pDest->iSdst = dest.iSdst;pDest->nSdst = dest.nSdst;+ pDest->iSDParm2 = dest.iSDParm2;if( pDelete ){sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete);}@@ -147655,7 +150656,7 @@ static int multiSelectOrderBy(** ## About "isOuterJoin":**** The isOuterJoin column indicates that the replacement will occur into a-** position in the parent that NULL-able due to an OUTER JOIN. Either the+** position in the parent that is NULL-able due to an OUTER JOIN. Either the** target slot in the parent is the right operand of a LEFT JOIN, or one of** the left operands of a RIGHT JOIN. In either case, we need to potentially** bypass the substituted expression with OP_IfNullRow.@@ -147685,6 +150686,7 @@ typedef struct SubstContext {int iTable; /* Replace references to this table */int iNewTable; /* New table number */int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */+ int nSelDepth; /* Depth of sub-query recursion. Top==1 */ExprList *pEList; /* Replacement expressions */ExprList *pCList; /* Collation sequences for replacement expr */} SubstContext;@@ -147792,6 +150794,9 @@ static Expr *substExpr(if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){pExpr->iTable = pSubst->iNewTable;}+ if( pExpr->op==TK_AGG_FUNCTION && pExpr->op2>=pSubst->nSelDepth ){+ pExpr->op2--;+ }pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);pExpr->pRight = substExpr(pSubst, pExpr->pRight);if( ExprUseXSelect(pExpr) ){@@ -147829,6 +150834,7 @@ static void substSelect(SrcItem *pItem;int i;if( !p ) return;+ pSubst->nSelDepth++;do{substExprList(pSubst, p->pEList);substExprList(pSubst, p->pGroupBy);@@ -147846,6 +150852,7 @@ static void substSelect(}}}while( doPrior && (p = p->pPrior)!=0 );+ pSubst->nSelDepth--;}#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */@@ -148061,9 +151068,9 @@ static int compoundHasDifferentAffinities(Select *p){** from 2015-02-09.)**** (3) If the subquery is the right operand of a LEFT JOIN then-** (3a) the subquery may not be a join and-** (3b) the FROM clause of the subquery may not contain a virtual-** table and+** (3a) the subquery may not be a join+** (**) Was (3b): "the FROM clause of the subquery may not contain+** a virtual table"** (**) Was: "The outer query may not have a GROUP BY." This case** is now managed correctly** (3d) the outer query may not be DISTINCT.@@ -148279,7 +151286,7 @@ static int flattenSubquery(*/if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){if( pSubSrc->nSrc>1 /* (3a) */- || IsVirtual(pSubSrc->a[0].pSTab) /* (3b) */+ /**** || IsVirtual(pSubSrc->a[0].pSTab) (3b)-omitted */|| (p->selFlags & SF_Distinct)!=0 /* (3d) */|| (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */){@@ -148457,7 +151464,7 @@ static int flattenSubquery(** complete, since there may still exist Expr.pTab entries that** refer to the subquery even after flattening. Ticket #3346.**- ** pSubitem->pTab is always non-NULL by test restrictions and tests above.+ ** pSubitem->pSTab is always non-NULL by test restrictions and tests above.*/if( ALWAYS(pSubitem->pSTab!=0) ){Table *pTabToDel = pSubitem->pSTab;@@ -148487,17 +151494,12 @@ static int flattenSubquery(pSub = pSub1;for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){int nSubSrc;- u8 jointype = 0;- u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;+ u8 jointype = pSubitem->fg.jointype;assert( pSub!=0 );pSubSrc = pSub->pSrc; /* FROM clause of subquery */nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */pSrc = pParent->pSrc; /* FROM clause of the outer query */- if( pParent==p ){- jointype = pSubitem->fg.jointype; /* First time through the loop */- }-/* The subquery uses a single slot of the FROM clause of the outer** query. If the subquery has more than one element in its FROM clause,** then expand the outer query to make space for it to hold all elements@@ -148517,6 +151519,7 @@ static int flattenSubquery(pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);if( pSrc==0 ) break;pParent->pSrc = pSrc;+ pSubitem = &pSrc->a[iFrom];}/* Transfer the FROM clause terms from the subquery into the@@ -148531,11 +151534,10 @@ static int flattenSubquery(|| pItem->u4.zDatabase==0 );if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);*pItem = pSubSrc->a[i];- pItem->fg.jointype |= ltorj;+ pItem->fg.jointype |= (jointype & JT_LTORJ);memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));}- pSrc->a[iFrom].fg.jointype &= JT_LTORJ;- pSrc->a[iFrom].fg.jointype |= jointype | ltorj;+ pSubitem->fg.jointype |= jointype;/* Now begin substituting subquery result set expressions for** references to the iParent in the outer query.@@ -148587,6 +151589,7 @@ static int flattenSubquery(x.iTable = iParent;x.iNewTable = iNewParent;x.isOuterJoin = isOuterJoin;+ x.nSelDepth = 0;x.pEList = pSub->pEList;x.pCList = findLeftmostExprlist(pSub);substSelect(&x, pParent, 0);@@ -148683,7 +151686,8 @@ static void constInsert(return; /* Already present. Return without doing anything. */}}- if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){+ assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );+ if( sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){pConst->bHasAffBlob = 1;}@@ -148758,7 +151762,8 @@ static int propagateConstantExprRewriteOne(if( pColumn==pExpr ) continue;if( pColumn->iTable!=pExpr->iTable ) continue;if( pColumn->iColumn!=pExpr->iColumn ) continue;- if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){+ assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );+ if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){break;}/* A match is found. Add the EP_FixedCol property */@@ -149170,6 +152175,7 @@ static int pushDownWhereTerms(x.iTable = pSrc->iCursor;x.iNewTable = pSrc->iCursor;x.isOuterJoin = 0;+ x.nSelDepth = 0;x.pEList = pSubq->pEList;x.pCList = findLeftmostExprlist(pSubq);pNew = substExpr(&x, pNew);@@ -149411,7 +152417,7 @@ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){** above that generates the code for a compound SELECT with an ORDER BY clause** uses a merge algorithm that requires the same collating sequence on the** result columns as on the ORDER BY clause. See ticket-** http://www.sqlite.org/src/info/6709574d2a+** http://sqlite.org/src/info/6709574d2a**** This transformation is only needed for EXCEPT, INTERSECT, and UNION.** The UNION ALL operator works fine with multiSelectOrderBy() even when@@ -149472,7 +152478,7 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){#ifndef SQLITE_OMIT_WINDOWFUNCp->pWinDefn = 0;#endif- p->selFlags &= ~SF_Compound;+ p->selFlags &= ~(u32)SF_Compound;assert( (p->selFlags & SF_Converted)==0 );p->selFlags |= SF_Converted;assert( pNew->pPrior!=0 );@@ -149567,7 +152573,7 @@ SQLITE_PRIVATE With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){** CTE expression, through routine checks to see if the reference is** a recursive reference to the CTE.**-** If pFrom matches a CTE according to either of these two above, pFrom->pTab+** If pFrom matches a CTE according to either of these two above, pFrom->pSTab** and other fields are populated accordingly.**** Return 0 if no match is found.@@ -149888,7 +152894,7 @@ static int selectExpander(Walker *pWalker, Select *p){pEList = p->pEList;if( pParse->pWith && (p->selFlags & SF_View) ){if( p->pWith==0 ){- p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));+ p->pWith = (With*)sqlite3DbMallocZero(db, SZ_WITH(1) );if( p->pWith==0 ){return WRC_Abort;}@@ -150605,6 +153611,7 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){if( pFunc->bOBPayload ){/* extra columns for the function arguments */assert( ExprUseXList(pFunc->pFExpr) );+ assert( pFunc->pFExpr->x.pList!=0 );nExtra += pFunc->pFExpr->x.pList->nExpr;}if( pFunc->bUseSubtype ){@@ -151027,6 +154034,7 @@ static void agginfoFree(sqlite3 *db, void *pArg){** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries** * The outer query is a simple count(*) with no WHERE clause or other** extraneous syntax.+** * None of the subqueries are DISTINCT (forumpost/a860f5fb2e 2025-03-10)**** Return TRUE if the optimization is undertaken.*/@@ -151059,7 +154067,11 @@ static int countOfViewOptimization(Parse *pParse, Select *p){if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */if( pSub->pWhere ) return 0; /* No WHERE clause */if( pSub->pLimit ) return 0; /* No LIMIT clause */- if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */+ if( pSub->selFlags & (SF_Aggregate|SF_Distinct) ){+ testcase( pSub->selFlags & SF_Aggregate );+ testcase( pSub->selFlags & SF_Distinct );+ return 0; /* Not an aggregate nor DISTINCT */+ }assert( pSub->pHaving==0 ); /* Due to the previous */pSub = pSub->pPrior; /* Repeat over compound */}while( pSub );@@ -151071,14 +154083,14 @@ static int countOfViewOptimization(Parse *pParse, Select *p){pExpr = 0;pSub = sqlite3SubqueryDetach(db, pFrom);sqlite3SrcListDelete(db, p->pSrc);- p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));+ p->pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);while( pSub ){Expr *pTerm;pPrior = pSub->pPrior;pSub->pPrior = 0;pSub->pNext = 0;pSub->selFlags |= SF_Aggregate;- pSub->selFlags &= ~SF_Compound;+ pSub->selFlags &= ~(u32)SF_Compound;pSub->nSelectRow = 0;sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;@@ -151093,7 +154105,7 @@ static int countOfViewOptimization(Parse *pParse, Select *p){pSub = pPrior;}p->pEList->a[0].pExpr = pExpr;- p->selFlags &= ~SF_Aggregate;+ p->selFlags &= ~(u32)SF_Aggregate;#if TREETRACE_ENABLEDif( sqlite3TreeTrace & 0x200 ){@@ -151189,6 +154201,205 @@ static int fromClauseTermCanBeCoroutine(return 1;}+/*+** Argument pWhere is the WHERE clause belonging to SELECT statement p. This+** function attempts to transform expressions of the form:+**+** EXISTS (SELECT ...)+**+** into joins. For example, given+**+** CREATE TABLE sailors(sid INTEGER PRIMARY KEY, name TEXT);+** CREATE TABLE reserves(sid INT, day DATE, PRIMARY KEY(sid, day));+**+** SELECT name FROM sailors AS S WHERE EXISTS (+** SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25'+** );+**+** the SELECT statement may be transformed as follows:+**+** SELECT name FROM sailors AS S, reserves AS R+** WHERE S.sid = R.sid AND R.day = '2022-10-25';+**+** **Approximately**. Really, we have to ensure that the FROM-clause term+** that was formerly inside the EXISTS is only executed once. This is handled+** by setting the SrcItem.fg.fromExists flag, which then causes code in+** the where.c file to exit the corresponding loop after the first successful+** match (if any).+*/+static SQLITE_NOINLINE void existsToJoin(+ Parse *pParse, /* Parsing context */+ Select *p, /* The SELECT statement being optimized */+ Expr *pWhere /* part of the WHERE clause currently being examined */+){+ if( pParse->nErr==0+ && pWhere!=0+ && !ExprHasProperty(pWhere, EP_OuterON|EP_InnerON)+ && ALWAYS(p->pSrc!=0)+ && p->pSrc->nSrc<BMS+ ){+ if( pWhere->op==TK_AND ){+ Expr *pRight = pWhere->pRight;+ existsToJoin(pParse, p, pWhere->pLeft);+ existsToJoin(pParse, p, pRight);+ }+ else if( pWhere->op==TK_EXISTS ){+ Select *pSub = pWhere->x.pSelect;+ Expr *pSubWhere = pSub->pWhere;+ if( pSub->pSrc->nSrc==1+ && (pSub->selFlags & SF_Aggregate)==0+ && !pSub->pSrc->a[0].fg.isSubquery+ && pSub->pLimit==0+ && pSub->pPrior==0+ ){+ /* Before combining the sub-select with the parent, renumber the+ ** cursor used by the subselect. This is because the EXISTS expression+ ** might be a copy of another EXISTS expression from somewhere+ ** else in the tree, and in this case it is important that it use+ ** a unique cursor number. */+ sqlite3 *db = pParse->db;+ int *aCsrMap = sqlite3DbMallocZero(db, (pParse->nTab+2)*sizeof(int));+ if( aCsrMap==0 ) return;+ aCsrMap[0] = (pParse->nTab+1);+ renumberCursors(pParse, pSub, -1, aCsrMap);+ sqlite3DbFree(db, aCsrMap);++ memset(pWhere, 0, sizeof(*pWhere));+ pWhere->op = TK_INTEGER;+ pWhere->u.iValue = 1;+ ExprSetProperty(pWhere, EP_IntValue);+ assert( p->pWhere!=0 );+ pSub->pSrc->a[0].fg.fromExists = 1;+ pSub->pSrc->a[0].fg.jointype |= JT_CROSS;+ p->pSrc = sqlite3SrcListAppendList(pParse, p->pSrc, pSub->pSrc);+ if( pSubWhere ){+ p->pWhere = sqlite3PExpr(pParse, TK_AND, p->pWhere, pSubWhere);+ pSub->pWhere = 0;+ }+ pSub->pSrc = 0;+ sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSub);+#if TREETRACE_ENABLED+ if( sqlite3TreeTrace & 0x100000 ){+ TREETRACE(0x100000,pParse,p,+ ("After EXISTS-to-JOIN optimization:\n"));+ sqlite3TreeViewSelect(0, p, 0);+ }+#endif+ existsToJoin(pParse, p, pSubWhere);+ }+ }+ }+}++/*+** Type used for Walker callbacks by selectCheckOnClauses().+*/+typedef struct CheckOnCtx CheckOnCtx;+struct CheckOnCtx {+ SrcList *pSrc; /* SrcList for this context */+ int iJoin; /* Cursor numbers must be =< than this */+ CheckOnCtx *pParent; /* Parent context */+};++/*+** True if the SrcList passed as the only argument contains at least+** one RIGHT or FULL JOIN. False otherwise.+*/+#define hasRightJoin(pSrc) (((pSrc)->a[0].fg.jointype & JT_LTORJ)!=0)++/*+** The xExpr callback for the search of invalid ON clause terms.+*/+static int selectCheckOnClausesExpr(Walker *pWalker, Expr *pExpr){+ CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx;++ /* Check if pExpr is root or near-root of an ON clause constraint that needs+ ** to be checked to ensure that it does not refer to tables in its FROM+ ** clause to the right of itself. i.e. it is either:+ **+ ** + an ON clause on an OUTER join, or+ ** + an ON clause on an INNER join within a FROM that features at+ ** least one RIGHT or FULL join.+ */+ if( (ExprHasProperty(pExpr, EP_OuterON))+ || (ExprHasProperty(pExpr, EP_InnerON) && hasRightJoin(pCtx->pSrc))+ ){+ /* If CheckOnCtx.iJoin is already set, then fall through and process+ ** this expression node as normal. Or, if CheckOnCtx.iJoin is still 0,+ ** set it to the cursor number of the RHS of the join to which this+ ** ON expression was attached and then iterate through the entire+ ** expression. */+ assert( pCtx->iJoin==0 || pCtx->iJoin==pExpr->w.iJoin );+ if( pCtx->iJoin==0 ){+ pCtx->iJoin = pExpr->w.iJoin;+ sqlite3WalkExprNN(pWalker, pExpr);+ pCtx->iJoin = 0;+ return WRC_Prune;+ }+ }++ if( pExpr->op==TK_COLUMN ){+ /* A column expression. Find the SrcList (if any) to which it refers.+ ** Then, if CheckOnCtx.iJoin indicates that this expression is part of an+ ** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it+ ** does not refer to a table to the right of CheckOnCtx.iJoin. */+ do {+ SrcList *pSrc = pCtx->pSrc;+ int iTab = pExpr->iTable;+ if( iTab>=pSrc->a[0].iCursor && iTab<=pSrc->a[pSrc->nSrc-1].iCursor ){+ if( pCtx->iJoin && iTab>pCtx->iJoin ){+ sqlite3ErrorMsg(pWalker->pParse,+ "ON clause references tables to its right");+ return WRC_Abort;+ }+ break;+ }+ pCtx = pCtx->pParent;+ }while( pCtx );+ }+ return WRC_Continue;+}++/*+** The xSelect callback for the search of invalid ON clause terms.+*/+static int selectCheckOnClausesSelect(Walker *pWalker, Select *pSelect){+ CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx;+ if( pSelect->pSrc==pCtx->pSrc || pSelect->pSrc->nSrc==0 ){+ return WRC_Continue;+ }else{+ CheckOnCtx sCtx;+ memset(&sCtx, 0, sizeof(sCtx));+ sCtx.pSrc = pSelect->pSrc;+ sCtx.pParent = pCtx;+ pWalker->u.pCheckOnCtx = &sCtx;+ sqlite3WalkSelect(pWalker, pSelect);+ pWalker->u.pCheckOnCtx = pCtx;+ pSelect->selFlags &= ~SF_OnToWhere;+ return WRC_Prune;+ }+}++/*+** Check all ON clauses in pSelect to verify that they do not reference+** columns to the right.+*/+SQLITE_PRIVATE void sqlite3SelectCheckOnClauses(Parse *pParse, Select *pSelect){+ Walker w;+ CheckOnCtx sCtx;+ assert( pSelect->selFlags & SF_OnToWhere );+ assert( pSelect->pSrc!=0 && pSelect->pSrc->nSrc>=2 );+ memset(&w, 0, sizeof(w));+ w.pParse = pParse;+ w.xExprCallback = selectCheckOnClausesExpr;+ w.xSelectCallback = selectCheckOnClausesSelect;+ w.u.pCheckOnCtx = &sCtx;+ memset(&sCtx, 0, sizeof(sCtx));+ sCtx.pSrc = pSelect->pSrc;+ sqlite3WalkExprNN(&w, pSelect->pWhere);+ pSelect->selFlags &= ~SF_OnToWhere;+}+/*** Generate byte-code for the SELECT statement given in the p argument.**@@ -151300,7 +154511,7 @@ SQLITE_PRIVATE int sqlite3Select(testcase( pParse->earlyCleanup );p->pOrderBy = 0;}- p->selFlags &= ~SF_Distinct;+ p->selFlags &= ~(u32)SF_Distinct;p->selFlags |= SF_NoopOrderBy;}sqlite3SelectPrep(pParse, p, 0);@@ -151339,7 +154550,7 @@ SQLITE_PRIVATE int sqlite3Select(** and leaving this flag set can cause errors if a compound sub-query** in p->pSrc is flattened into this query and this function called** again as part of compound SELECT processing. */- p->selFlags &= ~SF_UFSrcCheck;+ p->selFlags &= ~(u32)SF_UFSrcCheck;}if( pDest->eDest==SRT_Output ){@@ -151557,6 +154768,13 @@ SQLITE_PRIVATE int sqlite3Select(}#endif+ /* If there may be an "EXISTS (SELECT ...)" in the WHERE clause, attempt+ ** to change it into a join. */+ if( pParse->bHasExists && OptimizationEnabled(db,SQLITE_ExistsToJoin) ){+ existsToJoin(pParse, p, p->pWhere);+ pTabList = p->pSrc;+ }+/* Do the WHERE-clause constant propagation optimization if this is** a join. No need to spend time on this operation for non-join queries** as the equivalent optimization will be handled by query planner in@@ -151828,7 +155046,7 @@ SQLITE_PRIVATE int sqlite3Select(&& p->pWin==0#endif){- p->selFlags &= ~SF_Distinct;+ p->selFlags &= ~(u32)SF_Distinct;pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);if( pGroupBy ){for(i=0; i<pGroupBy->nExpr; i++){@@ -151937,6 +155155,12 @@ SQLITE_PRIVATE int sqlite3Select(if( pWInfo==0 ) goto select_end;if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);+ if( pDest->eDest<=SRT_DistQueue && pDest->eDest>=SRT_DistFifo ){+ /* TUNING: For a UNION CTE, because UNION is implies DISTINCT,+ ** reduce the estimated output row count by 8 (LogEst 30).+ ** Search for tag-20250414a to see other cases */+ p->nSelectRow -= 30;+ }}if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);@@ -152167,6 +155391,7 @@ SQLITE_PRIVATE int sqlite3Select(sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);VdbeComment((v, "clear abort flag"));sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);+ sqlite3ExprNullRegisterRange(pParse, iAMem, pGroupBy->nExpr);/* Begin a loop that will extract all source rows in GROUP BY order.** This might involve two separate loops with an OP_Sort in between, or@@ -152310,6 +155535,10 @@ SQLITE_PRIVATE int sqlite3Select(if( iOrderByCol ){Expr *pX = p->pEList->a[iOrderByCol-1].pExpr;Expr *pBase = sqlite3ExprSkipCollateAndLikely(pX);+ while( ALWAYS(pBase!=0) && pBase->op==TK_IF_NULL_ROW ){+ pX = pBase->pLeft;+ pBase = sqlite3ExprSkipCollateAndLikely(pX);+ }if( ALWAYS(pBase!=0)&& pBase->op!=TK_AGG_COLUMN&& pBase->op!=TK_REGISTER@@ -152333,12 +155562,12 @@ SQLITE_PRIVATE int sqlite3Select(** for the next GROUP BY batch.*/sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);- VdbeComment((v, "output one row"));+ VdbeComment((v, "output one row of %d", p->selId));sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);VdbeComment((v, "check abort flag"));sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);- VdbeComment((v, "reset accumulator"));+ VdbeComment((v, "reset accumulator %d", p->selId));/* Update the aggregate accumulators based on the content of** the current row@@ -152346,7 +155575,7 @@ SQLITE_PRIVATE int sqlite3Select(sqlite3VdbeJumpHere(v, addr1);updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);- VdbeComment((v, "indicate data in accumulator"));+ VdbeComment((v, "indicate data in accumulator %d", p->selId));/* End of the loop*/@@ -152363,7 +155592,7 @@ SQLITE_PRIVATE int sqlite3Select(/* Output the final row of result*/sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);- VdbeComment((v, "output final row"));+ VdbeComment((v, "output final row of %d", p->selId));/* Jump over the subroutines*/@@ -152384,7 +155613,7 @@ SQLITE_PRIVATE int sqlite3Select(addrOutputRow = sqlite3VdbeCurrentAddr(v);sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);VdbeCoverage(v);- VdbeComment((v, "Groupby result generator entry point"));+ VdbeComment((v, "Groupby result generator entry point %d", p->selId));sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);finalizeAggFunctions(pParse, pAggInfo);sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);@@ -152392,14 +155621,14 @@ SQLITE_PRIVATE int sqlite3Select(&sDistinct, pDest,addrOutputRow+1, addrSetAbort);sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);- VdbeComment((v, "end groupby result generator"));+ VdbeComment((v, "end groupby result generator %d", p->selId));/* Generate a subroutine that will reset the group-by accumulator*/sqlite3VdbeResolveLabel(v, addrReset);resetAccumulator(pParse, pAggInfo);sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);- VdbeComment((v, "indicate accumulator empty"));+ VdbeComment((v, "indicate accumulator %d empty", p->selId));sqlite3VdbeAddOp1(v, OP_Return, regReset);if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){@@ -152893,7 +156122,8 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){assert( pParse->db->pVtabCtx==0 );#endifassert( pParse->bReturning );- assert( &(pParse->u1.pReturning->retTrig) == pTrig );+ assert( !pParse->isCreate );+ assert( &(pParse->u1.d.pReturning->retTrig) == pTrig );pTrig->table = pTab->zName;pTrig->pTabSchema = pTab->pSchema;pTrig->pNext = pList;@@ -153861,7 +157091,11 @@ static void codeReturningTrigger(ExprList *pNew;Returning *pReturning;Select sSelect;- SrcList sFrom;+ SrcList *pFrom;+ union {+ SrcList sSrc;+ u8 fromSpace[SZ_SRCLIST_1];+ } uSrc;assert( v!=0 );if( !pParse->bReturning ){@@ -153870,19 +157104,21 @@ static void codeReturningTrigger(return;}assert( db->pParse==pParse );- pReturning = pParse->u1.pReturning;+ assert( !pParse->isCreate );+ pReturning = pParse->u1.d.pReturning;if( pTrigger != &(pReturning->retTrig) ){/* This RETURNING trigger is for a different statement */return;}memset(&sSelect, 0, sizeof(sSelect));- memset(&sFrom, 0, sizeof(sFrom));+ memset(&uSrc, 0, sizeof(uSrc));+ pFrom = &uSrc.sSrc;sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);- sSelect.pSrc = &sFrom;- sFrom.nSrc = 1;- sFrom.a[0].pSTab = pTab;- sFrom.a[0].zName = pTab->zName; /* tag-20240424-1 */- sFrom.a[0].iCursor = -1;+ sSelect.pSrc = pFrom;+ pFrom->nSrc = 1;+ pFrom->a[0].pSTab = pTab;+ pFrom->a[0].zName = pTab->zName; /* tag-20240424-1 */+ pFrom->a[0].iCursor = -1;sqlite3SelectPrep(pParse, &sSelect, 0);if( pParse->nErr==0 ){assert( db->mallocFailed==0 );@@ -154100,6 +157336,8 @@ static TriggerPrg *codeRowTrigger(sSubParse.eTriggerOp = pTrigger->op;sSubParse.nQueryLoop = pParse->nQueryLoop;sSubParse.prepFlags = pParse->prepFlags;+ sSubParse.oldmask = 0;+ sSubParse.newmask = 0;v = sqlite3GetVdbe(&sSubParse);if( v ){@@ -154854,38 +158092,32 @@ SQLITE_PRIVATE void sqlite3Update(*/chngRowid = chngPk = 0;for(i=0; i<pChanges->nExpr; i++){- u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName);/* If this is an UPDATE with a FROM clause, do not resolve expressions** here. The call to sqlite3Select() below will do that. */if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){goto update_cleanup;}- for(j=0; j<pTab->nCol; j++){- if( pTab->aCol[j].hName==hCol- && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0- ){- if( j==pTab->iPKey ){- chngRowid = 1;- pRowidExpr = pChanges->a[i].pExpr;- iRowidExpr = i;- }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){- chngPk = 1;- }+ j = sqlite3ColumnIndex(pTab, pChanges->a[i].zEName);+ if( j>=0 ){+ if( j==pTab->iPKey ){+ chngRowid = 1;+ pRowidExpr = pChanges->a[i].pExpr;+ iRowidExpr = i;+ }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){+ chngPk = 1;+ }#ifndef SQLITE_OMIT_GENERATED_COLUMNS- else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){- testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );- testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );- sqlite3ErrorMsg(pParse,- "cannot UPDATE generated column \"%s\"",- pTab->aCol[j].zCnName);- goto update_cleanup;- }-#endif- aXRef[j] = i;- break;+ else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){+ testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );+ testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );+ sqlite3ErrorMsg(pParse,+ "cannot UPDATE generated column \"%s\"",+ pTab->aCol[j].zCnName);+ goto update_cleanup;}- }- if( j>=pTab->nCol ){+#endif+ aXRef[j] = i;+ }else{if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){j = -1;chngRowid = 1;@@ -156208,7 +159440,7 @@ SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){#else/* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments** to VACUUM are silently ignored. This is a back-out of a bug fix that- ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).+ ** occurred on 2016-08-19 (https://sqlite.org/src/info/083f9e6270).** The buggy behavior is required for binary compatibility with some** legacy applications. */iDb = sqlite3FindDb(pParse->db, pNm);@@ -156287,7 +159519,8 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(saved_nChange = db->nChange;saved_nTotalChange = db->nTotalChange;saved_mTrace = db->mTrace;- db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;+ db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_Comments+ | SQLITE_AttachCreate | SQLITE_AttachWrite;db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder| SQLITE_Defensive | SQLITE_CountRows);@@ -156992,11 +160225,12 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){** schema table. We just need to update that slot with all** the information we've collected.**- ** The VM register number pParse->regRowid holds the rowid of an+ ** The VM register number pParse->u1.cr.regRowid holds the rowid of an** entry in the sqlite_schema table that was created for this vtab** by sqlite3StartTable().*/iDb = sqlite3SchemaToIndex(db, pTab->pSchema);+ assert( pParse->isCreate );sqlite3NestedParse(pParse,"UPDATE %Q." LEGACY_SCHEMA_TABLE " ""SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "@@ -157005,7 +160239,7 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){pTab->zName,pTab->zName,zStmt,- pParse->regRowid+ pParse->u1.cr.regRowid);v = sqlite3GetVdbe(pParse);sqlite3ChangeCookie(pParse, iDb);@@ -157791,9 +161025,12 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));addModuleArgument(pParse, pTab, 0);addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));+ db->nSchemaLock++;rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);+ db->nSchemaLock--;if( rc ){sqlite3ErrorMsg(pParse, "%s", zErr);+ pParse->rc = rc;sqlite3DbFree(db, zErr);sqlite3VtabEponymousTableClear(db, pMod);}@@ -157989,6 +161226,7 @@ struct WhereLevel {int iTabCur; /* The VDBE cursor used to access the table */int iIdxCur; /* The VDBE cursor used to access pIdx */int addrBrk; /* Jump here to break out of the loop */+ int addrHalt; /* Abort the query due to empty table or similar */int addrNxt; /* Jump here to start the next IN combination */int addrSkip; /* Jump here for next iteration of skip-scan */int addrCont; /* Jump here to continue with the next loop cycle */@@ -158194,6 +161432,9 @@ struct WhereTerm {u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */int iParent; /* Disable pWC->a[iParent] when this term disabled */int leftCursor; /* Cursor number of X in "X <op> <expr>" */+#ifdef SQLITE_DEBUG+ int iTerm; /* Which WhereTerm is this, for debug purposes */+#endifunion {struct {int leftColumn; /* Column number of X in "X <op> <expr>" */@@ -158415,9 +161656,14 @@ struct WhereInfo {Bitmask revMask; /* Mask of ORDER BY terms that need reversing */WhereClause sWC; /* Decomposition of the WHERE clause */WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */- WhereLevel a[1]; /* Information about each nest loop in WHERE */+ WhereLevel a[FLEXARRAY]; /* Information about each nest loop in WHERE */};+/*+** The size (in bytes) of a WhereInfo object that holds N WhereLevels.+*/+#define SZ_WHEREINFO(N) ROUND8(offsetof(WhereInfo,a)+(N)*sizeof(WhereLevel))+/*** Private interfaces - callable only by other where.c routines.**@@ -158681,7 +161927,6 @@ SQLITE_PRIVATE void sqlite3WhereAddExplainText(#endif{VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe, addr);-SrcItem *pItem = &pTabList->a[pLevel->iFrom];sqlite3 *db = pParse->db; /* Database handle */int isSearch; /* True for a SEARCH. False for SCAN. */@@ -158704,7 +161949,10 @@ SQLITE_PRIVATE void sqlite3WhereAddExplainText(sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);str.printfFlags = SQLITE_PRINTF_INTERNAL;- sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem);+ sqlite3_str_appendf(&str, "%s %S%s",+ isSearch ? "SEARCH" : "SCAN",+ pItem,+ pItem->fg.fromExists ? " EXISTS" : "");if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){const char *zFmt = 0;Index *pIdx;@@ -159097,7 +162345,7 @@ static void adjustOrderByCol(ExprList *pOrderBy, ExprList *pEList){/*** pX is an expression of the form: (vector) IN (SELECT ...)** In other words, it is a vector IN operator with a SELECT clause on the-** LHS. But not all terms in the vector are indexable and the terms might+** RHS. But not all terms in the vector are indexable and the terms might** not be in the correct order for indexing.**** This routine makes a copy of the input pX expression and then adjusts@@ -159153,7 +162401,9 @@ static Expr *removeUnindexableInClauseTerms(int iField;assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );iField = pLoop->aLTerm[i]->u.x.iField - 1;- if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */+ if( NEVER(pOrigRhs->a[iField].pExpr==0) ){+ continue; /* Duplicate PK column */+ }pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);pOrigRhs->a[iField].pExpr = 0;if( pRhs ) pRhs->a[pRhs->nExpr-1].u.x.iOrderByCol = iField+1;@@ -159250,7 +162500,7 @@ static SQLITE_NOINLINE void codeINTerm(return;}}- for(i=iEq;i<pLoop->nLTerm; i++){+ for(i=iEq; i<pLoop->nLTerm; i++){assert( pLoop->aLTerm[i]!=0 );if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;}@@ -159259,22 +162509,13 @@ static SQLITE_NOINLINE void codeINTerm(if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);}else{- Expr *pExpr = pTerm->pExpr;- if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){- sqlite3 *db = pParse->db;- pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);- if( !db->mallocFailed ){- aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);- eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab);- pExpr->iTable = iTab;- }- sqlite3ExprDelete(db, pX);- }else{- int n = sqlite3ExprVectorSize(pX->pLeft);- aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));- eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);+ sqlite3 *db = pParse->db;+ Expr *pXMod = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);+ if( !db->mallocFailed ){+ aiMap = (int*)sqlite3DbMallocZero(db, sizeof(int)*nEq);+ eType = sqlite3FindInIndex(pParse, pXMod, IN_INDEX_LOOP, 0, aiMap, &iTab);}- pX = pExpr;+ sqlite3ExprDelete(db, pXMod);}if( eType==IN_INDEX_INDEX_DESC ){@@ -159304,7 +162545,7 @@ static SQLITE_NOINLINE void codeINTerm(if( pIn ){int iMap = 0; /* Index in aiMap[] */pIn += i;- for(i=iEq;i<pLoop->nLTerm; i++){+ for(i=iEq; i<pLoop->nLTerm; i++){if( pLoop->aLTerm[i]->pExpr==pX ){int iOut = iTarget + i - iEq;if( eType==IN_INDEX_ROWID ){@@ -159955,6 +163196,7 @@ static SQLITE_NOINLINE void filterPullDown(int addrNxt, /* Jump here to bypass inner loops */Bitmask notReady /* Loops that are not ready */){+ int saved_addrBrk;while( ++iLevel < pWInfo->nLevel ){WhereLevel *pLevel = &pWInfo->a[iLevel];WhereLoop *pLoop = pLevel->pWLoop;@@ -159963,7 +163205,7 @@ static SQLITE_NOINLINE void filterPullDown(/* ,--- Because sqlite3ConstructBloomFilter() has will not have set** vvvvv--' pLevel->regFilter if this were true. */if( NEVER(pLoop->prereq & notReady) ) continue;- assert( pLevel->addrBrk==0 );+ saved_addrBrk = pLevel->addrBrk;pLevel->addrBrk = addrNxt;if( pLoop->wsFlags & WHERE_IPK ){WhereTerm *pTerm = pLoop->aLTerm[0];@@ -159993,7 +163235,7 @@ static SQLITE_NOINLINE void filterPullDown(VdbeCoverage(pParse->pVdbe);}pLevel->regFilter = 0;- pLevel->addrBrk = 0;+ pLevel->addrBrk = saved_addrBrk;}}@@ -160040,7 +163282,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(sqlite3 *db; /* Database connection */SrcItem *pTabItem; /* FROM clause term being coded */int addrBrk; /* Jump here to break out of the loop */- int addrHalt; /* addrBrk for the outermost loop */int addrCont; /* Jump here to continue with next cycle */int iRowidReg = 0; /* Rowid is stored in this register, if not zero */int iReleaseReg = 0; /* Temp register to free before returning */@@ -160084,7 +163325,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(** there are no IN operators in the constraints, the "addrNxt" label** is the same as "addrBrk".*/- addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);+ addrBrk = pLevel->addrNxt = pLevel->addrBrk;addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);/* If this is the right table of a LEFT OUTER JOIN, allocate and@@ -160100,14 +163341,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(VdbeComment((v, "init LEFT JOIN match flag"));}- /* Compute a safe address to jump to if we discover that the table for- ** this loop is empty and can never contribute content. */- for(j=iLevel; j>0; j--){- if( pWInfo->a[j].iLeftJoin ) break;- if( pWInfo->a[j].pRJ ) break;- }- addrHalt = pWInfo->a[j].addrBrk;-/* Special case of a FROM clause subquery implemented as a co-routine */if( pTabItem->fg.viaCoroutine ){int regYield;@@ -160163,6 +163396,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(}sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);+ /* The instruction immediately prior to OP_VFilter must be an OP_Integer+ ** that sets the "argc" value for xVFilter. This is necessary for+ ** resolveP2() to work correctly. See tag-20250207a. */sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,pLoop->u.vtab.idxStr,pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);@@ -160343,7 +163579,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(VdbeCoverageIf(v, pX->op==TK_GE);sqlite3ReleaseTempReg(pParse, rTemp);}else{- sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);+ sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, pLevel->addrHalt);VdbeCoverageIf(v, bRev==0);VdbeCoverageIf(v, bRev!=0);}@@ -160383,36 +163619,36 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);}}else if( pLoop->wsFlags & WHERE_INDEXED ){- /* Case 4: A scan using an index.+ /* Case 4: Search using an index.**- ** The WHERE clause may contain zero or more equality- ** terms ("==" or "IN" operators) that refer to the N- ** left-most columns of the index. It may also contain- ** inequality constraints (>, <, >= or <=) on the indexed- ** column that immediately follows the N equalities. Only- ** the right-most column can be an inequality - the rest must- ** use the "==" and "IN" operators. For example, if the- ** index is on (x,y,z), then the following clauses are all- ** optimized:+ ** The WHERE clause may contain zero or more equality+ ** terms ("==" or "IN" or "IS" operators) that refer to the N+ ** left-most columns of the index. It may also contain+ ** inequality constraints (>, <, >= or <=) on the indexed+ ** column that immediately follows the N equalities. Only+ ** the right-most column can be an inequality - the rest must+ ** use the "==", "IN", or "IS" operators. For example, if the+ ** index is on (x,y,z), then the following clauses are all+ ** optimized:**- ** x=5- ** x=5 AND y=10- ** x=5 AND y<10- ** x=5 AND y>5 AND y<10- ** x=5 AND y=5 AND z<=10+ ** x=5+ ** x=5 AND y=10+ ** x=5 AND y<10+ ** x=5 AND y>5 AND y<10+ ** x=5 AND y=5 AND z<=10**- ** The z<10 term of the following cannot be used, only- ** the x=5 term:+ ** The z<10 term of the following cannot be used, only+ ** the x=5 term:**- ** x=5 AND z<10+ ** x=5 AND z<10**- ** N may be zero if there are inequality constraints.- ** If there are no inequality constraints, then N is at- ** least one.+ ** N may be zero if there are inequality constraints.+ ** If there are no inequality constraints, then N is at+ ** least one.**- ** This case is also used when there are no WHERE clause- ** constraints but an index is selected anyway, in order- ** to force the output order to conform to an ORDER BY.+ ** This case is also used when there are no WHERE clause+ ** constraints but an index is selected anyway, in order+ ** to force the output order to conform to an ORDER BY.*/static const u8 aStartOp[] = {0,@@ -160753,12 +163989,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(if( pLevel->iLeftJoin==0 ){/* If a partial index is driving the loop, try to eliminate WHERE clause** terms from the query that must be true due to the WHERE clause of- ** the partial index.+ ** the partial index. This optimization does not work on an outer join,+ ** as shown by:**- ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work- ** for a LEFT JOIN.+ ** 2019-11-02 ticket 623eff57e76d45f6 (LEFT JOIN)+ ** 2025-05-29 forum post 7dee41d32506c4ae (RIGHT JOIN)*/- if( pIdx->pPartIdxWhere ){+ if( pIdx->pPartIdxWhere && pLevel->pRJ==0 ){whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);}}else{@@ -160865,8 +164102,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(int nNotReady; /* The number of notReady tables */SrcItem *origSrc; /* Original list of tables */nNotReady = pWInfo->nLevel - iLevel - 1;- pOrTab = sqlite3DbMallocRawNN(db,- sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));+ pOrTab = sqlite3DbMallocRawNN(db, SZ_SRCLIST(nNotReady+1));if( pOrTab==0 ) return notReady;pOrTab->nAlloc = (u8)(nNotReady + 1);pOrTab->nSrc = pOrTab->nAlloc;@@ -160917,7 +164153,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(**** This optimization also only applies if the (x1 OR x2 OR ...) term** is not contained in the ON clause of a LEFT JOIN.- ** See ticket http://www.sqlite.org/src/info/f2369304e4+ ** See ticket http://sqlite.org/src/info/f2369304e4**** 2022-02-04: Do not push down slices of a row-value comparison.** In other words, "w" or "y" may not be a slice of a vector. Otherwise,@@ -161138,7 +164374,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(codeCursorHint(pTabItem, pWInfo, pLevel, 0);pLevel->op = aStep[bRev];pLevel->p1 = iCur;- pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);+ pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev],iCur,pLevel->addrHalt);VdbeCoverageIf(v, bRev==0);VdbeCoverageIf(v, bRev!=0);pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;@@ -161409,7 +164645,11 @@ SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(WhereInfo *pSubWInfo;WhereLoop *pLoop = pLevel->pWLoop;SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];- SrcList sFrom;+ SrcList *pFrom;+ union {+ SrcList sSrc;+ u8 fromSpace[SZ_SRCLIST_1];+ } uSrc;Bitmask mAll = 0;int k;@@ -161453,13 +164693,23 @@ SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));}}- sFrom.nSrc = 1;- sFrom.nAlloc = 1;- memcpy(&sFrom.a[0], pTabItem, sizeof(SrcItem));- sFrom.a[0].fg.jointype = 0;+ if( pLevel->iIdxCur ){+ /* pSubWhere may contain expressions that read from an index on the+ ** table on the RHS of the right join. All such expressions first test+ ** if the index is pointing at a NULL row, and if so, read from the+ ** table cursor instead. So ensure that the index cursor really is+ ** pointing at a NULL row here, so that no values are read from it during+ ** the scan of the RHS of the RIGHT join below. */+ sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);+ }+ pFrom = &uSrc.sSrc;+ pFrom->nSrc = 1;+ pFrom->nAlloc = 1;+ memcpy(&pFrom->a[0], pTabItem, sizeof(SrcItem));+ pFrom->a[0].fg.jointype = 0;assert( pParse->withinRJSubrtn < 100 );pParse->withinRJSubrtn++;- pSubWInfo = sqlite3WhereBegin(pParse, &sFrom, pSubWhere, 0, 0, 0,+ pSubWInfo = sqlite3WhereBegin(pParse, pFrom, pSubWhere, 0, 0, 0,WHERE_RIGHT_JOIN, 0);if( pSubWInfo ){int iCur = pLevel->iTabCur;@@ -162430,30 +165680,42 @@ static void exprAnalyzeOrTerm(** 1. The SQLITE_Transitive optimization must be enabled** 2. Must be either an == or an IS operator** 3. Not originating in the ON clause of an OUTER JOIN-** 4. The affinities of A and B must be compatible-** 5a. Both operands use the same collating sequence OR-** 5b. The overall collating sequence is BINARY+** 4. The operator is not IS or else the query does not contain RIGHT JOIN+** 5. The affinities of A and B must be compatible+** 6a. Both operands use the same collating sequence OR+** 6b. The overall collating sequence is BINARY** If this routine returns TRUE, that means that the RHS can be substituted** for the LHS anyplace else in the WHERE clause where the LHS column occurs.** This is an optimization. No harm comes from returning 0. But if 1 is** returned when it should not be, then incorrect answers might result.*/-static int termIsEquivalence(Parse *pParse, Expr *pExpr){+static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){char aff1, aff2;CollSeq *pColl;- if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;- if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;- if( ExprHasProperty(pExpr, EP_OuterON) ) return 0;+ if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */+ if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */+ if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* (3) */+ assert( pSrc!=0 );+ if( pExpr->op==TK_IS+ && pSrc->nSrc>=2+ && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0+ ){+ return 0; /* (4) */+ }aff1 = sqlite3ExprAffinity(pExpr->pLeft);aff2 = sqlite3ExprAffinity(pExpr->pRight);if( aff1!=aff2&& (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))){- return 0;+ return 0; /* (5) */}pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);- if( sqlite3IsBinary(pColl) ) return 1;- return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);+ if( !sqlite3IsBinary(pColl)+ && !sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight)+ ){+ return 0; /* (6) */+ }+ return 1;}/*@@ -162611,6 +165873,9 @@ static void exprAnalyze(}assert( pWC->nTerm > idxTerm );pTerm = &pWC->a[idxTerm];+#ifdef SQLITE_DEBUG+ pTerm->iTerm = idxTerm;+#endifpMaskSet = &pWInfo->sMaskSet;pExpr = pTerm->pExpr;assert( pExpr!=0 ); /* Because malloc() has not failed */@@ -162654,21 +165919,7 @@ static void exprAnalyze(prereqAll |= x;extraRight = x-1; /* ON clause terms may not be used with an index** on left table of a LEFT JOIN. Ticket #3015 */- if( (prereqAll>>1)>=x ){- sqlite3ErrorMsg(pParse, "ON clause references tables to its right");- return;- }}else if( (prereqAll>>1)>=x ){- /* The ON clause of an INNER JOIN references a table to its right.- ** Most other SQL database engines raise an error. But SQLite versions- ** 3.0 through 3.38 just put the ON clause constraint into the WHERE- ** clause and carried on. Beginning with 3.39, raise an error only- ** if there is a RIGHT or FULL JOIN in the query. This makes SQLite- ** more like other systems, and also preserves legacy. */- if( ALWAYS(pSrc->nSrc>0) && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){- sqlite3ErrorMsg(pParse, "ON clause references tables to its right");- return;- }ExprClearProperty(pExpr, EP_InnerON);}}@@ -162718,8 +165969,8 @@ static void exprAnalyze(if( op==TK_IS ) pNew->wtFlags |= TERM_IS;pTerm = &pWC->a[idxTerm];pTerm->wtFlags |= TERM_COPIED;-- if( termIsEquivalence(pParse, pDup) ){+ assert( pWInfo->pTabList!=0 );+ if( termIsEquivalence(pParse, pDup, pWInfo->pTabList) ){pTerm->eOperator |= WO_EQUIV;eExtraOp = WO_EQUIV;}@@ -163025,7 +166276,7 @@ static void exprAnalyze(idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);testcase( idxNew==0 );pNewTerm = &pWC->a[idxNew];- pNewTerm->prereqRight = prereqExpr;+ pNewTerm->prereqRight = prereqExpr | extraRight;pNewTerm->leftCursor = pLeft->iTable;pNewTerm->u.x.leftColumn = pLeft->iColumn;pNewTerm->eOperator = WO_AUX;@@ -163136,7 +166387,7 @@ static void whereAddLimitExpr(**** 1. The SELECT statement has a LIMIT clause, and** 2. The SELECT statement is not an aggregate or DISTINCT query, and-** 3. The SELECT statement has exactly one object in its from clause, and+** 3. The SELECT statement has exactly one object in its FROM clause, and** that object is a virtual table, and** 4. There are no terms in the WHERE clause that will not be passed** to the virtual table xBestIndex method.@@ -163173,8 +166424,22 @@ SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3WhereAddLimit(WhereClause *pWC, Selec** (leftCursor==iCsr) test below. */continue;}- if( pWC->a[ii].leftCursor!=iCsr ) return;- if( pWC->a[ii].prereqRight!=0 ) return;+ if( pWC->a[ii].leftCursor==iCsr && pWC->a[ii].prereqRight==0 ) continue;++ /* If this term has a parent with exactly one child, and the parent will+ ** be passed through to xBestIndex, then this term can be ignored. */+ if( pWC->a[ii].iParent>=0 ){+ WhereTerm *pParent = &pWC->a[ pWC->a[ii].iParent ];+ if( pParent->leftCursor==iCsr+ && pParent->prereqRight==0+ && pParent->nChild==1+ ){+ continue;+ }+ }++ /* This term will not be passed through. Do not add a LIMIT clause. */+ return;}/* Check condition (5). Return early if it is not met. */@@ -163447,11 +166712,16 @@ struct HiddenIndexInfo {int eDistinct; /* Value to return from sqlite3_vtab_distinct() */u32 mIn; /* Mask of terms that are <col> IN (...) */u32 mHandleIn; /* Terms that vtab will handle as <col> IN (...) */- sqlite3_value *aRhs[1]; /* RHS values for constraints. MUST BE LAST- ** because extra space is allocated to hold up- ** to nTerm such values */+ sqlite3_value *aRhs[FLEXARRAY]; /* RHS values for constraints. MUST BE LAST+ ** Extra space is allocated to hold up+ ** to nTerm such values */};+/* Size (in bytes) of a HiddenIndeInfo object sufficient to hold as+** many as N constraints */+#define SZ_HIDDENINDEXINFO(N) \+ (offsetof(HiddenIndexInfo,aRhs) + (N)*sizeof(sqlite3_value*))+/* Forward declaration of methods */static int whereLoopResize(sqlite3*, WhereLoop*, int);@@ -163833,11 +167103,11 @@ static WhereTerm *whereScanNext(WhereScan *pScan){pScan->pWC = pWC;pScan->k = k+1;#ifdef WHERETRACE_ENABLED- if( sqlite3WhereTrace & 0x20000 ){+ if( (sqlite3WhereTrace & 0x20000)!=0 && pScan->nEquiv>1 ){int ii;- sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",- pTerm, pScan->nEquiv);- for(ii=0; ii<pScan->nEquiv; ii++){+ sqlite3DebugPrintf("EQUIVALENT TO {%d:%d} (due to TERM-%d):",+ pScan->aiCur[0], pScan->aiColumn[0], pTerm->iTerm);+ for(ii=1; ii<pScan->nEquiv; ii++){sqlite3DebugPrintf(" {%d:%d}",pScan->aiCur[ii], pScan->aiColumn[ii]);}@@ -164516,6 +167786,8 @@ static SQLITE_NOINLINE void constructAutomaticIndex(}/* Construct the Index object to describe this index */+ assert( nKeyCol <= pTable->nCol + MAX(0, pTable->nCol - BMS + 1) );+ /* ^-- This guarantees that the number of index columns will fit in the u16 */pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable),0, &zNotUsed);if( pIdx==0 ) goto end_auto_index_create;@@ -164606,7 +167878,9 @@ static SQLITE_NOINLINE void constructAutomaticIndex(VdbeCoverage(v);VdbeComment((v, "next row of %s", pSrc->pSTab->zName));}else{- addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);+ assert( pLevel->addrHalt );+ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind,pLevel->iTabCur,pLevel->addrHalt);+ VdbeCoverage(v);}if( pPartial ){iContinue = sqlite3VdbeMakeLabel(pParse);@@ -164634,11 +167908,14 @@ static SQLITE_NOINLINE void constructAutomaticIndex(pSrc->u4.pSubq->regResult, pLevel->iIdxCur);sqlite3VdbeGoto(v, addrTop);pSrc->fg.viaCoroutine = 0;+ sqlite3VdbeJumpHere(v, addrTop);}else{sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);+ if( (pSrc->fg.jointype & JT_LEFT)!=0 ){+ sqlite3VdbeJumpHere(v, addrTop);+ }}- sqlite3VdbeJumpHere(v, addrTop);sqlite3ReleaseTempReg(pParse, regRecord);/* Jump here when skipping the initialization */@@ -164927,8 +168204,8 @@ static sqlite3_index_info *allocateIndexInfo(*/pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)+ (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm- + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)- + sizeof(sqlite3_value*)*nTerm );+ + sizeof(*pIdxOrderBy)*nOrderBy+ + SZ_HIDDENINDEXINFO(nTerm) );if( pIdxInfo==0 ){sqlite3ErrorMsg(pParse, "out of memory");return 0;@@ -165790,6 +169067,7 @@ SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){}else{sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);}+ iTerm = pTerm->iTerm = MAX(iTerm,pTerm->iTerm);sqlite3DebugPrintf("TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);@@ -166564,11 +169842,8 @@ static int whereLoopAddBtreeIndex(assert( pNew->u.btree.nBtm==0 );opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;}- if( pProbe->bUnordered || pProbe->bLowQual ){- if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);- if( pProbe->bLowQual && pSrc->fg.isIndexedBy==0 ){- opMask &= ~(WO_EQ|WO_IN|WO_IS);- }+ if( pProbe->bUnordered ){+ opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);}assert( pNew->u.btree.nEq<pProbe->nColumn );@@ -166641,6 +169916,7 @@ static int whereLoopAddBtreeIndex(if( ExprUseXSelect(pExpr) ){/* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */int i;+ int bRedundant = 0;nIn = 46; assert( 46==sqlite3LogEst(25) );/* The expression may actually be of the form (x, y) IN (SELECT...).@@ -166649,7 +169925,20 @@ static int whereLoopAddBtreeIndex(** for each such term. The following loop checks that pTerm is the** first such term in use, and sets nIn back to 0 if it is not. */for(i=0; i<pNew->nLTerm-1; i++){- if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;+ if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ){+ nIn = 0;+ if( pNew->aLTerm[i]->u.x.iField == pTerm->u.x.iField ){+ /* Detect when two or more columns of an index match the same+ ** column of a vector IN operater, and avoid adding the column+ ** to the WhereLoop more than once. See tag-20250707-01+ ** in test/rowvalue.test */+ bRedundant = 1;+ }+ }+ }+ if( bRedundant ){+ pNew->nLTerm--;+ continue;}}else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){/* "x IN (value, value, ...)" */@@ -166881,7 +170170,7 @@ static int whereLoopAddBtreeIndex(if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0&& pNew->u.btree.nEq<pProbe->nColumn&& (pNew->u.btree.nEq<pProbe->nKeyCol ||- pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)+ pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)){if( pNew->u.btree.nEq>3 ){sqlite3ProgressCheck(pParse);@@ -166920,6 +170209,7 @@ static int whereLoopAddBtreeIndex(&& pProbe->hasStat1!=0&& OptimizationEnabled(db, SQLITE_SkipScan)&& pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */+ && pSrc->fg.fromExists==0&& (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK){LogEst nIter;@@ -167010,6 +170300,7 @@ static int whereUsablePartialIndex(if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)&& ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))&& sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)+ && !sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, -1)&& (pTerm->wtFlags & TERM_VNULL)==0){return 1;@@ -167423,6 +170714,7 @@ static int whereLoopAddBtree(pNew->u.btree.nEq = 0;pNew->u.btree.nBtm = 0;pNew->u.btree.nTop = 0;+ pNew->u.btree.nDistinctCol = 0;pNew->nSkip = 0;pNew->nLTerm = 0;pNew->iSortIdx = 0;@@ -167505,7 +170797,7 @@ static int whereLoopAddBtree(&& (HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700))){WHERETRACE(0x200,- ("-> %s a covering index according to bitmasks\n",+ ("-> %s is a covering index according to bitmasks\n",pProbe->zName, m==0 ? "is" : "is not"));pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;}@@ -168489,10 +171781,12 @@ static i8 wherePathSatisfiesOrderBy(&& ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)){obSat = obDone;+ }else{+ /* No further ORDER BY terms may be matched. So this call should+ ** return >=0, not -1. Clear isOrderDistinct to ensure it does so. */+ isOrderDistinct = 0;}break;- }else if( wctrlFlags & WHERE_DISTINCTBY ){- pLoop->u.btree.nDistinctCol = 0;}iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;@@ -169236,8 +172530,15 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){** mxChoice best-so-far paths.**** First look for an existing path among best-so-far paths- ** that covers the same set of loops and has the same isOrdered- ** setting as the current path candidate.+ ** that:+ ** (1) covers the same set of loops, and+ ** (2) has a compatible isOrdered value.+ **+ ** "Compatible isOrdered value" means either+ ** (A) both have isOrdered==-1, or+ ** (B) both have isOrder>=0, or+ ** (C) ordering does not matter because this is the last round+ ** of the solver.**** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range@@ -169246,7 +172547,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){testcase( nTo==0 );for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){if( pTo->maskLoop==maskNew- && ((pTo->isOrdered^isOrdered)&0x80)==0+ && ( ((pTo->isOrdered^isOrdered)&0x80)==0 || iLoop==nLoop-1 )){testcase( jj==nTo-1 );break;@@ -169401,11 +172702,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){return SQLITE_ERROR;}- /* Find the lowest cost path. pFrom will be left pointing to that path */+ /* Only one path is available, which is the best path */+ assert( nFrom==1 );pFrom = aFrom;- for(ii=1; ii<nFrom; ii++){- if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];- }+assert( pWInfo->nLevel==nLoop );/* Load the lowest cost path into pWInfo */for(iLoop=0; iLoop<nLoop; iLoop++){@@ -169538,7 +172838,10 @@ static SQLITE_NOINLINE void whereInterstageHeuristic(WhereInfo *pWInfo){for(i=0; i<pWInfo->nLevel; i++){WhereLoop *p = pWInfo->a[i].pWLoop;if( p==0 ) break;- if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ) continue;+ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ){+ /* Treat a vtab scan as similar to a full-table scan */+ break;+ }if( (p->wsFlags & (WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 ){u8 iTab = p->iTab;WhereLoop *pLoop;@@ -170122,10 +173425,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(** field (type Bitmask) it must be aligned on an 8-byte boundary on** some architectures. Hence the ROUND8() below.*/- nByteWInfo = ROUND8P(sizeof(WhereInfo));- if( nTabList>1 ){- nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel));- }+ nByteWInfo = SZ_WHEREINFO(nTabList);pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));if( db->mallocFailed ){sqlite3DbFree(db, pWInfo);@@ -170342,7 +173642,8 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(}/* TUNING: Assume that a DISTINCT clause on a subquery reduces- ** the output size by a factor of 8 (LogEst -30).+ ** the output size by a factor of 8 (LogEst -30). Search for+ ** tag-20250414a to see other cases.*/if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",@@ -170478,6 +173779,14 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(pTab = pTabItem->pSTab;iDb = sqlite3SchemaToIndex(db, pTab->pSchema);pLoop = pLevel->pWLoop;+ pLevel->addrBrk = sqlite3VdbeMakeLabel(pParse);+ if( ii==0 || (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){+ pLevel->addrHalt = pLevel->addrBrk;+ }else if( pWInfo->a[ii-1].pRJ ){+ pLevel->addrHalt = pWInfo->a[ii-1].addrBrk;+ }else{+ pLevel->addrHalt = pWInfo->a[ii-1].addrHalt;+ }if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){/* Do nothing */}else@@ -170529,6 +173838,13 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,(const u8*)&pTabItem->colUsed, P4_INT64);#endif+ if( ii>=2+ && (pTabItem[0].fg.jointype & (JT_LTORJ|JT_LEFT))==0+ && pLevel->addrHalt==pWInfo->a[0].addrHalt+ ){+ sqlite3VdbeAddOp2(v, OP_IfEmpty, pTabItem->iCursor, pWInfo->iBreak);+ VdbeCoverage(v);+ }}else{sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);}@@ -170741,6 +174057,9 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){sqlite3 *db = pParse->db;int iEnd = sqlite3VdbeCurrentAddr(v);int nRJ = 0;+#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT+ int addrSeek = 0;+#endif/* Generate loop termination code.*/@@ -170753,7 +174072,10 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){** the RIGHT JOIN table */WhereRightJoin *pRJ = pLevel->pRJ;sqlite3VdbeResolveLabel(v, pLevel->addrCont);- pLevel->addrCont = 0;+ /* Replace addrCont with a new label that will never be used, just so+ ** the subsequent call to resolve pLevel->addrCont will have something+ ** to resolve. */+ pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);VdbeCoverage(v);@@ -170762,7 +174084,6 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){pLoop = pLevel->pWLoop;if( pLevel->op!=OP_Noop ){#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT- int addrSeek = 0;Index *pIdx;int n;if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED@@ -170785,8 +174106,26 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);}#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */- /* The common case: Advance to the next row */- if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);+ }+ if( pTabList->a[pLevel->iFrom].fg.fromExists && i==pWInfo->nLevel-1 ){+ /* If the EXISTS-to-JOIN optimization was applied, then the EXISTS+ ** loop(s) will be the inner-most loops of the join. There might be+ ** multiple EXISTS loops, but they will all be nested, and the join+ ** order will not have been changed by the query planner. If the+ ** inner-most EXISTS loop sees a single successful row, it should+ ** break out of *all* EXISTS loops. But only the inner-most of the+ ** nested EXISTS loops should do this breakout. */+ int nOuter = 0; /* Nr of outer EXISTS that this one is nested within */+ while( nOuter<i ){+ if( !pTabList->a[pLevel[-nOuter-1].iFrom].fg.fromExists ) break;+ nOuter++;+ }+ testcase( nOuter>0 );+ sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel[-nOuter].addrBrk);+ VdbeComment((v, "EXISTS break"));+ }+ sqlite3VdbeResolveLabel(v, pLevel->addrCont);+ if( pLevel->op!=OP_Noop ){sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);sqlite3VdbeChangeP5(v, pLevel->p5);VdbeCoverage(v);@@ -170799,10 +174138,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){VdbeCoverage(v);}#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT- if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);+ if( addrSeek ){+ sqlite3VdbeJumpHere(v, addrSeek);+ addrSeek = 0;+ }#endif- }else if( pLevel->addrCont ){- sqlite3VdbeResolveLabel(v, pLevel->addrCont);}if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){struct InLoop *pIn;@@ -172077,7 +175417,7 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){p->pWhere = 0;p->pGroupBy = 0;p->pHaving = 0;- p->selFlags &= ~SF_Aggregate;+ p->selFlags &= ~(u32)SF_Aggregate;p->selFlags |= SF_WinRewrite;/* Create the ORDER BY clause for the sub-select. This is the concatenation@@ -173635,7 +176975,7 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){**** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING**-** ... loop started by sqlite3WhereBegin() ...+** ... loop started by sqlite3WhereBegin() ...** if( new partition ){** Gosub flush** }@@ -174153,6 +177493,12 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);}else{assert( pMWin->eEnd==TK_FOLLOWING );+ /* assert( regStart>=0 );+ ** regEnd = regEnd - regStart;+ ** regStart = 0; */+ sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);+ sqlite3VdbeAddOp2(v, OP_Integer, 0, regStart);+addrStart = sqlite3VdbeCurrentAddr(v);addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);@@ -174217,6 +177563,11 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(/* #include "sqliteInt.h" */+/*+** Verify that the pParse->isCreate field is set+*/+#define ASSERT_IS_CREATE assert(pParse->isCreate)+/*** Disable all error recovery processing in the parser push-down** automaton.@@ -174280,6 +177631,10 @@ static void parserSyntaxError(Parse *pParse, Token *p){static void disableLookaside(Parse *pParse){sqlite3 *db = pParse->db;pParse->disableLookaside++;+#ifdef SQLITE_DEBUG+ pParse->isCreate = 1;+#endif+ memset(&pParse->u1.cr, 0, sizeof(pParse->u1.cr));DisableLookaside;}@@ -177916,7 +181271,9 @@ static YYACTIONTYPE yy_reduce(}break;case 14: /* createkw ::= CREATE */-{disableLookaside(pParse);}+{+ disableLookaside(pParse);+}break;case 15: /* ifnotexists ::= */case 18: /* temp ::= */ yytestcase(yyruleno==18);@@ -178008,7 +181365,7 @@ static YYACTIONTYPE yy_reduce(break;case 32: /* ccons ::= CONSTRAINT nm */case 67: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==67);-{pParse->constraintName = yymsp[0].minor.yy0;}+{ASSERT_IS_CREATE; pParse->u1.cr.constraintName = yymsp[0].minor.yy0;}break;case 33: /* ccons ::= DEFAULT scantok term */{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy590,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}@@ -178118,7 +181475,7 @@ static YYACTIONTYPE yy_reduce({yymsp[-1].minor.yy502 = 0;}break;case 66: /* tconscomma ::= COMMA */-{pParse->constraintName.n = 0;}+{ASSERT_IS_CREATE; pParse->u1.cr.constraintName.n = 0;}break;case 68: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy402,yymsp[0].minor.yy502,yymsp[-2].minor.yy502,0);}@@ -178205,8 +181562,8 @@ static YYACTIONTYPE yy_reduce(if( pRhs ){pRhs->op = (u8)yymsp[-1].minor.yy502;pRhs->pPrior = pLhs;- if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;- pRhs->selFlags &= ~SF_MultiValue;+ if( ALWAYS(pLhs) ) pLhs->selFlags &= ~(u32)SF_MultiValue;+ pRhs->selFlags &= ~(u32)SF_MultiValue;if( yymsp[-1].minor.yy502!=TK_ALL ) pParse->hasCompound = 1;}else{sqlite3SelectDelete(pParse->db, pLhs);@@ -178846,12 +182203,21 @@ static YYACTIONTYPE yy_reduce(** expr1 IN ()** expr1 NOT IN ()**- ** simplify to constants 0 (false) and 1 (true), respectively,- ** regardless of the value of expr1.+ ** simplify to constants 0 (false) and 1 (true), respectively.+ **+ ** Except, do not apply this optimization if expr1 contains a function+ ** because that function might be an aggregate (we don't know yet whether+ ** it is or not) and if it is an aggregate, that could change the meaning+ ** of the whole query.*/- sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy590);- yymsp[-4].minor.yy590 = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy502 ? "true" : "false");- if( yymsp[-4].minor.yy590 ) sqlite3ExprIdToTrueFalse(yymsp[-4].minor.yy590);+ Expr *pB = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy502 ? "true" : "false");+ if( pB ) sqlite3ExprIdToTrueFalse(pB);+ if( !ExprHasProperty(yymsp[-4].minor.yy590, EP_HasFunc) ){+ sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy590);+ yymsp[-4].minor.yy590 = pB;+ }else{+ yymsp[-4].minor.yy590 = sqlite3PExpr(pParse, yymsp[-3].minor.yy502 ? TK_OR : TK_AND, pB, yymsp[-4].minor.yy590);+ }}else{Expr *pRHS = yymsp[-1].minor.yy402->a[0].pExpr;if( yymsp[-1].minor.yy402->nExpr==1 && sqlite3ExprIsConstant(pParse,pRHS) && yymsp[-4].minor.yy590->op!=TK_VECTOR ){@@ -179011,6 +182377,10 @@ static YYACTIONTYPE yy_reduce({sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy502, yymsp[-4].minor.yy28.a, yymsp[-4].minor.yy28.b, yymsp[-2].minor.yy563, yymsp[0].minor.yy590, yymsp[-10].minor.yy502, yymsp[-8].minor.yy502);yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/+#ifdef SQLITE_DEBUG+ assert( pParse->isCreate ); /* Set by createkw reduce action */+ pParse->isCreate = 0; /* But, should not be set for CREATE TRIGGER */+#endif}break;case 262: /* trigger_time ::= BEFORE|AFTER */@@ -180453,7 +183823,7 @@ static int getToken(const unsigned char **pz){int t; /* Token type to return */do {z += sqlite3GetToken(z, &t);- }while( t==TK_SPACE );+ }while( t==TK_SPACE || t==TK_COMMENT );if( t==TK_ID|| t==TK_STRING|| t==TK_JOIN_KW@@ -180524,8 +183894,9 @@ static int analyzeFilterKeyword(const unsigned char *z, int lastToken){** Return the length (in bytes) of the token that begins at z[0].** Store the token type in *tokenType before returning.*/-SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){- int i, c;+SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *z, int *tokenType){+ i64 i;+ int c;switch( aiClass[*z] ){ /* Switch on the character-class of the first byte** of the token. See the comment on the CC_ defines** above. */@@ -180853,7 +184224,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){int nErr = 0; /* Number of errors encountered */void *pEngine; /* The LEMON-generated LALR(1) parser */- int n = 0; /* Length of the next token token */+ i64 n = 0; /* Length of the next token token */int tokenType; /* type of the next token */int lastTokenParsed = -1; /* type of the previous token */sqlite3 *db = pParse->db; /* The database connection */@@ -180946,19 +184317,23 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){assert( n==6 );tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);#endif /* SQLITE_OMIT_WINDOWFUNC */- }else if( tokenType==TK_COMMENT && (db->flags & SQLITE_Comments)!=0 ){+ }else if( tokenType==TK_COMMENT+ && (db->init.busy || (db->flags & SQLITE_Comments)!=0)+ ){+ /* Ignore SQL comments if either (1) we are reparsing the schema or+ ** (2) SQLITE_DBCONFIG_ENABLE_COMMENTS is turned on (the default). */zSql += n;continue;}else if( tokenType!=TK_QNUMBER ){Token x;x.z = zSql;- x.n = n;+ x.n = (u32)n;sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &x);break;}}pParse->sLastToken.z = zSql;- pParse->sLastToken.n = n;+ pParse->sLastToken.n = (u32)n;sqlite3Parser(pEngine, tokenType, pParse->sLastToken);lastTokenParsed = tokenType;zSql += n;@@ -181034,7 +184409,7 @@ SQLITE_PRIVATE char *sqlite3Normalize(){sqlite3 *db; /* The database connection */int i; /* Next unread byte of zSql[] */- int n; /* length of current token */+ i64 n; /* length of current token */int tokenType; /* type of current token */int prevType = 0; /* Previous non-whitespace token */int nParen; /* Number of nested levels of parentheses */@@ -181612,9 +184987,6 @@ static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {sqlite3DbstatRegister,#endifsqlite3TestExtInit,-#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)- sqlite3JsonTableFunctions,-#endif#ifdef SQLITE_ENABLE_STMTVTABsqlite3StmtVtabInit,#endif@@ -181841,6 +185213,14 @@ SQLITE_API int sqlite3_initialize(void){if( rc==SQLITE_OK ){sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);+#ifdef SQLITE_EXTRA_INIT_MUTEXED+ {+ int SQLITE_EXTRA_INIT_MUTEXED(const char*);+ rc = SQLITE_EXTRA_INIT_MUTEXED(0);+ }+#endif+ }+ if( rc==SQLITE_OK ){sqlite3MemoryBarrier();sqlite3GlobalConfig.isInit = 1;#ifdef SQLITE_EXTRA_INIT@@ -182297,17 +185677,22 @@ SQLITE_API int sqlite3_config(int op, ...){** If lookaside is already active, return SQLITE_BUSY.**** The sz parameter is the number of bytes in each lookaside slot.-** The cnt parameter is the number of slots. If pStart is NULL the-** space for the lookaside memory is obtained from sqlite3_malloc().-** If pStart is not NULL then it is sz*cnt bytes of memory to use for-** the lookaside memory.+** The cnt parameter is the number of slots. If pBuf is NULL the+** space for the lookaside memory is obtained from sqlite3_malloc()+** or similar. If pBuf is not NULL then it is sz*cnt bytes of memory+** to use for the lookaside memory.*/-static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){+static int setupLookaside(+ sqlite3 *db, /* Database connection being configured */+ void *pBuf, /* Memory to use for lookaside. May be NULL */+ int sz, /* Desired size of each lookaside memory slot */+ int cnt /* Number of slots to allocate */+){#ifndef SQLITE_OMIT_LOOKASIDE- void *pStart;- sqlite3_int64 szAlloc;- int nBig; /* Number of full-size slots */- int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */+ void *pStart; /* Start of the lookaside buffer */+ sqlite3_int64 szAlloc; /* Total space set aside for lookaside memory */+ int nBig; /* Number of full-size slots */+ int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */if( sqlite3LookasideUsed(db,0)>0 ){return SQLITE_BUSY;@@ -182320,19 +185705,22 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){sqlite3_free(db->lookaside.pStart);}/* The size of a lookaside slot after ROUNDDOWN8 needs to be larger- ** than a pointer to be useful.+ ** than a pointer and small enough to fit in a u16.*/- sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */+ sz = ROUNDDOWN8(sz);if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;if( sz>65528 ) sz = 65528;- if( cnt<0 ) cnt = 0;+ /* Count must be at least 1 to be useful, but not so large as to use+ ** more than 0x7fff0000 total bytes for lookaside. */+ if( cnt<1 ) cnt = 0;+ if( sz>0 && cnt>(0x7fff0000/sz) ) cnt = 0x7fff0000/sz;szAlloc = (i64)sz*(i64)cnt;- if( sz==0 || cnt==0 ){+ if( szAlloc==0 ){sz = 0;pStart = 0;}else if( pBuf==0 ){sqlite3BeginBenignMalloc();- pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */+ pStart = sqlite3Malloc( szAlloc );sqlite3EndBenignMalloc();if( pStart ) szAlloc = sqlite3MallocSize(pStart);}else{@@ -182919,6 +186307,7 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){/* Clear the TEMP schema separately and last */if( db->aDb[1].pSchema ){sqlite3SchemaClear(db->aDb[1].pSchema);+ assert( db->aDb[1].pSchema->trigHash.count==0 );}sqlite3VtabUnlockList(db);@@ -183054,6 +186443,9 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){case SQLITE_OK: zName = "SQLITE_OK"; break;case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;+ case SQLITE_ERROR_RETRY: zName = "SQLITE_ERROR_RETRY"; break;+ case SQLITE_ERROR_MISSING_COLLSEQ:+ zName = "SQLITE_ERROR_MISSING_COLLSEQ"; break;case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;case SQLITE_PERM: zName = "SQLITE_PERM"; break;case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;@@ -183309,6 +186701,9 @@ SQLITE_API int sqlite3_busy_handler(db->busyHandler.pBusyArg = pArg;db->busyHandler.nBusy = 0;db->busyTimeout = 0;+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ db->setlkTimeout = 0;+#endifsqlite3_mutex_leave(db->mutex);return SQLITE_OK;}@@ -183358,12 +186753,49 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,(void*)db);db->busyTimeout = ms;+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ db->setlkTimeout = ms;+#endif}else{sqlite3_busy_handler(db, 0, 0);}return SQLITE_OK;}+/*+** Set the setlk timeout value.+*/+SQLITE_API int sqlite3_setlk_timeout(sqlite3 *db, int ms, int flags){+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ int iDb;+ int bBOC = ((flags & SQLITE_SETLK_BLOCK_ON_CONNECT) ? 1 : 0);+#endif+#ifdef SQLITE_ENABLE_API_ARMOR+ if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;+#endif+ if( ms<-1 ) return SQLITE_RANGE;+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT+ sqlite3_mutex_enter(db->mutex);+ db->setlkTimeout = ms;+ db->setlkFlags = flags;+ sqlite3BtreeEnterAll(db);+ for(iDb=0; iDb<db->nDb; iDb++){+ Btree *pBt = db->aDb[iDb].pBt;+ if( pBt ){+ sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pBt));+ sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, (void*)&bBOC);+ }+ }+ sqlite3BtreeLeaveAll(db);+ sqlite3_mutex_leave(db->mutex);+#endif+#if !defined(SQLITE_ENABLE_API_ARMOR) && !defined(SQLITE_ENABLE_SETLK_TIMEOUT)+ UNUSED_PARAMETER(db);+ UNUSED_PARAMETER(flags);+#endif+ return SQLITE_OK;+}+/*** Cause any pending operation to stop at its earliest opportunity.*/@@ -184195,6 +187627,29 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){return z;}+/*+** Set the error code and error message associated with the database handle.+**+** This routine is intended to be called by outside extensions (ex: the+** Session extension). Internal logic should invoke sqlite3Error() or+** sqlite3ErrorWithMsg() directly.+*/+SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zMsg){+ int rc = SQLITE_OK;+ if( !sqlite3SafetyCheckOk(db) ){+ return SQLITE_MISUSE_BKPT;+ }+ sqlite3_mutex_enter(db->mutex);+ if( zMsg ){+ sqlite3ErrorWithMsg(db, errcode, "%s", zMsg);+ }else{+ sqlite3Error(db, errcode);+ }+ rc = sqlite3ApiExit(db, rc);+ sqlite3_mutex_leave(db->mutex);+ return rc;+}+/*** Return the byte offset of the most recent error*/@@ -185329,7 +188784,7 @@ SQLITE_API int sqlite3_set_clientdata(return SQLITE_OK;}else{size_t n = strlen(zName);- p = sqlite3_malloc64( sizeof(DbClientData)+n+1 );+ p = sqlite3_malloc64( SZ_DBCLIENTDATA(n+1) );if( p==0 ){if( xDestructor ) xDestructor(pData);sqlite3_mutex_leave(db->mutex);@@ -185483,13 +188938,10 @@ SQLITE_API int sqlite3_table_column_metadata(if( zColumnName==0 ){/* Query for existence of table only */}else{- for(iCol=0; iCol<pTab->nCol; iCol++){+ iCol = sqlite3ColumnIndex(pTab, zColumnName);+ if( iCol>=0 ){pCol = &pTab->aCol[iCol];- if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){- break;- }- }- if( iCol==pTab->nCol ){+ }else{if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){iCol = pTab->iPKey;pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;@@ -185698,8 +189150,8 @@ SQLITE_API int sqlite3_test_control(int op, ...){/* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b);**** If b is true, then activate the SQLITE_FkNoAction setting. If b is- ** false then clearn that setting. If the SQLITE_FkNoAction setting is- ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if+ ** false then clear that setting. If the SQLITE_FkNoAction setting is+ ** enabled, all foreign key ON DELETE and ON UPDATE actions behave as if** they were NO ACTION, regardless of how they are defined.**** NB: One must usually run "PRAGMA writable_schema=RESET" after@@ -186022,13 +189474,15 @@ SQLITE_API int sqlite3_test_control(int op, ...){break;}- /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);+ /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, mode, tnum);**** This test control is used to create imposter tables. "db" is a pointer** to the database connection. dbName is the database name (ex: "main" or- ** "temp") which will receive the imposter. "onOff" turns imposter mode on- ** or off. "tnum" is the root page of the b-tree to which the imposter- ** table should connect.+ ** "temp") which will receive the imposter. "mode" turns imposter mode on+ ** or off. mode==0 means imposter mode is off. mode==1 means imposter mode+ ** is on. mode==2 means imposter mode is on but results in an imposter+ ** table that is read-only unless writable_schema is on. "tnum" is the+ ** root page of the b-tree to which the imposter table should connect.**** Enable imposter mode only when the schema has already been parsed. Then** run a single CREATE TABLE statement to construct the imposter table in@@ -187046,7 +190500,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){** Here, array { X } means zero or more occurrences of X, adjacent in** memory. A "position" is an index of a token in the token stream** generated by the tokenizer. Note that POS_END and POS_COLUMN occur-** in the same logical place as the position element, and act as sentinals+** in the same logical place as the position element, and act as sentinels** ending a position list array. POS_END is 0. POS_COLUMN is 1.** The positions numbers are not stored literally but rather as two more** than the difference from the prior position, or the just the position plus@@ -187265,10 +190719,20 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){#ifndef _FTSINT_H#define _FTSINT_H+/*+** Activate assert() only if SQLITE_TEST is enabled.+*/#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)# define NDEBUG 1#endif+/* #include <assert.h> */+/* #include <stdlib.h> */+/* #include <stddef.h> */+/* #include <stdio.h> */+/* #include <string.h> */+/* #include <stdarg.h> */+/* FTS3/FTS4 require virtual tables */#ifdef SQLITE_OMIT_VIRTUALTABLE# undef SQLITE_ENABLE_FTS3@@ -187711,13 +191175,6 @@ typedef sqlite3_int64 i64; /* 8-byte signed integer */*/#define UNUSED_PARAMETER(x) (void)(x)-/*-** Activate assert() only if SQLITE_TEST is enabled.-*/-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)-# define NDEBUG 1-#endif-/*** The TESTONLY macro is used to enclose variable declarations or** other bits of code that are needed to support the arguments@@ -187734,6 +191191,19 @@ typedef sqlite3_int64 i64; /* 8-byte signed integer */#define deliberate_fall_through+/*+** Macros needed to provide flexible arrays in a portable way+*/+#ifndef offsetof+# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))+#endif+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)+# define FLEXARRAY+#else+# define FLEXARRAY 1+#endif++#endif /* SQLITE_AMALGAMATION */#ifdef SQLITE_DEBUG@@ -187838,7 +191308,7 @@ struct Fts3Table {#endif#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)- /* True to disable the incremental doclist optimization. This is controled+ /* True to disable the incremental doclist optimization. This is controlled** by special insert command 'test-no-incr-doclist'. */int bNoIncrDoclist;@@ -187890,7 +191360,7 @@ struct Fts3Cursor {/*** The Fts3Cursor.eSearch member is always set to one of the following.-** Actualy, Fts3Cursor.eSearch can be greater than or equal to+** Actually, Fts3Cursor.eSearch can be greater than or equal to** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index** of the column to be searched. For example, in**@@ -187963,9 +191433,13 @@ struct Fts3Phrase {*/int nToken; /* Number of tokens in the phrase */int iColumn; /* Index of column this phrase must match */- Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */+ Fts3PhraseToken aToken[FLEXARRAY]; /* One for each token in the phrase */};+/* Size (in bytes) of an Fts3Phrase object large enough to hold N tokens */+#define SZ_FTS3PHRASE(N) \+ (offsetof(Fts3Phrase,aToken)+(N)*sizeof(Fts3PhraseToken))+/*** A tree of these objects forms the RHS of a MATCH operator.**@@ -188199,12 +191673,6 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk);# define SQLITE_CORE 1#endif-/* #include <assert.h> */-/* #include <stdlib.h> */-/* #include <stddef.h> */-/* #include <stdio.h> */-/* #include <string.h> */-/* #include <stdarg.h> *//* #include "fts3.h" */#ifndef SQLITE_CORE@@ -190543,7 +194011,7 @@ static int fts3DoclistOrMerge(** sizes of the two inputs, plus enough space for exactly one of the input** docids to grow.**- ** A symetric argument may be made if the doclists are in descending+ ** A symmetric argument may be made if the doclists are in descending** order.*/aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);@@ -192342,7 +195810,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){nDistance = iPrev - nMaxUndeferred;}- aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING);+ aOut = (char *)sqlite3Fts3MallocZero(((i64)nPoslist)+FTS3_BUFFER_PADDING);if( !aOut ){sqlite3_free(aPoslist);return SQLITE_NOMEM;@@ -192641,7 +196109,7 @@ static int incrPhraseTokenNext(**** * does not contain any deferred tokens.**-** Advance it to the next matching documnent in the database and populate+** Advance it to the next matching document in the database and populate** the Fts3Doclist.pList and nList fields.**** If there is no "next" entry and no error occurs, then *pbEof is set to@@ -193648,7 +197116,7 @@ static int fts3EvalNext(Fts3Cursor *pCsr){}/*-** Restart interation for expression pExpr so that the next call to+** Restart iteration for expression pExpr so that the next call to** fts3EvalNext() visits the first row. Do not allow incremental** loading or merging of phrase doclists for this iteration.**@@ -194840,6 +198308,23 @@ SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(*/static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);+/*+** Search buffer z[], size n, for a '"' character. Or, if enable_parenthesis+** is defined, search for '(' and ')' as well. Return the index of the first+** such character in the buffer. If there is no such character, return -1.+*/+static int findBarredChar(const char *z, int n){+ int ii;+ for(ii=0; ii<n; ii++){+ if( (z[ii]=='"')+ || (sqlite3_fts3_enable_parentheses && (z[ii]=='(' || z[ii]==')'))+ ){+ return ii;+ }+ }+ return -1;+}+/*** Extract the next token from buffer z (length n) using the tokenizer** and other information (column names etc.) in pParse. Create an Fts3Expr@@ -194864,16 +198349,9 @@ static int getNextToken(int rc;sqlite3_tokenizer_cursor *pCursor;Fts3Expr *pRet = 0;- int i = 0;- /* Set variable i to the maximum number of bytes of input to tokenize. */- for(i=0; i<n; i++){- if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;- if( z[i]=='"' ) break;- }-- *pnConsumed = i;- rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);+ *pnConsumed = n;+ rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);if( rc==SQLITE_OK ){const char *zToken;int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;@@ -194881,7 +198359,18 @@ static int getNextToken(rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);if( rc==SQLITE_OK ){- nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;+ /* Check that this tokenization did not gobble up any " characters. Or,+ ** if enable_parenthesis is true, that it did not gobble up any+ ** open or close parenthesis characters either. If it did, call+ ** getNextToken() again, but pass only that part of the input buffer+ ** up to the first such character. */+ int iBarred = findBarredChar(z, iEnd);+ if( iBarred>=0 ){+ pModule->xClose(pCursor);+ return getNextToken(pParse, iCol, z, iBarred, ppExpr, pnConsumed);+ }++ nByte = sizeof(Fts3Expr) + SZ_FTS3PHRASE(1) + nToken;pRet = (Fts3Expr *)sqlite3Fts3MallocZero(nByte);if( !pRet ){rc = SQLITE_NOMEM;@@ -194891,7 +198380,7 @@ static int getNextToken(pRet->pPhrase->nToken = 1;pRet->pPhrase->iColumn = iCol;pRet->pPhrase->aToken[0].n = nToken;- pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];+ pRet->pPhrase->aToken[0].z = (char*)&pRet->pPhrase->aToken[1];memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);if( iEnd<n && z[iEnd]=='*' ){@@ -194915,7 +198404,11 @@ static int getNextToken(}*pnConsumed = iEnd;- }else if( i && rc==SQLITE_DONE ){+ }else if( n && rc==SQLITE_DONE ){+ int iBarred = findBarredChar(z, n);+ if( iBarred>=0 ){+ *pnConsumed = iBarred;+ }rc = SQLITE_OK;}@@ -194962,9 +198455,9 @@ static int getNextString(Fts3Expr *p = 0;sqlite3_tokenizer_cursor *pCursor = 0;char *zTemp = 0;- int nTemp = 0;+ i64 nTemp = 0;- const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);+ const int nSpace = sizeof(Fts3Expr) + SZ_FTS3PHRASE(1);int nToken = 0;/* The final Fts3Expr data structure, including the Fts3Phrase,@@ -195336,7 +198829,7 @@ static int fts3ExprParse(/* The isRequirePhrase variable is set to true if a phrase or** an expression contained in parenthesis is required. If a- ** binary operator (AND, OR, NOT or NEAR) is encounted when+ ** binary operator (AND, OR, NOT or NEAR) is encountered when** isRequirePhrase is set, this is a syntax error.*/if( !isPhrase && isRequirePhrase ){@@ -195918,7 +199411,6 @@ static void fts3ExprTestCommon(}if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){- sqlite3Fts3ExprFree(pExpr);sqlite3_result_error(context, "Error parsing expression", -1);}else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){sqlite3_result_error_nomem(context);@@ -196161,7 +199653,7 @@ static void fts3HashInsertElement(}-/* Resize the hash table so that it cantains "new_size" buckets.+/* Resize the hash table so that it contains "new_size" buckets.** "new_size" must be a power of 2. The hash table might fail** to resize if sqliteMalloc() fails.**@@ -196616,7 +200108,7 @@ static int star_oh(const char *z){/*** If the word ends with zFrom and xCond() is true for the stem-** of the word that preceeds the zFrom ending, then change the+** of the word that precedes the zFrom ending, then change the** ending to zTo.**** The input word *pz and zFrom are both in reverse order. zTo@@ -198127,7 +201619,7 @@ static int fts3tokFilterMethod(fts3tokResetCursor(pCsr);if( idxNum==1 ){const char *zByte = (const char *)sqlite3_value_text(apVal[0]);- int nByte = sqlite3_value_bytes(apVal[0]);+ sqlite3_int64 nByte = sqlite3_value_bytes(apVal[0]);pCsr->zInput = sqlite3_malloc64(nByte+1);if( pCsr->zInput==0 ){rc = SQLITE_NOMEM;@@ -201957,8 +205449,8 @@ struct NodeWriter {** to an appendable b-tree segment.*/struct IncrmergeWriter {- int nLeafEst; /* Space allocated for leaf blocks */- int nWork; /* Number of leaf pages flushed */+ i64 nLeafEst; /* Space allocated for leaf blocks */+ i64 nWork; /* Number of leaf pages flushed */sqlite3_int64 iAbsLevel; /* Absolute level of input segments */int iIdx; /* Index of *output* segment in iAbsLevel+1 */sqlite3_int64 iStart; /* Block number of first allocated block */@@ -202199,7 +205691,7 @@ static int fts3IncrmergePush(**** It is assumed that the buffer associated with pNode is already large** enough to accommodate the new entry. The buffer associated with pPrev-** is extended by this function if requrired.+** is extended by this function if required.**** If an error (i.e. OOM condition) occurs, an SQLite error code is** returned. Otherwise, SQLITE_OK.@@ -202704,7 +206196,7 @@ static int fts3IncrmergeWriter(){int rc; /* Return Code */int i; /* Iterator variable */- int nLeafEst = 0; /* Blocks allocated for leaf nodes */+ i64 nLeafEst = 0; /* Blocks allocated for leaf nodes */sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */@@ -202714,7 +206206,7 @@ static int fts3IncrmergeWriter(sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);if( SQLITE_ROW==sqlite3_step(pLeafEst) ){- nLeafEst = sqlite3_column_int(pLeafEst, 0);+ nLeafEst = sqlite3_column_int64(pLeafEst, 0);}rc = sqlite3_reset(pLeafEst);}@@ -203862,7 +207354,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferToken(/*** SQLite value pRowid contains the rowid of a row that may or may not be** present in the FTS3 table. If it is, delete it and adjust the contents-** of subsiduary data structures accordingly.+** of subsidiary data structures accordingly.*/static int fts3DeleteByRowid(Fts3Table *p,@@ -204097,10 +207589,6 @@ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){/* #include <string.h> *//* #include <assert.h> */-#ifndef SQLITE_AMALGAMATION-typedef sqlite3_int64 i64;-#endif-/*** Characters that may appear in the second argument to matchinfo().*/@@ -204188,9 +207676,13 @@ struct MatchinfoBuffer {int nElem;int bGlobal; /* Set if global data is loaded */char *zMatchinfo;- u32 aMatchinfo[1];+ u32 aMI[FLEXARRAY];};+/* Size (in bytes) of a MatchinfoBuffer sufficient for N elements */+#define SZ_MATCHINFOBUFFER(N) \+ (offsetof(MatchinfoBuffer,aMI)+(((N)+1)/2)*sizeof(u64))+/*** The snippet() and offsets() functions both return text values. An instance@@ -204215,13 +207707,13 @@ struct StrBuffer {static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){MatchinfoBuffer *pRet;sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)- + sizeof(MatchinfoBuffer);+ + SZ_MATCHINFOBUFFER(1);sqlite3_int64 nStr = strlen(zMatchinfo);pRet = sqlite3Fts3MallocZero(nByte + nStr+1);if( pRet ){- pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;- pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]+ pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet;+ pRet->aMI[1+nElem] = pRet->aMI[0]+ sizeof(u32)*((int)nElem+1);pRet->nElem = (int)nElem;pRet->zMatchinfo = ((char*)pRet) + nByte;@@ -204235,10 +207727,10 @@ static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){static void fts3MIBufferFree(void *p){MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);- assert( (u32*)p==&pBuf->aMatchinfo[1]- || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]+ assert( (u32*)p==&pBuf->aMI[1]+ || (u32*)p==&pBuf->aMI[pBuf->nElem+2]);- if( (u32*)p==&pBuf->aMatchinfo[1] ){+ if( (u32*)p==&pBuf->aMI[1] ){pBuf->aRef[1] = 0;}else{pBuf->aRef[2] = 0;@@ -204255,18 +207747,18 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){if( p->aRef[1]==0 ){p->aRef[1] = 1;- aOut = &p->aMatchinfo[1];+ aOut = &p->aMI[1];xRet = fts3MIBufferFree;}else if( p->aRef[2]==0 ){p->aRef[2] = 1;- aOut = &p->aMatchinfo[p->nElem+2];+ aOut = &p->aMI[p->nElem+2];xRet = fts3MIBufferFree;}else{aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));if( aOut ){xRet = sqlite3_free;- if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));+ if( p->bGlobal ) memcpy(aOut, &p->aMI[1], p->nElem*sizeof(u32));}}@@ -204276,7 +207768,7 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){p->bGlobal = 1;- memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));+ memcpy(&p->aMI[2+p->nElem], &p->aMI[1], p->nElem*sizeof(u32));}/*@@ -204691,7 +208183,7 @@ static int fts3StringAppend(}/* If there is insufficient space allocated at StrBuffer.z, use realloc()- ** to grow the buffer until so that it is big enough to accomadate the+ ** to grow the buffer until so that it is big enough to accommodate the** appended data.*/if( pStr->n+nAppend+1>=pStr->nAlloc ){@@ -205103,16 +208595,16 @@ static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){break;case FTS3_MATCHINFO_LHITS:- nVal = pInfo->nCol * pInfo->nPhrase;+ nVal = (size_t)pInfo->nCol * pInfo->nPhrase;break;case FTS3_MATCHINFO_LHITS_BM:- nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);+ nVal = (size_t)pInfo->nPhrase * ((pInfo->nCol + 31) / 32);break;default:assert( cArg==FTS3_MATCHINFO_HITS );- nVal = pInfo->nCol * pInfo->nPhrase * 3;+ nVal = (size_t)pInfo->nCol * pInfo->nPhrase * 3;break;}@@ -206670,8 +210162,8 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){** Beginning with version 3.45.0 (circa 2024-01-01), these routines also** accept BLOB values that have JSON encoded using a binary representation** called "JSONB". The name JSONB comes from PostgreSQL, however the on-disk-** format SQLite JSONB is completely different and incompatible with-** PostgreSQL JSONB.+** format for SQLite-JSONB is completely different and incompatible with+** PostgreSQL-JSONB.**** Decoding and interpreting JSONB is still O(N) where N is the size of** the input, the same as text JSON. However, the constant of proportionality@@ -206728,7 +210220,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){**** The payload size need not be expressed in its minimal form. For example,** if the payload size is 10, the size can be expressed in any of 5 different-** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by on 0x0a byte,+** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by one 0x0a byte,** (3) (X>>4)==13 followed by 0x00 and 0x0a, (4) (X>>4)==14 followed by** 0x00 0x00 0x00 0x0a, or (5) (X>>4)==15 followed by 7 bytes of 0x00 and** a single byte of 0x0a. The shorter forms are preferred, of course, but@@ -206738,7 +210230,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){** the size when it becomes known, resulting in a non-minimal encoding.**** The value (X>>4)==15 is not actually used in the current implementation-** (as SQLite is currently unable handle BLOBs larger than about 2GB)+** (as SQLite is currently unable to handle BLOBs larger than about 2GB)** but is included in the design to allow for future enhancements.**** The payload follows the header. NULL, TRUE, and FALSE have no payload and@@ -206798,23 +210290,47 @@ static const char * const jsonbType[] = {** increase for the text-JSON parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).*/static const char jsonIsSpace[] = {- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+#ifdef SQLITE_ASCII+/*0 1 2 3 4 5 6 7 8 9 a b c d e f */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, /* 0 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */+#endif+#ifdef SQLITE_EBCDIC+/*0 1 2 3 4 5 6 7 8 9 a b c d e f */+ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, /* 0 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */+ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */++ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */+#endif+};#define jsonIsspace(x) (jsonIsSpace[(unsigned char)x])@@ -206822,7 +210338,13 @@ static const char jsonIsSpace[] = {** The set of all space characters recognized by jsonIsspace().** Useful as the second argument to strspn().*/+#ifdef SQLITE_ASCIIstatic const char jsonSpaces[] = "\011\012\015\040";+#endif+#ifdef SQLITE_EBCDIC+static const char jsonSpaces[] = "\005\045\015\100";+#endif+/*** Characters that are special to JSON. Control characters,@@ -206831,23 +210353,46 @@ static const char jsonSpaces[] = "\011\012\015\040";** it in the set of special characters.*/static const char jsonIsOk[256] = {- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,- 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1+#ifdef SQLITE_ASCII+/*0 1 2 3 4 5 6 7 8 9 a b c d e f */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */+ 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, /* 2 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 3 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, /* 5 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 7 */++ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */+#endif+#ifdef SQLITE_EBCDIC+/*0 1 2 3 4 5 6 7 8 9 a b c d e f */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, /* 3 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 5 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, /* 7 */++ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */+#endif};/* Objects */@@ -206992,7 +210537,7 @@ struct JsonParse {** Forward references**************************************************************************/static void jsonReturnStringAsBlob(JsonString*);-static int jsonFuncArgMightBeBinary(sqlite3_value *pJson);+static int jsonArgIsJsonb(sqlite3_value *pJson, JsonParse *p);static u32 jsonTranslateBlobToText(const JsonParse*,u32,JsonString*);static void jsonReturnParse(sqlite3_context*,JsonParse*);static JsonParse *jsonParseFuncArg(sqlite3_context*,sqlite3_value*,u32);@@ -207066,7 +210611,7 @@ static int jsonCacheInsert(** most-recently used entry if it isn't so already.**** The JsonParse object returned still belongs to the Cache and might-** be deleted at any moment. If the caller whants the JsonParse to+** be deleted at any moment. If the caller wants the JsonParse to** linger, it needs to increment the nPJRef reference counter.*/static JsonParse *jsonCacheSearch(@@ -207410,11 +210955,9 @@ static void jsonAppendSqlValue(break;}default: {- if( jsonFuncArgMightBeBinary(pValue) ){- JsonParse px;- memset(&px, 0, sizeof(px));- px.aBlob = (u8*)sqlite3_value_blob(pValue);- px.nBlob = sqlite3_value_bytes(pValue);+ JsonParse px;+ memset(&px, 0, sizeof(px));+ if( jsonArgIsJsonb(pValue, &px) ){jsonTranslateBlobToText(&px, 0, p);}else if( p->eErr==0 ){sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);@@ -207733,7 +211276,7 @@ static void jsonWrongNumArgs(*/static int jsonBlobExpand(JsonParse *pParse, u32 N){u8 *aNew;- u32 t;+ u64 t;assert( N>pParse->nBlobAlloc );if( pParse->nBlobAlloc==0 ){t = 100;@@ -207743,8 +211286,9 @@ static int jsonBlobExpand(JsonParse *pParse, u32 N){if( t<N ) t = N+100;aNew = sqlite3DbRealloc(pParse->db, pParse->aBlob, t);if( aNew==0 ){ pParse->oom = 1; return 1; }+ assert( t<0x7fffffff );pParse->aBlob = aNew;- pParse->nBlobAlloc = t;+ pParse->nBlobAlloc = (u32)t;return 0;}@@ -207811,7 +211355,7 @@ static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode(}-/* Append an node type byte together with the payload size and+/* Append a node type byte together with the payload size and** possibly also the payload.**** If aPayload is not NULL, then it is a pointer to the payload which@@ -207880,8 +211424,10 @@ static int jsonBlobChangePayloadSize(nExtra = 1;}else if( szType==13 ){nExtra = 2;- }else{+ }else if( szType==14 ){nExtra = 4;+ }else{+ nExtra = 8;}if( szPayload<=11 ){nNeeded = 0;@@ -208351,7 +211897,12 @@ json_parse_restart:|| c=='n' || c=='r' || c=='t'|| (c=='u' && jsonIs4Hex(&z[j+1])) ){if( opcode==JSONB_TEXT ) opcode = JSONB_TEXTJ;- }else if( c=='\'' || c=='0' || c=='v' || c=='\n'+ }else if( c=='\'' || c=='v' || c=='\n'+#ifdef SQLITE_BUG_COMPATIBLE_20250510+ || (c=='0') /* Legacy bug compatible */+#else+ || (c=='0' && !sqlite3Isdigit(z[j+1])) /* Correct implementation */+#endif|| (0xe2==(u8)c && 0x80==(u8)z[j+1]&& (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2]))|| (c=='x' && jsonIs2Hex(&z[j+1])) ){@@ -208701,10 +212252,7 @@ static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){u8 x;u32 sz;u32 n;- if( NEVER(i>pParse->nBlob) ){- *pSz = 0;- return 0;- }+ assert( i<=pParse->nBlob );x = pParse->aBlob[i]>>4;if( x<=11 ){sz = x;@@ -208741,15 +212289,15 @@ static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){*pSz = 0;return 0;}- sz = (pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) ++ sz = ((u32)pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) +(pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8];n = 9;}if( (i64)i+sz+n > pParse->nBlob&& (i64)i+sz+n > pParse->nBlob-pParse->delta){- sz = 0;- n = 0;+ *pSz = 0;+ return 0;}*pSz = sz;return n;@@ -208846,9 +212394,12 @@ static u32 jsonTranslateBlobToText(}case JSONB_TEXT:case JSONB_TEXTJ: {- jsonAppendChar(pOut, '"');- jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz);- jsonAppendChar(pOut, '"');+ if( pOut->nUsed+sz+2<=pOut->nAlloc || jsonStringGrow(pOut, sz+2)==0 ){+ pOut->zBuf[pOut->nUsed] = '"';+ memcpy(pOut->zBuf+pOut->nUsed+1,(const char*)&pParse->aBlob[i+n],sz);+ pOut->zBuf[pOut->nUsed+sz+1] = '"';+ pOut->nUsed += sz+2;+ }break;}case JSONB_TEXT5: {@@ -208891,7 +212442,7 @@ static u32 jsonTranslateBlobToText(jsonAppendChar(pOut, '\'');break;case 'v':- jsonAppendRawNZ(pOut, "\\u0009", 6);+ jsonAppendRawNZ(pOut, "\\u000b", 6);break;case 'x':if( sz2<4 ){@@ -209087,33 +212638,6 @@ static u32 jsonTranslateBlobToPrettyText(return i;}--/* Return true if the input pJson-**-** For performance reasons, this routine does not do a detailed check of the-** input BLOB to ensure that it is well-formed. Hence, false positives are-** possible. False negatives should never occur, however.-*/-static int jsonFuncArgMightBeBinary(sqlite3_value *pJson){- u32 sz, n;- const u8 *aBlob;- int nBlob;- JsonParse s;- if( sqlite3_value_type(pJson)!=SQLITE_BLOB ) return 0;- aBlob = sqlite3_value_blob(pJson);- nBlob = sqlite3_value_bytes(pJson);- if( nBlob<1 ) return 0;- if( NEVER(aBlob==0) || (aBlob[0] & 0x0f)>JSONB_OBJECT ) return 0;- memset(&s, 0, sizeof(s));- s.aBlob = (u8*)aBlob;- s.nBlob = nBlob;- n = jsonbPayloadSize(&s, 0, &sz);- if( n==0 ) return 0;- if( sz+n!=(u32)nBlob ) return 0;- if( (aBlob[0] & 0x0f)<=JSONB_FALSE && sz>0 ) return 0;- return sz+n==(u32)nBlob;-}-/*** Given that a JSONB_ARRAY object starts at offset i, return** the number of entries in that array.@@ -209146,6 +212670,82 @@ static void jsonAfterEditSizeAdjust(JsonParse *pParse, u32 iRoot){pParse->delta += jsonBlobChangePayloadSize(pParse, iRoot, sz);}+/*+** If the JSONB at aIns[0..nIns-1] can be expanded (by denormalizing the+** size field) by d bytes, then write the expansion into aOut[] and+** return true. In this way, an overwrite happens without changing the+** size of the JSONB, which reduces memcpy() operations and also make it+** faster and easier to update the B-Tree entry that contains the JSONB+** in the database.+**+** If the expansion of aIns[] by d bytes cannot be (easily) accomplished+** then return false.+**+** The d parameter is guaranteed to be between 1 and 8.+**+** This routine is an optimization. A correct answer is obtained if it+** always leaves the output unchanged and returns false.+*/+static int jsonBlobOverwrite(+ u8 *aOut, /* Overwrite here */+ const u8 *aIns, /* New content */+ u32 nIns, /* Bytes of new content */+ u32 d /* Need to expand new content by this much */+){+ u32 szPayload; /* Bytes of payload */+ u32 i; /* New header size, after expansion & a loop counter */+ u8 szHdr; /* Size of header before expansion */++ /* Lookup table for finding the upper 4 bits of the first byte of the+ ** expanded aIns[], based on the size of the expanded aIns[] header:+ **+ ** 2 3 4 5 6 7 8 9 */+ static const u8 aType[] = { 0xc0, 0xd0, 0, 0xe0, 0, 0, 0, 0xf0 };++ if( (aIns[0]&0x0f)<=2 ) return 0; /* Cannot enlarge NULL, true, false */+ switch( aIns[0]>>4 ){+ default: { /* aIns[] header size 1 */+ if( ((1<<d)&0x116)==0 ) return 0; /* d must be 1, 2, 4, or 8 */+ i = d + 1; /* New hdr sz: 2, 3, 5, or 9 */+ szHdr = 1;+ break;+ }+ case 12: { /* aIns[] header size is 2 */+ if( ((1<<d)&0x8a)==0) return 0; /* d must be 1, 3, or 7 */+ i = d + 2; /* New hdr sz: 2, 5, or 9 */+ szHdr = 2;+ break;+ }+ case 13: { /* aIns[] header size is 3 */+ if( d!=2 && d!=6 ) return 0; /* d must be 2 or 6 */+ i = d + 3; /* New hdr sz: 5 or 9 */+ szHdr = 3;+ break;+ }+ case 14: { /* aIns[] header size is 5 */+ if( d!=4 ) return 0; /* d must be 4 */+ i = 9; /* New hdr sz: 9 */+ szHdr = 5;+ break;+ }+ case 15: { /* aIns[] header size is 9 */+ return 0; /* No solution */+ }+ }+ assert( i>=2 && i<=9 && aType[i-2]!=0 );+ aOut[0] = (aIns[0] & 0x0f) | aType[i-2];+ memcpy(&aOut[i], &aIns[szHdr], nIns-szHdr);+ szPayload = nIns - szHdr;+ while( 1/*edit-by-break*/ ){+ i--;+ aOut[i] = szPayload & 0xff;+ if( i==1 ) break;+ szPayload >>= 8;+ }+ assert( (szPayload>>8)==0 );+ return 1;+}+/*** Modify the JSONB blob at pParse->aBlob by removing nDel bytes of** content beginning at iDel, and replacing them with nIns bytes of@@ -209167,6 +212767,11 @@ static void jsonBlobEdit(u32 nIns /* Bytes of content to insert */){i64 d = (i64)nIns - (i64)nDel;+ if( d<0 && d>=(-8) && aIns!=0+ && jsonBlobOverwrite(&pParse->aBlob[iDel], aIns, nIns, (int)-d)+ ){+ return;+ }if( d!=0 ){if( pParse->nBlob + d > pParse->nBlobAlloc ){jsonBlobExpand(pParse, pParse->nBlob+d);@@ -209178,7 +212783,9 @@ static void jsonBlobEdit(pParse->nBlob += d;pParse->delta += d;}- if( nIns && aIns ) memcpy(&pParse->aBlob[iDel], aIns, nIns);+ if( nIns && aIns ){+ memcpy(&pParse->aBlob[iDel], aIns, nIns);+ }}/*@@ -209263,7 +212870,21 @@ static u32 jsonUnescapeOneChar(const char *z, u32 n, u32 *piOut){case 'r': { *piOut = '\r'; return 2; }case 't': { *piOut = '\t'; return 2; }case 'v': { *piOut = '\v'; return 2; }- case '0': { *piOut = 0; return 2; }+ case '0': {+ /* JSON5 requires that the \0 escape not be followed by a digit.+ ** But SQLite did not enforce this restriction in versions 3.42.0+ ** through 3.49.2. That was a bug. But some applications might have+ ** come to depend on that bug. Use the SQLITE_BUG_COMPATIBLE_20250510+ ** option to restore the old buggy behavior. */+#ifdef SQLITE_BUG_COMPATIBLE_20250510+ /* Legacy bug-compatible behavior */+ *piOut = 0;+#else+ /* Correct behavior */+ *piOut = (n>2 && sqlite3Isdigit(z[2])) ? JSON_INVALID_CHAR : 0;+#endif+ return 2;+ }case '\'':case '"':case '/':@@ -209671,19 +213292,27 @@ static void jsonReturnTextJsonFromBlob(**** If the value is a primitive, return it as an SQL value.** If the value is an array or object, return it as either-** JSON text or the BLOB encoding, depending on the JSON_B flag-** on the userdata.+** JSON text or the BLOB encoding, depending on the eMode flag+** as follows:+**+** eMode==0 JSONB if the JSON_B flag is set in userdata or+** text if the JSON_B flag is omitted from userdata.+**+** eMode==1 Text+**+** eMode==2 JSONB*/static void jsonReturnFromBlob(JsonParse *pParse, /* Complete JSON parse tree */u32 i, /* Index of the node */sqlite3_context *pCtx, /* Return value for this function */- int textOnly /* return text JSON. Disregard user-data */+ int eMode /* Format of return: text of JSONB */){u32 n, sz;int rc;sqlite3 *db = sqlite3_context_db_handle(pCtx);+ assert( eMode>=0 && eMode<=2 );n = jsonbPayloadSize(pParse, i, &sz);if( n==0 ){sqlite3_result_error(pCtx, "malformed JSON", -1);@@ -209724,7 +213353,19 @@ static void jsonReturnFromBlob(rc = sqlite3DecOrHexToI64(z, &iRes);sqlite3DbFree(db, z);if( rc==0 ){- sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes);+ if( iRes<0 ){+ /* A hexadecimal literal with 16 significant digits and with the+ ** high-order bit set is a negative integer in SQLite (and hence+ ** iRes comes back as negative) but should be interpreted as a+ ** positive value if it occurs within JSON. The value is too+ ** large to appear as an SQLite integer so it must be converted+ ** into floating point. */+ double r;+ r = (double)*(sqlite3_uint64*)&iRes;+ sqlite3_result_double(pCtx, bNeg ? -r : r);+ }else{+ sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes);+ }}else if( rc==3 && bNeg ){sqlite3_result_int64(pCtx, SMALLEST_INT64);}else if( rc==1 ){@@ -209763,7 +213404,7 @@ static void jsonReturnFromBlob(char *zOut;u32 nOut = sz;z = (const char*)&pParse->aBlob[i+n];- zOut = sqlite3DbMallocRaw(db, nOut+1);+ zOut = sqlite3DbMallocRaw(db, ((u64)nOut)+1);if( zOut==0 ) goto returnfromblob_oom;for(iIn=iOut=0; iIn<sz; iIn++){char c = z[iIn];@@ -209802,8 +213443,14 @@ static void jsonReturnFromBlob(}case JSONB_ARRAY:case JSONB_OBJECT: {- int flags = textOnly ? 0 : SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx));- if( flags & JSON_BLOB ){+ if( eMode==0 ){+ if( (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx)) & JSON_BLOB)!=0 ){+ eMode = 2;+ }else{+ eMode = 1;+ }+ }+ if( eMode==2 ){sqlite3_result_blob(pCtx, &pParse->aBlob[i], sz+n, SQLITE_TRANSIENT);}else{jsonReturnTextJsonFromBlob(pCtx, &pParse->aBlob[i], sz+n);@@ -209858,10 +213505,7 @@ static int jsonFunctionArgToBlob(return 0;}case SQLITE_BLOB: {- if( jsonFuncArgMightBeBinary(pArg) ){- pParse->aBlob = (u8*)sqlite3_value_blob(pArg);- pParse->nBlob = sqlite3_value_bytes(pArg);- }else{+ if( !jsonArgIsJsonb(pArg, pParse) ){sqlite3_result_error(ctx, "JSON cannot hold BLOB values", -1);return 1;}@@ -209941,7 +213585,7 @@ static char *jsonBadPathError(}/* argv[0] is a BLOB that seems likely to be a JSONB. Subsequent-** arguments come in parse where each pair contains a JSON path and+** arguments come in pairs where each pair contains a JSON path and** content to insert or set at that patch. Do the updates** and return the result.**@@ -210012,27 +213656,46 @@ jsonInsertIntoBlob_patherror:/*** If pArg is a blob that seems like a JSONB blob, then initialize** p to point to that JSONB and return TRUE. If pArg does not seem like-** a JSONB blob, then return FALSE;-**-** This routine is only called if it is already known that pArg is a-** blob. The only open question is whether or not the blob appears-** to be a JSONB blob.+** a JSONB blob, then return FALSE.+**+** For small BLOBs (having no more than 7 bytes of payload) a full+** validity check is done. So for small BLOBs this routine only returns+** true if the value is guaranteed to be a valid JSONB. For larger BLOBs+** (8 byte or more of payload) only the size of the outermost element is+** checked to verify that the BLOB is superficially valid JSONB.+**+** A full JSONB validation is done on smaller BLOBs because those BLOBs might+** also be text JSON that has been incorrectly cast into a BLOB.+** (See tag-20240123-a and https://sqlite.org/forum/forumpost/012136abd5)+** If the BLOB is 9 bytes are larger, then it is not possible for the+** superficial size check done here to pass if the input is really text+** JSON so we do not need to look deeper in that case.+**+** Why we only need to do full JSONB validation for smaller BLOBs:+**+** The first byte of valid JSON text must be one of: '{', '[', '"', ' ', '\n',+** '\r', '\t', '-', or a digit '0' through '9'. Of these, only a subset+** can also be the first byte of JSONB: '{', '[', and digits '3'+** through '9'. In every one of those cases, the payload size is 7 bytes+** or less. So if we do full JSONB validation for every BLOB where the+** payload is less than 7 bytes, we will never get a false positive for+** JSONB on an input that is really text JSON.*/static int jsonArgIsJsonb(sqlite3_value *pArg, JsonParse *p){u32 n, sz = 0;+ u8 c;+ if( sqlite3_value_type(pArg)!=SQLITE_BLOB ) return 0;p->aBlob = (u8*)sqlite3_value_blob(pArg);p->nBlob = (u32)sqlite3_value_bytes(pArg);- if( p->nBlob==0 ){- p->aBlob = 0;- return 0;- }- if( NEVER(p->aBlob==0) ){- return 0;- }- if( (p->aBlob[0] & 0x0f)<=JSONB_OBJECT+ if( p->nBlob>0+ && ALWAYS(p->aBlob!=0)+ && ((c = p->aBlob[0]) & 0x0f)<=JSONB_OBJECT&& (n = jsonbPayloadSize(p, 0, &sz))>0&& sz+n==p->nBlob- && ((p->aBlob[0] & 0x0f)>JSONB_FALSE || sz==0)+ && ((c & 0x0f)>JSONB_FALSE || sz==0)+ && (sz>7+ || (c!=0x7b && c!=0x5b && !sqlite3Isdigit(c))+ || jsonbValidityCheck(p, 0, p->nBlob, 1)==0)){return 1;}@@ -210110,7 +213773,7 @@ rebuild_from_cache:** JSON functions were suppose to work. From the beginning, blob was** reserved for expansion and a blob value should have raised an error.** But it did not, due to a bug. And many applications came to depend- ** upon this buggy behavior, espeically when using the CLI and reading+ ** upon this buggy behavior, especially when using the CLI and reading** JSON text using readfile(), which returns a blob. For this reason** we will continue to support the bug moving forward.** See for example https://sqlite.org/forum/forumpost/012136abd5292b8d@@ -211125,21 +214788,17 @@ static void jsonValidFunc(return;}case SQLITE_BLOB: {- if( jsonFuncArgMightBeBinary(argv[0]) ){+ JsonParse py;+ memset(&py, 0, sizeof(py));+ if( jsonArgIsJsonb(argv[0], &py) ){if( flags & 0x04 ){/* Superficial checking only - accomplished by the- ** jsonFuncArgMightBeBinary() call above. */+ ** jsonArgIsJsonb() call above. */res = 1;}else if( flags & 0x08 ){/* Strict checking. Check by translating BLOB->TEXT->BLOB. If** no errors occur, call that a "strict check". */- JsonParse px;- u32 iErr;- memset(&px, 0, sizeof(px));- px.aBlob = (u8*)sqlite3_value_blob(argv[0]);- px.nBlob = sqlite3_value_bytes(argv[0]);- iErr = jsonbValidityCheck(&px, 0, px.nBlob, 1);- res = iErr==0;+ res = 0==jsonbValidityCheck(&py, 0, py.nBlob, 1);}break;}@@ -211197,9 +214856,7 @@ static void jsonErrorFunc(UNUSED_PARAMETER(argc);memset(&s, 0, sizeof(s));s.db = sqlite3_context_db_handle(ctx);- if( jsonFuncArgMightBeBinary(argv[0]) ){- s.aBlob = (u8*)sqlite3_value_blob(argv[0]);- s.nBlob = sqlite3_value_bytes(argv[0]);+ if( jsonArgIsJsonb(argv[0], &s) ){iErrPos = (i64)jsonbValidityCheck(&s, 0, s.nBlob, 1);}else{s.zJson = (char*)sqlite3_value_text(argv[0]);@@ -211360,18 +215017,20 @@ static void jsonObjectStep(UNUSED_PARAMETER(argc);pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));if( pStr ){+ z = (const char*)sqlite3_value_text(argv[0]);+ n = sqlite3Strlen30(z);if( pStr->zBuf==0 ){jsonStringInit(pStr, ctx);jsonAppendChar(pStr, '{');- }else if( pStr->nUsed>1 ){+ }else if( pStr->nUsed>1 && z!=0 ){jsonAppendChar(pStr, ',');}pStr->pCtx = ctx;- z = (const char*)sqlite3_value_text(argv[0]);- n = sqlite3Strlen30(z);- jsonAppendString(pStr, z, n);- jsonAppendChar(pStr, ':');- jsonAppendSqlValue(pStr, argv[1]);+ if( z!=0 ){+ jsonAppendString(pStr, z, n);+ jsonAppendChar(pStr, ':');+ jsonAppendSqlValue(pStr, argv[1]);+ }}}static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){@@ -211438,6 +215097,7 @@ struct JsonEachCursor {u32 nRoot; /* Size of the root path in bytes */u8 eType; /* Type of the container for element i */u8 bRecursive; /* True for json_tree(). False for json_each() */+ u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */u32 nParent; /* Current nesting depth */u32 nParentAlloc; /* Space allocated for aParent[] */JsonParent *aParent; /* Parent elements of i */@@ -211449,6 +215109,8 @@ typedef struct JsonEachConnection JsonEachConnection;struct JsonEachConnection {sqlite3_vtab base; /* Base class - must be first */sqlite3 *db; /* Database connection */+ u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */+ u8 bRecursive; /* True for json_tree(). False for json_each() */};@@ -211491,6 +215153,8 @@ static int jsonEachConnect(if( pNew==0 ) return SQLITE_NOMEM;sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);pNew->db = db;+ pNew->eMode = argv[0][4]=='b' ? 2 : 1;+ pNew->bRecursive = argv[0][4+pNew->eMode]=='t';}return rc;}@@ -211502,8 +215166,8 @@ static int jsonEachDisconnect(sqlite3_vtab *pVtab){return SQLITE_OK;}-/* constructor for a JsonEachCursor object for json_each(). */-static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){+/* constructor for a JsonEachCursor object for json_each()/json_tree(). */+static int jsonEachOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){JsonEachConnection *pVtab = (JsonEachConnection*)p;JsonEachCursor *pCur;@@ -211511,21 +215175,13 @@ static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){pCur = sqlite3DbMallocZero(pVtab->db, sizeof(*pCur));if( pCur==0 ) return SQLITE_NOMEM;pCur->db = pVtab->db;+ pCur->eMode = pVtab->eMode;+ pCur->bRecursive = pVtab->bRecursive;jsonStringZero(&pCur->path);*ppCursor = &pCur->base;return SQLITE_OK;}-/* constructor for a JsonEachCursor object for json_tree(). */-static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){- int rc = jsonEachOpenEach(p, ppCursor);- if( rc==SQLITE_OK ){- JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;- pCur->bRecursive = 1;- }- return rc;-}-/* Reset a JsonEachCursor back to its original state. Free any memory** held. */static void jsonEachCursorReset(JsonEachCursor *p){@@ -211730,7 +215386,7 @@ static int jsonEachColumn(}case JEACH_VALUE: {u32 i = jsonSkipLabel(p);- jsonReturnFromBlob(&p->sParse, i, ctx, 1);+ jsonReturnFromBlob(&p->sParse, i, ctx, p->eMode);if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY ){sqlite3_result_subtype(ctx, JSON_SUBTYPE);}@@ -211884,9 +215540,8 @@ static int jsonEachFilter(memset(&p->sParse, 0, sizeof(p->sParse));p->sParse.nJPRef = 1;p->sParse.db = p->db;- if( jsonFuncArgMightBeBinary(argv[0]) ){- p->sParse.nBlob = sqlite3_value_bytes(argv[0]);- p->sParse.aBlob = (u8*)sqlite3_value_blob(argv[0]);+ if( jsonArgIsJsonb(argv[0], &p->sParse) ){+ /* We have JSONB */}else{p->sParse.zJson = (char*)sqlite3_value_text(argv[0]);p->sParse.nJson = sqlite3_value_bytes(argv[0]);@@ -211975,36 +215630,7 @@ static sqlite3_module jsonEachModule = {jsonEachBestIndex, /* xBestIndex */jsonEachDisconnect, /* xDisconnect */0, /* xDestroy */- jsonEachOpenEach, /* xOpen - open a cursor */- jsonEachClose, /* xClose - close a cursor */- jsonEachFilter, /* xFilter - configure scan constraints */- jsonEachNext, /* xNext - advance a cursor */- jsonEachEof, /* xEof - check for end of scan */- jsonEachColumn, /* xColumn - read data */- jsonEachRowid, /* xRowid - read data */- 0, /* xUpdate */- 0, /* xBegin */- 0, /* xSync */- 0, /* xCommit */- 0, /* xRollback */- 0, /* xFindMethod */- 0, /* xRename */- 0, /* xSavepoint */- 0, /* xRelease */- 0, /* xRollbackTo */- 0, /* xShadowName */- 0 /* xIntegrity */-};--/* The methods of the json_tree virtual table. */-static sqlite3_module jsonTreeModule = {- 0, /* iVersion */- 0, /* xCreate */- jsonEachConnect, /* xConnect */- jsonEachBestIndex, /* xBestIndex */- jsonEachDisconnect, /* xDisconnect */- 0, /* xDestroy */- jsonEachOpenTree, /* xOpen - open a cursor */+ jsonEachOpen, /* xOpen - open a cursor */jsonEachClose, /* xClose - close a cursor */jsonEachFilter, /* xFilter - configure scan constraints */jsonEachNext, /* xNext - advance a cursor */@@ -212093,22 +215719,21 @@ SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON)/*-** Register the JSON table-valued functions+** Register the JSON table-valued function named zName and return a+** pointer to its Module object. Return NULL if something goes wrong.*/-SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){- int rc = SQLITE_OK;- static const struct {- const char *zName;- sqlite3_module *pModule;- } aMod[] = {- { "json_each", &jsonEachModule },- { "json_tree", &jsonTreeModule },- };+SQLITE_PRIVATE Module *sqlite3JsonVtabRegister(sqlite3 *db, const char *zName){unsigned int i;- for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){- rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);+ static const char *azModule[] = {+ "json_each", "json_tree", "jsonb_each", "jsonb_tree"+ };+ assert( sqlite3HashFind(&db->aModule, zName)==0 );+ for(i=0; i<sizeof(azModule)/sizeof(azModule[0]); i++){+ if( sqlite3StrICmp(azModule[i],zName)==0 ){+ return sqlite3VtabCreateModule(db, azModule[i], &jsonEachModule, 0, 0);+ }}- return rc;+ return 0;}#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */@@ -212178,7 +215803,9 @@ SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){#else/* #include "sqlite3.h" */#endif-SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */+SQLITE_PRIVATE sqlite3_int64 sqlite3GetToken(const unsigned char*,int*); /* In SQLite core */++/* #include <stddef.h> *//*** If building separately, we will need some setup that is normally@@ -212210,6 +215837,14 @@ typedef unsigned int u32;# define ALWAYS(X) (X)# define NEVER(X) (X)#endif+#ifndef offsetof+# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))+#endif+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)+# define FLEXARRAY+#else+# define FLEXARRAY 1+#endif#endif /* !defined(SQLITE_AMALGAMATION) *//* Macro to check for 4-byte alignment. Only used inside of assert() */@@ -212530,9 +216165,13 @@ struct RtreeMatchArg {RtreeGeomCallback cb; /* Info about the callback functions */int nParam; /* Number of parameters to the SQL function */sqlite3_value **apSqlParam; /* Original SQL parameter values */- RtreeDValue aParam[1]; /* Values for parameters to the SQL function */+ RtreeDValue aParam[FLEXARRAY]; /* Values for parameters to the SQL function */};+/* Size of an RtreeMatchArg object with N parameters */+#define SZ_RTREEMATCHARG(N) \+ (offsetof(RtreeMatchArg,aParam)+(N)*sizeof(RtreeDValue))+#ifndef MAX# define MAX(x,y) ((x) < (y) ? (y) : (x))#endif@@ -213237,6 +216876,12 @@ static void resetCursor(RtreeCursor *pCsr){pCsr->base.pVtab = (sqlite3_vtab*)pRtree;pCsr->pReadAux = pStmt;+ /* The following will only fail if the previous sqlite3_step() call failed,+ ** in which case the error has already been caught. This statement never+ ** encounters an error within an sqlite3_column_xxx() function, as it+ ** calls sqlite3_column_value(), which does not use malloc(). So it is safe+ ** to ignore the error code here. */+ sqlite3_reset(pStmt);}/*@@ -214221,7 +217866,7 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){}/*-** Return the N-dimensional volumn of the cell stored in *p.+** Return the N-dimensional volume of the cell stored in *p.*/static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){RtreeDValue area = (RtreeDValue)1;@@ -215871,7 +219516,7 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){if( node.zData==0 ) return;nData = sqlite3_value_bytes(apArg[1]);if( nData<4 ) return;- if( nData<NCELL(&node)*tree.nBytesPerCell ) return;+ if( nData<4+NCELL(&node)*tree.nBytesPerCell ) return;pOut = sqlite3_str_new(0);for(ii=0; ii<NCELL(&node); ii++){@@ -215987,7 +219632,7 @@ static sqlite3_stmt *rtreeCheckPrepare(/*** The second and subsequent arguments to this function are a printf()** style format string and arguments. This function formats the string and-** appends it to the report being accumuated in pCheck.+** appends it to the report being accumulated in pCheck.*/static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){va_list ap;@@ -217175,7 +220820,7 @@ static void geopolyBBoxFinal(** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).** Returns:**-** +2 x0,y0 is on the line segement+** +2 x0,y0 is on the line segment**** +1 x0,y0 is beneath line segment**@@ -217281,7 +220926,7 @@ static void geopolyWithinFunc(sqlite3_free(p2);}-/* Objects used by the overlap algorihm. */+/* Objects used by the overlap algorithm. */typedef struct GeoEvent GeoEvent;typedef struct GeoSegment GeoSegment;typedef struct GeoOverlap GeoOverlap;@@ -218328,8 +221973,7 @@ static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){sqlite3_int64 nBlob;int memErr = 0;- nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)- + nArg*sizeof(sqlite3_value*);+ nBlob = SZ_RTREEMATCHARG(nArg) + nArg*sizeof(sqlite3_value*);pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);if( !pBlob ){sqlite3_result_error_nomem(ctx);@@ -219424,7 +223068,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(**** "RBU" stands for "Resumable Bulk Update". As in a large database update** transmitted via a wireless network to a mobile device. A transaction-** applied using this extension is hence refered to as an "RBU update".+** applied using this extension is hence referred to as an "RBU update".****** LIMITATIONS@@ -219721,7 +223365,7 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open(** the next call to sqlite3rbu_vacuum() opens a handle that starts a** new RBU vacuum operation.**-** As with sqlite3rbu_open(), Zipvfs users should rever to the comment+** As with sqlite3rbu_open(), Zipvfs users should refer to the comment** describing the sqlite3rbu_create_vfs() API function below for** a description of the complications associated with using RBU with** zipvfs databases.@@ -219817,7 +223461,7 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);**** If the RBU update has been completely applied, mark the RBU database** as fully applied. Otherwise, assuming no error has occurred, save the-** current state of the RBU update appliation to the RBU database.+** current state of the RBU update application to the RBU database.**** If an error has already occurred as part of an sqlite3rbu_step()** or sqlite3rbu_open() call, or if one occurs within this function, an@@ -220544,7 +224188,7 @@ static int rbuDeltaApply(/* ERROR: copy exceeds output file size */return -1;}- if( (int)(ofst+cnt) > lenSrc ){+ if( (u64)ofst+(u64)cnt > (u64)lenSrc ){/* ERROR: copy extends past end of input */return -1;}@@ -224743,7 +228387,7 @@ static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){/* If this is an RBU vacuum operation and this is the target database,** pretend that it has at least one page. Otherwise, SQLite will not- ** check for the existance of a *-wal file. rbuVfsRead() contains+ ** check for the existence of a *-wal file. rbuVfsRead() contains** similar logic. */if( rc==SQLITE_OK && *pSize==0&& p->pRbu && rbuIsVacuum(p->pRbu)@@ -226326,8 +229970,8 @@ typedef struct DbpageCursor DbpageCursor;struct DbpageCursor {sqlite3_vtab_cursor base; /* Base class. Must be first */- int pgno; /* Current page number */- int mxPgno; /* Last page to visit on this scan */+ Pgno pgno; /* Current page number */+ Pgno mxPgno; /* Last page to visit on this scan */Pager *pPager; /* Pager being read/written */DbPage *pPage1; /* Page 1 of the database */int iDb; /* Index of database to analyze */@@ -226464,7 +230108,7 @@ static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){}else{memset(pCsr, 0, sizeof(DbpageCursor));pCsr->base.pVtab = pVTab;- pCsr->pgno = -1;+ pCsr->pgno = 0;}*ppCursor = (sqlite3_vtab_cursor *)pCsr;@@ -226517,7 +230161,8 @@ static int dbpageFilter(sqlite3 *db = pTab->db;Btree *pBt;- (void)idxStr;+ UNUSED_PARAMETER(idxStr);+ UNUSED_PARAMETER(argc);/* Default setting is no rows of result */pCsr->pgno = 1;@@ -226563,12 +230208,12 @@ static int dbpageColumn(int rc = SQLITE_OK;switch( i ){case 0: { /* pgno */- sqlite3_result_int(ctx, pCsr->pgno);+ sqlite3_result_int64(ctx, (sqlite3_int64)pCsr->pgno);break;}case 1: { /* data */DbPage *pDbPage = 0;- if( pCsr->pgno==((PENDING_BYTE/pCsr->szPage)+1) ){+ if( pCsr->pgno==(Pgno)((PENDING_BYTE/pCsr->szPage)+1) ){/* The pending byte page. Assume it is zeroed out. Attempting to** request this page from the page is an SQLITE_CORRUPT error. */sqlite3_result_zeroblob(ctx, pCsr->szPage);@@ -226642,10 +230287,10 @@ static int dbpageUpdate(goto update_fail;}if( sqlite3_value_type(argv[0])==SQLITE_NULL ){- pgno = (Pgno)sqlite3_value_int(argv[2]);+ pgno = (Pgno)sqlite3_value_int64(argv[2]);isInsert = 1;}else{- pgno = sqlite3_value_int(argv[0]);+ pgno = (Pgno)sqlite3_value_int64(argv[0]);if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){zErr = "cannot insert";goto update_fail;@@ -226675,8 +230320,8 @@ static int dbpageUpdate(/* "INSERT INTO dbpage($PGNO,NULL)" causes page number $PGNO and** all subsequent pages to be deleted. */pTab->iDbTrunc = iDb;- pgno--;- pTab->pgnoTrunc = pgno;+ pTab->pgnoTrunc = pgno-1;+ pgno = 1;}else{zErr = "bad page value";goto update_fail;@@ -226697,7 +230342,8 @@ static int dbpageUpdate(memcpy(aPage, pData, szPage);pTab->pgnoTrunc = 0;}- }else{+ }+ if( rc!=SQLITE_OK ){pTab->pgnoTrunc = 0;}sqlite3PagerUnref(pDbPage);@@ -226780,6 +230426,536 @@ SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }#endif /* SQLITE_ENABLE_DBSTAT_VTAB *//************** End of dbpage.c **********************************************/+/************** Begin file carray.c ******************************************/+/*+** 2016-06-29+**+** The author disclaims copyright to this source code. In place of+** a legal notice, here is a blessing:+**+** May you do good and not evil.+** May you find forgiveness for yourself and forgive others.+** May you share freely, never taking more than you give.+**+*************************************************************************+**+** This file implements a table-valued-function that+** returns the values in a C-language array.+** Examples:+**+** SELECT * FROM carray($ptr,5)+**+** The query above returns 5 integers contained in a C-language array+** at the address $ptr. $ptr is a pointer to the array of integers.+** The pointer value must be assigned to $ptr using the+** sqlite3_bind_pointer() interface with a pointer type of "carray".+** For example:+**+** static int aX[] = { 53, 9, 17, 2231, 4, 99 };+** int i = sqlite3_bind_parameter_index(pStmt, "$ptr");+** sqlite3_bind_pointer(pStmt, i, aX, "carray", 0);+**+** There is an optional third parameter to determine the datatype of+** the C-language array. Allowed values of the third parameter are+** 'int32', 'int64', 'double', 'char*', 'struct iovec'. Example:+**+** SELECT * FROM carray($ptr,10,'char*');+**+** The default value of the third parameter is 'int32'.+**+** HOW IT WORKS+**+** The carray "function" is really a virtual table with the+** following schema:+**+** CREATE TABLE carray(+** value,+** pointer HIDDEN,+** count HIDDEN,+** ctype TEXT HIDDEN+** );+**+** If the hidden columns "pointer" and "count" are unconstrained, then+** the virtual table has no rows. Otherwise, the virtual table interprets+** the integer value of "pointer" as a pointer to the array and "count"+** as the number of elements in the array. The virtual table steps through+** the array, element by element.+*/+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY)+/* #include "sqliteInt.h" */+#if defined(_WIN32) || defined(__RTP__) || defined(_WRS_KERNEL)+ struct iovec {+ void *iov_base;+ size_t iov_len;+ };+#else+# include <sys/uio.h>+#endif++/*+** Names of allowed datatypes+*/+static const char *azCarrayType[] = {+ "int32", "int64", "double", "char*", "struct iovec"+};++/*+** Structure used to hold the sqlite3_carray_bind() information+*/+typedef struct carray_bind carray_bind;+struct carray_bind {+ void *aData; /* The data */+ int nData; /* Number of elements */+ int mFlags; /* Control flags */+ void (*xDel)(void*); /* Destructor for aData */+};+++/* carray_cursor is a subclass of sqlite3_vtab_cursor which will+** serve as the underlying representation of a cursor that scans+** over rows of the result+*/+typedef struct carray_cursor carray_cursor;+struct carray_cursor {+ sqlite3_vtab_cursor base; /* Base class - must be first */+ sqlite3_int64 iRowid; /* The rowid */+ void *pPtr; /* Pointer to the array of values */+ sqlite3_int64 iCnt; /* Number of integers in the array */+ unsigned char eType; /* One of the CARRAY_type values */+};++/*+** The carrayConnect() method is invoked to create a new+** carray_vtab that describes the carray virtual table.+**+** Think of this routine as the constructor for carray_vtab objects.+**+** All this routine needs to do is:+**+** (1) Allocate the carray_vtab object and initialize all fields.+**+** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the+** result set of queries against carray will look like.+*/+static int carrayConnect(+ sqlite3 *db,+ void *pAux,+ int argc, const char *const*argv,+ sqlite3_vtab **ppVtab,+ char **pzErr+){+ sqlite3_vtab *pNew;+ int rc;++/* Column numbers */+#define CARRAY_COLUMN_VALUE 0+#define CARRAY_COLUMN_POINTER 1+#define CARRAY_COLUMN_COUNT 2+#define CARRAY_COLUMN_CTYPE 3++ rc = sqlite3_declare_vtab(db,+ "CREATE TABLE x(value,pointer hidden,count hidden,ctype hidden)");+ if( rc==SQLITE_OK ){+ pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );+ if( pNew==0 ) return SQLITE_NOMEM;+ memset(pNew, 0, sizeof(*pNew));+ }+ return rc;+}++/*+** This method is the destructor for carray_cursor objects.+*/+static int carrayDisconnect(sqlite3_vtab *pVtab){+ sqlite3_free(pVtab);+ return SQLITE_OK;+}++/*+** Constructor for a new carray_cursor object.+*/+static int carrayOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){+ carray_cursor *pCur;+ pCur = sqlite3_malloc( sizeof(*pCur) );+ if( pCur==0 ) return SQLITE_NOMEM;+ memset(pCur, 0, sizeof(*pCur));+ *ppCursor = &pCur->base;+ return SQLITE_OK;+}++/*+** Destructor for a carray_cursor.+*/+static int carrayClose(sqlite3_vtab_cursor *cur){+ sqlite3_free(cur);+ return SQLITE_OK;+}+++/*+** Advance a carray_cursor to its next row of output.+*/+static int carrayNext(sqlite3_vtab_cursor *cur){+ carray_cursor *pCur = (carray_cursor*)cur;+ pCur->iRowid++;+ return SQLITE_OK;+}++/*+** Return values of columns for the row at which the carray_cursor+** is currently pointing.+*/+static int carrayColumn(+ sqlite3_vtab_cursor *cur, /* The cursor */+ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */+ int i /* Which column to return */+){+ carray_cursor *pCur = (carray_cursor*)cur;+ sqlite3_int64 x = 0;+ switch( i ){+ case CARRAY_COLUMN_POINTER: return SQLITE_OK;+ case CARRAY_COLUMN_COUNT: x = pCur->iCnt; break;+ case CARRAY_COLUMN_CTYPE: {+ sqlite3_result_text(ctx, azCarrayType[pCur->eType], -1, SQLITE_STATIC);+ return SQLITE_OK;+ }+ default: {+ switch( pCur->eType ){+ case CARRAY_INT32: {+ int *p = (int*)pCur->pPtr;+ sqlite3_result_int(ctx, p[pCur->iRowid-1]);+ return SQLITE_OK;+ }+ case CARRAY_INT64: {+ sqlite3_int64 *p = (sqlite3_int64*)pCur->pPtr;+ sqlite3_result_int64(ctx, p[pCur->iRowid-1]);+ return SQLITE_OK;+ }+ case CARRAY_DOUBLE: {+ double *p = (double*)pCur->pPtr;+ sqlite3_result_double(ctx, p[pCur->iRowid-1]);+ return SQLITE_OK;+ }+ case CARRAY_TEXT: {+ const char **p = (const char**)pCur->pPtr;+ sqlite3_result_text(ctx, p[pCur->iRowid-1], -1, SQLITE_TRANSIENT);+ return SQLITE_OK;+ }+ default: {+ const struct iovec *p = (struct iovec*)pCur->pPtr;+ assert( pCur->eType==CARRAY_BLOB );+ sqlite3_result_blob(ctx, p[pCur->iRowid-1].iov_base,+ (int)p[pCur->iRowid-1].iov_len, SQLITE_TRANSIENT);+ return SQLITE_OK;+ }+ }+ }+ }+ sqlite3_result_int64(ctx, x);+ return SQLITE_OK;+}++/*+** Return the rowid for the current row. In this implementation, the+** rowid is the same as the output value.+*/+static int carrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){+ carray_cursor *pCur = (carray_cursor*)cur;+ *pRowid = pCur->iRowid;+ return SQLITE_OK;+}++/*+** Return TRUE if the cursor has been moved off of the last+** row of output.+*/+static int carrayEof(sqlite3_vtab_cursor *cur){+ carray_cursor *pCur = (carray_cursor*)cur;+ return pCur->iRowid>pCur->iCnt;+}++/*+** This method is called to "rewind" the carray_cursor object back+** to the first row of output.+*/+static int carrayFilter(+ sqlite3_vtab_cursor *pVtabCursor,+ int idxNum, const char *idxStr,+ int argc, sqlite3_value **argv+){+ carray_cursor *pCur = (carray_cursor *)pVtabCursor;+ pCur->pPtr = 0;+ pCur->iCnt = 0;+ switch( idxNum ){+ case 1: {+ carray_bind *pBind = sqlite3_value_pointer(argv[0], "carray-bind");+ if( pBind==0 ) break;+ pCur->pPtr = pBind->aData;+ pCur->iCnt = pBind->nData;+ pCur->eType = pBind->mFlags & 0x07;+ break;+ }+ case 2:+ case 3: {+ pCur->pPtr = sqlite3_value_pointer(argv[0], "carray");+ pCur->iCnt = pCur->pPtr ? sqlite3_value_int64(argv[1]) : 0;+ if( idxNum<3 ){+ pCur->eType = CARRAY_INT32;+ }else{+ unsigned char i;+ const char *zType = (const char*)sqlite3_value_text(argv[2]);+ for(i=0; i<sizeof(azCarrayType)/sizeof(azCarrayType[0]); i++){+ if( sqlite3_stricmp(zType, azCarrayType[i])==0 ) break;+ }+ if( i>=sizeof(azCarrayType)/sizeof(azCarrayType[0]) ){+ pVtabCursor->pVtab->zErrMsg = sqlite3_mprintf(+ "unknown datatype: %Q", zType);+ return SQLITE_ERROR;+ }else{+ pCur->eType = i;+ }+ }+ break;+ }+ }+ pCur->iRowid = 1;+ return SQLITE_OK;+}++/*+** SQLite will invoke this method one or more times while planning a query+** that uses the carray virtual table. This routine needs to create+** a query plan for each invocation and compute an estimated cost for that+** plan.+**+** In this implementation idxNum is used to represent the+** query plan. idxStr is unused.+**+** idxNum is:+**+** 1 If only the pointer= constraint exists. In this case, the+** parameter must be bound using sqlite3_carray_bind().+**+** 2 if the pointer= and count= constraints exist.+**+** 3 if the ctype= constraint also exists.+**+** idxNum is 0 otherwise and carray becomes an empty table.+*/+static int carrayBestIndex(+ sqlite3_vtab *tab,+ sqlite3_index_info *pIdxInfo+){+ int i; /* Loop over constraints */+ int ptrIdx = -1; /* Index of the pointer= constraint, or -1 if none */+ int cntIdx = -1; /* Index of the count= constraint, or -1 if none */+ int ctypeIdx = -1; /* Index of the ctype= constraint, or -1 if none */+ unsigned seen = 0; /* Bitmask of == constrainted columns */++ const struct sqlite3_index_constraint *pConstraint;+ pConstraint = pIdxInfo->aConstraint;+ for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){+ if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;+ if( pConstraint->iColumn>=0 ) seen |= 1 << pConstraint->iColumn;+ if( pConstraint->usable==0 ) continue;+ switch( pConstraint->iColumn ){+ case CARRAY_COLUMN_POINTER:+ ptrIdx = i;+ break;+ case CARRAY_COLUMN_COUNT:+ cntIdx = i;+ break;+ case CARRAY_COLUMN_CTYPE:+ ctypeIdx = i;+ break;+ }+ }+ if( ptrIdx>=0 ){+ pIdxInfo->aConstraintUsage[ptrIdx].argvIndex = 1;+ pIdxInfo->aConstraintUsage[ptrIdx].omit = 1;+ pIdxInfo->estimatedCost = (double)1;+ pIdxInfo->estimatedRows = 100;+ pIdxInfo->idxNum = 1;+ if( cntIdx>=0 ){+ pIdxInfo->aConstraintUsage[cntIdx].argvIndex = 2;+ pIdxInfo->aConstraintUsage[cntIdx].omit = 1;+ pIdxInfo->idxNum = 2;+ if( ctypeIdx>=0 ){+ pIdxInfo->aConstraintUsage[ctypeIdx].argvIndex = 3;+ pIdxInfo->aConstraintUsage[ctypeIdx].omit = 1;+ pIdxInfo->idxNum = 3;+ }else if( seen & (1<<CARRAY_COLUMN_CTYPE) ){+ /* In a three-argument carray(), we need to know the value of all+ ** three arguments */+ return SQLITE_CONSTRAINT;+ }+ }else if( seen & (1<<CARRAY_COLUMN_COUNT) ){+ /* In a two-argument carray(), we need to know the value of both+ ** arguments */+ return SQLITE_CONSTRAINT;+ }+ }else{+ pIdxInfo->estimatedCost = (double)2147483647;+ pIdxInfo->estimatedRows = 2147483647;+ pIdxInfo->idxNum = 0;+ }+ return SQLITE_OK;+}++/*+** This following structure defines all the methods for the+** carray virtual table.+*/+static sqlite3_module carrayModule = {+ 0, /* iVersion */+ 0, /* xCreate */+ carrayConnect, /* xConnect */+ carrayBestIndex, /* xBestIndex */+ carrayDisconnect, /* xDisconnect */+ 0, /* xDestroy */+ carrayOpen, /* xOpen - open a cursor */+ carrayClose, /* xClose - close a cursor */+ carrayFilter, /* xFilter - configure scan constraints */+ carrayNext, /* xNext - advance a cursor */+ carrayEof, /* xEof - check for end of scan */+ carrayColumn, /* xColumn - read data */+ carrayRowid, /* xRowid - read data */+ 0, /* xUpdate */+ 0, /* xBegin */+ 0, /* xSync */+ 0, /* xCommit */+ 0, /* xRollback */+ 0, /* xFindMethod */+ 0, /* xRename */+ 0, /* xSavepoint */+ 0, /* xRelease */+ 0, /* xRollbackTo */+ 0, /* xShadow */+ 0 /* xIntegrity */+};++/*+** Destructor for the carray_bind object+*/+static void carrayBindDel(void *pPtr){+ carray_bind *p = (carray_bind*)pPtr;+ if( p->xDel!=SQLITE_STATIC ){+ p->xDel(p->aData);+ }+ sqlite3_free(p);+}++/*+** Invoke this interface in order to bind to the single-argument+** version of CARRAY().+*/+SQLITE_API int sqlite3_carray_bind(+ sqlite3_stmt *pStmt,+ int idx,+ void *aData,+ int nData,+ int mFlags,+ void (*xDestroy)(void*)+){+ carray_bind *pNew = 0;+ int i;+ int rc = SQLITE_OK;++ /* Ensure that the mFlags value is acceptable. */+ assert( CARRAY_INT32==0 && CARRAY_INT64==1 && CARRAY_DOUBLE==2 );+ assert( CARRAY_TEXT==3 && CARRAY_BLOB==4 );+ if( mFlags<CARRAY_INT32 || mFlags>CARRAY_BLOB ){+ rc = SQLITE_ERROR;+ goto carray_bind_error;+ }++ pNew = sqlite3_malloc64(sizeof(*pNew));+ if( pNew==0 ){+ rc = SQLITE_NOMEM;+ goto carray_bind_error;+ }++ pNew->nData = nData;+ pNew->mFlags = mFlags;+ if( xDestroy==SQLITE_TRANSIENT ){+ sqlite3_int64 sz = nData;+ switch( mFlags ){+ case CARRAY_INT32: sz *= 4; break;+ case CARRAY_INT64: sz *= 8; break;+ case CARRAY_DOUBLE: sz *= 8; break;+ case CARRAY_TEXT: sz *= sizeof(char*); break;+ default: sz *= sizeof(struct iovec); break;+ }+ if( mFlags==CARRAY_TEXT ){+ for(i=0; i<nData; i++){+ const char *z = ((char**)aData)[i];+ if( z ) sz += strlen(z) + 1;+ }+ }else if( mFlags==CARRAY_BLOB ){+ for(i=0; i<nData; i++){+ sz += ((struct iovec*)aData)[i].iov_len;+ }+ }++ pNew->aData = sqlite3_malloc64( sz );+ if( pNew->aData==0 ){+ rc = SQLITE_NOMEM;+ goto carray_bind_error;+ }++ if( mFlags==CARRAY_TEXT ){+ char **az = (char**)pNew->aData;+ char *z = (char*)&az[nData];+ for(i=0; i<nData; i++){+ const char *zData = ((char**)aData)[i];+ sqlite3_int64 n;+ if( zData==0 ){+ az[i] = 0;+ continue;+ }+ az[i] = z;+ n = strlen(zData);+ memcpy(z, zData, n+1);+ z += n+1;+ }+ }else if( mFlags==CARRAY_BLOB ){+ struct iovec *p = (struct iovec*)pNew->aData;+ unsigned char *z = (unsigned char*)&p[nData];+ for(i=0; i<nData; i++){+ size_t n = ((struct iovec*)aData)[i].iov_len;+ p[i].iov_len = n;+ p[i].iov_base = z;+ z += n;+ memcpy(p[i].iov_base, ((struct iovec*)aData)[i].iov_base, n);+ }+ }else{+ memcpy(pNew->aData, aData, sz);+ }+ pNew->xDel = sqlite3_free;+ }else{+ pNew->aData = aData;+ pNew->xDel = xDestroy;+ }+ return sqlite3_bind_pointer(pStmt, idx, pNew, "carray-bind", carrayBindDel);++ carray_bind_error:+ if( xDestroy!=SQLITE_STATIC && xDestroy!=SQLITE_TRANSIENT ){+ xDestroy(aData);+ }+ sqlite3_free(pNew);+ return rc;+}++/*+** Invoke this routine to register the carray() function.+*/+SQLITE_PRIVATE Module *sqlite3CarrayRegister(sqlite3 *db){+ return sqlite3VtabCreateModule(db, "carray", &carrayModule, 0, 0);+}++#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY) */++/************** End of carray.c **********************************************//************** Begin file sqlite3session.c **********************************/#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)@@ -227973,7 +232149,7 @@ static int sessionTableInfo(/*** This function is called to initialize the SessionTable.nCol, azCol[]** abPK[] and azDflt[] members of SessionTable object pTab. If these-** fields are already initilialized, this function is a no-op.+** fields are already initialized, this function is a no-op.**** If an error occurs, an error code is stored in sqlite3_session.rc and** non-zero returned. Or, if no error occurs but the table has no primary@@ -227992,6 +232168,8 @@ static int sessionInitTable(if( pTab->nCol==0 ){u8 *abPK;assert( pTab->azCol==0 || pTab->abPK==0 );+ sqlite3_free(pTab->azCol);+ pTab->abPK = 0;rc = sessionTableInfo(pSession, db, zDb,pTab->zName, &pTab->nCol, &pTab->nTotalCol, 0, &pTab->azCol,&pTab->azDflt, &pTab->aiIdx, &abPK,@@ -228999,7 +233177,9 @@ SQLITE_API int sqlite3session_diff(SessionTable *pTo; /* Table zTbl *//* Locate and if necessary initialize the target table object */+ pSession->bAutoAttach++;rc = sessionFindTable(pSession, zTbl, &pTo);+ pSession->bAutoAttach--;if( pTo==0 ) goto diff_out;if( sessionInitTable(pSession, pTo, pSession->db, pSession->zDb) ){rc = pSession->rc;@@ -229010,17 +233190,43 @@ SQLITE_API int sqlite3session_diff(if( rc==SQLITE_OK ){int bHasPk = 0;int bMismatch = 0;- int nCol; /* Columns in zFrom.zTbl */+ int nCol = 0; /* Columns in zFrom.zTbl */int bRowid = 0;- u8 *abPK;+ u8 *abPK = 0;const char **azCol = 0;- rc = sessionTableInfo(0, db, zFrom, zTbl,- &nCol, 0, 0, &azCol, 0, 0, &abPK,- pSession->bImplicitPK ? &bRowid : 0- );+ char *zDbExists = 0;++ /* Check that database zFrom is attached. */+ zDbExists = sqlite3_mprintf("SELECT * FROM %Q.sqlite_schema", zFrom);+ if( zDbExists==0 ){+ rc = SQLITE_NOMEM;+ }else{+ sqlite3_stmt *pDbExists = 0;+ rc = sqlite3_prepare_v2(db, zDbExists, -1, &pDbExists, 0);+ if( rc==SQLITE_ERROR ){+ rc = SQLITE_OK;+ nCol = -1;+ }+ sqlite3_finalize(pDbExists);+ sqlite3_free(zDbExists);+ }++ if( rc==SQLITE_OK && nCol==0 ){+ rc = sessionTableInfo(0, db, zFrom, zTbl,+ &nCol, 0, 0, &azCol, 0, 0, &abPK,+ pSession->bImplicitPK ? &bRowid : 0+ );+ }if( rc==SQLITE_OK ){if( pTo->nCol!=nCol ){- bMismatch = 1;+ if( nCol<=0 ){+ rc = SQLITE_SCHEMA;+ if( pzErrMsg ){+ *pzErrMsg = sqlite3_mprintf("no such table: %s.%s", zFrom, zTbl);+ }+ }else{+ bMismatch = 1;+ }}else{int i;for(i=0; i<nCol; i++){@@ -229568,6 +233774,19 @@ static int sessionAppendDelete(return rc;}+static int sessionPrepare(+ sqlite3 *db,+ sqlite3_stmt **pp,+ char **pzErrmsg,+ const char *zSql+){+ int rc = sqlite3_prepare_v2(db, zSql, -1, pp, 0);+ if( pzErrmsg && rc!=SQLITE_OK ){+ *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));+ }+ return rc;+}+/*** Formulate and prepare a SELECT statement to retrieve a row from table** zTab in database zDb based on its primary key. i.e.@@ -229589,12 +233808,12 @@ static int sessionSelectStmt(int nCol, /* Number of columns in table */const char **azCol, /* Names of table columns */u8 *abPK, /* PRIMARY KEY array */- sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */+ sqlite3_stmt **ppStmt, /* OUT: Prepared SELECT statement */+ char **pzErrmsg /* OUT: Error message */){int rc = SQLITE_OK;char *zSql = 0;const char *zSep = "";- int nSql = -1;int i;SessionBuffer cols = {0, 0, 0};@@ -229674,7 +233893,7 @@ static int sessionSelectStmt(#endifif( rc==SQLITE_OK ){- rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);+ rc = sessionPrepare(db, ppStmt, pzErrmsg, zSql);}sqlite3_free(zSql);sqlite3_free(nooptest.aBuf);@@ -229796,7 +234015,7 @@ static int sessionGenerateChangeset(){sqlite3 *db = pSession->db; /* Source database handle */SessionTable *pTab; /* Used to iterate through attached tables */- SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */+ SessionBuffer buf = {0,0,0}; /* Buffer in which to accumulate changeset */int rc; /* Return code */assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) );@@ -229838,7 +234057,7 @@ static int sessionGenerateChangeset(/* Build and compile a statement to execute: */if( rc==SQLITE_OK ){rc = sessionSelectStmt(db, 0, pSession->zDb,- zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel+ zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel, 0);}@@ -230149,14 +234368,15 @@ SQLITE_API int sqlite3changeset_start_v2_strm(** object and the buffer is full, discard some data to free up space.*/static void sessionDiscardData(SessionInput *pIn){- if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){- int nMove = pIn->buf.nBuf - pIn->iNext;+ if( pIn->xInput && pIn->iCurrent>=sessions_strm_chunk_size ){+ int nMove = pIn->buf.nBuf - pIn->iCurrent;assert( nMove>=0 );if( nMove>0 ){- memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);+ memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iCurrent], nMove);}- pIn->buf.nBuf -= pIn->iNext;- pIn->iNext = 0;+ pIn->buf.nBuf -= pIn->iCurrent;+ pIn->iNext -= pIn->iCurrent;+ pIn->iCurrent = 0;pIn->nData = pIn->buf.nBuf;}}@@ -230510,8 +234730,8 @@ static int sessionChangesetNextOne(p->rc = sessionInputBuffer(&p->in, 2);if( p->rc!=SQLITE_OK ) return p->rc;- sessionDiscardData(&p->in);p->in.iCurrent = p->in.iNext;+ sessionDiscardData(&p->in);/* If the iterator is already at the end of the changeset, return DONE. */if( p->in.iNext>=p->in.nData ){@@ -231046,6 +235266,7 @@ struct SessionApplyCtx {u8 bRebase; /* True to collect rebase information */u8 bIgnoreNoop; /* True to ignore no-op conflicts */int bRowid;+ char *zErr; /* Error message, if any */};/* Number of prepared UPDATE statements to cache. */@@ -231271,7 +235492,7 @@ static int sessionDeleteRow(}if( rc==SQLITE_OK ){- rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);+ rc = sessionPrepare(db, &p->pDelete, &p->zErr, (char*)buf.aBuf);}sqlite3_free(buf.aBuf);@@ -231298,7 +235519,7 @@ static int sessionSelectRow(){/* TODO */return sessionSelectStmt(db, p->bIgnoreNoop,- "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect+ "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect, &p->zErr);}@@ -231335,16 +235556,12 @@ static int sessionInsertRow(sessionAppendStr(&buf, ")", &rc);if( rc==SQLITE_OK ){- rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);+ rc = sessionPrepare(db, &p->pInsert, &p->zErr, (char*)buf.aBuf);}sqlite3_free(buf.aBuf);return rc;}-static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){- return sqlite3_prepare_v2(db, zSql, -1, pp, 0);-}-/*** Prepare statements for applying changes to the sqlite_stat1 table.** These are similar to those created by sessionSelectRow(),@@ -231354,14 +235571,14 @@ static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){int rc = sessionSelectRow(db, "sqlite_stat1", p);if( rc==SQLITE_OK ){- rc = sessionPrepare(db, &p->pInsert,+ rc = sessionPrepare(db, &p->pInsert, 0,"INSERT INTO main.sqlite_stat1 VALUES(?1, ""CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, ""?3)");}if( rc==SQLITE_OK ){- rc = sessionPrepare(db, &p->pDelete,+ rc = sessionPrepare(db, &p->pDelete, 0,"DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS ""CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END ""AND (?4 OR stat IS ?3)"@@ -231585,7 +235802,7 @@ static int sessionConflictHandler(void *pCtx, /* First argument for conflict handler */int *pbReplace /* OUT: Set to true if PK row is found */){- int res = 0; /* Value returned by conflict handler */+ int res = SQLITE_CHANGESET_OMIT;/* Value returned by conflict handler */int rc;int nCol;int op;@@ -231606,11 +235823,9 @@ static int sessionConflictHandler(if( rc==SQLITE_ROW ){/* There exists another row with the new.* primary key. */- if( p->bIgnoreNoop- && sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1)+ if( 0==p->bIgnoreNoop+ || 0==sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1)){- res = SQLITE_CHANGESET_OMIT;- }else{pIter->pConflict = p->pSelect;res = xConflict(pCtx, eType, pIter);pIter->pConflict = 0;@@ -231624,7 +235839,9 @@ static int sessionConflictHandler(int nBlob = pIter->in.iNext - pIter->in.iCurrent;sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);return SQLITE_OK;- }else{+ }else if( p->bIgnoreNoop==0 || op!=SQLITE_DELETE+ || eType==SQLITE_CHANGESET_CONFLICT+ ){/* No other row with the new.* primary key. */res = xConflict(pCtx, eType+1, pIter);if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;@@ -231722,7 +235939,7 @@ static int sessionApplyOneOp(sqlite3_step(p->pDelete);rc = sqlite3_reset(p->pDelete);- if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 && p->bIgnoreNoop==0 ){+ if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){rc = sessionConflictHandler(SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry);@@ -231934,6 +236151,10 @@ static int sessionChangesetApply(void *pCtx, /* Copy of sixth arg to _apply() */const char *zTab /* Table name */),+ int(*xFilterIter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p+ ),int(*xConflict)(void *pCtx, /* Copy of fifth arg to _apply() */int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */@@ -232074,6 +236295,9 @@ static int sessionChangesetApply(** next change. A log message has already been issued. */if( schemaMismatch ) continue;+ /* If this is a call to apply_v3(), invoke xFilterIter here. */+ if( xFilterIter && 0==xFilterIter(pCtx, pIter) ) continue;+rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);}@@ -232120,6 +236344,7 @@ static int sessionChangesetApply(assert( sApply.bRebase || sApply.rebase.nBuf==0 );if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){+ assert( ppRebase!=0 && pnRebase!=0 );*ppRebase = (void*)sApply.rebase.aBuf;*pnRebase = sApply.rebase.nBuf;sApply.rebase.aBuf = 0;@@ -232137,22 +236362,74 @@ static int sessionChangesetApply(db->flags &= ~((u64)SQLITE_FkNoAction);db->aDb[0].pSchema->schema_cookie -= 32;}++ assert( rc!=SQLITE_OK || sApply.zErr==0 );+ sqlite3_set_errmsg(db, rc, sApply.zErr);+ sqlite3_free(sApply.zErr);+sqlite3_mutex_leave(sqlite3_db_mutex(db));return rc;}/*-** Apply the changeset passed via pChangeset/nChangeset to the main-** database attached to handle "db".+** This function is called by all six sqlite3changeset_apply() variants:+**+** + sqlite3changeset_apply()+** + sqlite3changeset_apply_v2()+** + sqlite3changeset_apply_v3()+** + sqlite3changeset_apply_strm()+** + sqlite3changeset_apply_strm_v2()+** + sqlite3changeset_apply_strm_v3()+**+** Arguments passed to this function are as follows:+**+** db:+** Database handle to apply changeset to main database of.+**+** nChangeset/pChangeset:+** These are both passed zero for the streaming variants. For the normal+** apply() functions, these are passed the size of and the buffer containing+** the changeset, respectively.+**+** xInput/pIn:+** These are both passed zero for the normal variants. For the streaming+** apply() functions, these are passed the input callback and context+** pointer, respectively.+**+** xFilter:+** The filter function as passed to apply() or apply_v2() (to filter by+** table name), if any. This is always NULL for apply_v3() calls.+**+** xFilterIter:+** The filter function as passed to apply_v3(), if any.+**+** xConflict:+** The conflict handler callback (must not be NULL).+**+** pCtx:+** The context pointer passed to the xFilter and xConflict handler callbacks.+**+** ppRebase, pnRebase:+** Zero for apply(). The rebase changeset output pointers, if any, for+** apply_v2() and apply_v3().+**+** flags:+** Zero for apply(). The flags parameter for apply_v2() and apply_v3().*/-SQLITE_API int sqlite3changeset_apply_v2(+static int sessionChangesetApplyV23(sqlite3 *db, /* Apply change to "main" db of this handle */int nChangeset, /* Size of changeset in bytes */void *pChangeset, /* Changeset blob */+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */+ void *pIn, /* First arg for xInput */int(*xFilter)(void *pCtx, /* Copy of sixth arg to _apply() */const char *zTab /* Table name */),+ int(*xFilterIter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p /* Handle describing current change */+ ),int(*xConflict)(void *pCtx, /* Copy of sixth arg to _apply() */int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */@@ -232163,18 +236440,74 @@ SQLITE_API int sqlite3changeset_apply_v2(int flags){sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */- int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);- int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1);-+ int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);+ int rc = sessionChangesetStart(+ &pIter, xInput, pIn, nChangeset, pChangeset, bInverse, 1+ );if( rc==SQLITE_OK ){- rc = sessionChangesetApply(- db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags+ rc = sessionChangesetApply(db, pIter,+ xFilter, xFilterIter, xConflict, pCtx, ppRebase, pnRebase, flags);}-return rc;}+/*+** Apply the changeset passed via pChangeset/nChangeset to the main+** database attached to handle "db".+*/+SQLITE_API int sqlite3changeset_apply_v2(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int nChangeset, /* Size of changeset in bytes */+ void *pChangeset, /* Changeset blob */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ const char *zTab /* Table name */+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase,+ int flags+){+ return sessionChangesetApplyV23(db,+ nChangeset, pChangeset, 0, 0,+ xFilter, 0, xConflict, pCtx,+ ppRebase, pnRebase, flags+ );+}++/*+** Apply the changeset passed via pChangeset/nChangeset to the main+** database attached to handle "db".+*/+SQLITE_API int sqlite3changeset_apply_v3(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int nChangeset, /* Size of changeset in bytes */+ void *pChangeset, /* Changeset blob */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p /* Handle describing current change */+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase,+ int flags+){+ return sessionChangesetApplyV23(db,+ nChangeset, pChangeset, 0, 0,+ 0, xFilter, xConflict, pCtx,+ ppRebase, pnRebase, flags+ );+}+/*** Apply the changeset passed via pChangeset/nChangeset to the main database** attached to handle "db". Invoke the supplied conflict handler callback@@ -232195,8 +236528,10 @@ SQLITE_API int sqlite3changeset_apply(),void *pCtx /* First argument passed to xConflict */){- return sqlite3changeset_apply_v2(- db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0+ return sessionChangesetApplyV23(db,+ nChangeset, pChangeset, 0, 0,+ xFilter, 0, xConflict, pCtx,+ 0, 0, 0);}@@ -232205,6 +236540,29 @@ SQLITE_API int sqlite3changeset_apply(** attached to handle "db". Invoke the supplied conflict handler callback** to resolve any conflicts encountered while applying the change.*/+SQLITE_API int sqlite3changeset_apply_v3_strm(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */+ void *pIn, /* First arg for xInput */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase,+ int flags+){+ return sessionChangesetApplyV23(db,+ 0, 0, xInput, pIn,+ 0, xFilter, xConflict, pCtx,+ ppRebase, pnRebase, flags+ );+}SQLITE_API int sqlite3changeset_apply_v2_strm(sqlite3 *db, /* Apply change to "main" db of this handle */int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */@@ -232222,15 +236580,11 @@ SQLITE_API int sqlite3changeset_apply_v2_strm(void **ppRebase, int *pnRebase,int flags){- sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */- int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);- int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse, 1);- if( rc==SQLITE_OK ){- rc = sessionChangesetApply(- db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags- );- }- return rc;+ return sessionChangesetApplyV23(db,+ 0, 0, xInput, pIn,+ xFilter, 0, xConflict, pCtx,+ ppRebase, pnRebase, flags+ );}SQLITE_API int sqlite3changeset_apply_strm(sqlite3 *db, /* Apply change to "main" db of this handle */@@ -232247,8 +236601,10 @@ SQLITE_API int sqlite3changeset_apply_strm(),void *pCtx /* First argument passed to xConflict */){- return sqlite3changeset_apply_v2_strm(- db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0+ return sessionChangesetApplyV23(db,+ 0, 0, xInput, pIn,+ xFilter, 0, xConflict, pCtx,+ 0, 0, 0);}@@ -232870,14 +237226,19 @@ SQLITE_API int sqlite3changegroup_add_change(sqlite3_changegroup *pGrp,sqlite3_changeset_iter *pIter){+ int rc = SQLITE_OK;+if( pIter->in.iCurrent==pIter->in.iNext|| pIter->rc!=SQLITE_OK|| pIter->bInvert){/* Iterator does not point to any valid entry or is an INVERT iterator. */- return SQLITE_ERROR;+ rc = SQLITE_ERROR;+ }else{+ pIter->in.bNoDiscard = 1;+ rc = sessionOneChangeToHash(pGrp, pIter, 0);}- return sessionOneChangeToHash(pGrp, pIter, 0);+ return rc;}/*@@ -234175,6 +238536,7 @@ SQLITE_EXTENSION_INIT1/* #include <string.h> *//* #include <assert.h> */+/* #include <stddef.h> */#ifndef SQLITE_AMALGAMATION@@ -234214,23 +238576,34 @@ typedef sqlite3_uint64 u64;# define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)-/* The uptr type is an unsigned integer large enough to hold a pointer+/*+** This macro is used in a single assert() within fts5 to check that an+** allocation is aligned to an 8-byte boundary. But it is a complicated+** macro to get right for multiple platforms without generating warnings.+** So instead of reproducing the entire definition from sqliteInt.h, we+** just do without this assert() for the rare non-amalgamation builds.*/-#if defined(HAVE_STDINT_H)- typedef uintptr_t uptr;-#elif SQLITE_PTRSIZE==4- typedef u32 uptr;-#else- typedef u64 uptr;-#endif+#define EIGHT_BYTE_ALIGNMENT(x) 1-#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC-# define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&3)==0)+/*+** Macros needed to provide flexible arrays in a portable way+*/+#ifndef offsetof+# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))+#endif+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)+# define FLEXARRAY#else-# define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&7)==0)+# define FLEXARRAY 1#endif-#endif+#endif /* SQLITE_AMALGAMATION */++/*+** Constants for the largest and smallest possible 32-bit signed integers.+*/+# define LARGEST_INT32 ((int)(0x7fffffff))+# define SMALLEST_INT32 ((int)((-1) - LARGEST_INT32))/* Truncate very long tokens to this many bytes. Hard limit is** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset@@ -234302,10 +238675,11 @@ typedef struct Fts5Colset Fts5Colset;*/struct Fts5Colset {int nCol;- int aiCol[1];+ int aiCol[FLEXARRAY];};-+/* Size (int bytes) of a complete Fts5Colset object with N columns. */+#define SZ_FTS5COLSET(N) (sizeof(i64)*((N+2)/2))/**************************************************************************** Interface to code in fts5_config.c. fts5_config.c contains contains code@@ -234963,7 +239337,7 @@ static int sqlite3Fts5ExprPattern(** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);** }*/-static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);+static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, i64, int bDesc);static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);static int sqlite3Fts5ExprEof(Fts5Expr*);static i64 sqlite3Fts5ExprRowid(Fts5Expr*);@@ -235134,7 +239508,7 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*);**** The "lemon" program processes an LALR(1) input grammar file, then uses** this template to construct a parser. The "lemon" program inserts text-** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the+** at each "%%" line. Also, any "P-a-r-s-e" identifier prefix (without the** interstitial "-" characters) contained in this template is changed into** the value of the %name directive from the grammar. Otherwise, the content** of this template is copied straight through into the generate parser@@ -237288,7 +241662,7 @@ static int fts5Bm25GetData(** under consideration.**** The problem with this is that if (N < 2*nHit), the IDF is- ** negative. Which is undesirable. So the mimimum allowable IDF is+ ** negative. Which is undesirable. So the minimum allowable IDF is** (1e-6) - roughly the same as a term that appears in just over** half of set of 5,000,000 documents. */double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );@@ -237751,7 +242125,7 @@ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){** * The 52 upper and lower case ASCII characters, and** * The 10 integer ASCII characters.** * The underscore character "_" (0x5F).-** * The unicode "subsitute" character (0x1A).+** * The unicode "substitute" character (0x1A).*/static int sqlite3Fts5IsBareword(char t){u8 aBareword[128] = {@@ -239069,9 +243443,13 @@ struct Fts5ExprNode {/* Child nodes. For a NOT node, this array always contains 2 entries. For** AND or OR nodes, it contains 2 or more entries. */int nChild; /* Number of child nodes */- Fts5ExprNode *apChild[1]; /* Array of child nodes */+ Fts5ExprNode *apChild[FLEXARRAY]; /* Array of child nodes */};+/* Size (in bytes) of an Fts5ExprNode object that holds up to N children */+#define SZ_FTS5EXPRNODE(N) \+ (offsetof(Fts5ExprNode,apChild) + (N)*sizeof(Fts5ExprNode*))+#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)/*@@ -239102,9 +243480,13 @@ struct Fts5ExprPhrase {Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */Fts5Buffer poslist; /* Current position list */int nTerm; /* Number of entries in aTerm[] */- Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */+ Fts5ExprTerm aTerm[FLEXARRAY]; /* Terms that make up this phrase */};+/* Size (in bytes) of an Fts5ExprPhrase object that holds up to N terms */+#define SZ_FTS5EXPRPHRASE(N) \+ (offsetof(Fts5ExprPhrase,aTerm) + (N)*sizeof(Fts5ExprTerm))+/*** One or more phrases that must appear within a certain token distance of** each other within each matching document.@@ -239113,9 +243495,12 @@ struct Fts5ExprNearset {int nNear; /* NEAR parameter */Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */int nPhrase; /* Number of entries in aPhrase[] array */- Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */+ Fts5ExprPhrase *apPhrase[FLEXARRAY]; /* Array of phrase pointers */};+/* Size (in bytes) of an Fts5ExprNearset object covering up to N phrases */+#define SZ_FTS5EXPRNEARSET(N) \+ (offsetof(Fts5ExprNearset,apPhrase)+(N)*sizeof(Fts5ExprPhrase*))/*** Parse context.@@ -239275,7 +243660,7 @@ static int sqlite3Fts5ExprNew(/* If the LHS of the MATCH expression was a user column, apply the** implicit column-filter. */if( sParse.rc==SQLITE_OK && iCol<pConfig->nCol ){- int n = sizeof(Fts5Colset);+ int n = SZ_FTS5COLSET(1);Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);if( pColset ){pColset->nCol = 1;@@ -240521,7 +244906,13 @@ static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){** Return SQLITE_OK if successful, or an SQLite error code otherwise. It** is not considered an error if the query does not match any documents.*/-static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){+static int sqlite3Fts5ExprFirst(+ Fts5Expr *p,+ Fts5Index *pIdx,+ i64 iFirst,+ i64 iLast,+ int bDesc+){Fts5ExprNode *pRoot = p->pRoot;int rc; /* Return code */@@ -240543,6 +244934,9 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDassert( pRoot->bEof==0 );rc = fts5ExprNodeNext(p, pRoot, 0, 0);}+ if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){+ pRoot->bEof = 1;+ }return rc;}@@ -240633,7 +245027,7 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset(if( pParse->rc==SQLITE_OK ){if( pNear==0 ){sqlite3_int64 nByte;- nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);+ nByte = SZ_FTS5EXPRNEARSET(SZALLOC+1);pRet = sqlite3_malloc64(nByte);if( pRet==0 ){pParse->rc = SQLITE_NOMEM;@@ -240644,7 +245038,7 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset(int nNew = pNear->nPhrase + SZALLOC;sqlite3_int64 nByte;- nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);+ nByte = SZ_FTS5EXPRNEARSET(nNew+1);pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);if( pRet==0 ){pParse->rc = SQLITE_NOMEM;@@ -240735,12 +245129,12 @@ static int fts5ParseTokenize(int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,- sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew+ SZ_FTS5EXPRPHRASE(nNew+1));if( pNew==0 ){rc = SQLITE_NOMEM;}else{- if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));+ if( pPhrase==0 ) memset(pNew, 0, SZ_FTS5EXPRPHRASE(1));pCtx->pPhrase = pPhrase = pNew;pNew->nTerm = nNew - SZALLOC;}@@ -240848,7 +245242,7 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm(if( sCtx.pPhrase==0 ){/* This happens when parsing a token or quoted phrase that contains** no token characters at all. (e.g ... MATCH '""'). */- sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));+ sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, SZ_FTS5EXPRPHRASE(1));}else if( sCtx.pPhrase->nTerm ){sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;}@@ -240883,19 +245277,18 @@ static int sqlite3Fts5ExprClonePhrase(sizeof(Fts5ExprPhrase*));}if( rc==SQLITE_OK ){- pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,- sizeof(Fts5ExprNode));+ pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, SZ_FTS5EXPRNODE(1));}if( rc==SQLITE_OK ){pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,- sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));+ SZ_FTS5EXPRNEARSET(2));}if( rc==SQLITE_OK && ALWAYS(pOrig!=0) ){Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;if( pColsetOrig ){sqlite3_int64 nByte;Fts5Colset *pColset;- nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);+ nByte = SZ_FTS5COLSET(pColsetOrig->nCol);pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);if( pColset ){memcpy(pColset, pColsetOrig, (size_t)nByte);@@ -240923,7 +245316,7 @@ static int sqlite3Fts5ExprClonePhrase(}else{/* This happens when parsing a token or quoted phrase that contains** no token characters at all. (e.g ... MATCH '""'). */- sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));+ sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, SZ_FTS5EXPRPHRASE(1));}}@@ -240988,7 +245381,8 @@ static void sqlite3Fts5ParseSetDistance();return;}- nNear = nNear * 10 + (p->p[i] - '0');+ if( nNear<214748363 ) nNear = nNear * 10 + (p->p[i] - '0');+ /* ^^^^^^^^^^^^^^^--- Prevent integer overflow */}}else{nNear = FTS5_DEFAULT_NEARDIST;@@ -241017,7 +245411,7 @@ static Fts5Colset *fts5ParseColset(assert( pParse->rc==SQLITE_OK );assert( iCol>=0 && iCol<pParse->pConfig->nCol );- pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);+ pNew = sqlite3_realloc64(p, SZ_FTS5COLSET(nCol+1));if( pNew==0 ){pParse->rc = SQLITE_NOMEM;}else{@@ -241052,7 +245446,7 @@ static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *pint nCol = pParse->pConfig->nCol;pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,- sizeof(Fts5Colset) + sizeof(int)*nCol+ SZ_FTS5COLSET(nCol+1));if( pRet ){int i;@@ -241113,7 +245507,7 @@ static Fts5Colset *sqlite3Fts5ParseColset(static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){Fts5Colset *pRet;if( pOrig ){- sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);+ sqlite3_int64 nByte = SZ_FTS5COLSET(pOrig->nCol);pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);if( pRet ){memcpy(pRet, pOrig, (size_t)nByte);@@ -241281,7 +245675,7 @@ static Fts5ExprNode *fts5ParsePhraseToAnd(assert( pNear->nPhrase==1 );assert( pParse->bPhraseToAnd );- nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);+ nByte = SZ_FTS5EXPRNODE(nTerm+1);pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);if( pRet ){pRet->eType = FTS5_AND;@@ -241291,7 +245685,7 @@ static Fts5ExprNode *fts5ParsePhraseToAnd(pParse->nPhrase--;for(ii=0; ii<nTerm; ii++){Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(- &pParse->rc, sizeof(Fts5ExprPhrase)+ &pParse->rc, SZ_FTS5EXPRPHRASE(1));if( pPhrase ){if( parseGrowPhraseArray(pParse) ){@@ -241360,7 +245754,7 @@ static Fts5ExprNode *sqlite3Fts5ParseNode(if( pRight->eType==eType ) nChild += pRight->nChild-1;}- nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);+ nByte = SZ_FTS5EXPRNODE(nChild);pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);if( pRet ){@@ -242235,7 +246629,7 @@ static int sqlite3Fts5ExprInstToken(}/*-** Clear the token mappings for all Fts5IndexIter objects mannaged by+** Clear the token mappings for all Fts5IndexIter objects managed by** the expression passed as the only argument.*/static void sqlite3Fts5ExprClearTokens(Fts5Expr *pExpr){@@ -242270,7 +246664,7 @@ typedef struct Fts5HashEntry Fts5HashEntry;/*** This file contains the implementation of an in-memory hash table used-** to accumuluate "term -> doclist" content before it is flused to a level-0+** to accumulate "term -> doclist" content before it is flushed to a level-0** segment.*/@@ -242327,7 +246721,7 @@ struct Fts5HashEntry {};/*-** Eqivalent to:+** Equivalent to:**** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }*/@@ -243263,9 +247657,13 @@ struct Fts5Structure {u64 nOriginCntr; /* Origin value for next top-level segment */int nSegment; /* Total segments in this structure */int nLevel; /* Number of levels in this index */- Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */+ Fts5StructureLevel aLevel[FLEXARRAY]; /* Array of nLevel level objects */};+/* Size (in bytes) of an Fts5Structure object holding up to N levels */+#define SZ_FTS5STRUCTURE(N) \+ (offsetof(Fts5Structure,aLevel) + (N)*sizeof(Fts5StructureLevel))+/*** An object of type Fts5SegWriter is used to write to segments.*/@@ -243391,15 +247789,49 @@ struct Fts5SegIter {u8 bDel; /* True if the delete flag is set */};+static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){+ pIdx->rc = FTS5_CORRUPT;+ sqlite3Fts5ConfigErrmsg(pIdx->pConfig,+ "fts5: corruption found reading blob %lld from table \"%s\"",+ iRowid, pIdx->pConfig->zName+ );+ return SQLITE_CORRUPT_VTAB;+}+#define FTS5_CORRUPT_ROWID(pIdx, iRowid) fts5IndexCorruptRowid(pIdx, iRowid)++static int fts5IndexCorruptIter(Fts5Index *pIdx, Fts5SegIter *pIter){+ pIdx->rc = FTS5_CORRUPT;+ sqlite3Fts5ConfigErrmsg(pIdx->pConfig,+ "fts5: corruption on page %d, segment %d, table \"%s\"",+ pIter->iLeafPgno, pIter->pSeg->iSegid, pIdx->pConfig->zName+ );+ return SQLITE_CORRUPT_VTAB;+}+#define FTS5_CORRUPT_ITER(pIdx, pIter) fts5IndexCorruptIter(pIdx, pIter)++static int fts5IndexCorruptIdx(Fts5Index *pIdx){+ pIdx->rc = FTS5_CORRUPT;+ sqlite3Fts5ConfigErrmsg(pIdx->pConfig,+ "fts5: corruption in table \"%s\"", pIdx->pConfig->zName+ );+ return SQLITE_CORRUPT_VTAB;+}+#define FTS5_CORRUPT_IDX(pIdx) fts5IndexCorruptIdx(pIdx)++/*** Array of tombstone pages. Reference counted.*/struct Fts5TombstoneArray {- int nRef; /* Number of pointers to this object */+ int nRef; /* Number of pointers to this object */int nTombstone;- Fts5Data *apTombstone[1]; /* Array of tombstone pages */+ Fts5Data *apTombstone[FLEXARRAY]; /* Array of tombstone pages */};+/* Size (in bytes) of an Fts5TombstoneArray holding up to N tombstones */+#define SZ_FTS5TOMBSTONEARRAY(N) \+ (offsetof(Fts5TombstoneArray,apTombstone)+(N)*sizeof(Fts5Data*))+/*** Argument is a pointer to an Fts5Data structure that contains a** leaf page.@@ -243468,9 +247900,12 @@ struct Fts5Iter {i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */Fts5CResult *aFirst; /* Current merge state (see above) */- Fts5SegIter aSeg[1]; /* Array of segment iterators */+ Fts5SegIter aSeg[FLEXARRAY]; /* Array of segment iterators */};+/* Size (in bytes) of an Fts5Iter object holding up to N segment iterators */+#define SZ_FTS5ITER(N) (offsetof(Fts5Iter,aSeg)+(N)*sizeof(Fts5SegIter))+/*** An instance of the following type is used to iterate through the contents** of a doclist-index record.@@ -243497,9 +247932,13 @@ struct Fts5DlidxLvl {struct Fts5DlidxIter {int nLvl;int iSegid;- Fts5DlidxLvl aLvl[1];+ Fts5DlidxLvl aLvl[FLEXARRAY];};+/* Size (in bytes) of an Fts5DlidxIter object with up to N levels */+#define SZ_FTS5DLIDXITER(N) \+ (offsetof(Fts5DlidxIter,aLvl)+(N)*sizeof(Fts5DlidxLvl))+static void fts5PutU16(u8 *aOut, u16 iVal){aOut[0] = (iVal>>8);aOut[1] = (iVal&0xFF);@@ -243669,13 +248108,13 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){** All the reasons those functions might return SQLITE_ERROR - missing** table, missing row, non-blob/text in block column - indicate** backing store corruption. */- if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;+ if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT_ROWID(p, iRowid);if( rc==SQLITE_OK ){u8 *aOut = 0; /* Read blob data into this buffer */- int nByte = sqlite3_blob_bytes(p->pReader);- int szData = (sizeof(Fts5Data) + 7) & ~7;- sqlite3_int64 nAlloc = szData + nByte + FTS5_DATA_PADDING;+ i64 nByte = sqlite3_blob_bytes(p->pReader);+ i64 szData = (sizeof(Fts5Data) + 7) & ~7;+ i64 nAlloc = szData + nByte + FTS5_DATA_PADDING;pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);if( pRet ){pRet->nn = nByte;@@ -243719,7 +248158,7 @@ static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){Fts5Data *pRet = fts5DataRead(p, iRowid);if( pRet ){if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);fts5DataRelease(pRet);pRet = 0;}@@ -243867,7 +248306,7 @@ static int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){Fts5Structure *p = *pp;if( *pRc==SQLITE_OK && p->nRef>1 ){- i64 nByte = sizeof(Fts5Structure)+(p->nLevel-1)*sizeof(Fts5StructureLevel);+ i64 nByte = SZ_FTS5STRUCTURE(p->nLevel);Fts5Structure *pNew;pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte);if( pNew ){@@ -243941,10 +248380,7 @@ static int fts5StructureDecode(){return FTS5_CORRUPT;}- nByte = (- sizeof(Fts5Structure) + /* Main structure */- sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */- );+ nByte = SZ_FTS5STRUCTURE(nLevel);pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);if( pRet ){@@ -244024,10 +248460,7 @@ static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){if( *pRc==SQLITE_OK ){Fts5Structure *pStruct = *ppStruct;int nLevel = pStruct->nLevel;- sqlite3_int64 nByte = (- sizeof(Fts5Structure) + /* Main structure */- sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */- );+ sqlite3_int64 nByte = SZ_FTS5STRUCTURE(nLevel+2);pStruct = sqlite3_realloc64(pStruct, nByte);if( pStruct ){@@ -244084,8 +248517,14 @@ static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){/* TODO: Do we need this if the leaf-index is appended? Probably... */memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);- if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){- p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);+ if( p->rc==SQLITE_OK ){+ if( (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){+ p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);+ }+ }else if( p->rc==SQLITE_CORRUPT_VTAB ){+ sqlite3Fts5ConfigErrmsg(p->pConfig,+ "fts5: corrupt structure record for table \"%s\"", p->pConfig->zName+ );}fts5DataRelease(pData);if( p->rc!=SQLITE_OK ){@@ -244566,7 +249005,7 @@ static Fts5DlidxIter *fts5DlidxIterInit(int bDone = 0;for(i=0; p->rc==SQLITE_OK && bDone==0; i++){- sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);+ sqlite3_int64 nByte = SZ_FTS5DLIDXITER(i+1);Fts5DlidxIter *pNew;pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);@@ -244708,7 +249147,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){while( iOff>=pIter->pLeaf->szLeaf ){fts5SegIterNextPage(p, pIter);if( pIter->pLeaf==0 ){- if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;+ if( p->rc==SQLITE_OK ) FTS5_CORRUPT_ITER(p, pIter);return;}iOff = 4;@@ -244740,7 +249179,7 @@ static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){iOff += fts5GetVarint32(&a[iOff], nNew);if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}pIter->term.n = nKeep;@@ -244782,9 +249221,9 @@ static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){** leave an error in the Fts5Index object.*/static void fts5SegIterAllocTombstone(Fts5Index *p, Fts5SegIter *pIter){- const int nTomb = pIter->pSeg->nPgTombstone;+ const i64 nTomb = (i64)pIter->pSeg->nPgTombstone;if( nTomb>0 ){- int nByte = nTomb * sizeof(Fts5Data*) + sizeof(Fts5TombstoneArray);+ i64 nByte = SZ_FTS5TOMBSTONEARRAY(nTomb+1);Fts5TombstoneArray *pNew;pNew = (Fts5TombstoneArray*)sqlite3Fts5MallocZero(&p->rc, nByte);if( pNew ){@@ -244870,6 +249309,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){while( 1 ){u64 iDelta = 0;+ if( i>=n ) break;if( eDetail==FTS5_DETAIL_NONE ){/* todo */if( i<n && a[i]==0 ){@@ -244935,7 +249375,7 @@ static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){iRowidOff = fts5LeafFirstRowidOff(pNew);if( iRowidOff ){if( iRowidOff>=pNew->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);}else{pIter->pLeaf = pNew;pIter->iLeafOffset = iRowidOff;@@ -245169,7 +249609,7 @@ static void fts5SegIterNext(}assert_nc( iOff<pLeaf->szLeaf );if( iOff>pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}}@@ -245277,18 +249717,20 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){fts5DataRelease(pIter->pLeaf);pIter->pLeaf = pLast;pIter->iLeafPgno = pgnoLast;- iOff = fts5LeafFirstRowidOff(pLast);- if( iOff>pLast->szLeaf ){- p->rc = FTS5_CORRUPT;- return;- }- iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);- pIter->iLeafOffset = iOff;+ if( p->rc==SQLITE_OK ){+ iOff = fts5LeafFirstRowidOff(pLast);+ if( iOff>pLast->szLeaf ){+ FTS5_CORRUPT_ITER(p, pIter);+ return;+ }+ iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);+ pIter->iLeafOffset = iOff;- if( fts5LeafIsTermless(pLast) ){- pIter->iEndofDoclist = pLast->nn+1;- }else{- pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);+ if( fts5LeafIsTermless(pLast) ){+ pIter->iEndofDoclist = pLast->nn+1;+ }else{+ pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);+ }}}@@ -245358,7 +249800,7 @@ static void fts5LeafSeek(iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);iOff = iTermOff;if( iOff>n ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}@@ -245401,7 +249843,7 @@ static void fts5LeafSeek(iOff = iTermOff;if( iOff>=n ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}@@ -245423,7 +249865,7 @@ static void fts5LeafSeek(iPgidx = (u32)pIter->pLeaf->szLeaf;iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}else{nKeep = 0;@@ -245438,7 +249880,7 @@ static void fts5LeafSeek(search_success:if( (i64)iOff+nNew>n || nNew<1 ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ITER(p, pIter);return;}pIter->iLeafOffset = iOff + nNew;@@ -245903,7 +250345,7 @@ static void fts5SegIterGotoPage(assert( iLeafPgno>pIter->iLeafPgno );if( iLeafPgno>pIter->pSeg->pgnoLast ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);}else{fts5DataRelease(pIter->pNextLeaf);pIter->pNextLeaf = 0;@@ -245918,7 +250360,7 @@ static void fts5SegIterGotoPage(u8 *a = pIter->pLeaf->p;int n = pIter->pLeaf->szLeaf;if( iOff<4 || iOff>=n ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);}else{iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);pIter->iLeafOffset = iOff;@@ -246245,8 +250687,7 @@ static Fts5Iter *fts5MultiIterAlloc(for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);pNew = fts5IdxMalloc(p,- sizeof(Fts5Iter) + /* pNew */- sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */+ SZ_FTS5ITER(nSlot) + /* pNew + pNew->aSeg[] */sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */);if( pNew ){@@ -246398,7 +250839,7 @@ static void fts5ChunkIterate(if( nRem<=0 ){break;}else if( pSeg->pSeg==0 ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);return;}else{pgno++;@@ -247501,7 +251942,7 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){** a single page has been assigned to more than one segment. In** this case a prior iteration of this loop may have corrupted the** segment currently being trimmed. */- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iLeafRowid);}else{fts5BufferZero(&buf);fts5BufferGrow(&p->rc, &buf, pData->nn);@@ -247968,7 +252409,7 @@ static void fts5SecureDeleteOverflow(}else if( bDetailNone ){break;}else if( iNext>=pLeaf->szLeaf || pLeaf->nn<pLeaf->szLeaf || iNext<4 ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);break;}else{int nShift = iNext - 4;@@ -247988,7 +252429,7 @@ static void fts5SecureDeleteOverflow(i1 += fts5GetVarint32(&aPg[i1], iFirst);if( iFirst<iNext ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);break;}aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2);@@ -248034,7 +252475,7 @@ static void fts5DoSecureDelete(int iSegid = pSeg->pSeg->iSegid;u8 *aPg = pSeg->pLeaf->p;int nPg = pSeg->pLeaf->nn;- int iPgIdx = pSeg->pLeaf->szLeaf;+ int iPgIdx = pSeg->pLeaf->szLeaf; /* Offset of page footer */u64 iDelta = 0;int iNextOff = 0;@@ -248047,7 +252488,7 @@ static void fts5DoSecureDelete(int iDelKeyOff = 0; /* Offset of deleted key, if any */nIdx = nPg-iPgIdx;- aIdx = sqlite3Fts5MallocZero(&p->rc, nIdx+16);+ aIdx = sqlite3Fts5MallocZero(&p->rc, ((i64)nIdx)+16);if( p->rc ) return;memcpy(aIdx, &aPg[iPgIdx], nIdx);@@ -248113,7 +252554,7 @@ static void fts5DoSecureDelete(iSOP += fts5GetVarint32(&aPg[iSOP], nPos);}assert_nc( iSOP==pSeg->iLeafOffset );- iNextOff = pSeg->iLeafOffset + pSeg->nPos;+ iNextOff = iSOP + pSeg->nPos;}}@@ -248211,14 +252652,14 @@ static void fts5DoSecureDelete(nSuffix = (nPrefix2 + nSuffix2) - nPrefix;if( (iKeyOff+nSuffix)>iPgIdx || (iNextOff+nSuffix2)>iPgIdx ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);}else{if( iKey!=1 ){iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix);}iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix);if( nPrefix2>pSeg->term.n ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);}else if( nPrefix2>nPrefix ){memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix);iOff += (nPrefix2-nPrefix);@@ -248612,7 +253053,7 @@ static Fts5Structure *fts5IndexOptimizeStruct(Fts5Structure *pStruct){Fts5Structure *pNew = 0;- sqlite3_int64 nByte = sizeof(Fts5Structure);+ sqlite3_int64 nByte = SZ_FTS5STRUCTURE(1);int nSeg = pStruct->nSegment;int i;@@ -248641,7 +253082,8 @@ static Fts5Structure *fts5IndexOptimizeStruct(assert( pStruct->aLevel[i].nMerge<=nThis );}- nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);+ nByte += (((i64)pStruct->nLevel)+1) * sizeof(Fts5StructureLevel);+ assert( nByte==(i64)SZ_FTS5STRUCTURE(pStruct->nLevel+2) );pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);if( pNew ){@@ -248724,7 +253166,7 @@ static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){fts5StructureRelease(pStruct);pStruct = pNew;nMin = 1;- nMerge = nMerge*-1;+ nMerge = (nMerge==SMALLEST_INT32 ? LARGEST_INT32 : (nMerge*-1));}if( pStruct && pStruct->nLevel ){if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){@@ -249010,7 +253452,7 @@ static void fts5MergePrefixLists(}if( pHead==0 || pHead->pNext==0 ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_IDX(p);break;}@@ -249047,7 +253489,7 @@ static void fts5MergePrefixLists(assert_nc( tmp.n+nTail<=nTmp );assert( tmp.n+nTail<=nTmp+nMerge*10 );if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){- if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;+ if( p->rc==SQLITE_OK ) FTS5_CORRUPT_IDX(p);break;}fts5BufferSafeAppendVarint(&out, (tmp.n+nTail) * 2);@@ -249218,9 +253660,13 @@ struct Fts5TokenDataIter {int nIterAlloc;Fts5PoslistReader *aPoslistReader;int *aPoslistToIter;- Fts5Iter *apIter[1];+ Fts5Iter *apIter[FLEXARRAY];};+/* Size in bytes of an Fts5TokenDataIter object holding up to N iterators */+#define SZ_FTS5TOKENDATAITER(N) \+ (offsetof(Fts5TokenDataIter,apIter) + (N)*sizeof(Fts5Iter))+/*** The two input arrays - a1[] and a2[] - are in sorted order. This function** merges the two arrays together and writes the result to output array@@ -249292,7 +253738,7 @@ static void fts5TokendataIterAppendMap(/*** Sort the contents of the pT->aMap[] array.**-** The sorting algorithm requries a malloc(). If this fails, an error code+** The sorting algorithm requires a malloc(). If this fails, an error code** is left in Fts5Index.rc before returning.*/static void fts5TokendataIterSortMap(Fts5Index *p, Fts5TokenDataIter *pT){@@ -249483,7 +253929,7 @@ static void fts5SetupPrefixIter(&& p->pConfig->bPrefixInsttoken){s.pTokendata = &s2;- s2.pT = (Fts5TokenDataIter*)fts5IdxMalloc(p, sizeof(*s2.pT));+ s2.pT = (Fts5TokenDataIter*)fts5IdxMalloc(p, SZ_FTS5TOKENDATAITER(1));}if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){@@ -249529,7 +253975,8 @@ static void fts5SetupPrefixIter(}}- pData = fts5IdxMalloc(p, sizeof(*pData)+s.doclist.n+FTS5_DATA_ZERO_PADDING);+ pData = fts5IdxMalloc(p, sizeof(*pData)+ + ((i64)s.doclist.n)+FTS5_DATA_ZERO_PADDING);assert( pData!=0 || p->rc!=SQLITE_OK );if( pData ){pData->p = (u8*)&pData[1];@@ -249610,15 +254057,20 @@ static int sqlite3Fts5IndexRollback(Fts5Index *p){** and the initial version of the "averages" record (a zero-byte blob).*/static int sqlite3Fts5IndexReinit(Fts5Index *p){- Fts5Structure s;+ Fts5Structure *pTmp;+ union {+ Fts5Structure sFts;+ u8 tmpSpace[SZ_FTS5STRUCTURE(1)];+ } uFts;fts5StructureInvalidate(p);fts5IndexDiscardData(p);- memset(&s, 0, sizeof(Fts5Structure));+ pTmp = &uFts.sFts;+ memset(uFts.tmpSpace, 0, sizeof(uFts.tmpSpace));if( p->pConfig->bContentlessDelete ){- s.nOriginCntr = 1;+ pTmp->nOriginCntr = 1;}fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);- fts5StructureWrite(p, &s);+ fts5StructureWrite(p, pTmp);return fts5IndexReturn(p);}@@ -249826,7 +254278,7 @@ static Fts5TokenDataIter *fts5AppendTokendataIter(if( p->rc==SQLITE_OK ){if( pIn==0 || pIn->nIter==pIn->nIterAlloc ){int nAlloc = pIn ? pIn->nIterAlloc*2 : 16;- int nByte = nAlloc * sizeof(Fts5Iter*) + sizeof(Fts5TokenDataIter);+ int nByte = SZ_FTS5TOKENDATAITER(nAlloc+1);Fts5TokenDataIter *pNew = (Fts5TokenDataIter*)sqlite3_realloc(pIn, nByte);if( pNew==0 ){@@ -250342,7 +254794,8 @@ static int fts5SetupPrefixIterTokendata(fts5BufferGrow(&p->rc, &token, nToken+1);assert( token.p!=0 || p->rc!=SQLITE_OK );- ctx.pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc, sizeof(*ctx.pT));+ ctx.pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc,+ SZ_FTS5TOKENDATAITER(1));if( p->rc==SQLITE_OK ){@@ -250473,7 +254926,8 @@ static int sqlite3Fts5IndexIterWriteTokendata(if( pIter->nSeg>0 ){/* This is a prefix term iterator. */if( pT==0 ){- pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc, sizeof(*pT));+ pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc,+ SZ_FTS5TOKENDATAITER(1));pIter->pTokenDataIter = pT;}if( pT ){@@ -251071,19 +255525,27 @@ static int fts5TestUtf8(const char *z, int n){/*** This function is also purely an internal test. It does not contribute to** FTS functionality, or even the integrity-check, in any way.+**+** This function sets output variable (*pbFail) to true if the test fails. Or+** leaves it unchanged if the test succeeds.*/static void fts5TestTerm(Fts5Index *p,Fts5Buffer *pPrev, /* Previous term */const char *z, int n, /* Possibly new term to test */u64 expected,- u64 *pCksum+ u64 *pCksum,+ int *pbFail){int rc = p->rc;if( pPrev->n==0 ){fts5BufferSet(&rc, pPrev, n, (const u8*)z);}else- if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){+ if( *pbFail==0+ && rc==SQLITE_OK+ && (pPrev->n!=n || memcmp(pPrev->p, z, n))+ && (p->pHash==0 || p->pHash->nEntry==0)+ ){u64 cksum3 = *pCksum;const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */int nTerm = pPrev->n-1; /* Size of zTerm in bytes */@@ -251133,7 +255595,7 @@ static void fts5TestTerm(fts5BufferSet(&rc, pPrev, n, (const u8*)z);if( rc==SQLITE_OK && cksum3!=expected ){- rc = FTS5_CORRUPT;+ *pbFail = 1;}*pCksum = cksum3;}@@ -251142,7 +255604,7 @@ static void fts5TestTerm(#else# define fts5TestDlidxReverse(x,y,z)-# define fts5TestTerm(u,v,w,x,y,z)+# define fts5TestTerm(t,u,v,w,x,y,z)#endif/*@@ -251167,14 +255629,17 @@ static void fts5IndexIntegrityCheckEmpty(for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));if( pLeaf ){- if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;- if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;+ if( !fts5LeafIsTermless(pLeaf)+ || (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf))+ ){+ FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));+ }}fts5DataRelease(pLeaf);}}-static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){+static void fts5IntegrityCheckPgidx(Fts5Index *p, i64 iRowid, Fts5Data *pLeaf){i64 iTermOff = 0;int ii;@@ -251192,12 +255657,12 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){iOff = iTermOff;if( iOff>=pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);}else if( iTermOff==nIncr ){int nByte;iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);if( (iOff+nByte)>pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);}else{fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);}@@ -251206,7 +255671,7 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRowid);}else{buf1.n = nKeep;fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);@@ -251214,7 +255679,7 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){if( p->rc==SQLITE_OK ){res = fts5BufferCompare(&buf1, &buf2);- if( res<=0 ) p->rc = FTS5_CORRUPT;+ if( res<=0 ) FTS5_CORRUPT_ROWID(p, iRowid);}}fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);@@ -251275,7 +255740,7 @@ static void fts5IndexIntegrityCheckSegment(** entry even if all the terms are removed from it by secure-delete** operations. */}else{- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRow);}}else{@@ -251287,15 +255752,15 @@ static void fts5IndexIntegrityCheckSegment(iOff = fts5LeafFirstTermOff(pLeaf);iRowidOff = fts5LeafFirstRowidOff(pLeaf);if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iRow);}else{iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));if( res==0 ) res = nTerm - nIdxTerm;- if( res<0 ) p->rc = FTS5_CORRUPT;+ if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow);}- fts5IntegrityCheckPgidx(p, pLeaf);+ fts5IntegrityCheckPgidx(p, iRow, pLeaf);}fts5DataRelease(pLeaf);if( p->rc ) break;@@ -251325,7 +255790,7 @@ static void fts5IndexIntegrityCheckSegment(iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);pLeaf = fts5DataRead(p, iKey);if( pLeaf ){- if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;+ if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey);fts5DataRelease(pLeaf);}}@@ -251340,12 +255805,12 @@ static void fts5IndexIntegrityCheckSegment(int iRowidOff = fts5LeafFirstRowidOff(pLeaf);ASSERT_SZLEAF_OK(pLeaf);if( iRowidOff>=pLeaf->szLeaf ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iKey);}else if( bSecureDelete==0 || iRowidOff>0 ){i64 iDlRowid = fts5DlidxIterRowid(pDlidx);fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){- p->rc = FTS5_CORRUPT;+ FTS5_CORRUPT_ROWID(p, iKey);}}fts5DataRelease(pLeaf);@@ -251397,6 +255862,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum/* Used by extra internal tests only run if NDEBUG is not defined */u64 cksum3 = 0; /* Checksum based on contents of indexes */Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */+ int bTestFail = 0;#endifconst int flags = FTS5INDEX_QUERY_NOOUTPUT;@@ -251439,7 +255905,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksumchar *z = (char*)fts5MultiIterTerm(pIter, &n);/* If this is a new term, query for it. Update cksum3 with the results. */- fts5TestTerm(p, &term, z, n, cksum2, &cksum3);+ fts5TestTerm(p, &term, z, n, cksum2, &cksum3, &bTestFail);if( p->rc ) break;if( eDetail==FTS5_DETAIL_NONE ){@@ -251457,15 +255923,26 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum}}}- fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);+ fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3, &bTestFail);fts5MultiIterFree(pIter);- if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;-- fts5StructureRelease(pStruct);+ if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ){+ p->rc = FTS5_CORRUPT;+ sqlite3Fts5ConfigErrmsg(p->pConfig,+ "fts5: checksum mismatch for table \"%s\"", p->pConfig->zName+ );+ }#ifdef SQLITE_DEBUG+ /* In SQLITE_DEBUG builds, expensive extra checks were run as part of+ ** the integrity-check above. If no other errors were detected, but one+ ** of these tests failed, set the result to SQLITE_CORRUPT_VTAB here. */+ if( p->rc==SQLITE_OK && bTestFail ){+ p->rc = FTS5_CORRUPT;+ }fts5BufferFree(&term);#endif++ fts5StructureRelease(pStruct);fts5BufferFree(&poslist);return fts5IndexReturn(p);}@@ -251507,7 +255984,7 @@ static void fts5DecodeRowid(#if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){- int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid compenents */+ int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid components */fts5DecodeRowid(iKey, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);if( iSegid==0 ){@@ -251753,7 +256230,7 @@ static void fts5DecodeFunction(** buffer overreads even if the record is corrupt. */n = sqlite3_value_bytes(apVal[1]);aBlob = sqlite3_value_blob(apVal[1]);- nSpace = n + FTS5_DATA_ZERO_PADDING;+ nSpace = ((i64)n) + FTS5_DATA_ZERO_PADDING;a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);if( a==0 ) goto decode_out;if( n>0 ) memcpy(a, aBlob, n);@@ -252468,9 +256945,11 @@ struct Fts5Sorter {i64 iRowid; /* Current rowid */const u8 *aPoslist; /* Position lists for current row */int nIdx; /* Number of entries in aIdx[] */- int aIdx[1]; /* Offsets into aPoslist for current row */+ int aIdx[FLEXARRAY]; /* Offsets into aPoslist for current row */};+/* Size (int bytes) of an Fts5Sorter object with N indexes */+#define SZ_FTS5SORTER(N) (offsetof(Fts5Sorter,nIdx)+((N+2)/2)*sizeof(i64))/*** Virtual-table cursor object.@@ -252807,6 +257286,17 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){#endif}+static void fts5SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){+#if SQLITE_VERSION_NUMBER>=3008002+#ifndef SQLITE_CORE+ if( sqlite3_libversion_number()>=3008002 )+#endif+ {+ pIdxInfo->estimatedRows = nRow;+ }+#endif+}+static int fts5UsePatternMatch(Fts5Config *pConfig,struct sqlite3_index_constraint *p@@ -252942,7 +257432,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){nSeenMatch++;idxStr[iIdxStr++] = 'M';sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);- idxStr += strlen(&idxStr[iIdxStr]);+ iIdxStr += (int)strlen(&idxStr[iIdxStr]);assert( idxStr[iIdxStr]=='\0' );}pInfo->aConstraintUsage[i].argvIndex = ++iCons;@@ -252961,6 +257451,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){idxStr[iIdxStr++] = '=';bSeenEq = 1;pInfo->aConstraintUsage[i].argvIndex = ++iCons;+ pInfo->aConstraintUsage[i].omit = 1;}}}@@ -253008,17 +257499,21 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){/* Calculate the estimated cost based on the flags set in idxFlags. */if( bSeenEq ){- pInfo->estimatedCost = nSeenMatch ? 1000.0 : 10.0;- if( nSeenMatch==0 ) fts5SetUniqueFlag(pInfo);- }else if( bSeenLt && bSeenGt ){- pInfo->estimatedCost = nSeenMatch ? 5000.0 : 250000.0;- }else if( bSeenLt || bSeenGt ){- pInfo->estimatedCost = nSeenMatch ? 7500.0 : 750000.0;- }else{- pInfo->estimatedCost = nSeenMatch ? 10000.0 : 1000000.0;- }- for(i=1; i<nSeenMatch; i++){- pInfo->estimatedCost *= 0.4;+ pInfo->estimatedCost = nSeenMatch ? 1000.0 : 25.0;+ fts5SetUniqueFlag(pInfo);+ fts5SetEstimatedRows(pInfo, 1);+ }else{+ if( bSeenLt && bSeenGt ){+ pInfo->estimatedCost = nSeenMatch ? 5000.0 : 750000.0;+ }else if( bSeenLt || bSeenGt ){+ pInfo->estimatedCost = nSeenMatch ? 7500.0 : 2250000.0;+ }else{+ pInfo->estimatedCost = nSeenMatch ? 10000.0 : 3000000.0;+ }+ for(i=1; i<nSeenMatch; i++){+ pInfo->estimatedCost *= 0.4;+ }+ fts5SetEstimatedRows(pInfo, (i64)(pInfo->estimatedCost / 4.0));}pInfo->idxNum = idxFlags;@@ -253217,7 +257712,9 @@ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){int bDesc = pCsr->bDesc;i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);- rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);+ rc = sqlite3Fts5ExprFirst(+ pCsr->pExpr, pTab->p.pIndex, iRowid, pCsr->iLastRowid, bDesc+ );if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){*pbSkip = 1;}@@ -253348,7 +257845,7 @@ static int fts5CursorFirstSorted(const char *zRankArgs = pCsr->zRankArgs;nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);- nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);+ nByte = SZ_FTS5SORTER(nPhrase);pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);if( pSorter==0 ) return SQLITE_NOMEM;memset(pSorter, 0, (size_t)nByte);@@ -253389,7 +257886,9 @@ static int fts5CursorFirstSorted(static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){int rc;Fts5Expr *pExpr = pCsr->pExpr;- rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);+ rc = sqlite3Fts5ExprFirst(+ pExpr, pTab->p.pIndex, pCsr->iFirstRowid, pCsr->iLastRowid, bDesc+ );if( sqlite3Fts5ExprEof(pExpr) ){CsrFlagSet(pCsr, FTS5CSR_EOF);}@@ -255874,7 +260373,7 @@ static void fts5SourceIdFunc(){assert( nArg==0 );UNUSED_PARAM2(nArg, apUnused);- sqlite3_result_text(pCtx, "fts5: 2025-02-18 13:38:58 873d4e274b4988d260ba8354a9718324a1c26187a4ab4c1cc0227c03d0f10e70", -1, SQLITE_TRANSIENT);+ sqlite3_result_text(pCtx, "fts5: 2026-03-13 10:38:09 737ae4a34738ffa0c3ff7f9bb18df914dd1cad163f28fd6b6e114a344fe6d618", -1, SQLITE_TRANSIENT);}/*@@ -255897,9 +260396,9 @@ static void fts5LocaleFunc(sqlite3_value **apArg /* Function arguments */){const char *zLocale = 0;- int nLocale = 0;+ i64 nLocale = 0;const char *zText = 0;- int nText = 0;+ i64 nText = 0;assert( nArg==2 );UNUSED_PARAM(nArg);@@ -255916,10 +260415,10 @@ static void fts5LocaleFunc(Fts5Global *p = (Fts5Global*)sqlite3_user_data(pCtx);u8 *pBlob = 0;u8 *pCsr = 0;- int nBlob = 0;+ i64 nBlob = 0;nBlob = FTS5_LOCALE_HDR_SIZE + nLocale + 1 + nText;- pBlob = (u8*)sqlite3_malloc(nBlob);+ pBlob = (u8*)sqlite3_malloc64(nBlob);if( pBlob==0 ){sqlite3_result_error_nomem(pCtx);return;@@ -255997,8 +260496,9 @@ static int fts5IntegrityMethod(" FTS5 table %s.%s: %s",zSchema, zTabname, sqlite3_errstr(rc));}+ }else if( (rc&0xff)==SQLITE_CORRUPT ){+ rc = SQLITE_OK;}-sqlite3Fts5IndexCloseReader(pTab->p.pIndex);pTab->p.pConfig->pzErrmsg = 0;@@ -256099,8 +260599,8 @@ static int fts5Init(sqlite3 *db){** its entry point to enable the matchinfo() demo. */#ifdef SQLITE_FTS5_ENABLE_TEST_MIif( rc==SQLITE_OK ){- extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);- rc = sqlite3Fts5TestRegisterMatchinfo(db);+ extern int sqlite3Fts5TestRegisterMatchinfoAPI(fts5_api*);+ rc = sqlite3Fts5TestRegisterMatchinfoAPI(&pGlobal->api);}#endif@@ -256689,6 +261189,7 @@ static int fts5StorageDeleteFromIndex(for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){if( pConfig->abUnindexed[iCol-1]==0 ){sqlite3_value *pVal = 0;+ sqlite3_value *pFree = 0;const char *pText = 0;int nText = 0;const char *pLoc = 0;@@ -256705,11 +261206,22 @@ static int fts5StorageDeleteFromIndex(if( pConfig->bLocale && sqlite3Fts5IsLocaleValue(pConfig, pVal) ){rc = sqlite3Fts5DecodeLocaleValue(pVal, &pText, &nText, &pLoc, &nLoc);}else{- pText = (const char*)sqlite3_value_text(pVal);- nText = sqlite3_value_bytes(pVal);- if( pConfig->bLocale && pSeek ){- pLoc = (const char*)sqlite3_column_text(pSeek, iCol + pConfig->nCol);- nLoc = sqlite3_column_bytes(pSeek, iCol + pConfig->nCol);+ if( sqlite3_value_type(pVal)!=SQLITE_TEXT ){+ /* Make a copy of the value to work with. This is because the call+ ** to sqlite3_value_text() below forces the type of the value to+ ** SQLITE_TEXT, and we may need to use it again later. */+ pFree = pVal = sqlite3_value_dup(pVal);+ if( pVal==0 ){+ rc = SQLITE_NOMEM;+ }+ }+ if( rc==SQLITE_OK ){+ pText = (const char*)sqlite3_value_text(pVal);+ nText = sqlite3_value_bytes(pVal);+ if( pConfig->bLocale && pSeek ){+ pLoc = (const char*)sqlite3_column_text(pSeek, iCol+pConfig->nCol);+ nLoc = sqlite3_column_bytes(pSeek, iCol + pConfig->nCol);+ }}}@@ -256725,6 +261237,7 @@ static int fts5StorageDeleteFromIndex(}sqlite3Fts5ClearLocale(pConfig);}+ sqlite3_value_free(pFree);}}if( rc==SQLITE_OK && p->nTotalRow<1 ){@@ -259938,7 +264451,6 @@ static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){aAscii[0] = 0; /* 0x00 is never a token character */}-/*** 2015 May 30**@@ -260479,12 +264991,12 @@ static int fts5VocabInitVtab(*pzErr = sqlite3_mprintf("wrong number of vtable arguments");rc = SQLITE_ERROR;}else{- int nByte; /* Bytes of space to allocate */+ i64 nByte; /* Bytes of space to allocate */const char *zDb = bDb ? argv[3] : argv[1];const char *zTab = bDb ? argv[4] : argv[3];const char *zType = bDb ? argv[5] : argv[4];- int nDb = (int)strlen(zDb)+1;- int nTab = (int)strlen(zTab)+1;+ i64 nDb = strlen(zDb)+1;+ i64 nTab = strlen(zTab)+1;int eType = 0;rc = fts5VocabTableType(zType, pzErr, &eType);@@ -260682,7 +265194,12 @@ static int fts5VocabOpenMethod(return rc;}+/*+** Restore cursor pCsr to the state it was in immediately after being+** created by the xOpen() method.+*/static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){+ int nCol = pCsr->pFts5->pConfig->nCol;pCsr->rowid = 0;sqlite3Fts5IterClose(pCsr->pIter);sqlite3Fts5StructureRelease(pCsr->pStruct);@@ -260692,6 +265209,12 @@ static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){pCsr->nLeTerm = -1;pCsr->zLeTerm = 0;pCsr->bEof = 0;+ pCsr->iCol = 0;+ pCsr->iInstPos = 0;+ pCsr->iInstOff = 0;+ pCsr->colUsed = 0;+ memset(pCsr->aCnt, 0, sizeof(i64)*nCol);+ memset(pCsr->aDoc, 0, sizeof(i64)*nCol);}/*diff --git a/vendored/sqlite3/sqlite3.h b/vendored/sqlite3/sqlite3.hindex 082a9f9dc..302f0f5b1 100644--- a/vendored/sqlite3/sqlite3.h+++ b/vendored/sqlite3/sqlite3.h@@ -133,7 +133,7 @@ extern "C" {**** Since [version 3.6.18] ([dateof:3.6.18]),** SQLite source code has been stored in the-** <a href="http://www.fossil-scm.org/">Fossil configuration management+** <a href="http://fossil-scm.org/">Fossil configuration management** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to** a string which identifies a particular check-in of SQLite** within its configuration management system. ^The SQLITE_SOURCE_ID@@ -146,9 +146,12 @@ extern "C" {** [sqlite3_libversion_number()], [sqlite3_sourceid()],** [sqlite_version()] and [sqlite_source_id()].*/-#define SQLITE_VERSION "3.49.1"-#define SQLITE_VERSION_NUMBER 3049001-#define SQLITE_SOURCE_ID "2025-02-18 13:38:58 873d4e274b4988d260ba8354a9718324a1c26187a4ab4c1cc0227c03d0f10e70"+#define SQLITE_VERSION "3.51.3"+#define SQLITE_VERSION_NUMBER 3051003+#define SQLITE_SOURCE_ID "2026-03-13 10:38:09 737ae4a34738ffa0c3ff7f9bb18df914dd1cad163f28fd6b6e114a344fe6d618"+#define SQLITE_SCM_BRANCH "branch-3.51"+#define SQLITE_SCM_TAGS "release version-3.51.3"+#define SQLITE_SCM_DATETIME "2026-03-13T10:38:09.694Z"/*** CAPI3REF: Run-Time Library Version Numbers@@ -168,9 +171,9 @@ extern "C" {** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );** </pre></blockquote>)^**-** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]-** macro. ^The sqlite3_libversion() function returns a pointer to the-** to the sqlite3_version[] string constant. The sqlite3_libversion()+** ^The sqlite3_version[] string constant contains the text of the+** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a+** pointer to the sqlite3_version[] string constant. The sqlite3_libversion()** function is provided for use in DLLs since DLL users usually do not have** direct access to string constants within the DLL. ^The** sqlite3_libversion_number() function returns an integer equal to@@ -370,7 +373,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);** without having to use a lot of C code.**** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,-** semicolon-separate SQL statements passed into its 2nd argument,+** semicolon-separated SQL statements passed into its 2nd argument,** in the context of the [database connection] passed in as its 1st** argument. ^If the callback function of the 3rd argument to** sqlite3_exec() is not NULL, then it is invoked for each result row@@ -403,7 +406,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);** result row is NULL then the corresponding string pointer for the** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the** sqlite3_exec() callback is an array of pointers to strings where each-** entry represents the name of corresponding result column as obtained+** entry represents the name of a corresponding result column as obtained** from [sqlite3_column_name()].**** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer@@ -497,6 +500,9 @@ SQLITE_API int sqlite3_exec(#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))#define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))#define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))+#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8))+#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8))+#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8))#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))@@ -531,6 +537,8 @@ SQLITE_API int sqlite3_exec(#define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))#define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8))#define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8))+#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8))+#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8))#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))#define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))@@ -589,7 +597,7 @@ SQLITE_API int sqlite3_exec(** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into** [sqlite3_open_v2()] does *not* cause the underlying database file** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into-** [sqlite3_open_v2()] has historically be a no-op and might become an+** [sqlite3_open_v2()] has historically been a no-op and might become an** error in future versions of SQLite.*/#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */@@ -683,7 +691,7 @@ SQLITE_API int sqlite3_exec(** SQLite uses one of these integer values as the second** argument to calls it makes to the xLock() and xUnlock() methods** of an [sqlite3_io_methods] object. These values are ordered from-** lest restrictive to most restrictive.+** least restrictive to most restrictive.**** The argument to xLock() is always SHARED or higher. The argument to** xUnlock is either SHARED or NONE.@@ -924,7 +932,7 @@ struct sqlite3_io_methods {** connection. See also [SQLITE_FCNTL_FILE_POINTER].**** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]-** No longer in use.+** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used.**** <li>[[SQLITE_FCNTL_SYNC]]** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and@@ -999,7 +1007,7 @@ struct sqlite3_io_methods {**** <li>[[SQLITE_FCNTL_VFSNAME]]** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of-** all [VFSes] in the VFS stack. The names are of all VFS shims and the+** all [VFSes] in the VFS stack. The names of all VFS shims and the** final bottom-level VFS are written into memory obtained from** [sqlite3_malloc()] and the result is stored in the char* variable** that the fourth parameter of [sqlite3_file_control()] points to.@@ -1013,7 +1021,7 @@ struct sqlite3_io_methods {** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level** [VFSes] currently in use. ^(The argument X in** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be-** of type "[sqlite3_vfs] **". This opcodes will set *X+** of type "[sqlite3_vfs] **". This opcode will set *X** to a pointer to the top-level VFS.)^** ^When there are multiple VFS shims in the stack, this opcode finds the** upper-most shim only.@@ -1163,6 +1171,12 @@ struct sqlite3_io_methods {** the value that M is to be set to. Before returning, the 32-bit signed** integer is overwritten with the previous value of M.**+** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]]+** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the+** VFS to block when taking a SHARED lock to connect to a wal mode database.+** This is used to implement the functionality associated with+** SQLITE_SETLK_BLOCK_ON_CONNECT.+**** <li>[[SQLITE_FCNTL_DATA_VERSION]]** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to** a database file. The argument is a pointer to a 32-bit unsigned integer.@@ -1197,7 +1211,7 @@ struct sqlite3_io_methods {** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect** whether or not there is a database client in another process with a wal-mode-** transaction open on the database or not. It is only available on unix.The+** transaction open on the database or not. It is only available on unix. The** (void*) argument passed with this file-control should be a pointer to a** value of type (int). The integer value is set to 1 if the database is a wal** mode database and there exists at least one client in another process that@@ -1215,6 +1229,15 @@ struct sqlite3_io_methods {** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control** purges the contents of the in-memory page cache. If there is an open** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.+**+** <li>[[SQLITE_FCNTL_FILESTAT]]+** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information+** about the [sqlite3_file] objects used access the database and journal files+** for the given schema. The fourth parameter to [sqlite3_file_control()]+** should be an initialized [sqlite3_str] pointer. JSON text describing+** various aspects of the sqlite3_file object is appended to the sqlite3_str.+** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time+** options are used to enable it.** </ul>*/#define SQLITE_FCNTL_LOCKSTATE 1@@ -1259,6 +1282,8 @@ struct sqlite3_io_methods {#define SQLITE_FCNTL_CKSM_FILE 41#define SQLITE_FCNTL_RESET_CACHE 42#define SQLITE_FCNTL_NULL_IO 43+#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44+#define SQLITE_FCNTL_FILESTAT 45/* deprecated names */#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE@@ -1621,7 +1646,7 @@ struct sqlite3_vfs {** SQLite interfaces so that an application usually does not need to** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]** calls sqlite3_initialize() so the SQLite library will be automatically-** initialized when [sqlite3_open()] is called if it has not be initialized+** initialized when [sqlite3_open()] is called if it has not been initialized** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]** compile-time option, then the automatic calls to sqlite3_initialize()** are omitted and the application must call sqlite3_initialize() directly@@ -1878,21 +1903,21 @@ struct sqlite3_mem_methods {** The [sqlite3_mem_methods]** structure is filled with the currently defined memory allocation routines.)^** This option can be used to overload the default memory allocation-** routines with a wrapper that simulations memory allocation failure or+** routines with a wrapper that simulates memory allocation failure or** tracks memory usage, for example. </dd>**** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>-** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of+** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes a single argument of** type int, interpreted as a boolean, which if true provides a hint to** SQLite that it should avoid large memory allocations if possible.** SQLite will run faster if it is free to make large memory allocations,-** but some application might prefer to run slower in exchange for+** but some applications might prefer to run slower in exchange for** guarantees about memory fragmentation that are possible if large** allocations are avoided. This hint is normally off.** </dd>**** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>-** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,+** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes a single argument of type int,** interpreted as a boolean, which enables or disables the collection of** memory allocation statistics. ^(When memory allocation statistics are** disabled, the following SQLite interfaces become non-operational:@@ -1937,7 +1962,7 @@ struct sqlite3_mem_methods {** ^If pMem is NULL and N is non-zero, then each database connection** does an initial bulk allocation for page cache memory** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or-** of -1024*N bytes if N is negative, . ^If additional+** of -1024*N bytes if N is negative. ^If additional** page cache memory is needed beyond what is provided by the initial** allocation, then SQLite goes to [sqlite3_malloc()] separately for each** additional cache line. </dd>@@ -1966,7 +1991,7 @@ struct sqlite3_mem_methods {** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a** pointer to an instance of the [sqlite3_mutex_methods] structure.** The argument specifies alternative low-level mutex routines to be used-** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of+** in place of the mutex routines built into SQLite.)^ ^SQLite makes a copy of** the content of the [sqlite3_mutex_methods] structure before the call to** [sqlite3_config()] returns. ^If SQLite is compiled with** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then@@ -1989,13 +2014,16 @@ struct sqlite3_mem_methods {**** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine-** the default size of lookaside memory on each [database connection].+** the default size of [lookaside memory] on each [database connection].** The first argument is the-** size of each lookaside buffer slot and the second is the number of-** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE-** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]-** option to [sqlite3_db_config()] can be used to change the lookaside-** configuration on individual connections.)^ </dd>+** size of each lookaside buffer slot ("sz") and the second is the number of+** slots allocated to each database connection ("cnt").)^+** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size.+** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can+** be used to change the lookaside configuration on individual connections.)^+** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the+** default lookaside configuration at compile-time.+** </dd>**** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is@@ -2005,7 +2033,7 @@ struct sqlite3_mem_methods {**** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which-** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of+** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies off** the current page cache implementation into that object.)^ </dd>**** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>@@ -2022,7 +2050,7 @@ struct sqlite3_mem_methods {** the logger function is a copy of the first parameter to the corresponding** [sqlite3_log()] call and is intended to be a [result code] or an** [extended result code]. ^The third parameter passed to the logger is-** log message after formatting via [sqlite3_snprintf()].+** a log message after formatting via [sqlite3_snprintf()].** The SQLite logging interface is not reentrant; the logger function** supplied by the application must not invoke any SQLite interface.** In a multi-threaded application, the application-defined logger@@ -2213,7 +2241,7 @@ struct sqlite3_mem_methods {** These constants are the available integer configuration options that** can be passed as the second parameter to the [sqlite3_db_config()] interface.**-** The [sqlite3_db_config()] interface is a var-args functions. It takes a+** The [sqlite3_db_config()] interface is a var-args function. It takes a** variable number of parameters, though always at least two. The number of** parameters passed into sqlite3_db_config() depends on which of these** constants is given as the second parameter. This documentation page@@ -2232,31 +2260,50 @@ struct sqlite3_mem_methods {** [[SQLITE_DBCONFIG_LOOKASIDE]]** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the-** configuration of the lookaside memory allocator within a database+** configuration of the [lookaside memory allocator] within a database** connection.** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i>** in the [DBCONFIG arguments|usual format].** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two,** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE** should have a total of five parameters.-** ^The first argument (the third parameter to [sqlite3_db_config()] is a+** <ol>+** <li><p>The first argument ("buf") is a** pointer to a memory buffer to use for lookaside memory.-** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb-** may be NULL in which case SQLite will allocate the-** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the-** size of each lookaside buffer slot. ^The third argument is the number of-** slots. The size of the buffer in the first argument must be greater than-** or equal to the product of the second and third arguments. The buffer-** must be aligned to an 8-byte boundary. ^If the second argument to-** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally-** rounded down to the next smaller multiple of 8. ^(The lookaside memory+** The first argument may be NULL in which case SQLite will allocate the+** lookaside buffer itself using [sqlite3_malloc()].+** <li><P>The second argument ("sz") is the+** size of each lookaside buffer slot. Lookaside is disabled if "sz"+** is less than 8. The "sz" argument should be a multiple of 8 less than+** 65536. If "sz" does not meet this constraint, it is reduced in size until+** it does.+** <li><p>The third argument ("cnt") is the number of slots. Lookaside is disabled+** if "cnt"is less than 1. The "cnt" value will be reduced, if necessary, so+** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt"+** parameter is usually chosen so that the product of "sz" and "cnt" is less+** than 1,000,000.+** </ol>+** <p>If the "buf" argument is not NULL, then it must+** point to a memory buffer with a size that is greater than+** or equal to the product of "sz" and "cnt".+** The buffer must be aligned to an 8-byte boundary.+** The lookaside memory** configuration for a database connection can only be changed when that** connection is not currently using lookaside memory, or in other words-** when the "current value" returned by-** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero.+** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero.** Any attempt to change the lookaside memory configuration when lookaside** memory is in use leaves the configuration unchanged and returns-** [SQLITE_BUSY].)^</dd>+** [SQLITE_BUSY].+** If the "buf" argument is NULL and an attempt+** to allocate memory based on "sz" and "cnt" fails, then+** lookaside is silently disabled.+** <p>+** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the+** default lookaside configuration at initialization. The+** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside+** configuration at compile-time. Typical values for lookaside are 1200 for+** "sz" and 40 to 100 for "cnt".+** </dd>**** [[SQLITE_DBCONFIG_ENABLE_FKEY]]** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>@@ -2306,17 +2353,20 @@ struct sqlite3_mem_methods {**** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>-** <dd> ^This option is used to enable or disable the-** [fts3_tokenizer()] function which is part of the-** [FTS3] full-text search engine extension.-** There must be two additional arguments.-** The first argument is an integer which is 0 to disable fts3_tokenizer() or-** positive to enable fts3_tokenizer() or negative to leave the setting-** unchanged.-** The second parameter is a pointer to an integer into which-** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled-** following this call. The second parameter may be a NULL pointer, in-** which case the new setting is not reported back. </dd>+** <dd> ^This option is used to enable or disable using the+** [fts3_tokenizer()] function - part of the [FTS3] full-text search engine+** extension - without using bound parameters as the parameters. Doing so+** is disabled by default. There must be two additional arguments. The first+** argument is an integer. If it is passed 0, then using fts3_tokenizer()+** without bound parameters is disabled. If it is passed a positive value,+** then calling fts3_tokenizer without bound parameters is enabled. If it+** is passed a negative value, this setting is not modified - this can be+** used to query for the current setting. The second parameter is a pointer+** to an integer into which is written 0 or 1 to indicate the current value+** of this setting (after it is modified, if applicable). The second+** parameter may be a NULL pointer, in which case the value of the setting+** is not reported back. Refer to [FTS3] documentation for further details.+** </dd>**** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>@@ -2328,8 +2378,8 @@ struct sqlite3_mem_methods {** When the first argument to this interface is 1, then only the C-API is** enabled and the SQL function remains disabled. If the first argument to** this interface is 0, then both the C-API and the SQL function are disabled.-** If the first argument is -1, then no changes are made to state of either the-** C-API or the SQL function.+** If the first argument is -1, then no changes are made to the state of either+** the C-API or the SQL function.** The second parameter is a pointer to an integer into which** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface** is disabled or enabled following this call. The second parameter may@@ -2447,7 +2497,7 @@ struct sqlite3_mem_methods {** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates-** the legacy behavior of the [ALTER TABLE RENAME] command such it+** the legacy behavior of the [ALTER TABLE RENAME] command such that it** behaves as it did prior to [version 3.24.0] (2018-06-04). See the** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for** additional information. This feature can also be turned on and off@@ -2496,7 +2546,7 @@ struct sqlite3_mem_methods {** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt>** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates** the legacy file format flag. When activated, this flag causes all newly-** created database file to have a schema format version number (the 4-byte+** created database files to have a schema format version number (the 4-byte** integer found at offset 44 into the database header) of 1. This in turn** means that the resulting database file will be readable and writable by** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,@@ -2523,7 +2573,7 @@ struct sqlite3_mem_methods {** the database handle both when the SQL statement is prepared and when it** is stepped. The flag is set (collection of statistics is enabled)** by default. <p>This option takes two arguments: an integer and a pointer to-** an integer.. The first argument is 1, 0, or -1 to enable, disable, or+** an integer. The first argument is 1, 0, or -1 to enable, disable, or** leave unchanged the statement scanstatus option. If the second argument** is not NULL, then the value of the statement scanstatus setting after** processing the first argument is written into the integer that the second@@ -2566,8 +2616,8 @@ struct sqlite3_mem_methods {** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the** ability of the [ATTACH DATABASE] SQL command to open a database for writing.** This capability is enabled by default. Applications can disable or-** reenable this capability using the current DBCONFIG option. If the-** the this capability is disabled, the [ATTACH] command will still work,+** reenable this capability using the current DBCONFIG option. If+** this capability is disabled, the [ATTACH] command will still work,** but the database will be opened read-only. If this option is disabled,** then the ability to create a new database using [ATTACH] is also disabled,** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]@@ -2601,7 +2651,7 @@ struct sqlite3_mem_methods {**** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the** overall call to [sqlite3_db_config()] has a total of four parameters.-** The first argument (the third parameter to sqlite3_db_config()) is a integer.+** The first argument (the third parameter to sqlite3_db_config()) is an integer.** The second argument is a pointer to an integer. If the first argument is 1,** then the option becomes enabled. If the first integer argument is 0, then the** option is disabled. If the first argument is -1, then the option setting@@ -2891,7 +2941,7 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*);** ^These routines return 0 if the statement is incomplete. ^If a** memory allocation fails, then SQLITE_NOMEM is returned.**-** ^These routines do not parse the SQL statements thus+** ^These routines do not parse the SQL statements and thus** will not detect syntactically incorrect SQL.**** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior@@ -2993,6 +3043,44 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);*/SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);+/*+** CAPI3REF: Set the Setlk Timeout+** METHOD: sqlite3+**+** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If+** the VFS supports blocking locks, it sets the timeout in ms used by+** eligible locks taken on wal mode databases by the specified database+** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does+** not support blocking locks, this function is a no-op.+**+** Passing 0 to this function disables blocking locks altogether. Passing+** -1 to this function requests that the VFS blocks for a long time -+** indefinitely if possible. The results of passing any other negative value+** are undefined.+**+** Internally, each SQLite database handle stores two timeout values - the+** busy-timeout (used for rollback mode databases, or if the VFS does not+** support blocking locks) and the setlk-timeout (used for blocking locks+** on wal-mode databases). The sqlite3_busy_timeout() method sets both+** values, this function sets only the setlk-timeout value. Therefore,+** to configure separate busy-timeout and setlk-timeout values for a single+** database handle, call sqlite3_busy_timeout() followed by this function.+**+** Whenever the number of connections to a wal mode database falls from+** 1 to 0, the last connection takes an exclusive lock on the database,+** then checkpoints and deletes the wal file. While it is doing this, any+** new connection that tries to read from the database fails with an+** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is+** passed to this API, the new connection blocks until the exclusive lock+** has been released.+*/+SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags);++/*+** CAPI3REF: Flags for sqlite3_setlk_timeout()+*/+#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01+/*** CAPI3REF: Convenience Routines For Running Queries** METHOD: sqlite3@@ -3000,7 +3088,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);** This is a legacy interface that is preserved for backwards compatibility.** Use of this interface is not recommended.**-** Definition: A <b>result table</b> is memory data structure created by the+** Definition: A <b>result table</b> is a memory data structure created by the** [sqlite3_get_table()] interface. A result table records the** complete query results from one or more queries.**@@ -3143,7 +3231,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);** ^Calling sqlite3_free() with a pointer previously returned** by sqlite3_malloc() or sqlite3_realloc() releases that memory so** that it might be reused. ^The sqlite3_free() routine is-** a no-op if is called with a NULL pointer. Passing a NULL pointer+** a no-op if it is called with a NULL pointer. Passing a NULL pointer** to sqlite3_free() is harmless. After being freed, memory** should neither be read nor written. Even reading previously freed** memory might result in a segmentation fault or other severe error.@@ -3161,13 +3249,13 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);** sqlite3_free(X).** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation** of at least N bytes in size or NULL if insufficient memory is available.-** ^If M is the size of the prior allocation, then min(N,M) bytes-** of the prior allocation are copied into the beginning of buffer returned+** ^If M is the size of the prior allocation, then min(N,M) bytes of the+** prior allocation are copied into the beginning of the buffer returned** by sqlite3_realloc(X,N) and the prior allocation is freed.** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the** prior allocation is not freed.**-** ^The sqlite3_realloc64(X,N) interfaces works the same as+** ^The sqlite3_realloc64(X,N) interface works the same as** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead** of a 32-bit signed integer.**@@ -3217,7 +3305,7 @@ SQLITE_API sqlite3_uint64 sqlite3_msize(void*);** was last reset. ^The values returned by [sqlite3_memory_used()] and** [sqlite3_memory_highwater()] include any overhead** added by SQLite in its implementation of [sqlite3_malloc()],-** but not overhead added by the any underlying system library+** but not overhead added by any underlying system library** routines that [sqlite3_malloc()] may call.**** ^The memory high-water mark is reset to the current value of@@ -3669,7 +3757,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);** there is no harm in trying.)**** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>-** <dd>The database is opened [shared cache] enabled, overriding+** <dd>The database is opened with [shared cache] enabled, overriding** the default shared cache setting provided by** [sqlite3_enable_shared_cache()].)^** The [use of shared cache mode is discouraged] and hence shared cache@@ -3677,7 +3765,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);** this option is a no-op.**** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>-** <dd>The database is opened [shared cache] disabled, overriding+** <dd>The database is opened with [shared cache] disabled, overriding** the default shared cache setting provided by** [sqlite3_enable_shared_cache()].)^**@@ -4012,7 +4100,7 @@ SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);**** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of** database filename D with corresponding journal file J and WAL file W and-** with N URI parameters key/values pairs in the array P. The result from+** an array P of N URI Key/Value pairs. The result from** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that** is safe to pass to routines like:** <ul>@@ -4095,7 +4183,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);** subsequent calls to other SQLite interface functions.)^**** ^The sqlite3_errstr(E) interface returns the English-language text-** that describes the [result code] E, as UTF-8, or NULL if E is not an+** that describes the [result code] E, as UTF-8, or NULL if E is not a** result code for which a text error message is available.** ^(Memory to hold the error message string is managed internally** and must not be freed by the application)^.@@ -4103,7 +4191,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename);** ^If the most recent error references a specific token in the input** SQL, the sqlite3_error_offset() interface returns the byte offset** of the start of that token. ^The byte offset returned by-** sqlite3_error_offset() assumes that the input SQL is UTF8.+** sqlite3_error_offset() assumes that the input SQL is UTF-8.** ^If the most recent error does not reference a specific token in the input** SQL, then the sqlite3_error_offset() function returns -1.**@@ -4128,6 +4216,34 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*);SQLITE_API const char *sqlite3_errstr(int);SQLITE_API int sqlite3_error_offset(sqlite3 *db);+/*+** CAPI3REF: Set Error Codes And Message+** METHOD: sqlite3+**+** Set the error code of the database handle passed as the first argument+** to errcode, and the error message to a copy of nul-terminated string+** zErrMsg. If zErrMsg is passed NULL, then the error message is set to+** the default message associated with the supplied error code. Subsequent+** calls to [sqlite3_errcode()] and [sqlite3_errmsg()] and similar will+** return the values set by this routine in place of what was previously+** set by SQLite itself.+**+** This function returns SQLITE_OK if the error code and error message are+** successfully set, SQLITE_NOMEM if an OOM occurs, and SQLITE_MISUSE if+** the database handle is NULL or invalid.+**+** The error code and message set by this routine remains in effect until+** they are changed, either by another call to this routine or until they are+** changed to by SQLite itself to reflect the result of some subsquent+** API call.+**+** This function is intended for use by SQLite extensions or wrappers. The+** idea is that an extension or wrapper can use this routine to set error+** messages and error codes and thus behave more like a core SQLite+** feature from the point of view of an application.+*/+SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zErrMsg);+/*** CAPI3REF: Prepared Statement Object** KEYWORDS: {prepared statement} {prepared statements}@@ -4202,8 +4318,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);**** These constants define various performance limits** that can be lowered at run-time using [sqlite3_limit()].-** The synopsis of the meanings of the various limits is shown below.-** Additional information is available at [limits | Limits in SQLite].+** A concise description of these limits follows, and additional information+** is available at [limits | Limits in SQLite].**** <dl>** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>@@ -4268,7 +4384,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);/*** CAPI3REF: Prepare Flags**-** These constants define various flags that can be passed into+** These constants define various flags that can be passed into the** "prepFlags" parameter of the [sqlite3_prepare_v3()] and** [sqlite3_prepare16_v3()] interfaces.**@@ -4355,7 +4471,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);** there is a small performance advantage to passing an nByte parameter that** is the number of bytes in the input string <i>including</i>** the nul-terminator.-** Note that nByte measure the length of the input in bytes, not+** Note that nByte measures the length of the input in bytes, not** characters, even for the UTF-16 interfaces.**** ^If pzTail is not NULL then *pzTail is made to point to the first byte@@ -4489,7 +4605,7 @@ SQLITE_API int sqlite3_prepare16_v3(**** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory** is available to hold the result, or if the result would exceed the-** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].+** maximum string length determined by the [SQLITE_LIMIT_LENGTH].**** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time@@ -4677,7 +4793,7 @@ typedef struct sqlite3_value sqlite3_value;**** The context in which an SQL function executes is stored in an** sqlite3_context object. ^A pointer to an sqlite3_context object-** is always first parameter to [application-defined SQL functions].+** is always the first parameter to [application-defined SQL functions].** The application-defined SQL function implementation will pass this** pointer through into calls to [sqlite3_result_int | sqlite3_result()],** [sqlite3_aggregate_context()], [sqlite3_user_data()],@@ -4693,7 +4809,7 @@ typedef struct sqlite3_context sqlite3_context;** METHOD: sqlite3_stmt**** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,-** literals may be replaced by a [parameter] that matches one of following+** literals may be replaced by a [parameter] that matches one of the following** templates:**** <ul>@@ -4738,7 +4854,7 @@ typedef struct sqlite3_context sqlite3_context;**** [[byte-order determination rules]] ^The byte-order of** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)-** found in first character, which is removed, or in the absence of a BOM+** found in the first character, which is removed, or in the absence of a BOM** the byte order is the native byte order of the host** machine for sqlite3_bind_text16() or the byte order specified in** the 6th parameter for sqlite3_bind_text64().)^@@ -4758,7 +4874,7 @@ typedef struct sqlite3_context sqlite3_context;** or sqlite3_bind_text16() or sqlite3_bind_text64() then** that parameter must be the byte offset** where the NUL terminator would occur assuming the string were NUL-** terminated. If any NUL characters occurs at byte offsets less than+** terminated. If any NUL characters occur at byte offsets less than** the value of the fourth parameter then the resulting string value will** contain embedded NULs. The result of expressions involving strings** with embedded NULs is undefined.@@ -4801,9 +4917,11 @@ typedef struct sqlite3_context sqlite3_context;** associated with the pointer P of type T. ^D is either a NULL pointer or** a pointer to a destructor function for P. ^SQLite will invoke the** destructor D with a single argument of P when it is finished using-** P. The T parameter should be a static string, preferably a string-** literal. The sqlite3_bind_pointer() routine is part of the-** [pointer passing interface] added for SQLite 3.20.0.+** P, even if the call to sqlite3_bind_pointer() fails. Due to a+** historical design quirk, results are undefined if D is+** SQLITE_TRANSIENT. The T parameter should be a static string,+** preferably a string literal. The sqlite3_bind_pointer() routine is+** part of the [pointer passing interface] added for SQLite 3.20.0.**** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer** for the [prepared statement] or with a prepared statement for which@@ -4970,7 +5088,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);** METHOD: sqlite3_stmt**** ^These routines provide a means to determine the database, table, and-** table column that is the origin of a particular result column in+** table column that is the origin of a particular result column in a** [SELECT] statement.** ^The name of the database or table or column can be returned as** either a UTF-8 or UTF-16 string. ^The _database_ routines return@@ -5108,7 +5226,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);** other than [SQLITE_ROW] before any subsequent invocation of** sqlite3_step(). Failure to reset the prepared statement using** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from-** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],+** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]),** sqlite3_step() began** calling [sqlite3_reset()] automatically in this circumstance rather** than returning [SQLITE_MISUSE]. This is not considered a compatibility@@ -5414,7 +5532,7 @@ SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);**** ^The sqlite3_finalize() function is called to delete a [prepared statement].** ^If the most recent evaluation of the statement encountered no errors-** or if the statement is never been evaluated, then sqlite3_finalize() returns+** or if the statement has never been evaluated, then sqlite3_finalize() returns** SQLITE_OK. ^If the most recent evaluation of statement S failed, then** sqlite3_finalize(S) returns the appropriate [error code] or** [extended error code].@@ -5539,8 +5657,8 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);**** For best security, the [SQLITE_DIRECTONLY] flag is recommended for** all application-defined SQL functions that do not need to be-** used inside of triggers, view, CHECK constraints, or other elements of-** the database schema. This flags is especially recommended for SQL+** used inside of triggers, views, CHECK constraints, or other elements of+** the database schema. This flag is especially recommended for SQL** functions that have side effects or reveal internal application state.** Without this flag, an attacker might be able to modify the schema of** a database file to include invocations of the function with parameters@@ -5571,7 +5689,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);** [user-defined window functions|available here].**** ^(If the final parameter to sqlite3_create_function_v2() or-** sqlite3_create_window_function() is not NULL, then it is destructor for+** sqlite3_create_window_function() is not NULL, then it is the destructor for** the application data pointer. The destructor is invoked when the function** is deleted, either by being overloaded or when the database connection** closes.)^ ^The destructor is also invoked if the call to@@ -5646,7 +5764,7 @@ SQLITE_API int sqlite3_create_window_function(/*** CAPI3REF: Text Encodings**-** These constant define integer codes that represent the various+** These constants define integer codes that represent the various** text encodings supported by SQLite.*/#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */@@ -5738,7 +5856,7 @@ SQLITE_API int sqlite3_create_window_function(** result.** Every function that invokes [sqlite3_result_subtype()] should have this** property. If it does not, then the call to [sqlite3_result_subtype()]-** might become a no-op if the function is used as term in an+** might become a no-op if the function is used as a term in an** [expression index]. On the other hand, SQL functions that never invoke** [sqlite3_result_subtype()] should avoid setting this property, as the** purpose of this property is to disable certain optimizations that are@@ -5865,7 +5983,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6** sqlite3_value_nochange(X) interface returns true if and only if** the column corresponding to X is unchanged by the UPDATE operation** that the xUpdate method call was invoked to implement and if-** and the prior [xColumn] method call that was invoked to extracted+** the prior [xColumn] method call that was invoked to extract** the value for that column returned without setting a result (probably** because it queried [sqlite3_vtab_nochange()] and found that the column** was unchanging). ^Within an [xUpdate] method, any value for which@@ -5971,7 +6089,7 @@ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);** METHOD: sqlite3_value**** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]-** object D and returns a pointer to that copy. ^The [sqlite3_value] returned+** object V and returns a pointer to that copy. ^The [sqlite3_value] returned** is a [protected sqlite3_value] object even if the input is not.** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a** memory allocation fails. ^If V is a [pointer value], then the result@@ -6009,7 +6127,7 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);** allocation error occurs.**** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is-** determined by the N parameter on first successful call. Changing the+** determined by the N parameter on the first successful call. Changing the** value of N in any subsequent call to sqlite3_aggregate_context() within** the same aggregate function instance will not resize the memory** allocation.)^ Within the xFinal callback, it is customary to set@@ -6138,6 +6256,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi** or a NULL pointer if there were no prior calls to** sqlite3_set_clientdata() with the same values of D and N.** Names are compared using strcmp() and are thus case sensitive.+** It returns 0 on success and SQLITE_NOMEM on allocation failure.**** If P and X are both non-NULL, then the destructor X is invoked with** argument P on the first of the following occurrences:@@ -6171,7 +6290,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi**** Security Warning: These interfaces should not be exposed in scripting** languages or in other circumstances where it might be possible for an-** an attacker to invoke them. Any agent that can invoke these interfaces+** attacker to invoke them. Any agent that can invoke these interfaces** can probably also take control of the process.**** Database connection client data is only available for SQLite@@ -6285,7 +6404,7 @@ typedef void (*sqlite3_destructor_type)(void*);** pointed to by the 2nd parameter are taken as the application-defined** function result. If the 3rd parameter is non-negative, then it** must be the byte offset into the string where the NUL terminator would-** appear if the string where NUL terminated. If any NUL characters occur+** appear if the string were NUL terminated. If any NUL characters occur** in the string at a byte offset that is less than the value of the 3rd** parameter, then the resulting string will contain embedded NULs and the** result of expressions operating on strings with embedded NULs is undefined.@@ -6343,7 +6462,7 @@ typedef void (*sqlite3_destructor_type)(void*);** string and preferably a string literal. The sqlite3_result_pointer()** routine is part of the [pointer passing interface] added for SQLite 3.20.0.**-** If these routines are called from within the different thread+** If these routines are called from within a different thread** than the one containing the application-defined function that received** the [sqlite3_context] pointer, the results are undefined.*/@@ -6749,7 +6868,7 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);** METHOD: sqlite3**** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name-** for the N-th database on database connection D, or a NULL pointer of N is+** for the N-th database on database connection D, or a NULL pointer if N is** out of range. An N value of 0 means the main database file. An N of 1 is** the "temp" schema. Larger values of N correspond to various ATTACH-ed** databases.@@ -6844,7 +6963,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);** <dd>The SQLITE_TXN_READ state means that the database is currently** in a read transaction. Content has been read from the database file** but nothing in the database file has changed. The transaction state-** will advanced to SQLITE_TXN_WRITE if any changes occur and there are+** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are** no other conflicting concurrent write transactions. The transaction** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or** [COMMIT].</dd>@@ -6853,7 +6972,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);** <dd>The SQLITE_TXN_WRITE state means that the database is currently** in a write transaction. Content has been written to the database file** but has not yet committed. The transaction state will change to-** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>+** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>*/#define SQLITE_TXN_NONE 0#define SQLITE_TXN_READ 1@@ -7004,6 +7123,8 @@ SQLITE_API int sqlite3_autovacuum_pages(**** ^The second argument is a pointer to the function to invoke when a** row is updated, inserted or deleted in a rowid table.+** ^The update hook is disabled by invoking sqlite3_update_hook()+** with a NULL pointer as the second parameter.** ^The first argument to the callback is a copy of the third argument** to sqlite3_update_hook().** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],@@ -7132,7 +7253,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);** CAPI3REF: Impose A Limit On Heap Size**** These interfaces impose limits on the amount of heap memory that will be-** by all database connections within a single process.+** used by all database connections within a single process.**** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the** soft limit on the amount of heap memory that may be allocated by SQLite.@@ -7190,7 +7311,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);** </ul>)^**** The circumstances under which SQLite will enforce the heap limits may-** changes in future releases of SQLite.+** change in future releases of SQLite.*/SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);@@ -7305,8 +7426,8 @@ SQLITE_API int sqlite3_table_column_metadata(** ^The entry point is zProc.** ^(zProc may be 0, in which case SQLite will try to come up with an** entry point name on its own. It first tries "sqlite3_extension_init".-** If that does not work, it constructs a name "sqlite3_X_init" where the-** X is consists of the lower-case equivalent of all ASCII alphabetic+** If that does not work, it constructs a name "sqlite3_X_init" where+** X consists of the lower-case equivalent of all ASCII alphabetic** characters in the filename from the last "/" to the first following** "." and omitting any initial "lib".)^** ^The sqlite3_load_extension() interface returns@@ -7377,7 +7498,7 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);** ^(Even though the function prototype shows that xEntryPoint() takes** no arguments and returns void, SQLite invokes xEntryPoint() with three** arguments and expects an integer result as if the signature of the-** entry point where as follows:+** entry point were as follows:**** <blockquote><pre>** int xEntryPoint(@@ -7541,7 +7662,7 @@ struct sqlite3_module {** virtual table and might not be checked again by the byte code.)^ ^(The** aConstraintUsage[].omit flag is an optimization hint. When the omit flag** is left in its default setting of false, the constraint will always be-** checked separately in byte code. If the omit flag is change to true, then+** checked separately in byte code. If the omit flag is changed to true, then** the constraint may or may not be checked in byte code. In other words,** when the omit flag is true there is no guarantee that the constraint will** not be checked again using byte code.)^@@ -7567,7 +7688,7 @@ struct sqlite3_module {** The xBestIndex method may optionally populate the idxFlags field with a** mask of SQLITE_INDEX_SCAN_* flags. One such flag is** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN]-** output to show the idxNum has hex instead of as decimal. Another flag is+** output to show the idxNum as hex instead of as decimal. Another flag is** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will** return at most one row.**@@ -7708,7 +7829,7 @@ struct sqlite3_index_info {** the implementation of the [virtual table module]. ^The fourth** parameter is an arbitrary client data pointer that is passed through** into the [xCreate] and [xConnect] methods of the virtual table module-** when a new virtual table is be being created or reinitialized.+** when a new virtual table is being created or reinitialized.**** ^The sqlite3_create_module_v2() interface has a fifth parameter which** is a pointer to a destructor for the pClientData. ^SQLite will@@ -7873,7 +7994,7 @@ typedef struct sqlite3_blob sqlite3_blob;** in *ppBlob. Otherwise an [error code] is returned and, unless the error** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided** the API is not misused, it is always safe to call [sqlite3_blob_close()]-** on *ppBlob after this function it returns.+** on *ppBlob after this function returns.**** This function fails with SQLITE_ERROR if any of the following are true:** <ul>@@ -7993,7 +8114,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *);**** ^Returns the size in bytes of the BLOB accessible via the** successfully opened [BLOB handle] in its only argument. ^The-** incremental blob I/O routines can only read or overwriting existing+** incremental blob I/O routines can only read or overwrite existing** blob content; they cannot change the size of a blob.**** This routine only works on a [BLOB handle] which has been created@@ -8143,7 +8264,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);** ^The sqlite3_mutex_alloc() routine allocates a new** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()** routine returns NULL if it is unable to allocate the requested-** mutex. The argument to sqlite3_mutex_alloc() must one of these+** mutex. The argument to sqlite3_mutex_alloc() must be one of these** integer constants:**** <ul>@@ -8376,7 +8497,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);** CAPI3REF: Retrieve the mutex for a database connection** METHOD: sqlite3**-** ^This interface returns a pointer the [sqlite3_mutex] object that+** ^This interface returns a pointer to the [sqlite3_mutex] object that** serializes access to the [database connection] given in the argument** when the [threading mode] is Serialized.** ^If the [threading mode] is Single-thread or Multi-thread then this@@ -8499,7 +8620,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);** CAPI3REF: SQL Keyword Checking**** These routines provide access to the set of SQL language keywords-** recognized by SQLite. Applications can uses these routines to determine+** recognized by SQLite. Applications can use these routines to determine** whether or not a specific identifier needs to be escaped (for example,** by enclosing in double-quotes) so as not to confuse the parser.**@@ -8667,7 +8788,7 @@ SQLITE_API void sqlite3_str_reset(sqlite3_str*);** content of the dynamic string under construction in X. The value** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X** and might be freed or altered by any subsequent method on the same-** [sqlite3_str] object. Applications must not used the pointer returned+** [sqlite3_str] object. Applications must not use the pointer returned by** [sqlite3_str_value(X)] after any subsequent method call on the same** object. ^Applications may change the content of the string returned** by [sqlite3_str_value(X)] as long as they do not write into any bytes@@ -8753,7 +8874,7 @@ SQLITE_API int sqlite3_status64(** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]** buffer and where forced to overflow to [sqlite3_malloc()]. The** returned value includes allocations that overflowed because they-** where too large (they were larger than the "sz" parameter to+** were too large (they were larger than the "sz" parameter to** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because** no space was left in the page cache.</dd>)^**@@ -8812,9 +8933,18 @@ SQLITE_API int sqlite3_status64(** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a** non-zero [error code] on failure.**+** ^The sqlite3_db_status64(D,O,C,H,R) routine works exactly the same+** way as sqlite3_db_status(D,O,C,H,R) routine except that the C and H+** parameters are pointer to 64-bit integers (type: sqlite3_int64) instead+** of pointers to 32-bit integers, which allows larger status values+** to be returned. If a status value exceeds 2,147,483,647 then+** sqlite3_db_status() will truncate the value whereas sqlite3_db_status64()+** will return the full value.+**** See also: [sqlite3_status()] and [sqlite3_stmt_status()].*/SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);+SQLITE_API int sqlite3_db_status64(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int);/*** CAPI3REF: Status Parameters for database connections@@ -8837,28 +8967,29 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>** <dd>This parameter returns the number of malloc attempts that were** satisfied using lookaside memory. Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>-** <dd>This parameter returns the number malloc attempts that might have+** <dd>This parameter returns the number of malloc attempts that might have** been satisfied using lookaside memory but failed due to the amount of** memory requested being larger than the lookaside slot size.** Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>-** <dd>This parameter returns the number malloc attempts that might have+** <dd>This parameter returns the number of malloc attempts that might have** been satisfied using lookaside memory but failed due to all lookaside** memory already being in use.** Only the high-water value is meaningful;-** the current value is always zero.)^+** the current value is always zero.</dd>)^**** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap** memory used by all pager caches associated with the database connection.)^** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.+** </dd>**** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>@@ -8867,10 +8998,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** memory used by that pager cache is divided evenly between the attached** connections.)^ In other words, if none of the pager caches associated** with the database connection are shared, this request returns the same-** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are+** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are** shared, the value returned by this call will be smaller than that returned** by DBSTATUS_CACHE_USED. ^The highwater mark associated with-** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.+** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd>**** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap@@ -8880,6 +9011,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** schema memory is shared with other database connections due to** [shared cache mode] being enabled.** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.+** </dd>**** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>** <dd>This parameter returns the approximate number of bytes of heap@@ -8909,6 +9041,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** If an IO or other error occurs while writing a page to disk, the effect** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.+** <p>+** ^(There is overlap between the quantities measured by this parameter+** (SQLITE_DBSTATUS_CACHE_WRITE) and SQLITE_DBSTATUS_TEMPBUF_SPILL.+** Resetting one will reduce the other.)^** </dd>**** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>@@ -8916,7 +9052,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** been written to disk in the middle of a transaction due to the page** cache overflowing. Transactions are more efficient if they are written** to disk all at once. When pages spill mid-transaction, that introduces-** additional overhead. This parameter can be used help identify+** additional overhead. This parameter can be used to help identify** inefficiencies that can be resolved by increasing the cache size.** </dd>**@@ -8924,6 +9060,18 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r** <dd>This parameter returns zero for the current value if and only if** all foreign key constraints (deferred or immediate) have been** resolved.)^ ^The highwater mark is always 0.+**+** [[SQLITE_DBSTATUS_TEMPBUF_SPILL] ^(<dt>SQLITE_DBSTATUS_TEMPBUF_SPILL</dt>+** <dd>^(This parameter returns the number of bytes written to temporary+** files on disk that could have been kept in memory had sufficient memory+** been available. This value includes writes to intermediate tables that+** are part of complex queries, external sorts that spill to disk, and+** writes to TEMP tables.)^+** ^The highwater mark is always 0.+** <p>+** ^(There is overlap between the quantities measured by this parameter+** (SQLITE_DBSTATUS_TEMPBUF_SPILL) and SQLITE_DBSTATUS_CACHE_WRITE.+** Resetting one will reduce the other.)^** </dd>** </dl>*/@@ -8940,7 +9088,8 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r#define SQLITE_DBSTATUS_DEFERRED_FKS 10#define SQLITE_DBSTATUS_CACHE_USED_SHARED 11#define SQLITE_DBSTATUS_CACHE_SPILL 12-#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */+#define SQLITE_DBSTATUS_TEMPBUF_SPILL 13+#define SQLITE_DBSTATUS_MAX 13 /* Largest defined DBSTATUS *//*@@ -8987,13 +9136,13 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>** <dd>^This is the number of sort operations that have occurred.** A non-zero value in this counter may indicate an opportunity to-** improvement performance through careful use of indices.</dd>+** improve performance through careful use of indices.</dd>**** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>** <dd>^This is the number of rows inserted into transient indices that** were created automatically in order to help joins run faster.** A non-zero value in this counter may indicate an opportunity to-** improvement performance by adding permanent indices that do not+** improve performance by adding permanent indices that do not** need to be reinitialized each time the statement is run.</dd>**** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>@@ -9002,19 +9151,19 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** to 2147483647. The number of virtual machine operations can be** used as a proxy for the total work done by the prepared statement.** If the number of virtual machine operations exceeds 2147483647-** then the value returned by this statement status code is undefined.+** then the value returned by this statement status code is undefined.</dd>**** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>** <dd>^This is the number of times that the prepare statement has been** automatically regenerated due to schema changes or changes to-** [bound parameters] that might affect the query plan.+** [bound parameters] that might affect the query plan.</dd>**** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>** <dd>^This is the number of times that the prepared statement has** been run. A single "run" for the purposes of this counter is one** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].** The counter is incremented on the first [sqlite3_step()] call of each-** cycle.+** cycle.</dd>**** [[SQLITE_STMTSTATUS_FILTER_MISS]]** [[SQLITE_STMTSTATUS_FILTER HIT]]@@ -9024,7 +9173,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);** step was bypassed because a Bloom filter returned not-found. The** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of** times that the Bloom filter returned a find, and thus the join step-** had to be processed as normal.+** had to be processed as normal.</dd>**** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>** <dd>^This is the approximate number of bytes of heap memory@@ -9129,9 +9278,9 @@ struct sqlite3_pcache_page {** SQLite will typically create one cache instance for each open database file,** though this is not guaranteed. ^The** first parameter, szPage, is the size in bytes of the pages that must-** be allocated by the cache. ^szPage will always a power of two. ^The+** be allocated by the cache. ^szPage will always be a power of two. ^The** second parameter szExtra is a number of bytes of extra storage-** associated with each page cache entry. ^The szExtra parameter will+** associated with each page cache entry. ^The szExtra parameter will be** a number less than 250. SQLite will use the** extra szExtra bytes on each page to store metadata about the underlying** database page on disk. The value passed into szExtra depends@@ -9139,17 +9288,17 @@ struct sqlite3_pcache_page {** ^The third argument to xCreate(), bPurgeable, is true if the cache being** created will be used to cache database pages of a file stored on disk, or** false if it is used for an in-memory database. The cache implementation-** does not have to do anything special based with the value of bPurgeable;+** does not have to do anything special based upon the value of bPurgeable;** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will** never invoke xUnpin() except to deliberately delete a page.** ^In other words, calls to xUnpin() on a cache with bPurgeable set to** false will always have the "discard" flag set to true.-** ^Hence, a cache created with bPurgeable false will+** ^Hence, a cache created with bPurgeable set to false will** never contain any unpinned pages.**** [[the xCachesize() page cache method]]** ^(The xCachesize() method may be called at any time by SQLite to set the-** suggested maximum cache-size (number of pages stored by) the cache+** suggested maximum cache-size (number of pages stored) for the cache** instance passed as the first argument. This is the value configured using** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable** parameter, the implementation is not required to do anything with this@@ -9176,12 +9325,12 @@ struct sqlite3_pcache_page {** implementation must return a pointer to the page buffer with its content** intact. If the requested page is not already in the cache, then the** cache implementation should use the value of the createFlag-** parameter to help it determined what action to take:+** parameter to help it determine what action to take:**** <table border=1 width=85% align=center>** <tr><th> createFlag <th> Behavior when page is not already in cache** <tr><td> 0 <td> Do not allocate a new page. Return NULL.-** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.+** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so.** Otherwise return NULL.** <tr><td> 2 <td> Make every effort to allocate a new page. Only return** NULL if allocating a new page is effectively impossible.@@ -9198,7 +9347,7 @@ struct sqlite3_pcache_page {** as its second argument. If the third parameter, discard, is non-zero,** then the page must be evicted from the cache.** ^If the discard parameter is-** zero, then the page may be discarded or retained at the discretion of+** zero, then the page may be discarded or retained at the discretion of the** page cache implementation. ^The page cache implementation** may choose to evict unpinned pages at any time.**@@ -9216,7 +9365,7 @@ struct sqlite3_pcache_page {** When SQLite calls the xTruncate() method, the cache must discard all** existing cache entries with page numbers (keys) greater than or equal** to the value of the iLimit parameter passed to xTruncate(). If any-** of these pages are pinned, they are implicitly unpinned, meaning that+** of these pages are pinned, they become implicitly unpinned, meaning that** they can be safely discarded.**** [[the xDestroy() page cache method]]@@ -9396,7 +9545,7 @@ typedef struct sqlite3_backup sqlite3_backup;** external process or via a database connection other than the one being** used by the backup operation, then the backup will be automatically** restarted by the next call to sqlite3_backup_step(). ^If the source-** database is modified by the using the same database connection as is used+** database is modified by using the same database connection as is used** by the backup operation, then the backup database is automatically** updated at the same time.**@@ -9413,7 +9562,7 @@ typedef struct sqlite3_backup sqlite3_backup;** and may not be used following a call to sqlite3_backup_finish().**** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no-** sqlite3_backup_step() errors occurred, regardless or whether or not+** sqlite3_backup_step() errors occurred, regardless of whether or not** sqlite3_backup_step() completed.** ^If an out-of-memory condition or IO error occurred during any prior** sqlite3_backup_step() call on the same [sqlite3_backup] object, then@@ -9515,7 +9664,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);** application receives an SQLITE_LOCKED error, it may call the** sqlite3_unlock_notify() method with the blocked connection handle as** the first argument to register for a callback that will be invoked-** when the blocking connections current transaction is concluded. ^The+** when the blocking connection's current transaction is concluded. ^The** callback is invoked from within the [sqlite3_step] or [sqlite3_close]** call that concludes the blocking connection's transaction.**@@ -9535,7 +9684,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);** blocked connection already has a registered unlock-notify callback,** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is** called with a NULL pointer as its second argument, then any existing-** unlock-notify callback is canceled. ^The blocked connections+** unlock-notify callback is canceled. ^The blocked connection's** unlock-notify callback may also be canceled by closing the blocked** connection using [sqlite3_close()].**@@ -9705,7 +9854,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);** is the number of pages currently in the write-ahead log file,** including those that were just committed.**-** The callback function should normally return [SQLITE_OK]. ^If an error+** ^The callback function should normally return [SQLITE_OK]. ^If an error** code is returned, that error will propagate back up through the** SQLite code base to cause the statement that provoked the callback** to report an error, though the commit will have still occurred. If the@@ -9713,13 +9862,26 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);** that does not correspond to any valid SQLite error code, the results** are undefined.**-** A single database handle may have at most a single write-ahead log callback-** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any-** previously registered write-ahead log callback. ^The return value is-** a copy of the third parameter from the previous call, if any, or 0.-** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the-** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will-** overwrite any prior [sqlite3_wal_hook()] settings.+** ^A single database handle may have at most a single write-ahead log+** callback registered at one time. ^Calling [sqlite3_wal_hook()]+** replaces the default behavior or previously registered write-ahead+** log callback.+**+** ^The return value is a copy of the third parameter from the+** previous call, if any, or 0.+**+** ^The [sqlite3_wal_autocheckpoint()] interface and the+** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and+** will overwrite any prior [sqlite3_wal_hook()] settings.+**+** ^If a write-ahead log callback is set using this function then+** [sqlite3_wal_checkpoint_v2()] or [PRAGMA wal_checkpoint]+** should be invoked periodically to keep the write-ahead log file+** from growing without bound.+**+** ^Passing a NULL pointer for the callback disables automatic+** checkpointing entirely. To re-enable the default behavior, call+** sqlite3_wal_autocheckpoint(db,1000) or use [PRAGMA wal_checkpoint].*/SQLITE_API void *sqlite3_wal_hook(sqlite3*,@@ -9736,7 +9898,7 @@ SQLITE_API void *sqlite3_wal_hook(** to automatically [checkpoint]** after committing a transaction if there are N or** more frames in the [write-ahead log] file. ^Passing zero or-** a negative value as the nFrame parameter disables automatic+** a negative value as the N parameter disables automatic** checkpoints entirely.**** ^The callback registered by this function replaces any existing callback@@ -9752,9 +9914,10 @@ SQLITE_API void *sqlite3_wal_hook(**** ^Every new [database connection] defaults to having the auto-checkpoint** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]-** pages. The use of this interface-** is only necessary if the default setting is found to be suboptimal-** for a particular application.+** pages.+**+** ^The use of this interface is only necessary if the default setting+** is found to be suboptimal for a particular application.*/SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);@@ -9819,6 +9982,11 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the** addition that it also truncates the log file to zero bytes just prior** to a successful return.+**+** <dt>SQLITE_CHECKPOINT_NOOP<dd>+** ^This mode always checkpoints zero frames. The only reason to invoke+** a NOOP checkpoint is to access the values returned by+** sqlite3_wal_checkpoint_v2() via output parameters *pnLog and *pnCkpt.** </dl>**** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in@@ -9889,6 +10057,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the** meaning of each of these checkpoint modes.*/+#define SQLITE_CHECKPOINT_NOOP -1 /* Do no work at all */#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */@@ -9933,7 +10102,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);** support constraints. In this configuration (which is the default) if** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire** statement is rolled back as if [ON CONFLICT | OR ABORT] had been-** specified as part of the users SQL statement, regardless of the actual+** specified as part of the user's SQL statement, regardless of the actual** ON CONFLICT mode specified.**** If X is non-zero, then the virtual table implementation guarantees@@ -9967,7 +10136,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>** <dd>Calls of the form** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the-** the [xConnect] or [xCreate] methods of a [virtual table] implementation+** [xConnect] or [xCreate] methods of a [virtual table] implementation** identify that virtual table as being safe to use from within triggers** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the** virtual table can do no serious harm even if it is controlled by a@@ -10135,7 +10304,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);** </table>**** ^For the purposes of comparing virtual table output values to see if the-** values are same value for sorting purposes, two NULL values are considered+** values are the same value for sorting purposes, two NULL values are considered** to be the same. In other words, the comparison operator is "IS"** (or "IS NOT DISTINCT FROM") and not "==".**@@ -10145,7 +10314,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int);**** ^A virtual table implementation is always free to return rows in any order** it wants, as long as the "orderByConsumed" flag is not set. ^When the-** the "orderByConsumed" flag is unset, the query planner will add extra+** "orderByConsumed" flag is unset, the query planner will add extra** [bytecode] to ensure that the final results returned by the SQL query are** ordered correctly. The use of the "orderByConsumed" flag and the** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful@@ -10242,7 +10411,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);** sqlite3_vtab_in_next(X,P) should be one of the parameters to the** xFilter method which invokes these routines, and specifically** a parameter that was previously selected for all-at-once IN constraint-** processing use the [sqlite3_vtab_in()] interface in the+** processing using the [sqlite3_vtab_in()] interface in the** [xBestIndex|xBestIndex method]. ^(If the X parameter is not** an xFilter argument that was selected for all-at-once IN constraint** processing, then these routines return [SQLITE_ERROR].)^@@ -10257,7 +10426,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);** ){** // do something with pVal** }-** if( rc!=SQLITE_OK ){+** if( rc!=SQLITE_DONE ){** // an error has occurred** }** </pre></blockquote>)^@@ -10297,7 +10466,7 @@ SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V)** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th** constraint is not available. ^The sqlite3_vtab_rhs_value() interface-** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if+** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if** something goes wrong.**** The sqlite3_vtab_rhs_value() interface is usually only successful if@@ -10325,8 +10494,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** KEYWORDS: {conflict resolution mode}**** These constants are returned by [sqlite3_vtab_on_conflict()] to-** inform a [virtual table] implementation what the [ON CONFLICT] mode-** is for the SQL statement being evaluated.+** inform a [virtual table] implementation of the [ON CONFLICT] mode+** for the SQL statement being evaluated.**** Note that the [SQLITE_IGNORE] constant is also used as a potential** return value from the [sqlite3_set_authorizer()] callback and that@@ -10366,39 +10535,39 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>** <dd>^The "double" variable pointed to by the V parameter will be set to the** query planner's estimate for the average number of rows output from each-** iteration of the X-th loop. If the query planner's estimates was accurate,+** iteration of the X-th loop. If the query planner's estimate was accurate,** then this value will approximate the quotient NVISIT/NLOOP and the** product of this value for all prior loops with the same SELECTID will-** be the NLOOP value for the current loop.+** be the NLOOP value for the current loop.</dd>**** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>** <dd>^The "const char *" variable pointed to by the V parameter will be set** to a zero-terminated UTF-8 string containing the name of the index or table-** used for the X-th loop.+** used for the X-th loop.</dd>**** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>** <dd>^The "const char *" variable pointed to by the V parameter will be set** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]-** description for the X-th loop.+** description for the X-th loop.</dd>**** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt>** <dd>^The "int" variable pointed to by the V parameter will be set to the** id for the X-th query plan element. The id value is unique within the** statement. The select-id is the same value as is output in the first-** column of an [EXPLAIN QUERY PLAN] query.+** column of an [EXPLAIN QUERY PLAN] query.</dd>**** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt>** <dd>The "int" variable pointed to by the V parameter will be set to the-** the id of the parent of the current query element, if applicable, or+** id of the parent of the current query element, if applicable, or** to zero if the query element has no parent. This is the same value as-** returned in the second column of an [EXPLAIN QUERY PLAN] query.+** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd>**** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt>** <dd>The sqlite3_int64 output value is set to the number of cycles,** according to the processor time-stamp counter, that elapsed while the** query element was being processed. This value is not available for** all query elements - if it is unavailable the output variable is-** set to -1.+** set to -1.</dd>** </dl>*/#define SQLITE_SCANSTAT_NLOOP 0@@ -10439,8 +10608,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter.**** Parameter "idx" identifies the specific query element to retrieve statistics-** for. Query elements are numbered starting from zero. A value of -1 may be-** to query for statistics regarding the entire query. ^If idx is out of range+** for. Query elements are numbered starting from zero. A value of -1 may+** retrieve statistics for the entire query. ^If idx is out of range** - less than -1 or greater than or equal to the total number of query** elements used to implement the statement - a non-zero value is returned and** the variable that pOut points to is unchanged.@@ -10483,7 +10652,7 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);** METHOD: sqlite3**** ^If a write-transaction is open on [database connection] D when the-** [sqlite3_db_cacheflush(D)] interface invoked, any dirty+** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty** pages in the pager-cache that are not currently in use are written out** to disk. A dirty page may be in use if a database cursor created by an** active SQL statement is reading from it, or if it is page 1 of a database@@ -10597,8 +10766,8 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);** triggers; and so forth.**** When the [sqlite3_blob_write()] API is used to update a blob column,-** the pre-update hook is invoked with SQLITE_DELETE. This is because the-** in this case the new values are not available. In this case, when a+** the pre-update hook is invoked with SQLITE_DELETE, because+** the new values are not yet available. In this case, when a** callback made with op==SQLITE_DELETE is actually a write using the** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns** the index of the column being written. In other cases, where the@@ -10716,7 +10885,7 @@ typedef struct sqlite3_snapshot {** The [sqlite3_snapshot_get()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(+SQLITE_API int sqlite3_snapshot_get(sqlite3 *db,const char *zSchema,sqlite3_snapshot **ppSnapshot@@ -10765,7 +10934,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(** The [sqlite3_snapshot_open()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(+SQLITE_API int sqlite3_snapshot_open(sqlite3 *db,const char *zSchema,sqlite3_snapshot *pSnapshot@@ -10782,7 +10951,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(** The [sqlite3_snapshot_free()] interface is only available when the** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.*/-SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);+SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot*);/*** CAPI3REF: Compare the ages of two snapshot handles.@@ -10809,7 +10978,7 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);** This interface is only available if SQLite is compiled with the** [SQLITE_ENABLE_SNAPSHOT] option.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(+SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1,sqlite3_snapshot *p2);@@ -10837,7 +11006,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(** This interface is only available if SQLite is compiled with the** [SQLITE_ENABLE_SNAPSHOT] option.*/-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);+SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);/*** CAPI3REF: Serialize a database@@ -10851,7 +11020,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c** For an ordinary on-disk database file, the serialization is just a** copy of the disk file. For an in-memory database or a "TEMP" database,** the serialization is the same sequence of bytes which would be written-** to disk if that database where backed up to disk.+** to disk if that database were backed up to disk.**** The usual case is that sqlite3_serialize() copies the serialization of** the database into memory obtained from [sqlite3_malloc64()] and returns@@ -10860,7 +11029,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations** are made, and the sqlite3_serialize() function will return a pointer** to the contiguous memory representation of the database that SQLite-** is currently using for that database, or NULL if the no such contiguous+** is currently using for that database, or NULL if no such contiguous** memory representation of the database exists. A contiguous memory** representation of the database will usually only exist if there has** been a prior call to [sqlite3_deserialize(D,S,...)] with the same@@ -10911,12 +11080,13 @@ SQLITE_API unsigned char *sqlite3_serialize(**** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the** [database connection] D to disconnect from database S and then-** reopen S as an in-memory database based on the serialization contained-** in P. The serialized database P is N bytes in size. M is the size of-** the buffer P, which might be larger than N. If M is larger than N, and-** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is-** permitted to add content to the in-memory database as long as the total-** size does not exceed M bytes.+** reopen S as an in-memory database based on the serialization+** contained in P. If S is a NULL pointer, the main database is+** used. The serialized database P is N bytes in size. M is the size+** of the buffer P, which might be larger than N. If M is larger than+** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then+** SQLite is permitted to add content to the in-memory database as+** long as the total size does not exceed M bytes.**** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will** invoke sqlite3_free() on the serialization buffer when the database@@ -10931,7 +11101,7 @@ SQLITE_API unsigned char *sqlite3_serialize(** database is currently in a read transaction or is involved in a backup** operation.**-** It is not possible to deserialized into the TEMP database. If the+** It is not possible to deserialize into the TEMP database. If the** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the** function returns SQLITE_ERROR.**@@ -10953,7 +11123,7 @@ SQLITE_API int sqlite3_deserialize(sqlite3 *db, /* The database connection */const char *zSchema, /* Which DB to reopen with the deserialization */unsigned char *pData, /* The serialized database content */- sqlite3_int64 szDb, /* Number bytes in the deserialization */+ sqlite3_int64 szDb, /* Number of bytes in the deserialization */sqlite3_int64 szBuf, /* Total size of buffer pData[] */unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */);@@ -10961,7 +11131,7 @@ SQLITE_API int sqlite3_deserialize(/*** CAPI3REF: Flags for sqlite3_deserialize()**-** The following are allowed values for 6th argument (the F argument) to+** The following are allowed values for the 6th argument (the F argument) to** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.**** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization@@ -10983,6 +11153,54 @@ SQLITE_API int sqlite3_deserialize(#define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */#define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */+/*+** CAPI3REF: Bind array values to the CARRAY table-valued function+**+** The sqlite3_carray_bind(S,I,P,N,F,X) interface binds an array value to+** one of the first argument of the [carray() table-valued function]. The+** S parameter is a pointer to the [prepared statement] that uses the carray()+** functions. I is the parameter index to be bound. P is a pointer to the+** array to be bound, and N is the number of eements in the array. The+** F argument is one of constants [SQLITE_CARRAY_INT32], [SQLITE_CARRAY_INT64],+** [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT], or [SQLITE_CARRAY_BLOB] to+** indicate the datatype of the array being bound. The X argument is not a+** NULL pointer, then SQLite will invoke the function X on the P parameter+** after it has finished using P, even if the call to+** sqlite3_carray_bind() fails. The special-case finalizer+** SQLITE_TRANSIENT has no effect here.+*/+SQLITE_API int sqlite3_carray_bind(+ sqlite3_stmt *pStmt, /* Statement to be bound */+ int i, /* Parameter index */+ void *aData, /* Pointer to array data */+ int nData, /* Number of data elements */+ int mFlags, /* CARRAY flags */+ void (*xDel)(void*) /* Destructor for aData */+);++/*+** CAPI3REF: Datatypes for the CARRAY table-valued function+**+** The fifth argument to the [sqlite3_carray_bind()] interface musts be+** one of the following constants, to specify the datatype of the array+** that is being bound into the [carray table-valued function].+*/+#define SQLITE_CARRAY_INT32 0 /* Data is 32-bit signed integers */+#define SQLITE_CARRAY_INT64 1 /* Data is 64-bit signed integers */+#define SQLITE_CARRAY_DOUBLE 2 /* Data is doubles */+#define SQLITE_CARRAY_TEXT 3 /* Data is char* */+#define SQLITE_CARRAY_BLOB 4 /* Data is struct iovec */++/*+** Versions of the above #defines that omit the initial SQLITE_, for+** legacy compatibility.+*/+#define CARRAY_INT32 0 /* Data is 32-bit signed integers */+#define CARRAY_INT64 1 /* Data is 64-bit signed integers */+#define CARRAY_DOUBLE 2 /* Data is doubles */+#define CARRAY_TEXT 3 /* Data is char* */+#define CARRAY_BLOB 4 /* Data is struct iovec */+/*** Undo the hack that converts floating point types to integer for** builds on processors without floating point support.@@ -11486,9 +11704,10 @@ SQLITE_API void sqlite3session_table_filter(** is inserted while a session object is enabled, then later deleted while** the same session object is disabled, no INSERT record will appear in the** changeset, even though the delete took place while the session was disabled.-** Or, if one field of a row is updated while a session is disabled, and-** another field of the same row is updated while the session is enabled, the-** resulting changeset will contain an UPDATE change that updates both fields.+** Or, if one field of a row is updated while a session is enabled, and+** then another field of the same row is updated while the session is disabled,+** the resulting changeset will contain an UPDATE change that updates both+** fields.*/SQLITE_API int sqlite3session_changeset(sqlite3_session *pSession, /* Session object */@@ -11560,8 +11779,9 @@ SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession** database zFrom the contents of the two compatible tables would be** identical.**-** It an error if database zFrom does not exist or does not contain the-** required compatible table.+** Unless the call to this function is a no-op as described above, it is an+** error if database zFrom does not exist or does not contain the required+** compatible table.**** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg@@ -11696,7 +11916,7 @@ SQLITE_API int sqlite3changeset_start_v2(** The following flags may passed via the 4th parameter to** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:**-** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>+** <dt>SQLITE_CHANGESETSTART_INVERT <dd>** Invert the changeset while iterating through it. This is equivalent to** inverting a changeset using sqlite3changeset_invert() before applying it.** It is an error to specify this flag with a patchset.@@ -12011,19 +12231,6 @@ SQLITE_API int sqlite3changeset_concat(void **ppOut /* OUT: Buffer containing output changeset */);--/*-** CAPI3REF: Upgrade the Schema of a Changeset/Patchset-*/-SQLITE_API int sqlite3changeset_upgrade(- sqlite3 *db,- const char *zDb,- int nIn, const void *pIn, /* Input changeset */- int *pnOut, void **ppOut /* OUT: Inverse of input */-);---/*** CAPI3REF: Changegroup Handle**@@ -12253,14 +12460,32 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** update the "main" database attached to handle db with the changes found in** the changeset passed via the second and third arguments.**+** All changes made by these functions are enclosed in a savepoint transaction.+** If any other error (aside from a constraint failure when attempting to+** write to the target database) occurs, then the savepoint transaction is+** rolled back, restoring the target database to its original state, and an+** SQLite error code returned. Additionally, starting with version 3.51.0,+** an error code and error message that may be accessed using the+** [sqlite3_errcode()] and [sqlite3_errmsg()] APIs are left in the database+** handle.+**** The fourth argument (xFilter) passed to these functions is the "filter-** callback". If it is not NULL, then for each table affected by at least one-** change in the changeset, the filter callback is invoked with-** the table name as the second argument, and a copy of the context pointer-** passed as the sixth argument as the first. If the "filter callback"-** returns zero, then no attempt is made to apply any changes to the table.-** Otherwise, if the return value is non-zero or the xFilter argument to-** is NULL, all changes related to the table are attempted.+** callback". This may be passed NULL, in which case all changes in the+** changeset are applied to the database. For sqlite3changeset_apply() and+** sqlite3_changeset_apply_v2(), if it is not NULL, then it is invoked once+** for each table affected by at least one change in the changeset. In this+** case the table name is passed as the second argument, and a copy of+** the context pointer passed as the sixth argument to apply() or apply_v2()+** as the first. If the "filter callback" returns zero, then no attempt is+** made to apply any changes to the table. Otherwise, if the return value is+** non-zero, all changes related to the table are attempted.+**+** For sqlite3_changeset_apply_v3(), the xFilter callback is invoked once+** per change. The second argument in this case is an sqlite3_changeset_iter+** that may be queried using the usual APIs for the details of the current+** change. If the "filter callback" returns zero in this case, then no attempt+** is made to apply the current change. If it returns non-zero, the change+** is applied.**** For each table that is not excluded by the filter callback, this function** tests that the target database contains a compatible table. A table is@@ -12281,11 +12506,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** one such warning is issued for each table in the changeset.**** For each change for which there is a compatible table, an attempt is made-** to modify the table contents according to the UPDATE, INSERT or DELETE-** change. If a change cannot be applied cleanly, the conflict handler-** function passed as the fifth argument to sqlite3changeset_apply() may be-** invoked. A description of exactly when the conflict handler is invoked for-** each type of change is below.+** to modify the table contents according to each UPDATE, INSERT or DELETE+** change that is not excluded by a filter callback. If a change cannot be+** applied cleanly, the conflict handler function passed as the fifth argument+** to sqlite3changeset_apply() may be invoked. A description of exactly when+** the conflict handler is invoked for each type of change is below.**** Unlike the xFilter argument, xConflict may not be passed NULL. The results** of passing anything other than a valid function pointer as the xConflict@@ -12381,12 +12606,6 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);** This can be used to further customize the application's conflict** resolution strategy.**-** All changes made by these functions are enclosed in a savepoint transaction.-** If any other error (aside from a constraint failure when attempting to-** write to the target database) occurs, then the savepoint transaction is-** rolled back, restoring the target database to its original state, and an-** SQLite error code returned.-**** If the output parameters (ppRebase) and (pnRebase) are non-NULL and** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()** may set (*ppRebase) to point to a "rebase" that may be used with the@@ -12436,6 +12655,23 @@ SQLITE_API int sqlite3changeset_apply_v2(void **ppRebase, int *pnRebase, /* OUT: Rebase data */int flags /* SESSION_CHANGESETAPPLY_* flags */);+SQLITE_API int sqlite3changeset_apply_v3(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int nChangeset, /* Size of changeset in bytes */+ void *pChangeset, /* Changeset blob */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p /* Handle describing change */+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase, /* OUT: Rebase data */+ int flags /* SESSION_CHANGESETAPPLY_* flags */+);/*** CAPI3REF: Flags for sqlite3changeset_apply_v2@@ -12855,6 +13091,23 @@ SQLITE_API int sqlite3changeset_apply_v2_strm(void **ppRebase, int *pnRebase,int flags);+SQLITE_API int sqlite3changeset_apply_v3_strm(+ sqlite3 *db, /* Apply change to "main" db of this handle */+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */+ void *pIn, /* First arg for xInput */+ int(*xFilter)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ sqlite3_changeset_iter *p+ ),+ int(*xConflict)(+ void *pCtx, /* Copy of sixth arg to _apply() */+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */+ sqlite3_changeset_iter *p /* Handle describing change and conflict */+ ),+ void *pCtx, /* First argument passed to xConflict */+ void **ppRebase, int *pnRebase,+ int flags+);SQLITE_API int sqlite3changeset_concat_strm(int (*xInputA)(void *pIn, void *pData, int *pnData),void *pInA,diff --git a/vendored/sqlite3/sqlite3ext.h b/vendored/sqlite3/sqlite3ext.hindex ae0949baf..5258faaed 100644--- a/vendored/sqlite3/sqlite3ext.h+++ b/vendored/sqlite3/sqlite3ext.h@@ -366,6 +366,12 @@ struct sqlite3_api_routines {/* Version 3.44.0 and later */void *(*get_clientdata)(sqlite3*,const char*);int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*));+ /* Version 3.50.0 and later */+ int (*setlk_timeout)(sqlite3*,int,int);+ /* Version 3.51.0 and later */+ int (*set_errmsg)(sqlite3*,int,const char*);+ int (*db_status64)(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int);+};/*@@ -699,6 +705,11 @@ typedef int (*sqlite3_loadext_entry)(/* Version 3.44.0 and later */#define sqlite3_get_clientdata sqlite3_api->get_clientdata#define sqlite3_set_clientdata sqlite3_api->set_clientdata+/* Version 3.50.0 and later */+#define sqlite3_setlk_timeout sqlite3_api->setlk_timeout+/* Version 3.51.0 and later */+#define sqlite3_set_errmsg sqlite3_api->set_errmsg+#define sqlite3_db_status64 sqlite3_api->db_status64#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)