3 * Written by Erik Andersen <andersee@codepoet.org>
6 * Parts of the memalign code were stolen from malloc-930716.
19 libc_hidden_proto(memcpy)
20 /*libc_hidden_proto(memset)*/
21 libc_hidden_proto(mmap)
22 libc_hidden_proto(munmap)
25 void *malloc(size_t size)
29 if (unlikely(size == 0)) {
30 #if defined(__MALLOC_GLIBC_COMPAT__)
33 /* Some programs will call malloc (0). Lets be strict and return NULL */
38 #ifdef __ARCH_HAS_MMU__
39 # define MMAP_FLAGS MAP_PRIVATE | MAP_ANONYMOUS
41 # define MMAP_FLAGS MAP_SHARED | MAP_ANONYMOUS
44 result = mmap((void *) 0, size + sizeof(size_t), PROT_READ | PROT_WRITE,
46 if (result == MAP_FAILED)
48 * (size_t *) result = size;
49 return(result + sizeof(size_t));
54 void * calloc(size_t nmemb, size_t lsize)
57 size_t size=lsize * nmemb;
59 /* guard vs integer overflow, but allow nmemb
60 * to fall through and call malloc(0) */
61 if (nmemb && lsize != (size / nmemb)) {
67 /* Standard unix mmap using /dev/zero clears memory so calloc
68 * doesn't need to actually zero anything....
71 memset(result, 0, size);
79 void *realloc(void *ptr, size_t size)
90 newptr = malloc(size);
92 memcpy(newptr, ptr, *((size_t *) (ptr - sizeof(size_t))));
100 extern int weak_function __libc_free_aligned(void *ptr);
103 if (unlikely(ptr == NULL))
105 if (unlikely(__libc_free_aligned != NULL)) {
106 if (__libc_free_aligned(ptr))
109 ptr -= sizeof(size_t);
110 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
115 #ifdef __UCLIBC_HAS_THREADS__
116 # include <pthread.h>
117 pthread_mutex_t __malloc_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
119 #define LOCK __pthread_mutex_lock(&__malloc_lock)
120 #define UNLOCK __pthread_mutex_unlock(&__malloc_lock)
122 /* List of blocks allocated with memalign or valloc */
125 struct alignlist *next;
126 __ptr_t aligned; /* The address that memaligned returned. */
127 __ptr_t exact; /* The address that malloc returned. */
129 struct alignlist *_aligned_blocks;
131 /* Return memory to the heap. */
132 int __libc_free_aligned(void *ptr)
140 for (l = _aligned_blocks; l != NULL; l = l->next) {
141 if (l->aligned == ptr) {
142 /* Mark the block as free */
145 ptr -= sizeof(size_t);
146 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
153 void * memalign (size_t alignment, size_t size)
156 unsigned long int adj;
158 result = malloc (size + alignment - 1);
162 adj = (unsigned long int) ((unsigned long int) ((char *) result -
163 (char *) NULL)) % alignment;
167 for (l = _aligned_blocks; l != NULL; l = l->next)
168 if (l->aligned == NULL)
169 /* This slot is free. Use it. */
172 l = (struct alignlist *) malloc (sizeof (struct alignlist));
178 l->next = _aligned_blocks;
182 result = l->aligned = (char *) result + alignment - adj;