mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-06 20:13:40 +00:00
Implement minimal bump pointer allocator
Useful for MCUs, until a real garbage collector has been implemented.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
|
||||
// +build !linux
|
||||
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
_extern__heap_start unsafe.Pointer // defined by the linker
|
||||
heapptr = uintptr(unsafe.Pointer(&_extern__heap_start))
|
||||
)
|
||||
|
||||
func alloc(size uintptr) unsafe.Pointer {
|
||||
// TODO: this can be optimized by not casting between pointers and ints so
|
||||
// much. And by using platform-native data types (e.g. *uint8 for 8-bit
|
||||
// systems).
|
||||
size = align(size)
|
||||
addr := heapptr
|
||||
heapptr += size
|
||||
for i := uintptr(0); i < uintptr(size); i += 4 {
|
||||
ptr := (*uint32)(unsafe.Pointer(addr + i))
|
||||
*ptr = 0
|
||||
}
|
||||
return unsafe.Pointer(addr)
|
||||
}
|
||||
|
||||
func free(ptr unsafe.Pointer) {
|
||||
// TODO: use a GC
|
||||
}
|
||||
@@ -3,6 +3,10 @@
|
||||
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// #include <stdio.h>
|
||||
// #include <stdlib.h>
|
||||
// #include <unistd.h>
|
||||
@@ -21,3 +25,15 @@ func Sleep(d Duration) {
|
||||
func abort() {
|
||||
C.abort()
|
||||
}
|
||||
|
||||
func alloc(size uintptr) unsafe.Pointer {
|
||||
buf := C.calloc(1, C.size_t(size))
|
||||
if buf == nil {
|
||||
panic("cannot allocate memory")
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
func free(ptr unsafe.Pointer) {
|
||||
C.free(ptr)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user