1 /*-
2 * Copyright (c) 1983 Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30 #if defined(LIBC_SCCS) && !defined(lint)
31 /*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/
32 static char *rcsid = "$FreeBSD$";
33 #endif /* LIBC_SCCS and not lint */
34
35 /*
36 * malloc.c (Caltech) 2/21/82
37 * Chris Kingsley, kingsley@cit-20.
38 *
39 * This is a very fast storage allocator. It allocates blocks of a small
40 * number of different sizes, and keeps free lists of each size. Blocks that
41 * don't exactly fit are passed up to the next larger size. In this
42 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
43 * This is designed for use in a virtual memory environment.
44 */
45
46 #include <sys/types.h>
47 #include <sys/sysctl.h>
48 #include <paths.h>
49 #include <stdarg.h>
50 #include <stddef.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <sys/param.h>
56 #include <sys/mman.h>
57 #include "rtld_printf.h"
58
59 static void morecore();
60 static int findbucket();
61
62 /*
63 * Pre-allocate mmap'ed pages
64 */
65 #define NPOOLPAGES (32*1024/pagesz)
66 static caddr_t pagepool_start, pagepool_end;
67 static int morepages();
68
69 /*
70 * The overhead on a block is at least 4 bytes. When free, this space
71 * contains a pointer to the next free block, and the bottom two bits must
72 * be zero. When in use, the first byte is set to MAGIC, and the second
73 * byte is the size index. The remaining bytes are for alignment.
74 * If range checking is enabled then a second word holds the size of the
75 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
76 * The order of elements is critical: ov_magic must overlay the low order
77 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
78 */
79 union overhead {
80 union overhead *ov_next; /* when free */
81 struct {
82 u_char ovu_magic; /* magic number */
83 u_char ovu_index; /* bucket # */
84 #ifdef RCHECK
85 u_short ovu_rmagic; /* range magic number */
86 u_int ovu_size; /* actual block size */
87 #endif
88 } ovu;
89 #define ov_magic ovu.ovu_magic
90 #define ov_index ovu.ovu_index
91 #define ov_rmagic ovu.ovu_rmagic
92 #define ov_size ovu.ovu_size
93 };
94
95 #define MAGIC 0xef /* magic # on accounting info */
96 #define RMAGIC 0x5555 /* magic # on range info */
97
98 #ifdef RCHECK
99 #define RSLOP sizeof (u_short)
100 #else
101 #define RSLOP 0
102 #endif
103
104 /*
105 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
106 * smallest allocatable block is 8 bytes. The overhead information
107 * precedes the data area returned to the user.
108 */
109 #define NBUCKETS 30
110 static union overhead *nextf[NBUCKETS];
111
112 static int pagesz; /* page size */
113 static int pagebucket; /* page size bucket */
114
115 #ifdef MSTATS
116 /*
117 * nmalloc[i] is the difference between the number of mallocs and frees
118 * for a given block size.
119 */
120 static u_int nmalloc[NBUCKETS];
121 #include <stdio.h>
122 #endif
123
124 #if defined(MALLOC_DEBUG) || defined(RCHECK)
125 #define ASSERT(p) if (!(p)) botch("p")
126 #include <stdio.h>
127 static void
botch(s)128 botch(s)
129 char *s;
130 {
131 fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
132 (void) fflush(stderr); /* just in case user buffered it */
133 abort();
134 }
135 #else
136 #define ASSERT(p)
137 #endif
138
139 /* Debugging stuff */
140 #define TRACE() rtld_printf("TRACE %s:%d\n", __FILE__, __LINE__)
141
142 /*
143 * The array of supported page sizes is provided by the user, i.e., the
144 * program that calls this storage allocator. That program must initialize
145 * the array before making its first call to allocate storage. The array
146 * must contain at least one page size. The page sizes must be stored in
147 * increasing order.
148 */
149 extern size_t *pagesizes;
150
151 void *
malloc(nbytes)152 malloc(nbytes)
153 size_t nbytes;
154 {
155 register union overhead *op;
156 register int bucket;
157 register long n;
158 register unsigned amt;
159
160 /*
161 * First time malloc is called, setup page size and
162 * align break pointer so all data will be page aligned.
163 */
164 if (pagesz == 0) {
165 pagesz = n = pagesizes[0];
166 if (morepages(NPOOLPAGES) == 0)
167 return NULL;
168 op = (union overhead *)(pagepool_start);
169 n = n - sizeof (*op) - ((long)op & (n - 1));
170 if (n < 0)
171 n += pagesz;
172 if (n) {
173 pagepool_start += n;
174 }
175 bucket = 0;
176 amt = 8;
177 while ((unsigned)pagesz > amt) {
178 amt <<= 1;
179 bucket++;
180 }
181 pagebucket = bucket;
182 }
183 /*
184 * Convert amount of memory requested into closest block size
185 * stored in hash buckets which satisfies request.
186 * Account for space used per block for accounting.
187 */
188 if (nbytes <= (unsigned long)(n = pagesz - sizeof (*op) - RSLOP)) {
189 #ifndef RCHECK
190 amt = 8; /* size of first bucket */
191 bucket = 0;
192 #else
193 amt = 16; /* size of first bucket */
194 bucket = 1;
195 #endif
196 n = -(sizeof (*op) + RSLOP);
197 } else {
198 amt = pagesz;
199 bucket = pagebucket;
200 }
201 while (nbytes > amt + n) {
202 amt <<= 1;
203 if (amt == 0)
204 return (NULL);
205 bucket++;
206 }
207 /*
208 * If nothing in hash bucket right now,
209 * request more memory from the system.
210 */
211 if ((op = nextf[bucket]) == NULL) {
212 morecore(bucket);
213 if ((op = nextf[bucket]) == NULL)
214 return (NULL);
215 }
216 /* remove from linked list */
217 nextf[bucket] = op->ov_next;
218 op->ov_magic = MAGIC;
219 op->ov_index = bucket;
220 #ifdef MSTATS
221 nmalloc[bucket]++;
222 #endif
223 #ifdef RCHECK
224 /*
225 * Record allocated size of block and
226 * bound space with magic numbers.
227 */
228 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
229 op->ov_rmagic = RMAGIC;
230 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
231 #endif
232 return ((char *)(op + 1));
233 }
234
235 void *
calloc(size_t num,size_t size)236 calloc(size_t num, size_t size)
237 {
238 void *ret;
239
240 if (size != 0 && (num * size) / size != num) {
241 /* size_t overflow. */
242 return (NULL);
243 }
244
245 if ((ret = malloc(num * size)) != NULL)
246 memset(ret, 0, num * size);
247
248 return (ret);
249 }
250
251 /*
252 * Allocate more memory to the indicated bucket.
253 */
254 static void
morecore(bucket)255 morecore(bucket)
256 int bucket;
257 {
258 register union overhead *op;
259 register int sz; /* size of desired block */
260 int amt; /* amount to allocate */
261 int nblks; /* how many blocks we get */
262
263 /*
264 * sbrk_size <= 0 only for big, FLUFFY, requests (about
265 * 2^30 bytes on a VAX, I think) or for a negative arg.
266 */
267 sz = 1 << (bucket + 3);
268 #ifdef MALLOC_DEBUG
269 ASSERT(sz > 0);
270 #else
271 if (sz <= 0)
272 return;
273 #endif
274 if (sz < pagesz) {
275 amt = pagesz;
276 nblks = amt / sz;
277 } else {
278 amt = sz + pagesz;
279 nblks = 1;
280 }
281 if (amt > pagepool_end - pagepool_start)
282 if (morepages(amt/pagesz + NPOOLPAGES) == 0)
283 return;
284 op = (union overhead *)pagepool_start;
285 pagepool_start += amt;
286
287 /*
288 * Add new memory allocated to that on
289 * free list for this hash bucket.
290 */
291 nextf[bucket] = op;
292 while (--nblks > 0) {
293 op->ov_next = (union overhead *)((caddr_t)op + sz);
294 op = (union overhead *)((caddr_t)op + sz);
295 }
296 }
297
298 void
free(cp)299 free(cp)
300 void *cp;
301 {
302 register int size;
303 register union overhead *op;
304
305 if (cp == NULL)
306 return;
307 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
308 #ifdef MALLOC_DEBUG
309 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
310 #else
311 if (op->ov_magic != MAGIC)
312 return; /* sanity */
313 #endif
314 #ifdef RCHECK
315 ASSERT(op->ov_rmagic == RMAGIC);
316 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
317 #endif
318 size = op->ov_index;
319 ASSERT(size < NBUCKETS);
320 op->ov_next = nextf[size]; /* also clobbers ov_magic */
321 nextf[size] = op;
322 #ifdef MSTATS
323 nmalloc[size]--;
324 #endif
325 }
326
327 /*
328 * When a program attempts "storage compaction" as mentioned in the
329 * old malloc man page, it realloc's an already freed block. Usually
330 * this is the last block it freed; occasionally it might be farther
331 * back. We have to search all the free lists for the block in order
332 * to determine its bucket: 1st we make one pass thru the lists
333 * checking only the first block in each; if that fails we search
334 * ``realloc_srchlen'' blocks in each list for a match (the variable
335 * is extern so the caller can modify it). If that fails we just copy
336 * however many bytes was given to realloc() and hope it's not huge.
337 */
338 int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
339
340 void *
realloc(cp,nbytes)341 realloc(cp, nbytes)
342 void *cp;
343 size_t nbytes;
344 {
345 register u_int onb;
346 register int i;
347 union overhead *op;
348 char *res;
349 int was_alloced = 0;
350
351 if (cp == NULL)
352 return (malloc(nbytes));
353 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
354 if (op->ov_magic == MAGIC) {
355 was_alloced++;
356 i = op->ov_index;
357 } else {
358 /*
359 * Already free, doing "compaction".
360 *
361 * Search for the old block of memory on the
362 * free list. First, check the most common
363 * case (last element free'd), then (this failing)
364 * the last ``realloc_srchlen'' items free'd.
365 * If all lookups fail, then assume the size of
366 * the memory block being realloc'd is the
367 * largest possible (so that all "nbytes" of new
368 * memory are copied into). Note that this could cause
369 * a memory fault if the old area was tiny, and the moon
370 * is gibbous. However, that is very unlikely.
371 */
372 if ((i = findbucket(op, 1)) < 0 &&
373 (i = findbucket(op, realloc_srchlen)) < 0)
374 i = NBUCKETS;
375 }
376 onb = 1 << (i + 3);
377 if (onb < (u_int)pagesz)
378 onb -= sizeof (*op) + RSLOP;
379 else
380 onb += pagesz - sizeof (*op) - RSLOP;
381 /* avoid the copy if same size block */
382 if (was_alloced) {
383 if (i) {
384 i = 1 << (i + 2);
385 if (i < pagesz)
386 i -= sizeof (*op) + RSLOP;
387 else
388 i += pagesz - sizeof (*op) - RSLOP;
389 }
390 if (nbytes <= onb && nbytes > (size_t)i) {
391 #ifdef RCHECK
392 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
393 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
394 #endif
395 return(cp);
396 } else
397 free(cp);
398 }
399 if ((res = malloc(nbytes)) == NULL)
400 return (NULL);
401 if (cp != res) /* common optimization if "compacting" */
402 bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
403 return (res);
404 }
405
406 /*
407 * Search ``srchlen'' elements of each free list for a block whose
408 * header starts at ``freep''. If srchlen is -1 search the whole list.
409 * Return bucket number, or -1 if not found.
410 */
411 static int
findbucket(freep,srchlen)412 findbucket(freep, srchlen)
413 union overhead *freep;
414 int srchlen;
415 {
416 register union overhead *p;
417 register int i, j;
418
419 for (i = 0; i < NBUCKETS; i++) {
420 j = 0;
421 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
422 if (p == freep)
423 return (i);
424 j++;
425 }
426 }
427 return (-1);
428 }
429
430 #ifdef MSTATS
431 /*
432 * mstats - print out statistics about malloc
433 *
434 * Prints two lines of numbers, one showing the length of the free list
435 * for each size category, the second showing the number of mallocs -
436 * frees for each size category.
437 */
mstats(s)438 mstats(s)
439 char *s;
440 {
441 register int i, j;
442 register union overhead *p;
443 int totfree = 0,
444 totused = 0;
445
446 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
447 for (i = 0; i < NBUCKETS; i++) {
448 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
449 ;
450 fprintf(stderr, " %d", j);
451 totfree += j * (1 << (i + 3));
452 }
453 fprintf(stderr, "\nused:\t");
454 for (i = 0; i < NBUCKETS; i++) {
455 fprintf(stderr, " %d", nmalloc[i]);
456 totused += nmalloc[i] * (1 << (i + 3));
457 }
458 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
459 totused, totfree);
460 }
461 #endif
462
463
464 static int
morepages(n)465 morepages(n)
466 int n;
467 {
468 int fd = -1;
469 int offset;
470
471 if (pagepool_end - pagepool_start > pagesz) {
472 caddr_t addr = (caddr_t)
473 (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1));
474 if (munmap(addr, pagepool_end - addr) != 0)
475 rtld_fdprintf(STDERR_FILENO, "morepages: munmap %p",
476 addr);
477 }
478
479 offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1));
480
481 if ((pagepool_start = mmap(0, n * pagesz,
482 PROT_READ|PROT_WRITE,
483 MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) {
484 rtld_printf("Cannot map anonymous memory\n");
485 return 0;
486 }
487 pagepool_end = pagepool_start + n * pagesz;
488 pagepool_start += offset;
489
490 return n;
491 }
492