16
16
#include " libc/assert.h"
17
17
#include " libc/dce.h"
18
18
#include " libc/errno.h"
19
+ #include " libc/intrin/kprintf.h"
19
20
#include " libc/mem/mem.h"
20
21
#include " libc/stdalign.internal.h"
21
22
#include " libc/stdckdint.h"
26
27
#endif
27
28
28
29
#ifndef TINYMALLOC_MAX_ALIGN
29
- #define TINYMALLOC_MAX_ALIGN 4096
30
+ #define TINYMALLOC_MAX_ALIGN sizeof ( max_align_t )
30
31
#endif
31
32
32
- alignas (TINYMALLOC_MAX_ALIGN) static struct {
33
- char memory[TINYMALLOC_MAX_BYTES];
34
- size_t used, last, free;
33
+ static struct {
34
+ alignas (max_align_t ) char bits[TINYMALLOC_MAX_BYTES];
35
+ char *memory;
36
+ int once;
37
+ size_t size, used, last, free;
35
38
} heap;
36
39
37
- static inline bool isheap (char *mem) {
40
+ static void tinymalloc_init (void ) {
41
+ int align;
42
+ if (heap.once )
43
+ return ;
44
+ align = TINYMALLOC_MAX_ALIGN;
45
+ heap.memory = (char *)(((uintptr_t )heap.bits + align - 1 ) & -align);
46
+ heap.size = sizeof (heap.bits ) - (heap.memory - heap.bits );
47
+ kprintf (" heap.memory = %p\n " , heap.memory );
48
+ kprintf (" heap.size = %p\n " , heap.size );
49
+ heap.once = 1 ;
50
+ }
51
+
52
+ static inline int isheap (char *mem) {
38
53
return heap.memory <= mem && mem < heap.memory + heap.used ;
39
54
}
40
55
@@ -59,6 +74,7 @@ size_t malloc_usable_size(void *ptr) {
59
74
void *memalign (size_t align, size_t need) {
60
75
char *res;
61
76
size_t next, next2, base, toto, *link, *link2;
77
+ tinymalloc_init ();
62
78
63
79
// normalize arguments
64
80
while (align & (align - 1 ))
@@ -95,7 +111,7 @@ void *memalign(size_t align, size_t need) {
95
111
base &= -align;
96
112
if (ckd_add (&toto, base, need))
97
113
goto OutOfMemory;
98
- if (toto > TINYMALLOC_MAX_BYTES )
114
+ if (toto > heap. size )
99
115
goto OutOfMemory;
100
116
res = heap.memory + base;
101
117
((size_t *)res)[-1 ] = need;
@@ -148,7 +164,7 @@ void *realloc(void *ptr, size_t need) {
148
164
need &= -sizeof (size_t );
149
165
if (ckd_add (&toto, base, need))
150
166
goto OutOfMemory;
151
- if (toto > TINYMALLOC_MAX_BYTES )
167
+ if (toto > heap. size )
152
168
goto OutOfMemory;
153
169
((size_t *)mem)[-1 ] = need;
154
170
heap.used = toto;
0 commit comments