Newer
Older
#if defined(CONFIG_UNIT_TEST)
#include <asm/io.h>
#ifdef DEBUG
#if __STD_C
static void malloc_update_mallinfo (void);
void malloc_stats (void);
#else
static void malloc_update_mallinfo ();
void malloc_stats();
#endif
#endif /* DEBUG */
DECLARE_GLOBAL_DATA_PTR;
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
/*
Emulation of sbrk for WIN32
All code within the ifdef WIN32 is untested by me.
Thanks to Martin Fong and others for supplying this.
*/
#ifdef WIN32
#define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
~(malloc_getpagesize-1))
#define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
/* resrve 64MB to insure large contiguous space */
#define RESERVED_SIZE (1024*1024*64)
#define NEXT_SIZE (2048*1024)
#define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
struct GmListElement;
typedef struct GmListElement GmListElement;
struct GmListElement
{
GmListElement* next;
void* base;
};
static GmListElement* head = 0;
static unsigned int gNextAddress = 0;
static unsigned int gAddressBase = 0;
static unsigned int gAllocatedSize = 0;
static
GmListElement* makeGmListElement (void* bas)
{
GmListElement* this;
this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
assert (this);
if (this)
{
this->base = bas;
this->next = head;
head = this;
}
return this;
}
void gcleanup ()
{
BOOL rval;
assert ( (head == NULL) || (head->base == (void*)gAddressBase));
if (gAddressBase && (gNextAddress - gAddressBase))
{
rval = VirtualFree ((void*)gAddressBase,
gNextAddress - gAddressBase,
MEM_DECOMMIT);
}
while (head)
{
GmListElement* next = head->next;
rval = VirtualFree (head->base, 0, MEM_RELEASE);
assert (rval);
LocalFree (head);
head = next;
}
}
static
void* findRegion (void* start_address, unsigned long size)
{
MEMORY_BASIC_INFORMATION info;
if (size >= TOP_MEMORY) return NULL;
while ((unsigned long)start_address + size < TOP_MEMORY)
{
VirtualQuery (start_address, &info, sizeof (info));
if ((info.State == MEM_FREE) && (info.RegionSize >= size))
return start_address;
else
{
/* Requested region is not available so see if the */
/* next region is available. Set 'start_address' */
/* to the next region and call 'VirtualQuery()' */
/* again. */
start_address = (char*)info.BaseAddress + info.RegionSize;
/* Make sure we start looking for the next region */
/* on the *next* 64K boundary. Otherwise, even if */
/* the new region is free according to */
/* 'VirtualQuery()', the subsequent call to */
/* 'VirtualAlloc()' (which follows the call to */
/* this routine in 'wsbrk()') will round *down* */
/* the requested address to a 64K boundary which */
/* we already know is an address in the */
/* unavailable region. Thus, the subsequent call */
/* to 'VirtualAlloc()' will fail and bring us back */
/* here, causing us to go into an infinite loop. */
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
start_address =
(void *) AlignPage64K((unsigned long) start_address);
}
}
return NULL;
}
void* wsbrk (long size)
{
void* tmp;
if (size > 0)
{
if (gAddressBase == 0)
{
gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
gNextAddress = gAddressBase =
(unsigned int)VirtualAlloc (NULL, gAllocatedSize,
MEM_RESERVE, PAGE_NOACCESS);
} else if (AlignPage (gNextAddress + size) > (gAddressBase +
gAllocatedSize))
{
long new_size = max (NEXT_SIZE, AlignPage (size));
void* new_address = (void*)(gAddressBase+gAllocatedSize);
do
{
new_address = findRegion (new_address, new_size);
if (new_address == 0)
return (void*)-1;
gAddressBase = gNextAddress =
(unsigned int)VirtualAlloc (new_address, new_size,
MEM_RESERVE, PAGE_NOACCESS);
/* repeat in case of race condition */
/* The region that we found has been snagged */
/* by another thread */
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
}
while (gAddressBase == 0);
assert (new_address == (void*)gAddressBase);
gAllocatedSize = new_size;
if (!makeGmListElement ((void*)gAddressBase))
return (void*)-1;
}
if ((size + gNextAddress) > AlignPage (gNextAddress))
{
void* res;
res = VirtualAlloc ((void*)AlignPage (gNextAddress),
(size + gNextAddress -
AlignPage (gNextAddress)),
MEM_COMMIT, PAGE_READWRITE);
if (res == 0)
return (void*)-1;
}
tmp = (void*)gNextAddress;
gNextAddress = (unsigned int)tmp + size;
return tmp;
}
else if (size < 0)
{
unsigned int alignedGoal = AlignPage (gNextAddress + size);
/* Trim by releasing the virtual memory */
if (alignedGoal >= gAddressBase)
{
VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
MEM_DECOMMIT);
gNextAddress = gNextAddress + size;
return (void*)gNextAddress;
}
else
{
VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
MEM_DECOMMIT);
gNextAddress = gAddressBase;
return (void*)-1;
}
}
else
{
return (void*)gNextAddress;
}
}
#endif
/*
Type declarations
*/
struct malloc_chunk
{
INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
typedef struct malloc_chunk* mchunkptr;
/*
malloc_chunk details:
(The following includes lightly edited explanations by Colin Plumb.)
Chunks of memory are maintained using a `boundary tag' method as
described in e.g., Knuth or Standish. (See the paper by Paul
Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
survey of such techniques.) Sizes of free chunks are stored both
in the front of each chunk and at the end. This makes
consolidating fragmented chunks into bigger chunks very fast. The
size fields also hold bits representing whether chunks are free or
in use.
An allocated chunk looks like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk, if allocated | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User data starts here... .
. .
. (malloc_usable_space() bytes) .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Where "chunk" is the front of the chunk for the purpose of most of
the malloc code, but "mem" is the pointer that is returned to the
user. "Nextchunk" is the beginning of the next contiguous chunk.
Chunks always begin on even word boundries, so the mem portion
(which is returned to the user) is also on an even word boundary, and
thus double-word aligned.
Free chunks are stored in circular doubly-linked lists, and look like this:
chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Size of previous chunk |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`head:' | Size of chunk, in bytes |P|
mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Forward pointer to next chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Back pointer to previous chunk in list |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Unused space (may be 0 bytes long) .
. .
. |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
`foot:' | Size of chunk, in bytes |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
The P (PREV_INUSE) bit, stored in the unused low-order bit of the
chunk size (which is always a multiple of two words), is an in-use
bit for the *previous* chunk. If that bit is *clear*, then the
word before the current chunk size contains the previous chunk
size, and can be used to find the front of the previous chunk.
(The very first chunk allocated always has this bit set,
preventing access to non-existent (or non-owned) memory.)
Note that the `foot' of the current chunk is actually represented
as the prev_size of the NEXT chunk. (This makes it easier to
deal with alignments etc).
The two exceptions to all this are
1. The special chunk `top', which doesn't bother using the
trailing size field since there is no
next contiguous chunk that would have to index off it. (After
initialization, `top' is forced to always exist. If it would
become less than MINSIZE bytes long, it is replenished via
malloc_extend_top.)
2. Chunks allocated via mmap, which have the second-lowest-order
bit (IS_MMAPPED) set in their size fields. Because they are
never merged or traversed from any other chunk, they have no
foot size or inuse information.
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
Available chunks are kept in any of several places (all declared below):
* `av': An array of chunks serving as bin headers for consolidated
chunks. Each bin is doubly linked. The bins are approximately
proportionally (log) spaced. There are a lot of these bins
(128). This may look excessive, but works very well in
practice. All procedures maintain the invariant that no
consolidated chunk physically borders another one. Chunks in
bins are kept in size order, with ties going to the
approximately least recently used chunk.
The chunks in each bin are maintained in decreasing sorted order by
size. This is irrelevant for the small bins, which all contain
the same-sized chunks, but facilitates best-fit allocation for
larger chunks. (These lists are just sequential. Keeping them in
order almost never requires enough traversal to warrant using
fancier ordered data structures.) Chunks of the same size are
linked with the most recently freed at the front, and allocations
are taken from the back. This results in LRU or FIFO allocation
order, which tends to give each chunk an equal opportunity to be
consolidated with adjacent freed chunks, resulting in larger free
chunks and less fragmentation.
* `top': The top-most available chunk (i.e., the one bordering the
end of available memory) is treated specially. It is never
included in any bin, is used only if no other chunk is
available, and is released back to the system if it is very
large (see M_TRIM_THRESHOLD).
* `last_remainder': A bin holding only the remainder of the
most recently split (non-top) chunk. This bin is checked
before other non-fitting chunks, so as to provide better
locality for runs of sequentially allocated chunks.
* Implicitly, through the host system's memory mapping tables.
If supported, requests greater than a threshold are usually
serviced via calls to mmap, and then later released via munmap.
*/
/* sizes, alignments */
#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
#define MALLOC_ALIGNMENT (SIZE_SZ + SIZE_SZ)
#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
#define MINSIZE (sizeof(struct malloc_chunk))
/* conversion from malloc headers to user pointers, and back */
#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))
#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
/* pad request bytes into a usable size */
#define request2size(req) \
(((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
(long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
(((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
/* Check if m has acceptable alignment */
#define aligned_OK(m) (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
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
/*
Physical chunk operations
*/
/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
#define PREV_INUSE 0x1
/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
#define IS_MMAPPED 0x2
/* Bits to mask off when extracting size */
#define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
/* Ptr to next physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
/* Ptr to previous physical malloc_chunk */
#define prev_chunk(p)\
((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
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
/*
Dealing with use bits
*/
/* extract p's inuse bit */
#define inuse(p)\
((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
/* extract inuse bit of previous chunk */
#define prev_inuse(p) ((p)->size & PREV_INUSE)
/* check for mmap()'ed chunk */
#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
/* set/clear chunk as in use without otherwise disturbing */
#define set_inuse(p)\
((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
#define clear_inuse(p)\
((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
/* check/set/clear inuse bits in known places */
#define inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
#define set_inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
#define clear_inuse_bit_at_offset(p, s)\
(((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
/*
Dealing with size fields
*/
/* Get size, ignoring use bits */
#define chunksize(p) ((p)->size & ~(SIZE_BITS))
/* Set size at head, without disturbing its use bit */
#define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))
/* Set size/use ignoring previous bits in header */
#define set_head(p, s) ((p)->size = (s))
/* Set size at footer (only when chunk is not in use) */
#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
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
/*
Bins
The bins, `av_' are an array of pairs of pointers serving as the
heads of (initially empty) doubly-linked lists of chunks, laid out
in a way so that each pair can be treated as if it were in a
malloc_chunk. (This way, the fd/bk offsets for linking bin heads
and chunks are the same).
Bins for sizes < 512 bytes contain chunks of all the same size, spaced
8 bytes apart. Larger bins are approximately logarithmically
spaced. (See the table below.) The `av_' array is never mentioned
directly in the code, but instead via bin access macros.
Bin layout:
64 bins of size 8
32 bins of size 64
16 bins of size 512
8 bins of size 4096
4 bins of size 32768
2 bins of size 262144
1 bin of size what's left
There is actually a little bit of slop in the numbers in bin_index
for the sake of speed. This makes no difference elsewhere.
The special chunks `top' and `last_remainder' get their own bins,
(this is implemented via yet more trickery with the av_ array),
although `top' is never properly linked to its bin since it is
always handled specially.
*/
#define NAV 128 /* number of bins */
typedef struct malloc_chunk* mbinptr;
/* access macros */
#define bin_at(i) ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
#define next_bin(b) ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
#define prev_bin(b) ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
/*
The first 2 bins are never indexed. The corresponding av_ cells are instead
used for bookkeeping. This is not to save space, but to simplify
indexing, maintain locality, and avoid some initialization tests.
*/
#define last_remainder (bin_at(1)) /* remainder from last split */
/*
Because top initially points to its own bin with initial
zero size, thus forcing extension on the first malloc request,
we avoid having any special code in malloc to check whether
it even exists yet. But we still need to in malloc_extend_top.
*/
#define initial_top ((mchunkptr)(bin_at(0)))
/* Helper macro to initialize bins */
#define IAV(i) bin_at(i), bin_at(i)
static mbinptr av_[NAV * 2 + 2] = {
IAV(0), IAV(1), IAV(2), IAV(3), IAV(4), IAV(5), IAV(6), IAV(7),
IAV(8), IAV(9), IAV(10), IAV(11), IAV(12), IAV(13), IAV(14), IAV(15),
IAV(16), IAV(17), IAV(18), IAV(19), IAV(20), IAV(21), IAV(22), IAV(23),
IAV(24), IAV(25), IAV(26), IAV(27), IAV(28), IAV(29), IAV(30), IAV(31),
IAV(32), IAV(33), IAV(34), IAV(35), IAV(36), IAV(37), IAV(38), IAV(39),
IAV(40), IAV(41), IAV(42), IAV(43), IAV(44), IAV(45), IAV(46), IAV(47),
IAV(48), IAV(49), IAV(50), IAV(51), IAV(52), IAV(53), IAV(54), IAV(55),
IAV(56), IAV(57), IAV(58), IAV(59), IAV(60), IAV(61), IAV(62), IAV(63),
IAV(64), IAV(65), IAV(66), IAV(67), IAV(68), IAV(69), IAV(70), IAV(71),
IAV(72), IAV(73), IAV(74), IAV(75), IAV(76), IAV(77), IAV(78), IAV(79),
IAV(80), IAV(81), IAV(82), IAV(83), IAV(84), IAV(85), IAV(86), IAV(87),
IAV(88), IAV(89), IAV(90), IAV(91), IAV(92), IAV(93), IAV(94), IAV(95),
IAV(96), IAV(97), IAV(98), IAV(99), IAV(100), IAV(101), IAV(102), IAV(103),
IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
};
#ifdef CONFIG_NEEDS_MANUAL_RELOC
mbinptr *p = &av_[2];
size_t i;
for (i = 2; i < ARRAY_SIZE(av_); ++i, ++p)
*p = (mbinptr)((ulong)*p + gd->reloc_off);
#else
static inline void malloc_bin_reloc(void) {}
ulong mem_malloc_start = 0;
ulong mem_malloc_end = 0;
ulong mem_malloc_brk = 0;
void *sbrk(ptrdiff_t increment)
{
ulong old = mem_malloc_brk;
ulong new = old + increment;
/*
* if we are giving memory back make sure we clear it out since
* we set MORECORE_CLEARS to 1
*/
if (increment < 0)
memset((void *)new, 0, -increment);
if ((new < mem_malloc_start) || (new > mem_malloc_end))
karl.beldan@gmail.com
committed
return (void *)MORECORE_FAILURE;
mem_malloc_brk = new;
return (void *)old;
}
void mem_malloc_init(ulong start, ulong size)
{
mem_malloc_start = start;
mem_malloc_end = start + size;
mem_malloc_brk = start;
debug("using memory %#lx-%#lx for malloc()\n", mem_malloc_start,
mem_malloc_end);
#ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
memset((void *)mem_malloc_start, 0x0, size);
#endif
/* field-extraction macros */
#define first(b) ((b)->fd)
#define last(b) ((b)->bk)
/*
Indexing into bins
*/
#define bin_index(sz) \
(((((unsigned long)(sz)) >> 9) == 0) ? (((unsigned long)(sz)) >> 3): \
((((unsigned long)(sz)) >> 9) <= 4) ? 56 + (((unsigned long)(sz)) >> 6): \
((((unsigned long)(sz)) >> 9) <= 20) ? 91 + (((unsigned long)(sz)) >> 9): \
((((unsigned long)(sz)) >> 9) <= 84) ? 110 + (((unsigned long)(sz)) >> 12): \
((((unsigned long)(sz)) >> 9) <= 340) ? 119 + (((unsigned long)(sz)) >> 15): \
((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
/*
bins for chunks < 512 are all spaced 8 bytes apart, and hold
identically sized chunks. This is exploited in malloc.
*/
#define MAX_SMALLBIN 63
#define MAX_SMALLBIN_SIZE 512
#define SMALLBIN_WIDTH 8
#define smallbin_index(sz) (((unsigned long)(sz)) >> 3)
/*
Requests are `small' if both the corresponding and the next bin are small
*/
#define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
/*
To help compensate for the large number of bins, a one-level index
structure is used for bin-by-bin searching. `binblocks' is a
one-word bitvector recording whether groups of BINBLOCKWIDTH bins
have any (possibly) non-empty bins, so they can be skipped over
all at once during during traversals. The bits are NOT always
cleared as soon as all bins in a block are empty, but instead only
when all are noticed to be empty during traversal in malloc.
*/
#define BINBLOCKWIDTH 4 /* bins per block */
#define binblocks_r ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
#define binblocks_w (av_[1])
/* bin<->block macros */
#define idx2binblock(ix) ((unsigned)1 << (ix / BINBLOCKWIDTH))
#define mark_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
#define clear_binblock(ii) (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
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
/* Other static bookkeeping data */
/* variables holding tunable values */
static unsigned long trim_threshold = DEFAULT_TRIM_THRESHOLD;
static unsigned long top_pad = DEFAULT_TOP_PAD;
static unsigned int n_mmaps_max = DEFAULT_MMAP_MAX;
static unsigned long mmap_threshold = DEFAULT_MMAP_THRESHOLD;
/* The first value returned from sbrk */
static char* sbrk_base = (char*)(-1);
/* The maximum memory obtained from system via sbrk */
static unsigned long max_sbrked_mem = 0;
/* The maximum via either sbrk or mmap */
static unsigned long max_total_mem = 0;
/* internal working copy of mallinfo */
static struct mallinfo current_mallinfo = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/* The total memory obtained from system via sbrk */
#define sbrked_mem (current_mallinfo.arena)
/* Tracking mmaps */
#ifdef DEBUG
#endif /* DEBUG */
static unsigned long mmapped_mem = 0;
#if HAVE_MMAP
static unsigned int max_n_mmaps = 0;
static unsigned long max_mmapped_mem = 0;
#endif
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
/*
Debugging support
*/
#ifdef DEBUG
/*
These routines make a number of assertions about the states
of data structures that should be true at all times. If any
are not true, it's very likely that a user program has somehow
trashed memory. (It's also possible that there is a coding error
in malloc. In which case, please report it!)
*/
#if __STD_C
static void do_check_chunk(mchunkptr p)
#else
static void do_check_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
/* No checkable chunk is mmapped */
assert(!chunk_is_mmapped(p));
/* Check for legal address ... */
assert((char*)p >= sbrk_base);
if (p != top)
assert((char*)p + sz <= (char*)top);
else
assert((char*)p + sz <= sbrk_base + sbrked_mem);
}
#if __STD_C
static void do_check_free_chunk(mchunkptr p)
#else
static void do_check_free_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
mchunkptr next = chunk_at_offset(p, sz);
do_check_chunk(p);
/* Check whether it claims to be free ... */
assert(!inuse(p));
/* Unless a special marker, must have OK fields */
if ((long)sz >= (long)MINSIZE)
{
assert((sz & MALLOC_ALIGN_MASK) == 0);
assert(aligned_OK(chunk2mem(p)));
/* ... matching footer field */
assert(next->prev_size == sz);
/* ... and is fully consolidated */
assert(prev_inuse(p));
assert (next == top || inuse(next));
/* ... and has minimally sane links */
assert(p->fd->bk == p);
assert(p->bk->fd == p);
}
else /* markers are always of size SIZE_SZ */
assert(sz == SIZE_SZ);
}
#if __STD_C
static void do_check_inuse_chunk(mchunkptr p)
#else
static void do_check_inuse_chunk(p) mchunkptr p;
#endif
{
mchunkptr next = next_chunk(p);
do_check_chunk(p);
/* Check whether it claims to be in use ... */
assert(inuse(p));
/* ... and is surrounded by OK chunks.
Since more things can be checked with free chunks than inuse ones,
if an inuse chunk borders them and debug is on, it's worth doing them.
*/
if (!prev_inuse(p))
{
mchunkptr prv = prev_chunk(p);
assert(next_chunk(prv) == p);
do_check_free_chunk(prv);
}
if (next == top)
{
assert(prev_inuse(next));
assert(chunksize(next) >= MINSIZE);
}
else if (!inuse(next))
do_check_free_chunk(next);
}
#if __STD_C
static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
#else
static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
#endif
{
INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
long room = sz - s;
do_check_inuse_chunk(p);
/* Legal size ... */
assert((long)sz >= (long)MINSIZE);
assert((sz & MALLOC_ALIGN_MASK) == 0);
assert(room >= 0);
assert(room < (long)MINSIZE);
/* ... and alignment */
assert(aligned_OK(chunk2mem(p)));
/* ... and was allocated at front of an available chunk */
assert(prev_inuse(p));
}
#define check_free_chunk(P) do_check_free_chunk(P)
#define check_inuse_chunk(P) do_check_inuse_chunk(P)
#define check_chunk(P) do_check_chunk(P)
#define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
#else
#define check_free_chunk(P)
#define check_inuse_chunk(P)
#define check_chunk(P)
#define check_malloced_chunk(P,N)
#endif
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
/*
Macro-based internal utilities
*/
/*
Linking chunks in bin lists.
Call these only with variables, not arbitrary expressions, as arguments.
*/
/*
Place chunk p of size s in its bin, in size order,
putting it ahead of others of same size.
*/
#define frontlink(P, S, IDX, BK, FD) \
{ \
if (S < MAX_SMALLBIN_SIZE) \
{ \
IDX = smallbin_index(S); \
mark_binblock(IDX); \
BK = bin_at(IDX); \
FD = BK->fd; \
P->bk = BK; \
P->fd = FD; \
FD->bk = BK->fd = P; \
} \
else \
{ \
IDX = bin_index(S); \
BK = bin_at(IDX); \
FD = BK->fd; \
if (FD == BK) mark_binblock(IDX); \
else \
{ \
while (FD != BK && S < chunksize(FD)) FD = FD->fd; \
BK = FD->bk; \
} \
P->bk = BK; \
P->fd = FD; \
FD->bk = BK->fd = P; \
} \
}
/* take a chunk off a list */
#define unlink(P, BK, FD) \
{ \
BK = P->bk; \
FD = P->fd; \
FD->bk = BK; \
BK->fd = FD; \
} \
/* Place p as the last remainder */
#define link_last_remainder(P) \
{ \
last_remainder->fd = last_remainder->bk = P; \
P->fd = P->bk = last_remainder; \
}
/* Clear the last_remainder bin */
#define clear_last_remainder \
(last_remainder->fd = last_remainder->bk = last_remainder)
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
/* Routines dealing with mmap(). */
#if HAVE_MMAP
#if __STD_C
static mchunkptr mmap_chunk(size_t size)
#else
static mchunkptr mmap_chunk(size) size_t size;
#endif
{
size_t page_mask = malloc_getpagesize - 1;
mchunkptr p;
#ifndef MAP_ANONYMOUS
static int fd = -1;
#endif
if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
/* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
* there is no following chunk whose prev_size field could be used.
*/
size = (size + SIZE_SZ + page_mask) & ~page_mask;
#ifdef MAP_ANONYMOUS
p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
#else /* !MAP_ANONYMOUS */
if (fd < 0)
{
fd = open("/dev/zero", O_RDWR);
if(fd < 0) return 0;
}
p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
#endif
if(p == (mchunkptr)-1) return 0;
n_mmaps++;
if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
/* We demand that eight bytes into a page must be 8-byte aligned. */
assert(aligned_OK(chunk2mem(p)));
/* The offset to the start of the mmapped region is stored
* in the prev_size field of the chunk; normally it is zero,
* but that can be changed in memalign().
*/
p->prev_size = 0;
set_head(p, size|IS_MMAPPED);
mmapped_mem += size;
if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
max_mmapped_mem = mmapped_mem;
if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
max_total_mem = mmapped_mem + sbrked_mem;
return p;
}
#if __STD_C
static void munmap_chunk(mchunkptr p)
#else
static void munmap_chunk(p) mchunkptr p;
#endif
{
INTERNAL_SIZE_T size = chunksize(p);
int ret;
assert (chunk_is_mmapped(p));
assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
assert((n_mmaps > 0));
assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
n_mmaps--;