Home | History | Annotate | Line # | Download | only in ld.elf_so
      1 /*	$NetBSD: xmalloc.c,v 1.12 2013/01/24 17:57:29 christos 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.12 2013/01/24 17:57:29 christos 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 char 		*pagepool_start, *pagepool_end;
    100 static int		morepages(int);
    101 #define PAGEPOOL_SIZE	(size_t)(pagepool_end - pagepool_start)
    102 
    103 /*
    104  * The overhead on a block is at least 4 bytes.  When free, this space
    105  * contains a pointer to the next free block, and the bottom two bits must
    106  * be zero.  When in use, the first byte is set to MAGIC, and the second
    107  * byte is the size index.  The remaining bytes are for alignment.
    108  * If range checking is enabled then a second word holds the size of the
    109  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
    110  * The order of elements is critical: ov_magic must overlay the low order
    111  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
    112  */
    113 union	overhead {
    114 	union	overhead *ov_next;	/* when free */
    115 	struct {
    116 		u_char	ovu_magic;	/* magic number */
    117 		u_char	ovu_index;	/* bucket # */
    118 #ifdef RCHECK
    119 		u_short	ovu_rmagic;	/* range magic number */
    120 		u_int	ovu_size;	/* actual block size */
    121 #endif
    122 	} ovu;
    123 #define	ov_magic	ovu.ovu_magic
    124 #define	ov_index	ovu.ovu_index
    125 #define	ov_rmagic	ovu.ovu_rmagic
    126 #define	ov_size		ovu.ovu_size
    127 };
    128 
    129 static void morecore(size_t);
    130 static void *imalloc(size_t);
    131 
    132 #define	MAGIC		0xef		/* magic # on accounting info */
    133 #define RMAGIC		0x5555		/* magic # on range info */
    134 
    135 #ifdef RCHECK
    136 #define	RSLOP		(sizeof (u_short))
    137 #else
    138 #define	RSLOP		0
    139 #endif
    140 
    141 /*
    142  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
    143  * smallest allocatable block is 8 bytes.  The overhead information
    144  * precedes the data area returned to the user.
    145  */
    146 #define	NBUCKETS 30
    147 static	union overhead *nextf[NBUCKETS];
    148 
    149 static	size_t pagesz;			/* page size */
    150 static	size_t pagebucket;		/* page size bucket */
    151 static	size_t pageshift;		/* page size shift */
    152 
    153 #ifdef MSTATS
    154 /*
    155  * nmalloc[i] is the difference between the number of mallocs and frees
    156  * for a given block size.
    157  */
    158 static	u_int nmalloc[NBUCKETS];
    159 #endif
    160 
    161 #if defined(MALLOC_DEBUG) || defined(RCHECK)
    162 #define	ASSERT(p)   if (!(p)) botch("p")
    163 static void
    164 botch(const char *s)
    165 {
    166     xwarnx("\r\nassertion botched: %s\r\n", s);
    167     abort();
    168 }
    169 #else
    170 #define	ASSERT(p)
    171 #endif
    172 
    173 #define TRACE()	xprintf("TRACE %s:%d\n", __FILE__, __LINE__)
    174 
    175 static void *
    176 imalloc(size_t nbytes)
    177 {
    178   	union overhead *op;
    179   	size_t bucket;
    180 	size_t n, m;
    181 	unsigned amt;
    182 
    183 	/*
    184 	 * First time malloc is called, setup page size and
    185 	 * align break pointer so all data will be page aligned.
    186 	 */
    187 	if (pagesz == 0) {
    188 		pagesz = n = _rtld_pagesz;
    189 		if (morepages(NPOOLPAGES) == 0)
    190 			return NULL;
    191 		op = (union overhead *)(pagepool_start);
    192 		m = sizeof (*op) - (((char *)op - (char *)NULL) & (n - 1));
    193 		if (n < m)
    194 			n += pagesz - m;
    195 		else
    196 			n -= m;
    197   		if (n) {
    198 			pagepool_start += n;
    199 		}
    200 		bucket = 0;
    201 		amt = sizeof(union overhead);
    202 		while (pagesz > amt) {
    203 			amt <<= 1;
    204 			bucket++;
    205 		}
    206 		pagebucket = bucket;
    207 		pageshift = ffs(pagesz) - 1;
    208 	}
    209 	/*
    210 	 * Convert amount of memory requested into closest block size
    211 	 * stored in hash buckets which satisfies request.
    212 	 * Account for space used per block for accounting.
    213 	 */
    214 	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
    215 		if (sizeof(union overhead) & (sizeof(union overhead) - 1)) {
    216 		    amt = sizeof(union overhead) * 2;
    217 		    bucket = 1;
    218 		} else {
    219 		    amt = sizeof(union overhead); /* size of first bucket */
    220 		    bucket = 0;
    221 		}
    222 		n = -(sizeof (*op) + RSLOP);
    223 	} else {
    224 		amt = pagesz;
    225 		bucket = pagebucket;
    226 	}
    227 	while (nbytes > amt + n) {
    228 		amt <<= 1;
    229 		if (amt == 0)
    230 			return (NULL);
    231 		bucket++;
    232 	}
    233 	/*
    234 	 * If nothing in hash bucket right now,
    235 	 * request more memory from the system.
    236 	 */
    237   	if ((op = nextf[bucket]) == NULL) {
    238   		morecore(bucket);
    239   		if ((op = nextf[bucket]) == NULL)
    240   			return (NULL);
    241 	}
    242 	/* remove from linked list */
    243   	nextf[bucket] = op->ov_next;
    244 	op->ov_magic = MAGIC;
    245 	op->ov_index = bucket;
    246 #ifdef MSTATS
    247   	nmalloc[bucket]++;
    248 #endif
    249 #ifdef RCHECK
    250 	/*
    251 	 * Record allocated size of block and
    252 	 * bound space with magic numbers.
    253 	 */
    254 	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
    255 	op->ov_rmagic = RMAGIC;
    256   	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
    257 #endif
    258   	return ((char *)(op + 1));
    259 }
    260 
    261 /*
    262  * Allocate more memory to the indicated bucket.
    263  */
    264 static void
    265 morecore(size_t bucket)
    266 {
    267   	union overhead *op;
    268 	size_t sz;		/* size of desired block */
    269   	size_t amt;		/* amount to allocate */
    270   	size_t nblks;		/* how many blocks we get */
    271 
    272 	/*
    273 	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
    274 	 * 2^30 bytes on a VAX, I think) or for a negative arg.
    275 	 */
    276 	sz = 1 << (bucket + 3);
    277 #ifdef MALLOC_DEBUG
    278 	ASSERT(sz > 0);
    279 #endif
    280 	if (sz < pagesz) {
    281 		amt = pagesz;
    282 		nblks = amt >> (bucket + 3);
    283 	} else {
    284 		amt = sz + pagesz;
    285 		nblks = 1;
    286 	}
    287 	if (amt > PAGEPOOL_SIZE)
    288 		if (morepages((amt >> pageshift) + NPOOLPAGES) == 0)
    289 			return;
    290 	op = (union overhead *)pagepool_start;
    291 	pagepool_start += amt;
    292 
    293 	/*
    294 	 * Add new memory allocated to that on
    295 	 * free list for this hash bucket.
    296 	 */
    297   	nextf[bucket] = op;
    298   	while (--nblks > 0) {
    299 		op->ov_next = (union overhead *)((caddr_t)op + sz);
    300 		op = (union overhead *)((caddr_t)op + sz);
    301   	}
    302 }
    303 
    304 void
    305 xfree(void *cp)
    306 {
    307   	int size;
    308 	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   	size_t onb;
    336 	size_t 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 	}
    373   	if ((res = imalloc(nbytes)) == NULL)
    374   		return (NULL);
    375   	if (cp != res) {	/* common optimization if "compacting" */
    376 		memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
    377 		xfree(cp);
    378 	}
    379   	return (res);
    380 }
    381 
    382 #ifdef MSTATS
    383 /*
    384  * mstats - print out statistics about malloc
    385  *
    386  * Prints two lines of numbers, one showing the length of the free list
    387  * for each size category, the second showing the number of mallocs -
    388  * frees for each size category.
    389  */
    390 void
    391 mstats(char *s)
    392 {
    393   	int i, j;
    394   	union overhead *p;
    395   	int totfree = 0,
    396   	totused = 0;
    397 
    398   	xprintf("Memory allocation statistics %s\nfree:\t", s);
    399   	for (i = 0; i < NBUCKETS; i++) {
    400   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
    401   			;
    402   		xprintf(" %d", j);
    403   		totfree += j * (1 << (i + 3));
    404   	}
    405   	xprintf("\nused:\t");
    406   	for (i = 0; i < NBUCKETS; i++) {
    407   		xprintf(" %d", nmalloc[i]);
    408   		totused += nmalloc[i] * (1 << (i + 3));
    409   	}
    410   	xprintf("\n\tTotal in use: %d, total free: %d\n",
    411 	    totused, totfree);
    412 }
    413 #endif
    414 
    415 
    416 static int
    417 morepages(int n)
    418 {
    419 	int	fd = -1;
    420 	int	offset;
    421 
    422 #ifdef NEED_DEV_ZERO
    423 	fd = open("/dev/zero", O_RDWR, 0);
    424 	if (fd == -1)
    425 		xerr(1, "/dev/zero");
    426 #endif
    427 
    428 	if (PAGEPOOL_SIZE > pagesz) {
    429 		caddr_t	addr = (caddr_t)
    430 			(((long)pagepool_start + pagesz - 1) & ~(pagesz - 1));
    431 		if (munmap(addr, pagepool_end - addr) != 0)
    432 			xwarn("morepages: munmap %p", addr);
    433 	}
    434 
    435 	offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1));
    436 
    437 	if ((pagepool_start = mmap(0, n * pagesz,
    438 			PROT_READ|PROT_WRITE,
    439 			MAP_ANON|MAP_PRIVATE, fd, 0)) == (caddr_t)-1) {
    440 		xprintf("Cannot map anonymous memory");
    441 		return 0;
    442 	}
    443 	pagepool_end = pagepool_start + n * pagesz;
    444 	pagepool_start += offset;
    445 
    446 #ifdef NEED_DEV_ZERO
    447 	close(fd);
    448 #endif
    449 	return n;
    450 }
    451 
    452 void *
    453 xcalloc(size_t size)
    454 {
    455 
    456 	return memset(xmalloc(size), 0, size);
    457 }
    458 
    459 void *
    460 xmalloc(size_t size)
    461 {
    462 	void *p = imalloc(size);
    463 
    464 	if (p == NULL)
    465 		xerr(1, "%s", xstrerror(errno));
    466 	return p;
    467 }
    468 
    469 void *
    470 xrealloc(void *p, size_t size)
    471 {
    472 	p = irealloc(p, size);
    473 
    474 	if (p == NULL)
    475 		xerr(1, "%s", xstrerror(errno));
    476 	return p;
    477 }
    478 
    479 char *
    480 xstrdup(const char *str)
    481 {
    482 	size_t len;
    483 	char *copy;
    484 
    485 	len = strlen(str) + 1;
    486 	copy = xmalloc(len);
    487 	memcpy(copy, str, len);
    488 	return (copy);
    489 }
    490