Skip to content
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

fix: wasm module test #8099

Merged
merged 2 commits into from
Dec 16, 2024
Merged
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
20 changes: 4 additions & 16 deletions pkg/module/wasm/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package wasm
import (
"encoding/json"
"fmt"
"reflect"
"unsafe"

"github.com/aquasecurity/trivy/pkg/module/api"
Expand Down Expand Up @@ -141,28 +140,17 @@ func marshal(v any) uint64 {
}

func unmarshal(ptr, size uint32, v any) error {
var b []byte
s := (*reflect.SliceHeader)(unsafe.Pointer(&b))
s.Len = uintptr(size)
s.Cap = uintptr(size)
s.Data = uintptr(ptr)

if err := json.Unmarshal(b, v); err != nil {
s := ptrToString(ptr, size)
if err := json.Unmarshal([]byte(s), v); err != nil {
return fmt.Errorf("unmarshal error: %s", err)
}

return nil
}

// ptrToString returns a string from WebAssembly compatible numeric types representing its pointer and length.
func ptrToString(ptr uint32, size uint32) string {
// Get a slice view of the underlying bytes in the stream. We use SliceHeader, not StringHeader
// as it allows us to fix the capacity to what was allocated.
return *(*string)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(ptr),
Len: uintptr(size), // Tinygo requires these as uintptrs even if they are int fields.
Cap: uintptr(size), // ^^ See https://github.com/tinygo-org/tinygo/issues/1284
}))
b := unsafe.Slice((*byte)(unsafe.Pointer(uintptr(ptr))), size)
return *(*string)(unsafe.Pointer(&b))
}

// stringToPtr returns a pointer and size pair for the given string in a way compatible with WebAssembly numeric types.
Expand Down
Loading