-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathiso_alloc.c
More file actions
2192 lines (1792 loc) · 69.8 KB
/
iso_alloc.c
File metadata and controls
2192 lines (1792 loc) · 69.8 KB
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
/* iso_alloc.c - A secure memory allocator
* Copyright 2023 - chris.rohlf@gmail.com */
#include "iso_alloc_internal.h"
#include "iso_alloc_sanity.h"
#if HEAP_PROFILER
#include "iso_alloc_profiler.h"
#endif
#if THREAD_SUPPORT
#if USE_SPINLOCK
atomic_flag root_busy_flag;
#else
pthread_mutex_t root_busy_mutex;
#endif
/* We cannot initialize this on thread creation so
* we can't mmap them somewhere with guard pages but
* they are thread local storage so their location
* won't be as predictable as .bss
* If a thread dies with the zone cache populated there
* is no undefined behavior */
static __thread _tzc zone_cache[ZONE_CACHE_SZ];
static __thread size_t zone_cache_count;
#else
/* When not using thread local storage we can mmap
* these pages somewhere safer than global memory
* and surrounded by guard pages */
static _tzc *zone_cache;
static size_t zone_cache_count;
#endif
uint32_t g_page_size;
uint32_t g_page_size_shift;
iso_alloc_root *_root;
INTERNAL_HIDDEN iso_alloc_root *iso_alloc_new_root(void) {
iso_alloc_root *p = NULL;
p = (void *) mmap_guarded_rw_pages(sizeof(iso_alloc_root), true, ROOT_NAME);
if(p == NULL) {
LOG_AND_ABORT("Cannot allocate pages for root");
}
#if __APPLE__
while(madvise((void *) p, ROUND_UP_PAGE(sizeof(iso_alloc_root)), MADV_FREE_REUSE) && errno == EAGAIN) {
}
#endif
return p;
}
INTERNAL_HIDDEN void iso_alloc_initialize_global_root(void) {
/* Do not allow a reinitialization unless root is NULL */
if(_root != NULL) {
return;
}
_root = iso_alloc_new_root();
if(_root == NULL) {
LOG_AND_ABORT("Could not initialize global root");
}
/* We mlock the root or every allocation would
* result in a soft page fault */
MLOCK(&_root, sizeof(iso_alloc_root));
#if ARM_MTE
if(iso_is_mte_supported() == false) {
_root->arm_mte_enabled = false;
} else {
_root->arm_mte_enabled = true;
prctl(PR_SET_TAGGED_ADDR_CTRL,
PR_TAGGED_ADDR_ENABLE | PR_MTE_TCF_SYNC | (0xfffe << PR_MTE_TAG_SHIFT),
0, 0, 0);
}
#endif
_root->zone_retirement_shf = _log2(ZONE_ALLOC_RETIRE);
_root->zones_size = (MAX_ZONES * sizeof(iso_alloc_zone_t));
_root->zones_size += (g_page_size * 2);
_root->zones_size = ROUND_UP_PAGE(_root->zones_size);
/* Allocate memory with guard pages to hold zone data */
_root->zones = mmap_guarded_rw_pages(_root->zones_size, false, "isoalloc zone metadata");
#if __APPLE__
darwin_reuse(_root->zones, g_page_size);
#endif
MLOCK(_root->zones, _root->zones_size);
size_t c = ROUND_UP_PAGE(CHUNK_QUARANTINE_SZ * sizeof(uintptr_t));
_root->chunk_quarantine = mmap_guarded_rw_pages(c, true, NULL);
#if __APPLE__
darwin_reuse(_root->chunk_quarantine, c);
#endif
MLOCK(_root->chunk_quarantine, c);
#if !THREAD_SUPPORT
size_t z = ROUND_UP_PAGE(ZONE_CACHE_SZ * sizeof(_tzc));
zone_cache = mmap_guarded_rw_pages(z, true, NULL);
#if __APPLE__
darwin_reuse(zone_cache, z);
#endif
MLOCK(zone_cache, z);
#endif
_root->chunk_lookup_table = mmap_guarded_rw_pages(CHUNK_TO_ZONE_TABLE_SZ, true, NULL);
#if __APPLE__
darwin_reuse(_root->chunk_lookup_table, CHUNK_TO_ZONE_TABLE_SZ);
#endif
MLOCK(_root->chunk_lookup_table, CHUNK_TO_ZONE_TABLE_SZ);
for(int i = 0; i < DEFAULT_ZONE_COUNT; i++) {
if((_iso_new_zone(default_zones[i], true, -1)) == NULL) {
LOG_AND_ABORT("Failed to create a new zone");
}
}
char *name = NULL;
#if NAMED_MAPPINGS && (__ANDROID__ || KERNEL_VERSION_SEQ_5_17)
name = PREALLOC_BITMAPS;
#endif
const int sbsi = (sizeof(small_bitmap_sizes) / sizeof(int)) - 1 - 1;
for(int i = 0; i < sbsi; i++) {
_root->bitmaps[i].bitmap = mmap_rw_pages(g_page_size, false, name);
_root->bitmaps[i].bucket = small_bitmap_sizes[i];
}
_root->seed = rand_uint64();
/* Handle masks may be leaked via iso_alloc_new_zone */
_root->zone_handle_mask = rand_uint64();
_root->big_zone_next_mask = us_rand_uint64(&_root->seed);
_root->big_zone_canary_secret = us_rand_uint64(&_root->seed);
}
INTERNAL_HIDDEN void _iso_alloc_initialize(void) {
if(_root != NULL) {
return;
}
g_page_size = sysconf(_SC_PAGESIZE);
g_page_size_shift = _log2(g_page_size);
iso_alloc_initialize_global_root();
#if THREAD_SUPPORT && !USE_SPINLOCK
pthread_mutex_init(&root_busy_mutex, NULL);
pthread_mutex_init(&_root->big_zone_free_mutex, NULL);
pthread_mutex_init(&_root->big_zone_used_mutex, NULL);
#if ALLOC_SANITY
pthread_mutex_init(&sane_cache_mutex, NULL);
#endif
#endif
#if HEAP_PROFILER
_initialize_profiler();
#endif
#if NO_ZERO_ALLOCATIONS
_root->zero_alloc_page = mmap_pages(g_page_size, false, NULL, PROT_NONE);
#endif
#if UAF_PTR_PAGE
_root->uaf_ptr_page = mmap_pages(g_page_size, false, NULL, PROT_NONE);
#endif
#if ALLOC_SANITY && UNINIT_READ_SANITY
_iso_alloc_setup_userfaultfd();
#endif
#if ALLOC_SANITY
_sanity_canary = us_rand_uint64(&_root->seed);
#endif
#if SIGNAL_HANDLER
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sa.sa_sigaction = &handle_signal;
if(sigaction(SIGSEGV, &sa, NULL) == ERR) {
LOG("Could not register signal handler");
}
#endif
}
#if AUTO_CTOR_DTOR
__attribute__((destructor(LAST_DTOR))) void iso_alloc_dtor(void) {
_iso_alloc_destroy();
}
__attribute__((constructor(FIRST_CTOR))) void iso_alloc_ctor(void) {
_iso_alloc_initialize();
}
#endif
INTERNAL_HIDDEN void _iso_alloc_destroy_zone(iso_alloc_zone_t *zone) {
LOCK_ROOT();
_iso_alloc_destroy_zone_unlocked(zone, true, true);
UNLOCK_ROOT();
}
INTERNAL_HIDDEN void _iso_alloc_destroy_zone_unlocked(iso_alloc_zone_t *zone, bool flush_caches, bool replace) {
if(flush_caches == true) {
/* We don't need a lock to clear the zone cache
* but we do it here because we don't want another
* thread to stick the zone we are about to delete
* into the cache for later */
clear_zone_cache();
flush_chunk_quarantine();
}
UNMASK_ZONE_PTRS(zone);
UNPOISON_ZONE(zone);
#if MEMORY_TAGGING
/* If the zone is tagged then unmap the page holding the tags */
if(zone->tagged == true) {
size_t s = ROUND_UP_PAGE(zone->chunk_count * MEM_TAG_SIZE);
void *_mtp = (zone->user_pages_start - s - g_page_size);
munmap(_mtp, g_page_size + s);
zone->tagged = false;
}
#endif
_root->chunk_lookup_table[ADDR_TO_CHUNK_TABLE(zone->user_pages_start)] = 0;
if(zone->preallocated_bitmap_idx == -1) {
munmap(zone->bitmap_start - g_page_size, (zone->bitmap_size + g_page_size * 2));
} else {
const int sbsi = (sizeof(small_bitmap_sizes) / sizeof(int)) - 1;
for(int i = 0; i < sbsi; i++) {
if(zone->bitmap_size == _root->bitmaps[i].bucket) {
UNSET_BIT(_root->bitmaps[i].in_use, zone->preallocated_bitmap_idx);
__iso_memset(zone->bitmap_start, 0x0, zone->bitmap_size);
break;
}
}
}
munmap(zone->user_pages_start - g_page_size, (ZONE_USER_SIZE + g_page_size * 2));
if(replace == true) {
_iso_new_zone(zone->chunk_size, true, zone->index);
}
}
INTERNAL_HIDDEN iso_alloc_zone_t *iso_new_zone(size_t size, bool internal) {
if(size > SMALL_SIZE_MAX) {
return NULL;
}
LOCK_ROOT();
iso_alloc_zone_t *zone = _iso_new_zone(size, internal, -1);
UNLOCK_ROOT();
return zone;
}
INTERNAL_HIDDEN INLINE void clear_zone_cache(void) {
#if THREAD_SUPPORT
__iso_memset(zone_cache, 0x0, sizeof(zone_cache));
#else
__iso_memset(zone_cache, 0x0, ZONE_CACHE_SZ * sizeof(_tzc));
#endif
zone_cache_count = 0;
}
/* Select a random number of chunks to be canaries. These
* can be verified anytime by calling check_canary()
* or check_canary_no_abort() */
INTERNAL_HIDDEN void create_canary_chunks(iso_alloc_zone_t *zone) {
#if ENABLE_ASAN || DISABLE_CANARY
return;
#else
/* Canary chunks are only for default zone sizes. This
* is because larger zones would waste a lot of memory
* if we set aside some of their chunks as canaries */
if(zone->chunk_size > MAX_DEFAULT_ZONE_SZ) {
return;
}
bitmap_index_t *bm = (bitmap_index_t *) zone->bitmap_start;
bit_slot_t bit_slot;
const bitmap_index_t max_bitmap_idx = (zone->max_bitmap_idx - 1);
/* Roughly %1 of the chunks in this zone will become a canary */
const uint64_t canary_count = (zone->chunk_count >> CANARY_COUNT_DIV);
/* This function is only ever called during zone
* initialization so we don't need to check the
* current state of any chunks, they're all free.
* It's possible the call to us_rand_uint64() here
* will return the same index twice. We can live
* with that collision as canary chunks only provide
* a small probabilistic security guarantee */
for(uint64_t i = 0; i < canary_count; i++) {
bitmap_index_t bm_idx = ALIGN_SZ_DOWN((us_rand_uint64(&_root->seed) % (max_bitmap_idx)));
if(0 > bm_idx) {
bm_idx = 0;
}
/* We may have already chosen this index */
if(GET_BIT(bm[bm_idx], 0)) {
continue;
}
/* Set the 1st and 2nd bits as 1 */
SET_BIT(bm[bm_idx], 0);
SET_BIT(bm[bm_idx], 1);
bit_slot = (bm_idx << BITS_PER_QWORD_SHIFT);
void *p = POINTER_FROM_BITSLOT(zone, bit_slot);
write_canary(zone, p);
}
#endif
}
/* Requires the root is locked */
INTERNAL_HIDDEN iso_alloc_zone_t *_iso_new_zone(size_t size, bool internal, int32_t index) {
if(UNLIKELY(_root->zones_used >= MAX_ZONES) || UNLIKELY(index >= MAX_ZONES)) {
LOG_AND_ABORT("Cannot allocate additional zones. I have already allocated %d zones", _root->zones_used);
}
if(size > SMALL_SIZE_MAX) {
LOG("Request for new zone with %ld byte chunks should be handled by big alloc path", size);
return NULL;
}
/* This is a good time to refresh the root rng seed
* because we will soon create memory tags, canary
* chunks, and other uses of us_rand_uint64 */
_root->seed = rand_uint64();
/* Minimum chunk size */
if(size < SMALLEST_CHUNK_SZ) {
size = SMALLEST_CHUNK_SZ;
} else if((size % SZ_ALIGNMENT) != 0) {
size = ALIGN_SZ_UP(size);
}
iso_alloc_zone_t *new_zone = NULL;
/* We created a new zone, we did not replace a retired one */
if(index >= 0) {
new_zone = &_root->zones[index];
} else {
new_zone = &_root->zones[_root->zones_used];
}
uint16_t next_sz_index = new_zone->next_sz_index;
__iso_memset(new_zone, 0x0, sizeof(iso_alloc_zone_t));
/* Restore next_sz_index */
new_zone->next_sz_index = next_sz_index;
new_zone->internal = internal;
new_zone->is_full = false;
new_zone->chunk_size = size;
new_zone->chunk_count = (ZONE_USER_SIZE / new_zone->chunk_size);
/* If a caller requests an allocation that is >=(ZONE_USER_SIZE/2)
* then we need to allocate a minimum size bitmap */
uint32_t bitmap_size = (new_zone->chunk_count * BITS_PER_CHUNK) / BITS_PER_BYTE;
new_zone->bitmap_size = (bitmap_size > sizeof(bitmap_index_t)) ? bitmap_size : sizeof(bitmap_index_t);
new_zone->max_bitmap_idx = (new_zone->bitmap_size >> 3);
if(g_page_size >= new_zone->bitmap_size) {
const int sbsi = (sizeof(small_bitmap_sizes) / sizeof(int)) - 1;
for(int i = 0; i < sbsi; i++) {
if(_root->bitmaps[i].bucket == new_zone->bitmap_size) {
/* Easy path is the bitmap is unused */
if(_root->bitmaps[i].in_use == 0) {
new_zone->bitmap_start = _root->bitmaps[i].bitmap;
new_zone->preallocated_bitmap_idx = 0;
SET_BIT(_root->bitmaps[i].in_use, 0);
break;
}
int bits_available = g_page_size / new_zone->bitmap_size;
for(int z = 0; z < bits_available; z++) {
if((GET_BIT(_root->bitmaps[i].in_use, z)) == 0) {
new_zone->bitmap_start = _root->bitmaps[i].bitmap + (new_zone->bitmap_size * z);
new_zone->preallocated_bitmap_idx = z;
SET_BIT(_root->bitmaps[i].in_use, z);
break;
}
}
}
if(new_zone->bitmap_start != NULL) {
break;
}
}
if(new_zone->bitmap_start == NULL) {
new_zone->bitmap_start = mmap_guarded_rw_pages(new_zone->bitmap_size, true, ZONE_BITMAP_NAME);
new_zone->preallocated_bitmap_idx = -1;
}
} else {
new_zone->bitmap_start = mmap_guarded_rw_pages(new_zone->bitmap_size, true, ZONE_BITMAP_NAME);
new_zone->preallocated_bitmap_idx = -1;
}
char *name = NULL;
#if NAMED_MAPPINGS && (__ANDROID__ || KERNEL_VERSION_SEQ_5_17)
if(internal == true) {
name = INTERNAL_UZ_NAME;
} else {
name = PRIVATE_UZ_NAME;
}
#endif
size_t total_size = ZONE_USER_SIZE + (g_page_size << 1);
#if MEMORY_TAGGING
/* Each tag is 1 byte in size and the start address
* of each valid chunk is assigned a tag */
size_t tag_mapping_size = ROUND_UP_PAGE((new_zone->chunk_count * MEM_TAG_SIZE));
if(internal == false) {
total_size += (tag_mapping_size + g_page_size);
new_zone->tagged = true;
} else {
tag_mapping_size = 0;
}
#endif
void *p = NULL;
#if ARM_MTE
if(_root->arm_mte_enabled == true) {
p = mmap_rw_mte_pages(total_size, false, name);
} else {
p = mmap_rw_pages(total_size, false, name);
}
#else
p = mmap_rw_pages(total_size, false, name);
#endif
#if(__ANDROID__ || KERNEL_VERSION_SEQ_5_17) && NAMED_MAPPINGS && MEMORY_TAGGING
if(new_zone->tagged == false) {
name = MEM_TAG_NAME;
}
#endif
void *user_pages_guard_below = p;
create_guard_page(user_pages_guard_below);
#if MEMORY_TAGGING
if(new_zone->tagged == true) {
create_guard_page(p + g_page_size + tag_mapping_size);
new_zone->user_pages_start = (p + g_page_size + tag_mapping_size + g_page_size);
uint64_t *_mtp = p + g_page_size;
/* (>> 3) == sizeof(uint64_t) == 8 */
uint64_t tms = tag_mapping_size >> 3;
/* Generate random tags */
for(uint64_t o = 0; o < tms; o++) {
_mtp[o] = us_rand_uint64(&_root->seed);
}
} else {
new_zone->user_pages_start = (p + g_page_size);
}
#else
new_zone->user_pages_start = (p + g_page_size);
#endif
void *user_pages_guard_above;
#if MEMORY_TAGGING
if(new_zone->tagged == false) {
user_pages_guard_above = (void *) ROUND_UP_PAGE((uintptr_t) p + (ZONE_USER_SIZE + g_page_size));
} else {
user_pages_guard_above = (void *) ROUND_UP_PAGE((uintptr_t) p + tag_mapping_size + (ZONE_USER_SIZE + g_page_size * 2));
}
#else
user_pages_guard_above = (void *) ROUND_UP_PAGE((uintptr_t) p + (ZONE_USER_SIZE + g_page_size));
#endif
create_guard_page(user_pages_guard_above);
/* We created a new zone, we did not replace a retired one */
if(index > 0) {
new_zone->index = index;
} else {
new_zone->index = _root->zones_used;
}
new_zone->canary_secret = us_rand_uint64(&_root->seed);
new_zone->pointer_mask = us_rand_uint64(&_root->seed);
create_canary_chunks(new_zone);
/* When we create a new zone its an opportunity to
* populate our free list cache with random entries */
fill_free_bit_slots(new_zone);
/* Prime the next_free_bit_slot member */
get_next_free_bit_slot(new_zone);
#if CPU_PIN
new_zone->cpu_core = _iso_getcpu();
#endif
POISON_ZONE(new_zone);
_root->chunk_lookup_table[ADDR_TO_CHUNK_TABLE(new_zone->user_pages_start)] = new_zone->index;
/* The lookup table is never used for private zones */
if(LIKELY(internal == true)) {
/* If no other zones of this size exist then set the
* index in the zone lookup table to its index */
if(_root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)] == 0) {
_root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)] = new_zone->index;
new_zone->next_sz_index = 0;
} else if(index < 0) {
/* If the index is < 0 then this is a brand new zone and
* not a replacement which means we need to add it to the
* zone_lookup_table. We prepend it to the start of the
* list ensuring it is checked first on alloc path */
int32_t current_idx = _root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)];
_root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)] = new_zone->index;
new_zone->next_sz_index = current_idx;
}
}
MASK_ZONE_PTRS(new_zone);
/* We created a new zone, we did not replace a retired one */
if(index < 0) {
_root->zones_used++;
}
return new_zone;
}
/* Pick a random index in the bitmap and start looking
* for free bit slots we can add to the cache. The random
* bitmap index is to protect against biasing the free
* slot cache with only chunks towards the start of the
* user mapping. Theres no guarantee this function will
* find any free slots. */
INTERNAL_HIDDEN void fill_free_bit_slots(iso_alloc_zone_t *zone) {
const bitmap_index_t *bm = (bitmap_index_t *) zone->bitmap_start;
/* This gives us an arbitrary spot in the bitmap to
* start searching but may mean we end up with a smaller
* cache. This may negatively affect performance but
* leads to a less predictable free list */
bitmap_index_t bm_idx = 0;
/* Refresh the random seed for wyrand. This only
* requires a single syscall to getrandom() */
_root->seed = rand_uint64();
/* The largest zone->max_bitmap_idx we will ever
* have is 8192 for SMALLEST_CHUNK_SZ. The
* smallest zone->max_bitmap_idx is 1 when chunk
* size is SMALL_SIZE_MAX because the bitmap_size
* is only 8 bytes. If our max bitmap index is
* small then it won't provide enough search
* space for a random list to be of value */
if(zone->max_bitmap_idx > MIN_BITMAP_IDX) {
bm_idx = ((uint32_t) us_rand_uint64(&_root->seed) & (zone->max_bitmap_idx - 1));
}
bit_slot_t *free_bit_slots = zone->free_bit_slots;
__iso_memset(free_bit_slots, BAD_BIT_SLOT, ZONE_FREE_LIST_SZ);
zone->free_bit_slots_usable = 0;
free_bit_slot_t free_bit_slots_index;
for(free_bit_slots_index = 0; free_bit_slots_index < ZONE_FREE_LIST_SZ; bm_idx++) {
/* Don't index outside of the bitmap or
* we will return inaccurate bit slots */
if(UNLIKELY(bm_idx >= zone->max_bitmap_idx)) {
break;
}
const bit_slot_t bts = bm[bm_idx];
const bitmap_index_t bm_idx_shf = bm_idx << BITS_PER_QWORD_SHIFT;
/* If the byte is 0 then its faster to add each
* bitslot without checking each bit value */
if(bts == 0x0) {
for(uint64_t z = 0; z < BITS_PER_QWORD; z += BITS_PER_CHUNK) {
free_bit_slots[free_bit_slots_index] = (bm_idx_shf + z);
free_bit_slots_index++;
if(UNLIKELY(free_bit_slots_index >= ZONE_FREE_LIST_SZ)) {
break;
}
}
} else {
/* Use ctzll to skip directly to each free slot instead
* of iterating all 32 even-bit positions */
uint64_t free_mask = ~(uint64_t) bts & USED_BIT_VECTOR;
while(free_mask) {
free_bit_slots[free_bit_slots_index] = (bm_idx_shf + __builtin_ctzll(free_mask));
free_bit_slots_index++;
if(UNLIKELY(free_bit_slots_index >= ZONE_FREE_LIST_SZ)) {
break;
}
free_mask &= free_mask - 1; /* clear lowest set bit */
}
}
}
#if RANDOMIZE_FREELIST
static_assert(MIN_RAND_FREELIST >= 2, "MIN_RAND_FREELIST should be at least 2");
/* Randomize the list of free bitslots */
if(free_bit_slots_index > MIN_RAND_FREELIST) {
for(free_bit_slot_t i = free_bit_slots_index - 1; i > 0; i--) {
free_bit_slot_t j = ((free_bit_slot_t) us_rand_uint64(&_root->seed) * i) >> FREE_LIST_SHF;
bit_slot_t t = free_bit_slots[j];
free_bit_slots[j] = free_bit_slots[i];
free_bit_slots[i] = t;
}
}
#endif
zone->free_bit_slots_index = free_bit_slots_index;
}
INTERNAL_HIDDEN INLINE void insert_free_bit_slot(iso_alloc_zone_t *zone, int64_t bit_slot) {
#if VERIFY_FREE_BIT_SLOTS
/* The cache is sorted at creation time but once we start
* free'ing chunks we add bit_slots to it in an unpredictable
* order. So we can't search the cache with something like
* a binary search. This brute force search shouldn't incur
* too much of a performance penalty as we only search starting
* at the free_bit_slots_usable index which is updated
* everytime we call get_next_free_bit_slot(). We do this in
* order to detect any corruption of the cache that attempts
* to add duplicate bit_slots which would result in iso_alloc()
* handing out in-use chunks. The _iso_alloc() path also does
* a check on the bitmap itself before handing out any chunks */
const free_bit_slot_t max_cache_slots = (ZONE_FREE_LIST_SZ >> 3);
for(free_bit_slot_t i = zone->free_bit_slots_usable; i < max_cache_slots; i++) {
if(zone->free_bit_slots[i] == bit_slot) {
LOG_AND_ABORT("Zone[%d] already contains bit slot %lu in cache", zone->index, bit_slot);
}
}
#endif
if(zone->free_bit_slots_index >= ZONE_FREE_LIST_SZ) {
return;
}
zone->free_bit_slots[zone->free_bit_slots_index] = bit_slot;
zone->free_bit_slots_index++;
zone->is_full = false;
}
INTERNAL_HIDDEN bit_slot_t get_next_free_bit_slot(iso_alloc_zone_t *zone) {
if(zone->free_bit_slots_usable >= ZONE_FREE_LIST_SZ ||
zone->free_bit_slots_usable > zone->free_bit_slots_index) {
return BAD_BIT_SLOT;
}
zone->next_free_bit_slot = zone->free_bit_slots[zone->free_bit_slots_usable];
zone->free_bit_slots[zone->free_bit_slots_usable++] = BAD_BIT_SLOT;
return zone->next_free_bit_slot;
}
/* Iterate through a zone bitmap a qword at
* a time looking for empty slots */
INTERNAL_HIDDEN bit_slot_t iso_scan_zone_free_slot(iso_alloc_zone_t *zone) {
#if USE_NEON
const bitmap_index_t *bm = (bitmap_index_t *) zone->bitmap_start;
const bitmap_index_t max = (zone->max_bitmap_idx & ~(2 - 1));
for(int i = 0; i < max; i += 2) {
int64x2_t im = vld1q_s64(&bm[i]);
if(vgetq_lane_s64(im, 0) == 0x0) {
return (i << BITS_PER_QWORD_SHIFT);
}
if(vgetq_lane_s64(im, 1) == 0x0) {
return ((i + 1) << BITS_PER_QWORD_SHIFT);
}
}
#elif __SIZEOF_INT128__
const __int128 *bm = (__int128 *) zone->bitmap_start;
const size_t max = (zone->max_bitmap_idx >> 1);
for(size_t i = 0; i < max; i++) {
if(bm[i] == 0x0) {
return (i << BITS_PER_ODWORD_SHIFT);
}
}
#else
const bitmap_index_t *bm = (bitmap_index_t *) zone->bitmap_start;
const bitmap_index_t max = zone->max_bitmap_idx;
/* Iterate the entire bitmap a qword at a time */
for(bitmap_index_t i = 0; i < max; i++) {
if(bm[i] == 0x0) {
return (i << BITS_PER_QWORD_SHIFT);
}
}
#endif
return BAD_BIT_SLOT;
}
/* This function scans an entire bitmap bit-by-bit
* and returns the first free bit position. In a heavily
* used zone this function may be slow to search. */
INTERNAL_HIDDEN bit_slot_t iso_scan_zone_free_slot_slow(iso_alloc_zone_t *zone) {
size_t max = 0;
bitmap_index_t *bm;
#if USE_NEON
bm = (bitmap_index_t *) zone->bitmap_start;
max = (zone->max_bitmap_idx & ~(2 - 1));
for(bitmap_index_t i = 0; i < max; i += 2) {
int64x2_t im = vld1q_s64(&bm[i]);
/* Use ctzll to find the first free slot in O(1) instead of
* scanning bit-by-bit. USED_BIT_VECTOR selects even-position
* bits (one per chunk); inverting gives 1s where chunks are
* free (use bitwise ops on multiple values) */
uint64_t free_mask0 = ~(uint64_t) vgetq_lane_s64(im, 0) & USED_BIT_VECTOR;
if(free_mask0) {
return ((i << BITS_PER_QWORD_SHIFT) + __builtin_ctzll(free_mask0));
}
uint64_t free_mask1 = ~(uint64_t) vgetq_lane_s64(im, 1) & USED_BIT_VECTOR;
if(free_mask1) {
return (((i + 1) << BITS_PER_QWORD_SHIFT) + __builtin_ctzll(free_mask1));
}
}
if(max == zone->max_bitmap_idx) {
return BAD_BIT_SLOT;
}
#elif __SIZEOF_INT128__
const __int128 *ebm = (__int128 *) zone->bitmap_start;
max = (zone->max_bitmap_idx >> 1);
for(size_t i = 0; i < max; i++) {
unsigned __int128 bts = (unsigned __int128) ebm[i];
/* Split 128-bit word into two 64-bit halves and use ctzll */
uint64_t free_lo = ~(uint64_t) bts & USED_BIT_VECTOR;
if(free_lo) {
return ((i << BITS_PER_ODWORD_SHIFT) + __builtin_ctzll(free_lo));
}
uint64_t free_hi = ~(uint64_t) (bts >> 64) & USED_BIT_VECTOR;
if(free_hi) {
return ((i << BITS_PER_ODWORD_SHIFT) + 64 + __builtin_ctzll(free_hi));
}
}
#endif
bm = (bitmap_index_t *) zone->bitmap_start;
for(bitmap_index_t i = max; i < zone->max_bitmap_idx; i++) {
uint64_t free_mask = ~(uint64_t) bm[i] & USED_BIT_VECTOR;
if(free_mask) {
return ((i << BITS_PER_QWORD_SHIFT) + __builtin_ctzll(free_mask));
}
}
return BAD_BIT_SLOT;
}
INTERNAL_HIDDEN iso_alloc_zone_t *is_zone_usable(iso_alloc_zone_t *zone, size_t size) {
#if CPU_PIN
if(zone->cpu_core != _iso_getcpu()) {
return false;
}
#endif
/* If the zone is full it is not usable */
if(zone->is_full == true) {
return NULL;
}
#if STRONG_SIZE_ISOLATION
if(UNLIKELY(zone->internal == false && size != zone->chunk_size)) {
return NULL;
}
#endif
/* This zone may fit this chunk but if the zone was
* created for chunks more than (N * larger) than the
* requested allocation size then we would be wasting
* a lot of memory by using it. We only do this for
* sizes larger than 1024 bytes. In other words we can
* live with some wasted space in zones that manage
* chunks smaller than ZONE_1024 */
if(size > ZONE_1024 && zone->chunk_size >= (size << WASTED_SZ_MULTIPLIER_SHIFT)) {
return NULL;
}
if(size <= ZONE_1024 && zone->chunk_size > ZONE_1024) {
return NULL;
}
if(zone->next_free_bit_slot != BAD_BIT_SLOT) {
return zone;
}
UNMASK_ZONE_PTRS(zone);
/* If the cache for this zone is empty we should
* refill it to make future allocations faster
* for all threads */
if(zone->free_bit_slots_usable >= zone->free_bit_slots_index) {
fill_free_bit_slots(zone);
}
bit_slot_t bit_slot = get_next_free_bit_slot(zone);
if(LIKELY(bit_slot != BAD_BIT_SLOT)) {
MASK_ZONE_PTRS(zone);
return zone;
}
/* Free list failed, use a fast search */
bit_slot = iso_scan_zone_free_slot(zone);
if(UNLIKELY(bit_slot == BAD_BIT_SLOT)) {
/* Fast search failed, search bit by bit */
bit_slot = iso_scan_zone_free_slot_slow(zone);
MASK_ZONE_PTRS(zone);
/* This zone may be entirely full, try the next one
* but mark this zone full so future allocations can
* take a faster path */
if(bit_slot == BAD_BIT_SLOT) {
zone->is_full = true;
return NULL;
} else {
zone->next_free_bit_slot = bit_slot;
return zone;
}
} else {
zone->next_free_bit_slot = bit_slot;
MASK_ZONE_PTRS(zone);
return zone;
}
}
/* Finds a zone that can fit this allocation request */
INTERNAL_HIDDEN iso_alloc_zone_t *find_suitable_zone(size_t size) {
iso_alloc_zone_t *zone = NULL;
int32_t i = 0;
size_t orig_size = size;
const size_t zones_used = _root->zones_used;
#if !STRONG_SIZE_ISOLATION
/* If we are dealing with small zones then
* find the first zone in the lookup table that
* could possibly allocate this chunk. We only
* do this for sizes up to 1024 because we don't
* want 1) to waste memory and 2) weaken our
* isolation primitives */
while(size <= ZONE_1024) {
if(_root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)] == 0) {
size += ALIGN_SZ_UP(size + 1);
} else {
break;
}
}
#endif
/* Fast path via lookup table */
if(_root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)] != 0) {
i = _root->zone_lookup_table[SZ_TO_ZONE_LOOKUP_IDX(size)];
for(; i < zones_used;) {
iso_alloc_zone_t *zone = &_root->zones[i];
if(zone->chunk_size != size) {
LOG_AND_ABORT("Zone lookup table failed to match sizes for zone[%d](%d) for chunk size (%d)", zone->index, zone->chunk_size, size);
}
if(zone->internal == false) {
LOG_AND_ABORT("Lookup table should never contain private zones");
}
if(is_zone_usable(zone, size) != NULL) {
return zone;
}
if(zone->next_sz_index != 0) {
i = zone->next_sz_index;
} else {
/* We have reached the end of our linked zones. The
* lookup table failed to find us a usable zone.
* Instead of creating a new one we will break out
* of this loop and try iterating through all zones,
* including ones we may have skipped over, to find
* a suitable candidate. */
break;
}
}
}
#if SMALL_MEM_STARTUP
/* A simple optimization to find which default zone
* should fit this allocation. If we fail then a
* slower iterative approach is used. The longer a
* program runs the more likely we will fail this
* fast path as default zones may fill up */
if(orig_size >= ZONE_512 && orig_size <= MAX_DEFAULT_ZONE_SZ) {
i = DEFAULT_ZONE_COUNT >> 1;
} else if(orig_size > MAX_DEFAULT_ZONE_SZ) {
i = DEFAULT_ZONE_COUNT;
}
#else
i = 0;
#endif
for(; i < zones_used; i++) {
zone = &_root->zones[i];
if(zone->chunk_size < orig_size || zone->internal == false) {
continue;
}
if(is_zone_usable(zone, orig_size) != NULL) {
return zone;
}
}
return NULL;
}
INTERNAL_HIDDEN ASSUME_ALIGNED void *_iso_alloc_bitslot_from_zone(bit_slot_t bitslot, iso_alloc_zone_t *zone) {
const bitmap_index_t dwords_to_bit_slot = (bitslot >> BITS_PER_QWORD_SHIFT);
const int64_t which_bit = WHICH_BIT(bitslot);
void *p = POINTER_FROM_BITSLOT(zone, bitslot);
UNPOISON_ZONE_CHUNK(zone, p);
bitmap_index_t *bm = (bitmap_index_t *) zone->bitmap_start;
/* Read out 64 bits from the bitmap. We will write
* them back before we return. This reduces the
* number of times we have to hit the bitmap page
* which could result in a page fault */
bitmap_index_t b = bm[dwords_to_bit_slot];
if(UNLIKELY(p >= zone->user_pages_start + ZONE_USER_SIZE)) {
LOG_AND_ABORT("Allocating an address 0x%p from zone[%d], bit slot %lu %ld bytes %ld pages outside zones user pages 0x%p 0x%p",
p, zone->index, bitslot, p - zone->user_pages_start + ZONE_USER_SIZE, (p - zone->user_pages_start + ZONE_USER_SIZE) / g_page_size,
zone->user_pages_start, zone->user_pages_start + ZONE_USER_SIZE);
}
if(UNLIKELY((GET_BIT(b, which_bit)) != 0)) {
LOG_AND_ABORT("Zone[%d] for chunk size %d cannot return allocated chunk at 0x%p bitmap location @ 0x%p. bit slot was %lu, bit number was %lu",
zone->index, zone->chunk_size, p, &bm[dwords_to_bit_slot], bitslot, which_bit);
}
/* This chunk was either previously allocated and free'd
* or it's a canary chunk. In either case this means it
* has a canary written in its first qword. Here we check
* that canary and abort if its been corrupted */
#if !ENABLE_ASAN && !DISABLE_CANARY
if((GET_BIT(b, (which_bit + 1))) == 1) {
check_canary(zone, p);
*(uint64_t *) p = 0x0;
}
#endif
zone->af_count++;
zone->alloc_count++;
/* Set the in-use bit */
SET_BIT(b, which_bit);
/* The second bit is flipped to 0 while in use. This
* is because a previously in use chunk would have
* a bit pattern of 11 which makes it looks the same
* as a canary chunk. This bit is set again upon free */
UNSET_BIT(b, (which_bit + 1));
bm[dwords_to_bit_slot] = b;
return p;
}