2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
9 * $FreeBSD: src/lib/libc/stdlib/malloc.c,v 1.49.2.4 2001/12/29 08:10:14 knu Exp $
14 * Defining EXTRA_SANITY will enable extra checks which are related
15 * to internal conditions and consistency in malloc.c. This has a
16 * noticeable runtime performance hit, and generally will not do you
17 * any good unless you fiddle with the internals of malloc or want
18 * to catch random pointer corruption as early as possible.
20 #ifndef MALLOC_EXTRA_SANITY
21 #undef MALLOC_EXTRA_SANITY
25 * What to use for Junk. This is the byte value we use to fill with
26 * when the 'J' option is enabled.
28 #define SOME_JUNK 0xd0 /* as in "Duh" :-) */
31 * The basic parameters you can tweak.
33 * malloc_pageshift pagesize = 1 << malloc_pageshift
34 * It's probably best if this is the native
35 * page size, but it doesn't have to be.
37 * malloc_minsize minimum size of an allocation in bytes.
38 * If this is too small it's too much work
39 * to manage them. This is also the smallest
40 * unit of alignment used for the storage
41 * returned by malloc/realloc.
45 #if defined(__FreeBSD__)
46 # if defined(__i386__)
47 # define malloc_pageshift 12U
48 # define malloc_minsize 16U
50 # if defined(__alpha__)
51 # define malloc_pageshift 13U
52 # define malloc_minsize 16U
54 # if !defined(__NETBSD_SYSCALLS)
58 * Make malloc/free/realloc thread-safe in libc for use with
61 # include "libc_private.h"
62 # include "spinlock.h"
63 static spinlock_t thread_lock = _SPINLOCK_INITIALIZER;
64 # define THREAD_LOCK() if (__isthreaded) _SPINLOCK(&thread_lock);
65 # define THREAD_UNLOCK() if (__isthreaded) _SPINUNLOCK(&thread_lock);
66 #endif /* __FreeBSD__ */
68 #if defined(__sparc__) && defined(sun)
69 # define malloc_pageshift 12U
70 # define malloc_minsize 16U
73 # define MMAP_FD fdzero
74 # define INIT_MMAP() \
75 { if ((fdzero = _open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
76 wrterror("open of /dev/zero"); }
77 # define MADV_FREE MADV_DONTNEED
78 #endif /* __sparc__ */
80 /* Insert your combination here... */
81 #if defined(__FOOCPU__) && defined(__BAROS__)
82 # define malloc_pageshift 12U
83 # define malloc_minsize 16U
84 #endif /* __FOOCPU__ && __BAROS__ */
88 * No user serviceable parts behind this point.
90 #include <sys/types.h>
102 * This structure describes a page worth of chunks.
106 struct pginfo *next; /* next on the free list */
107 void *page; /* Pointer to the page */
108 u_short size; /* size of this page's chunks */
109 u_short shift; /* How far to shift for this size chunks */
110 u_short free; /* How many free chunks */
111 u_short total; /* How many chunk */
112 u_int bits[1]; /* Which chunks are free */
116 * This structure describes a number of free pages.
120 struct pgfree *next; /* next run of free pages */
121 struct pgfree *prev; /* prev run of free pages */
122 void *page; /* pointer to free pages */
123 void *end; /* pointer to end of free pages */
124 size_t size; /* number of bytes free */
128 * How many bits per u_int in the bitmap.
129 * Change only if not 8 bits/byte
131 #define MALLOC_BITS (8*sizeof(u_int))
134 * Magic values to put in the page_directory
136 #define MALLOC_NOT_MINE ((struct pginfo*) 0)
137 #define MALLOC_FREE ((struct pginfo*) 1)
138 #define MALLOC_FIRST ((struct pginfo*) 2)
139 #define MALLOC_FOLLOW ((struct pginfo*) 3)
140 #define MALLOC_MAGIC ((struct pginfo*) 4)
142 #ifndef malloc_pageshift
143 #define malloc_pageshift 12U
146 #ifndef malloc_minsize
147 #define malloc_minsize 16U
150 #if !defined(malloc_pagesize)
151 #define malloc_pagesize (1UL<<malloc_pageshift)
154 #if ((1<<malloc_pageshift) != malloc_pagesize)
155 #error "(1<<malloc_pageshift) != malloc_pagesize"
158 #ifndef malloc_maxsize
159 #define malloc_maxsize ((malloc_pagesize)>>1)
162 /* A mask for the offset inside a page. */
163 #define malloc_pagemask ((malloc_pagesize)-1)
165 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
166 #define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)
169 #define THREAD_LOCK()
172 #ifndef THREAD_UNLOCK
173 #define THREAD_UNLOCK()
184 /* Set when initialization has been done */
185 static unsigned malloc_started;
187 /* Recusion flag for public interface. */
188 static int malloc_active;
190 /* Number of free pages we cache */
191 static unsigned malloc_cache = 16;
193 /* The offset from pagenumber to index into the page directory */
194 static u_long malloc_origo;
196 /* The last index in the page directory we care about */
197 static u_long last_index;
199 /* Pointer to page directory. Allocated "as if with" malloc */
200 static struct pginfo **page_dir;
202 /* How many slots in the page directory */
203 static unsigned malloc_ninfo;
205 /* Free pages line up here */
206 static struct pgfree free_list;
208 /* Abort(), user doesn't handle problems. */
209 static int malloc_abort;
211 /* Are we trying to die ? */
214 /* always realloc ? */
215 static int malloc_realloc;
217 /* pass the kernel a hint on free pages ? */
218 static int malloc_hint = 0;
220 /* xmalloc behaviour ? */
221 static int malloc_xmalloc;
223 /* sysv behaviour for malloc(0) ? */
224 static int malloc_sysv;
227 static int malloc_zero;
230 static int malloc_junk;
235 static int malloc_utrace;
237 struct ut { void *p; size_t s; void *r; };
239 void utrace __P((struct ut *, int));
241 #define UTRACE(a, b, c) \
243 {struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}
244 #else /* !HAS_UTRACE */
245 #define UTRACE(a,b,c)
246 #endif /* HAS_UTRACE */
249 static void *malloc_brk;
251 /* one location cache for free-list holders */
252 static struct pgfree *px;
254 /* compile-time options */
255 char *malloc_options;
257 /* Name of the current public function */
258 static char *malloc_func;
262 mmap(0, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
266 * Necessary function declarations
268 static int extend_pgdir(u_long index);
269 static void *imalloc(size_t size);
270 static void ifree(void *ptr);
271 static void *irealloc(void *ptr, size_t size);
273 extern char *__progname;
278 char *q = " error: ";
279 _write(STDERR_FILENO, __progname, strlen(__progname));
280 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
281 _write(STDERR_FILENO, q, strlen(q));
282 _write(STDERR_FILENO, p, strlen(p));
290 char *q = " warning: ";
293 _write(STDERR_FILENO, __progname, strlen(__progname));
294 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
295 _write(STDERR_FILENO, q, strlen(q));
296 _write(STDERR_FILENO, p, strlen(p));
300 * Allocate a number of pages from the OS
303 map_pages(size_t pages)
305 caddr_t result, tail;
307 result = (caddr_t)pageround((u_long)sbrk(0));
308 tail = result + (pages << malloc_pageshift);
312 wrterror("(ES): map_pages fails\n");
313 #endif /* EXTRA_SANITY */
317 last_index = ptr2index(tail) - 1;
320 if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index))
327 * Extend page directory
330 extend_pgdir(u_long index)
332 struct pginfo **new, **old;
335 /* Make it this many pages */
336 i = index * sizeof *page_dir;
337 i /= malloc_pagesize;
340 /* remember the old mapping size */
341 oldlen = malloc_ninfo * sizeof *page_dir;
344 * NOTE: we allocate new pages and copy the directory rather than tempt
345 * fate by trying to "grow" the region.. There is nothing to prevent
346 * us from accidently re-mapping space that's been allocated by our caller
347 * via dlopen() or other mmap().
349 * The copy problem is not too bad, as there is 4K of page index per
350 * 4MB of malloc arena.
352 * We can totally avoid the copy if we open a file descriptor to associate
353 * the anon mappings with. Then, when we remap the pages at the new
354 * address, the old pages will be "magically" remapped.. But this means
355 * keeping open a "secret" file descriptor.....
359 new = (struct pginfo**) MMAP(i * malloc_pagesize);
360 if (new == (struct pginfo **)-1)
363 /* Copy the old stuff */
364 memcpy(new, page_dir,
365 malloc_ninfo * sizeof *page_dir);
367 /* register the new size */
368 malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
370 /* swap the pointers */
374 /* Now free the old stuff */
380 * Initialize the world
393 #endif /* EXTRA_SANITY */
395 for (i = 0; i < 3; i++) {
398 j = readlink("/etc/malloc.conf", b, sizeof b - 1);
405 p = getenv("MALLOC_OPTIONS");
409 for (; p && *p; p++) {
411 case '>': malloc_cache <<= 1; break;
412 case '<': malloc_cache >>= 1; break;
413 case 'a': malloc_abort = 0; break;
414 case 'A': malloc_abort = 1; break;
415 case 'h': malloc_hint = 0; break;
416 case 'H': malloc_hint = 1; break;
417 case 'r': malloc_realloc = 0; break;
418 case 'R': malloc_realloc = 1; break;
419 case 'j': malloc_junk = 0; break;
420 case 'J': malloc_junk = 1; break;
422 case 'u': malloc_utrace = 0; break;
423 case 'U': malloc_utrace = 1; break;
425 case 'v': malloc_sysv = 0; break;
426 case 'V': malloc_sysv = 1; break;
427 case 'x': malloc_xmalloc = 0; break;
428 case 'X': malloc_xmalloc = 1; break;
429 case 'z': malloc_zero = 0; break;
430 case 'Z': malloc_zero = 1; break;
434 wrtwarning("unknown char in MALLOC_OPTIONS\n");
444 * We want junk in the entire allocation, and zero only in the part
445 * the user asked for.
451 * If we run with junk (or implicitly from above: zero), we want to
452 * force realloc() to get new storage, so we can DTRT with it.
457 /* Allocate one page for the page directory */
458 page_dir = (struct pginfo **) MMAP(malloc_pagesize);
460 if (page_dir == (struct pginfo **) -1)
461 wrterror("mmap(2) failed, check limits\n");
464 * We need a maximum of malloc_pageshift buckets, steal these from the
465 * front of the page_directory;
467 malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift;
468 malloc_origo -= malloc_pageshift;
470 malloc_ninfo = malloc_pagesize / sizeof *page_dir;
472 /* Recalculate the cache size in bytes, and make sure it's nonzero */
477 malloc_cache <<= malloc_pageshift;
480 * This is a nice hack from Kaleb Keithly (kaleb@x.org).
481 * We can sbrk(2) further back when we keep this on a low address.
483 px = (struct pgfree *) imalloc (sizeof *px);
485 /* Been here, done that */
490 * Allocate a number of complete pages
493 malloc_pages(size_t size)
495 void *p, *delay_free = 0;
500 size = pageround(size);
504 /* Look for free pages before asking for more */
505 for(pf = free_list.next; pf; pf = pf->next) {
508 if (pf->size & malloc_pagemask)
509 wrterror("(ES): junk length entry on free_list\n");
511 wrterror("(ES): zero length entry on free_list\n");
512 if (pf->page == pf->end)
513 wrterror("(ES): zero entry on free_list\n");
514 if (pf->page > pf->end)
515 wrterror("(ES): sick entry on free_list\n");
516 if ((void*)pf->page >= (void*)sbrk(0))
517 wrterror("(ES): entry on free_list past brk\n");
518 if (page_dir[ptr2index(pf->page)] != MALLOC_FREE)
519 wrterror("(ES): non-free first page on free-list\n");
520 if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE)
521 wrterror("(ES): non-free last page on free-list\n");
522 #endif /* EXTRA_SANITY */
527 if (pf->size == size) {
530 pf->next->prev = pf->prev;
531 pf->prev->next = pf->next;
537 pf->page = (char *)pf->page + size;
543 if (p && page_dir[ptr2index(p)] != MALLOC_FREE)
544 wrterror("(ES): allocated non-free page on free-list\n");
545 #endif /* EXTRA_SANITY */
547 size >>= malloc_pageshift;
555 index = ptr2index(p);
556 page_dir[index] = MALLOC_FIRST;
558 page_dir[index+i] = MALLOC_FOLLOW;
561 memset(p, SOME_JUNK, size << malloc_pageshift);
575 * Allocate a page of fragments
578 static __inline__ int
579 malloc_make_chunks(int bits)
585 /* Allocate a new bucket */
586 pp = malloc_pages(malloc_pagesize);
590 /* Find length of admin structure */
591 l = offsetof(struct pginfo, bits[0]);
592 l += sizeof bp->bits[0] *
593 (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
595 /* Don't waste more than two chunks on this */
596 if ((1<<(bits)) <= l+l) {
597 bp = (struct pginfo *)pp;
599 bp = (struct pginfo *)imalloc(l);
606 bp->size = (1<<bits);
608 bp->total = bp->free = malloc_pagesize >> bits;
611 /* set all valid bits in the bitmap */
615 /* Do a bunch at a time */
616 for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
617 bp->bits[i / MALLOC_BITS] = ~0;
620 bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
622 if (bp == bp->page) {
623 /* Mark the ones we stole for ourselves */
625 bp->bits[i/MALLOC_BITS] &= ~(1<<(i%MALLOC_BITS));
634 page_dir[ptr2index(pp)] = bp;
636 bp->next = page_dir[bits];
645 * Allocate a fragment
648 malloc_bytes(size_t size)
656 /* Don't bother with anything less than this */
657 if (size < malloc_minsize)
658 size = malloc_minsize;
660 /* Find the right bucket */
666 /* If it's empty, make a page more of that size chunks */
667 if (!page_dir[j] && !malloc_make_chunks(j))
672 /* Find first word of bitmap which isn't empty */
673 for (lp = bp->bits; !*lp; lp++)
676 /* Find that bit, and tweak it */
685 /* If there are no more free, remove from free-list */
687 page_dir[j] = bp->next;
691 /* Adjust to the real offset of that chunk */
692 k += (lp-bp->bits)*MALLOC_BITS;
696 memset((u_char*)bp->page + k, SOME_JUNK, bp->size);
698 return (u_char *)bp->page + k;
702 * Allocate a piece of memory
712 if ((size + malloc_pagesize) < size) /* Check for overflow */
714 else if (size <= malloc_maxsize)
715 result = malloc_bytes(size);
717 result = malloc_pages(size);
719 if (malloc_zero && result)
720 memset(result, 0, size);
726 * Change the size of an allocation.
729 irealloc(void *ptr, size_t size)
739 index = ptr2index(ptr);
741 if (index < malloc_pageshift) {
742 wrtwarning("junk pointer, too low to make sense\n");
746 if (index > last_index) {
747 wrtwarning("junk pointer, too high to make sense\n");
751 mp = &page_dir[index];
753 if (*mp == MALLOC_FIRST) { /* Page allocation */
755 /* Check the pointer */
756 if ((u_long)ptr & malloc_pagemask) {
757 wrtwarning("modified (page-) pointer\n");
761 /* Find the size in bytes */
762 for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
763 osize += malloc_pagesize;
765 if (!malloc_realloc && /* unless we have to, */
766 size <= osize && /* .. or are too small, */
767 size > (osize - malloc_pagesize)) { /* .. or can free a page, */
768 return ptr; /* don't do anything. */
771 } else if (*mp >= MALLOC_MAGIC) { /* Chunk allocation */
773 /* Check the pointer for sane values */
774 if (((u_long)ptr & ((*mp)->size-1))) {
775 wrtwarning("modified (chunk-) pointer\n");
779 /* Find the chunk index in the page */
780 i = ((u_long)ptr & malloc_pagemask) >> (*mp)->shift;
782 /* Verify that it isn't a free chunk already */
783 if ((*mp)->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
784 wrtwarning("chunk is already free\n");
790 if (!malloc_realloc && /* Unless we have to, */
791 size < osize && /* ..or are too small, */
792 (size > osize/2 || /* ..or could use a smaller size, */
793 osize == malloc_minsize)) { /* ..(if there is one) */
794 return ptr; /* ..Don't do anything */
798 wrtwarning("pointer to wrong page\n");
805 /* copy the lesser of the two sizes, and free the old one */
808 else if (osize < size)
809 memcpy(p, ptr, osize);
811 memcpy(p, ptr, size);
818 * Free a sequence of pages
821 static __inline__ void
822 free_pages(void *ptr, u_long index, struct pginfo *info)
825 struct pgfree *pf, *pt=0;
829 if (info == MALLOC_FREE) {
830 wrtwarning("page is already free\n");
834 if (info != MALLOC_FIRST) {
835 wrtwarning("pointer to wrong page\n");
839 if ((u_long)ptr & malloc_pagemask) {
840 wrtwarning("modified (page-) pointer\n");
844 /* Count how many pages and mark them free at the same time */
845 page_dir[index] = MALLOC_FREE;
846 for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
847 page_dir[index + i] = MALLOC_FREE;
849 l = i << malloc_pageshift;
852 memset(ptr, SOME_JUNK, l);
855 madvise(ptr, l, MADV_FREE);
857 tail = (char *)ptr+l;
859 /* add to free-list */
861 px = imalloc(sizeof *pt); /* This cannot fail... */
865 if (!free_list.next) {
867 /* Nothing on free list, put this at head */
868 px->next = free_list.next;
869 px->prev = &free_list;
876 /* Find the right spot, leave pf pointing to the modified entry. */
877 tail = (char *)ptr+l;
879 for(pf = free_list.next; pf->end < ptr && pf->next; pf = pf->next)
880 ; /* Race ahead here */
882 if (pf->page > tail) {
883 /* Insert before entry */
890 } else if (pf->end == ptr ) {
891 /* Append to the previous entry */
892 pf->end = (char *)pf->end + l;
894 if (pf->next && pf->end == pf->next->page ) {
895 /* And collapse the next too. */
898 pf->size += pt->size;
903 } else if (pf->page == tail) {
904 /* Prepend to entry */
907 } else if (!pf->next) {
908 /* Append at tail of chain */
915 wrterror("freelist is destroyed\n");
919 /* Return something to OS ? */
920 if (!pf->next && /* If we're the last one, */
921 pf->size > malloc_cache && /* ..and the cache is full, */
922 pf->end == malloc_brk && /* ..and none behind us, */
923 malloc_brk == sbrk(0)) { /* ..and it's OK to do... */
926 * Keep the cache intact. Notice that the '>' above guarantees that
927 * the pf will always have at least one page afterwards.
929 pf->end = (char *)pf->page + malloc_cache;
930 pf->size = malloc_cache;
933 malloc_brk = pf->end;
935 index = ptr2index(pf->end);
936 last_index = index - 1;
938 for(i=index;i <= last_index;)
939 page_dir[i++] = MALLOC_NOT_MINE;
941 /* XXX: We could realloc/shrink the pagedir here I guess. */
948 * Free a chunk, and possibly the page it's on, if the page becomes empty.
951 static __inline__ void
952 free_bytes(void *ptr, u_long index, struct pginfo *info)
958 /* Find the chunk number on the page */
959 i = ((u_long)ptr & malloc_pagemask) >> info->shift;
961 if (((u_long)ptr & (info->size-1))) {
962 wrtwarning("modified (chunk-) pointer\n");
966 if (info->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
967 wrtwarning("chunk is already free\n");
972 memset(ptr, SOME_JUNK, info->size);
974 info->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
977 mp = page_dir + info->shift;
979 if (info->free == 1) {
981 /* Page became non-full */
983 mp = page_dir + info->shift;
984 /* Insert in address order */
985 while (*mp && (*mp)->next && (*mp)->next->page < info->page)
992 if (info->free != info->total)
995 /* Find & remove this page in the queue */
996 while (*mp != info) {
1000 wrterror("(ES): Not on queue\n");
1001 #endif /* EXTRA_SANITY */
1005 /* Free the page & the info structure if need be */
1006 page_dir[ptr2index(info->page)] = MALLOC_FIRST;
1007 vp = info->page; /* Order is important ! */
1008 if(vp != (void*)info)
1016 struct pginfo *info;
1023 if (!malloc_started) {
1024 wrtwarning("malloc() has never been called\n");
1028 /* If we're already sinking, don't make matters any worse. */
1032 index = ptr2index(ptr);
1034 if (index < malloc_pageshift) {
1035 wrtwarning("junk pointer, too low to make sense\n");
1039 if (index > last_index) {
1040 wrtwarning("junk pointer, too high to make sense\n");
1044 info = page_dir[index];
1046 if (info < MALLOC_MAGIC)
1047 free_pages(ptr, index, info);
1049 free_bytes(ptr, index, info);
1054 * These are the public exported interface routines.
1064 malloc_func = " in malloc():";
1065 if (malloc_active++) {
1066 wrtwarning("recursive call\n");
1071 if (!malloc_started)
1073 if (malloc_sysv && !size)
1080 if (malloc_xmalloc && !r)
1081 wrterror("out of memory\n");
1089 malloc_func = " in free():";
1090 if (malloc_active++) {
1091 wrtwarning("recursive call\n");
1105 realloc(void *ptr, size_t size)
1111 malloc_func = " in realloc():";
1112 if (malloc_active++) {
1113 wrtwarning("recursive call\n");
1118 if (ptr && !malloc_started) {
1119 wrtwarning("malloc() has never been called\n");
1122 if (!malloc_started)
1124 if (malloc_sysv && !size) {
1131 r = irealloc(ptr, size);
1134 UTRACE(ptr, size, r);
1137 if (malloc_xmalloc && err)
1138 wrterror("out of memory\n");