Compare commits

..
Author SHA1 Message Date
t3hn3rd 0a4bd589ee feature: Compiler flag added for verbose debug output
VM will now only output verbose debugging information if -dDEBUG_OUTPUT is supplied.
2026-02-24 23:07:58 +00:00
t3hn3rd eda3669ab2 Merge branch 'feature/build-script-conversion-ps' into develop 2026-02-24 21:52:51 +00:00
t3hn3rd a5b532d0c1 ALL BUILD SCRIPTS MUST BE POWERSHELL
SEE COMMIT HEADER
2026-02-24 21:52:33 +00:00
t3hn3rd a8817e0350 Merge branch 'feature/spec-conformity' into develop 2026-02-24 21:45:45 +00:00
t3hn3rd b937e60838 feature: implement all float, conversion, table & bulk memory opcodes with IEEE 754 hardening
Complete implementation of remaining WASM MVP and post-MVP opcodes:

Float arithmetic (f32/f64):
- abs, neg (purely bitwise), ceil, floor, trunc, nearest, sqrt
- add, sub, mul, div with indeterminate form handling
  (Inf+(-Inf), Inf-Inf, Inf*0, 0/0, Inf/Inf -> NaN; x/0 -> ±Inf)
- min, max with signed-zero fix (OR for min, AND for max)
- copysign (bitwise sign transfer)

Float comparisons (f64 eq/ne/lt/gt/le/ge):
- Added bitwise NaN detection before comparisons to prevent EInvalidOp on x64 FPC

Conversion opcodes:
- i32.wrap_i64, i64.extend_i32_s/u
- i32/i64.trunc_f32/f64_s/u with NaN + overflow traps
- f32/f64.convert_i32/i64_s/u
- f32.demote_f64, f64.promote_f32
- i32/i64.reinterpret_f32/f64, f32/f64.reinterpret_i32/i64
- i32.extend8_s, i32.extend16_s, i64.extend8_s/16_s/32_s

0xFC prefix dispatch + saturating truncation (FC 00-07):
- i32/i64.trunc_sat_f32/f64_s/u with NaN->0, clamp to min/max

Bulk memory (FC 08-0B):
- memory.init, data.drop, memory.copy (overlap-safe), memory.fill

Table operations (FC 0C-11 + opcodes 0x25/0x26):
- table.get, table.set, table.init, elem.drop
- table.copy (overlap-safe), table.grow, table.size, table.fill

Control flow & infrastructure:
- select t* (typed select, 0x1C) with LEB128 type vector
- block/loop/if blocktype now parsed as LEB128 s33 (multi-byte support)
- Control flow scanner updated for all new opcodes (0xFC sub-opcodes,
  table.get/set, typed select)
- VM init: jump tables heap-allocated via kalloc, FC table initialized

All float ops use bitwise NaN detection to avoid FPC x64 EInvalidOp.
2026-02-24 21:45:10 +00:00
t3hn3rd 255ad4806e Merge branch 'feature/opcode-refactor' into develop 2026-02-24 15:38:48 +00:00
t3hn3rd 93dfff358d refactor: Split monolithic wasm.vm.opcodes.pas into 119 individual opcode units
- Extract each opcode procedure from wasm.vm.opcodes.pas into its own
unit file under src/wasm/vm/opcodes/ following the naming convention
wasm.vm.opcode.<name>.pas. The hub file now only imports the individual
units and contains initializeOpcodeJumpTable with fully qualified
procedure references.
- Add missing test coverage for the else opcode (4 tests), bringing the
total from 425 to 429 with all tests passing.

Files:
- 119 new opcode units under src/wasm/vm/opcodes/
- 1 new test: wasm.test.opcode.elseop.pas
- Modified: wasm.vm.opcodes.pas (hub-only), wasm.test.pas, build.bat
2026-02-24 15:38:36 +00:00
t3hn3rd 3ed5c0a847 Merge branch 'feature/build-clean' into develop 2026-02-24 14:57:43 +00:00
t3hn3rd ff65a0d5f0 refactor: build.bat flexible argument parsing, add run & help commands
- Replaced positional `%1` checks with a loop-based argument parser
  so flags (`test`, `clean`, `run`, `help`) work in any order/combination
- Added `run` flag: executes `bin\WASURO.exe` after a successful build
- Added `help` flag: prints usage info and exits
- Fixed `clean` early-exit to also check `DO_RUN` (not just `TESTFLAGS`),
  so `build.bat clean run` correctly continues to build+run
- Added section comment headers (Build, Run) for consistency
2026-02-24 14:57:30 +00:00
t3hn3rd 76d7d737c0 Merge branch 'feature/missing-opcodes' into develop 2026-02-24 14:47:01 +00:00
t3hn3rd d12ad11746 feature: implement control flow opcodes, extract constants & helpers
## Control Flow Opcodes
- Implemented all 10 remaining stub control flow opcodes:
  block, loop, if, else, end, br, br_if, br_table, call, call_indirect
- Rewrote return opcode to walk control stack and restore call frames
- Fixed tick() hang: now halts when IP >= Limit

## Refactoring
- Extracted WASM_HDR_MAGIC and CTRL_FRAME_* constants to wasm.types.constants.pas
- Extracted push_control_frame, scan_forward, do_branch helpers to wasm.vm.control.pas
- Updated wasm.parser.pas to reference constants via wasm.types.constants

## Tests
- Added 9 new test units (25 tests):
  block, loop, if, end, br, br_if, br_table, call, call_indirect
- Added E2E binary test: 115-byte handcrafted WASM binary exercising
  all control flow opcodes (2 functions, expected result=30)
- All 425/425 tests passing
2026-02-24 14:46:30 +00:00
t3hn3rd 679973c6e9 Merge branch 'feature/type-refactoring' into develop 2026-02-24 13:24:15 +00:00
t3hn3rd 68df3565cb feature: types refactored from one monolithic file to seperation of duties
- wasm.types.context.pas
- wasm.types.enums.pas
- wasm.types.sections.pas
- wasm.types.values.pas
2026-02-24 13:23:46 +00:00
t3hn3rd 862e3254df Merge branch 'hotfix/binary-test-builtins' into develop 2026-02-24 13:05:42 +00:00
t3hn3rd 6794c52a77 patch: binary-test patched to use builtin types 2026-02-24 13:05:33 +00:00
t3hn3rd 7cc4459dfd Merge branch 'feature/builtin-types' into develop 2026-02-24 13:04:25 +00:00
t3hn3rd ae344e7495 Merge branch 'feature/binary-tests' into develop 2026-02-24 13:04:20 +00:00
t3hn3rd 430ebcd203 feature: added built-in types as a OS/RTL->VM decoupling mechanism
- Added src/wasm/types/wasm.types.builtin.pas as a decoupling unit.
- Updated all units to only use these types.
- Added linter step (lint.ps1) to enforce usage of these types.
2026-02-24 13:03:27 +00:00
t3hn3rd 835f6f86cc feature: Binary E2E tests
Implemented the following E2E tests:
- src/wasm/test/wasm.test.binary.addnums.pas
- src/wasm/test/wasm.test.binary.arithmetic.pas
- src/wasm/test/wasm.test.binary.locals.pas
- src/wasm/test/wasm.test.binary.memroundtrip.pas
- src/wasm/test/wasm.test.binary.return42.pas
2026-02-24 12:26:43 +00:00
t3hn3rd a5192366ed Merge branch 'hotfix/readme.1' into develop 2026-02-24 00:47:36 +00:00
t3hn3rd d3cd71072b hotfix: Fixed errors & formatting in generated ReadMe
- Incorrect link to the Asuro project.
- Formatting issues.
2026-02-24 00:47:23 +00:00
t3hn3rd e40d8e9ed5 Merge branch 'feature/readme' into develop 2026-02-24 00:42:31 +00:00
t3hn3rd fca24af1b0 docs: add project README
Add README.md documenting WASURO's architecture, implemented opcodes,
parsed sections, build instructions, testing, and constraints.

Covers:
- Project overview (WASM VM for Asuro OS, Standard Pascal, bare-metal)
- Source tree layout and key components (VM, parser, stack, heap, emu layer)
- Full table of implemented opcodes (control, variables, constants,
  i32/i64 arithmetic/bitwise/comparison, f32/f64 comparison,
  memory loads/stores, memory.size/grow)
- Parsed WASM binary sections
- Build and test instructions (build.bat / build.bat test)
- Kernel compatibility constraints (no RTL, no classes)
2026-02-24 00:42:17 +00:00
t3hn3rd 8c16550bd4 Merge branch 'feature/test-suite' into develop 2026-02-24 00:38:11 +00:00
t3hn3rd 9a3b813c96 Merge branch 'feature/opcode-parser-implementation' into develop 2026-02-24 00:38:06 +00:00
t3hn3rd 8a4bb2ca35 Merge branch 'feature/build-scripts' into develop 2026-02-24 00:38:00 +00:00
t3hn3rd ff28299132 feature: add build script and update .gitignore
Add build.bat for compiling WASURO with FPC 3.2.2 (x86_64-win64).
Supports optional "test" argument to enable the test suite.

build.bat:
- Configures FPC with all source unit paths (emu, wasm, parser,
  sections, types, vm, test infrastructure)
- Outputs to bin/WASURO.exe, intermediate units to lib/
- "build.bat test" passes -dRUN_TESTS to include test units
- Debug info enabled (-gw3)
- Propagates FPC exit code on failure

.gitignore:
- Add AGENTS.md (AI agent instructions, not project source), this file
should be personal choice, not dictated at a project level.
2026-02-24 00:37:37 +00:00
t3hn3rd dc67262477 feature: add comprehensive WASM test suite (374 tests)
Add a full test framework and 123 test files covering infrastructure,
parser sections, and VM opcodes. All 374 tests pass; exit code reflects
failure count for CI/CD integration.

Test framework (wasm.test.framework):
- Assert helpers: assert_true, assert_i32/i64/u32/u64/f32/f64/bool
- Context builders: make_test_context, setup_test_locals, setup_test_globals
- Global counters: TotalTests, PassedTests, FailedTests

Test runner (wasm.test, WASURO.lpr):
- Master runner calls all 108 test units and prints summary
- halt(FailedTests) returns exit code for pipeline consumption
- Gated behind {$IFDEF RUN_TESTS} / build.bat test

Infrastructure tests (3 units):
- Stack push/pop for i32, i64, f32, f64
- Heap read/write across all widths (8/16/32/64-bit)
- LEB128 unsigned/signed encoding/decoding

Parser tests (8 units):
- type, function, export, code, global, memory, start, data sections

Opcode tests (97 units, ~374 assertions):
- Control: nop, unreachable, drop, select, return
- Variables: local.get/set/tee, global.get/set
- Constants: i32/i64/f32/f64.const
- I32: all arithmetic, bitwise, and comparison ops (29 units)
- I64: all arithmetic, bitwise, and comparison ops (29 units)
- F32/F64: all comparison ops (12 units)
- Memory loads: i32/i64/f32/f64.load + sign/zero-extending variants (14 units)
- Memory stores: i32/i64/f32/f64.store + narrowing variants (9 units)
2026-02-24 00:34:49 +00:00
456 changed files with 21674 additions and 2360 deletions

No files matched your search

+2
View File
@@ -1,2 +1,4 @@
bin bin
lib lib
AGENTS.md
GAP_ANALYSIS.md
+89
View File
@@ -0,0 +1,89 @@
# WASURO
A WebAssembly virtual machine for the [Asuro](https://gitea.spexeah.com/Spexeah/Asuro) operating system, written in Standard Pascal.
WASURO parses and executes WASM binaries directly in a bare-metal kernel environment — no runtime library, no classes, no heap manager beyond what the OS provides.
## Architecture
```
src/
├── emu/ # OS emulation layer (types, console, memory, LEB128)
├── wasm/ # WASM Virtual Machine
│ ├── parser/ # WASM binary parser
│ │ └── sections/ # Section-specific parsers (type, function, export,
│ │ # code, global, memory, start, data, etc.)
│ ├── types/ # WASM type system, stack, and linear memory (heap)
│ ├── vm/ # VM tick loop and opcode jump table
│ └── test/ # Test suite
│ ├── infra/ # Stack, heap, LEB128 tests
│ ├── opcodes/ # Per-opcode test units
│ └── parsers/ # Per-section parser tests
└── project/ # Lazarus project files
```
### Key components
- **VM** (`wasm.vm`) — Tick-based execution loop dispatching opcodes through a 256-entry jump table.
- **Parser** (`wasm.parser`) — Validates the WASM magic/version header, then routes each binary section to its handler.
- **Stack** (`wasm.types.stack`) — Operand and control stacks supporting i32, i64, f32, f64 push/pop.
- **Heap** (`wasm.types.heap`) — Paged linear memory with read/write at 8/16/32/64-bit widths.
- **Emulation layer** (`src/emu/`) — Provides the same `types`, `console`, `lmemorymanager`, and `leb128` interfaces that exist in the real Asuro kernel, allowing development and testing on a host OS.
### Implemented opcodes
| Category | Opcodes |
|---|---|
| Control | `nop`, `unreachable`, `drop`, `select`, `return` |
| Variables | `local.get/set/tee`, `global.get/set` |
| Constants | `i32.const`, `i64.const`, `f32.const`, `f64.const` |
| i32 Arithmetic | `add`, `sub`, `mul`, `div_s/u`, `rem_s/u`, `clz`, `ctz`, `popcnt` |
| i32 Bitwise | `and`, `or`, `xor`, `shl`, `shr_s/u`, `rotl`, `rotr` |
| i32 Comparison | `eqz`, `eq`, `ne`, `lt_s/u`, `gt_s/u`, `le_s/u`, `ge_s/u` |
| i64 Arithmetic | `add`, `sub`, `mul`, `div_s/u`, `rem_s/u`, `clz`, `ctz`, `popcnt` |
| i64 Bitwise | `and`, `or`, `xor`, `shl`, `shr_s/u`, `rotl`, `rotr` |
| i64 Comparison | `eqz`, `eq`, `ne`, `lt_s/u`, `gt_s/u`, `le_s/u`, `ge_s/u` |
| f32/f64 Comparison | `eq`, `ne`, `lt`, `gt`, `le`, `ge` |
| Memory Loads | `i32/i64/f32/f64.load`, sign/zero-extending variants (8/16/32-bit) |
| Memory Stores | `i32/i64/f32/f64.store`, narrowing variants (8/16/32-bit) |
| Memory Mgmt | `memory.size`, `memory.grow` |
### Parsed sections
Type, Function, Export, Code, Global, Memory, Start, Data, Import (stub), Table (stub), Element (stub), Custom (stub).
## Constraints
- **Standard Pascal only** — no runtime library, no classes.
- **Kernel-compatible** — all arithmetic (including `shr_s`) uses manual implementations, no RTL intrinsics.
- **Emulation layer** — `src/emu/` mirrors the real Asuro kernel API; only these interfaces are available.
## Requirements
- [Free Pascal Compiler](https://www.freepascal.org/) 3.2.2+ (x86_64-win64)
- Windows (build script is a `.bat` file)
## Building
```bat
# Normal build
build.bat
# Build with test suite
build.bat test
```
Output: `bin\WASURO.exe`
## Testing
```bat
build.bat test
bin\WASURO.exe
```
Runs 374 tests across 108 test units. Exit code equals the number of failed tests (0 on success), making it CI/CD-friendly.
## License
See repository for license details.
+93
View File
@@ -0,0 +1,93 @@
# build.ps1 — Build script for the WASURO project
param(
[switch]$Test,
[switch]$Clean,
[switch]$Run,
[switch]$Help,
[switch]$Debug
)
# Also accept positional string args (e.g. .\build.ps1 clean test run)
foreach ($a in $args) {
switch ($a.ToLower()) {
'test' { $Test = $true }
'clean' { $Clean = $true }
'run' { $Run = $true }
'debug' { $Debug = $true }
'help' { $Help = $true }
}
}
if ($Help) {
Write-Host 'Usage: .\build.ps1 [options]'
Write-Host 'Options:'
Write-Host ' test - Build with tests enabled'
Write-Host ' clean - Clean build outputs'
Write-Host ' run - Run the built executable after building'
Write-Host ' debug - Build with debug info and assertions enabled'
Write-Host ' help - Show this help message'
exit 0
}
$Root = $PSScriptRoot
$Src = Join-Path $Root 'src'
$Bin = Join-Path $Root 'bin'
$Lib = Join-Path $Root 'lib'
$FPC = 'C:\Lazarus\fpc\3.2.2\bin\x86_64-win64\fpc.exe'
# ── Clean ────────────────────────────────────────────────────────────
if ($Clean) {
Write-Host 'Cleaning build outputs...'
if (Test-Path $Bin) { Remove-Item $Bin -Recurse -Force }
if (Test-Path $Lib) { Remove-Item $Lib -Recurse -Force }
Write-Host 'Clean complete.'
}
if (-not (Test-Path $Bin)) { New-Item $Bin -ItemType Directory | Out-Null }
if (-not (Test-Path $Lib)) { New-Item $Lib -ItemType Directory | Out-Null }
# ── Lint ─────────────────────────────────────────────────────────────
& (Join-Path $Root 'lint.ps1') -SrcRoot $Src
if ($LASTEXITCODE -ne 0) { exit 1 }
# ── Build ────────────────────────────────────────────────────────────
$TestFlags = @()
if ($Test) { $TestFlags += '-dRUN_TESTS' }
if ($Debug) { $TestFlags += '-dDEBUG_OUTPUT' }
$fpcArgs = @(
$TestFlags
"-FE$Bin"
"-FU$Lib"
"-Fu$Src\emu"
"-Fu$Src\wasm"
"-Fu$Src\wasm\parser"
"-Fu$Src\wasm\parser\sections"
"-Fu$Src\wasm\test"
"-Fu$Src\wasm\test\opcodes"
"-Fu$Src\wasm\test\parsers"
"-Fu$Src\wasm\test\binaries"
"-Fu$Src\wasm\test\infra"
"-Fu$Src\wasm\types"
"-Fu$Src\wasm\vm"
"-Fu$Src\wasm\vm\opcodes"
'-gw3'
"-o$Bin\WASURO.exe"
"$Src\project\WASURO.lpr"
)
Write-Output $fpcArgs
& $FPC @fpcArgs
if ($LASTEXITCODE -ne 0) {
Write-Host "Build failed with error code $LASTEXITCODE"
exit $LASTEXITCODE
}
Write-Host "Build succeeded: $Bin\WASURO.exe"
# ── Run ──────────────────────────────────────────────────────────────
if ($Run) {
Write-Host 'Running WASURO...'
& "$Bin\WASURO.exe"
}
+48
View File
@@ -0,0 +1,48 @@
# lint.ps1 — Static lint rules for the WASURO project
# Called by build.ps1 before compilation. Exit 1 on any violation.
param(
[string]$SrcRoot = (Join-Path $PSScriptRoot 'src')
)
$fail = $false
# ── Rule: No native types in src\wasm ────────────────────────────────
# All code under src\wasm must use TWASM* aliases from wasm.types.builtin.
# Only wasm.types.builtin.pas itself may reference the raw types.
$forbiddenTypes = @(
'uint8','uint16','uint32','uint64',
'sint8','sint16',
'int32','int64',
'float','double',
'puint8','puint16','puint32','puint64',
'pfloat','pdouble','pchar',
'boolean','char','void','integer'
)
$pattern = '(?i)(?<![a-z0-9_])(' + ($forbiddenTypes -join '|') + ')(?![a-z0-9_])'
$files = Get-ChildItem (Join-Path $SrcRoot 'wasm') -Recurse -Filter '*.pas' |
Where-Object { $_.Name -ne 'wasm.types.builtin.pas' }
$ruleHits = 0
foreach ($file in $files) {
$content = [IO.File]::ReadAllText($file.FullName)
$matches = [regex]::Matches($content, $pattern)
if ($matches.Count -gt 0) {
$found = @{}
foreach ($m in $matches) { $found[$m.Value.ToLower()] = $true }
$list = ($found.Keys | Sort-Object) -join ', '
Write-Host " $($file.Name): $list"
$ruleHits++
}
}
if ($ruleHits -gt 0) {
Write-Host ''
Write-Host "Lint failed: $ruleHits file(s) use native types. Use TWASM* from wasm.types.builtin instead."
$fail = $true
}
# ── Add more rules here ─────────────────────────────────────────────
if ($fail) { exit 1 }
Write-Host 'Lint passed.'
exit 0
+55 -19
View File
@@ -5,32 +5,68 @@ uses
console, console,
types, wasm.types.builtin,
wasm.types.context,
wasm.types, wasm.types.stack,
wasm.parser, wasm.parser,
wasm.vm, wasm.test.binary, wasm.vm
wasm.types.stack; {$IFDEF RUN_TESTS}
, wasm.test
, wasm.test.framework
{$ENDIF}
;
var var
Context : PWASMProcessContext; Context : PWASMProcessContext;
ModuleSize : Int64;
ModuleBuffer : TWASMPUInt8;
ModuleFile : File;
begin begin
writestringln('[main] Initializing VM'); {$IFDEF RUN_TESTS}
wasm.vm.init(); wasm.vm.init();
wasm.test.run_all_tests;
writestringln('[main] Parsing WASM Binary'); halt(wasm.test.framework.FailedTests);
Context:= wasm.parser.parse(@wasm.test.binary.TEST_BINARY_1[0], puint8(@wasm.test.binary.TEST_BINARY_1[0] + $26)); {$ELSE}
console.writestringln('WASURO - WebAssembly Runtime in Object Pascal');
writestringln('[main] Running...'); wasm.vm.init();
Context^.ExecutionState.Running:= true; if ParamCount > 0 then begin
while (wasm.vm.tick(Context)) do; if not FileExists(ParamStr(1)) then begin
writestringln('[main] Finished Execution'); console.writestringln('File not found.');
writestring('[main] Returns: '); halt(1);
while Context^.ExecutionState.Operand_Stack^.Top > 0 do begin
write(wasm.types.stack.popi32(Context^.ExecutionState.Operand_Stack),', ');
end; end;
writeln(); Assign(ModuleFile, ParamStr(1));
while true do sleep(1000); Reset(ModuleFile, 1);
ModuleSize := FileSize(ModuleFile);
GetMem(ModuleBuffer, ModuleSize);
BlockRead(ModuleFile, ModuleBuffer^, ModuleSize);
Close(ModuleFile);
console.writestringln('Module loaded.');
Context := wasm.parser.parse(ModuleBuffer, TWASMPUInt8(ModuleBuffer + ModuleSize));
while wasm.vm.tick(Context) do ;
console.writestringln('Execution finished.');
console.writestringln('');
console.writestringln('--- VM State ---');
writeln('IP: ', Context^.ExecutionState.IP);
writeln('Running: ', Context^.ExecutionState.Running);
writeln('');
writeln('Operand Stack (', Context^.ExecutionState.Operand_Stack^.Top, ' entries):');
if Context^.ExecutionState.Operand_Stack^.Top > 0 then
wasm.types.stack.walk(Context^.ExecutionState.Operand_Stack)
else
console.writestringln(' (empty)');
writeln('');
writeln('Control Stack (', Context^.ExecutionState.Control_Stack^.Top, ' entries):');
if Context^.ExecutionState.Control_Stack^.Top > 0 then
wasm.types.stack.walk(Context^.ExecutionState.Control_Stack)
else
console.writestringln(' (empty)');
console.writestringln('----------------');
FreeMem(ModuleBuffer);
end else begin
console.writestringln('Usage: WASURO <module.wasm>');
halt(1);
end;
{$ENDIF}
end. end.
@@ -3,16 +3,16 @@ unit wasm.parser.sections.codeSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.enums, wasm.types.values, wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure printCtxCode(ctx : PWASMProcessContext); procedure printCtxCode(ctx : PWASMProcessContext);
var var
i : uint32; i : TWASMUInt32;
begin begin
writestring('[wasm.parser] Flat Code: '); writestring('[wasm.parser] Flat Code: ');
@@ -25,15 +25,15 @@ end;
procedure walk(ctx : PWASMProcessContext); procedure walk(ctx : PWASMProcessContext);
var var
localpos, pos, bend : puint8; localpos, pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
currentEntry : PWASMCodeEntry; currentEntry : PWASMCodeEntry;
i,j,l : uint32; i,j,l : TWASMUInt32;
localCount,localTemp,localIndex : uint32; localCount,localTemp,localIndex : TWASMUInt32;
localType: TWasmValueType; localType: TWasmValueType;
codeLength: uint32; codeLength: TWASMUInt32;
codeOffset: uint32; codeOffset: TWASMUInt32;
totalSize: uint32; totalSize: TWASMUInt32;
begin begin
// Walk the code entries // Walk the code entries
for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin
@@ -59,25 +59,27 @@ begin
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
localpos, pos, bend : puint8; localpos, pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
currentEntry : PWASMCodeEntry; currentEntry : PWASMCodeEntry;
i,j,l : uint32; i,j,l : TWASMUInt32;
localCount,localTemp,localIndex : uint32; localCount,localTemp,localIndex : TWASMUInt32;
localType: TWasmValueType; localType: TWasmValueType;
codeLength: uint32; codeLength: TWASMUInt32;
codeOffset: uint32; codeOffset: TWASMUInt32;
totalSize: uint32; totalSize: TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Code - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Code - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers // Initialize the read/end pointers
pos:= buffer; pos:= buffer;
bend:= puint8(pos + section_length); bend:= TWASMPUInt8(pos + section_length);
// Initialize the code section // Initialize the code section
ctx^.Sections.CodeSection:= PWASMCodeSection(kalloc(sizeof(TWASMCodeSection))); ctx^.Sections.CodeSection:= PWASMCodeSection(kalloc(sizeof(TWASMCodeSection)));
@@ -158,7 +160,7 @@ begin
end; end;
// Read the code // Read the code
currentEntry^.Code:= puint8(kalloc(currentEntry^.CodeLength)); currentEntry^.Code:= TWASMPUInt8(kalloc(currentEntry^.CodeLength));
for j:=1 to currentEntry^.CodeLength do begin for j:=1 to currentEntry^.CodeLength do begin
currentEntry^.Code[j - 1]:= pos^; currentEntry^.Code[j - 1]:= pos^;
inc(pos); inc(pos);
@@ -171,20 +173,21 @@ begin
totalSize:= totalSize + currentEntry^.CodeLength; totalSize:= totalSize + currentEntry^.CodeLength;
end; end;
ctx^.ExecutionState.Code:= puint8(kalloc(totalSize)); ctx^.ExecutionState.Code:= TWASMPUInt8(kalloc(totalSize));
ctx^.ExecutionState.Limit:= totalSize; ctx^.ExecutionState.Limit:= totalSize;
localpos:= ctx^.ExecutionState.Code; localpos:= ctx^.ExecutionState.Code;
for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin
currentEntry:= @ctx^.Sections.CodeSection^.Entries[i - 1]; currentEntry:= @ctx^.Sections.CodeSection^.Entries[i - 1];
currentEntry^.CodeIndex:= uint32(localpos - ctx^.ExecutionState.Code); currentEntry^.CodeIndex:= TWASMUInt32(localpos - ctx^.ExecutionState.Code);
for j:=1 to currentEntry^.CodeLength do begin for j:=1 to currentEntry^.CodeLength do begin
localpos^:= currentEntry^.Code[j - 1]; localpos^:= currentEntry^.Code[j - 1];
inc(localpos); inc(localpos);
end; end;
end; end;
end; end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
@@ -3,17 +3,21 @@ unit wasm.parser.sections.customSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
begin begin
writestring('[wasm.parser] Handle Section: Custom - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Custom - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
{ Custom sections are ignored in this implementation }
console.writestringln('[wasm.parser] TODO: Custom section skipped.');
end; end;
end. end.
@@ -0,0 +1,48 @@
unit wasm.parser.sections.dataCountSection;
interface
uses
wasm.types.builtin, wasm.types.context;
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation
uses console, leb128, lmemorymanager, wasm.types.sections;
{ DataCount section (ID 12): contains a single u32 count of data segments.
Pre-allocates the DataSegments array so that bulk memory opcodes
can reference segments by index during validation. }
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
dataCount : TWASMUInt32;
begin
{$IFDEF DEBUG_OUTPUT}
console.writestring('[wasm.parser] Handle Section: DataCount - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer;
bend := TWASMPUInt8(buffer + section_length);
bytesRead := read_leb128_to_uint32(pos, bend, @dataCount);
Inc(pos, bytesRead);
{$IFDEF DEBUG_OUTPUT}
writestring('[wasm.parser] Data Count: ');
writeintlnWND(dataCount, 0);
{$ENDIF}
{ Pre-allocate data segment storage with correct count.
The actual segment data will be filled when the Data section is parsed. }
ctx^.ExecutionState.DataSegments^.SegmentCount := dataCount;
if dataCount > 0 then
ctx^.ExecutionState.DataSegments^.Segments := PWASMDataSegment(kalloc(dataCount * sizeof(TWASMDataSegment)))
else
ctx^.ExecutionState.DataSegments^.Segments := nil;
end;
end.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -3,17 +3,17 @@ unit wasm.parser.sections.exportSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.enums, wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure walk(ctx : PWASMProcessContext); procedure walk(ctx : PWASMProcessContext);
var var
currentEntry : PWASMExportEntry; currentEntry : PWASMExportEntry;
i : uint32; i : TWASMUInt32;
begin begin
// Walk the export entries // Walk the export entries
@@ -28,20 +28,22 @@ begin
end; end;
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
pos, bend : puint8; pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
currentEntry : PWASMExportEntry; currentEntry : PWASMExportEntry;
i,j : uint32; i,j : TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Export - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Export - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers // Initialize the read/end pointers
pos:= buffer; pos:= buffer;
bend:= puint8(pos + section_length); bend:= TWASMPUInt8(pos + section_length);
// Initialize the export section // Initialize the export section
ctx^.Sections.ExportSection:= PWASMExportSection(kalloc(sizeof(TWASMExportSection))); ctx^.Sections.ExportSection:= PWASMExportSection(kalloc(sizeof(TWASMExportSection)));
@@ -69,12 +71,12 @@ begin
inc(pos, bytesRead); inc(pos, bytesRead);
// Read the export name // Read the export name
currentEntry^.Name:= pchar(kalloc(currentEntry^.NameLength + 1)); currentEntry^.Name:= TWASMPChar(kalloc(currentEntry^.NameLength + 1));
for j:=0 to currentEntry^.NameLength - 1 do begin for j:=0 to currentEntry^.NameLength - 1 do begin
currentEntry^.Name[j]:= char(pos^); currentEntry^.Name[j]:= TWASMChar(pos^);
inc(pos); inc(pos);
end; end;
currentEntry^.Name[currentEntry^.NameLength]:= char($00); currentEntry^.Name[currentEntry^.NameLength]:= TWASMChar($00);
// Read the export type // Read the export type
currentEntry^.ExportType:= TWasmExportType(pos^); currentEntry^.ExportType:= TWasmExportType(pos^);
@@ -85,8 +87,9 @@ begin
inc(pos, bytesRead); inc(pos, bytesRead);
end; end;
end; end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
@@ -3,17 +3,17 @@ unit wasm.parser.sections.functionSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure walk(ctx : PWASMProcessContext); procedure walk(ctx : PWASMProcessContext);
var var
currentFunc : PWASMFunction; currentFunc : PWASMFunction;
i : uint32; i : TWASMUInt32;
begin begin
// Walk the functions // Walk the functions
@@ -24,20 +24,22 @@ begin
end; end;
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
pos, bend : puint8; pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
currentFunc : PWASMFunction; currentFunc : PWASMFunction;
i : uint32; i : TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Function - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Function - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers // Initialize the read/end pointers
pos:= buffer; pos:= buffer;
bend:= puint8(pos + section_length); bend:= TWASMPUInt8(pos + section_length);
// Initialize the function section // Initialize the function section
ctx^.Sections.FunctionSection:= PWASMFunctionSection(kalloc(sizeof(TWASMFunctionSection))); ctx^.Sections.FunctionSection:= PWASMFunctionSection(kalloc(sizeof(TWASMFunctionSection)));
@@ -64,8 +66,9 @@ begin
inc(pos, bytesRead); inc(pos, bytesRead);
end; end;
end; end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
@@ -3,16 +3,16 @@ unit wasm.parser.sections.globalSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.enums, wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure walk(ctx : PWASMProcessContext); procedure walk(ctx : PWASMProcessContext);
var var
i : uint32; i : TWASMUInt32;
entry : PWASMGlobalEntry; entry : PWASMGlobalEntry;
begin begin
for i := 0 to ctx^.ExecutionState.Globals^.GlobalCount - 1 do begin for i := 0 to ctx^.ExecutionState.Globals^.GlobalCount - 1 do begin
@@ -35,25 +35,27 @@ begin
end; end;
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
pos, bend : puint8; pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
globalCount : uint32; globalCount : TWASMUInt32;
i : uint32; i : TWASMUInt32;
entry : PWASMGlobalEntry; entry : PWASMGlobalEntry;
valType : uint8; valType : TWASMUInt8;
mutFlag : uint8; mutFlag : TWASMUInt8;
opcode : uint8; opcode : TWASMUInt8;
tmpU32 : uint32; tmpU32 : TWASMUInt32;
tmpU64 : uint64; tmpU64 : TWASMUInt64;
begin begin
writestring('[wasm.parser] Handle Section: Global - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Global - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer; pos := buffer;
bend := puint8(buffer + section_length); bend := TWASMPUInt8(buffer + section_length);
{ Read global count } { Read global count }
bytesRead := read_leb128_to_uint32(pos, bend, @globalCount); bytesRead := read_leb128_to_uint32(pos, bend, @globalCount);
@@ -88,19 +90,19 @@ begin
$41: begin { i32.const } $41: begin { i32.const }
bytesRead := read_leb128_to_uint32(pos, bend, @tmpU32); bytesRead := read_leb128_to_uint32(pos, bend, @tmpU32);
Inc(pos, bytesRead); Inc(pos, bytesRead);
entry^.Value.i32Value := int32(tmpU32); entry^.Value.i32Value := TWASMInt32(tmpU32);
end; end;
$42: begin { i64.const } $42: begin { i64.const }
bytesRead := read_leb128_to_uint64(pos, bend, @tmpU64); bytesRead := read_leb128_to_uint64(pos, bend, @tmpU64);
Inc(pos, bytesRead); Inc(pos, bytesRead);
entry^.Value.i64Value := int64(tmpU64); entry^.Value.i64Value := TWASMInt64(tmpU64);
end; end;
$43: begin { f32.const } $43: begin { f32.const }
entry^.Value.f32Value := pfloat(pos)^; entry^.Value.f32Value := TWASMPFloat(pos)^;
Inc(pos, 4); Inc(pos, 4);
end; end;
$44: begin { f64.const } $44: begin { f64.const }
entry^.Value.f64Value := pdouble(pos)^; entry^.Value.f64Value := TWASMPDouble(pos)^;
Inc(pos, 8); Inc(pos, 8);
end; end;
else else
@@ -115,8 +117,9 @@ begin
if (pos < bend) and (pos^ = $0B) then if (pos < bend) and (pos^ = $0B) then
Inc(pos); Inc(pos);
end; end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
File diff suppressed because it is too large. Load diff
@@ -3,16 +3,16 @@ unit wasm.parser.sections.memorySection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types, wasm.types.heap; wasm.types.sections, wasm.types.context, wasm.types.heap;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure walk(ctx : PWASMProcessContext); procedure walk(ctx : PWASMProcessContext);
var var
i : uint32; i : TWASMUInt32;
mem : PWASMMemoryLimits; mem : PWASMMemoryLimits;
begin begin
for i := 0 to ctx^.Sections.MemorySection^.MemoryCount - 1 do begin for i := 0 to ctx^.Sections.MemorySection^.MemoryCount - 1 do begin
@@ -29,21 +29,23 @@ begin
end; end;
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
pos, bend : puint8; pos, bend : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
memCount : uint32; memCount : TWASMUInt32;
i : uint32; i : TWASMUInt32;
mem : PWASMMemoryLimits; mem : PWASMMemoryLimits;
flags : uint32; flags : TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Memory - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Memory - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer; pos := buffer;
bend := puint8(buffer + section_length); bend := TWASMPUInt8(buffer + section_length);
{ Read memory count } { Read memory count }
bytesRead := read_leb128_to_uint32(pos, bend, @memCount); bytesRead := read_leb128_to_uint32(pos, bend, @memCount);
@@ -77,8 +79,9 @@ begin
while ctx^.ExecutionState.Memory^.PageCount < mem^.InitialPages do while ctx^.ExecutionState.Memory^.PageCount < mem^.InitialPages do
wasm.types.heap.expand_heap(ctx^.ExecutionState.Memory); wasm.types.heap.expand_heap(ctx^.ExecutionState.Memory);
end; end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
@@ -3,28 +3,32 @@ unit wasm.parser.sections.startSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
bytesRead : uint8; bytesRead : TWASMUInt8;
funcIdx : uint32; funcIdx : TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Start - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Start - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
{ Read the start function index } { Read the start function index }
bytesRead := read_leb128_to_uint32(buffer, puint8(buffer + section_length), @funcIdx); bytesRead := read_leb128_to_uint32(buffer, TWASMPUInt8(buffer + section_length), @funcIdx);
ctx^.Sections.StartIndex := int32(funcIdx); ctx^.Sections.StartIndex := TWASMInt32(funcIdx);
writestring('[wasm.parser] Start Function Index: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(funcIdx, 0); console.writestring('[wasm.parser] Start Function Index: ');
console.writeintlnWND(funcIdx, 0);
{$ENDIF}
end; end;
end. end.
@@ -3,17 +3,92 @@ unit wasm.parser.sections.tableSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos: TWASMPUInt8;
buf_end: TWASMPUInt8;
bytesRead: TWASMUInt8;
table_count, i, j, min_size, max_size: TWASMUInt32;
elem_type, limits_flag: TWASMUInt8;
tables: PWASMTables;
begin begin
writestring('[wasm.parser] Handle Section: Table - Size: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(section_length, 0); console.writestring('[wasm.parser] Handle Section: Table - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer;
buf_end := buffer;
Inc(buf_end, section_length);
bytesRead := read_leb128_to_uint32(pos, buf_end, @table_count);
Inc(pos, bytesRead);
{$IFDEF DEBUG_OUTPUT}
writestring('[wasm.parser] Tables: ');
writeintlnWND(table_count, 0);
{$ENDIF}
tables := ctx^.ExecutionState.Tables;
tables^.TableCount := table_count;
if table_count > 0 then
tables^.Tables := PWASMTableInstance(kalloc(sizeof(TWASMTableInstance) * table_count))
else
tables^.Tables := nil;
for i := 0 to table_count - 1 do begin
elem_type := pos^;
Inc(pos);
limits_flag := pos^;
Inc(pos);
bytesRead := read_leb128_to_uint32(pos, buf_end, @min_size);
Inc(pos, bytesRead);
max_size := 0;
if limits_flag = 1 then begin
bytesRead := read_leb128_to_uint32(pos, buf_end, @max_size);
Inc(pos, bytesRead);
end;
{$IFDEF DEBUG_OUTPUT}
console.writestring('[wasm.parser] Table ');
console.writeintWND(i, 0);
console.writestring(' - ElemType: $');
console.writeintWND(elem_type, 0);
console.writestring(' Initial: ');
console.writeintWND(min_size, 0);
if limits_flag = 1 then begin
console.writestring(' Max: ');
console.writeintWND(max_size, 0);
end;
console.writestringln('');
{$ENDIF}
tables^.Tables[i].ElementType := elem_type;
tables^.Tables[i].Size := min_size;
tables^.Tables[i].HasMax := (limits_flag = 1);
if limits_flag = 1 then
tables^.Tables[i].MaxSize := max_size
else
tables^.Tables[i].MaxSize := 0;
{ Allocate elements and initialize to $FFFFFFFF (uninitialized) }
if min_size > 0 then begin
tables^.Tables[i].Elements := TWASMPUInt32(kalloc(sizeof(TWASMUInt32) * min_size));
for j := 0 to min_size - 1 do
tables^.Tables[i].Elements[j] := $FFFFFFFF;
end else
tables^.Tables[i].Elements := nil;
end;
end; end;
end. end.
@@ -3,10 +3,10 @@ unit wasm.parser.sections.typeSection;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types; wasm.types.enums, wasm.types.values, wasm.types.sections, wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation implementation
@@ -14,10 +14,10 @@ procedure walk(ctx : PWASMProcessContext);
var var
currentType : PWASMType; currentType : PWASMType;
currentParam : PWASMParam; currentParam : PWASMParam;
i,j : uint32; i,j : TWASMUInt32;
begin begin
// Walk the types // Walk the wasm.types.builtin
for i:=1 to ctx^.Sections.TypeSection^.TypeCount do begin for i:=1 to ctx^.Sections.TypeSection^.TypeCount do begin
currentType:= @ctx^.Sections.TypeSection^.Types[i - 1]; currentType:= @ctx^.Sections.TypeSection^.Types[i - 1];
writestring('[wasm.parser] Index: '); writestring('[wasm.parser] Index: ');
@@ -50,48 +50,51 @@ begin
end; end;
end; end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext); procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var var
pos : puint8; pos : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
currentType : PWASMType; currentType : PWASMType;
currentParam : PWASMParam; currentParam : PWASMParam;
i, parsedTypes : uint32; i, parsedTypes : TWASMUInt32;
begin begin
writestring('[wasm.parser] Handle Section: Type - Size: ');
writeintlnWND(section_length, 0); {$IFDEF DEBUG_OUTPUT}
console.writestring('[wasm.parser] Handle Section: Type - Size: ');
console.writeintlnWND(section_length, 0);
{$ENDIF}
pos:= buffer; pos:= buffer;
// Initialize the type section // Initialize the type section
ctx^.Sections.TypeSection:= PWASMTypeSection(kalloc(sizeof(TWASMTypeSection))); ctx^.Sections.TypeSection:= PWASMTypeSection(kalloc(sizeof(TWASMTypeSection)));
ctx^.Sections.TypeSection^.TypeCount:= 0; ctx^.Sections.TypeSection^.TypeCount:= 0;
// Read the number of function types // Read the number of function wasm.types.builtin
bytesRead:= read_leb128_to_uint32(buffer, puint8(buffer + section_length), @ctx^.Sections.TypeSection^.TypeCount); bytesRead:= read_leb128_to_uint32(buffer, TWASMPUInt8(buffer + section_length), @ctx^.Sections.TypeSection^.TypeCount);
inc(pos, bytesRead); inc(pos, bytesRead);
// Read the function types // Read the function wasm.types.builtin
if(ctx^.Sections.TypeSection^.TypeCount > 0) then begin if(ctx^.Sections.TypeSection^.TypeCount > 0) then begin
// Allocate the first type // Allocate the first type
ctx^.Sections.TypeSection^.Types:= PWASMType(kalloc(sizeof(TWASMType) * ctx^.Sections.TypeSection^.TypeCount)); ctx^.Sections.TypeSection^.Types:= PWASMType(kalloc(sizeof(TWASMType) * ctx^.Sections.TypeSection^.TypeCount));
// Read the function types // Read the function wasm.types.builtin
for parsedTypes:=1 to ctx^.Sections.TypeSection^.TypeCount do begin for parsedTypes:=1 to ctx^.Sections.TypeSection^.TypeCount do begin
currentType:= @ctx^.Sections.TypeSection^.Types[parsedTypes - 1]; currentType:= @ctx^.Sections.TypeSection^.Types[parsedTypes - 1];
// Check if we are at the end of the buffer // Check if we are at the end of the buffer
if pos >= puint8(buffer + section_length) then Exit; if pos >= TWASMPUInt8(buffer + section_length) then Exit;
// Read the function type // Read the function type
currentType^._type:= pos^; currentType^._type:= pos^;
inc(pos); inc(pos);
// Read the number of parameters // Read the number of parameters
bytesRead:= read_leb128_to_uint32(pos, puint8(buffer + section_length), @currentType^.ParamCount); bytesRead:= read_leb128_to_uint32(pos, TWASMPUInt8(buffer + section_length), @currentType^.ParamCount);
inc(pos, bytesRead); inc(pos, bytesRead);
// Read the parameter types // Read the parameter wasm.types.builtin
if(currentType^.ParamCount > 0) then begin if(currentType^.ParamCount > 0) then begin
currentType^.ParamTypes:= PWASMParam(kalloc(sizeof(TWASMParam) * currentType^.ParamCount)); currentType^.ParamTypes:= PWASMParam(kalloc(sizeof(TWASMParam) * currentType^.ParamCount));
for i:=1 to currentType^.ParamCount do begin for i:=1 to currentType^.ParamCount do begin
@@ -102,10 +105,10 @@ begin
end; end;
// Read the number of return values // Read the number of return values
bytesRead:= read_leb128_to_uint32(pos, puint8(buffer + section_length), @currentType^.ReturnCount); bytesRead:= read_leb128_to_uint32(pos, TWASMPUInt8(buffer + section_length), @currentType^.ReturnCount);
inc(pos, bytesRead); inc(pos, bytesRead);
// Read the return types // Read the return wasm.types.builtin
if(currentType^.ReturnCount > 0) then begin if(currentType^.ReturnCount > 0) then begin
currentType^.ReturnTypes:= PWASMParam(kalloc(sizeof(TWASMParam) * currentType^.ReturnCount)); currentType^.ReturnTypes:= PWASMParam(kalloc(sizeof(TWASMParam) * currentType^.ReturnCount));
for i:=1 to currentType^.ReturnCount do begin for i:=1 to currentType^.ReturnCount do begin
@@ -117,8 +120,10 @@ begin
end; end;
end; end;
// Walk the types // Walk the wasm.types.builtin
{$IFDEF DEBUG_OUTPUT}
walk(ctx); walk(ctx);
{$ENDIF}
end; end;
end. end.
+37 -15
View File
@@ -3,11 +3,11 @@ unit wasm.parser;
interface interface
uses uses
types, lmemorymanager, console, leb128, wasm.types.builtin, lmemorymanager, console, leb128,
wasm.types, wasm.types.heap, wasm.types.stack, wasm.types.enums, wasm.types.sections, wasm.types.context, wasm.types.heap, wasm.types.stack,
wasm.parser.sections; wasm.parser.sections, wasm.types.constants;
function parse(buffer: puint8; buffer_end: puint8) : PWASMProcessContext; function parse(buffer: TWASMPUInt8; buffer_end: TWASMPUInt8) : PWASMProcessContext;
implementation implementation
@@ -36,6 +36,7 @@ begin
// Initialize the sections // Initialize the sections
ctx^.Sections.TypeSection:= nil; ctx^.Sections.TypeSection:= nil;
ctx^.Sections.ImportSection:= nil;
ctx^.Sections.FunctionSection:= nil; ctx^.Sections.FunctionSection:= nil;
ctx^.Sections.ExportSection:= nil; ctx^.Sections.ExportSection:= nil;
ctx^.Sections.CodeSection:= nil; ctx^.Sections.CodeSection:= nil;
@@ -47,37 +48,58 @@ begin
ctx^.ExecutionState.Globals^.GlobalCount:= 0; ctx^.ExecutionState.Globals^.GlobalCount:= 0;
ctx^.ExecutionState.Globals^.Globals:= nil; ctx^.ExecutionState.Globals^.Globals:= nil;
// Initialize tables (empty until table section is parsed)
ctx^.ExecutionState.Tables:= PWASMTables(kalloc(sizeof(TWASMTables)));
ctx^.ExecutionState.Tables^.TableCount:= 0;
ctx^.ExecutionState.Tables^.Tables:= nil;
// Initialize data segments (empty until data section is parsed)
ctx^.ExecutionState.DataSegments:= PWASMDataSegments(kalloc(sizeof(TWASMDataSegments)));
ctx^.ExecutionState.DataSegments^.SegmentCount:= 0;
ctx^.ExecutionState.DataSegments^.Segments:= nil;
// Initialize element segments (empty until element section is parsed)
ctx^.ExecutionState.ElementSegments:= PWASMElementSegments(kalloc(sizeof(TWASMElementSegments)));
ctx^.ExecutionState.ElementSegments^.SegmentCount:= 0;
ctx^.ExecutionState.ElementSegments^.Segments:= nil;
newContext:= ctx; newContext:= ctx;
end; end;
function parse(buffer: puint8; buffer_end: puint8): PWASMProcessContext; function parse(buffer: TWASMPUInt8; buffer_end: TWASMPUInt8): PWASMProcessContext;
var var
ctx : PWASMProcessContext; ctx : PWASMProcessContext;
pos : puint8; pos : TWASMPUInt8;
bytesRead : uint8; bytesRead : TWASMUInt8;
section_id : uint8; section_id : TWASMUInt8;
section_length : uint32; section_length : TWASMUInt32;
begin begin
// Allocate the context // Allocate the context
ctx:= newContext(); ctx:= newContext();
pos:= buffer; pos:= buffer;
writestringln('[wasm.parser] Parsing WASM Binary'); {$IFDEF DEBUG_OUTPUT}
console.writestringln('[wasm.parser] Starting parse of WASM binary.');
{$ENDIF}
// Check for the WASM Magic // Check for the WASM Magic
if(puint32(pos)^ = wasm.types.WASM_HDR_MAGIC) then begin if(TWASMPUInt32(pos)^ = wasm.types.constants.WASM_HDR_MAGIC) then begin
writestringln('[wasm.parser] Binary is valid.'); {$IFDEF DEBUG_OUTPUT}
console.writestringln('[wasm.parser] Binary is valid.');
{$ENDIF}
// Set binary to valid // Set binary to valid
ctx^.ValidBinary:= true; ctx^.ValidBinary:= true;
inc(pos, 4); inc(pos, 4);
// Read the version // Read the version
ctx^.Version:= puint32(pos)^; ctx^.Version:= TWASMPUInt32(pos)^;
inc(pos, 4); inc(pos, 4);
writestring('[wasm.parser] Version: '); {$IFDEF DEBUG_OUTPUT}
writeintlnWND(ctx^.Version, 0); console.writestring('[wasm.parser] Version: ');
console.writeintlnWND(ctx^.Version, 0);
{$ENDIF}
// Read the sections // Read the sections
while (pos < buffer_end) do begin while (pos < buffer_end) do begin
+8 -5
View File
@@ -3,8 +3,8 @@ unit wasm.parser.sections;
interface interface
uses uses
types, wasm.types.builtin,
wasm.types, wasm.types.enums, wasm.types.context,
wasm.parser.sections.customSection, wasm.parser.sections.customSection,
wasm.parser.sections.typeSection, wasm.parser.sections.typeSection,
wasm.parser.sections.importSection, wasm.parser.sections.importSection,
@@ -16,13 +16,14 @@ uses
wasm.parser.sections.startSection, wasm.parser.sections.startSection,
wasm.parser.sections.elementSection, wasm.parser.sections.elementSection,
wasm.parser.sections.codeSection, wasm.parser.sections.codeSection,
wasm.parser.sections.dataSection; wasm.parser.sections.dataSection,
wasm.parser.sections.dataCountSection;
procedure handle(sectionId : uint8; buffer : puint8; section_length : uint32; ctx : PWASMProcessContext); procedure handle(sectionId : TWASMUInt8; buffer : TWASMPUInt8; section_length : TWASMUInt32; ctx : PWASMProcessContext);
implementation implementation
procedure handle(sectionId : uint8; buffer : puint8; section_length : uint32; ctx : PWASMProcessContext); procedure handle(sectionId : TWASMUInt8; buffer : TWASMPUInt8; section_length : TWASMUInt32; ctx : PWASMProcessContext);
begin begin
// Handle the section // Handle the section
case sectionId of case sectionId of
@@ -50,6 +51,8 @@ begin
ord(sidCode): wasm.parser.sections.codeSection.handle (buffer, section_length, ctx); ord(sidCode): wasm.parser.sections.codeSection.handle (buffer, section_length, ctx);
// Data Section // Data Section
ord(sidData): wasm.parser.sections.dataSection.handle (buffer, section_length, ctx); ord(sidData): wasm.parser.sections.dataSection.handle (buffer, section_length, ctx);
// DataCount Section
ord(sidDataCount): wasm.parser.sections.dataCountSection.handle (buffer, section_length, ctx);
end; end;
end; end;
Loaded 20 of 456 files, more files were not shown because too many files have changed in this diff. Show more