Skip to content
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

[browser] cleanup for emscripten main in a web worker #92280

Merged
merged 10 commits into from
Sep 22, 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
12 changes: 10 additions & 2 deletions src/mono/wasm/runtime/dotnet.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@ type MonoConfig = {
extensions?: {
[name: string]: any;
};
/**
* This is current working directory for the runtime on the virtual file system. Default is "/".
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
*/
virtualWorkingDirectory?: string;
/**
* This is the arguments to the Main() method of the program. Default is [].
*/
applicationArguments?: string[];
};
type ResourceExtensions = {
[extensionName: string]: ResourceList;
Expand Down Expand Up @@ -369,8 +377,8 @@ type DotnetModuleConfig = {
exports?: string[];
} & Partial<EmscriptenModule>;
type APIType = {
runMain: (mainAssemblyName: string, args: string[]) => Promise<number>;
runMainAndExit: (mainAssemblyName: string, args: string[]) => Promise<number>;
runMain: (mainAssemblyName: string, args?: string[]) => Promise<number>;
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
runMainAndExit: (mainAssemblyName: string, args?: string[]) => Promise<number>;
setEnvironmentVariable: (name: string, value: string) => void;
getAssemblyExports(assemblyName: string): Promise<any>;
setModuleImports(moduleName: string, moduleImports: any): void;
Expand Down
25 changes: 13 additions & 12 deletions src/mono/wasm/runtime/es6/dotnet.es6.lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ function setup(linkerSetup) {
const pthreadReplacements = {};
const dotnet_replacements = {
fetch: globalThis.fetch,
ENVIRONMENT_IS_WORKER,
require,
updateMemoryViews,
pthreadReplacements,
Expand All @@ -35,12 +36,23 @@ function setup(linkerSetup) {
const ENVIRONMENT_IS_PTHREAD = false;
#endif

ENVIRONMENT_IS_WORKER = dotnet_replacements.ENVIRONMENT_IS_WORKER;
Module.__dotnet_runtime.initializeReplacements(dotnet_replacements);
updateMemoryViews = dotnet_replacements.updateMemoryViews;
noExitRuntime = dotnet_replacements.noExitRuntime;
fetch = dotnet_replacements.fetch;
require = dotnet_replacements.require;
_scriptDir = __dirname = scriptDirectory = dotnet_replacements.scriptDirectory;
#if USE_PTHREADS
PThread.loadWasmModuleToWorker = pthreadReplacements.loadWasmModuleToWorker;
PThread.threadInitTLS = pthreadReplacements.threadInitTLS;
PThread.allocateUnusedWorker = pthreadReplacements.allocateUnusedWorker;
#endif
Module.__dotnet_runtime.passEmscriptenInternals({
isPThread: ENVIRONMENT_IS_PTHREAD,
quit_, ExitStatus,
...linkerSetup
});
Module.__dotnet_runtime.initializeReplacements(dotnet_replacements);

#if USE_PTHREADS
if (ENVIRONMENT_IS_PTHREAD) {
Expand All @@ -52,17 +64,6 @@ function setup(linkerSetup) {
#if USE_PTHREADS
}
#endif

updateMemoryViews = dotnet_replacements.updateMemoryViews;
noExitRuntime = dotnet_replacements.noExitRuntime;
fetch = dotnet_replacements.fetch;
require = dotnet_replacements.require;
_scriptDir = __dirname = scriptDirectory = dotnet_replacements.scriptDirectory;
#if USE_PTHREADS
PThread.loadWasmModuleToWorker = pthreadReplacements.loadWasmModuleToWorker;
PThread.threadInitTLS = pthreadReplacements.threadInitTLS;
PThread.allocateUnusedWorker = pthreadReplacements.allocateUnusedWorker;
#endif
}

const DotnetSupportLib = {
Expand Down
11 changes: 8 additions & 3 deletions src/mono/wasm/runtime/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

/* eslint-disable @typescript-eslint/triple-slash-reference */
/// <reference path="./types/v8.d.ts" />
/// <reference path="./types/sidecar.d.ts" />
/// <reference path="./types/node.d.ts" />

import gitHash from "consts:gitHash";
Expand All @@ -14,10 +15,14 @@ import type { GlobalObjects, EmscriptenInternals, RuntimeHelpers, LoaderHelpers,
export let Module: DotnetModuleInternal;
export let INTERNAL: any;

// keep in sync with src\mono\wasm\runtime\loader\globals.ts and src\mono\wasm\test-main.js
export const ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string";
export const ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
export const ENVIRONMENT_IS_WEB = typeof window == "object" || (ENVIRONMENT_IS_WORKER && !ENVIRONMENT_IS_NODE);
export const ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
export const ENVIRONMENT_IS_WEB_WORKER = typeof importScripts == "function";
export const ENVIRONMENT_IS_SIDECAR = ENVIRONMENT_IS_WEB_WORKER && typeof dotnetSidecar !== "undefined"; // sidecar is emscripten main running in a web worker
export const ENVIRONMENT_IS_WORKER = ENVIRONMENT_IS_WEB_WORKER && !ENVIRONMENT_IS_SIDECAR; // we redefine what ENVIRONMENT_IS_WORKER, we replace it in emscripten internals, so that sidecar works
export const ENVIRONMENT_IS_WEB = typeof window == "object" || (ENVIRONMENT_IS_WEB_WORKER && !ENVIRONMENT_IS_NODE);
export const ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE;

// these are imported and re-exported from emscripten internals
export let ENVIRONMENT_IS_PTHREAD: boolean;
export let exportedRuntimeAPI: RuntimeAPI = null as any;
Expand Down
2 changes: 1 addition & 1 deletion src/mono/wasm/runtime/loader/assetsCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ async function getCacheToUseIfEnabled(config: MonoConfig): Promise<Cache | null>

// cache integrity is compromised if the first request has been served over http (except localhost)
// in this case, we want to disable caching and integrity validation
if (window.isSecureContext === false) {
if (globalThis.isSecureContext === false) {
return null;
}

Expand Down
2 changes: 2 additions & 0 deletions src/mono/wasm/runtime/loader/exit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ function logOnExit(exit_code: number, reason: any) {
// tell xharness WasmTestMessagesProcessor we are done.
// note this sends last few bytes into the same WS
mono_log_info_no_prefix("WASM EXIT " + exit_code);
consoleWebSocket.onclose = null;
consoleWebSocket.close(1000, "exit_code:" + exit_code + ": " + reason);
}
else {
globalThis.setTimeout(stop_when_ws_buffer_empty, 100);
Expand Down
29 changes: 22 additions & 7 deletions src/mono/wasm/runtime/loader/globals.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,51 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

/* eslint-disable @typescript-eslint/triple-slash-reference */
/// <reference path="../types/sidecar.d.ts" />

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

import gitHash from "consts:gitHash";

import type { AssetEntryInternal, GlobalObjects, LoaderHelpers, RuntimeHelpers } from "../types/internal";
import type { AssetEntryInternal, DotnetModuleInternal, GlobalObjects, LoaderHelpers, MonoConfigInternal, RuntimeHelpers } from "../types/internal";
import type { MonoConfig, RuntimeAPI } from "../types";
import { assert_runtime_running, is_exited, is_runtime_running, mono_exit } from "./exit";
import { assertIsControllablePromise, createPromiseController, getPromiseController } from "./promise-controller";
import { mono_download_assets, resolve_single_asset_path, retrieve_asset_download } from "./assets";
import { setup_proxy_console } from "./logging";
import { invokeLibraryInitializers } from "./libraryInitializers";
import { hasDebuggingEnabled } from "./config";
import { deep_merge_config, hasDebuggingEnabled } from "./config";
import { logDownloadStatsToConsole, purgeUnusedCacheEntriesAsync } from "./assetsCache";

// if we are the first script loaded in the web worker, we are expected to become the sidecar
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved
if (typeof importScripts === "function" && !globalThis.onmessage) {
(globalThis as any).dotnetSidecar = true;
}

// keep in sync with src\mono\wasm\runtime\globals.ts and src\mono\wasm\test-main.js
export const ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string";
export const ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
export const ENVIRONMENT_IS_WEB = typeof window == "object" || (ENVIRONMENT_IS_WORKER && !ENVIRONMENT_IS_NODE);
export const ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
export const ENVIRONMENT_IS_WEB_WORKER = typeof importScripts == "function";
export const ENVIRONMENT_IS_SIDECAR = ENVIRONMENT_IS_WEB_WORKER && typeof dotnetSidecar !== "undefined"; // sidecar is emscripten main running in a web worker
export const ENVIRONMENT_IS_WORKER = ENVIRONMENT_IS_WEB_WORKER && !ENVIRONMENT_IS_SIDECAR; // we redefine what ENVIRONMENT_IS_WORKER, we replace it in emscripten internals, so that sidecar works
export const ENVIRONMENT_IS_WEB = typeof window == "object" || (ENVIRONMENT_IS_WEB_WORKER && !ENVIRONMENT_IS_NODE);
export const ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE;

export let runtimeHelpers: RuntimeHelpers = {} as any;
export let loaderHelpers: LoaderHelpers = {} as any;
export let exportedRuntimeAPI: RuntimeAPI = {} as any;
export let INTERNAL: any = {};
export let _loaderModuleLoaded = false; // please keep it in place also as rollup guard

export const monoConfig: MonoConfigInternal = {} as any;
export const emscriptenModule: DotnetModuleInternal = {
config: monoConfig
} as any;
export const globalObjectsRoot: GlobalObjects = {
mono: {},
binding: {},
internal: INTERNAL,
module: {},
module: emscriptenModule,
loaderHelpers,
runtimeHelpers,
api: exportedRuntimeAPI,
Expand All @@ -56,7 +71,7 @@ export function setLoaderGlobals(

Object.assign(globalObjects.module, {
disableDotnet6Compatibility: true,
config: { environmentVariables: {} }
config: deep_merge_config(monoConfig, { environmentVariables: {} }),
});
Object.assign(runtimeHelpers, {
mono_wasm_bindings_is_ready: false,
Expand Down
3 changes: 2 additions & 1 deletion src/mono/wasm/runtime/loader/icu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export function init_globalization() {

export function getIcuResourceName(config: MonoConfig): string | null {
if (config.resources?.icu && config.globalizationMode != GlobalizationMode.Invariant) {
const culture = config.applicationCulture || (ENVIRONMENT_IS_WEB ? (navigator.languages && navigator.languages[0]) : Intl.DateTimeFormat().resolvedOptions().locale);
// TODO: when starting on sidecar, we should pass default culture from UI thread
const culture = config.applicationCulture || (ENVIRONMENT_IS_WEB ? (globalThis.navigator && globalThis.navigator.languages && globalThis.navigator.languages[0]) : Intl.DateTimeFormat().resolvedOptions().locale);
pavelsavara marked this conversation as resolved.
Show resolved Hide resolved

const icuFiles = Object.keys(config.resources.icu);

Expand Down
Loading