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.7 2005/03/09 18:52:21 joerg 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 #include "namespace.h"
47 #if defined(__FreeBSD__) || defined(__DragonFly__)
48 # if defined(__i386__)
49 # define malloc_pageshift 12U
50 # define malloc_minsize 16U
52 # if defined(__alpha__)
53 # define malloc_pageshift 13U
54 # define malloc_minsize 16U
56 # if !defined(__NETBSD_SYSCALLS)
60 * Make malloc/free/realloc thread-safe in libc for use with
63 # include "libc_private.h"
64 # include "spinlock.h"
65 static spinlock_t thread_lock = _SPINLOCK_INITIALIZER;
66 # define THREAD_LOCK() if (__isthreaded) _SPINLOCK(&thread_lock);
67 # define THREAD_UNLOCK() if (__isthreaded) _SPINUNLOCK(&thread_lock);
68 #endif /* __FreeBSD__ || __DragonFly__ */
70 #if defined(__sparc__) && defined(sun)
71 # define malloc_pageshift 12U
72 # define malloc_minsize 16U
75 # define MMAP_FD fdzero
76 # define INIT_MMAP() \
77 { if ((fdzero = _open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
78 wrterror("open of /dev/zero"); }
79 # define MADV_FREE MADV_DONTNEED
80 #endif /* __sparc__ */
82 /* Insert your combination here... */
83 #if defined(__FOOCPU__) && defined(__BAROS__)
84 # define malloc_pageshift 12U
85 # define malloc_minsize 16U
86 #endif /* __FOOCPU__ && __BAROS__ */
90 * No user serviceable parts behind this point.
92 #include <sys/types.h>
102 #include "un-namespace.h"
105 * This structure describes a page worth of chunks.
109 struct pginfo *next; /* next on the free list */
110 void *page; /* Pointer to the page */
111 u_short size; /* size of this page's chunks */
112 u_short shift; /* How far to shift for this size chunks */
113 u_short free; /* How many free chunks */
114 u_short total; /* How many chunk */
115 u_int bits[1]; /* Which chunks are free */
119 * This structure describes a number of free pages.
123 struct pgfree *next; /* next run of free pages */
124 struct pgfree *prev; /* prev run of free pages */
125 void *page; /* pointer to free pages */
126 void *end; /* pointer to end of free pages */
127 size_t size; /* number of bytes free */
131 * How many bits per u_int in the bitmap.
132 * Change only if not 8 bits/byte
134 #define MALLOC_BITS (8*sizeof(u_int))
137 * Magic values to put in the page_directory
139 #define MALLOC_NOT_MINE ((struct pginfo*) 0)
140 #define MALLOC_FREE ((struct pginfo*) 1)
141 #define MALLOC_FIRST ((struct pginfo*) 2)
142 #define MALLOC_FOLLOW ((struct pginfo*) 3)
143 #define MALLOC_MAGIC ((struct pginfo*) 4)
145 #ifndef malloc_pageshift
146 #define malloc_pageshift 12U
149 #ifndef malloc_minsize
150 #define malloc_minsize 16U
153 #if !defined(malloc_pagesize)
154 #define malloc_pagesize (1UL<<malloc_pageshift)
157 #if ((1<<malloc_pageshift) != malloc_pagesize)
158 #error "(1<<malloc_pageshift) != malloc_pagesize"
161 #ifndef malloc_maxsize
162 #define malloc_maxsize ((malloc_pagesize)>>1)
165 /* A mask for the offset inside a page. */
166 #define malloc_pagemask ((malloc_pagesize)-1)
168 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
169 #define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)
172 #define THREAD_LOCK()
175 #ifndef THREAD_UNLOCK
176 #define THREAD_UNLOCK()
187 /* Set when initialization has been done */
188 static unsigned malloc_started;
190 /* Recusion flag for public interface. */
191 static int malloc_active;
193 /* Number of free pages we cache */
194 static unsigned malloc_cache = 16;
196 /* The offset from pagenumber to index into the page directory */
197 static u_long malloc_origo;
199 /* The last index in the page directory we care about */
200 static u_long last_index;
202 /* Pointer to page directory. Allocated "as if with" malloc */
203 static struct pginfo **page_dir;
205 /* How many slots in the page directory */
206 static unsigned malloc_ninfo;
208 /* Free pages line up here */
209 static struct pgfree free_list;
211 /* Abort(), user doesn't handle problems. */
212 static int malloc_abort;
214 /* Are we trying to die ? */
217 /* always realloc ? */
218 static int malloc_realloc;
220 /* pass the kernel a hint on free pages ? */
221 static int malloc_hint = 0;
223 /* xmalloc behaviour ? */
224 static int malloc_xmalloc;
226 /* sysv behaviour for malloc(0) ? */
227 static int malloc_sysv;
230 static int malloc_zero;
233 static int malloc_junk;
238 static int malloc_utrace;
240 struct ut { void *p; size_t s; void *r; };
242 void utrace (struct ut *, int);
244 #define UTRACE(a, b, c) \
246 {struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}
247 #else /* !HAS_UTRACE */
248 #define UTRACE(a,b,c)
249 #endif /* HAS_UTRACE */
252 static void *malloc_brk;
254 /* one location cache for free-list holders */
255 static struct pgfree *px;
257 /* compile-time options */
258 char *malloc_options;
260 /* Name of the current public function */
261 static char *malloc_func;
265 mmap(0, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
269 * Necessary function declarations
271 static int extend_pgdir(u_long index);
272 static void *imalloc(size_t size);
273 static void ifree(void *ptr);
274 static void *irealloc(void *ptr, size_t size);
277 wrterror(const char *p)
279 const char *progname = getprogname();
280 const char *q = " error: ";
282 _write(STDERR_FILENO, progname, strlen(progname));
283 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
284 _write(STDERR_FILENO, q, strlen(q));
285 _write(STDERR_FILENO, p, strlen(p));
291 wrtwarning(const char *p)
293 const char *progname = getprogname();
294 const char *q = " warning: ";
298 _write(STDERR_FILENO, progname, strlen(progname));
299 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
300 _write(STDERR_FILENO, q, strlen(q));
301 _write(STDERR_FILENO, p, strlen(p));
305 * Allocate a number of pages from the OS
308 map_pages(size_t pages)
310 caddr_t result, tail;
312 result = (caddr_t)pageround((u_long)sbrk(0));
313 tail = result + (pages << malloc_pageshift);
317 wrterror("(ES): map_pages fails\n");
318 #endif /* EXTRA_SANITY */
322 last_index = ptr2index(tail) - 1;
325 if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index))
332 * Extend page directory
335 extend_pgdir(u_long index)
337 struct pginfo **new, **old;
340 /* Make it this many pages */
341 i = index * sizeof *page_dir;
342 i /= malloc_pagesize;
345 /* remember the old mapping size */
346 oldlen = malloc_ninfo * sizeof *page_dir;
349 * NOTE: we allocate new pages and copy the directory rather than tempt
350 * fate by trying to "grow" the region.. There is nothing to prevent
351 * us from accidently re-mapping space that's been allocated by our caller
352 * via dlopen() or other mmap().
354 * The copy problem is not too bad, as there is 4K of page index per
355 * 4MB of malloc arena.
357 * We can totally avoid the copy if we open a file descriptor to associate
358 * the anon mappings with. Then, when we remap the pages at the new
359 * address, the old pages will be "magically" remapped.. But this means
360 * keeping open a "secret" file descriptor.....
364 new = (struct pginfo**) MMAP(i * malloc_pagesize);
365 if (new == (struct pginfo **)-1)
368 /* Copy the old stuff */
369 memcpy(new, page_dir,
370 malloc_ninfo * sizeof *page_dir);
372 /* register the new size */
373 malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
375 /* swap the pointers */
379 /* Now free the old stuff */
385 * Initialize the world
398 #endif /* EXTRA_SANITY */
400 for (i = 0; i < 3; i++) {
403 j = readlink("/etc/malloc.conf", b, sizeof b - 1);
410 p = getenv("MALLOC_OPTIONS");
414 for (; p && *p; p++) {
416 case '>': malloc_cache <<= 1; break;
417 case '<': malloc_cache >>= 1; break;
418 case 'a': malloc_abort = 0; break;
419 case 'A': malloc_abort = 1; break;
420 case 'h': malloc_hint = 0; break;
421 case 'H': malloc_hint = 1; break;
422 case 'r': malloc_realloc = 0; break;
423 case 'R': malloc_realloc = 1; break;
424 case 'j': malloc_junk = 0; break;
425 case 'J': malloc_junk = 1; break;
427 case 'u': malloc_utrace = 0; break;
428 case 'U': malloc_utrace = 1; break;
430 case 'v': malloc_sysv = 0; break;
431 case 'V': malloc_sysv = 1; break;
432 case 'x': malloc_xmalloc = 0; break;
433 case 'X': malloc_xmalloc = 1; break;
434 case 'z': malloc_zero = 0; break;
435 case 'Z': malloc_zero = 1; break;
439 wrtwarning("unknown char in MALLOC_OPTIONS\n");
449 * We want junk in the entire allocation, and zero only in the part
450 * the user asked for.
456 * If we run with junk (or implicitly from above: zero), we want to
457 * force realloc() to get new storage, so we can DTRT with it.
462 /* Allocate one page for the page directory */
463 page_dir = (struct pginfo **) MMAP(malloc_pagesize);
465 if (page_dir == (struct pginfo **) -1)
466 wrterror("mmap(2) failed, check limits\n");
469 * We need a maximum of malloc_pageshift buckets, steal these from the
470 * front of the page_directory;
472 malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift;
473 malloc_origo -= malloc_pageshift;
475 malloc_ninfo = malloc_pagesize / sizeof *page_dir;
477 /* Recalculate the cache size in bytes, and make sure it's nonzero */
482 malloc_cache <<= malloc_pageshift;
485 * This is a nice hack from Kaleb Keithly (kaleb@x.org).
486 * We can sbrk(2) further back when we keep this on a low address.
488 px = (struct pgfree *) imalloc (sizeof *px);
490 /* Been here, done that */
495 * Allocate a number of complete pages
498 malloc_pages(size_t size)
500 void *p, *delay_free = 0;
505 size = pageround(size);
509 /* Look for free pages before asking for more */
510 for(pf = free_list.next; pf; pf = pf->next) {
513 if (pf->size & malloc_pagemask)
514 wrterror("(ES): junk length entry on free_list\n");
516 wrterror("(ES): zero length entry on free_list\n");
517 if (pf->page == pf->end)
518 wrterror("(ES): zero entry on free_list\n");
519 if (pf->page > pf->end)
520 wrterror("(ES): sick entry on free_list\n");
521 if ((void*)pf->page >= (void*)sbrk(0))
522 wrterror("(ES): entry on free_list past brk\n");
523 if (page_dir[ptr2index(pf->page)] != MALLOC_FREE)
524 wrterror("(ES): non-free first page on free-list\n");
525 if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE)
526 wrterror("(ES): non-free last page on free-list\n");
527 #endif /* EXTRA_SANITY */
532 if (pf->size == size) {
535 pf->next->prev = pf->prev;
536 pf->prev->next = pf->next;
542 pf->page = (char *)pf->page + size;
548 if (p && page_dir[ptr2index(p)] != MALLOC_FREE)
549 wrterror("(ES): allocated non-free page on free-list\n");
550 #endif /* EXTRA_SANITY */
552 size >>= malloc_pageshift;
560 index = ptr2index(p);
561 page_dir[index] = MALLOC_FIRST;
563 page_dir[index+i] = MALLOC_FOLLOW;
566 memset(p, SOME_JUNK, size << malloc_pageshift);
580 * Allocate a page of fragments
583 static __inline__ int
584 malloc_make_chunks(int bits)
590 /* Allocate a new bucket */
591 pp = malloc_pages(malloc_pagesize);
595 /* Find length of admin structure */
596 l = offsetof(struct pginfo, bits[0]);
597 l += sizeof bp->bits[0] *
598 (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
600 /* Don't waste more than two chunks on this */
601 if ((1<<(bits)) <= l+l) {
602 bp = (struct pginfo *)pp;
604 bp = (struct pginfo *)imalloc(l);
611 bp->size = (1<<bits);
613 bp->total = bp->free = malloc_pagesize >> bits;
616 /* set all valid bits in the bitmap */
620 /* Do a bunch at a time */
621 for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
622 bp->bits[i / MALLOC_BITS] = ~0;
625 bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
627 if (bp == bp->page) {
628 /* Mark the ones we stole for ourselves */
630 bp->bits[i/MALLOC_BITS] &= ~(1<<(i%MALLOC_BITS));
639 page_dir[ptr2index(pp)] = bp;
641 bp->next = page_dir[bits];
650 * Allocate a fragment
653 malloc_bytes(size_t size)
661 /* Don't bother with anything less than this */
662 if (size < malloc_minsize)
663 size = malloc_minsize;
665 /* Find the right bucket */
671 /* If it's empty, make a page more of that size chunks */
672 if (!page_dir[j] && !malloc_make_chunks(j))
677 /* Find first word of bitmap which isn't empty */
678 for (lp = bp->bits; !*lp; lp++)
681 /* Find that bit, and tweak it */
690 /* If there are no more free, remove from free-list */
692 page_dir[j] = bp->next;
696 /* Adjust to the real offset of that chunk */
697 k += (lp-bp->bits)*MALLOC_BITS;
701 memset((u_char*)bp->page + k, SOME_JUNK, bp->size);
703 return (u_char *)bp->page + k;
707 * Allocate a piece of memory
717 if ((size + malloc_pagesize) < size) /* Check for overflow */
719 else if (size <= malloc_maxsize)
720 result = malloc_bytes(size);
722 result = malloc_pages(size);
724 if (malloc_zero && result)
725 memset(result, 0, size);
731 * Change the size of an allocation.
734 irealloc(void *ptr, size_t size)
744 index = ptr2index(ptr);
746 if (index < malloc_pageshift) {
747 wrtwarning("junk pointer, too low to make sense\n");
751 if (index > last_index) {
752 wrtwarning("junk pointer, too high to make sense\n");
756 mp = &page_dir[index];
758 if (*mp == MALLOC_FIRST) { /* Page allocation */
760 /* Check the pointer */
761 if ((u_long)ptr & malloc_pagemask) {
762 wrtwarning("modified (page-) pointer\n");
766 /* Find the size in bytes */
767 for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
768 osize += malloc_pagesize;
770 if (!malloc_realloc && /* unless we have to, */
771 size <= osize && /* .. or are too small, */
772 size > (osize - malloc_pagesize)) { /* .. or can free a page, */
773 return ptr; /* don't do anything. */
776 } else if (*mp >= MALLOC_MAGIC) { /* Chunk allocation */
778 /* Check the pointer for sane values */
779 if (((u_long)ptr & ((*mp)->size-1))) {
780 wrtwarning("modified (chunk-) pointer\n");
784 /* Find the chunk index in the page */
785 i = ((u_long)ptr & malloc_pagemask) >> (*mp)->shift;
787 /* Verify that it isn't a free chunk already */
788 if ((*mp)->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
789 wrtwarning("chunk is already free\n");
795 if (!malloc_realloc && /* Unless we have to, */
796 size < osize && /* ..or are too small, */
797 (size > osize/2 || /* ..or could use a smaller size, */
798 osize == malloc_minsize)) { /* ..(if there is one) */
799 return ptr; /* ..Don't do anything */
803 wrtwarning("pointer to wrong page\n");
810 /* copy the lesser of the two sizes, and free the old one */
813 else if (osize < size)
814 memcpy(p, ptr, osize);
816 memcpy(p, ptr, size);
823 * Free a sequence of pages
826 static __inline__ void
827 free_pages(void *ptr, u_long index, struct pginfo *info)
830 struct pgfree *pf, *pt=0;
834 if (info == MALLOC_FREE) {
835 wrtwarning("page is already free\n");
839 if (info != MALLOC_FIRST) {
840 wrtwarning("pointer to wrong page\n");
844 if ((u_long)ptr & malloc_pagemask) {
845 wrtwarning("modified (page-) pointer\n");
849 /* Count how many pages and mark them free at the same time */
850 page_dir[index] = MALLOC_FREE;
851 for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
852 page_dir[index + i] = MALLOC_FREE;
854 l = i << malloc_pageshift;
857 memset(ptr, SOME_JUNK, l);
860 madvise(ptr, l, MADV_FREE);
862 tail = (char *)ptr+l;
864 /* add to free-list */
866 px = imalloc(sizeof *pt); /* This cannot fail... */
870 if (!free_list.next) {
872 /* Nothing on free list, put this at head */
873 px->next = free_list.next;
874 px->prev = &free_list;
881 /* Find the right spot, leave pf pointing to the modified entry. */
882 tail = (char *)ptr+l;
884 for(pf = free_list.next; pf->end < ptr && pf->next; pf = pf->next)
885 ; /* Race ahead here */
887 if (pf->page > tail) {
888 /* Insert before entry */
895 } else if (pf->end == ptr ) {
896 /* Append to the previous entry */
897 pf->end = (char *)pf->end + l;
899 if (pf->next && pf->end == pf->next->page ) {
900 /* And collapse the next too. */
903 pf->size += pt->size;
908 } else if (pf->page == tail) {
909 /* Prepend to entry */
912 } else if (!pf->next) {
913 /* Append at tail of chain */
920 wrterror("freelist is destroyed\n");
924 /* Return something to OS ? */
925 if (!pf->next && /* If we're the last one, */
926 pf->size > malloc_cache && /* ..and the cache is full, */
927 pf->end == malloc_brk && /* ..and none behind us, */
928 malloc_brk == sbrk(0)) { /* ..and it's OK to do... */
931 * Keep the cache intact. Notice that the '>' above guarantees that
932 * the pf will always have at least one page afterwards.
934 pf->end = (char *)pf->page + malloc_cache;
935 pf->size = malloc_cache;
938 malloc_brk = pf->end;
940 index = ptr2index(pf->end);
941 last_index = index - 1;
943 for(i=index;i <= last_index;)
944 page_dir[i++] = MALLOC_NOT_MINE;
946 /* XXX: We could realloc/shrink the pagedir here I guess. */
953 * Free a chunk, and possibly the page it's on, if the page becomes empty.
956 static __inline__ void
957 free_bytes(void *ptr, u_long index, struct pginfo *info)
963 /* Find the chunk number on the page */
964 i = ((u_long)ptr & malloc_pagemask) >> info->shift;
966 if (((u_long)ptr & (info->size-1))) {
967 wrtwarning("modified (chunk-) pointer\n");
971 if (info->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
972 wrtwarning("chunk is already free\n");
977 memset(ptr, SOME_JUNK, info->size);
979 info->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
982 mp = page_dir + info->shift;
984 if (info->free == 1) {
986 /* Page became non-full */
988 mp = page_dir + info->shift;
989 /* Insert in address order */
990 while (*mp && (*mp)->next && (*mp)->next->page < info->page)
997 if (info->free != info->total)
1000 /* Find & remove this page in the queue */
1001 while (*mp != info) {
1002 mp = &((*mp)->next);
1005 wrterror("(ES): Not on queue\n");
1006 #endif /* EXTRA_SANITY */
1010 /* Free the page & the info structure if need be */
1011 page_dir[ptr2index(info->page)] = MALLOC_FIRST;
1012 vp = info->page; /* Order is important ! */
1013 if(vp != (void*)info)
1021 struct pginfo *info;
1028 if (!malloc_started) {
1029 wrtwarning("malloc() has never been called\n");
1033 /* If we're already sinking, don't make matters any worse. */
1037 index = ptr2index(ptr);
1039 if (index < malloc_pageshift) {
1040 wrtwarning("junk pointer, too low to make sense\n");
1044 if (index > last_index) {
1045 wrtwarning("junk pointer, too high to make sense\n");
1049 info = page_dir[index];
1051 if (info < MALLOC_MAGIC)
1052 free_pages(ptr, index, info);
1054 free_bytes(ptr, index, info);
1059 * These are the public exported interface routines.
1069 malloc_func = " in malloc():";
1070 if (malloc_active++) {
1071 wrtwarning("recursive call\n");
1076 if (!malloc_started)
1078 if (malloc_sysv && !size)
1085 if (malloc_xmalloc && !r)
1086 wrterror("out of memory\n");
1094 malloc_func = " in free():";
1095 if (malloc_active++) {
1096 wrtwarning("recursive call\n");
1110 realloc(void *ptr, size_t size)
1116 malloc_func = " in realloc():";
1117 if (malloc_active++) {
1118 wrtwarning("recursive call\n");
1123 if (ptr && !malloc_started) {
1124 wrtwarning("malloc() has never been called\n");
1127 if (!malloc_started)
1129 if (malloc_sysv && !size) {
1136 r = irealloc(ptr, size);
1139 UTRACE(ptr, size, r);
1142 if (malloc_xmalloc && err)
1143 wrterror("out of memory\n");