1 #ifdef __LITEOS_DEBUG__
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <errno.h>
5 #include "libc.h"
6 #include "pthread_impl.h"
7 #include "oldmalloc/malloc_impl.h"
8 
lock(volatile int *lk)9 static inline void lock(volatile int *lk)
10 {
11 	if (libc.threads_minus_1)
12 		while (a_swap(lk, 1)) __wait(lk, lk + 1, 1, 1);
13 }
14 
unlock(volatile int *lk)15 static inline void unlock(volatile int *lk)
16 {
17 	if (lk[0]) {
18 		a_store(lk, 0);
19 		if (lk[1]) __wake(lk, 1, 1);
20 	}
21 }
22 
__memalign(size_t align, size_t len)23 void *__memalign(size_t align, size_t len)
24 {
25 	unsigned char *mem, *new;
26 
27 	if ((align & -align) != align) {
28 		errno = EINVAL;
29 		return 0;
30 	}
31 
32 	if (len > SIZE_MAX - align || __malloc_replaced) {
33 		errno = ENOMEM;
34 		return 0;
35 	}
36 
37 	if (align <= SIZE_ALIGN)
38 		return malloc(len);
39 
40 	if (!(mem = malloc(len + align-1)))
41 		return 0;
42 
43 	new = (void *)((uintptr_t)mem + align-1 & -align);
44 	if (new == mem) return mem;
45 
46 	struct chunk *c = MEM_TO_CHUNK(mem);
47 	struct chunk *n = MEM_TO_CHUNK(new);
48 
49 	if (g_enable_check) {
50 		int status = delete_node(mem);
51 		if (status != 0) {
52 			get_free_trace(mem);
53 			a_crash();
54 		}
55 	}
56 
57 	if (IS_MMAPPED(c)) {
58 		/* Apply difference between aligned and original
59 		 * address to the "extra" field of mmapped chunk. */
60 		n->psize = c->psize + (new-mem);
61 		n->csize = c->csize - (new-mem);
62 		if (g_enable_check) {
63 			insert_node(CHUNK_TO_MEM(n), CHUNK_SIZE(n));
64 		}
65 		return new;
66 	}
67 
68 	struct chunk *t = NEXT_CHUNK(c);
69 
70 	/* Split the allocated chunk into two chunks. The aligned part
71 	 * that will be used has the size in its footer reduced by the
72 	 * difference between the aligned and original addresses, and
73 	 * the resulting size copied to its header. A new header and
74 	 * footer are written for the split-off part to be freed. */
75 	lock(g_mem_lock);
76 	n->psize = c->csize = C_INUSE | (new-mem);
77 	n->csize = t->psize -= new-mem;
78 	calculate_checksum(c, n);
79 	calculate_checksum(NULL, t);
80 	unlock(g_mem_lock);
81 	if (g_enable_check) {
82 		insert_node(CHUNK_TO_MEM(n), CHUNK_SIZE(n));
83 	}
84 
85 	__bin_chunk(c);
86 	return new;
87 }
88 
89 weak_alias(__memalign, memalign);
90 #else
91 #define _BSD_SOURCE
92 #include <stdlib.h>
93 
memalign(size_t align, size_t len)94 void *memalign(size_t align, size_t len)
95 {
96 	return aligned_alloc(align, len);
97 }
98 #endif
99