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