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
#include "../src/arena/arena.h"
#include "../src/arena/arena-page.h"
#include "mimalloc/alloc/page.h"
#include "mimalloc/heap/theap.h"
#include "mimalloc/prim/prim.h"
#include "mimalloc/prim/os.h"
#include "testhelper.h"

static mi_subproc_t test_subproc;
static mi_heap_t test_heap;
static mi_arena_t test_arenas[6];

typedef struct arena_visit_s {
  size_t indexes[6];
  size_t count;
  size_t stop_after;
} arena_visit_t;

typedef struct arena_visit_info_s {
  arena_visit_t* visit;
} arena_visit_info_t;

static void arena_setup(size_t count) {
  test_heap.subproc = &test_subproc;
  test_heap.heap_seq = 0;
  mi_atomic_store_relaxed(&test_subproc.heap_count, 1);
  mi_atomic_store_relaxed(&test_subproc.arena_count, count);
  for (size_t i = 0; i < 6; i++) {
    test_arenas[i].arena_idx = i;
    test_arenas[i].parent = NULL;
    test_arenas[i].is_exclusive = false;
    test_arenas[i].memid.is_pinned = false;
    test_arenas[i].numa_node = 0;
    mi_atomic_store_ptr_release(mi_arena_t, &test_subproc.arenas[i], &test_arenas[i]);
  }
}

static bool arena_record(mi_arena_t* arena, const void* arg, void** result) {
  MI_UNUSED(result);
  const arena_visit_info_t* info = (const arena_visit_info_t*)arg;
  arena_visit_t* visit = info->visit;
  if (visit->count >= 6) return false;
  visit->indexes[visit->count++] = arena->arena_idx;
  return (visit->stop_after == 0 || visit->count < visit->stop_after);
}

static bool arena_matches(const arena_visit_t* visit, const size_t* expected, size_t count) {
  if (visit->count != count) return false;
  for (size_t i = 0; i < count; i++) {
    if (visit->indexes[i] != expected[i]) return false;
  }
  return true;
}

static bool test_arena_order(void) {
  for (size_t count = 0; count <= 6; count++) {
    arena_setup(count);
    for (size_t tseq = 0; tseq < 8; tseq++) {
      arena_visit_t visit = { { 0 }, 0, 0 };
      const arena_visit_info_t info = { &visit };
      if (!mi_forall_arenas(&test_heap, NULL, tseq, &arena_record, &info, NULL)) return false;
      if (visit.count != count) return false;
      for (size_t i = 0; i < count; i++) {
        const size_t expected = (i + 1 == count ? i : (tseq + i) % (count - 1));
        if (visit.indexes[i] != expected) return false;
      }
    }
  }
  arena_setup(6);
  test_heap.heap_seq = 1;
  mi_atomic_store_relaxed(&test_subproc.heap_count, 2);
  arena_visit_t visit = { { 0 }, 0, 0 };
  const arena_visit_info_t info = { &visit };
  const size_t expected[] = { 3, 4, 0, 1, 2, 5 };
  if (!mi_forall_arenas(&test_heap, NULL, 1, &arena_record, &info, NULL)) return false;
  return arena_matches(&visit, expected, 6);
}

static bool test_arena_filter(void) {
  arena_setup(6);
  mi_atomic_store_ptr_release(mi_arena_t, &test_subproc.arenas[1], NULL);
  test_arenas[2].memid.is_pinned = true;
  test_arenas[2].numa_node = 1;
  test_arenas[3].is_exclusive = true;
  test_arenas[4].numa_node = -1;
  test_arenas[5].numa_node = 1;

  arena_visit_t visit = { { 0 }, 0, 0 };
  const arena_visit_info_t info = { &visit };
  const size_t all[] = { 0, 2, 3, 4, 5 };
  if (!mi_forall_arenas(&test_heap, NULL, 0, &arena_record, &info, NULL) || !arena_matches(&visit, all, 5)) return false;

  visit.count = 0;
  const size_t local[] = { 0, 4 };
  if (!mi_forall_suitable_arenas(&test_heap, NULL, 0, true, 0, false, &arena_record, &info, NULL) ||
      !arena_matches(&visit, local, 2)) return false;

  visit.count = 0;
  const size_t remote[] = { 2, 5 };
  if (!mi_forall_suitable_arenas(&test_heap, NULL, 0, false, 0, true, &arena_record, &info, NULL) ||
      !arena_matches(&visit, remote, 2)) return false;

  visit.count = 0;
  const size_t any[] = { 0, 2, 4, 5 };
  if (!mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, true, &arena_record, &info, NULL) ||
      !arena_matches(&visit, any, 4)) return false;

  visit.count = 0;
  if (!mi_forall_suitable_arenas(&test_heap, NULL, 0, false, -1, true, &arena_record, &info, NULL) || visit.count != 0) return false;

  test_arenas[4].parent = &test_arenas[3];
  test_arenas[5].parent = &test_arenas[3];
  test_arenas[4].is_exclusive = true;
  test_arenas[5].is_exclusive = true;
  const size_t family[] = { 3, 4, 5 };
  if (!mi_forall_suitable_arenas(&test_heap, &test_arenas[3], 0, false, 99, false, &arena_record, &info, NULL) ||
      !arena_matches(&visit, family, 3)) return false;

  visit.count = 0;
  test_arenas[3].memid.is_pinned = true;
  const size_t children[] = { 4, 5 };
  if (!mi_forall_suitable_arenas(&test_heap, &test_arenas[3], 0, true, 99, false, &arena_record, &info, NULL) ||
      !arena_matches(&visit, children, 2)) return false;

  visit.count = 0;
  test_arenas[5].parent = NULL;
  const size_t last[] = { 5 };
  if (!mi_forall_arenas(&test_heap, &test_arenas[5], 0, &arena_record, &info, NULL)) return false;
  return arena_matches(&visit, last, 1);
}

static bool test_arena_stop(void) {
  arena_setup(6);
  for (size_t stop = 1; stop <= 6; stop++) {
    arena_visit_t visit = { { 0 }, 0, stop };
    const arena_visit_info_t info = { &visit };
    if (mi_forall_arenas(&test_heap, NULL, 0, &arena_record, &info, NULL) || visit.count != stop) return false;
  }
  test_arenas[0].is_exclusive = true;
  test_arenas[1].memid.is_pinned = true;
  arena_visit_t visit = { { 0 }, 0, 2 };
  const arena_visit_info_t info = { &visit };
  const size_t expected[] = { 2, 3 };
  if (mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, false, &arena_record, &info, NULL)) return false;
  return arena_matches(&visit, expected, 2);
}

static bool arena_publish(mi_arena_t* arena, const void* arg, void** result) {
  mi_atomic_store_relaxed(&test_subproc.arena_count, 6);
  return arena_record(arena, arg, result);
}

static bool test_arena_snapshot(void) {
  arena_setup(3);
  arena_visit_t visit = { { 0 }, 0, 0 };
  const arena_visit_info_t info = { &visit };
  const size_t expected[] = { 0, 1, 2 };
  if (!mi_forall_arenas(&test_heap, NULL, 0, &arena_publish, &info, NULL)) return false;
  return arena_matches(&visit, expected, 3);
}

static bool arena_find(mi_arena_t* arena, const void* arg, void** result) {
  const size_t* index = (const size_t*)arg;
  if (arena->arena_idx != *index) return true; // continue
  if (result != NULL) *result = arena;
  return false; // break
}

static bool test_arena_result(void) {
  arena_setup(6);
  const size_t index = 3;
  void* found = NULL;
  if (mi_forall_arenas(&test_heap, NULL, 0, &arena_find, &index, &found) || found != &test_arenas[3]) return false;
  found = NULL;
  if (mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, false, &arena_find, &index, &found) ||
      found != &test_arenas[3]) return false;
  if (mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, false, &arena_find, &index, NULL)) return false;

  test_arenas[3].is_exclusive = true;
  if (!mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, false, &arena_find, &index, &found) || found != NULL) return false;
  const size_t absent = 6;
  found = &test_arenas[0];
  if (!mi_forall_arenas(&test_heap, NULL, 0, &arena_find, &absent, &found) || found != NULL) return false;
  arena_setup(0);
  found = &test_arenas[0];
  if (!mi_forall_arenas(&test_heap, NULL, 0, &arena_find, &index, &found) || found != NULL) return false;
  found = &test_arenas[0];
  return (mi_forall_suitable_arenas(&test_heap, NULL, 0, true, -1, false, &arena_find, &index, &found) && found == NULL);
}

#if MI_PAGE_META_IS_ALIGNED
static bool test_arena_oversized_alloc(void) {
  void* warm = mi_malloc(64);
  if (warm == NULL) return false;
  mi_free(warm);
  mi_subproc_t* subproc = mi_theap_subproc(mi_theap_get_default());
  const size_t arena_count = mi_arenas_get_count(subproc);
  const size_t size = (MI_PAGE_META_ALIGNED_CHUNKS - 1) * MI_ARENA_CHUNK_SIZE + MI_ARENA_SLICE_SIZE;
  bool result = true;
  for (size_t i = 0; i < 2; i++) {
    void* p = mi_malloc(size);
    if (p == NULL || mi_arenas_get_count(subproc) != arena_count) { result = false; }
    mi_free(p);
  }
  return result;
}
#endif

#if MI_PAGE_META_IS_SEPARATED && !MI_PAGE_META_IS_ALIGNED
static bool test_arena_page_meta_permutation(void) {
  mi_arena_id_t arena_id;
  if (mi_reserve_os_memory_ex(5 * MI_ARENA_CHUNK_SIZE, false, false, true, &arena_id) != 0) return false;
  mi_arena_t* arena = _mi_arena_from_id(arena_id);
  if (arena == NULL || arena->pages_meta == NULL || arena->slice_count != 5 * MI_BCHUNK_BITS) return false;
  bool seen[5 * MI_BCHUNK_BITS] = { false };
  for (size_t i = 0; i < arena->slice_count; i++) {
    const mi_page_t* entry = mi_arena_page_meta_at_slice(arena, i);
    const size_t idx = (size_t)(entry - arena->pages_meta);
    if (idx >= arena->slice_count || seen[idx] || idx / MI_BCHUNK_BITS != i / MI_BCHUNK_BITS) return false;
    seen[idx] = true;
  }

  mi_heap_t* heap = mi_heap_new_in_arena(arena_id);
  if (heap == NULL) return false;
  void* blocks[MI_BCHUNK_BITS / 4 + 1] = { NULL };
  bool result = true;
  bool crossed_chunk = false;
  for (size_t i = 0; result && i < sizeof(blocks)/sizeof(blocks[0]); i++) {
    blocks[i] = mi_heap_malloc(heap, MI_MEDIUM_PAGE_SIZE / 2);
    if (blocks[i] == NULL) { result = false; break; }
    mi_page_t* page = mi_ptr_page(blocks[i]);
    result = (page != NULL && page->memid.memkind == MI_MEM_ARENA && mi_memid_arena(page->memid) == arena);
    if (!result) break;
    const size_t slice_index = page->memid.mem.arena.slice_index;
    result = (mi_addr(page) == mi_addr(mi_arena_page_meta_at_slice(arena, slice_index)) &&
              mi_arena_page_at_slice(arena, slice_index) == page);
    if (slice_index >= MI_BCHUNK_BITS) crossed_chunk = true;
  }
  for (size_t i = 0; i < sizeof(blocks)/sizeof(blocks[0]); i++) { mi_free(blocks[i]); }
  mi_heap_destroy(heap);
  return (result && crossed_chunk);
}
#endif

#if MI_STATS
static bool test_os_aligned_offset_stats(void) {
  mi_subproc_t* subproc = mi_theap_subproc(mi_theap_get_default());
  const size_t page_size = _mi_os_page_size();
  const size_t alignment = 16 * page_size;
  const size_t size = 2 * alignment;
  const size_t offsets[] = { page_size, page_size + 1, alignment - 1 };
  bool result = true;
  for (size_t commit = 0; commit < 2; commit++) {
    for (size_t i = 0; i < sizeof(offsets)/sizeof(offsets[0]); i++) {
      const int64_t committed = subproc->stats.committed.current;
      const int64_t reserved = subproc->stats.reserved.current;
      mi_memid_t memid;
      void* p = _mi_os_alloc_aligned_at_offset(subproc, size, alignment, offsets[i], commit != 0, false, &memid);
      if (p == NULL) return false;
      result = result && ((mi_addr(p) + offsets[i]) % alignment == 0);
      _mi_os_free(subproc, p, size, memid);
      result = result && subproc->stats.committed.current == committed && subproc->stats.reserved.current == reserved;
    }
  }
  return result;
}
#endif

static bool test_os_allow_large(void) {
  const long allow_large = mi_option_get(mi_option_allow_large_os_pages);
  mi_option_enable(mi_option_allow_large_os_pages);
  mi_subproc_t* subproc = mi_theap_subproc(mi_theap_get_default());
  const size_t size = mi_align_up(2 * MI_MiB, _mi_os_large_page_size());
  mi_memid_t memid;
  void* p = _mi_os_alloc_aligned(subproc, size, _mi_os_large_page_size(), true, true, &memid);
  mi_option_set(mi_option_allow_large_os_pages, allow_large);
  if (p == NULL) return false;
  bool result = true;
  #if MI_SECURE > 0 && MI_OS_HAS_GUARD_PAGES
  result = !memid.is_pinned;
  #endif
  memset(p, 0x5A, size);
  _mi_os_free(subproc, p, size, memid);
  return result;
}

#if MI_SECURE > 0 && MI_OS_HAS_GUARD_PAGES
static bool record_pinned_commit(bool commit, void* start, size_t size, bool* is_zero, void* arg) {
  MI_UNUSED(commit); MI_UNUSED(start); MI_UNUSED(size); MI_UNUSED(is_zero);
  (*(size_t*)arg)++;
  return false;
}

static bool test_arena_reject_pinned(void) {
  mi_subproc_t* subproc = mi_theap_subproc(mi_theap_get_default());
  const size_t arena_count = mi_arenas_get_count(subproc);
  const size_t size = MI_ARENA_MIN_SIZE;
  mi_memid_t memid;
  void* p = _mi_os_alloc_aligned(subproc, size, MI_ARENA_ALIGNMENT, false, false, &memid);
  if (p == NULL) return false;
  // Leave the memory uncommitted: rejection must not access the supplied area.
  if (mi_manage_os_memory(p, size, true, true, true, -1)) return false;
  mi_arena_id_t arena_id = &test_arenas[0];
  if (mi_manage_os_memory_ex(p, size, true, true, true, -1, true, &arena_id)) return false;
  bool result = (arena_id == NULL);
  size_t commits = 0;
  arena_id = &test_arenas[0];
  if (mi_manage_memory(p, size, false, true, true, -1, true, &record_pinned_commit, &commits, &arena_id)) return false;
  result = (result && arena_id == NULL && commits == 0 && mi_arenas_get_count(subproc) == arena_count);
  _mi_os_free(subproc, p, size, memid);
  return result;
}

static bool test_os_reject_huge_pages(void) {
  mi_subproc_t* subproc = mi_theap_subproc(mi_theap_get_default());
  size_t pages = 1;
  size_t size = 1;
  mi_memid_t memid;
  void* p = _mi_os_alloc_huge_os_pages(subproc, 1, -1, 0, &pages, &size, &memid);
  if (p != NULL) {
    _mi_os_free(subproc, p, size, memid);
    return false;
  }
  if (pages != 0 || size != 0 || memid.memkind != MI_MEM_NONE) return false;
  mi_arena_id_t arena_id = &test_arenas[0];
  if (mi_reserve_huge_os_pages_at_ex(1, -1, 0, true, &arena_id) == 0 || arena_id != NULL) return false;
  return (mi_reserve_huge_os_pages_interleave(1, 1, 0) != 0 &&
          mi_reserve_huge_os_pages_at_ex(0, -1, 0, true, &arena_id) == 0 && arena_id == NULL);
}
#endif

static mi_heap_t* visit_heap;

static bool allocate_pages(void) {
  if (mi_heap_malloc(visit_heap, 64) == NULL ||
      mi_heap_malloc(visit_heap, 256) == NULL ||
      mi_heap_malloc(visit_heap, 4096) == NULL) return false;
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  mi_option_enable(mi_option_disallow_arena_alloc);
  void* p = mi_heap_malloc(visit_heap, 2 * MI_MiB);
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  return (p != NULL);
}

typedef struct block_visit_s {
  size_t areas;
  size_t blocks;
  bool stop;
  bool stop_on_block;
} block_visit_t;

static bool block_record(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {
  MI_UNUSED(heap);
  MI_UNUSED(area);
  MI_UNUSED(block_size);
  block_visit_t* visit = (block_visit_t*)arg;
  if (block == NULL) { visit->areas++; }
  else { visit->blocks++; }
  return (!visit->stop || (visit->stop_on_block && block == NULL));
}

static bool test_heap_visit_stop(void) {
  visit_heap = mi_heap_new();
  if (visit_heap == NULL) return false;
  bool result = mi_run_on_thread(&allocate_pages);
  for (size_t abandoned = 0; result && abandoned < 2; abandoned++) {
    for (size_t mode = 0; result && mode < 3; mode++) {
      block_visit_t visit = { 0, 0, mode != 0, mode == 2 };
      const bool completed = (abandoned == 0
          ? mi_heap_visit_blocks(visit_heap, true, &block_record, &visit)
          : mi_heap_visit_abandoned_blocks(visit_heap, true, &block_record, &visit));
      if (mode == 0) {
        result = (completed && visit.areas == 4 && visit.blocks == 4);
      }
      else {
        result = (!completed && visit.areas == 1 && visit.blocks == (mode == 2 ? 1 : 0));
      }
    }
  }
  mi_heap_destroy(visit_heap);
  visit_heap = NULL;
  return result;
}

#define VISIT_OWNED_BLOCKS 256
static void* owned_blocks[VISIT_OWNED_BLOCKS + 1];

typedef struct owned_visit_s {
  size_t used;
  size_t blocks;
  size_t os_areas;
  size_t arena_areas;
  bool seen[VISIT_OWNED_BLOCKS + 1];
} owned_visit_t;

static bool owned_record(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {
  MI_UNUSED(block_size);
  owned_visit_t* visit = (owned_visit_t*)arg;
  if (heap != visit_heap) return false;
  if (block == NULL) {
    visit->used += area->used;
    const mi_page_t* page = mi_ptr_page(area->blocks);
    if (page->memid.memkind == MI_MEM_ARENA) { visit->arena_areas++; }
    else { visit->os_areas++; }
    return true;
  }
  for (size_t i = 0; i <= VISIT_OWNED_BLOCKS; i++) {
    if (block == owned_blocks[i]) {
      if (visit->seen[i]) return false;
      visit->seen[i] = true;
      visit->blocks++;
      return true;
    }
  }
  return false;
}

static bool free_owned_blocks(void) {
  for (size_t i = 0; i < VISIT_OWNED_BLOCKS / 4; i++) {
    mi_free(owned_blocks[i]);
    owned_blocks[i] = NULL;
  }
  return true;
}

static bool test_heap_visit_owned_os(bool mixed) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long retain = mi_option_get(mi_option_page_full_retain);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  mi_option_set(mi_option_page_full_retain, -1);
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_option_disable(mi_option_disallow_arena_alloc);
  visit_heap = mi_heap_new();
  bool result = (visit_heap != NULL);
  owned_blocks[VISIT_OWNED_BLOCKS] = (mixed && result ? mi_heap_malloc(visit_heap, 64) : NULL);
  if (mixed && owned_blocks[VISIT_OWNED_BLOCKS] == NULL) result = false;
  mi_option_enable(mi_option_disallow_arena_alloc);
  for (size_t i = 0; result && i < VISIT_OWNED_BLOCKS; i++) {
    owned_blocks[i] = mi_heap_malloc(visit_heap, 4096);
    result = (owned_blocks[i] != NULL);
  }
  if (result) {
    result = (mi_heap_theap(visit_heap)->pages[MI_BIN_FULL].first != NULL);
  }
  for (size_t i = 0; result && i < VISIT_OWNED_BLOCKS; i++) {
    result = (mi_thread_id_of(owned_blocks[i]) == mi_heap_theap(visit_heap)->tld->thread_id);
  }
  if (result) result = mi_run_on_thread(&free_owned_blocks);
  const size_t expected = VISIT_OWNED_BLOCKS * 3 / 4 + (mixed ? 1 : 0);
  for (size_t mode = 0; result && mode < 2; mode++) {
    owned_visit_t visit = { 0, 0, 0, 0, { false } };
    result = (mi_heap_visit_blocks(visit_heap, mode != 0, &owned_record, &visit) &&
              visit.used == expected && visit.blocks == (mode != 0 ? expected : 0) &&
              visit.os_areas > 0 && visit.os_areas == mi_heap_theap(visit_heap)->page_count_os &&
              visit.arena_areas == (mixed ? 1 : 0));
  }
  if (result) {
    block_visit_t visit = { 0, 0, false, false };
    result = (mi_heap_visit_abandoned_blocks(visit_heap, true, &block_record, &visit) &&
              visit.areas == 0 && visit.blocks == 0);
  }
  for (size_t mode = 1; result && mode <= 2; mode++) {
    block_visit_t visit = { 0, 0, true, mode == 2 };
    result = (!mi_heap_visit_blocks(visit_heap, true, &block_record, &visit) &&
              visit.areas == 1 && visit.blocks == (mode == 2 ? 1 : 0));
  }
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  if (result) result = mi_run_on_thread(&allocate_pages);
  if (result) {
    block_visit_t all = { 0, 0, false, false };
    block_visit_t abandoned = { 0, 0, false, false };
    result = (mi_heap_visit_blocks(visit_heap, true, &block_record, &all) && all.blocks == expected + 4 &&
              mi_heap_visit_abandoned_blocks(visit_heap, true, &block_record, &abandoned) && abandoned.blocks == 4);
  }
  mi_heap_destroy(visit_heap);
  visit_heap = NULL;
  mi_option_set(mi_option_page_full_retain, retain);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  return result;
}

static bool test_heap_page_count_os(void) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  const long reclaim = mi_option_get(mi_option_page_reclaim_on_free);
  mi_option_enable(mi_option_disallow_arena_alloc);
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_option_set(mi_option_page_reclaim_on_free, 0);
  mi_heap_t* heap = mi_heap_new();
  mi_theap_t* theap = (heap == NULL ? NULL : mi_heap_theap(heap));
  bool result = (theap != NULL && theap->page_count_os == 0);
  if (result) {
    void* p = mi_heap_malloc(heap, 64);
    void* q = mi_heap_malloc(heap, 64);
    void* r = mi_heap_malloc(heap, 256);
    result = (p != NULL && q != NULL && r != NULL);
    if (result) {
      result = (theap->page_count_os == 2);
      mi_free(r);
      mi_heap_collect(heap, true);
      result = (theap->page_count_os == 1 && result);
      _mi_theap_collect_abandon(theap);
      result = (theap->page_count_os == 0 && result);
      mi_free(p); // reclaim the page containing q into the originating theap
      result = (theap->page_count_os == 1 && result);
      block_visit_t visit = { 0, 0, false, false };
      result = (mi_heap_visit_blocks(heap, true, &block_record, &visit) && visit.blocks == 1 && result);
      mi_free(q);
      mi_heap_collect(heap, true);
      result = (theap->page_count_os == 0 && result);
    }
  }
  mi_heap_destroy(heap);
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  mi_option_set(mi_option_page_reclaim_on_free, reclaim);
  return result;
}

static _Atomic(size_t) visit_exit_state;

static bool visit_exit_owner(void) {
  const bool result = allocate_pages();
  mi_atomic_store_release(&visit_exit_state, 1);
  while (mi_atomic_load_acquire(&visit_exit_state) < 2) { _mi_prim_thread_yield(); }
  mi_atomic_store_release(&visit_exit_state, 3);
  return result;
}

static bool exit_record(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t block_size, void* arg) {
  if (mi_atomic_load_acquire(&visit_exit_state) == 1) {
    mi_atomic_store_release(&visit_exit_state, 2);
    while (mi_atomic_load_acquire(&visit_exit_state) < 3) { _mi_prim_thread_yield(); }
    for (size_t i = 0; i < 64; i++) { _mi_prim_thread_yield(); }
  }
  return block_record(heap, area, block, block_size, arg);
}

static bool test_heap_visit_thread_exit(void) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  mi_option_set(mi_option_guarded_sample_rate, 0);
  bool result = true;
  for (size_t i = 0; result && i < 32; i++) {
    mi_option_set(mi_option_disallow_arena_alloc, (long)(i % 2));
    visit_heap = mi_heap_new();
    if (visit_heap == NULL) { result = false; break; }
    if (mi_heap_malloc(visit_heap, 128) == NULL) {
      mi_heap_destroy(visit_heap);
      visit_heap = NULL;
      result = false;
      break;
    }
    mi_atomic_store_release(&visit_exit_state, 0);
    mi_thread_fun_args_t args = { &visit_exit_owner, false };
    #ifdef _WIN32
    HANDLE thread = CreateThread(NULL, 0, &mi_win_thread_entry, &args, 0, NULL);
    const bool started = (thread != NULL);
    #else
    pthread_t thread;
    const bool started = (pthread_create(&thread, NULL, &mi_pthread_entry, &args) == 0);
    #endif
    if (started) {
      while (mi_atomic_load_acquire(&visit_exit_state) == 0) { _mi_prim_thread_yield(); }
      block_visit_t visit = { 0, 0, false, false };
      result = (mi_heap_visit_blocks(visit_heap, true, &exit_record, &visit) && visit.blocks == 5);
      if (mi_atomic_load_acquire(&visit_exit_state) == 1) mi_atomic_store_release(&visit_exit_state, 2);
      #ifdef _WIN32
      WaitForSingleObject(thread, INFINITE);
      CloseHandle(thread);
      #else
      pthread_join(thread, NULL);
      #endif
      visit.blocks = visit.areas = 0;
      result = (result && args.result &&
                mi_heap_visit_abandoned_blocks(visit_heap, true, &block_record, &visit) && visit.blocks == 4);
    }
    else {
      result = false;
    }
    mi_heap_destroy(visit_heap);
    visit_heap = NULL;
  }
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  return result;
}

static bool test_theap_collect_detached(void) {
  mi_theap_t* const theap = mi_theap_get_default();
  mi_subproc_t* const subproc = theap->tld->subproc;
  int* p = NULL;
  bool result = false;
  mi_lock(&subproc->theap_meta_lock) {
    p = (int*)mi_theap_malloc(subproc->theap_meta, sizeof(int));
    if (p != NULL) {
      *p = 42;
      mi_theap_collect(subproc->theap_meta, false);
      mi_theap_collect(subproc->theap_meta, true);
      result = (*p == 42 && mi_thread_id_of(p) == 0);
    }
  }
  mi_free(p);
  return result;
}

static mi_heap_t* thread_id_heap;
static void* thread_id_blocks[3];
static size_t thread_id_owner;

static bool read_thread_ids(void) {
  for (size_t i = 0; i < 3; i++) {
    const uint8_t* p = (const uint8_t*)thread_id_blocks[i];
    if (mi_thread_id_of(p) != thread_id_owner ||
        mi_thread_id_of(p + sizeof(size_t)) != thread_id_owner ||
        mi_thread_id_of(p + 2 * sizeof(size_t)) != thread_id_owner) return false;
  }
  return (mi_thread_id_of((const uint8_t*)thread_id_blocks[2] + MI_SMALL_SIZE_MAX - sizeof(size_t)) == thread_id_owner);
}

static bool allocate_thread_id_blocks(void) {
  thread_id_blocks[0] = mi_heap_malloc(thread_id_heap, 256);
  thread_id_blocks[1] = mi_heap_malloc(thread_id_heap, 256);
  thread_id_blocks[2] = mi_heap_malloc_aligned_at(thread_id_heap, 2 * MI_SMALL_SIZE_MAX, 64, sizeof(size_t));
  if (thread_id_blocks[0] == NULL || thread_id_blocks[1] == NULL || thread_id_blocks[2] == NULL) return false;
  thread_id_owner = mi_heap_theap(thread_id_heap)->tld->thread_id;
  return (read_thread_ids() && mi_run_on_thread(&read_thread_ids));
}

static bool test_thread_id_of(bool os_pages, long reclaim_mode) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  const long reclaim = mi_option_get(mi_option_page_reclaim_on_free);
  mi_option_set(mi_option_disallow_arena_alloc, (os_pages ? 1 : 0));
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_option_set(mi_option_page_reclaim_on_free, reclaim_mode);
  thread_id_heap = mi_heap_new();
  mi_option_set(mi_option_page_reclaim_on_free, (reclaim_mode == 1 ? -1 : 1));
  mi_theap_t* theap = (thread_id_heap == NULL ? NULL : mi_heap_theap(thread_id_heap));
  bool result = (theap != NULL && mi_thread_id_of(NULL) == 0 &&
                 theap->allow_page_reclaim == (reclaim_mode >= 0));
  for (size_t i = 0; i < 3; i++) { thread_id_blocks[i] = NULL; }
  if (result) result = mi_run_on_thread(&allocate_thread_id_blocks);
  if (result) {
    const mi_page_t* page = mi_ptr_page(thread_id_blocks[0]);
    result = (mi_page_thread_id(page) == (os_pages ? MI_THREAD_ID_ABANDONED : MI_THREAD_ID_ABANDONED_MAPPED));
    for (size_t i = 0; i < 3; i++) {
      result = (mi_thread_id_of(thread_id_blocks[i]) == 0 &&
                mi_thread_id_of((const uint8_t*)thread_id_blocks[i] + 2 * sizeof(size_t)) == 0 && result);
    }
    mi_free(thread_id_blocks[0]); // only the heap's creation-time mode can permit cross-thread reclaim
    thread_id_blocks[0] = NULL;
    const size_t expected_owner = (reclaim_mode == 1 ? theap->tld->thread_id : 0);
    result = (mi_thread_id_of(thread_id_blocks[1]) == expected_owner &&
              mi_thread_id_of(thread_id_blocks[2]) == 0 && result);
  }
  for (size_t i = 0; i < 3; i++) {
    mi_free(thread_id_blocks[i]);
    thread_id_blocks[i] = NULL;
  }
  mi_heap_destroy(thread_id_heap);
  thread_id_heap = NULL;
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  mi_option_set(mi_option_page_reclaim_on_free, reclaim);
  return result;
}

static bool test_theap_delete_owner(void) {
  mi_theap_t* const main = mi_theap_get_default();
  mi_tld_t* const tld = main->tld;
  bool result = true;
  for (size_t cached = 0; result && cached < 2; cached++) {
    mi_heap_t* heap = mi_heap_new();
    if (heap == NULL) return false;
    mi_theap_t* theap = mi_heap_theap(heap);
    int* p = (int*)mi_theap_malloc(theap, sizeof(int));
    int* q = (int*)mi_theap_malloc(main, sizeof(int));
    result = (p != NULL && q != NULL);
    if (result) {
      *p = 42;
      *q = 43;
      mi_free(mi_theap_malloc(theap, 4096)); // include an empty retired page
      mi_theap_set_default(theap);
      if (cached == 0) {
        // Reach the statistics update threshold during quiescent abandonment.
        for (size_t i = 0; i < 0x8000; i++) {
          mi_free(mi_theap_malloc(theap, sizeof(int)));
        }
        mi_theap_quiescent_abandon(theap);
        result = (theap->page_count == 0 && theap->tld == tld &&
                  mi_theap_get_default() == theap && mi_heap_theap(heap) == theap &&
                  *p == 42 && mi_thread_id_of(p) == 0 && result);
        mi_free(mi_malloc(4096));
      }
      mi_theap_delete(main);
      result = (mi_theap_get_default() == theap && main->tld == tld &&
                *q == 43 && mi_thread_id_of(q) == 0 && result);
      (void)mi_heap_theap(cached ? heap : mi_heap_main());
      mi_theap_delete(theap);
      result = (mi_theap_get_default() == main && main->tld == tld &&
                heap->theaps == NULL && *p == 42 && mi_heap_of(p) == heap &&
                mi_thread_id_of(p) == 0 && result);
      block_visit_t visit = { 0, 0, false, false };
      result = (mi_heap_visit_abandoned_blocks(heap, true, &block_record, &visit) &&
                visit.blocks == 1 && result);
      theap = mi_heap_theap(heap);
      int* r = (int*)mi_heap_malloc(heap, sizeof(int));
      result = (r != NULL && theap->tld == tld && mi_heap_of(r) == heap && result);
      mi_free(r);
      mi_theap_delete(theap);
    }
    mi_free(p);
    mi_free(q);
    mi_heap_destroy(heap);
  }
  mi_theap_delete(main);
  void* p = mi_malloc(64);
  result = (p != NULL && mi_theap_get_default() == main && main->tld == tld && result);
  mi_free(p);
  return result;
}

#define CLEANUP_BLOCKS 64
static mi_heap_t* cleanup_heap;
static mi_theap_t* cleanup_theap;
static void* cleanup_blocks[CLEANUP_BLOCKS];
static _Atomic(size_t) cleanup_state;

static bool abandon_owner(void) {
  cleanup_theap = mi_heap_theap(cleanup_heap);
  mi_theap_set_default(cleanup_theap);
  bool result = true;
  for (size_t i = 0; i < CLEANUP_BLOCKS; i++) {
    cleanup_blocks[i] = mi_malloc(4096);
    if (cleanup_blocks[i] == NULL) { result = false; }
    else { memset(cleanup_blocks[i], (int)i, 4096); }
  }
  mi_free(mi_malloc(128));
  (void)mi_heap_theap(cleanup_heap);
  mi_atomic_store_release(&cleanup_state, 1);
  while (mi_atomic_load_acquire(&cleanup_state) < 2) { _mi_prim_thread_yield(); }
  result = (cleanup_theap->page_count == 0 && cleanup_theap->page_count_os == 0 &&
            mi_theap_get_default() == cleanup_theap && mi_heap_theap(cleanup_heap) == cleanup_theap && result);
  void* p = mi_malloc(64);
  void* q = mi_theap_malloc(cleanup_theap, 128);
  void* r = mi_heap_malloc(cleanup_heap, 256);
  result = (p != NULL && q != NULL && r != NULL && mi_heap_of(p) == cleanup_heap &&
            mi_heap_of(q) == cleanup_heap && mi_heap_of(r) == cleanup_heap && result);
  mi_free(p);
  mi_free(q);
  mi_free(r);
  return result; // leave the default set to exercise automatic thread cleanup
}

static bool test_theap_abandon_foreign(void) {
  cleanup_heap = mi_heap_new();
  if (cleanup_heap == NULL) return false;
  mi_theap_t* const local = mi_heap_theap(cleanup_heap);
  int* p = (int*)mi_theap_malloc(local, sizeof(int));
  if (p != NULL) { *p = 42; }
  mi_atomic_store_release(&cleanup_state, 0);
  mi_thread_fun_args_t args = { &abandon_owner, false };
  #ifdef _WIN32
  HANDLE thread = CreateThread(NULL, 0, &mi_win_thread_entry, &args, 0, NULL);
  const bool started = (thread != NULL);
  #else
  pthread_t thread;
  const bool started = (pthread_create(&thread, NULL, &mi_pthread_entry, &args) == 0);
  #endif
  bool result = (p != NULL && started);
  if (started) {
    while (mi_atomic_load_acquire(&cleanup_state) < 1) { _mi_prim_thread_yield(); }
    result = (cleanup_theap->pages[MI_BIN_FULL].first != NULL && result);
    mi_free(cleanup_blocks[0]); // collect a pending cross-thread free during abandonment
    cleanup_blocks[0] = NULL;
    mi_theap_quiescent_abandon(cleanup_theap);
    mi_theap_quiescent_abandon(cleanup_theap);
    block_visit_t visit = { 0, 0, false, false };
    result = (mi_heap_visit_blocks(cleanup_heap, true, &block_record, &visit) &&
              visit.blocks == CLEANUP_BLOCKS && mi_heap_theap(cleanup_heap) == local &&
              p != NULL && *p == 42 && mi_thread_id_of(p) == local->tld->thread_id && result);
    for (size_t i = 1; i < CLEANUP_BLOCKS; i++) {
      const uint8_t* block = (const uint8_t*)cleanup_blocks[i];
      result = (block != NULL && block[0] == i && block[4095] == i &&
                mi_thread_id_of(block) == 0 && result);
    }
    mi_atomic_store_release(&cleanup_state, 2);
    #ifdef _WIN32
    WaitForSingleObject(thread, INFINITE);
    CloseHandle(thread);
    #else
    pthread_join(thread, NULL);
    #endif
    result = (args.result && cleanup_heap->theaps == local && local->hnext == NULL && result);
    for (size_t i = 0; i < CLEANUP_BLOCKS; i++) { mi_free(cleanup_blocks[i]); }
  }
  mi_free(p);
  mi_heap_destroy(cleanup_heap);
  cleanup_heap = NULL;
  cleanup_theap = NULL;
  return result;
}

static bool delete_owner(void) {
  mi_theap_t* const main = mi_theap_get_default();
  mi_theap_t* const theap = mi_heap_theap(cleanup_heap);
  cleanup_blocks[0] = mi_theap_malloc(theap, 64);
  const bool allocated = (cleanup_blocks[0] != NULL);
  mi_theap_set_default(theap);
  (void)mi_heap_theap(mi_heap_main()); // the default is deliberately not protected by the cache
  mi_atomic_store_release(&cleanup_state, 1);
  while (mi_atomic_load_acquire(&cleanup_state) < 2) { _mi_prim_thread_yield(); }
  mi_theap_delete(theap);
  mi_atomic_store_release(&cleanup_state, 3);
  void* p = mi_malloc(32);
  const bool result = (allocated && p != NULL && mi_theap_get_default() == main && mi_heap_of(p) == mi_heap_main());
  mi_free(p);
  return result;
}

static bool test_theap_delete_heap_race(void) {
  bool result = true;
  for (size_t i = 0; result && i < 48; i++) {
    cleanup_heap = mi_heap_new();
    if (cleanup_heap == NULL) return false;
    mi_atomic_store_release(&cleanup_state, 0);
    mi_thread_fun_args_t args = { &delete_owner, false };
    #ifdef _WIN32
    HANDLE thread = CreateThread(NULL, 0, &mi_win_thread_entry, &args, 0, NULL);
    const bool started = (thread != NULL);
    #else
    pthread_t thread;
    const bool started = (pthread_create(&thread, NULL, &mi_pthread_entry, &args) == 0);
    #endif
    if (started) {
      while (mi_atomic_load_acquire(&cleanup_state) < 1) { _mi_prim_thread_yield(); }
      if (i % 3 != 0) { mi_atomic_store_release(&cleanup_state, 2); }
      if (i % 3 == 2) {
        while (mi_atomic_load_acquire(&cleanup_state) < 3) { _mi_prim_thread_yield(); }
      }
      if (i % 2 == 0) { mi_heap_destroy(cleanup_heap); }
                 else { mi_heap_delete(cleanup_heap); }
      if (i % 3 == 0) { mi_atomic_store_release(&cleanup_state, 2); }
      #ifdef _WIN32
      WaitForSingleObject(thread, INFINITE);
      CloseHandle(thread);
      #else
      pthread_join(thread, NULL);
      #endif
      result = args.result;
      if (i % 2 != 0) { mi_free(cleanup_blocks[0]); }
    }
    else {
      mi_heap_destroy(cleanup_heap);
      result = false;
    }
    cleanup_heap = NULL;
  }
  return result;
}

static bool test_theap_cleanup(bool os_pages) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  const long retain = mi_option_get(mi_option_page_full_retain);
  mi_option_set(mi_option_disallow_arena_alloc, (os_pages ? 1 : 0));
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_option_set(mi_option_page_full_retain, -1);
  const bool result = (mi_run_on_thread(&test_theap_delete_owner) &&
                       test_theap_abandon_foreign() && test_theap_delete_heap_race());
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  mi_option_set(mi_option_page_full_retain, retain);
  return result;
}

#if MI_FREE_IS_CHECKED
static bool test_page_capacity_size(bool os_pages) {
  const long disallow = mi_option_get(mi_option_disallow_arena_alloc);
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  mi_option_set(mi_option_disallow_arena_alloc, (os_pages ? 1 : 0));
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_heap_t* heap = mi_heap_new();
  void* blocks[256] = { NULL };
  mi_page_t* first_page = NULL;
  size_t initial_size = 0;
  bool result = (heap != NULL);
  for (size_t i = 0; result && i < 256; i++) {
    blocks[i] = mi_heap_malloc(heap, 64);
    if (blocks[i] == NULL) { result = false; break; }
    mi_page_t* page = mi_ptr_page(blocks[i]);
    const size_t capacity_size = mi_atomic_load_relaxed(&page->capacity_size);
    if (i == 0) {
      first_page = page;
      initial_size = capacity_size;
    }
    result = (capacity_size > 0 &&
              (size_t)(mi_addr(blocks[i]) - mi_addr(mi_page_start(page))) < capacity_size);
  }
  if (result) {
    result = (mi_atomic_load_relaxed(&first_page->capacity_size) > initial_size);
  }
  for (size_t i = 0; i < 256; i++) {
    if (blocks[i] == NULL) continue;
    size_t bsize = 0;
    mi_ufree(blocks[i], &bsize);
    result = (bsize > 0 && result);
  }
  mi_heap_destroy(heap);
  mi_option_set(mi_option_disallow_arena_alloc, disallow);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  return result;
}
#endif

static void mi_cdecl record_free_list_error(int err, void* arg) {
  if (err == EFAULT) { (*(size_t*)arg)++; }
}

static bool record_free_list_block(const mi_heap_t* heap, const mi_heap_area_t* area, void* block, size_t size, void* arg) {
  MI_UNUSED(heap); MI_UNUSED(area); MI_UNUSED(block); MI_UNUSED(size);
  (*(size_t*)arg)++;
  return true;
}

static bool test_free_list_cycle(bool collect, bool self_cycle) {
  const long guarded = mi_option_get(mi_option_guarded_sample_rate);
  mi_option_set(mi_option_guarded_sample_rate, 0);
  mi_heap_t* heap = mi_heap_new();
  void* p = (heap == NULL ? NULL : mi_heap_malloc(heap, 64));
  void* q = (heap == NULL ? NULL : mi_heap_malloc(heap, 64));
  void* live = (heap == NULL ? NULL : mi_heap_malloc(heap, 64));
  bool result = (p != NULL && q != NULL && live != NULL);
  if (result) {
    mi_page_t* page = mi_ptr_page(p);
    result = (page == mi_ptr_page(q) && page == mi_ptr_page(live) && page->free != NULL);
    if (result) {
      mi_free(p);
      mi_free(q);
      if (!collect) { _mi_page_free_collect(page, true); }
      mi_block_t* head = (collect ? page->local_free : page->free);
      mi_block_t* link = (self_cycle ? head : mi_block_next(page, head));
      mi_block_t* saved_next = mi_block_next(page, link);
      mi_block_t* saved_free = page->free;
      mi_block_set_next(page, link, head);
      size_t errors = 0;
      size_t visited = 0;
      mi_heap_area_t area;
      _mi_heap_area_init(&area, page);
      mi_register_error(&record_free_list_error, &errors);
      if (collect) {
        _mi_page_free_collect(page, true);
        result = (page->local_free == head && page->free == saved_free);
      }
      else {
        result = (_mi_theap_area_visit_blocks(&area, page, &record_free_list_block, &visited) &&
                  visited == (size_t)page->capacity - (self_cycle ? 1 : 2));
      }
      mi_block_set_next(page, link, saved_next);
      mi_register_error(NULL, NULL);
      result = (errors == (collect ? 1 : 0) && result);
      _mi_page_free_collect(page, true);
      visited = 0;
      result = (_mi_theap_area_visit_blocks(&area, page, &record_free_list_block, &visited) && visited == 1 && result);
    }
  }
  mi_heap_destroy(heap);
  mi_option_set(mi_option_guarded_sample_rate, guarded);
  return result;
}

#if MI_PAC
// Corrupt the (signed) page map entry of a pointer and check that the lookup fails with EFAULT
static bool test_page_map_tamper(void) {
  void* p = mi_malloc(64);
  if (p == NULL) return false;
  mi_page_t* const page = _mi_safe_ptr_page(p);
  size_t sub_idx;
  const size_t idx = mi_page_map_index(p, &sub_idx);
  mi_page_submap_t* const sub = mi_page_map_at(mi_page_map(), idx);
  _Atomic(mi_ptr_signed_t)* const entry = &sub->page_metas[sub_idx];
  const mi_ptr_signed_t saved = mi_atomic_load_relaxed(entry);
  size_t errors = 0;
  mi_register_error(&record_free_list_error, &errors);
  bool result = (page != NULL && mi_submap_at(sub, sub_idx) == page);
  mi_atomic_store_relaxed(entry, (mi_ptr_signed_t)page);        // a raw pointer
  result = (_mi_safe_ptr_page(p) == NULL && result);
  mi_atomic_store_relaxed(entry, mi_ptr_sign(page, mi_addr(entry + 1)));  // validly signed for the next slot
  result = (_mi_safe_ptr_page(p) == NULL && result);
  mi_atomic_store_relaxed(entry, saved);
  result = (_mi_safe_ptr_page(p) == page && result);
  mi_register_error(NULL, NULL);
  mi_free(p);
  return (result && errors == 2);
}
#endif

static bool test_collect_self_cycle(void)      { return test_free_list_cycle(true, true); }
static bool test_collect_two_block_cycle(void) { return test_free_list_cycle(true, false); }

// In secure mode an `EFAULT` error always aborts (even if the error handler returns),
// so then check that the test aborts in a child process instead.
#if MI_SECURE && !defined(_WIN32)
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
static bool test_efault(bool (*test)(void)) {
  #if !MI_SECURE
  return test();
  #elif defined(_WIN32)
  MI_UNUSED(test);
  return true;  // skip
  #else
  fflush(NULL);
  const pid_t pid = fork();
  if (pid == 0) { test(); _exit(0); }
  int status = 0;
  return (pid > 0 && waitpid(pid, &status, 0) == pid && WIFSIGNALED(status) && WTERMSIG(status) == SIGABRT);
  #endif
}

int main(void) {
  CHECK("os-allow-large", test_os_allow_large());
  #if MI_SECURE > 0 && MI_OS_HAS_GUARD_PAGES
  CHECK("arena-reject-pinned", test_arena_reject_pinned());
  CHECK("os-reject-huge-pages", test_os_reject_huge_pages());
  #endif
  #if MI_STATS
  CHECK("os-aligned-offset-stats", test_os_aligned_offset_stats());
  #endif
  #if MI_PAGE_META_IS_ALIGNED
  CHECK("arena-oversized-alloc", test_arena_oversized_alloc());
  #endif
  #if MI_PAGE_META_IS_SEPARATED && !MI_PAGE_META_IS_ALIGNED
  CHECK("arena-page-meta-permutation", test_arena_page_meta_permutation());
  #endif
  #if MI_PAC
  CHECK("page-map-tamper", test_efault(&test_page_map_tamper));
  #endif
  CHECK("collect-self-cycle", test_efault(&test_collect_self_cycle));
  CHECK("collect-two-block-cycle", test_efault(&test_collect_two_block_cycle));
  CHECK("visit-self-cycle", test_free_list_cycle(false, true));
  CHECK("visit-two-block-cycle", test_free_list_cycle(false, false));
  #if MI_FREE_IS_CHECKED
  CHECK("page-capacity-size-arena", test_page_capacity_size(false));
  CHECK("page-capacity-size-os", test_page_capacity_size(true));
  #endif
  CHECK_THREADS("theap-cleanup-arena", test_theap_cleanup(false));
  CHECK_THREADS("theap-cleanup-os", test_theap_cleanup(true));
  CHECK("theap-collect-detached", test_theap_collect_detached());
  CHECK_THREADS("theap-collect-detached-thread", mi_run_on_thread(&test_theap_collect_detached));
  CHECK_THREADS("thread-id-of-arena", test_thread_id_of(false, 1));
  CHECK_THREADS("thread-id-of-os", test_thread_id_of(true, 1));
  CHECK_THREADS("reclaim-on-free-snapshot-disabled", test_thread_id_of(false, -1));
  CHECK_THREADS("reclaim-on-free-snapshot-origin-only", test_thread_id_of(false, 0));
  CHECK("arena-order", test_arena_order());
  CHECK("arena-filter", test_arena_filter());
  CHECK("arena-stop", test_arena_stop());
  CHECK("arena-snapshot", test_arena_snapshot());
  CHECK("arena-result", test_arena_result());
  CHECK_THREADS("heap-visit-stop", test_heap_visit_stop());
  CHECK_THREADS("heap-visit-owned-os", test_heap_visit_owned_os(false));
  CHECK_THREADS("heap-visit-owned-os-mixed", test_heap_visit_owned_os(true));
  CHECK("heap-page-count-os", test_heap_page_count_os());
  CHECK_THREADS("heap-visit-thread-exit", test_heap_visit_thread_exit());
  return print_test_summary();
}