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