3 * Written by Erik Andersen <andersee@debian.org>
6 * Parts of the memalign code were stolen from malloc-930716.
21 void *malloc(size_t size)
25 if (unlikely(size == 0)) {
26 #if defined(__MALLOC_GLIBC_COMPAT__)
29 /* Some programs will call malloc (0). Lets be strict and return NULL */
34 #ifdef __ARCH_HAS_MMU__
35 result = mmap((void *) 0, size + sizeof(size_t), PROT_READ | PROT_WRITE,
36 MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
37 if (result == MAP_FAILED)
39 * (size_t *) result = size;
40 return(result + sizeof(size_t));
42 result = mmap((void *) 0, size, PROT_READ | PROT_WRITE,
43 MAP_SHARED | MAP_ANONYMOUS, 0, 0);
44 if (result == MAP_FAILED)
52 void * calloc(size_t nmemb, size_t lsize)
55 size_t size=lsize * nmemb;
57 /* guard vs integer overflow, but allow nmemb
58 * to fall through and call malloc(0) */
59 if (nmemb && lsize != (size / nmemb)) {
65 /* Standard unix mmap using /dev/zero clears memory so calloc
66 * doesn't need to actually zero anything....
69 memset(result, 0, size);
77 void *realloc(void *ptr, size_t size)
88 newptr = malloc(size);
91 #ifdef __ARCH_HAS_MMU__
92 *((size_t *) (ptr - sizeof(size_t)))
104 extern int weak_function __libc_free_aligned(void *ptr);
109 if (unlikely(__libc_free_aligned!=NULL)) {
110 if (__libc_free_aligned(ptr)) {
114 #ifdef __ARCH_HAS_MMU__
115 ptr -= sizeof(size_t);
116 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
124 #ifdef __UCLIBC_HAS_THREADS__
126 pthread_mutex_t __malloc_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
127 # define LOCK __pthread_mutex_lock(&__malloc_lock)
128 # define UNLOCK __pthread_mutex_unlock(&__malloc_lock);
134 /* List of blocks allocated with memalign or valloc */
137 struct alignlist *next;
138 __ptr_t aligned; /* The address that memaligned returned. */
139 __ptr_t exact; /* The address that malloc returned. */
141 struct alignlist *_aligned_blocks;
143 /* Return memory to the heap. */
144 int __libc_free_aligned(void *ptr)
152 for (l = _aligned_blocks; l != NULL; l = l->next) {
153 if (l->aligned == ptr) {
154 /* Mark the block as free */
157 #ifdef __ARCH_HAS_MMU__
158 ptr -= sizeof(size_t);
159 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
169 void * memalign (size_t alignment, size_t size)
172 unsigned long int adj;
174 result = malloc (size + alignment - 1);
177 adj = (unsigned long int) ((unsigned long int) ((char *) result -
178 (char *) NULL)) % alignment;
183 for (l = _aligned_blocks; l != NULL; l = l->next)
184 if (l->aligned == NULL)
185 /* This slot is free. Use it. */
189 l = (struct alignlist *) malloc (sizeof (struct alignlist));
195 l->next = _aligned_blocks;
199 result = l->aligned = (char *) result + alignment - adj;