wasilibs / nottinygc

Higher-performance allocator for TinyGo WASI apps
MIT License
64 stars 6 forks source link

Can I use malloc? #14

Closed tillknuesting closed 1 year ago

tillknuesting commented 1 year ago

I am using malloc with TinyGo but with nottinygc it panics.

How can I resolve this?

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x1199875]

`// These function are exported by TinyGo malloc := mod.ExportedFunction("malloc") free := mod.ExportedFunction("free")

// Allocate Memory
results, err := malloc.Call(ctx, nameSize)
if err != nil {
    log.Panicln(err)
}
namePosition := results[0]

// This pointer is managed by TinyGo,
// but TinyGo is unaware of external usage.
// So, we have to free it when finished
defer free.Call(ctx, namePosition)

`

tillknuesting commented 1 year ago

Can we export this https://github.com/wasilibs/nottinygc/blob/59403c79b29c9ae0e70cc463cd87fbfdf6c6fb66/gc.go#L53?

TinyGo does https://github.com/tinygo-org/tinygo/blob/d01d85930d19a73010853b7ba8648d8811891bee/src/runtime/arch_tinygowasm_malloc.go#L13

anuraaga commented 1 year ago

Hi @tillknuesting - at the time, the plan was for TinyGo to stop exporting those in 0.28.0 so did not export them here either. But it looks like that didn't happen yet, let me confirm if this is a long-term decision to keep the exports, and if so we'll add them.

https://github.com/tinygo-org/tinygo/pull/3142#issuecomment-1590263334

In the meantime, you can define your own functions if needed

import "C"

//export allocate
func allocate(size uint32) unsafe.Pointer {
  // IIRC, the type actually is unsigned long in wasi-libc source for some reason, or otherwise whatever C. cast works :)
  return C.malloc(C.ulong(size))
}

//export deallocate
func deallocate(ptr unsafe.Pointer) {
  C.free(ptr)
}
anuraaga commented 1 year ago

Oh, I found this even simpler workaround

https://github.com/tetratelabs/wazero/pull/1429#issuecomment-1532326475

I think we'll probably end up exporting by default here to match 0.28 but let me hear a bit on what the plan on TinyGo is first.

anuraaga commented 1 year ago

@tillknuesting Thanks for bringing this up, I have made the change to export malloc/free by default. Will try to cut a release soon after debugging #13 further