malloc.c revision 110801
190792Sgshapiro/*- 2261363Sgshapiro * Copyright (c) 1983 Regents of the University of California. 390792Sgshapiro * All rights reserved. 490792Sgshapiro * 590792Sgshapiro * Redistribution and use in source and binary forms, with or without 690792Sgshapiro * modification, are permitted provided that the following conditions 790792Sgshapiro * are met: 890792Sgshapiro * 1. Redistributions of source code must retain the above copyright 990792Sgshapiro * notice, this list of conditions and the following disclaimer. 1090792Sgshapiro * 2. Redistributions in binary form must reproduce the above copyright 1190792Sgshapiro * notice, this list of conditions and the following disclaimer in the 1290792Sgshapiro * documentation and/or other materials provided with the distribution. 1390792Sgshapiro * 3. All advertising materials mentioning features or use of this software 14266692Sgshapiro * must display the following acknowledgement: 1590792Sgshapiro * This product includes software developed by the University of 1690792Sgshapiro * California, Berkeley and its contributors. 1790792Sgshapiro * 4. Neither the name of the University nor the names of its contributors 1890792Sgshapiro * may be used to endorse or promote products derived from this software 1990792Sgshapiro * without specific prior written permission. 2090792Sgshapiro * 2190792Sgshapiro * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22157001Sgshapiro * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 2390792Sgshapiro * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 2490792Sgshapiro * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 2590792Sgshapiro * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 2690792Sgshapiro * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 2790792Sgshapiro * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 2890792Sgshapiro * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 2990792Sgshapiro * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 3090792Sgshapiro * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 3190792Sgshapiro * SUCH DAMAGE. 3290792Sgshapiro */ 3390792Sgshapiro 3490792Sgshapiro#if defined(LIBC_SCCS) && !defined(lint) 3590792Sgshapiro/*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/ 3690792Sgshapirostatic char *rcsid = "$FreeBSD: head/libexec/rtld-elf/malloc.c 110801 2003-02-13 17:05:10Z kan $"; 3790792Sgshapiro#endif /* LIBC_SCCS and not lint */ 3890792Sgshapiro 3990792Sgshapiro/* 4090792Sgshapiro * malloc.c (Caltech) 2/21/82 4190792Sgshapiro * Chris Kingsley, kingsley@cit-20. 4290792Sgshapiro * 4390792Sgshapiro * This is a very fast storage allocator. It allocates blocks of a small 4490792Sgshapiro * number of different sizes, and keeps free lists of each size. Blocks that 4590792Sgshapiro * don't exactly fit are passed up to the next larger size. In this 4690792Sgshapiro * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long. 4790792Sgshapiro * This is designed for use in a virtual memory environment. 4890792Sgshapiro */ 4990792Sgshapiro 5090792Sgshapiro#include <sys/types.h> 5190792Sgshapiro#include <err.h> 5290792Sgshapiro#include <paths.h> 5390792Sgshapiro#include <stdlib.h> 5490792Sgshapiro#include <string.h> 5590792Sgshapiro#include <stddef.h> 5690792Sgshapiro#include <unistd.h> 5790792Sgshapiro#include <sys/param.h> 5890792Sgshapiro#include <sys/mman.h> 5990792Sgshapiro#ifndef BSD 6090792Sgshapiro#define MAP_COPY MAP_PRIVATE 6190792Sgshapiro#define MAP_FILE 0 6290792Sgshapiro#define MAP_ANON 0 6390792Sgshapiro#endif 6490792Sgshapiro 6590792Sgshapiro#ifndef BSD /* Need do better than this */ 6690792Sgshapiro#define NEED_DEV_ZERO 1 6790792Sgshapiro#endif 6890792Sgshapiro 6990792Sgshapirostatic void morecore(); 7090792Sgshapirostatic int findbucket(); 7190792Sgshapiro 7290792Sgshapiro/* 7390792Sgshapiro * Pre-allocate mmap'ed pages 7490792Sgshapiro */ 7590792Sgshapiro#define NPOOLPAGES (32*1024/pagesz) 7690792Sgshapirostatic caddr_t pagepool_start, pagepool_end; 7790792Sgshapirostatic int morepages(); 7890792Sgshapiro 7990792Sgshapiro/* 8090792Sgshapiro * The overhead on a block is at least 4 bytes. When free, this space 8190792Sgshapiro * contains a pointer to the next free block, and the bottom two bits must 8290792Sgshapiro * be zero. When in use, the first byte is set to MAGIC, and the second 8390792Sgshapiro * byte is the size index. The remaining bytes are for alignment. 8490792Sgshapiro * If range checking is enabled then a second word holds the size of the 8590792Sgshapiro * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). 8690792Sgshapiro * The order of elements is critical: ov_magic must overlay the low order 8790792Sgshapiro * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. 8890792Sgshapiro */ 8990792Sgshapirounion overhead { 9090792Sgshapiro union overhead *ov_next; /* when free */ 9190792Sgshapiro struct { 9290792Sgshapiro u_char ovu_magic; /* magic number */ 9390792Sgshapiro u_char ovu_index; /* bucket # */ 9490792Sgshapiro#ifdef RCHECK 9590792Sgshapiro u_short ovu_rmagic; /* range magic number */ 9690792Sgshapiro u_int ovu_size; /* actual block size */ 9790792Sgshapiro#endif 9890792Sgshapiro } ovu; 9990792Sgshapiro#define ov_magic ovu.ovu_magic 10094334Sgshapiro#define ov_index ovu.ovu_index 10190792Sgshapiro#define ov_rmagic ovu.ovu_rmagic 10290792Sgshapiro#define ov_size ovu.ovu_size 10390792Sgshapiro}; 10490792Sgshapiro 105168515Sgshapiro#define MAGIC 0xef /* magic # on accounting info */ 106168515Sgshapiro#define RMAGIC 0x5555 /* magic # on range info */ 10790792Sgshapiro 10890792Sgshapiro#ifdef RCHECK 10990792Sgshapiro#define RSLOP sizeof (u_short) 11090792Sgshapiro#else 11190792Sgshapiro#define RSLOP 0 11290792Sgshapiro#endif 11390792Sgshapiro 11490792Sgshapiro/* 11590792Sgshapiro * nextf[i] is the pointer to the next free block of size 2^(i+3). The 11690792Sgshapiro * smallest allocatable block is 8 bytes. The overhead information 11790792Sgshapiro * precedes the data area returned to the user. 11890792Sgshapiro */ 11990792Sgshapiro#define NBUCKETS 30 12090792Sgshapirostatic union overhead *nextf[NBUCKETS]; 12190792Sgshapiro 12290792Sgshapirostatic int pagesz; /* page size */ 12390792Sgshapirostatic int pagebucket; /* page size bucket */ 12490792Sgshapiro 12590792Sgshapiro#ifdef MSTATS 12690792Sgshapiro/* 12790792Sgshapiro * nmalloc[i] is the difference between the number of mallocs and frees 12890792Sgshapiro * for a given block size. 12990792Sgshapiro */ 13090792Sgshapirostatic u_int nmalloc[NBUCKETS]; 13190792Sgshapiro#include <stdio.h> 13290792Sgshapiro#endif 13390792Sgshapiro 13490792Sgshapiro#if defined(MALLOC_DEBUG) || defined(RCHECK) 13590792Sgshapiro#define ASSERT(p) if (!(p)) botch("p") 13690792Sgshapiro#include <stdio.h> 13790792Sgshapirostatic void 13890792Sgshapirobotch(s) 13990792Sgshapiro char *s; 14090792Sgshapiro{ 14190792Sgshapiro fprintf(stderr, "\r\nassertion botched: %s\r\n", s); 14290792Sgshapiro (void) fflush(stderr); /* just in case user buffered it */ 14390792Sgshapiro abort(); 14490792Sgshapiro} 14590792Sgshapiro#else 14690792Sgshapiro#define ASSERT(p) 14790792Sgshapiro#endif 14890792Sgshapiro 14990792Sgshapiro/* Debugging stuff */ 15090792Sgshapirostatic void xprintf(const char *, ...); 15190792Sgshapiro#define TRACE() xprintf("TRACE %s:%d\n", __FILE__, __LINE__) 15290792Sgshapiro 15390792Sgshapirovoid * 15490792Sgshapiromalloc(nbytes) 15590792Sgshapiro size_t nbytes; 15690792Sgshapiro{ 15790792Sgshapiro register union overhead *op; 15890792Sgshapiro register int bucket; 15990792Sgshapiro register long n; 16090792Sgshapiro register unsigned amt; 161157001Sgshapiro 16290792Sgshapiro /* 16390792Sgshapiro * First time malloc is called, setup page size and 16490792Sgshapiro * align break pointer so all data will be page aligned. 16590792Sgshapiro */ 16690792Sgshapiro if (pagesz == 0) { 16790792Sgshapiro pagesz = n = getpagesize(); 16890792Sgshapiro if (morepages(NPOOLPAGES) == 0) 16990792Sgshapiro return NULL; 17090792Sgshapiro op = (union overhead *)(pagepool_start); 17190792Sgshapiro n = n - sizeof (*op) - ((long)op & (n - 1)); 17290792Sgshapiro if (n < 0) 17390792Sgshapiro n += pagesz; 17490792Sgshapiro if (n) { 17590792Sgshapiro pagepool_start += n; 17690792Sgshapiro } 17790792Sgshapiro bucket = 0; 17890792Sgshapiro amt = 8; 17990792Sgshapiro while (pagesz > amt) { 18090792Sgshapiro amt <<= 1; 18190792Sgshapiro bucket++; 18290792Sgshapiro } 18390792Sgshapiro pagebucket = bucket; 18490792Sgshapiro } 18590792Sgshapiro /* 18690792Sgshapiro * Convert amount of memory requested into closest block size 18790792Sgshapiro * stored in hash buckets which satisfies request. 18890792Sgshapiro * Account for space used per block for accounting. 18990792Sgshapiro */ 19090792Sgshapiro if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) { 19190792Sgshapiro#ifndef RCHECK 19290792Sgshapiro amt = 8; /* size of first bucket */ 19390792Sgshapiro bucket = 0; 19490792Sgshapiro#else 19590792Sgshapiro amt = 16; /* size of first bucket */ 19690792Sgshapiro bucket = 1; 19790792Sgshapiro#endif 19890792Sgshapiro n = -(sizeof (*op) + RSLOP); 19990792Sgshapiro } else { 20090792Sgshapiro amt = pagesz; 20190792Sgshapiro bucket = pagebucket; 20290792Sgshapiro } 20390792Sgshapiro while (nbytes > amt + n) { 20490792Sgshapiro amt <<= 1; 20590792Sgshapiro if (amt == 0) 20690792Sgshapiro return (NULL); 20790792Sgshapiro bucket++; 20890792Sgshapiro } 20990792Sgshapiro /* 21090792Sgshapiro * If nothing in hash bucket right now, 21190792Sgshapiro * request more memory from the system. 21290792Sgshapiro */ 21390792Sgshapiro if ((op = nextf[bucket]) == NULL) { 21490792Sgshapiro morecore(bucket); 21590792Sgshapiro if ((op = nextf[bucket]) == NULL) 21690792Sgshapiro return (NULL); 21790792Sgshapiro } 21890792Sgshapiro /* remove from linked list */ 21990792Sgshapiro nextf[bucket] = op->ov_next; 22090792Sgshapiro op->ov_magic = MAGIC; 22190792Sgshapiro op->ov_index = bucket; 22290792Sgshapiro#ifdef MSTATS 22390792Sgshapiro nmalloc[bucket]++; 22490792Sgshapiro#endif 22590792Sgshapiro#ifdef RCHECK 22690792Sgshapiro /* 22790792Sgshapiro * Record allocated size of block and 22890792Sgshapiro * bound space with magic numbers. 22990792Sgshapiro */ 23090792Sgshapiro op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); 23190792Sgshapiro op->ov_rmagic = RMAGIC; 23290792Sgshapiro *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 23390792Sgshapiro#endif 23490792Sgshapiro return ((char *)(op + 1)); 23590792Sgshapiro} 23690792Sgshapiro 23790792Sgshapiro/* 23890792Sgshapiro * Allocate more memory to the indicated bucket. 23990792Sgshapiro */ 24090792Sgshapirostatic void 24190792Sgshapiromorecore(bucket) 24290792Sgshapiro int bucket; 24390792Sgshapiro{ 24490792Sgshapiro register union overhead *op; 245157001Sgshapiro register int sz; /* size of desired block */ 24690792Sgshapiro int amt; /* amount to allocate */ 247110560Sgshapiro int nblks; /* how many blocks we get */ 248110560Sgshapiro 249110560Sgshapiro /* 250110560Sgshapiro * sbrk_size <= 0 only for big, FLUFFY, requests (about 251110560Sgshapiro * 2^30 bytes on a VAX, I think) or for a negative arg. 25290792Sgshapiro */ 25390792Sgshapiro sz = 1 << (bucket + 3); 25490792Sgshapiro#ifdef MALLOC_DEBUG 25590792Sgshapiro ASSERT(sz > 0); 25690792Sgshapiro#else 25790792Sgshapiro if (sz <= 0) 258157001Sgshapiro return; 259157001Sgshapiro#endif 260157001Sgshapiro if (sz < pagesz) { 261157001Sgshapiro amt = pagesz; 262157001Sgshapiro nblks = amt / sz; 26390792Sgshapiro } else { 26490792Sgshapiro amt = sz + pagesz; 26590792Sgshapiro nblks = 1; 26690792Sgshapiro } 26790792Sgshapiro if (amt > pagepool_end - pagepool_start) 26890792Sgshapiro if (morepages(amt/pagesz + NPOOLPAGES) == 0) 26990792Sgshapiro return; 27090792Sgshapiro op = (union overhead *)pagepool_start; 27190792Sgshapiro pagepool_start += amt; 27290792Sgshapiro 27390792Sgshapiro /* 27490792Sgshapiro * Add new memory allocated to that on 27590792Sgshapiro * free list for this hash bucket. 27690792Sgshapiro */ 277157001Sgshapiro nextf[bucket] = op; 278157001Sgshapiro while (--nblks > 0) { 279157001Sgshapiro op->ov_next = (union overhead *)((caddr_t)op + sz); 28090792Sgshapiro op = (union overhead *)((caddr_t)op + sz); 28190792Sgshapiro } 28290792Sgshapiro} 28390792Sgshapiro 28490792Sgshapirovoid 28590792Sgshapirofree(cp) 28690792Sgshapiro void *cp; 28790792Sgshapiro{ 28890792Sgshapiro register int size; 28990792Sgshapiro register union overhead *op; 29090792Sgshapiro 29190792Sgshapiro if (cp == NULL) 29290792Sgshapiro return; 29390792Sgshapiro op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); 29490792Sgshapiro#ifdef MALLOC_DEBUG 29590792Sgshapiro ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */ 29690792Sgshapiro#else 297 if (op->ov_magic != MAGIC) 298 return; /* sanity */ 299#endif 300#ifdef RCHECK 301 ASSERT(op->ov_rmagic == RMAGIC); 302 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC); 303#endif 304 size = op->ov_index; 305 ASSERT(size < NBUCKETS); 306 op->ov_next = nextf[size]; /* also clobbers ov_magic */ 307 nextf[size] = op; 308#ifdef MSTATS 309 nmalloc[size]--; 310#endif 311} 312 313/* 314 * When a program attempts "storage compaction" as mentioned in the 315 * old malloc man page, it realloc's an already freed block. Usually 316 * this is the last block it freed; occasionally it might be farther 317 * back. We have to search all the free lists for the block in order 318 * to determine its bucket: 1st we make one pass thru the lists 319 * checking only the first block in each; if that fails we search 320 * ``realloc_srchlen'' blocks in each list for a match (the variable 321 * is extern so the caller can modify it). If that fails we just copy 322 * however many bytes was given to realloc() and hope it's not huge. 323 */ 324int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ 325 326void * 327realloc(cp, nbytes) 328 void *cp; 329 size_t nbytes; 330{ 331 register u_int onb; 332 register int i; 333 union overhead *op; 334 char *res; 335 int was_alloced = 0; 336 337 if (cp == NULL) 338 return (malloc(nbytes)); 339 op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); 340 if (op->ov_magic == MAGIC) { 341 was_alloced++; 342 i = op->ov_index; 343 } else { 344 /* 345 * Already free, doing "compaction". 346 * 347 * Search for the old block of memory on the 348 * free list. First, check the most common 349 * case (last element free'd), then (this failing) 350 * the last ``realloc_srchlen'' items free'd. 351 * If all lookups fail, then assume the size of 352 * the memory block being realloc'd is the 353 * largest possible (so that all "nbytes" of new 354 * memory are copied into). Note that this could cause 355 * a memory fault if the old area was tiny, and the moon 356 * is gibbous. However, that is very unlikely. 357 */ 358 if ((i = findbucket(op, 1)) < 0 && 359 (i = findbucket(op, realloc_srchlen)) < 0) 360 i = NBUCKETS; 361 } 362 onb = 1 << (i + 3); 363 if (onb < pagesz) 364 onb -= sizeof (*op) + RSLOP; 365 else 366 onb += pagesz - sizeof (*op) - RSLOP; 367 /* avoid the copy if same size block */ 368 if (was_alloced) { 369 if (i) { 370 i = 1 << (i + 2); 371 if (i < pagesz) 372 i -= sizeof (*op) + RSLOP; 373 else 374 i += pagesz - sizeof (*op) - RSLOP; 375 } 376 if (nbytes <= onb && nbytes > i) { 377#ifdef RCHECK 378 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); 379 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 380#endif 381 return(cp); 382 } else 383 free(cp); 384 } 385 if ((res = malloc(nbytes)) == NULL) 386 return (NULL); 387 if (cp != res) /* common optimization if "compacting" */ 388 bcopy(cp, res, (nbytes < onb) ? nbytes : onb); 389 return (res); 390} 391 392/* 393 * Search ``srchlen'' elements of each free list for a block whose 394 * header starts at ``freep''. If srchlen is -1 search the whole list. 395 * Return bucket number, or -1 if not found. 396 */ 397static int 398findbucket(freep, srchlen) 399 union overhead *freep; 400 int srchlen; 401{ 402 register union overhead *p; 403 register int i, j; 404 405 for (i = 0; i < NBUCKETS; i++) { 406 j = 0; 407 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { 408 if (p == freep) 409 return (i); 410 j++; 411 } 412 } 413 return (-1); 414} 415 416#ifdef MSTATS 417/* 418 * mstats - print out statistics about malloc 419 * 420 * Prints two lines of numbers, one showing the length of the free list 421 * for each size category, the second showing the number of mallocs - 422 * frees for each size category. 423 */ 424mstats(s) 425 char *s; 426{ 427 register int i, j; 428 register union overhead *p; 429 int totfree = 0, 430 totused = 0; 431 432 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); 433 for (i = 0; i < NBUCKETS; i++) { 434 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) 435 ; 436 fprintf(stderr, " %d", j); 437 totfree += j * (1 << (i + 3)); 438 } 439 fprintf(stderr, "\nused:\t"); 440 for (i = 0; i < NBUCKETS; i++) { 441 fprintf(stderr, " %d", nmalloc[i]); 442 totused += nmalloc[i] * (1 << (i + 3)); 443 } 444 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", 445 totused, totfree); 446} 447#endif 448 449 450static int 451morepages(n) 452int n; 453{ 454 int fd = -1; 455 int offset; 456 457#ifdef NEED_DEV_ZERO 458 fd = open(_PATH_DEVZERO, O_RDWR, 0); 459 if (fd == -1) 460 perror(_PATH_DEVZERO); 461#endif 462 463 if (pagepool_end - pagepool_start > pagesz) { 464 caddr_t addr = (caddr_t) 465 (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1)); 466 if (munmap(addr, pagepool_end - addr) != 0) 467 warn("morepages: munmap %p", addr); 468 } 469 470 offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1)); 471 472 if ((pagepool_start = mmap(0, n * pagesz, 473 PROT_READ|PROT_WRITE, 474 MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { 475 xprintf("Cannot map anonymous memory"); 476 return 0; 477 } 478 pagepool_end = pagepool_start + n * pagesz; 479 pagepool_start += offset; 480 481#ifdef NEED_DEV_ZERO 482 close(fd); 483#endif 484 return n; 485} 486 487/* 488 * Non-mallocing printf, for use by malloc itself. 489 */ 490static void 491xprintf(const char *fmt, ...) 492{ 493 char buf[256]; 494 va_list ap; 495 496 va_start(ap, fmt); 497 vsprintf(buf, fmt, ap); 498 (void)write(STDOUT_FILENO, buf, strlen(buf)); 499 va_end(ap); 500} 501