📄 malloc.c
字号:
/* malloc.c - dynamic memory allocation for bash. *//* Copyright (C) 1985-2005 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne-Again SHell. Bash is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bash is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Bash. If not, see <http://www.gnu.org/licenses/>.*//* * @(#)nmalloc.c 1 (Caltech) 2/21/82 * * U of M Modified: 20 Jun 1983 ACT: strange hacks for Emacs * * Nov 1983, Mike@BRL, Added support for 4.1C/4.2 BSD. * * This is a very fast storage allocator. It allocates blocks of a small * number of different sizes, and keeps free lists of each size. Blocks * that don't exactly fit are passed up to the next larger size. In this * implementation, the available sizes are (2^n)-4 (or -16) bytes long. * This is designed for use in a program that uses vast quantities of * memory, but bombs when it runs out. To make it a little better, it * warns the user when he starts to get near the end. * * June 84, ACT: modified rcheck code to check the range given to malloc, * rather than the range determined by the 2-power used. * * Jan 85, RMS: calls malloc_warning to issue warning on nearly full. * No longer Emacs-specific; can serve as all-purpose malloc for GNU. * You should call malloc_init to reinitialize after loading dumped Emacs. * Call malloc_stats to get info on memory stats if MALLOC_STATS turned on. * realloc knows how to return same block given, just changing its size, * if the power of 2 is correct. *//* * nextf[i] is the pointer to the next free block of size 2^(i+3). The * smallest allocatable block is 8 bytes. The overhead information will * go in the first int of the block, and the returned pointer will point * to the second. *//* Define MEMSCRAMBLE to have free() write 0xcf into memory as it's freed, to uncover callers that refer to freed memory, and to have malloc() write 0xdf into memory as it's allocated to avoid referring to previous contents. *//* SCO 3.2v4 getcwd and possibly other libc routines fail with MEMSCRAMBLE; handled by configure. */#if defined (HAVE_CONFIG_H)# include <config.h>#endif /* HAVE_CONFIG_H */#if defined (SHELL)# include "bashtypes.h"# include "stdc.h"#else# include <sys/types.h>#endif#if defined (HAVE_UNISTD_H)# include <unistd.h>#endif/* Determine which kind of system this is. */#include <signal.h>#if defined (HAVE_STRING_H)# include <string.h>#else# include <strings.h>#endif#include <stdio.h>/* Define getpagesize () if the system does not. */#ifndef HAVE_GETPAGESIZE# include "getpagesize.h"#endif#include "imalloc.h"#ifdef MALLOC_STATS# include "mstats.h"#endif#ifdef MALLOC_REGISTER# include "table.h"#endif#ifdef MALLOC_WATCH# include "watch.h"#endif/* System-specific omissions. */#ifdef HPUX# define NO_VALLOC#endif#define NBUCKETS 30#define ISALLOC ((char) 0xf7) /* magic byte that implies allocation */#define ISFREE ((char) 0x54) /* magic byte that implies free block */ /* this is for error checking only */#define ISMEMALIGN ((char) 0xd6) /* Stored before the value returned by memalign, with the rest of the word being the distance to the true beginning of the block. *//* We have a flag indicating whether memory is allocated, an index in nextf[], a size field, and a sentinel value to determine whether or not a caller wrote before the start of allocated memory; to realloc() memory we either copy mh_nbytes or just change mh_nbytes if there is enough room in the block for the new size. Range checking is always done. */union mhead { bits64_t mh_align; /* 8 */ struct { char mi_alloc; /* ISALLOC or ISFREE */ /* 1 */ char mi_index; /* index in nextf[] */ /* 1 */ /* Remainder are valid only when block is allocated */ u_bits16_t mi_magic2; /* should be == MAGIC2 */ /* 2 */ u_bits32_t mi_nbytes; /* # of bytes allocated */ /* 4 */ } minfo;};#define mh_alloc minfo.mi_alloc#define mh_index minfo.mi_index#define mh_nbytes minfo.mi_nbytes#define mh_magic2 minfo.mi_magic2#define MOVERHEAD sizeof(union mhead)#define MALIGN_MASK 7 /* one less than desired alignment */typedef union _malloc_guard { char s[4]; u_bits32_t i;} mguard_t;/* Access free-list pointer of a block. It is stored at block + sizeof (char *). This is not a field in the minfo structure member of union mhead because we want sizeof (union mhead) to describe the overhead for when the block is in use, and we do not want the free-list pointer to count in that. */#define CHAIN(a) \ (*(union mhead **) (sizeof (char *) + (char *) (a)))/* To implement range checking, we write magic values in at the beginning and end of each allocated block, and make sure they are undisturbed whenever a free or a realloc occurs. *//* Written in the 2 bytes before the block's real space (-4 bytes) */#define MAGIC2 0x5555#define MSLOP 4 /* 4 bytes extra for u_bits32_t size *//* How many bytes are actually allocated for a request of size N -- rounded up to nearest multiple of 8 after accounting for malloc overhead. */#define ALLOCATED_BYTES(n) \ (((n) + MOVERHEAD + MSLOP + MALIGN_MASK) & ~MALIGN_MASK)#define ASSERT(p) \ do \ { \ if (!(p)) xbotch((PTR_T)0, ERR_ASSERT_FAILED, __STRING(p), file, line); \ } \ while (0)/* Minimum and maximum bucket indices for block splitting (and to bound the search for a block to split). */#define SPLIT_MIN 2 /* XXX - was 3 */#define SPLIT_MID 11#define SPLIT_MAX 14/* Minimum and maximum bucket indices for block coalescing. */#define COMBINE_MIN 2#define COMBINE_MAX (pagebucket - 1) /* XXX */#define LESSCORE_MIN 10#define LESSCORE_FRC 13#define STARTBUCK 1/* Flags for the internal functions. */#define MALLOC_WRAPPER 0x01 /* wrapper function */#define MALLOC_INTERNAL 0x02 /* internal function calling another */#define MALLOC_NOTRACE 0x04 /* don't trace this allocation or free */#define MALLOC_NOREG 0x08 /* don't register this allocation or free *//* Future use. */#define ERR_DUPFREE 0x01#define ERR_UNALLOC 0x02#define ERR_UNDERFLOW 0x04 #define ERR_ASSERT_FAILED 0x08/* Evaluates to true if NB is appropriate for bucket NU. NB is adjusted appropriately by the caller to account for malloc overhead. This only checks that the recorded size is not too big for the bucket. We can't check whether or not it's in between NU and NU-1 because we might have encountered a busy bucket when allocating and moved up to the next size. */#define IN_BUCKET(nb, nu) ((nb) <= binsizes[(nu)])/* Use this when we want to be sure that NB is in bucket NU. */#define RIGHT_BUCKET(nb, nu) \ (((nb) > binsizes[(nu)-1]) && ((nb) <= binsizes[(nu)]))/* nextf[i] is free list of blocks of size 2**(i + 3) */static union mhead *nextf[NBUCKETS];/* busy[i] is nonzero while allocation or free of block size i is in progress. */static char busy[NBUCKETS];static int pagesz; /* system page size. */static int pagebucket; /* bucket for requests a page in size */static int maxbuck; /* highest bucket receiving allocation request. */static char *memtop; /* top of heap */static const unsigned long binsizes[NBUCKETS] = { 8UL, 16UL, 32UL, 64UL, 128UL, 256UL, 512UL, 1024UL, 2048UL, 4096UL, 8192UL, 16384UL, 32768UL, 65536UL, 131072UL, 262144UL, 524288UL, 1048576UL, 2097152UL, 4194304UL, 8388608UL, 16777216UL, 33554432UL, 67108864UL, 134217728UL, 268435456UL, 536870912UL, 1073741824UL, 2147483648UL, 4294967295UL};/* binsizes[x] == (1 << ((x) + 3)) */#define binsize(x) binsizes[(x)]/* Declarations for internal functions */static PTR_T internal_malloc __P((size_t, const char *, int, int));static PTR_T internal_realloc __P((PTR_T, size_t, const char *, int, int));static void internal_free __P((PTR_T, const char *, int, int));static PTR_T internal_memalign __P((size_t, size_t, const char *, int, int));#ifndef NO_CALLOCstatic PTR_T internal_calloc __P((size_t, size_t, const char *, int, int));static void internal_cfree __P((PTR_T, const char *, int, int));#endif#ifndef NO_VALLOCstatic PTR_T internal_valloc __P((size_t, const char *, int, int));#endif#if defined (botch)extern void botch ();#elsestatic void botch __P((const char *, const char *, int));#endifstatic void xbotch __P((PTR_T, int, const char *, const char *, int));#if !HAVE_DECL_SBRKextern char *sbrk ();#endif /* !HAVE_DECL_SBRK */#ifdef SHELLextern int interrupt_immediately;extern int signal_is_trapped __P((int));#endif#ifdef MALLOC_STATSstruct _malstats _mstats;#endif /* MALLOC_STATS *//* Debugging variables available to applications. */int malloc_flags = 0; /* future use */int malloc_trace = 0; /* trace allocations and frees to stderr */int malloc_register = 0; /* future use */#ifdef MALLOC_TRACEchar _malloc_trace_buckets[NBUCKETS];/* These should really go into a header file. */extern void mtrace_alloc __P((const char *, PTR_T, size_t, const char *, int));extern void mtrace_free __P((PTR_T, int, const char *, int));#endif#if !defined (botch)static voidbotch (s, file, line) const char *s; const char *file; int line;{ fprintf (stderr, _("malloc: failed assertion: %s\n"), s); (void)fflush (stderr); abort ();}#endif/* print the file and line number that caused the assertion failure and call botch() to do whatever the application wants with the information */static voidxbotch (mem, e, s, file, line) PTR_T mem; int e; const char *s; const char *file; int line;{ fprintf (stderr, _("\r\nmalloc: %s:%d: assertion botched\r\n"), file ? file : _("unknown"), line);#ifdef MALLOC_REGISTER if (mem != NULL && malloc_register) mregister_describe_mem (mem, stderr);#endif (void)fflush (stderr); botch(s, file, line);}/* Coalesce two adjacent free blocks off the free list for size NU - 1, as long as we can find two adjacent free blocks. nextf[NU -1] is assumed to not be busy; the caller (morecore()) checks for this. BUSY[NU] must be set to 1. */static voidbcoalesce (nu) register int nu;{ register union mhead *mp, *mp1, *mp2; register int nbuck; unsigned long siz; nbuck = nu - 1; if (nextf[nbuck] == 0 || busy[nbuck]) return; busy[nbuck] = 1; siz = binsize (nbuck); mp2 = mp1 = nextf[nbuck]; mp = CHAIN (mp1); while (mp && mp != (union mhead *)((char *)mp1 + siz)) { mp2 = mp1; mp1 = mp; mp = CHAIN (mp); } if (mp == 0) { busy[nbuck] = 0; return; } /* OK, now we have mp1 pointing to the block we want to add to nextf[NU]. CHAIN(mp2) must equal mp1. Check that mp1 and mp are adjacent. */ if (mp2 != mp1 && CHAIN(mp2) != mp1) { busy[nbuck] = 0; xbotch ((PTR_T)0, 0, "bcoalesce: CHAIN(mp2) != mp1", (char *)NULL, 0); }#ifdef MALLOC_DEBUG if (CHAIN (mp1) != (union mhead *)((char *)mp1 + siz)) { busy[nbuck] = 0; return; /* not adjacent */ }#endif /* Since they are adjacent, remove them from the free list */ if (mp1 == nextf[nbuck]) nextf[nbuck] = CHAIN (mp); else CHAIN (mp2) = CHAIN (mp); busy[nbuck] = 0;#ifdef MALLOC_STATS _mstats.tbcoalesce++; _mstats.ncoalesce[nbuck]++;#endif /* And add the combined two blocks to nextf[NU]. */ mp1->mh_alloc = ISFREE; mp1->mh_index = nu; CHAIN (mp1) = nextf[nu]; nextf[nu] = mp1;}/* Split a block at index > NU (but less than SPLIT_MAX) into a set of blocks of the correct size, and attach them to nextf[NU]. nextf[NU] is assumed to be empty. Must be called with signals blocked (e.g., by morecore()). BUSY[NU] must be set to 1. */static voidbsplit (nu) register int nu;{ register union mhead *mp; int nbuck, nblks, split_max; unsigned long siz; split_max = (maxbuck > SPLIT_MAX) ? maxbuck : SPLIT_MAX; if (nu >= SPLIT_MID) { for (nbuck = split_max; nbuck > nu; nbuck--) { if (busy[nbuck] || nextf[nbuck] == 0) continue; break; } } else { for (nbuck = nu + 1; nbuck <= split_max; nbuck++) { if (busy[nbuck] || nextf[nbuck] == 0) continue; break; } } if (nbuck > split_max || nbuck <= nu) return; /* XXX might want to split only if nextf[nbuck] has >= 2 blocks free and nbuck is below some threshold. */ /* Remove the block from the chain of larger blocks. */ busy[nbuck] = 1; mp = nextf[nbuck]; nextf[nbuck] = CHAIN (mp); busy[nbuck] = 0;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -