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 $
10 * $DragonFly: src/lib/libc/stdlib/malloc.c,v 1.4 2003/09/06 08:19:16 asmodai Exp $
15 * Defining EXTRA_SANITY will enable extra checks which are related
16 * to internal conditions and consistency in malloc.c. This has a
17 * noticeable runtime performance hit, and generally will not do you
18 * any good unless you fiddle with the internals of malloc or want
19 * to catch random pointer corruption as early as possible.
21 #ifndef MALLOC_EXTRA_SANITY
22 #undef MALLOC_EXTRA_SANITY
26 * What to use for Junk. This is the byte value we use to fill with
27 * when the 'J' option is enabled.
29 #define SOME_JUNK 0xd0 /* as in "Duh" :-) */
32 * The basic parameters you can tweak.
34 * malloc_pageshift pagesize = 1 << malloc_pageshift
35 * It's probably best if this is the native
36 * page size, but it doesn't have to be.
38 * malloc_minsize minimum size of an allocation in bytes.
39 * If this is too small it's too much work
40 * to manage them. This is also the smallest
41 * unit of alignment used for the storage
42 * returned by malloc/realloc.
46 #if defined(__FreeBSD__)
47 # if defined(__i386__)
48 # define malloc_pageshift 12U
49 # define malloc_minsize 16U
51 # if defined(__alpha__)
52 # define malloc_pageshift 13U
53 # define malloc_minsize 16U
55 # if !defined(__NETBSD_SYSCALLS)
59 * Make malloc/free/realloc thread-safe in libc for use with
62 # include "libc_private.h"
63 # include "spinlock.h"
64 static spinlock_t thread_lock = _SPINLOCK_INITIALIZER;
65 # define THREAD_LOCK() if (__isthreaded) _SPINLOCK(&thread_lock);
66 # define THREAD_UNLOCK() if (__isthreaded) _SPINUNLOCK(&thread_lock);
67 #endif /* __FreeBSD__ */
69 #if defined(__sparc__) && defined(sun)
70 # define malloc_pageshift 12U
71 # define malloc_minsize 16U
74 # define MMAP_FD fdzero
75 # define INIT_MMAP() \
76 { if ((fdzero = _open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
77 wrterror("open of /dev/zero"); }
78 # define MADV_FREE MADV_DONTNEED
79 #endif /* __sparc__ */
81 /* Insert your combination here... */
82 #if defined(__FOOCPU__) && defined(__BAROS__)
83 # define malloc_pageshift 12U
84 # define malloc_minsize 16U
85 #endif /* __FOOCPU__ && __BAROS__ */
89 * No user serviceable parts behind this point.
91 #include <sys/types.h>
103 * This structure describes a page worth of chunks.
107 struct pginfo *next; /* next on the free list */
108 void *page; /* Pointer to the page */
109 u_short size; /* size of this page's chunks */
110 u_short shift; /* How far to shift for this size chunks */
111 u_short free; /* How many free chunks */
112 u_short total; /* How many chunk */
113 u_int bits[1]; /* Which chunks are free */
117 * This structure describes a number of free pages.
121 struct pgfree *next; /* next run of free pages */
122 struct pgfree *prev; /* prev run of free pages */
123 void *page; /* pointer to free pages */
124 void *end; /* pointer to end of free pages */
125 size_t size; /* number of bytes free */
129 * How many bits per u_int in the bitmap.
130 * Change only if not 8 bits/byte
132 #define MALLOC_BITS (8*sizeof(u_int))
135 * Magic values to put in the page_directory
137 #define MALLOC_NOT_MINE ((struct pginfo*) 0)
138 #define MALLOC_FREE ((struct pginfo*) 1)
139 #define MALLOC_FIRST ((struct pginfo*) 2)
140 #define MALLOC_FOLLOW ((struct pginfo*) 3)
141 #define MALLOC_MAGIC ((struct pginfo*) 4)
143 #ifndef malloc_pageshift
144 #define malloc_pageshift 12U
147 #ifndef malloc_minsize
148 #define malloc_minsize 16U
151 #if !defined(malloc_pagesize)
152 #define malloc_pagesize (1UL<<malloc_pageshift)
155 #if ((1<<malloc_pageshift) != malloc_pagesize)
156 #error "(1<<malloc_pageshift) != malloc_pagesize"
159 #ifndef malloc_maxsize
160 #define malloc_maxsize ((malloc_pagesize)>>1)
163 /* A mask for the offset inside a page. */
164 #define malloc_pagemask ((malloc_pagesize)-1)
166 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
167 #define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)
170 #define THREAD_LOCK()
173 #ifndef THREAD_UNLOCK
174 #define THREAD_UNLOCK()
185 /* Set when initialization has been done */
186 static unsigned malloc_started;
188 /* Recusion flag for public interface. */
189 static int malloc_active;
191 /* Number of free pages we cache */
192 static unsigned malloc_cache = 16;
194 /* The offset from pagenumber to index into the page directory */
195 static u_long malloc_origo;
197 /* The last index in the page directory we care about */
198 static u_long last_index;
200 /* Pointer to page directory. Allocated "as if with" malloc */
201 static struct pginfo **page_dir;
203 /* How many slots in the page directory */
204 static unsigned malloc_ninfo;
206 /* Free pages line up here */
207 static struct pgfree free_list;
209 /* Abort(), user doesn't handle problems. */
210 static int malloc_abort;
212 /* Are we trying to die ? */
215 /* always realloc ? */
216 static int malloc_realloc;
218 /* pass the kernel a hint on free pages ? */
219 static int malloc_hint = 0;
221 /* xmalloc behaviour ? */
222 static int malloc_xmalloc;
224 /* sysv behaviour for malloc(0) ? */
225 static int malloc_sysv;
228 static int malloc_zero;
231 static int malloc_junk;
236 static int malloc_utrace;
238 struct ut { void *p; size_t s; void *r; };
240 void utrace (struct ut *, int);
242 #define UTRACE(a, b, c) \
244 {struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}
245 #else /* !HAS_UTRACE */
246 #define UTRACE(a,b,c)
247 #endif /* HAS_UTRACE */
250 static void *malloc_brk;
252 /* one location cache for free-list holders */
253 static struct pgfree *px;
255 /* compile-time options */
256 char *malloc_options;
258 /* Name of the current public function */
259 static char *malloc_func;
263 mmap(0, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
267 * Necessary function declarations
269 static int extend_pgdir(u_long index);
270 static void *imalloc(size_t size);
271 static void ifree(void *ptr);
272 static void *irealloc(void *ptr, size_t size);
274 extern char *__progname;
279 char *q = " error: ";
280 _write(STDERR_FILENO, __progname, strlen(__progname));
281 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
282 _write(STDERR_FILENO, q, strlen(q));
283 _write(STDERR_FILENO, p, strlen(p));
291 char *q = " warning: ";
294 _write(STDERR_FILENO, __progname, strlen(__progname));
295 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
296 _write(STDERR_FILENO, q, strlen(q));
297 _write(STDERR_FILENO, p, strlen(p));
301 * Allocate a number of pages from the OS
304 map_pages(size_t pages)
306 caddr_t result, tail;
308 result = (caddr_t)pageround((u_long)sbrk(0));
309 tail = result + (pages << malloc_pageshift);
313 wrterror("(ES): map_pages fails\n");
314 #endif /* EXTRA_SANITY */
318 last_index = ptr2index(tail) - 1;
321 if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index))
328 * Extend page directory
331 extend_pgdir(u_long index)
333 struct pginfo **new, **old;
336 /* Make it this many pages */
337 i = index * sizeof *page_dir;
338 i /= malloc_pagesize;
341 /* remember the old mapping size */
342 oldlen = malloc_ninfo * sizeof *page_dir;
345 * NOTE: we allocate new pages and copy the directory rather than tempt
346 * fate by trying to "grow" the region.. There is nothing to prevent
347 * us from accidently re-mapping space that's been allocated by our caller
348 * via dlopen() or other mmap().
350 * The copy problem is not too bad, as there is 4K of page index per
351 * 4MB of malloc arena.
353 * We can totally avoid the copy if we open a file descriptor to associate
354 * the anon mappings with. Then, when we remap the pages at the new
355 * address, the old pages will be "magically" remapped.. But this means
356 * keeping open a "secret" file descriptor.....
360 new = (struct pginfo**) MMAP(i * malloc_pagesize);
361 if (new == (struct pginfo **)-1)
364 /* Copy the old stuff */
365 memcpy(new, page_dir,
366 malloc_ninfo * sizeof *page_dir);
368 /* register the new size */
369 malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
371 /* swap the pointers */
375 /* Now free the old stuff */
381 * Initialize the world
394 #endif /* EXTRA_SANITY */
396 for (i = 0; i < 3; i++) {
399 j = readlink("/etc/malloc.conf", b, sizeof b - 1);
406 p = getenv("MALLOC_OPTIONS");
410 for (; p && *p; p++) {
412 case '>': malloc_cache <<= 1; break;
413 case '<': malloc_cache >>= 1; break;
414 case 'a': malloc_abort = 0; break;
415 case 'A': malloc_abort = 1; break;
416 case 'h': malloc_hint = 0; break;
417 case 'H': malloc_hint = 1; break;
418 case 'r': malloc_realloc = 0; break;
419 case 'R': malloc_realloc = 1; break;
420 case 'j': malloc_junk = 0; break;
421 case 'J': malloc_junk = 1; break;
423 case 'u': malloc_utrace = 0; break;
424 case 'U': malloc_utrace = 1; break;
426 case 'v': malloc_sysv = 0; break;
427 case 'V': malloc_sysv = 1; break;
428 case 'x': malloc_xmalloc = 0; break;
429 case 'X': malloc_xmalloc = 1; break;
430 case 'z': malloc_zero = 0; break;
431 case 'Z': malloc_zero = 1; break;
435 wrtwarning("unknown char in MALLOC_OPTIONS\n");
445 * We want junk in the entire allocation, and zero only in the part
446 * the user asked for.
452 * If we run with junk (or implicitly from above: zero), we want to
453 * force realloc() to get new storage, so we can DTRT with it.
458 /* Allocate one page for the page directory */
459 page_dir = (struct pginfo **) MMAP(malloc_pagesize);
461 if (page_dir == (struct pginfo **) -1)
462 wrterror("mmap(2) failed, check limits\n");
465 * We need a maximum of malloc_pageshift buckets, steal these from the
466 * front of the page_directory;
468 malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift;
469 malloc_origo -= malloc_pageshift;
471 malloc_ninfo = malloc_pagesize / sizeof *page_dir;
473 /* Recalculate the cache size in bytes, and make sure it's nonzero */
478 malloc_cache <<= malloc_pageshift;
481 * This is a nice hack from Kaleb Keithly (kaleb@x.org).
482 * We can sbrk(2) further back when we keep this on a low address.
484 px = (struct pgfree *) imalloc (sizeof *px);
486 /* Been here, done that */
491 * Allocate a number of complete pages
494 malloc_pages(size_t size)
496 void *p, *delay_free = 0;
501 size = pageround(size);
505 /* Look for free pages before asking for more */
506 for(pf = free_list.next; pf; pf = pf->next) {
509 if (pf->size & malloc_pagemask)
510 wrterror("(ES): junk length entry on free_list\n");
512 wrterror("(ES): zero length entry on free_list\n");
513 if (pf->page == pf->end)
514 wrterror("(ES): zero entry on free_list\n");
515 if (pf->page > pf->end)
516 wrterror("(ES): sick entry on free_list\n");
517 if ((void*)pf->page >= (void*)sbrk(0))
518 wrterror("(ES): entry on free_list past brk\n");
519 if (page_dir[ptr2index(pf->page)] != MALLOC_FREE)
520 wrterror("(ES): non-free first page on free-list\n");
521 if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE)
522 wrterror("(ES): non-free last page on free-list\n");
523 #endif /* EXTRA_SANITY */
528 if (pf->size == size) {
531 pf->next->prev = pf->prev;
532 pf->prev->next = pf->next;
538 pf->page = (char *)pf->page + size;
544 if (p && page_dir[ptr2index(p)] != MALLOC_FREE)
545 wrterror("(ES): allocated non-free page on free-list\n");
546 #endif /* EXTRA_SANITY */
548 size >>= malloc_pageshift;
556 index = ptr2index(p);
557 page_dir[index] = MALLOC_FIRST;
559 page_dir[index+i] = MALLOC_FOLLOW;
562 memset(p, SOME_JUNK, size << malloc_pageshift);
576 * Allocate a page of fragments
579 static __inline__ int
580 malloc_make_chunks(int bits)
586 /* Allocate a new bucket */
587 pp = malloc_pages(malloc_pagesize);
591 /* Find length of admin structure */
592 l = offsetof(struct pginfo, bits[0]);
593 l += sizeof bp->bits[0] *
594 (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
596 /* Don't waste more than two chunks on this */
597 if ((1<<(bits)) <= l+l) {
598 bp = (struct pginfo *)pp;
600 bp = (struct pginfo *)imalloc(l);
607 bp->size = (1<<bits);
609 bp->total = bp->free = malloc_pagesize >> bits;
612 /* set all valid bits in the bitmap */
616 /* Do a bunch at a time */
617 for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
618 bp->bits[i / MALLOC_BITS] = ~0;
621 bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
623 if (bp == bp->page) {
624 /* Mark the ones we stole for ourselves */
626 bp->bits[i/MALLOC_BITS] &= ~(1<<(i%MALLOC_BITS));
635 page_dir[ptr2index(pp)] = bp;
637 bp->next = page_dir[bits];
646 * Allocate a fragment
649 malloc_bytes(size_t size)
657 /* Don't bother with anything less than this */
658 if (size < malloc_minsize)
659 size = malloc_minsize;
661 /* Find the right bucket */
667 /* If it's empty, make a page more of that size chunks */
668 if (!page_dir[j] && !malloc_make_chunks(j))
673 /* Find first word of bitmap which isn't empty */
674 for (lp = bp->bits; !*lp; lp++)
677 /* Find that bit, and tweak it */
686 /* If there are no more free, remove from free-list */
688 page_dir[j] = bp->next;
692 /* Adjust to the real offset of that chunk */
693 k += (lp-bp->bits)*MALLOC_BITS;
697 memset((u_char*)bp->page + k, SOME_JUNK, bp->size);
699 return (u_char *)bp->page + k;
703 * Allocate a piece of memory
713 if ((size + malloc_pagesize) < size) /* Check for overflow */
715 else if (size <= malloc_maxsize)
716 result = malloc_bytes(size);
718 result = malloc_pages(size);
720 if (malloc_zero && result)
721 memset(result, 0, size);
727 * Change the size of an allocation.
730 irealloc(void *ptr, size_t size)
740 index = ptr2index(ptr);
742 if (index < malloc_pageshift) {
743 wrtwarning("junk pointer, too low to make sense\n");
747 if (index > last_index) {
748 wrtwarning("junk pointer, too high to make sense\n");
752 mp = &page_dir[index];
754 if (*mp == MALLOC_FIRST) { /* Page allocation */
756 /* Check the pointer */
757 if ((u_long)ptr & malloc_pagemask) {
758 wrtwarning("modified (page-) pointer\n");
762 /* Find the size in bytes */
763 for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
764 osize += malloc_pagesize;
766 if (!malloc_realloc && /* unless we have to, */
767 size <= osize && /* .. or are too small, */
768 size > (osize - malloc_pagesize)) { /* .. or can free a page, */
769 return ptr; /* don't do anything. */
772 } else if (*mp >= MALLOC_MAGIC) { /* Chunk allocation */
774 /* Check the pointer for sane values */
775 if (((u_long)ptr & ((*mp)->size-1))) {
776 wrtwarning("modified (chunk-) pointer\n");
780 /* Find the chunk index in the page */
781 i = ((u_long)ptr & malloc_pagemask) >> (*mp)->shift;
783 /* Verify that it isn't a free chunk already */
784 if ((*mp)->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
785 wrtwarning("chunk is already free\n");
791 if (!malloc_realloc && /* Unless we have to, */
792 size < osize && /* ..or are too small, */
793 (size > osize/2 || /* ..or could use a smaller size, */
794 osize == malloc_minsize)) { /* ..(if there is one) */
795 return ptr; /* ..Don't do anything */
799 wrtwarning("pointer to wrong page\n");
806 /* copy the lesser of the two sizes, and free the old one */
809 else if (osize < size)
810 memcpy(p, ptr, osize);
812 memcpy(p, ptr, size);
819 * Free a sequence of pages
822 static __inline__ void
823 free_pages(void *ptr, u_long index, struct pginfo *info)
826 struct pgfree *pf, *pt=0;
830 if (info == MALLOC_FREE) {
831 wrtwarning("page is already free\n");
835 if (info != MALLOC_FIRST) {
836 wrtwarning("pointer to wrong page\n");
840 if ((u_long)ptr & malloc_pagemask) {
841 wrtwarning("modified (page-) pointer\n");
845 /* Count how many pages and mark them free at the same time */
846 page_dir[index] = MALLOC_FREE;
847 for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
848 page_dir[index + i] = MALLOC_FREE;
850 l = i << malloc_pageshift;
853 memset(ptr, SOME_JUNK, l);
856 madvise(ptr, l, MADV_FREE);
858 tail = (char *)ptr+l;
860 /* add to free-list */
862 px = imalloc(sizeof *pt); /* This cannot fail... */
866 if (!free_list.next) {
868 /* Nothing on free list, put this at head */
869 px->next = free_list.next;
870 px->prev = &free_list;
877 /* Find the right spot, leave pf pointing to the modified entry. */
878 tail = (char *)ptr+l;
880 for(pf = free_list.next; pf->end < ptr && pf->next; pf = pf->next)
881 ; /* Race ahead here */
883 if (pf->page > tail) {
884 /* Insert before entry */
891 } else if (pf->end == ptr ) {
892 /* Append to the previous entry */
893 pf->end = (char *)pf->end + l;
895 if (pf->next && pf->end == pf->next->page ) {
896 /* And collapse the next too. */
899 pf->size += pt->size;
904 } else if (pf->page == tail) {
905 /* Prepend to entry */
908 } else if (!pf->next) {
909 /* Append at tail of chain */
916 wrterror("freelist is destroyed\n");
920 /* Return something to OS ? */
921 if (!pf->next && /* If we're the last one, */
922 pf->size > malloc_cache && /* ..and the cache is full, */
923 pf->end == malloc_brk && /* ..and none behind us, */
924 malloc_brk == sbrk(0)) { /* ..and it's OK to do... */
927 * Keep the cache intact. Notice that the '>' above guarantees that
928 * the pf will always have at least one page afterwards.
930 pf->end = (char *)pf->page + malloc_cache;
931 pf->size = malloc_cache;
934 malloc_brk = pf->end;
936 index = ptr2index(pf->end);
937 last_index = index - 1;
939 for(i=index;i <= last_index;)
940 page_dir[i++] = MALLOC_NOT_MINE;
942 /* XXX: We could realloc/shrink the pagedir here I guess. */
949 * Free a chunk, and possibly the page it's on, if the page becomes empty.
952 static __inline__ void
953 free_bytes(void *ptr, u_long index, struct pginfo *info)
959 /* Find the chunk number on the page */
960 i = ((u_long)ptr & malloc_pagemask) >> info->shift;
962 if (((u_long)ptr & (info->size-1))) {
963 wrtwarning("modified (chunk-) pointer\n");
967 if (info->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
968 wrtwarning("chunk is already free\n");
973 memset(ptr, SOME_JUNK, info->size);
975 info->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
978 mp = page_dir + info->shift;
980 if (info->free == 1) {
982 /* Page became non-full */
984 mp = page_dir + info->shift;
985 /* Insert in address order */
986 while (*mp && (*mp)->next && (*mp)->next->page < info->page)
993 if (info->free != info->total)
996 /* Find & remove this page in the queue */
997 while (*mp != info) {
1001 wrterror("(ES): Not on queue\n");
1002 #endif /* EXTRA_SANITY */
1006 /* Free the page & the info structure if need be */
1007 page_dir[ptr2index(info->page)] = MALLOC_FIRST;
1008 vp = info->page; /* Order is important ! */
1009 if(vp != (void*)info)
1017 struct pginfo *info;
1024 if (!malloc_started) {
1025 wrtwarning("malloc() has never been called\n");
1029 /* If we're already sinking, don't make matters any worse. */
1033 index = ptr2index(ptr);
1035 if (index < malloc_pageshift) {
1036 wrtwarning("junk pointer, too low to make sense\n");
1040 if (index > last_index) {
1041 wrtwarning("junk pointer, too high to make sense\n");
1045 info = page_dir[index];
1047 if (info < MALLOC_MAGIC)
1048 free_pages(ptr, index, info);
1050 free_bytes(ptr, index, info);
1055 * These are the public exported interface routines.
1065 malloc_func = " in malloc():";
1066 if (malloc_active++) {
1067 wrtwarning("recursive call\n");
1072 if (!malloc_started)
1074 if (malloc_sysv && !size)
1081 if (malloc_xmalloc && !r)
1082 wrterror("out of memory\n");
1090 malloc_func = " in free():";
1091 if (malloc_active++) {
1092 wrtwarning("recursive call\n");
1106 realloc(void *ptr, size_t size)
1112 malloc_func = " in realloc():";
1113 if (malloc_active++) {
1114 wrtwarning("recursive call\n");
1119 if (ptr && !malloc_started) {
1120 wrtwarning("malloc() has never been called\n");
1123 if (!malloc_started)
1125 if (malloc_sysv && !size) {
1132 r = irealloc(ptr, size);
1135 UTRACE(ptr, size, r);
1138 if (malloc_xmalloc && err)
1139 wrterror("out of memory\n");