Home | History | Annotate | Line # | Download | only in stdlib
malloc.c revision 1.19
      1 /*	$NetBSD: malloc.c,v 1.19 1999/07/05 21:08:38 thorpej Exp $	*/
      2 
      3 /*
      4  * ----------------------------------------------------------------------------
      5  * "THE BEER-WARE LICENSE" (Revision 42):
      6  * <phk (at) FreeBSD.ORG> wrote this file.  As long as you retain this notice you
      7  * can do whatever you want with this stuff. If we meet some day, and you think
      8  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
      9  * ----------------------------------------------------------------------------
     10  *
     11  * From FreeBSD: malloc.c,v 1.43 1998/09/30 06:13:59 jb
     12  *
     13  */
     14 
     15 /*
     16  * Defining MALLOC_EXTRA_SANITY will enable extra checks which are related
     17  * to internal conditions and consistency in malloc.c. This has a
     18  * noticeable runtime performance hit, and generally will not do you
     19  * any good unless you fiddle with the internals of malloc or want
     20  * to catch random pointer corruption as early as possible.
     21  */
     22 #ifndef MALLOC_EXTRA_SANITY
     23 #undef MALLOC_EXTRA_SANITY
     24 #endif
     25 
     26 /*
     27  * What to use for Junk.  This is the byte value we use to fill with
     28  * when the 'J' option is enabled.
     29  */
     30 #define SOME_JUNK	0xd0		/* as in "Duh" :-) */
     31 
     32 /*
     33  * The basic parameters you can tweak.
     34  *
     35  * malloc_pageshift	pagesize = 1 << malloc_pageshift
     36  *			It's probably best if this is the native
     37  *			page size, but it doesn't have to be.
     38  *
     39  * malloc_minsize	minimum size of an allocation in bytes.
     40  *			If this is too small it's too much work
     41  *			to manage them.  This is also the smallest
     42  *			unit of alignment used for the storage
     43  *			returned by malloc/realloc.
     44  *
     45  */
     46 
     47 #if defined(__FreeBSD__)
     48 #   if defined(__i386__)
     49 #       define malloc_pageshift		12U
     50 #       define malloc_minsize		16U
     51 #   endif
     52 #   if defined(__alpha__)
     53 #       define malloc_pageshift		13U
     54 #       define malloc_minsize		16U
     55 #   endif
     56 #   if !defined(__NETBSD_SYSCALLS)
     57 #       define HAS_UTRACE
     58 #   endif
     59     /*
     60      * Make malloc/free/realloc thread-safe in libc for use with
     61      * kernel threads.
     62      */
     63 #   include "libc_private.h"
     64 #   include "spinlock.h"
     65     static spinlock_t thread_lock	= _SPINLOCK_INITIALIZER;
     66 #   define THREAD_LOCK()		if (__isthreaded) _SPINLOCK(&thread_lock);
     67 #   define THREAD_UNLOCK()		if (__isthreaded) _SPINUNLOCK(&thread_lock);
     68 #endif /* __FreeBSD__ */
     69 
     70 #if defined(__NetBSD__)
     71 #   include <sys/param.h>
     72 #   define malloc_pageshift             PGSHIFT
     73 #   define malloc_minsize               16U
     74 #endif /* __NetBSD__ */
     75 
     76 #if defined(__sparc__) && defined(sun)
     77 #   define malloc_pageshift		12U
     78 #   define malloc_minsize		16U
     79 #   define MAP_ANON			(0)
     80     static int fdzero;
     81 #   define MMAP_FD	fdzero
     82 #   define INIT_MMAP() \
     83 	{ if ((fdzero=open("/dev/zero", O_RDWR, 0000)) == -1) \
     84 	    wrterror("open of /dev/zero"); }
     85 #endif /* __sparc__ */
     86 
     87 /* Insert your combination here... */
     88 #if defined(__FOOCPU__) && defined(__BAROS__)
     89 #   define malloc_pageshift		12U
     90 #   define malloc_minsize		16U
     91 #endif /* __FOOCPU__ && __BAROS__ */
     92 
     93 
     94 /*
     95  * No user serviceable parts behind this point.
     96  */
     97 #include <sys/types.h>
     98 #include <sys/mman.h>
     99 #include <errno.h>
    100 #include <fcntl.h>
    101 #include <stddef.h>
    102 #include <stdio.h>
    103 #include <stdlib.h>
    104 #include <string.h>
    105 #include <unistd.h>
    106 
    107 /*
    108  * This structure describes a page worth of chunks.
    109  */
    110 
    111 struct pginfo {
    112     struct pginfo	*next;	/* next on the free list */
    113     void		*page;	/* Pointer to the page */
    114     u_short		size;	/* size of this page's chunks */
    115     u_short		shift;	/* How far to shift for this size chunks */
    116     u_short		free;	/* How many free chunks */
    117     u_short		total;	/* How many chunk */
    118     u_int		bits[1]; /* Which chunks are free */
    119 };
    120 
    121 /*
    122  * This structure describes a number of free pages.
    123  */
    124 
    125 struct pgfree {
    126     struct pgfree	*next;	/* next run of free pages */
    127     struct pgfree	*prev;	/* prev run of free pages */
    128     void		*page;	/* pointer to free pages */
    129     void		*end;	/* pointer to end of free pages */
    130     size_t		size;	/* number of bytes free */
    131 };
    132 
    133 /*
    134  * How many bits per u_int in the bitmap.
    135  * Change only if not 8 bits/byte
    136  */
    137 #define	MALLOC_BITS	(8*sizeof(u_int))
    138 
    139 /*
    140  * Magic values to put in the page_directory
    141  */
    142 #define MALLOC_NOT_MINE	((struct pginfo*) 0)
    143 #define MALLOC_FREE 	((struct pginfo*) 1)
    144 #define MALLOC_FIRST	((struct pginfo*) 2)
    145 #define MALLOC_FOLLOW	((struct pginfo*) 3)
    146 #define MALLOC_MAGIC	((struct pginfo*) 4)
    147 
    148 #ifndef malloc_pageshift
    149 #define malloc_pageshift		12U
    150 #endif
    151 
    152 #ifndef malloc_minsize
    153 #define malloc_minsize			16U
    154 #endif
    155 
    156 #if !defined(malloc_pagesize)
    157 #define malloc_pagesize			(1UL<<malloc_pageshift)
    158 #endif
    159 
    160 #if ((1<<malloc_pageshift) != malloc_pagesize)
    161 #error	"(1<<malloc_pageshift) != malloc_pagesize"
    162 #endif
    163 
    164 #ifndef malloc_maxsize
    165 #define malloc_maxsize			((malloc_pagesize)>>1)
    166 #endif
    167 
    168 /* A mask for the offset inside a page.  */
    169 #define malloc_pagemask	((malloc_pagesize)-1)
    170 
    171 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
    172 #define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)
    173 
    174 #ifndef THREAD_LOCK
    175 #define THREAD_LOCK()
    176 #endif
    177 
    178 #ifndef THREAD_UNLOCK
    179 #define THREAD_UNLOCK()
    180 #endif
    181 
    182 #ifndef MMAP_FD
    183 #define MMAP_FD (-1)
    184 #endif
    185 
    186 #ifndef INIT_MMAP
    187 #define INIT_MMAP()
    188 #endif
    189 
    190 #ifndef MADV_FREE
    191 #define MADV_FREE MADV_DONTNEED
    192 #endif
    193 
    194 /* Set when initialization has been done */
    195 static unsigned malloc_started;
    196 
    197 /* Recusion flag for public interface. */
    198 static int malloc_active;
    199 
    200 /* Number of free pages we cache */
    201 static unsigned malloc_cache = 16;
    202 
    203 /* The offset from pagenumber to index into the page directory */
    204 static u_long malloc_origo;
    205 
    206 /* The last index in the page directory we care about */
    207 static u_long last_index;
    208 
    209 /* Pointer to page directory. Allocated "as if with" malloc */
    210 static struct	pginfo **page_dir;
    211 
    212 /* How many slots in the page directory */
    213 static unsigned	malloc_ninfo;
    214 
    215 /* Free pages line up here */
    216 static struct pgfree free_list;
    217 
    218 /* Abort(), user doesn't handle problems.  */
    219 static int malloc_abort;
    220 
    221 /* Are we trying to die ?  */
    222 static int suicide;
    223 
    224 /* always realloc ?  */
    225 static int malloc_realloc;
    226 
    227 /* pass the kernel a hint on free pages ?  */
    228 static int malloc_hint = 1;
    229 
    230 /* xmalloc behaviour ?  */
    231 static int malloc_xmalloc;
    232 
    233 /* sysv behaviour for malloc(0) ?  */
    234 static int malloc_sysv;
    235 
    236 /* zero fill ?  */
    237 static int malloc_zero;
    238 
    239 /* junk fill ?  */
    240 static int malloc_junk;
    241 
    242 #ifdef HAS_UTRACE
    243 
    244 /* utrace ?  */
    245 static int malloc_utrace;
    246 
    247 struct ut { void *p; size_t s; void *r; };
    248 
    249 void utrace __P((struct ut *, int));
    250 
    251 #define UTRACE(a, b, c) \
    252 	if (malloc_utrace) \
    253 		{struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}
    254 #else /* !HAS_UTRACE */
    255 #define UTRACE(a,b,c)
    256 #endif /* HAS_UTRACE */
    257 
    258 /* my last break. */
    259 static void *malloc_brk;
    260 
    261 /* one location cache for free-list holders */
    262 static struct pgfree *px;
    263 
    264 /* compile-time options */
    265 char *malloc_options;
    266 
    267 /* Name of the current public function */
    268 static char *malloc_func;
    269 
    270 /* Macro for mmap */
    271 #define MMAP(size) \
    272 	mmap(0, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
    273 	    MMAP_FD, 0);
    274 
    275 /*
    276  * Necessary function declarations
    277  */
    278 static int extend_pgdir(u_long index);
    279 static void *imalloc(size_t size);
    280 static void ifree(void *ptr);
    281 static void *irealloc(void *ptr, size_t size);
    282 
    283 extern char *__progname;
    284 
    285 static void
    286 wrterror(char *p)
    287 {
    288     char *q = " error: ";
    289     write(STDERR_FILENO, __progname, strlen(__progname));
    290     write(STDERR_FILENO, malloc_func, strlen(malloc_func));
    291     write(STDERR_FILENO, q, strlen(q));
    292     write(STDERR_FILENO, p, strlen(p));
    293     suicide = 1;
    294     abort();
    295 }
    296 
    297 static void
    298 wrtwarning(char *p)
    299 {
    300     char *q = " warning: ";
    301     if (malloc_abort)
    302 	wrterror(p);
    303     write(STDERR_FILENO, __progname, strlen(__progname));
    304     write(STDERR_FILENO, malloc_func, strlen(malloc_func));
    305     write(STDERR_FILENO, q, strlen(q));
    306     write(STDERR_FILENO, p, strlen(p));
    307 }
    308 
    309 
    310 /*
    311  * Allocate a number of pages from the OS
    312  */
    313 static void *
    314 map_pages(int pages)
    315 {
    316     caddr_t result, tail;
    317 
    318     result = (caddr_t)pageround((u_long)sbrk(0));
    319     tail = result + (pages << malloc_pageshift);
    320 
    321     if (brk(tail)) {
    322 #ifdef MALLOC_EXTRA_SANITY
    323 	wrterror("(ES): map_pages fails\n");
    324 #endif /* MALLOC_EXTRA_SANITY */
    325 	return 0;
    326     }
    327 
    328     last_index = ptr2index(tail) - 1;
    329     malloc_brk = tail;
    330 
    331     if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index))
    332 	return 0;;
    333 
    334     return result;
    335 }
    336 
    337 /*
    338  * Extend page directory
    339  */
    340 static int
    341 extend_pgdir(u_long index)
    342 {
    343     struct  pginfo **new, **old;
    344     int i, oldlen;
    345 
    346     /* Make it this many pages */
    347     i = index * sizeof *page_dir;
    348     i /= malloc_pagesize;
    349     i += 2;
    350 
    351     /* remember the old mapping size */
    352     oldlen = malloc_ninfo * sizeof *page_dir;
    353 
    354     /*
    355      * NOTE: we allocate new pages and copy the directory rather than tempt
    356      * fate by trying to "grow" the region.. There is nothing to prevent
    357      * us from accidently re-mapping space that's been allocated by our caller
    358      * via dlopen() or other mmap().
    359      *
    360      * The copy problem is not too bad, as there is 4K of page index per
    361      * 4MB of malloc arena.
    362      *
    363      * We can totally avoid the copy if we open a file descriptor to associate
    364      * the anon mappings with.  Then, when we remap the pages at the new
    365      * address, the old pages will be "magically" remapped..  But this means
    366      * keeping open a "secret" file descriptor.....
    367      */
    368 
    369     /* Get new pages */
    370     new = (struct pginfo**) MMAP(i * malloc_pagesize);
    371     if (new == (struct pginfo **)-1)
    372 	return 0;
    373 
    374     /* Copy the old stuff */
    375     memcpy(new, page_dir,
    376 	    malloc_ninfo * sizeof *page_dir);
    377 
    378     /* register the new size */
    379     malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
    380 
    381     /* swap the pointers */
    382     old = page_dir;
    383     page_dir = new;
    384 
    385     /* Now free the old stuff */
    386     munmap(old, oldlen);
    387     return 1;
    388 }
    389 
    390 /*
    391  * Initialize the world
    392  */
    393 static void
    394 malloc_init (void)
    395 {
    396     char *p, b[64];
    397     int i, j;
    398     int errnosave;
    399 
    400     INIT_MMAP();
    401 
    402 #ifdef MALLOC_EXTRA_SANITY
    403     malloc_junk = 1;
    404 #endif /* MALLOC_EXTRA_SANITY */
    405 
    406     for (i = 0; i < 3; i++) {
    407 	if (i == 0) {
    408 	    errnosave = errno;
    409 	    j = readlink("/etc/malloc.conf", b, sizeof b - 1);
    410 	    errno = errnosave;
    411 	    if (j <= 0)
    412 		continue;
    413 	    b[j] = '\0';
    414 	    p = b;
    415 	} else if (i == 1) {
    416 	    p = getenv("MALLOC_OPTIONS");
    417 	} else {
    418 	    p = malloc_options;
    419 	}
    420 	for (; p && *p; p++) {
    421 	    switch (*p) {
    422 		case '>': malloc_cache   <<= 1; break;
    423 		case '<': malloc_cache   >>= 1; break;
    424 		case 'a': malloc_abort   = 0; break;
    425 		case 'A': malloc_abort   = 1; break;
    426 		case 'h': malloc_hint    = 0; break;
    427 		case 'H': malloc_hint    = 1; break;
    428 		case 'r': malloc_realloc = 0; break;
    429 		case 'R': malloc_realloc = 1; break;
    430 		case 'j': malloc_junk    = 0; break;
    431 		case 'J': malloc_junk    = 1; break;
    432 #ifdef HAS_UTRACE
    433 		case 'u': malloc_utrace  = 0; break;
    434 		case 'U': malloc_utrace  = 1; break;
    435 #endif
    436 		case 'v': malloc_sysv    = 0; break;
    437 		case 'V': malloc_sysv    = 1; break;
    438 		case 'x': malloc_xmalloc = 0; break;
    439 		case 'X': malloc_xmalloc = 1; break;
    440 		case 'z': malloc_zero    = 0; break;
    441 		case 'Z': malloc_zero    = 1; break;
    442 		default:
    443 		    j = malloc_abort;
    444 		    malloc_abort = 0;
    445 		    wrtwarning("unknown char in MALLOC_OPTIONS\n");
    446 		    malloc_abort = j;
    447 		    break;
    448 	    }
    449 	}
    450     }
    451 
    452     UTRACE(0, 0, 0);
    453 
    454     /*
    455      * We want junk in the entire allocation, and zero only in the part
    456      * the user asked for.
    457      */
    458     if (malloc_zero)
    459 	malloc_junk=1;
    460 
    461     /*
    462      * If we run with junk (or implicitly from above: zero), we want to
    463      * force realloc() to get new storage, so we can DTRT with it.
    464      */
    465     if (malloc_junk)
    466 	malloc_realloc=1;
    467 
    468     /* Allocate one page for the page directory */
    469     page_dir = (struct pginfo **) MMAP(malloc_pagesize);
    470 
    471     if (page_dir == (struct pginfo **) -1)
    472 	wrterror("mmap(2) failed, check limits.\n");
    473 
    474     /*
    475      * We need a maximum of malloc_pageshift buckets, steal these from the
    476      * front of the page_directory;
    477      */
    478     malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift;
    479     malloc_origo -= malloc_pageshift;
    480 
    481     malloc_ninfo = malloc_pagesize / sizeof *page_dir;
    482 
    483     /* Recalculate the cache size in bytes, and make sure it's nonzero */
    484 
    485     if (!malloc_cache)
    486 	malloc_cache++;
    487 
    488     malloc_cache <<= malloc_pageshift;
    489 
    490     /*
    491      * This is a nice hack from Kaleb Keithly (kaleb (at) x.org).
    492      * We can sbrk(2) further back when we keep this on a low address.
    493      */
    494     px = (struct pgfree *) imalloc (sizeof *px);
    495 
    496     /* Been here, done that */
    497     malloc_started++;
    498 }
    499 
    500 /*
    501  * Allocate a number of complete pages
    502  */
    503 static void *
    504 malloc_pages(size_t size)
    505 {
    506     void *p, *delay_free = 0;
    507     int i;
    508     struct pgfree *pf;
    509     u_long index;
    510 
    511     size = pageround(size);
    512 
    513     p = 0;
    514 
    515     /* Look for free pages before asking for more */
    516     for(pf = free_list.next; pf; pf = pf->next) {
    517 
    518 #ifdef MALLOC_EXTRA_SANITY
    519 	if (pf->size & malloc_pagemask)
    520 	    wrterror("(ES): junk length entry on free_list\n");
    521 	if (!pf->size)
    522 	    wrterror("(ES): zero length entry on free_list\n");
    523 	if (pf->page == pf->end)
    524 	    wrterror("(ES): zero entry on free_list\n");
    525 	if (pf->page > pf->end)
    526 	    wrterror("(ES): sick entry on free_list\n");
    527 	if ((void*)pf->page >= (void*)sbrk(0))
    528 	    wrterror("(ES): entry on free_list past brk\n");
    529 	if (page_dir[ptr2index(pf->page)] != MALLOC_FREE)
    530 	    wrterror("(ES): non-free first page on free-list\n");
    531 	if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE)
    532 	    wrterror("(ES): non-free last page on free-list\n");
    533 #endif /* MALLOC_EXTRA_SANITY */
    534 
    535 	if (pf->size < size)
    536 	    continue;
    537 
    538 	if (pf->size == size) {
    539 	    p = pf->page;
    540 	    if (pf->next)
    541 		    pf->next->prev = pf->prev;
    542 	    pf->prev->next = pf->next;
    543 	    delay_free = pf;
    544 	    break;
    545 	}
    546 
    547 	p = pf->page;
    548 	pf->page = (char *)pf->page + size;
    549 	pf->size -= size;
    550 	break;
    551     }
    552 
    553 #ifdef MALLOC_EXTRA_SANITY
    554     if (p && page_dir[ptr2index(p)] != MALLOC_FREE)
    555 	wrterror("(ES): allocated non-free page on free-list\n");
    556 #endif /* MALLOC_EXTRA_SANITY */
    557 
    558     size >>= malloc_pageshift;
    559 
    560     /* Map new pages */
    561     if (!p)
    562 	p = map_pages(size);
    563 
    564     if (p) {
    565 
    566 	index = ptr2index(p);
    567 	page_dir[index] = MALLOC_FIRST;
    568 	for (i=1;i<size;i++)
    569 	    page_dir[index+i] = MALLOC_FOLLOW;
    570 
    571 	if (malloc_junk)
    572 	    memset(p, SOME_JUNK, size << malloc_pageshift);
    573     }
    574 
    575     if (delay_free) {
    576 	if (!px)
    577 	    px = delay_free;
    578 	else
    579 	    ifree(delay_free);
    580     }
    581 
    582     return p;
    583 }
    584 
    585 /*
    586  * Allocate a page of fragments
    587  */
    588 
    589 static __inline__ int
    590 malloc_make_chunks(int bits)
    591 {
    592     struct  pginfo *bp;
    593     void *pp;
    594     int i, k, l;
    595 
    596     /* Allocate a new bucket */
    597     pp = malloc_pages(malloc_pagesize);
    598     if (!pp)
    599 	return 0;
    600 
    601     /* Find length of admin structure */
    602     l = offsetof(struct pginfo, bits[0]);
    603     l += sizeof bp->bits[0] *
    604 	(((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
    605 
    606     /* Don't waste more than two chunks on this */
    607     if ((1<<(bits)) <= l+l) {
    608 	bp = (struct  pginfo *)pp;
    609     } else {
    610 	bp = (struct  pginfo *)imalloc(l);
    611 	if (!bp) {
    612 	    ifree(pp);
    613 	    return 0;
    614 	}
    615     }
    616 
    617     bp->size = (1<<bits);
    618     bp->shift = bits;
    619     bp->total = bp->free = malloc_pagesize >> bits;
    620     bp->page = pp;
    621 
    622     /* set all valid bits in the bitmap */
    623     k = bp->total;
    624     i = 0;
    625 
    626     /* Do a bunch at a time */
    627     for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
    628 	bp->bits[i / MALLOC_BITS] = ~0;
    629 
    630     for(; i < k; i++)
    631         bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
    632 
    633     if (bp == bp->page) {
    634 	/* Mark the ones we stole for ourselves */
    635 	for(i=0;l > 0;i++) {
    636 	    bp->bits[i/MALLOC_BITS] &= ~(1<<(i%MALLOC_BITS));
    637 	    bp->free--;
    638 	    bp->total--;
    639 	    l -= (1 << bits);
    640 	}
    641     }
    642 
    643     /* MALLOC_LOCK */
    644 
    645     page_dir[ptr2index(pp)] = bp;
    646 
    647     bp->next = page_dir[bits];
    648     page_dir[bits] = bp;
    649 
    650     /* MALLOC_UNLOCK */
    651 
    652     return 1;
    653 }
    654 
    655 /*
    656  * Allocate a fragment
    657  */
    658 static void *
    659 malloc_bytes(size_t size)
    660 {
    661     int i,j;
    662     u_int u;
    663     struct  pginfo *bp;
    664     int k;
    665     u_int *lp;
    666 
    667     /* Don't bother with anything less than this */
    668     if (size < malloc_minsize)
    669 	size = malloc_minsize;
    670 
    671     /* Find the right bucket */
    672     j = 1;
    673     i = size-1;
    674     while (i >>= 1)
    675 	j++;
    676 
    677     /* If it's empty, make a page more of that size chunks */
    678     if (!page_dir[j] && !malloc_make_chunks(j))
    679 	return 0;
    680 
    681     bp = page_dir[j];
    682 
    683     /* Find first word of bitmap which isn't empty */
    684     for (lp = bp->bits; !*lp; lp++)
    685 	;
    686 
    687     /* Find that bit, and tweak it */
    688     u = 1;
    689     k = 0;
    690     while (!(*lp & u)) {
    691 	u += u;
    692 	k++;
    693     }
    694     *lp ^= u;
    695 
    696     /* If there are no more free, remove from free-list */
    697     if (!--bp->free) {
    698 	page_dir[j] = bp->next;
    699 	bp->next = 0;
    700     }
    701 
    702     /* Adjust to the real offset of that chunk */
    703     k += (lp-bp->bits)*MALLOC_BITS;
    704     k <<= bp->shift;
    705 
    706     if (malloc_junk)
    707 	memset((u_char*)bp->page + k, SOME_JUNK, bp->size);
    708 
    709     return (u_char *)bp->page + k;
    710 }
    711 
    712 /*
    713  * Allocate a piece of memory
    714  */
    715 static void *
    716 imalloc(size_t size)
    717 {
    718     void *result;
    719 
    720     if (suicide)
    721 	abort();
    722 
    723     if ((size + malloc_pagesize) < size)	/* Check for overflow */
    724 	result = 0;
    725     else if (size <= malloc_maxsize)
    726 	result =  malloc_bytes(size);
    727     else
    728 	result =  malloc_pages(size);
    729 
    730     if (malloc_abort && !result)
    731 	wrterror("allocation failed.\n");
    732 
    733     if (malloc_zero && result)
    734 	memset(result, 0, size);
    735 
    736     return result;
    737 }
    738 
    739 /*
    740  * Change the size of an allocation.
    741  */
    742 static void *
    743 irealloc(void *ptr, size_t size)
    744 {
    745     void *p;
    746     u_long osize, index;
    747     struct pginfo **mp;
    748     int i;
    749 
    750     if (suicide)
    751 	abort();
    752 
    753     index = ptr2index(ptr);
    754 
    755     if (index < malloc_pageshift) {
    756 	wrtwarning("junk pointer, too low to make sense.\n");
    757 	return 0;
    758     }
    759 
    760     if (index > last_index) {
    761 	wrtwarning("junk pointer, too high to make sense.\n");
    762 	return 0;
    763     }
    764 
    765     mp = &page_dir[index];
    766 
    767     if (*mp == MALLOC_FIRST) {			/* Page allocation */
    768 
    769 	/* Check the pointer */
    770 	if ((u_long)ptr & malloc_pagemask) {
    771 	    wrtwarning("modified (page-) pointer.\n");
    772 	    return 0;
    773 	}
    774 
    775 	/* Find the size in bytes */
    776 	for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
    777 	    osize += malloc_pagesize;
    778 
    779         if (!malloc_realloc && 			/* unless we have to, */
    780 	  size <= osize && 			/* .. or are too small, */
    781 	  size > (osize - malloc_pagesize)) {	/* .. or can free a page, */
    782 	    return ptr;				/* don't do anything. */
    783 	}
    784 
    785     } else if (*mp >= MALLOC_MAGIC) {		/* Chunk allocation */
    786 
    787 	/* Check the pointer for sane values */
    788 	if (((u_long)ptr & ((*mp)->size-1))) {
    789 	    wrtwarning("modified (chunk-) pointer.\n");
    790 	    return 0;
    791 	}
    792 
    793 	/* Find the chunk index in the page */
    794 	i = ((u_long)ptr & malloc_pagemask) >> (*mp)->shift;
    795 
    796 	/* Verify that it isn't a free chunk already */
    797         if ((*mp)->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
    798 	    wrtwarning("chunk is already free.\n");
    799 	    return 0;
    800 	}
    801 
    802 	osize = (*mp)->size;
    803 
    804 	if (!malloc_realloc &&		/* Unless we have to, */
    805 	  size < osize && 		/* ..or are too small, */
    806 	  (size > osize/2 ||	 	/* ..or could use a smaller size, */
    807 	  osize == malloc_minsize)) {	/* ..(if there is one) */
    808 	    return ptr;			/* ..Don't do anything */
    809 	}
    810 
    811     } else {
    812 	wrtwarning("pointer to wrong page.\n");
    813 	return 0;
    814     }
    815 
    816     p = imalloc(size);
    817 
    818     if (p) {
    819 	/* copy the lesser of the two sizes, and free the old one */
    820 	if (!size || !osize)
    821 	    ;
    822 	else if (osize < size)
    823 	    memcpy(p, ptr, osize);
    824 	else
    825 	    memcpy(p, ptr, size);
    826 	ifree(ptr);
    827     }
    828     return p;
    829 }
    830 
    831 /*
    832  * Free a sequence of pages
    833  */
    834 
    835 static __inline__ void
    836 free_pages(void *ptr, int index, struct pginfo *info)
    837 {
    838     int i;
    839     struct pgfree *pf, *pt=0;
    840     u_long l;
    841     void *tail;
    842 
    843     if (info == MALLOC_FREE) {
    844 	wrtwarning("page is already free.\n");
    845 	return;
    846     }
    847 
    848     if (info != MALLOC_FIRST) {
    849 	wrtwarning("pointer to wrong page.\n");
    850 	return;
    851     }
    852 
    853     if ((u_long)ptr & malloc_pagemask) {
    854 	wrtwarning("modified (page-) pointer.\n");
    855 	return;
    856     }
    857 
    858     /* Count how many pages and mark them free at the same time */
    859     page_dir[index] = MALLOC_FREE;
    860     for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
    861 	page_dir[index + i] = MALLOC_FREE;
    862 
    863     l = i << malloc_pageshift;
    864 
    865     if (malloc_junk)
    866 	memset(ptr, SOME_JUNK, l);
    867 
    868     if (malloc_hint)
    869 	madvise(ptr, l, MADV_FREE);
    870 
    871     tail = (char *)ptr+l;
    872 
    873     /* add to free-list */
    874     if (!px)
    875 	px = imalloc(sizeof *pt);	/* This cannot fail... */
    876     px->page = ptr;
    877     px->end =  tail;
    878     px->size = l;
    879     if (!free_list.next) {
    880 
    881 	/* Nothing on free list, put this at head */
    882 	px->next = free_list.next;
    883 	px->prev = &free_list;
    884 	free_list.next = px;
    885 	pf = px;
    886 	px = 0;
    887 
    888     } else {
    889 
    890 	/* Find the right spot, leave pf pointing to the modified entry. */
    891 	tail = (char *)ptr+l;
    892 
    893 	for(pf = free_list.next; pf->end < ptr && pf->next; pf = pf->next)
    894 	    ; /* Race ahead here */
    895 
    896 	if (pf->page > tail) {
    897 	    /* Insert before entry */
    898 	    px->next = pf;
    899 	    px->prev = pf->prev;
    900 	    pf->prev = px;
    901 	    px->prev->next = px;
    902 	    pf = px;
    903 	    px = 0;
    904 	} else if (pf->end == ptr ) {
    905 	    /* Append to the previous entry */
    906 	    pf->end = (char *)pf->end + l;
    907 	    pf->size += l;
    908 	    if (pf->next && pf->end == pf->next->page ) {
    909 		/* And collapse the next too. */
    910 		pt = pf->next;
    911 		pf->end = pt->end;
    912 		pf->size += pt->size;
    913 		pf->next = pt->next;
    914 		if (pf->next)
    915 		    pf->next->prev = pf;
    916 	    }
    917 	} else if (pf->page == tail) {
    918 	    /* Prepend to entry */
    919 	    pf->size += l;
    920 	    pf->page = ptr;
    921 	} else if (!pf->next) {
    922 	    /* Append at tail of chain */
    923 	    px->next = 0;
    924 	    px->prev = pf;
    925 	    pf->next = px;
    926 	    pf = px;
    927 	    px = 0;
    928 	} else {
    929 	    wrterror("freelist is destroyed.\n");
    930 	}
    931     }
    932 
    933     /* Return something to OS ? */
    934     if (!pf->next &&				/* If we're the last one, */
    935       pf->size > malloc_cache &&		/* ..and the cache is full, */
    936       pf->end == malloc_brk &&			/* ..and none behind us, */
    937       malloc_brk == sbrk(0)) {			/* ..and it's OK to do... */
    938 
    939 	/*
    940 	 * Keep the cache intact.  Notice that the '>' above guarantees that
    941 	 * the pf will always have at least one page afterwards.
    942 	 */
    943 	pf->end = (char *)pf->page + malloc_cache;
    944 	pf->size = malloc_cache;
    945 
    946 	brk(pf->end);
    947 	malloc_brk = pf->end;
    948 
    949 	index = ptr2index(pf->end);
    950 	last_index = index - 1;
    951 
    952 	for(i=index;i <= last_index;)
    953 	    page_dir[i++] = MALLOC_NOT_MINE;
    954 
    955 	/* XXX: We could realloc/shrink the pagedir here I guess. */
    956     }
    957     if (pt)
    958 	ifree(pt);
    959 }
    960 
    961 /*
    962  * Free a chunk, and possibly the page it's on, if the page becomes empty.
    963  */
    964 
    965 static __inline__ void
    966 free_bytes(void *ptr, int index, struct pginfo *info)
    967 {
    968     int i;
    969     struct pginfo **mp;
    970     void *vp;
    971 
    972     /* Find the chunk number on the page */
    973     i = ((u_long)ptr & malloc_pagemask) >> info->shift;
    974 
    975     if (((u_long)ptr & (info->size-1))) {
    976 	wrtwarning("modified (chunk-) pointer.\n");
    977 	return;
    978     }
    979 
    980     if (info->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
    981 	wrtwarning("chunk is already free.\n");
    982 	return;
    983     }
    984 
    985     if (malloc_junk)
    986 	memset(ptr, SOME_JUNK, info->size);
    987 
    988     info->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
    989     info->free++;
    990 
    991     mp = page_dir + info->shift;
    992 
    993     if (info->free == 1) {
    994 
    995 	/* Page became non-full */
    996 
    997 	mp = page_dir + info->shift;
    998 	/* Insert in address order */
    999 	while (*mp && (*mp)->next && (*mp)->next->page < info->page)
   1000 	    mp = &(*mp)->next;
   1001 	info->next = *mp;
   1002 	*mp = info;
   1003 	return;
   1004     }
   1005 
   1006     if (info->free != info->total)
   1007 	return;
   1008 
   1009     /* Find & remove this page in the queue */
   1010     while (*mp != info) {
   1011 	mp = &((*mp)->next);
   1012 #ifdef MALLOC_EXTRA_SANITY
   1013 	if (!*mp)
   1014 		wrterror("(ES): Not on queue\n");
   1015 #endif /* MALLOC_EXTRA_SANITY */
   1016     }
   1017     *mp = info->next;
   1018 
   1019     /* Free the page & the info structure if need be */
   1020     page_dir[ptr2index(info->page)] = MALLOC_FIRST;
   1021     vp = info->page;		/* Order is important ! */
   1022     if(vp != (void*)info)
   1023 	ifree(info);
   1024     ifree(vp);
   1025 }
   1026 
   1027 static void
   1028 ifree(void *ptr)
   1029 {
   1030     struct pginfo *info;
   1031     int index;
   1032 
   1033     /* This is legal */
   1034     if (!ptr)
   1035 	return;
   1036 
   1037     if (!malloc_started) {
   1038 	wrtwarning("malloc() has never been called.\n");
   1039 	return;
   1040     }
   1041 
   1042     /* If we're already sinking, don't make matters any worse. */
   1043     if (suicide)
   1044 	return;
   1045 
   1046     index = ptr2index(ptr);
   1047 
   1048     if (index < malloc_pageshift) {
   1049 	wrtwarning("junk pointer, too low to make sense.\n");
   1050 	return;
   1051     }
   1052 
   1053     if (index > last_index) {
   1054 	wrtwarning("junk pointer, too high to make sense.\n");
   1055 	return;
   1056     }
   1057 
   1058     info = page_dir[index];
   1059 
   1060     if (info < MALLOC_MAGIC)
   1061         free_pages(ptr, index, info);
   1062     else
   1063 	free_bytes(ptr, index, info);
   1064     return;
   1065 }
   1066 
   1067 /*
   1068  * These are the public exported interface routines.
   1069  */
   1070 
   1071 
   1072 void *
   1073 malloc(size_t size)
   1074 {
   1075     register void *r;
   1076 
   1077     THREAD_LOCK();
   1078     malloc_func = " in malloc():";
   1079     if (malloc_active++) {
   1080 	wrtwarning("recursive call.\n");
   1081         malloc_active--;
   1082 	return (0);
   1083     }
   1084     if (!malloc_started)
   1085 	malloc_init();
   1086     if (malloc_sysv && !size)
   1087 	r = 0;
   1088     else
   1089 	r = imalloc(size);
   1090     UTRACE(0, size, r);
   1091     malloc_active--;
   1092     THREAD_UNLOCK();
   1093     if (malloc_xmalloc && !r)
   1094 	wrterror("out of memory.\n");
   1095     return (r);
   1096 }
   1097 
   1098 void
   1099 free(void *ptr)
   1100 {
   1101     THREAD_LOCK();
   1102     malloc_func = " in free():";
   1103     if (malloc_active++) {
   1104 	wrtwarning("recursive call.\n");
   1105 	malloc_active--;
   1106 	return;
   1107     } else {
   1108 	ifree(ptr);
   1109 	UTRACE(ptr, 0, 0);
   1110     }
   1111     malloc_active--;
   1112     THREAD_UNLOCK();
   1113     return;
   1114 }
   1115 
   1116 void *
   1117 realloc(void *ptr, size_t size)
   1118 {
   1119     register void *r;
   1120 
   1121     THREAD_LOCK();
   1122     malloc_func = " in realloc():";
   1123     if (malloc_active++) {
   1124 	wrtwarning("recursive call.\n");
   1125         malloc_active--;
   1126 	return (0);
   1127     }
   1128     if (ptr && !malloc_started) {
   1129 	wrtwarning("malloc() has never been called.\n");
   1130 	ptr = 0;
   1131     }
   1132     if (!malloc_started)
   1133 	malloc_init();
   1134     if (malloc_sysv && !size) {
   1135 	ifree(ptr);
   1136 	r = 0;
   1137     } else if (!ptr) {
   1138 	r = imalloc(size);
   1139     } else {
   1140         r = irealloc(ptr, size);
   1141     }
   1142     UTRACE(ptr, size, r);
   1143     malloc_active--;
   1144     THREAD_UNLOCK();
   1145     if (malloc_xmalloc && !r)
   1146 	wrterror("out of memory.\n");
   1147     return (r);
   1148 }
   1149