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