diff options
Diffstat (limited to 'malloc/malloc.c')
-rw-r--r-- | malloc/malloc.c | 4283 |
1 files changed, 2214 insertions, 2069 deletions
diff --git a/malloc/malloc.c b/malloc/malloc.c index 63d1d152ab..813e94eea3 100644 --- a/malloc/malloc.c +++ b/malloc/malloc.c @@ -353,10 +353,10 @@ __malloc_assert (const char *assertion, const char *file, unsigned int line, malloc_set_state than will returning blocks not adequately aligned for long double objects under -mlong-double-128. */ -# define MALLOC_ALIGNMENT (2 * SIZE_SZ < __alignof__ (long double) \ - ? __alignof__ (long double) : 2 * SIZE_SZ) +# define MALLOC_ALIGNMENT (2 *SIZE_SZ < __alignof__ (long double) \ + ? __alignof__ (long double) : 2 *SIZE_SZ) # else -# define MALLOC_ALIGNMENT (2 * SIZE_SZ) +# define MALLOC_ALIGNMENT (2 *SIZE_SZ) # endif #endif @@ -463,10 +463,10 @@ void *(*__morecore)(ptrdiff_t) = __default_morecore; some systems, if the application first decrements and then increments the break value, the contents of the reallocated space are unspecified. -*/ + */ #ifndef MORECORE_CLEARS -#define MORECORE_CLEARS 1 +# define MORECORE_CLEARS 1 #endif @@ -1232,11 +1232,11 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Check if a request is so large that it would wrap around zero when padded and aligned. To simplify some other code, the bound is made low enough so that adding MINSIZE will also not wrap around zero. -*/ + */ #define REQUEST_OUT_OF_RANGE(req) \ - ((unsigned long)(req) >= \ - (unsigned long)(INTERNAL_SIZE_T)(-2 * MINSIZE)) + ((unsigned long) (req) >= \ + (unsigned long) (INTERNAL_SIZE_T) (-2 * MINSIZE)) /* pad request bytes into a usable size -- internal version */ @@ -1248,15 +1248,15 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /* Same, except also perform argument check */ #define checked_request2size(req, sz) \ - if (REQUEST_OUT_OF_RANGE(req)) { \ - __set_errno (ENOMEM); \ - return 0; \ - } \ - (sz) = request2size(req); + if (REQUEST_OUT_OF_RANGE (req)) { \ + __set_errno (ENOMEM); \ + return 0; \ + } \ + (sz) = request2size (req); /* - --------------- Physical chunk operations --------------- -*/ + --------------- Physical chunk operations --------------- + */ /* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */ @@ -1283,49 +1283,49 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /* - Bits to mask off when extracting size + Bits to mask off when extracting size - Note: IS_MMAPPED is intentionally not masked off from size field in - macros for which mmapped chunks should never be seen. This should - cause helpful core dumps to occur if it is tried by accident by - people extending or adapting this malloc. -*/ -#define SIZE_BITS (PREV_INUSE|IS_MMAPPED|NON_MAIN_ARENA) + Note: IS_MMAPPED is intentionally not masked off from size field in + macros for which mmapped chunks should never be seen. This should + cause helpful core dumps to occur if it is tried by accident by + people extending or adapting this malloc. + */ +#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) /* Get size, ignoring use bits */ #define chunksize(p) ((p)->size & ~(SIZE_BITS)) /* Ptr to next physical malloc_chunk. */ -#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~SIZE_BITS) )) +#define next_chunk(p) ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS))) /* Ptr to previous physical malloc_chunk */ -#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) )) +#define prev_chunk(p) ((mchunkptr) (((char *) (p)) - ((p)->prev_size))) /* Treat space at ptr + offset as a chunk */ -#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s))) /* extract p's inuse bit */ -#define inuse(p)\ -((((mchunkptr)(((char*)(p))+((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE) +#define inuse(p) \ + ((((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size) & PREV_INUSE) /* set/clear chunk as being inuse without otherwise disturbing */ -#define set_inuse(p)\ -((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE +#define set_inuse(p) \ + ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size |= PREV_INUSE -#define clear_inuse(p)\ -((mchunkptr)(((char*)(p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE) +#define clear_inuse(p) \ + ((mchunkptr) (((char *) (p)) + ((p)->size & ~SIZE_BITS)))->size &= ~(PREV_INUSE) /* check/set/clear inuse bits in known places */ -#define inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE) +#define inuse_bit_at_offset(p, s) \ + (((mchunkptr) (((char *) (p)) + (s)))->size & PREV_INUSE) -#define set_inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE) +#define set_inuse_bit_at_offset(p, s) \ + (((mchunkptr) (((char *) (p)) + (s)))->size |= PREV_INUSE) -#define clear_inuse_bit_at_offset(p, s)\ - (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE)) +#define clear_inuse_bit_at_offset(p, s) \ + (((mchunkptr) (((char *) (p)) + (s)))->size &= ~(PREV_INUSE)) /* Set size at head, without disturbing its use bit */ @@ -1335,26 +1335,26 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ #define set_head(p, s) ((p)->size = (s)) /* Set size at footer (only when chunk is not in use) */ -#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s)) +#define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->prev_size = (s)) /* - -------------------- Internal data structures -------------------- + -------------------- Internal data structures -------------------- All internal state is held in an instance of malloc_state defined below. There are no other static variables, except in two optional cases: - * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above. - * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor + * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above. + * If mmap doesn't support MAP_ANONYMOUS, a dummy file descriptor for mmap. Beware of lots of tricks that minimize the total bookkeeping space requirements. The result is a little over 1K bytes (for 4byte pointers and size_t.) -*/ + */ /* - Bins + Bins An array of bin headers for free chunks. Each bin is doubly linked. The bins are approximately proportionally (log) spaced. @@ -1387,17 +1387,17 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ But to conserve space and improve locality, we allocate only the fd/bk pointers of bins, and then use repositioning tricks to treat these as the fields of a malloc_chunk*. -*/ + */ -typedef struct malloc_chunk* mbinptr; +typedef struct malloc_chunk *mbinptr; /* addressing -- note that bin_at(0) does not exist */ #define bin_at(m, i) \ (mbinptr) (((char *) &((m)->bins[((i) - 1) * 2])) \ - - offsetof (struct malloc_chunk, fd)) + - offsetof (struct malloc_chunk, fd)) /* analog of ++bin */ -#define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1))) +#define next_bin(b) ((mbinptr) ((char *) (b) + (sizeof (mchunkptr) << 1))) /* Reminders about list directionality within bins */ #define first(b) ((b)->fd) @@ -1405,36 +1405,36 @@ typedef struct malloc_chunk* mbinptr; /* Take a chunk off a bin list */ #define unlink(P, BK, FD) { \ - FD = P->fd; \ - BK = P->bk; \ - if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ - malloc_printerr (check_action, "corrupted double-linked list", P); \ - else { \ - FD->bk = BK; \ - BK->fd = FD; \ - if (!in_smallbin_range (P->size) \ - && __builtin_expect (P->fd_nextsize != NULL, 0)) { \ - assert (P->fd_nextsize->bk_nextsize == P); \ - assert (P->bk_nextsize->fd_nextsize == P); \ - if (FD->fd_nextsize == NULL) { \ - if (P->fd_nextsize == P) \ - FD->fd_nextsize = FD->bk_nextsize = FD; \ - else { \ - FD->fd_nextsize = P->fd_nextsize; \ - FD->bk_nextsize = P->bk_nextsize; \ - P->fd_nextsize->bk_nextsize = FD; \ - P->bk_nextsize->fd_nextsize = FD; \ - } \ - } else { \ - P->fd_nextsize->bk_nextsize = P->bk_nextsize; \ - P->bk_nextsize->fd_nextsize = P->fd_nextsize; \ - } \ - } \ - } \ + FD = P->fd; \ + BK = P->bk; \ + if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ + malloc_printerr (check_action, "corrupted double-linked list", P); \ + else { \ + FD->bk = BK; \ + BK->fd = FD; \ + if (!in_smallbin_range (P->size) \ + && __builtin_expect (P->fd_nextsize != NULL, 0)) { \ + assert (P->fd_nextsize->bk_nextsize == P); \ + assert (P->bk_nextsize->fd_nextsize == P); \ + if (FD->fd_nextsize == NULL) { \ + if (P->fd_nextsize == P) \ + FD->fd_nextsize = FD->bk_nextsize = FD; \ + else { \ + FD->fd_nextsize = P->fd_nextsize; \ + FD->bk_nextsize = P->bk_nextsize; \ + P->fd_nextsize->bk_nextsize = FD; \ + P->bk_nextsize->fd_nextsize = FD; \ + } \ + } else { \ + P->fd_nextsize->bk_nextsize = P->bk_nextsize; \ + P->bk_nextsize->fd_nextsize = P->fd_nextsize; \ + } \ + } \ + } \ } /* - Indexing + Indexing Bins for sizes < 512 bytes contain chunks of all the same size, spaced 8 bytes apart. Larger bins are approximately logarithmically spaced: @@ -1455,7 +1455,7 @@ typedef struct malloc_chunk* mbinptr; Bin 0 does not exist. Bin 1 is the unordered list; if that would be a valid chunk size the small bins are bumped up one. -*/ + */ #define NBINS 128 #define NSMALLBINS 64 @@ -1464,38 +1464,38 @@ typedef struct malloc_chunk* mbinptr; #define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH) #define in_smallbin_range(sz) \ - ((unsigned long)(sz) < (unsigned long)MIN_LARGE_SIZE) + ((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE) #define smallbin_index(sz) \ - ((SMALLBIN_WIDTH == 16 ? (((unsigned)(sz)) >> 4) : (((unsigned)(sz)) >> 3)) \ + ((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\ + SMALLBIN_CORRECTION) #define largebin_index_32(sz) \ -(((((unsigned long)(sz)) >> 6) <= 38)? 56 + (((unsigned long)(sz)) >> 6): \ - ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \ - ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \ - ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \ - ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \ - 126) + (((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\ + ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ + ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ + ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ + ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ + 126) #define largebin_index_32_big(sz) \ -(((((unsigned long)(sz)) >> 6) <= 45)? 49 + (((unsigned long)(sz)) >> 6): \ - ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \ - ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \ - ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \ - ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \ - 126) + (((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\ + ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ + ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ + ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ + ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ + 126) // XXX It remains to be seen whether it is good to keep the widths of // XXX the buckets the same or whether it should be scaled by a factor // XXX of two as well. #define largebin_index_64(sz) \ -(((((unsigned long)(sz)) >> 6) <= 48)? 48 + (((unsigned long)(sz)) >> 6): \ - ((((unsigned long)(sz)) >> 9) <= 20)? 91 + (((unsigned long)(sz)) >> 9): \ - ((((unsigned long)(sz)) >> 12) <= 10)? 110 + (((unsigned long)(sz)) >> 12): \ - ((((unsigned long)(sz)) >> 15) <= 4)? 119 + (((unsigned long)(sz)) >> 15): \ - ((((unsigned long)(sz)) >> 18) <= 2)? 124 + (((unsigned long)(sz)) >> 18): \ - 126) + (((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\ + ((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\ + ((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\ + ((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\ + ((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\ + 126) #define largebin_index(sz) \ (SIZE_SZ == 8 ? largebin_index_64 (sz) \ @@ -1503,11 +1503,11 @@ typedef struct malloc_chunk* mbinptr; : largebin_index_32 (sz)) #define bin_index(sz) \ - ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz)) + ((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz)) /* - Unsorted chunks + Unsorted chunks All remainders from chunk splits, as well as all returned chunks, are first placed in the "unsorted" bin. They are then placed @@ -1518,13 +1518,13 @@ typedef struct malloc_chunk* mbinptr; The NON_MAIN_ARENA flag is never set for unsorted chunks, so it does not have to be taken into account in size comparisons. -*/ + */ /* The otherwise unindexable 1-bin is used to hold unsorted chunks. */ -#define unsorted_chunks(M) (bin_at(M, 1)) +#define unsorted_chunks(M) (bin_at (M, 1)) /* - Top + Top The top-most available chunk (i.e., the one bordering the end of available memory) is treated specially. It is never included in @@ -1539,13 +1539,13 @@ typedef struct malloc_chunk* mbinptr; interval between initialization and the first call to sysmalloc. (This is somewhat delicate, since it relies on the 2 preceding words to be zero during this interval as well.) -*/ + */ /* Conveniently, the unsorted bin can be used as dummy top on first call */ -#define initial_top(M) (unsorted_chunks(M)) +#define initial_top(M) (unsorted_chunks (M)) /* - Binmap + Binmap To help compensate for the large number of bins, a one-level index structure is used for bin-by-bin searching. `binmap' is a @@ -1553,7 +1553,7 @@ typedef struct malloc_chunk* mbinptr; be skipped over during during traversals. The bits are NOT always cleared as soon as bins are empty, but instead only when they are noticed to be empty during traversal in malloc. -*/ + */ /* Conservatively use 32 bits per map word, even if on 64bit system */ #define BINMAPSHIFT 5 @@ -1561,14 +1561,14 @@ typedef struct malloc_chunk* mbinptr; #define BINMAPSIZE (NBINS / BITSPERMAP) #define idx2block(i) ((i) >> BINMAPSHIFT) -#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1)))) +#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1)))) -#define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i)) -#define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i))) -#define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i)) +#define mark_bin(m, i) ((m)->binmap[idx2block (i)] |= idx2bit (i)) +#define unmark_bin(m, i) ((m)->binmap[idx2block (i)] &= ~(idx2bit (i))) +#define get_binmap(m, i) ((m)->binmap[idx2block (i)] & idx2bit (i)) /* - Fastbins + Fastbins An array of lists holding recently freed small chunks. Fastbins are not doubly linked. It is faster to single-link them, and @@ -1582,69 +1582,69 @@ typedef struct malloc_chunk* mbinptr; be consolidated with other free chunks. malloc_consolidate releases all chunks in fastbins and consolidates them with other free chunks. -*/ + */ -typedef struct malloc_chunk* mfastbinptr; +typedef struct malloc_chunk *mfastbinptr; #define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx]) /* offset 2 to use otherwise unindexable first 2 bins */ #define fastbin_index(sz) \ - ((((unsigned int)(sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) + ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) /* The maximum fastbin request size we support */ #define MAX_FAST_SIZE (80 * SIZE_SZ / 4) -#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1) +#define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1) /* - FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free() - that triggers automatic consolidation of possibly-surrounding - fastbin chunks. This is a heuristic, so the exact value should not - matter too much. It is defined at half the default trim threshold as a - compromise heuristic to only attempt consolidation if it is likely - to lead to trimming. However, it is not dynamically tunable, since - consolidation reduces fragmentation surrounding large chunks even - if trimming is not used. -*/ + FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free() + that triggers automatic consolidation of possibly-surrounding + fastbin chunks. This is a heuristic, so the exact value should not + matter too much. It is defined at half the default trim threshold as a + compromise heuristic to only attempt consolidation if it is likely + to lead to trimming. However, it is not dynamically tunable, since + consolidation reduces fragmentation surrounding large chunks even + if trimming is not used. + */ #define FASTBIN_CONSOLIDATION_THRESHOLD (65536UL) /* - Since the lowest 2 bits in max_fast don't matter in size comparisons, - they are used as flags. -*/ + Since the lowest 2 bits in max_fast don't matter in size comparisons, + they are used as flags. + */ /* - FASTCHUNKS_BIT held in max_fast indicates that there are probably - some fastbin chunks. It is set true on entering a chunk into any - fastbin, and cleared only in malloc_consolidate. + FASTCHUNKS_BIT held in max_fast indicates that there are probably + some fastbin chunks. It is set true on entering a chunk into any + fastbin, and cleared only in malloc_consolidate. - The truth value is inverted so that have_fastchunks will be true - upon startup (since statics are zero-filled), simplifying - initialization checks. -*/ + The truth value is inverted so that have_fastchunks will be true + upon startup (since statics are zero-filled), simplifying + initialization checks. + */ #define FASTCHUNKS_BIT (1U) -#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0) +#define have_fastchunks(M) (((M)->flags & FASTCHUNKS_BIT) == 0) #define clear_fastchunks(M) catomic_or (&(M)->flags, FASTCHUNKS_BIT) #define set_fastchunks(M) catomic_and (&(M)->flags, ~FASTCHUNKS_BIT) /* - NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous - regions. Otherwise, contiguity is exploited in merging together, - when possible, results from consecutive MORECORE calls. + NONCONTIGUOUS_BIT indicates that MORECORE does not return contiguous + regions. Otherwise, contiguity is exploited in merging together, + when possible, results from consecutive MORECORE calls. - The initial value comes from MORECORE_CONTIGUOUS, but is - changed dynamically if mmap is ever used as an sbrk substitute. -*/ + The initial value comes from MORECORE_CONTIGUOUS, but is + changed dynamically if mmap is ever used as an sbrk substitute. + */ #define NONCONTIGUOUS_BIT (2U) -#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0) -#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0) -#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT) +#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0) +#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0) +#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT) #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT) /* @@ -1652,19 +1652,20 @@ typedef struct malloc_chunk* mfastbinptr; Use impossibly small value if 0. Precondition: there are no existing fastbin chunks. Setting the value clears fastchunk bit but preserves noncontiguous bit. -*/ + */ #define set_max_fast(s) \ global_max_fast = (((s) == 0) \ - ? SMALLBIN_WIDTH: ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK)) + ? SMALLBIN_WIDTH : ((s + SIZE_SZ) & ~MALLOC_ALIGN_MASK)) #define get_max_fast() global_max_fast /* ----------- Internal state representation and initialization ----------- -*/ + */ -struct malloc_state { +struct malloc_state +{ /* Serialize access. */ mutex_t mutex; @@ -1677,19 +1678,19 @@ struct malloc_state { #endif /* Fastbins */ - mfastbinptr fastbinsY[NFASTBINS]; + mfastbinptr fastbinsY[NFASTBINS]; /* Base of the topmost chunk -- not otherwise kept in a bin */ - mchunkptr top; + mchunkptr top; /* The remainder from the most recent split of a small request */ - mchunkptr last_remainder; + mchunkptr last_remainder; /* Normal bins packed as described above */ - mchunkptr bins[NBINS * 2 - 2]; + mchunkptr bins[NBINS * 2 - 2]; /* Bitmap of bins */ - unsigned int binmap[BINMAPSIZE]; + unsigned int binmap[BINMAPSIZE]; /* Linked list */ struct malloc_state *next; @@ -1702,32 +1703,33 @@ struct malloc_state { INTERNAL_SIZE_T max_system_mem; }; -struct malloc_par { +struct malloc_par +{ /* Tunable parameters */ - unsigned long trim_threshold; - INTERNAL_SIZE_T top_pad; - INTERNAL_SIZE_T mmap_threshold; - INTERNAL_SIZE_T arena_test; - INTERNAL_SIZE_T arena_max; + unsigned long trim_threshold; + INTERNAL_SIZE_T top_pad; + INTERNAL_SIZE_T mmap_threshold; + INTERNAL_SIZE_T arena_test; + INTERNAL_SIZE_T arena_max; /* Memory map support */ - int n_mmaps; - int n_mmaps_max; - int max_n_mmaps; + int n_mmaps; + int n_mmaps_max; + int max_n_mmaps; /* the mmap_threshold is dynamic, until the user sets it manually, at which point we need to disable any dynamic behavior. */ - int no_dyn_threshold; + int no_dyn_threshold; /* Statistics */ - INTERNAL_SIZE_T mmapped_mem; + INTERNAL_SIZE_T mmapped_mem; /*INTERNAL_SIZE_T sbrked_mem;*/ /*INTERNAL_SIZE_T max_sbrked_mem;*/ - INTERNAL_SIZE_T max_mmapped_mem; - INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */ + INTERNAL_SIZE_T max_mmapped_mem; + INTERNAL_SIZE_T max_total_mem; /* only kept for NO_THREADS */ /* First address handed out by MORECORE/sbrk. */ - char* sbrk_base; + char *sbrk_base; }; /* There are several instances of this struct ("arenas") in this @@ -1737,22 +1739,22 @@ struct malloc_par { is initialized to all zeroes (as is true of C statics). */ static struct malloc_state main_arena = - { - .mutex = MUTEX_INITIALIZER, - .next = &main_arena - }; +{ + .mutex = MUTEX_INITIALIZER, + .next = &main_arena +}; /* There is only one instance of the malloc parameters. */ static struct malloc_par mp_ = - { - .top_pad = DEFAULT_TOP_PAD, - .n_mmaps_max = DEFAULT_MMAP_MAX, - .mmap_threshold = DEFAULT_MMAP_THRESHOLD, - .trim_threshold = DEFAULT_TRIM_THRESHOLD, -# define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8)) - .arena_test = NARENAS_FROM_NCORES (1) - }; +{ + .top_pad = DEFAULT_TOP_PAD, + .n_mmaps_max = DEFAULT_MMAP_MAX, + .mmap_threshold = DEFAULT_MMAP_THRESHOLD, + .trim_threshold = DEFAULT_TRIM_THRESHOLD, +#define NARENAS_FROM_NCORES(n) ((n) * (sizeof (long) == 4 ? 2 : 8)) + .arena_test = NARENAS_FROM_NCORES (1) +}; /* Non public mallopt parameters. */ @@ -1764,44 +1766,46 @@ static struct malloc_par mp_ = static INTERNAL_SIZE_T global_max_fast; /* - Initialize a malloc_state struct. + Initialize a malloc_state struct. - This is called only from within malloc_consolidate, which needs - be called in the same contexts anyway. It is never called directly - outside of malloc_consolidate because some optimizing compilers try - to inline it at all call points, which turns out not to be an - optimization at all. (Inlining it in malloc_consolidate is fine though.) -*/ + This is called only from within malloc_consolidate, which needs + be called in the same contexts anyway. It is never called directly + outside of malloc_consolidate because some optimizing compilers try + to inline it at all call points, which turns out not to be an + optimization at all. (Inlining it in malloc_consolidate is fine though.) + */ -static void malloc_init_state(mstate av) +static void +malloc_init_state (mstate av) { - int i; + int i; mbinptr bin; /* Establish circular links for normal bins */ - for (i = 1; i < NBINS; ++i) { - bin = bin_at(av,i); - bin->fd = bin->bk = bin; - } + for (i = 1; i < NBINS; ++i) + { + bin = bin_at (av, i); + bin->fd = bin->bk = bin; + } #if MORECORE_CONTIGUOUS if (av != &main_arena) #endif - set_noncontiguous(av); + set_noncontiguous (av); if (av == &main_arena) - set_max_fast(DEFAULT_MXFAST); + set_max_fast (DEFAULT_MXFAST); av->flags |= FASTCHUNKS_BIT; - av->top = initial_top(av); + av->top = initial_top (av); } /* Other internal utilities operating on mstates -*/ + */ -static void* sysmalloc(INTERNAL_SIZE_T, mstate); -static int systrim(size_t, mstate); -static void malloc_consolidate(mstate); +static void *sysmalloc (INTERNAL_SIZE_T, mstate); +static int systrim (size_t, mstate); +static void malloc_consolidate (mstate); /* -------------- Early definitions for debugging hooks ---------------- */ @@ -1815,31 +1819,31 @@ static void malloc_consolidate(mstate); #endif /* Forward declarations. */ -static void* malloc_hook_ini (size_t sz, - const void *caller) __THROW; -static void* realloc_hook_ini (void* ptr, size_t sz, - const void *caller) __THROW; -static void* memalign_hook_ini (size_t alignment, size_t sz, - const void *caller) __THROW; +static void *malloc_hook_ini (size_t sz, + const void *caller) __THROW; +static void *realloc_hook_ini (void *ptr, size_t sz, + const void *caller) __THROW; +static void *memalign_hook_ini (size_t alignment, size_t sz, + const void *caller) __THROW; void weak_variable (*__malloc_initialize_hook) (void) = NULL; void weak_variable (*__free_hook) (void *__ptr, - const void *) = NULL; + const void *) = NULL; void *weak_variable (*__malloc_hook) - (size_t __size, const void *) = malloc_hook_ini; + (size_t __size, const void *) = malloc_hook_ini; void *weak_variable (*__realloc_hook) - (void *__ptr, size_t __size, const void *) - = realloc_hook_ini; + (void *__ptr, size_t __size, const void *) + = realloc_hook_ini; void *weak_variable (*__memalign_hook) - (size_t __alignment, size_t __size, const void *) - = memalign_hook_ini; + (size_t __alignment, size_t __size, const void *) + = memalign_hook_ini; void weak_variable (*__after_morecore_hook) (void) = NULL; /* ---------------- Error behavior ------------------------------------ */ #ifndef DEFAULT_CHECK_ACTION -#define DEFAULT_CHECK_ACTION 3 +# define DEFAULT_CHECK_ACTION 3 #endif static int check_action = DEFAULT_CHECK_ACTION; @@ -1871,207 +1875,220 @@ free_perturb (char *p, size_t n) #include "arena.c" /* - Debugging support + Debugging support - These routines make a number of assertions about the states - of data structures that should be true at all times. If any - are not true, it's very likely that a user program has somehow - trashed memory. (It's also possible that there is a coding error - in malloc. In which case, please report it!) -*/ + These routines make a number of assertions about the states + of data structures that should be true at all times. If any + are not true, it's very likely that a user program has somehow + trashed memory. (It's also possible that there is a coding error + in malloc. In which case, please report it!) + */ -#if ! MALLOC_DEBUG +#if !MALLOC_DEBUG -#define check_chunk(A,P) -#define check_free_chunk(A,P) -#define check_inuse_chunk(A,P) -#define check_remalloced_chunk(A,P,N) -#define check_malloced_chunk(A,P,N) -#define check_malloc_state(A) +# define check_chunk(A, P) +# define check_free_chunk(A, P) +# define check_inuse_chunk(A, P) +# define check_remalloced_chunk(A, P, N) +# define check_malloced_chunk(A, P, N) +# define check_malloc_state(A) #else -#define check_chunk(A,P) do_check_chunk(A,P) -#define check_free_chunk(A,P) do_check_free_chunk(A,P) -#define check_inuse_chunk(A,P) do_check_inuse_chunk(A,P) -#define check_remalloced_chunk(A,P,N) do_check_remalloced_chunk(A,P,N) -#define check_malloced_chunk(A,P,N) do_check_malloced_chunk(A,P,N) -#define check_malloc_state(A) do_check_malloc_state(A) +# define check_chunk(A, P) do_check_chunk (A, P) +# define check_free_chunk(A, P) do_check_free_chunk (A, P) +# define check_inuse_chunk(A, P) do_check_inuse_chunk (A, P) +# define check_remalloced_chunk(A, P, N) do_check_remalloced_chunk (A, P, N) +# define check_malloced_chunk(A, P, N) do_check_malloced_chunk (A, P, N) +# define check_malloc_state(A) do_check_malloc_state (A) /* - Properties of all chunks -*/ + Properties of all chunks + */ -static void do_check_chunk(mstate av, mchunkptr p) +static void +do_check_chunk (mstate av, mchunkptr p) { - unsigned long sz = chunksize(p); + unsigned long sz = chunksize (p); /* min and max possible addresses assuming contiguous allocation */ - char* max_address = (char*)(av->top) + chunksize(av->top); - char* min_address = max_address - av->system_mem; + char *max_address = (char *) (av->top) + chunksize (av->top); + char *min_address = max_address - av->system_mem; - if (!chunk_is_mmapped(p)) { - - /* Has legal address ... */ - if (p != av->top) { - if (contiguous(av)) { - assert(((char*)p) >= min_address); - assert(((char*)p + sz) <= ((char*)(av->top))); - } - } - else { - /* top size is always at least MINSIZE */ - assert((unsigned long)(sz) >= MINSIZE); - /* top predecessor always marked inuse */ - assert(prev_inuse(p)); + if (!chunk_is_mmapped (p)) + { + /* Has legal address ... */ + if (p != av->top) + { + if (contiguous (av)) + { + assert (((char *) p) >= min_address); + assert (((char *) p + sz) <= ((char *) (av->top))); + } + } + else + { + /* top size is always at least MINSIZE */ + assert ((unsigned long) (sz) >= MINSIZE); + /* top predecessor always marked inuse */ + assert (prev_inuse (p)); + } } - - } - else { - /* address is outside main heap */ - if (contiguous(av) && av->top != initial_top(av)) { - assert(((char*)p) < min_address || ((char*)p) >= max_address); + else + { + /* address is outside main heap */ + if (contiguous (av) && av->top != initial_top (av)) + { + assert (((char *) p) < min_address || ((char *) p) >= max_address); + } + /* chunk is page-aligned */ + assert (((p->prev_size + sz) & (GLRO (dl_pagesize) - 1)) == 0); + /* mem is aligned */ + assert (aligned_OK (chunk2mem (p))); } - /* chunk is page-aligned */ - assert(((p->prev_size + sz) & (GLRO(dl_pagesize)-1)) == 0); - /* mem is aligned */ - assert(aligned_OK(chunk2mem(p))); - } } /* - Properties of free chunks -*/ + Properties of free chunks + */ -static void do_check_free_chunk(mstate av, mchunkptr p) +static void +do_check_free_chunk (mstate av, mchunkptr p) { - INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA); - mchunkptr next = chunk_at_offset(p, sz); + INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA); + mchunkptr next = chunk_at_offset (p, sz); - do_check_chunk(av, p); + do_check_chunk (av, p); /* Chunk must claim to be free ... */ - assert(!inuse(p)); - assert (!chunk_is_mmapped(p)); + assert (!inuse (p)); + assert (!chunk_is_mmapped (p)); /* Unless a special marker, must have OK fields */ - if ((unsigned long)(sz) >= MINSIZE) - { - assert((sz & MALLOC_ALIGN_MASK) == 0); - assert(aligned_OK(chunk2mem(p))); - /* ... matching footer field */ - assert(next->prev_size == sz); - /* ... and is fully consolidated */ - assert(prev_inuse(p)); - assert (next == av->top || inuse(next)); - - /* ... and has minimally sane links */ - assert(p->fd->bk == p); - assert(p->bk->fd == p); - } + if ((unsigned long) (sz) >= MINSIZE) + { + assert ((sz & MALLOC_ALIGN_MASK) == 0); + assert (aligned_OK (chunk2mem (p))); + /* ... matching footer field */ + assert (next->prev_size == sz); + /* ... and is fully consolidated */ + assert (prev_inuse (p)); + assert (next == av->top || inuse (next)); + + /* ... and has minimally sane links */ + assert (p->fd->bk == p); + assert (p->bk->fd == p); + } else /* markers are always of size SIZE_SZ */ - assert(sz == SIZE_SZ); + assert (sz == SIZE_SZ); } /* - Properties of inuse chunks -*/ + Properties of inuse chunks + */ -static void do_check_inuse_chunk(mstate av, mchunkptr p) +static void +do_check_inuse_chunk (mstate av, mchunkptr p) { mchunkptr next; - do_check_chunk(av, p); + do_check_chunk (av, p); - if (chunk_is_mmapped(p)) + if (chunk_is_mmapped (p)) return; /* mmapped chunks have no next/prev */ /* Check whether it claims to be in use ... */ - assert(inuse(p)); + assert (inuse (p)); - next = next_chunk(p); + next = next_chunk (p); /* ... and is surrounded by OK chunks. - Since more things can be checked with free chunks than inuse ones, - if an inuse chunk borders them and debug is on, it's worth doing them. - */ - if (!prev_inuse(p)) { - /* Note that we cannot even look at prev unless it is not inuse */ - mchunkptr prv = prev_chunk(p); - assert(next_chunk(prv) == p); - do_check_free_chunk(av, prv); - } + Since more things can be checked with free chunks than inuse ones, + if an inuse chunk borders them and debug is on, it's worth doing them. + */ + if (!prev_inuse (p)) + { + /* Note that we cannot even look at prev unless it is not inuse */ + mchunkptr prv = prev_chunk (p); + assert (next_chunk (prv) == p); + do_check_free_chunk (av, prv); + } - if (next == av->top) { - assert(prev_inuse(next)); - assert(chunksize(next) >= MINSIZE); - } - else if (!inuse(next)) - do_check_free_chunk(av, next); + if (next == av->top) + { + assert (prev_inuse (next)); + assert (chunksize (next) >= MINSIZE); + } + else if (!inuse (next)) + do_check_free_chunk (av, next); } /* - Properties of chunks recycled from fastbins -*/ + Properties of chunks recycled from fastbins + */ -static void do_check_remalloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s) +static void +do_check_remalloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s) { - INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE|NON_MAIN_ARENA); + INTERNAL_SIZE_T sz = p->size & ~(PREV_INUSE | NON_MAIN_ARENA); - if (!chunk_is_mmapped(p)) { - assert(av == arena_for_chunk(p)); - if (chunk_non_main_arena(p)) - assert(av != &main_arena); - else - assert(av == &main_arena); - } + if (!chunk_is_mmapped (p)) + { + assert (av == arena_for_chunk (p)); + if (chunk_non_main_arena (p)) + assert (av != &main_arena); + else + assert (av == &main_arena); + } - do_check_inuse_chunk(av, p); + do_check_inuse_chunk (av, p); /* Legal size ... */ - assert((sz & MALLOC_ALIGN_MASK) == 0); - assert((unsigned long)(sz) >= MINSIZE); + assert ((sz & MALLOC_ALIGN_MASK) == 0); + assert ((unsigned long) (sz) >= MINSIZE); /* ... and alignment */ - assert(aligned_OK(chunk2mem(p))); + assert (aligned_OK (chunk2mem (p))); /* chunk is less than MINSIZE more than request */ - assert((long)(sz) - (long)(s) >= 0); - assert((long)(sz) - (long)(s + MINSIZE) < 0); + assert ((long) (sz) - (long) (s) >= 0); + assert ((long) (sz) - (long) (s + MINSIZE) < 0); } /* - Properties of nonrecycled chunks at the point they are malloced -*/ + Properties of nonrecycled chunks at the point they are malloced + */ -static void do_check_malloced_chunk(mstate av, mchunkptr p, INTERNAL_SIZE_T s) +static void +do_check_malloced_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T s) { /* same as recycled case ... */ - do_check_remalloced_chunk(av, p, s); + do_check_remalloced_chunk (av, p, s); /* - ... plus, must obey implementation invariant that prev_inuse is - always true of any allocated chunk; i.e., that each allocated - chunk borders either a previously allocated and still in-use - chunk, or the base of its memory arena. This is ensured - by making all allocations from the `lowest' part of any found - chunk. This does not necessarily hold however for chunks - recycled via fastbins. - */ - - assert(prev_inuse(p)); + ... plus, must obey implementation invariant that prev_inuse is + always true of any allocated chunk; i.e., that each allocated + chunk borders either a previously allocated and still in-use + chunk, or the base of its memory arena. This is ensured + by making all allocations from the `lowest' part of any found + chunk. This does not necessarily hold however for chunks + recycled via fastbins. + */ + + assert (prev_inuse (p)); } /* - Properties of malloc_state. + Properties of malloc_state. - This may be useful for debugging malloc, as well as detecting user - programmer errors that somehow write into malloc_state. + This may be useful for debugging malloc, as well as detecting user + programmer errors that somehow write into malloc_state. - If you are extending or experimenting with this malloc, you can - probably figure out how to hack this routine to print out or - display chunk addresses, sizes, bins, and other instrumentation. -*/ + If you are extending or experimenting with this malloc, you can + probably figure out how to hack this routine to print out or + display chunk addresses, sizes, bins, and other instrumentation. + */ -static void do_check_malloc_state(mstate av) +static void +do_check_malloc_state (mstate av) { int i; mchunkptr p; @@ -2083,126 +2100,132 @@ static void do_check_malloc_state(mstate av) int max_fast_bin; /* internal size_t must be no wider than pointer type */ - assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*)); + assert (sizeof (INTERNAL_SIZE_T) <= sizeof (char *)); /* alignment is a power of 2 */ - assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0); + assert ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - 1)) == 0); /* cannot run remaining checks until fully initialized */ - if (av->top == 0 || av->top == initial_top(av)) + if (av->top == 0 || av->top == initial_top (av)) return; /* pagesize is a power of 2 */ - assert((GLRO(dl_pagesize) & (GLRO(dl_pagesize)-1)) == 0); + assert ((GLRO (dl_pagesize) & (GLRO (dl_pagesize) - 1)) == 0); /* A contiguous main_arena is consistent with sbrk_base. */ - if (av == &main_arena && contiguous(av)) - assert((char*)mp_.sbrk_base + av->system_mem == - (char*)av->top + chunksize(av->top)); + if (av == &main_arena && contiguous (av)) + assert ((char *) mp_.sbrk_base + av->system_mem == + (char *) av->top + chunksize (av->top)); /* properties of fastbins */ /* max_fast is in allowed range */ - assert((get_max_fast () & ~1) <= request2size(MAX_FAST_SIZE)); - - max_fast_bin = fastbin_index(get_max_fast ()); - - for (i = 0; i < NFASTBINS; ++i) { - p = fastbin (av, i); - - /* The following test can only be performed for the main arena. - While mallopt calls malloc_consolidate to get rid of all fast - bins (especially those larger than the new maximum) this does - only happen for the main arena. Trying to do this for any - other arena would mean those arenas have to be locked and - malloc_consolidate be called for them. This is excessive. And - even if this is acceptable to somebody it still cannot solve - the problem completely since if the arena is locked a - concurrent malloc call might create a new arena which then - could use the newly invalid fast bins. */ - - /* all bins past max_fast are empty */ - if (av == &main_arena && i > max_fast_bin) - assert(p == 0); - - while (p != 0) { - /* each chunk claims to be inuse */ - do_check_inuse_chunk(av, p); - total += chunksize(p); - /* chunk belongs in this bin */ - assert(fastbin_index(chunksize(p)) == i); - p = p->fd; + assert ((get_max_fast () & ~1) <= request2size (MAX_FAST_SIZE)); + + max_fast_bin = fastbin_index (get_max_fast ()); + + for (i = 0; i < NFASTBINS; ++i) + { + p = fastbin (av, i); + + /* The following test can only be performed for the main arena. + While mallopt calls malloc_consolidate to get rid of all fast + bins (especially those larger than the new maximum) this does + only happen for the main arena. Trying to do this for any + other arena would mean those arenas have to be locked and + malloc_consolidate be called for them. This is excessive. And + even if this is acceptable to somebody it still cannot solve + the problem completely since if the arena is locked a + concurrent malloc call might create a new arena which then + could use the newly invalid fast bins. */ + + /* all bins past max_fast are empty */ + if (av == &main_arena && i > max_fast_bin) + assert (p == 0); + + while (p != 0) + { + /* each chunk claims to be inuse */ + do_check_inuse_chunk (av, p); + total += chunksize (p); + /* chunk belongs in this bin */ + assert (fastbin_index (chunksize (p)) == i); + p = p->fd; + } } - } if (total != 0) - assert(have_fastchunks(av)); - else if (!have_fastchunks(av)) - assert(total == 0); + assert (have_fastchunks (av)); + else if (!have_fastchunks (av)) + assert (total == 0); /* check normal bins */ - for (i = 1; i < NBINS; ++i) { - b = bin_at(av,i); - - /* binmap is accurate (except for bin 1 == unsorted_chunks) */ - if (i >= 2) { - unsigned int binbit = get_binmap(av,i); - int empty = last(b) == b; - if (!binbit) - assert(empty); - else if (!empty) - assert(binbit); - } - - for (p = last(b); p != b; p = p->bk) { - /* each chunk claims to be free */ - do_check_free_chunk(av, p); - size = chunksize(p); - total += size; - if (i >= 2) { - /* chunk belongs in bin */ - idx = bin_index(size); - assert(idx == i); - /* lists are sorted */ - assert(p->bk == b || - (unsigned long)chunksize(p->bk) >= (unsigned long)chunksize(p)); - - if (!in_smallbin_range(size)) - { - if (p->fd_nextsize != NULL) - { - if (p->fd_nextsize == p) - assert (p->bk_nextsize == p); - else - { - if (p->fd_nextsize == first (b)) - assert (chunksize (p) < chunksize (p->fd_nextsize)); - else - assert (chunksize (p) > chunksize (p->fd_nextsize)); - - if (p == first (b)) - assert (chunksize (p) > chunksize (p->bk_nextsize)); - else - assert (chunksize (p) < chunksize (p->bk_nextsize)); - } - } - else - assert (p->bk_nextsize == NULL); - } - } else if (!in_smallbin_range(size)) - assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL); - /* chunk is followed by a legal chain of inuse chunks */ - for (q = next_chunk(p); - (q != av->top && inuse(q) && - (unsigned long)(chunksize(q)) >= MINSIZE); - q = next_chunk(q)) - do_check_inuse_chunk(av, q); + for (i = 1; i < NBINS; ++i) + { + b = bin_at (av, i); + + /* binmap is accurate (except for bin 1 == unsorted_chunks) */ + if (i >= 2) + { + unsigned int binbit = get_binmap (av, i); + int empty = last (b) == b; + if (!binbit) + assert (empty); + else if (!empty) + assert (binbit); + } + + for (p = last (b); p != b; p = p->bk) + { + /* each chunk claims to be free */ + do_check_free_chunk (av, p); + size = chunksize (p); + total += size; + if (i >= 2) + { + /* chunk belongs in bin */ + idx = bin_index (size); + assert (idx == i); + /* lists are sorted */ + assert (p->bk == b || + (unsigned long) chunksize (p->bk) >= (unsigned long) chunksize (p)); + + if (!in_smallbin_range (size)) + { + if (p->fd_nextsize != NULL) + { + if (p->fd_nextsize == p) + assert (p->bk_nextsize == p); + else + { + if (p->fd_nextsize == first (b)) + assert (chunksize (p) < chunksize (p->fd_nextsize)); + else + assert (chunksize (p) > chunksize (p->fd_nextsize)); + + if (p == first (b)) + assert (chunksize (p) > chunksize (p->bk_nextsize)); + else + assert (chunksize (p) < chunksize (p->bk_nextsize)); + } + } + else + assert (p->bk_nextsize == NULL); + } + } + else if (!in_smallbin_range (size)) + assert (p->fd_nextsize == NULL && p->bk_nextsize == NULL); + /* chunk is followed by a legal chain of inuse chunks */ + for (q = next_chunk (p); + (q != av->top && inuse (q) && + (unsigned long) (chunksize (q)) >= MINSIZE); + q = next_chunk (q)) + do_check_inuse_chunk (av, q); + } } - } /* top chunk is OK */ - check_chunk(av, av->top); - + check_chunk (av, av->top); } #endif @@ -2214,461 +2237,482 @@ static void do_check_malloc_state(mstate av) /* ----------- Routines dealing with system allocation -------------- */ /* - sysmalloc handles malloc cases requiring more memory from the system. - On entry, it is assumed that av->top does not have enough - space to service request for nb bytes, thus requiring that av->top - be extended or replaced. -*/ + sysmalloc handles malloc cases requiring more memory from the system. + On entry, it is assumed that av->top does not have enough + space to service request for nb bytes, thus requiring that av->top + be extended or replaced. + */ -static void* sysmalloc(INTERNAL_SIZE_T nb, mstate av) +static void * +sysmalloc (INTERNAL_SIZE_T nb, mstate av) { - mchunkptr old_top; /* incoming value of av->top */ + mchunkptr old_top; /* incoming value of av->top */ INTERNAL_SIZE_T old_size; /* its size */ - char* old_end; /* its end address */ + char *old_end; /* its end address */ - long size; /* arg to first MORECORE or mmap call */ - char* brk; /* return value from MORECORE */ + long size; /* arg to first MORECORE or mmap call */ + char *brk; /* return value from MORECORE */ - long correction; /* arg to 2nd MORECORE call */ - char* snd_brk; /* 2nd return val */ + long correction; /* arg to 2nd MORECORE call */ + char *snd_brk; /* 2nd return val */ INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ - char* aligned_brk; /* aligned offset into brk */ + char *aligned_brk; /* aligned offset into brk */ - mchunkptr p; /* the allocated/returned chunk */ - mchunkptr remainder; /* remainder from allocation */ - unsigned long remainder_size; /* its size */ + mchunkptr p; /* the allocated/returned chunk */ + mchunkptr remainder; /* remainder from allocation */ + unsigned long remainder_size; /* its size */ - size_t pagemask = GLRO(dl_pagesize) - 1; - bool tried_mmap = false; + size_t pagemask = GLRO (dl_pagesize) - 1; + bool tried_mmap = false; /* - If have mmap, and the request size meets the mmap threshold, and - the system supports mmap, and there are few enough currently - allocated mmapped regions, try to directly map this request - rather than expanding top. - */ - - if ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) && - (mp_.n_mmaps < mp_.n_mmaps_max)) { - - char* mm; /* return value from mmap call*/ - - try_mmap: - /* - Round up size to nearest page. For mmapped chunks, the overhead - is one SIZE_SZ unit larger than for normal chunks, because there - is no following chunk whose prev_size field could be used. - - See the front_misalign handling below, for glibc there is no - need for further alignments unless we have have high alignment. - */ - if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) - size = (nb + SIZE_SZ + pagemask) & ~pagemask; - else - size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask; - tried_mmap = true; - - /* Don't try if size wraps around 0 */ - if ((unsigned long)(size) > (unsigned long)(nb)) { - - mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0)); - - if (mm != MAP_FAILED) { - - /* - The offset to the start of the mmapped region is stored - in the prev_size field of the chunk. This allows us to adjust - returned start address to meet alignment requirements here - and in memalign(), and still be able to compute proper - address argument for later munmap in free() and realloc(). - */ - - if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) - { - /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and - MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page - aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */ - assert (((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0); - front_misalign = 0; - } - else - front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) { - correction = MALLOC_ALIGNMENT - front_misalign; - p = (mchunkptr)(mm + correction); - p->prev_size = correction; - set_head(p, (size - correction) |IS_MMAPPED); - } - else - { - p = (mchunkptr)mm; - set_head(p, size|IS_MMAPPED); - } - - /* update statistics */ - - int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1; - atomic_max (&mp_.max_n_mmaps, new); - - unsigned long sum; - sum = atomic_exchange_and_add(&mp_.mmapped_mem, size) + size; - atomic_max (&mp_.max_mmapped_mem, sum); - - check_chunk(av, p); + If have mmap, and the request size meets the mmap threshold, and + the system supports mmap, and there are few enough currently + allocated mmapped regions, try to directly map this request + rather than expanding top. + */ + + if ((unsigned long) (nb) >= (unsigned long) (mp_.mmap_threshold) && + (mp_.n_mmaps < mp_.n_mmaps_max)) + { + char *mm; /* return value from mmap call*/ - return chunk2mem(p); - } + try_mmap: + /* + Round up size to nearest page. For mmapped chunks, the overhead + is one SIZE_SZ unit larger than for normal chunks, because there + is no following chunk whose prev_size field could be used. + + See the front_misalign handling below, for glibc there is no + need for further alignments unless we have have high alignment. + */ + if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) + size = (nb + SIZE_SZ + pagemask) & ~pagemask; + else + size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask; + tried_mmap = true; + + /* Don't try if size wraps around 0 */ + if ((unsigned long) (size) > (unsigned long) (nb)) + { + mm = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0)); + + if (mm != MAP_FAILED) + { + /* + The offset to the start of the mmapped region is stored + in the prev_size field of the chunk. This allows us to adjust + returned start address to meet alignment requirements here + and in memalign(), and still be able to compute proper + address argument for later munmap in free() and realloc(). + */ + + if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) + { + /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and + MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page + aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */ + assert (((INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK) == 0); + front_misalign = 0; + } + else + front_misalign = (INTERNAL_SIZE_T) chunk2mem (mm) & MALLOC_ALIGN_MASK; + if (front_misalign > 0) + { + correction = MALLOC_ALIGNMENT - front_misalign; + p = (mchunkptr) (mm + correction); + p->prev_size = correction; + set_head (p, (size - correction) | IS_MMAPPED); + } + else + { + p = (mchunkptr) mm; + set_head (p, size | IS_MMAPPED); + } + + /* update statistics */ + + int new = atomic_exchange_and_add (&mp_.n_mmaps, 1) + 1; + atomic_max (&mp_.max_n_mmaps, new); + + unsigned long sum; + sum = atomic_exchange_and_add (&mp_.mmapped_mem, size) + size; + atomic_max (&mp_.max_mmapped_mem, sum); + + check_chunk (av, p); + + return chunk2mem (p); + } + } } - } /* Record incoming configuration of top */ - old_top = av->top; - old_size = chunksize(old_top); - old_end = (char*)(chunk_at_offset(old_top, old_size)); + old_top = av->top; + old_size = chunksize (old_top); + old_end = (char *) (chunk_at_offset (old_top, old_size)); - brk = snd_brk = (char*)(MORECORE_FAILURE); + brk = snd_brk = (char *) (MORECORE_FAILURE); /* If not the first time through, we require old_size to be at least MINSIZE and to have prev_inuse set. - */ + */ - assert((old_top == initial_top(av) && old_size == 0) || - ((unsigned long) (old_size) >= MINSIZE && - prev_inuse(old_top) && - ((unsigned long)old_end & pagemask) == 0)); + assert ((old_top == initial_top (av) && old_size == 0) || + ((unsigned long) (old_size) >= MINSIZE && + prev_inuse (old_top) && + ((unsigned long) old_end & pagemask) == 0)); /* Precondition: not enough current space to satisfy nb request */ - assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE)); - - - if (av != &main_arena) { - - heap_info *old_heap, *heap; - size_t old_heap_size; - - /* First try to extend the current heap. */ - old_heap = heap_for_ptr(old_top); - old_heap_size = old_heap->size; - if ((long) (MINSIZE + nb - old_size) > 0 - && grow_heap(old_heap, MINSIZE + nb - old_size) == 0) { - av->system_mem += old_heap->size - old_heap_size; - arena_mem += old_heap->size - old_heap_size; - set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top) - | PREV_INUSE); - } - else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) { - /* Use a newly allocated heap. */ - heap->ar_ptr = av; - heap->prev = old_heap; - av->system_mem += heap->size; - arena_mem += heap->size; - /* Set up the new top. */ - top(av) = chunk_at_offset(heap, sizeof(*heap)); - set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE); - - /* Setup fencepost and free the old top chunk with a multiple of - MALLOC_ALIGNMENT in size. */ - /* The fencepost takes at least MINSIZE bytes, because it might - become the top chunk again later. Note that a footer is set - up, too, although the chunk is marked in use. */ - old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK; - set_head(chunk_at_offset(old_top, old_size + 2*SIZE_SZ), 0|PREV_INUSE); - if (old_size >= MINSIZE) { - set_head(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)|PREV_INUSE); - set_foot(chunk_at_offset(old_top, old_size), (2*SIZE_SZ)); - set_head(old_top, old_size|PREV_INUSE|NON_MAIN_ARENA); - _int_free(av, old_top, 1); - } else { - set_head(old_top, (old_size + 2*SIZE_SZ)|PREV_INUSE); - set_foot(old_top, (old_size + 2*SIZE_SZ)); - } - } - else if (!tried_mmap) - /* We can at least try to use to mmap memory. */ - goto try_mmap; - - } else { /* av == main_arena */ - - - /* Request enough space for nb + pad + overhead */ - - size = nb + mp_.top_pad + MINSIZE; - - /* - If contiguous, we can subtract out existing space that we hope to - combine with new space. We add it back later only if - we don't actually get contiguous space. - */ - - if (contiguous(av)) - size -= old_size; - - /* - Round to a multiple of page size. - If MORECORE is not contiguous, this ensures that we only call it - with whole-page arguments. And if MORECORE is contiguous and - this is not first time through, this preserves page-alignment of - previous calls. Otherwise, we correct to page-align below. - */ - - size = (size + pagemask) & ~pagemask; - - /* - Don't try to call MORECORE if argument is so big as to appear - negative. Note that since mmap takes size_t arg, it may succeed - below even if we cannot call MORECORE. - */ - - if (size > 0) { - brk = (char*)(MORECORE(size)); - LIBC_PROBE (memory_sbrk_more, 2, brk, size); - } - - if (brk != (char*)(MORECORE_FAILURE)) { - /* Call the `morecore' hook if necessary. */ - void (*hook) (void) = atomic_forced_read (__after_morecore_hook); - if (__builtin_expect (hook != NULL, 0)) - (*hook) (); - } else { - /* - If have mmap, try using it as a backup when MORECORE fails or - cannot be used. This is worth doing on systems that have "holes" in - address space, so sbrk cannot extend to give contiguous space, but - space is available elsewhere. Note that we ignore mmap max count - and threshold limits, since the space will not be used as a - segregated mmap region. - */ - - /* Cannot merge with old top, so add its size back in */ - if (contiguous(av)) - size = (size + old_size + pagemask) & ~pagemask; - - /* If we are relying on mmap as backup, then use larger units */ - if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE)) - size = MMAP_AS_MORECORE_SIZE; - - /* Don't try if size wraps around 0 */ - if ((unsigned long)(size) > (unsigned long)(nb)) { + assert ((unsigned long) (old_size) < (unsigned long) (nb + MINSIZE)); - char *mbrk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, 0)); - if (mbrk != MAP_FAILED) { - - /* We do not need, and cannot use, another sbrk call to find end */ - brk = mbrk; - snd_brk = brk + size; - - /* - Record that we no longer have a contiguous sbrk region. - After the first time mmap is used as backup, we do not - ever rely on contiguous space since this could incorrectly - bridge regions. - */ - set_noncontiguous(av); - } - } - } - - if (brk != (char*)(MORECORE_FAILURE)) { - if (mp_.sbrk_base == 0) - mp_.sbrk_base = brk; - av->system_mem += size; - - /* - If MORECORE extends previous space, we can likewise extend top size. - */ - - if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) - set_head(old_top, (size + old_size) | PREV_INUSE); - - else if (contiguous(av) && old_size && brk < old_end) { - /* Oops! Someone else killed our space.. Can't touch anything. */ - malloc_printerr (3, "break adjusted to free malloc space", brk); + if (av != &main_arena) + { + heap_info *old_heap, *heap; + size_t old_heap_size; + + /* First try to extend the current heap. */ + old_heap = heap_for_ptr (old_top); + old_heap_size = old_heap->size; + if ((long) (MINSIZE + nb - old_size) > 0 + && grow_heap (old_heap, MINSIZE + nb - old_size) == 0) + { + av->system_mem += old_heap->size - old_heap_size; + arena_mem += old_heap->size - old_heap_size; + set_head (old_top, (((char *) old_heap + old_heap->size) - (char *) old_top) + | PREV_INUSE); + } + else if ((heap = new_heap (nb + (MINSIZE + sizeof (*heap)), mp_.top_pad))) + { + /* Use a newly allocated heap. */ + heap->ar_ptr = av; + heap->prev = old_heap; + av->system_mem += heap->size; + arena_mem += heap->size; + /* Set up the new top. */ + top (av) = chunk_at_offset (heap, sizeof (*heap)); + set_head (top (av), (heap->size - sizeof (*heap)) | PREV_INUSE); + + /* Setup fencepost and free the old top chunk with a multiple of + MALLOC_ALIGNMENT in size. */ + /* The fencepost takes at least MINSIZE bytes, because it might + become the top chunk again later. Note that a footer is set + up, too, although the chunk is marked in use. */ + old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK; + set_head (chunk_at_offset (old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE); + if (old_size >= MINSIZE) + { + set_head (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE); + set_foot (chunk_at_offset (old_top, old_size), (2 * SIZE_SZ)); + set_head (old_top, old_size | PREV_INUSE | NON_MAIN_ARENA); + _int_free (av, old_top, 1); + } + else + { + set_head (old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE); + set_foot (old_top, (old_size + 2 * SIZE_SZ)); + } + } + else if (!tried_mmap) + /* We can at least try to use to mmap memory. */ + goto try_mmap; } + else /* av == main_arena */ - /* - Otherwise, make adjustments: - - * If the first time through or noncontiguous, we need to call sbrk - just to find out where the end of memory lies. - - * We need to ensure that all returned chunks from malloc will meet - MALLOC_ALIGNMENT - - * If there was an intervening foreign sbrk, we need to adjust sbrk - request size to account for fact that we will not be able to - combine new space with existing space in old_top. - - * Almost all systems internally allocate whole pages at a time, in - which case we might as well use the whole last page of request. - So we allocate enough more memory to hit a page boundary now, - which in turn causes future contiguous calls to page-align. - */ - - else { - front_misalign = 0; - end_misalign = 0; - correction = 0; - aligned_brk = brk; - /* handle contiguous cases */ - if (contiguous(av)) { + { /* Request enough space for nb + pad + overhead */ + size = nb + mp_.top_pad + MINSIZE; - /* Count foreign sbrk as system_mem. */ - if (old_size) - av->system_mem += brk - old_end; - - /* Guarantee alignment of first new chunk made from this space */ - - front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) { - - /* - Skip over some bytes to arrive at an aligned position. - We don't need to specially mark these wasted front bytes. - They will never be accessed anyway because - prev_inuse of av->top (and any chunk created from its start) - is always true after initialization. - */ - - correction = MALLOC_ALIGNMENT - front_misalign; - aligned_brk += correction; - } - - /* - If this isn't adjacent to existing space, then we will not - be able to merge with old_top space, so must add to 2nd request. - */ - - correction += old_size; - - /* Extend the end address to hit a page boundary */ - end_misalign = (INTERNAL_SIZE_T)(brk + size + correction); - correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign; - - assert(correction >= 0); - snd_brk = (char*)(MORECORE(correction)); - - /* - If can't allocate correction, try to at least find out current - brk. It might be enough to proceed without failing. - - Note that if second sbrk did NOT fail, we assume that space - is contiguous with first sbrk. This is a safe assumption unless - program is multithreaded but doesn't use locks and a foreign sbrk - occurred between our first and second calls. - */ - - if (snd_brk == (char*)(MORECORE_FAILURE)) { - correction = 0; - snd_brk = (char*)(MORECORE(0)); - } else { - /* Call the `morecore' hook if necessary. */ - void (*hook) (void) = atomic_forced_read (__after_morecore_hook); - if (__builtin_expect (hook != NULL, 0)) - (*hook) (); - } - } - - /* handle non-contiguous cases */ - else { - if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) - /* MORECORE/mmap must correctly align */ - assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0); - else { - front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK; - if (front_misalign > 0) { - - /* - Skip over some bytes to arrive at an aligned position. - We don't need to specially mark these wasted front bytes. - They will never be accessed anyway because - prev_inuse of av->top (and any chunk created from its start) - is always true after initialization. - */ - - aligned_brk += MALLOC_ALIGNMENT - front_misalign; - } - } - - /* Find out current end of memory */ - if (snd_brk == (char*)(MORECORE_FAILURE)) { - snd_brk = (char*)(MORECORE(0)); - } - } + /* + If contiguous, we can subtract out existing space that we hope to + combine with new space. We add it back later only if + we don't actually get contiguous space. + */ - /* Adjust top based on results of second sbrk */ - if (snd_brk != (char*)(MORECORE_FAILURE)) { - av->top = (mchunkptr)aligned_brk; - set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); - av->system_mem += correction; - - /* - If not the first time through, we either have a - gap due to foreign sbrk or a non-contiguous region. Insert a - double fencepost at old_top to prevent consolidation with space - we don't own. These fenceposts are artificial chunks that are - marked as inuse and are in any case too small to use. We need - two to make sizes and alignments work out. - */ - - if (old_size != 0) { - /* - Shrink old_top to insert fenceposts, keeping size a - multiple of MALLOC_ALIGNMENT. We know there is at least - enough space in old_top to do this. - */ - old_size = (old_size - 4*SIZE_SZ) & ~MALLOC_ALIGN_MASK; - set_head(old_top, old_size | PREV_INUSE); - - /* - Note that the following assignments completely overwrite - old_top when old_size was previously MINSIZE. This is - intentional. We need the fencepost, even if old_top otherwise gets - lost. - */ - chunk_at_offset(old_top, old_size )->size = - (2*SIZE_SZ)|PREV_INUSE; - - chunk_at_offset(old_top, old_size + 2*SIZE_SZ)->size = - (2*SIZE_SZ)|PREV_INUSE; - - /* If possible, release the rest. */ - if (old_size >= MINSIZE) { - _int_free(av, old_top, 1); - } + if (contiguous (av)) + size -= old_size; - } - } - } - } + /* + Round to a multiple of page size. + If MORECORE is not contiguous, this ensures that we only call it + with whole-page arguments. And if MORECORE is contiguous and + this is not first time through, this preserves page-alignment of + previous calls. Otherwise, we correct to page-align below. + */ - } /* if (av != &main_arena) */ + size = (size + pagemask) & ~pagemask; - if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem)) + /* + Don't try to call MORECORE if argument is so big as to appear + negative. Note that since mmap takes size_t arg, it may succeed + below even if we cannot call MORECORE. + */ + + if (size > 0) + { + brk = (char *) (MORECORE (size)); + LIBC_PROBE (memory_sbrk_more, 2, brk, size); + } + + if (brk != (char *) (MORECORE_FAILURE)) + { + /* Call the `morecore' hook if necessary. */ + void (*hook) (void) = atomic_forced_read (__after_morecore_hook); + if (__builtin_expect (hook != NULL, 0)) + (*hook)(); + } + else + { + /* + If have mmap, try using it as a backup when MORECORE fails or + cannot be used. This is worth doing on systems that have "holes" in + address space, so sbrk cannot extend to give contiguous space, but + space is available elsewhere. Note that we ignore mmap max count + and threshold limits, since the space will not be used as a + segregated mmap region. + */ + + /* Cannot merge with old top, so add its size back in */ + if (contiguous (av)) + size = (size + old_size + pagemask) & ~pagemask; + + /* If we are relying on mmap as backup, then use larger units */ + if ((unsigned long) (size) < (unsigned long) (MMAP_AS_MORECORE_SIZE)) + size = MMAP_AS_MORECORE_SIZE; + + /* Don't try if size wraps around 0 */ + if ((unsigned long) (size) > (unsigned long) (nb)) + { + char *mbrk = (char *) (MMAP (0, size, PROT_READ | PROT_WRITE, 0)); + + if (mbrk != MAP_FAILED) + { + /* We do not need, and cannot use, another sbrk call to find end */ + brk = mbrk; + snd_brk = brk + size; + + /* + Record that we no longer have a contiguous sbrk region. + After the first time mmap is used as backup, we do not + ever rely on contiguous space since this could incorrectly + bridge regions. + */ + set_noncontiguous (av); + } + } + } + + if (brk != (char *) (MORECORE_FAILURE)) + { + if (mp_.sbrk_base == 0) + mp_.sbrk_base = brk; + av->system_mem += size; + + /* + If MORECORE extends previous space, we can likewise extend top size. + */ + + if (brk == old_end && snd_brk == (char *) (MORECORE_FAILURE)) + set_head (old_top, (size + old_size) | PREV_INUSE); + + else if (contiguous (av) && old_size && brk < old_end) + { + /* Oops! Someone else killed our space.. Can't touch anything. */ + malloc_printerr (3, "break adjusted to free malloc space", brk); + } + + /* + Otherwise, make adjustments: + + * If the first time through or noncontiguous, we need to call sbrk + just to find out where the end of memory lies. + + * We need to ensure that all returned chunks from malloc will meet + MALLOC_ALIGNMENT + + * If there was an intervening foreign sbrk, we need to adjust sbrk + request size to account for fact that we will not be able to + combine new space with existing space in old_top. + + * Almost all systems internally allocate whole pages at a time, in + which case we might as well use the whole last page of request. + So we allocate enough more memory to hit a page boundary now, + which in turn causes future contiguous calls to page-align. + */ + + else + { + front_misalign = 0; + end_misalign = 0; + correction = 0; + aligned_brk = brk; + + /* handle contiguous cases */ + if (contiguous (av)) + { + /* Count foreign sbrk as system_mem. */ + if (old_size) + av->system_mem += brk - old_end; + + /* Guarantee alignment of first new chunk made from this space */ + + front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; + if (front_misalign > 0) + { + /* + Skip over some bytes to arrive at an aligned position. + We don't need to specially mark these wasted front bytes. + They will never be accessed anyway because + prev_inuse of av->top (and any chunk created from its start) + is always true after initialization. + */ + + correction = MALLOC_ALIGNMENT - front_misalign; + aligned_brk += correction; + } + + /* + If this isn't adjacent to existing space, then we will not + be able to merge with old_top space, so must add to 2nd request. + */ + + correction += old_size; + + /* Extend the end address to hit a page boundary */ + end_misalign = (INTERNAL_SIZE_T) (brk + size + correction); + correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign; + + assert (correction >= 0); + snd_brk = (char *) (MORECORE (correction)); + + /* + If can't allocate correction, try to at least find out current + brk. It might be enough to proceed without failing. + + Note that if second sbrk did NOT fail, we assume that space + is contiguous with first sbrk. This is a safe assumption unless + program is multithreaded but doesn't use locks and a foreign sbrk + occurred between our first and second calls. + */ + + if (snd_brk == (char *) (MORECORE_FAILURE)) + { + correction = 0; + snd_brk = (char *) (MORECORE (0)); + } + else + { + /* Call the `morecore' hook if necessary. */ + void (*hook) (void) = atomic_forced_read (__after_morecore_hook); + if (__builtin_expect (hook != NULL, 0)) + (*hook)(); + } + } + + /* handle non-contiguous cases */ + else + { + if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) + /* MORECORE/mmap must correctly align */ + assert (((unsigned long) chunk2mem (brk) & MALLOC_ALIGN_MASK) == 0); + else + { + front_misalign = (INTERNAL_SIZE_T) chunk2mem (brk) & MALLOC_ALIGN_MASK; + if (front_misalign > 0) + { + /* + Skip over some bytes to arrive at an aligned position. + We don't need to specially mark these wasted front bytes. + They will never be accessed anyway because + prev_inuse of av->top (and any chunk created from its start) + is always true after initialization. + */ + + aligned_brk += MALLOC_ALIGNMENT - front_misalign; + } + } + + /* Find out current end of memory */ + if (snd_brk == (char *) (MORECORE_FAILURE)) + { + snd_brk = (char *) (MORECORE (0)); + } + } + + /* Adjust top based on results of second sbrk */ + if (snd_brk != (char *) (MORECORE_FAILURE)) + { + av->top = (mchunkptr) aligned_brk; + set_head (av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); + av->system_mem += correction; + + /* + If not the first time through, we either have a + gap due to foreign sbrk or a non-contiguous region. Insert a + double fencepost at old_top to prevent consolidation with space + we don't own. These fenceposts are artificial chunks that are + marked as inuse and are in any case too small to use. We need + two to make sizes and alignments work out. + */ + + if (old_size != 0) + { + /* + Shrink old_top to insert fenceposts, keeping size a + multiple of MALLOC_ALIGNMENT. We know there is at least + enough space in old_top to do this. + */ + old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK; + set_head (old_top, old_size | PREV_INUSE); + + /* + Note that the following assignments completely overwrite + old_top when old_size was previously MINSIZE. This is + intentional. We need the fencepost, even if old_top otherwise gets + lost. + */ + chunk_at_offset (old_top, old_size)->size = + (2 * SIZE_SZ) | PREV_INUSE; + + chunk_at_offset (old_top, old_size + 2 * SIZE_SZ)->size = + (2 * SIZE_SZ) | PREV_INUSE; + + /* If possible, release the rest. */ + if (old_size >= MINSIZE) + { + _int_free (av, old_top, 1); + } + } + } + } + } + } /* if (av != &main_arena) */ + + if ((unsigned long) av->system_mem > (unsigned long) (av->max_system_mem)) av->max_system_mem = av->system_mem; - check_malloc_state(av); + check_malloc_state (av); /* finally, do the allocation */ p = av->top; - size = chunksize(p); + size = chunksize (p); /* check that one of the above allocation paths succeeded */ - if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(p, nb); - av->top = remainder; - set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE); - check_malloced_chunk(av, p, nb); - return chunk2mem(p); - } + if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) + { + remainder_size = size - nb; + remainder = chunk_at_offset (p, nb); + av->top = remainder; + set_head (p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE); + check_malloced_chunk (av, p, nb); + return chunk2mem (p); + } /* catch all failure paths */ __set_errno (ENOMEM); @@ -2677,26 +2721,27 @@ static void* sysmalloc(INTERNAL_SIZE_T nb, mstate av) /* - systrim is an inverse of sorts to sysmalloc. It gives memory back - to the system (via negative arguments to sbrk) if there is unused - memory at the `high' end of the malloc pool. It is called - automatically by free() when top space exceeds the trim - threshold. It is also called by the public malloc_trim routine. It - returns 1 if it actually released any memory, else 0. -*/ + systrim is an inverse of sorts to sysmalloc. It gives memory back + to the system (via negative arguments to sbrk) if there is unused + memory at the `high' end of the malloc pool. It is called + automatically by free() when top space exceeds the trim + threshold. It is also called by the public malloc_trim routine. It + returns 1 if it actually released any memory, else 0. + */ -static int systrim(size_t pad, mstate av) +static int +systrim (size_t pad, mstate av) { - long top_size; /* Amount of top-most memory */ - long extra; /* Amount to release */ - long released; /* Amount actually released */ - char* current_brk; /* address returned by pre-check sbrk call */ - char* new_brk; /* address returned by post-check sbrk call */ + long top_size; /* Amount of top-most memory */ + long extra; /* Amount to release */ + long released; /* Amount actually released */ + char *current_brk; /* address returned by pre-check sbrk call */ + char *new_brk; /* address returned by post-check sbrk call */ size_t pagesz; - long top_area; + long top_area; - pagesz = GLRO(dl_pagesize); - top_size = chunksize(av->top); + pagesz = GLRO (dl_pagesize); + top_size = chunksize (av->top); top_area = top_size - MINSIZE - 1; if (top_area <= pad) @@ -2706,53 +2751,55 @@ static int systrim(size_t pad, mstate av) extra = (top_area - pad) & ~(pagesz - 1); /* - Only proceed if end of memory is where we last set it. - This avoids problems if there were foreign sbrk calls. - */ - current_brk = (char*)(MORECORE(0)); - if (current_brk == (char*)(av->top) + top_size) { - - /* - Attempt to release memory. We ignore MORECORE return value, - and instead call again to find out where new end of memory is. - This avoids problems if first call releases less than we asked, - of if failure somehow altered brk value. (We could still - encounter problems if it altered brk in some very bad way, - but the only thing we can do is adjust anyway, which will cause - some downstream failure.) - */ - - MORECORE(-extra); - /* Call the `morecore' hook if necessary. */ - void (*hook) (void) = atomic_forced_read (__after_morecore_hook); - if (__builtin_expect (hook != NULL, 0)) - (*hook) (); - new_brk = (char*)(MORECORE(0)); - - LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra); - - if (new_brk != (char*)MORECORE_FAILURE) { - released = (long)(current_brk - new_brk); - - if (released != 0) { - /* Success. Adjust top. */ - av->system_mem -= released; - set_head(av->top, (top_size - released) | PREV_INUSE); - check_malloc_state(av); - return 1; - } + Only proceed if end of memory is where we last set it. + This avoids problems if there were foreign sbrk calls. + */ + current_brk = (char *) (MORECORE (0)); + if (current_brk == (char *) (av->top) + top_size) + { + /* + Attempt to release memory. We ignore MORECORE return value, + and instead call again to find out where new end of memory is. + This avoids problems if first call releases less than we asked, + of if failure somehow altered brk value. (We could still + encounter problems if it altered brk in some very bad way, + but the only thing we can do is adjust anyway, which will cause + some downstream failure.) + */ + + MORECORE (-extra); + /* Call the `morecore' hook if necessary. */ + void (*hook) (void) = atomic_forced_read (__after_morecore_hook); + if (__builtin_expect (hook != NULL, 0)) + (*hook)(); + new_brk = (char *) (MORECORE (0)); + + LIBC_PROBE (memory_sbrk_less, 2, new_brk, extra); + + if (new_brk != (char *) MORECORE_FAILURE) + { + released = (long) (current_brk - new_brk); + + if (released != 0) + { + /* Success. Adjust top. */ + av->system_mem -= released; + set_head (av->top, (top_size - released) | PREV_INUSE); + check_malloc_state (av); + return 1; + } + } } - } return 0; } static void internal_function -munmap_chunk(mchunkptr p) +munmap_chunk (mchunkptr p) { - INTERNAL_SIZE_T size = chunksize(p); + INTERNAL_SIZE_T size = chunksize (p); - assert (chunk_is_mmapped(p)); + assert (chunk_is_mmapped (p)); uintptr_t block = (uintptr_t) p - p->prev_size; size_t total_size = p->prev_size + size; @@ -2761,10 +2808,10 @@ munmap_chunk(mchunkptr p) page size. But gcc does not recognize the optimization possibility (in the moment at least) so we combine the two values into one before the bit test. */ - if (__builtin_expect (((block | total_size) & (GLRO(dl_pagesize) - 1)) != 0, 0)) + if (__builtin_expect (((block | total_size) & (GLRO (dl_pagesize) - 1)) != 0, 0)) { malloc_printerr (check_action, "munmap_chunk(): invalid pointer", - chunk2mem (p)); + chunk2mem (p)); return; } @@ -2774,22 +2821,22 @@ munmap_chunk(mchunkptr p) /* If munmap failed the process virtual memory address space is in a bad shape. Just leave the block hanging around, the process will terminate shortly anyway since not much can be done. */ - __munmap((char *)block, total_size); + __munmap ((char *) block, total_size); } #if HAVE_MREMAP static mchunkptr internal_function -mremap_chunk(mchunkptr p, size_t new_size) +mremap_chunk (mchunkptr p, size_t new_size) { - size_t page_mask = GLRO(dl_pagesize) - 1; + size_t page_mask = GLRO (dl_pagesize) - 1; INTERNAL_SIZE_T offset = p->prev_size; - INTERNAL_SIZE_T size = chunksize(p); + INTERNAL_SIZE_T size = chunksize (p); char *cp; - assert (chunk_is_mmapped(p)); - assert(((size + offset) & (GLRO(dl_pagesize)-1)) == 0); + assert (chunk_is_mmapped (p)); + assert (((size + offset) & (GLRO (dl_pagesize) - 1)) == 0); /* Note the extra SIZE_SZ overhead as in mmap_chunk(). */ new_size = (new_size + offset + SIZE_SZ + page_mask) & ~page_mask; @@ -2798,31 +2845,31 @@ mremap_chunk(mchunkptr p, size_t new_size) if (size + offset == new_size) return p; - cp = (char *)__mremap((char *)p - offset, size + offset, new_size, - MREMAP_MAYMOVE); + cp = (char *) __mremap ((char *) p - offset, size + offset, new_size, + MREMAP_MAYMOVE); - if (cp == MAP_FAILED) return 0; + if (cp == MAP_FAILED) + return 0; - p = (mchunkptr)(cp + offset); + p = (mchunkptr) (cp + offset); - assert(aligned_OK(chunk2mem(p))); + assert (aligned_OK (chunk2mem (p))); - assert((p->prev_size == offset)); - set_head(p, (new_size - offset)|IS_MMAPPED); + assert ((p->prev_size == offset)); + set_head (p, (new_size - offset) | IS_MMAPPED); INTERNAL_SIZE_T new; new = atomic_exchange_and_add (&mp_.mmapped_mem, new_size - size - offset) - + new_size - size - offset; + + new_size - size - offset; atomic_max (&mp_.max_mmapped_mem, new); return p; } - #endif /* HAVE_MREMAP */ /*------------------------ Public wrappers. --------------------------------*/ -void* -__libc_malloc(size_t bytes) +void * +__libc_malloc (size_t bytes) { mstate ar_ptr; void *victim; @@ -2832,73 +2879,78 @@ __libc_malloc(size_t bytes) if (__builtin_expect (hook != NULL, 0)) return (*hook)(bytes, RETURN_ADDRESS (0)); - arena_lookup(ar_ptr); + arena_lookup (ar_ptr); - arena_lock(ar_ptr, bytes); - if(!ar_ptr) + arena_lock (ar_ptr, bytes); + if (!ar_ptr) return 0; - victim = _int_malloc(ar_ptr, bytes); - if(!victim) { - LIBC_PROBE (memory_malloc_retry, 1, bytes); - ar_ptr = arena_get_retry(ar_ptr, bytes); - if (__builtin_expect(ar_ptr != NULL, 1)) { - victim = _int_malloc(ar_ptr, bytes); - (void)mutex_unlock(&ar_ptr->mutex); + + victim = _int_malloc (ar_ptr, bytes); + if (!victim) + { + LIBC_PROBE (memory_malloc_retry, 1, bytes); + ar_ptr = arena_get_retry (ar_ptr, bytes); + if (__builtin_expect (ar_ptr != NULL, 1)) + { + victim = _int_malloc (ar_ptr, bytes); + (void) mutex_unlock (&ar_ptr->mutex); + } } - } else - (void)mutex_unlock(&ar_ptr->mutex); - assert(!victim || chunk_is_mmapped(mem2chunk(victim)) || - ar_ptr == arena_for_chunk(mem2chunk(victim))); + else + (void) mutex_unlock (&ar_ptr->mutex); + assert (!victim || chunk_is_mmapped (mem2chunk (victim)) || + ar_ptr == arena_for_chunk (mem2chunk (victim))); return victim; } -libc_hidden_def(__libc_malloc) +libc_hidden_def (__libc_malloc) void -__libc_free(void* mem) +__libc_free (void *mem) { mstate ar_ptr; mchunkptr p; /* chunk corresponding to mem */ void (*hook) (void *, const void *) = atomic_forced_read (__free_hook); - if (__builtin_expect (hook != NULL, 0)) { - (*hook)(mem, RETURN_ADDRESS (0)); - return; - } + if (__builtin_expect (hook != NULL, 0)) + { + (*hook)(mem, RETURN_ADDRESS (0)); + return; + } if (mem == 0) /* free(0) has no effect */ return; - p = mem2chunk(mem); + p = mem2chunk (mem); - if (chunk_is_mmapped(p)) /* release mmapped memory. */ - { - /* see if the dynamic brk/mmap threshold needs adjusting */ - if (!mp_.no_dyn_threshold - && p->size > mp_.mmap_threshold - && p->size <= DEFAULT_MMAP_THRESHOLD_MAX) - { - mp_.mmap_threshold = chunksize (p); - mp_.trim_threshold = 2 * mp_.mmap_threshold; - LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2, - mp_.mmap_threshold, mp_.trim_threshold); - } - munmap_chunk(p); - return; - } + if (chunk_is_mmapped (p)) /* release mmapped memory. */ + { + /* see if the dynamic brk/mmap threshold needs adjusting */ + if (!mp_.no_dyn_threshold + && p->size > mp_.mmap_threshold + && p->size <= DEFAULT_MMAP_THRESHOLD_MAX) + { + mp_.mmap_threshold = chunksize (p); + mp_.trim_threshold = 2 * mp_.mmap_threshold; + LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2, + mp_.mmap_threshold, mp_.trim_threshold); + } + munmap_chunk (p); + return; + } - ar_ptr = arena_for_chunk(p); - _int_free(ar_ptr, p, 0); + ar_ptr = arena_for_chunk (p); + _int_free (ar_ptr, p, 0); } libc_hidden_def (__libc_free) -void* -__libc_realloc(void* oldmem, size_t bytes) +void * +__libc_realloc (void *oldmem, size_t bytes) { mstate ar_ptr; - INTERNAL_SIZE_T nb; /* padded request size */ + INTERNAL_SIZE_T nb; /* padded request size */ - void* newp; /* chunk to return */ + void *newp; /* chunk to return */ void *(*hook) (void *, size_t, const void *) = atomic_forced_read (__realloc_hook); @@ -2906,16 +2958,20 @@ __libc_realloc(void* oldmem, size_t bytes) return (*hook)(oldmem, bytes, RETURN_ADDRESS (0)); #if REALLOC_ZERO_BYTES_FREES - if (bytes == 0 && oldmem != NULL) { __libc_free(oldmem); return 0; } + if (bytes == 0 && oldmem != NULL) + { + __libc_free (oldmem); return 0; + } #endif /* realloc of null is supposed to be same as malloc */ - if (oldmem == 0) return __libc_malloc(bytes); + if (oldmem == 0) + return __libc_malloc (bytes); /* chunk corresponding to oldmem */ - const mchunkptr oldp = mem2chunk(oldmem); + const mchunkptr oldp = mem2chunk (oldmem); /* its size */ - const INTERNAL_SIZE_T oldsize = chunksize(oldp); + const INTERNAL_SIZE_T oldsize = chunksize (oldp); /* Little security check which won't hurt performance: the allocator never wrapps around at the end of the address space. @@ -2928,63 +2984,69 @@ __libc_realloc(void* oldmem, size_t bytes) return NULL; } - checked_request2size(bytes, nb); + checked_request2size (bytes, nb); - if (chunk_is_mmapped(oldp)) - { - void* newmem; + if (chunk_is_mmapped (oldp)) + { + void *newmem; #if HAVE_MREMAP - newp = mremap_chunk(oldp, nb); - if(newp) return chunk2mem(newp); + newp = mremap_chunk (oldp, nb); + if (newp) + return chunk2mem (newp); #endif - /* Note the extra SIZE_SZ overhead. */ - if(oldsize - SIZE_SZ >= nb) return oldmem; /* do nothing */ - /* Must alloc, copy, free. */ - newmem = __libc_malloc(bytes); - if (newmem == 0) return 0; /* propagate failure */ - memcpy(newmem, oldmem, oldsize - 2*SIZE_SZ); - munmap_chunk(oldp); - return newmem; - } + /* Note the extra SIZE_SZ overhead. */ + if (oldsize - SIZE_SZ >= nb) + return oldmem; /* do nothing */ + + /* Must alloc, copy, free. */ + newmem = __libc_malloc (bytes); + if (newmem == 0) + return 0; /* propagate failure */ + + memcpy (newmem, oldmem, oldsize - 2 * SIZE_SZ); + munmap_chunk (oldp); + return newmem; + } - ar_ptr = arena_for_chunk(oldp); + ar_ptr = arena_for_chunk (oldp); #if THREAD_STATS - if(!mutex_trylock(&ar_ptr->mutex)) + if (!mutex_trylock (&ar_ptr->mutex)) ++(ar_ptr->stat_lock_direct); - else { - (void)mutex_lock(&ar_ptr->mutex); - ++(ar_ptr->stat_lock_wait); - } + else + { + (void) mutex_lock (&ar_ptr->mutex); + ++(ar_ptr->stat_lock_wait); + } #else - (void)mutex_lock(&ar_ptr->mutex); + (void) mutex_lock (&ar_ptr->mutex); #endif - newp = _int_realloc(ar_ptr, oldp, oldsize, nb); + newp = _int_realloc (ar_ptr, oldp, oldsize, nb); - (void)mutex_unlock(&ar_ptr->mutex); - assert(!newp || chunk_is_mmapped(mem2chunk(newp)) || - ar_ptr == arena_for_chunk(mem2chunk(newp))); + (void) mutex_unlock (&ar_ptr->mutex); + assert (!newp || chunk_is_mmapped (mem2chunk (newp)) || + ar_ptr == arena_for_chunk (mem2chunk (newp))); if (newp == NULL) { /* Try harder to allocate memory in other arenas. */ LIBC_PROBE (memory_realloc_retry, 2, bytes, oldmem); - newp = __libc_malloc(bytes); + newp = __libc_malloc (bytes); if (newp != NULL) - { - memcpy (newp, oldmem, oldsize - SIZE_SZ); - _int_free(ar_ptr, oldp, 0); - } + { + memcpy (newp, oldmem, oldsize - SIZE_SZ); + _int_free (ar_ptr, oldp, 0); + } } return newp; } libc_hidden_def (__libc_realloc) -void* -__libc_memalign(size_t alignment, size_t bytes) +void * +__libc_memalign (size_t alignment, size_t bytes) { void *address = RETURN_ADDRESS (0); return _mid_memalign (alignment, bytes, address); @@ -3002,10 +3064,12 @@ _mid_memalign (size_t alignment, size_t bytes, void *address) return (*hook)(alignment, bytes, address); /* If we need less alignment than we give anyway, just relay to malloc. */ - if (alignment <= MALLOC_ALIGNMENT) return __libc_malloc(bytes); + if (alignment <= MALLOC_ALIGNMENT) + return __libc_malloc (bytes); /* Otherwise, ensure that it is at least a minimum chunk size */ - if (alignment < MINSIZE) alignment = MINSIZE; + if (alignment < MINSIZE) + alignment = MINSIZE; /* If the alignment is greater than SIZE_MAX / 2 + 1 it cannot be a power of 2 and will cause overflow in the check below. */ @@ -3024,58 +3088,63 @@ _mid_memalign (size_t alignment, size_t bytes, void *address) /* Make sure alignment is power of 2. */ - if (!powerof2(alignment)) { - size_t a = MALLOC_ALIGNMENT * 2; - while (a < alignment) a <<= 1; - alignment = a; - } + if (!powerof2 (alignment)) + { + size_t a = MALLOC_ALIGNMENT * 2; + while (a < alignment) + a <<= 1; + alignment = a; + } - arena_get(ar_ptr, bytes + alignment + MINSIZE); - if(!ar_ptr) + arena_get (ar_ptr, bytes + alignment + MINSIZE); + if (!ar_ptr) return 0; - p = _int_memalign(ar_ptr, alignment, bytes); - if(!p) { - LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment); - ar_ptr = arena_get_retry (ar_ptr, bytes); - if (__builtin_expect(ar_ptr != NULL, 1)) { - p = _int_memalign(ar_ptr, alignment, bytes); - (void)mutex_unlock(&ar_ptr->mutex); + + p = _int_memalign (ar_ptr, alignment, bytes); + if (!p) + { + LIBC_PROBE (memory_memalign_retry, 2, bytes, alignment); + ar_ptr = arena_get_retry (ar_ptr, bytes); + if (__builtin_expect (ar_ptr != NULL, 1)) + { + p = _int_memalign (ar_ptr, alignment, bytes); + (void) mutex_unlock (&ar_ptr->mutex); + } } - } else - (void)mutex_unlock(&ar_ptr->mutex); - assert(!p || chunk_is_mmapped(mem2chunk(p)) || - ar_ptr == arena_for_chunk(mem2chunk(p))); + else + (void) mutex_unlock (&ar_ptr->mutex); + assert (!p || chunk_is_mmapped (mem2chunk (p)) || + ar_ptr == arena_for_chunk (mem2chunk (p))); return p; } /* For ISO C11. */ weak_alias (__libc_memalign, aligned_alloc) libc_hidden_def (__libc_memalign) -void* -__libc_valloc(size_t bytes) +void * +__libc_valloc (size_t bytes) { - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); void *address = RETURN_ADDRESS (0); - size_t pagesz = GLRO(dl_pagesize); + size_t pagesz = GLRO (dl_pagesize); return _mid_memalign (pagesz, bytes, address); } -void* -__libc_pvalloc(size_t bytes) +void * +__libc_pvalloc (size_t bytes) { - - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); void *address = RETURN_ADDRESS (0); - size_t pagesz = GLRO(dl_pagesize); - size_t page_mask = GLRO(dl_pagesize) - 1; + size_t pagesz = GLRO (dl_pagesize); + size_t page_mask = GLRO (dl_pagesize) - 1; size_t rounded_bytes = (bytes + page_mask) & ~(page_mask); /* Check for overflow. */ - if (bytes > SIZE_MAX - 2*pagesz - MINSIZE) + if (bytes > SIZE_MAX - 2 * pagesz - MINSIZE) { __set_errno (ENOMEM); return 0; @@ -3084,235 +3153,254 @@ __libc_pvalloc(size_t bytes) return _mid_memalign (pagesz, rounded_bytes, address); } -void* -__libc_calloc(size_t n, size_t elem_size) +void * +__libc_calloc (size_t n, size_t elem_size) { mstate av; mchunkptr oldtop, p; INTERNAL_SIZE_T bytes, sz, csz, oldtopsize; - void* mem; + void *mem; unsigned long clearsize; unsigned long nclears; - INTERNAL_SIZE_T* d; + INTERNAL_SIZE_T *d; /* size_t is unsigned so the behavior on overflow is defined. */ bytes = n * elem_size; #define HALF_INTERNAL_SIZE_T \ (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2)) - if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) { - if (elem_size != 0 && bytes / elem_size != n) { - __set_errno (ENOMEM); - return 0; + if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) + { + if (elem_size != 0 && bytes / elem_size != n) + { + __set_errno (ENOMEM); + return 0; + } } - } void *(*hook) (size_t, const void *) = atomic_forced_read (__malloc_hook); - if (__builtin_expect (hook != NULL, 0)) { - sz = bytes; - mem = (*hook)(sz, RETURN_ADDRESS (0)); - if(mem == 0) - return 0; - return memset(mem, 0, sz); - } + if (__builtin_expect (hook != NULL, 0)) + { + sz = bytes; + mem = (*hook)(sz, RETURN_ADDRESS (0)); + if (mem == 0) + return 0; + + return memset (mem, 0, sz); + } sz = bytes; - arena_get(av, sz); - if(!av) + arena_get (av, sz); + if (!av) return 0; /* Check if we hand out the top chunk, in which case there may be no need to clear. */ #if MORECORE_CLEARS - oldtop = top(av); - oldtopsize = chunksize(top(av)); -#if MORECORE_CLEARS < 2 + oldtop = top (av); + oldtopsize = chunksize (top (av)); +# if MORECORE_CLEARS < 2 /* Only newly allocated memory is guaranteed to be cleared. */ if (av == &main_arena && - oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *)oldtop) - oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *)oldtop); -#endif + oldtopsize < mp_.sbrk_base + av->max_system_mem - (char *) oldtop) + oldtopsize = (mp_.sbrk_base + av->max_system_mem - (char *) oldtop); +# endif if (av != &main_arena) { heap_info *heap = heap_for_ptr (oldtop); if (oldtopsize < (char *) heap + heap->mprotect_size - (char *) oldtop) - oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop; + oldtopsize = (char *) heap + heap->mprotect_size - (char *) oldtop; } #endif - mem = _int_malloc(av, sz); + mem = _int_malloc (av, sz); - assert(!mem || chunk_is_mmapped(mem2chunk(mem)) || - av == arena_for_chunk(mem2chunk(mem))); + assert (!mem || chunk_is_mmapped (mem2chunk (mem)) || + av == arena_for_chunk (mem2chunk (mem))); - if (mem == 0) { - LIBC_PROBE (memory_calloc_retry, 1, sz); - av = arena_get_retry (av, sz); - if (__builtin_expect(av != NULL, 1)) { - mem = _int_malloc(av, sz); - (void)mutex_unlock(&av->mutex); + if (mem == 0) + { + LIBC_PROBE (memory_calloc_retry, 1, sz); + av = arena_get_retry (av, sz); + if (__builtin_expect (av != NULL, 1)) + { + mem = _int_malloc (av, sz); + (void) mutex_unlock (&av->mutex); + } + if (mem == 0) + return 0; } - if (mem == 0) return 0; - } else - (void)mutex_unlock(&av->mutex); - p = mem2chunk(mem); + else + (void) mutex_unlock (&av->mutex); + p = mem2chunk (mem); /* Two optional cases in which clearing not necessary */ if (chunk_is_mmapped (p)) { if (__builtin_expect (perturb_byte, 0)) - return memset (mem, 0, sz); + return memset (mem, 0, sz); + return mem; } - csz = chunksize(p); + csz = chunksize (p); #if MORECORE_CLEARS - if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize)) { - /* clear only the bytes from non-freshly-sbrked memory */ - csz = oldtopsize; - } + if (perturb_byte == 0 && (p == oldtop && csz > oldtopsize)) + { + /* clear only the bytes from non-freshly-sbrked memory */ + csz = oldtopsize; + } #endif /* Unroll clear of <= 36 bytes (72 if 8byte sizes). We know that contents have an odd number of INTERNAL_SIZE_T-sized words; minimally 3. */ - d = (INTERNAL_SIZE_T*)mem; + d = (INTERNAL_SIZE_T *) mem; clearsize = csz - SIZE_SZ; - nclears = clearsize / sizeof(INTERNAL_SIZE_T); - assert(nclears >= 3); + nclears = clearsize / sizeof (INTERNAL_SIZE_T); + assert (nclears >= 3); if (nclears > 9) - return memset(d, 0, clearsize); + return memset (d, 0, clearsize); - else { - *(d+0) = 0; - *(d+1) = 0; - *(d+2) = 0; - if (nclears > 4) { - *(d+3) = 0; - *(d+4) = 0; - if (nclears > 6) { - *(d+5) = 0; - *(d+6) = 0; - if (nclears > 8) { - *(d+7) = 0; - *(d+8) = 0; - } - } + else + { + *(d + 0) = 0; + *(d + 1) = 0; + *(d + 2) = 0; + if (nclears > 4) + { + *(d + 3) = 0; + *(d + 4) = 0; + if (nclears > 6) + { + *(d + 5) = 0; + *(d + 6) = 0; + if (nclears > 8) + { + *(d + 7) = 0; + *(d + 8) = 0; + } + } + } } - } return mem; } /* - ------------------------------ malloc ------------------------------ -*/ + ------------------------------ malloc ------------------------------ + */ -static void* -_int_malloc(mstate av, size_t bytes) +static void * +_int_malloc (mstate av, size_t bytes) { INTERNAL_SIZE_T nb; /* normalized request size */ - unsigned int idx; /* associated bin index */ - mbinptr bin; /* associated bin */ + unsigned int idx; /* associated bin index */ + mbinptr bin; /* associated bin */ - mchunkptr victim; /* inspected/selected chunk */ + mchunkptr victim; /* inspected/selected chunk */ INTERNAL_SIZE_T size; /* its size */ - int victim_index; /* its bin index */ + int victim_index; /* its bin index */ - mchunkptr remainder; /* remainder from a split */ - unsigned long remainder_size; /* its size */ + mchunkptr remainder; /* remainder from a split */ + unsigned long remainder_size; /* its size */ - unsigned int block; /* bit map traverser */ - unsigned int bit; /* bit map traverser */ - unsigned int map; /* current word of binmap */ + unsigned int block; /* bit map traverser */ + unsigned int bit; /* bit map traverser */ + unsigned int map; /* current word of binmap */ - mchunkptr fwd; /* misc temp for linking */ - mchunkptr bck; /* misc temp for linking */ + mchunkptr fwd; /* misc temp for linking */ + mchunkptr bck; /* misc temp for linking */ const char *errstr = NULL; /* - Convert request size to internal form by adding SIZE_SZ bytes - overhead plus possibly more to obtain necessary alignment and/or - to obtain a size of at least MINSIZE, the smallest allocatable - size. Also, checked_request2size traps (returning 0) request sizes - that are so large that they wrap around zero when padded and - aligned. - */ + Convert request size to internal form by adding SIZE_SZ bytes + overhead plus possibly more to obtain necessary alignment and/or + to obtain a size of at least MINSIZE, the smallest allocatable + size. Also, checked_request2size traps (returning 0) request sizes + that are so large that they wrap around zero when padded and + aligned. + */ - checked_request2size(bytes, nb); + checked_request2size (bytes, nb); /* - If the size qualifies as a fastbin, first check corresponding bin. - This code is safe to execute even if av is not yet initialized, so we - can try it without checking, which saves some time on this fast path. - */ + If the size qualifies as a fastbin, first check corresponding bin. + This code is safe to execute even if av is not yet initialized, so we + can try it without checking, which saves some time on this fast path. + */ - if ((unsigned long)(nb) <= (unsigned long)(get_max_fast ())) { - idx = fastbin_index(nb); - mfastbinptr* fb = &fastbin (av, idx); - mchunkptr pp = *fb; - do - { - victim = pp; - if (victim == NULL) - break; - } - while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim)) - != victim); - if (victim != 0) { - if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0)) - { - errstr = "malloc(): memory corruption (fast)"; - errout: - malloc_printerr (check_action, errstr, chunk2mem (victim)); - return NULL; - } - check_remalloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; + if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ())) + { + idx = fastbin_index (nb); + mfastbinptr *fb = &fastbin (av, idx); + mchunkptr pp = *fb; + do + { + victim = pp; + if (victim == NULL) + break; + } + while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim)) + != victim); + if (victim != 0) + { + if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0)) + { + errstr = "malloc(): memory corruption (fast)"; + errout: + malloc_printerr (check_action, errstr, chunk2mem (victim)); + return NULL; + } + check_remalloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } } - } /* - If a small request, check regular bin. Since these "smallbins" - hold one size each, no searching within bins is necessary. - (For a large request, we need to wait until unsorted chunks are - processed to find best fit. But for small ones, fits are exact - anyway, so we can check now, which is faster.) - */ - - if (in_smallbin_range(nb)) { - idx = smallbin_index(nb); - bin = bin_at(av,idx); - - if ( (victim = last(bin)) != bin) { - if (victim == 0) /* initialization check */ - malloc_consolidate(av); - else { - bck = victim->bk; - if (__builtin_expect (bck->fd != victim, 0)) - { - errstr = "malloc(): smallbin double linked list corrupted"; - goto errout; - } - set_inuse_bit_at_offset(victim, nb); - bin->bk = bck; - bck->fd = bin; - - if (av != &main_arena) - victim->size |= NON_MAIN_ARENA; - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } + If a small request, check regular bin. Since these "smallbins" + hold one size each, no searching within bins is necessary. + (For a large request, we need to wait until unsorted chunks are + processed to find best fit. But for small ones, fits are exact + anyway, so we can check now, which is faster.) + */ + + if (in_smallbin_range (nb)) + { + idx = smallbin_index (nb); + bin = bin_at (av, idx); + + if ((victim = last (bin)) != bin) + { + if (victim == 0) /* initialization check */ + malloc_consolidate (av); + else + { + bck = victim->bk; + if (__builtin_expect (bck->fd != victim, 0)) + { + errstr = "malloc(): smallbin double linked list corrupted"; + goto errout; + } + set_inuse_bit_at_offset (victim, nb); + bin->bk = bck; + bck->fd = bin; + + if (av != &main_arena) + victim->size |= NON_MAIN_ARENA; + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + } } - } /* If this is a large request, consolidate fastbins before continuing. @@ -3323,394 +3411,417 @@ _int_malloc(mstate av, size_t bytes) large requests, but less often mixtures, so consolidation is not invoked all that often in most programs. And the programs that it is called frequently in otherwise tend to fragment. - */ + */ - else { - idx = largebin_index(nb); - if (have_fastchunks(av)) - malloc_consolidate(av); - } + else + { + idx = largebin_index (nb); + if (have_fastchunks (av)) + malloc_consolidate (av); + } /* - Process recently freed or remaindered chunks, taking one only if - it is exact fit, or, if this a small request, the chunk is remainder from - the most recent non-exact fit. Place other traversed chunks in - bins. Note that this step is the only place in any routine where - chunks are placed in bins. - - The outer loop here is needed because we might not realize until - near the end of malloc that we should have consolidated, so must - do so and retry. This happens at most once, and only when we would - otherwise need to expand memory to service a "small" request. - */ - - for(;;) { - - int iters = 0; - while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) { - bck = victim->bk; - if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0) - || __builtin_expect (victim->size > av->system_mem, 0)) - malloc_printerr (check_action, "malloc(): memory corruption", - chunk2mem (victim)); - size = chunksize(victim); + Process recently freed or remaindered chunks, taking one only if + it is exact fit, or, if this a small request, the chunk is remainder from + the most recent non-exact fit. Place other traversed chunks in + bins. Note that this step is the only place in any routine where + chunks are placed in bins. + + The outer loop here is needed because we might not realize until + near the end of malloc that we should have consolidated, so must + do so and retry. This happens at most once, and only when we would + otherwise need to expand memory to service a "small" request. + */ + + for (;; ) + { + int iters = 0; + while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av)) + { + bck = victim->bk; + if (__builtin_expect (victim->size <= 2 * SIZE_SZ, 0) + || __builtin_expect (victim->size > av->system_mem, 0)) + malloc_printerr (check_action, "malloc(): memory corruption", + chunk2mem (victim)); + size = chunksize (victim); + + /* + If a small request, try to use last remainder if it is the + only chunk in unsorted bin. This helps promote locality for + runs of consecutive small requests. This is the only + exception to best-fit, and applies only when there is + no exact fit for a small chunk. + */ + + if (in_smallbin_range (nb) && + bck == unsorted_chunks (av) && + victim == av->last_remainder && + (unsigned long) (size) > (unsigned long) (nb + MINSIZE)) + { + /* split and reattach remainder */ + remainder_size = size - nb; + remainder = chunk_at_offset (victim, nb); + unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder; + av->last_remainder = remainder; + remainder->bk = remainder->fd = unsorted_chunks (av); + if (!in_smallbin_range (remainder_size)) + { + remainder->fd_nextsize = NULL; + remainder->bk_nextsize = NULL; + } + + set_head (victim, nb | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE); + set_foot (remainder, remainder_size); + + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + + /* remove from unsorted list */ + unsorted_chunks (av)->bk = bck; + bck->fd = unsorted_chunks (av); + + /* Take now instead of binning if exact fit */ + + if (size == nb) + { + set_inuse_bit_at_offset (victim, size); + if (av != &main_arena) + victim->size |= NON_MAIN_ARENA; + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + + /* place chunk in bin */ + + if (in_smallbin_range (size)) + { + victim_index = smallbin_index (size); + bck = bin_at (av, victim_index); + fwd = bck->fd; + } + else + { + victim_index = largebin_index (size); + bck = bin_at (av, victim_index); + fwd = bck->fd; + + /* maintain large bins in sorted order */ + if (fwd != bck) + { + /* Or with inuse bit to speed comparisons */ + size |= PREV_INUSE; + /* if smaller than smallest, bypass loop below */ + assert ((bck->bk->size & NON_MAIN_ARENA) == 0); + if ((unsigned long) (size) < (unsigned long) (bck->bk->size)) + { + fwd = bck; + bck = bck->bk; + + victim->fd_nextsize = fwd->fd; + victim->bk_nextsize = fwd->fd->bk_nextsize; + fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; + } + else + { + assert ((fwd->size & NON_MAIN_ARENA) == 0); + while ((unsigned long) size < fwd->size) + { + fwd = fwd->fd_nextsize; + assert ((fwd->size & NON_MAIN_ARENA) == 0); + } + + if ((unsigned long) size == (unsigned long) fwd->size) + /* Always insert in the second position. */ + fwd = fwd->fd; + else + { + victim->fd_nextsize = fwd; + victim->bk_nextsize = fwd->bk_nextsize; + fwd->bk_nextsize = victim; + victim->bk_nextsize->fd_nextsize = victim; + } + bck = fwd->bk; + } + } + else + victim->fd_nextsize = victim->bk_nextsize = victim; + } + + mark_bin (av, victim_index); + victim->bk = bck; + victim->fd = fwd; + fwd->bk = victim; + bck->fd = victim; + +#define MAX_ITERS 10000 + if (++iters >= MAX_ITERS) + break; + } /* - If a small request, try to use last remainder if it is the - only chunk in unsorted bin. This helps promote locality for - runs of consecutive small requests. This is the only - exception to best-fit, and applies only when there is - no exact fit for a small chunk. - */ + If a large request, scan through the chunks of current bin in + sorted order to find smallest that fits. Use the skip list for this. + */ + + if (!in_smallbin_range (nb)) + { + bin = bin_at (av, idx); + + /* skip scan if empty or largest chunk is too small */ + if ((victim = first (bin)) != bin && + (unsigned long) (victim->size) >= (unsigned long) (nb)) + { + victim = victim->bk_nextsize; + while (((unsigned long) (size = chunksize (victim)) < + (unsigned long) (nb))) + victim = victim->bk_nextsize; + + /* Avoid removing the first entry for a size so that the skip + list does not have to be rerouted. */ + if (victim != last (bin) && victim->size == victim->fd->size) + victim = victim->fd; + + remainder_size = size - nb; + unlink (victim, bck, fwd); + + /* Exhaust */ + if (remainder_size < MINSIZE) + { + set_inuse_bit_at_offset (victim, size); + if (av != &main_arena) + victim->size |= NON_MAIN_ARENA; + } + /* Split */ + else + { + remainder = chunk_at_offset (victim, nb); + /* We cannot assume the unsorted list is empty and therefore + have to perform a complete insert here. */ + bck = unsorted_chunks (av); + fwd = bck->fd; + if (__builtin_expect (fwd->bk != bck, 0)) + { + errstr = "malloc(): corrupted unsorted chunks"; + goto errout; + } + remainder->bk = bck; + remainder->fd = fwd; + bck->fd = remainder; + fwd->bk = remainder; + if (!in_smallbin_range (remainder_size)) + { + remainder->fd_nextsize = NULL; + remainder->bk_nextsize = NULL; + } + set_head (victim, nb | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE); + set_foot (remainder, remainder_size); + } + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + } - if (in_smallbin_range(nb) && - bck == unsorted_chunks(av) && - victim == av->last_remainder && - (unsigned long)(size) > (unsigned long)(nb + MINSIZE)) { - - /* split and reattach remainder */ - remainder_size = size - nb; - remainder = chunk_at_offset(victim, nb); - unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder; - av->last_remainder = remainder; - remainder->bk = remainder->fd = unsorted_chunks(av); - if (!in_smallbin_range(remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } - - set_head(victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } - - /* remove from unsorted list */ - unsorted_chunks(av)->bk = bck; - bck->fd = unsorted_chunks(av); - - /* Take now instead of binning if exact fit */ - - if (size == nb) { - set_inuse_bit_at_offset(victim, size); - if (av != &main_arena) - victim->size |= NON_MAIN_ARENA; - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } - - /* place chunk in bin */ - - if (in_smallbin_range(size)) { - victim_index = smallbin_index(size); - bck = bin_at(av, victim_index); - fwd = bck->fd; - } - else { - victim_index = largebin_index(size); - bck = bin_at(av, victim_index); - fwd = bck->fd; - - /* maintain large bins in sorted order */ - if (fwd != bck) { - /* Or with inuse bit to speed comparisons */ - size |= PREV_INUSE; - /* if smaller than smallest, bypass loop below */ - assert((bck->bk->size & NON_MAIN_ARENA) == 0); - if ((unsigned long)(size) < (unsigned long)(bck->bk->size)) { - fwd = bck; - bck = bck->bk; - - victim->fd_nextsize = fwd->fd; - victim->bk_nextsize = fwd->fd->bk_nextsize; - fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; - } - else { - assert((fwd->size & NON_MAIN_ARENA) == 0); - while ((unsigned long) size < fwd->size) - { - fwd = fwd->fd_nextsize; - assert((fwd->size & NON_MAIN_ARENA) == 0); - } - - if ((unsigned long) size == (unsigned long) fwd->size) - /* Always insert in the second position. */ - fwd = fwd->fd; - else - { - victim->fd_nextsize = fwd; - victim->bk_nextsize = fwd->bk_nextsize; - fwd->bk_nextsize = victim; - victim->bk_nextsize->fd_nextsize = victim; - } - bck = fwd->bk; - } - } else - victim->fd_nextsize = victim->bk_nextsize = victim; - } - - mark_bin(av, victim_index); - victim->bk = bck; - victim->fd = fwd; - fwd->bk = victim; - bck->fd = victim; - -#define MAX_ITERS 10000 - if (++iters >= MAX_ITERS) - break; - } - - /* - If a large request, scan through the chunks of current bin in - sorted order to find smallest that fits. Use the skip list for this. - */ - - if (!in_smallbin_range(nb)) { - bin = bin_at(av, idx); - - /* skip scan if empty or largest chunk is too small */ - if ((victim = first(bin)) != bin && - (unsigned long)(victim->size) >= (unsigned long)(nb)) { - - victim = victim->bk_nextsize; - while (((unsigned long)(size = chunksize(victim)) < - (unsigned long)(nb))) - victim = victim->bk_nextsize; - - /* Avoid removing the first entry for a size so that the skip - list does not have to be rerouted. */ - if (victim != last(bin) && victim->size == victim->fd->size) - victim = victim->fd; - - remainder_size = size - nb; - unlink(victim, bck, fwd); - - /* Exhaust */ - if (remainder_size < MINSIZE) { - set_inuse_bit_at_offset(victim, size); - if (av != &main_arena) - victim->size |= NON_MAIN_ARENA; - } - /* Split */ - else { - remainder = chunk_at_offset(victim, nb); - /* We cannot assume the unsorted list is empty and therefore - have to perform a complete insert here. */ - bck = unsorted_chunks(av); - fwd = bck->fd; - if (__builtin_expect (fwd->bk != bck, 0)) - { - errstr = "malloc(): corrupted unsorted chunks"; - goto errout; - } - remainder->bk = bck; - remainder->fd = fwd; - bck->fd = remainder; - fwd->bk = remainder; - if (!in_smallbin_range(remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } - set_head(victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - } - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } - } - - /* - Search for a chunk by scanning bins, starting with next largest - bin. This search is strictly by best-fit; i.e., the smallest - (with ties going to approximately the least recently used) chunk - that fits is selected. - - The bitmap avoids needing to check that most blocks are nonempty. - The particular case of skipping all bins during warm-up phases - when no chunks have been returned yet is faster than it might look. - */ - - ++idx; - bin = bin_at(av,idx); - block = idx2block(idx); - map = av->binmap[block]; - bit = idx2bit(idx); - - for (;;) { - - /* Skip rest of block if there are no more set bits in this block. */ - if (bit > map || bit == 0) { - do { - if (++block >= BINMAPSIZE) /* out of bins */ - goto use_top; - } while ( (map = av->binmap[block]) == 0); - - bin = bin_at(av, (block << BINMAPSHIFT)); - bit = 1; - } - - /* Advance to bin with set bit. There must be one. */ - while ((bit & map) == 0) { - bin = next_bin(bin); - bit <<= 1; - assert(bit != 0); - } - - /* Inspect the bin. It is likely to be non-empty */ - victim = last(bin); - - /* If a false alarm (empty bin), clear the bit. */ - if (victim == bin) { - av->binmap[block] = map &= ~bit; /* Write through */ - bin = next_bin(bin); - bit <<= 1; - } - - else { - size = chunksize(victim); - - /* We know the first chunk in this bin is big enough to use. */ - assert((unsigned long)(size) >= (unsigned long)(nb)); - - remainder_size = size - nb; - - /* unlink */ - unlink(victim, bck, fwd); - - /* Exhaust */ - if (remainder_size < MINSIZE) { - set_inuse_bit_at_offset(victim, size); - if (av != &main_arena) - victim->size |= NON_MAIN_ARENA; - } - - /* Split */ - else { - remainder = chunk_at_offset(victim, nb); - - /* We cannot assume the unsorted list is empty and therefore - have to perform a complete insert here. */ - bck = unsorted_chunks(av); - fwd = bck->fd; - if (__builtin_expect (fwd->bk != bck, 0)) - { - errstr = "malloc(): corrupted unsorted chunks 2"; - goto errout; - } - remainder->bk = bck; - remainder->fd = fwd; - bck->fd = remainder; - fwd->bk = remainder; - - /* advertise as last remainder */ - if (in_smallbin_range(nb)) - av->last_remainder = remainder; - if (!in_smallbin_range(remainder_size)) - { - remainder->fd_nextsize = NULL; - remainder->bk_nextsize = NULL; - } - set_head(victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE); - set_foot(remainder, remainder_size); - } - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } - } - - use_top: - /* - If large enough, split off the chunk bordering the end of memory - (held in av->top). Note that this is in accord with the best-fit - search rule. In effect, av->top is treated as larger (and thus - less well fitting) than any other available chunk since it can - be extended to be as large as necessary (up to system - limitations). - - We require that av->top always exists (i.e., has size >= - MINSIZE) after initialization, so if it would otherwise be - exhausted by current request, it is replenished. (The main - reason for ensuring it exists is that we may need MINSIZE space - to put in fenceposts in sysmalloc.) - */ - - victim = av->top; - size = chunksize(victim); - - if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(victim, nb); - av->top = remainder; - set_head(victim, nb | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE); - - check_malloced_chunk(av, victim, nb); - void *p = chunk2mem(victim); - alloc_perturb (p, bytes); - return p; - } + /* + Search for a chunk by scanning bins, starting with next largest + bin. This search is strictly by best-fit; i.e., the smallest + (with ties going to approximately the least recently used) chunk + that fits is selected. + + The bitmap avoids needing to check that most blocks are nonempty. + The particular case of skipping all bins during warm-up phases + when no chunks have been returned yet is faster than it might look. + */ + + ++idx; + bin = bin_at (av, idx); + block = idx2block (idx); + map = av->binmap[block]; + bit = idx2bit (idx); + + for (;; ) + { + /* Skip rest of block if there are no more set bits in this block. */ + if (bit > map || bit == 0) + { + do + { + if (++block >= BINMAPSIZE) /* out of bins */ + goto use_top; + } + while ((map = av->binmap[block]) == 0); + + bin = bin_at (av, (block << BINMAPSHIFT)); + bit = 1; + } + + /* Advance to bin with set bit. There must be one. */ + while ((bit & map) == 0) + { + bin = next_bin (bin); + bit <<= 1; + assert (bit != 0); + } + + /* Inspect the bin. It is likely to be non-empty */ + victim = last (bin); + + /* If a false alarm (empty bin), clear the bit. */ + if (victim == bin) + { + av->binmap[block] = map &= ~bit; /* Write through */ + bin = next_bin (bin); + bit <<= 1; + } + + else + { + size = chunksize (victim); + + /* We know the first chunk in this bin is big enough to use. */ + assert ((unsigned long) (size) >= (unsigned long) (nb)); + + remainder_size = size - nb; + + /* unlink */ + unlink (victim, bck, fwd); + + /* Exhaust */ + if (remainder_size < MINSIZE) + { + set_inuse_bit_at_offset (victim, size); + if (av != &main_arena) + victim->size |= NON_MAIN_ARENA; + } + + /* Split */ + else + { + remainder = chunk_at_offset (victim, nb); + + /* We cannot assume the unsorted list is empty and therefore + have to perform a complete insert here. */ + bck = unsorted_chunks (av); + fwd = bck->fd; + if (__builtin_expect (fwd->bk != bck, 0)) + { + errstr = "malloc(): corrupted unsorted chunks 2"; + goto errout; + } + remainder->bk = bck; + remainder->fd = fwd; + bck->fd = remainder; + fwd->bk = remainder; + + /* advertise as last remainder */ + if (in_smallbin_range (nb)) + av->last_remainder = remainder; + if (!in_smallbin_range (remainder_size)) + { + remainder->fd_nextsize = NULL; + remainder->bk_nextsize = NULL; + } + set_head (victim, nb | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE); + set_foot (remainder, remainder_size); + } + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + } + + use_top: + /* + If large enough, split off the chunk bordering the end of memory + (held in av->top). Note that this is in accord with the best-fit + search rule. In effect, av->top is treated as larger (and thus + less well fitting) than any other available chunk since it can + be extended to be as large as necessary (up to system + limitations). + + We require that av->top always exists (i.e., has size >= + MINSIZE) after initialization, so if it would otherwise be + exhausted by current request, it is replenished. (The main + reason for ensuring it exists is that we may need MINSIZE space + to put in fenceposts in sysmalloc.) + */ + + victim = av->top; + size = chunksize (victim); + + if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) + { + remainder_size = size - nb; + remainder = chunk_at_offset (victim, nb); + av->top = remainder; + set_head (victim, nb | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE); + + check_malloced_chunk (av, victim, nb); + void *p = chunk2mem (victim); + alloc_perturb (p, bytes); + return p; + } + + /* When we are using atomic ops to free fast chunks we can get + here for all block sizes. */ + else if (have_fastchunks (av)) + { + malloc_consolidate (av); + /* restore original bin index */ + if (in_smallbin_range (nb)) + idx = smallbin_index (nb); + else + idx = largebin_index (nb); + } - /* When we are using atomic ops to free fast chunks we can get - here for all block sizes. */ - else if (have_fastchunks(av)) { - malloc_consolidate(av); - /* restore original bin index */ - if (in_smallbin_range(nb)) - idx = smallbin_index(nb); + /* + Otherwise, relay to handle system-dependent cases + */ else - idx = largebin_index(nb); + { + void *p = sysmalloc (nb, av); + if (p != NULL) + alloc_perturb (p, bytes); + return p; + } } - - /* - Otherwise, relay to handle system-dependent cases - */ - else { - void *p = sysmalloc(nb, av); - if (p != NULL) - alloc_perturb (p, bytes); - return p; - } - } } /* - ------------------------------ free ------------------------------ -*/ + ------------------------------ free ------------------------------ + */ static void -_int_free(mstate av, mchunkptr p, int have_lock) +_int_free (mstate av, mchunkptr p, int have_lock) { INTERNAL_SIZE_T size; /* its size */ - mfastbinptr* fb; /* associated fastbin */ - mchunkptr nextchunk; /* next contiguous chunk */ + mfastbinptr *fb; /* associated fastbin */ + mchunkptr nextchunk; /* next contiguous chunk */ INTERNAL_SIZE_T nextsize; /* its size */ - int nextinuse; /* true if nextchunk is used */ + int nextinuse; /* true if nextchunk is used */ INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */ - mchunkptr bck; /* misc temp for linking */ - mchunkptr fwd; /* misc temp for linking */ + mchunkptr bck; /* misc temp for linking */ + mchunkptr fwd; /* misc temp for linking */ const char *errstr = NULL; int locked = 0; - size = chunksize(p); + size = chunksize (p); /* Little security check which won't hurt performance: the allocator never wrapps around at the end of the address space. @@ -3721,9 +3832,9 @@ _int_free(mstate av, mchunkptr p, int have_lock) { errstr = "free(): invalid pointer"; errout: - if (! have_lock && locked) - (void)mutex_unlock(&av->mutex); - malloc_printerr (check_action, errstr, chunk2mem(p)); + if (!have_lock && locked) + (void) mutex_unlock (&av->mutex); + malloc_printerr (check_action, errstr, chunk2mem (p)); return; } /* We know that each chunk is at least MINSIZE bytes in size or a @@ -4117,17 +4228,17 @@ _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize, { errstr = "realloc(): invalid old size"; errout: - malloc_printerr (check_action, errstr, chunk2mem(oldp)); + malloc_printerr (check_action, errstr, chunk2mem (oldp)); return NULL; } - check_inuse_chunk(av, oldp); + check_inuse_chunk (av, oldp); /* All callers already filter out mmap'ed chunks. */ - assert (!chunk_is_mmapped(oldp)); + assert (!chunk_is_mmapped (oldp)); - next = chunk_at_offset(oldp, oldsize); - INTERNAL_SIZE_T nextsize = chunksize(next); + next = chunk_at_offset (oldp, oldsize); + INTERNAL_SIZE_T nextsize = chunksize (next); if (__builtin_expect (next->size <= 2 * SIZE_SZ, 0) || __builtin_expect (nextsize >= av->system_mem, 0)) { @@ -4135,216 +4246,233 @@ _int_realloc(mstate av, mchunkptr oldp, INTERNAL_SIZE_T oldsize, goto errout; } - if ((unsigned long)(oldsize) >= (unsigned long)(nb)) { - /* already big enough; split below */ - newp = oldp; - newsize = oldsize; - } - - else { - /* Try to expand forward into top */ - if (next == av->top && - (unsigned long)(newsize = oldsize + nextsize) >= - (unsigned long)(nb + MINSIZE)) { - set_head_size(oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0)); - av->top = chunk_at_offset(oldp, nb); - set_head(av->top, (newsize - nb) | PREV_INUSE); - check_inuse_chunk(av, oldp); - return chunk2mem(oldp); - } - - /* Try to expand forward into next chunk; split off remainder below */ - else if (next != av->top && - !inuse(next) && - (unsigned long)(newsize = oldsize + nextsize) >= - (unsigned long)(nb)) { + if ((unsigned long) (oldsize) >= (unsigned long) (nb)) + { + /* already big enough; split below */ newp = oldp; - unlink(next, bck, fwd); + newsize = oldsize; } - /* allocate, copy, free */ - else { - newmem = _int_malloc(av, nb - MALLOC_ALIGN_MASK); - if (newmem == 0) - return 0; /* propagate failure */ - - newp = mem2chunk(newmem); - newsize = chunksize(newp); - - /* - Avoid copy if newp is next chunk after oldp. - */ - if (newp == next) { - newsize += oldsize; - newp = oldp; - } - else { - /* - Unroll copy of <= 36 bytes (72 if 8byte sizes) - We know that contents have an odd number of - INTERNAL_SIZE_T-sized words; minimally 3. - */ - - copysize = oldsize - SIZE_SZ; - s = (INTERNAL_SIZE_T*)(chunk2mem(oldp)); - d = (INTERNAL_SIZE_T*)(newmem); - ncopies = copysize / sizeof(INTERNAL_SIZE_T); - assert(ncopies >= 3); - - if (ncopies > 9) - memcpy(d, s, copysize); - - else { - *(d+0) = *(s+0); - *(d+1) = *(s+1); - *(d+2) = *(s+2); - if (ncopies > 4) { - *(d+3) = *(s+3); - *(d+4) = *(s+4); - if (ncopies > 6) { - *(d+5) = *(s+5); - *(d+6) = *(s+6); - if (ncopies > 8) { - *(d+7) = *(s+7); - *(d+8) = *(s+8); - } - } - } - } - - _int_free(av, oldp, 1); - check_inuse_chunk(av, newp); - return chunk2mem(newp); - } + else + { + /* Try to expand forward into top */ + if (next == av->top && + (unsigned long) (newsize = oldsize + nextsize) >= + (unsigned long) (nb + MINSIZE)) + { + set_head_size (oldp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0)); + av->top = chunk_at_offset (oldp, nb); + set_head (av->top, (newsize - nb) | PREV_INUSE); + check_inuse_chunk (av, oldp); + return chunk2mem (oldp); + } + + /* Try to expand forward into next chunk; split off remainder below */ + else if (next != av->top && + !inuse (next) && + (unsigned long) (newsize = oldsize + nextsize) >= + (unsigned long) (nb)) + { + newp = oldp; + unlink (next, bck, fwd); + } + + /* allocate, copy, free */ + else + { + newmem = _int_malloc (av, nb - MALLOC_ALIGN_MASK); + if (newmem == 0) + return 0; /* propagate failure */ + + newp = mem2chunk (newmem); + newsize = chunksize (newp); + + /* + Avoid copy if newp is next chunk after oldp. + */ + if (newp == next) + { + newsize += oldsize; + newp = oldp; + } + else + { + /* + Unroll copy of <= 36 bytes (72 if 8byte sizes) + We know that contents have an odd number of + INTERNAL_SIZE_T-sized words; minimally 3. + */ + + copysize = oldsize - SIZE_SZ; + s = (INTERNAL_SIZE_T *) (chunk2mem (oldp)); + d = (INTERNAL_SIZE_T *) (newmem); + ncopies = copysize / sizeof (INTERNAL_SIZE_T); + assert (ncopies >= 3); + + if (ncopies > 9) + memcpy (d, s, copysize); + + else + { + *(d + 0) = *(s + 0); + *(d + 1) = *(s + 1); + *(d + 2) = *(s + 2); + if (ncopies > 4) + { + *(d + 3) = *(s + 3); + *(d + 4) = *(s + 4); + if (ncopies > 6) + { + *(d + 5) = *(s + 5); + *(d + 6) = *(s + 6); + if (ncopies > 8) + { + *(d + 7) = *(s + 7); + *(d + 8) = *(s + 8); + } + } + } + } + + _int_free (av, oldp, 1); + check_inuse_chunk (av, newp); + return chunk2mem (newp); + } + } } - } /* If possible, free extra space in old or extended chunk */ - assert((unsigned long)(newsize) >= (unsigned long)(nb)); + assert ((unsigned long) (newsize) >= (unsigned long) (nb)); remainder_size = newsize - nb; - if (remainder_size < MINSIZE) { /* not enough extra to split off */ - set_head_size(newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_inuse_bit_at_offset(newp, newsize); - } - else { /* split remainder */ - remainder = chunk_at_offset(newp, nb); - set_head_size(newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head(remainder, remainder_size | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - /* Mark remainder as inuse so free() won't complain */ - set_inuse_bit_at_offset(remainder, remainder_size); - _int_free(av, remainder, 1); - } + if (remainder_size < MINSIZE) /* not enough extra to split off */ + { + set_head_size (newp, newsize | (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_inuse_bit_at_offset (newp, newsize); + } + else /* split remainder */ + { + remainder = chunk_at_offset (newp, nb); + set_head_size (newp, nb | (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head (remainder, remainder_size | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + /* Mark remainder as inuse so free() won't complain */ + set_inuse_bit_at_offset (remainder, remainder_size); + _int_free (av, remainder, 1); + } - check_inuse_chunk(av, newp); - return chunk2mem(newp); + check_inuse_chunk (av, newp); + return chunk2mem (newp); } /* - ------------------------------ memalign ------------------------------ -*/ + ------------------------------ memalign ------------------------------ + */ -static void* -_int_memalign(mstate av, size_t alignment, size_t bytes) +static void * +_int_memalign (mstate av, size_t alignment, size_t bytes) { INTERNAL_SIZE_T nb; /* padded request size */ - char* m; /* memory returned by malloc call */ - mchunkptr p; /* corresponding chunk */ - char* brk; /* alignment point within p */ - mchunkptr newp; /* chunk to return */ + char *m; /* memory returned by malloc call */ + mchunkptr p; /* corresponding chunk */ + char *brk; /* alignment point within p */ + mchunkptr newp; /* chunk to return */ INTERNAL_SIZE_T newsize; /* its size */ INTERNAL_SIZE_T leadsize; /* leading space before alignment point */ - mchunkptr remainder; /* spare room at end to split off */ - unsigned long remainder_size; /* its size */ + mchunkptr remainder; /* spare room at end to split off */ + unsigned long remainder_size; /* its size */ INTERNAL_SIZE_T size; - checked_request2size(bytes, nb); + checked_request2size (bytes, nb); /* - Strategy: find a spot within that chunk that meets the alignment - request, and then possibly free the leading and trailing space. - */ + Strategy: find a spot within that chunk that meets the alignment + request, and then possibly free the leading and trailing space. + */ /* Call malloc with worst case padding to hit alignment. */ - m = (char*)(_int_malloc(av, nb + alignment + MINSIZE)); - - if (m == 0) return 0; /* propagate failure */ - - p = mem2chunk(m); - - if ((((unsigned long)(m)) % alignment) != 0) { /* misaligned */ - - /* - Find an aligned spot inside chunk. Since we need to give back - leading space in a chunk of at least MINSIZE, if the first - calculation places us at a spot with less than MINSIZE leader, - we can move to the next aligned spot -- we've allocated enough - total room so that this is always possible. - */ - - brk = (char*)mem2chunk(((unsigned long)(m + alignment - 1)) & - -((signed long) alignment)); - if ((unsigned long)(brk - (char*)(p)) < MINSIZE) - brk += alignment; - - newp = (mchunkptr)brk; - leadsize = brk - (char*)(p); - newsize = chunksize(p) - leadsize; - - /* For mmapped chunks, just adjust offset */ - if (chunk_is_mmapped(p)) { - newp->prev_size = p->prev_size + leadsize; - set_head(newp, newsize|IS_MMAPPED); - return chunk2mem(newp); + m = (char *) (_int_malloc (av, nb + alignment + MINSIZE)); + + if (m == 0) + return 0; /* propagate failure */ + + p = mem2chunk (m); + + if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */ + + { /* + Find an aligned spot inside chunk. Since we need to give back + leading space in a chunk of at least MINSIZE, if the first + calculation places us at a spot with less than MINSIZE leader, + we can move to the next aligned spot -- we've allocated enough + total room so that this is always possible. + */ + brk = (char *) mem2chunk (((unsigned long) (m + alignment - 1)) & + - ((signed long) alignment)); + if ((unsigned long) (brk - (char *) (p)) < MINSIZE) + brk += alignment; + + newp = (mchunkptr) brk; + leadsize = brk - (char *) (p); + newsize = chunksize (p) - leadsize; + + /* For mmapped chunks, just adjust offset */ + if (chunk_is_mmapped (p)) + { + newp->prev_size = p->prev_size + leadsize; + set_head (newp, newsize | IS_MMAPPED); + return chunk2mem (newp); + } + + /* Otherwise, give back leader, use the rest */ + set_head (newp, newsize | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_inuse_bit_at_offset (newp, newsize); + set_head_size (p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0)); + _int_free (av, p, 1); + p = newp; + + assert (newsize >= nb && + (((unsigned long) (chunk2mem (p))) % alignment) == 0); } - /* Otherwise, give back leader, use the rest */ - set_head(newp, newsize | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_inuse_bit_at_offset(newp, newsize); - set_head_size(p, leadsize | (av != &main_arena ? NON_MAIN_ARENA : 0)); - _int_free(av, p, 1); - p = newp; - - assert (newsize >= nb && - (((unsigned long)(chunk2mem(p))) % alignment) == 0); - } - /* Also give back spare room at the end */ - if (!chunk_is_mmapped(p)) { - size = chunksize(p); - if ((unsigned long)(size) > (unsigned long)(nb + MINSIZE)) { - remainder_size = size - nb; - remainder = chunk_at_offset(p, nb); - set_head(remainder, remainder_size | PREV_INUSE | - (av != &main_arena ? NON_MAIN_ARENA : 0)); - set_head_size(p, nb); - _int_free(av, remainder, 1); + if (!chunk_is_mmapped (p)) + { + size = chunksize (p); + if ((unsigned long) (size) > (unsigned long) (nb + MINSIZE)) + { + remainder_size = size - nb; + remainder = chunk_at_offset (p, nb); + set_head (remainder, remainder_size | PREV_INUSE | + (av != &main_arena ? NON_MAIN_ARENA : 0)); + set_head_size (p, nb); + _int_free (av, remainder, 1); + } } - } - check_inuse_chunk(av, p); - return chunk2mem(p); + check_inuse_chunk (av, p); + return chunk2mem (p); } /* - ------------------------------ malloc_trim ------------------------------ -*/ + ------------------------------ malloc_trim ------------------------------ + */ -static int mtrim(mstate av, size_t pad) +static int +mtrim (mstate av, size_t pad) { /* Ensure initialization/consolidation */ malloc_consolidate (av); - const size_t ps = GLRO(dl_pagesize); + const size_t ps = GLRO (dl_pagesize); int psindex = bin_index (ps); const size_t psm1 = ps - 1; @@ -4352,42 +4480,43 @@ static int mtrim(mstate av, size_t pad) for (int i = 1; i < NBINS; ++i) if (i == 1 || i >= psindex) { - mbinptr bin = bin_at (av, i); + mbinptr bin = bin_at (av, i); - for (mchunkptr p = last (bin); p != bin; p = p->bk) - { - INTERNAL_SIZE_T size = chunksize (p); + for (mchunkptr p = last (bin); p != bin; p = p->bk) + { + INTERNAL_SIZE_T size = chunksize (p); - if (size > psm1 + sizeof (struct malloc_chunk)) - { - /* See whether the chunk contains at least one unused page. */ - char *paligned_mem = (char *) (((uintptr_t) p - + sizeof (struct malloc_chunk) - + psm1) & ~psm1); + if (size > psm1 + sizeof (struct malloc_chunk)) + { + /* See whether the chunk contains at least one unused page. */ + char *paligned_mem = (char *) (((uintptr_t) p + + sizeof (struct malloc_chunk) + + psm1) & ~psm1); - assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem); - assert ((char *) p + size > paligned_mem); + assert ((char *) chunk2mem (p) + 4 * SIZE_SZ <= paligned_mem); + assert ((char *) p + size > paligned_mem); - /* This is the size we could potentially free. */ - size -= paligned_mem - (char *) p; + /* This is the size we could potentially free. */ + size -= paligned_mem - (char *) p; - if (size > psm1) - { + if (size > psm1) + { #ifdef MALLOC_DEBUG - /* When debugging we simulate destroying the memory - content. */ - memset (paligned_mem, 0x89, size & ~psm1); + /* When debugging we simulate destroying the memory + content. */ + memset (paligned_mem, 0x89, size & ~psm1); #endif - __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED); + __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED); - result = 1; - } - } - } + result = 1; + } + } + } } #ifndef MORECORE_CANNOT_TRIM return result | (av == &main_arena ? systrim (pad, av) : 0); + #else return result; #endif @@ -4395,11 +4524,11 @@ static int mtrim(mstate av, size_t pad) int -__malloc_trim(size_t s) +__malloc_trim (size_t s) { int result = 0; - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); mstate ar_ptr = &main_arena; @@ -4418,43 +4547,45 @@ __malloc_trim(size_t s) /* - ------------------------- malloc_usable_size ------------------------- -*/ + ------------------------- malloc_usable_size ------------------------- + */ static size_t -musable(void* mem) +musable (void *mem) { mchunkptr p; - if (mem != 0) { - p = mem2chunk(mem); - - if (__builtin_expect(using_malloc_checking == 1, 0)) - return malloc_check_get_size(p); - if (chunk_is_mmapped(p)) - return chunksize(p) - 2*SIZE_SZ; - else if (inuse(p)) - return chunksize(p) - SIZE_SZ; - } + if (mem != 0) + { + p = mem2chunk (mem); + + if (__builtin_expect (using_malloc_checking == 1, 0)) + return malloc_check_get_size (p); + + if (chunk_is_mmapped (p)) + return chunksize (p) - 2 * SIZE_SZ; + else if (inuse (p)) + return chunksize (p) - SIZE_SZ; + } return 0; } size_t -__malloc_usable_size(void* m) +__malloc_usable_size (void *m) { size_t result; - result = musable(m); + result = musable (m); return result; } /* - ------------------------------ mallinfo ------------------------------ - Accumulate malloc statistics for arena AV into M. -*/ + ------------------------------ mallinfo ------------------------------ + Accumulate malloc statistics for arena AV into M. + */ static void -int_mallinfo(mstate av, struct mallinfo *m) +int_mallinfo (mstate av, struct mallinfo *m) { size_t i; mbinptr b; @@ -4465,35 +4596,40 @@ int_mallinfo(mstate av, struct mallinfo *m) int nfastblocks; /* Ensure initialization */ - if (av->top == 0) malloc_consolidate(av); + if (av->top == 0) + malloc_consolidate (av); - check_malloc_state(av); + check_malloc_state (av); /* Account for top */ - avail = chunksize(av->top); + avail = chunksize (av->top); nblocks = 1; /* top always exists */ /* traverse fastbins */ nfastblocks = 0; fastavail = 0; - for (i = 0; i < NFASTBINS; ++i) { - for (p = fastbin (av, i); p != 0; p = p->fd) { - ++nfastblocks; - fastavail += chunksize(p); + for (i = 0; i < NFASTBINS; ++i) + { + for (p = fastbin (av, i); p != 0; p = p->fd) + { + ++nfastblocks; + fastavail += chunksize (p); + } } - } avail += fastavail; /* traverse regular bins */ - for (i = 1; i < NBINS; ++i) { - b = bin_at(av, i); - for (p = last(b); p != b; p = p->bk) { - ++nblocks; - avail += chunksize(p); + for (i = 1; i < NBINS; ++i) + { + b = bin_at (av, i); + for (p = last (b); p != b; p = p->bk) + { + ++nblocks; + avail += chunksize (p); + } } - } m->smblks += nfastblocks; m->ordblks += nblocks; @@ -4506,35 +4642,38 @@ int_mallinfo(mstate av, struct mallinfo *m) m->hblks = mp_.n_mmaps; m->hblkhd = mp_.mmapped_mem; m->usmblks = mp_.max_total_mem; - m->keepcost = chunksize(av->top); + m->keepcost = chunksize (av->top); } } -struct mallinfo __libc_mallinfo() +struct mallinfo +__libc_mallinfo () { struct mallinfo m; mstate ar_ptr; - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); - memset(&m, 0, sizeof (m)); + memset (&m, 0, sizeof (m)); ar_ptr = &main_arena; - do { - (void)mutex_lock(&ar_ptr->mutex); - int_mallinfo(ar_ptr, &m); - (void)mutex_unlock(&ar_ptr->mutex); + do + { + (void) mutex_lock (&ar_ptr->mutex); + int_mallinfo (ar_ptr, &m); + (void) mutex_unlock (&ar_ptr->mutex); - ar_ptr = ar_ptr->next; - } while (ar_ptr != &main_arena); + ar_ptr = ar_ptr->next; + } + while (ar_ptr != &main_arena); return m; } /* - ------------------------------ malloc_stats ------------------------------ -*/ + ------------------------------ malloc_stats ------------------------------ + */ void __malloc_stats (void) @@ -4546,48 +4685,50 @@ __malloc_stats (void) long stat_lock_direct = 0, stat_lock_loop = 0, stat_lock_wait = 0; #endif - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); _IO_flockfile (stderr); int old_flags2 = ((_IO_FILE *) stderr)->_flags2; ((_IO_FILE *) stderr)->_flags2 |= _IO_FLAGS2_NOTCANCEL; - for (i=0, ar_ptr = &main_arena;; i++) { - struct mallinfo mi; - - memset(&mi, 0, sizeof(mi)); - (void)mutex_lock(&ar_ptr->mutex); - int_mallinfo(ar_ptr, &mi); - fprintf(stderr, "Arena %d:\n", i); - fprintf(stderr, "system bytes = %10u\n", (unsigned int)mi.arena); - fprintf(stderr, "in use bytes = %10u\n", (unsigned int)mi.uordblks); + for (i = 0, ar_ptr = &main_arena;; i++) + { + struct mallinfo mi; + + memset (&mi, 0, sizeof (mi)); + (void) mutex_lock (&ar_ptr->mutex); + int_mallinfo (ar_ptr, &mi); + fprintf (stderr, "Arena %d:\n", i); + fprintf (stderr, "system bytes = %10u\n", (unsigned int) mi.arena); + fprintf (stderr, "in use bytes = %10u\n", (unsigned int) mi.uordblks); #if MALLOC_DEBUG > 1 - if (i > 0) - dump_heap(heap_for_ptr(top(ar_ptr))); + if (i > 0) + dump_heap (heap_for_ptr (top (ar_ptr))); #endif - system_b += mi.arena; - in_use_b += mi.uordblks; + system_b += mi.arena; + in_use_b += mi.uordblks; #if THREAD_STATS - stat_lock_direct += ar_ptr->stat_lock_direct; - stat_lock_loop += ar_ptr->stat_lock_loop; - stat_lock_wait += ar_ptr->stat_lock_wait; + stat_lock_direct += ar_ptr->stat_lock_direct; + stat_lock_loop += ar_ptr->stat_lock_loop; + stat_lock_wait += ar_ptr->stat_lock_wait; #endif - (void)mutex_unlock(&ar_ptr->mutex); - ar_ptr = ar_ptr->next; - if(ar_ptr == &main_arena) break; - } - fprintf(stderr, "Total (incl. mmap):\n"); - fprintf(stderr, "system bytes = %10u\n", system_b); - fprintf(stderr, "in use bytes = %10u\n", in_use_b); - fprintf(stderr, "max mmap regions = %10u\n", (unsigned int)mp_.max_n_mmaps); - fprintf(stderr, "max mmap bytes = %10lu\n", - (unsigned long)mp_.max_mmapped_mem); + (void) mutex_unlock (&ar_ptr->mutex); + ar_ptr = ar_ptr->next; + if (ar_ptr == &main_arena) + break; + } + fprintf (stderr, "Total (incl. mmap):\n"); + fprintf (stderr, "system bytes = %10u\n", system_b); + fprintf (stderr, "in use bytes = %10u\n", in_use_b); + fprintf (stderr, "max mmap regions = %10u\n", (unsigned int) mp_.max_n_mmaps); + fprintf (stderr, "max mmap bytes = %10lu\n", + (unsigned long) mp_.max_mmapped_mem); #if THREAD_STATS - fprintf(stderr, "heaps created = %10d\n", stat_n_heaps); - fprintf(stderr, "locked directly = %10ld\n", stat_lock_direct); - fprintf(stderr, "locked in loop = %10ld\n", stat_lock_loop); - fprintf(stderr, "locked waiting = %10ld\n", stat_lock_wait); - fprintf(stderr, "locked total = %10ld\n", - stat_lock_direct + stat_lock_loop + stat_lock_wait); + fprintf (stderr, "heaps created = %10d\n", stat_n_heaps); + fprintf (stderr, "locked directly = %10ld\n", stat_lock_direct); + fprintf (stderr, "locked in loop = %10ld\n", stat_lock_loop); + fprintf (stderr, "locked waiting = %10ld\n", stat_lock_wait); + fprintf (stderr, "locked total = %10ld\n", + stat_lock_direct + stat_lock_loop + stat_lock_wait); #endif ((_IO_FILE *) stderr)->_flags2 |= old_flags2; _IO_funlockfile (stderr); @@ -4595,201 +4736,203 @@ __malloc_stats (void) /* - ------------------------------ mallopt ------------------------------ -*/ + ------------------------------ mallopt ------------------------------ + */ -int __libc_mallopt(int param_number, int value) +int +__libc_mallopt (int param_number, int value) { mstate av = &main_arena; int res = 1; - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); - (void)mutex_lock(&av->mutex); + (void) mutex_lock (&av->mutex); /* Ensure initialization/consolidation */ - malloc_consolidate(av); + malloc_consolidate (av); LIBC_PROBE (memory_mallopt, 2, param_number, value); - switch(param_number) { - case M_MXFAST: - if (value >= 0 && value <= MAX_FAST_SIZE) - { - LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ()); - set_max_fast(value); - } - else - res = 0; - break; - - case M_TRIM_THRESHOLD: - LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, - mp_.trim_threshold, mp_.no_dyn_threshold); - mp_.trim_threshold = value; - mp_.no_dyn_threshold = 1; - break; - - case M_TOP_PAD: - LIBC_PROBE (memory_mallopt_top_pad, 3, value, - mp_.top_pad, mp_.no_dyn_threshold); - mp_.top_pad = value; - mp_.no_dyn_threshold = 1; - break; - - case M_MMAP_THRESHOLD: - /* Forbid setting the threshold too high. */ - if((unsigned long)value > HEAP_MAX_SIZE/2) - res = 0; - else - { - LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, - mp_.mmap_threshold, mp_.no_dyn_threshold); - mp_.mmap_threshold = value; - mp_.no_dyn_threshold = 1; - } - break; - - case M_MMAP_MAX: - LIBC_PROBE (memory_mallopt_mmap_max, 3, value, - mp_.n_mmaps_max, mp_.no_dyn_threshold); - mp_.n_mmaps_max = value; - mp_.no_dyn_threshold = 1; - break; - - case M_CHECK_ACTION: - LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action); - check_action = value; - break; - - case M_PERTURB: - LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte); - perturb_byte = value; - break; - - case M_ARENA_TEST: - if (value > 0) - { - LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test); - mp_.arena_test = value; - } - break; - - case M_ARENA_MAX: - if (value > 0) - { - LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max); - mp_.arena_max = value; - } - break; - } - (void)mutex_unlock(&av->mutex); + switch (param_number) + { + case M_MXFAST: + if (value >= 0 && value <= MAX_FAST_SIZE) + { + LIBC_PROBE (memory_mallopt_mxfast, 2, value, get_max_fast ()); + set_max_fast (value); + } + else + res = 0; + break; + + case M_TRIM_THRESHOLD: + LIBC_PROBE (memory_mallopt_trim_threshold, 3, value, + mp_.trim_threshold, mp_.no_dyn_threshold); + mp_.trim_threshold = value; + mp_.no_dyn_threshold = 1; + break; + + case M_TOP_PAD: + LIBC_PROBE (memory_mallopt_top_pad, 3, value, + mp_.top_pad, mp_.no_dyn_threshold); + mp_.top_pad = value; + mp_.no_dyn_threshold = 1; + break; + + case M_MMAP_THRESHOLD: + /* Forbid setting the threshold too high. */ + if ((unsigned long) value > HEAP_MAX_SIZE / 2) + res = 0; + else + { + LIBC_PROBE (memory_mallopt_mmap_threshold, 3, value, + mp_.mmap_threshold, mp_.no_dyn_threshold); + mp_.mmap_threshold = value; + mp_.no_dyn_threshold = 1; + } + break; + + case M_MMAP_MAX: + LIBC_PROBE (memory_mallopt_mmap_max, 3, value, + mp_.n_mmaps_max, mp_.no_dyn_threshold); + mp_.n_mmaps_max = value; + mp_.no_dyn_threshold = 1; + break; + + case M_CHECK_ACTION: + LIBC_PROBE (memory_mallopt_check_action, 2, value, check_action); + check_action = value; + break; + + case M_PERTURB: + LIBC_PROBE (memory_mallopt_perturb, 2, value, perturb_byte); + perturb_byte = value; + break; + + case M_ARENA_TEST: + if (value > 0) + { + LIBC_PROBE (memory_mallopt_arena_test, 2, value, mp_.arena_test); + mp_.arena_test = value; + } + break; + + case M_ARENA_MAX: + if (value > 0) + { + LIBC_PROBE (memory_mallopt_arena_max, 2, value, mp_.arena_max); + mp_.arena_max = value; + } + break; + } + (void) mutex_unlock (&av->mutex); return res; } libc_hidden_def (__libc_mallopt) /* - -------------------- Alternative MORECORE functions -------------------- -*/ + -------------------- Alternative MORECORE functions -------------------- + */ /* - General Requirements for MORECORE. + General Requirements for MORECORE. - The MORECORE function must have the following properties: + The MORECORE function must have the following properties: - If MORECORE_CONTIGUOUS is false: + If MORECORE_CONTIGUOUS is false: - * MORECORE must allocate in multiples of pagesize. It will + * MORECORE must allocate in multiples of pagesize. It will only be called with arguments that are multiples of pagesize. - * MORECORE(0) must return an address that is at least + * MORECORE(0) must return an address that is at least MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.) - else (i.e. If MORECORE_CONTIGUOUS is true): + else (i.e. If MORECORE_CONTIGUOUS is true): - * Consecutive calls to MORECORE with positive arguments + * Consecutive calls to MORECORE with positive arguments return increasing addresses, indicating that space has been contiguously extended. - * MORECORE need not allocate in multiples of pagesize. + * MORECORE need not allocate in multiples of pagesize. Calls to MORECORE need not have args of multiples of pagesize. - * MORECORE need not page-align. + * MORECORE need not page-align. - In either case: + In either case: - * MORECORE may allocate more memory than requested. (Or even less, + * MORECORE may allocate more memory than requested. (Or even less, but this will generally result in a malloc failure.) - * MORECORE must not allocate memory when given argument zero, but + * MORECORE must not allocate memory when given argument zero, but instead return one past the end address of memory from previous nonzero call. This malloc does NOT call MORECORE(0) until at least one call with positive arguments is made, so the initial value returned is not important. - * Even though consecutive calls to MORECORE need not return contiguous + * Even though consecutive calls to MORECORE need not return contiguous addresses, it must be OK for malloc'ed chunks to span multiple regions in those cases where they do happen to be contiguous. - * MORECORE need not handle negative arguments -- it may instead + * MORECORE need not handle negative arguments -- it may instead just return MORECORE_FAILURE when given negative arguments. Negative arguments are always multiples of pagesize. MORECORE must not misinterpret negative args as large positive unsigned args. You can suppress all such calls from even occurring by defining MORECORE_CANNOT_TRIM, - There is some variation across systems about the type of the - argument to sbrk/MORECORE. If size_t is unsigned, then it cannot - actually be size_t, because sbrk supports negative args, so it is - normally the signed type of the same width as size_t (sometimes - declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much - matter though. Internally, we use "long" as arguments, which should - work across all reasonable possibilities. - - Additionally, if MORECORE ever returns failure for a positive - request, then mmap is used as a noncontiguous system allocator. This - is a useful backup strategy for systems with holes in address spaces - -- in this case sbrk cannot contiguously expand the heap, but mmap - may be able to map noncontiguous space. - - If you'd like mmap to ALWAYS be used, you can define MORECORE to be - a function that always returns MORECORE_FAILURE. - - If you are using this malloc with something other than sbrk (or its - emulation) to supply memory regions, you probably want to set - MORECORE_CONTIGUOUS as false. As an example, here is a custom - allocator kindly contributed for pre-OSX macOS. It uses virtually - but not necessarily physically contiguous non-paged memory (locked - in, present and won't get swapped out). You can use it by - uncommenting this section, adding some #includes, and setting up the - appropriate defines above: - - #define MORECORE osMoreCore - #define MORECORE_CONTIGUOUS 0 - - There is also a shutdown routine that should somehow be called for - cleanup upon program exit. - - #define MAX_POOL_ENTRIES 100 - #define MINIMUM_MORECORE_SIZE (64 * 1024) - static int next_os_pool; - void *our_os_pools[MAX_POOL_ENTRIES]; - - void *osMoreCore(int size) - { + There is some variation across systems about the type of the + argument to sbrk/MORECORE. If size_t is unsigned, then it cannot + actually be size_t, because sbrk supports negative args, so it is + normally the signed type of the same width as size_t (sometimes + declared as "intptr_t", and sometimes "ptrdiff_t"). It doesn't much + matter though. Internally, we use "long" as arguments, which should + work across all reasonable possibilities. + + Additionally, if MORECORE ever returns failure for a positive + request, then mmap is used as a noncontiguous system allocator. This + is a useful backup strategy for systems with holes in address spaces + -- in this case sbrk cannot contiguously expand the heap, but mmap + may be able to map noncontiguous space. + + If you'd like mmap to ALWAYS be used, you can define MORECORE to be + a function that always returns MORECORE_FAILURE. + + If you are using this malloc with something other than sbrk (or its + emulation) to supply memory regions, you probably want to set + MORECORE_CONTIGUOUS as false. As an example, here is a custom + allocator kindly contributed for pre-OSX macOS. It uses virtually + but not necessarily physically contiguous non-paged memory (locked + in, present and won't get swapped out). You can use it by + uncommenting this section, adding some #includes, and setting up the + appropriate defines above: + + *#define MORECORE osMoreCore + *#define MORECORE_CONTIGUOUS 0 + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + *#define MAX_POOL_ENTRIES 100 + *#define MINIMUM_MORECORE_SIZE (64 * 1024) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { void *ptr = 0; static void *sbrk_top = 0; if (size > 0) { if (size < MINIMUM_MORECORE_SIZE) - size = MINIMUM_MORECORE_SIZE; + size = MINIMUM_MORECORE_SIZE; if (CurrentExecutionLevel() == kTaskLevel) - ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); if (ptr == 0) { - return (void *) MORECORE_FAILURE; + return (void *) MORECORE_FAILURE; } // save ptrs so they can be freed during cleanup our_os_pools[next_os_pool] = ptr; @@ -4807,24 +4950,24 @@ libc_hidden_def (__libc_mallopt) { return sbrk_top; } - } + } - // cleanup any allocated memory pools - // called as last thing before shutting down driver + // cleanup any allocated memory pools + // called as last thing before shutting down driver - void osCleanupMem(void) - { + void osCleanupMem(void) + { void **ptr; for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) if (*ptr) { - PoolDeallocate(*ptr); - *ptr = 0; + PoolDeallocate(*ptr); + * ptr = 0; } - } + } -*/ + */ /* Helper code. */ @@ -4832,7 +4975,7 @@ libc_hidden_def (__libc_mallopt) extern char **__libc_argv attribute_hidden; static void -malloc_printerr(int action, const char *str, void *ptr) +malloc_printerr (int action, const char *str, void *ptr) { if ((action & 5) == 5) __libc_message (action & 2, "%s\n", str); @@ -4843,10 +4986,10 @@ malloc_printerr(int action, const char *str, void *ptr) buf[sizeof (buf) - 1] = '\0'; char *cp = _itoa_word ((uintptr_t) ptr, &buf[sizeof (buf) - 1], 16, 0); while (cp > buf) - *--cp = '0'; + *--cp = '0'; __libc_message (action & 2, "*** Error in `%s': %s: 0x%s ***\n", - __libc_argv[0] ?: "<unknown>", str, cp); + __libc_argv[0] ? : "<unknown>", str, cp); } else if (action & 2) abort (); @@ -4869,10 +5012,11 @@ __posix_memalign (void **memptr, size_t alignment, size_t size) void *address = RETURN_ADDRESS (0); mem = _mid_memalign (alignment, size, address); - if (mem != NULL) { - *memptr = mem; - return 0; - } + if (mem != NULL) + { + *memptr = mem; + return 0; + } return ENOMEM; } @@ -4896,7 +5040,8 @@ malloc_info (int options, FILE *fp) size_t total_aspace = 0; size_t total_aspace_mprotect = 0; - void mi_arena (mstate ar_ptr) + void + mi_arena (mstate ar_ptr) { fprintf (fp, "<heap nr=\"%d\">\n<sizes>\n", n++); @@ -4917,28 +5062,28 @@ malloc_info (int options, FILE *fp) for (size_t i = 0; i < NFASTBINS; ++i) { - mchunkptr p = fastbin (ar_ptr, i); - if (p != NULL) - { - size_t nthissize = 0; - size_t thissize = chunksize (p); - - while (p != NULL) - { - ++nthissize; - p = p->fd; - } - - fastavail += nthissize * thissize; - nfastblocks += nthissize; - sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1); - sizes[i].to = thissize; - sizes[i].count = nthissize; - } - else - sizes[i].from = sizes[i].to = sizes[i].count = 0; - - sizes[i].total = sizes[i].count * sizes[i].to; + mchunkptr p = fastbin (ar_ptr, i); + if (p != NULL) + { + size_t nthissize = 0; + size_t thissize = chunksize (p); + + while (p != NULL) + { + ++nthissize; + p = p->fd; + } + + fastavail += nthissize * thissize; + nfastblocks += nthissize; + sizes[i].from = thissize - (MALLOC_ALIGNMENT - 1); + sizes[i].to = thissize; + sizes[i].count = nthissize; + } + else + sizes[i].from = sizes[i].to = sizes[i].count = 0; + + sizes[i].total = sizes[i].count * sizes[i].to; } @@ -4947,29 +5092,29 @@ malloc_info (int options, FILE *fp) for (size_t i = 1; i < NBINS; ++i) { - bin = bin_at (ar_ptr, i); - r = bin->fd; - sizes[NFASTBINS - 1 + i].from = ~((size_t) 0); - sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total - = sizes[NFASTBINS - 1 + i].count = 0; - - if (r != NULL) - while (r != bin) - { - ++sizes[NFASTBINS - 1 + i].count; - sizes[NFASTBINS - 1 + i].total += r->size; - sizes[NFASTBINS - 1 + i].from - = MIN (sizes[NFASTBINS - 1 + i].from, r->size); - sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to, - r->size); - - r = r->fd; - } - - if (sizes[NFASTBINS - 1 + i].count == 0) - sizes[NFASTBINS - 1 + i].from = 0; - nblocks += sizes[NFASTBINS - 1 + i].count; - avail += sizes[NFASTBINS - 1 + i].total; + bin = bin_at (ar_ptr, i); + r = bin->fd; + sizes[NFASTBINS - 1 + i].from = ~((size_t) 0); + sizes[NFASTBINS - 1 + i].to = sizes[NFASTBINS - 1 + i].total + = sizes[NFASTBINS - 1 + i].count = 0; + + if (r != NULL) + while (r != bin) + { + ++sizes[NFASTBINS - 1 + i].count; + sizes[NFASTBINS - 1 + i].total += r->size; + sizes[NFASTBINS - 1 + i].from + = MIN (sizes[NFASTBINS - 1 + i].from, r->size); + sizes[NFASTBINS - 1 + i].to = MAX (sizes[NFASTBINS - 1 + i].to, + r->size); + + r = r->fd; + } + + if (sizes[NFASTBINS - 1 + i].count == 0) + sizes[NFASTBINS - 1 + i].from = 0; + nblocks += sizes[NFASTBINS - 1 + i].count; + avail += sizes[NFASTBINS - 1 + i].total; } mutex_unlock (&ar_ptr->mutex); @@ -4982,51 +5127,51 @@ malloc_info (int options, FILE *fp) for (size_t i = 0; i < nsizes; ++i) if (sizes[i].count != 0 && i != NFASTBINS) - fprintf (fp, "\ + fprintf (fp, " \ <size from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n", - sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count); + sizes[i].from, sizes[i].to, sizes[i].total, sizes[i].count); if (sizes[NFASTBINS].count != 0) fprintf (fp, "\ <unsorted from=\"%zu\" to=\"%zu\" total=\"%zu\" count=\"%zu\"/>\n", - sizes[NFASTBINS].from, sizes[NFASTBINS].to, - sizes[NFASTBINS].total, sizes[NFASTBINS].count); + sizes[NFASTBINS].from, sizes[NFASTBINS].to, + sizes[NFASTBINS].total, sizes[NFASTBINS].count); total_system += ar_ptr->system_mem; total_max_system += ar_ptr->max_system_mem; fprintf (fp, - "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n" - "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n" - "<system type=\"current\" size=\"%zu\"/>\n" - "<system type=\"max\" size=\"%zu\"/>\n", - nfastblocks, fastavail, nblocks, avail, - ar_ptr->system_mem, ar_ptr->max_system_mem); + "</sizes>\n<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n" + "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n" + "<system type=\"current\" size=\"%zu\"/>\n" + "<system type=\"max\" size=\"%zu\"/>\n", + nfastblocks, fastavail, nblocks, avail, + ar_ptr->system_mem, ar_ptr->max_system_mem); if (ar_ptr != &main_arena) { - heap_info *heap = heap_for_ptr(top(ar_ptr)); - fprintf (fp, - "<aspace type=\"total\" size=\"%zu\"/>\n" - "<aspace type=\"mprotect\" size=\"%zu\"/>\n", - heap->size, heap->mprotect_size); - total_aspace += heap->size; - total_aspace_mprotect += heap->mprotect_size; + heap_info *heap = heap_for_ptr (top (ar_ptr)); + fprintf (fp, + "<aspace type=\"total\" size=\"%zu\"/>\n" + "<aspace type=\"mprotect\" size=\"%zu\"/>\n", + heap->size, heap->mprotect_size); + total_aspace += heap->size; + total_aspace_mprotect += heap->mprotect_size; } else { - fprintf (fp, - "<aspace type=\"total\" size=\"%zu\"/>\n" - "<aspace type=\"mprotect\" size=\"%zu\"/>\n", - ar_ptr->system_mem, ar_ptr->system_mem); - total_aspace += ar_ptr->system_mem; - total_aspace_mprotect += ar_ptr->system_mem; + fprintf (fp, + "<aspace type=\"total\" size=\"%zu\"/>\n" + "<aspace type=\"mprotect\" size=\"%zu\"/>\n", + ar_ptr->system_mem, ar_ptr->system_mem); + total_aspace += ar_ptr->system_mem; + total_aspace_mprotect += ar_ptr->system_mem; } fputs ("</heap>\n", fp); } - if(__malloc_initialized < 0) + if (__malloc_initialized < 0) ptmalloc_init (); fputs ("<malloc version=\"1\">\n", fp); @@ -5041,16 +5186,16 @@ malloc_info (int options, FILE *fp) while (ar_ptr != &main_arena); fprintf (fp, - "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n" - "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n" - "<system type=\"current\" size=\"%zu\"/>\n" - "<system type=\"max\" size=\"%zu\"/>\n" - "<aspace type=\"total\" size=\"%zu\"/>\n" - "<aspace type=\"mprotect\" size=\"%zu\"/>\n" - "</malloc>\n", - total_nfastblocks, total_fastavail, total_nblocks, total_avail, - total_system, total_max_system, - total_aspace, total_aspace_mprotect); + "<total type=\"fast\" count=\"%zu\" size=\"%zu\"/>\n" + "<total type=\"rest\" count=\"%zu\" size=\"%zu\"/>\n" + "<system type=\"current\" size=\"%zu\"/>\n" + "<system type=\"max\" size=\"%zu\"/>\n" + "<aspace type=\"total\" size=\"%zu\"/>\n" + "<aspace type=\"mprotect\" size=\"%zu\"/>\n" + "</malloc>\n", + total_nfastblocks, total_fastavail, total_nblocks, total_avail, + total_system, total_max_system, + total_aspace, total_aspace_mprotect); return 0; } @@ -5077,11 +5222,11 @@ weak_alias (__malloc_set_state, malloc_set_state) /* ------------------------------------------------------------ -History: + History: -[see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc] + [see ftp://g.oswego.edu/pub/misc/malloc.c for the history of dlmalloc] -*/ + */ /* * Local variables: * c-basic-offset: 2 |