ata: sata_sil: Remove useless BLK guard in sata_sil.h
[platform/kernel/u-boot.git] / common / dlmalloc.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * This code is based on a version (aka dlmalloc) of malloc/free/realloc written
4  * by Doug Lea and released to the public domain, as explained at
5  * http://creativecommons.org/publicdomain/zero/1.0/-
6  *
7  * The original code is available at http://gee.cs.oswego.edu/pub/misc/
8  * as file malloc-2.6.6.c.
9  */
10
11 #include <common.h>
12 #include <log.h>
13 #include <asm/global_data.h>
14
15 #if CONFIG_IS_ENABLED(UNIT_TEST)
16 #define DEBUG
17 #endif
18
19 #include <malloc.h>
20 #include <asm/io.h>
21 #include <valgrind/memcheck.h>
22
23 #ifdef DEBUG
24 #if __STD_C
25 static void malloc_update_mallinfo (void);
26 void malloc_stats (void);
27 #else
28 static void malloc_update_mallinfo ();
29 void malloc_stats();
30 #endif
31 #endif  /* DEBUG */
32
33 DECLARE_GLOBAL_DATA_PTR;
34
35 /*
36   Emulation of sbrk for WIN32
37   All code within the ifdef WIN32 is untested by me.
38
39   Thanks to Martin Fong and others for supplying this.
40 */
41
42
43 #ifdef WIN32
44
45 #define AlignPage(add) (((add) + (malloc_getpagesize-1)) & \
46 ~(malloc_getpagesize-1))
47 #define AlignPage64K(add) (((add) + (0x10000 - 1)) & ~(0x10000 - 1))
48
49 /* resrve 64MB to insure large contiguous space */
50 #define RESERVED_SIZE (1024*1024*64)
51 #define NEXT_SIZE (2048*1024)
52 #define TOP_MEMORY ((unsigned long)2*1024*1024*1024)
53
54 struct GmListElement;
55 typedef struct GmListElement GmListElement;
56
57 struct GmListElement
58 {
59         GmListElement* next;
60         void* base;
61 };
62
63 static GmListElement* head = 0;
64 static unsigned int gNextAddress = 0;
65 static unsigned int gAddressBase = 0;
66 static unsigned int gAllocatedSize = 0;
67
68 static
69 GmListElement* makeGmListElement (void* bas)
70 {
71         GmListElement* this;
72         this = (GmListElement*)(void*)LocalAlloc (0, sizeof (GmListElement));
73         assert (this);
74         if (this)
75         {
76                 this->base = bas;
77                 this->next = head;
78                 head = this;
79         }
80         return this;
81 }
82
83 void gcleanup ()
84 {
85         BOOL rval;
86         assert ( (head == NULL) || (head->base == (void*)gAddressBase));
87         if (gAddressBase && (gNextAddress - gAddressBase))
88         {
89                 rval = VirtualFree ((void*)gAddressBase,
90                                                         gNextAddress - gAddressBase,
91                                                         MEM_DECOMMIT);
92         assert (rval);
93         }
94         while (head)
95         {
96                 GmListElement* next = head->next;
97                 rval = VirtualFree (head->base, 0, MEM_RELEASE);
98                 assert (rval);
99                 LocalFree (head);
100                 head = next;
101         }
102 }
103
104 static
105 void* findRegion (void* start_address, unsigned long size)
106 {
107         MEMORY_BASIC_INFORMATION info;
108         if (size >= TOP_MEMORY) return NULL;
109
110         while ((unsigned long)start_address + size < TOP_MEMORY)
111         {
112                 VirtualQuery (start_address, &info, sizeof (info));
113                 if ((info.State == MEM_FREE) && (info.RegionSize >= size))
114                         return start_address;
115                 else
116                 {
117                         /* Requested region is not available so see if the */
118                         /* next region is available.  Set 'start_address' */
119                         /* to the next region and call 'VirtualQuery()' */
120                         /* again. */
121
122                         start_address = (char*)info.BaseAddress + info.RegionSize;
123
124                         /* Make sure we start looking for the next region */
125                         /* on the *next* 64K boundary.  Otherwise, even if */
126                         /* the new region is free according to */
127                         /* 'VirtualQuery()', the subsequent call to */
128                         /* 'VirtualAlloc()' (which follows the call to */
129                         /* this routine in 'wsbrk()') will round *down* */
130                         /* the requested address to a 64K boundary which */
131                         /* we already know is an address in the */
132                         /* unavailable region.  Thus, the subsequent call */
133                         /* to 'VirtualAlloc()' will fail and bring us back */
134                         /* here, causing us to go into an infinite loop. */
135
136                         start_address =
137                                 (void *) AlignPage64K((unsigned long) start_address);
138                 }
139         }
140         return NULL;
141
142 }
143
144
145 void* wsbrk (long size)
146 {
147         void* tmp;
148         if (size > 0)
149         {
150                 if (gAddressBase == 0)
151                 {
152                         gAllocatedSize = max (RESERVED_SIZE, AlignPage (size));
153                         gNextAddress = gAddressBase =
154                                 (unsigned int)VirtualAlloc (NULL, gAllocatedSize,
155                                                                                         MEM_RESERVE, PAGE_NOACCESS);
156                 } else if (AlignPage (gNextAddress + size) > (gAddressBase +
157 gAllocatedSize))
158                 {
159                         long new_size = max (NEXT_SIZE, AlignPage (size));
160                         void* new_address = (void*)(gAddressBase+gAllocatedSize);
161                         do
162                         {
163                                 new_address = findRegion (new_address, new_size);
164
165                                 if (!new_address)
166                                         return (void*)-1;
167
168                                 gAddressBase = gNextAddress =
169                                         (unsigned int)VirtualAlloc (new_address, new_size,
170                                                                                                 MEM_RESERVE, PAGE_NOACCESS);
171                                 /* repeat in case of race condition */
172                                 /* The region that we found has been snagged */
173                                 /* by another thread */
174                         }
175                         while (gAddressBase == 0);
176
177                         assert (new_address == (void*)gAddressBase);
178
179                         gAllocatedSize = new_size;
180
181                         if (!makeGmListElement ((void*)gAddressBase))
182                                 return (void*)-1;
183                 }
184                 if ((size + gNextAddress) > AlignPage (gNextAddress))
185                 {
186                         void* res;
187                         res = VirtualAlloc ((void*)AlignPage (gNextAddress),
188                                                                 (size + gNextAddress -
189                                                                  AlignPage (gNextAddress)),
190                                                                 MEM_COMMIT, PAGE_READWRITE);
191                         if (!res)
192                                 return (void*)-1;
193                 }
194                 tmp = (void*)gNextAddress;
195                 gNextAddress = (unsigned int)tmp + size;
196                 return tmp;
197         }
198         else if (size < 0)
199         {
200                 unsigned int alignedGoal = AlignPage (gNextAddress + size);
201                 /* Trim by releasing the virtual memory */
202                 if (alignedGoal >= gAddressBase)
203                 {
204                         VirtualFree ((void*)alignedGoal, gNextAddress - alignedGoal,
205                                                  MEM_DECOMMIT);
206                         gNextAddress = gNextAddress + size;
207                         return (void*)gNextAddress;
208                 }
209                 else
210                 {
211                         VirtualFree ((void*)gAddressBase, gNextAddress - gAddressBase,
212                                                  MEM_DECOMMIT);
213                         gNextAddress = gAddressBase;
214                         return (void*)-1;
215                 }
216         }
217         else
218         {
219                 return (void*)gNextAddress;
220         }
221 }
222
223 #endif
224
225
226
227 /*
228   Type declarations
229 */
230
231
232 struct malloc_chunk
233 {
234   INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
235   INTERNAL_SIZE_T size;      /* Size in bytes, including overhead. */
236   struct malloc_chunk* fd;   /* double links -- used only if free. */
237   struct malloc_chunk* bk;
238 } __attribute__((__may_alias__)) ;
239
240 typedef struct malloc_chunk* mchunkptr;
241
242 /*
243
244    malloc_chunk details:
245
246     (The following includes lightly edited explanations by Colin Plumb.)
247
248     Chunks of memory are maintained using a `boundary tag' method as
249     described in e.g., Knuth or Standish.  (See the paper by Paul
250     Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
251     survey of such techniques.)  Sizes of free chunks are stored both
252     in the front of each chunk and at the end.  This makes
253     consolidating fragmented chunks into bigger chunks very fast.  The
254     size fields also hold bits representing whether chunks are free or
255     in use.
256
257     An allocated chunk looks like this:
258
259
260     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
261             |             Size of previous chunk, if allocated            | |
262             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
263             |             Size of chunk, in bytes                         |P|
264       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
265             |             User data starts here...                          .
266             .                                                               .
267             .             (malloc_usable_space() bytes)                     .
268             .                                                               |
269 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
270             |             Size of chunk                                     |
271             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
272
273
274     Where "chunk" is the front of the chunk for the purpose of most of
275     the malloc code, but "mem" is the pointer that is returned to the
276     user.  "Nextchunk" is the beginning of the next contiguous chunk.
277
278     Chunks always begin on even word boundries, so the mem portion
279     (which is returned to the user) is also on an even word boundary, and
280     thus double-word aligned.
281
282     Free chunks are stored in circular doubly-linked lists, and look like this:
283
284     chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
285             |             Size of previous chunk                            |
286             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
287     `head:' |             Size of chunk, in bytes                         |P|
288       mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
289             |             Forward pointer to next chunk in list             |
290             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
291             |             Back pointer to previous chunk in list            |
292             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
293             |             Unused space (may be 0 bytes long)                .
294             .                                                               .
295             .                                                               |
296
297 nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
298     `foot:' |             Size of chunk, in bytes                           |
299             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
300
301     The P (PREV_INUSE) bit, stored in the unused low-order bit of the
302     chunk size (which is always a multiple of two words), is an in-use
303     bit for the *previous* chunk.  If that bit is *clear*, then the
304     word before the current chunk size contains the previous chunk
305     size, and can be used to find the front of the previous chunk.
306     (The very first chunk allocated always has this bit set,
307     preventing access to non-existent (or non-owned) memory.)
308
309     Note that the `foot' of the current chunk is actually represented
310     as the prev_size of the NEXT chunk. (This makes it easier to
311     deal with alignments etc).
312
313     The two exceptions to all this are
314
315      1. The special chunk `top', which doesn't bother using the
316         trailing size field since there is no
317         next contiguous chunk that would have to index off it. (After
318         initialization, `top' is forced to always exist.  If it would
319         become less than MINSIZE bytes long, it is replenished via
320         malloc_extend_top.)
321
322      2. Chunks allocated via mmap, which have the second-lowest-order
323         bit (IS_MMAPPED) set in their size fields.  Because they are
324         never merged or traversed from any other chunk, they have no
325         foot size or inuse information.
326
327     Available chunks are kept in any of several places (all declared below):
328
329     * `av': An array of chunks serving as bin headers for consolidated
330        chunks. Each bin is doubly linked.  The bins are approximately
331        proportionally (log) spaced.  There are a lot of these bins
332        (128). This may look excessive, but works very well in
333        practice.  All procedures maintain the invariant that no
334        consolidated chunk physically borders another one. Chunks in
335        bins are kept in size order, with ties going to the
336        approximately least recently used chunk.
337
338        The chunks in each bin are maintained in decreasing sorted order by
339        size.  This is irrelevant for the small bins, which all contain
340        the same-sized chunks, but facilitates best-fit allocation for
341        larger chunks. (These lists are just sequential. Keeping them in
342        order almost never requires enough traversal to warrant using
343        fancier ordered data structures.)  Chunks of the same size are
344        linked with the most recently freed at the front, and allocations
345        are taken from the back.  This results in LRU or FIFO allocation
346        order, which tends to give each chunk an equal opportunity to be
347        consolidated with adjacent freed chunks, resulting in larger free
348        chunks and less fragmentation.
349
350     * `top': The top-most available chunk (i.e., the one bordering the
351        end of available memory) is treated specially. It is never
352        included in any bin, is used only if no other chunk is
353        available, and is released back to the system if it is very
354        large (see M_TRIM_THRESHOLD).
355
356     * `last_remainder': A bin holding only the remainder of the
357        most recently split (non-top) chunk. This bin is checked
358        before other non-fitting chunks, so as to provide better
359        locality for runs of sequentially allocated chunks.
360
361     *  Implicitly, through the host system's memory mapping tables.
362        If supported, requests greater than a threshold are usually
363        serviced via calls to mmap, and then later released via munmap.
364
365 */
366
367 /*  sizes, alignments */
368
369 #define SIZE_SZ                (sizeof(INTERNAL_SIZE_T))
370 #define MALLOC_ALIGNMENT       (SIZE_SZ + SIZE_SZ)
371 #define MALLOC_ALIGN_MASK      (MALLOC_ALIGNMENT - 1)
372 #define MINSIZE                (sizeof(struct malloc_chunk))
373
374 /* conversion from malloc headers to user pointers, and back */
375
376 #define chunk2mem(p)   ((Void_t*)((char*)(p) + 2*SIZE_SZ))
377 #define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
378
379 /* pad request bytes into a usable size */
380
381 #define request2size(req) \
382  (((long)((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) < \
383   (long)(MINSIZE + MALLOC_ALIGN_MASK)) ? MINSIZE : \
384    (((req) + (SIZE_SZ + MALLOC_ALIGN_MASK)) & ~(MALLOC_ALIGN_MASK)))
385
386 /* Check if m has acceptable alignment */
387
388 #define aligned_OK(m)    (((unsigned long)((m)) & (MALLOC_ALIGN_MASK)) == 0)
389
390
391
392
393 /*
394   Physical chunk operations
395 */
396
397
398 /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
399
400 #define PREV_INUSE 0x1
401
402 /* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
403
404 #define IS_MMAPPED 0x2
405
406 /* Bits to mask off when extracting size */
407
408 #define SIZE_BITS (PREV_INUSE|IS_MMAPPED)
409
410
411 /* Ptr to next physical malloc_chunk. */
412
413 #define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))
414
415 /* Ptr to previous physical malloc_chunk */
416
417 #define prev_chunk(p)\
418    ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))
419
420
421 /* Treat space at ptr + offset as a chunk */
422
423 #define chunk_at_offset(p, s)  ((mchunkptr)(((char*)(p)) + (s)))
424
425
426
427
428 /*
429   Dealing with use bits
430 */
431
432 /* extract p's inuse bit */
433
434 #define inuse(p)\
435 ((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)
436
437 /* extract inuse bit of previous chunk */
438
439 #define prev_inuse(p)  ((p)->size & PREV_INUSE)
440
441 /* check for mmap()'ed chunk */
442
443 #define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)
444
445 /* set/clear chunk as in use without otherwise disturbing */
446
447 #define set_inuse(p)\
448 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE
449
450 #define clear_inuse(p)\
451 ((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)
452
453 /* check/set/clear inuse bits in known places */
454
455 #define inuse_bit_at_offset(p, s)\
456  (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)
457
458 #define set_inuse_bit_at_offset(p, s)\
459  (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)
460
461 #define clear_inuse_bit_at_offset(p, s)\
462  (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))
463
464
465
466
467 /*
468   Dealing with size fields
469 */
470
471 /* Get size, ignoring use bits */
472
473 #define chunksize(p)          ((p)->size & ~(SIZE_BITS))
474
475 /* Set size at head, without disturbing its use bit */
476
477 #define set_head_size(p, s)   ((p)->size = (((p)->size & PREV_INUSE) | (s)))
478
479 /* Set size/use ignoring previous bits in header */
480
481 #define set_head(p, s)        ((p)->size = (s))
482
483 /* Set size at footer (only when chunk is not in use) */
484
485 #define set_foot(p, s)   (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))
486
487
488
489
490
491 /*
492    Bins
493
494     The bins, `av_' are an array of pairs of pointers serving as the
495     heads of (initially empty) doubly-linked lists of chunks, laid out
496     in a way so that each pair can be treated as if it were in a
497     malloc_chunk. (This way, the fd/bk offsets for linking bin heads
498     and chunks are the same).
499
500     Bins for sizes < 512 bytes contain chunks of all the same size, spaced
501     8 bytes apart. Larger bins are approximately logarithmically
502     spaced. (See the table below.) The `av_' array is never mentioned
503     directly in the code, but instead via bin access macros.
504
505     Bin layout:
506
507     64 bins of size       8
508     32 bins of size      64
509     16 bins of size     512
510      8 bins of size    4096
511      4 bins of size   32768
512      2 bins of size  262144
513      1 bin  of size what's left
514
515     There is actually a little bit of slop in the numbers in bin_index
516     for the sake of speed. This makes no difference elsewhere.
517
518     The special chunks `top' and `last_remainder' get their own bins,
519     (this is implemented via yet more trickery with the av_ array),
520     although `top' is never properly linked to its bin since it is
521     always handled specially.
522
523 */
524
525 #define NAV             128   /* number of bins */
526
527 typedef struct malloc_chunk* mbinptr;
528
529 /* access macros */
530
531 #define bin_at(i)      ((mbinptr)((char*)&(av_[2*(i) + 2]) - 2*SIZE_SZ))
532 #define next_bin(b)    ((mbinptr)((char*)(b) + 2 * sizeof(mbinptr)))
533 #define prev_bin(b)    ((mbinptr)((char*)(b) - 2 * sizeof(mbinptr)))
534
535 /*
536    The first 2 bins are never indexed. The corresponding av_ cells are instead
537    used for bookkeeping. This is not to save space, but to simplify
538    indexing, maintain locality, and avoid some initialization tests.
539 */
540
541 #define top            (av_[2])          /* The topmost chunk */
542 #define last_remainder (bin_at(1))       /* remainder from last split */
543
544
545 /*
546    Because top initially points to its own bin with initial
547    zero size, thus forcing extension on the first malloc request,
548    we avoid having any special code in malloc to check whether
549    it even exists yet. But we still need to in malloc_extend_top.
550 */
551
552 #define initial_top    ((mchunkptr)(bin_at(0)))
553
554 /* Helper macro to initialize bins */
555
556 #define IAV(i)  bin_at(i), bin_at(i)
557
558 static mbinptr av_[NAV * 2 + 2] = {
559  NULL, NULL,
560  IAV(0),   IAV(1),   IAV(2),   IAV(3),   IAV(4),   IAV(5),   IAV(6),   IAV(7),
561  IAV(8),   IAV(9),   IAV(10),  IAV(11),  IAV(12),  IAV(13),  IAV(14),  IAV(15),
562  IAV(16),  IAV(17),  IAV(18),  IAV(19),  IAV(20),  IAV(21),  IAV(22),  IAV(23),
563  IAV(24),  IAV(25),  IAV(26),  IAV(27),  IAV(28),  IAV(29),  IAV(30),  IAV(31),
564  IAV(32),  IAV(33),  IAV(34),  IAV(35),  IAV(36),  IAV(37),  IAV(38),  IAV(39),
565  IAV(40),  IAV(41),  IAV(42),  IAV(43),  IAV(44),  IAV(45),  IAV(46),  IAV(47),
566  IAV(48),  IAV(49),  IAV(50),  IAV(51),  IAV(52),  IAV(53),  IAV(54),  IAV(55),
567  IAV(56),  IAV(57),  IAV(58),  IAV(59),  IAV(60),  IAV(61),  IAV(62),  IAV(63),
568  IAV(64),  IAV(65),  IAV(66),  IAV(67),  IAV(68),  IAV(69),  IAV(70),  IAV(71),
569  IAV(72),  IAV(73),  IAV(74),  IAV(75),  IAV(76),  IAV(77),  IAV(78),  IAV(79),
570  IAV(80),  IAV(81),  IAV(82),  IAV(83),  IAV(84),  IAV(85),  IAV(86),  IAV(87),
571  IAV(88),  IAV(89),  IAV(90),  IAV(91),  IAV(92),  IAV(93),  IAV(94),  IAV(95),
572  IAV(96),  IAV(97),  IAV(98),  IAV(99),  IAV(100), IAV(101), IAV(102), IAV(103),
573  IAV(104), IAV(105), IAV(106), IAV(107), IAV(108), IAV(109), IAV(110), IAV(111),
574  IAV(112), IAV(113), IAV(114), IAV(115), IAV(116), IAV(117), IAV(118), IAV(119),
575  IAV(120), IAV(121), IAV(122), IAV(123), IAV(124), IAV(125), IAV(126), IAV(127)
576 };
577
578 #ifdef CONFIG_NEEDS_MANUAL_RELOC
579 static void malloc_bin_reloc(void)
580 {
581         mbinptr *p = &av_[2];
582         size_t i;
583
584         for (i = 2; i < ARRAY_SIZE(av_); ++i, ++p)
585                 *p = (mbinptr)((ulong)*p + gd->reloc_off);
586 }
587 #else
588 static inline void malloc_bin_reloc(void) {}
589 #endif
590
591 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
592 static void malloc_init(void);
593 #endif
594
595 ulong mem_malloc_start = 0;
596 ulong mem_malloc_end = 0;
597 ulong mem_malloc_brk = 0;
598
599 void *sbrk(ptrdiff_t increment)
600 {
601         ulong old = mem_malloc_brk;
602         ulong new = old + increment;
603
604         /*
605          * if we are giving memory back make sure we clear it out since
606          * we set MORECORE_CLEARS to 1
607          */
608         if (increment < 0)
609                 memset((void *)new, 0, -increment);
610
611         if ((new < mem_malloc_start) || (new > mem_malloc_end))
612                 return (void *)MORECORE_FAILURE;
613
614         mem_malloc_brk = new;
615
616         return (void *)old;
617 }
618
619 void mem_malloc_init(ulong start, ulong size)
620 {
621         mem_malloc_start = start;
622         mem_malloc_end = start + size;
623         mem_malloc_brk = start;
624
625 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
626         malloc_init();
627 #endif
628
629         debug("using memory %#lx-%#lx for malloc()\n", mem_malloc_start,
630               mem_malloc_end);
631 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
632         memset((void *)mem_malloc_start, 0x0, size);
633 #endif
634         malloc_bin_reloc();
635 }
636
637 /* field-extraction macros */
638
639 #define first(b) ((b)->fd)
640 #define last(b)  ((b)->bk)
641
642 /*
643   Indexing into bins
644 */
645
646 #define bin_index(sz)                                                          \
647 (((((unsigned long)(sz)) >> 9) ==    0) ?       (((unsigned long)(sz)) >>  3): \
648  ((((unsigned long)(sz)) >> 9) <=    4) ?  56 + (((unsigned long)(sz)) >>  6): \
649  ((((unsigned long)(sz)) >> 9) <=   20) ?  91 + (((unsigned long)(sz)) >>  9): \
650  ((((unsigned long)(sz)) >> 9) <=   84) ? 110 + (((unsigned long)(sz)) >> 12): \
651  ((((unsigned long)(sz)) >> 9) <=  340) ? 119 + (((unsigned long)(sz)) >> 15): \
652  ((((unsigned long)(sz)) >> 9) <= 1364) ? 124 + (((unsigned long)(sz)) >> 18): \
653                                           126)
654 /*
655   bins for chunks < 512 are all spaced 8 bytes apart, and hold
656   identically sized chunks. This is exploited in malloc.
657 */
658
659 #define MAX_SMALLBIN         63
660 #define MAX_SMALLBIN_SIZE   512
661 #define SMALLBIN_WIDTH        8
662
663 #define smallbin_index(sz)  (((unsigned long)(sz)) >> 3)
664
665 /*
666    Requests are `small' if both the corresponding and the next bin are small
667 */
668
669 #define is_small_request(nb) (nb < MAX_SMALLBIN_SIZE - SMALLBIN_WIDTH)
670
671
672
673 /*
674     To help compensate for the large number of bins, a one-level index
675     structure is used for bin-by-bin searching.  `binblocks' is a
676     one-word bitvector recording whether groups of BINBLOCKWIDTH bins
677     have any (possibly) non-empty bins, so they can be skipped over
678     all at once during during traversals. The bits are NOT always
679     cleared as soon as all bins in a block are empty, but instead only
680     when all are noticed to be empty during traversal in malloc.
681 */
682
683 #define BINBLOCKWIDTH     4   /* bins per block */
684
685 #define binblocks_r     ((INTERNAL_SIZE_T)av_[1]) /* bitvector of nonempty blocks */
686 #define binblocks_w     (av_[1])
687
688 /* bin<->block macros */
689
690 #define idx2binblock(ix)    ((unsigned)1 << (ix / BINBLOCKWIDTH))
691 #define mark_binblock(ii)   (binblocks_w = (mbinptr)(binblocks_r | idx2binblock(ii)))
692 #define clear_binblock(ii)  (binblocks_w = (mbinptr)(binblocks_r & ~(idx2binblock(ii))))
693
694
695
696
697
698 /*  Other static bookkeeping data */
699
700 /* variables holding tunable values */
701
702 static unsigned long trim_threshold   = DEFAULT_TRIM_THRESHOLD;
703 static unsigned long top_pad          = DEFAULT_TOP_PAD;
704 static unsigned int  n_mmaps_max      = DEFAULT_MMAP_MAX;
705 static unsigned long mmap_threshold   = DEFAULT_MMAP_THRESHOLD;
706
707 /* The first value returned from sbrk */
708 static char* sbrk_base = (char*)(-1);
709
710 /* The maximum memory obtained from system via sbrk */
711 static unsigned long max_sbrked_mem = 0;
712
713 /* The maximum via either sbrk or mmap */
714 static unsigned long max_total_mem = 0;
715
716 /* internal working copy of mallinfo */
717 static struct mallinfo current_mallinfo = {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
718
719 /* The total memory obtained from system via sbrk */
720 #define sbrked_mem  (current_mallinfo.arena)
721
722 /* Tracking mmaps */
723
724 #ifdef DEBUG
725 static unsigned int n_mmaps = 0;
726 #endif  /* DEBUG */
727 static unsigned long mmapped_mem = 0;
728 #if HAVE_MMAP
729 static unsigned int max_n_mmaps = 0;
730 static unsigned long max_mmapped_mem = 0;
731 #endif
732
733 #ifdef CONFIG_SYS_MALLOC_DEFAULT_TO_INIT
734 static void malloc_init(void)
735 {
736         int i, j;
737
738         debug("bins (av_ array) are at %p\n", (void *)av_);
739
740         av_[0] = NULL; av_[1] = NULL;
741         for (i = 2, j = 2; i < NAV * 2 + 2; i += 2, j++) {
742                 av_[i] = bin_at(j - 2);
743                 av_[i + 1] = bin_at(j - 2);
744
745                 /* Just print the first few bins so that
746                  * we can see there are alright.
747                  */
748                 if (i < 10)
749                         debug("av_[%d]=%lx av_[%d]=%lx\n",
750                               i, (ulong)av_[i],
751                               i + 1, (ulong)av_[i + 1]);
752         }
753
754         /* Init the static bookkeeping as well */
755         sbrk_base = (char *)(-1);
756         max_sbrked_mem = 0;
757         max_total_mem = 0;
758 #ifdef DEBUG
759         memset((void *)&current_mallinfo, 0, sizeof(struct mallinfo));
760 #endif
761 }
762 #endif
763
764 /*
765   Debugging support
766 */
767
768 #ifdef DEBUG
769
770
771 /*
772   These routines make a number of assertions about the states
773   of data structures that should be true at all times. If any
774   are not true, it's very likely that a user program has somehow
775   trashed memory. (It's also possible that there is a coding error
776   in malloc. In which case, please report it!)
777 */
778
779 #if __STD_C
780 static void do_check_chunk(mchunkptr p)
781 #else
782 static void do_check_chunk(p) mchunkptr p;
783 #endif
784 {
785   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
786
787   /* No checkable chunk is mmapped */
788   assert(!chunk_is_mmapped(p));
789
790   /* Check for legal address ... */
791   assert((char*)p >= sbrk_base);
792   if (p != top)
793     assert((char*)p + sz <= (char*)top);
794   else
795     assert((char*)p + sz <= sbrk_base + sbrked_mem);
796
797 }
798
799
800 #if __STD_C
801 static void do_check_free_chunk(mchunkptr p)
802 #else
803 static void do_check_free_chunk(p) mchunkptr p;
804 #endif
805 {
806   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
807   mchunkptr next = chunk_at_offset(p, sz);
808
809   do_check_chunk(p);
810
811   /* Check whether it claims to be free ... */
812   assert(!inuse(p));
813
814   /* Unless a special marker, must have OK fields */
815   if ((long)sz >= (long)MINSIZE)
816   {
817     assert((sz & MALLOC_ALIGN_MASK) == 0);
818     assert(aligned_OK(chunk2mem(p)));
819     /* ... matching footer field */
820     assert(next->prev_size == sz);
821     /* ... and is fully consolidated */
822     assert(prev_inuse(p));
823     assert (next == top || inuse(next));
824
825     /* ... and has minimally sane links */
826     assert(p->fd->bk == p);
827     assert(p->bk->fd == p);
828   }
829   else /* markers are always of size SIZE_SZ */
830     assert(sz == SIZE_SZ);
831 }
832
833 #if __STD_C
834 static void do_check_inuse_chunk(mchunkptr p)
835 #else
836 static void do_check_inuse_chunk(p) mchunkptr p;
837 #endif
838 {
839   mchunkptr next = next_chunk(p);
840   do_check_chunk(p);
841
842   /* Check whether it claims to be in use ... */
843   assert(inuse(p));
844
845   /* ... and is surrounded by OK chunks.
846     Since more things can be checked with free chunks than inuse ones,
847     if an inuse chunk borders them and debug is on, it's worth doing them.
848   */
849   if (!prev_inuse(p))
850   {
851     mchunkptr prv = prev_chunk(p);
852     assert(next_chunk(prv) == p);
853     do_check_free_chunk(prv);
854   }
855   if (next == top)
856   {
857     assert(prev_inuse(next));
858     assert(chunksize(next) >= MINSIZE);
859   }
860   else if (!inuse(next))
861     do_check_free_chunk(next);
862
863 }
864
865 #if __STD_C
866 static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)
867 #else
868 static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;
869 #endif
870 {
871   INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;
872   long room = sz - s;
873
874   do_check_inuse_chunk(p);
875
876   /* Legal size ... */
877   assert((long)sz >= (long)MINSIZE);
878   assert((sz & MALLOC_ALIGN_MASK) == 0);
879   assert(room >= 0);
880   assert(room < (long)MINSIZE);
881
882   /* ... and alignment */
883   assert(aligned_OK(chunk2mem(p)));
884
885
886   /* ... and was allocated at front of an available chunk */
887   assert(prev_inuse(p));
888
889 }
890
891
892 #define check_free_chunk(P)  do_check_free_chunk(P)
893 #define check_inuse_chunk(P) do_check_inuse_chunk(P)
894 #define check_chunk(P) do_check_chunk(P)
895 #define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)
896 #else
897 #define check_free_chunk(P)
898 #define check_inuse_chunk(P)
899 #define check_chunk(P)
900 #define check_malloced_chunk(P,N)
901 #endif
902
903
904
905 /*
906   Macro-based internal utilities
907 */
908
909
910 /*
911   Linking chunks in bin lists.
912   Call these only with variables, not arbitrary expressions, as arguments.
913 */
914
915 /*
916   Place chunk p of size s in its bin, in size order,
917   putting it ahead of others of same size.
918 */
919
920
921 #define frontlink(P, S, IDX, BK, FD)                                          \
922 {                                                                             \
923   if (S < MAX_SMALLBIN_SIZE)                                                  \
924   {                                                                           \
925     IDX = smallbin_index(S);                                                  \
926     mark_binblock(IDX);                                                       \
927     BK = bin_at(IDX);                                                         \
928     FD = BK->fd;                                                              \
929     P->bk = BK;                                                               \
930     P->fd = FD;                                                               \
931     FD->bk = BK->fd = P;                                                      \
932   }                                                                           \
933   else                                                                        \
934   {                                                                           \
935     IDX = bin_index(S);                                                       \
936     BK = bin_at(IDX);                                                         \
937     FD = BK->fd;                                                              \
938     if (FD == BK) mark_binblock(IDX);                                         \
939     else                                                                      \
940     {                                                                         \
941       while (FD != BK && S < chunksize(FD)) FD = FD->fd;                      \
942       BK = FD->bk;                                                            \
943     }                                                                         \
944     P->bk = BK;                                                               \
945     P->fd = FD;                                                               \
946     FD->bk = BK->fd = P;                                                      \
947   }                                                                           \
948 }
949
950
951 /* take a chunk off a list */
952
953 #define unlink(P, BK, FD)                                                     \
954 {                                                                             \
955   BK = P->bk;                                                                 \
956   FD = P->fd;                                                                 \
957   FD->bk = BK;                                                                \
958   BK->fd = FD;                                                                \
959 }                                                                             \
960
961 /* Place p as the last remainder */
962
963 #define link_last_remainder(P)                                                \
964 {                                                                             \
965   last_remainder->fd = last_remainder->bk =  P;                               \
966   P->fd = P->bk = last_remainder;                                             \
967 }
968
969 /* Clear the last_remainder bin */
970
971 #define clear_last_remainder \
972   (last_remainder->fd = last_remainder->bk = last_remainder)
973
974
975
976
977
978 /* Routines dealing with mmap(). */
979
980 #if HAVE_MMAP
981
982 #if __STD_C
983 static mchunkptr mmap_chunk(size_t size)
984 #else
985 static mchunkptr mmap_chunk(size) size_t size;
986 #endif
987 {
988   size_t page_mask = malloc_getpagesize - 1;
989   mchunkptr p;
990
991 #ifndef MAP_ANONYMOUS
992   static int fd = -1;
993 #endif
994
995   if(n_mmaps >= n_mmaps_max) return 0; /* too many regions */
996
997   /* For mmapped chunks, the overhead is one SIZE_SZ unit larger, because
998    * there is no following chunk whose prev_size field could be used.
999    */
1000   size = (size + SIZE_SZ + page_mask) & ~page_mask;
1001
1002 #ifdef MAP_ANONYMOUS
1003   p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE,
1004                       MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
1005 #else /* !MAP_ANONYMOUS */
1006   if (fd < 0)
1007   {
1008     fd = open("/dev/zero", O_RDWR);
1009     if(fd < 0) return 0;
1010   }
1011   p = (mchunkptr)mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
1012 #endif
1013
1014   if(p == (mchunkptr)-1) return 0;
1015
1016   n_mmaps++;
1017   if (n_mmaps > max_n_mmaps) max_n_mmaps = n_mmaps;
1018
1019   /* We demand that eight bytes into a page must be 8-byte aligned. */
1020   assert(aligned_OK(chunk2mem(p)));
1021
1022   /* The offset to the start of the mmapped region is stored
1023    * in the prev_size field of the chunk; normally it is zero,
1024    * but that can be changed in memalign().
1025    */
1026   p->prev_size = 0;
1027   set_head(p, size|IS_MMAPPED);
1028
1029   mmapped_mem += size;
1030   if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1031     max_mmapped_mem = mmapped_mem;
1032   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1033     max_total_mem = mmapped_mem + sbrked_mem;
1034   return p;
1035 }
1036
1037 #if __STD_C
1038 static void munmap_chunk(mchunkptr p)
1039 #else
1040 static void munmap_chunk(p) mchunkptr p;
1041 #endif
1042 {
1043   INTERNAL_SIZE_T size = chunksize(p);
1044   int ret;
1045
1046   assert (chunk_is_mmapped(p));
1047   assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1048   assert((n_mmaps > 0));
1049   assert(((p->prev_size + size) & (malloc_getpagesize-1)) == 0);
1050
1051   n_mmaps--;
1052   mmapped_mem -= (size + p->prev_size);
1053
1054   ret = munmap((char *)p - p->prev_size, size + p->prev_size);
1055
1056   /* munmap returns non-zero on failure */
1057   assert(ret == 0);
1058 }
1059
1060 #if HAVE_MREMAP
1061
1062 #if __STD_C
1063 static mchunkptr mremap_chunk(mchunkptr p, size_t new_size)
1064 #else
1065 static mchunkptr mremap_chunk(p, new_size) mchunkptr p; size_t new_size;
1066 #endif
1067 {
1068   size_t page_mask = malloc_getpagesize - 1;
1069   INTERNAL_SIZE_T offset = p->prev_size;
1070   INTERNAL_SIZE_T size = chunksize(p);
1071   char *cp;
1072
1073   assert (chunk_is_mmapped(p));
1074   assert(! ((char*)p >= sbrk_base && (char*)p < sbrk_base + sbrked_mem));
1075   assert((n_mmaps > 0));
1076   assert(((size + offset) & (malloc_getpagesize-1)) == 0);
1077
1078   /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
1079   new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask;
1080
1081   cp = (char *)mremap((char *)p - offset, size + offset, new_size, 1);
1082
1083   if (cp == (char *)-1) return 0;
1084
1085   p = (mchunkptr)(cp + offset);
1086
1087   assert(aligned_OK(chunk2mem(p)));
1088
1089   assert((p->prev_size == offset));
1090   set_head(p, (new_size - offset)|IS_MMAPPED);
1091
1092   mmapped_mem -= size + offset;
1093   mmapped_mem += new_size;
1094   if ((unsigned long)mmapped_mem > (unsigned long)max_mmapped_mem)
1095     max_mmapped_mem = mmapped_mem;
1096   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1097     max_total_mem = mmapped_mem + sbrked_mem;
1098   return p;
1099 }
1100
1101 #endif /* HAVE_MREMAP */
1102
1103 #endif /* HAVE_MMAP */
1104
1105 /*
1106   Extend the top-most chunk by obtaining memory from system.
1107   Main interface to sbrk (but see also malloc_trim).
1108 */
1109
1110 #if __STD_C
1111 static void malloc_extend_top(INTERNAL_SIZE_T nb)
1112 #else
1113 static void malloc_extend_top(nb) INTERNAL_SIZE_T nb;
1114 #endif
1115 {
1116   char*     brk;                  /* return value from sbrk */
1117   INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of sbrked space */
1118   INTERNAL_SIZE_T correction;     /* bytes for 2nd sbrk call */
1119   char*     new_brk;              /* return of 2nd sbrk call */
1120   INTERNAL_SIZE_T top_size;       /* new size of top chunk */
1121
1122   mchunkptr old_top     = top;  /* Record state of old top */
1123   INTERNAL_SIZE_T old_top_size = chunksize(old_top);
1124   char*     old_end      = (char*)(chunk_at_offset(old_top, old_top_size));
1125
1126   /* Pad request with top_pad plus minimal overhead */
1127
1128   INTERNAL_SIZE_T    sbrk_size     = nb + top_pad + MINSIZE;
1129   unsigned long pagesz    = malloc_getpagesize;
1130
1131   /* If not the first time through, round to preserve page boundary */
1132   /* Otherwise, we need to correct to a page size below anyway. */
1133   /* (We also correct below if an intervening foreign sbrk call.) */
1134
1135   if (sbrk_base != (char*)(-1))
1136     sbrk_size = (sbrk_size + (pagesz - 1)) & ~(pagesz - 1);
1137
1138   brk = (char*)(MORECORE (sbrk_size));
1139
1140   /* Fail if sbrk failed or if a foreign sbrk call killed our space */
1141   if (brk == (char*)(MORECORE_FAILURE) ||
1142       (brk < old_end && old_top != initial_top))
1143     return;
1144
1145   sbrked_mem += sbrk_size;
1146
1147   if (brk == old_end) /* can just add bytes to current top */
1148   {
1149     top_size = sbrk_size + old_top_size;
1150     set_head(top, top_size | PREV_INUSE);
1151   }
1152   else
1153   {
1154     if (sbrk_base == (char*)(-1))  /* First time through. Record base */
1155       sbrk_base = brk;
1156     else  /* Someone else called sbrk().  Count those bytes as sbrked_mem. */
1157       sbrked_mem += brk - (char*)old_end;
1158
1159     /* Guarantee alignment of first new chunk made from this space */
1160     front_misalign = (unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK;
1161     if (front_misalign > 0)
1162     {
1163       correction = (MALLOC_ALIGNMENT) - front_misalign;
1164       brk += correction;
1165     }
1166     else
1167       correction = 0;
1168
1169     /* Guarantee the next brk will be at a page boundary */
1170
1171     correction += ((((unsigned long)(brk + sbrk_size))+(pagesz-1)) &
1172                    ~(pagesz - 1)) - ((unsigned long)(brk + sbrk_size));
1173
1174     /* Allocate correction */
1175     new_brk = (char*)(MORECORE (correction));
1176     if (new_brk == (char*)(MORECORE_FAILURE)) return;
1177
1178     sbrked_mem += correction;
1179
1180     top = (mchunkptr)brk;
1181     top_size = new_brk - brk + correction;
1182     set_head(top, top_size | PREV_INUSE);
1183
1184     if (old_top != initial_top)
1185     {
1186
1187       /* There must have been an intervening foreign sbrk call. */
1188       /* A double fencepost is necessary to prevent consolidation */
1189
1190       /* If not enough space to do this, then user did something very wrong */
1191       if (old_top_size < MINSIZE)
1192       {
1193         set_head(top, PREV_INUSE); /* will force null return from malloc */
1194         return;
1195       }
1196
1197       /* Also keep size a multiple of MALLOC_ALIGNMENT */
1198       old_top_size = (old_top_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;
1199       set_head_size(old_top, old_top_size);
1200       chunk_at_offset(old_top, old_top_size          )->size =
1201         SIZE_SZ|PREV_INUSE;
1202       chunk_at_offset(old_top, old_top_size + SIZE_SZ)->size =
1203         SIZE_SZ|PREV_INUSE;
1204       /* If possible, release the rest. */
1205       if (old_top_size >= MINSIZE)
1206         fREe(chunk2mem(old_top));
1207     }
1208   }
1209
1210   if ((unsigned long)sbrked_mem > (unsigned long)max_sbrked_mem)
1211     max_sbrked_mem = sbrked_mem;
1212   if ((unsigned long)(mmapped_mem + sbrked_mem) > (unsigned long)max_total_mem)
1213     max_total_mem = mmapped_mem + sbrked_mem;
1214
1215   /* We always land on a page boundary */
1216   assert(((unsigned long)((char*)top + top_size) & (pagesz - 1)) == 0);
1217 }
1218
1219
1220
1221
1222 /* Main public routines */
1223
1224
1225 /*
1226   Malloc Algorthim:
1227
1228     The requested size is first converted into a usable form, `nb'.
1229     This currently means to add 4 bytes overhead plus possibly more to
1230     obtain 8-byte alignment and/or to obtain a size of at least
1231     MINSIZE (currently 16 bytes), the smallest allocatable size.
1232     (All fits are considered `exact' if they are within MINSIZE bytes.)
1233
1234     From there, the first successful of the following steps is taken:
1235
1236       1. The bin corresponding to the request size is scanned, and if
1237          a chunk of exactly the right size is found, it is taken.
1238
1239       2. The most recently remaindered chunk is used if it is big
1240          enough.  This is a form of (roving) first fit, used only in
1241          the absence of exact fits. Runs of consecutive requests use
1242          the remainder of the chunk used for the previous such request
1243          whenever possible. This limited use of a first-fit style
1244          allocation strategy tends to give contiguous chunks
1245          coextensive lifetimes, which improves locality and can reduce
1246          fragmentation in the long run.
1247
1248       3. Other bins are scanned in increasing size order, using a
1249          chunk big enough to fulfill the request, and splitting off
1250          any remainder.  This search is strictly by best-fit; i.e.,
1251          the smallest (with ties going to approximately the least
1252          recently used) chunk that fits is selected.
1253
1254       4. If large enough, the chunk bordering the end of memory
1255          (`top') is split off. (This use of `top' is in accord with
1256          the best-fit search rule.  In effect, `top' is treated as
1257          larger (and thus less well fitting) than any other available
1258          chunk since it can be extended to be as large as necessary
1259          (up to system limitations).
1260
1261       5. If the request size meets the mmap threshold and the
1262          system supports mmap, and there are few enough currently
1263          allocated mmapped regions, and a call to mmap succeeds,
1264          the request is allocated via direct memory mapping.
1265
1266       6. Otherwise, the top of memory is extended by
1267          obtaining more space from the system (normally using sbrk,
1268          but definable to anything else via the MORECORE macro).
1269          Memory is gathered from the system (in system page-sized
1270          units) in a way that allows chunks obtained across different
1271          sbrk calls to be consolidated, but does not require
1272          contiguous memory. Thus, it should be safe to intersperse
1273          mallocs with other sbrk calls.
1274
1275
1276       All allocations are made from the the `lowest' part of any found
1277       chunk. (The implementation invariant is that prev_inuse is
1278       always true of any allocated chunk; i.e., that each allocated
1279       chunk borders either a previously allocated and still in-use chunk,
1280       or the base of its memory arena.)
1281
1282 */
1283
1284 #if __STD_C
1285 Void_t* mALLOc(size_t bytes)
1286 #else
1287 Void_t* mALLOc(bytes) size_t bytes;
1288 #endif
1289 {
1290   mchunkptr victim;                  /* inspected/selected chunk */
1291   INTERNAL_SIZE_T victim_size;       /* its size */
1292   int       idx;                     /* index for bin traversal */
1293   mbinptr   bin;                     /* associated bin */
1294   mchunkptr remainder;               /* remainder from a split */
1295   long      remainder_size;          /* its size */
1296   int       remainder_index;         /* its bin index */
1297   unsigned long block;               /* block traverser bit */
1298   int       startidx;                /* first bin of a traversed block */
1299   mchunkptr fwd;                     /* misc temp for linking */
1300   mchunkptr bck;                     /* misc temp for linking */
1301   mbinptr q;                         /* misc temp */
1302
1303   INTERNAL_SIZE_T nb;
1304
1305 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1306         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT))
1307                 return malloc_simple(bytes);
1308 #endif
1309
1310   /* check if mem_malloc_init() was run */
1311   if ((mem_malloc_start == 0) && (mem_malloc_end == 0)) {
1312     /* not initialized yet */
1313     return NULL;
1314   }
1315
1316   if ((long)bytes < 0) return NULL;
1317
1318   nb = request2size(bytes);  /* padded request size; */
1319
1320   /* Check for exact match in a bin */
1321
1322   if (is_small_request(nb))  /* Faster version for small requests */
1323   {
1324     idx = smallbin_index(nb);
1325
1326     /* No traversal or size check necessary for small bins.  */
1327
1328     q = bin_at(idx);
1329     victim = last(q);
1330
1331     /* Also scan the next one, since it would have a remainder < MINSIZE */
1332     if (victim == q)
1333     {
1334       q = next_bin(q);
1335       victim = last(q);
1336     }
1337     if (victim != q)
1338     {
1339       victim_size = chunksize(victim);
1340       unlink(victim, bck, fwd);
1341       set_inuse_bit_at_offset(victim, victim_size);
1342       check_malloced_chunk(victim, nb);
1343       VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1344       return chunk2mem(victim);
1345     }
1346
1347     idx += 2; /* Set for bin scan below. We've already scanned 2 bins. */
1348
1349   }
1350   else
1351   {
1352     idx = bin_index(nb);
1353     bin = bin_at(idx);
1354
1355     for (victim = last(bin); victim != bin; victim = victim->bk)
1356     {
1357       victim_size = chunksize(victim);
1358       remainder_size = victim_size - nb;
1359
1360       if (remainder_size >= (long)MINSIZE) /* too big */
1361       {
1362         --idx; /* adjust to rescan below after checking last remainder */
1363         break;
1364       }
1365
1366       else if (remainder_size >= 0) /* exact fit */
1367       {
1368         unlink(victim, bck, fwd);
1369         set_inuse_bit_at_offset(victim, victim_size);
1370         check_malloced_chunk(victim, nb);
1371         VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1372         return chunk2mem(victim);
1373       }
1374     }
1375
1376     ++idx;
1377
1378   }
1379
1380   /* Try to use the last split-off remainder */
1381
1382   if ( (victim = last_remainder->fd) != last_remainder)
1383   {
1384     victim_size = chunksize(victim);
1385     remainder_size = victim_size - nb;
1386
1387     if (remainder_size >= (long)MINSIZE) /* re-split */
1388     {
1389       remainder = chunk_at_offset(victim, nb);
1390       set_head(victim, nb | PREV_INUSE);
1391       link_last_remainder(remainder);
1392       set_head(remainder, remainder_size | PREV_INUSE);
1393       set_foot(remainder, remainder_size);
1394       check_malloced_chunk(victim, nb);
1395       VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1396       return chunk2mem(victim);
1397     }
1398
1399     clear_last_remainder;
1400
1401     if (remainder_size >= 0)  /* exhaust */
1402     {
1403       set_inuse_bit_at_offset(victim, victim_size);
1404       check_malloced_chunk(victim, nb);
1405       VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1406       return chunk2mem(victim);
1407     }
1408
1409     /* Else place in bin */
1410
1411     frontlink(victim, victim_size, remainder_index, bck, fwd);
1412   }
1413
1414   /*
1415      If there are any possibly nonempty big-enough blocks,
1416      search for best fitting chunk by scanning bins in blockwidth units.
1417   */
1418
1419   if ( (block = idx2binblock(idx)) <= binblocks_r)
1420   {
1421
1422     /* Get to the first marked block */
1423
1424     if ( (block & binblocks_r) == 0)
1425     {
1426       /* force to an even block boundary */
1427       idx = (idx & ~(BINBLOCKWIDTH - 1)) + BINBLOCKWIDTH;
1428       block <<= 1;
1429       while ((block & binblocks_r) == 0)
1430       {
1431         idx += BINBLOCKWIDTH;
1432         block <<= 1;
1433       }
1434     }
1435
1436     /* For each possibly nonempty block ... */
1437     for (;;)
1438     {
1439       startidx = idx;          /* (track incomplete blocks) */
1440       q = bin = bin_at(idx);
1441
1442       /* For each bin in this block ... */
1443       do
1444       {
1445         /* Find and use first big enough chunk ... */
1446
1447         for (victim = last(bin); victim != bin; victim = victim->bk)
1448         {
1449           victim_size = chunksize(victim);
1450           remainder_size = victim_size - nb;
1451
1452           if (remainder_size >= (long)MINSIZE) /* split */
1453           {
1454             remainder = chunk_at_offset(victim, nb);
1455             set_head(victim, nb | PREV_INUSE);
1456             unlink(victim, bck, fwd);
1457             link_last_remainder(remainder);
1458             set_head(remainder, remainder_size | PREV_INUSE);
1459             set_foot(remainder, remainder_size);
1460             check_malloced_chunk(victim, nb);
1461             VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1462             return chunk2mem(victim);
1463           }
1464
1465           else if (remainder_size >= 0)  /* take */
1466           {
1467             set_inuse_bit_at_offset(victim, victim_size);
1468             unlink(victim, bck, fwd);
1469             check_malloced_chunk(victim, nb);
1470             VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1471             return chunk2mem(victim);
1472           }
1473
1474         }
1475
1476        bin = next_bin(bin);
1477
1478       } while ((++idx & (BINBLOCKWIDTH - 1)) != 0);
1479
1480       /* Clear out the block bit. */
1481
1482       do   /* Possibly backtrack to try to clear a partial block */
1483       {
1484         if ((startidx & (BINBLOCKWIDTH - 1)) == 0)
1485         {
1486           av_[1] = (mbinptr)(binblocks_r & ~block);
1487           break;
1488         }
1489         --startidx;
1490        q = prev_bin(q);
1491       } while (first(q) == q);
1492
1493       /* Get to the next possibly nonempty block */
1494
1495       if ( (block <<= 1) <= binblocks_r && (block != 0) )
1496       {
1497         while ((block & binblocks_r) == 0)
1498         {
1499           idx += BINBLOCKWIDTH;
1500           block <<= 1;
1501         }
1502       }
1503       else
1504         break;
1505     }
1506   }
1507
1508
1509   /* Try to use top chunk */
1510
1511   /* Require that there be a remainder, ensuring top always exists  */
1512   if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1513   {
1514
1515 #if HAVE_MMAP
1516     /* If big and would otherwise need to extend, try to use mmap instead */
1517     if ((unsigned long)nb >= (unsigned long)mmap_threshold &&
1518         (victim = mmap_chunk(nb)))
1519       VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1520       return chunk2mem(victim);
1521 #endif
1522
1523     /* Try to extend */
1524     malloc_extend_top(nb);
1525     if ( (remainder_size = chunksize(top) - nb) < (long)MINSIZE)
1526       return NULL; /* propagate failure */
1527   }
1528
1529   victim = top;
1530   set_head(victim, nb | PREV_INUSE);
1531   top = chunk_at_offset(victim, nb);
1532   set_head(top, remainder_size | PREV_INUSE);
1533   check_malloced_chunk(victim, nb);
1534   VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(victim), bytes, SIZE_SZ, false);
1535   return chunk2mem(victim);
1536
1537 }
1538
1539
1540
1541
1542 /*
1543
1544   free() algorithm :
1545
1546     cases:
1547
1548        1. free(0) has no effect.
1549
1550        2. If the chunk was allocated via mmap, it is release via munmap().
1551
1552        3. If a returned chunk borders the current high end of memory,
1553           it is consolidated into the top, and if the total unused
1554           topmost memory exceeds the trim threshold, malloc_trim is
1555           called.
1556
1557        4. Other chunks are consolidated as they arrive, and
1558           placed in corresponding bins. (This includes the case of
1559           consolidating with the current `last_remainder').
1560
1561 */
1562
1563
1564 #if __STD_C
1565 void fREe(Void_t* mem)
1566 #else
1567 void fREe(mem) Void_t* mem;
1568 #endif
1569 {
1570   mchunkptr p;         /* chunk corresponding to mem */
1571   INTERNAL_SIZE_T hd;  /* its head field */
1572   INTERNAL_SIZE_T sz;  /* its size */
1573   int       idx;       /* its bin index */
1574   mchunkptr next;      /* next contiguous chunk */
1575   INTERNAL_SIZE_T nextsz; /* its size */
1576   INTERNAL_SIZE_T prevsz; /* size of previous contiguous chunk */
1577   mchunkptr bck;       /* misc temp for linking */
1578   mchunkptr fwd;       /* misc temp for linking */
1579   int       islr;      /* track whether merging with last_remainder */
1580
1581 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1582         /* free() is a no-op - all the memory will be freed on relocation */
1583         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
1584                 VALGRIND_FREELIKE_BLOCK(mem, SIZE_SZ);
1585                 return;
1586         }
1587 #endif
1588
1589   if (mem == NULL)                              /* free(0) has no effect */
1590     return;
1591
1592   p = mem2chunk(mem);
1593   hd = p->size;
1594
1595 #if HAVE_MMAP
1596   if (hd & IS_MMAPPED)                       /* release mmapped memory. */
1597   {
1598     munmap_chunk(p);
1599     return;
1600   }
1601 #endif
1602
1603   check_inuse_chunk(p);
1604
1605   sz = hd & ~PREV_INUSE;
1606   next = chunk_at_offset(p, sz);
1607   nextsz = chunksize(next);
1608   VALGRIND_FREELIKE_BLOCK(mem, SIZE_SZ);
1609
1610   if (next == top)                            /* merge with top */
1611   {
1612     sz += nextsz;
1613
1614     if (!(hd & PREV_INUSE))                    /* consolidate backward */
1615     {
1616       prevsz = p->prev_size;
1617       p = chunk_at_offset(p, -((long) prevsz));
1618       sz += prevsz;
1619       unlink(p, bck, fwd);
1620     }
1621
1622     set_head(p, sz | PREV_INUSE);
1623     top = p;
1624     if ((unsigned long)(sz) >= (unsigned long)trim_threshold)
1625       malloc_trim(top_pad);
1626     return;
1627   }
1628
1629   set_head(next, nextsz);                    /* clear inuse bit */
1630
1631   islr = 0;
1632
1633   if (!(hd & PREV_INUSE))                    /* consolidate backward */
1634   {
1635     prevsz = p->prev_size;
1636     p = chunk_at_offset(p, -((long) prevsz));
1637     sz += prevsz;
1638
1639     if (p->fd == last_remainder)             /* keep as last_remainder */
1640       islr = 1;
1641     else
1642       unlink(p, bck, fwd);
1643   }
1644
1645   if (!(inuse_bit_at_offset(next, nextsz)))   /* consolidate forward */
1646   {
1647     sz += nextsz;
1648
1649     if (!islr && next->fd == last_remainder)  /* re-insert last_remainder */
1650     {
1651       islr = 1;
1652       link_last_remainder(p);
1653     }
1654     else
1655       unlink(next, bck, fwd);
1656   }
1657
1658
1659   set_head(p, sz | PREV_INUSE);
1660   set_foot(p, sz);
1661   if (!islr)
1662     frontlink(p, sz, idx, bck, fwd);
1663 }
1664
1665
1666
1667
1668
1669 /*
1670
1671   Realloc algorithm:
1672
1673     Chunks that were obtained via mmap cannot be extended or shrunk
1674     unless HAVE_MREMAP is defined, in which case mremap is used.
1675     Otherwise, if their reallocation is for additional space, they are
1676     copied.  If for less, they are just left alone.
1677
1678     Otherwise, if the reallocation is for additional space, and the
1679     chunk can be extended, it is, else a malloc-copy-free sequence is
1680     taken.  There are several different ways that a chunk could be
1681     extended. All are tried:
1682
1683        * Extending forward into following adjacent free chunk.
1684        * Shifting backwards, joining preceding adjacent space
1685        * Both shifting backwards and extending forward.
1686        * Extending into newly sbrked space
1687
1688     Unless the #define REALLOC_ZERO_BYTES_FREES is set, realloc with a
1689     size argument of zero (re)allocates a minimum-sized chunk.
1690
1691     If the reallocation is for less space, and the new request is for
1692     a `small' (<512 bytes) size, then the newly unused space is lopped
1693     off and freed.
1694
1695     The old unix realloc convention of allowing the last-free'd chunk
1696     to be used as an argument to realloc is no longer supported.
1697     I don't know of any programs still relying on this feature,
1698     and allowing it would also allow too many other incorrect
1699     usages of realloc to be sensible.
1700
1701
1702 */
1703
1704
1705 #if __STD_C
1706 Void_t* rEALLOc(Void_t* oldmem, size_t bytes)
1707 #else
1708 Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;
1709 #endif
1710 {
1711   INTERNAL_SIZE_T    nb;      /* padded request size */
1712
1713   mchunkptr oldp;             /* chunk corresponding to oldmem */
1714   INTERNAL_SIZE_T    oldsize; /* its size */
1715
1716   mchunkptr newp;             /* chunk to return */
1717   INTERNAL_SIZE_T    newsize; /* its size */
1718   Void_t*   newmem;           /* corresponding user mem */
1719
1720   mchunkptr next;             /* next contiguous chunk after oldp */
1721   INTERNAL_SIZE_T  nextsize;  /* its size */
1722
1723   mchunkptr prev;             /* previous contiguous chunk before oldp */
1724   INTERNAL_SIZE_T  prevsize;  /* its size */
1725
1726   mchunkptr remainder;        /* holds split off extra space from newp */
1727   INTERNAL_SIZE_T  remainder_size;   /* its size */
1728
1729   mchunkptr bck;              /* misc temp for linking */
1730   mchunkptr fwd;              /* misc temp for linking */
1731
1732 #ifdef REALLOC_ZERO_BYTES_FREES
1733   if (!bytes) {
1734         fREe(oldmem);
1735         return NULL;
1736   }
1737 #endif
1738
1739   if ((long)bytes < 0) return NULL;
1740
1741   /* realloc of null is supposed to be same as malloc */
1742   if (oldmem == NULL) return mALLOc(bytes);
1743
1744 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1745         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
1746                 /* This is harder to support and should not be needed */
1747                 panic("pre-reloc realloc() is not supported");
1748         }
1749 #endif
1750
1751   newp    = oldp    = mem2chunk(oldmem);
1752   newsize = oldsize = chunksize(oldp);
1753
1754
1755   nb = request2size(bytes);
1756
1757 #if HAVE_MMAP
1758   if (chunk_is_mmapped(oldp))
1759   {
1760 #if HAVE_MREMAP
1761     newp = mremap_chunk(oldp, nb);
1762     if(newp) return chunk2mem(newp);
1763 #endif
1764     /* Note the extra SIZE_SZ overhead. */
1765     if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */
1766     /* Must alloc, copy, free. */
1767     newmem = mALLOc(bytes);
1768     if (!newmem)
1769         return NULL; /* propagate failure */
1770     MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);
1771     munmap_chunk(oldp);
1772     return newmem;
1773   }
1774 #endif
1775
1776   check_inuse_chunk(oldp);
1777
1778   if ((long)(oldsize) < (long)(nb))
1779   {
1780
1781     /* Try expanding forward */
1782
1783     next = chunk_at_offset(oldp, oldsize);
1784     if (next == top || !inuse(next))
1785     {
1786       nextsize = chunksize(next);
1787
1788       /* Forward into top only if a remainder */
1789       if (next == top)
1790       {
1791         if ((long)(nextsize + newsize) >= (long)(nb + MINSIZE))
1792         {
1793           newsize += nextsize;
1794           top = chunk_at_offset(oldp, nb);
1795           set_head(top, (newsize - nb) | PREV_INUSE);
1796           set_head_size(oldp, nb);
1797           VALGRIND_RESIZEINPLACE_BLOCK(chunk2mem(oldp), 0, bytes, SIZE_SZ);
1798           VALGRIND_MAKE_MEM_DEFINED(chunk2mem(oldp), bytes);
1799           return chunk2mem(oldp);
1800         }
1801       }
1802
1803       /* Forward into next chunk */
1804       else if (((long)(nextsize + newsize) >= (long)(nb)))
1805       {
1806         unlink(next, bck, fwd);
1807         newsize  += nextsize;
1808         VALGRIND_RESIZEINPLACE_BLOCK(chunk2mem(oldp), 0, bytes, SIZE_SZ);
1809         VALGRIND_MAKE_MEM_DEFINED(chunk2mem(oldp), bytes);
1810         goto split;
1811       }
1812     }
1813     else
1814     {
1815       next = NULL;
1816       nextsize = 0;
1817     }
1818
1819     /* Try shifting backwards. */
1820
1821     if (!prev_inuse(oldp))
1822     {
1823       prev = prev_chunk(oldp);
1824       prevsize = chunksize(prev);
1825
1826       /* try forward + backward first to save a later consolidation */
1827
1828       if (next != NULL)
1829       {
1830         /* into top */
1831         if (next == top)
1832         {
1833           if ((long)(nextsize + prevsize + newsize) >= (long)(nb + MINSIZE))
1834           {
1835             unlink(prev, bck, fwd);
1836             newp = prev;
1837             newsize += prevsize + nextsize;
1838             newmem = chunk2mem(newp);
1839             VALGRIND_MALLOCLIKE_BLOCK(newmem, bytes, SIZE_SZ, false);
1840             MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1841             top = chunk_at_offset(newp, nb);
1842             set_head(top, (newsize - nb) | PREV_INUSE);
1843             set_head_size(newp, nb);
1844             VALGRIND_FREELIKE_BLOCK(oldmem, SIZE_SZ);
1845             return newmem;
1846           }
1847         }
1848
1849         /* into next chunk */
1850         else if (((long)(nextsize + prevsize + newsize) >= (long)(nb)))
1851         {
1852           unlink(next, bck, fwd);
1853           unlink(prev, bck, fwd);
1854           newp = prev;
1855           newsize += nextsize + prevsize;
1856           newmem = chunk2mem(newp);
1857           VALGRIND_MALLOCLIKE_BLOCK(newmem, bytes, SIZE_SZ, false);
1858           MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1859           goto split;
1860         }
1861       }
1862
1863       /* backward only */
1864       if (prev != NULL && (long)(prevsize + newsize) >= (long)nb)
1865       {
1866         unlink(prev, bck, fwd);
1867         newp = prev;
1868         newsize += prevsize;
1869         newmem = chunk2mem(newp);
1870         VALGRIND_MALLOCLIKE_BLOCK(newmem, bytes, SIZE_SZ, false);
1871         MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1872         goto split;
1873       }
1874     }
1875
1876     /* Must allocate */
1877
1878     newmem = mALLOc (bytes);
1879
1880     if (newmem == NULL)  /* propagate failure */
1881       return NULL;
1882
1883     /* Avoid copy if newp is next chunk after oldp. */
1884     /* (This can only happen when new chunk is sbrk'ed.) */
1885
1886     if ( (newp = mem2chunk(newmem)) == next_chunk(oldp))
1887     {
1888       newsize += chunksize(newp);
1889       newp = oldp;
1890       goto split;
1891     }
1892
1893     /* Otherwise copy, free, and exit */
1894     MALLOC_COPY(newmem, oldmem, oldsize - SIZE_SZ);
1895     fREe(oldmem);
1896     return newmem;
1897   } else {
1898     VALGRIND_RESIZEINPLACE_BLOCK(oldmem, 0, bytes, SIZE_SZ);
1899     VALGRIND_MAKE_MEM_DEFINED(oldmem, bytes);
1900   }
1901
1902
1903  split:  /* split off extra room in old or expanded chunk */
1904
1905   if (newsize - nb >= MINSIZE) /* split off remainder */
1906   {
1907     remainder = chunk_at_offset(newp, nb);
1908     remainder_size = newsize - nb;
1909     set_head_size(newp, nb);
1910     set_head(remainder, remainder_size | PREV_INUSE);
1911     set_inuse_bit_at_offset(remainder, remainder_size);
1912     VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(remainder), remainder_size, SIZE_SZ,
1913                               false);
1914     fREe(chunk2mem(remainder)); /* let free() deal with it */
1915   }
1916   else
1917   {
1918     set_head_size(newp, newsize);
1919     set_inuse_bit_at_offset(newp, newsize);
1920   }
1921
1922   check_inuse_chunk(newp);
1923   return chunk2mem(newp);
1924 }
1925
1926
1927
1928
1929 /*
1930
1931   memalign algorithm:
1932
1933     memalign requests more than enough space from malloc, finds a spot
1934     within that chunk that meets the alignment request, and then
1935     possibly frees the leading and trailing space.
1936
1937     The alignment argument must be a power of two. This property is not
1938     checked by memalign, so misuse may result in random runtime errors.
1939
1940     8-byte alignment is guaranteed by normal malloc calls, so don't
1941     bother calling memalign with an argument of 8 or less.
1942
1943     Overreliance on memalign is a sure way to fragment space.
1944
1945 */
1946
1947
1948 #if __STD_C
1949 Void_t* mEMALIGn(size_t alignment, size_t bytes)
1950 #else
1951 Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;
1952 #endif
1953 {
1954   INTERNAL_SIZE_T    nb;      /* padded  request size */
1955   char*     m;                /* memory returned by malloc call */
1956   mchunkptr p;                /* corresponding chunk */
1957   char*     brk;              /* alignment point within p */
1958   mchunkptr newp;             /* chunk to return */
1959   INTERNAL_SIZE_T  newsize;   /* its size */
1960   INTERNAL_SIZE_T  leadsize;  /* leading space befor alignment point */
1961   mchunkptr remainder;        /* spare room at end to split off */
1962   long      remainder_size;   /* its size */
1963
1964   if ((long)bytes < 0) return NULL;
1965
1966 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
1967         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
1968                 return memalign_simple(alignment, bytes);
1969         }
1970 #endif
1971
1972   /* If need less alignment than we give anyway, just relay to malloc */
1973
1974   if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);
1975
1976   /* Otherwise, ensure that it is at least a minimum chunk size */
1977
1978   if (alignment <  MINSIZE) alignment = MINSIZE;
1979
1980   /* Call malloc with worst case padding to hit alignment. */
1981
1982   nb = request2size(bytes);
1983   m  = (char*)(mALLOc(nb + alignment + MINSIZE));
1984
1985   /*
1986   * The attempt to over-allocate (with a size large enough to guarantee the
1987   * ability to find an aligned region within allocated memory) failed.
1988   *
1989   * Try again, this time only allocating exactly the size the user wants. If
1990   * the allocation now succeeds and just happens to be aligned, we can still
1991   * fulfill the user's request.
1992   */
1993   if (m == NULL) {
1994     size_t extra, extra2;
1995     /*
1996      * Use bytes not nb, since mALLOc internally calls request2size too, and
1997      * each call increases the size to allocate, to account for the header.
1998      */
1999     m  = (char*)(mALLOc(bytes));
2000     /* Aligned -> return it */
2001     if ((((unsigned long)(m)) % alignment) == 0)
2002       return m;
2003     /*
2004      * Otherwise, try again, requesting enough extra space to be able to
2005      * acquire alignment.
2006      */
2007     fREe(m);
2008     /* Add in extra bytes to match misalignment of unexpanded allocation */
2009     extra = alignment - (((unsigned long)(m)) % alignment);
2010     m  = (char*)(mALLOc(bytes + extra));
2011     /*
2012      * m might not be the same as before. Validate that the previous value of
2013      * extra still works for the current value of m.
2014      * If (!m), extra2=alignment so 
2015      */
2016     if (m) {
2017       extra2 = alignment - (((unsigned long)(m)) % alignment);
2018       if (extra2 > extra) {
2019         fREe(m);
2020         m = NULL;
2021       }
2022     }
2023     /* Fall through to original NULL check and chunk splitting logic */
2024   }
2025
2026   if (m == NULL) return NULL; /* propagate failure */
2027
2028   p = mem2chunk(m);
2029
2030   if ((((unsigned long)(m)) % alignment) == 0) /* aligned */
2031   {
2032 #if HAVE_MMAP
2033     if(chunk_is_mmapped(p))
2034       return chunk2mem(p); /* nothing more to do */
2035 #endif
2036   }
2037   else /* misaligned */
2038   {
2039     /*
2040       Find an aligned spot inside chunk.
2041       Since we need to give back leading space in a chunk of at
2042       least MINSIZE, if the first calculation places us at
2043       a spot with less than MINSIZE leader, we can move to the
2044       next aligned spot -- we've allocated enough total room so that
2045       this is always possible.
2046     */
2047
2048     brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & -((signed) alignment));
2049     if ((long)(brk - (char*)(p)) < MINSIZE) brk = brk + alignment;
2050
2051     newp = (mchunkptr)brk;
2052     leadsize = brk - (char*)(p);
2053     newsize = chunksize(p) - leadsize;
2054
2055 #if HAVE_MMAP
2056     if(chunk_is_mmapped(p))
2057     {
2058       newp->prev_size = p->prev_size + leadsize;
2059       set_head(newp, newsize|IS_MMAPPED);
2060       return chunk2mem(newp);
2061     }
2062 #endif
2063
2064     /* give back leader, use the rest */
2065
2066     set_head(newp, newsize | PREV_INUSE);
2067     set_inuse_bit_at_offset(newp, newsize);
2068     set_head_size(p, leadsize);
2069     fREe(chunk2mem(p));
2070     p = newp;
2071     VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(p), bytes, SIZE_SZ, false);
2072
2073     assert (newsize >= nb && (((unsigned long)(chunk2mem(p))) % alignment) == 0);
2074   }
2075
2076   /* Also give back spare room at the end */
2077
2078   remainder_size = chunksize(p) - nb;
2079
2080   if (remainder_size >= (long)MINSIZE)
2081   {
2082     remainder = chunk_at_offset(p, nb);
2083     set_head(remainder, remainder_size | PREV_INUSE);
2084     set_head_size(p, nb);
2085     VALGRIND_MALLOCLIKE_BLOCK(chunk2mem(remainder), remainder_size, SIZE_SZ,
2086                               false);
2087     fREe(chunk2mem(remainder));
2088   }
2089
2090   check_inuse_chunk(p);
2091   return chunk2mem(p);
2092
2093 }
2094
2095
2096
2097
2098 /*
2099     valloc just invokes memalign with alignment argument equal
2100     to the page size of the system (or as near to this as can
2101     be figured out from all the includes/defines above.)
2102 */
2103
2104 #if __STD_C
2105 Void_t* vALLOc(size_t bytes)
2106 #else
2107 Void_t* vALLOc(bytes) size_t bytes;
2108 #endif
2109 {
2110   return mEMALIGn (malloc_getpagesize, bytes);
2111 }
2112
2113 /*
2114   pvalloc just invokes valloc for the nearest pagesize
2115   that will accommodate request
2116 */
2117
2118
2119 #if __STD_C
2120 Void_t* pvALLOc(size_t bytes)
2121 #else
2122 Void_t* pvALLOc(bytes) size_t bytes;
2123 #endif
2124 {
2125   size_t pagesize = malloc_getpagesize;
2126   return mEMALIGn (pagesize, (bytes + pagesize - 1) & ~(pagesize - 1));
2127 }
2128
2129 /*
2130
2131   calloc calls malloc, then zeroes out the allocated chunk.
2132
2133 */
2134
2135 #if __STD_C
2136 Void_t* cALLOc(size_t n, size_t elem_size)
2137 #else
2138 Void_t* cALLOc(n, elem_size) size_t n; size_t elem_size;
2139 #endif
2140 {
2141   mchunkptr p;
2142   INTERNAL_SIZE_T csz;
2143
2144   INTERNAL_SIZE_T sz = n * elem_size;
2145
2146
2147   /* check if expand_top called, in which case don't need to clear */
2148 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
2149 #if MORECORE_CLEARS
2150   mchunkptr oldtop = top;
2151   INTERNAL_SIZE_T oldtopsize = chunksize(top);
2152 #endif
2153 #endif
2154   Void_t* mem = mALLOc (sz);
2155
2156   if ((long)n < 0) return NULL;
2157
2158   if (mem == NULL)
2159     return NULL;
2160   else
2161   {
2162 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
2163         if (!(gd->flags & GD_FLG_FULL_MALLOC_INIT)) {
2164                 memset(mem, 0, sz);
2165                 return mem;
2166         }
2167 #endif
2168     p = mem2chunk(mem);
2169
2170     /* Two optional cases in which clearing not necessary */
2171
2172
2173 #if HAVE_MMAP
2174     if (chunk_is_mmapped(p)) return mem;
2175 #endif
2176
2177     csz = chunksize(p);
2178
2179 #ifdef CONFIG_SYS_MALLOC_CLEAR_ON_INIT
2180 #if MORECORE_CLEARS
2181     if (p == oldtop && csz > oldtopsize)
2182     {
2183       /* clear only the bytes from non-freshly-sbrked memory */
2184       csz = oldtopsize;
2185     }
2186 #endif
2187 #endif
2188
2189     MALLOC_ZERO(mem, csz - SIZE_SZ);
2190     VALGRIND_MAKE_MEM_DEFINED(mem, sz);
2191     return mem;
2192   }
2193 }
2194
2195 /*
2196
2197   cfree just calls free. It is needed/defined on some systems
2198   that pair it with calloc, presumably for odd historical reasons.
2199
2200 */
2201
2202 #if !defined(INTERNAL_LINUX_C_LIB) || !defined(__ELF__)
2203 #if __STD_C
2204 void cfree(Void_t *mem)
2205 #else
2206 void cfree(mem) Void_t *mem;
2207 #endif
2208 {
2209   fREe(mem);
2210 }
2211 #endif
2212
2213
2214
2215 /*
2216
2217     Malloc_trim gives memory back to the system (via negative
2218     arguments to sbrk) if there is unused memory at the `high' end of
2219     the malloc pool. You can call this after freeing large blocks of
2220     memory to potentially reduce the system-level memory requirements
2221     of a program. However, it cannot guarantee to reduce memory. Under
2222     some allocation patterns, some large free blocks of memory will be
2223     locked between two used chunks, so they cannot be given back to
2224     the system.
2225
2226     The `pad' argument to malloc_trim represents the amount of free
2227     trailing space to leave untrimmed. If this argument is zero,
2228     only the minimum amount of memory to maintain internal data
2229     structures will be left (one page or less). Non-zero arguments
2230     can be supplied to maintain enough trailing space to service
2231     future expected allocations without having to re-obtain memory
2232     from the system.
2233
2234     Malloc_trim returns 1 if it actually released any memory, else 0.
2235
2236 */
2237
2238 #if __STD_C
2239 int malloc_trim(size_t pad)
2240 #else
2241 int malloc_trim(pad) size_t pad;
2242 #endif
2243 {
2244   long  top_size;        /* Amount of top-most memory */
2245   long  extra;           /* Amount to release */
2246   char* current_brk;     /* address returned by pre-check sbrk call */
2247   char* new_brk;         /* address returned by negative sbrk call */
2248
2249   unsigned long pagesz = malloc_getpagesize;
2250
2251   top_size = chunksize(top);
2252   extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;
2253
2254   if (extra < (long)pagesz)  /* Not enough memory to release */
2255     return 0;
2256
2257   else
2258   {
2259     /* Test to make sure no one else called sbrk */
2260     current_brk = (char*)(MORECORE (0));
2261     if (current_brk != (char*)(top) + top_size)
2262       return 0;     /* Apparently we don't own memory; must fail */
2263
2264     else
2265     {
2266       new_brk = (char*)(MORECORE (-extra));
2267
2268       if (new_brk == (char*)(MORECORE_FAILURE)) /* sbrk failed? */
2269       {
2270         /* Try to figure out what we have */
2271         current_brk = (char*)(MORECORE (0));
2272         top_size = current_brk - (char*)top;
2273         if (top_size >= (long)MINSIZE) /* if not, we are very very dead! */
2274         {
2275           sbrked_mem = current_brk - sbrk_base;
2276           set_head(top, top_size | PREV_INUSE);
2277         }
2278         check_chunk(top);
2279         return 0;
2280       }
2281
2282       else
2283       {
2284         /* Success. Adjust top accordingly. */
2285         set_head(top, (top_size - extra) | PREV_INUSE);
2286         sbrked_mem -= extra;
2287         check_chunk(top);
2288         return 1;
2289       }
2290     }
2291   }
2292 }
2293
2294
2295
2296 /*
2297   malloc_usable_size:
2298
2299     This routine tells you how many bytes you can actually use in an
2300     allocated chunk, which may be more than you requested (although
2301     often not). You can use this many bytes without worrying about
2302     overwriting other allocated objects. Not a particularly great
2303     programming practice, but still sometimes useful.
2304
2305 */
2306
2307 #if __STD_C
2308 size_t malloc_usable_size(Void_t* mem)
2309 #else
2310 size_t malloc_usable_size(mem) Void_t* mem;
2311 #endif
2312 {
2313   mchunkptr p;
2314   if (mem == NULL)
2315     return 0;
2316   else
2317   {
2318     p = mem2chunk(mem);
2319     if(!chunk_is_mmapped(p))
2320     {
2321       if (!inuse(p)) return 0;
2322       check_inuse_chunk(p);
2323       return chunksize(p) - SIZE_SZ;
2324     }
2325     return chunksize(p) - 2*SIZE_SZ;
2326   }
2327 }
2328
2329
2330
2331
2332 /* Utility to update current_mallinfo for malloc_stats and mallinfo() */
2333
2334 #ifdef DEBUG
2335 static void malloc_update_mallinfo()
2336 {
2337   int i;
2338   mbinptr b;
2339   mchunkptr p;
2340 #ifdef DEBUG
2341   mchunkptr q;
2342 #endif
2343
2344   INTERNAL_SIZE_T avail = chunksize(top);
2345   int   navail = ((long)(avail) >= (long)MINSIZE)? 1 : 0;
2346
2347   for (i = 1; i < NAV; ++i)
2348   {
2349     b = bin_at(i);
2350     for (p = last(b); p != b; p = p->bk)
2351     {
2352 #ifdef DEBUG
2353       check_free_chunk(p);
2354       for (q = next_chunk(p);
2355            q < top && inuse(q) && (long)(chunksize(q)) >= (long)MINSIZE;
2356            q = next_chunk(q))
2357         check_inuse_chunk(q);
2358 #endif
2359       avail += chunksize(p);
2360       navail++;
2361     }
2362   }
2363
2364   current_mallinfo.ordblks = navail;
2365   current_mallinfo.uordblks = sbrked_mem - avail;
2366   current_mallinfo.fordblks = avail;
2367   current_mallinfo.hblks = n_mmaps;
2368   current_mallinfo.hblkhd = mmapped_mem;
2369   current_mallinfo.keepcost = chunksize(top);
2370
2371 }
2372 #endif  /* DEBUG */
2373
2374
2375
2376 /*
2377
2378   malloc_stats:
2379
2380     Prints on the amount of space obtain from the system (both
2381     via sbrk and mmap), the maximum amount (which may be more than
2382     current if malloc_trim and/or munmap got called), the maximum
2383     number of simultaneous mmap regions used, and the current number
2384     of bytes allocated via malloc (or realloc, etc) but not yet
2385     freed. (Note that this is the number of bytes allocated, not the
2386     number requested. It will be larger than the number requested
2387     because of alignment and bookkeeping overhead.)
2388
2389 */
2390
2391 #ifdef DEBUG
2392 void malloc_stats()
2393 {
2394   malloc_update_mallinfo();
2395   printf("max system bytes = %10u\n",
2396           (unsigned int)(max_total_mem));
2397   printf("system bytes     = %10u\n",
2398           (unsigned int)(sbrked_mem + mmapped_mem));
2399   printf("in use bytes     = %10u\n",
2400           (unsigned int)(current_mallinfo.uordblks + mmapped_mem));
2401 #if HAVE_MMAP
2402   printf("max mmap regions = %10u\n",
2403           (unsigned int)max_n_mmaps);
2404 #endif
2405 }
2406 #endif  /* DEBUG */
2407
2408 /*
2409   mallinfo returns a copy of updated current mallinfo.
2410 */
2411
2412 #ifdef DEBUG
2413 struct mallinfo mALLINFo()
2414 {
2415   malloc_update_mallinfo();
2416   return current_mallinfo;
2417 }
2418 #endif  /* DEBUG */
2419
2420
2421
2422
2423 /*
2424   mallopt:
2425
2426     mallopt is the general SVID/XPG interface to tunable parameters.
2427     The format is to provide a (parameter-number, parameter-value) pair.
2428     mallopt then sets the corresponding parameter to the argument
2429     value if it can (i.e., so long as the value is meaningful),
2430     and returns 1 if successful else 0.
2431
2432     See descriptions of tunable parameters above.
2433
2434 */
2435
2436 #if __STD_C
2437 int mALLOPt(int param_number, int value)
2438 #else
2439 int mALLOPt(param_number, value) int param_number; int value;
2440 #endif
2441 {
2442   switch(param_number)
2443   {
2444     case M_TRIM_THRESHOLD:
2445       trim_threshold = value; return 1;
2446     case M_TOP_PAD:
2447       top_pad = value; return 1;
2448     case M_MMAP_THRESHOLD:
2449       mmap_threshold = value; return 1;
2450     case M_MMAP_MAX:
2451 #if HAVE_MMAP
2452       n_mmaps_max = value; return 1;
2453 #else
2454       if (value != 0) return 0; else  n_mmaps_max = value; return 1;
2455 #endif
2456
2457     default:
2458       return 0;
2459   }
2460 }
2461
2462 int initf_malloc(void)
2463 {
2464 #if CONFIG_VAL(SYS_MALLOC_F_LEN)
2465         assert(gd->malloc_base);        /* Set up by crt0.S */
2466         gd->malloc_limit = CONFIG_VAL(SYS_MALLOC_F_LEN);
2467         gd->malloc_ptr = 0;
2468 #endif
2469
2470         return 0;
2471 }
2472
2473 /*
2474
2475 History:
2476
2477     V2.6.6 Sun Dec  5 07:42:19 1999  Doug Lea  (dl at gee)
2478       * return null for negative arguments
2479       * Added Several WIN32 cleanups from Martin C. Fong <mcfong@yahoo.com>
2480          * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
2481           (e.g. WIN32 platforms)
2482          * Cleanup up header file inclusion for WIN32 platforms
2483          * Cleanup code to avoid Microsoft Visual C++ compiler complaints
2484          * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
2485            memory allocation routines
2486          * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
2487          * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
2488            usage of 'assert' in non-WIN32 code
2489          * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
2490            avoid infinite loop
2491       * Always call 'fREe()' rather than 'free()'
2492
2493     V2.6.5 Wed Jun 17 15:57:31 1998  Doug Lea  (dl at gee)
2494       * Fixed ordering problem with boundary-stamping
2495
2496     V2.6.3 Sun May 19 08:17:58 1996  Doug Lea  (dl at gee)
2497       * Added pvalloc, as recommended by H.J. Liu
2498       * Added 64bit pointer support mainly from Wolfram Gloger
2499       * Added anonymously donated WIN32 sbrk emulation
2500       * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
2501       * malloc_extend_top: fix mask error that caused wastage after
2502         foreign sbrks
2503       * Add linux mremap support code from HJ Liu
2504
2505     V2.6.2 Tue Dec  5 06:52:55 1995  Doug Lea  (dl at gee)
2506       * Integrated most documentation with the code.
2507       * Add support for mmap, with help from
2508         Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2509       * Use last_remainder in more cases.
2510       * Pack bins using idea from  colin@nyx10.cs.du.edu
2511       * Use ordered bins instead of best-fit threshhold
2512       * Eliminate block-local decls to simplify tracing and debugging.
2513       * Support another case of realloc via move into top
2514       * Fix error occuring when initial sbrk_base not word-aligned.
2515       * Rely on page size for units instead of SBRK_UNIT to
2516         avoid surprises about sbrk alignment conventions.
2517       * Add mallinfo, mallopt. Thanks to Raymond Nijssen
2518         (raymond@es.ele.tue.nl) for the suggestion.
2519       * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
2520       * More precautions for cases where other routines call sbrk,
2521         courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
2522       * Added macros etc., allowing use in linux libc from
2523         H.J. Lu (hjl@gnu.ai.mit.edu)
2524       * Inverted this history list
2525
2526     V2.6.1 Sat Dec  2 14:10:57 1995  Doug Lea  (dl at gee)
2527       * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
2528       * Removed all preallocation code since under current scheme
2529         the work required to undo bad preallocations exceeds
2530         the work saved in good cases for most test programs.
2531       * No longer use return list or unconsolidated bins since
2532         no scheme using them consistently outperforms those that don't
2533         given above changes.
2534       * Use best fit for very large chunks to prevent some worst-cases.
2535       * Added some support for debugging
2536
2537     V2.6.0 Sat Nov  4 07:05:23 1995  Doug Lea  (dl at gee)
2538       * Removed footers when chunks are in use. Thanks to
2539         Paul Wilson (wilson@cs.texas.edu) for the suggestion.
2540
2541     V2.5.4 Wed Nov  1 07:54:51 1995  Doug Lea  (dl at gee)
2542       * Added malloc_trim, with help from Wolfram Gloger
2543         (wmglo@Dent.MED.Uni-Muenchen.DE).
2544
2545     V2.5.3 Tue Apr 26 10:16:01 1994  Doug Lea  (dl at g)
2546
2547     V2.5.2 Tue Apr  5 16:20:40 1994  Doug Lea  (dl at g)
2548       * realloc: try to expand in both directions
2549       * malloc: swap order of clean-bin strategy;
2550       * realloc: only conditionally expand backwards
2551       * Try not to scavenge used bins
2552       * Use bin counts as a guide to preallocation
2553       * Occasionally bin return list chunks in first scan
2554       * Add a few optimizations from colin@nyx10.cs.du.edu
2555
2556     V2.5.1 Sat Aug 14 15:40:43 1993  Doug Lea  (dl at g)
2557       * faster bin computation & slightly different binning
2558       * merged all consolidations to one part of malloc proper
2559          (eliminating old malloc_find_space & malloc_clean_bin)
2560       * Scan 2 returns chunks (not just 1)
2561       * Propagate failure in realloc if malloc returns 0
2562       * Add stuff to allow compilation on non-ANSI compilers
2563           from kpv@research.att.com
2564
2565     V2.5 Sat Aug  7 07:41:59 1993  Doug Lea  (dl at g.oswego.edu)
2566       * removed potential for odd address access in prev_chunk
2567       * removed dependency on getpagesize.h
2568       * misc cosmetics and a bit more internal documentation
2569       * anticosmetics: mangled names in macros to evade debugger strangeness
2570       * tested on sparc, hp-700, dec-mips, rs6000
2571           with gcc & native cc (hp, dec only) allowing
2572           Detlefs & Zorn comparison study (in SIGPLAN Notices.)
2573
2574     Trial version Fri Aug 28 13:14:29 1992  Doug Lea  (dl at g.oswego.edu)
2575       * Based loosely on libg++-1.2X malloc. (It retains some of the overall
2576          structure of old version,  but most details differ.)
2577
2578 */