3 * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org>
5 * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
8 * Parts of the memalign code were stolen from malloc-930716.
20 /* Experimentally off - libc_hidden_proto(memcpy) */
21 /*libc_hidden_proto(memset)*/
22 libc_hidden_proto(mmap)
23 libc_hidden_proto(munmap)
26 void *malloc(size_t size)
30 if (unlikely(size == 0)) {
31 #if defined(__MALLOC_GLIBC_COMPAT__)
34 /* Some programs will call malloc (0). Lets be strict and return NULL */
40 #ifdef __ARCH_USE_MMU__
41 # define MMAP_FLAGS MAP_PRIVATE | MAP_ANONYMOUS
43 # define MMAP_FLAGS MAP_SHARED | MAP_ANONYMOUS
46 result = mmap((void *) 0, size + sizeof(size_t), PROT_READ | PROT_WRITE,
48 if (result == MAP_FAILED)
50 * (size_t *) result = size;
51 return(result + sizeof(size_t));
56 void * calloc(size_t nmemb, size_t lsize)
59 size_t size=lsize * nmemb;
61 /* guard vs integer overflow, but allow nmemb
62 * to fall through and call malloc(0) */
63 if (nmemb && lsize != (size / nmemb)) {
69 /* Standard unix mmap using /dev/zero clears memory so calloc
70 * doesn't need to actually zero anything....
73 memset(result, 0, size);
81 void *realloc(void *ptr, size_t size)
92 newptr = malloc(size);
94 size_t old_size = *((size_t *) (ptr - sizeof(size_t)));
95 memcpy(newptr, ptr, (old_size < size ? old_size : size));
103 extern int weak_function __libc_free_aligned(void *ptr);
106 if (unlikely(ptr == NULL))
108 if (unlikely(__libc_free_aligned != NULL)) {
109 if (__libc_free_aligned(ptr))
112 ptr -= sizeof(size_t);
113 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
119 #include <bits/uClibc_mutex.h>
120 __UCLIBC_MUTEX_INIT(__malloc_lock, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP);
121 #define __MALLOC_LOCK __UCLIBC_MUTEX_LOCK(__malloc_lock)
122 #define __MALLOC_UNLOCK __UCLIBC_MUTEX_UNLOCK(__malloc_lock)
124 /* List of blocks allocated with memalign or valloc */
127 struct alignlist *next;
128 __ptr_t aligned; /* The address that memaligned returned. */
129 __ptr_t exact; /* The address that malloc returned. */
131 struct alignlist *_aligned_blocks;
133 /* Return memory to the heap. */
134 int __libc_free_aligned(void *ptr)
142 for (l = _aligned_blocks; l != NULL; l = l->next) {
143 if (l->aligned == ptr) {
144 /* Mark the block as free */
147 ptr -= sizeof(size_t);
148 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
155 void * memalign (size_t alignment, size_t size)
158 unsigned long int adj;
160 result = malloc (size + alignment - 1);
164 adj = (unsigned long int) ((unsigned long int) ((char *) result - (char *) NULL)) % alignment;
168 for (l = _aligned_blocks; l != NULL; l = l->next)
169 if (l->aligned == NULL)
170 /* This slot is free. Use it. */
173 l = (struct alignlist *) malloc (sizeof (struct alignlist));
179 l->next = _aligned_blocks;
183 result = l->aligned = (char *) result + alignment - adj;