From 502af3ae560ff27f585141aa498c78baf0149c21 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 2 Nov 2026 00:43:41 +0100 Subject: [PATCH 01/10] Use trusted publishing --- .github/workflows/ci.yml | 15 ++++++++++++++- build/Build.cs | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index abf3672..66b5b60 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: [push, pull_request] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} DOCS_PATH: ${{ secrets.DOCS_PATH }} DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }} @@ -61,6 +60,9 @@ jobs: windows: runs-on: windows-latest + permissions: + contents: write # create the GitHub release + id-token: write # request the OIDC token for NuGet trusted publishing steps: - uses: actions/checkout@v5 @@ -71,7 +73,18 @@ jobs: dotnet-version: | 10.0.x + # Exchanges the GitHub OIDC token for a short-lived (1 hour) NuGet API key. + # Requires a trusted publishing policy on nuget.org for this repository and workflow file. + - name: NuGet login + id: nuget_login + if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/devel') + uses: NuGet/login@v1 + with: + user: ${{ secrets.NUGET_USER }} + - name: Build + env: + NUGET_API_KEY: ${{ steps.nuget_login.outputs.NUGET_API_KEY }} run: | if ($env:GITHUB_REF -eq "refs/heads/main") { .\build.ps1 -Target Publish -AngleSharpVersion 1.5.0 diff --git a/build/Build.cs b/build/Build.cs index 7d9ef65..4eb85a1 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -197,9 +197,9 @@ protected override void OnBuildInitialized() .DependsOn(RunUnitTests) .Executes(() => { + // In CI this is the short-lived key issued by NuGet trusted publishing (NuGet/login). var apiKey = Environment.GetEnvironmentVariable("NUGET_API_KEY"); - if (apiKey.IsNullOrEmpty()) { throw new BuildAbortedException("Could not resolve the NuGet API key."); From 6849f6094d7bc533e9e0f50b720dec59e44850bd Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:06:19 +0100 Subject: [PATCH 02/10] Make the library trim and Native AOT compatible - Mark the net8.0 and net10.0 targets IsAotCompatible, so the trim and AOT analyzers run on every build, with the same KnownILLinkPack override as AngleSharp, AngleSharp.Xml, AngleSharp.Css and AngleSharp.Io - Update AGENTS.md and CHANGELOG.md No code changes were needed: both targets build without trim or AOT warnings, and a console app published with PublishAot (runtime API, DOM bridge, host imports, CompileError) compiles without warnings, Wasmtime included, and runs correctly. --- AGENTS.md | 3 +++ CHANGELOG.md | 4 ++++ src/AngleSharp.Wasm/AngleSharp.Wasm.csproj | 14 ++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index a9feabf..97bbacb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,9 @@ AngleSharp.Wasm extends AngleSharp with WebAssembly execution and a DOM/JavaScri - The solution is `src/AngleSharp.Wasm.sln`. - The library and test projects target `net8.0` and `net10.0`. - The library references AngleSharp 1.x and Wasmtime 44.0.0. +- The library sets `IsAotCompatible`, so a trim or AOT analyzer warning breaks the build. Avoid + reflection over runtime types; the analyzers only see this assembly, so publishing a small + `PublishAot` console app against it is the end-to-end check. - The default runtime is `WasmtimeWasmRuntime`, registered through `Configuration.WithWasm()`. - `global.json`, when present, controls the SDK version used by the build wrapper. diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd4982..22a905e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 1.1.1 + +- Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets @michaelthyregod + # 1.1.0 Released on Friday, August 21 2026. diff --git a/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj b/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj index 8bd909b..868bf5f 100644 --- a/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj +++ b/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj @@ -4,8 +4,22 @@ AngleSharp.Wasm net8.0;net10.0 true + + true + + + + + https://anglesharp.github.io MIT From aaa150937890309e834bd1e35de22061609eb366 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:07:10 +0100 Subject: [PATCH 03/10] Pass host import arguments with their WebAssembly types The switch expression in ConvertArguments had int, long, float and double arms, so C# gave it the common type double: every argument reached the import callback as a boxed double, and i64 values above 2^53 lost precision. Box each arm as object instead, so i32, i64, f32 and f64 arrive as int, long, float and double. --- CHANGELOG.md | 4 ++ .../WasmtimeRuntimeTests.cs | 47 +++++++++++++++++++ src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs | 8 ++-- 3 files changed, 55 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd4982..9bfce72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 1.1.1 + +- Fixed host import arguments arriving as `double` instead of their WebAssembly types @michaelthyregod + # 1.1.0 Released on Friday, August 21 2026. diff --git a/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeTests.cs b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeTests.cs index c9e77b0..f071e98 100644 --- a/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeTests.cs +++ b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeTests.cs @@ -1,6 +1,8 @@ namespace AngleSharp.Wasm.Tests; using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using NUnit.Framework; @@ -43,6 +45,21 @@ public sealed class WasmtimeRuntimeTests 0x0A, 0x09, 0x01, 0x07, 0x00, 0x10, 0x00, 0x41, 0x01, 0x6A, 0x0B, }; + // (module + // (import "host" "echo" (func $echo (param i32 i64 f32 f64))) + // (func (export "run") (param i32 i64 f32 f64) + // local.get 0 local.get 1 local.get 2 local.get 3 call $echo)) + private static readonly byte[] HostImportArgumentsModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x01, 0x08, 0x01, 0x60, 0x04, 0x7F, 0x7E, 0x7D, 0x7C, 0x00, + 0x02, 0x0D, 0x01, 0x04, 0x68, 0x6F, 0x73, 0x74, 0x04, 0x65, 0x63, 0x68, 0x6F, 0x00, 0x00, + 0x03, 0x02, 0x01, 0x00, + 0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6E, 0x00, 0x01, + 0x0A, 0x0E, 0x01, 0x0C, 0x00, 0x20, 0x00, 0x20, 0x01, 0x20, 0x02, 0x20, 0x03, 0x10, 0x00, 0x0B, + }; + [Test] public async Task CanCompileInstantiateAndInvokeExport() { @@ -97,4 +114,34 @@ public async Task CanInstantiateWithHostImport() Assert.That(Convert.ToInt32(result), Is.EqualTo(42)); } + + [Test] + public async Task HostImportReceivesArgumentsWithTheirWasmTypes() + { + using var runtime = new WasmtimeWasmRuntime(); + using var module = await runtime.CompileAsync(HostImportArgumentsModule).ConfigureAwait(false); + var types = new[] { WasmValueType.Int32, WasmValueType.Int64, WasmValueType.Float32, WasmValueType.Float64 }; + IReadOnlyList? received = null; + + var imports = new[] + { + new WasmImportFunction( + "host", + "echo", + types, + Array.Empty(), + arguments => + { + received = arguments; + return null; + }), + }; + + using var instance = await runtime.InstantiateAsync(module, imports).ConfigureAwait(false); + await instance.InvokeAsync("run", new object?[] { 7, 9007199254740993L, 1.5f, 2.25 }).ConfigureAwait(false); + + Assert.That(received, Is.EqualTo(new object?[] { 7, 9007199254740993L, 1.5f, 2.25 })); + Assert.That(received!.Select(argument => argument?.GetType()), + Is.EqualTo(new[] { typeof(int), typeof(long), typeof(float), typeof(double) })); + } } diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs index 51dd0da..82f3edf 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs @@ -126,10 +126,10 @@ private static void BindImport(Linker linker, WasmImportFunction import) { converted[i] = types[i] switch { - WasmValueType.Int32 => arguments[i].AsInt32(), - WasmValueType.Int64 => arguments[i].AsInt64(), - WasmValueType.Float32 => arguments[i].AsSingle(), - WasmValueType.Float64 => arguments[i].AsDouble(), + WasmValueType.Int32 => (object)arguments[i].AsInt32(), + WasmValueType.Int64 => (object)arguments[i].AsInt64(), + WasmValueType.Float32 => (object)arguments[i].AsSingle(), + WasmValueType.Float64 => (object)arguments[i].AsDouble(), _ => throw new NotSupportedException($"Unsupported argument type '{types[i]}'."), }; } From 52e8b268f1d1b4d81e4b829955d9e42800a4015f Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:13:35 +0100 Subject: [PATCH 04/10] Add optional memory, table and fuel limits to the Wasmtime runtime WebAssembly from a page could grow its memory to 4 GiB and run an endless loop that nothing can interrupt. WasmtimeWasmRuntimeOptions adds three opt-in limits, all off by default so existing behavior is unchanged: - MaximumMemorySize and MaximumTableElements, applied with Store.SetLimits to every instance's store - Fuel, a per-call budget refilled when the host calls into an instance (and before instantiation, for the start function); calls a host import makes back into the same instance share the outer budget, so they cannot reset it The options are accepted by WasmtimeWasmRuntime, WasmtimeWasmRuntimeFactory and a new WithWasm(WasmtimeWasmRuntimeOptions) overload. A failed instantiation now disposes its store right away. --- CHANGELOG.md | 4 + docs/tutorials/01-API.md | 24 +++ docs/tutorials/03-Questions.md | 6 + .../WasmtimeRuntimeLimitsTests.cs | 184 ++++++++++++++++++ .../WasmConfigurationExtensions.cs | 16 ++ src/AngleSharp.Wasm/WasmtimeFunction.cs | 9 +- src/AngleSharp.Wasm/WasmtimeGlobal.cs | 8 +- src/AngleSharp.Wasm/WasmtimeInstance.cs | 18 +- src/AngleSharp.Wasm/WasmtimeStoreContext.cs | 44 +++++ src/AngleSharp.Wasm/WasmtimeTable.cs | 8 +- src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs | 55 +++++- .../WasmtimeWasmRuntimeFactory.cs | 21 +- .../WasmtimeWasmRuntimeOptions.cs | 32 +++ 13 files changed, 402 insertions(+), 27 deletions(-) create mode 100644 src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs create mode 100644 src/AngleSharp.Wasm/WasmtimeStoreContext.cs create mode 100644 src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd4982..8cf9b3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 1.1.1 + +- Added `WasmtimeWasmRuntimeOptions` to limit memory size, table elements and fuel per call @michaelthyregod + # 1.1.0 Released on Friday, August 21 2026. diff --git a/docs/tutorials/01-API.md b/docs/tutorials/01-API.md index 84ff770..b85cf78 100644 --- a/docs/tutorials/01-API.md +++ b/docs/tutorials/01-API.md @@ -18,6 +18,30 @@ Registers the default Wasmtime-backed runtime factory. var config = Configuration.Default.WithWasm(); ``` +### `WithWasm(WasmtimeWasmRuntimeOptions)` + +Registers the default Wasmtime-backed runtime factory with resource limits. Every limit is off by +default; set them when pages with untrusted WebAssembly are loaded. + +```cs +var config = Configuration.Default.WithWasm(new WasmtimeWasmRuntimeOptions +{ + MaximumMemorySize = 64 * 1024 * 1024, // bytes per linear memory + MaximumTableElements = 10_000, // elements per table + Fuel = 100_000_000, // per call from the host and per instantiation +}); +``` + +- `MaximumMemorySize` and `MaximumTableElements` make instantiation fail when a memory or table + starts larger, and make growing beyond them fail. +- `Fuel` is roughly one unit per executed WebAssembly instruction. A call that spends it traps, + which the bridge reports as `RuntimeError`; the next call gets a full budget again. Calls that + WebAssembly makes back into its own instance through a host import share the outer call's budget. + Fuel metering slows execution down, so it is only enabled when `Fuel` is set. + +The same options can be passed to `new WasmtimeWasmRuntime(options)` and +`new WasmtimeWasmRuntimeFactory(options)`. + ### `WithWasm(Func)` Registers a custom runtime factory creator. diff --git a/docs/tutorials/03-Questions.md b/docs/tutorials/03-Questions.md index 7e63161..f5fb0fc 100644 --- a/docs/tutorials/03-Questions.md +++ b/docs/tutorials/03-Questions.md @@ -63,6 +63,12 @@ Current numeric value kinds are supported: - `f32` - `f64` +## How do I limit what a module can consume? + +By default a module can grow its memory and tables up to the WebAssembly maximum and run for as +long as it likes. Pass `WasmtimeWasmRuntimeOptions` to `WithWasm(...)` to cap memory size, table +elements and fuel (executed instructions per call); see the API page. + ## What are known limitations today? - No Promise-based `compile` / `instantiate` bridge methods. diff --git a/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs new file mode 100644 index 0000000..6808be5 --- /dev/null +++ b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs @@ -0,0 +1,184 @@ +namespace AngleSharp.Wasm.Tests; + +using System; +using System.Threading.Tasks; +using AngleSharp.Wasm.Dom; +using NUnit.Framework; + +[TestFixture] +public sealed class WasmtimeRuntimeLimitsTests +{ + // (module + // (func (export "spin") (loop br 0)) + // (func (export "answer") (result i32) i32.const 42)) + private static readonly byte[] SpinModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x01, 0x08, 0x02, 0x60, 0x00, 0x00, 0x60, 0x00, 0x01, 0x7F, + 0x03, 0x03, 0x02, 0x00, 0x01, + 0x07, 0x11, 0x02, 0x04, 0x73, 0x70, 0x69, 0x6E, 0x00, 0x00, 0x06, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72, 0x00, 0x01, + 0x0A, 0x0E, 0x02, 0x07, 0x00, 0x03, 0x40, 0x0C, 0x00, 0x0B, 0x0B, 0x04, 0x00, 0x41, 0x2A, 0x0B, + }; + + // (module + // (import "host" "reenter" (func $reenter)) + // (func (export "spin") (loop call $reenter br 0)) + // (func (export "answer") (result i32) i32.const 42)) + private static readonly byte[] ReenteringSpinModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x01, 0x08, 0x02, 0x60, 0x00, 0x00, 0x60, 0x00, 0x01, 0x7F, + 0x02, 0x10, 0x01, 0x04, 0x68, 0x6F, 0x73, 0x74, 0x07, 0x72, 0x65, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x00, 0x00, + 0x03, 0x03, 0x02, 0x00, 0x01, + 0x07, 0x11, 0x02, 0x04, 0x73, 0x70, 0x69, 0x6E, 0x00, 0x01, 0x06, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72, 0x00, 0x02, + 0x0A, 0x10, 0x02, 0x09, 0x00, 0x03, 0x40, 0x10, 0x00, 0x0C, 0x00, 0x0B, 0x0B, 0x04, 0x00, 0x41, 0x2A, 0x0B, + }; + + // (module (memory (export "mem") 1)) + private static readonly byte[] OnePageMemoryModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x05, 0x03, 0x01, 0x00, 0x01, + 0x07, 0x07, 0x01, 0x03, 0x6D, 0x65, 0x6D, 0x02, 0x00, + }; + + // (module (memory (export "mem") 3)) + private static readonly byte[] ThreePageMemoryModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x05, 0x03, 0x01, 0x00, 0x03, + 0x07, 0x07, 0x01, 0x03, 0x6D, 0x65, 0x6D, 0x02, 0x00, + }; + + // (module (table (export "tab") 1 funcref)) + private static readonly byte[] OneElementTableModule = + { + 0x00, 0x61, 0x73, 0x6D, + 0x01, 0x00, 0x00, 0x00, + 0x04, 0x04, 0x01, 0x70, 0x00, 0x01, + 0x07, 0x07, 0x01, 0x03, 0x74, 0x61, 0x62, 0x01, 0x00, + }; + + private const long PageSize = 65536; + + [Test] + public async Task FuelStopsAnEndlessLoopAndIsRefilledForTheNextCall() + { + using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false); + using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); + + Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel")); + Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel")); + Assert.That(await instance.InvokeAsync("answer").ConfigureAwait(false), Is.EqualTo(42)); + } + + [Test] + public async Task FuelAppliesToExportedFunctionsObtainedFromTheInstance() + { + using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false); + using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); + var functions = (IWasmFunctionProvider)instance; + + Assert.That(() => functions.GetFunction("spin")!.Invoke(), Throws.Exception.With.Message.Contains("fuel")); + Assert.That(functions.GetFunction("answer")!.Invoke(), Is.EqualTo(42)); + } + + [Test] + public async Task ReenteringTheInstanceFromAHostImportDoesNotRefillTheFuel() + { + using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var module = await runtime.CompileAsync(ReenteringSpinModule).ConfigureAwait(false); + IWasmInstance? self = null; + var reentries = 0; + + var imports = new[] + { + new WasmImportFunction( + "host", + "reenter", + Array.Empty(), + Array.Empty(), + _ => + { + reentries++; + return self!.InvokeAsync("answer").AsTask().GetAwaiter().GetResult(); + }), + }; + + using var instance = await runtime.InstantiateAsync(module, imports).ConfigureAwait(false); + self = instance; + + Assert.That(async () => await instance.InvokeAsync("spin").ConfigureAwait(false), Throws.Exception.With.Message.Contains("fuel")); + Assert.That(reentries, Is.GreaterThan(0)); + Assert.That(await instance.InvokeAsync("answer").ConfigureAwait(false), Is.EqualTo(42)); + } + + [Test] + public async Task MaximumMemorySizeStopsGrowthAndLargerInitialMemory() + { + using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumMemorySize = 2 * PageSize }); + using var module = await runtime.CompileAsync(OnePageMemoryModule).ConfigureAwait(false); + using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); + var memory = ((IWasmMemoryProvider)instance).GetMemory("mem")!; + + Assert.That(memory.Grow(1), Is.EqualTo(1)); + Assert.That(() => memory.Grow(1), Throws.Exception.With.Message.Contains("failed to grow memory")); + Assert.That(memory.Length, Is.EqualTo(2 * PageSize)); + + using var largerModule = await runtime.CompileAsync(ThreePageMemoryModule).ConfigureAwait(false); + Assert.That(async () => await runtime.InstantiateAsync(largerModule).ConfigureAwait(false), Throws.Exception.With.Message.Contains("exceeds memory limits")); + } + + [Test] + public async Task MaximumTableElementsStopsGrowth() + { + using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumTableElements = 2 }); + using var module = await runtime.CompileAsync(OneElementTableModule).ConfigureAwait(false); + using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); + var table = ((IWasmTableProvider)instance).GetTable("tab")!; + + Assert.That(table.Grow(1, null), Is.EqualTo(1UL)); + Assert.That(() => table.Grow(1, null), Throws.Exception.With.Message.Contains("failed to grow table")); + Assert.That(table.Length, Is.EqualTo(2UL)); + } + + [Test] + public void NegativeMaximumMemorySizeIsRejected() + { + Assert.That( + () => new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumMemorySize = -1 }), + Throws.InstanceOf()); + } + + [Test] + public async Task BridgeReportsSpentFuelAsRuntimeError() + { + var config = Configuration.Default.WithWasm(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var context = BrowsingContext.New(config); + using var document = await context.OpenNewAsync(); + + var instance = WebAssembly.Instantiate(context.Current!, SpinModule).Instance; + + Assert.That(() => instance.Invoke("spin"), Throws.InstanceOf().With.Message.Contains("fuel")); + Assert.That(() => ((WasmJsExportedFunction)instance.Exports["spin"]!).Invoke(), Throws.InstanceOf().With.Message.Contains("fuel")); + Assert.That(instance.Invoke("answer"), Is.EqualTo(42)); + } + + [Test] + public async Task BridgeWithoutOptionsKeepsMemoryUnlimited() + { + var config = Configuration.Default.WithWasm(); + using var context = BrowsingContext.New(config); + using var document = await context.OpenNewAsync(); + + var memory = (WasmJsMemory)WebAssembly.Instantiate(context.Current!, OnePageMemoryModule).Instance.Exports["mem"]!; + + Assert.That(memory.Grow(16), Is.EqualTo(1)); + } +} diff --git a/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs b/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs index 525d498..78c28f2 100644 --- a/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs +++ b/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs @@ -17,6 +17,22 @@ public static class WasmConfigurationExtensions public static IConfiguration WithWasm(this IConfiguration configuration) => configuration.WithWasm(context => new WasmtimeWasmRuntimeFactory()); + /// + /// Registers the default Wasmtime-backed WebAssembly runtime factory with resource limits. + /// + /// The configuration. + /// The resource limits. + /// The updated configuration. + public static IConfiguration WithWasm(this IConfiguration configuration, WasmtimeWasmRuntimeOptions options) + { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + + return configuration.WithWasm(context => new WasmtimeWasmRuntimeFactory(options)); + } + /// /// Registers a custom WebAssembly runtime factory. /// diff --git a/src/AngleSharp.Wasm/WasmtimeFunction.cs b/src/AngleSharp.Wasm/WasmtimeFunction.cs index 9a668d7..b3a0330 100644 --- a/src/AngleSharp.Wasm/WasmtimeFunction.cs +++ b/src/AngleSharp.Wasm/WasmtimeFunction.cs @@ -6,8 +6,11 @@ namespace AngleSharp.Wasm; internal sealed class WasmtimeFunction : IWasmFunction { - internal WasmtimeFunction(Function function) + private readonly WasmtimeStoreContext _context; + + internal WasmtimeFunction(WasmtimeStoreContext context, Function function) { + _context = context; Function = function; } @@ -25,7 +28,7 @@ internal WasmtimeFunction(Function function) if (invocationArguments.Length == 0) { - return Function.Invoke(); + return _context.Run(() => Function.Invoke()); } var boxedArguments = new ValueBox[invocationArguments.Length]; @@ -42,6 +45,6 @@ internal WasmtimeFunction(Function function) }; } - return Function.Invoke(boxedArguments); + return _context.Run(() => Function.Invoke(boxedArguments)); } } \ No newline at end of file diff --git a/src/AngleSharp.Wasm/WasmtimeGlobal.cs b/src/AngleSharp.Wasm/WasmtimeGlobal.cs index 1cd373e..93069de 100644 --- a/src/AngleSharp.Wasm/WasmtimeGlobal.cs +++ b/src/AngleSharp.Wasm/WasmtimeGlobal.cs @@ -6,10 +6,12 @@ namespace AngleSharp.Wasm; internal sealed class WasmtimeGlobal : IWasmGlobal { + private readonly WasmtimeStoreContext _context; private readonly Global _global; - internal WasmtimeGlobal(Global global) + internal WasmtimeGlobal(WasmtimeStoreContext context, Global global) { + _context = context; _global = global; } @@ -27,10 +29,10 @@ public void SetValue(object? value) _global.SetValue(Unwrap(value)); } - private static object? Wrap(object? value) => value switch + private object? Wrap(object? value) => value switch { Function { IsNull: true } => null, - Function function => new WasmtimeFunction(function), + Function function => new WasmtimeFunction(_context, function), _ => value, }; diff --git a/src/AngleSharp.Wasm/WasmtimeInstance.cs b/src/AngleSharp.Wasm/WasmtimeInstance.cs index 3ded52a..86e3f77 100644 --- a/src/AngleSharp.Wasm/WasmtimeInstance.cs +++ b/src/AngleSharp.Wasm/WasmtimeInstance.cs @@ -11,13 +11,13 @@ namespace AngleSharp.Wasm; /// public sealed class WasmtimeInstance : IWasmInstance, IWasmFunctionProvider, IWasmGlobalProvider, IWasmMemoryProvider, IWasmTableProvider { - private readonly Store _store; + private readonly WasmtimeStoreContext _context; private readonly Instance _instance; private bool _disposed; - internal WasmtimeInstance(Store store, Instance instance) + internal WasmtimeInstance(WasmtimeStoreContext context, Instance instance) { - _store = store; + _context = context; _instance = instance; } @@ -32,7 +32,7 @@ internal WasmtimeInstance(Store store, Instance instance) } var function = _instance.GetFunction(exportName); - return function is null ? null : new WasmtimeFunction(function); + return function is null ? null : new WasmtimeFunction(_context, function); } /// @@ -46,7 +46,7 @@ internal WasmtimeInstance(Store store, Instance instance) } var global = _instance.GetGlobal(exportName); - return global is null ? null : new WasmtimeGlobal(global); + return global is null ? null : new WasmtimeGlobal(_context, global); } /// @@ -74,7 +74,7 @@ internal WasmtimeInstance(Store store, Instance instance) } var table = _instance.GetTable(exportName); - return table is null ? null : new WasmtimeTable(table); + return table is null ? null : new WasmtimeTable(_context, table); } /// @@ -105,7 +105,7 @@ internal WasmtimeInstance(Store store, Instance instance) if (invocationArguments.Length == 0) { - return ValueTask.FromResult(function.Invoke()); + return ValueTask.FromResult(_context.Run(() => function.Invoke())); } var boxedArguments = new ValueBox[invocationArguments.Length]; @@ -122,7 +122,7 @@ internal WasmtimeInstance(Store store, Instance instance) }; } - var result = function.Invoke(boxedArguments); + var result = _context.Run(() => function.Invoke(boxedArguments)); return ValueTask.FromResult(result); } @@ -135,7 +135,7 @@ public void Dispose() } _disposed = true; - _store.Dispose(); + _context.Store.Dispose(); } private void ThrowIfDisposed() diff --git a/src/AngleSharp.Wasm/WasmtimeStoreContext.cs b/src/AngleSharp.Wasm/WasmtimeStoreContext.cs new file mode 100644 index 0000000..8a9cc59 --- /dev/null +++ b/src/AngleSharp.Wasm/WasmtimeStoreContext.cs @@ -0,0 +1,44 @@ +namespace AngleSharp.Wasm; + +using System; +using Wasmtime; + +/// +/// Owns a Wasmtime store and refills its fuel when the host calls into it. +/// +internal sealed class WasmtimeStoreContext +{ + private readonly ulong? _fuel; + private int _depth; + + internal WasmtimeStoreContext(Store store, ulong? fuel) + { + Store = store; + _fuel = fuel; + } + + internal Store Store { get; } + + /// + /// Runs WebAssembly code in this store. Only the outermost entry refills the fuel, so a host + /// import that calls back into the store cannot reset the budget of the call it runs in. + /// + internal T Run(Func action) + { + var outermost = _depth++ == 0; + + try + { + if (outermost && _fuel is ulong fuel) + { + Store.Fuel = fuel; + } + + return action(); + } + finally + { + _depth--; + } + } +} diff --git a/src/AngleSharp.Wasm/WasmtimeTable.cs b/src/AngleSharp.Wasm/WasmtimeTable.cs index d7e6024..abd76f1 100644 --- a/src/AngleSharp.Wasm/WasmtimeTable.cs +++ b/src/AngleSharp.Wasm/WasmtimeTable.cs @@ -5,10 +5,12 @@ namespace AngleSharp.Wasm; internal sealed class WasmtimeTable : IWasmTable { + private readonly WasmtimeStoreContext _context; private readonly Table _table; - internal WasmtimeTable(Table table) + internal WasmtimeTable(WasmtimeStoreContext context, Table table) { + _context = context; _table = table; } @@ -20,10 +22,10 @@ internal WasmtimeTable(Table table) public ulong Grow(uint delta, object? value) => _table.Grow(delta, Unwrap(value)); - private static object? Wrap(object? value) => value switch + private object? Wrap(object? value) => value switch { Function { IsNull: true } => null, - Function function => new WasmtimeFunction(function), + Function function => new WasmtimeFunction(_context, function), _ => value, }; diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs index 51dd0da..fac32cc 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs @@ -14,14 +14,39 @@ namespace AngleSharp.Wasm; public sealed class WasmtimeWasmRuntime : IWasmRuntime, IWasmValidator { private readonly Engine _engine; + private readonly long? _maximumMemorySize; + private readonly uint? _maximumTableElements; + private readonly ulong? _fuel; private bool _disposed; /// - /// Creates a new runtime. + /// Creates a new runtime without resource limits. /// public WasmtimeWasmRuntime() + : this(new WasmtimeWasmRuntimeOptions()) { - _engine = new Engine(); + } + + /// + /// Creates a new runtime with the given resource limits. + /// + /// The resource limits. The values are read once, here. + public WasmtimeWasmRuntime(WasmtimeWasmRuntimeOptions options) + { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + + if (options.MaximumMemorySize < 0) + { + throw new ArgumentOutOfRangeException(nameof(options), "MaximumMemorySize must not be negative."); + } + + _maximumMemorySize = options.MaximumMemorySize; + _maximumTableElements = options.MaximumTableElements; + _fuel = options.Fuel; + _engine = _fuel is null ? new Engine() : new Engine(new Config().WithFuelConsumption(true)); } /// @@ -58,17 +83,31 @@ public ValueTask InstantiateAsync( var linker = new Linker(wasmtimeModule.Engine); var store = new Store(wasmtimeModule.Engine); - if (imports is not null) + try { - foreach (var import in imports) + if (_maximumMemorySize is not null || _maximumTableElements is not null) { - BindImport(linker, import); + store.SetLimits(_maximumMemorySize, _maximumTableElements, null, null, null); } - } - var instance = linker.Instantiate(store, wasmtimeModule.Module); + if (imports is not null) + { + foreach (var import in imports) + { + BindImport(linker, import); + } + } - return ValueTask.FromResult(new WasmtimeInstance(store, instance)); + var context = new WasmtimeStoreContext(store, _fuel); + var instance = context.Run(() => linker.Instantiate(store, wasmtimeModule.Module)); + + return ValueTask.FromResult(new WasmtimeInstance(context, instance)); + } + catch + { + store.Dispose(); + throw; + } } /// diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs index 1c56bdc..0e4b37f 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs @@ -7,6 +7,25 @@ namespace AngleSharp.Wasm; /// public sealed class WasmtimeWasmRuntimeFactory : IWasmRuntimeFactory { + private readonly WasmtimeWasmRuntimeOptions _options; + + /// + /// Creates a factory for runtimes without resource limits. + /// + public WasmtimeWasmRuntimeFactory() + : this(new WasmtimeWasmRuntimeOptions()) + { + } + + /// + /// Creates a factory for runtimes with the given resource limits. + /// + /// The resource limits, read by every runtime this factory creates. + public WasmtimeWasmRuntimeFactory(WasmtimeWasmRuntimeOptions options) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + } + /// public IWasmRuntime Create(IBrowsingContext context) { @@ -15,6 +34,6 @@ public IWasmRuntime Create(IBrowsingContext context) throw new ArgumentNullException(nameof(context)); } - return new WasmtimeWasmRuntime(); + return new WasmtimeWasmRuntime(_options); } } diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs new file mode 100644 index 0000000..1e9f5a3 --- /dev/null +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs @@ -0,0 +1,32 @@ +namespace AngleSharp.Wasm; + +/// +/// Optional resource limits for . Every limit is off by +/// default; set them when the runtime executes modules from untrusted content. +/// +public sealed class WasmtimeWasmRuntimeOptions +{ + /// + /// Gets or sets the maximum size in bytes that a single linear memory may have. Instantiating + /// a module whose memory starts larger fails, and growing a memory beyond it fails. + /// null (the default) means no limit beyond the WebAssembly maximum. + /// + public long? MaximumMemorySize { get; set; } + + /// + /// Gets or sets the maximum number of elements that a single table may have. Instantiating a + /// module whose table starts larger fails, and growing a table beyond it fails. + /// null (the default) means no limit beyond the WebAssembly maximum. + /// + public uint? MaximumTableElements { get; set; } + + /// + /// Gets or sets the fuel that WebAssembly code may consume per call from the host into an + /// instance, and per instantiation (start function). Fuel is roughly one unit per executed + /// WebAssembly instruction; when it runs out the call traps. Calls that WebAssembly makes back + /// into its own instance from a host import share the budget of the outer call. + /// null (the default) means no limit; setting it enables fuel metering, which slows + /// down execution. + /// + public ulong? Fuel { get; set; } +} From 563d1c339e0acf8af64c504b8fb79c5a0d3601f9 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:21:17 +0100 Subject: [PATCH 05/10] Add the PR number to the CHANGELOG line --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22a905e..5245b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.1.1 -- Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets @michaelthyregod +- Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets (#17) @michaelthyregod # 1.1.0 From 5b123e8831fe0191ec65b01b3f1a7f0cc2bef514 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:21:17 +0100 Subject: [PATCH 06/10] Add the PR number to the CHANGELOG line --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bfce72..5fe044d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.1.1 -- Fixed host import arguments arriving as `double` instead of their WebAssembly types @michaelthyregod +- Fixed host import arguments arriving as `double` instead of their WebAssembly types (#18) @michaelthyregod # 1.1.0 From 88164d7b2b4ecc5ca85b8ad97d54c20116783c1f Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:21:17 +0100 Subject: [PATCH 07/10] Add the PR number to the CHANGELOG line --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf9b3e..6c57b80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.1.1 -- Added `WasmtimeWasmRuntimeOptions` to limit memory size, table elements and fuel per call @michaelthyregod +- Added `WasmtimeWasmRuntimeOptions` to limit memory size, table elements and fuel per call (#19) @michaelthyregod # 1.1.0 From d9d4988ea4748175fc56061b996bb266b53c6490 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Mon, 9 Nov 2026 08:22:15 +0100 Subject: [PATCH 08/10] Pass call state to the store context instead of capturing it WasmtimeStoreContext.Run takes the state as a parameter, so every call site uses a static lambda and the default (no limits) path allocates nothing extra per call. Measured with BenchmarkDotNet against devel: per-call allocation is identical, time within 0-2.4%. --- src/AngleSharp.Wasm/WasmtimeFunction.cs | 4 ++-- src/AngleSharp.Wasm/WasmtimeInstance.cs | 4 ++-- src/AngleSharp.Wasm/WasmtimeStoreContext.cs | 5 +++-- src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/AngleSharp.Wasm/WasmtimeFunction.cs b/src/AngleSharp.Wasm/WasmtimeFunction.cs index b3a0330..6ff60fb 100644 --- a/src/AngleSharp.Wasm/WasmtimeFunction.cs +++ b/src/AngleSharp.Wasm/WasmtimeFunction.cs @@ -28,7 +28,7 @@ internal WasmtimeFunction(WasmtimeStoreContext context, Function function) if (invocationArguments.Length == 0) { - return _context.Run(() => Function.Invoke()); + return _context.Run(static function => function.Invoke(), Function); } var boxedArguments = new ValueBox[invocationArguments.Length]; @@ -45,6 +45,6 @@ internal WasmtimeFunction(WasmtimeStoreContext context, Function function) }; } - return _context.Run(() => Function.Invoke(boxedArguments)); + return _context.Run(static state => state.Function.Invoke(state.Arguments), (Function, Arguments: boxedArguments)); } } \ No newline at end of file diff --git a/src/AngleSharp.Wasm/WasmtimeInstance.cs b/src/AngleSharp.Wasm/WasmtimeInstance.cs index 86e3f77..bb4e607 100644 --- a/src/AngleSharp.Wasm/WasmtimeInstance.cs +++ b/src/AngleSharp.Wasm/WasmtimeInstance.cs @@ -105,7 +105,7 @@ internal WasmtimeInstance(WasmtimeStoreContext context, Instance instance) if (invocationArguments.Length == 0) { - return ValueTask.FromResult(_context.Run(() => function.Invoke())); + return ValueTask.FromResult(_context.Run(static function => function.Invoke(), function)); } var boxedArguments = new ValueBox[invocationArguments.Length]; @@ -122,7 +122,7 @@ internal WasmtimeInstance(WasmtimeStoreContext context, Instance instance) }; } - var result = _context.Run(() => function.Invoke(boxedArguments)); + var result = _context.Run(static state => state.Function.Invoke(state.Arguments), (Function: function, Arguments: boxedArguments)); return ValueTask.FromResult(result); } diff --git a/src/AngleSharp.Wasm/WasmtimeStoreContext.cs b/src/AngleSharp.Wasm/WasmtimeStoreContext.cs index 8a9cc59..618ff6a 100644 --- a/src/AngleSharp.Wasm/WasmtimeStoreContext.cs +++ b/src/AngleSharp.Wasm/WasmtimeStoreContext.cs @@ -22,8 +22,9 @@ internal WasmtimeStoreContext(Store store, ulong? fuel) /// /// Runs WebAssembly code in this store. Only the outermost entry refills the fuel, so a host /// import that calls back into the store cannot reset the budget of the call it runs in. + /// The state is passed through so callers can use a static lambda and allocate nothing per call. /// - internal T Run(Func action) + internal T Run(Func action, TState state) { var outermost = _depth++ == 0; @@ -34,7 +35,7 @@ internal T Run(Func action) Store.Fuel = fuel; } - return action(); + return action(state); } finally { diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs index 401ea26..95ea3ab 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs @@ -99,7 +99,7 @@ public ValueTask InstantiateAsync( } var context = new WasmtimeStoreContext(store, _fuel); - var instance = context.Run(() => linker.Instantiate(store, wasmtimeModule.Module)); + var instance = context.Run(static state => state.Linker.Instantiate(state.Store, state.Module), (Linker: linker, Store: store, wasmtimeModule.Module)); return ValueTask.FromResult(new WasmtimeInstance(context, instance)); } From c00030c9e40819e64f552ea28a28c61af3a10142 Mon Sep 17 00:00:00 2001 From: Michael Thyregod <2386496+michaelthyregod@users.noreply.github.com> Date: Thu, 12 Nov 2026 04:25:11 +0100 Subject: [PATCH 09/10] Rename WasmtimeWasmRuntimeOptions to WasmRuntimeOptions The options hold no Wasmtime types and the limits apply to any runtime, so the name stays independent of the Wasmtime implementation, as suggested in the review. --- CHANGELOG.md | 2 +- docs/tutorials/01-API.md | 4 ++-- docs/tutorials/03-Questions.md | 2 +- .../WasmtimeRuntimeLimitsTests.cs | 14 +++++++------- src/AngleSharp.Wasm/WasmConfigurationExtensions.cs | 2 +- ...WasmRuntimeOptions.cs => WasmRuntimeOptions.cs} | 7 ++++--- src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs | 4 ++-- src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs | 6 +++--- 8 files changed, 21 insertions(+), 20 deletions(-) rename src/AngleSharp.Wasm/{WasmtimeWasmRuntimeOptions.cs => WasmRuntimeOptions.cs} (83%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e18c31..98fe22e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Released on Monday, November 9 2026. - Fixed host import arguments arriving as `double` instead of their WebAssembly types (#18) @michaelthyregod - Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets (#17) @michaelthyregod -- Added `WasmtimeWasmRuntimeOptions` to limit memory size, table elements and fuel per call (#19) @michaelthyregod +- Added `WasmRuntimeOptions` to limit memory size, table elements and fuel per call (#19) @michaelthyregod # 1.1.0 diff --git a/docs/tutorials/01-API.md b/docs/tutorials/01-API.md index b85cf78..29cc449 100644 --- a/docs/tutorials/01-API.md +++ b/docs/tutorials/01-API.md @@ -18,13 +18,13 @@ Registers the default Wasmtime-backed runtime factory. var config = Configuration.Default.WithWasm(); ``` -### `WithWasm(WasmtimeWasmRuntimeOptions)` +### `WithWasm(WasmRuntimeOptions)` Registers the default Wasmtime-backed runtime factory with resource limits. Every limit is off by default; set them when pages with untrusted WebAssembly are loaded. ```cs -var config = Configuration.Default.WithWasm(new WasmtimeWasmRuntimeOptions +var config = Configuration.Default.WithWasm(new WasmRuntimeOptions { MaximumMemorySize = 64 * 1024 * 1024, // bytes per linear memory MaximumTableElements = 10_000, // elements per table diff --git a/docs/tutorials/03-Questions.md b/docs/tutorials/03-Questions.md index f5fb0fc..d2b1383 100644 --- a/docs/tutorials/03-Questions.md +++ b/docs/tutorials/03-Questions.md @@ -66,7 +66,7 @@ Current numeric value kinds are supported: ## How do I limit what a module can consume? By default a module can grow its memory and tables up to the WebAssembly maximum and run for as -long as it likes. Pass `WasmtimeWasmRuntimeOptions` to `WithWasm(...)` to cap memory size, table +long as it likes. Pass `WasmRuntimeOptions` to `WithWasm(...)` to cap memory size, table elements and fuel (executed instructions per call); see the API page. ## What are known limitations today? diff --git a/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs index 6808be5..d974d2d 100644 --- a/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs +++ b/src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs @@ -68,7 +68,7 @@ public sealed class WasmtimeRuntimeLimitsTests [Test] public async Task FuelStopsAnEndlessLoopAndIsRefilledForTheNextCall() { - using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 }); using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false); using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); @@ -80,7 +80,7 @@ public async Task FuelStopsAnEndlessLoopAndIsRefilledForTheNextCall() [Test] public async Task FuelAppliesToExportedFunctionsObtainedFromTheInstance() { - using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 }); using var module = await runtime.CompileAsync(SpinModule).ConfigureAwait(false); using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); var functions = (IWasmFunctionProvider)instance; @@ -92,7 +92,7 @@ public async Task FuelAppliesToExportedFunctionsObtainedFromTheInstance() [Test] public async Task ReenteringTheInstanceFromAHostImportDoesNotRefillTheFuel() { - using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { Fuel = 10_000 }); using var module = await runtime.CompileAsync(ReenteringSpinModule).ConfigureAwait(false); IWasmInstance? self = null; var reentries = 0; @@ -122,7 +122,7 @@ public async Task ReenteringTheInstanceFromAHostImportDoesNotRefillTheFuel() [Test] public async Task MaximumMemorySizeStopsGrowthAndLargerInitialMemory() { - using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumMemorySize = 2 * PageSize }); + using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumMemorySize = 2 * PageSize }); using var module = await runtime.CompileAsync(OnePageMemoryModule).ConfigureAwait(false); using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); var memory = ((IWasmMemoryProvider)instance).GetMemory("mem")!; @@ -138,7 +138,7 @@ public async Task MaximumMemorySizeStopsGrowthAndLargerInitialMemory() [Test] public async Task MaximumTableElementsStopsGrowth() { - using var runtime = new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumTableElements = 2 }); + using var runtime = new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumTableElements = 2 }); using var module = await runtime.CompileAsync(OneElementTableModule).ConfigureAwait(false); using var instance = await runtime.InstantiateAsync(module).ConfigureAwait(false); var table = ((IWasmTableProvider)instance).GetTable("tab")!; @@ -152,14 +152,14 @@ public async Task MaximumTableElementsStopsGrowth() public void NegativeMaximumMemorySizeIsRejected() { Assert.That( - () => new WasmtimeWasmRuntime(new WasmtimeWasmRuntimeOptions { MaximumMemorySize = -1 }), + () => new WasmtimeWasmRuntime(new WasmRuntimeOptions { MaximumMemorySize = -1 }), Throws.InstanceOf()); } [Test] public async Task BridgeReportsSpentFuelAsRuntimeError() { - var config = Configuration.Default.WithWasm(new WasmtimeWasmRuntimeOptions { Fuel = 10_000 }); + var config = Configuration.Default.WithWasm(new WasmRuntimeOptions { Fuel = 10_000 }); using var context = BrowsingContext.New(config); using var document = await context.OpenNewAsync(); diff --git a/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs b/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs index 78c28f2..5d4fb9a 100644 --- a/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs +++ b/src/AngleSharp.Wasm/WasmConfigurationExtensions.cs @@ -23,7 +23,7 @@ public static IConfiguration WithWasm(this IConfiguration configuration) => /// The configuration. /// The resource limits. /// The updated configuration. - public static IConfiguration WithWasm(this IConfiguration configuration, WasmtimeWasmRuntimeOptions options) + public static IConfiguration WithWasm(this IConfiguration configuration, WasmRuntimeOptions options) { if (options is null) { diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs b/src/AngleSharp.Wasm/WasmRuntimeOptions.cs similarity index 83% rename from src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs rename to src/AngleSharp.Wasm/WasmRuntimeOptions.cs index 1e9f5a3..a273688 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeOptions.cs +++ b/src/AngleSharp.Wasm/WasmRuntimeOptions.cs @@ -1,10 +1,11 @@ namespace AngleSharp.Wasm; /// -/// Optional resource limits for . Every limit is off by -/// default; set them when the runtime executes modules from untrusted content. +/// Optional resource limits for a WebAssembly runtime, honored by the default +/// . Every limit is off by default; set them when the runtime +/// executes modules from untrusted content. /// -public sealed class WasmtimeWasmRuntimeOptions +public sealed class WasmRuntimeOptions { /// /// Gets or sets the maximum size in bytes that a single linear memory may have. Instantiating diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs index 95ea3ab..8208025 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs @@ -23,7 +23,7 @@ public sealed class WasmtimeWasmRuntime : IWasmRuntime, IWasmValidator /// Creates a new runtime without resource limits. /// public WasmtimeWasmRuntime() - : this(new WasmtimeWasmRuntimeOptions()) + : this(new WasmRuntimeOptions()) { } @@ -31,7 +31,7 @@ public WasmtimeWasmRuntime() /// Creates a new runtime with the given resource limits. /// /// The resource limits. The values are read once, here. - public WasmtimeWasmRuntime(WasmtimeWasmRuntimeOptions options) + public WasmtimeWasmRuntime(WasmRuntimeOptions options) { if (options is null) { diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs index 0e4b37f..fc65a9f 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntimeFactory.cs @@ -7,13 +7,13 @@ namespace AngleSharp.Wasm; /// public sealed class WasmtimeWasmRuntimeFactory : IWasmRuntimeFactory { - private readonly WasmtimeWasmRuntimeOptions _options; + private readonly WasmRuntimeOptions _options; /// /// Creates a factory for runtimes without resource limits. /// public WasmtimeWasmRuntimeFactory() - : this(new WasmtimeWasmRuntimeOptions()) + : this(new WasmRuntimeOptions()) { } @@ -21,7 +21,7 @@ public WasmtimeWasmRuntimeFactory() /// Creates a factory for runtimes with the given resource limits. /// /// The resource limits, read by every runtime this factory creates. - public WasmtimeWasmRuntimeFactory(WasmtimeWasmRuntimeOptions options) + public WasmtimeWasmRuntimeFactory(WasmRuntimeOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); } From 86ea930d5f8da09b123403a71bf62e7fe6b629d2 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 12 Nov 2026 09:40:46 +0100 Subject: [PATCH 10/10] Updated version --- CHANGELOG.md | 2 +- CONTRIBUTORS.md | 1 + src/AngleSharp.Wasm.Docs/package.json | 2 +- src/Directory.Build.props | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98fe22e..922023f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 1.1.1 -Released on Monday, November 9 2026. +Released on Thursday, November 12 2026. - Fixed host import arguments arriving as `double` instead of their WebAssembly types (#18) @michaelthyregod - Added trimming and Native AOT compatibility (`IsAotCompatible`) for the .NET 8 and .NET 10 targets (#17) @michaelthyregod diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 9a0db1a..a3ceaa7 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,7 @@ Thanks :heart: to all who contributed to AngleSharp.Wasm via issues, pull reques AngleSharp.Wasm contains code written by (in order of first pull request / commit): * [Florian Rappl](https://github.com/FlorianRappl) +* [Michael Thyregod](https://github.com/michaelthyregod) Without these awesome people AngleSharp.Wasm could not exist. Thanks to everyone for your contributions! :beers: diff --git a/src/AngleSharp.Wasm.Docs/package.json b/src/AngleSharp.Wasm.Docs/package.json index 3defbe1..1984a5f 100644 --- a/src/AngleSharp.Wasm.Docs/package.json +++ b/src/AngleSharp.Wasm.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/wasm", - "version": "1.1.0", + "version": "1.1.1", "preview": true, "description": "The doclet for the AngleSharp.Wasm documentation.", "keywords": [ diff --git a/src/Directory.Build.props b/src/Directory.Build.props index bc7ce44..eb555d0 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ Adds a way to run WebAssembly to AngleSharp. AngleSharp.Wasm - 1.1.0 + 1.1.1 enable latest true