Compare commits

29 Commits
Author SHA1 Message Date
t3hn3rd b6115c88eb Merge pull request 'Bug: Removed direct calls to FPC Writeln/Write' (#2) from feature/compatability into develop
Reviewed-on: #2
2026-03-03 21:46:25 +00:00
t3hn3rd 152e6dc241 Bug: Removed direct calls to FPC Writeln/Write 2026-03-03 21:45:50 +00:00
t3hn3rd ac4c631a5c Merge pull request 'refactor: replace emu/console.pas with hookable wasm.vm.io abstraction' (#1) from feature/compatability into develop
Reviewed-on: #1
2026-03-03 21:32:27 +00:00
t3hn3rd 5bb7107997 refactor: replace emu/console.pas with hookable wasm.vm.io abstraction
All VM output now funnels through a single writechar hook
(TIOWriteCharHook) that the OS/emulator layer provides at startup.
High-level helpers (writestring, writeintWND, writehexpair, etc.)
are built entirely on writechar.

- Add src/wasm/vm/wasm.vm.io.pas (hookable IO layer)
- Add src/wasm/test/infra/wasm.test.io.pas (15 assertions)
- Update ~75 files: console -> wasm.vm.io in uses clauses
- Wire emu_writechar (RTL Write wrapper) in WASURO.lpr
- Remove emu/console.pas dependency from all wasm code
2026-03-03 21:31:27 +00:00
t3hn3rd 757d762faf Merge branch 'feature/WASI' into develop 2026-02-25 21:44:28 +00:00
t3hn3rd 302dcb66f0 feature: WASI preview1 support, per-context isolation & glue API
Implement full WASI snapshot_preview1 with 46 registered host functions,
per-context hook/registry isolation, and a single-unit public API.

WASI Preview1 (15 new handler units):
- Tier 1: fd_write, fd_read, fd_close, fd_seek, fd_prestat_get,
  fd_prestat_dir_name, fd_fdstat_get, proc_exit, environ_*, args_*
- Tier 2: clock_time_get, clock_res_get, random_get
- Tier 3: 14 fd_* stubs, 10 path_* stubs (ENOSYS)
- Tier 4: poll_oneoff, proc_raise, sched_yield, 4 sock_* stubs

Per-context isolation:
- Move WASIHooks (12 hook table) and HostFuncRegistry onto
  TWASMProcessContext — each context is fully independent
- Dynamic registry: starts at 16 entries, doubles on demand, no cap
- All 15 preview1 handlers read hooks from context, not globals

Glue API (wasm.pas):
- Single entry point: wasm_init, wasm_load, wasm_set_*,
  wasm_register_wasi_preview1, wasm_register_host_func,
  wasm_resolve_imports, wasm_start, wasm_prepare_start, wasm_tick,
  wasm_dump_state
- WASURO.lpr simplified to use only the wasm unit

Refactoring:
- Rename leb128.pas -> wasm.types.leb128.pas (updates 40+ opcode units)
- New wasm.types.wasi.pas with WASI errno/filetype constants
- New wasm.types.context.pas fields for hooks + registry types
- New wasm.vm.setup unit (find_start, count_func_imports)
- New wasi.emu.hooks for emulator-side hook implementations
- Add read_uint16, write_uint16 to wasm.types.heap

Testing:
- 10 new test units: hooks, registry, glue, stubs, clock, random,
  extensibility, call, types, vm.setup (1087 tests / 232 units)
- E2E WAT test runner (wat.ps1) with 9 integration tests:
  hello, exit42, multiwrite, prestat, fdstat, environ, clock,
  clockres, random

121 files changed, 5391 insertions(+), 267 deletions(-)
2026-02-25 21:44:00 +00:00
t3hn3rd 378f999143 Merge branch 'hotfix/readme.2' into develop 2026-02-24 23:18:43 +00:00
t3hn3rd c2e47ffd7a ReadMe updated to reflect current project status. 2026-02-24 23:18:35 +00:00
t3hn3rd 1f27b99284 Merge branch 'feature/debug-output' into develop 2026-02-24 23:08:12 +00:00
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
506 changed files with 22047 additions and 3143 deletions

No files matched your search

+3
View File
@@ -1,3 +1,6 @@
bin
lib
AGENTS.md
GAP_ANALYSIS.md
*.pdf
doc/WASI.md
+329 -62
View File
File diff suppressed because it is too large. Load diff
-39
View File
@@ -1,39 +0,0 @@
@echo off
setlocal
set ROOT=%~dp0
set SRC=%ROOT%src
set BIN=%ROOT%bin
set LIB=%ROOT%lib
set FPC=C:\Lazarus\fpc\3.2.2\bin\x86_64-win64\fpc.exe
set TESTFLAGS=
if "%1"=="test" set TESTFLAGS=-dRUN_TESTS
if not exist "%BIN%" mkdir "%BIN%"
if not exist "%LIB%" mkdir "%LIB%"
"%FPC%" ^
%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\infra" ^
-Fu"%SRC%\wasm\types" ^
-Fu"%SRC%\wasm\vm" ^
-gw3 ^
-o"%BIN%\WASURO.exe" ^
"%SRC%\project\WASURO.lpr"
if %ERRORLEVEL% NEQ 0 (
echo Build failed with error code %ERRORLEVEL%
exit /b %ERRORLEVEL%
)
echo Build succeeded: %BIN%\WASURO.exe
+113
View File
@@ -0,0 +1,113 @@
# build.ps1 — Build script for the WASURO project
param(
[switch]$Test,
[switch]$Clean,
[switch]$Run,
[switch]$Help,
[switch]$Debug,
[switch]$E2E
)
# 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 }
'e2e' { $E2E = $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 ' e2e - Run end-to-end wat tests'
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'
if (($Test -and $E2E) -or ($Run -and $E2E)) {
Write-Host 'Error: --e2e cannot be combined with --test or --run. E2E implies a run of E2E wat tests.' -ForegroundColor Red
exit 1
}
# ── 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
"-v0ew"
"-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"
"-Fu$Src\wasm\wasi"
"-Fu$Src\wasm\wasi\preview1"
"-Fu$Src\wasm\test\wasi"
'-gw3'
"-o$Bin\WASURO.exe"
"$Src\project\WASURO.lpr"
)
& $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"
}
if ($E2E) {
Write-Host 'Running end-to-end WAT tests...'
& (Join-Path $Root 'wat.ps1')
if ($LASTEXITCODE -ne 0) {
Write-Host "WAT tests failed with error code $LASTEXITCODE"
exit $LASTEXITCODE
}
exit $LASTEXITCODE
}
+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
-161
View File
File diff suppressed because it is too large. Load diff
-66
View File
@@ -1,66 +0,0 @@
unit leb128;
interface
uses
types;
function read_leb128_to_uint64(buf : puint8; buf_end : puint8; res : puint64) : uint8;
function read_leb128_to_uint32(buf : puint8; buf_end : puint8; res : puint32) : uint8;
implementation
function read_leb128_to_uint64(buf: puint8; buf_end: puint8; res: puint64): uint8;
var
ptr : puint8;
shift : uint32;
localResult : uint64;
currentByte : uint8;
begin
ptr:= buf;
shift:= 0;
localResult:= 0;
while (true) do begin
if (ptr >= buf_end) then begin
read_leb128_to_uint64:= 0;
exit;
end;
currentByte:= ptr^;
inc(ptr);
localResult:= localResult or uint64(currentByte and $7F) SHL Shift;
if ((currentByte AND $80) = 0) then break;
Inc(Shift, 7);
end;
res^:= localResult;
read_leb128_to_uint64:= uint8(ptr - buf);
end;
function read_leb128_to_uint32(buf: puint8; buf_end: puint8; res: puint32): uint8;
var
ptr : puint8;
shift : uint32;
localResult : uint32;
currentByte : uint8;
begin
ptr:= buf;
shift:= 0;
localResult:= 0;
while (true) do begin
if (ptr >= buf_end) then begin
read_leb128_to_uint32:= 0;
exit;
end;
currentByte:= ptr^;
inc(ptr);
localResult:= localResult or uint64(currentByte and $7F) SHL Shift;
if ((currentByte AND $80) = 0) then break;
Inc(Shift, 7);
end;
res^:= localResult;
read_leb128_to_uint32:= uint8(ptr - buf);
end;
end.
+1 -1
View File
@@ -36,7 +36,7 @@ type
sInt8 = shortint;
sInt16 = smallint;
sInt32 = integer;
sInt64 = longint;
sInt64 = int64;
Float = Single;
+112
View File
@@ -0,0 +1,112 @@
{ Emulator-layer WASI OS hook implementations.
This unit provides native hook callbacks for running WASI programs
on a host OS (Windows/Linux). On bare-metal (Asuro), these would be
replaced by kernel-level implementations.
Hooks are registered per-context via PWASMProcessContext.
This unit has NO knowledge of WASM internals (no stacks, no linear memory). }
unit wasi.emu.hooks;
interface
uses
wasm.types.context;
procedure register_emu_hooks(ctx : PWASMProcessContext);
implementation
uses
wasm.types.builtin,
wasm.wasi.hooks,
wasm.types.wasi;
{ fd_write: write buf to stdout (fd=1) or stderr (fd=2) }
function emu_fd_write(fd: TWASMUInt32;
buf: TWASMPUInt8;
len: TWASMUInt32): TWASMUInt32;
var
i: TWASMUInt32;
begin
if (fd = 1) or (fd = 2) then begin
for i := 0 to len - 1 do
Write(TWASMChar(buf[i]));
emu_fd_write := len;
end else
emu_fd_write := 0;
end;
{ fd_read: stub — no stdin support in emu layer yet }
function emu_fd_read(fd: TWASMUInt32;
buf: TWASMPUInt8;
len: TWASMUInt32): TWASMUInt32;
begin
emu_fd_read := 0;
end;
{ fd_close: no-op for emu layer }
function emu_fd_close(fd: TWASMUInt32): TWASMUInt32;
begin
emu_fd_close := 0; { ESUCCESS }
end;
{ proc_exit: halt the program with the given exit code }
procedure emu_proc_exit(code: TWASMUInt32);
begin
{ The glue layer already sets Running := false and ExitCode.
On the emu layer, we also halt the host process. }
halt(code);
end;
{ clock_time_get: return current time in nanoseconds }
function emu_clock_time_get(clock_id: TWASMUInt32;
precision: TWASMUInt64;
var time: TWASMUInt64): TWASMUInt32;
begin
{ Stub: return 0 nanoseconds. On a real OS we would query the system clock.
Bare-metal would use RDTSC or PIT. }
time := 0;
emu_clock_time_get := WASI_ESUCCESS;
end;
{ clock_res_get: return clock resolution in nanoseconds }
function emu_clock_res_get(clock_id: TWASMUInt32;
var resolution: TWASMUInt64): TWASMUInt32;
begin
{ Stub: report 1ms resolution }
resolution := 1000000;
emu_clock_res_get := WASI_ESUCCESS;
end;
{ random_get: fill buffer with random bytes }
function emu_random_get(buf: TWASMPUInt8;
len: TWASMUInt32): TWASMUInt32;
var
i: TWASMUInt32;
state: TWASMUInt32;
begin
{ Simple xorshift PRNG — not cryptographic, but deterministic
and works without RTL. On bare-metal, use RDRAND. }
state := 2463534242; { seed }
for i := 0 to len - 1 do begin
state := state xor (state shl 13);
state := state xor (state shr 17);
state := state xor (state shl 5);
buf[i] := TWASMUInt8(state and $FF);
end;
emu_random_get := WASI_ESUCCESS;
end;
procedure register_emu_hooks(ctx : PWASMProcessContext);
begin
wasm.wasi.hooks.init_hook_table(ctx);
wasm.wasi.hooks.register_fd_write(ctx, @emu_fd_write);
wasm.wasi.hooks.register_fd_read(ctx, @emu_fd_read);
wasm.wasi.hooks.register_fd_close(ctx, @emu_fd_close);
wasm.wasi.hooks.register_proc_exit(ctx, @emu_proc_exit);
wasm.wasi.hooks.register_clock_time_get(ctx, @emu_clock_time_get);
wasm.wasi.hooks.register_clock_res_get(ctx, @emu_clock_res_get);
wasm.wasi.hooks.register_random_get(ctx, @emu_random_get);
end;
end.
+65 -21
View File
@@ -2,46 +2,90 @@ program WASURO;
uses
sysutils,
wasm.vm.io,
wasm.types.builtin,
wasm.types.context,
wasm,
console,
{ Emu-layer OS hooks }
wasi.emu.hooks
types,
wasm.types,
wasm.parser,
wasm.vm, wasm.test.binary,
wasm.types.stack
{$IFDEF RUN_TESTS}
, wasm.test
, wasm.test.framework
{$ENDIF}
;
{ Emu-layer writechar hook — forwards to RTL Write for host OS output }
procedure emu_writechar(ch : TWASMChar);
begin
Write(ch);
end;
var
Context : PWASMProcessContext;
ModuleSize : Int64;
ModuleBuffer : TWASMPUInt8;
ModuleFile : File;
begin
{ Wire up the IO subsystem before anything else }
wasm.vm.io.io_set_writechar(@emu_writechar);
{$IFDEF RUN_TESTS}
wasm.vm.init();
wasm.wasm_init;
wasm.test.run_all_tests;
halt(wasm.test.framework.FailedTests);
{$ELSE}
writestringln('[main] Initializing VM');
wasm.vm.init();
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestringln('WASURO - WebAssembly Runtime in Object Pascal');
{$ENDIF}
wasm.wasm_init;
writestringln('[main] Parsing WASM Binary');
Context:= wasm.parser.parse(@wasm.test.binary.TEST_BINARY_1[0], puint8(@wasm.test.binary.TEST_BINARY_1[0] + $26));
if ParamCount > 0 then begin
if not FileExists(ParamStr(1)) then begin
wasm.vm.io.writestringln('File not found.');
halt(1);
end;
Assign(ModuleFile, ParamStr(1));
Reset(ModuleFile, 1);
ModuleSize := FileSize(ModuleFile);
GetMem(ModuleBuffer, ModuleSize);
BlockRead(ModuleFile, ModuleBuffer^, ModuleSize);
Close(ModuleFile);
{$IFDEF DEBUG_OUTPUT}
write('Module loaded from file: ');
writeln(ParamStr(1));
{$ENDIF}
writestringln('[main] Running...');
Context^.ExecutionState.Running:= true;
while (wasm.vm.tick(Context)) do;
writestringln('[main] Finished Execution');
writestring('[main] Returns: ');
while Context^.ExecutionState.Operand_Stack^.Top > 0 do begin
write(wasm.types.stack.popi32(Context^.ExecutionState.Operand_Stack),', ');
{ Load, configure, and run the WASM module }
Context := wasm.wasm_load(ModuleBuffer, TWASMPUInt8(ModuleBuffer + ModuleSize));
if not Context^.ValidBinary then begin
wasm.vm.io.writestringln('Error: Invalid WASM binary.');
halt(1);
end;
{ Register emu-layer OS hooks and WASI preview1 into context }
wasi.emu.hooks.register_emu_hooks(Context);
wasm.wasm_register_wasi_preview1(Context);
{ Find _start and run to completion }
if not wasm.wasm_start(Context) then begin
wasm.vm.io.writestringln('No _start export found.');
halt(1);
end;
{$IFDEF DEBUG_OUTPUT}
wasm.wasm_dump_state(Context);
{$ENDIF}
FreeMem(ModuleBuffer);
halt(Context^.ExitCode);
end else begin
wasm.vm.io.writestringln('Usage: WASURO <module.wasm>');
halt(1);
end;
writeln();
while true do sleep(1000);
{$ENDIF}
end.
@@ -3,16 +3,16 @@ unit wasm.parser.sections.codeSection;
interface
uses
types, lmemorymanager, console, leb128,
wasm.types;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
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
procedure printCtxCode(ctx : PWASMProcessContext);
var
i : uint32;
i : TWASMUInt32;
begin
writestring('[wasm.parser] Flat Code: ');
@@ -25,15 +25,15 @@ end;
procedure walk(ctx : PWASMProcessContext);
var
localpos, pos, bend : puint8;
bytesRead : uint8;
localpos, pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
currentEntry : PWASMCodeEntry;
i,j,l : uint32;
localCount,localTemp,localIndex : uint32;
i,j,l : TWASMUInt32;
localCount,localTemp,localIndex : TWASMUInt32;
localType: TWasmValueType;
codeLength: uint32;
codeOffset: uint32;
totalSize: uint32;
codeLength: TWASMUInt32;
codeOffset: TWASMUInt32;
totalSize: TWASMUInt32;
begin
// Walk the code entries
for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin
@@ -59,25 +59,27 @@ begin
end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
localpos, pos, bend : puint8;
bytesRead : uint8;
localpos, pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
currentEntry : PWASMCodeEntry;
i,j,l : uint32;
localCount,localTemp,localIndex : uint32;
i,j,l : TWASMUInt32;
localCount,localTemp,localIndex : TWASMUInt32;
localType: TWasmValueType;
codeLength: uint32;
codeOffset: uint32;
totalSize: uint32;
codeLength: TWASMUInt32;
codeOffset: TWASMUInt32;
totalSize: TWASMUInt32;
begin
writestring('[wasm.parser] Handle Section: Code - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Code - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers
pos:= buffer;
bend:= puint8(pos + section_length);
bend:= TWASMPUInt8(pos + section_length);
// Initialize the code section
ctx^.Sections.CodeSection:= PWASMCodeSection(kalloc(sizeof(TWASMCodeSection)));
@@ -158,7 +160,7 @@ begin
end;
// Read the code
currentEntry^.Code:= puint8(kalloc(currentEntry^.CodeLength));
currentEntry^.Code:= TWASMPUInt8(kalloc(currentEntry^.CodeLength));
for j:=1 to currentEntry^.CodeLength do begin
currentEntry^.Code[j - 1]:= pos^;
inc(pos);
@@ -171,20 +173,21 @@ begin
totalSize:= totalSize + currentEntry^.CodeLength;
end;
ctx^.ExecutionState.Code:= puint8(kalloc(totalSize));
ctx^.ExecutionState.Code:= TWASMPUInt8(kalloc(totalSize));
ctx^.ExecutionState.Limit:= totalSize;
localpos:= ctx^.ExecutionState.Code;
for i:=1 to ctx^.Sections.CodeSection^.CodeCount do begin
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
localpos^:= currentEntry^.Code[j - 1];
inc(localpos);
end;
end;
end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx);
{$ENDIF}
end;
end.
@@ -3,17 +3,21 @@ unit wasm.parser.sections.customSection;
interface
uses
types, lmemorymanager, console, leb128,
wasm.types;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
wasm.types.context;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
implementation
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
begin
writestring('[wasm.parser] Handle Section: Custom - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Custom - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
{ Custom sections are ignored in this implementation }
wasm.vm.io.writestringln('[wasm.parser] TODO: Custom section skipped.');
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 wasm.vm.io, wasm.types.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}
wasm.vm.io.writestring('[wasm.parser] Handle Section: DataCount - Size: ');
wasm.vm.io.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
uses
types, lmemorymanager, console, leb128,
wasm.types;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
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
procedure walk(ctx : PWASMProcessContext);
var
currentEntry : PWASMExportEntry;
i : uint32;
i : TWASMUInt32;
begin
// Walk the export entries
@@ -28,20 +28,22 @@ begin
end;
end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos, bend : puint8;
bytesRead : uint8;
pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
currentEntry : PWASMExportEntry;
i,j : uint32;
i,j : TWASMUInt32;
begin
writestring('[wasm.parser] Handle Section: Export - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Export - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers
pos:= buffer;
bend:= puint8(pos + section_length);
bend:= TWASMPUInt8(pos + section_length);
// Initialize the export section
ctx^.Sections.ExportSection:= PWASMExportSection(kalloc(sizeof(TWASMExportSection)));
@@ -69,12 +71,12 @@ begin
inc(pos, bytesRead);
// 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
currentEntry^.Name[j]:= char(pos^);
currentEntry^.Name[j]:= TWASMChar(pos^);
inc(pos);
end;
currentEntry^.Name[currentEntry^.NameLength]:= char($00);
currentEntry^.Name[currentEntry^.NameLength]:= TWASMChar($00);
// Read the export type
currentEntry^.ExportType:= TWasmExportType(pos^);
@@ -85,8 +87,9 @@ begin
inc(pos, bytesRead);
end;
end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx);
{$ENDIF}
end;
end.
@@ -3,17 +3,17 @@ unit wasm.parser.sections.functionSection;
interface
uses
types, lmemorymanager, console, leb128,
wasm.types;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
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
procedure walk(ctx : PWASMProcessContext);
var
currentFunc : PWASMFunction;
i : uint32;
i : TWASMUInt32;
begin
// Walk the functions
@@ -24,20 +24,22 @@ begin
end;
end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos, bend : puint8;
bytesRead : uint8;
pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
currentFunc : PWASMFunction;
i : uint32;
i : TWASMUInt32;
begin
writestring('[wasm.parser] Handle Section: Function - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Function - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
// Initialize the read/end pointers
pos:= buffer;
bend:= puint8(pos + section_length);
bend:= TWASMPUInt8(pos + section_length);
// Initialize the function section
ctx^.Sections.FunctionSection:= PWASMFunctionSection(kalloc(sizeof(TWASMFunctionSection)));
@@ -64,8 +66,9 @@ begin
inc(pos, bytesRead);
end;
end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx);
{$ENDIF}
end;
end.
@@ -3,16 +3,16 @@ unit wasm.parser.sections.globalSection;
interface
uses
types, lmemorymanager, console, leb128,
wasm.types;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
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
procedure walk(ctx : PWASMProcessContext);
var
i : uint32;
i : TWASMUInt32;
entry : PWASMGlobalEntry;
begin
for i := 0 to ctx^.ExecutionState.Globals^.GlobalCount - 1 do begin
@@ -35,25 +35,27 @@ begin
end;
end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos, bend : puint8;
bytesRead : uint8;
globalCount : uint32;
i : uint32;
pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
globalCount : TWASMUInt32;
i : TWASMUInt32;
entry : PWASMGlobalEntry;
valType : uint8;
mutFlag : uint8;
opcode : uint8;
tmpU32 : uint32;
tmpU64 : uint64;
valType : TWASMUInt8;
mutFlag : TWASMUInt8;
opcode : TWASMUInt8;
tmpU32 : TWASMUInt32;
tmpU64 : TWASMUInt64;
begin
writestring('[wasm.parser] Handle Section: Global - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Global - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer;
bend := puint8(buffer + section_length);
bend := TWASMPUInt8(buffer + section_length);
{ Read global count }
bytesRead := read_leb128_to_uint32(pos, bend, @globalCount);
@@ -88,19 +90,19 @@ begin
$41: begin { i32.const }
bytesRead := read_leb128_to_uint32(pos, bend, @tmpU32);
Inc(pos, bytesRead);
entry^.Value.i32Value := int32(tmpU32);
entry^.Value.i32Value := TWASMInt32(tmpU32);
end;
$42: begin { i64.const }
bytesRead := read_leb128_to_uint64(pos, bend, @tmpU64);
Inc(pos, bytesRead);
entry^.Value.i64Value := int64(tmpU64);
entry^.Value.i64Value := TWASMInt64(tmpU64);
end;
$43: begin { f32.const }
entry^.Value.f32Value := pfloat(pos)^;
entry^.Value.f32Value := TWASMPFloat(pos)^;
Inc(pos, 4);
end;
$44: begin { f64.const }
entry^.Value.f64Value := pdouble(pos)^;
entry^.Value.f64Value := TWASMPDouble(pos)^;
Inc(pos, 8);
end;
else
@@ -115,8 +117,9 @@ begin
if (pos < bend) and (pos^ = $0B) then
Inc(pos);
end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx);
{$ENDIF}
end;
end.
File diff suppressed because it is too large. Load diff
@@ -3,16 +3,16 @@ unit wasm.parser.sections.memorySection;
interface
uses
types, lmemorymanager, console, leb128,
wasm.types, wasm.types.heap;
wasm.types.builtin, lmemorymanager, wasm.vm.io, wasm.types.leb128,
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
procedure walk(ctx : PWASMProcessContext);
var
i : uint32;
i : TWASMUInt32;
mem : PWASMMemoryLimits;
begin
for i := 0 to ctx^.Sections.MemorySection^.MemoryCount - 1 do begin
@@ -29,21 +29,23 @@ begin
end;
end;
procedure handle(buffer: puint8; section_length: uint32; ctx: PWASMProcessContext);
procedure handle(buffer: TWASMPUInt8; section_length: TWASMUInt32; ctx: PWASMProcessContext);
var
pos, bend : puint8;
bytesRead : uint8;
memCount : uint32;
i : uint32;
pos, bend : TWASMPUInt8;
bytesRead : TWASMUInt8;
memCount : TWASMUInt32;
i : TWASMUInt32;
mem : PWASMMemoryLimits;
flags : uint32;
flags : TWASMUInt32;
begin
writestring('[wasm.parser] Handle Section: Memory - Size: ');
writeintlnWND(section_length, 0);
{$IFDEF DEBUG_OUTPUT}
wasm.vm.io.writestring('[wasm.parser] Handle Section: Memory - Size: ');
wasm.vm.io.writeintlnWND(section_length, 0);
{$ENDIF}
pos := buffer;
bend := puint8(buffer + section_length);
bend := TWASMPUInt8(buffer + section_length);
{ Read memory count }
bytesRead := read_leb128_to_uint32(pos, bend, @memCount);
@@ -77,8 +79,9 @@ begin
while ctx^.ExecutionState.Memory^.PageCount < mem^.InitialPages do
wasm.types.heap.expand_heap(ctx^.ExecutionState.Memory);
end;
{$IFDEF DEBUG_OUTPUT}
walk(ctx);
{$ENDIF}
end;
end.
Loaded 20 of 506 files, more files were not shown because too many files have changed in this diff. Show more