1/* Malloc implementation for multiple threads without lock contention.
2 Copyright (C) 1996-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Wolfram Gloger <wg@malloc.de>
5 and Doug Lea <dl@cs.oswego.edu>, 2001.
6
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License as
9 published by the Free Software Foundation; either version 2.1 of the
10 License, or (at your option) any later version.
11
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, see <http://www.gnu.org/licenses/>. */
20
21/*
22 This is a version (aka ptmalloc2) of malloc/free/realloc written by
23 Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.
24
25 There have been substantial changes made after the integration into
26 glibc in all parts of the code. Do not look for much commonality
27 with the ptmalloc2 version.
28
29* Version ptmalloc2-20011215
30 based on:
31 VERSION 2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
32
33* Quickstart
34
35 In order to compile this implementation, a Makefile is provided with
36 the ptmalloc2 distribution, which has pre-defined targets for some
37 popular systems (e.g. "make posix" for Posix threads). All that is
38 typically required with regard to compiler flags is the selection of
39 the thread package via defining one out of USE_PTHREADS, USE_THR or
40 USE_SPROC. Check the thread-m.h file for what effects this has.
41 Many/most systems will additionally require USE_TSD_DATA_HACK to be
42 defined, so this is the default for "make posix".
43
44* Why use this malloc?
45
46 This is not the fastest, most space-conserving, most portable, or
47 most tunable malloc ever written. However it is among the fastest
48 while also being among the most space-conserving, portable and tunable.
49 Consistent balance across these factors results in a good general-purpose
50 allocator for malloc-intensive programs.
51
52 The main properties of the algorithms are:
53 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
54 with ties normally decided via FIFO (i.e. least recently used).
55 * For small (<= 64 bytes by default) requests, it is a caching
56 allocator, that maintains pools of quickly recycled chunks.
57 * In between, and for combinations of large and small requests, it does
58 the best it can trying to meet both goals at once.
59 * For very large requests (>= 128KB by default), it relies on system
60 memory mapping facilities, if supported.
61
62 For a longer but slightly out of date high-level description, see
63 http://gee.cs.oswego.edu/dl/html/malloc.html
64
65 You may already by default be using a C library containing a malloc
66 that is based on some version of this malloc (for example in
67 linux). You might still want to use the one in this file in order to
68 customize settings or to avoid overheads associated with library
69 versions.
70
71* Contents, described in more detail in "description of public routines" below.
72
73 Standard (ANSI/SVID/...) functions:
74 malloc(size_t n);
75 calloc(size_t n_elements, size_t element_size);
76 free(void* p);
77 realloc(void* p, size_t n);
78 memalign(size_t alignment, size_t n);
79 valloc(size_t n);
80 mallinfo()
81 mallopt(int parameter_number, int parameter_value)
82
83 Additional functions:
84 independent_calloc(size_t n_elements, size_t size, void* chunks[]);
85 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
86 pvalloc(size_t n);
87 cfree(void* p);
88 malloc_trim(size_t pad);
89 malloc_usable_size(void* p);
90 malloc_stats();
91
92* Vital statistics:
93
94 Supported pointer representation: 4 or 8 bytes
95 Supported size_t representation: 4 or 8 bytes
96 Note that size_t is allowed to be 4 bytes even if pointers are 8.
97 You can adjust this by defining INTERNAL_SIZE_T
98
99 Alignment: 2 * sizeof(size_t) (default)
100 (i.e., 8 byte alignment with 4byte size_t). This suffices for
101 nearly all current machines and C compilers. However, you can
102 define MALLOC_ALIGNMENT to be wider than this if necessary.
103
104 Minimum overhead per allocated chunk: 4 or 8 bytes
105 Each malloced chunk has a hidden word of overhead holding size
106 and status information.
107
108 Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)
109 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)
110
111 When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte
112 ptrs but 4 byte size) or 24 (for 8/8) additional bytes are
113 needed; 4 (8) for a trailing size field and 8 (16) bytes for
114 free list pointers. Thus, the minimum allocatable size is
115 16/24/32 bytes.
116
117 Even a request for zero bytes (i.e., malloc(0)) returns a
118 pointer to something of the minimum allocatable size.
119
120 The maximum overhead wastage (i.e., number of extra bytes
121 allocated than were requested in malloc) is less than or equal
122 to the minimum size, except for requests >= mmap_threshold that
123 are serviced via mmap(), where the worst case wastage is 2 *
124 sizeof(size_t) bytes plus the remainder from a system page (the
125 minimal mmap unit); typically 4096 or 8192 bytes.
126
127 Maximum allocated size: 4-byte size_t: 2^32 minus about two pages
128 8-byte size_t: 2^64 minus about two pages
129
130 It is assumed that (possibly signed) size_t values suffice to
131 represent chunk sizes. `Possibly signed' is due to the fact
132 that `size_t' may be defined on a system as either a signed or
133 an unsigned type. The ISO C standard says that it must be
134 unsigned, but a few systems are known not to adhere to this.
135 Additionally, even when size_t is unsigned, sbrk (which is by
136 default used to obtain memory from system) accepts signed
137 arguments, and may not be able to handle size_t-wide arguments
138 with negative sign bit. Generally, values that would
139 appear as negative after accounting for overhead and alignment
140 are supported only via mmap(), which does not have this
141 limitation.
142
143 Requests for sizes outside the allowed range will perform an optional
144 failure action and then return null. (Requests may also
145 also fail because a system is out of memory.)
146
147 Thread-safety: thread-safe
148
149 Compliance: I believe it is compliant with the 1997 Single Unix Specification
150 Also SVID/XPG, ANSI C, and probably others as well.
151
152* Synopsis of compile-time options:
153
154 People have reported using previous versions of this malloc on all
155 versions of Unix, sometimes by tweaking some of the defines
156 below. It has been tested most extensively on Solaris and Linux.
157 People also report using it in stand-alone embedded systems.
158
159 The implementation is in straight, hand-tuned ANSI C. It is not
160 at all modular. (Sorry!) It uses a lot of macros. To be at all
161 usable, this code should be compiled using an optimizing compiler
162 (for example gcc -O3) that can simplify expressions and control
163 paths. (FAQ: some macros import variables as arguments rather than
164 declare locals because people reported that some debuggers
165 otherwise get confused.)
166
167 OPTION DEFAULT VALUE
168
169 Compilation Environment options:
170
171 HAVE_MREMAP 0
172
173 Changing default word sizes:
174
175 INTERNAL_SIZE_T size_t
176
177 Configuration and functionality options:
178
179 USE_PUBLIC_MALLOC_WRAPPERS NOT defined
180 USE_MALLOC_LOCK NOT defined
181 MALLOC_DEBUG NOT defined
182 REALLOC_ZERO_BYTES_FREES 1
183 TRIM_FASTBINS 0
184
185 Options for customizing MORECORE:
186
187 MORECORE sbrk
188 MORECORE_FAILURE -1
189 MORECORE_CONTIGUOUS 1
190 MORECORE_CANNOT_TRIM NOT defined
191 MORECORE_CLEARS 1
192 MMAP_AS_MORECORE_SIZE (1024 * 1024)
193
194 Tuning options that are also dynamically changeable via mallopt:
195
196 DEFAULT_MXFAST 64 (for 32bit), 128 (for 64bit)
197 DEFAULT_TRIM_THRESHOLD 128 * 1024
198 DEFAULT_TOP_PAD 0
199 DEFAULT_MMAP_THRESHOLD 128 * 1024
200 DEFAULT_MMAP_MAX 65536
201
202 There are several other #defined constants and macros that you
203 probably don't want to touch unless you are extending or adapting malloc. */
204
205/*
206 void* is the pointer type that malloc should say it returns
207*/
208
209#ifndef void
210#define void void
211#endif /*void*/
212
213#include <stddef.h> /* for size_t */
214#include <stdlib.h> /* for getenv(), abort() */
215#include <unistd.h> /* for __libc_enable_secure */
216
217#include <atomic.h>
218#include <_itoa.h>
219#include <bits/wordsize.h>
220#include <sys/sysinfo.h>
221
222#include <ldsodefs.h>
223
224#include <unistd.h>
225#include <stdio.h> /* needed for malloc_stats */
226#include <errno.h>
227
228#include <shlib-compat.h>
229
230/* For uintptr_t. */
231#include <stdint.h>
232
233/* For va_arg, va_start, va_end. */
234#include <stdarg.h>
235
236/* For MIN, MAX, powerof2. */
237#include <sys/param.h>
238
239/* For ALIGN_UP et. al. */
240#include <libc-pointer-arith.h>
241
242#include <malloc/malloc-internal.h>
243
244/*
245 Debugging:
246
247 Because freed chunks may be overwritten with bookkeeping fields, this
248 malloc will often die when freed memory is overwritten by user
249 programs. This can be very effective (albeit in an annoying way)
250 in helping track down dangling pointers.
251
252 If you compile with -DMALLOC_DEBUG, a number of assertion checks are
253 enabled that will catch more memory errors. You probably won't be
254 able to make much sense of the actual assertion errors, but they
255 should help you locate incorrectly overwritten memory. The checking
256 is fairly extensive, and will slow down execution
257 noticeably. Calling malloc_stats or mallinfo with MALLOC_DEBUG set
258 will attempt to check every non-mmapped allocated and free chunk in
259 the course of computing the summmaries. (By nature, mmapped regions
260 cannot be checked very much automatically.)
261
262 Setting MALLOC_DEBUG may also be helpful if you are trying to modify
263 this code. The assertions in the check routines spell out in more
264 detail the assumptions and invariants underlying the algorithms.
265
266 Setting MALLOC_DEBUG does NOT provide an automated mechanism for
267 checking that all accesses to malloced memory stay within their
268 bounds. However, there are several add-ons and adaptations of this
269 or other mallocs available that do this.
270*/
271
272#ifndef MALLOC_DEBUG
273#define MALLOC_DEBUG 0
274#endif
275
276#ifdef NDEBUG
277# define assert(expr) ((void) 0)
278#else
279# define assert(expr) \
280 ((expr) \
281 ? ((void) 0) \
282 : __malloc_assert (#expr, __FILE__, __LINE__, __func__))
283
284extern const char *__progname;
285
286static void
287__malloc_assert (const char *assertion, const char *file, unsigned int line,
288 const char *function)
289{
290 (void) __fxprintf (NULL, "%s%s%s:%u: %s%sAssertion `%s' failed.\n",
291 __progname, __progname[0] ? ": " : "",
292 file, line,
293 function ? function : "", function ? ": " : "",
294 assertion);
295 fflush (stderr);
296 abort ();
297}
298#endif
299
300
301/*
302 REALLOC_ZERO_BYTES_FREES should be set if a call to
303 realloc with zero bytes should be the same as a call to free.
304 This is required by the C standard. Otherwise, since this malloc
305 returns a unique pointer for malloc(0), so does realloc(p, 0).
306*/
307
308#ifndef REALLOC_ZERO_BYTES_FREES
309#define REALLOC_ZERO_BYTES_FREES 1
310#endif
311
312/*
313 TRIM_FASTBINS controls whether free() of a very small chunk can
314 immediately lead to trimming. Setting to true (1) can reduce memory
315 footprint, but will almost always slow down programs that use a lot
316 of small chunks.
317
318 Define this only if you are willing to give up some speed to more
319 aggressively reduce system-level memory footprint when releasing
320 memory in programs that use many small chunks. You can get
321 essentially the same effect by setting MXFAST to 0, but this can
322 lead to even greater slowdowns in programs using many small chunks.
323 TRIM_FASTBINS is an in-between compile-time option, that disables
324 only those chunks bordering topmost memory from being placed in
325 fastbins.
326*/
327
328#ifndef TRIM_FASTBINS
329#define TRIM_FASTBINS 0
330#endif
331
332
333/* Definition for getting more memory from the OS. */
334#define MORECORE (*__morecore)
335#define MORECORE_FAILURE 0
336void * __default_morecore (ptrdiff_t);
337void *(*__morecore)(ptrdiff_t) = __default_morecore;
338
339
340#include <string.h>
341
342/*
343 MORECORE-related declarations. By default, rely on sbrk
344*/
345
346
347/*
348 MORECORE is the name of the routine to call to obtain more memory
349 from the system. See below for general guidance on writing
350 alternative MORECORE functions, as well as a version for WIN32 and a
351 sample version for pre-OSX macos.
352*/
353
354#ifndef MORECORE
355#define MORECORE sbrk
356#endif
357
358/*
359 MORECORE_FAILURE is the value returned upon failure of MORECORE
360 as well as mmap. Since it cannot be an otherwise valid memory address,
361 and must reflect values of standard sys calls, you probably ought not
362 try to redefine it.
363*/
364
365#ifndef MORECORE_FAILURE
366#define MORECORE_FAILURE (-1)
367#endif
368
369/*
370 If MORECORE_CONTIGUOUS is true, take advantage of fact that
371 consecutive calls to MORECORE with positive arguments always return
372 contiguous increasing addresses. This is true of unix sbrk. Even
373 if not defined, when regions happen to be contiguous, malloc will
374 permit allocations spanning regions obtained from different
375 calls. But defining this when applicable enables some stronger
376 consistency checks and space efficiencies.
377*/
378
379#ifndef MORECORE_CONTIGUOUS
380#define MORECORE_CONTIGUOUS 1
381#endif
382
383/*
384 Define MORECORE_CANNOT_TRIM if your version of MORECORE
385 cannot release space back to the system when given negative
386 arguments. This is generally necessary only if you are using
387 a hand-crafted MORECORE function that cannot handle negative arguments.
388*/
389
390/* #define MORECORE_CANNOT_TRIM */
391
392/* MORECORE_CLEARS (default 1)
393 The degree to which the routine mapped to MORECORE zeroes out
394 memory: never (0), only for newly allocated space (1) or always
395 (2). The distinction between (1) and (2) is necessary because on
396 some systems, if the application first decrements and then
397 increments the break value, the contents of the reallocated space
398 are unspecified.
399 */
400
401#ifndef MORECORE_CLEARS
402# define MORECORE_CLEARS 1
403#endif
404
405
406/*
407 MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if
408 sbrk fails, and mmap is used as a backup. The value must be a
409 multiple of page size. This backup strategy generally applies only
410 when systems have "holes" in address space, so sbrk cannot perform
411 contiguous expansion, but there is still space available on system.
412 On systems for which this is known to be useful (i.e. most linux
413 kernels), this occurs only when programs allocate huge amounts of
414 memory. Between this, and the fact that mmap regions tend to be
415 limited, the size should be large, to avoid too many mmap calls and
416 thus avoid running out of kernel resources. */
417
418#ifndef MMAP_AS_MORECORE_SIZE
419#define MMAP_AS_MORECORE_SIZE (1024 * 1024)
420#endif
421
422/*
423 Define HAVE_MREMAP to make realloc() use mremap() to re-allocate
424 large blocks.
425*/
426
427#ifndef HAVE_MREMAP
428#define HAVE_MREMAP 0
429#endif
430
431/* We may need to support __malloc_initialize_hook for backwards
432 compatibility. */
433
434#if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_24)
435# define HAVE_MALLOC_INIT_HOOK 1
436#else
437# define HAVE_MALLOC_INIT_HOOK 0
438#endif
439
440
441/*
442 This version of malloc supports the standard SVID/XPG mallinfo
443 routine that returns a struct containing usage properties and
444 statistics. It should work on any SVID/XPG compliant system that has
445 a /usr/include/malloc.h defining struct mallinfo. (If you'd like to
446 install such a thing yourself, cut out the preliminary declarations
447 as described above and below and save them in a malloc.h file. But
448 there's no compelling reason to bother to do this.)
449
450 The main declaration needed is the mallinfo struct that is returned
451 (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a
452 bunch of fields that are not even meaningful in this version of
453 malloc. These fields are are instead filled by mallinfo() with
454 other numbers that might be of interest.
455*/
456
457
458/* ---------- description of public routines ------------ */
459
460/*
461 malloc(size_t n)
462 Returns a pointer to a newly allocated chunk of at least n bytes, or null
463 if no space is available. Additionally, on failure, errno is
464 set to ENOMEM on ANSI C systems.
465
466 If n is zero, malloc returns a minumum-sized chunk. (The minimum
467 size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
468 systems.) On most systems, size_t is an unsigned type, so calls
469 with negative arguments are interpreted as requests for huge amounts
470 of space, which will often fail. The maximum supported value of n
471 differs across systems, but is in all cases less than the maximum
472 representable value of a size_t.
473*/
474void* __libc_malloc(size_t);
475libc_hidden_proto (__libc_malloc)
476
477/*
478 free(void* p)
479 Releases the chunk of memory pointed to by p, that had been previously
480 allocated using malloc or a related routine such as realloc.
481 It has no effect if p is null. It can have arbitrary (i.e., bad!)
482 effects if p has already been freed.
483
484 Unless disabled (using mallopt), freeing very large spaces will
485 when possible, automatically trigger operations that give
486 back unused memory to the system, thus reducing program footprint.
487*/
488void __libc_free(void*);
489libc_hidden_proto (__libc_free)
490
491/*
492 calloc(size_t n_elements, size_t element_size);
493 Returns a pointer to n_elements * element_size bytes, with all locations
494 set to zero.
495*/
496void* __libc_calloc(size_t, size_t);
497
498/*
499 realloc(void* p, size_t n)
500 Returns a pointer to a chunk of size n that contains the same data
501 as does chunk p up to the minimum of (n, p's size) bytes, or null
502 if no space is available.
503
504 The returned pointer may or may not be the same as p. The algorithm
505 prefers extending p when possible, otherwise it employs the
506 equivalent of a malloc-copy-free sequence.
507
508 If p is null, realloc is equivalent to malloc.
509
510 If space is not available, realloc returns null, errno is set (if on
511 ANSI) and p is NOT freed.
512
513 if n is for fewer bytes than already held by p, the newly unused
514 space is lopped off and freed if possible. Unless the #define
515 REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of
516 zero (re)allocates a minimum-sized chunk.
517
518 Large chunks that were internally obtained via mmap will always
519 be reallocated using malloc-copy-free sequences unless
520 the system supports MREMAP (currently only linux).
521
522 The old unix realloc convention of allowing the last-free'd chunk
523 to be used as an argument to realloc is not supported.
524*/
525void* __libc_realloc(void*, size_t);
526libc_hidden_proto (__libc_realloc)
527
528/*
529 memalign(size_t alignment, size_t n);
530 Returns a pointer to a newly allocated chunk of n bytes, aligned
531 in accord with the alignment argument.
532
533 The alignment argument should be a power of two. If the argument is
534 not a power of two, the nearest greater power is used.
535 8-byte alignment is guaranteed by normal malloc calls, so don't
536 bother calling memalign with an argument of 8 or less.
537
538 Overreliance on memalign is a sure way to fragment space.
539*/
540void* __libc_memalign(size_t, size_t);
541libc_hidden_proto (__libc_memalign)
542
543/*
544 valloc(size_t n);
545 Equivalent to memalign(pagesize, n), where pagesize is the page
546 size of the system. If the pagesize is unknown, 4096 is used.
547*/
548void* __libc_valloc(size_t);
549
550
551
552/*
553 mallopt(int parameter_number, int parameter_value)
554 Sets tunable parameters The format is to provide a
555 (parameter-number, parameter-value) pair. mallopt then sets the
556 corresponding parameter to the argument value if it can (i.e., so
557 long as the value is meaningful), and returns 1 if successful else
558 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,
559 normally defined in malloc.h. Only one of these (M_MXFAST) is used
560 in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,
561 so setting them has no effect. But this malloc also supports four
562 other options in mallopt. See below for details. Briefly, supported
563 parameters are as follows (listed defaults are for "typical"
564 configurations).
565
566 Symbol param # default allowed param values
567 M_MXFAST 1 64 0-80 (0 disables fastbins)
568 M_TRIM_THRESHOLD -1 128*1024 any (-1U disables trimming)
569 M_TOP_PAD -2 0 any
570 M_MMAP_THRESHOLD -3 128*1024 any (or 0 if no MMAP support)
571 M_MMAP_MAX -4 65536 any (0 disables use of mmap)
572*/
573int __libc_mallopt(int, int);
574libc_hidden_proto (__libc_mallopt)
575
576
577/*
578 mallinfo()
579 Returns (by copy) a struct containing various summary statistics:
580
581 arena: current total non-mmapped bytes allocated from system
582 ordblks: the number of free chunks
583 smblks: the number of fastbin blocks (i.e., small chunks that
584 have been freed but not use resused or consolidated)
585 hblks: current number of mmapped regions
586 hblkhd: total bytes held in mmapped regions
587 usmblks: always 0
588 fsmblks: total bytes held in fastbin blocks
589 uordblks: current total allocated space (normal or mmapped)
590 fordblks: total free space
591 keepcost: the maximum number of bytes that could ideally be released
592 back to system via malloc_trim. ("ideally" means that
593 it ignores page restrictions etc.)
594
595 Because these fields are ints, but internal bookkeeping may
596 be kept as longs, the reported values may wrap around zero and
597 thus be inaccurate.
598*/
599struct mallinfo __libc_mallinfo(void);
600
601
602/*
603 pvalloc(size_t n);
604 Equivalent to valloc(minimum-page-that-holds(n)), that is,
605 round up n to nearest pagesize.
606 */
607void* __libc_pvalloc(size_t);
608
609/*
610 malloc_trim(size_t pad);
611
612 If possible, gives memory back to the system (via negative
613 arguments to sbrk) if there is unused memory at the `high' end of
614 the malloc pool. You can call this after freeing large blocks of
615 memory to potentially reduce the system-level memory requirements
616 of a program. However, it cannot guarantee to reduce memory. Under
617 some allocation patterns, some large free blocks of memory will be
618 locked between two used chunks, so they cannot be given back to
619 the system.
620
621 The `pad' argument to malloc_trim represents the amount of free
622 trailing space to leave untrimmed. If this argument is zero,
623 only the minimum amount of memory to maintain internal data
624 structures will be left (one page or less). Non-zero arguments
625 can be supplied to maintain enough trailing space to service
626 future expected allocations without having to re-obtain memory
627 from the system.
628
629 Malloc_trim returns 1 if it actually released any memory, else 0.
630 On systems that do not support "negative sbrks", it will always
631 return 0.
632*/
633int __malloc_trim(size_t);
634
635/*
636 malloc_usable_size(void* p);
637
638 Returns the number of bytes you can actually use in
639 an allocated chunk, which may be more than you requested (although
640 often not) due to alignment and minimum size constraints.
641 You can use this many bytes without worrying about
642 overwriting other allocated objects. This is not a particularly great
643 programming practice. malloc_usable_size can be more useful in
644 debugging and assertions, for example:
645
646 p = malloc(n);
647 assert(malloc_usable_size(p) >= 256);
648
649*/
650size_t __malloc_usable_size(void*);
651
652/*
653 malloc_stats();
654 Prints on stderr the amount of space obtained from the system (both
655 via sbrk and mmap), the maximum amount (which may be more than
656 current if malloc_trim and/or munmap got called), and the current
657 number of bytes allocated via malloc (or realloc, etc) but not yet
658 freed. Note that this is the number of bytes allocated, not the
659 number requested. It will be larger than the number requested
660 because of alignment and bookkeeping overhead. Because it includes
661 alignment wastage as being in use, this figure may be greater than
662 zero even when no user-level chunks are allocated.
663
664 The reported current and maximum system memory can be inaccurate if
665 a program makes other calls to system memory allocation functions
666 (normally sbrk) outside of malloc.
667
668 malloc_stats prints only the most commonly interesting statistics.
669 More information can be obtained by calling mallinfo.
670
671*/
672void __malloc_stats(void);
673
674/*
675 malloc_get_state(void);
676
677 Returns the state of all malloc variables in an opaque data
678 structure.
679*/
680void* __malloc_get_state(void);
681
682/*
683 malloc_set_state(void* state);
684
685 Restore the state of all malloc variables from data obtained with
686 malloc_get_state().
687*/
688int __malloc_set_state(void*);
689
690/*
691 posix_memalign(void **memptr, size_t alignment, size_t size);
692
693 POSIX wrapper like memalign(), checking for validity of size.
694*/
695int __posix_memalign(void **, size_t, size_t);
696
697/* mallopt tuning options */
698
699/*
700 M_MXFAST is the maximum request size used for "fastbins", special bins
701 that hold returned chunks without consolidating their spaces. This
702 enables future requests for chunks of the same size to be handled
703 very quickly, but can increase fragmentation, and thus increase the
704 overall memory footprint of a program.
705
706 This malloc manages fastbins very conservatively yet still
707 efficiently, so fragmentation is rarely a problem for values less
708 than or equal to the default. The maximum supported value of MXFAST
709 is 80. You wouldn't want it any higher than this anyway. Fastbins
710 are designed especially for use with many small structs, objects or
711 strings -- the default handles structs/objects/arrays with sizes up
712 to 8 4byte fields, or small strings representing words, tokens,
713 etc. Using fastbins for larger objects normally worsens
714 fragmentation without improving speed.
715
716 M_MXFAST is set in REQUEST size units. It is internally used in
717 chunksize units, which adds padding and alignment. You can reduce
718 M_MXFAST to 0 to disable all use of fastbins. This causes the malloc
719 algorithm to be a closer approximation of fifo-best-fit in all cases,
720 not just for larger requests, but will generally cause it to be
721 slower.
722*/
723
724
725/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */
726#ifndef M_MXFAST
727#define M_MXFAST 1
728#endif
729
730#ifndef DEFAULT_MXFAST
731#define DEFAULT_MXFAST (64 * SIZE_SZ / 4)
732#endif
733
734
735/*
736 M_TRIM_THRESHOLD is the maximum amount of unused top-most memory
737 to keep before releasing via malloc_trim in free().
738
739 Automatic trimming is mainly useful in long-lived programs.
740 Because trimming via sbrk can be slow on some systems, and can
741 sometimes be wasteful (in cases where programs immediately
742 afterward allocate more large chunks) the value should be high
743 enough so that your overall system performance would improve by
744 releasing this much memory.
745
746 The trim threshold and the mmap control parameters (see below)
747 can be traded off with one another. Trimming and mmapping are
748 two different ways of releasing unused memory back to the
749 system. Between these two, it is often possible to keep
750 system-level demands of a long-lived program down to a bare
751 minimum. For example, in one test suite of sessions measuring
752 the XF86 X server on Linux, using a trim threshold of 128K and a
753 mmap threshold of 192K led to near-minimal long term resource
754 consumption.
755
756 If you are using this malloc in a long-lived program, it should
757 pay to experiment with these values. As a rough guide, you
758 might set to a value close to the average size of a process
759 (program) running on your system. Releasing this much memory
760 would allow such a process to run in memory. Generally, it's
761 worth it to tune for trimming rather tham memory mapping when a
762 program undergoes phases where several large chunks are
763 allocated and released in ways that can reuse each other's
764 storage, perhaps mixed with phases where there are no such
765 chunks at all. And in well-behaved long-lived programs,
766 controlling release of large blocks via trimming versus mapping
767 is usually faster.
768
769 However, in most programs, these parameters serve mainly as
770 protection against the system-level effects of carrying around
771 massive amounts of unneeded memory. Since frequent calls to
772 sbrk, mmap, and munmap otherwise degrade performance, the default
773 parameters are set to relatively high values that serve only as
774 safeguards.
775
776 The trim value It must be greater than page size to have any useful
777 effect. To disable trimming completely, you can set to
778 (unsigned long)(-1)
779
780 Trim settings interact with fastbin (MXFAST) settings: Unless
781 TRIM_FASTBINS is defined, automatic trimming never takes place upon
782 freeing a chunk with size less than or equal to MXFAST. Trimming is
783 instead delayed until subsequent freeing of larger chunks. However,
784 you can still force an attempted trim by calling malloc_trim.
785
786 Also, trimming is not generally possible in cases where
787 the main arena is obtained via mmap.
788
789 Note that the trick some people use of mallocing a huge space and
790 then freeing it at program startup, in an attempt to reserve system
791 memory, doesn't have the intended effect under automatic trimming,
792 since that memory will immediately be returned to the system.
793*/
794
795#define M_TRIM_THRESHOLD -1
796
797#ifndef DEFAULT_TRIM_THRESHOLD
798#define DEFAULT_TRIM_THRESHOLD (128 * 1024)
799#endif
800
801/*
802 M_TOP_PAD is the amount of extra `padding' space to allocate or
803 retain whenever sbrk is called. It is used in two ways internally:
804
805 * When sbrk is called to extend the top of the arena to satisfy
806 a new malloc request, this much padding is added to the sbrk
807 request.
808
809 * When malloc_trim is called automatically from free(),
810 it is used as the `pad' argument.
811
812 In both cases, the actual amount of padding is rounded
813 so that the end of the arena is always a system page boundary.
814
815 The main reason for using padding is to avoid calling sbrk so
816 often. Having even a small pad greatly reduces the likelihood
817 that nearly every malloc request during program start-up (or
818 after trimming) will invoke sbrk, which needlessly wastes
819 time.
820
821 Automatic rounding-up to page-size units is normally sufficient
822 to avoid measurable overhead, so the default is 0. However, in
823 systems where sbrk is relatively slow, it can pay to increase
824 this value, at the expense of carrying around more memory than
825 the program needs.
826*/
827
828#define M_TOP_PAD -2
829
830#ifndef DEFAULT_TOP_PAD
831#define DEFAULT_TOP_PAD (0)
832#endif
833
834/*
835 MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically
836 adjusted MMAP_THRESHOLD.
837*/
838
839#ifndef DEFAULT_MMAP_THRESHOLD_MIN
840#define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024)
841#endif
842
843#ifndef DEFAULT_MMAP_THRESHOLD_MAX
844 /* For 32-bit platforms we cannot increase the maximum mmap
845 threshold much because it is also the minimum value for the
846 maximum heap size and its alignment. Going above 512k (i.e., 1M
847 for new heaps) wastes too much address space. */
848# if __WORDSIZE == 32
849# define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
850# else
851# define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
852# endif
853#endif
854
855/*
856 M_MMAP_THRESHOLD is the request size threshold for using mmap()
857 to service a request. Requests of at least this size that cannot
858 be allocated using already-existing space will be serviced via mmap.
859 (If enough normal freed space already exists it is used instead.)
860
861 Using mmap segregates relatively large chunks of memory so that
862 they can be individually obtained and released from the host
863 system. A request serviced through mmap is never reused by any
864 other request (at least not directly; the system may just so
865 happen to remap successive requests to the same locations).
866
867 Segregating space in this way has the benefits that:
868
869 1. Mmapped space can ALWAYS be individually released back
870 to the system, which helps keep the system level memory
871 demands of a long-lived program low.
872 2. Mapped memory can never become `locked' between
873 other chunks, as can happen with normally allocated chunks, which
874 means that even trimming via malloc_trim would not release them.
875 3. On some systems with "holes" in address spaces, mmap can obtain
876 memory that sbrk cannot.
877
878 However, it has the disadvantages that:
879
880 1. The space cannot be reclaimed, consolidated, and then
881 used to service later requests, as happens with normal chunks.
882 2. It can lead to more wastage because of mmap page alignment
883 requirements
884 3. It causes malloc performance to be more dependent on host
885 system memory management support routines which may vary in
886 implementation quality and may impose arbitrary
887 limitations. Generally, servicing a request via normal
888 malloc steps is faster than going through a system's mmap.
889
890 The advantages of mmap nearly always outweigh disadvantages for
891 "large" chunks, but the value of "large" varies across systems. The
892 default is an empirically derived value that works well in most
893 systems.
894
895
896 Update in 2006:
897 The above was written in 2001. Since then the world has changed a lot.
898 Memory got bigger. Applications got bigger. The virtual address space
899 layout in 32 bit linux changed.
900
901 In the new situation, brk() and mmap space is shared and there are no
902 artificial limits on brk size imposed by the kernel. What is more,
903 applications have started using transient allocations larger than the
904 128Kb as was imagined in 2001.
905
906 The price for mmap is also high now; each time glibc mmaps from the
907 kernel, the kernel is forced to zero out the memory it gives to the
908 application. Zeroing memory is expensive and eats a lot of cache and
909 memory bandwidth. This has nothing to do with the efficiency of the
910 virtual memory system, by doing mmap the kernel just has no choice but
911 to zero.
912
913 In 2001, the kernel had a maximum size for brk() which was about 800
914 megabytes on 32 bit x86, at that point brk() would hit the first
915 mmaped shared libaries and couldn't expand anymore. With current 2.6
916 kernels, the VA space layout is different and brk() and mmap
917 both can span the entire heap at will.
918
919 Rather than using a static threshold for the brk/mmap tradeoff,
920 we are now using a simple dynamic one. The goal is still to avoid
921 fragmentation. The old goals we kept are
922 1) try to get the long lived large allocations to use mmap()
923 2) really large allocations should always use mmap()
924 and we're adding now:
925 3) transient allocations should use brk() to avoid forcing the kernel
926 having to zero memory over and over again
927
928 The implementation works with a sliding threshold, which is by default
929 limited to go between 128Kb and 32Mb (64Mb for 64 bitmachines) and starts
930 out at 128Kb as per the 2001 default.
931
932 This allows us to satisfy requirement 1) under the assumption that long
933 lived allocations are made early in the process' lifespan, before it has
934 started doing dynamic allocations of the same size (which will
935 increase the threshold).
936
937 The upperbound on the threshold satisfies requirement 2)
938
939 The threshold goes up in value when the application frees memory that was
940 allocated with the mmap allocator. The idea is that once the application
941 starts freeing memory of a certain size, it's highly probable that this is
942 a size the application uses for transient allocations. This estimator
943 is there to satisfy the new third requirement.
944
945*/
946
947#define M_MMAP_THRESHOLD -3
948
949#ifndef DEFAULT_MMAP_THRESHOLD
950#define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN
951#endif
952
953/*
954 M_MMAP_MAX is the maximum number of requests to simultaneously
955 service using mmap. This parameter exists because
956 some systems have a limited number of internal tables for
957 use by mmap, and using more than a few of them may degrade
958 performance.
959
960 The default is set to a value that serves only as a safeguard.
961 Setting to 0 disables use of mmap for servicing large requests.
962*/
963
964#define M_MMAP_MAX -4
965
966#ifndef DEFAULT_MMAP_MAX
967#define DEFAULT_MMAP_MAX (65536)
968#endif
969
970#include <malloc.h>
971
972#ifndef RETURN_ADDRESS
973#define RETURN_ADDRESS(X_) (NULL)
974#endif
975
976/* On some platforms we can compile internal, not exported functions better.
977 Let the environment provide a macro and define it to be empty if it
978 is not available. */
979#ifndef internal_function
980# define internal_function
981#endif
982
983/* Forward declarations. */
984struct malloc_chunk;
985typedef struct malloc_chunk* mchunkptr;
986
987/* Internal routines. */
988
989static void* _int_malloc(mstate, size_t);
990static void _int_free(mstate, mchunkptr, int);
991static void* _int_realloc(mstate, mchunkptr, INTERNAL_SIZE_T,
992 INTERNAL_SIZE_T);
993static void* _int_memalign(mstate, size_t, size_t);
994static void* _mid_memalign(size_t, size_t, void *);
995
996static void malloc_printerr(int action, const char *str, void *ptr, mstate av);
997
998static void* internal_function mem2mem_check(void *p, size_t sz);
999static int internal_function top_check(void);
1000static void internal_function munmap_chunk(mchunkptr p);
1001#if HAVE_MREMAP
1002static mchunkptr internal_function mremap_chunk(mchunkptr p, size_t new_size);
1003#endif
1004
1005static void* malloc_check(size_t sz, const void *caller);
1006static void free_check(void* mem, const void *caller);
1007static void* realloc_check(void* oldmem, size_t bytes,
1008 const void *caller);
1009static void* memalign_check(size_t alignment, size_t bytes,
1010 const void *caller);
1011
1012/* ------------------ MMAP support ------------------ */
1013
1014
1015#include <fcntl.h>
1016#include <sys/mman.h>
1017
1018#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1019# define MAP_ANONYMOUS MAP_ANON
1020#endif
1021
1022#ifndef MAP_NORESERVE
1023# define MAP_NORESERVE 0
1024#endif
1025
1026#define MMAP(addr, size, prot, flags) \
1027 __mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0)
1028
1029
1030/*
1031 ----------------------- Chunk representations -----------------------
1032*/
1033
1034
1035/*
1036 This struct declaration is misleading (but accurate and necessary).
1037 It declares a "view" into memory allowing access to necessary
1038 fields at known offsets from a given base. See explanation below.
1039*/
1040
1041struct malloc_chunk {
1042
1043 INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk (if free). */
1044 INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
1045
1046 struct malloc_chunk* fd; /* double links -- used only if free. */
1047 struct malloc_chunk* bk;
1048
1049 /* Only used for large blocks: pointer to next larger size. */
1050 struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
1051 struct malloc_chunk* bk_nextsize;
1052};
1053
1054
1055/*
1056 malloc_chunk details:
1057
1058 (The following includes lightly edited explanations by Colin Plumb.)
1059
1060 Chunks of memory are maintained using a `boundary tag' method as
1061 described in e.g., Knuth or Standish. (See the paper by Paul
1062 Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
1063 survey of such techniques.) Sizes of free chunks are stored both
1064 in the front of each chunk and at the end. This makes
1065 consolidating fragmented chunks into bigger chunks very fast. The
1066 size fields also hold bits representing whether chunks are free or
1067 in use.
1068
1069 An allocated chunk looks like this:
1070
1071
1072 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1073 | Size of previous chunk, if unallocated (P clear) |
1074 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1075 | Size of chunk, in bytes |A|M|P|
1076 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1077 | User data starts here... .
1078 . .
1079 . (malloc_usable_size() bytes) .
1080 . |
1081nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1082 | (size of chunk, but used for application data) |
1083 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1084 | Size of next chunk, in bytes |A|0|1|
1085 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1086
1087 Where "chunk" is the front of the chunk for the purpose of most of
1088 the malloc code, but "mem" is the pointer that is returned to the
1089 user. "Nextchunk" is the beginning of the next contiguous chunk.
1090
1091 Chunks always begin on even word boundaries, so the mem portion
1092 (which is returned to the user) is also on an even word boundary, and
1093 thus at least double-word aligned.
1094
1095 Free chunks are stored in circular doubly-linked lists, and look like this:
1096
1097 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1098 | Size of previous chunk, if unallocated (P clear) |
1099 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1100 `head:' | Size of chunk, in bytes |A|0|P|
1101 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1102 | Forward pointer to next chunk in list |
1103 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1104 | Back pointer to previous chunk in list |
1105 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1106 | Unused space (may be 0 bytes long) .
1107 . .
1108 . |
1109nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1110 `foot:' | Size of chunk, in bytes |
1111 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1112 | Size of next chunk, in bytes |A|0|0|
1113 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1114
1115 The P (PREV_INUSE) bit, stored in the unused low-order bit of the
1116 chunk size (which is always a multiple of two words), is an in-use
1117 bit for the *previous* chunk. If that bit is *clear*, then the
1118 word before the current chunk size contains the previous chunk
1119 size, and can be used to find the front of the previous chunk.
1120 The very first chunk allocated always has this bit set,
1121 preventing access to non-existent (or non-owned) memory. If
1122 prev_inuse is set for any given chunk, then you CANNOT determine
1123 the size of the previous chunk, and might even get a memory
1124 addressing fault when trying to do so.
1125
1126 The A (NON_MAIN_ARENA) bit is cleared for chunks on the initial,
1127 main arena, described by the main_arena variable. When additional
1128 threads are spawned, each thread receives its own arena (up to a
1129 configurable limit, after which arenas are reused for multiple
1130 threads), and the chunks in these arenas have the A bit set. To
1131 find the arena for a chunk on such a non-main arena, heap_for_ptr
1132 performs a bit mask operation and indirection through the ar_ptr
1133 member of the per-heap header heap_info (see arena.c).
1134
1135 Note that the `foot' of the current chunk is actually represented
1136 as the prev_size of the NEXT chunk. This makes it easier to
1137 deal with alignments etc but can be very confusing when trying
1138 to extend or adapt this code.
1139
1140 The three exceptions to all this are:
1141
1142 1. The special chunk `top' doesn't bother using the
1143 trailing size field since there is no next contiguous chunk
1144 that would have to index off it. After initialization, `top'
1145 is forced to always exist. If it would become less than
1146 MINSIZE bytes long, it is replenished.
1147
1148 2. Chunks allocated via mmap, which have the second-lowest-order
1149 bit M (IS_MMAPPED) set in their size fields. Because they are
1150 allocated one-by-one, each must contain its own trailing size
1151 field. If the M bit is set, the other bits are ignored
1152 (because mmapped chunks are neither in an arena, nor adjacent
1153 to a freed chunk). The M bit is also used for chunks which
1154 originally came from a dumped heap via malloc_set_state in
1155 hooks.c.
1156
1157 3. Chunks in fastbins are treated as allocated chunks from the
1158 point of view of the chunk allocator. They are consolidated
1159 with their neighbors only in bulk, in malloc_consolidate.
1160*/
1161
1162/*
1163 ---------- Size and alignment checks and conversions ----------
1164*/
1165
1166/* conversion from malloc headers to user pointers, and back */
1167
1168#define chunk2mem(p) ((void*)((char*)(p) + 2*SIZE_SZ))
1169#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))
1170
1171/* The smallest possible chunk */
1172#define MIN_CHUNK_SIZE (offsetof(struct malloc_chunk, fd_nextsize))
1173
1174/* The smallest size we can malloc is an aligned minimal chunk */
1175
1176#define MINSIZE \
1177 (unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
1178
1179/* Check if m has acceptable alignment */
1180
1181#define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
1182
1183#define misaligned_chunk(p) \
1184 ((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem (p)) \
1185 & MALLOC_ALIGN_MASK)
1186
1187
1188/*
1189 Check if a request is so large that it would wrap around zero when
1190 padded and aligned. To simplify some other code, the bound is made
1191 low enough so that adding MINSIZE will also not wrap around zero.
1192 */
1193
1194#define REQUEST_OUT_OF_RANGE(req) \
1195 ((unsigned long) (req) >= \
1196 (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE))
1197
1198/* pad request bytes into a usable size -- internal version */
1199
1200#define request2size(req) \
1201 (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
1202 MINSIZE : \
1203 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
1204
1205/* Same, except also perform argument check */
1206
1207#define checked_request2size(req, sz) \
1208 if (REQUEST_OUT_OF_RANGE (req)) { \
1209 __set_errno (ENOMEM); \
1210 return 0; \
1211 } \
1212 (sz) = request2size (req);
1213
1214/*
1215 --------------- Physical chunk operations ---------------
1216 */
1217
1218
1219/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
1220#define PREV_INUSE 0x1
1221
1222/* extract inuse bit of previous chunk */
1223#define prev_inuse(p) ((p)->mchunk_size & PREV_INUSE)
1224
1225
1226/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
1227#define IS_MMAPPED 0x2
1228
1229/* check for mmap()'ed chunk */
1230#define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)
1231
1232
1233/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
1234 from a non-main arena. This is only set immediately before handing
1235 the chunk to the user, if necessary. */
1236#define NON_MAIN_ARENA 0x4
1237
1238/* Check for chunk from main arena. */
1239#define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)
1240
1241/* Mark a chunk as not being on the main arena. */
1242#define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
1243
1244
1245/*
1246 Bits to mask off when extracting size
1247
1248 Note: IS_MMAPPED is intentionally not masked off from size field in
1249 macros for which mmapped chunks should never be seen. This should
1250 cause helpful core dumps to occur if it is tried by accident by
1251 people extending or adapting this malloc.
1252 */
1253#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
1254
1255/* Get size, ignoring use bits */
1256#define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))
1257
1258/* Like chunksize, but do not mask SIZE_BITS. */
1259#define chunksize_nomask(p) ((p)->mchunk_size)
1260
1261/* Ptr to next physical malloc_chunk. */
1262#define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))
1263
1264/* Size of the chunk below P. Only valid if prev_inuse (P). */
1265#define prev_size(p) ((p)->mchunk_prev_size)
1266
1267/* Set the size of the chunk below P. Only valid if prev_inuse (P). */
1268#define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))
1269
1270/* Ptr to previous physical malloc_chunk. Only valid if prev_inuse (P). */
1271#define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))
1272
1273/* Treat space at ptr + offset as a chunk */
1274#define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
1275
1276/* extract p's inuse bit */
1277#define inuse(p) \
1278 ((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
1279
1280/* set/clear chunk as being inuse without otherwise disturbing */
1281#define set_inuse(p) \
1282 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
1283
1284#define clear_inuse(p) \
1285 ((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
1286
1287
1288/* check/set/clear inuse bits in known places */
1289#define inuse_bit_at_offset(p, s) \
1290 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
1291
1292#define set_inuse_bit_at_offset(p, s) \
1293 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
1294
1295#define clear_inuse_bit_at_offset(p, s) \
1296 (((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
1297
1298
1299/* Set size at head, without disturbing its use bit */
1300#define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
1301
1302/* Set size/use field */
1303#define set_head(p, s) ((p)->mchunk_size = (s))
1304
1305/* Set size at footer (only when chunk is not in use) */
1306#define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
1307
1308
1309#pragma GCC poison mchunk_size
1310#pragma GCC poison mchunk_prev_size
1311
1312/*
1313 -------------------- Internal data structures --------------------
1314
1315 All internal state is held in an instance of malloc_state defined
1316 below. There are no other static variables, except in two optional
1317 cases:
1318 * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.
1319 * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor
1320 for mmap.
1321
1322 Beware of lots of tricks that minimize the total bookkeeping space
1323 requirements. The result is a little over 1K bytes (for 4byte
1324 pointers and size_t.)
1325 */
1326
1327/*
1328 Bins
1329
1330 An array of bin headers for free chunks. Each bin is doubly
1331 linked. The bins are approximately proportionally (log) spaced.
1332 There are a lot of these bins (128). This may look excessive, but
1333 works very well in practice. Most bins hold sizes that are
1334 unusual as malloc request sizes, but are more usual for fragments
1335 and consolidated sets of chunks, which is what these bins hold, so
1336 they can be found quickly. All procedures maintain the invariant
1337 that no consolidated chunk physically borders another one, so each
1338 chunk in a list is known to be preceeded and followed by either
1339 inuse chunks or the ends of memory.
1340
1341 Chunks in bins are kept in size order, with ties going to the
1342 approximately least recently used chunk. Ordering isn't needed
1343 for the small bins, which all contain the same-sized chunks, but
1344 facilitates best-fit allocation for larger chunks. These lists
1345 are just sequential. Keeping them in order almost never requires
1346 enough traversal to warrant using fancier ordered data
1347 structures.
1348
1349 Chunks of the same size are linked with the most
1350 recently freed at the front, and allocations are taken from the
1351 back. This results in LRU (FIFO) allocation order, which tends
1352 to give each chunk an equal opportunity to be consolidated with
1353 adjacent freed chunks, resulting in larger free chunks and less
1354 fragmentation.
1355
1356 To simplify use in double-linked lists, each bin header acts
1357 as a malloc_chunk. This avoids special-casing for headers.
1358 But to conserve space and improve locality, we allocate
1359 only the fd/bk pointers of bins, and then use repositioning tricks
1360 to treat these as the fields of a malloc_chunk*.
1361 */
1362
1363typedef struct malloc_chunk *mbinptr;
1364
1365/* addressing -- note that bin_at(0) does not exist */
1366#define bin_at(m, i) \
1367 (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \
1368 - offsetof (struct malloc_chunk, fd))
1369
1370/* analog of ++bin */
1371#define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1)))
1372
1373/* Reminders about list directionality within bins */
1374#define first(b) ((b)->fd)
1375#define last(b) ((b)->bk)
1376
1377/* Take a chunk off a bin list */
1378#define unlink(AV, P, BK, FD) { \
1379 FD = P->fd; \
1380 BK = P->bk; \
1381 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1382 malloc_printerr (check_action, "corrupted double-linked list", P, AV); \
1383 else { \
1384 FD->bk = BK; \
1385 BK->fd = FD; \
1386 if (!in_smallbin_range (chunksize_nomask (P)) \
1387 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \
1388 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \
1389 || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \
1390 malloc_printerr (check_action, \
1391 "corrupted double-linked list (not small)", \
1392 P, AV); \
1393 if (FD->fd_nextsize == NULL) { \
1394 if (P->fd_nextsize == P) \
1395 FD->fd_nextsize = FD->bk_nextsize = FD; \
1396 else { \
1397 FD->fd_nextsize = P->fd_nextsize; \
1398 FD->bk_nextsize = P->bk_nextsize; \
1399 P->fd_nextsize->bk_nextsize = FD; \
1400 P->bk_nextsize->fd_nextsize = FD; \
1401 } \
1402 } else { \
1403 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \
1404 P->bk_nextsize->fd_nextsize = P->fd_nextsize; \
1405 } \
1406 } \
1407 } \
1408}
1409
1410/*
1411 Indexing
1412
1413 Bins for sizes < 512 bytes contain chunks of all the same size, spaced
1414 8 bytes apart. Larger bins are approximately logarithmically spaced:
1415
1416 64 bins of size 8
1417 32 bins of size 64
1418 16 bins of size 512
1419 8 bins of size 4096
1420 4 bins of size 32768
1421 2 bins of size 262144
1422 1 bin of size what's left
1423
1424 There is actually a little bit of slop in the numbers in bin_index
1425 for the sake of speed. This makes no difference elsewhere.
1426
1427 The bins top out around 1MB because we expect to service large
1428 requests via mmap.
1429
1430 Bin 0 does not exist. Bin 1 is the unordered list; if that would be
1431 a valid chunk size the small bins are bumped up one.
1432 */
1433
1434#define NBINS 128
1435#define NSMALLBINS 64
1436#define SMALLBIN_WIDTH MALLOC_ALIGNMENT
1437#define SMALLBIN_CORRECTION (MALLOC_ALIGNMENT > 2 * SIZE_SZ)
1438#define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
1439
1440#define in_smallbin_range(sz) \
1441 ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
1442
1443#define smallbin_index(sz) \
1444 ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
1445 + SMALLBIN_CORRECTION)
1446
1447#define largebin_index_32(sz) \
1448 (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
1449 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1450 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1451 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1452 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1453 126)
1454
1455#define largebin_index_32_big(sz) \
1456 (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
1457 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1458 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1459 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1460 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1461 126)
1462
1463// XXX It remains to be seen whether it is good to keep the widths of
1464// XXX the buckets the same or whether it should be scaled by a factor
1465// XXX of two as well.
1466#define largebin_index_64(sz) \
1467 (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
1468 ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
1469 ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
1470 ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
1471 ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
1472 126)
1473
1474#define largebin_index(sz) \
1475 (SIZE_SZ == 8 ? largebin_index_64 (sz) \
1476 : MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
1477 : largebin_index_32 (sz))
1478
1479#define bin_index(sz) \
1480 ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
1481
1482
1483/*
1484 Unsorted chunks
1485
1486 All remainders from chunk splits, as well as all returned chunks,
1487 are first placed in the "unsorted" bin. They are then placed
1488 in regular bins after malloc gives them ONE chance to be used before
1489 binning. So, basically, the unsorted_chunks list acts as a queue,
1490 with chunks being placed on it in free (and malloc_consolidate),
1491 and taken off (to be either used or placed in bins) in malloc.
1492
1493 The NON_MAIN_ARENA flag is never set for unsorted chunks, so it
1494 does not have to be taken into account in size comparisons.
1495 */
1496
1497/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */
1498#define unsorted_chunks(M) (bin_at (M, 1))
1499
1500/*
1501 Top
1502
1503 The top-most available chunk (i.e., the one bordering the end of
1504 available memory) is treated specially. It is never included in
1505 any bin, is used only if no other chunk is available, and is
1506 released back to the system if it is very large (see
1507 M_TRIM_THRESHOLD). Because top initially
1508 points to its own bin with initial zero size, thus forcing
1509 extension on the first malloc request, we avoid having any special
1510 code in malloc to check whether it even exists yet. But we still
1511 need to do so when getting memory from system, so we make
1512 initial_top treat the bin as a legal but unusable chunk during the
1513 interval between initialization and the first call to
1514 sysmalloc. (This is somewhat delicate, since it relies on
1515 the 2 preceding words to be zero during this interval as well.)
1516 */
1517
1518/* Conveniently, the unsorted bin can be used as dummy top on first call */
1519#define initial_top(M) (unsorted_chunks (M))
1520
1521/*
1522 Binmap
1523
1524 To help compensate for the large number of bins, a one-level index
1525 structure is used for bin-by-bin searching. `binmap' is a
1526 bitvector recording whether bins are definitely empty so they can
1527 be skipped over during during traversals. The bits are NOT always
1528 cleared as soon as bins are empty, but instead only
1529 when they are noticed to be empty during traversal in malloc.
1530 */
1531
1532/* Conservatively use 32 bits per map word, even if on 64bit system */
1533#define BINMAPSHIFT 5
1534#define BITSPERMAP (1U << BINMAPSHIFT)
1535#define BINMAPSIZE (NBINS / BITSPERMAP)
1536
1537#define idx2block(i) ((i) >> BINMAPSHIFT)
1538#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1))))
1539
1540#define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i))
1541#define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i)))
1542#define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i))
1543
1544/*
1545 Fastbins
1546
1547 An array of lists holding recently freed small chunks. Fastbins
1548 are not doubly linked. It is faster to single-link them, and
1549 since chunks are never removed from the middles of these lists,
1550 double linking is not necessary. Also, unlike regular bins, they
1551 are not even processed in FIFO order (they use faster LIFO) since
1552 ordering doesn't much matter in the transient contexts in which
1553 fastbins are normally used.
1554
1555 Chunks in fastbins keep their inuse bit set, so they cannot
1556 be consolidated with other free chunks. malloc_consolidate
1557 releases all chunks in fastbins and consolidates them with
1558 other free chunks.
1559 */
1560
1561typedef struct malloc_chunk *mfastbinptr;
1562#define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
1563
1564/* offset 2 to use otherwise unindexable first 2 bins */
1565#define fastbin_index(sz) \
1566 ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
1567
1568
1569/* The maximum fastbin request size we support */
1570#define MAX_FAST_SIZE (80 * SIZE_SZ / 4)
1571
1572#define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
1573
1574/*
1575 FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()
1576 that triggers automatic consolidation of possibly-surrounding
1577 fastbin chunks. This is a heuristic, so the exact value should not
1578 matter too much. It is defined at half the default trim threshold as a
1579 compromise heuristic to only attempt consolidation if it is likely
1580 to lead to trimming. However, it is not dynamically tunable, since
1581 consolidation reduces fragmentation surrounding large chunks even
1582 if trimming is not used.
1583 */
1584
1585#define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL)
1586
1587/*
1588 Since the lowest 2 bits in max_fast don't matter in size comparisons,
1589 they are used as flags.
1590 */
1591
1592/*
1593 FASTCHUNKS_BIT held in max_fast indicates that there are probably
1594 some fastbin chunks. It is set true on entering a chunk into any
1595 fastbin, and cleared only in malloc_consolidate.
1596
1597 The truth value is inverted so that have_fastchunks will be true
1598 upon startup (since statics are zero-filled), simplifying
1599 initialization checks.
1600 */
1601
1602#define FASTCHUNKS_BIT (1U)
1603
1604#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0)
1605#define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT)
1606#define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT)
1607
1608/*
1609 NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous
1610 regions. Otherwise, contiguity is exploited in merging together,
1611 when possible, results from consecutive MORECORE calls.
1612
1613 The initial value comes from MORECORE_CONTIGUOUS, but is
1614 changed dynamically if mmap is ever used as an sbrk substitute.
1615 */
1616
1617#define NONCONTIGUOUS_BIT (2U)
1618
1619#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
1620#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
1621#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
1622#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
1623
1624/* ARENA_CORRUPTION_BIT is set if a memory corruption was detected on the
1625 arena. Such an arena is no longer used to allocate chunks. Chunks
1626 allocated in that arena before detecting corruption are not freed. */
1627
1628#define ARENA_CORRUPTION_BIT (4U)
1629
1630#define arena_is_corrupt(A) (((A)->flags & ARENA_CORRUPTION_BIT))
1631#define set_arena_corrupt(A) ((A)->flags |= ARENA_CORRUPTION_BIT)
1632
1633/*
1634 Set value of max_fast.
1635 Use impossibly small value if 0.
1636 Precondition: there are no existing fastbin chunks.
1637 Setting the value clears fastchunk bit but preserves noncontiguous bit.
1638 */
1639
1640#define set_max_fast(s) \
1641 global_max_fast = (((s) == 0) \
1642 ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK))
1643#define get_max_fast() global_max_fast
1644
1645
1646/*
1647 ----------- Internal state representation and initialization -----------
1648 */
1649
1650struct malloc_state
1651{
1652 /* Serialize access. */
1653 __libc_lock_define (, mutex);
1654
1655 /* Flags (formerly in max_fast). */
1656 int flags;
1657
1658 /* Fastbins */
1659 mfastbinptr fastbinsY[NFASTBINS];
1660
1661 /* Base of the topmost chunk -- not otherwise kept in a bin */
1662 mchunkptr top;
1663
1664 /* The remainder from the most recent split of a small request */
1665 mchunkptr last_remainder;
1666
1667 /* Normal bins packed as described above */
1668 mchunkptr bins[NBINS * 2 - 2];
1669
1670 /* Bitmap of bins */
1671 unsigned int binmap[BINMAPSIZE];
1672
1673 /* Linked list */
1674 struct malloc_state *next;
1675
1676 /* Linked list for free arenas. Access to this field is serialized
1677 by free_list_lock in arena.c. */
1678 struct malloc_state *next_free;
1679
1680 /* Number of threads attached to this arena. 0 if the arena is on
1681 the free list. Access to this field is serialized by
1682 free_list_lock in arena.c. */
1683 INTERNAL_SIZE_T attached_threads;
1684
1685 /* Memory allocated from the system in this arena. */
1686 INTERNAL_SIZE_T system_mem;
1687 INTERNAL_SIZE_T max_system_mem;
1688};
1689
1690struct malloc_par
1691{
1692 /* Tunable parameters */
1693 unsigned long trim_threshold;
1694 INTERNAL_SIZE_T top_pad;
1695 INTERNAL_SIZE_T mmap_threshold;
1696 INTERNAL_SIZE_T arena_test;
1697 INTERNAL_SIZE_T arena_max;
1698
1699 /* Memory map support */
1700 int n_mmaps;
1701 int n_mmaps_max;
1702 int max_n_mmaps;
1703 /* the mmap_threshold is dynamic, until the user sets
1704 it manually, at which point we need to disable any
1705 dynamic behavior. */
1706 int no_dyn_threshold;
1707
1708 /* Statistics */
1709 INTERNAL_SIZE_T mmapped_mem;
1710 INTERNAL_SIZE_T max_mmapped_mem;
1711
1712 /* First address handed out by MORECORE/sbrk. */
1713 char *sbrk_base;
1714};
1715
1716/* There are several instances of this struct ("arenas") in this
1717 malloc. If you are adapting this malloc in a way that does NOT use
1718 a static or mmapped malloc_state, you MUST explicitly zero-fill it
1719 before using. This malloc relies on the property that malloc_state
1720 is initialized to all zeroes (as is true of C statics). */
1721
1722static struct malloc_state main_arena =
1723{
1724 .mutex = _LIBC_LOCK_INITIALIZER,
1725 .next = &main_arena,
1726 .attached_threads = 1
1727};
1728
1729/* These variables are used for undumping support. Chunked are marked
1730 as using mmap, but we leave them alone if they fall into this
1731 range. NB: The chunk size for these chunks only includes the
1732 initial size field (of SIZE_SZ bytes), there is no trailing size
1733 field (unlike with regular mmapped chunks). */
1734static mchunkptr dumped_main_arena_start; /* Inclusive. */
1735static mchunkptr dumped_main_arena_end; /* Exclusive. */
1736
1737/* True if the pointer falls into the dumped arena. Use this after
1738 chunk_is_mmapped indicates a chunk is mmapped. */
1739#define DUMPED_MAIN_ARENA_CHUNK(p) \
1740 ((p) >= dumped_main_arena_start && (p) < dumped_main_arena_end)
1741
1742/* There is only one instance of the malloc parameters. */
1743
1744static struct malloc_par mp_ =
1745{
1746 .top_pad = DEFAULT_TOP_PAD,
1747 .n_mmaps_max = DEFAULT_MMAP_MAX,
1748 .mmap_threshold = DEFAULT_MMAP_THRESHOLD,
1749 .trim_threshold = DEFAULT_TRIM_THRESHOLD,
1750#define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8))
1751 .arena_test = NARENAS_FROM_NCORES (1)
1752};
1753
1754/* Maximum size of memory handled in fastbins. */
1755static INTERNAL_SIZE_T global_max_fast;
1756
1757/*
1758 Initialize a malloc_state struct.
1759
1760 This is called only from within malloc_consolidate, which needs
1761 be called in the same contexts anyway. It is never called directly
1762 outside of malloc_consolidate because some optimizing compilers try
1763 to inline it at all call points, which turns out not to be an
1764 optimization at all. (Inlining it in malloc_consolidate is fine though.)
1765 */
1766
1767static void
1768malloc_init_state (mstate av)
1769{
1770 int i;
1771 mbinptr bin;
1772
1773 /* Establish circular links for normal bins */
1774 for (i = 1; i < NBINS; ++i)
1775 {
1776 bin = bin_at (av, i);
1777 bin->fd = bin->bk = bin;
1778 }
1779
1780#if MORECORE_CONTIGUOUS
1781 if (av != &main_arena)
1782#endif
1783 set_noncontiguous (av);
1784 if (av == &main_arena)
1785 set_max_fast (DEFAULT_MXFAST);
1786 av->flags |= FASTCHUNKS_BIT;
1787
1788 av->top = initial_top (av);
1789}
1790
1791/*
1792 Other internal utilities operating on mstates
1793 */
1794
1795static void *sysmalloc (INTERNAL_SIZE_T, mstate);
1796static int systrim (size_t, mstate);
1797static void malloc_consolidate (mstate);
1798
1799
1800/* -------------- Early definitions for debugging hooks ---------------- */
1801
1802/* Define and initialize the hook variables. These weak definitions must
1803 appear before any use of the variables in a function (arena.c uses one). */
1804#ifndef weak_variable
1805/* In GNU libc we want the hook variables to be weak definitions to
1806 avoid a problem with Emacs. */
1807# define weak_variable weak_function
1808#endif
1809
1810/* Forward declarations. */
1811static void *malloc_hook_ini (size_t sz,
1812 const void *caller) __THROW;
1813static void *realloc_hook_ini (void *ptr, size_t sz,
1814 const void *caller) __THROW;
1815static void *memalign_hook_ini (size_t alignment, size_t sz,
1816 const void *caller) __THROW;
1817
1818#if HAVE_MALLOC_INIT_HOOK
1819void weak_variable (*__malloc_initialize_hook) (void) = NULL;
1820compat_symbol (libc, __malloc_initialize_hook,
1821 __malloc_initialize_hook, GLIBC_2_0);
1822#endif
1823
1824void weak_variable (*__free_hook) (void *__ptr,
1825 const void *) = NULL;
1826void *weak_variable (*__malloc_hook)
1827 (size_t __size, const void *) = malloc_hook_ini;
1828void *weak_variable (*__realloc_hook)
1829 (void *__ptr, size_t __size, const void *)
1830 = realloc_hook_ini;
1831void *weak_variable (*__memalign_hook)
1832 (size_t __alignment, size_t __size, const void *)
1833 = memalign_hook_ini;
1834void weak_variable (*__after_morecore_hook) (void) = NULL;
1835
1836
1837/* ---------------- Error behavior ------------------------------------ */
1838
1839#ifndef DEFAULT_CHECK_ACTION
1840# define DEFAULT_CHECK_ACTION 3
1841#endif
1842
1843static int check_action = DEFAULT_CHECK_ACTION;
1844
1845
1846/* ------------------ Testing support ----------------------------------*/
1847
1848static int perturb_byte;
1849
1850static void
1851alloc_perturb (char *p, size_t n)
1852{
1853 if (__glibc_unlikely (perturb_byte))
1854 memset (p, perturb_byte ^ 0xff, n);
1855}
1856
1857static void
1858free_perturb (char *p, size_t n)
1859{
1860 if (__glibc_unlikely (perturb_byte))
1861 memset (p, perturb_byte, n);
1862}
1863
1864
1865
1866#include <stap-probe.h>
1867
1868/* ------------------- Support for multiple arenas -------------------- */
1869#include "arena.c"
1870
1871/*
1872 Debugging support
1873
1874 These routines make a number of assertions about the states
1875 of data structures that should be true at all times. If any
1876 are not true, it's very likely that a user program has somehow
1877 trashed memory. (It's also possible that there is a coding error
1878 in malloc. In which case, please report it!)
1879 */
1880
1881#if !MALLOC_DEBUG
1882
1883# define check_chunk(A, P)
1884# define check_free_chunk(A, P)
1885# define check_inuse_chunk(A, P)
1886# define check_remalloced_chunk(A, P, N)
1887# define check_malloced_chunk(A, P, N)
1888# define check_malloc_state(A)
1889
1890#else
1891
1892# define check_chunk(A, P) do_check_chunk (A, P)
1893# define check_free_chunk(A, P) do_check_free_chunk (A, P)
1894# define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P)
1895# define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N)
1896# define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N)
1897# define check_malloc_state(A) do_check_malloc_state (A)
1898
1899/*
1900 Properties of all chunks
1901 */
1902
1903static void
1904do_check_chunk (mstate av, mchunkptr p)
1905{
1906 unsigned long sz = chunksize (p);
1907 /* min and max possible addresses assuming contiguous allocation */
1908 char *max_address = (char *) (av->top) + chunksize (av->top);
1909 char *min_address = max_address - av->system_mem;
1910
1911 if (!chunk_is_mmapped (p))
1912 {
1913 /* Has legal address ... */
1914 if (p != av->top)
1915 {
1916 if (contiguous (av))
1917 {
1918 assert (((char *) p) >= min_address);
1919 assert (((char *) p + sz) <= ((char *) (av->top)));
1920 }
1921 }
1922 else
1923 {
1924 /* top size is always at least MINSIZE */
1925 assert ((unsigned long) (sz) >= MINSIZE);
1926 /* top predecessor always marked inuse */
1927 assert (prev_inuse (p));
1928 }
1929 }
1930 else if (!DUMPED_MAIN_ARENA_CHUNK (p))
1931 {
1932 /* address is outside main heap */
1933 if (contiguous (av) && av->top != initial_top (av))
1934 {
1935 assert (((char *) p) < min_address || ((char *) p) >= max_address);
1936 }
1937 /* chunk is page-aligned */
1938 assert (((prev_size (p) + sz) & (GLRO (dl_pagesize) - 1)) == 0);
1939 /* mem is aligned */
1940 assert (aligned_OK (chunk2mem (p)));
1941 }
1942}
1943
1944/*
1945 Properties of free chunks
1946 */
1947
1948static void
1949do_check_free_chunk (mstate av, mchunkptr p)
1950{
1951 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
1952 mchunkptr next = chunk_at_offset (p, sz);
1953
1954 do_check_chunk (av, p);
1955
1956 /* Chunk must claim to be free ... */
1957 assert (!inuse (p));
1958 assert (!chunk_is_mmapped (p));
1959
1960 /* Unless a special marker, must have OK fields */
1961 if ((unsigned long) (sz) >= MINSIZE)
1962 {
1963 assert ((sz & MALLOC_ALIGN_MASK) == 0);
1964 assert (aligned_OK (chunk2mem (p)));
1965 /* ... matching footer field */
1966 assert (prev_size (p) == sz);
1967 /* ... and is fully consolidated */
1968 assert (prev_inuse (p));
1969 assert (next == av->top || inuse (next));
1970
1971 /* ... and has minimally sane links */
1972 assert (p->fd->bk == p);
1973 assert (p->bk->fd == p);
1974 }
1975 else /* markers are always of size SIZE_SZ */
1976 assert (sz == SIZE_SZ);
1977}
1978
1979/*
1980 Properties of inuse chunks
1981 */
1982
1983static void
1984do_check_inuse_chunk (mstate av, mchunkptr p)
1985{
1986 mchunkptr next;
1987
1988 do_check_chunk (av, p);
1989
1990 if (chunk_is_mmapped (p))
1991 return; /* mmapped chunks have no next/prev */
1992
1993 /* Check whether it claims to be in use ... */
1994 assert (inuse (p));
1995
1996 next = next_chunk (p);
1997
1998 /* ... and is surrounded by OK chunks.
1999 Since more things can be checked with free chunks than inuse ones,
2000 if an inuse chunk borders them and debug is on, it's worth doing them.
2001 */
2002 if (!prev_inuse (p))
2003 {
2004 /* Note that we cannot even look at prev unless it is not inuse */
2005 mchunkptr prv = prev_chunk (p);
2006 assert (next_chunk (prv) == p);
2007 do_check_free_chunk (av, prv);
2008 }
2009
2010 if (next == av->top)
2011 {
2012 assert (prev_inuse (next));
2013 assert (chunksize (next) >= MINSIZE);
2014 }
2015 else if (!inuse (next))
2016 do_check_free_chunk (av, next);
2017}
2018
2019/*
2020 Properties of chunks recycled from fastbins
2021 */
2022
2023static void
2024do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2025{
2026 INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA);
2027
2028 if (!chunk_is_mmapped (p))
2029 {
2030 assert (av == arena_for_chunk (p));
2031 if (chunk_main_arena (p))
2032 assert (av == &main_arena);
2033 else
2034 assert (av != &main_arena);
2035 }
2036
2037 do_check_inuse_chunk (av, p);
2038
2039 /* Legal size ... */
2040 assert ((sz & MALLOC_ALIGN_MASK) == 0);
2041 assert ((unsigned long) (sz) >= MINSIZE);
2042 /* ... and alignment */
2043 assert (aligned_OK (chunk2mem (p)));
2044 /* chunk is less than MINSIZE more than request */
2045 assert ((long) (sz) - (long) (s) >= 0);
2046 assert ((long) (sz) - (long) (s + MINSIZE) < 0);
2047}
2048
2049/*
2050 Properties of nonrecycled chunks at the point they are malloced
2051 */
2052
2053static void
2054do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s)
2055{
2056 /* same as recycled case ... */
2057 do_check_remalloced_chunk (av, p, s);
2058
2059 /*
2060 ... plus, must obey implementation invariant that prev_inuse is
2061 always true of any allocated chunk; i.e., that each allocated
2062 chunk borders either a previously allocated and still in-use
2063 chunk, or the base of its memory arena. This is ensured
2064 by making all allocations from the `lowest' part of any found
2065 chunk. This does not necessarily hold however for chunks
2066 recycled via fastbins.
2067 */
2068
2069 assert (prev_inuse (p));
2070}
2071
2072
2073/*
2074 Properties of malloc_state.
2075
2076 This may be useful for debugging malloc, as well as detecting user
2077 programmer errors that somehow write into malloc_state.
2078
2079 If you are extending or experimenting with this malloc, you can
2080 probably figure out how to hack this routine to print out or
2081 display chunk addresses, sizes, bins, and other instrumentation.
2082 */
2083
2084static void
2085do_check_malloc_state (mstate av)
2086{
2087 int i;
2088 mchunkptr p;
2089 mchunkptr q;
2090 mbinptr b;
2091 unsigned int idx;
2092 INTERNAL_SIZE_T size;
2093 unsigned long total = 0;
2094 int max_fast_bin;
2095
2096 /* internal size_t must be no wider than pointer type */
2097 assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *));
2098
2099 /* alignment is a power of 2 */
2100 assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0);
2101
2102 /* cannot run remaining checks until fully initialized */
2103 if (av->top == 0 || av->top == initial_top (av))
2104 return;
2105
2106 /* pagesize is a power of 2 */
2107 assert (powerof2(GLRO (dl_pagesize)));
2108
2109 /* A contiguous main_arena is consistent with sbrk_base. */
2110 if (av == &main_arena && contiguous (av))
2111 assert ((char *) mp_.sbrk_base + av->system_mem ==
2112 (char *) av->top + chunksize (av->top));
2113
2114 /* properties of fastbins */
2115
2116 /* max_fast is in allowed range */
2117 assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE));
2118
2119 max_fast_bin = fastbin_index (get_max_fast ());
2120
2121 for (i = 0; i < NFASTBINS; ++i)
2122 {
2123 p = fastbin (av, i);
2124
2125 /* The following test can only be performed for the main arena.
2126 While mallopt calls malloc_consolidate to get rid of all fast
2127 bins (especially those larger than the new maximum) this does
2128 only happen for the main arena. Trying to do this for any
2129 other arena would mean those arenas have to be locked and
2130 malloc_consolidate be called for them. This is excessive. And
2131 even if this is acceptable to somebody it still cannot solve
2132 the problem completely since if the arena is locked a
2133 concurrent malloc call might create a new arena which then
2134 could use the newly invalid fast bins. */
2135
2136 /* all bins past max_fast are empty */
2137 if (av == &main_arena && i > max_fast_bin)
2138 assert (p == 0);
2139
2140 while (p != 0)
2141 {
2142 /* each chunk claims to be inuse */
2143 do_check_inuse_chunk (av, p);
2144 total += chunksize (p);
2145 /* chunk belongs in this bin */
2146 assert (fastbin_index (chunksize (p)) == i);
2147 p = p->fd;
2148 }
2149 }
2150
2151 if (total != 0)
2152 assert (have_fastchunks (av));
2153 else if (!have_fastchunks (av))
2154 assert (total == 0);
2155
2156 /* check normal bins */
2157 for (i = 1; i < NBINS; ++i)
2158 {
2159 b = bin_at (av, i);
2160
2161 /* binmap is accurate (except for bin 1 == unsorted_chunks) */
2162 if (i >= 2)
2163 {
2164 unsigned int binbit = get_binmap (av, i);
2165 int empty = last (b) == b;
2166 if (!binbit)
2167 assert (empty);
2168 else if (!empty)
2169 assert (binbit);
2170 }
2171
2172 for (p = last (b); p != b; p = p->bk)
2173 {
2174 /* each chunk claims to be free */
2175 do_check_free_chunk (av, p);
2176 size = chunksize (p);
2177 total += size;
2178 if (i >= 2)
2179 {
2180 /* chunk belongs in bin */
2181 idx = bin_index (size);
2182 assert (idx == i);
2183 /* lists are sorted */
2184 assert (p->bk == b ||
2185 (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p));
2186
2187 if (!in_smallbin_range (size))
2188 {
2189 if (p->fd_nextsize != NULL)
2190 {
2191 if (p->fd_nextsize == p)
2192 assert (p->bk_nextsize == p);
2193 else
2194 {
2195 if (p->fd_nextsize == first (b))
2196 assert (chunksize (p) < chunksize (p->fd_nextsize));
2197 else
2198 assert (chunksize (p) > chunksize (p->fd_nextsize));
2199
2200 if (p == first (b))
2201 assert (chunksize (p) > chunksize (p->bk_nextsize));
2202 else
2203 assert (chunksize (p) < chunksize (p->bk_nextsize));
2204 }
2205 }
2206 else
2207 assert (p->bk_nextsize == NULL);
2208 }
2209 }
2210 else if (!in_smallbin_range (size))
2211 assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL);
2212 /* chunk is followed by a legal chain of inuse chunks */
2213 for (q = next_chunk (p);
2214 (q != av->top && inuse (q) &&
2215 (unsigned long) (chunksize (q)) >= MINSIZE);
2216 q = next_chunk (q))
2217 do_check_inuse_chunk (av, q);
2218 }
2219 }
2220
2221 /* top chunk is OK */
2222 check_chunk (av, av->top);
2223}
2224#endif
2225
2226
2227/* ----------------- Support for debugging hooks -------------------- */
2228#include "hooks.c"
2229
2230
2231/* ----------- Routines dealing with system allocation -------------- */
2232
2233/*
2234 sysmalloc handles malloc cases requiring more memory from the system.
2235 On entry, it is assumed that av->top does not have enough
2236 space to service request for nb bytes, thus requiring that av->top
2237 be extended or replaced.
2238 */
2239
2240static void *
2241sysmalloc (INTERNAL_SIZE_T nb, mstate av)
2242{
2243 mchunkptr old_top; /* incoming value of av->top */
2244 INTERNAL_SIZE_T old_size; /* its size */
2245 char *old_end; /* its end address */
2246
2247 long size; /* arg to first MORECORE or mmap call */
2248 char *brk; /* return value from MORECORE */
2249
2250 long correction; /* arg to 2nd MORECORE call */
2251 char *snd_brk; /* 2nd return val */
2252
2253 INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */
2254 INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */
2255 char *aligned_brk; /* aligned offset into brk */
2256
2257 mchunkptr p; /* the allocated/returned chunk */
2258 mchunkptr remainder; /* remainder from allocation */
2259 unsigned long remainder_size; /* its size */
2260
2261
2262 size_t pagesize = GLRO (dl_pagesize);
2263 bool tried_mmap = false;
2264
2265
2266 /*
2267 If have mmap, and the request size meets the mmap threshold, and
2268 the system supports mmap, and there are few enough currently
2269 allocated mmapped regions, try to directly map this request
2270 rather than expanding top.
2271 */
2272
2273 if (av == NULL
2274 || ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold)
2275 && (mp_.n_mmaps < mp_.n_mmaps_max)))
2276 {
2277 char *mm; /* return value from mmap call*/
2278
2279 try_mmap:
2280 /*
2281 Round up size to nearest page. For mmapped chunks, the overhead
2282 is one SIZE_SZ unit larger than for normal chunks, because there
2283 is no following chunk whose prev_size field could be used.
2284
2285 See the front_misalign handling below, for glibc there is no
2286 need for further alignments unless we have have high alignment.
2287 */
2288 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2289 size = ALIGN_UP (nb + SIZE_SZ, pagesize);
2290 else
2291 size = ALIGN_UP (nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize);
2292 tried_mmap = true;
2293
2294 /* Don't try if size wraps around 0 */
2295 if ((unsigned long) (size) > (unsigned long) (nb))
2296 {
2297 mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2298
2299 if (mm != MAP_FAILED)
2300 {
2301 /*
2302 The offset to the start of the mmapped region is stored
2303 in the prev_size field of the chunk. This allows us to adjust
2304 returned start address to meet alignment requirements here
2305 and in memalign(), and still be able to compute proper
2306 address argument for later munmap in free() and realloc().
2307 */
2308
2309 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2310 {
2311 /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and
2312 MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page
2313 aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */
2314 assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0);
2315 front_misalign = 0;
2316 }
2317 else
2318 front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK;
2319 if (front_misalign > 0)
2320 {
2321 correction = MALLOC_ALIGNMENT - front_misalign;
2322 p = (mchunkptr) (mm + correction);
2323 set_prev_size (p, correction);
2324 set_head (p, (size - correction) | IS_MMAPPED);
2325 }
2326 else
2327 {
2328 p = (mchunkptr) mm;
2329 set_prev_size (p, 0);
2330 set_head (p, size | IS_MMAPPED);
2331 }
2332
2333 /* update statistics */
2334
2335 int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1;
2336 atomic_max (&mp_.max_n_mmaps, new);
2337
2338 unsigned long sum;
2339 sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size;
2340 atomic_max (&mp_.max_mmapped_mem, sum);
2341
2342 check_chunk (av, p);
2343
2344 return chunk2mem (p);
2345 }
2346 }
2347 }
2348
2349 /* There are no usable arenas and mmap also failed. */
2350 if (av == NULL)
2351 return 0;
2352
2353 /* Record incoming configuration of top */
2354
2355 old_top = av->top;
2356 old_size = chunksize (old_top);
2357 old_end = (char *) (chunk_at_offset (old_top, old_size));
2358
2359 brk = snd_brk = (char *) (MORECORE_FAILURE);
2360
2361 /*
2362 If not the first time through, we require old_size to be
2363 at least MINSIZE and to have prev_inuse set.
2364 */
2365
2366 assert ((old_top == initial_top (av) && old_size == 0) ||
2367 ((unsigned long) (old_size) >= MINSIZE &&
2368 prev_inuse (old_top) &&
2369 ((unsigned long) old_end & (pagesize - 1)) == 0));
2370
2371 /* Precondition: not enough current space to satisfy nb request */
2372 assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE));
2373
2374
2375 if (av != &main_arena)
2376 {
2377 heap_info *old_heap, *heap;
2378 size_t old_heap_size;
2379
2380 /* First try to extend the current heap. */
2381 old_heap = heap_for_ptr (old_top);
2382 old_heap_size = old_heap->size;
2383 if ((long) (MINSIZE + nb - old_size) > 0
2384 && grow_heap (old_heap, MINSIZE + nb - old_size) == 0)
2385 {
2386 av->system_mem += old_heap->size - old_heap_size;
2387 set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top)
2388 | PREV_INUSE);
2389 }
2390 else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad)))
2391 {
2392 /* Use a newly allocated heap. */
2393 heap->ar_ptr = av;
2394 heap->prev = old_heap;
2395 av->system_mem += heap->size;
2396 /* Set up the new top. */
2397 top (av) = chunk_at_offset (heap, sizeof (*heap));
2398 set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE);
2399
2400 /* Setup fencepost and free the old top chunk with a multiple of
2401 MALLOC_ALIGNMENT in size. */
2402 /* The fencepost takes at least MINSIZE bytes, because it might
2403 become the top chunk again later. Note that a footer is set
2404 up, too, although the chunk is marked in use. */
2405 old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK;
2406 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE);
2407 if (old_size >= MINSIZE)
2408 {
2409 set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE);
2410 set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ));
2411 set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA);
2412 _int_free (av, old_top, 1);
2413 }
2414 else
2415 {
2416 set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE);
2417 set_foot (old_top, (old_size + 2 * SIZE_SZ));
2418 }
2419 }
2420 else if (!tried_mmap)
2421 /* We can at least try to use to mmap memory. */
2422 goto try_mmap;
2423 }
2424 else /* av == main_arena */
2425
2426
2427 { /* Request enough space for nb + pad + overhead */
2428 size = nb + mp_.top_pad + MINSIZE;
2429
2430 /*
2431 If contiguous, we can subtract out existing space that we hope to
2432 combine with new space. We add it back later only if
2433 we don't actually get contiguous space.
2434 */
2435
2436 if (contiguous (av))
2437 size -= old_size;
2438
2439 /*
2440 Round to a multiple of page size.
2441 If MORECORE is not contiguous, this ensures that we only call it
2442 with whole-page arguments. And if MORECORE is contiguous and
2443 this is not first time through, this preserves page-alignment of
2444 previous calls. Otherwise, we correct to page-align below.
2445 */
2446
2447 size = ALIGN_UP (size, pagesize);
2448
2449 /*
2450 Don't try to call MORECORE if argument is so big as to appear
2451 negative. Note that since mmap takes size_t arg, it may succeed
2452 below even if we cannot call MORECORE.
2453 */
2454
2455 if (size > 0)
2456 {
2457 brk = (char *) (MORECORE (size));
2458 LIBC_PROBE (memory_sbrk_more, 2, brk, size);
2459 }
2460
2461 if (brk != (char *) (MORECORE_FAILURE))
2462 {
2463 /* Call the `morecore' hook if necessary. */
2464 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2465 if (__builtin_expect (hook != NULL, 0))
2466 (*hook)();
2467 }
2468 else
2469 {
2470 /*
2471 If have mmap, try using it as a backup when MORECORE fails or
2472 cannot be used. This is worth doing on systems that have "holes" in
2473 address space, so sbrk cannot extend to give contiguous space, but
2474 space is available elsewhere. Note that we ignore mmap max count
2475 and threshold limits, since the space will not be used as a
2476 segregated mmap region.
2477 */
2478
2479 /* Cannot merge with old top, so add its size back in */
2480 if (contiguous (av))
2481 size = ALIGN_UP (size + old_size, pagesize);
2482
2483 /* If we are relying on mmap as backup, then use larger units */
2484 if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE))
2485 size = MMAP_AS_MORECORE_SIZE;
2486
2487 /* Don't try if size wraps around 0 */
2488 if ((unsigned long) (size) > (unsigned long) (nb))
2489 {
2490 char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0));
2491
2492 if (mbrk != MAP_FAILED)
2493 {
2494 /* We do not need, and cannot use, another sbrk call to find end */
2495 brk = mbrk;
2496 snd_brk = brk + size;
2497
2498 /*
2499 Record that we no longer have a contiguous sbrk region.
2500 After the first time mmap is used as backup, we do not
2501 ever rely on contiguous space since this could incorrectly
2502 bridge regions.
2503 */
2504 set_noncontiguous (av);
2505 }
2506 }
2507 }
2508
2509 if (brk != (char *) (MORECORE_FAILURE))
2510 {
2511 if (mp_.sbrk_base == 0)
2512 mp_.sbrk_base = brk;
2513 av->system_mem += size;
2514
2515 /*
2516 If MORECORE extends previous space, we can likewise extend top size.
2517 */
2518
2519 if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE))
2520 set_head (old_top, (size + old_size) | PREV_INUSE);
2521
2522 else if (contiguous (av) && old_size && brk < old_end)
2523 {
2524 /* Oops! Someone else killed our space.. Can't touch anything. */
2525 malloc_printerr (3, "break adjusted to free malloc space", brk,
2526 av);
2527 }
2528
2529 /*
2530 Otherwise, make adjustments:
2531
2532 * If the first time through or noncontiguous, we need to call sbrk
2533 just to find out where the end of memory lies.
2534
2535 * We need to ensure that all returned chunks from malloc will meet
2536 MALLOC_ALIGNMENT
2537
2538 * If there was an intervening foreign sbrk, we need to adjust sbrk
2539 request size to account for fact that we will not be able to
2540 combine new space with existing space in old_top.
2541
2542 * Almost all systems internally allocate whole pages at a time, in
2543 which case we might as well use the whole last page of request.
2544 So we allocate enough more memory to hit a page boundary now,
2545 which in turn causes future contiguous calls to page-align.
2546 */
2547
2548 else
2549 {
2550 front_misalign = 0;
2551 end_misalign = 0;
2552 correction = 0;
2553 aligned_brk = brk;
2554
2555 /* handle contiguous cases */
2556 if (contiguous (av))
2557 {
2558 /* Count foreign sbrk as system_mem. */
2559 if (old_size)
2560 av->system_mem += brk - old_end;
2561
2562 /* Guarantee alignment of first new chunk made from this space */
2563
2564 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2565 if (front_misalign > 0)
2566 {
2567 /*
2568 Skip over some bytes to arrive at an aligned position.
2569 We don't need to specially mark these wasted front bytes.
2570 They will never be accessed anyway because
2571 prev_inuse of av->top (and any chunk created from its start)
2572 is always true after initialization.
2573 */
2574
2575 correction = MALLOC_ALIGNMENT - front_misalign;
2576 aligned_brk += correction;
2577 }
2578
2579 /*
2580 If this isn't adjacent to existing space, then we will not
2581 be able to merge with old_top space, so must add to 2nd request.
2582 */
2583
2584 correction += old_size;
2585
2586 /* Extend the end address to hit a page boundary */
2587 end_misalign = (INTERNAL_SIZE_T) (brk + size + correction);
2588 correction += (ALIGN_UP (end_misalign, pagesize)) - end_misalign;
2589
2590 assert (correction >= 0);
2591 snd_brk = (char *) (MORECORE (correction));
2592
2593 /*
2594 If can't allocate correction, try to at least find out current
2595 brk. It might be enough to proceed without failing.
2596
2597 Note that if second sbrk did NOT fail, we assume that space
2598 is contiguous with first sbrk. This is a safe assumption unless
2599 program is multithreaded but doesn't use locks and a foreign sbrk
2600 occurred between our first and second calls.
2601 */
2602
2603 if (snd_brk == (char *) (MORECORE_FAILURE))
2604 {
2605 correction = 0;
2606 snd_brk = (char *) (MORECORE (0));
2607 }
2608 else
2609 {
2610 /* Call the `morecore' hook if necessary. */
2611 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2612 if (__builtin_expect (hook != NULL, 0))
2613 (*hook)();
2614 }
2615 }
2616
2617 /* handle non-contiguous cases */
2618 else
2619 {
2620 if (MALLOC_ALIGNMENT == 2 * SIZE_SZ)
2621 /* MORECORE/mmap must correctly align */
2622 assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0);
2623 else
2624 {
2625 front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK;
2626 if (front_misalign > 0)
2627 {
2628 /*
2629 Skip over some bytes to arrive at an aligned position.
2630 We don't need to specially mark these wasted front bytes.
2631 They will never be accessed anyway because
2632 prev_inuse of av->top (and any chunk created from its start)
2633 is always true after initialization.
2634 */
2635
2636 aligned_brk += MALLOC_ALIGNMENT - front_misalign;
2637 }
2638 }
2639
2640 /* Find out current end of memory */
2641 if (snd_brk == (char *) (MORECORE_FAILURE))
2642 {
2643 snd_brk = (char *) (MORECORE (0));
2644 }
2645 }
2646
2647 /* Adjust top based on results of second sbrk */
2648 if (snd_brk != (char *) (MORECORE_FAILURE))
2649 {
2650 av->top = (mchunkptr) aligned_brk;
2651 set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);
2652 av->system_mem += correction;
2653
2654 /*
2655 If not the first time through, we either have a
2656 gap due to foreign sbrk or a non-contiguous region. Insert a
2657 double fencepost at old_top to prevent consolidation with space
2658 we don't own. These fenceposts are artificial chunks that are
2659 marked as inuse and are in any case too small to use. We need
2660 two to make sizes and alignments work out.
2661 */
2662
2663 if (old_size != 0)
2664 {
2665 /*
2666 Shrink old_top to insert fenceposts, keeping size a
2667 multiple of MALLOC_ALIGNMENT. We know there is at least
2668 enough space in old_top to do this.
2669 */
2670 old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK;
2671 set_head (old_top, old_size | PREV_INUSE);
2672
2673 /*
2674 Note that the following assignments completely overwrite
2675 old_top when old_size was previously MINSIZE. This is
2676 intentional. We need the fencepost, even if old_top otherwise gets
2677 lost.
2678 */
2679 set_head (chunk_at_offset (old_top, old_size),
2680 (2 * SIZE_SZ) | PREV_INUSE);
2681 set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ),
2682 (2 * SIZE_SZ) | PREV_INUSE);
2683
2684 /* If possible, release the rest. */
2685 if (old_size >= MINSIZE)
2686 {
2687 _int_free (av, old_top, 1);
2688 }
2689 }
2690 }
2691 }
2692 }
2693 } /* if (av != &main_arena) */
2694
2695 if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem))
2696 av->max_system_mem = av->system_mem;
2697 check_malloc_state (av);
2698
2699 /* finally, do the allocation */
2700 p = av->top;
2701 size = chunksize (p);
2702
2703 /* check that one of the above allocation paths succeeded */
2704 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
2705 {
2706 remainder_size = size - nb;
2707 remainder = chunk_at_offset (p, nb);
2708 av->top = remainder;
2709 set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0));
2710 set_head (remainder, remainder_size | PREV_INUSE);
2711 check_malloced_chunk (av, p, nb);
2712 return chunk2mem (p);
2713 }
2714
2715 /* catch all failure paths */
2716 __set_errno (ENOMEM);
2717 return 0;
2718}
2719
2720
2721/*
2722 systrim is an inverse of sorts to sysmalloc. It gives memory back
2723 to the system (via negative arguments to sbrk) if there is unused
2724 memory at the `high' end of the malloc pool. It is called
2725 automatically by free() when top space exceeds the trim
2726 threshold. It is also called by the public malloc_trim routine. It
2727 returns 1 if it actually released any memory, else 0.
2728 */
2729
2730static int
2731systrim (size_t pad, mstate av)
2732{
2733 long top_size; /* Amount of top-most memory */
2734 long extra; /* Amount to release */
2735 long released; /* Amount actually released */
2736 char *current_brk; /* address returned by pre-check sbrk call */
2737 char *new_brk; /* address returned by post-check sbrk call */
2738 size_t pagesize;
2739 long top_area;
2740
2741 pagesize = GLRO (dl_pagesize);
2742 top_size = chunksize (av->top);
2743
2744 top_area = top_size - MINSIZE - 1;
2745 if (top_area <= pad)
2746 return 0;
2747
2748 /* Release in pagesize units and round down to the nearest page. */
2749 extra = ALIGN_DOWN(top_area - pad, pagesize);
2750
2751 if (extra == 0)
2752 return 0;
2753
2754 /*
2755 Only proceed if end of memory is where we last set it.
2756 This avoids problems if there were foreign sbrk calls.
2757 */
2758 current_brk = (char *) (MORECORE (0));
2759 if (current_brk == (char *) (av->top) + top_size)
2760 {
2761 /*
2762 Attempt to release memory. We ignore MORECORE return value,
2763 and instead call again to find out where new end of memory is.
2764 This avoids problems if first call releases less than we asked,
2765 of if failure somehow altered brk value. (We could still
2766 encounter problems if it altered brk in some very bad way,
2767 but the only thing we can do is adjust anyway, which will cause
2768 some downstream failure.)
2769 */
2770
2771 MORECORE (-extra);
2772 /* Call the `morecore' hook if necessary. */
2773 void (*hook) (void) = atomic_forced_read (__after_morecore_hook);
2774 if (__builtin_expect (hook != NULL, 0))
2775 (*hook)();
2776 new_brk = (char *) (MORECORE (0));
2777
2778 LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra);
2779
2780 if (new_brk != (char *) MORECORE_FAILURE)
2781 {
2782 released = (long) (current_brk - new_brk);
2783
2784 if (released != 0)
2785 {
2786 /* Success. Adjust top. */
2787 av->system_mem -= released;
2788 set_head (av->top, (top_size - released) | PREV_INUSE);
2789 check_malloc_state (av);
2790 return 1;
2791 }
2792 }
2793 }
2794 return 0;
2795}
2796
2797static void
2798internal_function
2799munmap_chunk (mchunkptr p)
2800{
2801 INTERNAL_SIZE_T size = chunksize (p);
2802
2803 assert (chunk_is_mmapped (p));
2804
2805 /* Do nothing if the chunk is a faked mmapped chunk in the dumped
2806 main arena. We never free this memory. */
2807 if (DUMPED_MAIN_ARENA_CHUNK (p))
2808 return;
2809
2810 uintptr_t block = (uintptr_t) p - prev_size (p);
2811 size_t total_size = prev_size (p) + size;
2812 /* Unfortunately we have to do the compilers job by hand here. Normally
2813 we would test BLOCK and TOTAL-SIZE separately for compliance with the
2814 page size. But gcc does not recognize the optimization possibility
2815 (in the moment at least) so we combine the two values into one before
2816 the bit test. */
2817 if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0))
2818 {
2819 malloc_printerr (check_action, "munmap_chunk(): invalid pointer",
2820 chunk2mem (p), NULL);
2821 return;
2822 }
2823
2824 atomic_decrement (&mp_.n_mmaps);
2825 atomic_add (&mp_.mmapped_mem, -total_size);
2826
2827 /* If munmap failed the process virtual memory address space is in a
2828 bad shape. Just leave the block hanging around, the process will
2829 terminate shortly anyway since not much can be done. */
2830 __munmap ((char *) block, total_size);
2831}
2832
2833#if HAVE_MREMAP
2834
2835static mchunkptr
2836internal_function
2837mremap_chunk (mchunkptr p, size_t new_size)
2838{
2839 size_t pagesize = GLRO (dl_pagesize);
2840 INTERNAL_SIZE_T offset = prev_size (p);
2841 INTERNAL_SIZE_T size = chunksize (p);
2842 char *cp;
2843
2844 assert (chunk_is_mmapped (p));
2845 assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0);
2846
2847 /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */
2848 new_size = ALIGN_UP (new_size + offset + SIZE_SZ, pagesize);
2849
2850 /* No need to remap if the number of pages does not change. */
2851 if (size + offset == new_size)
2852 return p;
2853
2854 cp = (char *) __mremap ((char *) p - offset, size + offset, new_size,
2855 MREMAP_MAYMOVE);
2856
2857 if (cp == MAP_FAILED)
2858 return 0;
2859
2860 p = (mchunkptr) (cp + offset);
2861
2862 assert (aligned_OK (chunk2mem (p)));
2863
2864 assert (prev_size (p) == offset);
2865 set_head (p, (new_size - offset) | IS_MMAPPED);
2866
2867 INTERNAL_SIZE_T new;
2868 new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset)
2869 + new_size - size - offset;
2870 atomic_max (&mp_.max_mmapped_mem, new);
2871 return p;
2872}
2873#endif /* HAVE_MREMAP */
2874
2875/*------------------------ Public wrappers. --------------------------------*/
2876
2877void *
2878__libc_malloc (size_t bytes)
2879{
2880 mstate ar_ptr;
2881 void *victim;
2882
2883 void *(*hook) (size_t, const void *)
2884 = atomic_forced_read (__malloc_hook);
2885 if (__builtin_expect (hook != NULL, 0))
2886 return (*hook)(bytes, RETURN_ADDRESS (0));
2887
2888 arena_get (ar_ptr, bytes);
2889
2890 victim = _int_malloc (ar_ptr, bytes);
2891 /* Retry with another arena only if we were able to find a usable arena
2892 before. */
2893 if (!victim && ar_ptr != NULL)
2894 {
2895 LIBC_PROBE (memory_malloc_retry, 1, bytes);
2896 ar_ptr = arena_get_retry (ar_ptr, bytes);
2897 victim = _int_malloc (ar_ptr, bytes);
2898 }
2899
2900 if (ar_ptr != NULL)
2901 __libc_lock_unlock (ar_ptr->mutex);
2902
2903 assert (!victim || chunk_is_mmapped (mem2chunk (victim)) ||
2904 ar_ptr == arena_for_chunk (mem2chunk (victim)));
2905 return victim;
2906}
2907libc_hidden_def (__libc_malloc)
2908
2909void
2910__libc_free (void *mem)
2911{
2912 mstate ar_ptr;
2913 mchunkptr p; /* chunk corresponding to mem */
2914
2915 void (*hook) (void *, const void *)
2916 = atomic_forced_read (__free_hook);
2917 if (__builtin_expect (hook != NULL, 0))
2918 {
2919 (*hook)(mem, RETURN_ADDRESS (0));
2920 return;
2921 }
2922
2923 if (mem == 0) /* free(0) has no effect */
2924 return;
2925
2926 p = mem2chunk (mem);
2927
2928 if (chunk_is_mmapped (p)) /* release mmapped memory. */
2929 {
2930 /* See if the dynamic brk/mmap threshold needs adjusting.
2931 Dumped fake mmapped chunks do not affect the threshold. */
2932 if (!mp_.no_dyn_threshold
2933 && chunksize_nomask (p) > mp_.mmap_threshold
2934 && chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX
2935 && !DUMPED_MAIN_ARENA_CHUNK (p))
2936 {
2937 mp_.mmap_threshold = chunksize (p);
2938 mp_.trim_threshold = 2 * mp_.mmap_threshold;
2939 LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
2940 mp_.mmap_threshold, mp_.trim_threshold);
2941 }
2942 munmap_chunk (p);
2943 return;
2944 }
2945
2946 ar_ptr = arena_for_chunk (p);
2947 _int_free (ar_ptr, p, 0);
2948}
2949libc_hidden_def (__libc_free)
2950
2951void *
2952__libc_realloc (void *oldmem, size_t bytes)
2953{
2954 mstate ar_ptr;
2955 INTERNAL_SIZE_T nb; /* padded request size */
2956
2957 void *newp; /* chunk to return */
2958
2959 void *(*hook) (void *, size_t, const void *) =
2960 atomic_forced_read (__realloc_hook);
2961 if (__builtin_expect (hook != NULL, 0))
2962 return (*hook)(oldmem, bytes, RETURN_ADDRESS (0));
2963
2964#if REALLOC_ZERO_BYTES_FREES
2965 if (bytes == 0 && oldmem != NULL)
2966 {
2967 __libc_free (oldmem); return 0;
2968 }
2969#endif
2970
2971 /* realloc of null is supposed to be same as malloc */
2972 if (oldmem == 0)
2973 return __libc_malloc (bytes);
2974
2975 /* chunk corresponding to oldmem */
2976 const mchunkptr oldp = mem2chunk (oldmem);
2977 /* its size */
2978 const INTERNAL_SIZE_T oldsize = chunksize (oldp);
2979
2980 if (chunk_is_mmapped (oldp))
2981 ar_ptr = NULL;
2982 else
2983 ar_ptr = arena_for_chunk (oldp);
2984
2985 /* Little security check which won't hurt performance: the allocator
2986 never wrapps around at the end of the address space. Therefore
2987 we can exclude some size values which might appear here by
2988 accident or by "design" from some intruder. We need to bypass
2989 this check for dumped fake mmap chunks from the old main arena
2990 because the new malloc may provide additional alignment. */
2991 if ((__builtin_expect ((uintptr_t) oldp > (uintptr_t) -oldsize, 0)
2992 || __builtin_expect (misaligned_chunk (oldp), 0))
2993 && !DUMPED_MAIN_ARENA_CHUNK (oldp))
2994 {
2995 malloc_printerr (check_action, "realloc(): invalid pointer", oldmem,
2996 ar_ptr);
2997 return NULL;
2998 }
2999
3000 checked_request2size (bytes, nb);
3001
3002 if (chunk_is_mmapped (oldp))
3003 {
3004 /* If this is a faked mmapped chunk from the dumped main arena,
3005 always make a copy (and do not free the old chunk). */
3006 if (DUMPED_MAIN_ARENA_CHUNK (oldp))
3007 {
3008 /* Must alloc, copy, free. */
3009 void *newmem = __libc_malloc (bytes);
3010 if (newmem == 0)
3011 return NULL;
3012 /* Copy as many bytes as are available from the old chunk
3013 and fit into the new size. NB: The overhead for faked
3014 mmapped chunks is only SIZE_SZ, not 2 * SIZE_SZ as for
3015 regular mmapped chunks. */
3016 if (bytes > oldsize - SIZE_SZ)
3017 bytes = oldsize - SIZE_SZ;
3018 memcpy (newmem, oldmem, bytes);
3019 return newmem;
3020 }
3021
3022 void *newmem;
3023
3024#if HAVE_MREMAP
3025 newp = mremap_chunk (oldp, nb);
3026 if (newp)
3027 return chunk2mem (newp);
3028#endif
3029 /* Note the extra SIZE_SZ overhead. */
3030 if (oldsize - SIZE_SZ >= nb)
3031 return oldmem; /* do nothing */
3032
3033 /* Must alloc, copy, free. */
3034 newmem = __libc_malloc (bytes);
3035 if (newmem == 0)
3036 return 0; /* propagate failure */
3037
3038 memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ);
3039 munmap_chunk (oldp);
3040 return newmem;
3041 }
3042
3043 __libc_lock_lock (ar_ptr->mutex);
3044
3045 newp = _int_realloc (ar_ptr, oldp, oldsize, nb);
3046
3047 __libc_lock_unlock (ar_ptr->mutex);
3048 assert (!newp || chunk_is_mmapped (mem2chunk (newp)) ||
3049 ar_ptr == arena_for_chunk (mem2chunk (newp)));
3050
3051 if (newp == NULL)
3052 {
3053 /* Try harder to allocate memory in other arenas. */
3054 LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem);
3055 newp = __libc_malloc (bytes);
3056 if (newp != NULL)
3057 {
3058 memcpy (newp, oldmem, oldsize - SIZE_SZ);
3059 _int_free (ar_ptr, oldp, 0);
3060 }
3061 }
3062
3063 return newp;
3064}
3065libc_hidden_def (__libc_realloc)
3066
3067void *
3068__libc_memalign (size_t alignment, size_t bytes)
3069{
3070 void *address = RETURN_ADDRESS (0);
3071 return _mid_memalign (alignment, bytes, address);
3072}
3073
3074static void *
3075_mid_memalign (size_t alignment, size_t bytes, void *address)
3076{
3077 mstate ar_ptr;
3078 void *p;
3079
3080 void *(*hook) (size_t, size_t, const void *) =
3081 atomic_forced_read (__memalign_hook);
3082 if (__builtin_expect (hook != NULL, 0))
3083 return (*hook)(alignment, bytes, address);
3084
3085 /* If we need less alignment than we give anyway, just relay to malloc. */
3086 if (alignment <= MALLOC_ALIGNMENT)
3087 return __libc_malloc (bytes);
3088
3089 /* Otherwise, ensure that it is at least a minimum chunk size */
3090 if (alignment < MINSIZE)
3091 alignment = MINSIZE;
3092
3093 /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a
3094 power of 2 and will cause overflow in the check below. */
3095 if (alignment > SIZE_MAX / 2 + 1)
3096 {
3097 __set_errno (EINVAL);
3098 return 0;
3099 }
3100
3101 /* Check for overflow. */
3102 if (bytes > SIZE_MAX - alignment - MINSIZE)
3103 {
3104 __set_errno (ENOMEM);
3105 return 0;
3106 }
3107
3108
3109 /* Make sure alignment is power of 2. */
3110 if (!powerof2 (alignment))
3111 {
3112 size_t a = MALLOC_ALIGNMENT * 2;
3113 while (a < alignment)
3114 a <<= 1;
3115 alignment = a;
3116 }
3117
3118 arena_get (ar_ptr, bytes + alignment + MINSIZE);
3119
3120 p = _int_memalign (ar_ptr, alignment, bytes);
3121 if (!p && ar_ptr != NULL)
3122 {
3123 LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment);
3124 ar_ptr = arena_get_retry (ar_ptr, bytes);
3125 p = _int_memalign (ar_ptr, alignment, bytes);
3126 }
3127
3128 if (ar_ptr != NULL)
3129 __libc_lock_unlock (ar_ptr->mutex);
3130
3131 assert (!p || chunk_is_mmapped (mem2chunk (p)) ||
3132 ar_ptr == arena_for_chunk (mem2chunk (p)));
3133 return p;
3134}
3135/* For ISO C11. */
3136weak_alias (__libc_memalign, aligned_alloc)
3137libc_hidden_def (__libc_memalign)
3138
3139void *
3140__libc_valloc (size_t bytes)
3141{
3142 if (__malloc_initialized < 0)
3143 ptmalloc_init ();
3144
3145 void *address = RETURN_ADDRESS (0);
3146 size_t pagesize = GLRO (dl_pagesize);
3147 return _mid_memalign (pagesize, bytes, address);
3148}
3149
3150void *
3151__libc_pvalloc (size_t bytes)
3152{
3153 if (__malloc_initialized < 0)
3154 ptmalloc_init ();
3155
3156 void *address = RETURN_ADDRESS (0);
3157 size_t pagesize = GLRO (dl_pagesize);
3158 size_t rounded_bytes = ALIGN_UP (bytes, pagesize);
3159
3160 /* Check for overflow. */
3161 if (bytes > SIZE_MAX - 2 * pagesize - MINSIZE)
3162 {
3163 __set_errno (ENOMEM);
3164 return 0;
3165 }
3166
3167 return _mid_memalign (pagesize, rounded_bytes, address);
3168}
3169
3170void *
3171__libc_calloc (size_t n, size_t elem_size)
3172{
3173 mstate av;
3174 mchunkptr oldtop, p;
3175 INTERNAL_SIZE_T bytes, sz, csz, oldtopsize;
3176 void *mem;
3177 unsigned long clearsize;
3178 unsigned long nclears;
3179 INTERNAL_SIZE_T *d;
3180
3181 /* size_t is unsigned so the behavior on overflow is defined. */
3182 bytes = n * elem_size;
3183#define HALF_INTERNAL_SIZE_T \
3184 (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
3185 if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0))
3186 {
3187 if (elem_size != 0 && bytes / elem_size != n)
3188 {
3189 __set_errno (ENOMEM);
3190 return 0;
3191 }
3192 }
3193
3194 void *(*hook) (size_t, const void *) =
3195 atomic_forced_read (__malloc_hook);
3196 if (__builtin_expect (hook != NULL, 0))
3197 {
3198 sz = bytes;
3199 mem = (*hook)(sz, RETURN_ADDRESS (0));
3200 if (mem == 0)
3201 return 0;
3202
3203 return memset (mem, 0, sz);
3204 }
3205
3206 sz = bytes;
3207
3208 arena_get (av, sz);
3209 if (av)
3210 {
3211 /* Check if we hand out the top chunk, in which case there may be no
3212 need to clear. */
3213#if MORECORE_CLEARS
3214 oldtop = top (av);
3215 oldtopsize = chunksize (top (av));
3216# if MORECORE_CLEARS < 2
3217 /* Only newly allocated memory is guaranteed to be cleared. */
3218 if (av == &main_arena &&
3219 oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop)
3220 oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop);
3221# endif
3222 if (av != &main_arena)
3223 {
3224 heap_info *heap = heap_for_ptr (oldtop);
3225 if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop)
3226 oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop;
3227 }
3228#endif
3229 }
3230 else
3231 {
3232 /* No usable arenas. */
3233 oldtop = 0;
3234 oldtopsize = 0;
3235 }
3236 mem = _int_malloc (av, sz);
3237
3238
3239 assert (!mem || chunk_is_mmapped (mem2chunk (mem)) ||
3240 av == arena_for_chunk (mem2chunk (mem)));
3241
3242 if (mem == 0 && av != NULL)
3243 {
3244 LIBC_PROBE (memory_calloc_retry, 1, sz);
3245 av = arena_get_retry (av, sz);
3246 mem = _int_malloc (av, sz);
3247 }
3248
3249 if (av != NULL)
3250 __libc_lock_unlock (av->mutex);
3251
3252 /* Allocation failed even after a retry. */
3253 if (mem == 0)
3254 return 0;
3255
3256 p = mem2chunk (mem);
3257
3258 /* Two optional cases in which clearing not necessary */
3259 if (chunk_is_mmapped (p))
3260 {
3261 if (__builtin_expect (perturb_byte, 0))
3262 return memset (mem, 0, sz);
3263
3264 return mem;
3265 }
3266
3267 csz = chunksize (p);
3268
3269#if MORECORE_CLEARS
3270 if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize))
3271 {
3272 /* clear only the bytes from non-freshly-sbrked memory */
3273 csz = oldtopsize;
3274 }
3275#endif
3276
3277 /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that
3278 contents have an odd number of INTERNAL_SIZE_T-sized words;
3279 minimally 3. */
3280 d = (INTERNAL_SIZE_T *) mem;
3281 clearsize = csz - SIZE_SZ;
3282 nclears = clearsize / sizeof (INTERNAL_SIZE_T);
3283 assert (nclears >= 3);
3284
3285 if (nclears > 9)
3286 return memset (d, 0, clearsize);
3287
3288 else
3289 {
3290 *(d + 0) = 0;
3291 *(d + 1) = 0;
3292 *(d + 2) = 0;
3293 if (nclears > 4)
3294 {
3295 *(d + 3) = 0;
3296 *(d + 4) = 0;
3297 if (nclears > 6)
3298 {
3299 *(d + 5) = 0;
3300 *(d + 6) = 0;
3301 if (nclears > 8)
3302 {
3303 *(d + 7) = 0;
3304 *(d + 8) = 0;
3305 }
3306 }
3307 }
3308 }
3309
3310 return mem;
3311}
3312
3313/*
3314 ------------------------------ malloc ------------------------------
3315 */
3316
3317static void *
3318_int_malloc (mstate av, size_t bytes)
3319{
3320 INTERNAL_SIZE_T nb; /* normalized request size */
3321 unsigned int idx; /* associated bin index */
3322 mbinptr bin; /* associated bin */
3323
3324 mchunkptr victim; /* inspected/selected chunk */
3325 INTERNAL_SIZE_T size; /* its size */
3326 int victim_index; /* its bin index */
3327
3328 mchunkptr remainder; /* remainder from a split */
3329 unsigned long remainder_size; /* its size */
3330
3331 unsigned int block; /* bit map traverser */
3332 unsigned int bit; /* bit map traverser */
3333 unsigned int map; /* current word of binmap */
3334
3335 mchunkptr fwd; /* misc temp for linking */
3336 mchunkptr bck; /* misc temp for linking */
3337
3338 const char *errstr = NULL;
3339
3340 /*
3341 Convert request size to internal form by adding SIZE_SZ bytes
3342 overhead plus possibly more to obtain necessary alignment and/or
3343 to obtain a size of at least MINSIZE, the smallest allocatable
3344 size. Also, checked_request2size traps (returning 0) request sizes
3345 that are so large that they wrap around zero when padded and
3346 aligned.
3347 */
3348
3349 checked_request2size (bytes, nb);
3350
3351 /* There are no usable arenas. Fall back to sysmalloc to get a chunk from
3352 mmap. */
3353 if (__glibc_unlikely (av == NULL))
3354 {
3355 void *p = sysmalloc (nb, av);
3356 if (p != NULL)
3357 alloc_perturb (p, bytes);
3358 return p;
3359 }
3360
3361 /*
3362 If the size qualifies as a fastbin, first check corresponding bin.
3363 This code is safe to execute even if av is not yet initialized, so we
3364 can try it without checking, which saves some time on this fast path.
3365 */
3366
3367 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ()))
3368 {
3369 idx = fastbin_index (nb);
3370 mfastbinptr *fb = &fastbin (av, idx);
3371 mchunkptr pp = *fb;
3372 do
3373 {
3374 victim = pp;
3375 if (victim == NULL)
3376 break;
3377 }
3378 while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim))
3379 != victim);
3380 if (victim != 0)
3381 {
3382 if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0))
3383 {
3384 errstr = "malloc(): memory corruption (fast)";
3385 errout:
3386 malloc_printerr (check_action, errstr, chunk2mem (victim), av);
3387 return NULL;
3388 }
3389 check_remalloced_chunk (av, victim, nb);
3390 void *p = chunk2mem (victim);
3391 alloc_perturb (p, bytes);
3392 return p;
3393 }
3394 }
3395
3396 /*
3397 If a small request, check regular bin. Since these "smallbins"
3398 hold one size each, no searching within bins is necessary.
3399 (For a large request, we need to wait until unsorted chunks are
3400 processed to find best fit. But for small ones, fits are exact
3401 anyway, so we can check now, which is faster.)
3402 */
3403
3404 if (in_smallbin_range (nb))
3405 {
3406 idx = smallbin_index (nb);
3407 bin = bin_at (av, idx);
3408
3409 if ((victim = last (bin)) != bin)
3410 {
3411 if (victim == 0) /* initialization check */
3412 malloc_consolidate (av);
3413 else
3414 {
3415 bck = victim->bk;
3416 if (__glibc_unlikely (bck->fd != victim))
3417 {
3418 errstr = "malloc(): smallbin double linked list corrupted";
3419 goto errout;
3420 }
3421 set_inuse_bit_at_offset (victim, nb);
3422 bin->bk = bck;
3423 bck->fd = bin;
3424
3425 if (av != &main_arena)
3426 set_non_main_arena (victim);
3427 check_malloced_chunk (av, victim, nb);
3428 void *p = chunk2mem (victim);
3429 alloc_perturb (p, bytes);
3430 return p;
3431 }
3432 }
3433 }
3434
3435 /*
3436 If this is a large request, consolidate fastbins before continuing.
3437 While it might look excessive to kill all fastbins before
3438 even seeing if there is space available, this avoids
3439 fragmentation problems normally associated with fastbins.
3440 Also, in practice, programs tend to have runs of either small or
3441 large requests, but less often mixtures, so consolidation is not
3442 invoked all that often in most programs. And the programs that
3443 it is called frequently in otherwise tend to fragment.
3444 */
3445
3446 else
3447 {
3448 idx = largebin_index (nb);
3449 if (have_fastchunks (av))
3450 malloc_consolidate (av);
3451 }
3452
3453 /*
3454 Process recently freed or remaindered chunks, taking one only if
3455 it is exact fit, or, if this a small request, the chunk is remainder from
3456 the most recent non-exact fit. Place other traversed chunks in
3457 bins. Note that this step is the only place in any routine where
3458 chunks are placed in bins.
3459
3460 The outer loop here is needed because we might not realize until
3461 near the end of malloc that we should have consolidated, so must
3462 do so and retry. This happens at most once, and only when we would
3463 otherwise need to expand memory to service a "small" request.
3464 */
3465
3466 for (;; )
3467 {
3468 int iters = 0;
3469 while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av))
3470 {
3471 bck = victim->bk;
3472 if (__builtin_expect (chunksize_nomask (victim) <= 2 * SIZE_SZ, 0)
3473 || __builtin_expect (chunksize_nomask (victim)
3474 > av->system_mem, 0))
3475 malloc_printerr (check_action, "malloc(): memory corruption",
3476 chunk2mem (victim), av);
3477 size = chunksize (victim);
3478
3479 /*
3480 If a small request, try to use last remainder if it is the
3481 only chunk in unsorted bin. This helps promote locality for
3482 runs of consecutive small requests. This is the only
3483 exception to best-fit, and applies only when there is
3484 no exact fit for a small chunk.
3485 */
3486
3487 if (in_smallbin_range (nb) &&
3488 bck == unsorted_chunks (av) &&
3489 victim == av->last_remainder &&
3490 (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
3491 {
3492 /* split and reattach remainder */
3493 remainder_size = size - nb;
3494 remainder = chunk_at_offset (victim, nb);
3495 unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
3496 av->last_remainder = remainder;
3497 remainder->bk = remainder->fd = unsorted_chunks (av);
3498 if (!in_smallbin_range (remainder_size))
3499 {
3500 remainder->fd_nextsize = NULL;
3501 remainder->bk_nextsize = NULL;
3502 }
3503
3504 set_head (victim, nb | PREV_INUSE |
3505 (av != &main_arena ? NON_MAIN_ARENA : 0));
3506 set_head (remainder, remainder_size | PREV_INUSE);
3507 set_foot (remainder, remainder_size);
3508
3509 check_malloced_chunk (av, victim, nb);
3510 void *p = chunk2mem (victim);
3511 alloc_perturb (p, bytes);
3512 return p;
3513 }
3514
3515 /* remove from unsorted list */
3516 unsorted_chunks (av)->bk = bck;
3517 bck->fd = unsorted_chunks (av);
3518
3519 /* Take now instead of binning if exact fit */
3520
3521 if (size == nb)
3522 {
3523 set_inuse_bit_at_offset (victim, size);
3524 if (av != &main_arena)
3525 set_non_main_arena (victim);
3526 check_malloced_chunk (av, victim, nb);
3527 void *p = chunk2mem (victim);
3528 alloc_perturb (p, bytes);
3529 return p;
3530 }
3531
3532 /* place chunk in bin */
3533
3534 if (in_smallbin_range (size))
3535 {
3536 victim_index = smallbin_index (size);
3537 bck = bin_at (av, victim_index);
3538 fwd = bck->fd;
3539 }
3540 else
3541 {
3542 victim_index = largebin_index (size);
3543 bck = bin_at (av, victim_index);
3544 fwd = bck->fd;
3545
3546 /* maintain large bins in sorted order */
3547 if (fwd != bck)
3548 {
3549 /* Or with inuse bit to speed comparisons */
3550 size |= PREV_INUSE;
3551 /* if smaller than smallest, bypass loop below */
3552 assert (chunk_main_arena (bck->bk));
3553 if ((unsigned long) (size)
3554 < (unsigned long) chunksize_nomask (bck->bk))
3555 {
3556 fwd = bck;
3557 bck = bck->bk;
3558
3559 victim->fd_nextsize = fwd->fd;
3560 victim->bk_nextsize = fwd->fd->bk_nextsize;
3561 fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
3562 }
3563 else
3564 {
3565 assert (chunk_main_arena (fwd));
3566 while ((unsigned long) size < chunksize_nomask (fwd))
3567 {
3568 fwd = fwd->fd_nextsize;
3569 assert (chunk_main_arena (fwd));
3570 }
3571
3572 if ((unsigned long) size
3573 == (unsigned long) chunksize_nomask (fwd))
3574 /* Always insert in the second position. */
3575 fwd = fwd->fd;
3576 else
3577 {
3578 victim->fd_nextsize = fwd;
3579 victim->bk_nextsize = fwd->bk_nextsize;
3580 fwd->bk_nextsize = victim;
3581 victim->bk_nextsize->fd_nextsize = victim;
3582 }
3583 bck = fwd->bk;
3584 }
3585 }
3586 else
3587 victim->fd_nextsize = victim->bk_nextsize = victim;
3588 }
3589
3590 mark_bin (av, victim_index);
3591 victim->bk = bck;
3592 victim->fd = fwd;
3593 fwd->bk = victim;
3594 bck->fd = victim;
3595
3596#define MAX_ITERS 10000
3597 if (++iters >= MAX_ITERS)
3598 break;
3599 }
3600
3601 /*
3602 If a large request, scan through the chunks of current bin in
3603 sorted order to find smallest that fits. Use the skip list for this.
3604 */
3605
3606 if (!in_smallbin_range (nb))
3607 {
3608 bin = bin_at (av, idx);
3609
3610 /* skip scan if empty or largest chunk is too small */
3611 if ((victim = first (bin)) != bin
3612 && (unsigned long) chunksize_nomask (victim)
3613 >= (unsigned long) (nb))
3614 {
3615 victim = victim->bk_nextsize;
3616 while (((unsigned long) (size = chunksize (victim)) <
3617 (unsigned long) (nb)))
3618 victim = victim->bk_nextsize;
3619
3620 /* Avoid removing the first entry for a size so that the skip
3621 list does not have to be rerouted. */
3622 if (victim != last (bin)
3623 && chunksize_nomask (victim)
3624 == chunksize_nomask (victim->fd))
3625 victim = victim->fd;
3626
3627 remainder_size = size - nb;
3628 unlink (av, victim, bck, fwd);
3629
3630 /* Exhaust */
3631 if (remainder_size < MINSIZE)
3632 {
3633 set_inuse_bit_at_offset (victim, size);
3634 if (av != &main_arena)
3635 set_non_main_arena (victim);
3636 }
3637 /* Split */
3638 else
3639 {
3640 remainder = chunk_at_offset (victim, nb);
3641 /* We cannot assume the unsorted list is empty and therefore
3642 have to perform a complete insert here. */
3643 bck = unsorted_chunks (av);
3644 fwd = bck->fd;
3645 if (__glibc_unlikely (fwd->bk != bck))
3646 {
3647 errstr = "malloc(): corrupted unsorted chunks";
3648 goto errout;
3649 }
3650 remainder->bk = bck;
3651 remainder->fd = fwd;
3652 bck->fd = remainder;
3653 fwd->bk = remainder;
3654 if (!in_smallbin_range (remainder_size))
3655 {
3656 remainder->fd_nextsize = NULL;
3657 remainder->bk_nextsize = NULL;
3658 }
3659 set_head (victim, nb | PREV_INUSE |
3660 (av != &main_arena ? NON_MAIN_ARENA : 0));
3661 set_head (remainder, remainder_size | PREV_INUSE);
3662 set_foot (remainder, remainder_size);
3663 }
3664 check_malloced_chunk (av, victim, nb);
3665 void *p = chunk2mem (victim);
3666 alloc_perturb (p, bytes);
3667 return p;
3668 }
3669 }
3670
3671 /*
3672 Search for a chunk by scanning bins, starting with next largest
3673 bin. This search is strictly by best-fit; i.e., the smallest
3674 (with ties going to approximately the least recently used) chunk
3675 that fits is selected.
3676
3677 The bitmap avoids needing to check that most blocks are nonempty.
3678 The particular case of skipping all bins during warm-up phases
3679 when no chunks have been returned yet is faster than it might look.
3680 */
3681
3682 ++idx;
3683 bin = bin_at (av, idx);
3684 block = idx2block (idx);
3685 map = av->binmap[block];
3686 bit = idx2bit (idx);
3687
3688 for (;; )
3689 {
3690 /* Skip rest of block if there are no more set bits in this block. */
3691 if (bit > map || bit == 0)
3692 {
3693 do
3694 {
3695 if (++block >= BINMAPSIZE) /* out of bins */
3696 goto use_top;
3697 }
3698 while ((map = av->binmap[block]) == 0);
3699
3700 bin = bin_at (av, (block << BINMAPSHIFT));
3701 bit = 1;
3702 }
3703
3704 /* Advance to bin with set bit. There must be one. */
3705 while ((bit & map) == 0)
3706 {
3707 bin = next_bin (bin);
3708 bit <<= 1;
3709 assert (bit != 0);
3710 }
3711
3712 /* Inspect the bin. It is likely to be non-empty */
3713 victim = last (bin);
3714
3715 /* If a false alarm (empty bin), clear the bit. */
3716 if (victim == bin)
3717 {
3718 av->binmap[block] = map &= ~bit; /* Write through */
3719 bin = next_bin (bin);
3720 bit <<= 1;
3721 }
3722
3723 else
3724 {
3725 size = chunksize (victim);
3726
3727 /* We know the first chunk in this bin is big enough to use. */
3728 assert ((unsigned long) (size) >= (unsigned long) (nb));
3729
3730 remainder_size = size - nb;
3731
3732 /* unlink */
3733 unlink (av, victim, bck, fwd);
3734
3735 /* Exhaust */
3736 if (remainder_size < MINSIZE)
3737 {
3738 set_inuse_bit_at_offset (victim, size);
3739 if (av != &main_arena)
3740 set_non_main_arena (victim);
3741 }
3742
3743 /* Split */
3744 else
3745 {
3746 remainder = chunk_at_offset (victim, nb);
3747
3748 /* We cannot assume the unsorted list is empty and therefore
3749 have to perform a complete insert here. */
3750 bck = unsorted_chunks (av);
3751 fwd = bck->fd;
3752 if (__glibc_unlikely (fwd->bk != bck))
3753 {
3754 errstr = "malloc(): corrupted unsorted chunks 2";
3755 goto errout;
3756 }
3757 remainder->bk = bck;
3758 remainder->fd = fwd;
3759 bck->fd = remainder;
3760 fwd->bk = remainder;
3761
3762 /* advertise as last remainder */
3763 if (in_smallbin_range (nb))
3764 av->last_remainder = remainder;
3765 if (!in_smallbin_range (remainder_size))
3766 {
3767 remainder->fd_nextsize = NULL;
3768 remainder->bk_nextsize = NULL;
3769 }
3770 set_head (victim, nb | PREV_INUSE |
3771 (av != &main_arena ? NON_MAIN_ARENA : 0));
3772 set_head (remainder, remainder_size | PREV_INUSE);
3773 set_foot (remainder, remainder_size);
3774 }
3775 check_malloced_chunk (av, victim, nb);
3776 void *p = chunk2mem (victim);
3777 alloc_perturb (p, bytes);
3778 return p;
3779 }
3780 }
3781
3782 use_top:
3783 /*
3784 If large enough, split off the chunk bordering the end of memory
3785 (held in av->top). Note that this is in accord with the best-fit
3786 search rule. In effect, av->top is treated as larger (and thus
3787 less well fitting) than any other available chunk since it can
3788 be extended to be as large as necessary (up to system
3789 limitations).
3790
3791 We require that av->top always exists (i.e., has size >=
3792 MINSIZE) after initialization, so if it would otherwise be
3793 exhausted by current request, it is replenished. (The main
3794 reason for ensuring it exists is that we may need MINSIZE space
3795 to put in fenceposts in sysmalloc.)
3796 */
3797
3798 victim = av->top;
3799 size = chunksize (victim);
3800
3801 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
3802 {
3803 remainder_size = size - nb;
3804 remainder = chunk_at_offset (victim, nb);
3805 av->top = remainder;
3806 set_head (victim, nb | PREV_INUSE |
3807 (av != &main_arena ? NON_MAIN_ARENA : 0));
3808 set_head (remainder, remainder_size | PREV_INUSE);
3809
3810 check_malloced_chunk (av, victim, nb);
3811 void *p = chunk2mem (victim);
3812 alloc_perturb (p, bytes);
3813 return p;
3814 }
3815
3816 /* When we are using atomic ops to free fast chunks we can get
3817 here for all block sizes. */
3818 else if (have_fastchunks (av))
3819 {
3820 malloc_consolidate (av);
3821 /* restore original bin index */
3822 if (in_smallbin_range (nb))
3823 idx = smallbin_index (nb);
3824 else
3825 idx = largebin_index (nb);
3826 }
3827
3828 /*
3829 Otherwise, relay to handle system-dependent cases
3830 */
3831 else
3832 {
3833 void *p = sysmalloc (nb, av);
3834 if (p != NULL)
3835 alloc_perturb (p, bytes);
3836 return p;
3837 }
3838 }
3839}
3840
3841/*
3842 ------------------------------ free ------------------------------
3843 */
3844
3845static void
3846_int_free (mstate av, mchunkptr p, int have_lock)
3847{
3848 INTERNAL_SIZE_T size; /* its size */
3849 mfastbinptr *fb; /* associated fastbin */
3850 mchunkptr nextchunk; /* next contiguous chunk */
3851 INTERNAL_SIZE_T nextsize; /* its size */
3852 int nextinuse; /* true if nextchunk is used */
3853 INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
3854 mchunkptr bck; /* misc temp for linking */
3855 mchunkptr fwd; /* misc temp for linking */
3856
3857 const char *errstr = NULL;
3858 int locked = 0;
3859
3860 size = chunksize (p);
3861
3862 /* Little security check which won't hurt performance: the
3863 allocator never wrapps around at the end of the address space.
3864 Therefore we can exclude some size values which might appear
3865 here by accident or by "design" from some intruder. */
3866 if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
3867 || __builtin_expect (misaligned_chunk (p), 0))
3868 {
3869 errstr = "free(): invalid pointer";
3870 errout:
3871 if (!have_lock && locked)
3872 __libc_lock_unlock (av->mutex);
3873 malloc_printerr (check_action, errstr, chunk2mem (p), av);
3874 return;
3875 }
3876 /* We know that each chunk is at least MINSIZE bytes in size or a
3877 multiple of MALLOC_ALIGNMENT. */
3878 if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
3879 {
3880 errstr = "free(): invalid size";
3881 goto errout;
3882 }
3883
3884 check_inuse_chunk(av, p);
3885
3886 /*
3887 If eligible, place chunk on a fastbin so it can be found
3888 and used quickly in malloc.
3889 */
3890
3891 if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
3892
3893#if TRIM_FASTBINS
3894 /*
3895 If TRIM_FASTBINS set, don't place chunks
3896 bordering top into fastbins
3897 */
3898 && (chunk_at_offset(p, size) != av->top)
3899#endif
3900 ) {
3901
3902 if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
3903 <= 2 * SIZE_SZ, 0)
3904 || __builtin_expect (chunksize (chunk_at_offset (p, size))
3905 >= av->system_mem, 0))
3906 {
3907 /* We might not have a lock at this point and concurrent modifications
3908 of system_mem might have let to a false positive. Redo the test
3909 after getting the lock. */
3910 if (have_lock
3911 || ({ assert (locked == 0);
3912 __libc_lock_lock (av->mutex);
3913 locked = 1;
3914 chunksize_nomask (chunk_at_offset (p, size)) <= 2 * SIZE_SZ
3915 || chunksize (chunk_at_offset (p, size)) >= av->system_mem;
3916 }))
3917 {
3918 errstr = "free(): invalid next size (fast)";
3919 goto errout;
3920 }
3921 if (! have_lock)
3922 {
3923 __libc_lock_unlock (av->mutex);
3924 locked = 0;
3925 }
3926 }
3927
3928 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
3929
3930 set_fastchunks(av);
3931 unsigned int idx = fastbin_index(size);
3932 fb = &fastbin (av, idx);
3933
3934 /* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
3935 mchunkptr old = *fb, old2;
3936 unsigned int old_idx = ~0u;
3937 do
3938 {
3939 /* Check that the top of the bin is not the record we are going to add
3940 (i.e., double free). */
3941 if (__builtin_expect (old == p, 0))
3942 {
3943 errstr = "double free or corruption (fasttop)";
3944 goto errout;
3945 }
3946 /* Check that size of fastbin chunk at the top is the same as
3947 size of the chunk that we are adding. We can dereference OLD
3948 only if we have the lock, otherwise it might have already been
3949 deallocated. See use of OLD_IDX below for the actual check. */
3950 if (have_lock && old != NULL)
3951 old_idx = fastbin_index(chunksize(old));
3952 p->fd = old2 = old;
3953 }
3954 while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2);
3955
3956 if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0))
3957 {
3958 errstr = "invalid fastbin entry (free)";
3959 goto errout;
3960 }
3961 }
3962
3963 /*
3964 Consolidate other non-mmapped chunks as they arrive.
3965 */
3966
3967 else if (!chunk_is_mmapped(p)) {
3968 if (! have_lock) {
3969 __libc_lock_lock (av->mutex);
3970 locked = 1;
3971 }
3972
3973 nextchunk = chunk_at_offset(p, size);
3974
3975 /* Lightweight tests: check whether the block is already the
3976 top block. */
3977 if (__glibc_unlikely (p == av->top))
3978 {
3979 errstr = "double free or corruption (top)";
3980 goto errout;
3981 }
3982 /* Or whether the next chunk is beyond the boundaries of the arena. */
3983 if (__builtin_expect (contiguous (av)
3984 && (char *) nextchunk
3985 >= ((char *) av->top + chunksize(av->top)), 0))
3986 {
3987 errstr = "double free or corruption (out)";
3988 goto errout;
3989 }
3990 /* Or whether the block is actually not marked used. */
3991 if (__glibc_unlikely (!prev_inuse(nextchunk)))
3992 {
3993 errstr = "double free or corruption (!prev)";
3994 goto errout;
3995 }
3996
3997 nextsize = chunksize(nextchunk);
3998 if (__builtin_expect (chunksize_nomask (nextchunk) <= 2 * SIZE_SZ, 0)
3999 || __builtin_expect (nextsize >= av->system_mem, 0))
4000 {
4001 errstr = "free(): invalid next size (normal)";
4002 goto errout;
4003 }
4004
4005 free_perturb (chunk2mem(p), size - 2 * SIZE_SZ);
4006
4007 /* consolidate backward */
4008 if (!prev_inuse(p)) {
4009 prevsize = prev_size (p);
4010 size += prevsize;
4011 p = chunk_at_offset(p, -((long) prevsize));
4012 unlink(av, p, bck, fwd);
4013 }
4014
4015 if (nextchunk != av->top) {
4016 /* get and clear inuse bit */
4017 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4018
4019 /* consolidate forward */
4020 if (!nextinuse) {
4021 unlink(av, nextchunk, bck, fwd);
4022 size += nextsize;
4023 } else
4024 clear_inuse_bit_at_offset(nextchunk, 0);
4025
4026 /*
4027 Place the chunk in unsorted chunk list. Chunks are
4028 not placed into regular bins until after they have
4029 been given one chance to be used in malloc.
4030 */
4031
4032 bck = unsorted_chunks(av);
4033 fwd = bck->fd;
4034 if (__glibc_unlikely (fwd->bk != bck))
4035 {
4036 errstr = "free(): corrupted unsorted chunks";
4037 goto errout;
4038 }
4039 p->fd = fwd;
4040 p->bk = bck;
4041 if (!in_smallbin_range(size))
4042 {
4043 p->fd_nextsize = NULL;
4044 p->bk_nextsize = NULL;
4045 }
4046 bck->fd = p;
4047 fwd->bk = p;
4048
4049 set_head(p, size | PREV_INUSE);
4050 set_foot(p, size);
4051
4052 check_free_chunk(av, p);
4053 }
4054
4055 /*
4056 If the chunk borders the current high end of memory,
4057 consolidate into top
4058 */
4059
4060 else {
4061 size += nextsize;
4062 set_head(p, size | PREV_INUSE);
4063 av->top = p;
4064 check_chunk(av, p);
4065 }
4066
4067 /*
4068 If freeing a large space, consolidate possibly-surrounding
4069 chunks. Then, if the total unused topmost memory exceeds trim
4070 threshold, ask malloc_trim to reduce top.
4071
4072 Unless max_fast is 0, we don't know if there are fastbins
4073 bordering top, so we cannot tell for sure whether threshold
4074 has been reached unless fastbins are consolidated. But we
4075 don't want to consolidate on each free. As a compromise,
4076 consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD
4077 is reached.
4078 */
4079
4080 if ((unsigned long)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {
4081 if (have_fastchunks(av))
4082 malloc_consolidate(av);
4083
4084 if (av == &main_arena) {
4085#ifndef MORECORE_CANNOT_TRIM
4086 if ((unsigned long)(chunksize(av->top)) >=
4087 (unsigned long)(mp_.trim_threshold))
4088 systrim(mp_.top_pad, av);
4089#endif
4090 } else {
4091 /* Always try heap_trim(), even if the top chunk is not
4092 large, because the corresponding heap might go away. */
4093 heap_info *heap = heap_for_ptr(top(av));
4094
4095 assert(heap->ar_ptr == av);
4096 heap_trim(heap, mp_.top_pad);
4097 }
4098 }
4099
4100 if (! have_lock) {
4101 assert (locked);
4102 __libc_lock_unlock (av->mutex);
4103 }
4104 }
4105 /*
4106 If the chunk was allocated via mmap, release via munmap().
4107 */
4108
4109 else {
4110 munmap_chunk (p);
4111 }
4112}
4113
4114/*
4115 ------------------------- malloc_consolidate -------------------------
4116
4117 malloc_consolidate is a specialized version of free() that tears
4118 down chunks held in fastbins. Free itself cannot be used for this
4119 purpose since, among other things, it might place chunks back onto
4120 fastbins. So, instead, we need to use a minor variant of the same
4121 code.
4122
4123 Also, because this routine needs to be called the first time through
4124 malloc anyway, it turns out to be the perfect place to trigger
4125 initialization code.
4126*/
4127
4128static void malloc_consolidate(mstate av)
4129{
4130 mfastbinptr* fb; /* current fastbin being consolidated */
4131 mfastbinptr* maxfb; /* last fastbin (for loop control) */
4132 mchunkptr p; /* current chunk being consolidated */
4133 mchunkptr nextp; /* next chunk to consolidate */
4134 mchunkptr unsorted_bin; /* bin header */
4135 mchunkptr first_unsorted; /* chunk to link to */
4136
4137 /* These have same use as in free() */
4138 mchunkptr nextchunk;
4139 INTERNAL_SIZE_T size;
4140 INTERNAL_SIZE_T nextsize;
4141 INTERNAL_SIZE_T prevsize;
4142 int nextinuse;
4143 mchunkptr bck;
4144 mchunkptr fwd;
4145
4146 /*
4147 If max_fast is 0, we know that av hasn't
4148 yet been initialized, in which case do so below
4149 */
4150
4151 if (get_max_fast () != 0) {
4152 clear_fastchunks(av);
4153
4154 unsorted_bin = unsorted_chunks(av);
4155
4156 /*
4157 Remove each chunk from fast bin and consolidate it, placing it
4158 then in unsorted bin. Among other reasons for doing this,
4159 placing in unsorted bin avoids needing to calculate actual bins
4160 until malloc is sure that chunks aren't immediately going to be
4161 reused anyway.
4162 */
4163
4164 maxfb = &fastbin (av, NFASTBINS - 1);
4165 fb = &fastbin (av, 0);
4166 do {
4167 p = atomic_exchange_acq (fb, NULL);
4168 if (p != 0) {
4169 do {
4170 check_inuse_chunk(av, p);
4171 nextp = p->fd;
4172
4173 /* Slightly streamlined version of consolidation code in free() */
4174 size = chunksize (p);
4175 nextchunk = chunk_at_offset(p, size);
4176 nextsize = chunksize(nextchunk);
4177
4178 if (!prev_inuse(p)) {
4179 prevsize = prev_size (p);
4180 size += prevsize;
4181 p = chunk_at_offset(p, -((long) prevsize));
4182 unlink(av, p, bck, fwd);
4183 }
4184
4185 if (nextchunk != av->top) {
4186 nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
4187
4188 if (!nextinuse) {
4189 size += nextsize;
4190 unlink(av, nextchunk, bck, fwd);
4191 } else
4192 clear_inuse_bit_at_offset(nextchunk, 0);
4193
4194 first_unsorted = unsorted_bin->fd;
4195 unsorted_bin->fd = p;
4196 first_unsorted->bk = p;
4197
4198 if (!in_smallbin_range (size)) {
4199 p->fd_nextsize = NULL;
4200 p->bk_nextsize = NULL;
4201 }
4202
4203 set_head(p, size | PREV_INUSE);
4204 p->bk = unsorted_bin;
4205 p->fd = first_unsorted;
4206 set_foot(p, size);
4207 }
4208
4209 else {
4210 size += nextsize;
4211 set_head(p, size | PREV_INUSE);
4212 av->top = p;
4213 }
4214
4215 } while ( (p = nextp) != 0);
4216
4217 }
4218 } while (fb++ != maxfb);
4219 }
4220 else {
4221 malloc_init_state(av);
4222 check_malloc_state(av);
4223 }
4224}
4225
4226/*
4227 ------------------------------ realloc ------------------------------
4228*/
4229
4230void*
4231_int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize,
4232 INTERNAL_SIZE_T nb)
4233{
4234 mchunkptr newp; /* chunk to return */
4235 INTERNAL_SIZE_T newsize; /* its size */
4236 void* newmem; /* corresponding user mem */
4237
4238 mchunkptr next; /* next contiguous chunk after oldp */
4239
4240 mchunkptr remainder; /* extra space at end of newp */
4241 unsigned long remainder_size; /* its size */
4242
4243 mchunkptr bck; /* misc temp for linking */
4244 mchunkptr fwd; /* misc temp for linking */
4245
4246 unsigned long copysize; /* bytes to copy */
4247 unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */
4248 INTERNAL_SIZE_T* s; /* copy source */
4249 INTERNAL_SIZE_T* d; /* copy destination */
4250
4251 const char *errstr = NULL;
4252
4253 /* oldmem size */
4254 if (__builtin_expect (chunksize_nomask (oldp) <= 2 * SIZE_SZ, 0)
4255 || __builtin_expect (oldsize >= av->system_mem, 0))
4256 {
4257 errstr = "realloc(): invalid old size";
4258 errout:
4259 malloc_printerr (check_action, errstr, chunk2mem (oldp), av);
4260 return NULL;
4261 }
4262
4263 check_inuse_chunk (av, oldp);
4264
4265 /* All callers already filter out mmap'ed chunks. */
4266 assert (!chunk_is_mmapped (oldp));
4267
4268 next = chunk_at_offset (oldp, oldsize);
4269 INTERNAL_SIZE_T nextsize = chunksize (next);
4270 if (__builtin_expect (chunksize_nomask (next) <= 2 * SIZE_SZ, 0)
4271 || __builtin_expect (nextsize >= av->system_mem, 0))
4272 {
4273 errstr = "realloc(): invalid next size";
4274 goto errout;
4275 }
4276
4277 if ((unsigned long) (oldsize) >= (unsigned long) (nb))
4278 {
4279 /* already big enough; split below */
4280 newp = oldp;
4281 newsize = oldsize;
4282 }
4283
4284 else
4285 {
4286 /* Try to expand forward into top */
4287 if (next == av->top &&
4288 (unsigned long) (newsize = oldsize + nextsize) >=
4289 (unsigned long) (nb + MINSIZE))
4290 {
4291 set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4292 av->top = chunk_at_offset (oldp, nb);
4293 set_head (av->top, (newsize - nb) | PREV_INUSE);
4294 check_inuse_chunk (av, oldp);
4295 return chunk2mem (oldp);
4296 }
4297
4298 /* Try to expand forward into next chunk; split off remainder below */
4299 else if (next != av->top &&
4300 !inuse (next) &&
4301 (unsigned long) (newsize = oldsize + nextsize) >=
4302 (unsigned long) (nb))
4303 {
4304 newp = oldp;
4305 unlink (av, next, bck, fwd);
4306 }
4307
4308 /* allocate, copy, free */
4309 else
4310 {
4311 newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK);
4312 if (newmem == 0)
4313 return 0; /* propagate failure */
4314
4315 newp = mem2chunk (newmem);
4316 newsize = chunksize (newp);
4317
4318 /*
4319 Avoid copy if newp is next chunk after oldp.
4320 */
4321 if (newp == next)
4322 {
4323 newsize += oldsize;
4324 newp = oldp;
4325 }
4326 else
4327 {
4328 /*
4329 Unroll copy of <= 36 bytes (72 if 8byte sizes)
4330 We know that contents have an odd number of
4331 INTERNAL_SIZE_T-sized words; minimally 3.
4332 */
4333
4334 copysize = oldsize - SIZE_SZ;
4335 s = (INTERNAL_SIZE_T *) (chunk2mem (oldp));
4336 d = (INTERNAL_SIZE_T *) (newmem);
4337 ncopies = copysize / sizeof (INTERNAL_SIZE_T);
4338 assert (ncopies >= 3);
4339
4340 if (ncopies > 9)
4341 memcpy (d, s, copysize);
4342
4343 else
4344 {
4345 *(d + 0) = *(s + 0);
4346 *(d + 1) = *(s + 1);
4347 *(d + 2) = *(s + 2);
4348 if (ncopies > 4)
4349 {
4350 *(d + 3) = *(s + 3);
4351 *(d + 4) = *(s + 4);
4352 if (ncopies > 6)
4353 {
4354 *(d + 5) = *(s + 5);
4355 *(d + 6) = *(s + 6);
4356 if (ncopies > 8)
4357 {
4358 *(d + 7) = *(s + 7);
4359 *(d + 8) = *(s + 8);
4360 }
4361 }
4362 }
4363 }
4364
4365 _int_free (av, oldp, 1);
4366 check_inuse_chunk (av, newp);
4367 return chunk2mem (newp);
4368 }
4369 }
4370 }
4371
4372 /* If possible, free extra space in old or extended chunk */
4373
4374 assert ((unsigned long) (newsize) >= (unsigned long) (nb));
4375
4376 remainder_size = newsize - nb;
4377
4378 if (remainder_size < MINSIZE) /* not enough extra to split off */
4379 {
4380 set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4381 set_inuse_bit_at_offset (newp, newsize);
4382 }
4383 else /* split remainder */
4384 {
4385 remainder = chunk_at_offset (newp, nb);
4386 set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0));
4387 set_head (remainder, remainder_size | PREV_INUSE |
4388 (av != &main_arena ? NON_MAIN_ARENA : 0));
4389 /* Mark remainder as inuse so free() won't complain */
4390 set_inuse_bit_at_offset (remainder, remainder_size);
4391 _int_free (av, remainder, 1);
4392 }
4393
4394 check_inuse_chunk (av, newp);
4395 return chunk2mem (newp);
4396}
4397
4398/*
4399 ------------------------------ memalign ------------------------------
4400 */
4401
4402static void *
4403_int_memalign (mstate av, size_t alignment, size_t bytes)
4404{
4405 INTERNAL_SIZE_T nb; /* padded request size */
4406 char *m; /* memory returned by malloc call */
4407 mchunkptr p; /* corresponding chunk */
4408 char *brk; /* alignment point within p */
4409 mchunkptr newp; /* chunk to return */
4410 INTERNAL_SIZE_T newsize; /* its size */
4411 INTERNAL_SIZE_T leadsize; /* leading space before alignment point */
4412 mchunkptr remainder; /* spare room at end to split off */
4413 unsigned long remainder_size; /* its size */
4414 INTERNAL_SIZE_T size;
4415
4416
4417
4418 checked_request2size (bytes, nb);
4419
4420 /*
4421 Strategy: find a spot within that chunk that meets the alignment
4422 request, and then possibly free the leading and trailing space.
4423 */
4424
4425
4426 /* Call malloc with worst case padding to hit alignment. */
4427
4428 m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
4429
4430 if (m == 0)
4431 return 0; /* propagate failure */
4432
4433 p = mem2chunk (m);
4434
4435 if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
4436
4437 { /*
4438 Find an aligned spot inside chunk. Since we need to give back
4439 leading space in a chunk of at least MINSIZE, if the first
4440 calculation places us at a spot with less than MINSIZE leader,
4441 we can move to the next aligned spot -- we've allocated enough
4442 total room so that this is always possible.
4443 */
4444 brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) &
4445 - ((signed long) alignment));
4446 if ((unsigned long) (brk - (char *) (p)) < MINSIZE)
4447 brk += alignment;
4448
4449 newp = (mchunkptr) brk;
4450 leadsize = brk - (char *) (p);
4451 newsize = chunksize (p) - leadsize;
4452
4453 /* For mmapped chunks, just adjust offset */
4454 if (chunk_is_mmapped (p))
4455 {
4456 set_prev_size (newp, prev_size (p) + leadsize);
4457 set_head (newp, newsize | IS_MMAPPED);
4458 return chunk2mem (newp);
4459 }
4460
4461 /* Otherwise, give back leader, use the rest */
4462 set_head (newp, newsize | PREV_INUSE |
4463 (av != &main_arena ? NON_MAIN_ARENA : 0));
4464 set_inuse_bit_at_offset (newp, newsize);
4465 set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0));
4466 _int_free (av, p, 1);
4467 p = newp;
4468
4469 assert (newsize >= nb &&
4470 (((unsigned long) (chunk2mem (p))) % alignment) == 0);
4471 }
4472
4473 /* Also give back spare room at the end */
4474 if (!chunk_is_mmapped (p))
4475 {
4476 size = chunksize (p);
4477 if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE))
4478 {
4479 remainder_size = size - nb;
4480 remainder = chunk_at_offset (p, nb);
4481 set_head (remainder, remainder_size | PREV_INUSE |
4482 (av != &main_arena ? NON_MAIN_ARENA : 0));
4483 set_head_size (p, nb);
4484 _int_free (av, remainder, 1);
4485 }
4486 }
4487
4488 check_inuse_chunk (av, p);
4489 return chunk2mem (p);
4490}
4491
4492
4493/*
4494 ------------------------------ malloc_trim ------------------------------
4495 */
4496
4497static int
4498mtrim (mstate av, size_t pad)
4499{
4500 /* Don't touch corrupt arenas. */
4501 if (arena_is_corrupt (av))
4502 return 0;
4503
4504 /* Ensure initialization/consolidation */
4505 malloc_consolidate (av);
4506
4507 const size_t ps = GLRO (dl_pagesize);
4508 int psindex = bin_index (ps);
4509 const size_t psm1 = ps - 1;
4510
4511 int result = 0;
4512 for (int i = 1; i < NBINS; ++i)
4513 if (i == 1 || i >= psindex)
4514 {
4515 mbinptr bin = bin_at (av, i);
4516
4517 for (mchunkptr p = last (bin); p != bin; p = p->bk)
4518 {
4519 INTERNAL_SIZE_T size = chunksize (p);
4520
4521 if (size > psm1 + sizeof (struct malloc_chunk))
4522 {
4523 /* See whether the chunk contains at least one unused page. */
4524 char *paligned_mem = (char *) (((uintptr_t) p
4525 + sizeof (struct malloc_chunk)
4526 + psm1) & ~psm1);
4527
4528 assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem);
4529 assert ((char *) p + size > paligned_mem);
4530
4531 /* This is the size we could potentially free. */
4532 size -= paligned_mem - (char *) p;
4533
4534 if (size > psm1)
4535 {
4536#if MALLOC_DEBUG
4537 /* When debugging we simulate destroying the memory
4538 content. */
4539 memset (paligned_mem, 0x89, size & ~psm1);
4540#endif
4541 __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);
4542
4543 result = 1;
4544 }
4545 }
4546 }
4547 }
4548
4549#ifndef MORECORE_CANNOT_TRIM
4550 return result | (av == &main_arena ? systrim (pad, av) : 0);
4551
4552#else
4553 return result;
4554#endif
4555}
4556
4557
4558int
4559__malloc_trim (size_t s)
4560{
4561 int result = 0;
4562
4563 if (__malloc_initialized < 0)
4564 ptmalloc_init ();
4565
4566 mstate ar_ptr = &main_arena;
4567 do
4568 {
4569 __libc_lock_lock (ar_ptr->mutex);
4570 result |= mtrim (ar_ptr, s);
4571 __libc_lock_unlock (ar_ptr->mutex);
4572
4573 ar_ptr = ar_ptr->next;
4574 }
4575 while (ar_ptr != &main_arena);
4576
4577 return result;
4578}
4579
4580
4581/*
4582 ------------------------- malloc_usable_size -------------------------
4583 */
4584
4585static size_t
4586musable (void *mem)
4587{
4588 mchunkptr p;
4589 if (mem != 0)
4590 {
4591 p = mem2chunk (mem);
4592
4593 if (__builtin_expect (using_malloc_checking == 1, 0))
4594 return malloc_check_get_size (p);
4595
4596 if (chunk_is_mmapped (p))
4597 {
4598 if (DUMPED_MAIN_ARENA_CHUNK (p))
4599 return chunksize (p) - SIZE_SZ;
4600 else
4601 return chunksize (p) - 2 * SIZE_SZ;
4602 }
4603 else if (inuse (p))
4604 return chunksize (p) - SIZE_SZ;
4605 }
4606 return 0;
4607}
4608
4609
4610size_t
4611__malloc_usable_size (void *m)
4612{
4613 size_t result;
4614
4615 result = musable (m);
4616 return result;
4617}
4618
4619/*
4620 ------------------------------ mallinfo ------------------------------
4621 Accumulate malloc statistics for arena AV into M.
4622 */
4623
4624static void
4625int_mallinfo (mstate av, struct mallinfo *m)
4626{
4627 size_t i;
4628 mbinptr b;
4629 mchunkptr p;
4630 INTERNAL_SIZE_T avail;
4631 INTERNAL_SIZE_T fastavail;
4632 int nblocks;
4633 int nfastblocks;
4634
4635 /* Ensure initialization */
4636 if (av->top == 0)
4637 malloc_consolidate (av);
4638
4639 check_malloc_state (av);
4640
4641 /* Account for top */
4642 avail = chunksize (av->top);
4643 nblocks = 1; /* top always exists */
4644
4645 /* traverse fastbins */
4646 nfastblocks = 0;
4647 fastavail = 0;
4648
4649 for (i = 0; i < NFASTBINS; ++i)
4650 {
4651 for (p = fastbin (av, i); p != 0; p = p->fd)
4652 {
4653 ++nfastblocks;
4654 fastavail += chunksize (p);
4655 }
4656 }
4657
4658 avail += fastavail;
4659
4660 /* traverse regular bins */
4661 for (i = 1; i < NBINS; ++i)
4662 {
4663 b = bin_at (av, i);
4664 for (p = last (b); p != b; p = p->bk)
4665 {
4666 ++nblocks;
4667 avail += chunksize (p);
4668 }
4669 }
4670
4671 m->smblks += nfastblocks;
4672 m->ordblks += nblocks;
4673 m->fordblks += avail;
4674 m->uordblks += av->system_mem - avail;
4675 m->arena += av->system_mem;
4676 m->fsmblks += fastavail;
4677 if (av == &main_arena)
4678 {
4679 m->hblks = mp_.n_mmaps;
4680 m->hblkhd = mp_.mmapped_mem;
4681 m->usmblks = 0;
4682 m->keepcost = chunksize (av->top);
4683 }
4684}
4685
4686
4687struct mallinfo
4688__libc_mallinfo (void)
4689{
4690 struct mallinfo m;
4691 mstate ar_ptr;
4692
4693 if (__malloc_initialized < 0)
4694 ptmalloc_init ();
4695
4696 memset (&m, 0, sizeof (m));
4697 ar_ptr = &main_arena;
4698 do
4699 {
4700 __libc_lock_lock (ar_ptr->mutex);
4701 int_mallinfo (ar_ptr, &m);
4702 __libc_lock_unlock (ar_ptr->mutex);
4703
4704 ar_ptr = ar_ptr->next;
4705 }
4706 while (ar_ptr != &main_arena);
4707
4708 return m;
4709}
4710
4711/*
4712 ------------------------------ malloc_stats ------------------------------
4713 */
4714
4715void
4716__malloc_stats (void)
4717{
4718 int i;
4719 mstate ar_ptr;
4720 unsigned int in_use_b = mp_.mmapped_mem, system_b = in_use_b;
4721
4722 if (__malloc_initialized < 0)
4723 ptmalloc_init ();
4724 _IO_flockfile (stderr);
4725 int old_flags2 = ((_IO_FILE *) stderr)->_flags2;
4726 ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL;
4727 for (i = 0, ar_ptr = &main_arena;; i++)
4728 {
4729 struct mallinfo mi;
4730
4731 memset (&mi, 0, sizeof (mi));
4732 __libc_lock_lock (ar_ptr->mutex);
4733 int_mallinfo (ar_ptr, &mi);
4734 fprintf (stderr, "Arena %d:\n", i);
4735 fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena);
4736 fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks);
4737#if MALLOC_DEBUG > 1
4738 if (i > 0)
4739 dump_heap (heap_for_ptr (top (ar_ptr)));
4740#endif
4741 system_b += mi.arena;
4742 in_use_b += mi.uordblks;
4743 __libc_lock_unlock (ar_ptr->mutex);
4744 ar_ptr = ar_ptr->next;
4745 if (ar_ptr == &main_arena)
4746 break;
4747 }
4748 fprintf (stderr, "Total (incl. mmap):\n");
4749 fprintf (stderr, "system bytes = %10u\n", system_b);
4750 fprintf (stderr, "in use bytes = %10u\n", in_use_b);
4751 fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps);
4752 fprintf (stderr, "max mmap bytes = %10lu\n",
4753 (unsigned long) mp_.max_mmapped_mem);
4754 ((_IO_FILE *) stderr)->_flags2 |= old_flags2;
4755 _IO_funlockfile (stderr);
4756}
4757
4758
4759/*
4760 ------------------------------ mallopt ------------------------------
4761 */
4762static inline int
4763__always_inline
4764do_set_trim_threshold (size_t value)
4765{
4766 LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, mp_.trim_threshold,
4767 mp_.no_dyn_threshold);
4768 mp_.trim_threshold = value;
4769 mp_.no_dyn_threshold = 1;
4770 return 1;
4771}
4772
4773static inline int
4774__always_inline
4775do_set_top_pad (size_t value)
4776{
4777 LIBC_PROBE (memory_mallopt_top_pad, 3, value, mp_.top_pad,
4778 mp_.no_dyn_threshold);
4779 mp_.top_pad = value;
4780 mp_.no_dyn_threshold = 1;
4781 return 1;
4782}
4783
4784static inline int
4785__always_inline
4786do_set_mmap_threshold (size_t value)
4787{
4788 /* Forbid setting the threshold too high. */
4789 if (value <= HEAP_MAX_SIZE / 2)
4790 {
4791 LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, mp_.mmap_threshold,
4792 mp_.no_dyn_threshold);
4793 mp_.mmap_threshold = value;
4794 mp_.no_dyn_threshold = 1;
4795 return 1;
4796 }
4797 return 0;
4798}
4799
4800static inline int
4801__always_inline
4802do_set_mmaps_max (int32_t value)
4803{
4804 LIBC_PROBE (memory_mallopt_mmap_max, 3, value, mp_.n_mmaps_max,
4805 mp_.no_dyn_threshold);
4806 mp_.n_mmaps_max = value;
4807 mp_.no_dyn_threshold = 1;
4808 return 1;
4809}
4810
4811static inline int
4812__always_inline
4813do_set_mallopt_check (int32_t value)
4814{
4815 LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action);
4816 check_action = value;
4817 return 1;
4818}
4819
4820static inline int
4821__always_inline
4822do_set_perturb_byte (int32_t value)
4823{
4824 LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte);
4825 perturb_byte = value;
4826 return 1;
4827}
4828
4829static inline int
4830__always_inline
4831do_set_arena_test (size_t value)
4832{
4833 LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test);
4834 mp_.arena_test = value;
4835 return 1;
4836}
4837
4838static inline int
4839__always_inline
4840do_set_arena_max (size_t value)
4841{
4842 LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max);
4843 mp_.arena_max = value;
4844 return 1;
4845}
4846
4847
4848int
4849__libc_mallopt (int param_number, int value)
4850{
4851 mstate av = &main_arena;
4852 int res = 1;
4853
4854 if (__malloc_initialized < 0)
4855 ptmalloc_init ();
4856 __libc_lock_lock (av->mutex);
4857 /* Ensure initialization/consolidation */
4858 malloc_consolidate (av);
4859
4860 LIBC_PROBE (memory_mallopt, 2, param_number, value);
4861
4862 switch (param_number)
4863 {
4864 case M_MXFAST:
4865 if (value >= 0 && value <= MAX_FAST_SIZE)
4866 {
4867 LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ());
4868 set_max_fast (value);
4869 }
4870 else
4871 res = 0;
4872 break;
4873
4874 case M_TRIM_THRESHOLD:
4875 do_set_trim_threshold (value);
4876 break;
4877
4878 case M_TOP_PAD:
4879 do_set_top_pad (value);
4880 break;
4881
4882 case M_MMAP_THRESHOLD:
4883 res = do_set_mmap_threshold (value);
4884 break;
4885
4886 case M_MMAP_MAX:
4887 do_set_mmaps_max (value);
4888 break;
4889
4890 case M_CHECK_ACTION:
4891 do_set_mallopt_check (value);
4892 break;
4893
4894 case M_PERTURB:
4895 do_set_perturb_byte (value);
4896 break;
4897
4898 case M_ARENA_TEST:
4899 if (value > 0)
4900 do_set_arena_test (value);
4901 break;
4902
4903 case M_ARENA_MAX:
4904 if (value > 0)
4905 do_set_arena_test (value);
4906 break;
4907 }
4908 __libc_lock_unlock (av->mutex);
4909 return res;
4910}
4911libc_hidden_def (__libc_mallopt)
4912
4913
4914/*
4915 -------------------- Alternative MORECORE functions --------------------
4916 */
4917
4918
4919/*
4920 General Requirements for MORECORE.
4921
4922 The MORECORE function must have the following properties:
4923
4924 If MORECORE_CONTIGUOUS is false:
4925
4926 * MORECORE must allocate in multiples of pagesize. It will
4927 only be called with arguments that are multiples of pagesize.
4928
4929 * MORECORE(0) must return an address that is at least
4930 MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)
4931
4932 else (i.e. If MORECORE_CONTIGUOUS is true):
4933
4934 * Consecutive calls to MORECORE with positive arguments
4935 return increasing addresses, indicating that space has been
4936 contiguously extended.
4937
4938 * MORECORE need not allocate in multiples of pagesize.
4939 Calls to MORECORE need not have args of multiples of pagesize.
4940
4941 * MORECORE need not page-align.
4942
4943 In either case:
4944
4945 * MORECORE may allocate more memory than requested. (Or even less,
4946 but this will generally result in a malloc failure.)
4947
4948 * MORECORE must not allocate memory when given argument zero, but
4949 instead return one past the end address of memory from previous
4950 nonzero call. This malloc does NOT call MORECORE(0)
4951 until at least one call with positive arguments is made, so
4952 the initial value returned is not important.
4953
4954 * Even though consecutive calls to MORECORE need not return contiguous
4955 addresses, it must be OK for malloc'ed chunks to span multiple
4956 regions in those cases where they do happen to be contiguous.
4957
4958 * MORECORE need not handle negative arguments -- it may instead
4959 just return MORECORE_FAILURE when given negative arguments.
4960 Negative arguments are always multiples of pagesize. MORECORE
4961 must not misinterpret negative args as large positive unsigned
4962 args. You can suppress all such calls from even occurring by defining
4963 MORECORE_CANNOT_TRIM,
4964
4965 There is some variation across systems about the type of the
4966 argument to sbrk/MORECORE. If size_t is unsigned, then it cannot
4967 actually be size_t, because sbrk supports negative args, so it is
4968 normally the signed type of the same width as size_t (sometimes
4969 declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much
4970 matter though. Internally, we use "long" as arguments, which should
4971 work across all reasonable possibilities.
4972
4973 Additionally, if MORECORE ever returns failure for a positive
4974 request, then mmap is used as a noncontiguous system allocator. This
4975 is a useful backup strategy for systems with holes in address spaces
4976 -- in this case sbrk cannot contiguously expand the heap, but mmap
4977 may be able to map noncontiguous space.
4978
4979 If you'd like mmap to ALWAYS be used, you can define MORECORE to be
4980 a function that always returns MORECORE_FAILURE.
4981
4982 If you are using this malloc with something other than sbrk (or its
4983 emulation) to supply memory regions, you probably want to set
4984 MORECORE_CONTIGUOUS as false. As an example, here is a custom
4985 allocator kindly contributed for pre-OSX macOS. It uses virtually
4986 but not necessarily physically contiguous non-paged memory (locked
4987 in, present and won't get swapped out). You can use it by
4988 uncommenting this section, adding some #includes, and setting up the
4989 appropriate defines above:
4990
4991 *#define MORECORE osMoreCore
4992 *#define MORECORE_CONTIGUOUS 0
4993
4994 There is also a shutdown routine that should somehow be called for
4995 cleanup upon program exit.
4996
4997 *#define MAX_POOL_ENTRIES 100
4998 *#define MINIMUM_MORECORE_SIZE (64 * 1024)
4999 static int next_os_pool;
5000 void *our_os_pools[MAX_POOL_ENTRIES];
5001
5002 void *osMoreCore(int size)
5003 {
5004 void *ptr = 0;
5005 static void *sbrk_top = 0;
5006
5007 if (size > 0)
5008 {
5009 if (size < MINIMUM_MORECORE_SIZE)
5010 size = MINIMUM_MORECORE_SIZE;
5011 if (CurrentExecutionLevel() == kTaskLevel)
5012 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
5013 if (ptr == 0)
5014 {
5015 return (void *) MORECORE_FAILURE;
5016 }
5017 // save ptrs so they can be freed during cleanup
5018 our_os_pools[next_os_pool] = ptr;
5019 next_os_pool++;
5020 ptr = (void *) ((((unsigned long) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
5021 sbrk_top = (char *) ptr + size;
5022 return ptr;
5023 }
5024 else if (size < 0)
5025 {
5026 // we don't currently support shrink behavior
5027 return (void *) MORECORE_FAILURE;
5028 }
5029 else
5030 {
5031 return sbrk_top;
5032 }
5033 }
5034
5035 // cleanup any allocated memory pools
5036 // called as last thing before shutting down driver
5037
5038 void osCleanupMem(void)
5039 {
5040 void **ptr;
5041
5042 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
5043 if (*ptr)
5044 {
5045 PoolDeallocate(*ptr);
5046 * ptr = 0;
5047 }
5048 }
5049
5050 */
5051
5052
5053/* Helper code. */
5054
5055extern char **__libc_argv attribute_hidden;
5056
5057static void
5058malloc_printerr (int action, const char *str, void *ptr, mstate ar_ptr)
5059{
5060 /* Avoid using this arena in future. We do not attempt to synchronize this
5061 with anything else because we minimally want to ensure that __libc_message
5062 gets its resources safely without stumbling on the current corruption. */
5063 if (ar_ptr)
5064 set_arena_corrupt (ar_ptr);
5065
5066 if ((action & 5) == 5)
5067 __libc_message (action & 2, "%s\n", str);
5068 else if (action & 1)
5069 {
5070 char buf[2 * sizeof (uintptr_t) + 1];
5071
5072 buf[sizeof (buf) - 1] = '\0';
5073 char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0);
5074 while (cp > buf)
5075 *--cp = '0';
5076
5077 __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n",
5078 __libc_argv[0] ? : "<unknown>", str, cp);
5079 }
5080 else if (action & 2)
5081 abort ();
5082}
5083
5084/* We need a wrapper function for one of the additions of POSIX. */
5085int
5086__posix_memalign (void **memptr, size_t alignment, size_t size)
5087{
5088 void *mem;
5089
5090 /* Test whether the SIZE argument is valid. It must be a power of
5091 two multiple of sizeof (void *). */
5092 if (alignment % sizeof (void *) != 0
5093 || !powerof2 (alignment / sizeof (void *))
5094 || alignment == 0)
5095 return EINVAL;
5096
5097
5098 void *address = RETURN_ADDRESS (0);
5099 mem = _mid_memalign (alignment, size, address);
5100
5101 if (mem != NULL)
5102 {
5103 *memptr = mem;
5104 return 0;
5105 }
5106
5107 return ENOMEM;
5108}
5109weak_alias (__posix_memalign, posix_memalign)
5110
5111
5112int
5113__malloc_info (int options, FILE *fp)
5114{
5115 /* For now, at least. */
5116 if (options != 0)
5117 return EINVAL;
5118
5119 int n = 0;
5120 size_t total_nblocks = 0;
5121 size_t total_nfastblocks = 0;
5122 size_t total_avail = 0;
5123 size_t total_fastavail = 0;
5124 size_t total_system = 0;
5125 size_t total_max_system = 0;
5126 size_t total_aspace = 0;
5127 size_t total_aspace_mprotect = 0;
5128
5129
5130
5131 if (__malloc_initialized < 0)
5132 ptmalloc_init ();
5133
5134 fputs ("<malloc version=\"1\">\n", fp);
5135
5136 /* Iterate over all arenas currently in use. */
5137 mstate ar_ptr = &main_arena;
5138 do
5139 {
5140 fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++);
5141
5142 size_t nblocks = 0;
5143 size_t nfastblocks = 0;
5144 size_t avail = 0;
5145 size_t fastavail = 0;
5146 struct
5147 {
5148 size_t from;
5149 size_t to;
5150 size_t total;
5151 size_t count;
5152 } sizes[NFASTBINS + NBINS - 1];
5153#define nsizes (sizeof (sizes) / sizeof (sizes[0]))
5154
5155 __libc_lock_lock (ar_ptr->mutex);
5156
5157 for (size_t i = 0; i < NFASTBINS; ++i)
5158 {
5159 mchunkptr p = fastbin (ar_ptr, i);
5160 if (p != NULL)
5161 {
5162 size_t nthissize = 0;
5163 size_t thissize = chunksize (p);
5164
5165 while (p != NULL)
5166 {
5167 ++nthissize;
5168 p = p->fd;
5169 }
5170
5171 fastavail += nthissize * thissize;
5172 nfastblocks += nthissize;
5173 sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1);
5174 sizes[i].to = thissize;
5175 sizes[i].count = nthissize;
5176 }
5177 else
5178 sizes[i].from = sizes[i].to = sizes[i].count = 0;
5179
5180 sizes[i].total = sizes[i].count * sizes[i].to;
5181 }
5182
5183
5184 mbinptr bin;
5185 struct malloc_chunk *r;
5186
5187 for (size_t i = 1; i < NBINS; ++i)
5188 {
5189 bin = bin_at (ar_ptr, i);
5190 r = bin->fd;
5191 sizes[NFASTBINS - 1 + i].from = ~((size_t) 0);
5192 sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total
5193 = sizes[NFASTBINS - 1 + i].count = 0;
5194
5195 if (r != NULL)
5196 while (r != bin)
5197 {
5198 size_t r_size = chunksize_nomask (r);
5199 ++sizes[NFASTBINS - 1 + i].count;
5200 sizes[NFASTBINS - 1 + i].total += r_size;
5201 sizes[NFASTBINS - 1 + i].from
5202 = MIN (sizes[NFASTBINS - 1 + i].from, r_size);
5203 sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to,
5204 r_size);
5205
5206 r = r->fd;
5207 }
5208
5209 if (sizes[NFASTBINS - 1 + i].count == 0)
5210 sizes[NFASTBINS - 1 + i].from = 0;
5211 nblocks += sizes[NFASTBINS - 1 + i].count;
5212 avail += sizes[NFASTBINS - 1 + i].total;
5213 }
5214
5215 __libc_lock_unlock (ar_ptr->mutex);
5216
5217 total_nfastblocks += nfastblocks;
5218 total_fastavail += fastavail;
5219
5220 total_nblocks += nblocks;
5221 total_avail += avail;
5222
5223 for (size_t i = 0; i < nsizes; ++i)
5224 if (sizes[i].count != 0 && i != NFASTBINS)
5225 fprintf (fp, " \
5226 <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5227 sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count);
5228
5229 if (sizes[NFASTBINS].count != 0)
5230 fprintf (fp, "\
5231 <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n",
5232 sizes[NFASTBINS].from, sizes[NFASTBINS].to,
5233 sizes[NFASTBINS].total, sizes[NFASTBINS].count);
5234
5235 total_system += ar_ptr->system_mem;
5236 total_max_system += ar_ptr->max_system_mem;
5237
5238 fprintf (fp,
5239 "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5240 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5241 "<system type=\"current\" size=\"%zu\"/>\n"
5242 "<system type=\"max\" size=\"%zu\"/>\n",
5243 nfastblocks, fastavail, nblocks, avail,
5244 ar_ptr->system_mem, ar_ptr->max_system_mem);
5245
5246 if (ar_ptr != &main_arena)
5247 {
5248 heap_info *heap = heap_for_ptr (top (ar_ptr));
5249 fprintf (fp,
5250 "<aspace type=\"total\" size=\"%zu\"/>\n"
5251 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5252 heap->size, heap->mprotect_size);
5253 total_aspace += heap->size;
5254 total_aspace_mprotect += heap->mprotect_size;
5255 }
5256 else
5257 {
5258 fprintf (fp,
5259 "<aspace type=\"total\" size=\"%zu\"/>\n"
5260 "<aspace type=\"mprotect\" size=\"%zu\"/>\n",
5261 ar_ptr->system_mem, ar_ptr->system_mem);
5262 total_aspace += ar_ptr->system_mem;
5263 total_aspace_mprotect += ar_ptr->system_mem;
5264 }
5265
5266 fputs ("</heap>\n", fp);
5267 ar_ptr = ar_ptr->next;
5268 }
5269 while (ar_ptr != &main_arena);
5270
5271 fprintf (fp,
5272 "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n"
5273 "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n"
5274 "<total type=\"mmap\" count=\"%d\" size=\"%zu\"/>\n"
5275 "<system type=\"current\" size=\"%zu\"/>\n"
5276 "<system type=\"max\" size=\"%zu\"/>\n"
5277 "<aspace type=\"total\" size=\"%zu\"/>\n"
5278 "<aspace type=\"mprotect\" size=\"%zu\"/>\n"
5279 "</malloc>\n",
5280 total_nfastblocks, total_fastavail, total_nblocks, total_avail,
5281 mp_.n_mmaps, mp_.mmapped_mem,
5282 total_system, total_max_system,
5283 total_aspace, total_aspace_mprotect);
5284
5285 return 0;
5286}
5287weak_alias (__malloc_info, malloc_info)
5288
5289
5290strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5291strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5292strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5293strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5294strong_alias (__libc_memalign, __memalign)
5295weak_alias (__libc_memalign, memalign)
5296strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5297strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5298strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5299strong_alias (__libc_mallinfo, __mallinfo)
5300weak_alias (__libc_mallinfo, mallinfo)
5301strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5302
5303weak_alias (__malloc_stats, malloc_stats)
5304weak_alias (__malloc_usable_size, malloc_usable_size)
5305weak_alias (__malloc_trim, malloc_trim)
5306
5307
5308/* ------------------------------------------------------------
5309 History:
5310
5311 [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc]
5312
5313 */
5314/*
5315 * Local variables:
5316 * c-basic-offset: 2
5317 * End:
5318 */
5319