Pkg.WASM — API for parsing WebAssembly (WASM) modules

Overview

The Pkg.WASM module contains the API for parsing WebAssembly (WASM) modules. It supports the MVP instruction set as well as the standardised post-MVP proposals (bulk-memory, reference types, SIMD, atomics, exception handling, tail calls, multi-memory and the GC proposal). The module provides a textual disassembler that emits markers via Pro.Core.NTTextStream.startTag() so that UI views can resolve cross-references — calls, branches, locals, globals, memories, tables, types and data references all become navigable hyperlinks. i32.const values that point inside an active data segment are annotated inline with a decoded preview (ASCII or UTF-16 LE).

The package also contributes a custom bytecode view to the analysis UI: a per-function tree with filter line, a decompiler combo (populated through the wasm_decompilers plugin point — see Pkg.WASMDecompiler), Tab to toggle between disassembly and decompiler, Esc back history, and a Data XRefs view (Ctrl+5) listing every constant pointer into a data segment with its producing function and instruction offset.

Disassembling a WASM Module

The following code example demonstrates how to disassemble a WebAssembly module:

from Pro.Core import *
from Pkg.WASM import *

def disassembleWASM(fname):
    c = createContainerFromFile(fname)
    if c.isNull():
        return
    obj = WASMObject()
    if not obj.Load(c) or not obj.Initialize():
        return
    out = NTTextBuffer()
    obj.Disassemble(out)
    print(out.buffer)

Disassembling a Single Function

The following code example demonstrates how to disassemble one function by index:

from Pro.Core import *
from Pkg.WASM import *

def disassembleFunction(fname, funcidx):
    c = createContainerFromFile(fname)
    if c.isNull():
        return
    obj = WASMObject()
    if not obj.Load(c) or not obj.Initialize():
        return
    out = NTTextBuffer()
    obj.DisassembleFunction(out, funcidx)
    print(out.buffer)

Inspecting Module Structure

The following code example walks the parsed sections, imports and exports:

from Pro.Core import *
from Pkg.WASM import *

def inspectWASM(fname):
    c = createContainerFromFile(fname)
    if c.isNull():
        return
    obj = WASMObject()
    if not obj.Load(c) or not obj.Initialize():
        return
    print("version:", obj.GetVersion())
    print("sections:", len(obj.GetSections()))
    print("types:", len(obj.GetTypes()))
    print("imports:", len(obj.GetImports()))
    print("functions:", obj.GetTotalFunctionCount())
    for i, ex in enumerate(obj.GetExports()):
        print("  export[%d] %s -> %d" % (i, ex.name, ex.index))

Finding Data References in Code

The following code example walks every defined function looking for i32.const values that point into a data segment and prints a preview of the data they reference. This is the same scan used by the Data XRefs view:

from Pro.Core import *
from Pkg.WASM import *

def findDataRefs(fname):
    c = createContainerFromFile(fname)
    if c.isNull():
        return
    obj = WASMObject()
    if not obj.Load(c) or not obj.Initialize():
        return
    imp = obj.GetImportedFunctionCount()
    for fi in range(imp, obj.GetTotalFunctionCount()):
        for ins in obj.DecodeFunctionInstructions(fi):
            if ins.mnemonic != "i32.const":
                continue
            addr = ins.imm_args[0] & 0xFFFFFFFF
            info = obj.LookupDataAtAddress(addr, 64)
            if info is None:
                continue
            _idx, _local, data, _remaining = info
            preview = obj._formatDataPreview(bytes(data))
            if preview:
                print("f%d+0x%X -> %08X  %s" % (fi, ins.offset, addr, preview))

Module API

Pkg.WASM module API.

Classes:

WASMCode()

This class describes a function body.

WASMDataSegment()

This class describes a data segment.

WASMElement()

This class describes an element segment.

WASMExport()

This class describes a WebAssembly export.

WASMFuncType()

This class represents a WebAssembly function type.

WASMGlobal()

This class describes a WebAssembly global variable.

WASMImport()

This class represents a single import declaration.

WASMInstruction()

This class represents a single decoded instruction.

WASMMemory()

This class describes a WebAssembly linear memory.

WASMObject()

This class represents a WebAssembly module.

WASMSection()

This class describes a single section in a WebAssembly module.

WASMTable()

This class describes a WebAssembly table.

WASMTag()

This class describes a tag (used by exception handling).

class WASMCode

This class describes a function body.

Attributes:

body_offset

The offset of the size LEB introducing the body.

body_size

The total body size including the size LEB and locals.

code_offset

The offset of the first instruction byte.

code_size

The number of instruction bytes in the body.

locals

The local declarations encoded as (count, valtype) tuples.

body_offset: int

The offset of the size LEB introducing the body.

body_size: int

The total body size including the size LEB and locals.

code_offset: int

The offset of the first instruction byte.

code_size: int

The number of instruction bytes in the body.

locals: List[Tuple[int, int]]

The local declarations encoded as (count, valtype) tuples.

class WASMDataSegment

This class describes a data segment.

Attributes:

data_offset

The file offset of the segment payload.

data_size

The size of the segment payload in bytes.

flags

The raw segment flags (0=active in memory 0, 1=passive, 2=active with explicit memidx).

memory_index

The memory index for active segments.

offset_expr_offset

The offset of the offset expression for active segments.

offset_expr_size

The size of the offset expression for active segments.

runtime_offset

The runtime memory offset for active segments, or -1 when unevaluatable.

data_offset: int

The file offset of the segment payload.

data_size: int

The size of the segment payload in bytes.

flags: int

The raw segment flags (0=active in memory 0, 1=passive, 2=active with explicit memidx).

memory_index: int

The memory index for active segments.

offset_expr_offset: int

The offset of the offset expression for active segments.

offset_expr_size: int

The size of the offset expression for active segments.

runtime_offset: int

The runtime memory offset for active segments, or -1 when unevaluatable.

class WASMElement

This class describes an element segment.

Attributes:

elem_type

The element type.

flags

The raw element flags.

func_indices

The function indices, when items are encoded as bare funcidxs.

init_exprs

The list of init expressions, encoded as (offset, size) pairs.

offset_expr_offset

The offset of the offset expression for active segments.

offset_expr_size

The size of the offset expression for active segments.

table_index

The table index for active segments.

elem_type: int

The element type.

flags: int

The raw element flags.

func_indices: List[int]

The function indices, when items are encoded as bare funcidxs.

init_exprs: List[Tuple[int, int]]

The list of init expressions, encoded as (offset, size) pairs.

offset_expr_offset: int

The offset of the offset expression for active segments.

offset_expr_size: int

The size of the offset expression for active segments.

table_index: int

The table index for active segments.

class WASMExport

This class describes a WebAssembly export.

Attributes:

index

The index of the exported entity within its kind-specific space.

kind

The export kind (see IE_FUNC and friends).

name

The export name.

index: int

The index of the exported entity within its kind-specific space.

kind: int

The export kind (see IE_FUNC and friends).

name: str

The export name.

class WASMFuncType

This class represents a WebAssembly function type.

Attributes:

params

The list of parameter value types as one-byte tags.

results

The list of result value types as one-byte tags.

params: List[int]

The list of parameter value types as one-byte tags.

results: List[int]

The list of result value types as one-byte tags.

class WASMGlobal

This class describes a WebAssembly global variable.

Attributes:

init_offset

The offset of the initialiser expression.

init_size

The size of the initialiser expression in bytes.

mutable

Whether the global is mutable.

valtype

The global value type.

init_offset: int

The offset of the initialiser expression.

init_size: int

The size of the initialiser expression in bytes.

mutable: bool

Whether the global is mutable.

valtype: int

The global value type.

class WASMImport

This class represents a single import declaration.

Attributes:

field

The import field (entity) name.

global_type

The global descriptor (valtype, mutable) for IE_GLOBAL imports.

kind

The import kind: IE_FUNC, IE_TABLE, IE_MEMORY, IE_GLOBAL, IE_TAG.

memory_type

The memory descriptor (has_max, min, max) for IE_MEMORY imports.

module

The import module name.

table_type

The table descriptor (elem_type, has_max, min, max) for IE_TABLE imports.

type_index

The function type index for IE_FUNC and IE_TAG imports; otherwise -1.

field: str

The import field (entity) name.

global_type: Optional[Tuple[int, bool]]

The global descriptor (valtype, mutable) for IE_GLOBAL imports.

kind: int

The import kind: IE_FUNC, IE_TABLE, IE_MEMORY, IE_GLOBAL, IE_TAG.

memory_type: Optional[Tuple[bool, int, int]]

The memory descriptor (has_max, min, max) for IE_MEMORY imports.

module: str

The import module name.

table_type: Optional[Tuple[int, bool, int, int]]

The table descriptor (elem_type, has_max, min, max) for IE_TABLE imports.

type_index: int

The function type index for IE_FUNC and IE_TAG imports; otherwise -1.

class WASMInstruction

This class represents a single decoded instruction.

Attributes:

imm_args

A tuple holding the decoded immediates.

imm_kind

The immediate-format kind (see Pkg.WASM.Opcodes.IMM_NONE and friends).

mnemonic

The textual mnemonic (e.g.

offset

The byte offset of the instruction within the file.

opcode

The opcode key, encoded as (prefix << 16) | code.

size

The total size of the encoded instruction in bytes.

imm_args: Tuple

A tuple holding the decoded immediates. The shape depends on imm_kind.

imm_kind: int

The immediate-format kind (see Pkg.WASM.Opcodes.IMM_NONE and friends).

mnemonic: str

The textual mnemonic (e.g. "i32.add", "call").

offset: int

The byte offset of the instruction within the file.

opcode: int

The opcode key, encoded as (prefix << 16) | code.

size: int

The total size of the encoded instruction in bytes.

class WASMMemory

This class describes a WebAssembly linear memory.

Attributes:

has_max

Whether the memory has an explicit maximum size.

maximum

The maximum number of memory pages.

minimum

The minimum number of memory pages (64 KiB each).

has_max: bool

Whether the memory has an explicit maximum size.

maximum: int

The maximum number of memory pages.

minimum: int

The minimum number of memory pages (64 KiB each).

class WASMObject

Bases: Pro.Core.CFFObject

This class represents a WebAssembly module.

Methods:

CodeForFunction(funcidx)

Returns the WASMCode body for a declared function, or None for imports.

DecodeFunctionInstructions(funcidx, *[, wo])

Decodes and returns the list of instructions for the given function.

Disassemble(out, *[, wo])

Disassembles the entire module to the given text stream.

DisassembleFunction(out, funcidx, *[, wo])

Disassembles a single function to the given text stream.

DumpDataSegments(out)

Dumps the data segments to the given text stream.

DumpElements(out)

Dumps the element segments to the given text stream.

DumpExports(out)

Dumps the export table to the given text stream.

DumpGlobals(out)

Dumps the globals to the given text stream.

DumpHeader(out)

Dumps the module header to the given text stream.

DumpImports(out)

Dumps the import table to the given text stream.

DumpMemories(out)

Dumps the memories to the given text stream.

DumpSections(out)

Dumps a per-section summary table to the given text stream.

DumpTables(out)

Dumps the tables to the given text stream.

DumpTagsList(out)

Dumps the tag table to the given text stream.

DumpTypes(out)

Dumps the parsed function types to the given text stream.

FunctionTypeIndex(funcidx)

Returns the type index for the given global function index.

GetCodes()

Returns the list of function bodies parsed from the Code section.

GetDataCount()

Returns the value of the DataCount section, or -1 if absent.

GetDataName(idx)

Returns the symbolic name of a data segment, if available.

GetDataSegments()

Returns the list of data segments.

GetElemName(idx)

Returns the symbolic name of an element segment, if available.

GetElements()

Returns the list of element segments.

GetEndOffset()

Returns the offset immediately after the last byte consumed by the parser.

GetExports()

Returns the list of exports.

GetFunctionName(funcidx)

Returns the symbolic name of the function at funcidx (from the name section).

GetFunctions()

Returns the list of type indices for functions declared in this module (imports excluded).

GetGlobalName(idx)

Returns the symbolic name of a global, if available.

GetGlobals()

Returns the list of globals.

GetImportFunction(funcidx)

Returns the WASMImport describing an imported function index, or None.

GetImportedFunctionCount()

Returns the number of imported functions.

GetImportedGlobalCount()

Returns the number of imported globals.

GetImportedMemoryCount()

Returns the number of imported memories.

GetImportedTableCount()

Returns the number of imported tables.

GetImportedTagCount()

Returns the number of imported tags.

GetImports()

Returns the list of imports.

GetLocalName(funcidx, localidx)

Returns the local name from the name section, or None if not present.

GetMemories()

Returns the list of linear memories.

GetMemoryName(idx)

Returns the symbolic name of a memory, if available.

GetModuleName()

Returns the module name from the custom name section, or None if not present.

GetSections()

Returns the list of parsed sections in file order.

GetStartFunction()

Returns the index of the start function declared by the module, or -1 if none.

GetTableName(idx)

Returns the symbolic name of a table, if available.

GetTables()

Returns the list of tables.

GetTagName(idx)

Returns the symbolic name of a tag, if available.

GetTags()

Returns the list of tags.

GetTotalFunctionCount()

Returns the total number of functions (imports + declared).

GetTypeName(idx)

Returns the symbolic name of a type, if available.

GetTypes()

Returns the list of function types defined by the module.

GetVersion()

Returns the binary format version embedded in the module header.

IsImportedFunction(funcidx)

Returns True if the function at funcidx is imported.

LookupDataAtAddress(addr[, max_bytes])

Returns (data_index, offset_within_segment, bytes, remaining) for the active data segment containing addr, or None if no data segment maps to that address.

TypeSignature(typeidx)

Returns a printable function signature for the given type index, e.g.

CodeForFunction(funcidx: int)Optional[Pkg.WASM.WASMCode]

Returns the WASMCode body for a declared function, or None for imports.

Parameters

funcidx (int) – The global function index.

Returns

Returns the code body.

Return type

Optional[WASMCode]

DecodeFunctionInstructions(funcidx: int, *, wo: Optional[Pro.Core.NTIWait] = None)List[Pkg.WASM.WASMInstruction]

Decodes and returns the list of instructions for the given function.

Parameters
  • funcidx (int) – The global function index. Imports are not supported.

  • wo (Optional[NTIWait]) – Optional wait object.

Returns

Returns the instruction list.

Return type

List[WASMInstruction]

Disassemble(out: Pro.Core.NTTextStream, *, wo: Optional[Pro.Core.NTIWait] = None)None

Disassembles the entire module to the given text stream.

Tags are emitted via NTTextStream.startTag() so that UI views can resolve cross-references (jumps, calls, etc.).

Parameters
  • out (NTTextStream) – The output text stream.

  • wo (Optional[NTIWait]) – Optional wait object.

See also DisassembleFunction().

DisassembleFunction(out: Pro.Core.NTTextStream, funcidx: int, *, wo: Optional[Pro.Core.NTIWait] = None)None

Disassembles a single function to the given text stream.

Parameters
  • out (NTTextStream) – The output text stream.

  • funcidx (int) – The global function index.

  • wo (Optional[NTIWait]) – Optional wait object.

See also Disassemble(), DecodeFunctionInstructions().

DumpDataSegments(out: Pro.Core.NTTextStream)None

Dumps the data segments to the given text stream.

DumpElements(out: Pro.Core.NTTextStream)None

Dumps the element segments to the given text stream.

DumpExports(out: Pro.Core.NTTextStream)None

Dumps the export table to the given text stream.

DumpGlobals(out: Pro.Core.NTTextStream)None

Dumps the globals to the given text stream.

DumpHeader(out: Pro.Core.NTTextStream)None

Dumps the module header to the given text stream.

DumpImports(out: Pro.Core.NTTextStream)None

Dumps the import table to the given text stream.

DumpMemories(out: Pro.Core.NTTextStream)None

Dumps the memories to the given text stream.

DumpSections(out: Pro.Core.NTTextStream)None

Dumps a per-section summary table to the given text stream.

DumpTables(out: Pro.Core.NTTextStream)None

Dumps the tables to the given text stream.

DumpTagsList(out: Pro.Core.NTTextStream)None

Dumps the tag table to the given text stream.

DumpTypes(out: Pro.Core.NTTextStream)None

Dumps the parsed function types to the given text stream.

FunctionTypeIndex(funcidx: int)int

Returns the type index for the given global function index.

Parameters

funcidx (int) – The global function index.

Returns

Returns the type index, or -1 if out of range.

Return type

int

GetCodes()List[Pkg.WASM.WASMCode]

Returns the list of function bodies parsed from the Code section.

The list is parallel to GetFunctions().

Returns

Returns the code list.

Return type

List[WASMCode]

GetDataCount()int

Returns the value of the DataCount section, or -1 if absent.

Returns

Returns the data segment count.

Return type

int

GetDataName(idx: int)Optional[str]

Returns the symbolic name of a data segment, if available.

Return type

Optional[str]

GetDataSegments()List[Pkg.WASM.WASMDataSegment]

Returns the list of data segments.

Returns

Returns the data-segment list.

Return type

List[WASMDataSegment]

GetElemName(idx: int)Optional[str]

Returns the symbolic name of an element segment, if available.

Return type

Optional[str]

GetElements()List[Pkg.WASM.WASMElement]

Returns the list of element segments.

Returns

Returns the element-segment list.

Return type

List[WASMElement]

GetEndOffset()int

Returns the offset immediately after the last byte consumed by the parser.

Return type

int

GetExports()List[Pkg.WASM.WASMExport]

Returns the list of exports.

Returns

Returns the export list.

Return type

List[WASMExport]

GetFunctionName(funcidx: int)Optional[str]

Returns the symbolic name of the function at funcidx (from the name section).

Parameters

funcidx (int) – The global function index (imports first).

Returns

Returns the function name or None.

Return type

Optional[str]

GetFunctions()List[int]

Returns the list of type indices for functions declared in this module (imports excluded).

Returns

Returns the type-index list, one entry per declared function.

Return type

List[int]

GetGlobalName(idx: int)Optional[str]

Returns the symbolic name of a global, if available.

Return type

Optional[str]

GetGlobals()List[Pkg.WASM.WASMGlobal]

Returns the list of globals.

Returns

Returns the global list.

Return type

List[WASMGlobal]

GetImportFunction(funcidx: int)Optional[Pkg.WASM.WASMImport]

Returns the WASMImport describing an imported function index, or None.

Parameters

funcidx (int) – The global function index.

Returns

Returns the imported function descriptor or None.

Return type

Optional[WASMImport]

GetImportedFunctionCount()int

Returns the number of imported functions.

Return type

int

GetImportedGlobalCount()int

Returns the number of imported globals.

Return type

int

GetImportedMemoryCount()int

Returns the number of imported memories.

Return type

int

GetImportedTableCount()int

Returns the number of imported tables.

Return type

int

GetImportedTagCount()int

Returns the number of imported tags.

Return type

int

GetImports()List[Pkg.WASM.WASMImport]

Returns the list of imports.

Returns

Returns the import list.

Return type

List[WASMImport]

GetLocalName(funcidx: int, localidx: int)Optional[str]

Returns the local name from the name section, or None if not present.

Parameters
  • funcidx (int) – The global function index.

  • localidx (int) – The local variable index within the function.

Returns

Returns the local name.

Return type

Optional[str]

GetMemories()List[Pkg.WASM.WASMMemory]

Returns the list of linear memories.

Returns

Returns the memory list.

Return type

List[WASMMemory]

GetMemoryName(idx: int)Optional[str]

Returns the symbolic name of a memory, if available.

Return type

Optional[str]

GetModuleName()Optional[str]

Returns the module name from the custom name section, or None if not present.

Returns

Returns the module name.

Return type

Optional[str]

GetSections()List[Pkg.WASM.WASMSection]

Returns the list of parsed sections in file order.

Returns

Returns the section list.

Return type

List[WASMSection]

GetStartFunction()int

Returns the index of the start function declared by the module, or -1 if none.

Returns

Returns the start function index.

Return type

int

GetTableName(idx: int)Optional[str]

Returns the symbolic name of a table, if available.

Return type

Optional[str]

GetTables()List[Pkg.WASM.WASMTable]

Returns the list of tables.

Returns

Returns the table list.

Return type

List[WASMTable]

GetTagName(idx: int)Optional[str]

Returns the symbolic name of a tag, if available.

Return type

Optional[str]

GetTags()List[Pkg.WASM.WASMTag]

Returns the list of tags.

Returns

Returns the tag list.

Return type

List[WASMTag]

GetTotalFunctionCount()int

Returns the total number of functions (imports + declared).

Returns

Returns the total function count.

Return type

int

GetTypeName(idx: int)Optional[str]

Returns the symbolic name of a type, if available.

Return type

Optional[str]

GetTypes()List[Pkg.WASM.WASMFuncType]

Returns the list of function types defined by the module.

Returns

Returns the type list.

Return type

List[WASMFuncType]

GetVersion()int

Returns the binary format version embedded in the module header.

Returns

Returns the version (typically 1).

Return type

int

IsImportedFunction(funcidx: int)bool

Returns True if the function at funcidx is imported.

Return type

bool

LookupDataAtAddress(addr: int, max_bytes: int = 64)Optional[Tuple[int, int, bytes, int]]

Returns (data_index, offset_within_segment, bytes, remaining) for the active data segment containing addr, or None if no data segment maps to that address.

Parameters
  • addr (int) – The runtime address (32-bit unsigned).

  • max_bytes (int) – The maximum number of bytes to return.

Returns

A tuple (data_idx, local_offset, bytes, remaining) or None.

Return type

Optional[Tuple[int, int, bytes, int]]

TypeSignature(typeidx: int)str

Returns a printable function signature for the given type index, e.g. "(i32, i32) -> (i32)".

Parameters

typeidx (int) – The type index.

Returns

Returns the signature string.

Return type

str

class WASMSection

This class describes a single section in a WebAssembly module.

Attributes:

custom_name

The name of the custom section, when id is SEC_CUSTOM.

id

The section id (see Pkg.WASM.Opcodes.SEC_TYPE and friends).

name

The section name (e.g.

offset

The file offset of the section id byte.

payload_offset

The file offset where the section payload begins.

payload_size

The size of the section payload in bytes.

size

The total size of the section, including id and length prefix.

custom_name: Optional[str]

The name of the custom section, when id is SEC_CUSTOM.

id: int

The section id (see Pkg.WASM.Opcodes.SEC_TYPE and friends).

name: str

The section name (e.g. "Type", "Function", "Custom").

offset: int

The file offset of the section id byte.

payload_offset: int

The file offset where the section payload begins.

payload_size: int

The size of the section payload in bytes.

size: int

The total size of the section, including id and length prefix.

class WASMTable

This class describes a WebAssembly table.

Attributes:

elem_type

The element type (e.g.

has_max

Whether the table has an explicit maximum size.

maximum

The maximum number of entries (only valid when has_max is True).

minimum

The minimum number of entries.

elem_type: int

The element type (e.g. VT_FUNCREF).

has_max: bool

Whether the table has an explicit maximum size.

maximum: int

The maximum number of entries (only valid when has_max is True).

minimum: int

The minimum number of entries.

class WASMTag

This class describes a tag (used by exception handling).

Attributes:

attribute

The tag attribute byte.

type_index

The associated function type index.

attribute: int

The tag attribute byte.

type_index: int

The associated function type index.