| 1 | @[has_globals] |
| 2 | module builtin |
| 3 | |
| 4 | // Shitty `sbrk` basic `malloc` and `free` impl |
| 5 | // TODO: implement pure V `walloc` later |
| 6 | |
| 7 | __global g_heap_base = usize(vwasm_heap_base()) |
| 8 | |
| 9 | // malloc dynamically allocates a `n` bytes block of memory on the heap. |
| 10 | // malloc returns a `byteptr` pointing to the memory address of the allocated space. |
| 11 | // unlike the `calloc` family of functions - malloc will not zero the memory block. |
| 12 | @[unsafe] |
| 13 | pub fn malloc(n isize) &u8 { |
| 14 | if n <= 0 { |
| 15 | $if no_imports ? { |
| 16 | return unsafe { nil } |
| 17 | } $else { |
| 18 | panic('malloc(n <= 0)') |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | res := g_heap_base |
| 23 | g_heap_base += usize(n) |
| 24 | |
| 25 | return &u8(res) |
| 26 | } |
| 27 | |
| 28 | // free allows for manually freeing memory allocated at the address `ptr`. |
| 29 | // currently does not free any memory. |
| 30 | @[unsafe] |
| 31 | pub fn free(ptr voidptr) { |
| 32 | _ := ptr |
| 33 | } |
| 34 | |