-
Notifications
You must be signed in to change notification settings - Fork 872
/
malloc.c
2781 lines (2476 loc) · 65.6 KB
/
malloc.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
/* $OpenBSD: malloc.c,v 1.296 2024/03/30 07:50:39 miod Exp $ */
/*
* Copyright (c) 2008, 2010, 2011, 2016, 2023 Otto Moerbeek <[email protected]>
* Copyright (c) 2012 Matthew Dempsky <[email protected]>
* Copyright (c) 2008 Damien Miller <[email protected]>
* Copyright (c) 2000 Poul-Henning Kamp <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* If we meet some day, and you think this stuff is worth it, you
* can buy me a beer in return. Poul-Henning Kamp
*/
#ifndef MALLOC_SMALL
#define MALLOC_STATS
#endif
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/mman.h>
#include <sys/sysctl.h>
#include <uvm/uvmexp.h>
#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef MALLOC_STATS
#include <sys/tree.h>
#include <sys/ktrace.h>
#include <dlfcn.h>
#endif
#include "thread_private.h"
#include <tib.h>
#define MALLOC_PAGESHIFT _MAX_PAGE_SHIFT
#define MALLOC_MINSHIFT 4
#define MALLOC_MAXSHIFT (MALLOC_PAGESHIFT - 1)
#define MALLOC_PAGESIZE (1UL << MALLOC_PAGESHIFT)
#define MALLOC_MINSIZE (1UL << MALLOC_MINSHIFT)
#define MALLOC_PAGEMASK (MALLOC_PAGESIZE - 1)
#define MASK_POINTER(p) ((void *)(((uintptr_t)(p)) & ~MALLOC_PAGEMASK))
#define MALLOC_MAXCHUNK (1 << MALLOC_MAXSHIFT)
#define MALLOC_MAXCACHE 256
#define MALLOC_DELAYED_CHUNK_MASK 15
#ifdef MALLOC_STATS
#define MALLOC_INITIAL_REGIONS 512
#else
#define MALLOC_INITIAL_REGIONS (MALLOC_PAGESIZE / sizeof(struct region_info))
#endif
#define MALLOC_DEFAULT_CACHE 64
#define MALLOC_CHUNK_LISTS 4
#define CHUNK_CHECK_LENGTH 32
#define B2SIZE(b) ((b) * MALLOC_MINSIZE)
#define B2ALLOC(b) ((b) == 0 ? MALLOC_MINSIZE : \
(b) * MALLOC_MINSIZE)
#define BUCKETS (MALLOC_MAXCHUNK / MALLOC_MINSIZE)
/*
* We move allocations between half a page and a whole page towards the end,
* subject to alignment constraints. This is the extra headroom we allow.
* Set to zero to be the most strict.
*/
#define MALLOC_LEEWAY 0
#define MALLOC_MOVE_COND(sz) ((sz) - mopts.malloc_guard < \
MALLOC_PAGESIZE - MALLOC_LEEWAY)
#define MALLOC_MOVE(p, sz) (((char *)(p)) + \
((MALLOC_PAGESIZE - MALLOC_LEEWAY - \
((sz) - mopts.malloc_guard)) & \
~(MALLOC_MINSIZE - 1)))
#define PAGEROUND(x) (((x) + (MALLOC_PAGEMASK)) & ~MALLOC_PAGEMASK)
/*
* What to use for Junk. This is the byte value we use to fill with
* when the 'J' option is enabled. Use SOME_JUNK right after alloc,
* and SOME_FREEJUNK right before free.
*/
#define SOME_JUNK 0xdb /* deadbeef */
#define SOME_FREEJUNK 0xdf /* dead, free */
#define SOME_FREEJUNK_ULL 0xdfdfdfdfdfdfdfdfULL
#define MMAP(sz,f) mmap(NULL, (sz), PROT_READ | PROT_WRITE, \
MAP_ANON | MAP_PRIVATE | (f), -1, 0)
#define MMAPNONE(sz,f) mmap(NULL, (sz), PROT_NONE, \
MAP_ANON | MAP_PRIVATE | (f), -1, 0)
#define MMAPA(a,sz,f) mmap((a), (sz), PROT_READ | PROT_WRITE, \
MAP_ANON | MAP_PRIVATE | (f), -1, 0)
struct region_info {
void *p; /* page; low bits used to mark chunks */
uintptr_t size; /* size for pages, or chunk_info pointer */
#ifdef MALLOC_STATS
void **f; /* where allocated from */
#endif
};
LIST_HEAD(chunk_head, chunk_info);
/*
* Two caches, one for "small" regions, one for "big".
* Small cache is an array per size, big cache is one array with different
* sized regions
*/
#define MAX_SMALLCACHEABLE_SIZE 32
#define MAX_BIGCACHEABLE_SIZE 512
/* If the total # of pages is larger than this, evict before inserting */
#define BIGCACHE_FILL(sz) (MAX_BIGCACHEABLE_SIZE * (sz) / 4)
struct smallcache {
void **pages;
ushort length;
ushort max;
};
struct bigcache {
void *page;
size_t psize;
};
#ifdef MALLOC_STATS
#define NUM_FRAMES 4
struct btnode {
RBT_ENTRY(btnode) entry;
void *caller[NUM_FRAMES];
};
RBT_HEAD(btshead, btnode);
RBT_PROTOTYPE(btshead, btnode, entry, btcmp);
#endif /* MALLOC_STATS */
struct dir_info {
u_int32_t canary1;
int active; /* status of malloc */
struct region_info *r; /* region slots */
size_t regions_total; /* number of region slots */
size_t regions_free; /* number of free slots */
size_t rbytesused; /* random bytes used */
const char *func; /* current function */
int malloc_junk; /* junk fill? */
int mmap_flag; /* extra flag for mmap */
int mutex;
int malloc_mt; /* multi-threaded mode? */
/* lists of free chunk info structs */
struct chunk_head chunk_info_list[BUCKETS + 1];
/* lists of chunks with free slots */
struct chunk_head chunk_dir[BUCKETS + 1][MALLOC_CHUNK_LISTS];
/* delayed free chunk slots */
void *delayed_chunks[MALLOC_DELAYED_CHUNK_MASK + 1];
u_char rbytes[32]; /* random bytes */
/* free pages cache */
struct smallcache smallcache[MAX_SMALLCACHEABLE_SIZE];
size_t bigcache_used;
size_t bigcache_size;
struct bigcache *bigcache;
void *chunk_pages;
size_t chunk_pages_used;
#ifdef MALLOC_STATS
void *caller;
size_t inserts;
size_t insert_collisions;
size_t deletes;
size_t delete_moves;
size_t cheap_realloc_tries;
size_t cheap_reallocs;
size_t malloc_used; /* bytes allocated */
size_t malloc_guarded; /* bytes used for guards */
struct btshead btraces; /* backtraces seen */
struct btnode *btnodes; /* store of backtrace nodes */
size_t btnodesused;
#define STATS_ADD(x,y) ((x) += (y))
#define STATS_SUB(x,y) ((x) -= (y))
#define STATS_INC(x) ((x)++)
#define STATS_ZERO(x) ((x) = 0)
#define STATS_SETF(x,y) ((x)->f = (y))
#define STATS_SETFN(x,k,y) ((x)->f[k] = (y))
#define SET_CALLER(x,y) if (DO_STATS) ((x)->caller = (y))
#else
#define STATS_ADD(x,y) /* nothing */
#define STATS_SUB(x,y) /* nothing */
#define STATS_INC(x) /* nothing */
#define STATS_ZERO(x) /* nothing */
#define STATS_SETF(x,y) /* nothing */
#define STATS_SETFN(x,k,y) /* nothing */
#define SET_CALLER(x,y) /* nothing */
#endif /* MALLOC_STATS */
u_int32_t canary2;
};
static void unmap(struct dir_info *d, void *p, size_t sz, size_t clear);
/*
* This structure describes a page worth of chunks.
*
* How many bits per u_short in the bitmap
*/
#define MALLOC_BITS (NBBY * sizeof(u_short))
struct chunk_info {
LIST_ENTRY(chunk_info) entries;
void *page; /* pointer to the page */
/* number of shorts should add up to 8, check alloc_chunk_info() */
u_short canary;
u_short bucket;
u_short free; /* how many free chunks */
u_short total; /* how many chunks */
u_short offset; /* requested size table offset */
#define CHUNK_INFO_TAIL 3
u_short bits[CHUNK_INFO_TAIL]; /* which chunks are free */
};
#define CHUNK_FREE(i, n) ((i)->bits[(n) / MALLOC_BITS] & \
(1U << ((n) % MALLOC_BITS)))
struct malloc_readonly {
/* Main bookkeeping information */
struct dir_info *malloc_pool[_MALLOC_MUTEXES];
u_int malloc_mutexes; /* how much in actual use? */
int malloc_freecheck; /* Extensive double free check */
int malloc_freeunmap; /* mprotect free pages PROT_NONE? */
int def_malloc_junk; /* junk fill? */
int malloc_realloc; /* always realloc? */
int malloc_xmalloc; /* xmalloc behaviour? */
u_int chunk_canaries; /* use canaries after chunks? */
int internal_funcs; /* use better recallocarray/freezero? */
u_int def_maxcache; /* free pages we cache */
u_int junk_loc; /* variation in location of junk */
size_t malloc_guard; /* use guard pages after allocations? */
#ifdef MALLOC_STATS
int malloc_stats; /* save callers, dump leak report */
int malloc_verbose; /* dump verbose statistics at end */
#define DO_STATS mopts.malloc_stats
#else
#define DO_STATS 0
#endif
u_int32_t malloc_canary; /* Matched against ones in pool */
};
/* This object is mapped PROT_READ after initialisation to prevent tampering */
static union {
struct malloc_readonly mopts;
u_char _pad[MALLOC_PAGESIZE];
} malloc_readonly __attribute__((aligned(MALLOC_PAGESIZE)))
__attribute__((section(".openbsd.mutable")));
#define mopts malloc_readonly.mopts
char *malloc_options; /* compile-time options */
static __dead void wrterror(struct dir_info *d, char *msg, ...)
__attribute__((__format__ (printf, 2, 3)));
#ifdef MALLOC_STATS
void malloc_dump(void);
PROTO_NORMAL(malloc_dump);
static void malloc_exit(void);
static void print_chunk_details(struct dir_info *, void *, size_t, size_t);
static void* store_caller(struct dir_info *, struct btnode *);
/* below are the arches for which deeper caller info has been tested */
#if defined(__aarch64__) || \
defined(__amd64__) || \
defined(__arm__) || \
defined(__i386__) || \
defined(__powerpc__)
__attribute__((always_inline))
static inline void*
caller(struct dir_info *d)
{
struct btnode p;
int level = DO_STATS;
if (level == 0)
return NULL;
memset(&p.caller, 0, sizeof(p.caller));
if (level >= 1)
p.caller[0] = __builtin_extract_return_addr(
__builtin_return_address(0));
if (p.caller[0] != NULL && level >= 2)
p.caller[1] = __builtin_extract_return_addr(
__builtin_return_address(1));
if (p.caller[1] != NULL && level >= 3)
p.caller[2] = __builtin_extract_return_addr(
__builtin_return_address(2));
if (p.caller[2] != NULL && level >= 4)
p.caller[3] = __builtin_extract_return_addr(
__builtin_return_address(3));
return store_caller(d, &p);
}
#else
__attribute__((always_inline))
static inline void* caller(struct dir_info *d)
{
struct btnode p;
if (DO_STATS == 0)
return NULL;
memset(&p.caller, 0, sizeof(p.caller));
p.caller[0] = __builtin_extract_return_addr(__builtin_return_address(0));
return store_caller(d, &p);
}
#endif
#endif /* MALLOC_STATS */
/* low bits of r->p determine size: 0 means >= page size and r->size holding
* real size, otherwise low bits is the bucket + 1
*/
#define REALSIZE(sz, r) \
(sz) = (uintptr_t)(r)->p & MALLOC_PAGEMASK, \
(sz) = ((sz) == 0 ? (r)->size : B2SIZE((sz) - 1))
static inline size_t
hash(void *p)
{
size_t sum;
uintptr_t u;
u = (uintptr_t)p >> MALLOC_PAGESHIFT;
sum = u;
sum = (sum << 7) - sum + (u >> 16);
#ifdef __LP64__
sum = (sum << 7) - sum + (u >> 32);
sum = (sum << 7) - sum + (u >> 48);
#endif
return sum;
}
static inline struct dir_info *
getpool(void)
{
if (mopts.malloc_pool[1] == NULL || !mopts.malloc_pool[1]->malloc_mt)
return mopts.malloc_pool[1];
else /* first one reserved for special pool */
return mopts.malloc_pool[1 + TIB_GET()->tib_tid %
(mopts.malloc_mutexes - 1)];
}
static __dead void
wrterror(struct dir_info *d, char *msg, ...)
{
int saved_errno = errno;
va_list ap;
dprintf(STDERR_FILENO, "%s(%d) in %s(): ", __progname,
getpid(), (d != NULL && d->func) ? d->func : "unknown");
va_start(ap, msg);
vdprintf(STDERR_FILENO, msg, ap);
va_end(ap);
dprintf(STDERR_FILENO, "\n");
#ifdef MALLOC_STATS
if (DO_STATS && mopts.malloc_verbose)
malloc_dump();
#endif
errno = saved_errno;
abort();
}
static void
rbytes_init(struct dir_info *d)
{
arc4random_buf(d->rbytes, sizeof(d->rbytes));
/* add 1 to account for using d->rbytes[0] */
d->rbytesused = 1 + d->rbytes[0] % (sizeof(d->rbytes) / 2);
}
static inline u_char
getrbyte(struct dir_info *d)
{
u_char x;
if (d->rbytesused >= sizeof(d->rbytes))
rbytes_init(d);
x = d->rbytes[d->rbytesused++];
return x;
}
static void
omalloc_parseopt(char opt)
{
switch (opt) {
case '+':
mopts.malloc_mutexes <<= 1;
if (mopts.malloc_mutexes > _MALLOC_MUTEXES)
mopts.malloc_mutexes = _MALLOC_MUTEXES;
break;
case '-':
mopts.malloc_mutexes >>= 1;
if (mopts.malloc_mutexes < 2)
mopts.malloc_mutexes = 2;
break;
case '>':
mopts.def_maxcache <<= 1;
if (mopts.def_maxcache > MALLOC_MAXCACHE)
mopts.def_maxcache = MALLOC_MAXCACHE;
break;
case '<':
mopts.def_maxcache >>= 1;
break;
case 'c':
mopts.chunk_canaries = 0;
break;
case 'C':
mopts.chunk_canaries = 1;
break;
#ifdef MALLOC_STATS
case 'd':
mopts.malloc_stats = 0;
break;
case 'D':
case '1':
mopts.malloc_stats = 1;
break;
case '2':
mopts.malloc_stats = 2;
break;
case '3':
mopts.malloc_stats = 3;
break;
case '4':
mopts.malloc_stats = 4;
break;
#endif /* MALLOC_STATS */
case 'f':
mopts.malloc_freecheck = 0;
mopts.malloc_freeunmap = 0;
break;
case 'F':
mopts.malloc_freecheck = 1;
mopts.malloc_freeunmap = 1;
break;
case 'g':
mopts.malloc_guard = 0;
break;
case 'G':
mopts.malloc_guard = MALLOC_PAGESIZE;
break;
case 'j':
if (mopts.def_malloc_junk > 0)
mopts.def_malloc_junk--;
break;
case 'J':
if (mopts.def_malloc_junk < 2)
mopts.def_malloc_junk++;
break;
case 'r':
mopts.malloc_realloc = 0;
break;
case 'R':
mopts.malloc_realloc = 1;
break;
case 'u':
mopts.malloc_freeunmap = 0;
break;
case 'U':
mopts.malloc_freeunmap = 1;
break;
#ifdef MALLOC_STATS
case 'v':
mopts.malloc_verbose = 0;
break;
case 'V':
mopts.malloc_verbose = 1;
break;
#endif /* MALLOC_STATS */
case 'x':
mopts.malloc_xmalloc = 0;
break;
case 'X':
mopts.malloc_xmalloc = 1;
break;
default:
dprintf(STDERR_FILENO, "malloc() warning: "
"unknown char in MALLOC_OPTIONS\n");
break;
}
}
static void
omalloc_init(void)
{
char *p, *q, b[16];
int i, j;
const int mib[2] = { CTL_VM, VM_MALLOC_CONF };
size_t sb;
/*
* Default options
*/
mopts.malloc_mutexes = 8;
mopts.def_malloc_junk = 1;
mopts.def_maxcache = MALLOC_DEFAULT_CACHE;
for (i = 0; i < 3; i++) {
switch (i) {
case 0:
sb = sizeof(b);
j = sysctl(mib, 2, b, &sb, NULL, 0);
if (j != 0)
continue;
p = b;
break;
case 1:
if (issetugid() == 0)
p = getenv("MALLOC_OPTIONS");
else
continue;
break;
case 2:
p = malloc_options;
break;
default:
p = NULL;
}
for (; p != NULL && *p != '\0'; p++) {
switch (*p) {
case 'S':
for (q = "CFGJ"; *q != '\0'; q++)
omalloc_parseopt(*q);
mopts.def_maxcache = 0;
break;
case 's':
for (q = "cfgj"; *q != '\0'; q++)
omalloc_parseopt(*q);
mopts.def_maxcache = MALLOC_DEFAULT_CACHE;
break;
default:
omalloc_parseopt(*p);
break;
}
}
}
#ifdef MALLOC_STATS
if (DO_STATS && (atexit(malloc_exit) == -1)) {
dprintf(STDERR_FILENO, "malloc() warning: atexit(3) failed."
" Will not be able to dump stats on exit\n");
}
#endif
while ((mopts.malloc_canary = arc4random()) == 0)
;
mopts.junk_loc = arc4random();
if (mopts.chunk_canaries)
do {
mopts.chunk_canaries = arc4random();
} while ((u_char)mopts.chunk_canaries == 0 ||
(u_char)mopts.chunk_canaries == SOME_FREEJUNK);
}
static void
omalloc_poolinit(struct dir_info *d, int mmap_flag)
{
u_int i, j;
d->r = NULL;
d->rbytesused = sizeof(d->rbytes);
d->regions_free = d->regions_total = 0;
for (i = 0; i <= BUCKETS; i++) {
LIST_INIT(&d->chunk_info_list[i]);
for (j = 0; j < MALLOC_CHUNK_LISTS; j++)
LIST_INIT(&d->chunk_dir[i][j]);
}
d->mmap_flag = mmap_flag;
d->malloc_junk = mopts.def_malloc_junk;
#ifdef MALLOC_STATS
RBT_INIT(btshead, &d->btraces);
#endif
d->canary1 = mopts.malloc_canary ^ (u_int32_t)(uintptr_t)d;
d->canary2 = ~d->canary1;
}
static int
omalloc_grow(struct dir_info *d)
{
size_t newtotal;
size_t newsize;
size_t mask;
size_t i, oldpsz;
struct region_info *p;
if (d->regions_total > SIZE_MAX / sizeof(struct region_info) / 2)
return 1;
newtotal = d->regions_total == 0 ? MALLOC_INITIAL_REGIONS :
d->regions_total * 2;
newsize = PAGEROUND(newtotal * sizeof(struct region_info));
mask = newtotal - 1;
/* Don't use cache here, we don't want user uaf touch this */
p = MMAP(newsize, d->mmap_flag);
if (p == MAP_FAILED)
return 1;
STATS_ADD(d->malloc_used, newsize);
STATS_ZERO(d->inserts);
STATS_ZERO(d->insert_collisions);
for (i = 0; i < d->regions_total; i++) {
void *q = d->r[i].p;
if (q != NULL) {
size_t index = hash(q) & mask;
STATS_INC(d->inserts);
while (p[index].p != NULL) {
index = (index - 1) & mask;
STATS_INC(d->insert_collisions);
}
p[index] = d->r[i];
}
}
if (d->regions_total > 0) {
oldpsz = PAGEROUND(d->regions_total *
sizeof(struct region_info));
/* clear to avoid meta info ending up in the cache */
unmap(d, d->r, oldpsz, oldpsz);
}
d->regions_free += newtotal - d->regions_total;
d->regions_total = newtotal;
d->r = p;
return 0;
}
/*
* The hashtable uses the assumption that p is never NULL. This holds since
* non-MAP_FIXED mappings with hint 0 start at BRKSIZ.
*/
static int
insert(struct dir_info *d, void *p, size_t sz, void *f)
{
size_t index;
size_t mask;
void *q;
if (d->regions_free * 4 < d->regions_total || d->regions_total == 0) {
if (omalloc_grow(d))
return 1;
}
mask = d->regions_total - 1;
index = hash(p) & mask;
q = d->r[index].p;
STATS_INC(d->inserts);
while (q != NULL) {
index = (index - 1) & mask;
q = d->r[index].p;
STATS_INC(d->insert_collisions);
}
d->r[index].p = p;
d->r[index].size = sz;
STATS_SETF(&d->r[index], f);
d->regions_free--;
return 0;
}
static struct region_info *
find(struct dir_info *d, void *p)
{
size_t index;
size_t mask = d->regions_total - 1;
void *q, *r;
if (mopts.malloc_canary != (d->canary1 ^ (u_int32_t)(uintptr_t)d) ||
d->canary1 != ~d->canary2)
wrterror(d, "internal struct corrupt");
if (d->r == NULL)
return NULL;
p = MASK_POINTER(p);
index = hash(p) & mask;
r = d->r[index].p;
q = MASK_POINTER(r);
while (q != p && r != NULL) {
index = (index - 1) & mask;
r = d->r[index].p;
q = MASK_POINTER(r);
}
return (q == p && r != NULL) ? &d->r[index] : NULL;
}
static void
delete(struct dir_info *d, struct region_info *ri)
{
/* algorithm R, Knuth Vol III section 6.4 */
size_t mask = d->regions_total - 1;
size_t i, j, r;
if (d->regions_total & (d->regions_total - 1))
wrterror(d, "regions_total not 2^x");
d->regions_free++;
STATS_INC(d->deletes);
i = ri - d->r;
for (;;) {
d->r[i].p = NULL;
d->r[i].size = 0;
j = i;
for (;;) {
i = (i - 1) & mask;
if (d->r[i].p == NULL)
return;
r = hash(d->r[i].p) & mask;
if ((i <= r && r < j) || (r < j && j < i) ||
(j < i && i <= r))
continue;
d->r[j] = d->r[i];
STATS_INC(d->delete_moves);
break;
}
}
}
static inline void
junk_free(int junk, void *p, size_t sz)
{
size_t i, step = 1;
uint64_t *lp = p;
if (junk == 0 || sz == 0)
return;
sz /= sizeof(uint64_t);
if (junk == 1) {
if (sz > MALLOC_PAGESIZE / sizeof(uint64_t))
sz = MALLOC_PAGESIZE / sizeof(uint64_t);
step = sz / 4;
if (step == 0)
step = 1;
}
/* Do not always put the free junk bytes in the same spot.
There is modulo bias here, but we ignore that. */
for (i = mopts.junk_loc % step; i < sz; i += step)
lp[i] = SOME_FREEJUNK_ULL;
}
static inline void
validate_junk(struct dir_info *pool, void *p, size_t argsz)
{
size_t i, sz, step = 1;
uint64_t *lp = p;
if (pool->malloc_junk == 0 || argsz == 0)
return;
sz = argsz / sizeof(uint64_t);
if (pool->malloc_junk == 1) {
if (sz > MALLOC_PAGESIZE / sizeof(uint64_t))
sz = MALLOC_PAGESIZE / sizeof(uint64_t);
step = sz / 4;
if (step == 0)
step = 1;
}
/* see junk_free */
for (i = mopts.junk_loc % step; i < sz; i += step) {
if (lp[i] != SOME_FREEJUNK_ULL) {
#ifdef MALLOC_STATS
if (DO_STATS && argsz <= MALLOC_MAXCHUNK)
print_chunk_details(pool, lp, argsz, i);
else
#endif
wrterror(pool,
"write to free mem %p[%zu..%zu]@%zu",
lp, i * sizeof(uint64_t),
(i + 1) * sizeof(uint64_t) - 1, argsz);
}
}
}
/*
* Cache maintenance.
* Opposed to the regular region data structure, the sizes in the
* cache are in MALLOC_PAGESIZE units.
*/
static void
unmap(struct dir_info *d, void *p, size_t sz, size_t clear)
{
size_t psz = sz >> MALLOC_PAGESHIFT;
void *r;
u_short i;
struct smallcache *cache;
if (sz != PAGEROUND(sz) || psz == 0)
wrterror(d, "munmap round");
if (d->bigcache_size > 0 && psz > MAX_SMALLCACHEABLE_SIZE &&
psz <= MAX_BIGCACHEABLE_SIZE) {
u_short base = getrbyte(d);
u_short j;
/* don't look through all slots */
for (j = 0; j < d->bigcache_size / 4; j++) {
i = (base + j) & (d->bigcache_size - 1);
if (d->bigcache_used <
BIGCACHE_FILL(d->bigcache_size)) {
if (d->bigcache[i].psize == 0)
break;
} else {
if (d->bigcache[i].psize != 0)
break;
}
}
/* if we didn't find a preferred slot, use random one */
if (d->bigcache[i].psize != 0) {
size_t tmp;
r = d->bigcache[i].page;
d->bigcache_used -= d->bigcache[i].psize;
tmp = d->bigcache[i].psize << MALLOC_PAGESHIFT;
if (!mopts.malloc_freeunmap)
validate_junk(d, r, tmp);
if (munmap(r, tmp))
wrterror(d, "munmap %p", r);
STATS_SUB(d->malloc_used, tmp);
}
if (clear > 0)
explicit_bzero(p, clear);
if (mopts.malloc_freeunmap) {
if (mprotect(p, sz, PROT_NONE))
wrterror(d, "mprotect %p", r);
} else
junk_free(d->malloc_junk, p, sz);
d->bigcache[i].page = p;
d->bigcache[i].psize = psz;
d->bigcache_used += psz;
return;
}
if (psz > MAX_SMALLCACHEABLE_SIZE || d->smallcache[psz - 1].max == 0) {
if (munmap(p, sz))
wrterror(d, "munmap %p", p);
STATS_SUB(d->malloc_used, sz);
return;
}
cache = &d->smallcache[psz - 1];
if (cache->length == cache->max) {
int fresh;
/* use a random slot */
i = getrbyte(d) & (cache->max - 1);
r = cache->pages[i];
fresh = (uintptr_t)r & 1;
*(uintptr_t*)&r &= ~1UL;
if (!fresh && !mopts.malloc_freeunmap)
validate_junk(d, r, sz);
if (munmap(r, sz))
wrterror(d, "munmap %p", r);
STATS_SUB(d->malloc_used, sz);
cache->length--;
} else
i = cache->length;
/* fill slot */
if (clear > 0)
explicit_bzero(p, clear);
if (mopts.malloc_freeunmap)
mprotect(p, sz, PROT_NONE);
else
junk_free(d->malloc_junk, p, sz);
cache->pages[i] = p;
cache->length++;
}
static void *
map(struct dir_info *d, size_t sz, int zero_fill)
{
size_t psz = sz >> MALLOC_PAGESHIFT;
u_short i;
void *p;
struct smallcache *cache;
if (mopts.malloc_canary != (d->canary1 ^ (u_int32_t)(uintptr_t)d) ||
d->canary1 != ~d->canary2)
wrterror(d, "internal struct corrupt");
if (sz != PAGEROUND(sz) || psz == 0)
wrterror(d, "map round");
if (d->bigcache_size > 0 && psz > MAX_SMALLCACHEABLE_SIZE &&
psz <= MAX_BIGCACHEABLE_SIZE) {
size_t base = getrbyte(d);
size_t cached = d->bigcache_used;
ushort j;
for (j = 0; j < d->bigcache_size && cached >= psz; j++) {
i = (j + base) & (d->bigcache_size - 1);
if (d->bigcache[i].psize == psz) {
p = d->bigcache[i].page;
d->bigcache_used -= psz;
d->bigcache[i].page = NULL;
d->bigcache[i].psize = 0;
if (!mopts.malloc_freeunmap)
validate_junk(d, p, sz);
if (mopts.malloc_freeunmap)
mprotect(p, sz, PROT_READ | PROT_WRITE);
if (zero_fill)
memset(p, 0, sz);
else if (mopts.malloc_freeunmap)
junk_free(d->malloc_junk, p, sz);
return p;
}
cached -= d->bigcache[i].psize;
}
}
if (psz <= MAX_SMALLCACHEABLE_SIZE && d->smallcache[psz - 1].max > 0) {
cache = &d->smallcache[psz - 1];
if (cache->length > 0) {
int fresh;
if (cache->length == 1)
p = cache->pages[--cache->length];
else {
i = getrbyte(d) % cache->length;
p = cache->pages[i];
cache->pages[i] = cache->pages[--cache->length];
}
/* check if page was not junked, i.e. "fresh
we use the lsb of the pointer for that */
fresh = (uintptr_t)p & 1UL;
*(uintptr_t*)&p &= ~1UL;
if (!fresh && !mopts.malloc_freeunmap)
validate_junk(d, p, sz);
if (mopts.malloc_freeunmap)
mprotect(p, sz, PROT_READ | PROT_WRITE);
if (zero_fill)
memset(p, 0, sz);
else if (mopts.malloc_freeunmap)
junk_free(d->malloc_junk, p, sz);
return p;
}
if (psz <= 1) {
p = MMAP(cache->max * sz, d->mmap_flag);
if (p != MAP_FAILED) {
STATS_ADD(d->malloc_used, cache->max * sz);
cache->length = cache->max - 1;
for (i = 0; i < cache->max - 1; i++) {
void *q = (char*)p + i * sz;
cache->pages[i] = q;
/* mark pointer in slot as not junked */
*(uintptr_t*)&cache->pages[i] |= 1UL;
}
if (mopts.malloc_freeunmap)
mprotect(p, (cache->max - 1) * sz,
PROT_NONE);
p = (char*)p + (cache->max - 1) * sz;
/* zero fill not needed, freshly mmapped */
return p;
}
}
}
p = MMAP(sz, d->mmap_flag);
if (p != MAP_FAILED)
STATS_ADD(d->malloc_used, sz);
/* zero fill not needed */
return p;
}
static void
init_chunk_info(struct dir_info *d, struct chunk_info *p, u_int bucket)
{
u_int i;
p->bucket = bucket;
p->total = p->free = MALLOC_PAGESIZE / B2ALLOC(bucket);
p->offset = howmany(p->total, MALLOC_BITS);
p->canary = (u_short)d->canary1;
/* set all valid bits in the bitmap */
i = p->total - 1;
memset(p->bits, 0xff, sizeof(p->bits[0]) * (i / MALLOC_BITS));
p->bits[i / MALLOC_BITS] = (2U << (i % MALLOC_BITS)) - 1;
}
static struct chunk_info *
alloc_chunk_info(struct dir_info *d, u_int bucket)
{
struct chunk_info *p;
if (LIST_EMPTY(&d->chunk_info_list[bucket])) {
const size_t chunk_pages = 64;
size_t size, count, i;