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