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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
/* ----------------------------------------------------------------------------
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(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic ignored "-Walloc-size-larger-than="
#endif

/*
Testing allocators is difficult as bugs may only surface after particular
allocation patterns. The main approach to testing _mimalloc_ is therefore
to have extensive internal invariant checking (see `page_is_valid` in `alloc/page.c`
for example), which is enabled in debug mode with `-DMI_DEBUG_FULL=ON`.
The main testing is then to run `mimalloc-bench` [1] using full invariant checking
to catch any potential problems over a wide range of intensive allocation bench
marks.

However, this does not test well for the entire API surface. In this test file
we therefore test the API over various inputs. Please add more tests :-)

[1] https://github.com/daanx/mimalloc-bench
*/

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>

#ifdef __cplusplus
#include <new>
#include <vector>
#endif

#include "mimalloc.h"
#include "mimalloc-stats.h"
// #include "mimalloc/internal.h"
#include "mimalloc/types.h" // for MI_DEBUG and MI_PAGE_MAX_OVERALLOC_ALIGN

#include "testhelper.h"


// ---------------------------------------------------------------------------
// Test functions
// ---------------------------------------------------------------------------
bool test_theap1(void);
bool test_theap2(void);
bool test_theap_arena_destroy(void);
bool test_theap_arena_delete(void);
bool test_stl_allocator1(void);
bool test_stl_allocator2(void);

bool test_stl_theap_allocator1(void);
bool test_stl_theap_allocator2(void);
bool test_stl_theap_allocator3(void);
bool test_stl_theap_allocator4(void);

static bool test_zero_aligned_first(void);
static bool test_aligned_all(void);
static bool test_heap_destroy_xthread_free(void);
static bool test_heap_destroy_stale_theap(void);
static bool test_thread_done_no_reinit(void);
static bool test_thread_heap_release(void);
static bool test_heap_delete_concurrent_free(void);
#ifdef __cplusplus
static bool test_new_first(void);
#endif

#if !MI_QSBR
static void mi_cdecl qsbr_record_error(int err, void* arg) {
  *(int*)arg = err;
}
#endif

static bool mem_has_vals(const uint8_t* p, size_t size, uint8_t val) {
  if (p==NULL) return false;
  if (size==0) return true;
  return (p[0] == val && memcmp(p, p + 1, size - 1) == 0);  // all bytes equal the first one (fast even in debug builds)
}
static bool mem_is_zero(const void* p, size_t size) {
  return mem_has_vals((const uint8_t*)p,size,0);
}

// size sweeps use a larger odd multiple of the step beyond the smallest sizes (so all residues
// modulo the power-of-two alignments are still covered); with `MI_TEST_LIGHT` the steps are larger
// and repeated tests run fewer iterations (and even fewer with `MI_TEST_LIGHT=2`)
#if MI_TEST_LIGHT >= 2
#define MI_TEST_SIZE_STEP(size,step)  ((size) < 64 ? (step) : 15*(step))
#define MI_TEST_LARGE_STEP            (6*1024)
#define MI_TEST_ITERS(n)              ((n)/8)
#elif MI_TEST_LIGHT
#define MI_TEST_SIZE_STEP(size,step)  ((size) < 128 ? (step) : 7*(step))
#define MI_TEST_LARGE_STEP            (3*1024)
#define MI_TEST_ITERS(n)              ((n)/4)
#else
#define MI_TEST_SIZE_STEP(size,step)  ((size) < 256 ? (step) : 3*(step))
#define MI_TEST_LARGE_STEP            (1024)
#define MI_TEST_ITERS(n)              (n)
#endif
// small size sweeps stay dense around the `MI_SMALL_SIZE_MAX` boundary
#define MI_TEST_SMALL_SIZE_STEP(size) ((size) + 8 >= MI_SMALL_SIZE_MAX && (size) <= MI_SMALL_SIZE_MAX + 8 ? 1 : MI_TEST_SIZE_STEP(size,1))

// ---------------------------------------------------------------------------
// Main testing
// ---------------------------------------------------------------------------
int main(void) {
  mi_options_print();
  mi_option_disable(mi_option_verbose);

  CHECK_BODY("pointer-address-and-memtag") {
    uint8_t area[128];
    for (size_t tag = 0; tag < 16; tag++) {
      void* p = mi_ptr_with_memtag(area, tag);
      void* q = mi_ptr_with_addr(p, mi_addr(area) + 32);
      result = result && mi_addr(p) == mi_addr(area) && mi_addr(q) == mi_addr(area + 32);
      #if MI_MTE
      result = result && mi_ptr_memtag(p) == tag;
      #else
      result = result && mi_ptr_memtag(p) == 0;
      #endif
      result = result && mi_ptr_memtag(q) == mi_ptr_memtag(p);
      result = result && mi_ptr_memtag_meta(q) == area + 32;
    }
    #if MI_MTE
    // Ignored pointer bits are not logical memory-tag bits.
    void* p = (void*)((uintptr_t)mi_ptr_with_memtag(area, 5) | (~MI_PTR_ADDR_MASK & ~MI_PTR_MEMTAG_MASK));
    result = result && mi_addr(p) == mi_addr(area) && mi_ptr_memtag(p) == 5;
    result = result && mi_ptr_with_memtag(p, 0xF5) == mi_ptr_with_memtag(area, 5);
    #endif
  };
  CHECK_BODY("pointer-pack-rederive") {
    uint8_t area[128];
    for (size_t tag = 0; tag < 16; tag++) {
      void* p = mi_ptr_with_memtag(mi_ptr_bounded(area + 32, 16), tag);
      void* auth = mi_ptr_with_memtag(area, tag ^ 1);
      void* unpacked = mi_ptr_unpack(auth, mi_ptr_pack(p));
      void* derived = mi_ptr_rederive(auth, p);
      result = result && mi_addr(unpacked) == mi_addr(p) && mi_addr(derived) == mi_addr(p);
      result = result && mi_ptr_memtag(unpacked) == mi_ptr_memtag(p) && mi_ptr_memtag(derived) == mi_ptr_memtag(p);
      // Recover authority before moving outside the user's bounds.
      void* base = mi_ptr_with_addr(derived, mi_addr(area));
      result = result && mi_addr(base) == mi_addr(area) && mi_ptr_memtag(base) == mi_ptr_memtag(p);
      #if MI_CHERI
      result = result && __builtin_cheri_tag_get(unpacked) && __builtin_cheri_tag_get(base);
      result = result && __builtin_cheri_base_get(unpacked) == __builtin_cheri_base_get(auth);
      result = result && __builtin_cheri_length_get(unpacked) == __builtin_cheri_length_get(auth);
      result = result && __builtin_cheri_base_get(base) == __builtin_cheri_base_get(auth);
      result = result && __builtin_cheri_length_get(base) == __builtin_cheri_length_get(auth);
      #endif
    }
  };

  // ---------------------------------------------------
  // Malloc
  // ---------------------------------------------------

  CHECK_BODY("malloc-zero") {
    void* p = mi_malloc(0);
    result = (p != NULL);
    mi_free(p);
  };
  CHECK_BODY("malloc-nomem1") {
    result = (mi_malloc((size_t)PTRDIFF_MAX + (size_t)1) == NULL);
  };
  CHECK_BODY("malloc-free-null") {
    mi_free(NULL);
  };
  #if MI_INTPTR_BITS > 32
  CHECK_BODY("malloc-free-invalid-low") {
    mi_cfree((void*)(MI_ZU(0x0000000003990080))); // issue #1087
  };
  #endif
  CHECK_BODY("calloc-overflow") {
    // use (size_t)&mi_calloc to get some number without triggering compiler warnings
    result = (mi_calloc((size_t)&mi_calloc | 1024,SIZE_MAX/1000) == NULL);  // `| 1024` as on wasm function pointers are small indices
  };
  CHECK_BODY("malloc-large") {   // see PR #544.
    void* p = mi_malloc(67108872);
    mi_free(p);
  };
  CHECK_BODY("malloc-size") {
    void* p = mi_malloc(42);
    result = (mi_malloc_size(p) >= 42 && mi_malloc_usable_size(p) >= 42);
    mi_free(p);
  };

  CHECK_BODY("calloc0") {
    void* p = mi_calloc(0,1000);
    const size_t usable = mi_usable_size(p);
    result = (usable <= 16);
    mi_free(p);
  };

  CHECK_BODY("mi_urealloc_invalid") {
    void* p = mi_malloc(64);
    size_t pre, post;
    void* q = mi_urealloc((char*)p + 3, 58, &pre, &post);  // stays in place in release (no interior pointer check)
    mi_free(p);
    result = (q==NULL || q==(uint8_t*)p+3);
  }

  // ---------------------------------------------------
  // Extended
  // ---------------------------------------------------
  CHECK_BODY("posix_memalign1") {
    void* p = &p;
    int err = mi_posix_memalign(&p, sizeof(void*), 32);
    result = ((err==0 && (uintptr_t)p % sizeof(void*) == 0) || p==&p);
    mi_free(p);
  };
  CHECK_BODY("posix_memalign_no_align") {
    void* p = &p;
    int err = mi_posix_memalign(&p, 3, 32);
    result = (err==EINVAL && p==&p);
  };
  CHECK_BODY("posix_memalign_zero") {
    void* p = &p;
    int err = mi_posix_memalign(&p, sizeof(void*), 0);
    mi_free(p);
    result = (err==0);
  };
  CHECK_BODY("posix_memalign_nopow2") {
    void* p = &p;
    int err = mi_posix_memalign(&p, 3*sizeof(void*), 32);
    result = (err==EINVAL && p==&p);
  };
  CHECK_BODY("posix_memalign_nomem") {
    void* p = &p;
    int err = mi_posix_memalign(&p, sizeof(void*), SIZE_MAX);
    result = (err==ENOMEM && p==&p);
  };

  // ---------------------------------------------------
  // Aligned API
  // ---------------------------------------------------
  CHECK_BODY("malloc-aligned1") {
    void* p = mi_malloc_aligned(32,32); result = (p != NULL && (uintptr_t)(p) % 32 == 0); mi_free(p);
  };
  CHECK_BODY("malloc-aligned2") {
    void* p = mi_malloc_aligned(48,32); result = (p != NULL && (uintptr_t)(p) % 32 == 0); mi_free(p);
  };
  CHECK_BODY("malloc-aligned3") {
    void* p1 = mi_malloc_aligned(48,32); bool result1 = (p1 != NULL && (uintptr_t)(p1) % 32 == 0);
    void* p2 = mi_malloc_aligned(48,32); bool result2 = (p2 != NULL && (uintptr_t)(p2) % 32 == 0);
    mi_free(p2);
    mi_free(p1);
    result = (result1&&result2);
  };
  CHECK_BODY("malloc-aligned4") {
    void* p;
    bool ok = true;
    for (int i = 0; i < 8 && ok; i++) {
      p = mi_malloc_aligned(8, 16);
      ok = (p != NULL && (uintptr_t)(p) % 16 == 0); mi_free(p);
    }
    result = ok;
  };
  CHECK_BODY("free-size-aligned-overaligned") { // issue #1400
    const size_t size = 8;
    const size_t alignment = 16 * 1024;
    void* p[200];
    bool ok = true;
    for (size_t i = 0; i < 200; i++) {
      p[i] = mi_malloc_aligned(size, alignment);
      ok = ok && (p[i] != NULL) && ((uintptr_t)p[i] % alignment == 0);
    }
    for (size_t i = 0; i < 200; i++) {
      mi_free_size_aligned(p[i], size, alignment);
    }
    result = ok;
  };
  CHECK_BODY("malloc-aligned5") {
    void* p = mi_malloc_aligned(4097,4096);
    size_t usable = mi_usable_size(p);
    result = (usable >= 4097 && usable < 16000);
    fprintf(stderr, "malloc_aligned5: usable size: %zi.  ", usable);
    mi_free(p);
  };
  /*
  CHECK_BODY("malloc-aligned6") {
    bool ok = true;
    for (size_t align = 1; align <= MI_PAGE_MAX_OVERALLOC_ALIGN && ok; align *= 2) {
      void* ps[8];
      for (int i = 0; i < 8 && ok; i++) {
        ps[i] = mi_malloc_aligned(align*13  // size
                                 , align);
        if (ps[i] == NULL || (uintptr_t)(ps[i]) % align != 0) {
          ok = false;
        }
      }
      for (int i = 0; i < 8 && ok; i++) {
        mi_free(ps[i]);
      }
    }
    result = ok;
  };
  */
  CHECK_BODY("malloc-aligned7") {
    void* p = mi_malloc_aligned(1024,MI_PAGE_MAX_OVERALLOC_ALIGN);
    mi_free(p);
    result = ((uintptr_t)p % MI_PAGE_MAX_OVERALLOC_ALIGN) == 0;
  };
  CHECK_BODY("malloc-aligned8") {
    bool ok = true;
    for (int i = 0; i < 5 && ok; i++) {
      int n = (1 << i);
      void* p = mi_malloc_aligned(1024, n * MI_PAGE_MAX_OVERALLOC_ALIGN);
      ok = ((uintptr_t)p % (n*MI_PAGE_MAX_OVERALLOC_ALIGN)) == 0;
      mi_free(p);
    }
    result = ok;
  };

  CHECK_BODY("malloc-aligned9") { // test large alignments
    bool ok = true;
    void* p[8];
    const int max_align_shift =
      #if SIZE_MAX > UINT32_MAX
      28  /* up to 64 MiB alignment */
      #else
      20
      #endif
      ;
    size_t sizes[8] = { 8, 512, 1024 * 1024, MI_PAGE_MAX_OVERALLOC_ALIGN, MI_PAGE_MAX_OVERALLOC_ALIGN + 1, 2 * MI_PAGE_MAX_OVERALLOC_ALIGN, 8 * MI_PAGE_MAX_OVERALLOC_ALIGN, 0 };
    for (int i = 0; i < max_align_shift && ok; i++) {
      int align = (1 << i);
      for (int j = 0; j < 8 && ok; j++) {
        p[j] = mi_zalloc_aligned(sizes[j], align);
        ok = ((uintptr_t)p[j] % align) == 0;
      }
      for (int j = 0; j < 8; j++) {
        mi_free(p[j]);
      }
    }
    result = ok;
  };

  CHECK_BODY("malloc-aligned9a") { // test large alignments
    void* p = mi_zalloc_aligned(1024 * 1024, 2);
    mi_free(p);
    p = mi_zalloc_aligned(1024 * 1024, 2);
    mi_free(p);
    result = true;
  };

  CHECK_BODY("malloc-aligned10") {
    bool ok = true;
    void* p[10+1];
    int align;
    int j;
    for(j = 0, align = 1; j <= 10 && ok; align *= 2, j++ ) {
      p[j] = mi_malloc_aligned(43 + align, align);
      ok = ((uintptr_t)p[j] % align) == 0;
    }
    for ( ; j > 0; j--) {
      mi_free(p[j-1]);
    }
    result = ok;
  }
  //CHECK_BODY("malloc_aligned11") {
  //  mi_theap_t* theap = mi_theap_new();
  //  void* p = mi_theap_malloc_aligned(theap, 33554426, 8);
  //  result = mi_theap_contains_block(theap, p);
  //  mi_theap_destroy(theap);
  //}
  CHECK_BODY("mimalloc-aligned12") {
    void* p = mi_malloc_aligned(0x100, 0x100);
    result = (((uintptr_t)p % 0x100) == 0); // #602
    mi_free(p);
  }

  CHECK_BODY("mimalloc-aligned13") {
    bool ok = true;
    for( size_t size = 1; size <= (MI_SMALL_SIZE_MAX * 2) && ok; size += MI_TEST_SMALL_SIZE_STEP(size) ) {
      for(size_t align = 1; align <= size && ok; align *= 2 ) {
        void* p[10];
        for(int i = 0; i < 10 && ok; i++) {
          p[i] = mi_malloc_aligned(size,align);;
          ok = (p[i] != NULL && ((uintptr_t)(p[i]) % align) == 0);
        }
        for(int i = 0; i < 10 && ok; i++) {
          mi_free(p[i]);
        }
      }
    }
    result = ok;
  }
  CHECK_BODY("mimalloc-size-aligned14") {
    bool ok = true;
    for( size_t size = 1; size <= (MI_SMALL_SIZE_MAX * 2) && ok; size += MI_TEST_SMALL_SIZE_STEP(size) ) {
      for(size_t align = 1; align <= 16*size && ok; align *= 2) {
        void* p[10];
        for(int i = 0; i < 10 && ok; i++) {
          p[i] = mi_malloc_aligned(size,align);;
          ok = (p[i] != NULL && ((uintptr_t)(p[i]) % align) == 0);
        }
        for(int i = 0; i < 10 && ok; i++) {
          mi_free_size_aligned(p[i],size,align);
        }
      }
    }
    result = ok;
  }
  CHECK_BODY("mimalloc-aligned15") {
    result = test_aligned_all();
  }
  CHECK_BODY("malloc-aligned-at1") {
    void* p = mi_malloc_aligned_at(48,32,0); result = (p != NULL && ((uintptr_t)(p) + 0) % 32 == 0); mi_free(p);
  };
  CHECK_BODY("malloc-aligned-at2") {
    void* p = mi_malloc_aligned_at(50,32,8); result = (p != NULL && ((uintptr_t)(p) + 8) % 32 == 0); mi_free(p);
  };
  CHECK_BODY("realloc-aligned-from-offset") {  // realloc to a small alignment must realign a pointer allocated at an offset
    void* p = mi_malloc_aligned_at(16,16,4);
    void* q = mi_realloc_aligned(p,16,sizeof(void*));
    result = (p != NULL && q != NULL && (uintptr_t)q % sizeof(void*) == 0); mi_free(q);
  };
  CHECK_BODY("memalign1") {
    void* p;
    bool ok = true;
    for (int i = 0; i < 8 && ok; i++) {
      p = mi_memalign(16,8);
      ok = (p != NULL && (uintptr_t)(p) % 16 == 0); mi_free(p);
    }
    result = ok;
  };
  CHECK_BODY("zalloc-csize-large") {
    // mi_theap_zalloc_csize must zero its large branch too: it used to
    // delegate sizes above MI_SMALL_SIZE_MAX to the plain malloc path.
    mi_theap_t* theap = mi_theap_get_default();
    size_t size = MI_SMALL_SIZE_MAX + 64;
    bool ok = true;
    for (int round = 0; round < 16 && ok; round++) {
      uint8_t* junk = (uint8_t*)mi_theap_malloc(theap, size);
      memset(junk, 0xAB, size);
      mi_free(junk);
      uint8_t* z = (uint8_t*)mi_theap_zalloc_csize(theap, size);
      ok = mem_is_zero(z, size);
      mi_free(z);
    }
    result = ok;
  };
  CHECK_BODY("zalloc-aligned-small1") {
    size_t zalloc_size = MI_SMALL_SIZE_MAX / 2;
    uint8_t* p = (uint8_t*)mi_zalloc_aligned(zalloc_size, MI_MAX_ALIGN_SIZE * 2);
    result = mem_is_zero(p, zalloc_size);
    mi_free(p);
  };
  CHECK_BODY("rezalloc_aligned-small1") {
    size_t zalloc_size = MI_SMALL_SIZE_MAX / 2;
    uint8_t* p = (uint8_t*)mi_zalloc_aligned(zalloc_size, MI_MAX_ALIGN_SIZE * 2);
    result = mem_is_zero(p, zalloc_size);
    zalloc_size *= 3;
    p = (uint8_t*)mi_rezalloc_aligned(p, zalloc_size, MI_MAX_ALIGN_SIZE * 2);
    result = result && mem_is_zero(p, zalloc_size);
    mi_free(p);
  };

  CHECK_BODY("rezalloc_aligned_zeros") {  // issue #763
    size_t alignment = 1024;
    size_t n = 1024 * 6;
    void* ptr = mi_zalloc_aligned(n, alignment);
    assert(mem_is_zero(ptr,n));
    memset(ptr,123,n/2);

    ptr = mi_rezalloc_aligned(ptr, n/2, alignment);
    assert(mem_has_vals((uint8_t*)ptr,n/2,123));

    ptr = mi_rezalloc_aligned(ptr, n, alignment);
    assert(mem_has_vals((uint8_t*)ptr,n/2,123));
    result = mem_is_zero((uint8_t*)ptr + n/2, n/2);
    mi_free(ptr);
  }

  #if !MI_QSBR
  CHECK_BODY("heap-qsbr-unavailable") {
    int err = 0;
    mi_register_error(&qsbr_record_error, &err);
    mi_heap_t* heap = mi_heap_new_qsbr();
    mi_register_error(NULL, NULL);
    result = (heap == NULL && err == ENOSYS);
    if (heap != NULL) { mi_heap_destroy(heap); }
  }
  #endif

  CHECK_BODY("heap_aligned1") {
    mi_heap_t* heap = mi_heap_new();
    const size_t alignment = 128 * 1024;  // 128 KiB
    const size_t buffer_size = 1 * 1024 * 1024;  // 1 MiB
    void* buffer = mi_heap_malloc_aligned(heap, buffer_size, alignment);
    bool nonnull = (buffer != NULL);
    assert(nonnull);
    const bool is_aligned = ((uintptr_t)buffer % alignment) == 0;
    assert(is_aligned);
    mi_free(buffer);
    mi_heap_destroy(heap);
    result = (nonnull && is_aligned);
  }

  // ---------------------------------------------------
  // Reallocation
  // ---------------------------------------------------
  CHECK_BODY("realloc-null") {
    void* p = mi_realloc(NULL,4);
    result = (p != NULL);
    mi_free(p);
  };

  CHECK_BODY("realloc-null-sizezero") {
    void* p = mi_realloc(NULL,0);  // <https://en.cppreference.com/w/c/memory/realloc> "If ptr is NULL, the behavior is the same as calling malloc(new_size)."
    result = (p != NULL);
    mi_free(p);
  };

  CHECK_BODY("realloc-sizezero") {
    void* p = mi_malloc(4);
    void* q = mi_realloc(p, 0);
    result = (q != NULL);
    mi_free(q);
  };

  CHECK_BODY("realloc-shrink") {  // issue #1488
    void* p = mi_malloc(4096);
    const size_t size = mi_usable_size(p);
    void* q = mi_realloc(p, size - size/16);          // little waste: stays in place
    result = (q == p);
    void* r = mi_realloc(q, size/2 + 16);              // too much waste: shrinks
    result = result && (r != NULL && mi_usable_size(r) < size - size/8);
    void* s = mi_realloc_aligned(r, 4096, 64);
    const size_t asize = mi_usable_size(s);
    void* t = mi_realloc_aligned(s, asize/2 + 16, 64);
    result = result && (t != NULL && mi_usable_size(t) < asize - asize/8 && ((uintptr_t)t % 64) == 0);
    mi_free(t);
  };

  CHECK_BODY("realloc-shrink-huge") {
    const size_t size = 8*MI_MiB;
    uint8_t* p = (uint8_t*)mi_malloc(size);
    memset(p, 1, size);
    const size_t half = mi_usable_size(p)/2 + 1;      // (the usable size can be larger with guarded sampling)
    uint8_t* q = (uint8_t*)mi_realloc(p, half);       // huge and at least half: stays in place and resets the tail
    #if defined(__wasi__) || defined(__EMSCRIPTEN__)
    const bool in_place = false;                        // unless the OS cannot reset memory
    #else
    const bool in_place = true;
    #endif
    result = ((q == p) == in_place && q[0] == 1 && q[half - 1] == 1);
    uint8_t* volatile qv = q;                           // hide the alloc_size of `q` from fortified `memset`
    memset(qv, 2, mi_usable_size(q));                   // the tail stays accessible
    uint8_t* r = (uint8_t*)mi_realloc(q, size/8);      // less than half: copies
    result = result && (r != NULL && r != q && r[0] == 2 && r[size/8 - 1] == 2);
    mi_free(r);
  };

  CHECK_BODY("reallocarray-null-sizezero") {
    void* p = mi_reallocarray(NULL,0,16);  // issue #574
    result = (p != NULL && errno == 0);
    mi_free(p);
  };

  CHECK_BODY("reallocarray-overflow") {
    uint8_t* p = (uint8_t*)mi_malloc(32);
    if (p == NULL) { result = false; }
    else {
      memset(p, 0x5A, 32);
      errno = 0;
      void* q = mi_reallocarray(p, SIZE_MAX / 2 + 1, 2);
      result = (q == NULL && errno == ENOMEM && mem_has_vals(p, 32, 0x5A));
      mi_free(q == NULL ? p : q);
    }
  };

  CHECK_BODY("reallocarr-grow") {
    void* p = mi_malloc(32);
    if (p == NULL) { result = false; }
    else {
      memset(p, 0x5A, 32);
      int err = mi_reallocarr(&p, 64, 2);
      result = (err == 0 && mi_usable_size(p) >= 128 && mem_has_vals((uint8_t*)p, 32, 0x5A));
      mi_free(p);
    }
  };

  CHECK_BODY("reallocarr-zero-count") {
    void* p = mi_malloc(32);
    if (p == NULL) { result = false; }
    else {
      int err = mi_reallocarr(&p, 0, 2);
      result = (err == 0 && p == NULL);
      mi_free(p);
    }
  };

  CHECK_BODY("reallocarr-zero-size") {
    void* p = mi_malloc(32);
    if (p == NULL) { result = false; }
    else {
      int err = mi_reallocarr(&p, 2, 0);
      result = (err == 0 && p == NULL);
      mi_free(p);
    }
  };

  CHECK_BODY("realloc-aligned-other-heap") {
    mi_heap_t* heap = mi_heap_new();
    void* p = mi_heap_malloc_aligned(heap, 100, 64);
    void* q = mi_realloc_aligned(p, 100, 64);  // fits in place but must move to the default heap
    result = (q != NULL && mi_heap_of(q) != heap);
    mi_free(q);
    mi_heap_delete(heap);
  };

  CHECK_BODY("reallocarr-overflow") {
    void* p = mi_malloc(32);
    if (p == NULL) { result = false; }
    else {
      memset(p, 0x5A, 32);
      void* original = p;
      int err = mi_reallocarr(&p, SIZE_MAX / 2 + 1, 2);
      result = (err == EOVERFLOW && p == original && mem_has_vals((uint8_t*)p, 32, 0x5A));
      mi_free(original);
    }
  };

  CHECK_BODY("realloc-guarded") {      // issue #1304
 	  void* shared_ptr = NULL;
    for (int iterations = 0; iterations < MI_TEST_ITERS(64); ++iterations) {
      for (int i = 0; i < 1024; ++i) {
        shared_ptr = mi_realloc(shared_ptr, i * 64);
      }
    }
    mi_free(shared_ptr);
  }

  // ---------------------------------------------------
  // Small allocations
  // ---------------------------------------------------
  CHECK_BODY("guarded-api-small-free") {
    mi_heap_t* heap = mi_heap_new();
    mi_theap_t* theap = (heap == NULL ? NULL : mi_heap_theap(heap));
    if (theap == NULL) { result = false; }
    else {
      void* blocks[128];
      mi_theap_guarded_set_size_bound(theap, 0, MI_SMALL_SIZE_MAX);
      mi_theap_guarded_set_sample_rate(theap, 1, 1);
      for (size_t i = 0; i < 128; i++) {
        blocks[i] = mi_theap_malloc(theap, MI_SMALL_SIZE_MAX);
        if (blocks[i] == NULL) { result = false; }
        else { memset(blocks[i], 0x5A, MI_SMALL_SIZE_MAX); }
      }
      mi_theap_guarded_set_sample_rate(theap, 0, 0);
      for (size_t i = 0; i < 128; i++) {
        if (i % 2 == 0) { mi_free_small(blocks[i]); }
        else { mi_free_size(blocks[i], MI_SMALL_SIZE_MAX); }
      }
    }
    if (heap != NULL) { mi_heap_delete(heap); }
  }

  CHECK_BODY("free_small1") {
    for(size_t n = 1; n < MI_SMALL_SIZE_MAX; n *=2) {
      const size_t size = n*sizeof(int);
      int* p = (int*)mi_zalloc(size);
      p[n-1] = 42;
      mi_free_size(p,size);
    }
  }

  CHECK_BODY("free_small2") {
    for(size_t n = 1; n < MI_SMALL_SIZE_MAX; n *=2) {
      const size_t size = n*sizeof(int);
      int* p = (int*)mi_zalloc(size);
      p[n-1] = 42;
      p = (int*)mi_rezalloc(p, size + MI_SMALL_SIZE_MAX);
      mi_free_size(p,size + MI_SMALL_SIZE_MAX);
    }
  }

  CHECK_BODY("free_small3") {
    for(size_t n = 1; n < MI_SMALL_SIZE_MAX/sizeof(int); n *=2) {
      const size_t size = n*sizeof(int);
      int* p = (int*)mi_zalloc_small(size);
      p[n-1] = 42;
      mi_free_small(p);
    }
  }

  CHECK_BODY("free_small_null") {  // the nullable variants accept NULL
    mi_free_small(NULL);
    mi_free_small_local(NULL);
    result = (errno == 0);
  }

  CHECK_BODY("free_small4") {
    for(size_t n = 1; n < MI_SMALL_SIZE_MAX/sizeof(int); n *=2) {
      const size_t size = n*sizeof(int);
      int* p = (int*)mi_zalloc_small(size);
      p[n-1] = 42;
      mi_free(p);
    }
  }
  // ---------------------------------------------------
  // Returned block sizes
  // ---------------------------------------------------
  CHECK_BODY("umalloc1") {
    for(size_t size = 1; size <= 32*MI_MiB; size *= 2 ) {
      size_t bsize;
      void* p = mi_umalloc(size,&bsize);
      assert(bsize >= size);
      size_t pre_size;
      size_t post_size;
      p = mi_urealloc(p, size + 1024, &pre_size, &post_size);
      assert(pre_size == bsize);
      assert(post_size >= size + 1024);
      size_t fsize;
      mi_ufree(p,&fsize);
      assert(fsize == post_size);
    }
  }
  CHECK_BODY("ucalloc-nomem") {
    size_t bsize = 42;
    void* p = mi_ucalloc(SIZE_MAX/4, 4, &bsize);
    result = (p == NULL && bsize == 42);
  }

  #if (MI_SIZE_SIZE > 4)
  CHECK_BODY("arena_reserve") {
    result = (0==mi_reserve_os_memory(16*MI_GiB,false,true));
  }

  #if TEST_ARENAS // normally disabled as it takes long and consumes a lot of memory
  CHECK_BODY("arena_reserve_child") {
    // With the following setup, the arena size is 24 GiB and the total
    // allocation requires over 16 GiB. mimalloc arena internally creates
    // child arenas once the arena size is over 16 GiB so this test will
    // trigger the creation and access to child arenas to ensure the arena
    // traversal and space accounting works as expected.
    const size_t arena_size = 24 * MI_GiB;
    const size_t allocation_size = 63 * MI_MiB;
    const size_t allocation_count = 272;
    const size_t alignment = mi_arena_min_alignment();

    mi_arena_id_t arena_id = NULL;
    bool ok = (0==mi_reserve_os_memory_ex(arena_size,false /* commit */,false /* allow large */,
                                 true /* exclusive */, &arena_id));
    if (!ok) {
      fprintf(stderr, "failed to register the 24 GiB arena\n");
      ok = true; // don't fail the test on small machines
    }
    else {
      mi_heap_t* heap = mi_heap_new_in_arena(arena_id);
      for (size_t i = 0; i < allocation_count && ok; i++) {
        void* p = mi_heap_malloc(heap, allocation_size);
        if (p == NULL) {
          fprintf(stderr, "allocation %zu failed after %zu MiB; child arena was not used\n", i, i * allocation_size / MI_MiB);
          ok = false;
        }
        if (!mi_arena_contains(arena_id, p)) {
          fprintf(stderr, "allocation %zu came from outside the requested arena\n", i);
          ok = false;
        }
      }
      fprintf(stderr, "allocated %zu MiB from the parent arena and its children\n", allocation_count * allocation_size / MI_MiB);
      mi_heap_destroy(heap);
    }
    // mi_arena_destroy(arena_id);
    result = ok;
  }
  #endif
  #endif


  // ---------------------------------------------------
  // C++
  // ---------------------------------------------------

  #if defined(__cplusplus) && !defined(_MSC_VER)
  CHECK_BODY("c++ new-handler") {
    std::set_new_handler([]{ throw std::bad_alloc(); });
    void* p = mi_new_nothrow(SIZE_MAX/2);
    result = (p==NULL);
  }
  CHECK_BODY("c++ new handler2") {
    try {
      void* p = mi_new_n(SIZE_MAX/2, 4);
      (void)(p);
      result = false;
    }
    catch(const std::bad_alloc&) {
      result = true;
    }
  }
  #endif

  CHECK_BODY("stats-json-exact-buffer") {  // the output fits exactly in a buffer of its length + 1
    // (the process info in the output can change between calls so we retry until the length is the same)
    bool exact = false;
    for (int i = 0; i < 100 && !exact; i++) {
      char* json = mi_stats_get_json(0, NULL);
      if (json == NULL) break;
      const size_t len = strlen(json);
      char* buf = (char*)mi_malloc(len + 1);
      exact = (buf != NULL && mi_stats_get_json(len + 1, buf) == buf && strlen(buf) == len);
      mi_free(buf);
      mi_free(json);
    }
    result = exact;
  }

  // ---------------------------------------------------
  // Heaps
  // ---------------------------------------------------

  CHECK_BODY("heap-os1") {
    // @zoxc opus bug #2.
    mi_heap_t* h = mi_heap_new();
    void* p = mi_heap_malloc_aligned(h, 1<<20, 2<<20);   // forced OS allocation
    mi_heap_delete(h);
    mi_free(p);                                          // SIGSEGV
  }

  CHECK_BODY("heap-os2") {
    // @zoxc opus bug #3.
    mi_collect(true);
    mi_stats_t_decl(stats0);
    mi_stats_get(&stats0);

    mi_heap_t* h = mi_heap_new();
    long failed = 0;
    for(int i = 0; i < 10; i++) {
      int* p = (int*)mi_heap_malloc_aligned(h, 1<<20, 2<<20);   // forced OS allocation
      if (p==NULL) {
        failed++;
      }
      else {
        p[0] = 42;
      }
    }
    mi_heap_destroy(h);

    mi_collect(true);
    mi_stats_t_decl(stats1);
    mi_stats_get(&stats1);
    result = (stats0.pages.current == stats1.pages.current);
    if (!result) {
      fprintf(stderr, "heap-os2: pages: %ld != %ld (failed: %ld)\n", (long)stats0.pages.current, (long)stats1.pages.current, failed);
    }
  }

  CHECK_BODY("heap-destroy-os-pages") {   // regular OS-backed owned pages must not be orphaned on heap destroy
    mi_collect(true);
    mi_stats_t_decl(stats0);
    mi_stats_get(&stats0);
    mi_option_set(mi_option_disallow_arena_alloc, 1);   // force all pages to be OS allocated
    mi_heap_t* h = mi_heap_new();
    bool allocated = true;
    for (int i = 0; i < 1000; i++) {  // owned OS-backed pages with live blocks
      if (mi_heap_malloc(h, 48) == NULL) { allocated = false; }
    }
    mi_heap_destroy(h);
    mi_option_set(mi_option_disallow_arena_alloc, 0);
    mi_collect(true);
    mi_stats_t_decl(stats1);
    mi_stats_get(&stats1);
    result = allocated && (stats0.pages.current == stats1.pages.current);  // orphaned if destroy missed the owned OS pages
  }

  #define NHEAPS (1000)
  CHECK_BODY("heap-many") {    // check creating many heaps and threadlocals, see issue #1358
    mi_heap_t* heaps[NHEAPS];
    for (size_t i = 0; i < NHEAPS; i++) {
      heaps[i] = mi_heap_new();
      if (heaps[i] == NULL) { result = false; break; };
      if (mi_heap_malloc(heaps[i], 32) == NULL) { result = false; break; }
    }
    for (size_t i = 0; i < NHEAPS; i++) {
      mi_heap_destroy(heaps[i]);
    }
  }

  CHECK_BODY("subproc-destroy-keeps-thread-locals") {  // destroying another subproc must not release the caller's thread locals or the fast key
    mi_heap_t* const h2 = mi_heap_new();
    mi_theap_t* const t2 = mi_heap_theap(h2);
    mi_theap_t* const tmain = mi_heap_theap(mi_heap_main());
    mi_subproc_destroy(mi_subproc_new());
    mi_heap_t* const h3 = mi_heap_new();
    mi_theap_t* const t3 = mi_heap_theap(h3);
    mi_subproc_destroy(mi_subproc_new());
    mi_heap_t* const h4 = mi_heap_new();
    mi_theap_t* const t4 = mi_heap_theap(h4);
    result = (t2!=NULL && t3!=NULL && t4!=NULL && t2!=t3 && t3!=t4);
    for (int i = 0; i < 100 && result; i++) {
      result = (mi_heap_theap(h2)==t2 && mi_heap_theap(h3)==t3 && mi_heap_theap(h4)==t4 && mi_heap_theap(mi_heap_main())==tmain);
    }
    mi_heap_delete(h4);
    mi_heap_delete(h3);
    mi_heap_delete(h2);
  }
  CHECK_THREADS_BODY("heap-destroy-xthread-free") {   // destroy a heap with live blocks and pending cross-thread frees
    result = test_heap_destroy_xthread_free();
  }
  CHECK_THREADS_BODY("heap-destroy-stale-theap") {    // a thread's cached theap must not survive the destroy of its heap
    result = test_heap_destroy_stale_theap();
  }
  CHECK_THREADS_BODY("thread-done-no-reinit") {      // allocation after `mi_thread_done` (e.g. in thread-local destructors) must not re-initialize the thread
    result = test_thread_done_no_reinit();
  }
  CHECK_THREADS_BODY("thread-heap-release") {        // after `mi_thread_heap_release` a thread can still free but no longer allocate in the heap
    result = test_thread_heap_release();
  }
  CHECK_THREADS_BODY("heap-delete-concurrent-free") { // delete a heap while other threads free its blocks
    result = test_heap_delete_concurrent_free();
  }

  //CHECK("theap_destroy", test_theap1());
  //CHECK("theap_delete", test_theap2());
  //CHECK("theap_arena_destroy", test_theap_arena_destroy());
  //CHECK("theap_arena_delete", test_theap_arena_delete());


  // ---------------------------------------------------
  // Threads
  // ---------------------------------------------------
  CHECK_THREADS_BODY("thread_zero_aligned_first") {
    result = mi_run_on_thread(&test_zero_aligned_first);
  }

  #ifdef __cplusplus
  CHECK_THREADS_BODY("thread_new_first") {
    result = mi_run_on_thread(&test_new_first);
  }
  #endif

  //mi_stats_print(NULL);

  // ---------------------------------------------------
  // various
  // ---------------------------------------------------
  #if !defined(MI_TRACK_ASAN)   // realpath may leak with ASAN enabled (as the ASAN allocator intercepts it)
  CHECK_BODY("realpath") {
    char* s = mi_realpath( ".", NULL );
    // printf("realpath: %s\n",s);
    mi_free(s);
  };
  #endif

  CHECK("stl_allocator1", test_stl_allocator1());
  CHECK("stl_allocator2", test_stl_allocator2());

	//CHECK("stl_theap_allocator1", test_stl_theap_allocator1());
	//CHECK("stl_theap_allocator2", test_stl_theap_allocator2());
	//CHECK("stl_theap_allocator3", test_stl_theap_allocator3());
	//CHECK("stl_theap_allocator4", test_stl_theap_allocator4());

  // ---------------------------------------------------
  // Done
  // ---------------------------------------------------[]
  return print_test_summary();
}

// ---------------------------------------------------
// Larger test functions
// ---------------------------------------------------

/*
bool test_theap1(void) {
  mi_theap_t* theap = mi_theap_new();
  int* p1 = mi_theap_malloc_tp(theap,int);
  int* p2 = mi_theap_malloc_tp(theap,int);
  *p1 = *p2 = 43;
  mi_theap_destroy(theap);
  return true;
}

bool test_theap2(void) {
  mi_theap_t* theap = mi_theap_new();
  int* p1 = mi_theap_malloc_tp(theap,int);
  int* p2 = mi_theap_malloc_tp(theap,int);
  mi_theap_delete(theap);
  *p1 = 42;
  mi_free(p1);
  mi_free(p2);
  return true;
}

bool test_theap_arena_destroy(void) {
  mi_arena_id_t arena_id = NULL;
  if (mi_reserve_os_memory_ex(64 * 1024 * 1024, true, false, true, &arena_id) != 0) {
    return false;
  }
  mi_theap_t* theap = mi_theap_new_ex(0, true, arena_id);
  if (theap == NULL) {
    return false;
  }
  mi_theap_destroy(theap);
  return true;
}

bool test_theap_arena_delete(void) {
  mi_arena_id_t arena_id = NULL;
  if (mi_reserve_os_memory_ex(64 * 1024 * 1024, true, false, true, &arena_id) != 0) {
    return false;
  }
  mi_theap_t* theap = mi_theap_new_ex(0, true, arena_id);
  if (theap == NULL) {
    return false;
  }
  mi_theap_delete(theap);
  return true;
}
*/
bool test_stl_allocator1(void) {
#ifdef __cplusplus
  std::vector<int, mi_stl_allocator<int> > vec;
  vec.push_back(1);
  vec.pop_back();
  return vec.size() == 0;
#else
  return true;
#endif
}

struct some_struct  { int i; int j; double z; };

bool test_stl_allocator2(void) {
#ifdef __cplusplus
  std::vector<some_struct, mi_stl_allocator<some_struct> > vec;
  vec.push_back(some_struct());
  vec.pop_back();
  return vec.size() == 0;
#else
  return true;
#endif
}

/*
bool test_stl_theap_allocator1(void) {
#ifdef __cplusplus
  std::vector<some_struct, mi_theap_stl_allocator<some_struct> > vec;
  vec.push_back(some_struct());
  vec.pop_back();
  return vec.size() == 0;
#else
  return true;
#endif
}

bool test_stl_theap_allocator2(void) {
#ifdef __cplusplus
  std::vector<some_struct, mi_theap_destroy_stl_allocator<some_struct> > vec;
  vec.push_back(some_struct());
  vec.pop_back();
  return vec.size() == 0;
#else
  return true;
#endif
}

bool test_stl_theap_allocator3(void) {
#ifdef __cplusplus
	mi_theap_t* theap = mi_theap_new();
	bool good = false;
	{
		mi_theap_stl_allocator<some_struct> myAlloc(theap);
		std::vector<some_struct, mi_theap_stl_allocator<some_struct> > vec(myAlloc);
		vec.push_back(some_struct());
		vec.pop_back();
		good = vec.size() == 0;
	}
	mi_theap_delete(theap);
  return good;
#else
  return true;
#endif
}

bool test_stl_theap_allocator4(void) {
#ifdef __cplusplus
	mi_theap_t* theap = mi_theap_new();
	bool good = false;
	{
		mi_theap_destroy_stl_allocator<some_struct> myAlloc(theap);
		std::vector<some_struct, mi_theap_destroy_stl_allocator<some_struct> > vec(myAlloc);
		vec.push_back(some_struct());
		vec.pop_back();
		good = vec.size() == 0;
	}
	mi_theap_destroy(theap);
  return good;
#else
  return true;
#endif
}
*/

// ---------------------------------------------------------------------------
// Test a zero size aligned allocation as the very first allocation of a fresh thread.
// ---------------------------------------------------------------------------

static bool test_zero_aligned_first(void) {
  void* p = mi_malloc_aligned(0, 16);     // must be the first mimalloc call on this thread
  bool res = (p != NULL && (uintptr_t)(p) % 16 == 0);
  mi_free(p);
  p = mi_zalloc_aligned(0, 32);
  res = res && (p != NULL && (uintptr_t)(p) % 32 == 0);
  mi_free(p);
  return res;
}


// ---------------------------------------------------------------------------
// Aligned allocation for all size classes and alignments up to 4KiB (including huge blocks).
// Keeps several blocks live so alignment is checked beyond the first block in a page.
// ---------------------------------------------------------------------------

static bool test_aligned_check(size_t size, size_t align, bool zero) {
  void* p[8];
  bool ok = true;
  for (int i = 0; i < 8; i++) {
    p[i] = (zero ? mi_zalloc_aligned(size, align) : mi_malloc_aligned(size, align));
    if (p[i] == NULL || ((uintptr_t)p[i] % align) != 0 || mi_usable_size(p[i]) < size || (zero && !mem_is_zero(p[i], size))) {
      ok = false;
    }
    if (p[i] != NULL) { memset(p[i], 0xAB, size); }
  }
  for (int i = 0; i < 8; i++) {
    mi_free(p[i]);
  }
  return ok;
}

static bool test_aligned_all(void) {
  bool ok = true;
  for (size_t size = 0; size <= 300*1024 && ok; size += MI_TEST_SIZE_STEP(size, (size < 16*1024 ? 8 : 512))) {
    for (size_t align = 8; align <= 4096 && ok; align *= 2) {
      ok = test_aligned_check(size, align, ((size/8) & 1) != 0);
    }
  }
  for (size_t size = 4*1024*1024 - 4096; size <= 4*1024*1024 + 3*4096 && ok; size += MI_TEST_LARGE_STEP) {
    for (size_t align = 8; align <= 4096 && ok; align *= 2) {
      ok = test_aligned_check(size, align, false);
    }
  }
  return ok;
}


#ifdef __cplusplus
static bool test_new_first(void) {
  char* p = (char*)mi_new(20);
  bool res = (p != NULL && (uintptr_t)(p) % 16 == 0);
  mi_free_csize(p,20);
  return res;
}
#endif



// ---------------------------------------------------------------------------
// Heap destroy with blocks that were freed by another thread (and not yet collected).
// The destroyed pages still have live blocks; the pending thread-free block must
// not be reported as "corrupted meta-data in thread-free list".
// ---------------------------------------------------------------------------

static void* xthread_free_block;
static long  xthread_efault_count;

static bool xthread_free_fun(void) {
  mi_free(xthread_free_block);            // pushes onto the thread-free list of a page owned by the main thread
  return true;
}

static void xthread_count_efault(int err, void* arg) {
  (void)arg;
  if (err == EFAULT) { xthread_efault_count++; }
}

static bool test_heap_destroy_xthread_free(void) {
  mi_heap_t* heap = mi_heap_new();
  if (heap == NULL) return false;
  void* live = mi_heap_malloc(heap, 32);  // stays live, so the page is destroyed rather than freed
  xthread_free_block = mi_heap_malloc(heap, 32);
  if (live == NULL || xthread_free_block == NULL) return false;
  if (!mi_run_on_thread(&xthread_free_fun)) return false;

  xthread_efault_count = 0;
  mi_register_error(&xthread_count_efault, NULL);  // the default handler aborts in debug mode
  mi_heap_destroy(heap);
  mi_register_error(NULL, NULL);
  return (xthread_efault_count == 0);
}


// ---------------------------------------------------------------------------
// A thread that last allocated from a heap keeps that theap in its `_mi_theap_cached`.
// If another thread destroys the heap and a new heap is allocated at the same address,
// the stale cached theap must not be used for the new heap (it has `tld==NULL` and its
// pages were destroyed).
// ---------------------------------------------------------------------------

// run `fun(id)` on a fresh thread (see `test_thread_start`)
typedef struct test_worker_s {
  void (*fun)(size_t id);
  size_t id;
} test_worker_t;

typedef struct test_gate_s {
  int step;
  #ifdef _WIN32
  CRITICAL_SECTION   lock;
  CONDITION_VARIABLE cond;
  #else
  pthread_mutex_t    lock;
  pthread_cond_t     cond;
  #endif
} test_gate_t;

#ifdef _WIN32
static void test_gate_init(test_gate_t* g) { g->step = 0; InitializeCriticalSection(&g->lock); InitializeConditionVariable(&g->cond); }
static void test_gate_done(test_gate_t* g) { DeleteCriticalSection(&g->lock); }
static void test_gate_set(test_gate_t* g, int step) {
  EnterCriticalSection(&g->lock); g->step = step; LeaveCriticalSection(&g->lock);
  WakeAllConditionVariable(&g->cond);
}
static void test_gate_wait(test_gate_t* g, int step) {
  EnterCriticalSection(&g->lock);
  while (g->step < step) { SleepConditionVariableCS(&g->cond, &g->lock, INFINITE); }
  LeaveCriticalSection(&g->lock);
}
typedef HANDLE test_thread_t;
static DWORD WINAPI test_thread_entry(LPVOID arg) { const test_worker_t* w = (const test_worker_t*)arg; w->fun(w->id); return 0; }
static bool test_thread_start(test_thread_t* t, const test_worker_t* w) {
  *t = CreateThread(NULL, 0, &test_thread_entry, (LPVOID)w, 0, NULL);
  return (*t != NULL);
}
static void test_thread_join(test_thread_t t) { WaitForSingleObject(t, INFINITE); CloseHandle(t); }
#else
static void test_gate_init(test_gate_t* g) { g->step = 0; pthread_mutex_init(&g->lock, NULL); pthread_cond_init(&g->cond, NULL); }
static void test_gate_done(test_gate_t* g) { pthread_cond_destroy(&g->cond); pthread_mutex_destroy(&g->lock); }
static void test_gate_set(test_gate_t* g, int step) {
  pthread_mutex_lock(&g->lock); g->step = step; pthread_mutex_unlock(&g->lock);
  pthread_cond_broadcast(&g->cond);
}
static void test_gate_wait(test_gate_t* g, int step) {
  pthread_mutex_lock(&g->lock);
  while (g->step < step) { pthread_cond_wait(&g->cond, &g->lock); }
  pthread_mutex_unlock(&g->lock);
}
typedef pthread_t test_thread_t;
static void* test_thread_entry(void* arg) { const test_worker_t* w = (const test_worker_t*)arg; w->fun(w->id); return NULL; }
static bool test_thread_start(test_thread_t* t, const test_worker_t* w) {
  return (pthread_create(t, NULL, &test_thread_entry, (void*)w) == 0);
}
static void test_thread_join(test_thread_t t) { pthread_join(t, NULL); }
#endif

static test_gate_t stale_gate;
static mi_heap_t*  stale_heap;       // published through the gate
static bool        stale_result;

static void stale_theap_worker(size_t id) {
  (void)id;
  void* p = mi_heap_malloc(stale_heap, 16);  // creates this thread's theap of `stale_heap` (may leave the main theap cached)
  mi_free(p);
  p = mi_heap_malloc(stale_heap, 16);        // now `_mi_theap_cached` is this thread's theap of `stale_heap`
  test_gate_set(&stale_gate, 1);
  test_gate_wait(&stale_gate, 2);            // meanwhile: heap destroyed, new heap (likely) at the same address
  void* q = mi_heap_malloc(stale_heap, 16);  // must not use the cached theap of the destroyed heap
  stale_result = (p != NULL && q != NULL && mi_heap_contains(stale_heap, q));
  mi_free(q);
}

#define STALE_MAX_HEAPS (1000)

static bool test_heap_destroy_stale_theap(void) {
  test_gate_init(&stale_gate);
  mi_heap_t* const destroyed = mi_heap_new();
  if (destroyed == NULL) return false;
  stale_heap = destroyed;
  stale_result = false;

  test_thread_t thread;
  const test_worker_t worker = { &stale_theap_worker, 0 };
  if (!test_thread_start(&thread, &worker)) return false;
  test_gate_wait(&stale_gate, 1);
  mi_heap_destroy(destroyed);

  // allocate heaps until one reuses the address of the destroyed heap
  mi_heap_t* heaps[STALE_MAX_HEAPS];
  size_t count = 0;
  bool reused = false;
  while (count < STALE_MAX_HEAPS) {
    mi_heap_t* const heap = mi_heap_new();
    if (heap == NULL) break;
    heaps[count++] = heap;
    if (heap == destroyed) { reused = true; break; }
  }
  if (count == 0) return false;
  stale_heap = heaps[count-1];

  test_gate_set(&stale_gate, 2);
  test_thread_join(thread);
  for (size_t i = 0; i < count; i++) { mi_heap_destroy(heaps[i]); }
  test_gate_done(&stale_gate);

  if (!reused) { fprintf(stderr, "(heap address not reused, inconclusive) "); }
  return stale_result;
}


// ---------------------------------------------------------------------------
// Allocation after `mi_thread_done` must work without re-initializing the thread
// (which would leak as the thread-done hooks may have already run).
// ---------------------------------------------------------------------------

static int64_t current_threads(void) {
  mi_stats_t_decl(stats);
  mi_stats_get(&stats);
  return stats.threads.current;
}

static bool thread_done_no_reinit_fun(void) {
  mi_free(mi_malloc(32));  // ensure the thread is initialized
  mi_heap_t* const other = mi_heap_new();
  if (other == NULL) return false;
  const int64_t threads = current_threads();
  mi_thread_done();
  bool ok = (current_threads() == threads - 1);
  void* p = mi_malloc(64);
  void* q = mi_zalloc_aligned(100, 256);
  void* r = mi_malloc(1000000);
  ok = ok && p != NULL && q != NULL && r != NULL && mem_is_zero(q, 100) && ((uintptr_t)q % 256) == 0;
  mi_heap_t* heap = mi_heap_main();
  void* s = mi_heap_malloc(heap, 32);
  ok = ok && s != NULL;
  ok = ok && mi_heap_malloc(other, 32) == NULL;  // other heaps cannot allocate on a done thread
  mi_free(p); mi_free(q); mi_free(r); mi_free(s);
  ok = ok && (current_threads() == threads - 1);
  mi_thread_init();  // explicit re-initialization is allowed
  ok = ok && (current_threads() == threads);
  void* t = mi_malloc(32);
  ok = ok && t != NULL;
  mi_free(t);
  mi_heap_delete(other);
  return ok;
}

static bool test_thread_done_no_reinit(void) {
  return mi_run_on_thread(&thread_done_no_reinit_fun);
}


// ---------------------------------------------------------------------------
// After `mi_thread_heap_release` a thread can still free blocks but no longer allocate in the heap
// (and no theap is created again). The blocks can still be freed after the heap is deleted.
// ---------------------------------------------------------------------------

static mi_heap_t* release_heap;
static void*      release_blocks[64];

static bool thread_heap_release_fun(void) {
  for (int i = 0; i < 64; i++) {
    release_blocks[i] = mi_heap_malloc(release_heap, 16 + i);
    if (release_blocks[i] == NULL) return false;
  }
  mi_free(release_blocks[0]); release_blocks[0] = NULL;
  mi_thread_heap_release(release_heap);
  bool ok = (mi_heap_malloc(release_heap, 16) == NULL && mi_heap_malloc(release_heap, 100000) == NULL);
  mi_free(release_blocks[1]); release_blocks[1] = NULL;
  mi_thread_heap_release(release_heap);  // releasing again is allowed
  ok = ok && (mi_heap_malloc(release_heap, 16) == NULL);
  return ok;
}

static bool test_thread_heap_release(void) {
  release_heap = mi_heap_new();
  if (release_heap == NULL) return false;
  mi_thread_heap_release(release_heap);  // never used in this thread
  bool ok = (mi_heap_malloc(release_heap, 16) == NULL);
  ok = ok && mi_run_on_thread(&thread_heap_release_fun);
  mi_heap_delete(release_heap);
  for (int i = 0; i < 64; i++) { mi_free(release_blocks[i]); }
  return ok;
}


// ---------------------------------------------------------------------------
// Delete a heap while other threads concurrently free its blocks. The delete must
// claim each page before moving it, and retry pages briefly owned by a concurrent free.
// ---------------------------------------------------------------------------

#define DELETE_FREE_THREADS (4)
#define DELETE_FREE_BLOCKS  (4096)

static mi_heap_t* delete_free_heap;
static void*      delete_free_blocks[DELETE_FREE_THREADS][DELETE_FREE_BLOCKS];

static void delete_free_alloc_worker(size_t id) {
  for (size_t i = 0; i < DELETE_FREE_BLOCKS; i++) {
    const size_t size = (i % 100 == 0 ? 100000 + i : (i % 10 == 0 ? 2000 + i : 8 + i % 256));
    delete_free_blocks[id][i] = mi_heap_malloc(delete_free_heap, size);
  }
  for (size_t i = 0; i < DELETE_FREE_BLOCKS; i += 3) {
    mi_free(delete_free_blocks[id][i]);
    delete_free_blocks[id][i] = NULL;
  }
  mi_thread_heap_release(delete_free_heap);
}

static void delete_free_worker(size_t id) {
  for (size_t i = 0; i < DELETE_FREE_BLOCKS; i++) {
    mi_free(delete_free_blocks[id][i]);
  }
}

static bool test_heap_delete_concurrent_free(void) {
  const long disallow_arena_alloc = mi_option_get(mi_option_disallow_arena_alloc);
  for (int iter = 0; iter < MI_TEST_ITERS(20); iter++) {
    mi_option_set(mi_option_disallow_arena_alloc, iter % 2);  // odd iterations use OS allocated pages
    delete_free_heap = mi_heap_new();
    if (delete_free_heap == NULL) return false;
    test_thread_t threads[DELETE_FREE_THREADS];
    test_worker_t workers[DELETE_FREE_THREADS];
    for (size_t i = 0; i < DELETE_FREE_THREADS; i++) {
      workers[i].fun = &delete_free_alloc_worker; workers[i].id = i;
      if (!test_thread_start(&threads[i], &workers[i])) return false;
    }
    for (size_t i = 0; i < DELETE_FREE_THREADS; i++) { test_thread_join(threads[i]); }
    for (size_t i = 0; i < DELETE_FREE_THREADS; i++) {
      workers[i].fun = &delete_free_worker;
      if (!test_thread_start(&threads[i], &workers[i])) return false;
    }
    mi_heap_delete(delete_free_heap);
    for (size_t i = 0; i < DELETE_FREE_THREADS; i++) { test_thread_join(threads[i]); }
  }
  mi_option_set(mi_option_disallow_arena_alloc, disallow_arena_alloc);
  return true;
}