1 /* $NetBSD: malloc.c,v 1.52 2008/02/03 22:56:53 christos Exp $ */
4 * ----------------------------------------------------------------------------
5 * "THE BEER-WARE LICENSE" (Revision 42):
6 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
7 * can do whatever you want with this stuff. If we meet some day, and you think
8 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
9 * ----------------------------------------------------------------------------
11 * From FreeBSD: malloc.c,v 1.91 2006/01/12 07:28:20 jasone
16 #define mmap minix_mmap
17 #define munmap minix_munmap
19 #include <minix/sysutil.h>
20 #define MALLOC_NO_SYSCALLS
21 #define wrtwarning(w) printf("libminc malloc warning: %s\n", w)
22 #define wrterror(w) panic("libminc malloc error: %s\n", w)
27 * Defining MALLOC_EXTRA_SANITY will enable extra checks which are related
28 * to internal conditions and consistency in malloc.c. This has a
29 * noticeable runtime performance hit, and generally will not do you
30 * any good unless you fiddle with the internals of malloc or want
31 * to catch random pointer corruption as early as possible.
33 #ifndef MALLOC_EXTRA_SANITY
34 #undef MALLOC_EXTRA_SANITY
38 * What to use for Junk. This is the byte value we use to fill with
39 * when the 'J' option is enabled.
41 #define SOME_JUNK 0xd0 /* as in "Duh" :-) */
44 * The basic parameters you can tweak.
46 * malloc_minsize minimum size of an allocation in bytes.
47 * If this is too small it's too much work
48 * to manage them. This is also the smallest
49 * unit of alignment used for the storage
50 * returned by malloc/realloc.
54 #include "namespace.h"
55 #if defined(__FreeBSD__)
56 # if defined(__i386__)
57 # define malloc_minsize 16U
59 # if defined(__ia64__)
60 # define malloc_pageshift 13U
61 # define malloc_minsize 16U
63 # if defined(__alpha__)
64 # define malloc_pageshift 13U
65 # define malloc_minsize 16U
67 # if defined(__sparc64__)
68 # define malloc_pageshift 13U
69 # define malloc_minsize 16U
71 # if defined(__amd64__)
72 # define malloc_pageshift 12U
73 # define malloc_minsize 16U
76 # define malloc_pageshift 12U
77 # define malloc_minsize 16U
84 #include <sys/cdefs.h>
85 void utrace(struct ut
*, int);
88 * Make malloc/free/realloc thread-safe in libc for use with
91 # include "libc_private.h"
92 # include "spinlock.h"
93 static spinlock_t thread_lock
= _SPINLOCK_INITIALIZER
;
94 # define _MALLOC_LOCK() if (__isthreaded) _SPINLOCK(&thread_lock);
95 # define _MALLOC_UNLOCK() if (__isthreaded) _SPINUNLOCK(&thread_lock);
96 #endif /* __FreeBSD__ */
100 #include <sys/types.h>
101 #if defined(__NetBSD__)
102 # define malloc_minsize 16U
104 # define UTRACE_LABEL "malloc",
105 #include <sys/cdefs.h>
107 #if defined(LIBC_SCCS) && !defined(lint)
108 __RCSID("$NetBSD: malloc.c,v 1.52 2008/02/03 22:56:53 christos Exp $");
109 #endif /* LIBC_SCCS and not lint */
110 int utrace(const char *, void *, size_t);
112 #include <reentrant.h>
113 extern int __isthreaded
;
114 static mutex_t thread_lock
= MUTEX_INITIALIZER
;
115 #define _MALLOC_LOCK() if (__isthreaded) mutex_lock(&thread_lock);
116 #define _MALLOC_UNLOCK() if (__isthreaded) mutex_unlock(&thread_lock);
117 #endif /* __NetBSD__ */
119 #if defined(__sparc__) && defined(sun)
120 # define malloc_minsize 16U
121 # define MAP_ANON (0)
123 # define MMAP_FD fdzero
124 # define INIT_MMAP() \
125 { if ((fdzero = open(_PATH_DEVZERO, O_RDWR, 0000)) == -1) \
126 wrterror("open of /dev/zero"); }
127 #endif /* __sparc__ */
129 /* Insert your combination here... */
130 #if defined(__FOOCPU__) && defined(__BAROS__)
131 # define malloc_minsize 16U
132 #endif /* __FOOCPU__ && __BAROS__ */
135 #define ZEROSIZEPTR ((void *)(uintptr_t)(1UL << (malloc_pageshift - 1)))
139 * No user serviceable parts behind this point.
141 #include <sys/types.h>
142 #include <sys/mman.h>
153 * This structure describes a page worth of chunks.
157 struct pginfo
*next
; /* next on the free list */
158 void *page
; /* Pointer to the page */
159 u_short size
; /* size of this page's chunks */
160 u_short shift
; /* How far to shift for this size chunks */
161 u_short free
; /* How many free chunks */
162 u_short total
; /* How many chunk */
163 u_int bits
[1]; /* Which chunks are free */
167 * This structure describes a number of free pages.
171 struct pgfree
*next
; /* next run of free pages */
172 struct pgfree
*prev
; /* prev run of free pages */
173 void *page
; /* pointer to free pages */
174 void *end
; /* pointer to end of free pages */
175 size_t size
; /* number of bytes free */
179 * How many bits per u_int in the bitmap.
180 * Change only if not 8 bits/byte
182 #define MALLOC_BITS ((int)(8*sizeof(u_int)))
185 * Magic values to put in the page_directory
187 #define MALLOC_NOT_MINE ((struct pginfo*) 0)
188 #define MALLOC_FREE ((struct pginfo*) 1)
189 #define MALLOC_FIRST ((struct pginfo*) 2)
190 #define MALLOC_FOLLOW ((struct pginfo*) 3)
191 #define MALLOC_MAGIC ((struct pginfo*) 4)
194 * Page size related parameters, computed at run-time.
196 static size_t malloc_pagesize
;
197 static size_t malloc_pageshift
;
198 static size_t malloc_pagemask
;
200 #ifndef malloc_minsize
201 #define malloc_minsize 16U
204 #ifndef malloc_maxsize
205 #define malloc_maxsize ((malloc_pagesize)>>1)
208 #define pageround(foo) (((foo) + (malloc_pagemask))&(~(malloc_pagemask)))
209 #define ptr2idx(foo) \
210 (((size_t)(uintptr_t)(foo) >> malloc_pageshift)-malloc_origo)
213 #define _MALLOC_LOCK()
216 #ifndef _MALLOC_UNLOCK
217 #define _MALLOC_UNLOCK()
230 #define MADV_FREE MADV_DONTNEED
232 #endif /* !__minix */
234 /* Number of free pages we cache */
235 static size_t malloc_cache
= 16;
237 /* The offset from pagenumber to index into the page directory */
238 static size_t malloc_origo
;
240 /* The last index in the page directory we care about */
241 static size_t last_idx
;
243 /* Pointer to page directory. Allocated "as if with" malloc */
244 static struct pginfo
**page_dir
;
246 /* How many slots in the page directory */
247 static size_t malloc_ninfo
;
249 /* Free pages line up here */
250 static struct pgfree free_list
;
252 /* Abort(), user doesn't handle problems. */
253 static int malloc_abort
;
255 /* Are we trying to die ? */
258 /* always realloc ? */
259 static int malloc_realloc
;
261 /* pass the kernel a hint on free pages ? */
262 #if defined(MADV_FREE)
263 static int malloc_hint
= 0;
266 /* xmalloc behaviour ? */
267 static int malloc_xmalloc
;
269 /* sysv behaviour for malloc(0) ? */
270 static int malloc_sysv
;
273 static int malloc_zero
;
276 static int malloc_junk
;
281 static int malloc_utrace
;
283 struct ut
{ void *p
; size_t s
; void *r
; };
285 #define UTRACE(a, b, c) \
286 if (malloc_utrace) { \
288 u.p=a; u.s = b; u.r=c; \
289 utrace(UTRACE_LABEL (void *) &u, sizeof u); \
291 #else /* !HAS_UTRACE */
292 #define UTRACE(a,b,c)
293 #endif /* HAS_UTRACE */
296 static void *malloc_brk
;
298 /* one location cache for free-list holders */
299 static struct pgfree
*px
;
301 /* compile-time options */
302 const char *_malloc_options
;
304 /* Name of the current public function */
305 static const char *malloc_func
;
309 mmap(NULL, (size), PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, \
313 * Necessary function declarations
315 static int extend_pgdir(size_t idx
);
316 static void *imalloc(size_t size
);
317 static void ifree(void *ptr
);
318 static void *irealloc(void *ptr
, size_t size
);
320 #ifndef MALLOC_NO_SYSCALLS
322 wrtmessage(const char *p1
, const char *p2
, const char *p3
, const char *p4
)
325 write(STDERR_FILENO
, p1
, strlen(p1
));
326 write(STDERR_FILENO
, p2
, strlen(p2
));
327 write(STDERR_FILENO
, p3
, strlen(p3
));
328 write(STDERR_FILENO
, p4
, strlen(p4
));
331 void (*_malloc_message
)(const char *p1
, const char *p2
, const char *p3
,
332 const char *p4
) = wrtmessage
;
334 wrterror(const char *p
)
338 _malloc_message(getprogname(), malloc_func
, " error: ", p
);
343 wrtwarning(const char *p
)
347 * Sensitive processes, somewhat arbitrarily defined here as setuid,
348 * setgid, root and wheel cannot afford to have malloc mistakes.
350 if (malloc_abort
|| issetugid() || getuid() == 0 || getgid() == 0)
356 * Allocate a number of pages from the OS
359 map_pages(size_t pages
)
361 caddr_t result
, rresult
, tail
;
362 intptr_t bytes
= pages
<< malloc_pageshift
;
364 if (bytes
< 0 || (size_t)bytes
< pages
) {
369 if ((result
= sbrk(bytes
)) == (void *)-1)
373 * Round to a page, in case sbrk(2) did not do this for us
375 rresult
= (caddr_t
)pageround((size_t)(uintptr_t)result
);
376 if (result
< rresult
) {
377 /* make sure we have enough space to fit bytes */
378 if (sbrk((intptr_t)(rresult
- result
)) == (void *) -1) {
379 /* we failed, put everything back */
381 wrterror("brk(2) failed [internal error]\n");
385 tail
= rresult
+ (size_t)bytes
;
387 last_idx
= ptr2idx(tail
) - 1;
390 if ((last_idx
+1) >= malloc_ninfo
&& !extend_pgdir(last_idx
)) {
392 last_idx
= ptr2idx(malloc_brk
) - 1;
393 /* Put back break point since we failed. */
395 wrterror("brk(2) failed [internal error]\n");
403 * Extend page directory
406 extend_pgdir(size_t idx
)
408 struct pginfo
**new, **old
;
409 size_t newlen
, oldlen
;
411 /* check for overflow */
412 if ((((~(1UL << ((sizeof(size_t) * NBBY
) - 1)) / sizeof(*page_dir
)) + 1)
413 + (malloc_pagesize
/ sizeof *page_dir
)) < idx
) {
418 /* Make it this many pages */
419 newlen
= pageround(idx
* sizeof *page_dir
) + malloc_pagesize
;
421 /* remember the old mapping size */
422 oldlen
= malloc_ninfo
* sizeof *page_dir
;
425 * NOTE: we allocate new pages and copy the directory rather than tempt
426 * fate by trying to "grow" the region.. There is nothing to prevent
427 * us from accidentally re-mapping space that's been allocated by our caller
428 * via dlopen() or other mmap().
430 * The copy problem is not too bad, as there is 4K of page index per
431 * 4MB of malloc arena.
433 * We can totally avoid the copy if we open a file descriptor to associate
434 * the anon mappings with. Then, when we remap the pages at the new
435 * address, the old pages will be "magically" remapped.. But this means
436 * keeping open a "secret" file descriptor.....
441 if (new == MAP_FAILED
)
444 /* Copy the old stuff */
445 memcpy(new, page_dir
, oldlen
);
447 /* register the new size */
448 malloc_ninfo
= newlen
/ sizeof *page_dir
;
450 /* swap the pointers */
454 /* Now free the old stuff */
460 * Initialize the world
465 int save_errno
= errno
;
466 #ifndef MALLOC_NO_SYSCALLS
473 * Compute page-size related variables.
475 malloc_pagesize
= (size_t)sysconf(_SC_PAGESIZE
);
477 malloc_pagesize
= PAGE_SIZE
;
479 malloc_pagemask
= malloc_pagesize
- 1;
480 for (malloc_pageshift
= 0;
481 (1UL << malloc_pageshift
) != malloc_pagesize
;
487 #ifdef MALLOC_EXTRA_SANITY
489 #endif /* MALLOC_EXTRA_SANITY */
491 #ifndef MALLOC_NO_SYSCALLS
492 for (i
= 0; i
< 3; i
++) {
494 j
= readlink("/etc/malloc.conf", b
, sizeof b
- 1);
499 } else if (i
== 1 && issetugid() == 0) {
500 p
= getenv("MALLOC_OPTIONS");
506 for (; p
!= NULL
&& *p
!= '\0'; p
++) {
508 case '>': malloc_cache
<<= 1; break;
509 case '<': malloc_cache
>>= 1; break;
510 case 'a': malloc_abort
= 0; break;
511 case 'A': malloc_abort
= 1; break;
513 case 'h': malloc_hint
= 0; break;
514 case 'H': malloc_hint
= 1; break;
515 #endif /* !__minix */
516 case 'r': malloc_realloc
= 0; break;
517 case 'R': malloc_realloc
= 1; break;
518 case 'j': malloc_junk
= 0; break;
519 case 'J': malloc_junk
= 1; break;
521 case 'u': malloc_utrace
= 0; break;
522 case 'U': malloc_utrace
= 1; break;
524 case 'v': malloc_sysv
= 0; break;
525 case 'V': malloc_sysv
= 1; break;
526 case 'x': malloc_xmalloc
= 0; break;
527 case 'X': malloc_xmalloc
= 1; break;
528 case 'z': malloc_zero
= 0; break;
529 case 'Z': malloc_zero
= 1; break;
531 _malloc_message(getprogname(), malloc_func
,
532 " warning: ", "unknown char in MALLOC_OPTIONS\n");
542 * We want junk in the entire allocation, and zero only in the part
543 * the user asked for.
548 /* Allocate one page for the page directory */
549 page_dir
= MMAP(malloc_pagesize
);
551 if (page_dir
== MAP_FAILED
)
552 wrterror("mmap(2) failed, check limits.\n");
555 * We need a maximum of malloc_pageshift buckets, steal these from the
556 * front of the page_directory;
558 malloc_origo
= pageround((size_t)(uintptr_t)sbrk((intptr_t)0))
560 malloc_origo
-= malloc_pageshift
;
562 malloc_ninfo
= malloc_pagesize
/ sizeof *page_dir
;
564 /* Recalculate the cache size in bytes, and make sure it's nonzero */
569 malloc_cache
<<= malloc_pageshift
;
572 * This is a nice hack from Kaleb Keithly (kaleb@x.org).
573 * We can sbrk(2) further back when we keep this on a low address.
575 px
= imalloc(sizeof *px
);
581 * Allocate a number of complete pages
584 malloc_pages(size_t size
)
586 void *p
, *delay_free
= NULL
;
591 idx
= pageround(size
);
600 /* Look for free pages before asking for more */
601 for(pf
= free_list
.next
; pf
; pf
= pf
->next
) {
603 #ifdef MALLOC_EXTRA_SANITY
604 if (pf
->size
& malloc_pagemask
)
605 wrterror("(ES): junk length entry on free_list.\n");
607 wrterror("(ES): zero length entry on free_list.\n");
608 if (pf
->page
== pf
->end
)
609 wrterror("(ES): zero entry on free_list.\n");
610 if (pf
->page
> pf
->end
)
611 wrterror("(ES): sick entry on free_list.\n");
612 if ((void*)pf
->page
>= (void*)sbrk(0))
613 wrterror("(ES): entry on free_list past brk.\n");
614 if (page_dir
[ptr2idx(pf
->page
)] != MALLOC_FREE
)
615 wrterror("(ES): non-free first page on free-list.\n");
616 if (page_dir
[ptr2idx(pf
->end
)-1] != MALLOC_FREE
)
617 wrterror("(ES): non-free last page on free-list.\n");
618 #endif /* MALLOC_EXTRA_SANITY */
623 if (pf
->size
== size
) {
625 if (pf
->next
!= NULL
)
626 pf
->next
->prev
= pf
->prev
;
627 pf
->prev
->next
= pf
->next
;
633 pf
->page
= (char *)pf
->page
+ size
;
638 #ifdef MALLOC_EXTRA_SANITY
639 if (p
!= NULL
&& page_dir
[ptr2idx(p
)] != MALLOC_FREE
)
640 wrterror("(ES): allocated non-free page on free-list.\n");
641 #endif /* MALLOC_EXTRA_SANITY */
643 size
>>= malloc_pageshift
;
652 page_dir
[idx
] = MALLOC_FIRST
;
654 page_dir
[idx
+i
] = MALLOC_FOLLOW
;
657 memset(p
, SOME_JUNK
, size
<< malloc_pageshift
);
671 * Allocate a page of fragments
675 malloc_make_chunks(int bits
)
682 /* Allocate a new bucket */
683 pp
= malloc_pages(malloc_pagesize
);
687 /* Find length of admin structure */
688 l
= (long)offsetof(struct pginfo
, bits
[0]);
689 l
+= (long)sizeof bp
->bits
[0] *
690 (((malloc_pagesize
>> bits
)+MALLOC_BITS
-1) / MALLOC_BITS
);
692 /* Don't waste more than two chunks on this */
693 if ((1<<(bits
)) <= l
+l
) {
694 bp
= (struct pginfo
*)pp
;
696 bp
= imalloc((size_t)l
);
703 bp
->size
= (1<<bits
);
705 bp
->total
= bp
->free
= (u_short
)(malloc_pagesize
>> bits
);
708 /* set all valid bits in the bitmap */
712 /* Do a bunch at a time */
713 for(;k
-i
>= MALLOC_BITS
; i
+= MALLOC_BITS
)
714 bp
->bits
[i
/ MALLOC_BITS
] = ~0U;
717 bp
->bits
[i
/MALLOC_BITS
] |= 1<<(i
%MALLOC_BITS
);
719 if (bp
== bp
->page
) {
720 /* Mark the ones we stole for ourselves */
721 for(i
= 0; l
> 0; i
++) {
722 bp
->bits
[i
/ MALLOC_BITS
] &= ~(1 << (i
% MALLOC_BITS
));
725 l
-= (long)(1 << bits
);
731 page_dir
[ptr2idx(pp
)] = bp
;
733 bp
->next
= page_dir
[bits
];
742 * Allocate a fragment
745 malloc_bytes(size_t size
)
754 /* Don't bother with anything less than this */
755 if (size
< malloc_minsize
)
756 size
= malloc_minsize
;
759 /* Find the right bucket */
765 /* If it's empty, make a page more of that size chunks */
766 if (page_dir
[j
] == NULL
&& !malloc_make_chunks(j
))
771 /* Find first word of bitmap which isn't empty */
772 for (lp
= bp
->bits
; !*lp
; lp
++)
775 /* Find that bit, and tweak it */
784 /* If there are no more free, remove from free-list */
786 page_dir
[j
] = bp
->next
;
790 /* Adjust to the real offset of that chunk */
791 k
+= (lp
-bp
->bits
)*MALLOC_BITS
;
795 memset((u_char
*)bp
->page
+ k
, SOME_JUNK
, (size_t)bp
->size
);
797 return (u_char
*)bp
->page
+ k
;
801 * Allocate a piece of memory
811 if ((size
+ malloc_pagesize
) < size
) /* Check for overflow */
813 else if ((size
+ malloc_pagesize
) >= (uintptr_t)page_dir
)
815 else if (size
<= malloc_maxsize
)
816 result
= malloc_bytes(size
);
818 result
= malloc_pages(size
);
820 if (malloc_abort
&& result
== NULL
)
821 wrterror("allocation failed.\n");
823 if (malloc_zero
&& result
!= NULL
)
824 memset(result
, 0, size
);
830 * Change the size of an allocation.
833 irealloc(void *ptr
, size_t size
)
845 if (idx
< malloc_pageshift
) {
846 wrtwarning("junk pointer, too low to make sense.\n");
850 if (idx
> last_idx
) {
851 wrtwarning("junk pointer, too high to make sense.\n");
857 if (*mp
== MALLOC_FIRST
) { /* Page allocation */
859 /* Check the pointer */
860 if ((size_t)(uintptr_t)ptr
& malloc_pagemask
) {
861 wrtwarning("modified (page-) pointer.\n");
865 /* Find the size in bytes */
866 for (osize
= malloc_pagesize
; *++mp
== MALLOC_FOLLOW
;)
867 osize
+= malloc_pagesize
;
869 if (!malloc_realloc
&& /* unless we have to, */
870 size
<= osize
&& /* .. or are too small, */
871 size
> (osize
- malloc_pagesize
)) { /* .. or can free a page, */
873 memset((u_char
*)ptr
+ size
, SOME_JUNK
, osize
-size
);
874 return ptr
; /* don't do anything. */
877 } else if (*mp
>= MALLOC_MAGIC
) { /* Chunk allocation */
879 /* Check the pointer for sane values */
880 if (((size_t)(uintptr_t)ptr
& ((*mp
)->size
-1))) {
881 wrtwarning("modified (chunk-) pointer.\n");
885 /* Find the chunk index in the page */
886 i
= ((size_t)(uintptr_t)ptr
& malloc_pagemask
) >> (*mp
)->shift
;
888 /* Verify that it isn't a free chunk already */
889 if ((*mp
)->bits
[i
/MALLOC_BITS
] & (1UL << (i
% MALLOC_BITS
))) {
890 wrtwarning("chunk is already free.\n");
896 if (!malloc_realloc
&& /* Unless we have to, */
897 size
<= osize
&& /* ..or are too small, */
898 (size
> osize
/ 2 || /* ..or could use a smaller size, */
899 osize
== malloc_minsize
)) { /* ..(if there is one) */
901 memset((u_char
*)ptr
+ size
, SOME_JUNK
, osize
-size
);
902 return ptr
; /* ..Don't do anything */
906 wrtwarning("pointer to wrong page.\n");
913 /* copy the lesser of the two sizes, and free the old one */
916 else if (osize
< size
)
917 memcpy(p
, ptr
, osize
);
919 memcpy(p
, ptr
, size
);
926 * Free a sequence of pages
930 free_pages(void *ptr
, size_t idx
, struct pginfo
*info
)
933 struct pgfree
*pf
, *pt
=NULL
;
937 if (info
== MALLOC_FREE
) {
938 wrtwarning("page is already free.\n");
942 if (info
!= MALLOC_FIRST
) {
943 wrtwarning("pointer to wrong page.\n");
947 if ((size_t)(uintptr_t)ptr
& malloc_pagemask
) {
948 wrtwarning("modified (page-) pointer.\n");
952 /* Count how many pages and mark them free at the same time */
953 page_dir
[idx
] = MALLOC_FREE
;
954 for (i
= 1; page_dir
[idx
+i
] == MALLOC_FOLLOW
; i
++)
955 page_dir
[idx
+ i
] = MALLOC_FREE
;
957 l
= i
<< malloc_pageshift
;
960 memset(ptr
, SOME_JUNK
, l
);
964 madvise(ptr
, l
, MADV_FREE
);
965 #endif /* !__minix */
967 tail
= (char *)ptr
+l
;
969 /* add to free-list */
971 px
= imalloc(sizeof *px
); /* This cannot fail... */
975 if (free_list
.next
== NULL
) {
977 /* Nothing on free list, put this at head */
978 px
->next
= free_list
.next
;
979 px
->prev
= &free_list
;
986 /* Find the right spot, leave pf pointing to the modified entry. */
987 tail
= (char *)ptr
+l
;
989 for(pf
= free_list
.next
; pf
->end
< ptr
&& pf
->next
!= NULL
;
991 ; /* Race ahead here */
993 if (pf
->page
> tail
) {
994 /* Insert before entry */
1001 } else if (pf
->end
== ptr
) {
1002 /* Append to the previous entry */
1003 pf
->end
= (char *)pf
->end
+ l
;
1005 if (pf
->next
!= NULL
&& pf
->end
== pf
->next
->page
) {
1006 /* And collapse the next too. */
1009 pf
->size
+= pt
->size
;
1010 pf
->next
= pt
->next
;
1011 if (pf
->next
!= NULL
)
1012 pf
->next
->prev
= pf
;
1014 } else if (pf
->page
== tail
) {
1015 /* Prepend to entry */
1018 } else if (pf
->next
== NULL
) {
1019 /* Append at tail of chain */
1026 wrterror("freelist is destroyed.\n");
1030 /* Return something to OS ? */
1031 if (pf
->next
== NULL
&& /* If we're the last one, */
1032 pf
->size
> malloc_cache
&& /* ..and the cache is full, */
1033 pf
->end
== malloc_brk
&& /* ..and none behind us, */
1034 malloc_brk
== sbrk((intptr_t)0)) { /* ..and it's OK to do... */
1037 * Keep the cache intact. Notice that the '>' above guarantees that
1038 * the pf will always have at least one page afterwards.
1040 pf
->end
= (char *)pf
->page
+ malloc_cache
;
1041 pf
->size
= malloc_cache
;
1045 malloc_brk
= pf
->end
;
1047 idx
= ptr2idx(pf
->end
);
1049 for(i
=idx
;i
<= last_idx
;)
1050 page_dir
[i
++] = MALLOC_NOT_MINE
;
1054 /* XXX: We could realloc/shrink the pagedir here I guess. */
1061 * Free a chunk, and possibly the page it's on, if the page becomes empty.
1065 free_bytes(void *ptr
, size_t idx
, struct pginfo
*info
)
1071 /* Find the chunk number on the page */
1072 i
= ((size_t)(uintptr_t)ptr
& malloc_pagemask
) >> info
->shift
;
1074 if (((size_t)(uintptr_t)ptr
& (info
->size
-1))) {
1075 wrtwarning("modified (chunk-) pointer.\n");
1079 if (info
->bits
[i
/MALLOC_BITS
] & (1UL << (i
% MALLOC_BITS
))) {
1080 wrtwarning("chunk is already free.\n");
1085 memset(ptr
, SOME_JUNK
, (size_t)info
->size
);
1087 info
->bits
[i
/MALLOC_BITS
] |= (u_int
)(1UL << (i
% MALLOC_BITS
));
1090 mp
= page_dir
+ info
->shift
;
1092 if (info
->free
== 1) {
1094 /* Page became non-full */
1096 mp
= page_dir
+ info
->shift
;
1097 /* Insert in address order */
1098 while (*mp
&& (*mp
)->next
&& (*mp
)->next
->page
< info
->page
)
1105 if (info
->free
!= info
->total
)
1108 /* Find & remove this page in the queue */
1109 while (*mp
!= info
) {
1110 mp
= &((*mp
)->next
);
1111 #ifdef MALLOC_EXTRA_SANITY
1113 wrterror("(ES): Not on queue.\n");
1114 #endif /* MALLOC_EXTRA_SANITY */
1118 /* Free the page & the info structure if need be */
1119 page_dir
[idx
] = MALLOC_FIRST
;
1120 vp
= info
->page
; /* Order is important ! */
1121 if(vp
!= (void*)info
)
1129 struct pginfo
*info
;
1136 /* If we're already sinking, don't make matters any worse. */
1142 if (idx
< malloc_pageshift
) {
1143 wrtwarning("junk pointer, too low to make sense.\n");
1147 if (idx
> last_idx
) {
1148 wrtwarning("junk pointer, too high to make sense.\n");
1152 info
= page_dir
[idx
];
1154 if (info
< MALLOC_MAGIC
)
1155 free_pages(ptr
, idx
, info
);
1157 free_bytes(ptr
, idx
, info
);
1161 static int malloc_active
; /* Recusion flag for public interface. */
1162 static unsigned malloc_started
; /* Set when initialization has been done */
1165 pubrealloc(void *ptr
, size_t size
, const char *func
)
1171 * If a thread is inside our code with a functional lock held, and then
1172 * catches a signal which calls us again, we would get a deadlock if the
1173 * lock is not of a recursive type.
1177 if (malloc_active
> 0) {
1178 if (malloc_active
== 1) {
1179 wrtwarning("recursive call\n");
1188 if (!malloc_started
) {
1190 wrtwarning("malloc() has never been called\n");
1200 if (ptr
== ZEROSIZEPTR
)
1202 if (malloc_sysv
&& !size
) {
1210 } else if (ptr
== NULL
) {
1214 r
= irealloc(ptr
, size
);
1217 UTRACE(ptr
, size
, r
);
1220 if (malloc_xmalloc
&& err
)
1221 wrterror("out of memory\n");
1228 * These are the public exported interface routines.
1235 return pubrealloc(NULL
, size
, " in malloc():");
1239 posix_memalign(void **memptr
, size_t alignment
, size_t size
)
1244 if (!malloc_started
) {
1248 /* Make sure that alignment is a large enough power of 2. */
1249 if (((alignment
- 1) & alignment
) != 0 || alignment
< sizeof(void *) ||
1250 alignment
> malloc_pagesize
)
1254 * (size | alignment) is enough to assure the requested alignment, since
1255 * the allocator always allocates power-of-two blocks.
1257 err
= errno
; /* Protect errno against changes in pubrealloc(). */
1258 result
= pubrealloc(NULL
, (size
| alignment
), " in posix_memalign()");
1269 calloc(size_t num
, size_t size
)
1273 if (size
!= 0 && (num
* size
) / size
!= num
) {
1274 /* size_t overflow. */
1279 ret
= pubrealloc(NULL
, num
* size
, " in calloc():");
1282 memset(ret
, 0, num
* size
);
1291 pubrealloc(ptr
, 0, " in free():");
1295 realloc(void *ptr
, size_t size
)
1298 return pubrealloc(ptr
, size
, " in realloc():");
1302 * Begin library-private functions, used by threading libraries for protection
1303 * of malloc during fork(). These functions are only called if the program is
1304 * running in threaded mode, so there is no need to check whether the program
1309 _malloc_prefork(void)
1316 _malloc_postfork(void)