Skip to content

Fix panic when size 0 passed to malloc #3303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/runtime/arch_tinygowasm_malloc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ var allocs = make(map[uintptr][]byte)

//export malloc
func libc_malloc(size uintptr) unsafe.Pointer {
if size == 0 {
return nil
}
buf := make([]byte, size)
ptr := unsafe.Pointer(&buf[0])
allocs[uintptr(ptr)] = buf
Expand All @@ -39,6 +42,11 @@ func libc_calloc(nmemb, size uintptr) unsafe.Pointer {

//export realloc
func libc_realloc(oldPtr unsafe.Pointer, size uintptr) unsafe.Pointer {
if size == 0 {
libc_free(oldPtr)
return nil
}

// It's hard to optimize this to expand the current buffer with our GC, but
// it is theoretically possible. For now, just always allocate fresh.
buf := make([]byte, size)
Expand Down
29 changes: 29 additions & 0 deletions tests/runtime_wasi/malloc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,32 @@ func TestMallocFree(t *testing.T) {
})
}
}

func TestMallocEmpty(t *testing.T) {
ptr := libc_malloc(0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}

func TestCallocEmpty(t *testing.T) {
ptr := libc_calloc(0, 1)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
ptr = libc_calloc(1, 0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}

func TestReallocEmpty(t *testing.T) {
ptr := libc_malloc(1)
if ptr == nil {
t.Error("expected pointer but was nil")
}
ptr = libc_realloc(ptr, 0)
if ptr != nil {
t.Errorf("expected nil pointer, got %p", ptr)
}
}