ldivmod, uldivmod: fix qdivrem calls
[minix.git] / libexec / ld.elf_so / xmalloc.c
blobac516becfa9416152f9688dc6b24272bfcd88e6c
1 /* $NetBSD: xmalloc.c,v 1.11 2011/05/25 14:41:46 christos Exp $ */
3 /*
4 * Copyright 1996 John D. Polstra.
5 * Copyright 1996 Matt Thomas <matt@3am-software.com>
6 * All rights reserved.
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.
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.
35 * Copyright (c) 1983 Regents of the University of California.
36 * All rights reserved.
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.
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.
63 #ifdef __minix
64 /* Minix mmap can do this. */
65 #define mmap minix_mmap
66 #define munmap minix_munmap
67 #endif
69 #if defined(LIBC_SCCS) && !defined(lint)
70 /*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/
71 #endif /* LIBC_SCCS and not lint */
74 * malloc.c (Caltech) 2/21/82
75 * Chris Kingsley, kingsley@cit-20.
77 * This is a very fast storage allocator. It allocates blocks of a small
78 * number of different sizes, and keeps free lists of each size. Blocks that
79 * don't exactly fit are passed up to the next larger size. In this
80 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
81 * This is designed for use in a virtual memory environment.
84 #include <sys/cdefs.h>
85 #ifndef lint
86 __RCSID("$NetBSD: xmalloc.c,v 1.11 2011/05/25 14:41:46 christos Exp $");
87 #endif /* not lint */
89 #include <stdlib.h>
90 #include <string.h>
91 #include <unistd.h>
92 #include <errno.h>
94 #include <sys/types.h>
95 #include <sys/param.h>
96 #include <sys/mman.h>
97 #include <sys/stat.h>
99 #include "rtld.h"
102 * Pre-allocate mmap'ed pages
104 #define NPOOLPAGES (32*1024/pagesz)
105 static char *pagepool_start, *pagepool_end;
106 static int morepages(int);
107 #define PAGEPOOL_SIZE (size_t)(pagepool_end - pagepool_start)
110 * The overhead on a block is at least 4 bytes. When free, this space
111 * contains a pointer to the next free block, and the bottom two bits must
112 * be zero. When in use, the first byte is set to MAGIC, and the second
113 * byte is the size index. The remaining bytes are for alignment.
114 * If range checking is enabled then a second word holds the size of the
115 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
116 * The order of elements is critical: ov_magic must overlay the low order
117 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
119 union overhead {
120 union overhead *ov_next; /* when free */
121 struct {
122 u_char ovu_magic; /* magic number */
123 u_char ovu_index; /* bucket # */
124 #ifdef RCHECK
125 u_short ovu_rmagic; /* range magic number */
126 u_int ovu_size; /* actual block size */
127 #endif
128 } ovu;
129 #define ov_magic ovu.ovu_magic
130 #define ov_index ovu.ovu_index
131 #define ov_rmagic ovu.ovu_rmagic
132 #define ov_size ovu.ovu_size
135 static void morecore(size_t);
136 static void *imalloc(size_t);
138 #define MAGIC 0xef /* magic # on accounting info */
139 #define RMAGIC 0x5555 /* magic # on range info */
141 #ifdef RCHECK
142 #define RSLOP (sizeof (u_short))
143 #else
144 #define RSLOP 0
145 #endif
148 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
149 * smallest allocatable block is 8 bytes. The overhead information
150 * precedes the data area returned to the user.
152 #define NBUCKETS 30
153 static union overhead *nextf[NBUCKETS];
155 static size_t pagesz; /* page size */
156 static size_t pagebucket; /* page size bucket */
157 static size_t pageshift; /* page size shift */
159 #ifdef MSTATS
161 * nmalloc[i] is the difference between the number of mallocs and frees
162 * for a given block size.
164 static u_int nmalloc[NBUCKETS];
165 #endif
167 #if defined(MALLOC_DEBUG) || defined(RCHECK)
168 #define ASSERT(p) if (!(p)) botch("p")
169 static void
170 botch(const char *s)
172 xwarnx("\r\nassertion botched: %s\r\n", s);
173 abort();
175 #else
176 #define ASSERT(p)
177 #endif
179 #define TRACE() xprintf("TRACE %s:%d\n", __FILE__, __LINE__)
181 static void *
182 imalloc(size_t nbytes)
184 union overhead *op;
185 size_t bucket;
186 size_t n, m;
187 unsigned amt;
190 * First time malloc is called, setup page size and
191 * align break pointer so all data will be page aligned.
193 if (pagesz == 0) {
194 pagesz = n = _rtld_pagesz;
195 if (morepages(NPOOLPAGES) == 0)
196 return NULL;
197 op = (union overhead *)(pagepool_start);
198 m = sizeof (*op) - (((char *)op - (char *)NULL) & (n - 1));
199 if (n < m)
200 n += pagesz - m;
201 else
202 n -= m;
203 if (n) {
204 pagepool_start += n;
206 bucket = 0;
207 amt = sizeof(union overhead);
208 while (pagesz > amt) {
209 amt <<= 1;
210 bucket++;
212 pagebucket = bucket;
213 pageshift = ffs(pagesz) - 1;
216 * Convert amount of memory requested into closest block size
217 * stored in hash buckets which satisfies request.
218 * Account for space used per block for accounting.
220 if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
221 if (sizeof(union overhead) & (sizeof(union overhead) - 1)) {
222 amt = sizeof(union overhead) * 2;
223 bucket = 1;
224 } else {
225 amt = sizeof(union overhead); /* size of first bucket */
226 bucket = 0;
228 n = -(sizeof (*op) + RSLOP);
229 } else {
230 amt = pagesz;
231 bucket = pagebucket;
233 while (nbytes > amt + n) {
234 amt <<= 1;
235 if (amt == 0)
236 return (NULL);
237 bucket++;
240 * If nothing in hash bucket right now,
241 * request more memory from the system.
243 if ((op = nextf[bucket]) == NULL) {
244 morecore(bucket);
245 if ((op = nextf[bucket]) == NULL)
246 return (NULL);
248 /* remove from linked list */
249 nextf[bucket] = op->ov_next;
250 op->ov_magic = MAGIC;
251 op->ov_index = bucket;
252 #ifdef MSTATS
253 nmalloc[bucket]++;
254 #endif
255 #ifdef RCHECK
257 * Record allocated size of block and
258 * bound space with magic numbers.
260 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
261 op->ov_rmagic = RMAGIC;
262 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
263 #endif
264 return ((char *)(op + 1));
268 * Allocate more memory to the indicated bucket.
270 static void
271 morecore(size_t bucket)
273 union overhead *op;
274 size_t sz; /* size of desired block */
275 size_t amt; /* amount to allocate */
276 size_t nblks; /* how many blocks we get */
279 * sbrk_size <= 0 only for big, FLUFFY, requests (about
280 * 2^30 bytes on a VAX, I think) or for a negative arg.
282 sz = 1 << (bucket + 3);
283 #ifdef MALLOC_DEBUG
284 ASSERT(sz > 0);
285 #endif
286 if (sz < pagesz) {
287 amt = pagesz;
288 nblks = amt >> (bucket + 3);
289 } else {
290 amt = sz + pagesz;
291 nblks = 1;
293 if (amt > PAGEPOOL_SIZE)
294 if (morepages((amt >> pageshift) + NPOOLPAGES) == 0)
295 return;
296 op = (union overhead *)pagepool_start;
297 pagepool_start += amt;
300 * Add new memory allocated to that on
301 * free list for this hash bucket.
303 nextf[bucket] = op;
304 while (--nblks > 0) {
305 op->ov_next = (union overhead *)((caddr_t)op + sz);
306 op = (union overhead *)((caddr_t)op + sz);
310 void
311 xfree(void *cp)
313 int size;
314 union overhead *op;
316 if (cp == NULL)
317 return;
318 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
319 #ifdef MALLOC_DEBUG
320 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
321 #else
322 if (op->ov_magic != MAGIC)
323 return; /* sanity */
324 #endif
325 #ifdef RCHECK
326 ASSERT(op->ov_rmagic == RMAGIC);
327 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
328 #endif
329 size = op->ov_index;
330 ASSERT(size < NBUCKETS);
331 op->ov_next = nextf[size]; /* also clobbers ov_magic */
332 nextf[size] = op;
333 #ifdef MSTATS
334 nmalloc[size]--;
335 #endif
338 static void *
339 irealloc(void *cp, size_t nbytes)
341 size_t onb;
342 size_t i;
343 union overhead *op;
344 char *res;
346 if (cp == NULL)
347 return (imalloc(nbytes));
348 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
349 if (op->ov_magic != MAGIC) {
350 static const char *err_str =
351 "memory corruption or double free in realloc\n";
352 extern char *__progname;
353 write(STDERR_FILENO, __progname, strlen(__progname));
354 write(STDERR_FILENO, err_str, strlen(err_str));
355 abort();
358 i = op->ov_index;
359 onb = 1 << (i + 3);
360 if (onb < pagesz)
361 onb -= sizeof (*op) + RSLOP;
362 else
363 onb += pagesz - sizeof (*op) - RSLOP;
364 /* avoid the copy if same size block */
365 if (i) {
366 i = 1 << (i + 2);
367 if (i < pagesz)
368 i -= sizeof (*op) + RSLOP;
369 else
370 i += pagesz - sizeof (*op) - RSLOP;
372 if (nbytes <= onb && nbytes > i) {
373 #ifdef RCHECK
374 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
375 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
376 #endif
377 return(cp);
378 } else
379 xfree(cp);
380 if ((res = imalloc(nbytes)) == NULL)
381 return (NULL);
382 if (cp != res) /* common optimization if "compacting" */
383 memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
384 return (res);
387 #ifdef MSTATS
389 * mstats - print out statistics about malloc
391 * Prints two lines of numbers, one showing the length of the free list
392 * for each size category, the second showing the number of mallocs -
393 * frees for each size category.
395 void
396 mstats(char *s)
398 int i, j;
399 union overhead *p;
400 int totfree = 0,
401 totused = 0;
403 xprintf("Memory allocation statistics %s\nfree:\t", s);
404 for (i = 0; i < NBUCKETS; i++) {
405 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
407 xprintf(" %d", j);
408 totfree += j * (1 << (i + 3));
410 xprintf("\nused:\t");
411 for (i = 0; i < NBUCKETS; i++) {
412 xprintf(" %d", nmalloc[i]);
413 totused += nmalloc[i] * (1 << (i + 3));
415 xprintf("\n\tTotal in use: %d, total free: %d\n",
416 totused, totfree);
418 #endif
421 static int
422 morepages(int n)
424 int fd = -1;
425 int offset;
427 #ifdef NEED_DEV_ZERO
428 fd = open("/dev/zero", O_RDWR, 0);
429 if (fd == -1)
430 xerr(1, "/dev/zero");
431 #endif
433 if (PAGEPOOL_SIZE > pagesz) {
434 caddr_t addr = (caddr_t)
435 (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1));
436 if (munmap(addr, pagepool_end - addr) != 0)
437 xwarn("morepages: munmap %p", addr);
440 offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1));
442 if ((pagepool_start = mmap(0, n * pagesz,
443 PROT_READ|PROT_WRITE,
444 MAP_ANON|MAP_PRIVATE, fd, 0)) == (caddr_t)-1) {
445 xprintf("Cannot map anonymous memory");
446 return 0;
448 pagepool_end = pagepool_start + n * pagesz;
449 pagepool_start += offset;
451 #ifdef NEED_DEV_ZERO
452 close(fd);
453 #endif
454 return n;
457 void *
458 xcalloc(size_t size)
461 return memset(xmalloc(size), 0, size);
464 void *
465 xmalloc(size_t size)
467 void *p = imalloc(size);
469 if (p == NULL)
470 xerr(1, "%s", xstrerror(errno));
471 return p;
474 void *
475 xrealloc(void *p, size_t size)
477 p = irealloc(p, size);
479 if (p == NULL)
480 xerr(1, "%s", xstrerror(errno));
481 return p;
484 char *
485 xstrdup(const char *str)
487 size_t len;
488 char *copy;
490 len = strlen(str) + 1;
491 copy = xmalloc(len);
492 memcpy(copy, str, len);
493 return (copy);