Skip to content

[browser] detect SIMD and EH support #89387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 25, 2023
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
2 changes: 1 addition & 1 deletion eng/testing/performance/performance-setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ if [[ -n "$wasm_bundle_directory" ]]; then
wasm_bundle_directory_path=$payload_directory
mv $wasm_bundle_directory/* $wasm_bundle_directory_path
find $wasm_bundle_directory_path -type d
wasm_args="--expose_wasm"
wasm_args="--experimental-wasm-eh --expose_wasm"
if [ "$javascript_engine" == "v8" ]; then
# for es6 module support
wasm_args="$wasm_args --module"
Expand Down
4 changes: 2 additions & 2 deletions src/mono/sample/wasm/Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@
<Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="v8 --expose_wasm --module $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" />
</Target>
<Target Name="RunSampleWithNode" DependsOnTargets="BuildSampleInTree;_ComputeMainJSFileName">
<Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" />
<Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --experimental-wasm-eh --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args)" IgnoreExitCode="true" />
</Target>
<Target Name="DebugSampleWithNode" DependsOnTargets="BuildSampleInTree;_ComputeMainJSFileName">
<Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args) --inspect=9222" IgnoreExitCode="true" />
<Exec WorkingDirectory="bin/$(Configuration)/AppBundle" Command="node --experimental-wasm-eh --expose_wasm $(_WasmMainJSFileName) -- $(DOTNET_MONO_LOG_LEVEL) --run $(_SampleAssembly) $(Args) --inspect=9222" IgnoreExitCode="true" />
</Target>
<Target Name="CheckServe">
<Exec Command="dotnet tool install -g dotnet-serve" IgnoreExitCode="true" />
Expand Down
4 changes: 2 additions & 2 deletions src/mono/sample/wasm/wasm.mk
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ run-console:
cd bin/$(CONFIG)/AppBundle && $(V8_PATH) --stack-trace-limit=1000 --single-threaded --expose_wasm --module $(MAIN_JS) -- $(ARGS)

run-console-node:
cd bin/$(CONFIG)/AppBundle && node --stack-trace-limit=1000 --single-threaded --expose_wasm $(MAIN_JS) $(ARGS)
cd bin/$(CONFIG)/AppBundle && node --stack-trace-limit=1000 --single-threaded --experimental-wasm-eh --expose_wasm $(MAIN_JS) $(ARGS)

debug-console-node:
cd bin/$(CONFIG)/AppBundle && node --inspect=9222 --stack-trace-limit=1000 --single-threaded --expose_wasm $(MAIN_JS) $(ARGS)
cd bin/$(CONFIG)/AppBundle && node --inspect=9222 --stack-trace-limit=1000 --single-threaded --experimental-wasm-eh --expose_wasm $(MAIN_JS) $(ARGS)
4 changes: 4 additions & 0 deletions src/mono/wasm/build/WasmApp.Native.targets
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,10 @@
<EmscriptenEnvVars Include="EM_FROZEN_CACHE=True" />
<EmscriptenEnvVars Include="DISABLE_LEGACY_JS_INTEROP=1" Condition="'$(WasmEnableLegacyJsInterop)' == 'false'" />
<EmscriptenEnvVars Include="DISABLE_LEGACY_JS_INTEROP=0" Condition="'$(WasmEnableLegacyJsInterop)' != 'false'" />
<EmscriptenEnvVars Include="WASM_ENABLE_SIMD=1" Condition="'$(WasmEnableSIMD)' != 'false'" />
<EmscriptenEnvVars Include="WASM_ENABLE_SIMD=0" Condition="'$(WasmEnableSIMD)' == 'false'" />
<EmscriptenEnvVars Include="WASM_ENABLE_EH=1" Condition="'$(WasmEnableExceptionHandling)' != 'false'" />
<EmscriptenEnvVars Include="WASM_ENABLE_EH=0" Condition="'$(WasmEnableExceptionHandling)' == 'false'" />
<EmscriptenEnvVars Include="ENABLE_AOT_PROFILER=$([System.Convert]::ToInt32($(WasmProfilers.Contains('aot'))))" />
<EmscriptenEnvVars Include="ENABLE_BROWSER_PROFILER=$([System.Convert]::ToInt32($(WasmProfilers.Contains('browser'))))" />
</ItemGroup>
Expand Down
37 changes: 37 additions & 0 deletions src/mono/wasm/features.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Browser or JS engine features

dotnet for wasm can be compiled with various MSBuild flags which enable the use of browser features. If you need to target an older version of the browser, then you may need to disable some of the dotnet features or optimizations.

For full set of MSBuild properties [see top of](src\mono\wasm\build\WasmApp.targets)
For set of [browser WASM features see](https://webassembly.org/roadmap/)

# Multi-threading
Is enabled by `<WasmEnableThreads>true</WasmEnableThreads>`.
It requires HTTP headers similar to `Cross-Origin-Embedder-Policy:require-corp` and `Cross-Origin-Opener-Policy:same-origin`.
See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements

# SIMD - Single instruction, multiple data
Is performance optimization enabled by default. It requires recent version of browser.
You can disable it by `<WasmEnableSIMD>false</WasmEnableSIMD><WasmBuildNative>true</WasmBuildNative>`.
[See also](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md)

# EH - Exception handling
Is performance optimization enabled by default. It requires recent version of browser.
You can disable it by `<WasmEnableExceptionHandling>false</WasmEnableExceptionHandling><WasmBuildNative>true</WasmBuildNative>`.
[See also](https://github.com/WebAssembly/exception-handling/blob/master/proposals/exception-handling/Exceptions.md)

# BigInt
Is required if the application uses Int64 marshaling in JS interop.
[See also](https://github.com/WebAssembly/JS-BigInt-integration)

# fetch browser API
Is required if the application uses [HttpClient](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient)
NodeJS needs to install `node-fetch` and `node-abort-controller` npm packages.

# WebSocket browser API
Is required if the application uses [WebSocketClient](https://learn.microsoft.com/en-us/dotnet/api/system.net.websockets.clientwebsocket)
NodeJS needs to install `ws` npm package.

# Shell environments - NodeJS & V8
We pass most of the unit tests with NodeJS v 14 but it's not fully supported target platform. We would like to hear about community use-cases.
We also use v8 engine version 11 or higher to run some of the tests. The engine is lacking many APIs and features.
4 changes: 4 additions & 0 deletions src/mono/wasm/runtime/es6/dotnet.es6.lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

// because we can't pass custom define symbols to acorn optimizer, we use environment variables to pass other build options
const DISABLE_LEGACY_JS_INTEROP = process.env.DISABLE_LEGACY_JS_INTEROP === "1";
const WASM_ENABLE_SIMD = process.env.WASM_ENABLE_SIMD === "1";
const WASM_ENABLE_EH = process.env.WASM_ENABLE_EH === "1";
const ENABLE_BROWSER_PROFILER = process.env.ENABLE_BROWSER_PROFILER === "1";
const ENABLE_AOT_PROFILER = process.env.ENABLE_AOT_PROFILER === "1";

Expand Down Expand Up @@ -62,6 +64,8 @@ function setup(linkerSetup) {
const postset = `
DOTNET.setup({ `+
`linkerDisableLegacyJsInterop: ${DISABLE_LEGACY_JS_INTEROP ? "true" : "false"},` +
`linkerWasmEnableSIMD: ${WASM_ENABLE_SIMD ? "true" : "false"},` +
`linkerWasmEnableEH: ${WASM_ENABLE_EH ? "true" : "false"},` +
`linkerEnableAotProfiler: ${ENABLE_AOT_PROFILER ? "true" : "false"}, ` +
`linkerEnableBrowserProfiler: ${ENABLE_BROWSER_PROFILER ? "true" : "false"}` +
`});
Expand Down
4 changes: 4 additions & 0 deletions src/mono/wasm/runtime/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,17 @@ export let runtimeHelpers: RuntimeHelpers = null as any;
export let loaderHelpers: LoaderHelpers = null as any;
// this is when we link with workload tools. The consts:wasmEnableLegacyJsInterop is when we compile with rollup.
export let linkerDisableLegacyJsInterop = false;
export let linkerWasmEnableSIMD = true;
export let linkerWasmEnableEH = true;
export let linkerEnableAotProfiler = false;
export let linkerEnableBrowserProfiler = false;
export let _runtimeModuleLoaded = false; // please keep it in place also as rollup guard

export function passEmscriptenInternals(internals: EmscriptenInternals): void {
ENVIRONMENT_IS_PTHREAD = internals.isPThread;
linkerDisableLegacyJsInterop = internals.linkerDisableLegacyJsInterop;
linkerWasmEnableSIMD = internals.linkerWasmEnableSIMD;
linkerWasmEnableEH = internals.linkerWasmEnableEH;
linkerEnableAotProfiler = internals.linkerEnableAotProfiler;
linkerEnableBrowserProfiler = internals.linkerEnableBrowserProfiler;
runtimeHelpers.quit = internals.quit_;
Expand Down
4 changes: 2 additions & 2 deletions src/mono/wasm/runtime/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import type { VoidPtr } from "./types/emscripten";
function verifyEnvironment() {
if (typeof globalThis.fetch !== "function" || typeof globalThis.AbortController !== "function") {
const message = ENVIRONMENT_IS_NODE
? "Please install `node-fetch` and `node-abort-controller` npm packages to enable HTTP client support."
: "This browser doesn't support fetch API. Please use a modern browser.";
? "Please install `node-fetch` and `node-abort-controller` npm packages to enable HTTP client support. See also https://aka.ms/dotnet-wasm-features"
: "This browser doesn't support fetch API. Please use a modern browser. See also https://aka.ms/dotnet-wasm-features";
throw new Error(message);
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/mono/wasm/runtime/loader/globals.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

import { exceptions, simd } from "wasm-feature-detect";

import type { AssetEntryInternal, GlobalObjects, LoaderHelpers, RuntimeHelpers } from "../types/internal";
import type { MonoConfig, RuntimeAPI } from "../types";
import { assert_runtime_running, is_exited, is_runtime_running, mono_exit } from "./exit";
Expand Down Expand Up @@ -94,6 +96,10 @@ export function setLoaderGlobals(
hasDebuggingEnabled,
invokeLibraryInitializers,

// from wasm-feature-detect npm package
exceptions,
simd,

} as Partial<LoaderHelpers>);
}

Expand Down
22 changes: 14 additions & 8 deletions src/mono/wasm/runtime/loader/polyfills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,25 @@ const URLPolyfill = class URL {
};

export function verifyEnvironment() {
mono_assert(ENVIRONMENT_IS_SHELL || typeof globalThis.URL === "function", "This browser/engine doesn't support URL API. Please use a modern version.");
mono_assert(typeof globalThis.BigInt64Array === "function", "This browser/engine doesn't support BigInt64Array API. Please use a modern version.");
mono_assert(ENVIRONMENT_IS_SHELL || typeof globalThis.URL === "function", "This browser/engine doesn't support URL API. Please use a modern version. See also https://aka.ms/dotnet-wasm-features");
mono_assert(typeof globalThis.BigInt64Array === "function", "This browser/engine doesn't support BigInt64Array API. Please use a modern version. See also https://aka.ms/dotnet-wasm-features");
if (MonoWasmThreads) {
mono_assert(!ENVIRONMENT_IS_SHELL && !ENVIRONMENT_IS_NODE, "This build of dotnet is multi-threaded, it doesn't support shell environments like V8 or NodeJS.");
mono_assert(globalThis.SharedArrayBuffer !== undefined, "SharedArrayBuffer is not enabled on this page. Please use a modern browser and set Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy http headers. See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements");
mono_assert(typeof globalThis.EventTarget === "function", "This browser/engine doesn't support EventTarget API. Please use a modern version.");
mono_assert(!ENVIRONMENT_IS_SHELL && !ENVIRONMENT_IS_NODE, "This build of dotnet is multi-threaded, it doesn't support shell environments like V8 or NodeJS. See also https://aka.ms/dotnet-wasm-features");
mono_assert(globalThis.SharedArrayBuffer !== undefined, "SharedArrayBuffer is not enabled on this page. Please use a modern browser and set Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy http headers. See also https://aka.ms/dotnet-wasm-features");
mono_assert(typeof globalThis.EventTarget === "function", "This browser/engine doesn't support EventTarget API. Please use a modern version. See also https://aka.ms/dotnet-wasm-features");
}

// TODO detect other (WASM) features that are required for the runtime
// See https://github.com/dotnet/runtime/issues/84574
}

export async function detect_features_and_polyfill(module: DotnetModuleInternal): Promise<void> {
if (ENVIRONMENT_IS_NODE) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:
const process = await import(/* webpackIgnore: true */"process");
const minNodeVersion = 14;
if (process.versions.node.split(".")[0] < minNodeVersion) {
throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}', please use at least ${minNodeVersion}. See also https://aka.ms/dotnet-wasm-features`);
}
}

const scriptUrlQuery =/* webpackIgnore: true */import.meta.url;
const queryIndex = scriptUrlQuery.indexOf("?");
Expand Down
14 changes: 3 additions & 11 deletions src/mono/wasm/runtime/loader/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,14 +363,6 @@ export class HostBuilder implements DotnetHostBuilder {
if (ENVIRONMENT_IS_WEB && (module.config! as MonoConfigInternal).forwardConsoleLogsToWS && typeof globalThis.WebSocket != "undefined") {
setup_proxy_console("main", globalThis.console, globalThis.location.origin);
}
if (ENVIRONMENT_IS_NODE) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:
const process = await import(/* webpackIgnore: true */"process");
if (process.versions.node.split(".")[0] < 14) {
throw new Error(`NodeJS at '${process.execPath}' has too low version '${process.versions.node}'`);
}
}
mono_assert(module, "Null moduleConfig");
mono_assert(module.config, "Null moduleConfig.config");
await createEmscripten(module);
Expand Down Expand Up @@ -452,7 +444,7 @@ function importModules() {
];
}

function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) {
async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) {
const { initializeExports, initializeReplacements, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals } = es6Modules[0];
const { default: emscriptenFactory } = es6Modules[1];
setRuntimeGlobals(globalObjectsRoot);
Expand Down Expand Up @@ -491,7 +483,7 @@ async function createEmscriptenMain(): Promise<RuntimeAPI> {

// TODO call mono_download_assets(); here in parallel ?
const es6Modules = await Promise.all(promises);
initializeModules(es6Modules as any);
await initializeModules(es6Modules as any);

await runtimeHelpers.dotnetReady.promise;

Expand All @@ -507,7 +499,7 @@ async function createEmscriptenWorker(): Promise<EmscriptenModuleInternal> {

const promises = importModules();
const es6Modules = await Promise.all(promises);
initializeModules(es6Modules as any);
await initializeModules(es6Modules as any);

return module;
}
52 changes: 52 additions & 0 deletions src/mono/wasm/runtime/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion src/mono/wasm/runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,23 @@
"author": "Microsoft",
"license": "MIT",
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.1.0",
"@rollup/plugin-terser": "0.4.3",
"@rollup/plugin-typescript": "11.1.2",
"@rollup/plugin-virtual": "3.0.1",
"@typescript-eslint/eslint-plugin": "5.59.1",
"@typescript-eslint/parser": "5.59.1",
"magic-string": "0.30.1",
"eslint": "8.44.0",
"fast-glob": "3.3.0",
"git-commit-info": "2.0.2",
"magic-string": "0.30.1",
"rollup": "3.26.2",
"rollup-plugin-dts": "5.3.0",
"terser": "5.19.0",
"tslib": "2.6.0",
"typescript": "5.1.6"
},
"dependencies": {
"wasm-feature-detect": "1.5.1"
}
}
Loading