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