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