vey-mimalloc-sys 0.3.2+3.7.0

Rust FFI binding to mimalloc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
/* ----------------------------------------------------------------------------
Copyright (c) 2018-2026, Microsoft Research, Daan Leijen
This is free software; you can redistribute it and/or modify it under the
terms of the MIT license. A copy of the license can be found in the file
"LICENSE" at the root of this distribution.
-----------------------------------------------------------------------------*/
#if !defined(MI_IN_ALLOC_C)
#error "this file should be included from 'alloc.c' (so aliases can work from alloc-override)"
#endif

#include "mimalloc.h"
#include "mimalloc/types.h"
#include "mimalloc/prim/prim-tls.h"             // _mi_prim_thread_id()
#include "mimalloc/util/stats.h"
#include "mimalloc/arena/arena-page.h"
#include "mimalloc/arena/arena.h"               // _mi_arena_memid_is_suitable
#include "mimalloc/profile/sample-guarded.h"    // unguard
#include "mimalloc/alloc/page.h"
#include "mimalloc/alloc/free.h"
#include "mimalloc/heap/heap.h"


// forward declarations
mi_decl_nodiscard static bool mi_check_padding_on_free(const mi_page_t* page, const mi_block_t* block, bool is_guarded, size_t* usable_size);
mi_decl_nodiscard static bool mi_check_double_free(const mi_page_t* page, const mi_block_t* block);
static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool was_guarded);

#if (MI_DEBUG>0) && !MI_TRACK_ENABLED && !MI_TSAN
// Fill a block with a debug pattern, preserving the first `heap->debug_fill_preserve` bytes
// (used by CPython to keep object headers intact that may be read by concurrent lock-free readers)
static inline void mi_debug_fill_prim(void* block, int c, size_t size, size_t preserve) {
  if (preserve < size) {
    mi_memset((uint8_t*)block + preserve, c, size - preserve);
  }
}

// Fill by the owning thread: the heap is alive so we use its current setting and refresh the page copy
static inline void mi_debug_fill(mi_page_t* page, void* block, int c, size_t size) {
  const size_t preserve = mi_atomic_load_relaxed(&mi_page_heap(page)->debug_fill_preserve);
  if mi_unlikely(preserve != mi_atomic_load_relaxed(&page->debug_fill_preserve)) {
    mi_atomic_store_relaxed(&page->debug_fill_preserve, preserve);
  }
  mi_debug_fill_prim(block, c, size, preserve);
}

// Fill by a non-owning thread: the page heap may be deleted concurrently (and the page moved),
// so we use the copy in the page instead
static inline void mi_debug_fill_mt(const mi_page_t* page, void* block, int c, size_t size) {
  mi_debug_fill_prim(block, c, size, mi_atomic_load_relaxed(&page->debug_fill_preserve));
}
#endif

// ------------------------------------------------------
// Free
// ------------------------------------------------------

// regular free of a (thread local) block pointer
// fast path written carefully to prevent spilling on the stack

// Prepare a block for freeing: retag memory tagged blocks (which also zeroes small blocks), or at `MI_SECURE>=3`
// zero the block up to `MI_ZERO_ON_FREE_MAX` bytes (so only small blocks are fully zero, see `mi_page_is_zero_on_free`).
// The padding is never cleared as it marks the block as freed.
static inline mi_block_t* mi_block_free_clear(const mi_page_t* page, mi_block_t* block, bool was_guarded, bool memtag) {
  if (was_guarded) return block;
  if (memtag) {
    // the first and last block of a page always have a tag of their class (see `mi_memtag_blocks_init`)
    const size_t bsize = mi_page_block_size(page);
    const void* prev; const void* next;
    const size_t exclude = mi_page_block_memtag_adjacent(page, block, bsize, mi_memtag_class_of(block), &prev, &next);
    return (mi_block_t*)mi_memtag_block_free(block, bsize, exclude, prev, next);
  }
  #if MI_SECURE>=3
  const size_t usize = mi_page_usable_block_size(page);
  mi_memzero_block(block, (usize <= MI_ZERO_ON_FREE_MAX ? usize : MI_ZERO_ON_FREE_MAX));
  #endif
  return block;
}

static inline void mi_free_block_local(mi_page_t* page, mi_block_t* block, bool was_guarded, bool check_full, bool memtag)
{
  // checks
  size_t usable_size;
  if mi_unlikely(!mi_check_padding_on_free(page, block, was_guarded, &usable_size)) return;
  if mi_unlikely(!mi_check_double_free(page,block)) return;  // usually checked with padding

  // mi_stat_free(page, block);
  block = mi_block_free_clear(page, block, was_guarded, memtag);  // (before tracking the free)
  mi_track_free_size(block, usable_size);

  #if (MI_DEBUG>0) && !MI_TRACK_ENABLED  && !MI_TSAN
  const size_t dbgsize = (usable_size > MI_MiB ? MI_MiB : usable_size);
  mi_debug_fill(page, block, MI_DEBUG_FREED, dbgsize);
  #endif

  // actual free: push on the local free list fast-path
  mi_used_t xused = page->xused;
  mi_block_t* lfree = page->local_free;
  xused.used_alloc--;
  mi_block_set_next(page, block, lfree);
  page->xused = xused;
  page->local_free = block;
  const bool is_empty = (mi_xused_used_count(xused) == 0);
  mi_assert_internal(mi_page_alloc_count(page) + mi_page_last_used(page) >= mi_page_used(page));
  if mi_unlikely(is_empty) {      // is used count zero ?
    _mi_page_qsbr_clear(page);    // a new empty interval must not reuse an earlier grace period
    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, bool allow_reclaim) mi_attr_noexcept;

// Free a block multi-threaded
#if defined(_MSC_VER)
static mi_decl_noinline  /* ensures mi_free has no stack frame */
#else
static inline
#endif
void mi_free_block_mt(mi_page_t* page, mi_block_t* block, bool was_guarded, bool allow_reclaim, bool memtag) mi_attr_noexcept
{
  size_t usable_size;
  if mi_unlikely(!mi_check_padding_on_free(page, block, was_guarded, &usable_size)) return;    // checking padding is safe for mt
  block = mi_block_free_clear(page, block, was_guarded, memtag);  // (before tracking the free)
  mi_track_free_size(block, usable_size);

  // _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
  if (!was_guarded) {
    const size_t dbgsize = (usable_size > MI_MiB ? MI_MiB : usable_size);
    mi_debug_fill_mt(page, block, MI_DEBUG_FREED, dbgsize);
  }
  #endif

  // push atomically on the page thread free list
  // mi_theap_t* theap = _mi_page_associated_theap_peek(page);
  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);
  } while(!mi_atomic_cas_weak_acq_rel(&page->xthread_free, &tf_old, tf_new));

  // and atomically try to collect the page if it was abandoned
  mi_assert_internal(mi_tf_is_owned(tf_new));
  const bool is_newly_owned = !mi_tf_is_owned(tf_old); // && mi_tf_is_owned(tf_new)
  if (is_newly_owned) {
    mi_assert_internal(mi_page_is_abandoned(page));
    // mi_assert_internal(!mi_page_is_abandoned_mapped(page));
    mi_free_try_collect_mt(page, block, allow_reclaim);
  }
}


// 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_woffset` and `block_size` fields; however these are constant and the page won't be
// deallocated (as the block we are freeing keeps it alive) and thus safe to read concurrently.

// The index of the block at byte offset `diff` in the page (`diff / block_size`).
static inline size_t mi_page_block_index(const mi_page_t* page, size_t diff) {
  #if MI_FREE_IS_CHECKED
  // `floor(diff * ceil(2^64/block_size) / 2^64) == diff / block_size` if both `diff` and `block_size`
  // are below 2^32 (Lemire, Kaser, and Kurz, "Faster remainder by direct computation", 2019).
  // Pages with a single block have `block_recip == 1` as the block index is always 0.
  mi_assert_internal(page->block_recip==1 || diff <= UINT32_MAX);
  const size_t idx = (size_t)mi_mul_hi64_32((uint32_t)diff, page->block_recip);
  mi_assert_internal(idx == diff / mi_page_block_size(page));
  return idx;
  #else
  return diff / mi_page_block_size(page);
  #endif
}

static inline mi_block_t* mi_page_ptr_unalign_ex(const mi_page_t* page, const void* p, size_t* poffset) {
  mi_assert_internal(page!=NULL && p!=NULL);

  const size_t diff = mi_addr(p) - mi_addr(mi_page_start(page));
  const size_t block_size = mi_page_block_size(page);
  size_t adjust = diff & (block_size - 1);
  if mi_unlikely(!mi_is_power_of_two(block_size)) {
    #if MI_FREE_IS_CHECKED
    adjust = diff - (mi_page_block_index(page, diff) * block_size);  // avoid a (slow) division
    #else
    adjust = diff % block_size;
    #endif
  }
  if (poffset!=NULL) { *poffset = adjust; }
  void* const block = mi_ptr_rederive(mi_page_start(page), p);
  return (mi_block_t*)mi_ptr_with_addr(block, mi_addr(p) - adjust);
}

mi_block_t* _mi_page_ptr_unalign(const mi_page_t* page, const void* p) {
  return mi_page_ptr_unalign_ex(page,p,NULL);
}

// Retag the entire block of `p` with the canonical (meta) tag and return `p` with that tag.
// As the tag no longer determines the class of the block, frees in the page now use the generic path (see `mi_page_ptr_block_check`).
void* _mi_memtag_canonical(void* p) {
  if (p==NULL || mi_ptr_memtag(p)==MI_MEMTAG_META) return p;
  mi_page_t* const page = mi_ptr_page(p);
  mi_block_t* const block = _mi_page_ptr_unalign(page, p);
  mi_memtag_clear(block, mi_page_block_size(page));
  mi_page_set_has_interior_pointers(page, true);  // safe as in `alloc-aligned.c` (the block keeps the page alive)
  return mi_ptr_with_memtag(p, MI_MEMTAG_META);
}

// Get the block from a pointer `p` that is known to point to the start of a block
static inline mi_block_t* mi_block_from_ptr( const mi_page_t* page, const void* p ) {
  mi_assert(_mi_page_ptr_unalign(page,p) == (mi_block_t*)p); // should never be an interior pointer
  return (mi_block_t*)mi_ptr_rederive(mi_page_start(page), p);
}

static inline mi_block_t* mi_validate_block_from_ptr( const mi_page_t* page, const void* p ) {
  #if MI_SECURE>=2
  mi_assert(_mi_page_ptr_unalign(page,p) == (mi_block_t*)p); // should never be an interior pointer
  // in secure mode we always unalign to guard against free-ing interior pointers
  return _mi_page_ptr_unalign(page,p);
  #else
  return mi_block_from_ptr(page,p);
  #endif
}

static inline mi_block_t* mi_page_ptr_block_check(mi_page_t* page, void* p, bool* was_guarded) mi_attr_noexcept {
  MI_UNUSED(was_guarded);
  if mi_likely(!mi_page_has_interior_pointers(page)) {
    return mi_validate_block_from_ptr(page,p);
  }
  else {
    size_t offset;
    mi_block_t* block = mi_page_ptr_unalign_ex(page,p,&offset);
    #if MI_GUARDED || MI_PROFILE
    if (offset >= sizeof(mi_block_t)) {
      #if MI_PROFILE
      if (block->next == MI_BLOCK_TAG_PROFILED) {
        _mi_page_profile_on_free(page,block,p);
      }
      else
      #endif
      #if MI_GUARDED
      if (block->next == MI_BLOCK_TAG_GUARDED) {
        _mi_page_block_unguard(page, block, p);
        *was_guarded = true;
      }
      else
      #endif
      { /* nothing */ }
    }
    #endif
    if mi_unlikely(mi_page_is_memtag(page) && !*was_guarded && mi_ptr_memtag(block)==MI_MEMTAG_META) {  // a canonical block (see `_mi_memtag_canonical`)
      const size_t bsize = mi_page_block_size(page);
      const size_t idx = mi_page_block_index(page, mi_addr(block) - mi_addr(mi_page_start(page))) + mi_page_memtag_parity(page);
      const void* prev; const void* next;
      const size_t exclude = mi_page_block_memtag_adjacent(page, block, bsize, idx, &prev, &next);
      block = (mi_block_t*)mi_memtag_block_uncanonical(block, bsize, exclude, prev, next);
    }
    return block;
  }
}

// free a local pointer  (page parameter comes first for better codegen)
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);
  bool was_guarded = false;
  mi_block_t* block = mi_page_ptr_block_check(page,p,&was_guarded);
  // 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_profiled(page,block,p);
  // const bool was_guarded = mi_block_check_unguard(page, block, p);
  mi_free_block_local(page, block, was_guarded, true /* check for a full page */, mi_page_is_memtag(page));
}

// free a pointer owned by another thread (page parameter comes first for better codegen)
static void mi_decl_noinline mi_free_generic_mt(mi_page_t* page, void* p, bool allow_reclaim) mi_attr_noexcept {
  mi_assert_internal(p!=NULL && page != NULL);
  bool was_guarded = false;
  mi_block_t* block = mi_page_ptr_block_check(page,p,&was_guarded);
  // 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_profiled(page,block,p);
  // const bool was_guarded = mi_block_check_unguard(page, block, p);
  mi_free_block_mt(page, block, was_guarded, allow_reclaim, mi_page_is_memtag(page));
}

// generic free (for runtime integration)
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,true);
}


#if MI_DEBUG || MI_CHERI
// Report an invalid pointer; called in tail position so `mi_free` does not need a stack frame.
static mi_decl_noinline mi_decl_cold bool mi_ptr_invalid(const char* msg, const void* p, const char* reason) {
  _mi_error_message(EINVAL, "%s: invalid pointer%s: %p\n", msg, reason, p);
  return false;
}
#endif

// Get the page belonging to a pointer
// Does further checks in debug mode to see if this was a valid pointer.
static mi_decl_forceinline bool mi_ptr_page_is_valid_ex(const void* p, const char* msg, bool free_small, bool check_p_for_null, mi_page_t** ppage)
{
  MI_UNUSED_RELEASE(msg); MI_UNUSED(free_small);
  mi_page_t* page;
  #if MI_PAGE_META_SMALL_IS_ALIGNED
    if (free_small) {
      const mi_addr_t up = mi_addr(p) & ~MI_ADDR(MI_SMALL_PAGE_SIZE-1);  // like this for codegen on gcc
      if mi_unlikely(up==0 && check_p_for_null) { return false; }
      page = mi_page_meta_load((mi_page_t*)mi_ptr_with_addr(p, up));
    }
    else
  #endif
    {
      #if MI_PAGE_META_IS_ALIGNED
        { page = mi_aligned_ptr_page0(p); }
      #else
        { page = mi_ptr_page(p); }
      #endif
      if mi_unlikely(mi_ptr_page_is_null(p,page) && check_p_for_null) {
        #if MI_DEBUG || MI_CHERI  // on CHERI also report in release (e.g. untagged pointers)
        if (p!=NULL) { return mi_ptr_invalid(msg, p, ""); }
        #endif
        return false;
      }
      #if MI_PAGE_META_IS_ALIGNED
      page = mi_page_meta_load(page);
      #endif
    }
  #if MI_DEBUG
  mi_page_t* const cpage = mi_checked_ptr_page(p);
  if mi_unlikely(cpage==NULL) { mi_ptr_invalid(msg, p, ""); }
  #endif

  #if MI_PAGE_META_IS_ALIGNED
    #if MI_PAGE_META_SMALL_IS_ALIGNED
    if (free_small) { mi_assert_internal(NULL == mi_atomic_load_ptr_acquire(mi_page_t,&page->self)); }
    else
    #elif MI_SMALL_PAGE_SIZE == MI_ARENA_SLICE_SIZE && !MI_GUARDED
    // for mi_free_small we can avoid a load-acquire (but not when guarded as that may still allocate large blocks)
    if (free_small) { mi_assert_internal(page == mi_atomic_load_ptr_acquire(mi_page_t,&page->self)); }
    else
    #endif
    {
      // The `self` load can be relaxed here as we free a known pointer and thus it has been synchronized.
      // However, the ThreadSanitizer seems to require an acquire load to properly track memory dependencies.
      #if MI_TSAN
      page = mi_atomic_load_ptr_acquire(mi_page_t,&page->self);
      #else
      page = mi_atomic_load_ptr_relaxed(mi_page_t,&page->self);
      #endif
    }
  #endif

  mi_assert_internal(page!=NULL);
  mi_assert(cpage==page /* page_map lookup should be the same as aligned lookup */ );
  #if MI_DEBUG && !MI_UNSAFE_GUARDED_PRECISE
  // pointers allocated at an offset (`mi_malloc_aligned_at`) or guarded precise pointers can be unaligned
  if mi_unlikely(!mi_is_aligned(p,MI_SIZE_SIZE) && !mi_page_has_interior_pointers(page)) {
    return mi_ptr_invalid(msg, p, " (unaligned)");
  }
  #endif
  #if !MI_GUARDED
  if (free_small) { mi_assert_internal(page->block_size <= MI_SMALL_MAX_OBJ_SIZE); /* free small should only be called on small pages */ }
  #endif
  #if MI_FREE_IS_CHECKED
  // the page map maps all slices of a page, so `p` may still point below the page start (into the page meta data,
  // guard page, or alignment padding), or beyond the blocks handed out (`capacity`); freeing such pointer would
  // corrupt the free list. The unsigned difference checks both cases at once (as `p < page_start` wraps around).
  if mi_unlikely((size_t)(mi_addr(p) - mi_addr(mi_page_start(page))) >= mi_atomic_load_relaxed(&page->capacity_size)) {
    #if MI_DEBUG
    return mi_ptr_invalid(msg, p, "");
    #else
    return false;
    #endif
  }
  #endif
  #if MI_CHERI && MI_FREE_IS_CHECKED
  // The capability must be unsealed, have data access permissions, and cover its address (`ofs < len`).
  // This also rejects zero-length capabilities (we never hand those out) as these can be validly derived at the end of
  // a neighbouring block, which may be the start of another block.
  const size_t ofs = (size_t)__builtin_cheri_offset_get(p);
  if mi_unlikely(ofs >= (size_t)__builtin_cheri_length_get(p) || __builtin_cheri_sealed_get(p) ||
                 (__builtin_cheri_perms_get(p) & MI_CHERI_PERMS_FREE) != MI_CHERI_PERMS_FREE) {
    return mi_ptr_invalid(msg, p, " (sealed, insufficient permissions, or outside its capability bounds)");
  }
  #endif
  *ppage = page;
  return true;
}

static mi_decl_forceinline bool mi_ptr_page_is_valid(const void* p, const char* msg, mi_page_t** ppage) {
  return mi_ptr_page_is_valid_ex(p,msg,false /* free_small? */, true /* check_p_for_null */, ppage );
}

static mi_decl_forceinline mi_page_t* mi_ptr_page_validate(const void* p, const char* msg) {
  mi_page_t* page;
  return (mi_ptr_page_is_valid(p,msg,&page) ? page : NULL);
}

#if MI_SECURE>=2
// Is `p` at the start of a block? `diff` is a multiple of `block_size` iff `diff * ceil(2^64/block_size) mod 2^64 < ceil(2^64/block_size)`
// (for `diff < 2^32`) (Lemire, Kaser, and Kurz, "Faster remainder by direct computation", 2019).
// With a single block in the page, `block_recip == 1` and this checks `diff == 0`.
static inline bool mi_page_is_block_start(const mi_page_t* page, const void* p) {
  const uint64_t diff = mi_addr(p) - mi_addr(mi_page_start(page));
  return (diff * page->block_recip < page->block_recip);
}

// Free a pointer that is not at the start of a block: either an interior pointer
// (that we unalign to guard against free-ing interior pointers), or a pointer in a page with interior pointers (aligned allocations)
static mi_decl_noinline void mi_free_unaligned(mi_page_t* page, void* p, bool allow_reclaim) mi_attr_noexcept {
  void* const q = (mi_page_has_interior_pointers(page) ? p : (void*)_mi_page_ptr_unalign(page,p));
  if (mi_page_thread_id(page) == _mi_thread_id()) { mi_free_generic_local(page, q); }
                                             else { mi_free_generic_mt(page, q, allow_reclaim); }
}
#endif

// Free a block
// Fast path written carefully to prevent register spilling on the stack
static mi_decl_forceinline void mi_free_nonnull(void* p, mi_page_t* page, size_t* pblock_size, bool allow_reclaim)
{
  mi_assert_internal(p!=NULL && page!=NULL);
  if (pblock_size!=NULL) { *pblock_size = mi_page_block_size(page); }
  #if MI_SECURE>=2
  // in secure mode we guard against free-ing interior pointers (without needing to unalign in the fast path)
  if mi_unlikely(!mi_page_is_block_start(page,p)) { mi_free_unaligned(page, p, allow_reclaim); return; }
  #endif

  const mi_thread_id_t ptid = mi_page_xthread_id(page);
  const mi_thread_id_t xtid = (_mi_prim_thread_id() ^ ptid);
  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_block_from_ptr(page,p);
    mi_free_block_local(page, block, false /* was guarded */, false /* no need to check if the page is full */, false /* memtag */);
  }
  #if MI_MTE
  else if (xtid == MI_PAGE_IS_MEMTAGGED) {  // as the first case but memory tagged
    mi_block_t* const block = mi_block_from_ptr(page,p);
    mi_free_block_local(page, block, false /* was guarded */, false /* no need to check if the page is full */, true /* memtag */);
  }
  #endif
  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_block_from_ptr(page,p);
    mi_free_block_mt(page,block,false /* was_guarded */, allow_reclaim, false /* memtag */);
  }
  #if MI_MTE
  else if ((xtid & MI_PAGE_FLAG_MASK) == MI_PAGE_IS_MEMTAGGED) {  // as the previous case but memory tagged
    mi_block_t* const block = mi_block_from_ptr(page,p);
    mi_free_block_mt(page,block,false /* was_guarded */, allow_reclaim, true /* memtag */);
  }
  #endif
  else {
    // page is full or contains (inner) aligned blocks; use generic multi-thread path
    mi_free_generic_mt(page, p, allow_reclaim);
  }
}

void mi_free(void* p) mi_attr_noexcept {
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid(p,"mi_free",&page)) {
    mi_free_nonnull(p, page, NULL, true /* allow reclaim? */);
  }
}

void mi_ufree(void* p, size_t* pblock_size) mi_attr_noexcept {
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid(p,"mi_ufree",&page)) {
    mi_free_nonnull(p, page, pblock_size, true /* allow reclaim? */);
  }
  else {
    if (pblock_size!=NULL) { *pblock_size = 0; }
  }
}

// Free a pointer that is potentially allocated in a different sub-process
void _mi_free_subproc_safe(void* p) mi_attr_noexcept {
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid(p,"_mi_free_subproc_safe",&page)) {
    // const bool allow_reclaim = (_mi_subproc() == mi_page_subproc(page));
    mi_free_nonnull(p, page, NULL, false /* allow reclaim */);
  }
}

void mi_free_small(void* p) mi_attr_noexcept {
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid_ex(p,"mi_free_small",true /* is_small? */,true /*check p for null*/, &page)) {
    mi_free_nonnull(p, page, NULL, true /* allow reclaim? */);
  }
}

void mi_free_small_nonnull(void* p) mi_attr_noexcept {
  mi_assert(p!=NULL);
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid_ex(p,"mi_free_small_nonnull",true /* is_small? */,false /*check p for null*/, &page)) {
    mi_free_nonnull(p, page, NULL, true /* allow reclaim? */);
  }
}

// For runtime systems: Free a pointer that is guaranteed to be small, and in a page owned by the current thread.
static mi_decl_forceinline void mi_free_small_local_ex(void* p, bool check_p_for_null) mi_attr_noexcept {
  mi_assert(check_p_for_null || p!=NULL);
  mi_page_t* page = NULL;
  if mi_likely(mi_ptr_page_is_valid_ex(p,"mi_free_small_local_ex", true /* is_small? */, check_p_for_null /*check p for null*/, &page)) {
    mi_assert_internal(mi_page_thread_id(page) == _mi_thread_id());
    const mi_page_flags_t flags = mi_page_flags(page);
    if mi_likely(flags == 0 || (MI_PAGE_IS_MEMTAGGED != 0 && flags == MI_PAGE_IS_MEMTAGGED)) {
      // 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, false /* was guarded */, false /* no need to check if the page is full */, flags != 0 /* memtag */);
      return;
    }
    else {
      // page is local, but is full or contains (inner) aligned blocks; use generic path
      mi_free_generic_local(page, p);
    }
  }
}

void mi_free_small_local(void* p) mi_attr_noexcept {
  mi_free_small_local_ex(p, true /* check null */);
}

void mi_free_small_local_nonnull(void* p) mi_attr_noexcept {
  mi_free_small_local_ex(p, false /* check null */);
}



// ------------------------------------------------------
// Free variants
// ------------------------------------------------------

void mi_free_size(void* p, size_t size) mi_attr_noexcept {
  MI_UNUSED_RELEASE(size);
  #if MI_DEBUG
    const mi_page_t* const page = mi_ptr_page_validate(p,"mi_free_size");
    if (page==NULL) return;
    mi_assert(p!=NULL);
    const mi_block_t* block = _mi_page_ptr_unalign(page, p);
    const size_t usable = _mi_page_usable_size(page,p);
    const bool is_guarded = mi_block_ptr_is_guarded(block,p);  // guarded blocks are always in a non-small page
    if mi_unlikely(size > usable) {
      if (!is_guarded) {
        _mi_error_message(EINVAL, "pointer %p is freed with 'mi_free_size' but the size %zu is greater than the usable size %zu\n", p, size, usable);
        mi_free(p);
        return;
      }
    }
    else if mi_unlikely(size <= MI_SMALL_SIZE_MAX && !mi_page_is_small(page) && !is_guarded) {
      _mi_error_message(EINVAL, "pointer %p is freed with 'mi_free_size' with size %zu (<= MI_SMALL_SIZE_MAX), but it was allocated in a non-small page with block size %zu -- maybe a mismatched delete operator?\n", p, size, mi_page_block_size(page));
      mi_free(p);
      return;
    }
  #endif

  // note: only use `mi_free_small` if small allocations are aligned.
  // this allows building with `-DMI_OPT_FREE_SMALL=OFF` in case wrong sizes are passed to `mi_free_size`, see issue #1423
  #if MI_PAGE_META_SMALL_IS_ALIGNED
  if mi_likely(size <= MI_SMALL_SIZE_MAX) {
    mi_free_small(p);
  }
  else
  #endif
  {
    mi_free(p);
  }
}

void mi_free_size_aligned(void* p, size_t size, size_t alignment) mi_attr_noexcept {
  mi_assert((mi_addr(p) % alignment) == 0);
  // If the alignment is smaller than the `size`, then for `size <= MI_SMALL_SIZE_MAX`
  // the block must be allocated within a small page and can thus be handled safely by `mi_free_size`.
  // (since even with over-allocation the block size will be less than 2*MI_SMALL_SIZE_MAX <= MI_SMALL_OBJ_SIZE_MAX)
  if mi_likely(alignment <= size) {
    mi_free_size(p,size);
  }
  else {
    mi_free(p);
  }
}

void mi_free_aligned(void* p, size_t alignment) mi_attr_noexcept {
  MI_UNUSED_RELEASE(alignment);
  mi_assert((mi_addr(p) % alignment) == 0);
  mi_free(p);
}

// checked free
bool mi_cfree(void* p) mi_attr_noexcept {
  mi_page_t* const page = mi_checked_ptr_page(p);
  if mi_likely(page!=NULL) {
    mi_free_nonnull(p, page, NULL, true /* allow reclaim? */);
    return true;
  }
  else {
    return false;
  }
}


// --------------------------------------------------------------------------------------------
// `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)
// --------------------------------------------------------------------------------------------

// Free or reclaim an empty page
static bool mi_abandoned_page_collect_empty(mi_page_t* page)
{
  if (!mi_page_all_free(page)) return false;
  const bool should_delay = _mi_page_qsbr_should_delay(page);
  // 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);
  if mi_likely(!should_delay) {
    _mi_page_qsbr_clear(page);
    _mi_arenas_page_free_direct(page,NULL);
  }
  else {
    // A foreign theap may not collect again; only the originating theap may adopt a QSBR delayed page.
    // note: we don't have to do this but reclaiming into the originating theap puts it in the qsbr list which may help with collection across size classes.
    mi_theap_t* const theap = _mi_page_associated_theap_peek(page);
    if (theap != NULL && theap == page->theap) {
      _mi_theap_page_reclaim(theap, page);
    }
    else {
      // keep the page in abandoned or in the heap qsbr delayed list
      _mi_arenas_page_free(page,NULL);
    }
  }
  return true;
}

// 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)
{
  // 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 (1/8th should be free)
  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 reabandoned the page if other blocks are concurrently
// freed in the meantime. Returns `true` if the page was freed.
// By passing the captured `expected_thread_free`, we can often avoid calling `mi_page_free_collect`.
static void mi_abandoned_page_unown_from_free(mi_page_t* page, mi_block_t* page_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(page_thread_free,true);
  mi_thread_free_t tf_new    = mi_tf_set_owned(tf_expect,false);
  while mi_unlikely(!mi_atomic_cas_strong_release(&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_collect_empty(page)) return;
      if (mi_abandoned_page_try_reabandon_to_mapped(page)) return;
      // otherwise continue un-owning
      tf_expect = mi_atomic_load_acquire(&page->xthread_free);
    }
    // and try again to release ownership
    mi_subproc_stat_counter_increase(mi_page_subproc(page), pages_unown_cas_retry, 1);
    mi_assert_internal(mi_tf_block(tf_expect)==NULL);
    tf_new = mi_tf_create(NULL, false);
  }
}

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
{
  // 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_MAX_RECLAIM_OBJ_SIZE);
  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->tld==NULL || !theap->allow_page_reclaim) return false;  // see issue #1289

  // 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_used_at_frac(page,4) &&  // and at least 1/4th of the page is free
            _mi_arena_memid_is_suitable(page->memid, mi_theap_heap(theap)->exclusive_arena)) {   // and it fits our memory
    // across threads
    max_reclaim = _mi_option_get_fast(mi_option_page_cross_thread_max_reclaim);
  }
  else {
    return false;
  }

  // are we within the reclaim limit?
  if (max_reclaim >= 0 && !mi_page_queue_len_is_atmost(theap, page->block_size, max_reclaim)) {
    return false;
  }

  // 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, bool allow_reclaim) 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);
  // mi_assert_internal(!allow_reclaim || _mi_subproc() == mi_page_subproc(page));  // never reclaim across subprocesses

  // 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.
    mt_free = _mi_page_free_collect_partly(page, mt_free);
  }
  else {
    // 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_heap_reclaim_on_free(mi_page_heap(page));
  #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

  // try to: 1. free it, 2. reclaim it, or 3. reabandon it to be mapped
  if (mi_abandoned_page_collect_empty(page)) return;
  if (allow_reclaim && page->block_size <= MI_MAX_RECLAIM_OBJ_SIZE && 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);
}


// ------------------------------------------------------
// Usable size
// ------------------------------------------------------

// Bytes available in a block
static size_t mi_decl_noinline mi_page_usable_aligned_size_of(const mi_page_t* page, const void* p, const mi_block_t* block) mi_attr_noexcept {
  // const mi_block_t* block = _mi_page_ptr_unalign(page, p);
  const bool is_guarded = mi_block_ptr_is_guarded(block,p);
  const size_t size = mi_page_usable_size_of(page, block, is_guarded);
  mi_assert_internal((void*)p >= (void*)block);
  const size_t adjust = (uint8_t*)p - (uint8_t*)block;
  mi_assert_internal(adjust <= size);
  const size_t aligned_size = (adjust <= size ? size - adjust : 0);  // size can be zero if the padding is corrupted
  return aligned_size;
}

size_t _mi_page_usable_size(const mi_page_t* page, const void* p) mi_attr_noexcept {
  if mi_unlikely(page==NULL) return 0;
  mi_assert_internal(mi_ptr_page_validate(p,"_mi_page_usable_size") == page);
  const mi_block_t* block = _mi_page_ptr_unalign(page, p); // for safety, always unalign
  if mi_likely((const void*)block==p) {
    return mi_ptr_bounds_limit(p, mi_page_usable_size_of(page, block, false /* is guarded */));
  }
  else {
    // split out to separate routine for improved code generation
    return mi_ptr_bounds_limit(p, mi_page_usable_aligned_size_of(page, p, block));
  }
}

mi_decl_nodiscard size_t mi_usable_size(const void* p) mi_attr_noexcept {
  const mi_page_t* const page = mi_ptr_page_validate(p,"mi_usable_size");
  return _mi_page_usable_size(page,p);
}

mi_decl_nodiscard size_t mi_thread_id_of(const void* p) mi_attr_noexcept {
  const mi_page_t* const page = mi_ptr_page_validate(p,"mi_thread_id_of");
  if (page == NULL) return 0;
  #if MI_QSBR
  // on qsbr we keep the last owning thread id around so we can provide it even when a full page is abandoned
  // (this is needed for cpython where the thread id gets restored this way inside object headers);
  // it is 0 once the owning theap abandoned all its pages (e.g. when its thread terminated)
  return mi_page_qsbr_thread_id(page);
  #else
  const mi_thread_id_t tid = mi_page_thread_id(page);
  return (tid <= MI_THREAD_ID_DETACHED ? 0 : tid);
  #endif
}


// ------------------------------------------------------
// Deprecated: double free is usually checked with padding now
// as that is faster and works better for cross-thread free'ing.
// Check for double free in secure and debug mode
// This is somewhat expensive and only for thread-local frees, so only enabled at secure level 3 (at level 4 we use padding)
// ------------------------------------------------------

#if MI_SECURE>=3 && !MI_PADDING
// linear check if the free list contains a specific element
static bool mi_list_contains(const mi_page_t* page, const mi_block_t* list, const mi_block_t* elem, const char* list_kind) {
  const size_t max_count = page->capacity;      // can never hold more blocks than the capacity
  size_t count = 0;
  while (list != NULL && count <= max_count) {  // double-free can create cycles so we limit the number of iterations
    if (elem==list) return true;
    list = mi_block_next(page, list);
    count++;
  }
  if mi_unlikely(count > max_count) {
    _mi_error_message(EFAULT, "corrupted %s list (possibly due to a double free)\n", list_kind);
  }
  return false;
}

static mi_decl_noinline bool mi_check_double_freex(const mi_page_t* page, const mi_block_t* block) {
  // The block contains a valid free list link.
  // Walk the free lists to verify positively if it is already freed
  if (mi_list_contains(page, page->free, block, "free") ||
      mi_list_contains(page, page->local_free, block, "local free") ||
      mi_list_contains(page, mi_page_thread_free(page), block, "thread free"))
  {
    _mi_error_message(EAGAIN, "double free detected of block %p with size %zu\n", block, mi_page_block_size(page));
    return false;
  }
  return true;
}

// Used for double free checking to avoid checking free lists too frequently
static inline bool mi_block_could_be_double_free(const mi_page_t* page, const mi_block_t* block) {
  if (!mi_is_aligned(block,MI_SIZE_SIZE)) return false;   // quick check: aligned pointer?
  bool valid;
  mi_block_decode(page, block, mi_block_link(block), &valid);
  return valid;                                            // quick check: contains a valid free list link?
}

// check if `block` was free'd before
static inline bool mi_check_double_free(const mi_page_t* page, const mi_block_t* block) {
  if mi_unlikely(mi_block_could_be_double_free(page,block))  // quick check: contains a valid free list link?
  {
    // Suspicious: the block contains a valid free list link -- maybe a double free?
    // (continue in separate function to improve code generation)
    return mi_check_double_freex(page, block);
  }
  else return true;
}
#else
static inline bool mi_check_double_free(const mi_page_t* page, const mi_block_t* block) {
  MI_UNUSED(page);
  MI_UNUSED(block);
  return true;
}
#endif


// ---------------------------------------------------------------------------
// Check for theap block overflow by setting up padding at the end of the block
// ---------------------------------------------------------------------------

#if MI_PADDING // && !MI_TRACK_ENABLED
static inline bool mi_page_decode_padding(const mi_page_t* page, const mi_block_t* block, size_t* delta, size_t* bsize, bool* double_free) {
  *bsize = mi_page_usable_block_size(page);
  mi_padding_t* const padding = (mi_padding_t*)((uint8_t*)block + *bsize);
  mi_track_mem_defined(padding,sizeof(mi_padding_t));
  *delta = padding->delta;
  const uint32_t canary = padding->canary;
  const bool ok = (mi_ptr_encode_canary(page,block) == canary && *delta <= *bsize);
  if (double_free!=NULL) {
    *double_free = (!ok && mi_ptr_decode_canary_is_freed(canary));
    if (ok) { padding->canary = mi_ptr_encode_canary_freed(); }  // mark as freed
  }
  mi_track_mem_noaccess(padding,sizeof(mi_padding_t));
  return ok;
}

// Return the exact usable size of a block.
static size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool is_guarded) {
  if mi_unlikely(is_guarded) {
    const size_t bsize = mi_page_block_size(page);
    return (bsize - _mi_os_page_size());
  }
  else {
    size_t bsize;
    size_t delta;
    bool ok = mi_page_decode_padding(page, block, &delta, &bsize, NULL);
    mi_assert_internal(ok); mi_assert_internal(delta <= bsize);
    return (ok ? bsize - delta : 0);
  }
}

// When a non-thread-local block is freed, it becomes part of the thread delayed free
// 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) {
  if (mi_block_ptr_is_guarded(block,block + 1)) return;
  size_t bsize;
  size_t delta;
  bool ok = mi_page_decode_padding(page, block, &delta, &bsize, NULL);
  mi_assert_internal(ok);
  if (!ok || (bsize - delta) >= min_size) return;  // usually already enough space
  mi_assert_internal(bsize >= min_size);
  if (bsize < min_size) return;  // should never happen
  size_t new_delta = (bsize - min_size);
  mi_assert_internal(new_delta < bsize);
  mi_padding_t* padding = (mi_padding_t*)((uint8_t*)block + bsize);
  mi_track_mem_defined(padding,sizeof(mi_padding_t));
  padding->delta = (uint32_t)new_delta;
  mi_track_mem_noaccess(padding,sizeof(mi_padding_t));
}
#else
static inline size_t mi_page_usable_size_of(const mi_page_t* page, const mi_block_t* block, bool is_guarded) {
  MI_UNUSED(block);
  if mi_unlikely(is_guarded) {
    const size_t bsize = mi_page_block_size(page);
    return (bsize - _mi_os_page_size());
  }
  else {
    return mi_page_usable_block_size(page);
  }
}

void _mi_padding_shrink(const mi_page_t* page, const mi_block_t* block, const size_t min_size) {
  MI_UNUSED(page); MI_UNUSED(block); MI_UNUSED(min_size);
}
#endif

#if MI_PADDING

static bool mi_verify_padding(const mi_page_t* page, const mi_block_t* block, size_t* size, size_t* wrong, bool* is_double_free) {
  size_t bsize;
  size_t delta;
  bool ok = mi_page_decode_padding(page, block, &delta, &bsize, is_double_free );
  *size = *wrong = bsize;
  if (!ok) return false;
  mi_assert_internal(bsize >= delta);
  *size = bsize - delta;
  #if MI_PADDING_CHECK_BYTES
  if (!mi_page_is_huge(page)) {
    uint8_t* fill = (uint8_t*)block + bsize - delta;
    const size_t maxpad = (delta > MI_MAX_ALIGN_SIZE ? MI_MAX_ALIGN_SIZE : delta); // check at most the first N padding bytes
    mi_track_mem_defined(fill, maxpad);
    for (size_t i = 0; i < maxpad; i++) {
      if (fill[i] != MI_DEBUG_PADDING) {
        *wrong = bsize - delta + i;
        ok = false;
        break;
      }
    }
    mi_track_mem_noaccess(fill, maxpad);
  }
  #endif
  return ok;
}

mi_decl_nodiscard static bool mi_check_padding_on_free(const mi_page_t* page, const mi_block_t* block, bool is_guarded, size_t* usable_size) {
  if mi_unlikely(is_guarded) {
    const size_t bsize = mi_page_block_size(page);
    *usable_size = (bsize - _mi_os_page_size());
    return true;
  }
  else {
    size_t wrong;
    bool is_double_free;
    if mi_unlikely(!mi_verify_padding(page,block,usable_size,&wrong,&is_double_free)) {
      if (is_double_free) {
        _mi_error_message(EAGAIN, "double free detected of heap block %p with size %zu\n", block, *usable_size);
      }
      else {
        _mi_error_message(EFAULT, "buffer overflow in heap block %p of size %zu: write after %zu bytes\n", block, *usable_size, wrong );
      }
      return false;
    }
    return true;
  }
}

#else

mi_decl_nodiscard static bool mi_check_padding_on_free(const mi_page_t* page, const mi_block_t* block, bool is_guarded, size_t* usable_size) {
  *usable_size = mi_page_usable_size_of(page,block,is_guarded);
  return true;
}

#endif

// only maintain stats for smaller objects if requested
#if 0 && (MI_STATS>0)
static void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {
  MI_UNUSED(block);
  mi_theap_t* theap = _mi_theap_default();
  mi_lock_t* lock = NULL;
  mi_subproc_t* const subproc = mi_page_subproc(page);
  mi_theap_t* const theap_meta = subproc->theap_meta;
  if mi_unlikely(!mi_theap_is_initialized(theap) || // can happen if free'd after thread_done was called (usually a thread cleanup call by the OS)
                  // page->theap == subproc->theap_meta  .. but we cannot read `theap` if we don't own the page
                  (theap_meta != NULL && mi_page_thread_id(page) == theap_meta->tld->thread_id)) {
    theap = theap_meta;
    lock = &subproc->theap_meta_lock;
    mi_lock_acquire(lock);
  }

  const size_t bsize = mi_page_usable_block_size(page);
  // #if (MI_STATS>=2)
  // 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_STATS > 1)
    mi_theap_stat_decrease(theap, malloc_bins[_mi_bin(bsize)], 1);
    #endif
  }
  else {
    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);
  }

  if mi_unlikely(lock!=NULL) {
    mi_lock_release(lock);
  }
}
#else
void mi_stat_free(const mi_page_t* page, const mi_block_t* block) {
  MI_UNUSED(page); MI_UNUSED(block);
}
#endif