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.
This class describes a data segment.
This class describes an element segment.
This class describes a WebAssembly export.
This class represents a WebAssembly function type.
This class describes a WebAssembly global variable.
This class represents a single import declaration.
This class represents a single decoded instruction.
This class describes a WebAssembly linear memory.
This class represents a WebAssembly module.
This class describes a single section in a WebAssembly module.
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:
The offset of the size LEB introducing the body.
The total body size including the size LEB and locals.
The offset of the first instruction byte.
The number of instruction bytes in the body.
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:
The file offset of the segment payload.
The size of the segment payload in bytes.
The raw segment flags (0=active in memory 0, 1=passive, 2=active with explicit memidx).
The memory index for active segments.
The offset of the offset expression for active segments.
The size of the offset expression for active segments.
The runtime memory offset for active segments, or
-1when 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
-1when unevaluatable.
- class WASMElement¶
This class describes an element segment.
Attributes:
The element type.
The raw element flags.
The function indices, when items are encoded as bare funcidxs.
The list of init expressions, encoded as
(offset, size)pairs.The offset of the offset expression for active segments.
The size of the offset expression for active segments.
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:
The index of the exported entity within its kind-specific space.
The export kind (see
IE_FUNCand friends).The export name.
- index: int¶
The index of the exported entity within its kind-specific space.
- kind: int¶
The export kind (see
IE_FUNCand friends).
- name: str¶
The export name.
- class WASMFuncType¶
This class represents a WebAssembly function type.
Attributes:
The list of parameter value types as one-byte tags.
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:
The offset of the initialiser expression.
The size of the initialiser expression in bytes.
Whether the global is mutable.
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:
The import field (entity) name.
The global descriptor
(valtype, mutable)forIE_GLOBALimports.The import kind:
IE_FUNC,IE_TABLE,IE_MEMORY,IE_GLOBAL,IE_TAG.The memory descriptor
(has_max, min, max)forIE_MEMORYimports.The import module name.
The table descriptor
(elem_type, has_max, min, max)forIE_TABLEimports.The function type index for
IE_FUNCandIE_TAGimports; otherwise-1.
- field: str¶
The import field (entity) name.
- global_type: Optional[Tuple[int, bool]]¶
The global descriptor
(valtype, mutable)forIE_GLOBALimports.
- 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)forIE_MEMORYimports.
- module: str¶
The import module name.
- table_type: Optional[Tuple[int, bool, int, int]]¶
The table descriptor
(elem_type, has_max, min, max)forIE_TABLEimports.
- type_index: int¶
The function type index for
IE_FUNCandIE_TAGimports; otherwise-1.
- class WASMInstruction¶
This class represents a single decoded instruction.
Attributes:
A tuple holding the decoded immediates.
The immediate-format kind (see
Pkg.WASM.Opcodes.IMM_NONEand friends).The textual mnemonic (e.g.
The byte offset of the instruction within the file.
The opcode key, encoded as
(prefix << 16) | code.The total size of the encoded instruction in bytes.
- imm_kind: int¶
The immediate-format kind (see
Pkg.WASM.Opcodes.IMM_NONEand 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:
Whether the memory has an explicit maximum size.
The maximum number of memory pages.
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.CFFObjectThis class represents a WebAssembly module.
Methods:
CodeForFunction(funcidx)Returns the
WASMCodebody for a declared function, orNonefor 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.
Returns the value of the DataCount section, or
-1if absent.
GetDataName(idx)Returns the symbolic name of a data segment, if available.
Returns the list of data segments.
GetElemName(idx)Returns the symbolic name of an element segment, if available.
Returns the list of element segments.
Returns the offset immediately after the last byte consumed by the parser.
Returns the list of exports.
GetFunctionName(funcidx)Returns the symbolic name of the function at
funcidx(from the name section).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.
Returns the list of globals.
GetImportFunction(funcidx)Returns the
WASMImportdescribing an imported function index, orNone.Returns the number of imported functions.
Returns the number of imported globals.
Returns the number of imported memories.
Returns the number of imported tables.
Returns the number of imported tags.
Returns the list of imports.
GetLocalName(funcidx, localidx)Returns the local name from the name section, or
Noneif not present.Returns the list of linear memories.
GetMemoryName(idx)Returns the symbolic name of a memory, if available.
Returns the module name from the custom name section, or
Noneif not present.Returns the list of parsed sections in file order.
Returns the index of the start function declared by the module, or
-1if none.
GetTableName(idx)Returns the symbolic name of a table, if available.
Returns the list of tables.
GetTagName(idx)Returns the symbolic name of a tag, if available.
GetTags()Returns the list of tags.
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.
Returns the binary format version embedded in the module header.
IsImportedFunction(funcidx)Returns
Trueif the function atfuncidxis imported.
LookupDataAtAddress(addr[, max_bytes])Returns
(data_index, offset_within_segment, bytes, remaining)for the active data segment containingaddr, orNoneif 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
WASMCodebody for a declared function, orNonefor 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
-1if 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
-1if 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
WASMImportdescribing an imported function index, orNone.
- 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
Noneif 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
Noneif 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
-1if 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
Trueif the function atfuncidxis 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 containingaddr, orNoneif 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)orNone.- 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:
The name of the custom section, when
idisSEC_CUSTOM.The section id (see
Pkg.WASM.Opcodes.SEC_TYPEand friends).The section name (e.g.
The file offset of the section id byte.
The file offset where the section payload begins.
The size of the section payload in bytes.
The total size of the section, including id and length prefix.
- id: int¶
The section id (see
Pkg.WASM.Opcodes.SEC_TYPEand 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:
The element type (e.g.
Whether the table has an explicit maximum size.
The maximum number of entries (only valid when
has_maxisTrue).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.
- minimum: int¶
The minimum number of entries.