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