1 /* $Header: malloc.c,v 3.0.1.2 89/11/11 04:36:37 lwall Locked $
4 * Revision 3.0.1.2 89/11/11 04:36:37 lwall
5 * patch2: malloc pointer corruption check made more portable
7 * Revision 3.0.1.1 89/10/26 23:15:05 lwall
8 * patch1: some declarations were missing from malloc.c
9 * patch1: sparc machines had alignment problems in malloc.c
11 * Revision 3.0 89/10/18 15:20:39 lwall
17 static char sccsid[] = "@(#)malloc.c 4.3 (Berkeley) 9/16/83";
23 * malloc.c (Caltech) 2/21/82
24 * Chris Kingsley, kingsley@cit-20.
26 * This is a very fast storage allocator. It allocates blocks of a small
27 * number of different sizes, and keeps free lists of each size. Blocks that
28 * don't exactly fit are passed up to the next larger size. In this
29 * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
30 * This is designed for use in a program that uses vast quantities of memory,
31 * but bombs when it runs out.
37 static findbucket(), morecore();
39 /* I don't much care whether these are defined in sys/types.h--LAW */
41 #define u_char unsigned char
42 #define u_int unsigned int
43 #define u_short unsigned short
46 * The overhead on a block is at least 4 bytes. When free, this space
47 * contains a pointer to the next free block, and the bottom two bits must
48 * be zero. When in use, the first byte is set to MAGIC, and the second
49 * byte is the size index. The remaining bytes are for alignment.
50 * If range checking is enabled and the size of the block fits
51 * in two bytes, then the top two bytes hold the size of the requested block
52 * plus the range checking words, and the header word MINUS ONE.
55 union overhead *ov_next; /* when free */
56 #if defined (mips) || defined (sparc)
57 double strut; /* alignment problems */
60 u_char ovu_magic; /* magic number */
61 u_char ovu_index; /* bucket # */
63 u_short ovu_size; /* actual block size */
64 u_int ovu_rmagic; /* range magic number */
67 #define ov_magic ovu.ovu_magic
68 #define ov_index ovu.ovu_index
69 #define ov_size ovu.ovu_size
70 #define ov_rmagic ovu.ovu_rmagic
73 #define MAGIC 0xff /* magic # on accounting info */
74 #define OLDMAGIC 0x7f /* same after a free() */
75 #define RMAGIC 0x55555555 /* magic # on range info */
77 #define RSLOP sizeof (u_int)
83 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
84 * smallest allocatable block is 8 bytes. The overhead information
85 * precedes the data area returned to the user.
88 static union overhead *nextf[NBUCKETS];
93 * nmalloc[i] is the difference between the number of mallocs and frees
94 * for a given block size.
96 static u_int nmalloc[NBUCKETS];
101 #define ASSERT(p) if (!(p)) botch("p"); else
107 printf("assertion botched: %s\n", s);
116 register unsigned nbytes;
118 register union overhead *p;
119 register int bucket = 0;
120 register unsigned shiftr;
123 * Convert amount of memory requested into
124 * closest block size stored in hash buckets
125 * which satisfies request. Account for
126 * space used per block for accounting.
128 nbytes += sizeof (union overhead) + RSLOP;
129 nbytes = (nbytes + 3) &~ 3;
130 shiftr = (nbytes - 1) >> 2;
131 /* apart from this loop, this is O(1) */
135 * If nothing in hash bucket right now,
136 * request more memory from the system.
138 if (nextf[bucket] == NULL)
140 if ((p = (union overhead *)nextf[bucket]) == NULL)
142 /* remove from linked list */
144 if (*((int*)p) & (sizeof(union overhead) - 1))
146 fprintf(stderr,"Corrupt malloc ptr 0x%x at 0x%x\n",*((int*)p),p);
148 fprintf(stderr,"Corrupt malloc ptr 0x%lx at 0x%lx\n",*((int*)p),p);
151 nextf[bucket] = p->ov_next;
159 * Record allocated size of block and
160 * bound space with magic numbers.
162 if (nbytes <= 0x10000)
163 p->ov_size = nbytes - 1;
164 p->ov_rmagic = RMAGIC;
165 *((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
167 return ((char *)(p + 1));
171 * Allocate more memory to the indicated bucket.
177 register union overhead *op;
178 register int rnu; /* 2^rnu bytes will be requested */
179 register int nblks; /* become nblks blocks of the desired size */
185 * Insure memory is allocated
186 * on a page boundary. Should
187 * make getpageize call?
189 op = (union overhead *)sbrk(0);
192 (void)sbrk(1024 - ((int)op & 0x3ff));
194 /* The sbrk(0) call on the I286 always returns the next segment */
198 /* take 2k unless the block is bigger than that */
199 rnu = (bucket <= 8) ? 11 : bucket + 3;
201 /* take 16k unless the block is bigger than that
202 (80286s like large segments!) */
203 rnu = (bucket <= 11) ? 14 : bucket + 3;
205 nblks = 1 << (rnu - (bucket + 3)); /* how many blocks to get */
208 op = (union overhead *)sbrk(1 << rnu);
213 * Round up to minimum allocation size boundary
214 * and deduct from block count to reflect.
218 op = (union overhead *)(((int)op + 8) &~ 7);
222 /* Again, this should always be ok on an 80286 */
225 * Add new memory allocated to that on
226 * free list for this hash bucket.
229 siz = 1 << (bucket + 3);
230 while (--nblks > 0) {
231 op->ov_next = (union overhead *)((caddr_t)op + siz);
232 op = (union overhead *)((caddr_t)op + siz);
240 register union overhead *op;
244 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
246 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
248 if (op->ov_magic != MAGIC) {
249 warn("%s free() ignored",
250 op->ov_magic == OLDMAGIC ? "Duplicate" : "Bad");
253 op->ov_magic = OLDMAGIC;
256 ASSERT(op->ov_rmagic == RMAGIC);
257 if (op->ov_index <= 13)
258 ASSERT(*(u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP) == RMAGIC);
260 ASSERT(op->ov_index < NBUCKETS);
262 op->ov_next = nextf[size];
270 * When a program attempts "storage compaction" as mentioned in the
271 * old malloc man page, it realloc's an already freed block. Usually
272 * this is the last block it freed; occasionally it might be farther
273 * back. We have to search all the free lists for the block in order
274 * to determine its bucket: 1st we make one pass thru the lists
275 * checking only the first block in each; if that fails we search
276 * ``reall_srchlen'' blocks in each list for a match (the variable
277 * is extern so the caller can modify it). If that fails we just copy
278 * however many bytes was given to realloc() and hope it's not huge.
280 int reall_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
294 return (malloc(nbytes));
295 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
296 if (op->ov_magic == MAGIC) {
301 * Already free, doing "compaction".
303 * Search for the old block of memory on the
304 * free list. First, check the most common
305 * case (last element free'd), then (this failing)
306 * the last ``reall_srchlen'' items free'd.
307 * If all lookups fail, then assume the size of
308 * the memory block being realloc'd is the
311 if ((i = findbucket(op, 1)) < 0 &&
312 (i = findbucket(op, reall_srchlen)) < 0)
315 onb = (1 << (i + 3)) - sizeof (*op) - RSLOP;
316 /* avoid the copy if same size block */
318 nbytes <= onb && nbytes > (onb >> 1) - sizeof(*op) - RSLOP) {
321 * Record new allocated size of block and
322 * bound space with magic numbers.
324 if (op->ov_index <= 13) {
326 * Convert amount of memory requested into
327 * closest block size stored in hash buckets
328 * which satisfies request. Account for
329 * space used per block for accounting.
331 nbytes += sizeof (union overhead) + RSLOP;
332 nbytes = (nbytes + 3) &~ 3;
333 op->ov_size = nbytes - 1;
334 *((u_int *)((caddr_t)op + nbytes - RSLOP)) = RMAGIC;
339 if ((res = malloc(nbytes)) == NULL)
341 if (cp != res) /* common optimization */
342 (void)bcopy(cp, res, (int)((nbytes < onb) ? nbytes : onb));
349 * Search ``srchlen'' elements of each free list for a block whose
350 * header starts at ``freep''. If srchlen is -1 search the whole list.
351 * Return bucket number, or -1 if not found.
354 findbucket(freep, srchlen)
355 union overhead *freep;
358 register union overhead *p;
361 for (i = 0; i < NBUCKETS; i++) {
363 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
374 * mstats - print out statistics about malloc
376 * Prints two lines of numbers, one showing the length of the free list
377 * for each size category, the second showing the number of mallocs -
378 * frees for each size category.
384 register union overhead *p;
388 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
389 for (i = 0; i < NBUCKETS; i++) {
390 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
392 fprintf(stderr, " %d", j);
393 totfree += j * (1 << (i + 3));
395 fprintf(stderr, "\nused:\t");
396 for (i = 0; i < NBUCKETS; i++) {
397 fprintf(stderr, " %d", nmalloc[i]);
398 totused += nmalloc[i] * (1 << (i + 3));
400 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",