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 1/4] 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 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 2/4] 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 3/4] 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 4/4] 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)); }