malloc.c revision 330897
1/*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1983 Regents of the University of California. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32#if defined(LIBC_SCCS) && !defined(lint) 33/*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/ 34static char *rcsid = "$FreeBSD: stable/11/libexec/rtld-elf/malloc.c 330897 2018-03-14 03:19:51Z eadler $"; 35#endif /* LIBC_SCCS and not lint */ 36 37/* 38 * malloc.c (Caltech) 2/21/82 39 * Chris Kingsley, kingsley@cit-20. 40 * 41 * This is a very fast storage allocator. It allocates blocks of a small 42 * number of different sizes, and keeps free lists of each size. Blocks that 43 * don't exactly fit are passed up to the next larger size. In this 44 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long. 45 * This is designed for use in a virtual memory environment. 46 */ 47 48#include <sys/types.h> 49#include <sys/sysctl.h> 50#include <stdarg.h> 51#include <stddef.h> 52#include <stdio.h> 53#include <stdlib.h> 54#include <string.h> 55#include <unistd.h> 56#include <sys/param.h> 57#include <sys/mman.h> 58#include "rtld_printf.h" 59 60static void morecore(); 61static int findbucket(); 62 63/* 64 * Pre-allocate mmap'ed pages 65 */ 66#define NPOOLPAGES (32*1024/pagesz) 67static caddr_t pagepool_start, pagepool_end; 68static int morepages(); 69 70/* 71 * The overhead on a block is at least 4 bytes. When free, this space 72 * contains a pointer to the next free block, and the bottom two bits must 73 * be zero. When in use, the first byte is set to MAGIC, and the second 74 * byte is the size index. The remaining bytes are for alignment. 75 * If range checking is enabled then a second word holds the size of the 76 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). 77 * The order of elements is critical: ov_magic must overlay the low order 78 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. 79 */ 80union overhead { 81 union overhead *ov_next; /* when free */ 82 struct { 83 u_char ovu_magic; /* magic number */ 84 u_char ovu_index; /* bucket # */ 85#ifdef RCHECK 86 u_short ovu_rmagic; /* range magic number */ 87 u_int ovu_size; /* actual block size */ 88#endif 89 } ovu; 90#define ov_magic ovu.ovu_magic 91#define ov_index ovu.ovu_index 92#define ov_rmagic ovu.ovu_rmagic 93#define ov_size ovu.ovu_size 94}; 95 96#define MAGIC 0xef /* magic # on accounting info */ 97#define RMAGIC 0x5555 /* magic # on range info */ 98 99#ifdef RCHECK 100#define RSLOP sizeof (u_short) 101#else 102#define RSLOP 0 103#endif 104 105/* 106 * nextf[i] is the pointer to the next free block of size 2^(i+3). The 107 * smallest allocatable block is 8 bytes. The overhead information 108 * precedes the data area returned to the user. 109 */ 110#define NBUCKETS 30 111static union overhead *nextf[NBUCKETS]; 112 113static int pagesz; /* page size */ 114static int pagebucket; /* page size bucket */ 115 116#ifdef MSTATS 117/* 118 * nmalloc[i] is the difference between the number of mallocs and frees 119 * for a given block size. 120 */ 121static u_int nmalloc[NBUCKETS]; 122#include <stdio.h> 123#endif 124 125#if defined(MALLOC_DEBUG) || defined(RCHECK) 126#define ASSERT(p) if (!(p)) botch("p") 127#include <stdio.h> 128static void 129botch(s) 130 char *s; 131{ 132 fprintf(stderr, "\r\nassertion botched: %s\r\n", s); 133 (void) fflush(stderr); /* just in case user buffered it */ 134 abort(); 135} 136#else 137#define ASSERT(p) 138#endif 139 140/* Debugging stuff */ 141#define TRACE() rtld_printf("TRACE %s:%d\n", __FILE__, __LINE__) 142 143/* 144 * The array of supported page sizes is provided by the user, i.e., the 145 * program that calls this storage allocator. That program must initialize 146 * the array before making its first call to allocate storage. The array 147 * must contain at least one page size. The page sizes must be stored in 148 * increasing order. 149 */ 150extern size_t *pagesizes; 151 152void * 153malloc(nbytes) 154 size_t nbytes; 155{ 156 register union overhead *op; 157 register int bucket; 158 register long n; 159 register unsigned amt; 160 161 /* 162 * First time malloc is called, setup page size and 163 * align break pointer so all data will be page aligned. 164 */ 165 if (pagesz == 0) { 166 pagesz = n = pagesizes[0]; 167 if (morepages(NPOOLPAGES) == 0) 168 return NULL; 169 op = (union overhead *)(pagepool_start); 170 n = n - sizeof (*op) - ((long)op & (n - 1)); 171 if (n < 0) 172 n += pagesz; 173 if (n) { 174 pagepool_start += n; 175 } 176 bucket = 0; 177 amt = 8; 178 while ((unsigned)pagesz > amt) { 179 amt <<= 1; 180 bucket++; 181 } 182 pagebucket = bucket; 183 } 184 /* 185 * Convert amount of memory requested into closest block size 186 * stored in hash buckets which satisfies request. 187 * Account for space used per block for accounting. 188 */ 189 if (nbytes <= (unsigned long)(n = pagesz - sizeof (*op) - RSLOP)) { 190#ifndef RCHECK 191 amt = 8; /* size of first bucket */ 192 bucket = 0; 193#else 194 amt = 16; /* size of first bucket */ 195 bucket = 1; 196#endif 197 n = -(sizeof (*op) + RSLOP); 198 } else { 199 amt = pagesz; 200 bucket = pagebucket; 201 } 202 while (nbytes > amt + n) { 203 amt <<= 1; 204 if (amt == 0) 205 return (NULL); 206 bucket++; 207 } 208 /* 209 * If nothing in hash bucket right now, 210 * request more memory from the system. 211 */ 212 if ((op = nextf[bucket]) == NULL) { 213 morecore(bucket); 214 if ((op = nextf[bucket]) == NULL) 215 return (NULL); 216 } 217 /* remove from linked list */ 218 nextf[bucket] = op->ov_next; 219 op->ov_magic = MAGIC; 220 op->ov_index = bucket; 221#ifdef MSTATS 222 nmalloc[bucket]++; 223#endif 224#ifdef RCHECK 225 /* 226 * Record allocated size of block and 227 * bound space with magic numbers. 228 */ 229 op->ov_size = roundup2(nbytes, RSLOP); 230 op->ov_rmagic = RMAGIC; 231 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 232#endif 233 return ((char *)(op + 1)); 234} 235 236void * 237calloc(size_t num, size_t size) 238{ 239 void *ret; 240 241 if (size != 0 && (num * size) / size != num) { 242 /* size_t overflow. */ 243 return (NULL); 244 } 245 246 if ((ret = malloc(num * size)) != NULL) 247 memset(ret, 0, num * size); 248 249 return (ret); 250} 251 252/* 253 * Allocate more memory to the indicated bucket. 254 */ 255static void 256morecore(bucket) 257 int bucket; 258{ 259 register union overhead *op; 260 register int sz; /* size of desired block */ 261 int amt; /* amount to allocate */ 262 int nblks; /* how many blocks we get */ 263 264 /* 265 * sbrk_size <= 0 only for big, FLUFFY, requests (about 266 * 2^30 bytes on a VAX, I think) or for a negative arg. 267 */ 268 sz = 1 << (bucket + 3); 269#ifdef MALLOC_DEBUG 270 ASSERT(sz > 0); 271#else 272 if (sz <= 0) 273 return; 274#endif 275 if (sz < pagesz) { 276 amt = pagesz; 277 nblks = amt / sz; 278 } else { 279 amt = sz + pagesz; 280 nblks = 1; 281 } 282 if (amt > pagepool_end - pagepool_start) 283 if (morepages(amt/pagesz + NPOOLPAGES) == 0) 284 return; 285 op = (union overhead *)pagepool_start; 286 pagepool_start += amt; 287 288 /* 289 * Add new memory allocated to that on 290 * free list for this hash bucket. 291 */ 292 nextf[bucket] = op; 293 while (--nblks > 0) { 294 op->ov_next = (union overhead *)((caddr_t)op + sz); 295 op = (union overhead *)((caddr_t)op + sz); 296 } 297} 298 299void 300free(cp) 301 void *cp; 302{ 303 register int size; 304 register union overhead *op; 305 306 if (cp == NULL) 307 return; 308 op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); 309#ifdef MALLOC_DEBUG 310 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */ 311#else 312 if (op->ov_magic != MAGIC) 313 return; /* sanity */ 314#endif 315#ifdef RCHECK 316 ASSERT(op->ov_rmagic == RMAGIC); 317 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC); 318#endif 319 size = op->ov_index; 320 ASSERT(size < NBUCKETS); 321 op->ov_next = nextf[size]; /* also clobbers ov_magic */ 322 nextf[size] = op; 323#ifdef MSTATS 324 nmalloc[size]--; 325#endif 326} 327 328/* 329 * When a program attempts "storage compaction" as mentioned in the 330 * old malloc man page, it realloc's an already freed block. Usually 331 * this is the last block it freed; occasionally it might be farther 332 * back. We have to search all the free lists for the block in order 333 * to determine its bucket: 1st we make one pass through the lists 334 * checking only the first block in each; if that fails we search 335 * ``realloc_srchlen'' blocks in each list for a match (the variable 336 * is extern so the caller can modify it). If that fails we just copy 337 * however many bytes was given to realloc() and hope it's not huge. 338 */ 339int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ 340 341void * 342realloc(cp, nbytes) 343 void *cp; 344 size_t nbytes; 345{ 346 register u_int onb; 347 register int i; 348 union overhead *op; 349 char *res; 350 int was_alloced = 0; 351 352 if (cp == NULL) 353 return (malloc(nbytes)); 354 op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); 355 if (op->ov_magic == MAGIC) { 356 was_alloced++; 357 i = op->ov_index; 358 } else { 359 /* 360 * Already free, doing "compaction". 361 * 362 * Search for the old block of memory on the 363 * free list. First, check the most common 364 * case (last element free'd), then (this failing) 365 * the last ``realloc_srchlen'' items free'd. 366 * If all lookups fail, then assume the size of 367 * the memory block being realloc'd is the 368 * largest possible (so that all "nbytes" of new 369 * memory are copied into). Note that this could cause 370 * a memory fault if the old area was tiny, and the moon 371 * is gibbous. However, that is very unlikely. 372 */ 373 if ((i = findbucket(op, 1)) < 0 && 374 (i = findbucket(op, realloc_srchlen)) < 0) 375 i = NBUCKETS; 376 } 377 onb = 1 << (i + 3); 378 if (onb < (u_int)pagesz) 379 onb -= sizeof (*op) + RSLOP; 380 else 381 onb += pagesz - sizeof (*op) - RSLOP; 382 /* avoid the copy if same size block */ 383 if (was_alloced) { 384 if (i) { 385 i = 1 << (i + 2); 386 if (i < pagesz) 387 i -= sizeof (*op) + RSLOP; 388 else 389 i += pagesz - sizeof (*op) - RSLOP; 390 } 391 if (nbytes <= onb && nbytes > (size_t)i) { 392#ifdef RCHECK 393 op->ov_size = roundup2(nbytes, RSLOP); 394 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 395#endif 396 return(cp); 397 } else 398 free(cp); 399 } 400 if ((res = malloc(nbytes)) == NULL) 401 return (NULL); 402 if (cp != res) /* common optimization if "compacting" */ 403 bcopy(cp, res, (nbytes < onb) ? nbytes : onb); 404 return (res); 405} 406 407/* 408 * Search ``srchlen'' elements of each free list for a block whose 409 * header starts at ``freep''. If srchlen is -1 search the whole list. 410 * Return bucket number, or -1 if not found. 411 */ 412static int 413findbucket(freep, srchlen) 414 union overhead *freep; 415 int srchlen; 416{ 417 register union overhead *p; 418 register int i, j; 419 420 for (i = 0; i < NBUCKETS; i++) { 421 j = 0; 422 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { 423 if (p == freep) 424 return (i); 425 j++; 426 } 427 } 428 return (-1); 429} 430 431#ifdef MSTATS 432/* 433 * mstats - print out statistics about malloc 434 * 435 * Prints two lines of numbers, one showing the length of the free list 436 * for each size category, the second showing the number of mallocs - 437 * frees for each size category. 438 */ 439mstats(s) 440 char *s; 441{ 442 register int i, j; 443 register union overhead *p; 444 int totfree = 0, 445 totused = 0; 446 447 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); 448 for (i = 0; i < NBUCKETS; i++) { 449 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) 450 ; 451 fprintf(stderr, " %d", j); 452 totfree += j * (1 << (i + 3)); 453 } 454 fprintf(stderr, "\nused:\t"); 455 for (i = 0; i < NBUCKETS; i++) { 456 fprintf(stderr, " %d", nmalloc[i]); 457 totused += nmalloc[i] * (1 << (i + 3)); 458 } 459 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", 460 totused, totfree); 461} 462#endif 463 464 465static int 466morepages(n) 467int n; 468{ 469 int fd = -1; 470 int offset; 471 472 if (pagepool_end - pagepool_start > pagesz) { 473 caddr_t addr = (caddr_t) 474 (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1)); 475 if (munmap(addr, pagepool_end - addr) != 0) 476 rtld_fdprintf(STDERR_FILENO, "morepages: munmap %p", 477 addr); 478 } 479 480 offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1)); 481 482 if ((pagepool_start = mmap(0, n * pagesz, 483 PROT_READ|PROT_WRITE, 484 MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { 485 rtld_printf("Cannot map anonymous memory\n"); 486 return 0; 487 } 488 pagepool_end = pagepool_start + n * pagesz; 489 pagepool_start += offset; 490 491 return n; 492} 493