Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +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 `WasmRuntimeOptions` to limit memory size, table elements and fuel per call (#19) @michaelthyregod

# 1.1.0

Expand Down
24 changes: 24 additions & 0 deletions docs/tutorials/01-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,30 @@ Registers the default Wasmtime-backed runtime factory.
var config = Configuration.Default.WithWasm();
```

### `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 WasmRuntimeOptions
{
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<IBrowsingContext, IWasmRuntimeFactory>)`

Registers a custom runtime factory creator.
Expand Down
6 changes: 6 additions & 0 deletions docs/tutorials/03-Questions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `WasmRuntimeOptions` 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.
Expand Down
184 changes: 184 additions & 0 deletions src/AngleSharp.Wasm.Tests/WasmtimeRuntimeLimitsTests.cs
Original file line number Diff line number Diff line change
@@ -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 WasmRuntimeOptions { 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 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;

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 WasmRuntimeOptions { 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<WasmValueType>(),
Array.Empty<WasmValueType>(),
_ =>
{
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 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")!;

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 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")!;

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 WasmRuntimeOptions { MaximumMemorySize = -1 }),
Throws.InstanceOf<ArgumentOutOfRangeException>());
}

[Test]
public async Task BridgeReportsSpentFuelAsRuntimeError()
{
var config = Configuration.Default.WithWasm(new WasmRuntimeOptions { 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<WasmJsRuntimeError>().With.Message.Contains("fuel"));
Assert.That(() => ((WasmJsExportedFunction)instance.Exports["spin"]!).Invoke(), Throws.InstanceOf<WasmJsRuntimeError>().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));
}
}
16 changes: 16 additions & 0 deletions src/AngleSharp.Wasm/WasmConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ public static class WasmConfigurationExtensions
public static IConfiguration WithWasm(this IConfiguration configuration) =>
configuration.WithWasm(context => new WasmtimeWasmRuntimeFactory());

/// <summary>
/// Registers the default Wasmtime-backed WebAssembly runtime factory with resource limits.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="options">The resource limits.</param>
/// <returns>The updated configuration.</returns>
public static IConfiguration WithWasm(this IConfiguration configuration, WasmRuntimeOptions options)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}

return configuration.WithWasm(context => new WasmtimeWasmRuntimeFactory(options));
}

/// <summary>
/// Registers a custom WebAssembly runtime factory.
/// </summary>
Expand Down
33 changes: 33 additions & 0 deletions src/AngleSharp.Wasm/WasmRuntimeOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace AngleSharp.Wasm;

/// <summary>
/// Optional resource limits for a WebAssembly runtime, honored by the default
/// <see cref="WasmtimeWasmRuntime"/>. Every limit is off by default; set them when the runtime
/// executes modules from untrusted content.
/// </summary>
public sealed class WasmRuntimeOptions
{
/// <summary>
/// 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.
/// <c>null</c> (the default) means no limit beyond the WebAssembly maximum.
/// </summary>
public long? MaximumMemorySize { get; set; }

/// <summary>
/// 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.
/// <c>null</c> (the default) means no limit beyond the WebAssembly maximum.
/// </summary>
public uint? MaximumTableElements { get; set; }

/// <summary>
/// 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.
/// <c>null</c> (the default) means no limit; setting it enables fuel metering, which slows
/// down execution.
/// </summary>
public ulong? Fuel { get; set; }
}
9 changes: 6 additions & 3 deletions src/AngleSharp.Wasm/WasmtimeFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -25,7 +28,7 @@ internal WasmtimeFunction(Function function)

if (invocationArguments.Length == 0)
{
return Function.Invoke();
return _context.Run(static function => function.Invoke(), Function);
}

var boxedArguments = new ValueBox[invocationArguments.Length];
Expand All @@ -42,6 +45,6 @@ internal WasmtimeFunction(Function function)
};
}

return Function.Invoke(boxedArguments);
return _context.Run(static state => state.Function.Invoke(state.Arguments), (Function, Arguments: boxedArguments));
}
}
8 changes: 5 additions & 3 deletions src/AngleSharp.Wasm/WasmtimeGlobal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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,
};

Expand Down
Loading
Loading