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";*/ 34 static char *rcsid = "$FreeBSD$"; 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 <errno.h> 51 #include <stdarg.h> 52 #include <stddef.h> 53 #include <stdio.h> 54 #include <stdlib.h> 55 #include <string.h> 56 #include <unistd.h> 57 #include <sys/param.h> 58 #include <sys/mman.h> 59 #include "rtld.h" 60 #include "rtld_printf.h" 61 #include "paths.h" 62 63 /* 64 * Pre-allocate mmap'ed pages 65 */ 66 #define NPOOLPAGES (128*1024/pagesz) 67 static caddr_t pagepool_start, pagepool_end; 68 69 /* 70 * The overhead on a block is at least 4 bytes. When free, this space 71 * contains a pointer to the next free block, and the bottom two bits must 72 * be zero. When in use, the first byte is set to MAGIC, and the second 73 * byte is the size index. The remaining bytes are for alignment. 74 * If range checking is enabled then a second word holds the size of the 75 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). 76 * The order of elements is critical: ov_magic must overlay the low order 77 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. 78 */ 79 union overhead { 80 union overhead *ov_next; /* when free */ 81 struct { 82 u_char ovu_magic; /* magic number */ 83 u_char ovu_index; /* bucket # */ 84 #ifdef RCHECK 85 u_short ovu_rmagic; /* range magic number */ 86 u_int ovu_size; /* actual block size */ 87 #endif 88 } ovu; 89 #define ov_magic ovu.ovu_magic 90 #define ov_index ovu.ovu_index 91 #define ov_rmagic ovu.ovu_rmagic 92 #define ov_size ovu.ovu_size 93 }; 94 95 static void morecore(int bucket); 96 static int morepages(int n); 97 static int findbucket(union overhead *freep, int srchlen); 98 99 100 #define MAGIC 0xef /* magic # on accounting info */ 101 #define RMAGIC 0x5555 /* magic # on range info */ 102 103 #ifdef RCHECK 104 #define RSLOP sizeof (u_short) 105 #else 106 #define RSLOP 0 107 #endif 108 109 /* 110 * nextf[i] is the pointer to the next free block of size 2^(i+3). The 111 * smallest allocatable block is 8 bytes. The overhead information 112 * precedes the data area returned to the user. 113 */ 114 #define NBUCKETS 30 115 static union overhead *nextf[NBUCKETS]; 116 117 static int pagesz; /* page size */ 118 static int pagebucket; /* page size bucket */ 119 120 #ifdef MSTATS 121 /* 122 * nmalloc[i] is the difference between the number of mallocs and frees 123 * for a given block size. 124 */ 125 static u_int nmalloc[NBUCKETS]; 126 #include <stdio.h> 127 #endif 128 129 #if defined(MALLOC_DEBUG) || defined(RCHECK) 130 #define ASSERT(p) if (!(p)) botch("p") 131 #include <stdio.h> 132 static void 133 botch(s) 134 char *s; 135 { 136 fprintf(stderr, "\r\nassertion botched: %s\r\n", s); 137 (void) fflush(stderr); /* just in case user buffered it */ 138 abort(); 139 } 140 #else 141 #define ASSERT(p) 142 #endif 143 144 /* Debugging stuff */ 145 #define TRACE() rtld_printf("TRACE %s:%d\n", __FILE__, __LINE__) 146 147 /* 148 * The array of supported page sizes is provided by the user, i.e., the 149 * program that calls this storage allocator. That program must initialize 150 * the array before making its first call to allocate storage. The array 151 * must contain at least one page size. The page sizes must be stored in 152 * increasing order. 153 */ 154 155 void * 156 __crt_malloc(size_t nbytes) 157 { 158 union overhead *op; 159 int bucket; 160 ssize_t n; 161 size_t amt; 162 163 /* 164 * First time malloc is called, setup page size and 165 * align break pointer so all data will be page aligned. 166 */ 167 if (pagesz == 0) { 168 pagesz = n = pagesizes[0]; 169 if (morepages(NPOOLPAGES) == 0) 170 return NULL; 171 op = (union overhead *)(pagepool_start); 172 n = n - sizeof (*op) - ((long)op & (n - 1)); 173 if (n < 0) 174 n += pagesz; 175 if (n) { 176 pagepool_start += n; 177 } 178 bucket = 0; 179 amt = 8; 180 while ((unsigned)pagesz > amt) { 181 amt <<= 1; 182 bucket++; 183 } 184 pagebucket = bucket; 185 } 186 /* 187 * Convert amount of memory requested into closest block size 188 * stored in hash buckets which satisfies request. 189 * Account for space used per block for accounting. 190 */ 191 if (nbytes <= (unsigned long)(n = pagesz - sizeof (*op) - RSLOP)) { 192 #ifndef RCHECK 193 amt = 8; /* size of first bucket */ 194 bucket = 0; 195 #else 196 amt = 16; /* size of first bucket */ 197 bucket = 1; 198 #endif 199 n = -(sizeof (*op) + RSLOP); 200 } else { 201 amt = pagesz; 202 bucket = pagebucket; 203 } 204 while (nbytes > amt + n) { 205 amt <<= 1; 206 if (amt == 0) 207 return (NULL); 208 bucket++; 209 } 210 /* 211 * If nothing in hash bucket right now, 212 * request more memory from the system. 213 */ 214 if ((op = nextf[bucket]) == NULL) { 215 morecore(bucket); 216 if ((op = nextf[bucket]) == NULL) 217 return (NULL); 218 } 219 /* remove from linked list */ 220 nextf[bucket] = op->ov_next; 221 op->ov_magic = MAGIC; 222 op->ov_index = bucket; 223 #ifdef MSTATS 224 nmalloc[bucket]++; 225 #endif 226 #ifdef RCHECK 227 /* 228 * Record allocated size of block and 229 * bound space with magic numbers. 230 */ 231 op->ov_size = roundup2(nbytes, RSLOP); 232 op->ov_rmagic = RMAGIC; 233 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 234 #endif 235 return ((char *)(op + 1)); 236 } 237 238 void * 239 __crt_calloc(size_t num, size_t size) 240 { 241 void *ret; 242 243 if (size != 0 && (num * size) / size != num) { 244 /* size_t overflow. */ 245 return (NULL); 246 } 247 248 if ((ret = __crt_malloc(num * size)) != NULL) 249 memset(ret, 0, num * size); 250 251 return (ret); 252 } 253 254 /* 255 * Allocate more memory to the indicated bucket. 256 */ 257 static void 258 morecore(int bucket) 259 { 260 union overhead *op; 261 int sz; /* size of desired block */ 262 int amt; /* amount to allocate */ 263 int nblks; /* how many blocks we get */ 264 265 /* 266 * sbrk_size <= 0 only for big, FLUFFY, requests (about 267 * 2^30 bytes on a VAX, I think) or for a negative arg. 268 */ 269 sz = 1 << (bucket + 3); 270 #ifdef MALLOC_DEBUG 271 ASSERT(sz > 0); 272 #else 273 if (sz <= 0) 274 return; 275 #endif 276 if (sz < pagesz) { 277 amt = pagesz; 278 nblks = amt / sz; 279 } else { 280 amt = sz + pagesz; 281 nblks = 1; 282 } 283 if (amt > pagepool_end - pagepool_start) 284 if (morepages(amt/pagesz + NPOOLPAGES) == 0) 285 return; 286 op = (union overhead *)pagepool_start; 287 pagepool_start += amt; 288 289 /* 290 * Add new memory allocated to that on 291 * free list for this hash bucket. 292 */ 293 nextf[bucket] = op; 294 while (--nblks > 0) { 295 op->ov_next = (union overhead *)((caddr_t)op + sz); 296 op = (union overhead *)((caddr_t)op + sz); 297 } 298 } 299 300 void 301 __crt_free(void *cp) 302 { 303 int size; 304 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 */ 339 static int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ 340 341 void * 342 __crt_realloc(void *cp, size_t nbytes) 343 { 344 u_int onb; 345 int i; 346 union overhead *op; 347 char *res; 348 int was_alloced = 0; 349 350 if (cp == NULL) 351 return (__crt_malloc(nbytes)); 352 op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); 353 if (op->ov_magic == MAGIC) { 354 was_alloced++; 355 i = op->ov_index; 356 } else { 357 /* 358 * Already free, doing "compaction". 359 * 360 * Search for the old block of memory on the 361 * free list. First, check the most common 362 * case (last element free'd), then (this failing) 363 * the last ``realloc_srchlen'' items free'd. 364 * If all lookups fail, then assume the size of 365 * the memory block being realloc'd is the 366 * largest possible (so that all "nbytes" of new 367 * memory are copied into). Note that this could cause 368 * a memory fault if the old area was tiny, and the moon 369 * is gibbous. However, that is very unlikely. 370 */ 371 if ((i = findbucket(op, 1)) < 0 && 372 (i = findbucket(op, realloc_srchlen)) < 0) 373 i = NBUCKETS; 374 } 375 onb = 1 << (i + 3); 376 if (onb < (u_int)pagesz) 377 onb -= sizeof (*op) + RSLOP; 378 else 379 onb += pagesz - sizeof (*op) - RSLOP; 380 /* avoid the copy if same size block */ 381 if (was_alloced) { 382 if (i) { 383 i = 1 << (i + 2); 384 if (i < pagesz) 385 i -= sizeof (*op) + RSLOP; 386 else 387 i += pagesz - sizeof (*op) - RSLOP; 388 } 389 if (nbytes <= onb && nbytes > (size_t)i) { 390 #ifdef RCHECK 391 op->ov_size = roundup2(nbytes, RSLOP); 392 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; 393 #endif 394 return(cp); 395 } else 396 __crt_free(cp); 397 } 398 if ((res = __crt_malloc(nbytes)) == NULL) 399 return (NULL); 400 if (cp != res) /* common optimization if "compacting" */ 401 bcopy(cp, res, (nbytes < onb) ? nbytes : onb); 402 return (res); 403 } 404 405 /* 406 * Search ``srchlen'' elements of each free list for a block whose 407 * header starts at ``freep''. If srchlen is -1 search the whole list. 408 * Return bucket number, or -1 if not found. 409 */ 410 static int 411 findbucket(union overhead *freep, int srchlen) 412 { 413 union overhead *p; 414 int i, j; 415 416 for (i = 0; i < NBUCKETS; i++) { 417 j = 0; 418 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { 419 if (p == freep) 420 return (i); 421 j++; 422 } 423 } 424 return (-1); 425 } 426 427 #ifdef MSTATS 428 /* 429 * mstats - print out statistics about malloc 430 * 431 * Prints two lines of numbers, one showing the length of the free list 432 * for each size category, the second showing the number of mallocs - 433 * frees for each size category. 434 */ 435 mstats(char * s) 436 { 437 int i, j; 438 union overhead *p; 439 int totfree = 0, 440 totused = 0; 441 442 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); 443 for (i = 0; i < NBUCKETS; i++) { 444 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) 445 ; 446 fprintf(stderr, " %d", j); 447 totfree += j * (1 << (i + 3)); 448 } 449 fprintf(stderr, "\nused:\t"); 450 for (i = 0; i < NBUCKETS; i++) { 451 fprintf(stderr, " %d", nmalloc[i]); 452 totused += nmalloc[i] * (1 << (i + 3)); 453 } 454 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", 455 totused, totfree); 456 } 457 #endif 458 459 460 static int 461 morepages(int n) 462 { 463 int fd = -1; 464 int offset; 465 466 if (pagepool_end - pagepool_start > pagesz) { 467 caddr_t addr = (caddr_t) 468 (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1)); 469 if (munmap(addr, pagepool_end - addr) != 0) { 470 #ifdef IN_RTLD 471 rtld_fdprintf(STDERR_FILENO, _BASENAME_RTLD ": " 472 "morepages: cannot munmap %p: %s\n", 473 addr, rtld_strerror(errno)); 474 #endif 475 } 476 } 477 478 offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1)); 479 480 if ((pagepool_start = mmap(0, n * pagesz, 481 PROT_READ|PROT_WRITE, 482 MAP_ANON|MAP_PRIVATE, fd, 0)) == (caddr_t)-1) { 483 #ifdef IN_RTLD 484 rtld_fdprintf(STDERR_FILENO, _BASENAME_RTLD ": morepages: " 485 "cannot mmap anonymous memory: %s\n", 486 rtld_strerror(errno)); 487 #endif 488 return 0; 489 } 490 pagepool_end = pagepool_start + n * pagesz; 491 pagepool_start += offset; 492 493 return n; 494 } 495