1 /* $OpenBSD: malloc.c,v 1.227 2017/07/07 19:14:46 otto Exp $ */ 2 /* 3 * Copyright (c) 2008, 2010, 2011, 2016 Otto Moerbeek <otto@drijf.net> 4 * Copyright (c) 2012 Matthew Dempsky <matthew@openbsd.org> 5 * Copyright (c) 2008 Damien Miller <djm@openbsd.org> 6 * Copyright (c) 2000 Poul-Henning Kamp <phk@FreeBSD.org> 7 * 8 * Permission to use, copy, modify, and distribute this software for any 9 * purpose with or without fee is hereby granted, provided that the above 10 * copyright notice and this permission notice appear in all copies. 11 * 12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 19 */ 20 21 /* 22 * If we meet some day, and you think this stuff is worth it, you 23 * can buy me a beer in return. Poul-Henning Kamp 24 */ 25 26 /* #define MALLOC_STATS */ 27 28 #include <sys/types.h> 29 #include <sys/param.h> /* PAGE_SHIFT ALIGN */ 30 #include <sys/queue.h> 31 #include <sys/mman.h> 32 #include <sys/uio.h> 33 #include <errno.h> 34 #include <stdarg.h> 35 #include <stdint.h> 36 #include <stdlib.h> 37 #include <string.h> 38 #include <stdio.h> 39 #include <unistd.h> 40 41 #ifdef MALLOC_STATS 42 #include <sys/tree.h> 43 #include <fcntl.h> 44 #endif 45 46 #include "thread_private.h" 47 #include <tib.h> 48 49 #if defined(__mips64__) 50 #define MALLOC_PAGESHIFT (14U) 51 #else 52 #define MALLOC_PAGESHIFT (PAGE_SHIFT) 53 #endif 54 55 #define MALLOC_MINSHIFT 4 56 #define MALLOC_MAXSHIFT (MALLOC_PAGESHIFT - 1) 57 #define MALLOC_PAGESIZE (1UL << MALLOC_PAGESHIFT) 58 #define MALLOC_MINSIZE (1UL << MALLOC_MINSHIFT) 59 #define MALLOC_PAGEMASK (MALLOC_PAGESIZE - 1) 60 #define MASK_POINTER(p) ((void *)(((uintptr_t)(p)) & ~MALLOC_PAGEMASK)) 61 62 #define MALLOC_MAXCHUNK (1 << MALLOC_MAXSHIFT) 63 #define MALLOC_MAXCACHE 256 64 #define MALLOC_DELAYED_CHUNK_MASK 15 65 #define MALLOC_INITIAL_REGIONS 512 66 #define MALLOC_DEFAULT_CACHE 64 67 #define MALLOC_CHUNK_LISTS 4 68 #define CHUNK_CHECK_LENGTH 32 69 70 /* 71 * We move allocations between half a page and a whole page towards the end, 72 * subject to alignment constraints. This is the extra headroom we allow. 73 * Set to zero to be the most strict. 74 */ 75 #define MALLOC_LEEWAY 0 76 #define MALLOC_MOVE_COND(sz) ((sz) - mopts.malloc_guard < \ 77 MALLOC_PAGESIZE - MALLOC_LEEWAY) 78 #define MALLOC_MOVE(p, sz) (((char *)(p)) + \ 79 ((MALLOC_PAGESIZE - MALLOC_LEEWAY - \ 80 ((sz) - mopts.malloc_guard)) & \ 81 ~(MALLOC_MINSIZE - 1))) 82 83 #define PAGEROUND(x) (((x) + (MALLOC_PAGEMASK)) & ~MALLOC_PAGEMASK) 84 85 /* 86 * What to use for Junk. This is the byte value we use to fill with 87 * when the 'J' option is enabled. Use SOME_JUNK right after alloc, 88 * and SOME_FREEJUNK right before free. 89 */ 90 #define SOME_JUNK 0xdb /* deadbeef */ 91 #define SOME_FREEJUNK 0xdf /* dead, free */ 92 93 #define MMAP(sz) mmap(NULL, (sz), PROT_READ | PROT_WRITE, \ 94 MAP_ANON | MAP_PRIVATE, -1, 0) 95 96 #define MMAPA(a,sz) mmap((a), (sz), PROT_READ | PROT_WRITE, \ 97 MAP_ANON | MAP_PRIVATE, -1, 0) 98 99 #define MQUERY(a, sz) mquery((a), (sz), PROT_READ | PROT_WRITE, \ 100 MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) 101 102 struct region_info { 103 void *p; /* page; low bits used to mark chunks */ 104 uintptr_t size; /* size for pages, or chunk_info pointer */ 105 #ifdef MALLOC_STATS 106 void *f; /* where allocated from */ 107 #endif 108 }; 109 110 LIST_HEAD(chunk_head, chunk_info); 111 112 struct dir_info { 113 u_int32_t canary1; 114 int active; /* status of malloc */ 115 struct region_info *r; /* region slots */ 116 size_t regions_total; /* number of region slots */ 117 size_t regions_free; /* number of free slots */ 118 /* lists of free chunk info structs */ 119 struct chunk_head chunk_info_list[MALLOC_MAXSHIFT + 1]; 120 /* lists of chunks with free slots */ 121 struct chunk_head chunk_dir[MALLOC_MAXSHIFT + 1][MALLOC_CHUNK_LISTS]; 122 size_t free_regions_size; /* free pages cached */ 123 /* free pages cache */ 124 struct region_info free_regions[MALLOC_MAXCACHE]; 125 /* delayed free chunk slots */ 126 void *delayed_chunks[MALLOC_DELAYED_CHUNK_MASK + 1]; 127 size_t rbytesused; /* random bytes used */ 128 char *func; /* current function */ 129 int mutex; 130 u_char rbytes[32]; /* random bytes */ 131 u_short chunk_start; 132 #ifdef MALLOC_STATS 133 size_t inserts; 134 size_t insert_collisions; 135 size_t finds; 136 size_t find_collisions; 137 size_t deletes; 138 size_t delete_moves; 139 size_t cheap_realloc_tries; 140 size_t cheap_reallocs; 141 size_t malloc_used; /* bytes allocated */ 142 size_t malloc_guarded; /* bytes used for guards */ 143 #define STATS_ADD(x,y) ((x) += (y)) 144 #define STATS_SUB(x,y) ((x) -= (y)) 145 #define STATS_INC(x) ((x)++) 146 #define STATS_ZERO(x) ((x) = 0) 147 #define STATS_SETF(x,y) ((x)->f = (y)) 148 #else 149 #define STATS_ADD(x,y) /* nothing */ 150 #define STATS_SUB(x,y) /* nothing */ 151 #define STATS_INC(x) /* nothing */ 152 #define STATS_ZERO(x) /* nothing */ 153 #define STATS_SETF(x,y) /* nothing */ 154 #endif /* MALLOC_STATS */ 155 u_int32_t canary2; 156 }; 157 #define DIR_INFO_RSZ ((sizeof(struct dir_info) + MALLOC_PAGEMASK) & \ 158 ~MALLOC_PAGEMASK) 159 160 /* 161 * This structure describes a page worth of chunks. 162 * 163 * How many bits per u_short in the bitmap 164 */ 165 #define MALLOC_BITS (NBBY * sizeof(u_short)) 166 struct chunk_info { 167 LIST_ENTRY(chunk_info) entries; 168 void *page; /* pointer to the page */ 169 u_int32_t canary; 170 u_short size; /* size of this page's chunks */ 171 u_short shift; /* how far to shift for this size */ 172 u_short free; /* how many free chunks */ 173 u_short total; /* how many chunks */ 174 u_short offset; /* requested size table offset */ 175 /* which chunks are free */ 176 u_short bits[1]; 177 }; 178 179 struct malloc_readonly { 180 struct dir_info *malloc_pool[_MALLOC_MUTEXES]; /* Main bookkeeping information */ 181 int malloc_mt; /* multi-threaded mode? */ 182 int malloc_freenow; /* Free quickly - disable chunk rnd */ 183 int malloc_freeunmap; /* mprotect free pages PROT_NONE? */ 184 int malloc_junk; /* junk fill? */ 185 int malloc_realloc; /* always realloc? */ 186 int malloc_xmalloc; /* xmalloc behaviour? */ 187 int chunk_canaries; /* use canaries after chunks? */ 188 int internal_funcs; /* use better recallocarray/freezero? */ 189 u_int malloc_cache; /* free pages we cache */ 190 size_t malloc_guard; /* use guard pages after allocations? */ 191 #ifdef MALLOC_STATS 192 int malloc_stats; /* dump statistics at end */ 193 #endif 194 u_int32_t malloc_canary; /* Matched against ones in malloc_pool */ 195 }; 196 197 /* This object is mapped PROT_READ after initialisation to prevent tampering */ 198 static union { 199 struct malloc_readonly mopts; 200 u_char _pad[MALLOC_PAGESIZE]; 201 } malloc_readonly __attribute__((aligned(MALLOC_PAGESIZE))); 202 #define mopts malloc_readonly.mopts 203 204 char *malloc_options; /* compile-time options */ 205 206 static u_char getrbyte(struct dir_info *d); 207 static __dead void wrterror(struct dir_info *d, char *msg, ...) 208 __attribute__((__format__ (printf, 2, 3))); 209 static void fill_canary(char *ptr, size_t sz, size_t allocated); 210 211 #ifdef MALLOC_STATS 212 void malloc_dump(int, int, struct dir_info *); 213 PROTO_NORMAL(malloc_dump); 214 void malloc_gdump(int); 215 PROTO_NORMAL(malloc_gdump); 216 static void malloc_exit(void); 217 #define CALLER __builtin_return_address(0) 218 #else 219 #define CALLER NULL 220 #endif 221 222 /* low bits of r->p determine size: 0 means >= page size and r->size holding 223 * real size, otherwise low bits are a shift count, or 1 for malloc(0) 224 */ 225 #define REALSIZE(sz, r) \ 226 (sz) = (uintptr_t)(r)->p & MALLOC_PAGEMASK, \ 227 (sz) = ((sz) == 0 ? (r)->size : ((sz) == 1 ? 0 : (1 << ((sz)-1)))) 228 229 static inline void 230 _MALLOC_LEAVE(struct dir_info *d) 231 { 232 if (mopts.malloc_mt) { 233 d->active--; 234 _MALLOC_UNLOCK(d->mutex); 235 } 236 } 237 238 static inline void 239 _MALLOC_ENTER(struct dir_info *d) 240 { 241 if (mopts.malloc_mt) { 242 _MALLOC_LOCK(d->mutex); 243 d->active++; 244 } 245 } 246 247 static inline size_t 248 hash(void *p) 249 { 250 size_t sum; 251 uintptr_t u; 252 253 u = (uintptr_t)p >> MALLOC_PAGESHIFT; 254 sum = u; 255 sum = (sum << 7) - sum + (u >> 16); 256 #ifdef __LP64__ 257 sum = (sum << 7) - sum + (u >> 32); 258 sum = (sum << 7) - sum + (u >> 48); 259 #endif 260 return sum; 261 } 262 263 static inline 264 struct dir_info *getpool(void) 265 { 266 if (!mopts.malloc_mt) 267 return mopts.malloc_pool[0]; 268 else 269 return mopts.malloc_pool[TIB_GET()->tib_tid & 270 (_MALLOC_MUTEXES - 1)]; 271 } 272 273 static __dead void 274 wrterror(struct dir_info *d, char *msg, ...) 275 { 276 struct iovec iov[3]; 277 char pidbuf[80]; 278 char buf[80]; 279 int saved_errno = errno; 280 va_list ap; 281 282 iov[0].iov_base = pidbuf; 283 snprintf(pidbuf, sizeof(pidbuf), "%s(%d) in %s(): ", __progname, 284 getpid(), (d != NULL && d->func) ? d->func : "unknown"); 285 iov[0].iov_len = strlen(pidbuf); 286 iov[1].iov_base = buf; 287 va_start(ap, msg); 288 vsnprintf(buf, sizeof(buf), msg, ap); 289 va_end(ap); 290 iov[1].iov_len = strlen(buf); 291 iov[2].iov_base = "\n"; 292 iov[2].iov_len = 1; 293 writev(STDERR_FILENO, iov, 3); 294 295 #ifdef MALLOC_STATS 296 if (mopts.malloc_stats) { 297 int i; 298 299 for (i = 0; i < _MALLOC_MUTEXES; i++) 300 malloc_dump(STDERR_FILENO, i, mopts.malloc_pool[i]); 301 } 302 #endif /* MALLOC_STATS */ 303 304 errno = saved_errno; 305 306 abort(); 307 } 308 309 static void 310 rbytes_init(struct dir_info *d) 311 { 312 arc4random_buf(d->rbytes, sizeof(d->rbytes)); 313 /* add 1 to account for using d->rbytes[0] */ 314 d->rbytesused = 1 + d->rbytes[0] % (sizeof(d->rbytes) / 2); 315 } 316 317 static inline u_char 318 getrbyte(struct dir_info *d) 319 { 320 u_char x; 321 322 if (d->rbytesused >= sizeof(d->rbytes)) 323 rbytes_init(d); 324 x = d->rbytes[d->rbytesused++]; 325 return x; 326 } 327 328 /* 329 * Cache maintenance. We keep at most malloc_cache pages cached. 330 * If the cache is becoming full, unmap pages in the cache for real, 331 * and then add the region to the cache 332 * Opposed to the regular region data structure, the sizes in the 333 * cache are in MALLOC_PAGESIZE units. 334 */ 335 static void 336 unmap(struct dir_info *d, void *p, size_t sz, int clear) 337 { 338 size_t psz = sz >> MALLOC_PAGESHIFT; 339 size_t rsz, tounmap; 340 struct region_info *r; 341 u_int i, offset; 342 343 if (sz != PAGEROUND(sz)) 344 wrterror(d, "munmap round"); 345 346 rsz = mopts.malloc_cache - d->free_regions_size; 347 348 /* 349 * normally the cache holds recently freed regions, but if the region 350 * to unmap is larger than the cache size or we're clearing and the 351 * cache is full, just munmap 352 */ 353 if (psz > mopts.malloc_cache || (clear && rsz == 0)) { 354 i = munmap(p, sz); 355 if (i) 356 wrterror(d, "munmap %p", p); 357 STATS_SUB(d->malloc_used, sz); 358 return; 359 } 360 tounmap = 0; 361 if (psz > rsz) 362 tounmap = psz - rsz; 363 offset = getrbyte(d); 364 for (i = 0; tounmap > 0 && i < mopts.malloc_cache; i++) { 365 r = &d->free_regions[(i + offset) & (mopts.malloc_cache - 1)]; 366 if (r->p != NULL) { 367 rsz = r->size << MALLOC_PAGESHIFT; 368 if (munmap(r->p, rsz)) 369 wrterror(d, "munmap %p", r->p); 370 r->p = NULL; 371 if (tounmap > r->size) 372 tounmap -= r->size; 373 else 374 tounmap = 0; 375 d->free_regions_size -= r->size; 376 r->size = 0; 377 STATS_SUB(d->malloc_used, rsz); 378 } 379 } 380 if (tounmap > 0) 381 wrterror(d, "malloc cache underflow"); 382 for (i = 0; i < mopts.malloc_cache; i++) { 383 r = &d->free_regions[(i + offset) & (mopts.malloc_cache - 1)]; 384 if (r->p == NULL) { 385 if (clear) 386 memset(p, 0, sz - mopts.malloc_guard); 387 if (mopts.malloc_junk && !mopts.malloc_freeunmap) { 388 size_t amt = mopts.malloc_junk == 1 ? 389 MALLOC_MAXCHUNK : sz; 390 memset(p, SOME_FREEJUNK, amt); 391 } 392 if (mopts.malloc_freeunmap) 393 mprotect(p, sz, PROT_NONE); 394 r->p = p; 395 r->size = psz; 396 d->free_regions_size += psz; 397 break; 398 } 399 } 400 if (i == mopts.malloc_cache) 401 wrterror(d, "malloc free slot lost"); 402 if (d->free_regions_size > mopts.malloc_cache) 403 wrterror(d, "malloc cache overflow"); 404 } 405 406 static void 407 zapcacheregion(struct dir_info *d, void *p, size_t len) 408 { 409 u_int i; 410 struct region_info *r; 411 size_t rsz; 412 413 for (i = 0; i < mopts.malloc_cache; i++) { 414 r = &d->free_regions[i]; 415 if (r->p >= p && r->p <= (void *)((char *)p + len)) { 416 rsz = r->size << MALLOC_PAGESHIFT; 417 if (munmap(r->p, rsz)) 418 wrterror(d, "munmap %p", r->p); 419 r->p = NULL; 420 d->free_regions_size -= r->size; 421 r->size = 0; 422 STATS_SUB(d->malloc_used, rsz); 423 } 424 } 425 } 426 427 static void * 428 map(struct dir_info *d, void *hint, size_t sz, int zero_fill) 429 { 430 size_t psz = sz >> MALLOC_PAGESHIFT; 431 struct region_info *r, *big = NULL; 432 u_int i, offset; 433 void *p; 434 435 if (mopts.malloc_canary != (d->canary1 ^ (u_int32_t)(uintptr_t)d) || 436 d->canary1 != ~d->canary2) 437 wrterror(d, "internal struct corrupt"); 438 if (sz != PAGEROUND(sz)) 439 wrterror(d, "map round"); 440 441 if (!hint && psz > d->free_regions_size) { 442 _MALLOC_LEAVE(d); 443 p = MMAP(sz); 444 _MALLOC_ENTER(d); 445 if (p != MAP_FAILED) 446 STATS_ADD(d->malloc_used, sz); 447 /* zero fill not needed */ 448 return p; 449 } 450 offset = getrbyte(d); 451 for (i = 0; i < mopts.malloc_cache; i++) { 452 r = &d->free_regions[(i + offset) & (mopts.malloc_cache - 1)]; 453 if (r->p != NULL) { 454 if (hint && r->p != hint) 455 continue; 456 if (r->size == psz) { 457 p = r->p; 458 r->p = NULL; 459 r->size = 0; 460 d->free_regions_size -= psz; 461 if (mopts.malloc_freeunmap) 462 mprotect(p, sz, PROT_READ | PROT_WRITE); 463 if (zero_fill) 464 memset(p, 0, sz); 465 else if (mopts.malloc_junk == 2 && 466 mopts.malloc_freeunmap) 467 memset(p, SOME_FREEJUNK, sz); 468 return p; 469 } else if (r->size > psz) 470 big = r; 471 } 472 } 473 if (big != NULL) { 474 r = big; 475 p = r->p; 476 r->p = (char *)r->p + (psz << MALLOC_PAGESHIFT); 477 if (mopts.malloc_freeunmap) 478 mprotect(p, sz, PROT_READ | PROT_WRITE); 479 r->size -= psz; 480 d->free_regions_size -= psz; 481 if (zero_fill) 482 memset(p, 0, sz); 483 else if (mopts.malloc_junk == 2 && mopts.malloc_freeunmap) 484 memset(p, SOME_FREEJUNK, sz); 485 return p; 486 } 487 if (hint) 488 return MAP_FAILED; 489 if (d->free_regions_size > mopts.malloc_cache) 490 wrterror(d, "malloc cache"); 491 _MALLOC_LEAVE(d); 492 p = MMAP(sz); 493 _MALLOC_ENTER(d); 494 if (p != MAP_FAILED) 495 STATS_ADD(d->malloc_used, sz); 496 /* zero fill not needed */ 497 return p; 498 } 499 500 static void 501 omalloc_parseopt(char opt) 502 { 503 switch (opt) { 504 case '>': 505 mopts.malloc_cache <<= 1; 506 if (mopts.malloc_cache > MALLOC_MAXCACHE) 507 mopts.malloc_cache = MALLOC_MAXCACHE; 508 break; 509 case '<': 510 mopts.malloc_cache >>= 1; 511 break; 512 case 'c': 513 mopts.chunk_canaries = 0; 514 break; 515 case 'C': 516 mopts.chunk_canaries = 1; 517 break; 518 #ifdef MALLOC_STATS 519 case 'd': 520 mopts.malloc_stats = 0; 521 break; 522 case 'D': 523 mopts.malloc_stats = 1; 524 break; 525 #endif /* MALLOC_STATS */ 526 case 'f': 527 mopts.malloc_freenow = 0; 528 mopts.malloc_freeunmap = 0; 529 break; 530 case 'F': 531 mopts.malloc_freenow = 1; 532 mopts.malloc_freeunmap = 1; 533 break; 534 case 'g': 535 mopts.malloc_guard = 0; 536 break; 537 case 'G': 538 mopts.malloc_guard = MALLOC_PAGESIZE; 539 break; 540 case 'j': 541 if (mopts.malloc_junk > 0) 542 mopts.malloc_junk--; 543 break; 544 case 'J': 545 if (mopts.malloc_junk < 2) 546 mopts.malloc_junk++; 547 break; 548 case 'r': 549 mopts.malloc_realloc = 0; 550 break; 551 case 'R': 552 mopts.malloc_realloc = 1; 553 break; 554 case 'u': 555 mopts.malloc_freeunmap = 0; 556 break; 557 case 'U': 558 mopts.malloc_freeunmap = 1; 559 break; 560 case 'x': 561 mopts.malloc_xmalloc = 0; 562 break; 563 case 'X': 564 mopts.malloc_xmalloc = 1; 565 break; 566 default: { 567 static const char q[] = "malloc() warning: " 568 "unknown char in MALLOC_OPTIONS\n"; 569 write(STDERR_FILENO, q, sizeof(q) - 1); 570 break; 571 } 572 } 573 } 574 575 static void 576 omalloc_init(void) 577 { 578 char *p, *q, b[64]; 579 int i, j; 580 581 /* 582 * Default options 583 */ 584 mopts.malloc_junk = 1; 585 mopts.malloc_cache = MALLOC_DEFAULT_CACHE; 586 587 for (i = 0; i < 3; i++) { 588 switch (i) { 589 case 0: 590 j = readlink("/etc/malloc.conf", b, sizeof b - 1); 591 if (j <= 0) 592 continue; 593 b[j] = '\0'; 594 p = b; 595 break; 596 case 1: 597 if (issetugid() == 0) 598 p = getenv("MALLOC_OPTIONS"); 599 else 600 continue; 601 break; 602 case 2: 603 p = malloc_options; 604 break; 605 default: 606 p = NULL; 607 } 608 609 for (; p != NULL && *p != '\0'; p++) { 610 switch (*p) { 611 case 'S': 612 for (q = "CGJ"; *q != '\0'; q++) 613 omalloc_parseopt(*q); 614 mopts.malloc_cache = 0; 615 break; 616 case 's': 617 for (q = "cgj"; *q != '\0'; q++) 618 omalloc_parseopt(*q); 619 mopts.malloc_cache = MALLOC_DEFAULT_CACHE; 620 break; 621 default: 622 omalloc_parseopt(*p); 623 break; 624 } 625 } 626 } 627 628 #ifdef MALLOC_STATS 629 if (mopts.malloc_stats && (atexit(malloc_exit) == -1)) { 630 static const char q[] = "malloc() warning: atexit(2) failed." 631 " Will not be able to dump stats on exit\n"; 632 write(STDERR_FILENO, q, sizeof(q) - 1); 633 } 634 #endif /* MALLOC_STATS */ 635 636 while ((mopts.malloc_canary = arc4random()) == 0) 637 ; 638 } 639 640 /* 641 * Initialize a dir_info, which should have been cleared by caller 642 */ 643 static void 644 omalloc_poolinit(struct dir_info **dp) 645 { 646 void *p; 647 size_t d_avail, regioninfo_size; 648 struct dir_info *d; 649 int i, j; 650 651 /* 652 * Allocate dir_info with a guard page on either side. Also 653 * randomise offset inside the page at which the dir_info 654 * lies (subject to alignment by 1 << MALLOC_MINSHIFT) 655 */ 656 if ((p = MMAP(DIR_INFO_RSZ + (MALLOC_PAGESIZE * 2))) == MAP_FAILED) 657 wrterror(NULL, "malloc init mmap failed"); 658 mprotect(p, MALLOC_PAGESIZE, PROT_NONE); 659 mprotect((char *)p + MALLOC_PAGESIZE + DIR_INFO_RSZ, 660 MALLOC_PAGESIZE, PROT_NONE); 661 d_avail = (DIR_INFO_RSZ - sizeof(*d)) >> MALLOC_MINSHIFT; 662 d = (struct dir_info *)((char *)p + MALLOC_PAGESIZE + 663 (arc4random_uniform(d_avail) << MALLOC_MINSHIFT)); 664 665 rbytes_init(d); 666 d->regions_free = d->regions_total = MALLOC_INITIAL_REGIONS; 667 regioninfo_size = d->regions_total * sizeof(struct region_info); 668 d->r = MMAP(regioninfo_size); 669 if (d->r == MAP_FAILED) { 670 d->regions_total = 0; 671 wrterror(NULL, "malloc init mmap failed"); 672 } 673 for (i = 0; i <= MALLOC_MAXSHIFT; i++) { 674 LIST_INIT(&d->chunk_info_list[i]); 675 for (j = 0; j < MALLOC_CHUNK_LISTS; j++) 676 LIST_INIT(&d->chunk_dir[i][j]); 677 } 678 STATS_ADD(d->malloc_used, regioninfo_size); 679 d->canary1 = mopts.malloc_canary ^ (u_int32_t)(uintptr_t)d; 680 d->canary2 = ~d->canary1; 681 682 *dp = d; 683 } 684 685 static int 686 omalloc_grow(struct dir_info *d) 687 { 688 size_t newtotal; 689 size_t newsize; 690 size_t mask; 691 size_t i; 692 struct region_info *p; 693 694 if (d->regions_total > SIZE_MAX / sizeof(struct region_info) / 2 ) 695 return 1; 696 697 newtotal = d->regions_total * 2; 698 newsize = newtotal * sizeof(struct region_info); 699 mask = newtotal - 1; 700 701 p = MMAP(newsize); 702 if (p == MAP_FAILED) 703 return 1; 704 705 STATS_ADD(d->malloc_used, newsize); 706 STATS_ZERO(d->inserts); 707 STATS_ZERO(d->insert_collisions); 708 for (i = 0; i < d->regions_total; i++) { 709 void *q = d->r[i].p; 710 if (q != NULL) { 711 size_t index = hash(q) & mask; 712 STATS_INC(d->inserts); 713 while (p[index].p != NULL) { 714 index = (index - 1) & mask; 715 STATS_INC(d->insert_collisions); 716 } 717 p[index] = d->r[i]; 718 } 719 } 720 /* avoid pages containing meta info to end up in cache */ 721 if (munmap(d->r, d->regions_total * sizeof(struct region_info))) 722 wrterror(d, "munmap %p", (void *)d->r); 723 else 724 STATS_SUB(d->malloc_used, 725 d->regions_total * sizeof(struct region_info)); 726 d->regions_free = d->regions_free + d->regions_total; 727 d->regions_total = newtotal; 728 d->r = p; 729 return 0; 730 } 731 732 static struct chunk_info * 733 alloc_chunk_info(struct dir_info *d, int bits) 734 { 735 struct chunk_info *p; 736 size_t size, count; 737 738 if (bits == 0) 739 count = MALLOC_PAGESIZE / MALLOC_MINSIZE; 740 else 741 count = MALLOC_PAGESIZE >> bits; 742 743 size = howmany(count, MALLOC_BITS); 744 size = sizeof(struct chunk_info) + (size - 1) * sizeof(u_short); 745 if (mopts.chunk_canaries) 746 size += count * sizeof(u_short); 747 size = ALIGN(size); 748 749 if (LIST_EMPTY(&d->chunk_info_list[bits])) { 750 char *q; 751 int i; 752 753 q = MMAP(MALLOC_PAGESIZE); 754 if (q == MAP_FAILED) 755 return NULL; 756 STATS_ADD(d->malloc_used, MALLOC_PAGESIZE); 757 count = MALLOC_PAGESIZE / size; 758 for (i = 0; i < count; i++, q += size) 759 LIST_INSERT_HEAD(&d->chunk_info_list[bits], 760 (struct chunk_info *)q, entries); 761 } 762 p = LIST_FIRST(&d->chunk_info_list[bits]); 763 LIST_REMOVE(p, entries); 764 memset(p, 0, size); 765 p->canary = d->canary1; 766 return p; 767 } 768 769 770 /* 771 * The hashtable uses the assumption that p is never NULL. This holds since 772 * non-MAP_FIXED mappings with hint 0 start at BRKSIZ. 773 */ 774 static int 775 insert(struct dir_info *d, void *p, size_t sz, void *f) 776 { 777 size_t index; 778 size_t mask; 779 void *q; 780 781 if (d->regions_free * 4 < d->regions_total) { 782 if (omalloc_grow(d)) 783 return 1; 784 } 785 mask = d->regions_total - 1; 786 index = hash(p) & mask; 787 q = d->r[index].p; 788 STATS_INC(d->inserts); 789 while (q != NULL) { 790 index = (index - 1) & mask; 791 q = d->r[index].p; 792 STATS_INC(d->insert_collisions); 793 } 794 d->r[index].p = p; 795 d->r[index].size = sz; 796 #ifdef MALLOC_STATS 797 d->r[index].f = f; 798 #endif 799 d->regions_free--; 800 return 0; 801 } 802 803 static struct region_info * 804 find(struct dir_info *d, void *p) 805 { 806 size_t index; 807 size_t mask = d->regions_total - 1; 808 void *q, *r; 809 810 if (mopts.malloc_canary != (d->canary1 ^ (u_int32_t)(uintptr_t)d) || 811 d->canary1 != ~d->canary2) 812 wrterror(d, "internal struct corrupt"); 813 p = MASK_POINTER(p); 814 index = hash(p) & mask; 815 r = d->r[index].p; 816 q = MASK_POINTER(r); 817 STATS_INC(d->finds); 818 while (q != p && r != NULL) { 819 index = (index - 1) & mask; 820 r = d->r[index].p; 821 q = MASK_POINTER(r); 822 STATS_INC(d->find_collisions); 823 } 824 return (q == p && r != NULL) ? &d->r[index] : NULL; 825 } 826 827 static void 828 delete(struct dir_info *d, struct region_info *ri) 829 { 830 /* algorithm R, Knuth Vol III section 6.4 */ 831 size_t mask = d->regions_total - 1; 832 size_t i, j, r; 833 834 if (d->regions_total & (d->regions_total - 1)) 835 wrterror(d, "regions_total not 2^x"); 836 d->regions_free++; 837 STATS_INC(d->deletes); 838 839 i = ri - d->r; 840 for (;;) { 841 d->r[i].p = NULL; 842 d->r[i].size = 0; 843 j = i; 844 for (;;) { 845 i = (i - 1) & mask; 846 if (d->r[i].p == NULL) 847 return; 848 r = hash(d->r[i].p) & mask; 849 if ((i <= r && r < j) || (r < j && j < i) || 850 (j < i && i <= r)) 851 continue; 852 d->r[j] = d->r[i]; 853 STATS_INC(d->delete_moves); 854 break; 855 } 856 857 } 858 } 859 860 /* 861 * Allocate a page of chunks 862 */ 863 static struct chunk_info * 864 omalloc_make_chunks(struct dir_info *d, int bits, int listnum) 865 { 866 struct chunk_info *bp; 867 void *pp; 868 int i, k; 869 870 /* Allocate a new bucket */ 871 pp = map(d, NULL, MALLOC_PAGESIZE, 0); 872 if (pp == MAP_FAILED) 873 return NULL; 874 875 bp = alloc_chunk_info(d, bits); 876 if (bp == NULL) { 877 unmap(d, pp, MALLOC_PAGESIZE, 0); 878 return NULL; 879 } 880 881 /* memory protect the page allocated in the malloc(0) case */ 882 if (bits == 0) { 883 bp->size = 0; 884 bp->shift = 1; 885 i = MALLOC_MINSIZE - 1; 886 while (i >>= 1) 887 bp->shift++; 888 bp->total = bp->free = MALLOC_PAGESIZE >> bp->shift; 889 bp->page = pp; 890 891 k = mprotect(pp, MALLOC_PAGESIZE, PROT_NONE); 892 if (k < 0) { 893 unmap(d, pp, MALLOC_PAGESIZE, 0); 894 LIST_INSERT_HEAD(&d->chunk_info_list[0], bp, entries); 895 return NULL; 896 } 897 } else { 898 bp->size = 1U << bits; 899 bp->shift = bits; 900 bp->total = bp->free = MALLOC_PAGESIZE >> bits; 901 bp->offset = howmany(bp->total, MALLOC_BITS); 902 bp->page = pp; 903 } 904 905 /* set all valid bits in the bitmap */ 906 k = bp->total; 907 i = 0; 908 909 /* Do a bunch at a time */ 910 for (; (k - i) >= MALLOC_BITS; i += MALLOC_BITS) 911 bp->bits[i / MALLOC_BITS] = (u_short)~0U; 912 913 for (; i < k; i++) 914 bp->bits[i / MALLOC_BITS] |= (u_short)1U << (i % MALLOC_BITS); 915 916 LIST_INSERT_HEAD(&d->chunk_dir[bits][listnum], bp, entries); 917 918 bits++; 919 if ((uintptr_t)pp & bits) 920 wrterror(d, "pp & bits %p", pp); 921 922 insert(d, (void *)((uintptr_t)pp | bits), (uintptr_t)bp, NULL); 923 return bp; 924 } 925 926 static int 927 find_chunksize(size_t size) 928 { 929 int i, j; 930 931 /* Don't bother with anything less than this */ 932 /* unless we have a malloc(0) requests */ 933 if (size != 0 && size < MALLOC_MINSIZE) 934 size = MALLOC_MINSIZE; 935 936 /* Find the right bucket */ 937 if (size == 0) 938 j = 0; 939 else { 940 j = MALLOC_MINSHIFT; 941 i = (size - 1) >> (MALLOC_MINSHIFT - 1); 942 while (i >>= 1) 943 j++; 944 } 945 return j; 946 } 947 948 /* 949 * Allocate a chunk 950 */ 951 static void * 952 malloc_bytes(struct dir_info *d, size_t size, void *f) 953 { 954 int i, j, listnum; 955 size_t k; 956 u_short u, *lp; 957 struct chunk_info *bp; 958 959 if (mopts.malloc_canary != (d->canary1 ^ (u_int32_t)(uintptr_t)d) || 960 d->canary1 != ~d->canary2) 961 wrterror(d, "internal struct corrupt"); 962 963 j = find_chunksize(size); 964 965 listnum = getrbyte(d) % MALLOC_CHUNK_LISTS; 966 /* If it's empty, make a page more of that size chunks */ 967 if ((bp = LIST_FIRST(&d->chunk_dir[j][listnum])) == NULL) { 968 bp = omalloc_make_chunks(d, j, listnum); 969 if (bp == NULL) 970 return NULL; 971 } 972 973 if (bp->canary != d->canary1) 974 wrterror(d, "chunk info corrupted"); 975 976 i = d->chunk_start; 977 if (bp->free > 1) 978 i += getrbyte(d); 979 if (i >= bp->total) 980 i &= bp->total - 1; 981 for (;;) { 982 for (;;) { 983 lp = &bp->bits[i / MALLOC_BITS]; 984 if (!*lp) { 985 i += MALLOC_BITS; 986 i &= ~(MALLOC_BITS - 1); 987 if (i >= bp->total) 988 i = 0; 989 } else 990 break; 991 } 992 k = i % MALLOC_BITS; 993 u = 1 << k; 994 if (*lp & u) 995 break; 996 if (++i >= bp->total) 997 i = 0; 998 } 999 d->chunk_start += i + 1; 1000 #ifdef MALLOC_STATS 1001 if (i == 0) { 1002 struct region_info *r = find(d, bp->page); 1003 r->f = f; 1004 } 1005 #endif 1006 1007 *lp ^= u; 1008 1009 /* If there are no more free, remove from free-list */ 1010 if (!--bp->free) 1011 LIST_REMOVE(bp, entries); 1012 1013 /* Adjust to the real offset of that chunk */ 1014 k += (lp - bp->bits) * MALLOC_BITS; 1015 1016 if (mopts.chunk_canaries && size > 0) 1017 bp->bits[bp->offset + k] = size; 1018 1019 k <<= bp->shift; 1020 1021 if (bp->size > 0) { 1022 if (mopts.malloc_junk == 2) 1023 memset((char *)bp->page + k, SOME_JUNK, bp->size); 1024 else if (mopts.chunk_canaries) 1025 fill_canary((char *)bp->page + k, size, bp->size); 1026 } 1027 return ((char *)bp->page + k); 1028 } 1029 1030 static void 1031 fill_canary(char *ptr, size_t sz, size_t allocated) 1032 { 1033 size_t check_sz = allocated - sz; 1034 1035 if (check_sz > CHUNK_CHECK_LENGTH) 1036 check_sz = CHUNK_CHECK_LENGTH; 1037 memset(ptr + sz, SOME_JUNK, check_sz); 1038 } 1039 1040 static void 1041 validate_canary(struct dir_info *d, u_char *ptr, size_t sz, size_t allocated) 1042 { 1043 size_t check_sz = allocated - sz; 1044 u_char *p, *q; 1045 1046 if (check_sz > CHUNK_CHECK_LENGTH) 1047 check_sz = CHUNK_CHECK_LENGTH; 1048 p = ptr + sz; 1049 q = p + check_sz; 1050 1051 while (p < q) { 1052 if (*p++ != SOME_JUNK) { 1053 wrterror(d, "chunk canary corrupted %p %#tx@%#zx", 1054 ptr, p - ptr - 1, sz); 1055 } 1056 } 1057 } 1058 1059 static uint32_t 1060 find_chunknum(struct dir_info *d, struct region_info *r, void *ptr, int check) 1061 { 1062 struct chunk_info *info; 1063 uint32_t chunknum; 1064 1065 info = (struct chunk_info *)r->size; 1066 if (info->canary != d->canary1) 1067 wrterror(d, "chunk info corrupted"); 1068 1069 /* Find the chunk number on the page */ 1070 chunknum = ((uintptr_t)ptr & MALLOC_PAGEMASK) >> info->shift; 1071 if (check && info->size > 0) { 1072 validate_canary(d, ptr, info->bits[info->offset + chunknum], 1073 info->size); 1074 } 1075 1076 if ((uintptr_t)ptr & ((1U << (info->shift)) - 1)) 1077 wrterror(d, "modified chunk-pointer %p", ptr); 1078 if (info->bits[chunknum / MALLOC_BITS] & 1079 (1U << (chunknum % MALLOC_BITS))) 1080 wrterror(d, "chunk is already free %p", ptr); 1081 return chunknum; 1082 } 1083 1084 /* 1085 * Free a chunk, and possibly the page it's on, if the page becomes empty. 1086 */ 1087 static void 1088 free_bytes(struct dir_info *d, struct region_info *r, void *ptr) 1089 { 1090 struct chunk_head *mp; 1091 struct chunk_info *info; 1092 uint32_t chunknum; 1093 int listnum; 1094 1095 info = (struct chunk_info *)r->size; 1096 chunknum = find_chunknum(d, r, ptr, 0); 1097 1098 info->bits[chunknum / MALLOC_BITS] |= 1U << (chunknum % MALLOC_BITS); 1099 info->free++; 1100 1101 if (info->free == 1) { 1102 /* Page became non-full */ 1103 listnum = getrbyte(d) % MALLOC_CHUNK_LISTS; 1104 if (info->size != 0) 1105 mp = &d->chunk_dir[info->shift][listnum]; 1106 else 1107 mp = &d->chunk_dir[0][listnum]; 1108 1109 LIST_INSERT_HEAD(mp, info, entries); 1110 return; 1111 } 1112 1113 if (info->free != info->total) 1114 return; 1115 1116 LIST_REMOVE(info, entries); 1117 1118 if (info->size == 0 && !mopts.malloc_freeunmap) 1119 mprotect(info->page, MALLOC_PAGESIZE, PROT_READ | PROT_WRITE); 1120 unmap(d, info->page, MALLOC_PAGESIZE, 0); 1121 1122 delete(d, r); 1123 if (info->size != 0) 1124 mp = &d->chunk_info_list[info->shift]; 1125 else 1126 mp = &d->chunk_info_list[0]; 1127 LIST_INSERT_HEAD(mp, info, entries); 1128 } 1129 1130 1131 1132 static void * 1133 omalloc(struct dir_info *pool, size_t sz, int zero_fill, void *f) 1134 { 1135 void *p; 1136 size_t psz; 1137 1138 if (sz > MALLOC_MAXCHUNK) { 1139 if (sz >= SIZE_MAX - mopts.malloc_guard - MALLOC_PAGESIZE) { 1140 errno = ENOMEM; 1141 return NULL; 1142 } 1143 sz += mopts.malloc_guard; 1144 psz = PAGEROUND(sz); 1145 p = map(pool, NULL, psz, zero_fill); 1146 if (p == MAP_FAILED) { 1147 errno = ENOMEM; 1148 return NULL; 1149 } 1150 if (insert(pool, p, sz, f)) { 1151 unmap(pool, p, psz, 0); 1152 errno = ENOMEM; 1153 return NULL; 1154 } 1155 if (mopts.malloc_guard) { 1156 if (mprotect((char *)p + psz - mopts.malloc_guard, 1157 mopts.malloc_guard, PROT_NONE)) 1158 wrterror(pool, "mprotect"); 1159 STATS_ADD(pool->malloc_guarded, mopts.malloc_guard); 1160 } 1161 1162 if (MALLOC_MOVE_COND(sz)) { 1163 /* fill whole allocation */ 1164 if (mopts.malloc_junk == 2) 1165 memset(p, SOME_JUNK, psz - mopts.malloc_guard); 1166 /* shift towards the end */ 1167 p = MALLOC_MOVE(p, sz); 1168 /* fill zeros if needed and overwritten above */ 1169 if (zero_fill && mopts.malloc_junk == 2) 1170 memset(p, 0, sz - mopts.malloc_guard); 1171 } else { 1172 if (mopts.malloc_junk == 2) { 1173 if (zero_fill) 1174 memset((char *)p + sz - mopts.malloc_guard, 1175 SOME_JUNK, psz - sz); 1176 else 1177 memset(p, SOME_JUNK, 1178 psz - mopts.malloc_guard); 1179 } 1180 else if (mopts.chunk_canaries) 1181 fill_canary(p, sz - mopts.malloc_guard, 1182 psz - mopts.malloc_guard); 1183 } 1184 1185 } else { 1186 /* takes care of SOME_JUNK */ 1187 p = malloc_bytes(pool, sz, f); 1188 if (zero_fill && p != NULL && sz > 0) 1189 memset(p, 0, sz); 1190 } 1191 1192 return p; 1193 } 1194 1195 /* 1196 * Common function for handling recursion. Only 1197 * print the error message once, to avoid making the problem 1198 * potentially worse. 1199 */ 1200 static void 1201 malloc_recurse(struct dir_info *d) 1202 { 1203 static int noprint; 1204 1205 if (noprint == 0) { 1206 noprint = 1; 1207 wrterror(d, "recursive call"); 1208 } 1209 d->active--; 1210 _MALLOC_UNLOCK(d->mutex); 1211 errno = EDEADLK; 1212 } 1213 1214 void 1215 _malloc_init(int from_rthreads) 1216 { 1217 int i, max; 1218 struct dir_info *d; 1219 1220 _MALLOC_LOCK(0); 1221 if (!from_rthreads && mopts.malloc_pool[0]) { 1222 _MALLOC_UNLOCK(0); 1223 return; 1224 } 1225 if (!mopts.malloc_canary) 1226 omalloc_init(); 1227 1228 max = from_rthreads ? _MALLOC_MUTEXES : 1; 1229 if (((uintptr_t)&malloc_readonly & MALLOC_PAGEMASK) == 0) 1230 mprotect(&malloc_readonly, sizeof(malloc_readonly), 1231 PROT_READ | PROT_WRITE); 1232 for (i = 0; i < max; i++) { 1233 if (mopts.malloc_pool[i]) 1234 continue; 1235 omalloc_poolinit(&d); 1236 d->mutex = i; 1237 mopts.malloc_pool[i] = d; 1238 } 1239 1240 if (from_rthreads) 1241 mopts.malloc_mt = 1; 1242 else 1243 mopts.internal_funcs = 1; 1244 1245 /* 1246 * Options have been set and will never be reset. 1247 * Prevent further tampering with them. 1248 */ 1249 if (((uintptr_t)&malloc_readonly & MALLOC_PAGEMASK) == 0) 1250 mprotect(&malloc_readonly, sizeof(malloc_readonly), PROT_READ); 1251 _MALLOC_UNLOCK(0); 1252 } 1253 DEF_STRONG(_malloc_init); 1254 1255 void * 1256 malloc(size_t size) 1257 { 1258 void *r; 1259 struct dir_info *d; 1260 int saved_errno = errno; 1261 1262 d = getpool(); 1263 if (d == NULL) { 1264 _malloc_init(0); 1265 d = getpool(); 1266 } 1267 _MALLOC_LOCK(d->mutex); 1268 d->func = "malloc"; 1269 1270 if (d->active++) { 1271 malloc_recurse(d); 1272 return NULL; 1273 } 1274 r = omalloc(d, size, 0, CALLER); 1275 d->active--; 1276 _MALLOC_UNLOCK(d->mutex); 1277 if (r == NULL && mopts.malloc_xmalloc) 1278 wrterror(d, "out of memory"); 1279 if (r != NULL) 1280 errno = saved_errno; 1281 return r; 1282 } 1283 /*DEF_STRONG(malloc);*/ 1284 1285 static void 1286 validate_junk(struct dir_info *pool, void *p) 1287 { 1288 struct region_info *r; 1289 size_t byte, sz; 1290 1291 if (p == NULL) 1292 return; 1293 r = find(pool, p); 1294 if (r == NULL) 1295 wrterror(pool, "bogus pointer in validate_junk %p", p); 1296 REALSIZE(sz, r); 1297 if (sz > CHUNK_CHECK_LENGTH) 1298 sz = CHUNK_CHECK_LENGTH; 1299 for (byte = 0; byte < sz; byte++) { 1300 if (((unsigned char *)p)[byte] != SOME_FREEJUNK) 1301 wrterror(pool, "use after free %p", p); 1302 } 1303 } 1304 1305 static void 1306 ofree(struct dir_info *argpool, void *p, int clear, int check, size_t argsz) 1307 { 1308 struct dir_info *pool; 1309 struct region_info *r; 1310 size_t sz; 1311 int i; 1312 1313 pool = argpool; 1314 r = find(pool, p); 1315 if (r == NULL) { 1316 if (mopts.malloc_mt) { 1317 for (i = 0; i < _MALLOC_MUTEXES; i++) { 1318 if (i == argpool->mutex) 1319 continue; 1320 pool->active--; 1321 _MALLOC_UNLOCK(pool->mutex); 1322 pool = mopts.malloc_pool[i]; 1323 _MALLOC_LOCK(pool->mutex); 1324 pool->active++; 1325 r = find(pool, p); 1326 if (r != NULL) 1327 break; 1328 } 1329 } 1330 if (r == NULL) 1331 wrterror(pool, "bogus pointer (double free?) %p", p); 1332 } 1333 1334 REALSIZE(sz, r); 1335 if (check) { 1336 if (sz <= MALLOC_MAXCHUNK) { 1337 if (mopts.chunk_canaries && sz > 0) { 1338 struct chunk_info *info = 1339 (struct chunk_info *)r->size; 1340 uint32_t chunknum = 1341 find_chunknum(pool, r, p, 0); 1342 1343 if (info->bits[info->offset + chunknum] < 1344 argsz) 1345 wrterror(pool, "recorded size %hu" 1346 " < %zu", 1347 info->bits[info->offset + chunknum], 1348 argsz); 1349 } else { 1350 if (sz < argsz) 1351 wrterror(pool, "chunk size %zu < %zu", 1352 sz, argsz); 1353 } 1354 } else if (sz - mopts.malloc_guard < argsz) { 1355 wrterror(pool, "recorded size %zu < %zu", 1356 sz - mopts.malloc_guard, argsz); 1357 } 1358 } 1359 if (sz > MALLOC_MAXCHUNK) { 1360 if (!MALLOC_MOVE_COND(sz)) { 1361 if (r->p != p) 1362 wrterror(pool, "bogus pointer %p", p); 1363 if (mopts.chunk_canaries) 1364 validate_canary(pool, p, 1365 sz - mopts.malloc_guard, 1366 PAGEROUND(sz - mopts.malloc_guard)); 1367 } else { 1368 /* shifted towards the end */ 1369 if (p != MALLOC_MOVE(r->p, sz)) 1370 wrterror(pool, "bogus moved pointer %p", p); 1371 p = r->p; 1372 } 1373 if (mopts.malloc_guard) { 1374 if (sz < mopts.malloc_guard) 1375 wrterror(pool, "guard size"); 1376 if (!mopts.malloc_freeunmap) { 1377 if (mprotect((char *)p + PAGEROUND(sz) - 1378 mopts.malloc_guard, mopts.malloc_guard, 1379 PROT_READ | PROT_WRITE)) 1380 wrterror(pool, "mprotect"); 1381 } 1382 STATS_SUB(pool->malloc_guarded, mopts.malloc_guard); 1383 } 1384 unmap(pool, p, PAGEROUND(sz), clear); 1385 delete(pool, r); 1386 } else { 1387 void *tmp; 1388 int i; 1389 1390 /* Delayed free or canaries? Extra check */ 1391 if (!mopts.malloc_freenow || mopts.chunk_canaries) 1392 find_chunknum(pool, r, p, mopts.chunk_canaries); 1393 if (!clear && !mopts.malloc_freenow) { 1394 if (mopts.malloc_junk && sz > 0) 1395 memset(p, SOME_FREEJUNK, sz); 1396 i = getrbyte(pool) & MALLOC_DELAYED_CHUNK_MASK; 1397 tmp = p; 1398 p = pool->delayed_chunks[i]; 1399 if (tmp == p) 1400 wrterror(pool, "double free %p", tmp); 1401 if (mopts.malloc_junk) 1402 validate_junk(pool, p); 1403 pool->delayed_chunks[i] = tmp; 1404 } else { 1405 if ((clear || mopts.malloc_junk) && sz > 0) 1406 memset(p, clear ? 0 : SOME_FREEJUNK, sz); 1407 } 1408 if (p != NULL) { 1409 r = find(pool, p); 1410 if (r == NULL) 1411 wrterror(pool, 1412 "bogus pointer (double free?) %p", p); 1413 free_bytes(pool, r, p); 1414 } 1415 } 1416 1417 if (argpool != pool) { 1418 pool->active--; 1419 _MALLOC_UNLOCK(pool->mutex); 1420 _MALLOC_LOCK(argpool->mutex); 1421 argpool->active++; 1422 } 1423 } 1424 1425 void 1426 free(void *ptr) 1427 { 1428 struct dir_info *d; 1429 int saved_errno = errno; 1430 1431 /* This is legal. */ 1432 if (ptr == NULL) 1433 return; 1434 1435 d = getpool(); 1436 if (d == NULL) 1437 wrterror(d, "free() called before allocation"); 1438 _MALLOC_LOCK(d->mutex); 1439 d->func = "free"; 1440 if (d->active++) { 1441 malloc_recurse(d); 1442 return; 1443 } 1444 ofree(d, ptr, 0, 0, 0); 1445 d->active--; 1446 _MALLOC_UNLOCK(d->mutex); 1447 errno = saved_errno; 1448 } 1449 /*DEF_STRONG(free);*/ 1450 1451 static void 1452 freezero_p(void *ptr, size_t sz) 1453 { 1454 explicit_bzero(ptr, sz); 1455 free(ptr); 1456 } 1457 1458 void 1459 freezero(void *ptr, size_t sz) 1460 { 1461 struct dir_info *d; 1462 int saved_errno = errno; 1463 1464 /* This is legal. */ 1465 if (ptr == NULL) 1466 return; 1467 1468 if (!mopts.internal_funcs) 1469 return freezero_p(ptr, sz); 1470 1471 d = getpool(); 1472 if (d == NULL) 1473 wrterror(d, "freezero() called before allocation"); 1474 _MALLOC_LOCK(d->mutex); 1475 d->func = "freezero"; 1476 if (d->active++) { 1477 malloc_recurse(d); 1478 return; 1479 } 1480 ofree(d, ptr, 1, 1, sz); 1481 d->active--; 1482 _MALLOC_UNLOCK(d->mutex); 1483 errno = saved_errno; 1484 } 1485 DEF_WEAK(freezero); 1486 1487 static void * 1488 orealloc(struct dir_info *argpool, void *p, size_t newsz, void *f) 1489 { 1490 struct dir_info *pool; 1491 struct region_info *r; 1492 struct chunk_info *info; 1493 size_t oldsz, goldsz, gnewsz; 1494 void *q, *ret; 1495 int i; 1496 uint32_t chunknum; 1497 1498 pool = argpool; 1499 1500 if (p == NULL) 1501 return omalloc(pool, newsz, 0, f); 1502 1503 r = find(pool, p); 1504 if (r == NULL) { 1505 if (mopts.malloc_mt) { 1506 for (i = 0; i < _MALLOC_MUTEXES; i++) { 1507 if (i == argpool->mutex) 1508 continue; 1509 pool->active--; 1510 _MALLOC_UNLOCK(pool->mutex); 1511 pool = mopts.malloc_pool[i]; 1512 _MALLOC_LOCK(pool->mutex); 1513 pool->active++; 1514 r = find(pool, p); 1515 if (r != NULL) 1516 break; 1517 } 1518 } 1519 if (r == NULL) 1520 wrterror(pool, "bogus pointer (double free?) %p", p); 1521 } 1522 if (newsz >= SIZE_MAX - mopts.malloc_guard - MALLOC_PAGESIZE) { 1523 errno = ENOMEM; 1524 ret = NULL; 1525 goto done; 1526 } 1527 1528 REALSIZE(oldsz, r); 1529 if (mopts.chunk_canaries && oldsz <= MALLOC_MAXCHUNK) { 1530 chunknum = find_chunknum(pool, r, p, 0); 1531 info = (struct chunk_info *)r->size; 1532 } 1533 1534 goldsz = oldsz; 1535 if (oldsz > MALLOC_MAXCHUNK) { 1536 if (oldsz < mopts.malloc_guard) 1537 wrterror(pool, "guard size"); 1538 oldsz -= mopts.malloc_guard; 1539 } 1540 1541 gnewsz = newsz; 1542 if (gnewsz > MALLOC_MAXCHUNK) 1543 gnewsz += mopts.malloc_guard; 1544 1545 if (newsz > MALLOC_MAXCHUNK && oldsz > MALLOC_MAXCHUNK && 1546 !mopts.malloc_realloc) { 1547 /* First case: from n pages sized allocation to m pages sized 1548 allocation, m > n */ 1549 size_t roldsz = PAGEROUND(goldsz); 1550 size_t rnewsz = PAGEROUND(gnewsz); 1551 1552 if (rnewsz > roldsz) { 1553 /* try to extend existing region */ 1554 if (!mopts.malloc_guard) { 1555 void *hint = (char *)r->p + roldsz; 1556 size_t needed = rnewsz - roldsz; 1557 1558 STATS_INC(pool->cheap_realloc_tries); 1559 q = map(pool, hint, needed, 0); 1560 if (q == hint) 1561 goto gotit; 1562 zapcacheregion(pool, hint, needed); 1563 q = MQUERY(hint, needed); 1564 if (q == hint) 1565 q = MMAPA(hint, needed); 1566 else 1567 q = MAP_FAILED; 1568 if (q == hint) { 1569 gotit: 1570 STATS_ADD(pool->malloc_used, needed); 1571 if (mopts.malloc_junk == 2) 1572 memset(q, SOME_JUNK, needed); 1573 r->size = gnewsz; 1574 if (r->p != p) { 1575 /* old pointer is moved */ 1576 memmove(r->p, p, oldsz); 1577 p = r->p; 1578 } 1579 if (mopts.chunk_canaries) 1580 fill_canary(p, newsz, 1581 PAGEROUND(newsz)); 1582 STATS_SETF(r, f); 1583 STATS_INC(pool->cheap_reallocs); 1584 ret = p; 1585 goto done; 1586 } else if (q != MAP_FAILED) { 1587 if (munmap(q, needed)) 1588 wrterror(pool, "munmap %p", q); 1589 } 1590 } 1591 } else if (rnewsz < roldsz) { 1592 /* shrink number of pages */ 1593 if (mopts.malloc_guard) { 1594 if (mprotect((char *)r->p + roldsz - 1595 mopts.malloc_guard, mopts.malloc_guard, 1596 PROT_READ | PROT_WRITE)) 1597 wrterror(pool, "mprotect"); 1598 if (mprotect((char *)r->p + rnewsz - 1599 mopts.malloc_guard, mopts.malloc_guard, 1600 PROT_NONE)) 1601 wrterror(pool, "mprotect"); 1602 } 1603 unmap(pool, (char *)r->p + rnewsz, roldsz - rnewsz, 0); 1604 r->size = gnewsz; 1605 if (MALLOC_MOVE_COND(gnewsz)) { 1606 void *pp = MALLOC_MOVE(r->p, gnewsz); 1607 memmove(pp, p, newsz); 1608 p = pp; 1609 } else if (mopts.chunk_canaries) 1610 fill_canary(p, newsz, PAGEROUND(newsz)); 1611 STATS_SETF(r, f); 1612 ret = p; 1613 goto done; 1614 } else { 1615 /* number of pages remains the same */ 1616 void *pp = r->p; 1617 1618 r->size = gnewsz; 1619 if (MALLOC_MOVE_COND(gnewsz)) 1620 pp = MALLOC_MOVE(r->p, gnewsz); 1621 if (p != pp) { 1622 memmove(pp, p, oldsz < newsz ? oldsz : newsz); 1623 p = pp; 1624 } 1625 if (p == r->p) { 1626 if (newsz > oldsz && mopts.malloc_junk == 2) 1627 memset((char *)p + newsz, SOME_JUNK, 1628 rnewsz - mopts.malloc_guard - 1629 newsz); 1630 if (mopts.chunk_canaries) 1631 fill_canary(p, newsz, PAGEROUND(newsz)); 1632 } 1633 STATS_SETF(r, f); 1634 ret = p; 1635 goto done; 1636 } 1637 } 1638 if (oldsz <= MALLOC_MAXCHUNK && oldsz > 0 && 1639 newsz <= MALLOC_MAXCHUNK && newsz > 0 && 1640 1 << find_chunksize(newsz) == oldsz && !mopts.malloc_realloc) { 1641 /* do not reallocate if new size fits good in existing chunk */ 1642 if (mopts.malloc_junk == 2) 1643 memset((char *)p + newsz, SOME_JUNK, oldsz - newsz); 1644 if (mopts.chunk_canaries) { 1645 info->bits[info->offset + chunknum] = newsz; 1646 fill_canary(p, newsz, info->size); 1647 } 1648 STATS_SETF(r, f); 1649 ret = p; 1650 } else if (newsz != oldsz || mopts.malloc_realloc) { 1651 /* create new allocation */ 1652 q = omalloc(pool, newsz, 0, f); 1653 if (q == NULL) { 1654 ret = NULL; 1655 goto done; 1656 } 1657 if (newsz != 0 && oldsz != 0) 1658 memcpy(q, p, oldsz < newsz ? oldsz : newsz); 1659 ofree(pool, p, 0, 0, 0); 1660 ret = q; 1661 } else { 1662 /* oldsz == newsz */ 1663 if (newsz != 0) 1664 wrterror(pool, "realloc internal inconsistency"); 1665 STATS_SETF(r, f); 1666 ret = p; 1667 } 1668 done: 1669 if (argpool != pool) { 1670 pool->active--; 1671 _MALLOC_UNLOCK(pool->mutex); 1672 _MALLOC_LOCK(argpool->mutex); 1673 argpool->active++; 1674 } 1675 return ret; 1676 } 1677 1678 void * 1679 realloc(void *ptr, size_t size) 1680 { 1681 struct dir_info *d; 1682 void *r; 1683 int saved_errno = errno; 1684 1685 d = getpool(); 1686 if (d == NULL) { 1687 _malloc_init(0); 1688 d = getpool(); 1689 } 1690 _MALLOC_LOCK(d->mutex); 1691 d->func = "realloc"; 1692 if (d->active++) { 1693 malloc_recurse(d); 1694 return NULL; 1695 } 1696 r = orealloc(d, ptr, size, CALLER); 1697 1698 d->active--; 1699 _MALLOC_UNLOCK(d->mutex); 1700 if (r == NULL && mopts.malloc_xmalloc) 1701 wrterror(d, "out of memory"); 1702 if (r != NULL) 1703 errno = saved_errno; 1704 return r; 1705 } 1706 /*DEF_STRONG(realloc);*/ 1707 1708 1709 /* 1710 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX 1711 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW 1712 */ 1713 #define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4)) 1714 1715 void * 1716 calloc(size_t nmemb, size_t size) 1717 { 1718 struct dir_info *d; 1719 void *r; 1720 int saved_errno = errno; 1721 1722 d = getpool(); 1723 if (d == NULL) { 1724 _malloc_init(0); 1725 d = getpool(); 1726 } 1727 _MALLOC_LOCK(d->mutex); 1728 d->func = "calloc"; 1729 if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 1730 nmemb > 0 && SIZE_MAX / nmemb < size) { 1731 _MALLOC_UNLOCK(d->mutex); 1732 if (mopts.malloc_xmalloc) 1733 wrterror(d, "out of memory"); 1734 errno = ENOMEM; 1735 return NULL; 1736 } 1737 1738 if (d->active++) { 1739 malloc_recurse(d); 1740 return NULL; 1741 } 1742 1743 size *= nmemb; 1744 r = omalloc(d, size, 1, CALLER); 1745 1746 d->active--; 1747 _MALLOC_UNLOCK(d->mutex); 1748 if (r == NULL && mopts.malloc_xmalloc) 1749 wrterror(d, "out of memory"); 1750 if (r != NULL) 1751 errno = saved_errno; 1752 return r; 1753 } 1754 /*DEF_STRONG(calloc);*/ 1755 1756 static void * 1757 orecallocarray(struct dir_info *argpool, void *p, size_t oldsize, 1758 size_t newsize, void *f) 1759 { 1760 struct dir_info *pool; 1761 struct region_info *r; 1762 void *newptr; 1763 size_t sz; 1764 int i; 1765 1766 pool = argpool; 1767 1768 if (p == NULL) 1769 return omalloc(pool, newsize, 1, f); 1770 1771 if (oldsize == newsize) 1772 return p; 1773 1774 r = find(pool, p); 1775 if (r == NULL) { 1776 if (mopts.malloc_mt) { 1777 for (i = 0; i < _MALLOC_MUTEXES; i++) { 1778 if (i == argpool->mutex) 1779 continue; 1780 pool->active--; 1781 _MALLOC_UNLOCK(pool->mutex); 1782 pool = mopts.malloc_pool[i]; 1783 _MALLOC_LOCK(pool->mutex); 1784 pool->active++; 1785 r = find(pool, p); 1786 if (r != NULL) 1787 break; 1788 } 1789 } 1790 if (r == NULL) 1791 wrterror(pool, "bogus pointer (double free?) %p", p); 1792 } 1793 1794 REALSIZE(sz, r); 1795 if (sz <= MALLOC_MAXCHUNK) { 1796 if (mopts.chunk_canaries) { 1797 struct chunk_info *info = (struct chunk_info *)r->size; 1798 uint32_t chunknum = find_chunknum(pool, r, p, 0); 1799 1800 if (info->bits[info->offset + chunknum] != oldsize) 1801 wrterror(pool, "recorded old size %hu != %zu", 1802 info->bits[info->offset + chunknum], 1803 oldsize); 1804 } 1805 } else if (oldsize != sz - mopts.malloc_guard) 1806 wrterror(pool, "recorded old size %zu != %zu", 1807 sz - mopts.malloc_guard, oldsize); 1808 1809 newptr = omalloc(pool, newsize, 0, f); 1810 if (newptr == NULL) 1811 goto done; 1812 1813 if (newsize > oldsize) { 1814 memcpy(newptr, p, oldsize); 1815 memset((char *)newptr + oldsize, 0, newsize - oldsize); 1816 } else 1817 memcpy(newptr, p, newsize); 1818 1819 ofree(pool, p, 1, 0, 0); 1820 1821 done: 1822 if (argpool != pool) { 1823 pool->active--; 1824 _MALLOC_UNLOCK(pool->mutex); 1825 _MALLOC_LOCK(argpool->mutex); 1826 argpool->active++; 1827 } 1828 1829 return newptr; 1830 } 1831 1832 static void * 1833 recallocarray_p(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size) 1834 { 1835 size_t oldsize, newsize; 1836 void *newptr; 1837 1838 if (ptr == NULL) 1839 return calloc(newnmemb, size); 1840 1841 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 1842 newnmemb > 0 && SIZE_MAX / newnmemb < size) { 1843 errno = ENOMEM; 1844 return NULL; 1845 } 1846 newsize = newnmemb * size; 1847 1848 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 1849 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) { 1850 errno = EINVAL; 1851 return NULL; 1852 } 1853 oldsize = oldnmemb * size; 1854 1855 /* 1856 * Don't bother too much if we're shrinking just a bit, 1857 * we do not shrink for series of small steps, oh well. 1858 */ 1859 if (newsize <= oldsize) { 1860 size_t d = oldsize - newsize; 1861 1862 if (d < oldsize / 2 && d < MALLOC_PAGESIZE) { 1863 memset((char *)ptr + newsize, 0, d); 1864 return ptr; 1865 } 1866 } 1867 1868 newptr = malloc(newsize); 1869 if (newptr == NULL) 1870 return NULL; 1871 1872 if (newsize > oldsize) { 1873 memcpy(newptr, ptr, oldsize); 1874 memset((char *)newptr + oldsize, 0, newsize - oldsize); 1875 } else 1876 memcpy(newptr, ptr, newsize); 1877 1878 explicit_bzero(ptr, oldsize); 1879 free(ptr); 1880 1881 return newptr; 1882 } 1883 1884 void * 1885 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size) 1886 { 1887 struct dir_info *d; 1888 size_t oldsize = 0, newsize; 1889 void *r; 1890 int saved_errno = errno; 1891 1892 if (!mopts.internal_funcs) 1893 return recallocarray_p(ptr, oldnmemb, newnmemb, size); 1894 1895 d = getpool(); 1896 if (d == NULL) { 1897 _malloc_init(0); 1898 d = getpool(); 1899 } 1900 1901 _MALLOC_LOCK(d->mutex); 1902 d->func = "recallocarray"; 1903 1904 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 1905 newnmemb > 0 && SIZE_MAX / newnmemb < size) { 1906 _MALLOC_UNLOCK(d->mutex); 1907 if (mopts.malloc_xmalloc) 1908 wrterror(d, "out of memory"); 1909 errno = ENOMEM; 1910 return NULL; 1911 } 1912 newsize = newnmemb * size; 1913 1914 if (ptr != NULL) { 1915 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && 1916 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) { 1917 _MALLOC_UNLOCK(d->mutex); 1918 errno = EINVAL; 1919 return NULL; 1920 } 1921 oldsize = oldnmemb * size; 1922 } 1923 1924 if (d->active++) { 1925 malloc_recurse(d); 1926 return NULL; 1927 } 1928 1929 r = orecallocarray(d, ptr, oldsize, newsize, CALLER); 1930 1931 d->active--; 1932 _MALLOC_UNLOCK(d->mutex); 1933 if (r == NULL && mopts.malloc_xmalloc) 1934 wrterror(d, "out of memory"); 1935 if (r != NULL) 1936 errno = saved_errno; 1937 return r; 1938 } 1939 DEF_WEAK(recallocarray); 1940 1941 1942 static void * 1943 mapalign(struct dir_info *d, size_t alignment, size_t sz, int zero_fill) 1944 { 1945 char *p, *q; 1946 1947 if (alignment < MALLOC_PAGESIZE || ((alignment - 1) & alignment) != 0) 1948 wrterror(d, "mapalign bad alignment"); 1949 if (sz != PAGEROUND(sz)) 1950 wrterror(d, "mapalign round"); 1951 1952 /* Allocate sz + alignment bytes of memory, which must include a 1953 * subrange of size bytes that is properly aligned. Unmap the 1954 * other bytes, and then return that subrange. 1955 */ 1956 1957 /* We need sz + alignment to fit into a size_t. */ 1958 if (alignment > SIZE_MAX - sz) 1959 return MAP_FAILED; 1960 1961 p = map(d, NULL, sz + alignment, zero_fill); 1962 if (p == MAP_FAILED) 1963 return MAP_FAILED; 1964 q = (char *)(((uintptr_t)p + alignment - 1) & ~(alignment - 1)); 1965 if (q != p) { 1966 if (munmap(p, q - p)) 1967 wrterror(d, "munmap %p", p); 1968 } 1969 if (munmap(q + sz, alignment - (q - p))) 1970 wrterror(d, "munmap %p", q + sz); 1971 STATS_SUB(d->malloc_used, alignment); 1972 1973 return q; 1974 } 1975 1976 static void * 1977 omemalign(struct dir_info *pool, size_t alignment, size_t sz, int zero_fill, 1978 void *f) 1979 { 1980 size_t psz; 1981 void *p; 1982 1983 /* If between half a page and a page, avoid MALLOC_MOVE. */ 1984 if (sz > MALLOC_MAXCHUNK && sz < MALLOC_PAGESIZE) 1985 sz = MALLOC_PAGESIZE; 1986 if (alignment <= MALLOC_PAGESIZE) { 1987 /* 1988 * max(size, alignment) is enough to assure the requested 1989 * alignment, since the allocator always allocates 1990 * power-of-two blocks. 1991 */ 1992 if (sz < alignment) 1993 sz = alignment; 1994 return omalloc(pool, sz, zero_fill, f); 1995 } 1996 1997 if (sz >= SIZE_MAX - mopts.malloc_guard - MALLOC_PAGESIZE) { 1998 errno = ENOMEM; 1999 return NULL; 2000 } 2001 2002 sz += mopts.malloc_guard; 2003 psz = PAGEROUND(sz); 2004 2005 p = mapalign(pool, alignment, psz, zero_fill); 2006 if (p == NULL) { 2007 errno = ENOMEM; 2008 return NULL; 2009 } 2010 2011 if (insert(pool, p, sz, f)) { 2012 unmap(pool, p, psz, 0); 2013 errno = ENOMEM; 2014 return NULL; 2015 } 2016 2017 if (mopts.malloc_guard) { 2018 if (mprotect((char *)p + psz - mopts.malloc_guard, 2019 mopts.malloc_guard, PROT_NONE)) 2020 wrterror(pool, "mprotect"); 2021 STATS_ADD(pool->malloc_guarded, mopts.malloc_guard); 2022 } 2023 2024 if (mopts.malloc_junk == 2) { 2025 if (zero_fill) 2026 memset((char *)p + sz - mopts.malloc_guard, 2027 SOME_JUNK, psz - sz); 2028 else 2029 memset(p, SOME_JUNK, psz - mopts.malloc_guard); 2030 } 2031 else if (mopts.chunk_canaries) 2032 fill_canary(p, sz - mopts.malloc_guard, 2033 psz - mopts.malloc_guard); 2034 2035 return p; 2036 } 2037 2038 int 2039 posix_memalign(void **memptr, size_t alignment, size_t size) 2040 { 2041 struct dir_info *d; 2042 int res, saved_errno = errno; 2043 void *r; 2044 2045 /* Make sure that alignment is a large enough power of 2. */ 2046 if (((alignment - 1) & alignment) != 0 || alignment < sizeof(void *)) 2047 return EINVAL; 2048 2049 d = getpool(); 2050 if (d == NULL) { 2051 _malloc_init(0); 2052 d = getpool(); 2053 } 2054 _MALLOC_LOCK(d->mutex); 2055 d->func = "posix_memalign"; 2056 if (d->active++) { 2057 malloc_recurse(d); 2058 goto err; 2059 } 2060 r = omemalign(d, alignment, size, 0, CALLER); 2061 d->active--; 2062 _MALLOC_UNLOCK(d->mutex); 2063 if (r == NULL) { 2064 if (mopts.malloc_xmalloc) 2065 wrterror(d, "out of memory"); 2066 goto err; 2067 } 2068 errno = saved_errno; 2069 *memptr = r; 2070 return 0; 2071 2072 err: 2073 res = errno; 2074 errno = saved_errno; 2075 return res; 2076 } 2077 /*DEF_STRONG(posix_memalign);*/ 2078 2079 #ifdef MALLOC_STATS 2080 2081 struct malloc_leak { 2082 void (*f)(); 2083 size_t total_size; 2084 int count; 2085 }; 2086 2087 struct leaknode { 2088 RBT_ENTRY(leaknode) entry; 2089 struct malloc_leak d; 2090 }; 2091 2092 static inline int 2093 leakcmp(const struct leaknode *e1, const struct leaknode *e2) 2094 { 2095 return e1->d.f < e2->d.f ? -1 : e1->d.f > e2->d.f; 2096 } 2097 2098 static RBT_HEAD(leaktree, leaknode) leakhead; 2099 RBT_PROTOTYPE(leaktree, leaknode, entry, leakcmp); 2100 RBT_GENERATE(leaktree, leaknode, entry, leakcmp); 2101 2102 static void 2103 putleakinfo(void *f, size_t sz, int cnt) 2104 { 2105 struct leaknode key, *p; 2106 static struct leaknode *page; 2107 static int used; 2108 2109 if (cnt == 0 || page == MAP_FAILED) 2110 return; 2111 2112 key.d.f = f; 2113 p = RBT_FIND(leaktree, &leakhead, &key); 2114 if (p == NULL) { 2115 if (page == NULL || 2116 used >= MALLOC_PAGESIZE / sizeof(struct leaknode)) { 2117 page = MMAP(MALLOC_PAGESIZE); 2118 if (page == MAP_FAILED) 2119 return; 2120 used = 0; 2121 } 2122 p = &page[used++]; 2123 p->d.f = f; 2124 p->d.total_size = sz * cnt; 2125 p->d.count = cnt; 2126 RBT_INSERT(leaktree, &leakhead, p); 2127 } else { 2128 p->d.total_size += sz * cnt; 2129 p->d.count += cnt; 2130 } 2131 } 2132 2133 static struct malloc_leak *malloc_leaks; 2134 2135 static void 2136 writestr(int fd, const char *p) 2137 { 2138 write(fd, p, strlen(p)); 2139 } 2140 2141 static void 2142 dump_leaks(int fd) 2143 { 2144 struct leaknode *p; 2145 char buf[64]; 2146 int i = 0; 2147 2148 writestr(fd, "Leak report\n"); 2149 writestr(fd, " f sum # avg\n"); 2150 /* XXX only one page of summary */ 2151 if (malloc_leaks == NULL) 2152 malloc_leaks = MMAP(MALLOC_PAGESIZE); 2153 if (malloc_leaks != MAP_FAILED) 2154 memset(malloc_leaks, 0, MALLOC_PAGESIZE); 2155 RBT_FOREACH(p, leaktree, &leakhead) { 2156 snprintf(buf, sizeof(buf), "%18p %7zu %6u %6zu\n", p->d.f, 2157 p->d.total_size, p->d.count, p->d.total_size / p->d.count); 2158 write(fd, buf, strlen(buf)); 2159 if (malloc_leaks == MAP_FAILED || 2160 i >= MALLOC_PAGESIZE / sizeof(struct malloc_leak)) 2161 continue; 2162 malloc_leaks[i].f = p->d.f; 2163 malloc_leaks[i].total_size = p->d.total_size; 2164 malloc_leaks[i].count = p->d.count; 2165 i++; 2166 } 2167 } 2168 2169 static void 2170 dump_chunk(int fd, struct chunk_info *p, void *f, int fromfreelist) 2171 { 2172 char buf[64]; 2173 2174 while (p != NULL) { 2175 snprintf(buf, sizeof(buf), "chunk %18p %18p %4d %d/%d\n", 2176 p->page, ((p->bits[0] & 1) ? NULL : f), 2177 p->size, p->free, p->total); 2178 write(fd, buf, strlen(buf)); 2179 if (!fromfreelist) { 2180 if (p->bits[0] & 1) 2181 putleakinfo(NULL, p->size, p->total - p->free); 2182 else { 2183 putleakinfo(f, p->size, 1); 2184 putleakinfo(NULL, p->size, 2185 p->total - p->free - 1); 2186 } 2187 break; 2188 } 2189 p = LIST_NEXT(p, entries); 2190 if (p != NULL) 2191 writestr(fd, " "); 2192 } 2193 } 2194 2195 static void 2196 dump_free_chunk_info(int fd, struct dir_info *d) 2197 { 2198 char buf[64]; 2199 int i, j, count; 2200 struct chunk_info *p; 2201 2202 writestr(fd, "Free chunk structs:\n"); 2203 for (i = 0; i <= MALLOC_MAXSHIFT; i++) { 2204 count = 0; 2205 LIST_FOREACH(p, &d->chunk_info_list[i], entries) 2206 count++; 2207 for (j = 0; j < MALLOC_CHUNK_LISTS; j++) { 2208 p = LIST_FIRST(&d->chunk_dir[i][j]); 2209 if (p == NULL && count == 0) 2210 continue; 2211 snprintf(buf, sizeof(buf), "%2d) %3d ", i, count); 2212 write(fd, buf, strlen(buf)); 2213 if (p != NULL) 2214 dump_chunk(fd, p, NULL, 1); 2215 else 2216 write(fd, "\n", 1); 2217 } 2218 } 2219 2220 } 2221 2222 static void 2223 dump_free_page_info(int fd, struct dir_info *d) 2224 { 2225 char buf[64]; 2226 int i; 2227 2228 snprintf(buf, sizeof(buf), "Free pages cached: %zu\n", 2229 d->free_regions_size); 2230 write(fd, buf, strlen(buf)); 2231 for (i = 0; i < mopts.malloc_cache; i++) { 2232 if (d->free_regions[i].p != NULL) { 2233 snprintf(buf, sizeof(buf), "%2d) ", i); 2234 write(fd, buf, strlen(buf)); 2235 snprintf(buf, sizeof(buf), "free at %p: %zu\n", 2236 d->free_regions[i].p, d->free_regions[i].size); 2237 write(fd, buf, strlen(buf)); 2238 } 2239 } 2240 } 2241 2242 static void 2243 malloc_dump1(int fd, int poolno, struct dir_info *d) 2244 { 2245 char buf[100]; 2246 size_t i, realsize; 2247 2248 snprintf(buf, sizeof(buf), "Malloc dir of %s pool %d at %p\n", __progname, poolno, d); 2249 write(fd, buf, strlen(buf)); 2250 if (d == NULL) 2251 return; 2252 snprintf(buf, sizeof(buf), "Region slots free %zu/%zu\n", 2253 d->regions_free, d->regions_total); 2254 write(fd, buf, strlen(buf)); 2255 snprintf(buf, sizeof(buf), "Finds %zu/%zu\n", d->finds, 2256 d->find_collisions); 2257 write(fd, buf, strlen(buf)); 2258 snprintf(buf, sizeof(buf), "Inserts %zu/%zu\n", d->inserts, 2259 d->insert_collisions); 2260 write(fd, buf, strlen(buf)); 2261 snprintf(buf, sizeof(buf), "Deletes %zu/%zu\n", d->deletes, 2262 d->delete_moves); 2263 write(fd, buf, strlen(buf)); 2264 snprintf(buf, sizeof(buf), "Cheap reallocs %zu/%zu\n", 2265 d->cheap_reallocs, d->cheap_realloc_tries); 2266 write(fd, buf, strlen(buf)); 2267 snprintf(buf, sizeof(buf), "In use %zu\n", d->malloc_used); 2268 write(fd, buf, strlen(buf)); 2269 snprintf(buf, sizeof(buf), "Guarded %zu\n", d->malloc_guarded); 2270 write(fd, buf, strlen(buf)); 2271 dump_free_chunk_info(fd, d); 2272 dump_free_page_info(fd, d); 2273 writestr(fd, 2274 "slot) hash d type page f size [free/n]\n"); 2275 for (i = 0; i < d->regions_total; i++) { 2276 if (d->r[i].p != NULL) { 2277 size_t h = hash(d->r[i].p) & 2278 (d->regions_total - 1); 2279 snprintf(buf, sizeof(buf), "%4zx) #%4zx %zd ", 2280 i, h, h - i); 2281 write(fd, buf, strlen(buf)); 2282 REALSIZE(realsize, &d->r[i]); 2283 if (realsize > MALLOC_MAXCHUNK) { 2284 putleakinfo(d->r[i].f, realsize, 1); 2285 snprintf(buf, sizeof(buf), 2286 "pages %18p %18p %zu\n", d->r[i].p, 2287 d->r[i].f, realsize); 2288 write(fd, buf, strlen(buf)); 2289 } else 2290 dump_chunk(fd, 2291 (struct chunk_info *)d->r[i].size, 2292 d->r[i].f, 0); 2293 } 2294 } 2295 dump_leaks(fd); 2296 write(fd, "\n", 1); 2297 } 2298 2299 void 2300 malloc_dump(int fd, int poolno, struct dir_info *pool) 2301 { 2302 int i; 2303 void *p; 2304 struct region_info *r; 2305 int saved_errno = errno; 2306 2307 if (pool == NULL) 2308 return; 2309 for (i = 0; i < MALLOC_DELAYED_CHUNK_MASK + 1; i++) { 2310 p = pool->delayed_chunks[i]; 2311 if (p == NULL) 2312 continue; 2313 r = find(pool, p); 2314 if (r == NULL) 2315 wrterror(pool, "bogus pointer in malloc_dump %p", p); 2316 free_bytes(pool, r, p); 2317 pool->delayed_chunks[i] = NULL; 2318 } 2319 /* XXX leak when run multiple times */ 2320 RBT_INIT(leaktree, &leakhead); 2321 malloc_dump1(fd, poolno, pool); 2322 errno = saved_errno; 2323 } 2324 DEF_WEAK(malloc_dump); 2325 2326 void 2327 malloc_gdump(int fd) 2328 { 2329 int i; 2330 int saved_errno = errno; 2331 2332 for (i = 0; i < _MALLOC_MUTEXES; i++) 2333 malloc_dump(fd, i, mopts.malloc_pool[i]); 2334 2335 errno = saved_errno; 2336 } 2337 DEF_WEAK(malloc_gdump); 2338 2339 static void 2340 malloc_exit(void) 2341 { 2342 static const char q[] = "malloc() warning: Couldn't dump stats\n"; 2343 int save_errno = errno, fd, i; 2344 char buf[100]; 2345 2346 fd = open("malloc.out", O_RDWR|O_APPEND); 2347 if (fd != -1) { 2348 snprintf(buf, sizeof(buf), "******** Start dump %s *******\n", 2349 __progname); 2350 write(fd, buf, strlen(buf)); 2351 snprintf(buf, sizeof(buf), 2352 "MT=%d I=%d F=%d U=%d J=%d R=%d X=%d C=%d cache=%u G=%zu\n", 2353 mopts.malloc_mt, mopts.internal_funcs, 2354 mopts.malloc_freenow, 2355 mopts.malloc_freeunmap, mopts.malloc_junk, 2356 mopts.malloc_realloc, mopts.malloc_xmalloc, 2357 mopts.chunk_canaries, mopts.malloc_cache, 2358 mopts.malloc_guard); 2359 write(fd, buf, strlen(buf)); 2360 2361 for (i = 0; i < _MALLOC_MUTEXES; i++) 2362 malloc_dump(fd, i, mopts.malloc_pool[i]); 2363 snprintf(buf, sizeof(buf), "******** End dump %s *******\n", 2364 __progname); 2365 write(fd, buf, strlen(buf)); 2366 close(fd); 2367 } else 2368 write(STDERR_FILENO, q, sizeof(q) - 1); 2369 errno = save_errno; 2370 } 2371 2372 #endif /* MALLOC_STATS */ 2373