malloc.c 24.9 KB
Newer Older
Z
zhuoli 已提交
1 2 3 4 5 6 7 8 9 10 11
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdint.h>
#include <errno.h>
#include <sys/mman.h>
#include "libc.h"
#include "atomic.h"
#include "pthread_impl.h"
#include "malloc_impl.h"
F
Far 已提交
12
#include "malloc_random.h"
13
#include <sys/prctl.h>
Z
zhuoli 已提交
14 15 16 17 18

#if defined(__GNUC__) && defined(__PIC__)
#define inline inline __attribute__((always_inline))
#endif

chuxuezhe1111's avatar
chuxuezhe1111 已提交
19 20 21 22 23
#ifdef HOOK_ENABLE
void *__libc_malloc(size_t);
void __libc_free(void *p);
#endif

Z
zhuoli 已提交
24 25 26 27
static struct {
	volatile uint64_t binmap;
	struct bin bins[64];
	volatile int free_lock[2];
28 29 30 31
#ifdef MALLOC_FREELIST_QUARANTINE
	struct bin quarantine[QUARANTINE_NUM];
	size_t quarantined_count[QUARANTINE_NUM];
	size_t quarantined_size[QUARANTINE_NUM];
32 33 34 35 36
#ifdef MALLOC_RED_ZONE
	char poison[64];
	volatile int poison_lock[2];
	int poison_count_down;
#endif
37
#endif
Z
zhuoli 已提交
38 39 40 41 42 43
} mal;

int __malloc_replaced;

/* Synchronization tools */

F
Far 已提交
44 45 46 47 48 49 50 51 52 53
static inline struct chunk *encode_chunk(struct chunk *ptr, void *key)
{
#ifndef MALLOC_FREELIST_HARDENED
	(void)key;
	return ptr;
#else
	return (struct chunk *)encode_ptr(ptr, key);
#endif
}

Z
zhuoli 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
static inline void lock(volatile int *lk)
{
	if (libc.threads_minus_1)
		while(a_swap(lk, 1)) __wait(lk, lk+1, 1, 1);
}

static inline void unlock(volatile int *lk)
{
	if (lk[0]) {
		a_store(lk, 0);
		if (lk[1]) __wake(lk, 1, 1);
	}
}

static inline void lock_bin(int i)
{
	lock(mal.bins[i].lock);
F
Far 已提交
71 72 73 74 75
	if (!mal.bins[i].head) {
#ifdef MALLOC_FREELIST_HARDENED
		mal.bins[i].key = next_key();
		mal.bins[i].head = mal.bins[i].tail = encode_chunk(BIN_TO_CHUNK(i), mal.bins[i].key);
#else
Z
zhuoli 已提交
76
		mal.bins[i].head = mal.bins[i].tail = BIN_TO_CHUNK(i);
F
Far 已提交
77 78
#endif
	}
Z
zhuoli 已提交
79 80 81 82 83 84 85
}

static inline void unlock_bin(int i)
{
	unlock(mal.bins[i].lock);
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#ifdef MALLOC_FREELIST_QUARANTINE
static inline void lock_quarantine(int i)
{
	lock(mal.quarantine[i].lock);
	if (!mal.quarantine[i].head) {
		mal.quarantine[i].key = next_key();
		mal.quarantine[i].head = mal.quarantine[i].tail = encode_chunk(QUARANTINE_TO_CHUNK(i), mal.quarantine[i].key);
	}
}

static inline void unlock_quarantine(int i)
{
	unlock(mal.quarantine[i].lock);
}
#endif

Z
zhuoli 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
static int first_set(uint64_t x)
{
#if 1
	return a_ctz_64(x);
#else
	static const char debruijn64[64] = {
		0, 1, 2, 53, 3, 7, 54, 27, 4, 38, 41, 8, 34, 55, 48, 28,
		62, 5, 39, 46, 44, 42, 22, 9, 24, 35, 59, 56, 49, 18, 29, 11,
		63, 52, 6, 26, 37, 40, 33, 47, 61, 45, 43, 21, 23, 58, 17, 10,
		51, 25, 36, 32, 60, 20, 57, 16, 50, 31, 19, 15, 30, 14, 13, 12
	};
	static const char debruijn32[32] = {
		0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13,
		31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14
	};
	if (sizeof(long) < 8) {
		uint32_t y = x;
		if (!y) {
			y = x>>32;
			return 32 + debruijn32[(y&-y)*0x076be629 >> 27];
		}
		return debruijn32[(y&-y)*0x076be629 >> 27];
	}
	return debruijn64[(x&-x)*0x022fdd63cc95386dull >> 58];
#endif
}

static const unsigned char bin_tab[60] = {
	            32,33,34,35,36,36,37,37,38,38,39,39,
	40,40,40,40,41,41,41,41,42,42,42,42,43,43,43,43,
	44,44,44,44,44,44,44,44,45,45,45,45,45,45,45,45,
	46,46,46,46,46,46,46,46,47,47,47,47,47,47,47,47,
};

static int bin_index(size_t x)
{
	x = x / SIZE_ALIGN - 1;
	if (x <= 32) return x;
	if (x < 512) return bin_tab[x/8-4];
	if (x > 0x1c00) return 63;
	return bin_tab[x/128-4] + 16;
}

static int bin_index_up(size_t x)
{
	x = x / SIZE_ALIGN - 1;
	if (x <= 32) return x;
	x--;
	if (x < 512) return bin_tab[x/8-4] + 1;
	return bin_tab[x/128-4] + 17;
}

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
#ifdef MALLOC_RED_ZONE
static inline size_t chunk_checksum_calculate(struct chunk *c)
{
	return (((size_t)c) ^ c->csize ^ c->usize ^ (c->state & M_STATE_MASK)) << M_CHECKSUM_SHIFT;
}

void chunk_checksum_set(struct chunk *c)
{
	c->state = (c->state & M_STATE_MASK) | chunk_checksum_calculate(c);
}

int chunk_checksum_check(struct chunk *c)
{
	return (c->state & ~M_STATE_MASK) ^ chunk_checksum_calculate(c);
}

static inline char get_poison(int i)
{
	char poison = 0;
	lock(mal.poison_lock);
	if (!mal.poison[i]) {
		mal.poison[i] = (char)(uintptr_t)next_key();
	}
	poison = mal.poison[i];
	unlock(mal.poison_lock);
	return poison;
}

static inline int need_poison(void)
{
	int ret = 0;
	lock(mal.poison_lock);
	if (mal.poison_count_down == 0) {
		/* Make sure the period is POISON_COUNT_DOWN_BASE */
		mal.poison_count_down = POISON_PERIOD - 1;
		ret = 1;
	} else {
		--mal.poison_count_down;
	}
	unlock(mal.poison_lock);
	return ret;
}

static inline void chunk_poison_set(struct chunk *c)
{
	char * start = ((char *)CHUNK_TO_MEM(c)) + c->usize;
	size_t size = CHUNK_SIZE(c) - OVERHEAD - c->usize;
	char val = get_poison(bin_index(CHUNK_SIZE(c)));
	memset(start, val, size);
	c->state |= M_RZ_POISON;
}

void chunk_poison_check(struct chunk *c)
{
	size_t csize = CHUNK_SIZE(c);
	char poison = get_poison(bin_index(csize));
	size_t padding_size = csize - OVERHEAD - c->usize;
	char *start = (char *)c + OVERHEAD + c->usize;
	for (size_t i = 0; i < padding_size; ++i) {
		/* Poison not right, crash */
		if (start[i] != poison) {
			a_crash();
		}
	}
}
#endif

Z
zhuoli 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
#if 0
void __dump_heap(int x)
{
	struct chunk *c;
	int i;
	for (c = (void *)mal.heap; CHUNK_SIZE(c); c = NEXT_CHUNK(c))
		fprintf(stderr, "base %p size %zu (%d) flags %d/%d\n",
			c, CHUNK_SIZE(c), bin_index(CHUNK_SIZE(c)),
			c->csize & 15,
			NEXT_CHUNK(c)->psize & 15);
	for (i=0; i<64; i++) {
		if (mal.bins[i].head != BIN_TO_CHUNK(i) && mal.bins[i].head) {
			fprintf(stderr, "bin %d: %p\n", i, mal.bins[i].head);
			if (!(mal.binmap & 1ULL<<i))
				fprintf(stderr, "missing from binmap!\n");
		} else if (mal.binmap & 1ULL<<i)
			fprintf(stderr, "binmap wrongly contains %d!\n", i);
	}
}
#endif

static struct chunk *expand_heap(size_t n)
{
	static int heap_lock[2];
	static void *end;
	void *p;
	struct chunk *w;

	/* The argument n already accounts for the caller's chunk
	 * overhead needs, but if the heap can't be extended in-place,
	 * we need room for an extra zero-sized sentinel chunk. */
	n += SIZE_ALIGN;

	lock(heap_lock);

	p = __expand_heap(&n);
	if (!p) {
		unlock(heap_lock);
		return 0;
	}

	/* If not just expanding existing space, we need to make a
	 * new sentinel chunk below the allocated space. */
	if (p != end) {
		/* Valid/safe because of the prologue increment. */
		n -= SIZE_ALIGN;
		p = (char *)p + SIZE_ALIGN;
		w = MEM_TO_CHUNK(p);
		w->psize = 0 | C_INUSE;
	}

	/* Record new heap end and fill in footer. */
	end = (char *)p + n;
	w = MEM_TO_CHUNK(end);
	w->psize = n | C_INUSE;
	w->csize = 0 | C_INUSE;

	/* Fill in header, which may be new or may be replacing a
	 * zero-size sentinel header at the old end-of-heap. */
	w = MEM_TO_CHUNK(p);
	w->csize = n | C_INUSE;
282 283 284 285 286
#ifdef MALLOC_RED_ZONE
	w->state = M_STATE_BRK;
	w->usize = POINTER_USAGE;
	chunk_checksum_set(w);
#endif
Z
zhuoli 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

	unlock(heap_lock);

	return w;
}

static int adjust_size(size_t *n)
{
	/* Result of pointer difference must fit in ptrdiff_t. */
	if (*n-1 > PTRDIFF_MAX - SIZE_ALIGN - PAGE_SIZE) {
		if (*n) {
			errno = ENOMEM;
			return -1;
		} else {
			*n = SIZE_ALIGN;
			return 0;
		}
	}
305 306 307 308 309 310 311
#ifdef MALLOC_RED_ZONE
	/*
	 * *n + OVERHEAD + SIZE_ALIGN + 1 - 1
	 * to make sure a least 1 byte for red zone
	 */
	*n = (*n + OVERHEAD + SIZE_ALIGN) & SIZE_MASK;
#else
Z
zhuoli 已提交
312
	*n = (*n + OVERHEAD + SIZE_ALIGN - 1) & SIZE_MASK;
313
#endif
Z
zhuoli 已提交
314 315 316 317 318
	return 0;
}

static void unbin(struct chunk *c, int i)
{
F
Far 已提交
319 320 321 322 323 324 325 326 327 328 329 330
#ifdef MALLOC_FREELIST_HARDENED
	void *key = mal.bins[i].key;
#else
	void *key = NULL;
#endif
	struct chunk *next = encode_chunk(c->next, key);
	struct chunk *prev = encode_chunk(c->prev, key);
	if (prev->next != encode_chunk(c, key) ||
		next->prev != encode_chunk(c, key)) {
		/* crash when the double-link list is corrupt */
		a_crash();
	}
Z
zhuoli 已提交
331 332
	if (c->prev == c->next)
		a_and_64(&mal.binmap, ~(1ULL<<i));
F
Far 已提交
333 334
	prev->next = c->next;
	next->prev = c->prev;
Z
zhuoli 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	c->csize |= C_INUSE;
	NEXT_CHUNK(c)->psize |= C_INUSE;
}

static int alloc_fwd(struct chunk *c)
{
	int i;
	size_t k;
	while (!((k=c->csize) & C_INUSE)) {
		i = bin_index(k);
		lock_bin(i);
		if (c->csize == k) {
			unbin(c, i);
			unlock_bin(i);
			return 1;
		}
		unlock_bin(i);
	}
	return 0;
}

static int alloc_rev(struct chunk *c)
{
	int i;
	size_t k;
	while (!((k=c->psize) & C_INUSE)) {
		i = bin_index(k);
		lock_bin(i);
		if (c->psize == k) {
			unbin(PREV_CHUNK(c), i);
			unlock_bin(i);
			return 1;
		}
		unlock_bin(i);
	}
	return 0;
}


/* pretrim - trims a chunk _prior_ to removing it from its bin.
 * Must be called with i as the ideal bin for size n, j the bin
 * for the _free_ chunk self, and bin j locked. */
static int pretrim(struct chunk *self, size_t n, int i, int j)
{
	size_t n1;
	struct chunk *next, *split;

	/* We cannot pretrim if it would require re-binning. */
	if (j < 40) return 0;
	if (j < i+3) {
		if (j != 63) return 0;
		n1 = CHUNK_SIZE(self);
		if (n1-n <= MMAP_THRESHOLD) return 0;
	} else {
		n1 = CHUNK_SIZE(self);
	}
	if (bin_index(n1-n) != j) return 0;

	next = NEXT_CHUNK(self);
	split = (void *)((char *)self + n);

F
Far 已提交
396 397 398 399 400 401 402
#ifdef MALLOC_FREELIST_HARDENED
	void *key = mal.bins[j].key;
#else
	void *key = NULL;
#endif
	struct chunk *realprev = encode_chunk(self->prev, key);
	struct chunk *realnext = encode_chunk(self->next, key);
Z
zhuoli 已提交
403 404
	split->prev = self->prev;
	split->next = self->next;
F
Far 已提交
405 406
	realprev->next = encode_chunk(split, key);
	realnext->prev = encode_chunk(split, key);
Z
zhuoli 已提交
407 408 409 410
	split->psize = n | C_INUSE;
	split->csize = n1-n;
	next->psize = n1-n;
	self->csize = n | C_INUSE;
411 412 413 414 415 416 417
#ifdef MALLOC_RED_ZONE
	/* split poison state keep up to self for less poison operations */
	self->state &= ~M_RZ_POISON;
	split->state = M_STATE_BRK;
	split->usize = POINTER_USAGE;
	chunk_checksum_set(split);
#endif
Z
zhuoli 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	return 1;
}

static void trim(struct chunk *self, size_t n)
{
	size_t n1 = CHUNK_SIZE(self);
	struct chunk *next, *split;

	if (n >= n1 - DONTCARE) return;

	next = NEXT_CHUNK(self);
	split = (void *)((char *)self + n);

	split->psize = n | C_INUSE;
	split->csize = n1-n | C_INUSE;
	next->psize = n1-n | C_INUSE;
	self->csize = n | C_INUSE;
435 436 437 438 439 440
#ifdef MALLOC_RED_ZONE
	/* Remove the poison tag, because of triming chunk */
	split->state = M_STATE_BRK;
	split->usize = POINTER_USAGE;
	chunk_checksum_set(split);
#endif
Z
zhuoli 已提交
441 442 443 444

	__bin_chunk(split);
}

chuxuezhe1111's avatar
chuxuezhe1111 已提交
445 446 447
#ifdef HOOK_ENABLE
void *__libc_malloc(size_t n)
#else
Z
zhuoli 已提交
448
void *malloc(size_t n)
chuxuezhe1111's avatar
chuxuezhe1111 已提交
449
#endif
450 451 452 453 454
{
	return internal_malloc(n);
}

void *internal_malloc(size_t n)
Z
zhuoli 已提交
455 456 457
{
	struct chunk *c;
	int i, j;
458 459 460 461
#ifdef MALLOC_RED_ZONE
	size_t user_size = n;
	char poison;
#endif
Z
zhuoli 已提交
462 463 464 465 466 467 468 469

	if (adjust_size(&n) < 0) return 0;

	if (n > MMAP_THRESHOLD) {
		size_t len = n + OVERHEAD + PAGE_SIZE - 1 & -PAGE_SIZE;
		char *base = __mmap(0, len, PROT_READ|PROT_WRITE,
			MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
		if (base == (void *)-1) return 0;
470

471
		prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, base, len, "native_heap:musl");
472

Z
zhuoli 已提交
473 474 475
		c = (void *)(base + SIZE_ALIGN - OVERHEAD);
		c->csize = len - (SIZE_ALIGN - OVERHEAD);
		c->psize = SIZE_ALIGN - OVERHEAD;
476 477 478 479 480 481 482 483
#ifdef MALLOC_RED_ZONE
		c->state = M_STATE_MMAP | M_STATE_USED;
		c->usize = user_size;
		if (need_poison()) {
			chunk_poison_set(c);
		}
		chunk_checksum_set(c);
#endif
Z
zhuoli 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
		return CHUNK_TO_MEM(c);
	}

	i = bin_index_up(n);
	for (;;) {
		uint64_t mask = mal.binmap & -(1ULL<<i);
		if (!mask) {
			c = expand_heap(n);
			if (!c) return 0;
			if (alloc_rev(c)) {
				struct chunk *x = c;
				c = PREV_CHUNK(c);
				NEXT_CHUNK(x)->psize = c->csize =
					x->csize + CHUNK_SIZE(c);
			}
			break;
		}
		j = first_set(mask);
		lock_bin(j);
F
Far 已提交
503 504 505 506 507 508
#ifdef MALLOC_FREELIST_HARDENED
		void *key = mal.bins[j].key;
#else
		void *key = NULL;
#endif
		c = encode_chunk(mal.bins[j].head, key); /* Decode the head pointer */
Z
zhuoli 已提交
509
		if (c != BIN_TO_CHUNK(j)) {
510 511 512 513 514
#ifdef MALLOC_RED_ZONE
			if (c->state & M_RZ_POISON) {
				chunk_poison_check(c);
			}
#endif
Z
zhuoli 已提交
515 516 517 518 519 520 521 522 523 524
			if (!pretrim(c, n, i, j)) unbin(c, j);
			unlock_bin(j);
			break;
		}
		unlock_bin(j);
	}

	/* Now patch up in case we over-allocated */
	trim(c, n);

525 526 527 528 529 530 531 532 533 534
#ifdef MALLOC_RED_ZONE
	c->usize = user_size;
	c->state |= M_STATE_USED;
	if (need_poison()) {
		chunk_poison_set(c);
	} else {
		c->state &= ~M_RZ_POISON;
	}
	chunk_checksum_set(c);
#endif
Z
zhuoli 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
	return CHUNK_TO_MEM(c);
}

static size_t mal0_clear(char *p, size_t pagesz, size_t n)
{
#ifdef __GNUC__
	typedef uint64_t __attribute__((__may_alias__)) T;
#else
	typedef unsigned char T;
#endif
	char *pp = p + n;
	size_t i = (uintptr_t)pp & (pagesz - 1);
	for (;;) {
		pp = memset(pp - i, 0, i);
		if (pp - p < pagesz) return pp - p;
		for (i = pagesz; i; i -= 2*sizeof(T), pp -= 2*sizeof(T))
		        if (((T *)pp)[-1] | ((T *)pp)[-2])
				break;
	}
}

void *calloc(size_t m, size_t n)
557
{
L
leixin 已提交
558 559 560 561 562 563 564 565
	if(n && m > (size_t)-1/n){
		errno=ENOMEM;
		return 0;
	}
	n *= m;
	void *p=malloc(n);
	if(!p) return p;
	if(!__malloc_replaced) {
566
		if(IS_MMAPPED(MEM_TO_CHUNK(p)))
L
leixin 已提交
567 568 569 570 571
			return p;
		if(n >= PAGE_SIZE)
			n = mal0_clear(p, PAGE_SIZE, n);
	}
	return memset(p, 0, n);
572 573 574
}

void *internal_calloc(size_t m, size_t n)
Z
zhuoli 已提交
575 576 577 578 579 580
{
	if (n && m > (size_t)-1/n) {
		errno = ENOMEM;
		return 0;
	}
	n *= m;
581
	void *p = internal_malloc(n);
Z
zhuoli 已提交
582 583 584 585 586 587 588 589 590 591 592
	if (!p) return p;
	if (!__malloc_replaced) {
		if (IS_MMAPPED(MEM_TO_CHUNK(p)))
			return p;
		if (n >= PAGE_SIZE)
			n = mal0_clear(p, PAGE_SIZE, n);
	}
	return memset(p, 0, n);
}

void *realloc(void *p, size_t n)
593
{
L
leixin 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
	struct chunk *self, *next;
	size_t n0, n1;
	void *new;
#ifdef MALLOC_RED_ZONE
	size_t user_size = n;
#endif

	if (!p) return malloc(n);
	if (!n) {
		free(p);
		return NULL;
	}

	if (adjust_size(&n) < 0) return 0;

	self = MEM_TO_CHUNK(p);
	n1 = n0 = CHUNK_SIZE(self);
#ifdef MALLOC_RED_ZONE
	/* Not a valid chunk */
	if (!(self->state & M_STATE_USED)) a_crash();
	if (chunk_checksum_check(self)) a_crash();
	if (self->state & M_RZ_POISON) chunk_poison_check(self);
#endif

	if (IS_MMAPPED(self)) {
		size_t extra = self->psize;
		char *base = (char *)self - extra;
		size_t oldlen = n0 + extra;
		size_t newlen = n + extra;
		/* Crash on realloc of freed chunk */
#ifdef MALLOC_RED_ZONE
		/* Wrong malloc type */
		if (!(self->state & M_STATE_MMAP)) a_crash();
#endif
		if (extra & 1) a_crash();
		if (newlen < PAGE_SIZE && (new = malloc(n-OVERHEAD))) {
			n0 = n;
			goto copy_free_ret;
		}
		newlen = (newlen + PAGE_SIZE-1) & -PAGE_SIZE;
		if (oldlen == newlen) return p;
		base = __mremap(base, oldlen, newlen, MREMAP_MAYMOVE);
		if (base == (void *)-1)
			goto copy_realloc;
		self = (void *)(base + extra);
		self->csize = newlen - extra;
#ifdef MALLOC_RED_ZONE
		self->usize = user_size;
		if (need_poison()) {
			chunk_poison_set(self);
		} else {
			self->state &= ~M_RZ_POISON;
		}
		chunk_checksum_set(self);
#endif
		return CHUNK_TO_MEM(self);
	}

	next = NEXT_CHUNK(self);

	/* Crash on corrupted footer (likely from buffer overflow) */
	if (next->psize != self->csize) a_crash();

	/* Merge adjacent chunks if we need more space. This is not
	 * a waste of time even if we fail to get enough space, because our
	 * subsequent call to free would otherwise have to do the merge. */
	if (n > n1 && alloc_fwd(next)) {
		n1 += CHUNK_SIZE(next);
		next = NEXT_CHUNK(next);
#ifdef MALLOC_RED_ZONE
		/* alloc forward arises, remove the poison tag */
		self->state &= ~M_RZ_POISON;
#endif
	}
	/* FIXME: find what's wrong here and reenable it..? */
	if (0 && n > n1 && alloc_rev(self)) {
		self = PREV_CHUNK(self);
		n1 += CHUNK_SIZE(self);
	}
	self->csize = n1 | C_INUSE;
	next->psize = n1 | C_INUSE;

	/* If we got enough space, split off the excess and return */
	if (n <= n1) {
		//memmove(CHUNK_TO_MEM(self), p, n0-OVERHEAD);
		trim(self, n);
#ifdef MALLOC_RED_ZONE
		self->usize = user_size;
		if (need_poison()) {
			chunk_poison_set(self);
		} else {
			self->state &= ~M_RZ_POISON;
		}
		chunk_checksum_set(self);
#endif
		return CHUNK_TO_MEM(self);
	}

copy_realloc:
	/* As a last resort, allocate a new chunk and copy to it. */
	new = malloc(n-OVERHEAD);
	if (!new) return 0;
copy_free_ret:
#ifndef MALLOC_RED_ZONE
	memcpy(new, p, n0-OVERHEAD);
#else
	memcpy(new, p, self->usize < user_size ? self->usize : user_size);
	chunk_checksum_set(self);
#endif
	free(CHUNK_TO_MEM(self));
	return new;
705 706 707
}

void *internal_realloc(void *p, size_t n)
Z
zhuoli 已提交
708 709 710 711
{
	struct chunk *self, *next;
	size_t n0, n1;
	void *new;
712 713 714
#ifdef MALLOC_RED_ZONE
	size_t user_size = n;
#endif
Z
zhuoli 已提交
715

716
	if (!p) return internal_malloc(n);
Z
zhuoli 已提交
717
	if (!n) {
718
		internal_free(p);
Z
zhuoli 已提交
719 720 721 722 723 724 725
		return NULL;
	}

	if (adjust_size(&n) < 0) return 0;

	self = MEM_TO_CHUNK(p);
	n1 = n0 = CHUNK_SIZE(self);
726 727 728 729 730 731
#ifdef MALLOC_RED_ZONE
	/* Not a valid chunk */
	if (!(self->state & M_STATE_USED)) a_crash();
	if (chunk_checksum_check(self)) a_crash();
	if (self->state & M_RZ_POISON) chunk_poison_check(self);
#endif
Z
zhuoli 已提交
732 733 734 735 736 737 738

	if (IS_MMAPPED(self)) {
		size_t extra = self->psize;
		char *base = (char *)self - extra;
		size_t oldlen = n0 + extra;
		size_t newlen = n + extra;
		/* Crash on realloc of freed chunk */
739 740 741 742
#ifdef MALLOC_RED_ZONE
		/* Wrong malloc type */
		if (!(self->state & M_STATE_MMAP)) a_crash();
#endif
Z
zhuoli 已提交
743
		if (extra & 1) a_crash();
744
		if (newlen < PAGE_SIZE && (new = internal_malloc(n-OVERHEAD))) {
Z
zhuoli 已提交
745 746 747 748 749 750 751 752 753 754
			n0 = n;
			goto copy_free_ret;
		}
		newlen = (newlen + PAGE_SIZE-1) & -PAGE_SIZE;
		if (oldlen == newlen) return p;
		base = __mremap(base, oldlen, newlen, MREMAP_MAYMOVE);
		if (base == (void *)-1)
			goto copy_realloc;
		self = (void *)(base + extra);
		self->csize = newlen - extra;
755 756 757 758 759 760 761 762 763
#ifdef MALLOC_RED_ZONE
		self->usize = user_size;
		if (need_poison()) {
			chunk_poison_set(self);
		} else {
			self->state &= ~M_RZ_POISON;
		}
		chunk_checksum_set(self);
#endif
Z
zhuoli 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777
		return CHUNK_TO_MEM(self);
	}

	next = NEXT_CHUNK(self);

	/* Crash on corrupted footer (likely from buffer overflow) */
	if (next->psize != self->csize) a_crash();

	/* Merge adjacent chunks if we need more space. This is not
	 * a waste of time even if we fail to get enough space, because our
	 * subsequent call to free would otherwise have to do the merge. */
	if (n > n1 && alloc_fwd(next)) {
		n1 += CHUNK_SIZE(next);
		next = NEXT_CHUNK(next);
778 779 780 781
#ifdef MALLOC_RED_ZONE
		/* alloc forward arises, remove the poison tag */
		self->state &= ~M_RZ_POISON;
#endif
Z
zhuoli 已提交
782 783 784 785 786 787 788 789 790 791 792 793 794
	}
	/* FIXME: find what's wrong here and reenable it..? */
	if (0 && n > n1 && alloc_rev(self)) {
		self = PREV_CHUNK(self);
		n1 += CHUNK_SIZE(self);
	}
	self->csize = n1 | C_INUSE;
	next->psize = n1 | C_INUSE;

	/* If we got enough space, split off the excess and return */
	if (n <= n1) {
		//memmove(CHUNK_TO_MEM(self), p, n0-OVERHEAD);
		trim(self, n);
795 796 797 798 799 800 801 802 803
#ifdef MALLOC_RED_ZONE
		self->usize = user_size;
		if (need_poison()) {
			chunk_poison_set(self);
		} else {
			self->state &= ~M_RZ_POISON;
		}
		chunk_checksum_set(self);
#endif
Z
zhuoli 已提交
804 805 806 807 808
		return CHUNK_TO_MEM(self);
	}

copy_realloc:
	/* As a last resort, allocate a new chunk and copy to it. */
809
	new = internal_malloc(n-OVERHEAD);
Z
zhuoli 已提交
810 811
	if (!new) return 0;
copy_free_ret:
812
#ifndef MALLOC_RED_ZONE
Z
zhuoli 已提交
813
	memcpy(new, p, n0-OVERHEAD);
814 815 816 817
#else
	memcpy(new, p, self->usize < user_size ? self->usize : user_size);
	chunk_checksum_set(self);
#endif
818
	internal_free(CHUNK_TO_MEM(self));
Z
zhuoli 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
	return new;
}

void __bin_chunk(struct chunk *self)
{
	struct chunk *next = NEXT_CHUNK(self);
	size_t final_size, new_size, size;
	int reclaim=0;
	int i;

	final_size = new_size = CHUNK_SIZE(self);

	/* Crash on corrupted footer (likely from buffer overflow) */
	if (next->psize != self->csize) a_crash();

	for (;;) {
		if (self->psize & next->csize & C_INUSE) {
			self->csize = final_size | C_INUSE;
			next->psize = final_size | C_INUSE;
			i = bin_index(final_size);
			lock_bin(i);
			lock(mal.free_lock);
			if (self->psize & next->csize & C_INUSE)
				break;
			unlock(mal.free_lock);
			unlock_bin(i);
		}

		if (alloc_rev(self)) {
			self = PREV_CHUNK(self);
			size = CHUNK_SIZE(self);
			final_size += size;
			if (new_size+size > RECLAIM && (new_size+size^size) > size)
				reclaim = 1;
		}

		if (alloc_fwd(next)) {
			size = CHUNK_SIZE(next);
			final_size += size;
			if (new_size+size > RECLAIM && (new_size+size^size) > size)
				reclaim = 1;
			next = NEXT_CHUNK(next);
		}
862 863 864 865
#ifdef MALLOC_RED_ZONE
		/* if poisoned chunk is combined, we should remove the poisoned tag */
		self->state &= ~M_RZ_POISON;
#endif
Z
zhuoli 已提交
866 867 868 869 870 871 872 873 874
	}

	if (!(mal.binmap & 1ULL<<i))
		a_or_64(&mal.binmap, 1ULL<<i);

	self->csize = final_size;
	next->psize = final_size;
	unlock(mal.free_lock);

F
Far 已提交
875 876 877 878 879 880
#ifdef MALLOC_FREELIST_HARDENED
	void *key = mal.bins[i].key;
#else
	void *key = NULL;
#endif
	self->next = encode_chunk(BIN_TO_CHUNK(i), key);
Z
zhuoli 已提交
881
	self->prev = mal.bins[i].tail;
F
Far 已提交
882 883 884
	struct chunk *xorptr = encode_ptr(self, key);
	encode_chunk(mal.bins[i].tail, key)->next = xorptr;
	mal.bins[i].tail = xorptr;
Z
zhuoli 已提交
885 886 887 888 889 890 891 892 893 894

	/* Replace middle of large chunks with fresh zero pages */
	if (reclaim) {
		uintptr_t a = (uintptr_t)self + SIZE_ALIGN+PAGE_SIZE-1 & -PAGE_SIZE;
		uintptr_t b = (uintptr_t)next - SIZE_ALIGN & -PAGE_SIZE;
#if 1
		__madvise((void *)a, b-a, MADV_DONTNEED);
#else
		__mmap((void *)a, b-a, PROT_READ|PROT_WRITE,
			MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
895 896 897
#endif
#ifdef MALLOC_RED_ZONE
		self->state &= ~M_RZ_POISON;
Z
zhuoli 已提交
898 899 900
#endif
	}

901 902 903
#ifdef MALLOC_RED_ZONE
	chunk_checksum_set(self);
#endif
Z
zhuoli 已提交
904 905 906 907 908 909 910 911
	unlock_bin(i);
}

static void unmap_chunk(struct chunk *self)
{
	size_t extra = self->psize;
	char *base = (char *)self - extra;
	size_t len = CHUNK_SIZE(self) + extra;
912 913 914 915
#ifdef MALLOC_RED_ZONE
	/* Wrong chunk type */
	if (!(self->state & M_STATE_MMAP)) a_crash();
#endif
Z
zhuoli 已提交
916 917 918 919 920
	/* Crash on double free */
	if (extra & 1) a_crash();
	__munmap(base, len);
}

921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
#ifdef MALLOC_FREELIST_QUARANTINE
static inline int quarantine_index(size_t size)
{
	return (size / SIZE_ALIGN) & (QUARANTINE_NUM - 1);
}

static void quarantine_contained(struct chunk *self)
{
	size_t size = CHUNK_SIZE(self);
	int i = quarantine_index(size);
	struct chunk *cur;
	struct chunk *next;
	struct chunk *prev;
	void *key;

936 937 938 939 940
#ifdef MALLOC_RED_ZONE
	/* Wrong chunk type */
	if (!(self->state & M_STATE_BRK)) a_crash();
#endif

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
	lock_quarantine(i);
	key = mal.quarantine[i].key;
	cur = encode_chunk(mal.quarantine[i].head, key);
	prev = QUARANTINE_TO_CHUNK(i);
	while (cur != QUARANTINE_TO_CHUNK(i)) {
		/* "Safe-unlink" check */
		next = encode_chunk(cur->next, key);
		if (prev->next != encode_chunk(cur, key) ||
			next->prev != encode_chunk(cur, key))
		a_crash();
		/* Find that "self" is in the freelist, crash */
		if (cur == self) a_crash();
		prev = cur;
		cur = next;
	}
	unlock_quarantine(i);
}

static void quarantine_bin(struct chunk *self)
{
	size_t size = CHUNK_SIZE(self);
	struct chunk *cur;
	struct chunk *next;
	void *key;
	int i;

967 968 969
#ifdef MALLOC_RED_ZONE
	self->state &= ~M_STATE_USED;
#endif
970 971
	/* Avoid quarantining large memory */
	if (size > QUARANTINE_THRESHOLD) {
972 973 974 975 976 977 978 979 980 981 982
#ifdef MALLOC_RED_ZONE
		self->usize = POINTER_USAGE;
		if ((self->psize & self->csize & NEXT_CHUNK(self)->csize & C_INUSE) &&
			need_poison()) {
			/* Self will not be combined mostly */
			chunk_poison_set(self);
		} else {
			self->state &= ~M_RZ_POISON;
		}
		chunk_checksum_set(self);
#endif
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
		__bin_chunk(self);
		return;
	}

	i = quarantine_index(size);
	lock_quarantine(i);
	key = mal.quarantine[i].key;
	if (mal.quarantined_size[i] > QUARANTINE_THRESHOLD || mal.quarantined_count[i] > QUARANTINE_N_THRESHOLD) {
		/* cherry-pick an independent list from quarantine */
		cur = encode_chunk(mal.quarantine[i].head, key);
		/* now clear the quarantine[i] */
		mal.quarantine[i].head = mal.quarantine[i].tail = encode_chunk(QUARANTINE_TO_CHUNK(i), key);
		mal.quarantined_size[i] = mal.quarantined_count[i] = 0;
		unlock_quarantine(i);

		/* Bin the quarantined chunk */
		do {
			next = encode_chunk(cur->next, key);
1001 1002 1003
#ifdef MALLOC_RED_ZONE
			if (cur->state & M_RZ_POISON) chunk_poison_check(cur);
#endif
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
			__bin_chunk(cur);
			cur = next;
		} while (cur != QUARANTINE_TO_CHUNK(i));
	} else {
		unlock_quarantine(i);
	}

	lock_quarantine(i);
	self->next = encode_chunk(QUARANTINE_TO_CHUNK(i), key);
	self->prev = mal.quarantine[i].tail;
	encode_chunk(mal.quarantine[i].tail, key)->next = encode_chunk(self, key);
	mal.quarantine[i].tail = encode_chunk(self, key);

	mal.quarantined_size[i] += size;
	mal.quarantined_count[i] += 1;
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

#ifdef MALLOC_RED_ZONE
	if (need_poison()) {
		self->usize = POINTER_USAGE;
		chunk_poison_set(self);
	} else {
		self->state &= ~M_RZ_POISON;
	}
	chunk_checksum_set(self);
#endif
1029 1030 1031 1032
	unlock_quarantine(i);
}
#endif

chuxuezhe1111's avatar
chuxuezhe1111 已提交
1033 1034 1035
#ifdef HOOK_ENABLE
void __libc_free(void *p)
#else
Z
zhuoli 已提交
1036
void free(void *p)
chuxuezhe1111's avatar
chuxuezhe1111 已提交
1037
#endif
1038 1039 1040 1041 1042
{
	return internal_free(p);
}

void internal_free(void *p)
Z
zhuoli 已提交
1043 1044 1045 1046 1047
{
	if (!p) return;

	struct chunk *self = MEM_TO_CHUNK(p);

1048 1049 1050 1051 1052 1053
#ifdef MALLOC_RED_ZONE
	/* This is not a valid chunk for freeing */
	if (chunk_checksum_check(self)) a_crash();
	if (!(self->state & M_STATE_USED)) a_crash();
	if (self->state & M_RZ_POISON) chunk_poison_check(self);
#endif
Z
zhuoli 已提交
1054 1055
	if (IS_MMAPPED(self))
		unmap_chunk(self);
1056 1057 1058 1059 1060
	else {
#ifdef MALLOC_FREELIST_QUARANTINE
		quarantine_contained(self);
		quarantine_bin(self);
#else
Z
zhuoli 已提交
1061
		__bin_chunk(self);
1062 1063
#endif
	}
Z
zhuoli 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
}

void __malloc_donate(char *start, char *end)
{
	size_t align_start_up = (SIZE_ALIGN-1) & (-(uintptr_t)start - OVERHEAD);
	size_t align_end_down = (SIZE_ALIGN-1) & (uintptr_t)end;

	/* Getting past this condition ensures that the padding for alignment
	 * and header overhead will not overflow and will leave a nonzero
	 * multiple of SIZE_ALIGN bytes between start and end. */
	if (end - start <= OVERHEAD + align_start_up + align_end_down)
		return;
	start += align_start_up + OVERHEAD;
	end   -= align_end_down;

	struct chunk *c = MEM_TO_CHUNK(start), *n = MEM_TO_CHUNK(end);
	c->psize = n->csize = C_INUSE;
	c->csize = n->psize = C_INUSE | (end-start);
1082 1083 1084 1085 1086
#ifdef MALLOC_RED_ZONE
	c->usize = POINTER_USAGE;
	c->state = M_STATE_BRK;
	chunk_checksum_set(c);
#endif
Z
zhuoli 已提交
1087 1088
	__bin_chunk(c);
}