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.
19 /* Experimentally off - 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 */
39 #ifdef __ARCH_USE_MMU__
40 # define MMAP_FLAGS MAP_PRIVATE | MAP_ANONYMOUS
42 # define MMAP_FLAGS MAP_SHARED | MAP_ANONYMOUS
45 result = mmap((void *) 0, size + sizeof(size_t), PROT_READ | PROT_WRITE,
47 if (result == MAP_FAILED)
49 * (size_t *) result = size;
50 return(result + sizeof(size_t));
55 void * calloc(size_t nmemb, size_t lsize)
58 size_t size=lsize * nmemb;
60 /* guard vs integer overflow, but allow nmemb
61 * to fall through and call malloc(0) */
62 if (nmemb && lsize != (size / nmemb)) {
68 /* Standard unix mmap using /dev/zero clears memory so calloc
69 * doesn't need to actually zero anything....
72 memset(result, 0, size);
80 void *realloc(void *ptr, size_t size)
91 newptr = malloc(size);
93 size_t old_size = *((size_t *) (ptr - sizeof(size_t)));
94 memcpy(newptr, ptr, (old_size < size ? old_size : size));
102 extern int weak_function __libc_free_aligned(void *ptr);
105 if (unlikely(ptr == NULL))
107 if (unlikely(__libc_free_aligned != NULL)) {
108 if (__libc_free_aligned(ptr))
111 ptr -= sizeof(size_t);
112 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
118 #include <bits/uClibc_mutex.h>
119 __UCLIBC_MUTEX_INIT(__malloc_lock, PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP);
120 #define __MALLOC_LOCK __UCLIBC_MUTEX_LOCK(__malloc_lock)
121 #define __MALLOC_UNLOCK __UCLIBC_MUTEX_UNLOCK(__malloc_lock)
123 /* List of blocks allocated with memalign or valloc */
126 struct alignlist *next;
127 __ptr_t aligned; /* The address that memaligned returned. */
128 __ptr_t exact; /* The address that malloc returned. */
130 struct alignlist *_aligned_blocks;
132 /* Return memory to the heap. */
133 int __libc_free_aligned(void *ptr)
141 for (l = _aligned_blocks; l != NULL; l = l->next) {
142 if (l->aligned == ptr) {
143 /* Mark the block as free */
146 ptr -= sizeof(size_t);
147 munmap(ptr, * (size_t *) ptr + sizeof(size_t));
154 void * memalign (size_t alignment, size_t size)
157 unsigned long int adj;
159 result = malloc (size + alignment - 1);
163 adj = (unsigned long int) ((unsigned long int) ((char *) result - (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;