diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 66b5b60..1647528 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,45 +4,8 @@ on: [push, pull_request] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCS_PATH: ${{ secrets.DOCS_PATH }} - DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }} jobs: - can_document: - runs-on: ubuntu-latest - outputs: - value: ${{ steps.check_job.outputs.value }} - steps: - - name: Checks whether documentation can be built - id: check_job - run: | - echo "value: ${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - echo "::set-output name=value::${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - - documentation: - needs: [can_document] - runs-on: ubuntu-latest - if: needs.can_document.outputs.value == 'true' - - steps: - - uses: actions/checkout@v5 - - - name: Use Node.js - uses: actions/setup-node@v5 - with: - node-version: "20.x" - registry-url: 'https://registry.npmjs.org' - - - name: Install Dependencies - run: | - cd $DOCS_PATH - npm install - - - name: Deploy Doclet - run: | - cd $DOCS_PATH - npx pilet publish --fresh --url https://feed.piral.cloud/api/v1/pilet/anglesharp --api-key ${{ secrets.PIRAL_FEED_KEY }} - linux: runs-on: ubuntu-latest @@ -56,7 +19,7 @@ jobs: 10.0.x - name: Build - run: ./build.sh -AngleSharpVersion 1.5.0 + run: ./build.sh -AngleSharpVersion 1.11.0 windows: runs-on: windows-latest @@ -87,9 +50,9 @@ jobs: 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 + .\build.ps1 -Target Publish -AngleSharpVersion 1.11.0 } elseif ($env:GITHUB_REF -eq "refs/heads/devel") { - .\build.ps1 -Target PrePublish -AngleSharpVersion 1.5.0 + .\build.ps1 -Target PrePublish -AngleSharpVersion 1.11.0 } else { - .\build.ps1 -AngleSharpVersion 1.5.0 + .\build.ps1 -AngleSharpVersion 1.11.0 } diff --git a/CHANGELOG.md b/CHANGELOG.md index 922023f..e958194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +# 1.2.0 + +Released on Tuesday, November 24 2026. + +- Updated `WebAssembly` to no longer appear as members or global members +- Updated minimum version of AngleSharp to 1.11.0 +- Added the WebAssembly JavaScript API as in browsers for scripts +- Added `memory.buffer` sharing the bytes of the memory with scripts +- Added import objects of scripts +- Added `WasmDom.Register`, the DOM of this library declared for a scripting engine + # 1.1.1 Released on Thursday, November 12 2026. diff --git a/README.md b/README.md index 9008090..7dd4907 100644 --- a/README.md +++ b/README.md @@ -54,16 +54,24 @@ var config = Configuration.Default ## DOM / JS Integration -When using a scripting setup that discovers DOM-annotated members (for example, AngleSharp.Js with registered assemblies), AngleSharp.Wasm exposes a WebAssembly surface under `window.WebAssembly`. +With AngleSharp.Js, scripts get the WebAssembly JavaScript API as in browsers: + +```js +const memory = new WebAssembly.Memory({ initial: 1 }); +const { instance } = await WebAssembly.instantiateStreaming(fetch('program.wasm'), { + env: { memory, log: (value) => console.log(value) }, +}); +new Uint8Array(memory.buffer)[0] = 42; +instance.exports.run(); +``` -Available bridge capabilities include: +- `WebAssembly` is a namespace object with `validate`, `compile`, `instantiate`, `compileStreaming` and `instantiateStreaming` (giving promises) and the interfaces `Module`, `Instance`, `Memory`, `Table`, `Global`, `Tag`, `Exception`, `CompileError`, `LinkError` and `RuntimeError`. +- Import objects take functions of scripts, numbers and BigInts (for globals), and memories, tables and globals; `instance.exports` holds functions scripts call and the objects of memories, tables and globals. +- `memory.buffer` is an ArrayBuffer sharing the bytes of the memory (the default Wasmtime backend keeps the memories in pinned .NET arrays), so writes of scripts and of WebAssembly see each other. -- Compile module bytes -- Instantiate compiled modules -- Inspect module imports / exports / custom sections -- Access instance exports and invoke exported functions +The objects of a browsing context live in one Wasmtime store, so they can be imported by any of its modules. -Typical flow: +For C#, the synchronous bridge methods remain: ```cs var module = WebAssembly.Compile(context.Current!, wasmBytes); @@ -110,9 +118,9 @@ The current package targets `net8.0` and `net10.0`. AngleSharp.Wasm currently provides a practical subset of the WebAssembly JS API. -- Bridge methods are synchronous from the caller perspective. -- Promise-based namespace operations are not currently exposed. -- Streaming APIs synchronously buffer AngleSharp response streams because module metadata requires the complete binary. +- Streaming APIs read the whole response before compiling, because module metadata requires the complete binary. +- Shared memories (`shared: true`) are not supported. +- The JavaScript API needs the default Wasmtime backend; custom runtimes are used by the C# bridge methods. - Compile options are validated and forwarded to capable runtimes. Wasmtime 44 does not expose JavaScript string builtins or imported string constants, so requesting either option with the default backend throws `NotSupportedException`. - Exported memories, tables, globals, and tags have object projections; other non-function exports remain descriptors (`name`, `kind`). - Host-created tags and exceptions are supported. Wasmtime 44 does not expose native Tag or Exception handles or enable exception modules through its .NET API, so runtime-thrown Wasm exceptions are not yet projected. diff --git a/docs/general/01-Basics.md b/docs/general/01-Basics.md index ee7b144..6305277 100644 --- a/docs/general/01-Basics.md +++ b/docs/general/01-Basics.md @@ -14,7 +14,7 @@ You need to have AngleSharp installed already. This could be done via NuGet: Install-Package AngleSharp ``` -If you want JavaScript-side access to `window.WebAssembly`, you also need a scripting setup (for example, AngleSharp.Js) that discovers exported DOM members from loaded assemblies. +If you want JavaScript-side access to `window.WebAssembly`, you also need a scripting setup (for example, AngleSharp.Js) that discovers exported DOM members from loaded assemblies, or is given the registration of this library (see below). ## Getting AngleSharp.Wasm over NuGet @@ -60,6 +60,18 @@ var config = Configuration.Default }); ``` +## Scripting Without Reflection + +AngleSharp.Js finds the DOM of this library by reflecting over its DOM attributes by default. A trimmed or natively compiled (AoT) application can instead hand it the registration generated for this library at build time, `AngleSharp.Wasm.WasmDom.Register` (a `DomRegistration` of AngleSharp). It declares the `WebAssembly` namespace with its interfaces (`WebAssembly.Module`, `WebAssembly.Memory`, ...): + +```cs +var config = Configuration.Default + .WithWasm() + .WithJs(WasmDom.Register); +``` + +The registration describes the version of the library in use, so it never has to be kept in sync by hand. Several libraries are combined with `DomRegistrations.Combine`. + ## What Works Today - `WithWasm()` registers a default Wasmtime-backed runtime factory. diff --git a/docs/general/02-Spec-Coverage.md b/docs/general/02-Spec-Coverage.md index 77e2af3..fe478f6 100644 --- a/docs/general/02-Spec-Coverage.md +++ b/docs/general/02-Spec-Coverage.md @@ -16,20 +16,20 @@ Status values: | Spec Area | Status | Notes | | --- | --- | --- | -| WebAssembly namespace: `compile(bytes)` | Partial | Exposed as synchronous bridge method `WebAssembly.compile(byte[])`. | -| WebAssembly namespace: `instantiate(...)` | Partial | Exposed as synchronous bridge method `WebAssembly.instantiate(WasmJsModule)`. | +| WebAssembly namespace: `compile(bytes)` | Implemented | `WebAssembly.compile(bytes)` gives a promise of a `WebAssembly.Module`, rejected with a `CompileError` for invalid bytes. The synchronous `WebAssembly.Compile(window, bytes)` remains for C#. | +| WebAssembly namespace: `instantiate(...)` | Implemented | `WebAssembly.instantiate(bytes, importObject)` gives a promise of `{ module, instance }`, `instantiate(module, importObject)` one of the instance. Imports are read from the import object (functions, numbers, BigInts, memories, tables and globals); failures reject with a `LinkError` or `RuntimeError`. | | WebAssembly namespace: `validate(bytes)` | Implemented | Exposed as synchronous `WebAssembly.validate(byte[])`, using native Wasmtime validation or compile-and-dispose fallback for custom runtimes. | -| WebAssembly namespace: streaming APIs | Partial | `compileStreaming(IResponse)` and `instantiateStreaming(IResponse)` synchronously consume successful `application/wasm` AngleSharp responses. Response bodies are buffered for metadata extraction. | +| WebAssembly namespace: streaming APIs | Implemented | `compileStreaming` and `instantiateStreaming` take a `Response` of `fetch()` (or a promise of one, or an AngleSharp `IResponse`), which has to be successful and of the type `application/wasm`; the body is read completely before compiling. | | WebAssembly namespace: compile options | Partial | `WasmCompileOptions` validates and routes `builtins` and `importedStringConstants` through compile, byte instantiate, and streaming entry points. Wasmtime 44 cannot execute these options. | -| `Module.exports(module)` | Partial | Available as instance method `module.exports()` returning descriptor objects. | -| `Module.imports(module)` | Partial | Available as instance method `module.imports()` returning descriptor objects. | -| `Module.customSections(module, name)` | Partial | Available as instance method `module.customSections(name)` returning `byte[][]`. | -| `Instance.exports` | Partial | Available as `instance.exports`, with function, memory, table, global, and tag wrappers plus descriptor values for other export kinds. | -| Exported function invocation | Implemented | Supported via `instance.invoke(...)` and `WasmJsExportedFunction.invoke(...)`. | -| Host import functions | Implemented | Supported via `WithWasmImports(...)` and `WasmImportFunction`. | -| Memory object API (`Memory`) | Partial | Exported memories expose `buffer`, `read(offset, count)`, `write(offset, bytes)`, and `grow(delta)`. `buffer` is a current `byte[]` snapshot rather than a live JavaScript `ArrayBuffer`; memory construction and imports are not yet exposed. | -| Table object API (`Table`) | Partial | Exported `funcref` and `externref` tables expose `length`, `get(index)`, `set(index, value)`, and `grow(delta, value)`. Table construction and imports are not yet exposed. | -| Global object API (`Global`) | Partial | Exported numeric and reference globals expose a mutable or immutable `value` accessor and `valueOf()`. Global construction and imports are not yet exposed. | +| `Module.exports(module)` | Implemented | `WebAssembly.Module.exports(module)` gives descriptor objects (`name`, `kind`). | +| `Module.imports(module)` | Implemented | `WebAssembly.Module.imports(module)` gives descriptor objects (`module`, `name`, `kind`). | +| `Module.customSections(module, name)` | Implemented | `WebAssembly.Module.customSections(module, name)` gives ArrayBuffers. | +| `Instance.exports` | Implemented | An object with the exports in the order of the module: functions scripts call (the same function for the same export), and `WebAssembly.Memory`, `Table` and `Global` objects. `new WebAssembly.Instance(module, importObject)` instantiates synchronously. | +| Exported function invocation | Implemented | Exported functions are functions of scripts, converting their arguments and results as the standard says (`i64` as BigInt); a trap is a `RuntimeError`, and what a function of a script imported by the module threw reaches the caller as it is. | +| Host import functions | Implemented | Functions of scripts in the import object, and C# functions via `WithWasmImports(...)` and `WasmImportFunction`. | +| Memory object API (`Memory`) | Implemented | `new WebAssembly.Memory({ initial, maximum })`, imports and exports. With the default Wasmtime backend `buffer` is an ArrayBuffer sharing the bytes of the memory (the memories are pinned .NET arrays, via Wasmtime's host memory creator), which is a new one after the memory has grown. Shared memories are not supported. | +| Table object API (`Table`) | Implemented | `new WebAssembly.Table({ element, initial, maximum })`, imports and exports, with `length`, `get(index)`, `set(index, value)` and `grow(delta, value)`. | +| Global object API (`Global`) | Implemented | `new WebAssembly.Global({ value, mutable }, value)`, imports (also of numbers and BigInts) and exports, with `value` and `valueOf()`. | | Tag object API (`Tag`) | Partial | Host-created and exported tags expose `type().parameters`, including re-exported imported tags. Wasmtime 44 does not expose native Tag handles or enable exception modules through its .NET API. | | Exception object API (`Exception`) | Partial | Host-created exceptions validate typed payloads and expose `is(tag)` and `getArg(tag, index)`. Runtime-thrown Wasm exceptions cannot be projected through Wasmtime 44. | | Error constructors (`CompileError`, `LinkError`, `RuntimeError`) | Implemented | Public DOM-named constructors are available, and compile, instantiate/link, and execution failures are translated at bridge boundaries. | @@ -66,4 +66,4 @@ The current implementation is validated by runtime and bridge tests in the repos ## Interpretation Notes This matrix reflects API shape and behavior in AngleSharp.Wasm, not strict one-to-one Web IDL signatures. -Where the specification defines static namespace or Promise-based operations, AngleSharp.Wasm may expose equivalent functionality through synchronous bridge methods. +Scripts (with AngleSharp.Js) see the API of the standard: `WebAssembly` is a namespace object holding the interfaces (`WebAssembly.Module`, `Instance`, `Memory`, `Table`, `Global`, `Tag`, `Exception` and the errors), and its operations give promises. The synchronous bridge methods remain for C#. diff --git a/src/AngleSharp.Wasm.Docs/docs.config.json b/src/AngleSharp.Wasm.Docs/docs.config.json deleted file mode 100644 index 5504490..0000000 --- a/src/AngleSharp.Wasm.Docs/docs.config.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "AngleSharp.Wasm", - "author": "Florian Rappl", - "branch": "devel", - "repositoryUrl": "https://github.com/AngleSharp/AngleSharp.Wasm", - "rootDir": "../../", - "outputDir": "./dist", - "sitemap": { - "general": { - "sections": [ - { - "generator": "markdown", - "segment": "wasm", - "dir": "general" - } - ] - }, - "docs": { - "sections": [ - { - "generator": "markdown", - "segment": "wasm", - "dir": "tutorials" - } - ] - } - } -} \ No newline at end of file diff --git a/src/AngleSharp.Wasm.Docs/package.json b/src/AngleSharp.Wasm.Docs/package.json deleted file mode 100644 index 1984a5f..0000000 --- a/src/AngleSharp.Wasm.Docs/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@anglesharp/wasm", - "version": "1.1.1", - "preview": true, - "description": "The doclet for the AngleSharp.Wasm documentation.", - "keywords": [ - "pilet" - ], - "dependencies": {}, - "devDependencies": { - "@anglesharp/website": "1.0.0", - "@types/react": "^17.0.5", - "@types/react-dom": "^17.0.5", - "@types/react-router": "latest", - "@types/react-router-dom": "^5.1.7", - "@types/node": "^15.3.0", - "typescript": "^4.2.4", - "@dbeining/react-atom": "4.1.19", - "@libre/atom": "1.3.3", - "history": "4.10.1", - "react": "17.0.2", - "react-dom": "17.0.2", - "react-router": "5.2.0", - "react-router-dom": "5.2.0", - "tslib": "2.2.0", - "path-to-regexp": "1.8.0", - "piral-cli": "^0.13.3-pre.2480", - "piral-cli-parcel": "^0.13.3-pre.2480" - }, - "peerDependencies": { - "@dbeining/react-atom": "*", - "@libre/atom": "*", - "history": "*", - "react": "*", - "react-dom": "*", - "react-router": "*", - "react-router-dom": "*", - "tslib": "*", - "path-to-regexp": "*", - "@anglesharp/website": "*" - }, - "scripts": { - "start": "pilet debug", - "build": "pilet build", - "upgrade": "pilet upgrade" - }, - "main": "dist/index.js", - "files": [ - "dist" - ], - "piral": { - "comment": "Keep this section to use the Piral CLI.", - "name": "@anglesharp/website" - }, - "peerModules": [ - "piral-docs-tools/components" - ] -} diff --git a/src/AngleSharp.Wasm.Docs/src/index.tsx b/src/AngleSharp.Wasm.Docs/src/index.tsx deleted file mode 100644 index dc50b37..0000000 --- a/src/AngleSharp.Wasm.Docs/src/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { PiletApi } from 'piral-docs-tools'; - -const createDoclet = require('piral-docs-tools/doclet'); - -export function setup(api: PiletApi) { - createDoclet(api); -} diff --git a/src/AngleSharp.Wasm.Docs/tsconfig.json b/src/AngleSharp.Wasm.Docs/tsconfig.json deleted file mode 100644 index 610060f..0000000 --- a/src/AngleSharp.Wasm.Docs/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "declaration": true, - "noImplicitAny": false, - "removeComments": false, - "noLib": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es6", - "sourceMap": true, - "outDir": "./dist", - "skipLibCheck": true, - "lib": ["dom", "es2018"], - "moduleResolution": "node", - "module": "esnext", - "jsx": "react", - "importHelpers": true - }, - "include": [ - "./src" - ], - "exclude": [ - "node_modules" - ] -} diff --git a/src/AngleSharp.Wasm.Tests/WasmJsApiTests.cs b/src/AngleSharp.Wasm.Tests/WasmJsApiTests.cs new file mode 100644 index 0000000..b77ef2d --- /dev/null +++ b/src/AngleSharp.Wasm.Tests/WasmJsApiTests.cs @@ -0,0 +1,103 @@ +namespace AngleSharp.Wasm.Tests; + +using AngleSharp.Wasm.Dom; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Reflection; +using System.Threading.Tasks; + +/// +/// The members of the WebAssembly JavaScript API as a scripting library calls them: promises, +/// functions as , and memory shared as . +/// +[TestFixture] +public sealed class WasmJsApiTests +{ + private const string Program = """ + (module + (import "env" "twice" (func $twice (param i32) (result i32))) + (memory (export "memory") 1) + (func (export "callTwice") (param i32) (result i32) local.get 0 call $twice) + (func (export "load") (param i32) (result i32) local.get 0 i32.load8_u) + (func (export "add64") (param i64 i64) (result i64) local.get 0 local.get 1 i64.add) + (func (export "nothing"))) + """; + + private static IDictionary> Imports(WasmJsCallable twice) => + new Dictionary> + { + ["env"] = new Dictionary { ["twice"] = twice }, + }; + + [Test] + public async Task InstantiateGivesFunctionsCallingImports() + { + using var context = BrowsingContext.New(Configuration.Default.WithWasm()); + using var document = await context.OpenNewAsync(); + var bytes = Wasmtime.Module.ConvertText(Program); + + var source = await WebAssembly.InstantiateAsync(context.Current!, bytes, Imports(arguments => 2 * Convert.ToInt32(arguments[0]))); + var exports = source.Instance.ScriptExports; + var callTwice = (WasmJsCallable)exports["callTwice"]!; + var add64 = (WasmJsCallable)exports["add64"]!; + var nothing = (WasmJsCallable)exports["nothing"]!; + + Assert.That(callTwice(new object?[] { 21.0 }), Is.EqualTo(42)); + Assert.That(add64(new object?[] { new BigInteger(long.MaxValue), BigInteger.One }), Is.EqualTo(new BigInteger(long.MinValue))); + Assert.That(nothing(Array.Empty()), Is.SameAs(Missing.Value)); + Assert.That(source.Instance.ScriptExports["callTwice"], Is.SameAs(callTwice)); + } + + [Test] + public async Task MemoryIsSharedWithItsBuffer() + { + using var context = BrowsingContext.New(Configuration.Default.WithWasm()); + using var document = await context.OpenNewAsync(); + var bytes = Wasmtime.Module.ConvertText(Program); + var source = await WebAssembly.InstantiateAsync(context.Current!, bytes, Imports(arguments => arguments[0])); + var memory = (WasmJsMemory)source.Instance.ScriptExports["memory"]!; + var load = (WasmJsCallable)source.Instance.ScriptExports["load"]!; + + var buffer = (Memory)memory.ScriptBuffer; + buffer.Span[3] = 99; + + Assert.That(buffer.Length, Is.EqualTo(65536)); + Assert.That(load(new object?[] { 3.0 }), Is.EqualTo(99)); + Assert.That(memory.Grow(1), Is.EqualTo(1)); + + var grown = (Memory)memory.ScriptBuffer; + + Assert.That(grown.Length, Is.EqualTo(131072)); + Assert.That(grown.Span[3], Is.EqualTo(99)); + Assert.That(((Memory)memory.ScriptBuffer).Equals(grown), Is.True); + } + + [Test] + public async Task FailuresAreTheErrorsOfTheStandard() + { + using var context = BrowsingContext.New(Configuration.Default.WithWasm()); + using var document = await context.OpenNewAsync(); + var bytes = Wasmtime.Module.ConvertText(Program); + + Assert.That(async () => await WebAssembly.CompileAsync(context.Current!, new byte[] { 0, 97, 115, 109, 9 }), Throws.TypeOf()); + Assert.That(async () => await WebAssembly.InstantiateAsync(context.Current!, bytes, new Dictionary> + { + ["env"] = new Dictionary { ["twice"] = 5.0 }, + }), Throws.TypeOf()); + } + + [Test] + public async Task ExceptionOfAnImportReachesTheCaller() + { + using var context = BrowsingContext.New(Configuration.Default.WithWasm()); + using var document = await context.OpenNewAsync(); + var bytes = Wasmtime.Module.ConvertText(Program); + var thrown = new InvalidOperationException("exit"); + var source = await WebAssembly.InstantiateAsync(context.Current!, bytes, Imports(arguments => throw thrown)); + var callTwice = (WasmJsCallable)source.Instance.ScriptExports["callTwice"]!; + + Assert.That(() => callTwice(new object?[] { 1.0 }), Throws.Exception.SameAs(thrown)); + } +} diff --git a/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj b/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj index 868bf5f..c71c491 100644 --- a/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj +++ b/src/AngleSharp.Wasm/AngleSharp.Wasm.csproj @@ -33,7 +33,7 @@ true true snupkg - 1.5.0 + 1.11.0 @@ -55,6 +55,10 @@ <_Parameter1>false + + + <_Parameter1>AngleSharp.Wasm.WasmDom + diff --git a/src/AngleSharp.Wasm/Dom/WasmJsErrors.cs b/src/AngleSharp.Wasm/Dom/WasmJsErrors.cs index ea0de89..dabe9c9 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsErrors.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsErrors.cs @@ -7,6 +7,7 @@ namespace AngleSharp.Wasm.Dom; /// Represents a WebAssembly compilation failure. /// [DomName("CompileError")] +[DomExposed("WebAssembly")] public sealed class WasmJsCompileError : Exception { /// @@ -27,6 +28,7 @@ public WasmJsCompileError() /// /// Creates a compilation error with a message. /// + [DomConstructor] public WasmJsCompileError(string? message) : base(message) { @@ -42,6 +44,7 @@ internal WasmJsCompileError(string? message, Exception innerException) /// Represents a WebAssembly instantiation or linking failure. /// [DomName("LinkError")] +[DomExposed("WebAssembly")] public sealed class WasmJsLinkError : Exception { /// @@ -62,6 +65,7 @@ public WasmJsLinkError() /// /// Creates a linking error with a message. /// + [DomConstructor] public WasmJsLinkError(string? message) : base(message) { @@ -77,6 +81,7 @@ internal WasmJsLinkError(string? message, Exception innerException) /// Represents a WebAssembly execution failure. /// [DomName("RuntimeError")] +[DomExposed("WebAssembly")] public sealed class WasmJsRuntimeError : Exception { /// @@ -97,6 +102,7 @@ public WasmJsRuntimeError() /// /// Creates a runtime error with a message. /// + [DomConstructor] public WasmJsRuntimeError(string? message) : base(message) { diff --git a/src/AngleSharp.Wasm/Dom/WasmJsException.cs b/src/AngleSharp.Wasm/Dom/WasmJsException.cs index 93c6865..1d90ce9 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsException.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsException.cs @@ -8,6 +8,7 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible WebAssembly exception. /// [DomName("Exception")] +[DomExposed("WebAssembly")] public sealed class WasmJsException : Exception { private readonly WasmJsTag _tag; diff --git a/src/AngleSharp.Wasm/Dom/WasmJsExportValue.cs b/src/AngleSharp.Wasm/Dom/WasmJsExportValue.cs index 07902bc..7aa1294 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsExportValue.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsExportValue.cs @@ -6,6 +6,7 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible non-function export entry. /// [DomName("ExportedValue")] +[DomNoInterfaceObject] public sealed class WasmJsExportValue { internal WasmJsExportValue(string name, string kind) diff --git a/src/AngleSharp.Wasm/Dom/WasmJsExportedFunction.cs b/src/AngleSharp.Wasm/Dom/WasmJsExportedFunction.cs index 4c9d4aa..e76fbf7 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsExportedFunction.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsExportedFunction.cs @@ -7,6 +7,7 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible exported function wrapper. /// [DomName("ExportedFunction")] +[DomNoInterfaceObject] public sealed class WasmJsExportedFunction { private readonly WasmJsInstance? _owner; diff --git a/src/AngleSharp.Wasm/Dom/WasmJsExports.cs b/src/AngleSharp.Wasm/Dom/WasmJsExports.cs index b16232c..9959d63 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsExports.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsExports.cs @@ -9,12 +9,14 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible exports object. /// [DomName("Exports")] +[DomNoInterfaceObject] public sealed class WasmJsExports { private readonly IReadOnlyDictionary _entries; internal WasmJsExports(WasmJsInstance owner, IReadOnlyList exportsMetadata) { + Metadata = exportsMetadata; var tags = new Dictionary(); _entries = exportsMetadata .ToDictionary( @@ -22,6 +24,8 @@ internal WasmJsExports(WasmJsInstance owner, IReadOnlyList CreateExport(owner, m, tags)); } + internal IReadOnlyList Metadata { get; } + private static object CreateExport( WasmJsInstance owner, WasmModuleExportDescriptor metadata, diff --git a/src/AngleSharp.Wasm/Dom/WasmJsGlobal.cs b/src/AngleSharp.Wasm/Dom/WasmJsGlobal.cs index 592f0ce..fc92b14 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsGlobal.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsGlobal.cs @@ -1,41 +1,111 @@ namespace AngleSharp.Wasm.Dom; +using System; using AngleSharp.Attributes; +using AngleSharp.Dom; +using Wasmtime; /// -/// JavaScript-visible WebAssembly global. +/// A global of WebAssembly (WebAssembly.Global). /// [DomName("Global")] +[DomExposed("WebAssembly")] public sealed class WasmJsGlobal { private readonly IWasmGlobal _global; + private readonly WasmJsRealm? _realm; internal WasmJsGlobal(IWasmGlobal global) { _global = global; } + internal WasmJsGlobal(WasmJsRealm realm, WasmtimeGlobal global) + { + _global = global; + _realm = realm; + } + + /// + /// Creates a global (new WebAssembly.Global). + /// + /// The host. + /// The type of the value and if it may change. + /// The value, if any; else the default of the type. + [DomConstructor] + public WasmJsGlobal(IWindow window, WasmJsGlobalDescriptor descriptor, object? value = null) + { + if (descriptor is null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + _realm = WebAssembly.GetRealm(window); + var kind = ParseKind(descriptor.Value); + var initial = value is null || value == System.Reflection.Missing.Value ? DefaultOf(kind) : _realm.ToWasm(value, kind); + var global = new Global(_realm.Store, kind, initial, descriptor.Mutable ? Mutability.Mutable : Mutability.Immutable); + _global = new WasmtimeGlobal(_realm.Context, global); + } + + internal Global? Native => (_global as WasmtimeGlobal)?.Native; + /// - /// Gets or sets the global value. + /// Gets or sets the value: a number, or a BigInt for i64. /// [DomName("value")] [DomAccessor(Accessors.Getter | Accessors.Setter)] public object? Value { - get => Wrap(_global.GetValue()); - set => _global.SetValue(Unwrap(value)); + get => _realm is not null && Native is Global global ? _realm.FromWasm(global.GetValue()) : Wrap(_global.GetValue()); + set + { + if (_realm is not null && Native is Global global) + { + if (global.Mutability != Mutability.Mutable) + { + throw new InvalidOperationException("The WebAssembly global is immutable."); + } + + global.SetValue(_realm.ToWasm(value, global.Kind)); + } + else + { + _global.SetValue(Unwrap(value)); + } + } } /// - /// Gets the primitive global value. + /// Gets the value. /// - /// The current value. + /// The value. [DomName("valueOf")] public object? ValueOf() => Value; + internal static ValueKind ParseKind(string? type) => type switch + { + "i32" => ValueKind.Int32, + "i64" => ValueKind.Int64, + "f32" => ValueKind.Float32, + "f64" => ValueKind.Float64, + "anyfunc" or "funcref" => ValueKind.FuncRef, + "externref" => ValueKind.ExternRef, + _ => throw new ArgumentException($"'{type}' is no type of WebAssembly."), + }; + + internal static object? DefaultOf(ValueKind kind) => kind switch + { + ValueKind.Int32 => 0, + ValueKind.Int64 => 0L, + ValueKind.Float32 => 0f, + ValueKind.Float64 => 0d, + ValueKind.FuncRef => Function.Null, + _ => null, + }; + private static object? Wrap(object? value) => value is IWasmFunction function ? new WasmJsExportedFunction(function) : value; private static object? Unwrap(object? value) => value is WasmJsExportedFunction { Function: not null } function ? function.Function : value; -} \ No newline at end of file +} diff --git a/src/AngleSharp.Wasm/Dom/WasmJsInstance.cs b/src/AngleSharp.Wasm/Dom/WasmJsInstance.cs index e5e3938..81b4586 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsInstance.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsInstance.cs @@ -1,31 +1,67 @@ namespace AngleSharp.Wasm.Dom; using AngleSharp.Attributes; +using AngleSharp.Dom; using System; using System.Collections.Generic; /// -/// JavaScript-visible instance handle. +/// An instance of a module (WebAssembly.Instance). /// [DomName("Instance")] +[DomExposed("WebAssembly")] public sealed class WasmJsInstance { private readonly WasmJsExports _exports; + private readonly IDictionary _scriptExports; internal WasmJsInstance(IWasmInstance instance, IReadOnlyList exportsMetadata) { Instance = instance; _exports = new WasmJsExports(this, exportsMetadata); + _scriptExports = new Dictionary(); + } + + internal WasmJsInstance(WasmJsRealm realm, WasmtimeInstance instance, WasmJsModule module) + { + Instance = instance; + _exports = new WasmJsExports(this, module.ExportsMetadata); + _scriptExports = realm.GetExports(instance.Native, ((WasmtimeCompiledModule)module.Module).Module); + } + + /// + /// Instantiates a module (new WebAssembly.Instance), synchronously. + /// + /// The host. + /// The module. + /// What the module imports, by module and name. + [DomConstructor] + public WasmJsInstance(IWindow window, WasmJsModule module, IDictionary>? importObject = null) + : this(WebAssembly.InstantiateCore(window, module, importObject)) + { + } + + private WasmJsInstance(WasmJsInstance instance) + { + Instance = instance.Instance; + _exports = new WasmJsExports(this, instance._exports.Metadata); + _scriptExports = instance._scriptExports; } internal IWasmInstance Instance { get; } /// - /// Gets the module exports object. + /// Gets the exports of the instance for C#, by name. + /// + public WasmJsExports Exports => _exports; + + /// + /// Gets the exports as scripts see them (instance.exports): an object with the functions, + /// memories, tables and globals the module exports. /// [DomName("exports")] [DomAccessor(Accessors.Getter)] - public WasmJsExports Exports => _exports; + public IDictionary ScriptExports => _scriptExports; /// /// Invokes an exported function. @@ -33,7 +69,6 @@ internal WasmJsInstance(IWasmInstance instance, IReadOnlyListThe exported function name. /// The invocation arguments. /// The invocation result. - [DomName("invoke")] public object? Invoke(string exportName, params object?[] arguments) { try diff --git a/src/AngleSharp.Wasm/Dom/WasmJsInstantiationResult.cs b/src/AngleSharp.Wasm/Dom/WasmJsInstantiationResult.cs index 8ef0d4b..9b83a36 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsInstantiationResult.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsInstantiationResult.cs @@ -6,6 +6,7 @@ namespace AngleSharp.Wasm.Dom; /// Contains a compiled module and its instantiated instance. /// [DomName("WebAssemblyInstantiatedSource")] +[DomNoInterfaceObject] public sealed class WasmJsInstantiationResult { internal WasmJsInstantiationResult(WasmJsModule module, WasmJsInstance instance) diff --git a/src/AngleSharp.Wasm/Dom/WasmJsMemory.cs b/src/AngleSharp.Wasm/Dom/WasmJsMemory.cs index 03cf2f8..ac9bb5b 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsMemory.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsMemory.cs @@ -1,35 +1,89 @@ namespace AngleSharp.Wasm.Dom; -using AngleSharp.Attributes; using System; +using AngleSharp.Attributes; +using AngleSharp.Dom; +using Wasmtime; /// -/// JavaScript-visible WebAssembly linear memory. +/// A linear memory of WebAssembly (WebAssembly.Memory), whose buffer is an ArrayBuffer +/// sharing its bytes. /// [DomName("Memory")] +[DomExposed("WebAssembly")] public sealed class WasmJsMemory { + private const long PageSize = 65536; + private readonly IWasmMemory _memory; + private readonly WasmJsRealm? _realm; internal WasmJsMemory(IWasmMemory memory) { _memory = memory; } + internal WasmJsMemory(WasmJsRealm realm, WasmtimeMemory memory) + { + _memory = memory; + _realm = realm; + } + /// - /// Gets a snapshot of the current memory contents. + /// Creates a memory (new WebAssembly.Memory). + /// + /// The host. + /// The initial and maximum size in pages. + [DomConstructor] + public WasmJsMemory(IWindow window, WasmJsMemoryDescriptor descriptor) + { + if (descriptor is null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + else if (descriptor.Shared) + { + throw new NotSupportedException("Shared memories are not supported."); + } + + _realm = WebAssembly.GetRealm(window); + var maximum = descriptor.Maximum is double max ? (long?)ToSize(max) : null; + _memory = new WasmtimeMemory(_realm.CreateMemory(ToSize(descriptor.Initial), maximum)); + } + + internal Memory? Native => (_memory as WasmtimeMemory)?.Native; + + /// + /// Gets a copy of the bytes of the memory. + /// + public byte[] Buffer => Read(0, checked((int)_memory.Length)); + + /// + /// Gets the bytes of the memory as scripts see them (memory.buffer): an ArrayBuffer sharing + /// them, which is a new one once the memory has grown, as in browsers. /// [DomName("buffer")] [DomAccessor(Accessors.Getter)] - public byte[] Buffer => Read(0, checked((int)_memory.Length)); + public object ScriptBuffer + { + get + { + if (Native is Memory memory && HostMemory.Find(memory.GetPointer(), memory.GetLength()) is byte[] bytes) + { + return new Memory(bytes); + } + + // the memory isn't in an array of .NET, so scripts get what is there at the moment + return Buffer; + } + } /// - /// Reads bytes from memory. + /// Reads bytes of the memory. /// - /// The byte offset in memory. - /// The number of bytes to read. - /// A copy of the requested bytes. - [DomName("read")] + /// The address. + /// The number of bytes. + /// The bytes. public byte[] Read(long offset, int count) { if (count < 0) @@ -44,11 +98,10 @@ public byte[] Read(long offset, int count) } /// - /// Writes bytes into memory. + /// Writes bytes to the memory. /// - /// The byte offset in memory. - /// The bytes to write. - [DomName("write")] + /// The address. + /// The bytes. public void Write(long offset, byte[] bytes) { if (bytes is null) @@ -61,10 +114,10 @@ public void Write(long offset, byte[] bytes) } /// - /// Grows the memory by a number of WebAssembly pages. + /// Grows the memory (memory.grow). /// /// The number of pages to add. - /// The previous size in pages. + /// The size in pages before. [DomName("grow")] public long Grow(long delta) { @@ -73,9 +126,21 @@ public long Grow(long delta) throw new ArgumentOutOfRangeException(nameof(delta)); } - return _memory.Grow(delta); + try + { + return _memory.Grow(delta); + } + catch (Exception exception) when (exception is Wasmtime.WasmtimeException) + { + throw new ArgumentOutOfRangeException(nameof(delta), exception.Message); + } } + private static long ToSize(double pages) => + pages >= 0 && pages <= 65536 && pages == Math.Floor(pages) + ? (long)pages + : throw new ArgumentOutOfRangeException(nameof(pages), "The size has to be a number of pages from 0 to 65536."); + private void EnsureRange(long offset, int count) { if (offset < 0 || offset > _memory.Length - count) @@ -83,4 +148,4 @@ private void EnsureRange(long offset, int count) throw new ArgumentOutOfRangeException(nameof(offset)); } } -} \ No newline at end of file +} diff --git a/src/AngleSharp.Wasm/Dom/WasmJsModule.cs b/src/AngleSharp.Wasm/Dom/WasmJsModule.cs index 31054fa..6a8cde3 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsModule.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsModule.cs @@ -1,6 +1,7 @@ namespace AngleSharp.Wasm.Dom; using AngleSharp.Attributes; +using AngleSharp.Dom; using System; using System.Collections.Generic; using System.Linq; @@ -9,6 +10,7 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible module handle. /// [DomName("Module")] +[DomExposed("WebAssembly")] public sealed class WasmJsModule { private readonly WasmModuleMetadata _metadata; @@ -20,6 +22,52 @@ internal WasmJsModule(IWasmRuntime runtime, IWasmCompiledModule module, byte[] m _metadata = WasmModuleMetadata.Parse(moduleBytes); } + /// + /// Compiles a module (new WebAssembly.Module), synchronously. + /// + /// The host. + /// The bytes of the module. + [DomConstructor] + public WasmJsModule(IWindow window, byte[] bytes) + : this(WebAssembly.Compile(window, bytes)) + { + } + + private WasmJsModule(WasmJsModule compiled) + { + Runtime = compiled.Runtime; + Module = compiled.Module; + _metadata = compiled._metadata; + } + + /// + /// Gets the exports of a module (WebAssembly.Module.exports): their names and kinds. + /// + /// The module. + /// The descriptions of the exports. + [DomName("exports")] + public static WasmModuleExportDescriptor[] Exports(WasmJsModule module) => + (module ?? throw new ArgumentNullException(nameof(module))).Exports(); + + /// + /// Gets the imports of a module (WebAssembly.Module.imports): their modules, names and kinds. + /// + /// The module. + /// The descriptions of the imports. + [DomName("imports")] + public static WasmModuleImportDescriptor[] Imports(WasmJsModule module) => + (module ?? throw new ArgumentNullException(nameof(module))).Imports(); + + /// + /// Gets the custom sections of a module with the given name (WebAssembly.Module.customSections). + /// + /// The module. + /// The name of the sections. + /// The contents of the sections, ArrayBuffers for scripts. + [DomName("customSections")] + public static byte[][] CustomSections(WasmJsModule module, string sectionName) => + (module ?? throw new ArgumentNullException(nameof(module))).CustomSections(sectionName); + internal IWasmRuntime Runtime { get; } internal IWasmCompiledModule Module { get; } @@ -30,14 +78,12 @@ internal WasmJsModule(IWasmRuntime runtime, IWasmCompiledModule module, byte[] m /// Gets this module's exported names and kinds. /// /// The export descriptors. - [DomName("exports")] public WasmModuleExportDescriptor[] Exports() => _metadata.Exports.ToArray(); /// /// Gets this module's imported names and kinds. /// /// The import descriptors. - [DomName("imports")] public WasmModuleImportDescriptor[] Imports() => _metadata.Imports.ToArray(); /// @@ -45,7 +91,6 @@ internal WasmJsModule(IWasmRuntime runtime, IWasmCompiledModule module, byte[] m /// /// The custom section name. /// The custom section payloads. - [DomName("customSections")] public byte[][] CustomSections(string sectionName) { if (sectionName is null) diff --git a/src/AngleSharp.Wasm/Dom/WasmJsRealm.cs b/src/AngleSharp.Wasm/Dom/WasmJsRealm.cs new file mode 100644 index 0000000..91a4797 --- /dev/null +++ b/src/AngleSharp.Wasm/Dom/WasmJsRealm.cs @@ -0,0 +1,471 @@ +namespace AngleSharp.Wasm.Dom; + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Numerics; +using System.Reflection; +using System.Runtime.CompilerServices; +using AngleSharp.Dom; +using Wasmtime; + +/// +/// The WebAssembly JavaScript API of a browsing context (an agent, in the terms of the +/// standard): its objects (memories, tables, globals, instances) live in one store, so they can +/// be imported by any of its modules, and values are converted as the standard says. +/// +internal sealed class WasmJsRealm +{ + private static readonly ConditionalWeakTable Realms = new(); + + private readonly ConditionalWeakTable _functions = new(); + private readonly Dictionary<(ulong, IntPtr), WasmJsCallable> _callables = new(); + private Exception? _pending; + + private WasmJsRealm(WasmtimeWasmRuntime runtime) + { + Runtime = runtime; + Context = runtime.CreateStoreContext(); + } + + internal WasmtimeWasmRuntime Runtime { get; } + + internal WasmtimeStoreContext Context { get; } + + internal Store Store => Context.Store; + + /// + /// Gets the realm of the window's browsing context. + /// + public static WasmJsRealm Of(IWindow window, IWasmRuntime runtime) + { + var context = window?.Document?.Context ?? throw new InvalidOperationException("The window has no browsing context."); + + return Realms.GetValue(context, _ => runtime is WasmtimeWasmRuntime wasmtime + ? new WasmJsRealm(wasmtime) + : throw new NotSupportedException("The WebAssembly JavaScript API needs the Wasmtime runtime (WithWasm()).")); + } + + #region Instantiation + + public WasmJsInstance Instantiate(WasmJsModule module, IDictionary>? importObject) + { + var compiled = module.Module as WasmtimeCompiledModule + ?? throw new ArgumentException("The module was compiled by another runtime.", nameof(module)); + var native = compiled.Module; + + if (native.Imports.Count > 0 && importObject is null) + { + throw new ArgumentException("The module has imports, but no import object was given."); + } + + using var linker = new Linker(Runtime.Engine) { AllowShadowing = true }; + + foreach (var import in native.Imports) + { + if (importObject is null || !importObject.TryGetValue(import.ModuleName, out var entries) || entries is null) + { + throw new ArgumentException($"The import object has no module '{import.ModuleName}'."); + } + + entries.TryGetValue(import.Name, out var value); + var label = $"{import.ModuleName}.{import.Name}"; + + switch (import) + { + case FunctionImport function: + if (value?.Function is not WasmJsCallable callable) + { + throw new WasmJsLinkError($"The import {label} has to be a function."); + } + + linker.Define(import.ModuleName, import.Name, _functions.TryGetValue(callable, out var exported) + ? exported + : CreateHostFunction(callable, function.Parameters, function.Results)); + break; + case GlobalImport global: + linker.Define(import.ModuleName, import.Name, GetImportedGlobal(value, global, label)); + break; + case MemoryImport: + linker.Define(import.ModuleName, import.Name, value?.Value is WasmJsMemory { Native: { } memory } + ? memory + : throw new WasmJsLinkError($"The import {label} has to be a WebAssembly.Memory.")); + break; + case TableImport: + linker.Define(import.ModuleName, import.Name, value?.Value is WasmJsTable { Native: { } table } + ? table + : throw new WasmJsLinkError($"The import {label} has to be a WebAssembly.Table.")); + break; + } + } + + var instance = Run(() => linker.Instantiate(Store, native), error => new WasmJsLinkError(error.Message, error)); + return new WasmJsInstance(this, new WasmtimeInstance(Context, instance), module); + } + + private Global GetImportedGlobal(WasmJsImportValue? value, GlobalImport import, string label) + { + if (value?.Value is WasmJsGlobal { Native: { } global }) + { + return global; + } + + if (value is null || value.Value is null || import.Mutability == Mutability.Mutable) + { + throw new WasmJsLinkError($"The import {label} has to be a WebAssembly.Global or a number."); + } + + if (import.Kind == ValueKind.Int64 ? value.Value is not BigInteger : value.Value is BigInteger) + { + throw new WasmJsLinkError($"The import {label} has to be a {(import.Kind == ValueKind.Int64 ? "BigInt" : "number")}."); + } + + return new Global(Store, import.Kind, ToWasm(value.Value, import.Kind), Mutability.Immutable); + } + + /// + /// Gets the exports of an instance as scripts see them: functions, and the objects of the + /// memories, tables and globals, in the order of the module. + /// + public IDictionary GetExports(Instance instance, Wasmtime.Module module) + { + var exports = new Dictionary(StringComparer.Ordinal); + + foreach (var export in module.Exports) + { + var name = export.Name; + exports[name] = export switch + { + FunctionExport => GetCallable(instance.GetFunction(name)!), + MemoryExport => new WasmJsMemory(this, new WasmtimeMemory(instance.GetMemory(name)!)), + TableExport => new WasmJsTable(this, new WasmtimeTable(Context, instance.GetTable(name)!)), + GlobalExport => new WasmJsGlobal(this, new WasmtimeGlobal(Context, instance.GetGlobal(name)!)), + _ => null, + }; + } + + return exports; + } + + #endregion + + /// + /// Creates a memory (new WebAssembly.Memory). Wasmtime creates the memories of instances + /// only by the host memory creator, so it is the export of a module of just a memory. + /// + public Memory CreateMemory(long minimum, long? maximum) + { + if (!Runtime.HasHostMemory) + { + return new Memory(Store, minimum, maximum, false); + } + + using var module = Wasmtime.Module.FromBytes(Runtime.Engine, "memory", CreateMemoryModule(minimum, maximum)); + var instance = new Instance(Store, module); + return instance.GetMemory("m")!; + } + + // (module (memory (export "m") minimum maximum)) + private static byte[] CreateMemoryModule(long minimum, long? maximum) + { + var limits = new List { maximum is null ? (byte)0 : (byte)1 }; + limits.AddRange(Leb128((ulong)minimum)); + + if (maximum is long max) + { + limits.AddRange(Leb128((ulong)max)); + } + + var bytes = new List { 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00 }; + bytes.Add(0x05); + bytes.AddRange(Leb128((ulong)(limits.Count + 1))); + bytes.Add(0x01); + bytes.AddRange(limits); + bytes.AddRange(new byte[] { 0x07, 0x05, 0x01, 0x01, (byte)'m', 0x02, 0x00 }); + return bytes.ToArray(); + } + + private static IEnumerable Leb128(ulong value) + { + do + { + var current = (byte)(value & 0x7F); + value >>= 7; + yield return value != 0 ? (byte)(current | 0x80) : current; + } + while (value != 0); + } + + #region Functions + + /// + /// Gets the function scripts call for a function of WebAssembly (an "Exported Function"), + /// which is the same one for the same function. + /// + public WasmJsCallable GetCallable(Function function) + { + var key = GetKey(function); + + if (key is not null && _callables.TryGetValue(key.Value, out var known)) + { + return known; + } + + WasmJsCallable callable = arguments => Invoke(function, arguments); + _functions.Add(callable, function); + + if (key is not null) + { + _callables[key.Value] = callable; + } + + return callable; + } + + private static readonly FieldInfo? FuncField = typeof(Function).GetField("func", BindingFlags.Instance | BindingFlags.NonPublic); + + // Wasmtime gives a new object for the same function each time; what it stands for is the + // store and index of wasmtime_func_t, which is all the fields of the struct. + private static (ulong, IntPtr)? GetKey(Function function) + { + if (FuncField?.GetValue(function) is { } func) + { + var fields = func.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + if (fields.Length == 2 && fields[0].GetValue(func) is ulong store && fields[1].GetValue(func) is IntPtr index) + { + return (store, index); + } + } + + return null; + } + + /// + /// Gets the function of WebAssembly behind a function a script gave, if it is one. + /// + public Function? FindFunction(WasmJsCallable callable) => + _functions.TryGetValue(callable, out var function) ? function : null; + + private object? Invoke(Function function, object?[] arguments) + { + var parameters = function.Parameters; + var values = new ValueBox[parameters.Count]; + + for (var i = 0; i < values.Length; i++) + { + values[i] = ToBox(i < arguments.Length ? arguments[i] : Missing.Value, parameters[i]); + } + + var result = Run(() => function.Invoke(values), error => new WasmJsRuntimeError(error.Message, error)); + var results = function.Results; + + if (results.Count == 0) + { + return Missing.Value; + } + else if (results.Count == 1) + { + return FromWasm(result); + } + + var list = (object?[])result!; + var converted = new object?[list.Length]; + + for (var i = 0; i < list.Length; i++) + { + converted[i] = FromWasm(list[i]); + } + + return converted; + } + + private Function CreateHostFunction(WasmJsCallable callable, IReadOnlyList parameters, IReadOnlyList results) => + Function.FromCallback(Store, (Caller caller, ReadOnlySpan arguments, Span values) => + { + try + { + var given = new object?[arguments.Length]; + + for (var i = 0; i < given.Length; i++) + { + given[i] = FromBox(arguments[i], parameters[i]); + } + + var result = callable(given); + + if (values.Length == 1) + { + values[0] = ToBox(result, results[0]); + } + else if (values.Length > 1) + { + var list = result as IList ?? throw new ArgumentException("A function with several results has to return an array."); + + for (var i = 0; i < values.Length; i++) + { + values[i] = ToBox(i < list.Count ? list[i] : Missing.Value, results[i]); + } + } + } + catch (Exception exception) + { + // what the script threw is what reaches the script calling into WebAssembly + _pending = exception; + throw; + } + }, parameters, results); + + /// + /// Runs WebAssembly: a trap is a RuntimeError, unless a function of a script threw, which + /// goes on as it is (e.g. the exit of a program compiled by Emscripten). + /// + public T Run(Func action, Func translate) + { + _pending = null; + + try + { + return Context.Run(static run => run(), action); + } + catch (WasmtimeException exception) + { + var pending = _pending; + _pending = null; + throw pending ?? translate(exception); + } + } + + #endregion + + #region Values + + /// + /// Converts a value of WebAssembly to what scripts see (ToJSValue): i64 is a BigInt. + /// + public object? FromWasm(object? value) => value switch + { + int integer => integer, + long integer => new BigInteger(integer), + float number => (double)number, + double number => number, + Function { IsNull: true } => null, + Function function => GetCallable(function), + _ => value, + }; + + private object? FromBox(ValueBox value, ValueKind kind) => kind switch + { + ValueKind.Int32 => value.AsInt32(), + ValueKind.Int64 => new BigInteger(value.AsInt64()), + ValueKind.Float32 => (double)value.AsSingle(), + ValueKind.Float64 => value.AsDouble(), + ValueKind.FuncRef => FromWasm(value.AsFunction(Store)), + _ => value.As(), + }; + + /// + /// Converts what a script gave to a value of WebAssembly (ToWebAssemblyValue). + /// + public object? ToWasm(object? value, ValueKind kind) => kind switch + { + ValueKind.Int32 => ToInt32(ToNumber(value)), + ValueKind.Int64 => ToBigInt64(value), + ValueKind.Float32 => (float)ToNumber(value), + ValueKind.Float64 => ToNumber(value), + ValueKind.FuncRef => ToFunction(value), + _ => value == Missing.Value ? null : value, + }; + + private ValueBox ToBox(object? value, ValueKind kind) => kind switch + { + ValueKind.Int32 => ToInt32(ToNumber(value)), + ValueKind.Int64 => ToBigInt64(value), + ValueKind.Float32 => (float)ToNumber(value), + ValueKind.Float64 => ToNumber(value), + ValueKind.FuncRef => ToFunction(value), + _ => ValueBox.AsBox(value == Missing.Value ? null : value), + }; + + private Function ToFunction(object? value) => value switch + { + null => Function.Null, + WasmJsCallable callable when FindFunction(callable) is { } function => function, + _ => throw new ArgumentException("The value has to be null or an exported function of WebAssembly."), + }; + + /// + /// ToNumber of ECMAScript for what a script gave; a BigInt is no number. + /// + public static double ToNumber(object? value) => value switch + { + null => 0, + double number => number, + int number => number, + float number => number, + long number => number, + bool flag => flag ? 1 : 0, + string text => ParseNumber(text), + BigInteger => throw new ArgumentException("A BigInt can't be converted to a number."), + _ => double.NaN, + }; + + private static double ParseNumber(string text) + { + var trimmed = text.Trim(); + + if (trimmed.Length == 0) + { + return 0; + } + + if (trimmed.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && + long.TryParse(trimmed.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var hex)) + { + return hex; + } + + return trimmed switch + { + "Infinity" or "+Infinity" => double.PositiveInfinity, + "-Infinity" => double.NegativeInfinity, + _ => double.TryParse(trimmed, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? number : double.NaN, + }; + } + + /// + /// ToInt32 of ECMAScript: the number modulo 2^32. + /// + public static int ToInt32(double number) + { + if (double.IsNaN(number) || double.IsInfinity(number)) + { + return 0; + } + + var truncated = Math.Truncate(number); + var modulo = truncated % 4294967296.0; + return unchecked((int)(uint)(modulo < 0 ? modulo + 4294967296.0 : modulo)); + } + + /// + /// ToBigInt64 of ECMAScript: a BigInt (or what converts to one) modulo 2^64. + /// + public static long ToBigInt64(object? value) + { + var integer = value switch + { + BigInteger big => big, + bool flag => flag ? BigInteger.One : BigInteger.Zero, + string text => text.Trim().Length == 0 + ? BigInteger.Zero + : BigInteger.TryParse(text.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var parsed) + ? parsed + : throw new ArgumentException($"'{text}' can't be converted to a BigInt."), + _ => throw new ArgumentException("The value has to be a BigInt."), + }; + return unchecked((long)(ulong)(integer & ulong.MaxValue)); + } + + #endregion +} diff --git a/src/AngleSharp.Wasm/Dom/WasmJsTable.cs b/src/AngleSharp.Wasm/Dom/WasmJsTable.cs index 559278f..3fecf19 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsTable.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsTable.cs @@ -1,60 +1,128 @@ namespace AngleSharp.Wasm.Dom; -using AngleSharp.Attributes; using System; +using AngleSharp.Attributes; +using AngleSharp.Dom; +using Wasmtime; /// -/// JavaScript-visible WebAssembly table. +/// A table of WebAssembly (WebAssembly.Table), e.g. of functions. /// [DomName("Table")] +[DomExposed("WebAssembly")] public sealed class WasmJsTable { private readonly IWasmTable _table; + private readonly WasmJsRealm? _realm; internal WasmJsTable(IWasmTable table) { _table = table; } + internal WasmJsTable(WasmJsRealm realm, WasmtimeTable table) + { + _table = table; + _realm = realm; + } + + /// + /// Creates a table (new WebAssembly.Table). + /// + /// The host. + /// The type of the elements and the initial and maximum length. + /// The value of the elements, if any; else null. + [DomConstructor] + public WasmJsTable(IWindow window, WasmJsTableDescriptor descriptor, object? value = null) + { + if (descriptor is null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + _realm = WebAssembly.GetRealm(window); + var kind = WasmJsGlobal.ParseKind(descriptor.Element); + + if (kind != ValueKind.FuncRef && kind != ValueKind.ExternRef) + { + throw new ArgumentException($"'{descriptor.Element}' is no type of the elements of a table."); + } + + var initial = ToLength(descriptor.Initial); + var maximum = descriptor.Maximum is double max ? ToLength(max) : uint.MaxValue; + var element = value is null || value == System.Reflection.Missing.Value ? WasmJsGlobal.DefaultOf(kind) : _realm.ToWasm(value, kind); + _table = new WasmtimeTable(_realm.Context, new Table(_realm.Store, kind == ValueKind.FuncRef ? TableKind.FuncRef : TableKind.ExternRef, element, initial, maximum)); + } + + internal Table? Native => (_table as WasmtimeTable)?.Native; + /// - /// Gets the current number of elements. + /// Gets the number of elements. /// [DomName("length")] [DomAccessor(Accessors.Getter)] public ulong Length => _table.Length; /// - /// Gets an element by index. + /// Gets an element. /// - /// The element index. - /// The table element. + /// The index. + /// The element, e.g. a function or null. [DomName("get")] public object? Get(uint index) { EnsureIndex(index); + + if (_realm is not null && Native is Table table) + { + return _realm.FromWasm(table.GetElement(index)); + } + return Wrap(_table.Get(index)); } /// - /// Sets an element by index. + /// Sets an element. /// - /// The element index. - /// The new element value. + /// The index. + /// The element, e.g. an exported function or null. [DomName("set")] - public void Set(uint index, object? value) + public void Set(uint index, object? value = null) { EnsureIndex(index); - _table.Set(index, Unwrap(value)); + + if (_realm is not null && Native is Table table) + { + table.SetElement(index, ToElement(table, value)); + } + else + { + _table.Set(index, Unwrap(value)); + } } /// - /// Grows the table and initializes the new elements. + /// Grows the table. /// /// The number of elements to add. - /// The initial value for new elements. - /// The previous table length. + /// The value of the new elements, if any; else null. + /// The length before. [DomName("grow")] - public ulong Grow(uint delta, object? value = null) => _table.Grow(delta, Unwrap(value)); + public ulong Grow(uint delta, object? value = null) => + _realm is not null && Native is Table table + ? table.Grow(delta, ToElement(table, value)) + : _table.Grow(delta, Unwrap(value)); + + private object? ToElement(Table table, object? value) + { + var kind = table.Kind == TableKind.FuncRef ? ValueKind.FuncRef : ValueKind.ExternRef; + return value is null || value == System.Reflection.Missing.Value ? WasmJsGlobal.DefaultOf(kind) : _realm!.ToWasm(value, kind); + } + + private static uint ToLength(double length) => + length >= 0 && length <= uint.MaxValue && length == Math.Floor(length) + ? (uint)length + : throw new ArgumentOutOfRangeException(nameof(length)); private void EnsureIndex(uint index) { @@ -69,4 +137,4 @@ private void EnsureIndex(uint index) private static object? Unwrap(object? value) => value is WasmJsExportedFunction { Function: not null } function ? function.Function : value; -} \ No newline at end of file +} diff --git a/src/AngleSharp.Wasm/Dom/WasmJsTag.cs b/src/AngleSharp.Wasm/Dom/WasmJsTag.cs index fc87701..cef43ee 100644 --- a/src/AngleSharp.Wasm/Dom/WasmJsTag.cs +++ b/src/AngleSharp.Wasm/Dom/WasmJsTag.cs @@ -7,6 +7,7 @@ namespace AngleSharp.Wasm.Dom; /// JavaScript-visible WebAssembly exception tag. /// [DomName("Tag")] +[DomExposed("WebAssembly")] public sealed class WasmJsTag { private readonly WasmJsTagType _type; @@ -54,6 +55,7 @@ private static bool IsSupportedParameter(string? parameter) => parameter is /// Describes a WebAssembly exception tag type. /// [DomName("TagType")] +[DomNoInterfaceObject] public sealed class WasmJsTagType { private readonly string[] _parameters; diff --git a/src/AngleSharp.Wasm/Dom/WasmJsTypes.cs b/src/AngleSharp.Wasm/Dom/WasmJsTypes.cs new file mode 100644 index 0000000..6307efa --- /dev/null +++ b/src/AngleSharp.Wasm/Dom/WasmJsTypes.cs @@ -0,0 +1,137 @@ +namespace AngleSharp.Wasm.Dom; + +using System.Numerics; +using AngleSharp.Attributes; + +/// +/// A function as scripts see one: an exported function of WebAssembly, which scripts call, or a +/// function of a script, which a module imports. It takes all arguments given (a missing one, +/// i.e. undefined, is ), and gives the result. +/// +/// The arguments. +/// The result; for undefined. +public delegate object? WasmJsCallable(object?[] arguments); + +/// +/// What an import object may hold for an import: a function, a number or BigInt (for an +/// immutable global), or a WebAssembly.Memory, Table or Global. +/// +public sealed class WasmJsImportValue +{ + private WasmJsImportValue(object? value) + { + Value = value; + } + + /// + /// Gets the value given. + /// + public object? Value { get; } + + /// + /// Gets the function given, if a function was given. + /// + public WasmJsCallable? Function => Value as WasmJsCallable; + + /// + /// Takes a function. + /// + public static implicit operator WasmJsImportValue(WasmJsCallable value) => new(value); + + /// + /// Takes a number. + /// + public static implicit operator WasmJsImportValue(double value) => new(value); + + /// + /// Takes a BigInt. + /// + public static implicit operator WasmJsImportValue(BigInteger value) => new(value); + + /// + /// Takes a memory. + /// + public static implicit operator WasmJsImportValue(WasmJsMemory value) => new(value); + + /// + /// Takes a table. + /// + public static implicit operator WasmJsImportValue(WasmJsTable value) => new(value); + + /// + /// Takes a global. + /// + public static implicit operator WasmJsImportValue(WasmJsGlobal value) => new(value); +} + +/// +/// The descriptor of a new WebAssembly.Memory. +/// +[DomName("MemoryDescriptor")] +[DomNoInterfaceObject] +public sealed class WasmJsMemoryDescriptor +{ + /// + /// Gets or sets the initial size in pages (64 KiB each). + /// + [DomName("initial")] + public double Initial { get; set; } + + /// + /// Gets or sets the maximum size in pages, if any. + /// + [DomName("maximum")] + public double? Maximum { get; set; } + + /// + /// Gets or sets if the memory is shared (not supported). + /// + [DomName("shared")] + public bool Shared { get; set; } +} + +/// +/// The descriptor of a new WebAssembly.Table. +/// +[DomName("TableDescriptor")] +[DomNoInterfaceObject] +public sealed class WasmJsTableDescriptor +{ + /// + /// Gets or sets the type of the elements: "anyfunc" (or "funcref"), or "externref". + /// + [DomName("element")] + public string? Element { get; set; } + + /// + /// Gets or sets the initial number of elements. + /// + [DomName("initial")] + public double Initial { get; set; } + + /// + /// Gets or sets the maximum number of elements, if any. + /// + [DomName("maximum")] + public double? Maximum { get; set; } +} + +/// +/// The descriptor of a new WebAssembly.Global. +/// +[DomName("GlobalDescriptor")] +[DomNoInterfaceObject] +public sealed class WasmJsGlobalDescriptor +{ + /// + /// Gets or sets the type: "i32", "i64", "f32", "f64", "anyfunc" (or "funcref"), or "externref". + /// + [DomName("value")] + public string? Value { get; set; } + + /// + /// Gets or sets if the global may be changed. + /// + [DomName("mutable")] + public bool Mutable { get; set; } +} diff --git a/src/AngleSharp.Wasm/Dom/WebAssembly.cs b/src/AngleSharp.Wasm/Dom/WebAssembly.cs index 32407ef..493f3f4 100644 --- a/src/AngleSharp.Wasm/Dom/WebAssembly.cs +++ b/src/AngleSharp.Wasm/Dom/WebAssembly.cs @@ -5,16 +5,19 @@ namespace AngleSharp.Wasm.Dom; using AngleSharp.Io; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Threading.Tasks; /// -/// Minimal JavaScript bridge object exposed as WebAssembly in compatible JS engines. +/// The WebAssembly namespace of the JavaScript API: compiling and instantiating modules, which +/// gives promises, and the interfaces of its objects (WebAssembly.Module, Instance, Memory, ...). /// [DomName("WebAssembly")] -[DomNoInterfaceObject] [DomExposed("Window")] public static class WebAssembly { @@ -62,7 +65,6 @@ public static bool Validate(this IWindow window, byte[] moduleBytes) /// The host. /// The response containing the module. /// The compiled module. - [DomName("compileStreaming")] public static WasmJsModule CompileStreaming(this IWindow window, IResponse source) => CompileStreaming(window, source, null); @@ -73,7 +75,6 @@ public static WasmJsModule CompileStreaming(this IWindow window, IResponse sourc /// The response containing the module. /// The compile options. /// The compiled module. - [DomName("compileStreaming")] public static WasmJsModule CompileStreaming(this IWindow window, IResponse source, WasmCompileOptions? options) => Compile(window, ReadStreamingSource(source), options); @@ -83,7 +84,6 @@ public static WasmJsModule CompileStreaming(this IWindow window, IResponse sourc /// The host. /// The response containing the module. /// The compiled module and instance. - [DomName("instantiateStreaming")] public static WasmJsInstantiationResult InstantiateStreaming(this IWindow window, IResponse source) => InstantiateStreaming(window, source, null); @@ -94,7 +94,6 @@ public static WasmJsInstantiationResult InstantiateStreaming(this IWindow window /// The response containing the module. /// The compile options. /// The compiled module and instance. - [DomName("instantiateStreaming")] public static WasmJsInstantiationResult InstantiateStreaming( this IWindow window, IResponse source, @@ -111,7 +110,6 @@ public static WasmJsInstantiationResult InstantiateStreaming( /// The host. /// The module bytes. /// The compiled module and instance. - [DomName("instantiate")] public static WasmJsInstantiationResult Instantiate(this IWindow window, byte[] moduleBytes) => Instantiate(window, moduleBytes, null); @@ -122,7 +120,6 @@ public static WasmJsInstantiationResult Instantiate(this IWindow window, byte[] /// The module bytes. /// The compile options. /// The compiled module and instance. - [DomName("instantiate")] public static WasmJsInstantiationResult Instantiate( this IWindow window, byte[] moduleBytes, @@ -139,7 +136,6 @@ public static WasmJsInstantiationResult Instantiate( /// The host. /// The module bytes. /// The module handle. - [DomName("compile")] public static WasmJsModule Compile(this IWindow window, byte[] moduleBytes) => Compile(window, moduleBytes, null); @@ -150,7 +146,6 @@ public static WasmJsModule Compile(this IWindow window, byte[] moduleBytes) /// The module bytes. /// The compile options. /// The module handle. - [DomName("compile")] public static WasmJsModule Compile(this IWindow window, byte[] moduleBytes, WasmCompileOptions? options) { if (moduleBytes is null) @@ -192,7 +187,6 @@ public static WasmJsModule Compile(this IWindow window, byte[] moduleBytes, Wasm /// The host. /// The compiled module handle. /// The instance handle. - [DomName("instantiate")] public static WasmJsInstance Instantiate(this IWindow window, WasmJsModule module) { if (module is null) @@ -212,6 +206,138 @@ public static WasmJsInstance Instantiate(this IWindow window, WasmJsModule modul } } + /// + /// Compiles a module (WebAssembly.compile), which rejects with a CompileError if the bytes + /// are no valid module. + /// + /// The host. + /// The bytes of the module. + /// The module. + [DomName("compile")] + public static Task CompileAsync(this IWindow window, byte[] bytes) => + Settle(() => Compile(window, bytes)); + + /// + /// Compiles and instantiates a module (WebAssembly.instantiate). + /// + /// The host. + /// The bytes of the module. + /// What the module imports, by module and name. + /// The module and its instance. + [DomName("instantiate")] + public static Task InstantiateAsync(this IWindow window, byte[] bytes, IDictionary>? importObject = null) => + Settle(() => + { + var module = Compile(window, bytes); + return new WasmJsInstantiationResult(module, InstantiateCore(window, module, importObject)); + }); + + /// + /// Instantiates a compiled module (WebAssembly.instantiate). + /// + /// The host. + /// The module. + /// What the module imports, by module and name. + /// The instance. + [DomName("instantiate")] + public static Task InstantiateAsync(this IWindow window, WasmJsModule module, IDictionary>? importObject = null) => + Settle(() => InstantiateCore(window, module, importObject)); + + /// + /// Compiles the module of a response (WebAssembly.compileStreaming), e.g. of fetch(). + /// + /// The host. + /// The response, or a promise of it. + /// The module. + [DomName("compileStreaming")] + public static async Task CompileStreamingAsync(this IWindow window, Task source) => + Compile(window, await ReadResponseAsync(await source)); + + /// + /// Compiles and instantiates the module of a response (WebAssembly.instantiateStreaming). + /// + /// The host. + /// The response, or a promise of it. + /// What the module imports, by module and name. + /// The module and its instance. + [DomName("instantiateStreaming")] + public static async Task InstantiateStreamingAsync(this IWindow window, Task source, IDictionary>? importObject = null) + { + var module = Compile(window, await ReadResponseAsync(await source)); + return new WasmJsInstantiationResult(module, InstantiateCore(window, module, importObject)); + } + + internal static WasmJsInstance InstantiateCore(IWindow window, WasmJsModule module, IDictionary>? importObject) + { + if (module is null) + { + throw new ArgumentNullException(nameof(module)); + } + + return GetRealm(window).Instantiate(module, importObject); + } + + internal static WasmJsRealm GetRealm(IWindow window) => WasmJsRealm.Of(window, GetOrCreateRuntime(window)); + + // The work is done right away, but a failure rejects the promise rather than throwing. + private static Task Settle(Func action) + { + try + { + return Task.FromResult(action()); + } + catch (Exception exception) + { + return Task.FromException(exception); + } + } + + // A Response of a fetch(), known by the names of its members (it is AngleSharp.Io's), or + // a response of AngleSharp. + [UnconditionalSuppressMessage("Trimming", "IL2070", Justification = "The members of a response are those of a DOM object, which the scripting keeps.")] + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "The members of a response are those of a DOM object, which the scripting keeps.")] + private static async Task ReadResponseAsync(object? source) + { + if (source is IResponse response) + { + return ReadStreamingSource(response); + } + + var type = source?.GetType() ?? throw new ArgumentException("The source has to be a Response."); + var ok = FindMember(type, "ok") as PropertyInfo; + var headers = (FindMember(type, "headers") as PropertyInfo)?.GetValue(source); + var get = headers is null ? null : FindMember(headers.GetType(), "get") as MethodInfo; + var arrayBuffer = FindMember(type, "arrayBuffer") as MethodInfo + ?? throw new ArgumentException("The source has to be a Response."); + + if (ok?.GetValue(source) is false) + { + throw new ArgumentException("The response of the module was not successful."); + } + + var contentType = get?.Invoke(headers, new object?[] { "Content-Type" }) as string; + + if (contentType is null || !String.Equals(contentType.Split(';', 2)[0].Trim(), "application/wasm", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("The response of the module has to be of the type application/wasm."); + } + + var reading = (Task)arrayBuffer.Invoke(source, Array.Empty())!; + await reading.ConfigureAwait(false); + return reading.GetType().GetProperty(nameof(Task.Result))?.GetValue(reading) switch + { + byte[] bytes => bytes, + ArraySegment segment => segment.ToArray(), + _ => throw new ArgumentException("The body of the response could not be read."), + }; + } + + [UnconditionalSuppressMessage("Trimming", "IL2070", Justification = "The members of a response are those of a DOM object, which the scripting keeps.")] + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "The members of a response are those of a DOM object, which the scripting keeps.")] + private static MemberInfo? FindMember(Type type, string name) => + type.GetMembers(BindingFlags.Public | BindingFlags.Instance) + .FirstOrDefault(member => member.GetCustomAttributes().Any(attribute => attribute.OfficialName == name)); + private static IWasmRuntime GetOrCreateRuntime(IWindow window) => runtimeCache.GetValue(window.Document?.Context!, static context => { diff --git a/src/AngleSharp.Wasm/HostMemory.cs b/src/AngleSharp.Wasm/HostMemory.cs new file mode 100644 index 0000000..a4e9c15 --- /dev/null +++ b/src/AngleSharp.Wasm/HostMemory.cs @@ -0,0 +1,225 @@ +namespace AngleSharp.Wasm; + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +using Wasmtime; + +/// +/// Gives the linear memories of WebAssembly (Wasmtime's host memory creator) arrays of .NET, +/// pinned, so that a script's ArrayBuffer of a memory (memory.buffer) is the memory itself, as +/// in browsers, instead of a copy. Growing a memory moves it to a new array, like a browser +/// gives a new ArrayBuffer for it then. +/// +internal static class HostMemory +{ + private const string Library = "wasmtime"; + + private static readonly Dictionary Memories = new(); + private static readonly NewMemoryCallback NewMemoryDelegate = NewMemory; + private static readonly GetMemoryCallback GetMemoryDelegate = GetMemory; + private static readonly GrowMemoryCallback GrowMemoryDelegate = GrowMemory; + private static readonly FinalizerCallback FinalizeDelegate = Finalize; + + /// + /// Configures Wasmtime to create its memories here: they may move as they grow (nothing is + /// reserved up front, there are no guard pages, so accesses are checked explicitly). + /// + /// True if the memories are arrays of .NET, false if Wasmtime keeps its own. + public static bool TryConfigure(Config config) + { + try + { + var property = typeof(Config).GetProperty("NativeHandle", BindingFlags.Instance | BindingFlags.NonPublic); + + if (property?.GetValue(config) is not SafeHandle handle) + { + return false; + } + + config.WithMemoryMayMove(true) + .WithMemoryGuardSize(0) + .WithMemoryReservationForGrowth(0) + .WithMemoryInitCopyOnWrite(false); + + var native = handle.DangerousGetHandle(); + wasmtime_config_memory_reservation_set(native, 0); + var creator = new MemoryCreatorStruct + { + Env = IntPtr.Zero, + NewMemory = Marshal.GetFunctionPointerForDelegate(NewMemoryDelegate), + Finalizer = IntPtr.Zero, + }; + wasmtime_config_host_memory_creator_set(native, ref creator); + return true; + } + catch (Exception exception) when (exception is EntryPointNotFoundException or DllNotFoundException or TargetInvocationException) + { + return false; + } + } + + /// + /// Gets the array holding the memory at the given address, if it is one of the arrays here + /// and just as long as the memory. + /// + public static byte[]? Find(IntPtr address, long length) + { + lock (Memories) + { + return Memories.TryGetValue(address, out var memory) && memory.Data.LongLength == length && memory.Size == length + ? memory.Data + : null; + } + } + + private static IntPtr NewMemory(IntPtr env, IntPtr type, UIntPtr minimum, UIntPtr maximum, UIntPtr reserved, UIntPtr guard, IntPtr result) + { + try + { + var size = checked((long)minimum.ToUInt64()); + var capacity = Math.Max(size, checked((long)reserved.ToUInt64())); + var memory = new LinearMemory(Allocate(capacity), size); + var handle = GCHandle.Alloc(memory); + Register(memory); + Marshal.StructureToPtr(new LinearMemoryStruct + { + Env = GCHandle.ToIntPtr(handle), + GetMemory = Marshal.GetFunctionPointerForDelegate(GetMemoryDelegate), + GrowMemory = Marshal.GetFunctionPointerForDelegate(GrowMemoryDelegate), + Finalizer = Marshal.GetFunctionPointerForDelegate(FinalizeDelegate), + }, result, false); + return IntPtr.Zero; + } + catch (Exception exception) + { + return wasmtime_error_new($"The memory could not be created: {exception.Message}"); + } + } + + private static IntPtr GetMemory(IntPtr env, out UIntPtr size, out UIntPtr capacity) + { + var memory = (LinearMemory)GCHandle.FromIntPtr(env).Target!; + size = (UIntPtr)(ulong)memory.Size; + capacity = (UIntPtr)(ulong)memory.Data.LongLength; + return memory.Address; + } + + private static IntPtr GrowMemory(IntPtr env, UIntPtr newSize) + { + try + { + var memory = (LinearMemory)GCHandle.FromIntPtr(env).Target!; + var size = checked((long)newSize.ToUInt64()); + + if (size > memory.Data.LongLength) + { + // a new array (zeroed) with what there is, as an array can't grow + var data = Allocate(size); + Buffer.BlockCopy(memory.Data, 0, data, 0, checked((int)memory.Size)); + + lock (Memories) + { + Memories.Remove(memory.Address); + memory.Data = data; + memory.Size = size; + Memories[memory.Address] = memory; + } + } + else + { + lock (Memories) + { + memory.Size = size; + } + } + + return IntPtr.Zero; + } + catch (Exception exception) + { + return wasmtime_error_new($"The memory could not grow: {exception.Message}"); + } + } + + private static void Finalize(IntPtr env) + { + var handle = GCHandle.FromIntPtr(env); + + if (handle.Target is LinearMemory memory) + { + lock (Memories) + { + Memories.Remove(memory.Address); + } + } + + handle.Free(); + } + + private static void Register(LinearMemory memory) + { + lock (Memories) + { + Memories[memory.Address] = memory; + } + } + + // pinned, so the address stays; at least a byte, as an empty array has no address + private static byte[] Allocate(long length) => + GC.AllocateArray(checked((int)Math.Max(1, length)), pinned: true); + + private sealed class LinearMemory + { + public LinearMemory(byte[] data, long size) + { + Data = data; + Size = size; + } + + public byte[] Data { get; set; } + + public long Size { get; set; } + + public IntPtr Address => Marshal.UnsafeAddrOfPinnedArrayElement(Data, 0); + } + + [StructLayout(LayoutKind.Sequential)] + private struct MemoryCreatorStruct + { + public IntPtr Env; + public IntPtr NewMemory; + public IntPtr Finalizer; + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinearMemoryStruct + { + public IntPtr Env; + public IntPtr GetMemory; + public IntPtr GrowMemory; + public IntPtr Finalizer; + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr NewMemoryCallback(IntPtr env, IntPtr type, UIntPtr minimum, UIntPtr maximum, UIntPtr reserved, UIntPtr guard, IntPtr result); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr GetMemoryCallback(IntPtr env, out UIntPtr size, out UIntPtr capacity); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr GrowMemoryCallback(IntPtr env, UIntPtr newSize); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void FinalizerCallback(IntPtr env); + + [DllImport(Library)] + private static extern void wasmtime_config_host_memory_creator_set(IntPtr config, ref MemoryCreatorStruct creator); + + [DllImport(Library)] + private static extern void wasmtime_config_memory_reservation_set(IntPtr config, ulong size); + + [DllImport(Library)] + private static extern IntPtr wasmtime_error_new([MarshalAs(UnmanagedType.LPUTF8Str)] string message); +} diff --git a/src/AngleSharp.Wasm/WasmtimeGlobal.cs b/src/AngleSharp.Wasm/WasmtimeGlobal.cs index 93069de..51cae32 100644 --- a/src/AngleSharp.Wasm/WasmtimeGlobal.cs +++ b/src/AngleSharp.Wasm/WasmtimeGlobal.cs @@ -9,6 +9,8 @@ internal sealed class WasmtimeGlobal : IWasmGlobal private readonly WasmtimeStoreContext _context; private readonly Global _global; + internal Global Native => _global; + internal WasmtimeGlobal(WasmtimeStoreContext context, Global global) { _context = context; diff --git a/src/AngleSharp.Wasm/WasmtimeInstance.cs b/src/AngleSharp.Wasm/WasmtimeInstance.cs index bb4e607..e1103e4 100644 --- a/src/AngleSharp.Wasm/WasmtimeInstance.cs +++ b/src/AngleSharp.Wasm/WasmtimeInstance.cs @@ -13,6 +13,10 @@ public sealed class WasmtimeInstance : IWasmInstance, IWasmFunctionProvider, IWa { private readonly WasmtimeStoreContext _context; private readonly Instance _instance; + + internal Instance Native => _instance; + + internal WasmtimeStoreContext Context => _context; private bool _disposed; internal WasmtimeInstance(WasmtimeStoreContext context, Instance instance) diff --git a/src/AngleSharp.Wasm/WasmtimeMemory.cs b/src/AngleSharp.Wasm/WasmtimeMemory.cs index 5d40882..f205a55 100644 --- a/src/AngleSharp.Wasm/WasmtimeMemory.cs +++ b/src/AngleSharp.Wasm/WasmtimeMemory.cs @@ -7,6 +7,8 @@ internal sealed class WasmtimeMemory : IWasmMemory { private readonly Memory _memory; + internal Memory Native => _memory; + public WasmtimeMemory(Memory memory) { _memory = memory; diff --git a/src/AngleSharp.Wasm/WasmtimeTable.cs b/src/AngleSharp.Wasm/WasmtimeTable.cs index abd76f1..f81661a 100644 --- a/src/AngleSharp.Wasm/WasmtimeTable.cs +++ b/src/AngleSharp.Wasm/WasmtimeTable.cs @@ -8,6 +8,8 @@ internal sealed class WasmtimeTable : IWasmTable private readonly WasmtimeStoreContext _context; private readonly Table _table; + internal Table Native => _table; + internal WasmtimeTable(WasmtimeStoreContext context, Table table) { _context = context; diff --git a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs index 8208025..9255ea4 100644 --- a/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs +++ b/src/AngleSharp.Wasm/WasmtimeWasmRuntime.cs @@ -46,7 +46,40 @@ public WasmtimeWasmRuntime(WasmRuntimeOptions options) _maximumMemorySize = options.MaximumMemorySize; _maximumTableElements = options.MaximumTableElements; _fuel = options.Fuel; - _engine = _fuel is null ? new Engine() : new Engine(new Config().WithFuelConsumption(true)); + var config = new Config(); + + if (_fuel is not null) + { + config.WithFuelConsumption(true); + } + + // memories in arrays of .NET, which is what scripts get as their buffer + HasHostMemory = HostMemory.TryConfigure(config); + _engine = new Engine(config); + } + + /// + /// Gets if the linear memories are arrays of .NET, so a script's memory.buffer is the memory. + /// + internal bool HasHostMemory { get; } + + internal Engine Engine => _engine; + + /// + /// Creates a store with the limits of the runtime, e.g. the one of the objects of the + /// WebAssembly API of a browsing context, which are shared by its instances. + /// + internal WasmtimeStoreContext CreateStoreContext() + { + ThrowIfDisposed(); + var store = new Store(_engine); + + if (_maximumMemorySize is not null || _maximumTableElements is not null) + { + store.SetLimits(_maximumMemorySize, _maximumTableElements, null, null, null); + } + + return new WasmtimeStoreContext(store, _fuel); } /// diff --git a/src/Directory.Build.props b/src/Directory.Build.props index eb555d0..b899209 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.1 + 1.2.0 enable latest true