From 1b439614789968a94e5419151d88151635b662e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=BF=97=E5=BC=BA?= Date: Sun, 19 Apr 2020 00:51:54 +0800 Subject: [PATCH] calculate number of imported funcs * calculate number of imported funcs * add a test to check function's name --- wasm/index.go | 12 +++++++++++- wasm/module_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/wasm/index.go b/wasm/index.go index 63a1185c..3a542625 100644 --- a/wasm/index.go +++ b/wasm/index.go @@ -82,7 +82,17 @@ func (m *Module) populateFunctions() error { } // Add the functions from the wasm itself to the function list - numImports := len(m.FunctionIndexSpace) + + // when imported module not provided, len(m.FunctionIndecSpace) == 0 + // so must calculate number of imported funcs + var numImports int + if m.Import != nil { + for _, importEntry := range m.Import.Entries { + if importEntry.Type.Kind() == ExternalFunction { + numImports++ + } + } + } for codeIndex, typeIndex := range m.Function.Types { if int(typeIndex) >= len(m.Types.Entries) { return InvalidFunctionIndexError(typeIndex) diff --git a/wasm/module_test.go b/wasm/module_test.go index dcad6708..a2a33029 100644 --- a/wasm/module_test.go +++ b/wasm/module_test.go @@ -264,3 +264,50 @@ func TestGetFuntionSig(t *testing.T) { } } + +func TestFunctionName(t *testing.T) { + f, err := os.Open("testdata/hello-world-tinygo.wasm") + if err != nil { + t.Fatalf("%v", err) + } + + defer f.Close() + m, err := wasm.ReadModule(f, nil) + if err != nil { + t.Fatalf("error reading module %v", err) + } + + var names wasm.NameMap + if s := m.Custom(wasm.CustomSectionName); s != nil { + var nSec wasm.NameSection + err := nSec.UnmarshalWASM(bytes.NewReader(s.Data)) + if err != nil { + t.Fatalf("error Unmarhsal NameSection %v", err) + } + if len(nSec.Types[wasm.NameFunction]) > 0 { + sub, err := nSec.Decode(wasm.NameFunction) + if err != nil { + t.Fatalf("error Decode NameFunction %v", err) + } + funcs, ok := sub.(*wasm.FunctionNames) + if ok { + names = funcs.Names + } + } + } + + var numImports int + if m.Import != nil { + for _, importEntry := range m.Import.Entries { + if importEntry.Type.Kind() == wasm.ExternalFunction { + numImports++ + } + } + } + + for index, function := range m.FunctionIndexSpace { + if function.Name != names[uint32(index+numImports)] { + t.Fatalf("Err:function name expect %s, got %s", names[uint32(index+numImports)], function.Name) + } + } +}