github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/experimental/table/lookup.go (about)

     1  package table
     2  
     3  import (
     4  	"github.com/wasilibs/wazerox/api"
     5  	"github.com/wasilibs/wazerox/internal/wasm"
     6  )
     7  
     8  // LookupFunction tries to get an api.Function from the table instance specified by `tableIndex` and `tableOffset` in the
     9  // given api.Module. The user of this function must be well aware of the structure of the given api.Module,
    10  // and the offset and table index must be valid. If this fails to find it, e.g. table is not found,
    11  // table offset is out of range, violates the expected types, this panics according to the same semantics as
    12  // call_indirect instruction: https://www.w3.org/TR/2022/WD-wasm-core-2-20220419/exec/instructions.html#xref-syntax-instructions-syntax-instr-control-mathsf-call-indirect-x-y
    13  //
    14  //   - `module` is a module instance to look up the function.
    15  //   - `tableIndex` is the index of the table instance in the module.
    16  //   - `tableOffset` is the offset of the lookup target in the table.
    17  //   - `expectedParamTypes` and `expectedResultTypes` are used to check the type of the function found in the table.
    18  //
    19  // Note: the returned api.Function is always valid, i.e. not nil, if this returns without panic.
    20  func LookupFunction(
    21  	module api.Module, tableIndex uint32, tableOffset uint32,
    22  	expectedParamTypes, expectedResultTypes []api.ValueType,
    23  ) api.Function {
    24  	m := module.(*wasm.ModuleInstance)
    25  	typ := &wasm.FunctionType{Params: expectedParamTypes, Results: expectedResultTypes}
    26  	typ.CacheNumInUint64()
    27  	typeID := m.GetFunctionTypeID(typ)
    28  	if int(tableIndex) >= len(m.Tables) {
    29  		panic("table index out of range")
    30  	}
    31  	table := m.Tables[tableIndex]
    32  	return m.LookupFunction(table, typeID, tableOffset)
    33  }