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.9 2005/04/26 05:51:00 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
53 * Make malloc/free/realloc thread-safe in libc for use with
56 # include "libc_private.h"
57 # include "spinlock.h"
58 static spinlock_t thread_lock = _SPINLOCK_INITIALIZER;
59 # define THREAD_LOCK() if (__isthreaded) _SPINLOCK(&thread_lock);
60 # define THREAD_UNLOCK() if (__isthreaded) _SPINUNLOCK(&thread_lock);
61 #endif /* __FreeBSD__ || __DragonFly__ */
63 #if defined(__sparc__) && defined(sun)
64 # define malloc_pageshift 12U
65 # define malloc_minsize 16U
68 # define MMAP_FD fdzero
69 # define INIT_MMAP() \
70 { if ((fdzero = _open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
71 wrterror("open of /dev/zero"); }
72 # define MADV_FREE MADV_DONTNEED
73 #endif /* __sparc__ */
75 /* Insert your combination here... */
76 #if defined(__FOOCPU__) && defined(__BAROS__)
77 # define malloc_pageshift 12U
78 # define malloc_minsize 16U
79 #endif /* __FOOCPU__ && __BAROS__ */
83 * No user serviceable parts behind this point.
85 #include <sys/types.h>
95 #include "un-namespace.h"
98 * This structure describes a page worth of chunks.
102 struct pginfo *next; /* next on the free list */
103 void *page; /* Pointer to the page */
104 u_short size; /* size of this page's chunks */
105 u_short shift; /* How far to shift for this size chunks */
106 u_short free; /* How many free chunks */
107 u_short total; /* How many chunk */
108 u_int bits[1]; /* Which chunks are free */
112 * This structure describes a number of free pages.
116 struct pgfree *next; /* next run of free pages */
117 struct pgfree *prev; /* prev run of free pages */
118 void *page; /* pointer to free pages */
119 void *end; /* pointer to end of free pages */
120 size_t size; /* number of bytes free */
124 * How many bits per u_int in the bitmap.
125 * Change only if not 8 bits/byte
127 #define MALLOC_BITS (8*sizeof(u_int))
130 * Magic values to put in the page_directory
132 #define MALLOC_NOT_MINE ((struct pginfo*) 0)
133 #define MALLOC_FREE ((struct pginfo*) 1)
134 #define MALLOC_FIRST ((struct pginfo*) 2)
135 #define MALLOC_FOLLOW ((struct pginfo*) 3)
136 #define MALLOC_MAGIC ((struct pginfo*) 4)
138 #ifndef malloc_pageshift
139 #define malloc_pageshift 12U
142 #ifndef malloc_minsize
143 #define malloc_minsize 16U
146 #if !defined(malloc_pagesize)
147 #define malloc_pagesize (1UL<<malloc_pageshift)
150 #if ((1<<malloc_pageshift) != malloc_pagesize)
151 #error "(1<<malloc_pageshift) != malloc_pagesize"
154 #ifndef malloc_maxsize
155 #define malloc_maxsize ((malloc_pagesize)>>1)
158 /* A mask for the offset inside a page. */
159 #define malloc_pagemask ((malloc_pagesize)-1)
161 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
162 #define ptr2index(foo) (((u_long)(foo) >> malloc_pageshift)-malloc_origo)
165 #define THREAD_LOCK()
168 #ifndef THREAD_UNLOCK
169 #define THREAD_UNLOCK()
180 /* Set when initialization has been done */
181 static unsigned malloc_started;
183 /* Recusion flag for public interface. */
184 static int malloc_active;
186 /* Number of free pages we cache */
187 static unsigned malloc_cache = 16;
189 /* The offset from pagenumber to index into the page directory */
190 static u_long malloc_origo;
192 /* The last index in the page directory we care about */
193 static u_long last_index;
195 /* Pointer to page directory. Allocated "as if with" malloc */
196 static struct pginfo **page_dir;
198 /* How many slots in the page directory */
199 static unsigned malloc_ninfo;
201 /* Free pages line up here */
202 static struct pgfree free_list;
204 /* Abort(), user doesn't handle problems. */
205 static int malloc_abort;
207 /* Are we trying to die ? */
210 /* always realloc ? */
211 static int malloc_realloc;
213 /* pass the kernel a hint on free pages ? */
214 static int malloc_hint = 0;
216 /* xmalloc behaviour ? */
217 static int malloc_xmalloc;
219 /* sysv behaviour for malloc(0) ? */
220 static int malloc_sysv;
223 static int malloc_zero;
226 static int malloc_junk;
229 static int malloc_utrace;
231 struct ut { void *p; size_t s; void *r; };
233 void utrace (struct ut *, int);
235 #define UTRACE(a, b, c) \
237 {struct ut u; u.p=a; u.s = b; u.r=c; utrace(&u, sizeof u);}
240 static void *malloc_brk;
242 /* one location cache for free-list holders */
243 static struct pgfree *px;
245 /* compile-time options */
246 char *malloc_options;
248 /* Name of the current public function */
249 static char *malloc_func;
253 mmap(0, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
257 * Necessary function declarations
259 static int extend_pgdir(u_long index);
260 static void *imalloc(size_t size);
261 static void ifree(void *ptr);
262 static void *irealloc(void *ptr, size_t size);
265 wrterror(const char *p)
267 const char *progname = getprogname();
268 const char *q = " error: ";
270 _write(STDERR_FILENO, progname, strlen(progname));
271 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
272 _write(STDERR_FILENO, q, strlen(q));
273 _write(STDERR_FILENO, p, strlen(p));
279 wrtwarning(const char *p)
281 const char *progname = getprogname();
282 const char *q = " warning: ";
286 _write(STDERR_FILENO, progname, strlen(progname));
287 _write(STDERR_FILENO, malloc_func, strlen(malloc_func));
288 _write(STDERR_FILENO, q, strlen(q));
289 _write(STDERR_FILENO, p, strlen(p));
293 * Allocate a number of pages from the OS
296 map_pages(size_t pages)
298 caddr_t result, tail;
300 result = (caddr_t)pageround((u_long)sbrk(0));
301 tail = result + (pages << malloc_pageshift);
305 wrterror("(ES): map_pages fails\n");
306 #endif /* EXTRA_SANITY */
310 last_index = ptr2index(tail) - 1;
313 if ((last_index+1) >= malloc_ninfo && !extend_pgdir(last_index))
320 * Extend page directory
323 extend_pgdir(u_long index)
325 struct pginfo **new, **old;
328 /* Make it this many pages */
329 i = index * sizeof *page_dir;
330 i /= malloc_pagesize;
333 /* remember the old mapping size */
334 oldlen = malloc_ninfo * sizeof *page_dir;
337 * NOTE: we allocate new pages and copy the directory rather than tempt
338 * fate by trying to "grow" the region.. There is nothing to prevent
339 * us from accidently re-mapping space that's been allocated by our caller
340 * via dlopen() or other mmap().
342 * The copy problem is not too bad, as there is 4K of page index per
343 * 4MB of malloc arena.
345 * We can totally avoid the copy if we open a file descriptor to associate
346 * the anon mappings with. Then, when we remap the pages at the new
347 * address, the old pages will be "magically" remapped.. But this means
348 * keeping open a "secret" file descriptor.....
352 new = (struct pginfo**) MMAP(i * malloc_pagesize);
353 if (new == (struct pginfo **)-1)
356 /* Copy the old stuff */
357 memcpy(new, page_dir,
358 malloc_ninfo * sizeof *page_dir);
360 /* register the new size */
361 malloc_ninfo = i * malloc_pagesize / sizeof *page_dir;
363 /* swap the pointers */
367 /* Now free the old stuff */
373 * Initialize the world
386 #endif /* EXTRA_SANITY */
388 for (i = 0; i < 3; i++) {
391 j = readlink("/etc/malloc.conf", b, sizeof b - 1);
398 p = getenv("MALLOC_OPTIONS");
402 for (; p && *p; p++) {
404 case '>': malloc_cache <<= 1; break;
405 case '<': malloc_cache >>= 1; break;
406 case 'a': malloc_abort = 0; break;
407 case 'A': malloc_abort = 1; break;
408 case 'h': malloc_hint = 0; break;
409 case 'H': malloc_hint = 1; break;
410 case 'r': malloc_realloc = 0; break;
411 case 'R': malloc_realloc = 1; break;
412 case 'j': malloc_junk = 0; break;
413 case 'J': malloc_junk = 1; break;
414 case 'u': malloc_utrace = 0; break;
415 case 'U': malloc_utrace = 1; break;
416 case 'v': malloc_sysv = 0; break;
417 case 'V': malloc_sysv = 1; break;
418 case 'x': malloc_xmalloc = 0; break;
419 case 'X': malloc_xmalloc = 1; break;
420 case 'z': malloc_zero = 0; break;
421 case 'Z': malloc_zero = 1; break;
425 wrtwarning("unknown char in MALLOC_OPTIONS\n");
435 * We want junk in the entire allocation, and zero only in the part
436 * the user asked for.
442 * If we run with junk (or implicitly from above: zero), we want to
443 * force realloc() to get new storage, so we can DTRT with it.
448 /* Allocate one page for the page directory */
449 page_dir = (struct pginfo **) MMAP(malloc_pagesize);
451 if (page_dir == (struct pginfo **) -1)
452 wrterror("mmap(2) failed, check limits\n");
455 * We need a maximum of malloc_pageshift buckets, steal these from the
456 * front of the page_directory;
458 malloc_origo = ((u_long)pageround((u_long)sbrk(0))) >> malloc_pageshift;
459 malloc_origo -= malloc_pageshift;
461 malloc_ninfo = malloc_pagesize / sizeof *page_dir;
463 /* Recalculate the cache size in bytes, and make sure it's nonzero */
468 malloc_cache <<= malloc_pageshift;
471 * This is a nice hack from Kaleb Keithly (kaleb@x.org).
472 * We can sbrk(2) further back when we keep this on a low address.
474 px = (struct pgfree *) imalloc (sizeof *px);
476 /* Been here, done that */
481 * Allocate a number of complete pages
484 malloc_pages(size_t size)
486 void *p, *delay_free = 0;
491 size = pageround(size);
495 /* Look for free pages before asking for more */
496 for(pf = free_list.next; pf; pf = pf->next) {
499 if (pf->size & malloc_pagemask)
500 wrterror("(ES): junk length entry on free_list\n");
502 wrterror("(ES): zero length entry on free_list\n");
503 if (pf->page == pf->end)
504 wrterror("(ES): zero entry on free_list\n");
505 if (pf->page > pf->end)
506 wrterror("(ES): sick entry on free_list\n");
507 if ((void*)pf->page >= (void*)sbrk(0))
508 wrterror("(ES): entry on free_list past brk\n");
509 if (page_dir[ptr2index(pf->page)] != MALLOC_FREE)
510 wrterror("(ES): non-free first page on free-list\n");
511 if (page_dir[ptr2index(pf->end)-1] != MALLOC_FREE)
512 wrterror("(ES): non-free last page on free-list\n");
513 #endif /* EXTRA_SANITY */
518 if (pf->size == size) {
521 pf->next->prev = pf->prev;
522 pf->prev->next = pf->next;
528 pf->page = (char *)pf->page + size;
534 if (p && page_dir[ptr2index(p)] != MALLOC_FREE)
535 wrterror("(ES): allocated non-free page on free-list\n");
536 #endif /* EXTRA_SANITY */
538 size >>= malloc_pageshift;
546 index = ptr2index(p);
547 page_dir[index] = MALLOC_FIRST;
549 page_dir[index+i] = MALLOC_FOLLOW;
552 memset(p, SOME_JUNK, size << malloc_pageshift);
566 * Allocate a page of fragments
569 static __inline__ int
570 malloc_make_chunks(int bits)
576 /* Allocate a new bucket */
577 pp = malloc_pages(malloc_pagesize);
581 /* Find length of admin structure */
582 l = offsetof(struct pginfo, bits[0]);
583 l += sizeof bp->bits[0] *
584 (((malloc_pagesize >> bits)+MALLOC_BITS-1) / MALLOC_BITS);
586 /* Don't waste more than two chunks on this */
587 if ((1<<(bits)) <= l+l) {
588 bp = (struct pginfo *)pp;
590 bp = (struct pginfo *)imalloc(l);
597 bp->size = (1<<bits);
599 bp->total = bp->free = malloc_pagesize >> bits;
602 /* set all valid bits in the bitmap */
606 /* Do a bunch at a time */
607 for(;k-i >= MALLOC_BITS; i += MALLOC_BITS)
608 bp->bits[i / MALLOC_BITS] = ~0;
611 bp->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
613 if (bp == bp->page) {
614 /* Mark the ones we stole for ourselves */
616 bp->bits[i/MALLOC_BITS] &= ~(1<<(i%MALLOC_BITS));
625 page_dir[ptr2index(pp)] = bp;
627 bp->next = page_dir[bits];
636 * Allocate a fragment
639 malloc_bytes(size_t size)
647 /* Don't bother with anything less than this */
648 if (size < malloc_minsize)
649 size = malloc_minsize;
651 /* Find the right bucket */
657 /* If it's empty, make a page more of that size chunks */
658 if (!page_dir[j] && !malloc_make_chunks(j))
663 /* Find first word of bitmap which isn't empty */
664 for (lp = bp->bits; !*lp; lp++)
667 /* Find that bit, and tweak it */
676 /* If there are no more free, remove from free-list */
678 page_dir[j] = bp->next;
682 /* Adjust to the real offset of that chunk */
683 k += (lp-bp->bits)*MALLOC_BITS;
687 memset((u_char*)bp->page + k, SOME_JUNK, bp->size);
689 return (u_char *)bp->page + k;
693 * Allocate a piece of memory
703 if ((size + malloc_pagesize) < size) /* Check for overflow */
705 else if (size <= malloc_maxsize)
706 result = malloc_bytes(size);
708 result = malloc_pages(size);
710 if (malloc_zero && result)
711 memset(result, 0, size);
717 * Change the size of an allocation.
720 irealloc(void *ptr, size_t size)
730 index = ptr2index(ptr);
732 if (index < malloc_pageshift) {
733 wrtwarning("junk pointer, too low to make sense\n");
737 if (index > last_index) {
738 wrtwarning("junk pointer, too high to make sense\n");
742 mp = &page_dir[index];
744 if (*mp == MALLOC_FIRST) { /* Page allocation */
746 /* Check the pointer */
747 if ((u_long)ptr & malloc_pagemask) {
748 wrtwarning("modified (page-) pointer\n");
752 /* Find the size in bytes */
753 for (osize = malloc_pagesize; *++mp == MALLOC_FOLLOW;)
754 osize += malloc_pagesize;
756 if (!malloc_realloc && /* unless we have to, */
757 size <= osize && /* .. or are too small, */
758 size > (osize - malloc_pagesize)) { /* .. or can free a page, */
759 return ptr; /* don't do anything. */
762 } else if (*mp >= MALLOC_MAGIC) { /* Chunk allocation */
764 /* Check the pointer for sane values */
765 if (((u_long)ptr & ((*mp)->size-1))) {
766 wrtwarning("modified (chunk-) pointer\n");
770 /* Find the chunk index in the page */
771 i = ((u_long)ptr & malloc_pagemask) >> (*mp)->shift;
773 /* Verify that it isn't a free chunk already */
774 if ((*mp)->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
775 wrtwarning("chunk is already free\n");
781 if (!malloc_realloc && /* Unless we have to, */
782 size < osize && /* ..or are too small, */
783 (size > osize/2 || /* ..or could use a smaller size, */
784 osize == malloc_minsize)) { /* ..(if there is one) */
785 return ptr; /* ..Don't do anything */
789 wrtwarning("pointer to wrong page\n");
796 /* copy the lesser of the two sizes, and free the old one */
799 else if (osize < size)
800 memcpy(p, ptr, osize);
802 memcpy(p, ptr, size);
809 * Free a sequence of pages
812 static __inline__ void
813 free_pages(void *ptr, u_long index, struct pginfo *info)
816 struct pgfree *pf, *pt=0;
820 if (info == MALLOC_FREE) {
821 wrtwarning("page is already free\n");
825 if (info != MALLOC_FIRST) {
826 wrtwarning("pointer to wrong page\n");
830 if ((u_long)ptr & malloc_pagemask) {
831 wrtwarning("modified (page-) pointer\n");
835 /* Count how many pages and mark them free at the same time */
836 page_dir[index] = MALLOC_FREE;
837 for (i = 1; page_dir[index+i] == MALLOC_FOLLOW; i++)
838 page_dir[index + i] = MALLOC_FREE;
840 l = i << malloc_pageshift;
843 memset(ptr, SOME_JUNK, l);
846 madvise(ptr, l, MADV_FREE);
848 tail = (char *)ptr+l;
850 /* add to free-list */
852 px = imalloc(sizeof *pt); /* This cannot fail... */
856 if (!free_list.next) {
858 /* Nothing on free list, put this at head */
859 px->next = free_list.next;
860 px->prev = &free_list;
867 /* Find the right spot, leave pf pointing to the modified entry. */
868 tail = (char *)ptr+l;
870 for(pf = free_list.next; pf->end < ptr && pf->next; pf = pf->next)
871 ; /* Race ahead here */
873 if (pf->page > tail) {
874 /* Insert before entry */
881 } else if (pf->end == ptr ) {
882 /* Append to the previous entry */
883 pf->end = (char *)pf->end + l;
885 if (pf->next && pf->end == pf->next->page ) {
886 /* And collapse the next too. */
889 pf->size += pt->size;
894 } else if (pf->page == tail) {
895 /* Prepend to entry */
898 } else if (!pf->next) {
899 /* Append at tail of chain */
906 wrterror("freelist is destroyed\n");
910 /* Return something to OS ? */
911 if (!pf->next && /* If we're the last one, */
912 pf->size > malloc_cache && /* ..and the cache is full, */
913 pf->end == malloc_brk && /* ..and none behind us, */
914 malloc_brk == sbrk(0)) { /* ..and it's OK to do... */
917 * Keep the cache intact. Notice that the '>' above guarantees that
918 * the pf will always have at least one page afterwards.
920 pf->end = (char *)pf->page + malloc_cache;
921 pf->size = malloc_cache;
924 malloc_brk = pf->end;
926 index = ptr2index(pf->end);
927 last_index = index - 1;
929 for(i=index;i <= last_index;)
930 page_dir[i++] = MALLOC_NOT_MINE;
932 /* XXX: We could realloc/shrink the pagedir here I guess. */
939 * Free a chunk, and possibly the page it's on, if the page becomes empty.
942 static __inline__ void
943 free_bytes(void *ptr, u_long index, struct pginfo *info)
949 /* Find the chunk number on the page */
950 i = ((u_long)ptr & malloc_pagemask) >> info->shift;
952 if (((u_long)ptr & (info->size-1))) {
953 wrtwarning("modified (chunk-) pointer\n");
957 if (info->bits[i/MALLOC_BITS] & (1<<(i%MALLOC_BITS))) {
958 wrtwarning("chunk is already free\n");
963 memset(ptr, SOME_JUNK, info->size);
965 info->bits[i/MALLOC_BITS] |= 1<<(i%MALLOC_BITS);
968 mp = page_dir + info->shift;
970 if (info->free == 1) {
972 /* Page became non-full */
974 mp = page_dir + info->shift;
975 /* Insert in address order */
976 while (*mp && (*mp)->next && (*mp)->next->page < info->page)
983 if (info->free != info->total)
986 /* Find & remove this page in the queue */
987 while (*mp != info) {
991 wrterror("(ES): Not on queue\n");
992 #endif /* EXTRA_SANITY */
996 /* Free the page & the info structure if need be */
997 page_dir[ptr2index(info->page)] = MALLOC_FIRST;
998 vp = info->page; /* Order is important ! */
999 if(vp != (void*)info)
1007 struct pginfo *info;
1014 if (!malloc_started) {
1015 wrtwarning("malloc() has never been called\n");
1019 /* If we're already sinking, don't make matters any worse. */
1023 index = ptr2index(ptr);
1025 if (index < malloc_pageshift) {
1026 wrtwarning("junk pointer, too low to make sense\n");
1030 if (index > last_index) {
1031 wrtwarning("junk pointer, too high to make sense\n");
1035 info = page_dir[index];
1037 if (info < MALLOC_MAGIC)
1038 free_pages(ptr, index, info);
1040 free_bytes(ptr, index, info);
1045 * These are the public exported interface routines.
1055 malloc_func = " in malloc():";
1056 if (malloc_active++) {
1057 wrtwarning("recursive call\n");
1062 if (!malloc_started)
1064 if (malloc_sysv && !size)
1071 if (malloc_xmalloc && !r)
1072 wrterror("out of memory\n");
1080 malloc_func = " in free():";
1081 if (malloc_active++) {
1082 wrtwarning("recursive call\n");
1096 realloc(void *ptr, size_t size)
1102 malloc_func = " in realloc():";
1103 if (malloc_active++) {
1104 wrtwarning("recursive call\n");
1109 if (ptr && !malloc_started) {
1110 wrtwarning("malloc() has never been called\n");
1113 if (!malloc_started)
1115 if (malloc_sysv && !size) {
1122 r = irealloc(ptr, size);
1125 UTRACE(ptr, size, r);
1128 if (malloc_xmalloc && err)
1129 wrterror("out of memory\n");