-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathdlmalloc.rs
1888 lines (1704 loc) · 61.9 KB
/
dlmalloc.rs
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
// This is a version of dlmalloc.c ported to Rust. You can find the original
// source at ftp://g.oswego.edu/pub/misc/malloc.c
//
// The original source was written by Doug Lea and released to the public domain
macro_rules! debug_assert {
($($arg:tt)*) => {
if cfg!(all(feature = "debug", debug_assertions)) {
assert!($($arg)*);
}
};
}
macro_rules! debug_assert_eq {
($($arg:tt)*) => {
if cfg!(all(feature = "debug", debug_assertions)) {
assert_eq!($($arg)*);
}
};
}
use core::cmp;
use core::mem;
use core::ptr;
use crate::Allocator;
pub struct Dlmalloc<A> {
smallmap: u32,
treemap: u32,
smallbins: [*mut Chunk; (NSMALLBINS + 1) * 2],
treebins: [*mut TreeChunk; NTREEBINS],
dvsize: usize,
topsize: usize,
dv: *mut Chunk,
top: *mut Chunk,
footprint: usize,
max_footprint: usize,
seg: Segment,
trim_check: usize,
least_addr: *mut u8,
release_checks: usize,
system_allocator: A,
}
unsafe impl<A: Send> Send for Dlmalloc<A> {}
// TODO: document this
const NSMALLBINS: usize = 32;
const NTREEBINS: usize = 32;
const SMALLBIN_SHIFT: usize = 3;
const TREEBIN_SHIFT: usize = 8;
const NSMALLBINS_U32: u32 = NSMALLBINS as u32;
const NTREEBINS_U32: u32 = NTREEBINS as u32;
// TODO: runtime configurable? documentation?
const DEFAULT_GRANULARITY: usize = 64 * 1024;
const DEFAULT_TRIM_THRESHOLD: usize = 2 * 1024 * 1024;
const MAX_RELEASE_CHECK_RATE: usize = 4095;
#[repr(C)]
struct Chunk {
prev_foot: usize,
head: usize,
prev: *mut Chunk,
next: *mut Chunk,
}
#[repr(C)]
struct TreeChunk {
chunk: Chunk,
child: [*mut TreeChunk; 2],
parent: *mut TreeChunk,
index: u32,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Segment {
base: *mut u8,
size: usize,
next: *mut Segment,
flags: u32,
}
fn align_up(a: usize, alignment: usize) -> usize {
debug_assert!(alignment.is_power_of_two());
(a + (alignment - 1)) & !(alignment - 1)
}
fn left_bits(x: u32) -> u32 {
(x << 1) | (!(x << 1)).wrapping_add(1)
}
fn least_bit(x: u32) -> u32 {
x & (!x + 1)
}
fn leftshift_for_tree_index(x: u32) -> u32 {
let x = usize::try_from(x).unwrap();
if x == NTREEBINS - 1 {
0
} else {
(mem::size_of::<usize>() * 8 - 1 - ((x >> 1) + TREEBIN_SHIFT - 2)) as u32
}
}
impl<A> Dlmalloc<A> {
pub const fn new(system_allocator: A) -> Dlmalloc<A> {
Dlmalloc {
smallmap: 0,
treemap: 0,
smallbins: [ptr::null_mut(); (NSMALLBINS + 1) * 2],
treebins: [ptr::null_mut(); NTREEBINS],
dvsize: 0,
topsize: 0,
dv: ptr::null_mut(),
top: ptr::null_mut(),
footprint: 0,
max_footprint: 0,
seg: Segment {
base: ptr::null_mut(),
size: 0,
next: ptr::null_mut(),
flags: 0,
},
trim_check: 0,
least_addr: ptr::null_mut(),
release_checks: 0,
system_allocator,
}
}
}
impl<A: Allocator> Dlmalloc<A> {
// TODO: can we get rid of this?
pub fn malloc_alignment(&self) -> usize {
mem::size_of::<usize>() * 2
}
// TODO: dox
fn chunk_overhead(&self) -> usize {
mem::size_of::<usize>()
}
fn mmap_chunk_overhead(&self) -> usize {
2 * mem::size_of::<usize>()
}
// TODO: dox
fn min_large_size(&self) -> usize {
1 << TREEBIN_SHIFT
}
// TODO: dox
fn max_small_size(&self) -> usize {
self.min_large_size() - 1
}
// TODO: dox
fn max_small_request(&self) -> usize {
self.max_small_size() - (self.malloc_alignment() - 1) - self.chunk_overhead()
}
// TODO: dox
fn min_chunk_size(&self) -> usize {
align_up(mem::size_of::<Chunk>(), self.malloc_alignment())
}
// TODO: dox
fn min_request(&self) -> usize {
self.min_chunk_size() - self.chunk_overhead() - 1
}
// TODO: dox
fn max_request(&self) -> usize {
// min_sys_alloc_space: the largest `X` such that
// pad_request(X - 1) -- minus 1, because requests of exactly
// `max_request` will not be honored
// + self.top_foot_size()
// + self.malloc_alignment()
// + DEFAULT_GRANULARITY
// ==
// usize::MAX
let min_sys_alloc_space =
((!0 - (DEFAULT_GRANULARITY + self.top_foot_size() + self.malloc_alignment()) + 1)
& !self.malloc_alignment())
- self.chunk_overhead()
+ 1;
cmp::min((!self.min_chunk_size() + 1) << 2, min_sys_alloc_space)
}
fn pad_request(&self, amt: usize) -> usize {
align_up(amt + self.chunk_overhead(), self.malloc_alignment())
}
fn small_index(&self, size: usize) -> u32 {
(size >> SMALLBIN_SHIFT) as u32
}
fn small_index2size(&self, idx: u32) -> usize {
usize::try_from(idx).unwrap() << SMALLBIN_SHIFT
}
fn is_small(&self, s: usize) -> bool {
s >> SMALLBIN_SHIFT < NSMALLBINS
}
fn is_aligned(&self, a: usize) -> bool {
a & (self.malloc_alignment() - 1) == 0
}
fn align_offset(&self, addr: *mut u8) -> usize {
addr.align_offset(self.malloc_alignment())
}
fn align_offset_usize(&self, addr: usize) -> usize {
align_up(addr, self.malloc_alignment()) - addr
}
fn top_foot_size(&self) -> usize {
self.align_offset_usize(Chunk::mem_offset())
+ self.pad_request(mem::size_of::<Segment>())
+ self.min_chunk_size()
}
fn mmap_foot_pad(&self) -> usize {
4 * mem::size_of::<usize>()
}
fn align_as_chunk(&self, ptr: *mut u8) -> *mut Chunk {
unsafe {
let chunk = Chunk::to_mem(ptr.cast());
ptr.add(self.align_offset(chunk)).cast()
}
}
fn request2size(&self, req: usize) -> usize {
if req < self.min_request() {
self.min_chunk_size()
} else {
self.pad_request(req)
}
}
unsafe fn overhead_for(&self, p: *mut Chunk) -> usize {
if Chunk::mmapped(p) {
self.mmap_chunk_overhead()
} else {
self.chunk_overhead()
}
}
pub unsafe fn calloc_must_clear(&self, ptr: *mut u8) -> bool {
!self.system_allocator.allocates_zeros() || !Chunk::mmapped(Chunk::from_mem(ptr))
}
pub unsafe fn malloc(&mut self, size: usize) -> *mut u8 {
self.check_malloc_state();
let nb;
if size <= self.max_small_request() {
nb = self.request2size(size);
let mut idx = self.small_index(nb);
let smallbits = self.smallmap >> idx;
// Check the bin for `idx` (the lowest bit) but also check the next
// bin up to use that to satisfy our request, if needed.
if smallbits & 0b11 != 0 {
// If our the lowest bit, our `idx`, is unset then bump up the
// index as we'll be using the next bucket up.
idx += !smallbits & 1;
let b = self.smallbin_at(idx);
let p = (*b).prev;
self.unlink_first_small_chunk(b, p, idx);
let smallsize = self.small_index2size(idx);
Chunk::set_inuse_and_pinuse(p, smallsize);
let ret = Chunk::to_mem(p);
self.check_malloced_chunk(ret, nb);
return ret;
}
if nb > self.dvsize {
// If there's some other bin with some memory, then we just use
// the next smallest bin
if smallbits != 0 {
let leftbits = (smallbits << idx) & left_bits(1 << idx);
let leastbit = least_bit(leftbits);
let i = leastbit.trailing_zeros();
let b = self.smallbin_at(i);
let p = (*b).prev;
debug_assert_eq!(Chunk::size(p), self.small_index2size(i));
self.unlink_first_small_chunk(b, p, i);
let smallsize = self.small_index2size(i);
let rsize = smallsize - nb;
if mem::size_of::<usize>() != 4 && rsize < self.min_chunk_size() {
Chunk::set_inuse_and_pinuse(p, smallsize);
} else {
Chunk::set_size_and_pinuse_of_inuse_chunk(p, nb);
let r = Chunk::plus_offset(p, nb);
Chunk::set_size_and_pinuse_of_free_chunk(r, rsize);
self.replace_dv(r, rsize);
}
let ret = Chunk::to_mem(p);
self.check_malloced_chunk(ret, nb);
return ret;
} else if self.treemap != 0 {
let mem = self.tmalloc_small(nb);
if !mem.is_null() {
self.check_malloced_chunk(mem, nb);
self.check_malloc_state();
return mem;
}
}
}
} else if size >= self.max_request() {
// TODO: translate this to unsupported
return ptr::null_mut();
} else {
nb = self.pad_request(size);
if self.treemap != 0 {
let mem = self.tmalloc_large(nb);
if !mem.is_null() {
self.check_malloced_chunk(mem, nb);
self.check_malloc_state();
return mem;
}
}
}
// use the `dv` node if we can, splitting it if necessary or otherwise
// exhausting the entire chunk
if nb <= self.dvsize {
let rsize = self.dvsize - nb;
let p = self.dv;
if rsize >= self.min_chunk_size() {
self.dv = Chunk::plus_offset(p, nb);
self.dvsize = rsize;
let r = self.dv;
Chunk::set_size_and_pinuse_of_free_chunk(r, rsize);
Chunk::set_size_and_pinuse_of_inuse_chunk(p, nb);
} else {
let dvs = self.dvsize;
self.dvsize = 0;
self.dv = ptr::null_mut();
Chunk::set_inuse_and_pinuse(p, dvs);
}
let ret = Chunk::to_mem(p);
self.check_malloced_chunk(ret, nb);
self.check_malloc_state();
return ret;
}
// Split the top node if we can
if nb < self.topsize {
self.topsize -= nb;
let rsize = self.topsize;
let p = self.top;
self.top = Chunk::plus_offset(p, nb);
let r = self.top;
(*r).head = rsize | PINUSE;
Chunk::set_size_and_pinuse_of_inuse_chunk(p, nb);
self.check_top_chunk(self.top);
let ret = Chunk::to_mem(p);
self.check_malloced_chunk(ret, nb);
self.check_malloc_state();
return ret;
}
self.sys_alloc(nb)
}
/// allocates system resources
unsafe fn sys_alloc(&mut self, size: usize) -> *mut u8 {
self.check_malloc_state();
// keep in sync with max_request
let asize = align_up(
size + self.top_foot_size() + self.malloc_alignment(),
DEFAULT_GRANULARITY,
);
let (tbase, tsize, flags) = self.system_allocator.alloc(asize);
if tbase.is_null() {
return tbase;
}
self.footprint += tsize;
self.max_footprint = cmp::max(self.max_footprint, self.footprint);
if self.top.is_null() {
if self.least_addr.is_null() || tbase < self.least_addr {
self.least_addr = tbase;
}
self.seg.base = tbase;
self.seg.size = tsize;
self.seg.flags = flags;
self.release_checks = MAX_RELEASE_CHECK_RATE;
self.init_bins();
let tsize = tsize - self.top_foot_size();
self.init_top(tbase.cast(), tsize);
// let mn = Chunk::next(Chunk::from_mem(self as *mut _ as *mut u8));
// let top_foot_size = self.top_foot_size();
// self.init_top(mn, tbase as usize + tsize - mn as usize - top_foot_size);
} else {
let mut sp: *mut Segment = &mut self.seg;
while !sp.is_null() && tbase != Segment::top(sp) {
sp = (*sp).next;
}
if !sp.is_null()
&& !Segment::is_extern(sp)
&& Segment::sys_flags(sp) == flags
&& Segment::holds(sp, self.top.cast())
{
(*sp).size += tsize;
let ptr = self.top;
let size = self.topsize + tsize;
self.init_top(ptr, size);
} else {
self.least_addr = cmp::min(tbase, self.least_addr);
let mut sp: *mut Segment = &mut self.seg;
while !sp.is_null() && (*sp).base != tbase.add(tsize) {
sp = (*sp).next;
}
if !sp.is_null() && !Segment::is_extern(sp) && Segment::sys_flags(sp) == flags {
let oldbase = (*sp).base;
(*sp).base = tbase;
(*sp).size += tsize;
return self.prepend_alloc(tbase, oldbase, size);
} else {
self.add_segment(tbase, tsize, flags);
}
}
}
if size < self.topsize {
self.topsize -= size;
let rsize = self.topsize;
let p = self.top;
self.top = Chunk::plus_offset(p, size);
let r = self.top;
(*r).head = rsize | PINUSE;
Chunk::set_size_and_pinuse_of_inuse_chunk(p, size);
let ret = Chunk::to_mem(p);
self.check_top_chunk(self.top);
self.check_malloced_chunk(ret, size);
self.check_malloc_state();
return ret;
}
return ptr::null_mut();
}
pub unsafe fn realloc(&mut self, oldmem: *mut u8, bytes: usize) -> *mut u8 {
if bytes >= self.max_request() {
return ptr::null_mut();
}
let nb = self.request2size(bytes);
let oldp = Chunk::from_mem(oldmem);
let newp = self.try_realloc_chunk(oldp, nb, true);
if !newp.is_null() {
self.check_inuse_chunk(newp);
return Chunk::to_mem(newp);
}
let ptr = self.malloc(bytes);
if !ptr.is_null() {
let oc = Chunk::size(oldp) - self.overhead_for(oldp);
ptr::copy_nonoverlapping(oldmem, ptr, cmp::min(oc, bytes));
self.free(oldmem);
}
return ptr;
}
unsafe fn try_realloc_chunk(&mut self, p: *mut Chunk, nb: usize, can_move: bool) -> *mut Chunk {
let oldsize = Chunk::size(p);
let next = Chunk::plus_offset(p, oldsize);
if Chunk::mmapped(p) {
self.mmap_resize(p, nb, can_move)
} else if oldsize >= nb {
let rsize = oldsize - nb;
if rsize >= self.min_chunk_size() {
let r = Chunk::plus_offset(p, nb);
Chunk::set_inuse(p, nb);
Chunk::set_inuse(r, rsize);
self.dispose_chunk(r, rsize);
}
p
} else if next == self.top {
// extend into top
if oldsize + self.topsize <= nb {
return ptr::null_mut();
}
let newsize = oldsize + self.topsize;
let newtopsize = newsize - nb;
let newtop = Chunk::plus_offset(p, nb);
Chunk::set_inuse(p, nb);
(*newtop).head = newtopsize | PINUSE;
self.top = newtop;
self.topsize = newtopsize;
p
} else if next == self.dv {
// extend into dv
let dvs = self.dvsize;
if oldsize + dvs < nb {
return ptr::null_mut();
}
let dsize = oldsize + dvs - nb;
if dsize >= self.min_chunk_size() {
let r = Chunk::plus_offset(p, nb);
let n = Chunk::plus_offset(r, dsize);
Chunk::set_inuse(p, nb);
Chunk::set_size_and_pinuse_of_free_chunk(r, dsize);
Chunk::clear_pinuse(n);
self.dvsize = dsize;
self.dv = r;
} else {
// exhaust dv
let newsize = oldsize + dvs;
Chunk::set_inuse(p, newsize);
self.dvsize = 0;
self.dv = ptr::null_mut();
}
return p;
} else if !Chunk::cinuse(next) {
// extend into the next free chunk
let nextsize = Chunk::size(next);
if oldsize + nextsize < nb {
return ptr::null_mut();
}
let rsize = oldsize + nextsize - nb;
self.unlink_chunk(next, nextsize);
if rsize < self.min_chunk_size() {
let newsize = oldsize + nextsize;
Chunk::set_inuse(p, newsize);
} else {
let r = Chunk::plus_offset(p, nb);
Chunk::set_inuse(p, nb);
Chunk::set_inuse(r, rsize);
self.dispose_chunk(r, rsize);
}
p
} else {
ptr::null_mut()
}
}
unsafe fn mmap_resize(&mut self, oldp: *mut Chunk, nb: usize, can_move: bool) -> *mut Chunk {
let oldsize = Chunk::size(oldp);
// Can't shrink mmap regions below a small size
if self.is_small(nb) {
return ptr::null_mut();
}
// Keep the old chunk if it's big enough but not too big
if oldsize >= nb + mem::size_of::<usize>() && (oldsize - nb) <= (DEFAULT_GRANULARITY << 1) {
return oldp;
}
let offset = (*oldp).prev_foot;
let oldmmsize = oldsize + offset + self.mmap_foot_pad();
let newmmsize =
self.mmap_align(nb + 6 * mem::size_of::<usize>() + self.malloc_alignment() - 1);
let ptr = self.system_allocator.remap(
oldp.cast::<u8>().sub(offset),
oldmmsize,
newmmsize,
can_move,
);
if ptr.is_null() {
return ptr::null_mut();
}
let newp = ptr.add(offset).cast::<Chunk>();
let psize = newmmsize - offset - self.mmap_foot_pad();
(*newp).head = psize;
(*Chunk::plus_offset(newp, psize)).head = Chunk::fencepost_head();
(*Chunk::plus_offset(newp, psize + mem::size_of::<usize>())).head = 0;
self.least_addr = cmp::min(ptr, self.least_addr);
self.footprint = self.footprint + newmmsize - oldmmsize;
self.max_footprint = cmp::max(self.max_footprint, self.footprint);
self.check_mmapped_chunk(newp);
return newp;
}
fn mmap_align(&self, a: usize) -> usize {
align_up(a, self.system_allocator.page_size())
}
// Only call this with power-of-two alignment and alignment >
// `self.malloc_alignment()`
pub unsafe fn memalign(&mut self, mut alignment: usize, bytes: usize) -> *mut u8 {
if alignment < self.min_chunk_size() {
alignment = self.min_chunk_size();
}
if bytes >= self.max_request() - alignment {
return ptr::null_mut();
}
let nb = self.request2size(bytes);
let req = nb + alignment + self.min_chunk_size() - self.chunk_overhead();
let mem = self.malloc(req);
if mem.is_null() {
return mem;
}
let mut p = Chunk::from_mem(mem);
if mem as usize & (alignment - 1) != 0 {
// Here we find an aligned sopt inside the chunk. Since we need to
// give back leading space in a chunk of at least `min_chunk_size`,
// if the first calculation places us at a spot with less than
// `min_chunk_size` leader we can move to the next aligned spot.
// we've allocated enough total room so that this is always possible
let br =
Chunk::from_mem(((mem as usize + alignment - 1) & (!alignment + 1)) as *mut u8);
let pos = if (br as usize - p as usize) > self.min_chunk_size() {
br.cast::<u8>()
} else {
br.cast::<u8>().add(alignment)
};
let newp = pos.cast::<Chunk>();
let leadsize = pos as usize - p as usize;
let newsize = Chunk::size(p) - leadsize;
// for mmapped chunks just adjust the offset
if Chunk::mmapped(p) {
(*newp).prev_foot = (*p).prev_foot + leadsize;
(*newp).head = newsize;
} else {
// give back the leader, use the rest
Chunk::set_inuse(newp, newsize);
Chunk::set_inuse(p, leadsize);
self.dispose_chunk(p, leadsize);
}
p = newp;
}
// give back spare room at the end
if !Chunk::mmapped(p) {
let size = Chunk::size(p);
if size > nb + self.min_chunk_size() {
let remainder_size = size - nb;
let remainder = Chunk::plus_offset(p, nb);
Chunk::set_inuse(p, nb);
Chunk::set_inuse(remainder, remainder_size);
self.dispose_chunk(remainder, remainder_size);
}
}
let mem = Chunk::to_mem(p);
debug_assert!(Chunk::size(p) >= nb);
debug_assert_eq!(align_up(mem as usize, alignment), mem as usize);
self.check_inuse_chunk(p);
return mem;
}
// consolidate and bin a chunk, differs from exported versions of free
// mainly in that the chunk need not be marked as inuse
unsafe fn dispose_chunk(&mut self, mut p: *mut Chunk, mut psize: usize) {
let next = Chunk::plus_offset(p, psize);
if !Chunk::pinuse(p) {
let prevsize = (*p).prev_foot;
if Chunk::mmapped(p) {
psize += prevsize + self.mmap_foot_pad();
if self
.system_allocator
.free(p.cast::<u8>().sub(prevsize), psize)
{
self.footprint -= psize;
}
return;
}
let prev = Chunk::minus_offset(p, prevsize);
psize += prevsize;
p = prev;
if p != self.dv {
self.unlink_chunk(p, prevsize);
} else if (*next).head & INUSE == INUSE {
self.dvsize = psize;
Chunk::set_free_with_pinuse(p, psize, next);
return;
}
}
if !Chunk::cinuse(next) {
// consolidate forward
if next == self.top {
self.topsize += psize;
let tsize = self.topsize;
self.top = p;
(*p).head = tsize | PINUSE;
if p == self.dv {
self.dv = ptr::null_mut();
self.dvsize = 0;
}
return;
} else if next == self.dv {
self.dvsize += psize;
let dsize = self.dvsize;
self.dv = p;
Chunk::set_size_and_pinuse_of_free_chunk(p, dsize);
return;
} else {
let nsize = Chunk::size(next);
psize += nsize;
self.unlink_chunk(next, nsize);
Chunk::set_size_and_pinuse_of_free_chunk(p, psize);
if p == self.dv {
self.dvsize = psize;
return;
}
}
} else {
Chunk::set_free_with_pinuse(p, psize, next);
}
self.insert_chunk(p, psize);
}
unsafe fn init_top(&mut self, ptr: *mut Chunk, size: usize) {
let offset = self.align_offset(Chunk::to_mem(ptr));
let p = Chunk::plus_offset(ptr, offset);
let size = size - offset;
self.top = p;
self.topsize = size;
(*p).head = size | PINUSE;
(*Chunk::plus_offset(p, size)).head = self.top_foot_size();
self.trim_check = DEFAULT_TRIM_THRESHOLD;
}
unsafe fn init_bins(&mut self) {
for i in 0..NSMALLBINS_U32 {
let bin = self.smallbin_at(i);
(*bin).next = bin;
(*bin).prev = bin;
}
}
unsafe fn prepend_alloc(&mut self, newbase: *mut u8, oldbase: *mut u8, size: usize) -> *mut u8 {
let p = self.align_as_chunk(newbase);
let mut oldfirst = self.align_as_chunk(oldbase);
let psize = oldfirst as usize - p as usize;
let q = Chunk::plus_offset(p, size);
let mut qsize = psize - size;
Chunk::set_size_and_pinuse_of_inuse_chunk(p, size);
debug_assert!(oldfirst > q);
debug_assert!(Chunk::pinuse(oldfirst));
debug_assert!(qsize >= self.min_chunk_size());
// consolidate the remainder with the first chunk of the old base
if oldfirst == self.top {
self.topsize += qsize;
let tsize = self.topsize;
self.top = q;
(*q).head = tsize | PINUSE;
self.check_top_chunk(q);
} else if oldfirst == self.dv {
self.dvsize += qsize;
let dsize = self.dvsize;
self.dv = q;
Chunk::set_size_and_pinuse_of_free_chunk(q, dsize);
} else {
if !Chunk::inuse(oldfirst) {
let nsize = Chunk::size(oldfirst);
self.unlink_chunk(oldfirst, nsize);
oldfirst = Chunk::plus_offset(oldfirst, nsize);
qsize += nsize;
}
Chunk::set_free_with_pinuse(q, qsize, oldfirst);
self.insert_chunk(q, qsize);
self.check_free_chunk(q);
}
let ret = Chunk::to_mem(p);
self.check_malloced_chunk(ret, size);
self.check_malloc_state();
return ret;
}
// add a segment to hold a new noncontiguous region
unsafe fn add_segment(&mut self, tbase: *mut u8, tsize: usize, flags: u32) {
// TODO: what in the world is this function doing
// Determine locations and sizes of segment, fenceposts, and the old top
let old_top = self.top.cast::<u8>();
let oldsp = self.segment_holding(old_top);
let old_end = Segment::top(oldsp);
let ssize = self.pad_request(mem::size_of::<Segment>());
let offset = ssize + mem::size_of::<usize>() * 4 + self.malloc_alignment() - 1;
let rawsp = old_end.sub(offset);
let offset = self.align_offset(Chunk::to_mem(rawsp.cast()));
let asp = rawsp.add(offset);
let csp = if asp < old_top.add(self.min_chunk_size()) {
old_top
} else {
asp
};
let sp = csp.cast::<Chunk>();
let ss = Chunk::to_mem(sp).cast::<Segment>();
let tnext = Chunk::plus_offset(sp, ssize);
let mut p = tnext;
let mut nfences = 0;
// reset the top to our new space
let size = tsize - self.top_foot_size();
self.init_top(tbase.cast(), size);
// set up our segment record
debug_assert!(self.is_aligned(ss as usize));
Chunk::set_size_and_pinuse_of_inuse_chunk(sp, ssize);
*ss = self.seg; // push our current record
self.seg.base = tbase;
self.seg.size = tsize;
self.seg.flags = flags;
self.seg.next = ss;
// insert trailing fences
loop {
let nextp = Chunk::plus_offset(p, mem::size_of::<usize>());
(*p).head = Chunk::fencepost_head();
nfences += 1;
if ptr::addr_of!((*nextp).head).cast::<u8>() < old_end {
p = nextp;
} else {
break;
}
}
debug_assert!(nfences >= 2);
// insert the rest of the old top into a bin as an ordinary free chunk
if csp != old_top {
let q = old_top.cast::<Chunk>();
let psize = csp as usize - old_top as usize;
let tn = Chunk::plus_offset(q, psize);
Chunk::set_free_with_pinuse(q, psize, tn);
self.insert_chunk(q, psize);
}
self.check_top_chunk(self.top);
self.check_malloc_state();
}
unsafe fn segment_holding(&self, ptr: *mut u8) -> *mut Segment {
let mut sp = &self.seg as *const Segment as *mut Segment;
while !sp.is_null() {
if (*sp).base <= ptr && ptr < Segment::top(sp) {
return sp;
}
sp = (*sp).next;
}
ptr::null_mut()
}
unsafe fn tmalloc_small(&mut self, size: usize) -> *mut u8 {
let leastbit = least_bit(self.treemap);
let i = leastbit.trailing_zeros();
let mut v = *self.treebin_at(i);
let mut t = v;
let mut rsize = Chunk::size(TreeChunk::chunk(t)) - size;
loop {
t = TreeChunk::leftmost_child(t);
if t.is_null() {
break;
}
let trem = Chunk::size(TreeChunk::chunk(t)) - size;
if trem < rsize {
rsize = trem;
v = t;
}
}
let vc = TreeChunk::chunk(v);
let r = Chunk::plus_offset(vc, size).cast::<TreeChunk>();
debug_assert_eq!(Chunk::size(vc), rsize + size);
self.unlink_large_chunk(v);
if rsize < self.min_chunk_size() {
Chunk::set_inuse_and_pinuse(vc, rsize + size);
} else {
let rc = TreeChunk::chunk(r);
Chunk::set_size_and_pinuse_of_inuse_chunk(vc, size);
Chunk::set_size_and_pinuse_of_free_chunk(rc, rsize);
self.replace_dv(rc, rsize);
}
Chunk::to_mem(vc)
}
unsafe fn tmalloc_large(&mut self, size: usize) -> *mut u8 {
let mut v = ptr::null_mut();
let mut rsize = !size + 1;
let idx = self.compute_tree_index(size);
let mut t = *self.treebin_at(idx);
if !t.is_null() {
// Traverse thre tree for this bin looking for a node with size
// equal to the `size` above.
let mut sizebits = size << leftshift_for_tree_index(idx);
// Keep track of the deepest untaken right subtree
let mut rst = ptr::null_mut();
loop {
let csize = Chunk::size(TreeChunk::chunk(t));
if csize >= size && csize - size < rsize {
v = t;
rsize = csize - size;
if rsize == 0 {
break;
}
}
let rt = (*t).child[1];
t = (*t).child[(sizebits >> (mem::size_of::<usize>() * 8 - 1)) & 1];
if !rt.is_null() && rt != t {
rst = rt;
}
if t.is_null() {
// Reset `t` to the least subtree holding sizes greater than
// the `size` above, breaking out
t = rst;
break;
}
sizebits <<= 1;
}
}
// Set t to the root of the next non-empty treebin
if t.is_null() && v.is_null() {
let leftbits = left_bits(1 << idx) & self.treemap;
if leftbits != 0 {
let leastbit = least_bit(leftbits);
let i = leastbit.trailing_zeros();
t = *self.treebin_at(i);
}
}
// Find the smallest of this tree or subtree
while !t.is_null() {
let csize = Chunk::size(TreeChunk::chunk(t));
if csize >= size && csize - size < rsize {
rsize = csize - size;
v = t;
}
t = TreeChunk::leftmost_child(t);
}
// If dv is a better fit, then return null so malloc will use it
if v.is_null() || (self.dvsize >= size && !(rsize < self.dvsize - size)) {
return ptr::null_mut();
}
let vc = TreeChunk::chunk(v);
let r = Chunk::plus_offset(vc, size);
debug_assert_eq!(Chunk::size(vc), rsize + size);
self.unlink_large_chunk(v);
if rsize < self.min_chunk_size() {
Chunk::set_inuse_and_pinuse(vc, rsize + size);
} else {
Chunk::set_size_and_pinuse_of_inuse_chunk(vc, size);
Chunk::set_size_and_pinuse_of_free_chunk(r, rsize);
self.insert_chunk(r, rsize);
}
Chunk::to_mem(vc)
}
unsafe fn smallbin_at(&mut self, idx: u32) -> *mut Chunk {
let idx = usize::try_from(idx * 2).unwrap();
debug_assert!(idx < self.smallbins.len());
self.smallbins.as_mut_ptr().add(idx).cast()
}
unsafe fn treebin_at(&mut self, idx: u32) -> *mut *mut TreeChunk {
let idx = usize::try_from(idx).unwrap();
debug_assert!(idx < self.treebins.len());
self.treebins.as_mut_ptr().add(idx)
}
fn compute_tree_index(&self, size: usize) -> u32 {
let x = size >> TREEBIN_SHIFT;
if x == 0 {
0
} else if x > 0xffff {
NTREEBINS_U32 - 1
} else {
let k = mem::size_of_val(&x) * 8 - 1 - (x.leading_zeros() as usize);
((k << 1) + (size >> (k + TREEBIN_SHIFT - 1) & 1)) as u32
}
}
unsafe fn unlink_first_small_chunk(&mut self, head: *mut Chunk, next: *mut Chunk, idx: u32) {
let ptr = (*next).prev;
debug_assert!(next != head);
debug_assert!(next != ptr);
debug_assert_eq!(Chunk::size(next), self.small_index2size(idx));
if head == ptr {
self.clear_smallmap(idx);
} else {
(*ptr).next = head;
(*head).prev = ptr;
}
}
unsafe fn replace_dv(&mut self, chunk: *mut Chunk, size: usize) {
let dvs = self.dvsize;
debug_assert!(self.is_small(dvs));