-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlibaslrmalloc.c
1794 lines (1594 loc) · 49.4 KB
/
libaslrmalloc.c
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
// SPDX-License-Identifier: LGPL-2.1-or-later OR BSD-3-Clause
/*
libaslrmalloc is a LD_PRELOADed library which replaces malloc() and
other memory allocation functions from C library. The main design
goal is not performance or memory consumption but to increase
address space layout randomization (ASLR), hence the name. This is
achieved by not trying to keep the pages together, forcing the
kernel to map pages at random addresses and unmapping old memory
immediately when possible.
Compile as a shared library:
gcc -o libaslrmalloc.so libaslrmalloc.c -fPIC -Wall -g -nostdlib -shared -O
or as a test program:
gcc -o test libaslrmalloc.c -Wall -g -DDEBUG=1
or to verify that libc malloc agrees with the test suite:
gcc -o test libaslrmalloc.c -Wall -g -DDEBUG=1 -DLIBC
Usage:
LD_PRELOAD=/path/to/libaslrmalloc.so program
*/
// Fill character for free()d memory
#define FILL_JUNK 'Z'
#if !LIBC
#if DEBUG
#define malloc xmalloc
#define malloc_usable_size xmalloc_usable_size
#define free xfree
#define calloc xcalloc
#define realloc xrealloc
#define reallocarray xreallocarray
#define posix_memalign xposix_memalign
#define aligned_alloc xaligned_alloc
/* Flawfinder: ignore */
#define memalign xmemalign
#define valloc xvalloc
#define pvalloc xpvalloc
#endif // DEBUG
#endif // !LIBC
// For secure_getenv()
#define _GNU_SOURCE
#include <assert.h>
#include <cpuid.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <malloc.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/random.h>
#include <unistd.h>
#include "config.h"
#if !LIBC
// TODO assumes page size of 4096
#define PAGE_BITS 12
#define PAGE_SIZE (1 << PAGE_BITS)
#define PAGE_MASK (~(PAGE_SIZE - 1))
#define PAGE_ALIGN_UP(size) (((size) + (PAGE_SIZE - 1)) & PAGE_MASK)
// TODO assumes 64 bit longs
#define ULONG_BITS 6
#define ULONG_SIZE (1 << ULONG_BITS)
#define ULONG_MASK (~(ULONG_SIZE - 1))
#define ULONG_ALIGN_UP(size) (((size) + (ULONG_SIZE - 1)) & ULONG_MASK)
#define BITS_PER_BYTE 8
// Avoid addresses within ±32MB of stack
#define STACK_ZONE (32 * 1024 * 1024)
// Avoid addresses in lowest 1MB
#define LOW_ZONE (1 * 1024 * 1024)
#define MIN_ALLOC_BITS 4
#define MIN_ALLOC_SIZE (1 << MIN_ALLOC_BITS)
#define MIN_ALLOC_MASK (~(MIN_ALLOC_SIZE - 1))
#define MAX_SIZE_CLASSES (PAGE_BITS - MIN_ALLOC_BITS)
// Worst case: one bit for each smallest item (MIN_ALLOC_SIZE) per page
#define BITMAP_ULONGS (PAGE_SIZE / MIN_ALLOC_SIZE / ULONG_SIZE)
// TODO use hash tables or modern tree structures to speed up free()
// without weakening ASLR?
/*
small_pagelist is used for allocating small (16 ... 2048) byte
slabs and also page tables for internal use. Fields prev and
hash_next are not used for page tables.
*/
struct small_pagelist {
struct small_pagelist *next, *prev;
struct small_pagelist *hash_next;
void *page;
unsigned long bitmap[BITMAP_ULONGS];
unsigned long access_randomizer_state;
};
/*
large_pagelist is used for allocating multiples of page size blocks.
*/
struct large_pagelist {
struct large_pagelist *next, *prev;
struct large_pagelist *hash_next;
void *page;
size_t size;
};
/*
Global state for the library.
*/
struct malloc_state {
// b16, b32, b64, b128, b256, b512, b1024, b2048;
struct small_pagelist *pagetables;
struct small_pagelist *small_pages[MAX_SIZE_CLASSES];
struct large_pagelist *large_pages;
struct small_pagelist **small_hash_tables[MAX_SIZE_CLASSES];
struct large_pagelist **large_hash_table;
unsigned long small_count[MAX_SIZE_CLASSES];
unsigned long large_count;
};
static struct malloc_state *state;
// TODO replace global lock with a lock for each list?
static pthread_mutex_t malloc_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned long malloc_random_address_mask;
static int malloc_getrandom_bytes;
static int malloc_user_va_space_bits;
// Runtime options
static bool malloc_debug;
static bool malloc_debug_stats;
static char malloc_fill_junk = FILL_JUNK;
static bool malloc_passthrough;
static bool malloc_strict_malloc0;
static bool malloc_strict_posix_memalign_errno;
static void *(*libc_malloc)(size_t);
static size_t (*libc_malloc_usable_size)(void *);
static void (*libc_free)(void *);
static void *(*libc_calloc)(size_t, size_t);
static void *(*libc_realloc)(void *, size_t);
static void *(*libc_reallocarray)(void *, size_t, size_t);
static int (*libc_posix_memalign)(void **, size_t, size_t);
static void *(*libc_aligned_alloc)(size_t, size_t);
static void *(*libc_memalign)(size_t, size_t);
static void *(*libc_valloc)(size_t);
static void *(*libc_pvalloc)(size_t);
#define DPRINTF(format, ...) \
do { \
if (malloc_debug) { \
/* Flawfinder: ignore */ \
char _buf[1024]; \
/* Flawfinder: ignore */ \
int _r = snprintf(_buf, sizeof(_buf), "%s: " format, \
__FUNCTION__, ##__VA_ARGS__); \
if (_r > 0) \
_r = write(2, _buf, _r); \
(void)_r; \
} \
} while (0)
#define DPRINTF_NOPREFIX(format, ...) \
do { \
if (malloc_debug) { \
/* Flawfinder: ignore */ \
char _buf[1024]; \
/* Flawfinder: ignore */ \
int _r = snprintf(_buf, sizeof(_buf), format, \
##__VA_ARGS__); \
if (_r > 0) \
_r = write(2, _buf, _r); \
(void)_r; \
} \
} while (0)
#if DEBUG_BITMAPS
#define DPRINTF_BM DPRINTF
#else
#define DPRINTF_BM(format, ...) do { } while (0)
#endif
// TODO Maybe the guard pages could be even larger than one page, for
// example fill the entire 2MB page table entry, especially for large
// allocations. If they hold a small number of large items (as opposed
// to large number of small items), a small guard may not be enough.
static unsigned long get_guard_size(size_t size) {
return PAGE_SIZE;
}
/*
Get needed random bytes, never giving up.
*/
static void get_random(void *data, size_t bytes) {
for (;;) {
ssize_t r = getrandom(data, bytes, GRND_RANDOM);
if (r == bytes)
return;
}
}
/*
Randomize within [start ... end], inclusive.
*/
static unsigned int randomize_int(unsigned int start, unsigned int end) {
unsigned int randomizer;
get_random(&randomizer, sizeof(randomizer));
return start + randomizer % (end - start + 1);
}
// TODO: possibly use MAP_HUGETLB | MAP_HUGE_2MB in case the alignment
// is already that high
/*
map pages at a random address, possibly aligned more strictly.
MAP_FIXED_NOREPLACE is used to avoid already existing mappings. If
that happens (errno == EEXIST), retry,
*/
static void *mmap_random(size_t size, unsigned long extra_mask) {
unsigned long stack = (unsigned long)__builtin_frame_address(0);
unsigned long guard_size = get_guard_size(size);
for (;;) {
unsigned long addr;
get_random(&addr, malloc_getrandom_bytes);
addr <<= PAGE_BITS;
addr &= malloc_random_address_mask & extra_mask;
/*
Don't exceed VA space, get too close to the stack
or try use too low addresses.
*/
if (addr + size + guard_size > (1ULL << malloc_user_va_space_bits) ||
(addr + size + guard_size >= stack - STACK_ZONE &&
addr - guard_size <= stack + STACK_ZONE) ||
addr < LOW_ZONE)
continue;
addr -= guard_size;
void *ret = mmap((void *)addr, size + 2 * guard_size,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_FIXED_NOREPLACE | MAP_PRIVATE,
-1, 0);
if (ret == MAP_FAILED) {
/*
Sadly mmap() can return ENOMEM in case the
address supplied exceeds VA space, so this
isn't 100% watertight, but we try hard above
not to give such addresses to kernel.
*/
if (errno == ENOMEM)
return ret;
continue;
}
unsigned long lower_guard = (unsigned long)ret;
int r = mprotect((void *)lower_guard, guard_size, PROT_NONE);
if (r < 0) {
perror("mprotect lower guard");
abort();
}
unsigned long higher_guard = (unsigned long)ret + guard_size +
size;
r = mprotect((void *)higher_guard, guard_size, PROT_NONE);
if (r < 0) {
perror("mprotect higher guard");
abort();
}
ret = (void *)((unsigned long)ret + guard_size);
DPRINTF("returning %p, guard pages at %lx+%lu, %lx+%lu\n", ret,
lower_guard, guard_size, higher_guard, guard_size);
return ret;
}
}
/*
Find a slab class suitable for the size of the (small) allocation.
*/
static unsigned int get_index(size_t size) {
for (unsigned int index = MIN_ALLOC_BITS; index < PAGE_BITS; index++)
if (size <= (1UL << index))
return index - MIN_ALLOC_BITS;
return -1;
}
/*
Index for a slab at the end of page, used for managing the page itself.
*/
static unsigned int last_index(size_t size) {
for (unsigned int index = MIN_ALLOC_BITS; index < PAGE_BITS; index++)
if (size <= (1UL << index))
return (PAGE_SIZE / (1UL << index)) - 1;
abort();
}
/*
Get size aligned up to suitable slab size (all powers of 2 from 16 up to
page size).
*/
static unsigned int align_up_size(size_t size) {
for (unsigned int index = MIN_ALLOC_BITS; index < PAGE_BITS; index++)
if (size <= (1UL << index))
return 1U << index;
abort();
}
/*
Get number of bits in a bitmap: number of slabs in one complete page.
*/
static unsigned int bitmap_bits(size_t size) {
return PAGE_SIZE / align_up_size(size);
}
// Get a bit from bitmap.
static int bitmap_bit(const unsigned long *bitmap, unsigned int bit) {
return !!(bitmap[bit >> ULONG_BITS] & (1UL << (bit & ~ULONG_MASK)));
}
/*
Set bit in bitmap: indicates that the slab is in use.
*/
static void bitmap_set(unsigned long *bitmap, unsigned int bit) {
assert(bitmap_bit(bitmap, bit) == 0);
bitmap[bit >> ULONG_BITS] |= 1UL << (bit & ~ULONG_MASK);
}
/*
Clear bit in bitmap: slab is free.
*/
static void bitmap_clear(unsigned long *bitmap, unsigned int bit) {
assert(bitmap_bit(bitmap, bit) == 1);
bitmap[bit >> ULONG_BITS] &= ~(1UL << (bit & ~ULONG_MASK));
}
// TODO Use cryptographically secure, but perfect (no collisions) hash
// or randomization function
// https://en.wikipedia.org/wiki/Cryptographically-secure_pseudorandom_number_generator
// https://en.wikipedia.org/wiki/Perfect_hash_function
// https://en.wikipedia.org/wiki/Randomization_function
/*
Scramble bitmap index. Given an index, maximum index number and
state, the function computes a pseudorandomized index. The goal is
that, given an address of an allocated memory block, it's impossible
to determine addresses of previous or future allocations in the same
slab page without knowing the secret (which is not in the same
page). This is also helped by having a separate state for each slab
page. Of course the number of entries in a page is always very
small.
*/
static unsigned int scramble_index(unsigned int index, unsigned int max,
unsigned long access_randomizer_state) {
assert(max > 0);
unsigned int ret = (index + access_randomizer_state) % max;
DPRINTF_BM("scrambled %u -> %u (max %u state %lx)\n", index, ret, max,
access_randomizer_state);
return ret;
}
/*
Find a clear (free slab) bit in the bitmap. Not all words in the
bitmap are used in full.
*/
static int bitmap_find_clear(const unsigned long *bitmap,
unsigned int bitmap_bits,
unsigned long access_randomizer_state) {
DPRINTF_BM("bitmap_bits %u (%u words)\n", bitmap_bits,
bitmap_bits >> ULONG_BITS);
for (unsigned int bit = 0; bit < bitmap_bits; bit++) {
unsigned int scrambled_bit = scramble_index(
bit, bitmap_bits, access_randomizer_state);
unsigned int word_index = scrambled_bit >> ULONG_BITS;
unsigned int bit_index = scrambled_bit & ~ULONG_MASK;
unsigned long mask = (unsigned long)-1;
if (bitmap_bits - (scrambled_bit & ULONG_MASK) < ULONG_SIZE)
mask = (1UL
<< (bitmap_bits - (scrambled_bit & ULONG_MASK))) -
1;
unsigned long word = bitmap[word_index] & mask;
DPRINTF_BM("checking index %u+%u word %lx mask %lx bit %d "
"(original %d) bits left %d\n",
word_index, bit_index, word, mask, scrambled_bit, bit,
bitmap_bits - scrambled_bit);
if ((word & (1UL << bit_index)) == 0) {
DPRINTF_BM("returning %d\n", scrambled_bit);
return scrambled_bit;
}
}
DPRINTF_BM("returning -1\n");
return -1;
}
/*
Check if all bits in the bitmap are clear. Not all words in the
bitmap are used in full.
*/
static bool bitmap_is_empty(const unsigned long *bitmap,
unsigned int bitmap_bits) {
DPRINTF_BM("bitmap_bits %u (%u words)\n", bitmap_bits,
bitmap_bits >> ULONG_BITS);
for (unsigned int b = 0; b < bitmap_bits; b += 1 << ULONG_BITS) {
unsigned int i = b >> ULONG_BITS;
unsigned long mask = (unsigned long)-1;
if (bitmap_bits - b < ULONG_SIZE)
mask = (1UL << (bitmap_bits - b)) - 1;
unsigned long word = bitmap[i] & mask;
DPRINTF_BM("checking index %u word %lx mask %lx bits left %d\n", i,
word, mask, bitmap_bits - b);
if (word != 0) {
DPRINTF_BM("returning false\n");
return false;
}
}
DPRINTF_BM("returning true\n");
return true;
}
/*
Given a page, size class index of a slab and the number of the
position of the slab, return an address in the page.
*/
static void *ptr_to_offset_in_page(void *page, unsigned int size_index, int num) {
assert(size_index <= MAX_SIZE_CLASSES);
unsigned long offset = (1UL << (size_index + MIN_ALLOC_BITS)) * (unsigned long)num;
unsigned long address = ((unsigned long)page) + offset;
DPRINTF("offsetting page %p size index %u (0x%x) item number "
"%d -> 0x%lx\n",
page, size_index, 1 << (size_index + MIN_ALLOC_BITS), num,
address);
return (void *)address;
}
/*
Dump all pagetables for debugging.
*/
static void pagetables_dump(const char *label) {
if (!malloc_debug || malloc_passthrough)
return;
unsigned int count;
struct small_pagelist *p;
for (p = state->pagetables, count = 0; p; p = p->next, count++) {
DPRINTF("%s: pagetables (%p) [%u] .page=%p rnd=%lx bm=", label,
p, count, p->page, p->access_randomizer_state);
for (int i = 0; i < BITMAP_ULONGS; i++)
DPRINTF_NOPREFIX("%lx ", p->bitmap[i]);
DPRINTF_NOPREFIX("\n");
}
for (unsigned int i = 0; i < MAX_SIZE_CLASSES; i++) {
count = 0;
for (p = state->small_pages[i]; p; p = p->next, count++) {
DPRINTF("%s: small_pages[%u] (%p) [%u] .page=%p "
".rnd=%lx bm=",
label, i, p, count, p->page,
p->access_randomizer_state);
for (unsigned int j = 0; j < BITMAP_ULONGS; j++)
DPRINTF_NOPREFIX("%lx ", p->bitmap[j]);
DPRINTF_NOPREFIX("\n");
}
}
count = 0;
for (struct large_pagelist *p = state->large_pages; p;
p = p->next, count++)
DPRINTF("%s: large_pages (%p) [%u] .page=%p .size=%lx\n", label,
p, count, p->page, p->size);
for (unsigned int i = 0; i < MAX_SIZE_CLASSES; i++)
for (unsigned int j = 0; j < PAGE_SIZE / sizeof(void *); j++) {
if (state->small_hash_tables[i][j]) {
count = 0;
for (p = state->small_hash_tables[i][j]; p; p = p->next, count++) {
DPRINTF("%s: small_hash_tables[%u][%u] (%p) [%u] .page=%p "
".rnd=%lx bm=",
label, i, j, p, count, p->page,
p->access_randomizer_state);
for (int k = 0; k < BITMAP_ULONGS; k++)
DPRINTF_NOPREFIX("%lx ", p->bitmap[k]);
DPRINTF_NOPREFIX("\n");
}
}
}
for (unsigned int i = 0; i < PAGE_SIZE / sizeof(void *); i++) {
if (state->large_hash_table[i]) {
count = 0;
for (struct large_pagelist *p = state->large_hash_table[i]; p;
p = p->hash_next, count++) {
DPRINTF("%s: large_hash_table[%u] (%p) [%u] .page=%p .size=%lx\n", label,
i, p, count, p->page, p->size);
}
}
}
}
/*
Calculate a hash value from address for indexing
512 (sizeof(void *) / PAGE_SIZE) pointers in a page.
*/
static unsigned int malloc_hash(void *ptr) {
unsigned int r = 0;
unsigned long addr = (unsigned long)ptr >> PAGE_BITS;
// Folding hash of 9 bits
do {
r ^= addr & 0x1ff;
addr >>= 9;
} while (addr);
DPRINTF("hash(%p) => %u\n", ptr, r);
return r;
}
/*
Allocate a page table entry for internal use from dedicated page
table slabs.
*/
static struct small_pagelist *pagetable_new(void) {
struct small_pagelist *ret;
unsigned int index = get_index(sizeof(*ret));
for (;;) {
for (struct small_pagelist *p = state->pagetables; p;
p = p->next) {
int offset = bitmap_find_clear(
p->bitmap, bitmap_bits(sizeof(*ret)),
p->access_randomizer_state);
if (offset >= 0) {
ret = ptr_to_offset_in_page(p->page, index,
offset);
bitmap_set(p->bitmap, offset);
goto found;
}
}
// No free entries found, let's allocate a new page.
void *page = mmap_random(PAGE_SIZE, -1);
if (page == MAP_FAILED)
goto oom;
/*
Mark allocation for the page table entry for
managing the page itself in the bitmap.
*/
// TODO offset could be randomized instead of last index
int offset = last_index(sizeof(*ret));
struct small_pagelist *new = ptr_to_offset_in_page(page, index,
offset);
new->page = page;
bitmap_set(new->bitmap, offset);
get_random(&new->access_randomizer_state,
sizeof(new->access_randomizer_state));
new->next = state->pagetables;
DPRINTF("new pagetable %p page %p rnd %lx\n", new, new->page,
new->access_randomizer_state);
// New page is inserted at head of list, retry.
state->pagetables = new;
}
found:
DPRINTF("returning %p\n", ret);
return ret;
oom:
return NULL;
}
/*
Free a page table entry.
*/
static void pagetable_free(struct small_pagelist *entry) {
int size_index = get_index(sizeof(struct small_pagelist));
for (struct small_pagelist *p = state->pagetables, *prev = p; p;
prev = p, p = p->next) {
DPRINTF(".page=%p bm=%lx\n", p->page, p->bitmap[0]);
if (((unsigned long)p->page & PAGE_MASK) ==
((unsigned long)entry & PAGE_MASK)) {
// Calculate the number of the entry for its address
// using the size class
unsigned int bit = ((unsigned long)entry & ~PAGE_MASK) >>
(size_index + MIN_ALLOC_BITS);
DPRINTF("found match %p == %p, clearing bit %u "
"(index %d)\n",
entry, p->page, bit, size_index);
bitmap_clear(p->bitmap, bit);
/*
Check for emptiness excluding the last bit
(entry used for managing the page itself)
*/
if (bitmap_is_empty(
p->bitmap,
last_index(sizeof(struct small_pagelist)))) {
unsigned long guard_size = get_guard_size(
PAGE_SIZE);
DPRINTF("unmap pagetable %p (guards %lu)\n",
p->page, guard_size);
/*
Because the page contains the entry
for managing itself, grab next entry
pointer before the page is unmapped.
*/
struct small_pagelist *next = p->next;
int r = munmap((void *)((unsigned long)p->page -
guard_size),
PAGE_SIZE + 2 * guard_size);
if (r < 0) {
perror("munmap");
abort();
}
if (prev == p)
state->pagetables = next;
else
prev->next = next;
}
return;
}
}
fprintf(stderr, "pagetable_free: %p not found!\n", entry);
abort();
}
static void is_yes(const char *str, bool *ret) {
if (strcmp(str, "1") == 0 ||
strcmp(str, "y") == 0 ||
strcmp(str, "yes") == 0 ||
strcmp(str, "true") == 0) {
*ret = true;
DPRINTF("checking y/n for '%s' -> true\n", str);
} else if (strcmp(str, "0") == 0 ||
strcmp(str, "n") == 0 ||
strcmp(str, "no") == 0 ||
strcmp(str, "false") == 0) {
*ret = false;
DPRINTF("checking y/n for '%s' -> false\n", str);
}
}
// Macro because of sizeof(str)
#define CHECK_OPTION(line, str, ptr) \
if (strncmp(line, str, sizeof(str) - 1) == 0) \
is_yes(&line[sizeof(str) - 1], ptr)
static void check_env(const char *name, bool *ret) {
char *value = secure_getenv(name);
DPRINTF("checking env %s: '%s'\n", name, value);
if (value)
is_yes(value, ret);
}
static void init_from_profile(const char *prefix) {
int r;
/* Flawfinder: ignore */
char profile_path[PATH_MAX];
int profile_file;
/* Flawfinder: ignore */
char profile_data[2048];
r = snprintf(
profile_path,
sizeof(profile_path),
"%s/libaslrmalloc/profiles/%s.profile",
prefix,
program_invocation_short_name
);
if (r < 0 || r > sizeof(profile_path))
return;
/* Flawfinder: ignore */
profile_file = open(profile_path, O_RDONLY);
if (profile_file == -1) {
// Read default profile instead
r = snprintf(
profile_path,
sizeof(profile_path),
"%s/libaslrmalloc/default.profile",
prefix
);
if (r < 0 || r > sizeof(profile_path))
return;
/* Flawfinder: ignore */
profile_file = open(profile_path, O_RDONLY);
if (profile_file == -1)
return;
}
/* Flawfinder: ignore */
r = read(profile_file, profile_data, sizeof(profile_data));
if (r == -1 || r == sizeof(profile_data)) {
close(profile_file);
return;
}
profile_data[r] = '\0';
close(profile_file);
char *saveptr = NULL;
char *line = strtok_r(profile_data, "\n", &saveptr);
if (NULL == line)
return;
do {
DPRINTF("checking profile line %s\n", line);
if (*line == '#')
continue;
else CHECK_OPTION(line, "debug=", &malloc_debug);
else CHECK_OPTION(line, "passthrough=", &malloc_passthrough);
else CHECK_OPTION(line, "stats=", &malloc_debug_stats);
else CHECK_OPTION(line, "strict_malloc0=", &malloc_strict_malloc0);
else CHECK_OPTION(line, "strict_posix_memalign_errno=",
&malloc_strict_posix_memalign_errno);
else if (strncmp(line, "fill_junk=", sizeof("fill_junk=") - 1) == 0)
malloc_fill_junk = line[sizeof("fill_junk=") - 1];
} while ((line = strtok_r(NULL, "\n", &saveptr)));
}
/*
Load a profile named `app.profile` using the name of the
application. The profiles are loaded from directories
`/usr/lib/libaslrmalloc/profiles` (distro),
`/etc/libaslrmalloc/profiles` (local admin), and if the program
isn't setuid or setgid, $XDG_CONFIG_HOME/libaslrmalloc/profiles (or
$HOME/.config/libaslrmalloc/profiles).
If an application specific profile doesn't exist, 'default.profile'
is loaded instead from the directories, but dropping path component
'profiles': `/usr/lib/libaslrmalloc/default.profile` and so forth.
*/
static void init_from_profiles(void) {
init_from_profile(LIBDIR);
init_from_profile(SYSCONFDIR);
if (!getauxval(AT_SECURE) &&
geteuid() == getuid() && getegid() == getgid()) {
/* Flawfinder: ignore */
const char *xdg_config = getenv("XDG_CONFIG_HOME");
if (xdg_config)
init_from_profile(xdg_config);
else {
/* Flawfinder: ignore */
const char *home = getenv("HOME");
if (home) {
/* Flawfinder: ignore */
char home_config[PATH_MAX];
snprintf(home_config, sizeof(home_config),
"%s/.config", home);
init_from_profile(home_config);
}
}
}
#ifdef PROFILE_DIR
init_from_profile(PROFILE_DIR);
#endif
}
/*
dlsym() calls calloc(), so let's use a temporary version.
*/
static void *temp_calloc(size_t nmemb, size_t size) {
/* Flawfinder: ignore */
static char buf[256];
static int bufidx;
void *ret = &buf[bufidx];
bufidx += size;
assert(bufidx < sizeof(buf));
return ret;
}
/*
Initialization of the global state.
We need to allocate at least
- global state
- pagelist for the initial page
*/
static __attribute__((constructor)) void init(void) {
/*
Despite using the ELF constructor, the library may be used
(perhaps by other libraries' constructors) earlier. Ignore
later calls.
*/
if (state)
return;
int saved_errno = errno;
init_from_profiles();
check_env("LIBASLRMALLOC_DEBUG", &malloc_debug);
check_env("LIBASLRMALLOC_PASSTHROUGH", &malloc_passthrough);
check_env("LIBASLRMALLOC_STATS", &malloc_debug_stats);
check_env("LIBASLRMALLOC_STRICT_MALLOC0", &malloc_strict_malloc0);
check_env("LIBASLRMALLOC_STRICT_POSIX_MEMALIGN_ERRNO",
&malloc_strict_posix_memalign_errno);
char *junk = secure_getenv("LIBASLRMALLOC_FILL_JUNK");
if (junk)
malloc_fill_junk = *junk;
if (malloc_passthrough) {
libc_calloc = temp_calloc;
libc_calloc = dlsym(RTLD_NEXT, "calloc");
libc_malloc = dlsym(RTLD_NEXT, "malloc");
libc_malloc_usable_size = dlsym(RTLD_NEXT, "malloc_usable_size");
libc_free = dlsym(RTLD_NEXT, "free");
libc_realloc = dlsym(RTLD_NEXT, "realloc");
libc_reallocarray = dlsym(RTLD_NEXT, "reallocarray");
libc_posix_memalign = dlsym(RTLD_NEXT, "posix_memalign");
libc_aligned_alloc = dlsym(RTLD_NEXT, "aligned_alloc");
libc_memalign = dlsym(RTLD_NEXT, "memalign");
libc_valloc = dlsym(RTLD_NEXT, "valloc");
libc_pvalloc = dlsym(RTLD_NEXT, "pvalloc");
if (
libc_malloc == NULL
|| libc_malloc_usable_size == NULL
|| libc_free == NULL
|| libc_calloc == NULL
|| libc_realloc == NULL
|| libc_reallocarray == NULL
|| libc_posix_memalign == NULL
|| libc_aligned_alloc == NULL
|| libc_memalign == NULL
|| libc_valloc == NULL
|| libc_pvalloc == NULL
)
abort();
state = (void *) -1L;
errno = saved_errno;
return;
}
/*
Get number of virtual address bits with CPUID
instruction. There are lots of different values from 36 to
57 (https://en.wikipedia.org/wiki/X86).
*/
unsigned int eax, unused;
int r = __get_cpuid(0x80000008, &eax, &unused, &unused, &unused);
/*
Calculate a mask for requesting random addresses so that the
kernel should accept them.
*/
malloc_user_va_space_bits = 36;
if (r == 1)
malloc_user_va_space_bits = ((eax >> 8) & 0xff);
malloc_user_va_space_bits--;
malloc_random_address_mask = ((1UL << malloc_user_va_space_bits) - 1) &
PAGE_MASK;
// Also calculate number of random bytes needed for each address
malloc_getrandom_bytes = (malloc_user_va_space_bits - PAGE_BITS + 7) / 8;
/*
A temporary bitmap is used to store allocation of the first
page for global state and initial internal page tables. This
will be moved to the actual internal page table later.
*/
unsigned long temp_bitmap = 0;
/*
Allocate a slab page for global state and initial internal
pagetables. The global state is an exception for slab use
because it occupies multiple slabs. It will never be freed,
so this is OK (unless the global state should be freed in
the rare case of all allocations get freed).
*/
void *pagetables = mmap_random(PAGE_SIZE, -1);
if (pagetables == MAP_FAILED)
abort();
/*
Select random slabs for the state. Exclude last index, used
below for internal use.
*/
int pages_index = get_index(sizeof(struct small_pagelist));
unsigned int last_offset = last_index(sizeof(struct small_pagelist));
unsigned int num_slabs = align_up_size(sizeof(*state)) /
align_up_size(sizeof(struct small_pagelist));
unsigned int offset = randomize_int(0, last_offset - 1 - num_slabs);
state = ptr_to_offset_in_page(pagetables, pages_index, offset);
// Mark slab allocation for global state in the bitmap.
for (unsigned int i = offset; i < offset + num_slabs; i++)
bitmap_set(&temp_bitmap, i);
// Mark allocation for initial internal page tables in the bitmap.
// TODO offset could be randomized instead of last index
bitmap_set(&temp_bitmap, last_offset);
state->pagetables = ptr_to_offset_in_page(pagetables, pages_index,
last_offset);
state->pagetables->page = pagetables;
get_random(&state->pagetables->access_randomizer_state,
sizeof(state->pagetables->access_randomizer_state));
// Copy temporary bitmap
state->pagetables->bitmap[0] = temp_bitmap;
// Allocate hash tables
for (unsigned int i = 0; i < MAX_SIZE_CLASSES; i++) {
state->small_hash_tables[i] = mmap_random(PAGE_SIZE, -1);
if (state->small_hash_tables[i] == MAP_FAILED)
abort();
}
state->large_hash_table = mmap_random(PAGE_SIZE, -1);
if (state->large_hash_table == MAP_FAILED)
abort();
DPRINTF("%d VA space bits, mask %16.16lx, getrandom() bytes %d\n",
malloc_user_va_space_bits, malloc_random_address_mask,
malloc_getrandom_bytes);
DPRINTF("main state at %p +%zu\n", state, sizeof(*state));
pagetables_dump("initial");
errno = saved_errno;
}
static __attribute__((destructor)) void fini(void) {
if (!state) {
DPRINTF("destructor called before constructor\n");
return;
}
if (!malloc_debug || malloc_passthrough)
return;
if (malloc_debug_stats) {
pagetables_dump("final");
// Output as TSV
fprintf(stderr, "Size\tCount\n");
for (unsigned int i = 0; i < MAX_SIZE_CLASSES; i++)
fprintf(stderr, "%d\t%ld\n", 1 << (i + MIN_ALLOC_BITS),
state->small_count[i]);
fprintf(stderr, "%d\t%ld\n", PAGE_SIZE, state->large_count);
}
}
static void *aligned_malloc(size_t size, size_t alignment) {
int ret_errno = errno;
void *ret = NULL;
if (!state)
init();
DPRINTF("aligned_malloc(%lu, %lu)\n", size, alignment);
/*
The manual page says that malloc(0) may return NULL but
sadly some applications expect it to return accessible
memory and Glibc does that.
*/
if (size == 0) {
if (malloc_strict_malloc0)
goto finish;
else
size = 1;
}
if (size >= (1UL << malloc_user_va_space_bits) ||
alignment >= (1UL << malloc_user_va_space_bits)) {
ret_errno = ENOMEM;
goto finish;
}
// Get slab size class for the requested size.
unsigned long extra_mask = ~(alignment - 1);
unsigned int index = get_index(MAX(size, alignment));
size_t real_size;
void *alloc_start;
if (index == (unsigned int)-1) {
// New large allocation
real_size = PAGE_ALIGN_UP(size);
// TODO separate mutexes for large pages and page table entries?
pthread_mutex_lock(&malloc_lock);
struct large_pagelist *new =
(struct large_pagelist *)pagetable_new();
if (!new)
goto oom;
void *page = mmap_random(real_size, extra_mask);
if (page == MAP_FAILED)
goto oom;
new->page = page;
new->size = size;
// Insert in hash table and list
unsigned int hash = malloc_hash(new->page);
new->hash_next = state->large_hash_table[hash];
state->large_hash_table[hash] = new;