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