diff --git a/src/native/corehost/browserhost/host/cross-linked.ts b/src/native/corehost/browserhost/host/cross-linked.ts deleted file mode 100644 index 81235d123da0ff..00000000000000 --- a/src/native/corehost/browserhost/host/cross-linked.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -import { } from "../../../libs/Common/JavaScript/cross-linked"; -import type { VoidPtr } from "./types"; - -declare global { - export const BROWSER_HOST: any; - export function _BrowserHost_InitializeCoreCLR(): number; - export function _BrowserHost_ExecuteAssembly(mainAssemblyNamePtr: number, argsLength: number, argsPtr: number): number; - export function _wasm_load_icu_data(dataPtr: VoidPtr): number; -} diff --git a/src/native/corehost/browserhost/host/host.ts b/src/native/corehost/browserhost/host/host.ts index 32c4cfd2447c97..88a2664e4c94a6 100644 --- a/src/native/corehost/browserhost/host/host.ts +++ b/src/native/corehost/browserhost/host/host.ts @@ -2,48 +2,48 @@ // The .NET Foundation licenses this file to you under the MIT license. import type { CharPtr, VfsAsset, VoidPtr, VoidPtrPtr } from "./types"; -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../../libs/Common/JavaScript/ems-ambient"; const loadedAssemblies: Map = new Map(); export function registerDllBytes(bytes: Uint8Array, asset: { name: string, virtualPath: string }) { - const sp = Module.stackSave(); + const sp = _ems_.Module.stackSave(); try { const sizeOfPtr = 4; - const ptrPtr = Module.stackAlloc(sizeOfPtr); - if (Module._posix_memalign(ptrPtr as any, 16, bytes.length)) { + const ptrPtr = _ems_.Module.stackAlloc(sizeOfPtr); + if (_ems_.Module._posix_memalign(ptrPtr as any, 16, bytes.length)) { throw new Error("posix_memalign failed"); } - const ptr = Module.HEAPU32[ptrPtr as any >>> 2]; - Module.HEAPU8.set(bytes, ptr >>> 0); + const ptr = _ems_.Module.HEAPU32[ptrPtr as any >>> 2]; + _ems_.Module.HEAPU8.set(bytes, ptr >>> 0); loadedAssemblies.set(asset.virtualPath, { ptr, length: bytes.length }); if (!asset.virtualPath.startsWith("/")) { loadedAssemblies.set("/" + asset.virtualPath, { ptr, length: bytes.length }); } } finally { - Module.stackRestore(sp); + _ems_.Module.stackRestore(sp); } } export function loadIcuData(bytes: Uint8Array) { - const sp = Module.stackSave(); + const sp = _ems_.Module.stackSave(); try { const sizeOfPtr = 4; - const ptrPtr = Module.stackAlloc(sizeOfPtr); - if (Module._posix_memalign(ptrPtr as any, 16, bytes.length)) { + const ptrPtr = _ems_.Module.stackAlloc(sizeOfPtr); + if (_ems_.Module._posix_memalign(ptrPtr as any, 16, bytes.length)) { throw new Error("posix_memalign failed for ICU data"); } - const ptr = Module.HEAPU32[ptrPtr as any >>> 2]; - Module.HEAPU8.set(bytes, ptr >>> 0); + const ptr = _ems_.Module.HEAPU32[ptrPtr as any >>> 2]; + _ems_.Module.HEAPU8.set(bytes, ptr >>> 0); - const result = _wasm_load_icu_data(ptr as unknown as VoidPtr); + const result = _ems_._wasm_load_icu_data(ptr as unknown as VoidPtr); if (!result) { throw new Error("Failed to initialize ICU data"); } } finally { - Module.stackRestore(sp); + _ems_.Module.stackRestore(sp); } } @@ -68,89 +68,89 @@ export function installVfsFile(bytes: Uint8Array, asset: VfsAsset) { throw new Error("Cannot create files under /managed virtual directory as it is reserved for NodeFS mounting"); } - dotnetLogger.debug(`Creating directory '${parentDirectory}'`); + _ems_.dotnetLogger.debug(`Creating directory '${parentDirectory}'`); - Module.FS_createPath( + _ems_.Module.FS_createPath( "/", parentDirectory, true, true // fixme: should canWrite be false? ); } else { parentDirectory = "/"; } - dotnetLogger.debug(`Creating file '${fileName}' in directory '${parentDirectory}'`); + _ems_.dotnetLogger.debug(`Creating file '${fileName}' in directory '${parentDirectory}'`); - Module.FS_createDataFile( + _ems_.Module.FS_createDataFile( parentDirectory, fileName, bytes, true /* canRead */, true /* canWrite */, true /* canOwn */ ); } export function initializeCoreCLR(): number { - return _BrowserHost_InitializeCoreCLR(); + return _ems_._BrowserHost_InitializeCoreCLR(); } // bool BrowserHost_ExternalAssemblyProbe(const char* pathPtr, /*out*/ void **outDataStartPtr, /*out*/ int64_t* outSize); export function BrowserHost_ExternalAssemblyProbe(pathPtr: CharPtr, outDataStartPtr: VoidPtrPtr, outSize: VoidPtr) { - const path = Module.UTF8ToString(pathPtr); + const path = _ems_.Module.UTF8ToString(pathPtr); const assembly = loadedAssemblies.get(path); if (assembly) { - Module.HEAPU32[outDataStartPtr as any >>> 2] = assembly.ptr; + _ems_.Module.HEAPU32[outDataStartPtr as any >>> 2] = assembly.ptr; // int64_t target - Module.HEAPU32[outSize as any >>> 2] = assembly.length; - Module.HEAPU32[((outSize as any) + 4) >>> 2] = 0; + _ems_.Module.HEAPU32[outSize as any >>> 2] = assembly.length; + _ems_.Module.HEAPU32[((outSize as any) + 4) >>> 2] = 0; return true; } - dotnetLogger.debug(`Assembly not found: '${path}'`); - Module.HEAPU32[outDataStartPtr as any >>> 2] = 0; - Module.HEAPU32[outSize as any >>> 2] = 0; - Module.HEAPU32[((outSize as any) + 4) >>> 2] = 0; + _ems_.dotnetLogger.debug(`Assembly not found: '${path}'`); + _ems_.Module.HEAPU32[outDataStartPtr as any >>> 2] = 0; + _ems_.Module.HEAPU32[outSize as any >>> 2] = 0; + _ems_.Module.HEAPU32[((outSize as any) + 4) >>> 2] = 0; return false; } export async function runMain(mainAssemblyName?: string, args?: string[]): Promise { try { - const config = dotnetApi.getConfig(); + const config = _ems_.dotnetApi.getConfig(); if (!mainAssemblyName) { mainAssemblyName = config.mainAssemblyName!; } if (!mainAssemblyName.endsWith(".dll")) { mainAssemblyName += ".dll"; } - const mainAssemblyNamePtr = dotnetBrowserUtilsExports.stringToUTF8Ptr(mainAssemblyName) as any; + const mainAssemblyNamePtr = _ems_.dotnetBrowserUtilsExports.stringToUTF8Ptr(mainAssemblyName) as any; args ??= []; - const sp = Module.stackSave(); - const argsvPtr: number = Module.stackAlloc((args.length + 1) * 4) as any; + const sp = _ems_.Module.stackSave(); + const argsvPtr: number = _ems_.Module.stackAlloc((args.length + 1) * 4) as any; const ptrs: VoidPtr[] = []; try { for (let i = 0; i < args.length; i++) { - const ptr = dotnetBrowserUtilsExports.stringToUTF8Ptr(args[i]) as any; + const ptr = _ems_.dotnetBrowserUtilsExports.stringToUTF8Ptr(args[i]) as any; ptrs.push(ptr); - Module.HEAPU32[(argsvPtr >>> 2) + i] = ptr; + _ems_.Module.HEAPU32[(argsvPtr >>> 2) + i] = ptr; } - const res = _BrowserHost_ExecuteAssembly(mainAssemblyNamePtr, args.length, argsvPtr); + const res = _ems_._BrowserHost_ExecuteAssembly(mainAssemblyNamePtr, args.length, argsvPtr); for (const ptr of ptrs) { - Module._free(ptr); + _ems_.Module._free(ptr); } if (res != 0) { const reason = new Error("Failed to execute assembly"); - dotnetApi.exit(res, reason); + _ems_.dotnetApi.exit(res, reason); throw reason; } - return dotnetLoaderExports.getRunMainPromise(); + return _ems_.dotnetLoaderExports.getRunMainPromise(); } finally { - Module.stackRestore(sp); + _ems_.Module.stackRestore(sp); } } catch (error: any) { // if the error is an ExitStatus, use its status code if (error && typeof error.status === "number") { return error.status; } - dotnetApi.exit(1, error); + _ems_.dotnetApi.exit(1, error); throw error; } } @@ -158,11 +158,11 @@ export async function runMain(mainAssemblyName?: string, args?: string[]): Promi export async function runMainAndExit(mainAssemblyName?: string, args?: string[]): Promise { const res = await runMain(mainAssemblyName, args); try { - dotnetApi.exit(0, null); + _ems_.dotnetApi.exit(0, null); } catch (error: any) { // do not propagate ExitStatus exception if (error.status === undefined) { - dotnetApi.exit(1, error); + _ems_.dotnetApi.exit(1, error); throw error; } } diff --git a/src/native/corehost/browserhost/host/index.ts b/src/native/corehost/browserhost/host/index.ts index 3eadb4cb94c3c6..a957f8b37acd32 100644 --- a/src/native/corehost/browserhost/host/index.ts +++ b/src/native/corehost/browserhost/host/index.ts @@ -3,7 +3,7 @@ import type { InternalExchange, BrowserHostExports, RuntimeAPI, BrowserHostExportsTable } from "./types"; import { InternalExchangeIndex } from "./types"; -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../../libs/Common/JavaScript/ems-ambient"; import GitHash from "consts:gitHash"; @@ -28,7 +28,7 @@ export function dotnetInitializeModule(internals: InternalExchange): void { loadIcuData, initializeCoreCLR, }); - dotnetUpdateInternals(internals, dotnetUpdateInternalsSubscriber); + _ems_.dotnetUpdateInternals(internals, _ems_.dotnetUpdateInternalsSubscriber); function browserHostExportsToTable(map: BrowserHostExports): BrowserHostExportsTable { // keep in sync with browserHostExportsFromTable() return [ diff --git a/src/native/corehost/browserhost/libBrowserHost.footer.js b/src/native/corehost/browserhost/libBrowserHost.footer.js index 02f755ede4ecfa..b37e57dcea93da 100644 --- a/src/native/corehost/browserhost/libBrowserHost.footer.js +++ b/src/native/corehost/browserhost/libBrowserHost.footer.js @@ -76,10 +76,6 @@ if (name === "dotnetInitializeModule") continue; lib[name] = () => "dummy"; assignExportsBuilder += `_${String(name)} = exports.${String(name)};\n`; - const fn = exports[name]; - if (fn.__deps) { - lib[name + "__deps"] = fn.__deps; - } } lib.$BROWSER_HOST.assignExports = new Function("exports", assignExportsBuilder); diff --git a/src/native/corehost/browserhost/loader/assets.ts b/src/native/corehost/browserhost/loader/assets.ts index 779555ec24bb22..0d2d36dee0c011 100644 --- a/src/native/corehost/browserhost/loader/assets.ts +++ b/src/native/corehost/browserhost/loader/assets.ts @@ -1,16 +1,21 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { JsModuleExports, JsAsset, AssemblyAsset, WasmAsset, IcuAsset, EmscriptenModuleInternal, InstantiateWasmSuccessCallback, WebAssemblyBootResourceType, AssetEntryInternal } from "./types"; +import type { JsModuleExports, JsAsset, AssemblyAsset, WasmAsset, IcuAsset, EmscriptenModuleInternal, InstantiateWasmSuccessCallback, WebAssemblyBootResourceType, AssetEntryInternal, LoadBootResourceCallback } from "./types"; -import { dotnetAssert, dotnetGetInternals, dotnetBrowserHostExports, dotnetUpdateInternals } from "./cross-module"; +import { dotnetAssert, dotnetGetInternals, dotnetBrowserHostExports, dotnetUpdateInternals, dotnetLogger } from "./cross-module"; import { ENVIRONMENT_IS_WEB } from "./per-module"; import { createPromiseCompletionSource } from "./promise-completion-source"; import { locateFile, makeURLAbsoluteWithApplicationBase } from "./bootstrap"; import { fetchLike } from "./polyfills"; -import { loadBootResourceCallback } from "./host-builder"; import { loaderConfig } from "./config"; +let loadBootResourceCallback: LoadBootResourceCallback | undefined = undefined; + +export function setLoadBootResourceCallback(callback: LoadBootResourceCallback | undefined): void { + loadBootResourceCallback = callback; +} + export let wasmBinaryPromise: Promise | undefined = undefined; export const nativeModulePromiseController = createPromiseCompletionSource(() => { dotnetUpdateInternals(dotnetGetInternals()); diff --git a/src/native/corehost/browserhost/loader/dotnet.d.ts b/src/native/corehost/browserhost/loader/dotnet.d.ts index de8cd3331a3539..592a9ca70240e0 100644 --- a/src/native/corehost/browserhost/loader/dotnet.d.ts +++ b/src/native/corehost/browserhost/loader/dotnet.d.ts @@ -1,6 +1,6 @@ //! Licensed to the .NET Foundation under one or more agreements. //! The .NET Foundation licenses this file to you under the MIT license. -//! This is generated file, see src/native/libs/Browser/rollup.config.defines.js +//! This is generated file, see src/native/rollup.config.js //! This is not considered public API with backward compatibility guarantees. diff --git a/src/native/corehost/browserhost/loader/host-builder.ts b/src/native/corehost/browserhost/loader/host-builder.ts index a77cc59ab82504..062de202cda9fe 100644 --- a/src/native/corehost/browserhost/loader/host-builder.ts +++ b/src/native/corehost/browserhost/loader/host-builder.ts @@ -7,9 +7,9 @@ import { Module, dotnetApi } from "./cross-module"; import { getLoaderConfig, mergeLoaderConfig, validateLoaderConfig } from "./config"; import { createRuntime } from "./run"; import { exit } from "./exit"; +import { setLoadBootResourceCallback } from "./assets"; let applicationArguments: string[] | undefined = []; -export let loadBootResourceCallback: LoadBootResourceCallback | undefined = undefined; /* eslint-disable @typescript-eslint/no-unused-vars */ export class HostBuilder implements DotnetHostBuilder { @@ -89,7 +89,7 @@ export class HostBuilder implements DotnetHostBuilder { return this; } withResourceLoader(loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { - loadBootResourceCallback = loadBootResource; + setLoadBootResourceCallback(loadBootResource); return this; } diff --git a/src/native/libs/Common/JavaScript/CMakeLists.txt b/src/native/libs/Common/JavaScript/CMakeLists.txt index 91ab7c508d7dc1..b44a8d4f1700e2 100644 --- a/src/native/libs/Common/JavaScript/CMakeLists.txt +++ b/src/native/libs/Common/JavaScript/CMakeLists.txt @@ -17,7 +17,6 @@ set(ROLLUP_TS_SOURCES "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/libSystem.Native.Browser.footer.js" "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/libSystem.Runtime.InteropServices.JavaScript.Native.footer.js" - "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/host/cross-linked.ts" "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/host/host.ts" "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/host/index.ts" "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/host/types.ts" @@ -39,7 +38,7 @@ set(ROLLUP_TS_SOURCES "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/loader/run.ts" "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/loader/types.ts" "${CLR_SRC_NATIVE_DIR}/corehost/browserhost/types.ts" - "${CLR_SRC_NATIVE_DIR}/libs/Common/JavaScript/cross-linked/index.ts" + "${CLR_SRC_NATIVE_DIR}/libs/Common/JavaScript/ems-ambient/index.ts" "${CLR_SRC_NATIVE_DIR}/libs/Common/JavaScript/cross-module/index.ts" "${CLR_SRC_NATIVE_DIR}/libs/Common/JavaScript/per-module/index.ts" "${CLR_SRC_NATIVE_DIR}/libs/Common/JavaScript/types/consts.d.ts" @@ -59,7 +58,6 @@ set(ROLLUP_TS_SOURCES "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/diagnostics/per-module.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/diagnostics/symbolicate.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/diagnostics/types.ts" - "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/native/cross-linked.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/native/crypto.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/native/globalization-locale.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/native/index.ts" @@ -69,7 +67,6 @@ set(ROLLUP_TS_SOURCES "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/types.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/cdac.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/cross-module.ts" - "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/cross-linked.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/host.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/index.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Native.Browser/utils/memory.ts" @@ -84,7 +81,6 @@ set(ROLLUP_TS_SOURCES "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/interop/per-module.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/interop/types.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/interop/weak-ref.ts" - "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/native/cross-linked.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/native/index.ts" "${CLR_SRC_NATIVE_DIR}/libs/System.Runtime.InteropServices.JavaScript.Native/types.ts" ) diff --git a/src/native/libs/Common/JavaScript/cross-linked/index.ts b/src/native/libs/Common/JavaScript/cross-linked/index.ts deleted file mode 100644 index 2700568e6bada0..00000000000000 --- a/src/native/libs/Common/JavaScript/cross-linked/index.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -import type { AssertType, EmscriptenModuleInternal, LoggerType, LoaderExports, InternalExchange, InternalExchangeSubscriber, RuntimeAPI, BrowserUtilsExports, NativePointer, CharPtr, VoidPtr, RuntimeExports } from "../types"; - -// we want to use the cross-module symbols defined in closure of dotnet.native.js -// which are installed there by libSystem.Native.Browser.Utils.footer.js -// see also `reserved` in `rollup.config.defines.js` -declare global { - export const dotnetApi: RuntimeAPI; - export const dotnetAssert: AssertType; - export const dotnetLogger: LoggerType; - export const dotnetLoaderExports: LoaderExports; - export const dotnetRuntimeExports: RuntimeExports; - export const dotnetBrowserUtilsExports: BrowserUtilsExports; - export const dotnetUpdateInternals: (internals?: Partial, subscriber?: InternalExchangeSubscriber) => void; - export const dotnetUpdateInternalsSubscriber: (internals: InternalExchange) => void; - - // ambient in the emscripten closure - export const Module: EmscriptenModuleInternal; - export const ENVIRONMENT_IS_NODE: boolean; - export const ENVIRONMENT_IS_SHELL: boolean; - export const ENVIRONMENT_IS_WEB: boolean; - export const ENVIRONMENT_IS_WORKER: boolean; - export const ENVIRONMENT_IS_SIDECAR: boolean; - - export const VoidPtrNull: VoidPtr; - export const CharPtrNull: CharPtr; - export const NativePointerNull: NativePointer; - - export function safeSetTimeout(func: Function, timeout: number): number; - export function maybeExit(): void; - export function exitJS(status: number, implicit?: boolean | number): void; - -} diff --git a/src/native/libs/Common/JavaScript/cross-module/index.ts b/src/native/libs/Common/JavaScript/cross-module/index.ts index 3c874892112764..f89b3a73f12793 100644 --- a/src/native/libs/Common/JavaScript/cross-module/index.ts +++ b/src/native/libs/Common/JavaScript/cross-module/index.ts @@ -19,10 +19,10 @@ * - each JS module to use exported symbols in ergonomic way */ -import type { DotnetModuleInternal, InternalExchange, RuntimeExports, LoaderExports, RuntimeAPI, LoggerType, AssertType, BrowserHostExports, InteropJavaScriptExports, LoaderExportsTable, RuntimeExportsTable, BrowserHostExportsTable, InteropJavaScriptExportsTable, NativeBrowserExports, NativeBrowserExportsTable, InternalExchangeSubscriber, BrowserUtilsExports, BrowserUtilsExportsTable, VoidPtr, CharPtr, NativePointer, DiagnosticsExports, DiagnosticsExportsTable } from "../types"; +import type { DotnetModuleInternal, InternalExchange, RuntimeExports, LoaderExports, RuntimeAPI, LoggerType, AssertType, BrowserHostExports, InteropJavaScriptExports, LoaderExportsTable, RuntimeExportsTable, BrowserHostExportsTable, InteropJavaScriptExportsTable, NativeBrowserExports, NativeBrowserExportsTable, InternalExchangeSubscriber, BrowserUtilsExports, BrowserUtilsExportsTable, DiagnosticsExports, DiagnosticsExportsTable } from "../types"; import { InternalExchangeIndex } from "../types"; -let dotnetInternals: InternalExchange; +export let dotnetInternals: InternalExchange; export let Module: DotnetModuleInternal; export let dotnetApi: RuntimeAPI; export const dotnetLogger: LoggerType = {} as LoggerType; @@ -35,10 +35,6 @@ export const dotnetNativeBrowserExports: NativeBrowserExports = {} as any; export const dotnetBrowserUtilsExports: BrowserUtilsExports = {} as any; export const dotnetDiagnosticsExports: DiagnosticsExports = {} as any; -export const VoidPtrNull: VoidPtr = 0; -export const CharPtrNull: CharPtr = 0; -export const NativePointerNull: NativePointer = 0; - export function dotnetGetInternals(): InternalExchange { return dotnetInternals; } diff --git a/src/native/libs/Common/JavaScript/ems-ambient/index.ts b/src/native/libs/Common/JavaScript/ems-ambient/index.ts new file mode 100644 index 00000000000000..66dc3d452c610c --- /dev/null +++ b/src/native/libs/Common/JavaScript/ems-ambient/index.ts @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +import type { AssertType, EmscriptenModuleInternal, LoggerType, LoaderExports, InternalExchange, InternalExchangeSubscriber, RuntimeAPI, BrowserUtilsExports, VoidPtr, RuntimeExports } from "../types"; + +// we want to use the cross-module symbols defined in closure of dotnet.native.js +// which are installed there by libSystem.Native.Browser.Utils.footer.js +// see also `reserved` in `rollup.config.defines.js` + +type emAmbientSymbolsType = { + dotnetApi: RuntimeAPI; + dotnetAssert: AssertType; + dotnetLogger: LoggerType; + dotnetLoaderExports: LoaderExports; + dotnetRuntimeExports: RuntimeExports; + dotnetBrowserUtilsExports: BrowserUtilsExports; + + dotnetUpdateInternals: (internals?: Partial, subscriber?: InternalExchangeSubscriber) => void; + dotnetUpdateInternalsSubscriber: (internals: InternalExchange) => void; + + _GetDotNetRuntimeContractDescriptor: () => void; + _SystemJS_ExecuteTimerCallback: () => void; + _SystemJS_ExecuteBackgroundJobCallback: () => void; + _BrowserHost_InitializeCoreCLR: () => number; + _BrowserHost_ExecuteAssembly: (mainAssemblyNamePtr: number, argsLength: number, argsPtr: number) => number; + _wasm_load_icu_data: (dataPtr: VoidPtr) => number; + + DOTNET: any; + DOTNET_INTEROP: any; + BROWSER_HOST: any; + + Module: EmscriptenModuleInternal; + ENVIRONMENT_IS_NODE: boolean; + ENVIRONMENT_IS_SHELL: boolean; + ENVIRONMENT_IS_WEB: boolean; + ENVIRONMENT_IS_WORKER: boolean; + ENVIRONMENT_IS_SIDECAR: boolean; + ABORT: boolean; + EXITSTATUS: number; + + ExitStatus: (exitCode: number) => number; + _emscripten_force_exit: (exitCode: number) => void; + _exit: (exitCode: number, implicit?: boolean) => void; + safeSetTimeout: (func: Function, timeout: number) => number; + maybeExit: () => void; + exitJS: (status: number, implicit?: boolean | number) => void; + runtimeKeepalivePop: () => void; + runtimeKeepalivePush: () => void; +} + +const _ems_: emAmbientSymbolsType = globalThis as any; +//export default emAmbientSymbols; +export { _ems_ }; diff --git a/src/native/libs/Common/JavaScript/per-module/index.ts b/src/native/libs/Common/JavaScript/per-module/index.ts index 8858f9084f1885..585114e9875d90 100644 --- a/src/native/libs/Common/JavaScript/per-module/index.ts +++ b/src/native/libs/Common/JavaScript/per-module/index.ts @@ -1,9 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +import type { VoidPtr, CharPtr, NativePointer } from "../types"; + export const ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string"; export const ENVIRONMENT_IS_WEB_WORKER = typeof importScripts == "function"; export const ENVIRONMENT_IS_SIDECAR = ENVIRONMENT_IS_WEB_WORKER && typeof (globalThis as any).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 const VoidPtrNull: VoidPtr = 0; +export const CharPtrNull: CharPtr = 0; +export const NativePointerNull: NativePointer = 0; diff --git a/src/native/libs/System.Native.Browser/libSystem.Native.Browser.Utils.footer.js b/src/native/libs/System.Native.Browser/libSystem.Native.Browser.Utils.footer.js index 08148744a9ae80..ee6143a574de52 100644 --- a/src/native/libs/System.Native.Browser/libSystem.Native.Browser.Utils.footer.js +++ b/src/native/libs/System.Native.Browser/libSystem.Native.Browser.Utils.footer.js @@ -19,7 +19,7 @@ const exports = {}; libBrowserUtils(exports); - let commonDeps = ["$libBrowserUtilsFn", "$DOTNET", "emscripten_force_exit", "_exit"]; + let commonDeps = ["$libBrowserUtilsFn", "$DOTNET", "emscripten_force_exit", "_exit", "GetDotNetRuntimeContractDescriptor"]; const lib = { $BROWSER_UTILS: { selfInitialize: () => { @@ -37,13 +37,14 @@ $BROWSER_UTILS__deps: commonDeps, }; + // install cross-module symbols as "_ems_" ambient symbols in Emscripten closure // keep in sync with `reserved`+`keep_fnames` in src\native\rollup.config.defines.js - for (const exportName of Reflect.ownKeys(exports.cross)) { + for (const exportName of Reflect.ownKeys(exports._ems_ambient_)) { const name = String(exportName); if (name === "dotnetInternals") continue; if (name === "Module") continue; const emName = "$" + name; - lib[emName] = exports.cross[exportName]; + lib[emName] = exports._ems_ambient_[exportName]; commonDeps.push(emName); } diff --git a/src/native/libs/System.Native.Browser/libSystem.Native.Browser.footer.js b/src/native/libs/System.Native.Browser/libSystem.Native.Browser.footer.js index ff5f4523b1fc12..c7e48d369fea58 100644 --- a/src/native/libs/System.Native.Browser/libSystem.Native.Browser.footer.js +++ b/src/native/libs/System.Native.Browser/libSystem.Native.Browser.footer.js @@ -19,7 +19,7 @@ const exports = {}; libNativeBrowser(exports); - let commonDeps = ["$BROWSER_UTILS", "GetDotNetRuntimeContractDescriptor"]; + let commonDeps = ["$BROWSER_UTILS", "SystemJS_ExecuteTimerCallback", "SystemJS_ExecuteBackgroundJobCallback"]; const lib = { $DOTNET: { selfInitialize: () => { @@ -37,11 +37,8 @@ for (const exportName of Reflect.ownKeys(exports)) { const name = String(exportName); - if (name === "dotnetInitializeModule" || name === "gitHash") continue; - const fn = lib[name] = exports[name]; - if (fn.__deps) { - lib[name + "__deps"] = fn.__deps; - } + if (name === "dotnetInitializeModule") continue; + lib[name] = exports[name]; } autoAddDeps(lib, "$DOTNET"); diff --git a/src/native/libs/System.Native.Browser/native/cross-linked.ts b/src/native/libs/System.Native.Browser/native/cross-linked.ts deleted file mode 100644 index ca55149e376530..00000000000000 --- a/src/native/libs/System.Native.Browser/native/cross-linked.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - - -import { } from "../../Common/JavaScript/cross-linked"; -declare global { - export const DOTNET: any; - export function _emscripten_force_exit(exitCode: number): void; - export function _exit(exitCode: number, implicit?: boolean): void; - export function _GetDotNetRuntimeContractDescriptor(): void; - export function _SystemJS_ExecuteTimerCallback(): void; - export function _SystemJS_ExecuteBackgroundJobCallback(): void; -} diff --git a/src/native/libs/System.Native.Browser/native/crypto.ts b/src/native/libs/System.Native.Browser/native/crypto.ts index 2143d94ad20b47..6c977cf8158fed 100644 --- a/src/native/libs/System.Native.Browser/native/crypto.ts +++ b/src/native/libs/System.Native.Browser/native/crypto.ts @@ -1,7 +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 { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; + export function SystemJS_RandomBytes(bufferPtr: number, bufferLength: number): number { // batchedQuotaMax is the max number of bytes as specified by the api spec. @@ -11,18 +12,18 @@ export function SystemJS_RandomBytes(bufferPtr: number, bufferLength: number): n if (!globalThis.crypto || !globalThis.crypto.getRandomValues) { if (!(globalThis as any)["cryptoWarnOnce"]) { - dotnetLogger.warn("This engine doesn't support crypto.getRandomValues. Please use a modern version or provide polyfill for 'globalThis.crypto.getRandomValues'."); + _ems_.dotnetLogger.warn("This engine doesn't support crypto.getRandomValues. Please use a modern version or provide polyfill for 'globalThis.crypto.getRandomValues'."); (globalThis as any)["cryptoWarnOnce"] = true; } return -1; } bufferPtr = bufferPtr >>> 0; - const memoryView = dotnetApi.localHeapViewU8(); + const memoryView = _ems_.dotnetApi.localHeapViewU8(); const targetView = memoryView.subarray(bufferPtr, bufferPtr + bufferLength); // When threading is enabled, Chrome doesn't want SharedArrayBuffer to be passed to crypto APIs - const needsCopy = dotnetBrowserUtilsExports.isSharedArrayBuffer(memoryView.buffer); + const needsCopy = _ems_.dotnetBrowserUtilsExports.isSharedArrayBuffer(memoryView.buffer); const targetBuffer = needsCopy ? new Uint8Array(bufferLength) : targetView; diff --git a/src/native/libs/System.Native.Browser/native/globalization-locale.ts b/src/native/libs/System.Native.Browser/native/globalization-locale.ts index 0687aa5b44c7c0..f8622ae731df08 100644 --- a/src/native/libs/System.Native.Browser/native/globalization-locale.ts +++ b/src/native/libs/System.Native.Browser/native/globalization-locale.ts @@ -2,21 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. import { Int32Ptr, VoidPtr } from "../types"; -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; // char16_t* SystemJS_GetLocaleInfo (const uint16_t* locale, int32_t localeLength, const uint16_t* culture, int32_t cultureLength, const uint16_t* result, int32_t resultMaxLength, int *resultLength); export function SystemJS_GetLocaleInfo(culture: number, cultureLength: number, locale: number, localeLength: number, dst: number, dstMaxLength: number, dstLength: Int32Ptr): VoidPtr { const OUTER_SEPARATOR = "##"; try { - const localeNameOriginal = dotnetBrowserUtilsExports.utf16ToString(locale, (locale + 2 * localeLength)); + const localeNameOriginal = _ems_.dotnetBrowserUtilsExports.utf16ToString(locale, (locale + 2 * localeLength)); const localeName = normalizeLocale(localeNameOriginal); if (!localeName && localeNameOriginal) { // handle non-standard or malformed locales by forwarding the locale code - dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); - dotnetApi.setHeapI32(dstLength, localeNameOriginal.length); - return VoidPtrNull; + _ems_.dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); + _ems_.dotnetApi.setHeapI32(dstLength, localeNameOriginal.length); + return 0 as any; } - const cultureNameOriginal = dotnetBrowserUtilsExports.utf16ToString(culture, (culture + 2 * cultureLength)); + const cultureNameOriginal = _ems_.dotnetBrowserUtilsExports.utf16ToString(culture, (culture + 2 * cultureLength)); const cultureName = normalizeLocale(cultureNameOriginal); if (!localeName || !cultureName) @@ -43,9 +43,9 @@ export function SystemJS_GetLocaleInfo(culture: number, cultureLength: number, l } catch (error) { if (error instanceof RangeError && localeNameOriginal) { // handle non-standard or malformed locales by forwarding the locale code, e.g. "xx-u-xx" - dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); - dotnetApi.setHeapI32(dstLength, localeNameOriginal.length); - return VoidPtrNull; + _ems_.dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); + _ems_.dotnetApi.setHeapI32(dstLength, localeNameOriginal.length); + return 0 as any; } throw error; } @@ -65,12 +65,12 @@ export function SystemJS_GetLocaleInfo(culture: number, cultureLength: number, l if (result.length > dstMaxLength) throw new Error(`Locale info for locale=${localeName} exceeds length of ${dstMaxLength}.`); - dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * result.length, result); - dotnetApi.setHeapI32(dstLength, result.length); - return VoidPtrNull; + _ems_.dotnetBrowserUtilsExports.stringToUTF16(dst, dst + 2 * result.length, result); + _ems_.dotnetApi.setHeapI32(dstLength, result.length); + return 0 as any; } catch (ex: any) { - dotnetApi.setHeapI32(dstLength, -1); - return dotnetBrowserUtilsExports.stringToUTF16Ptr(ex.toString()); + _ems_.dotnetApi.setHeapI32(dstLength, -1); + return _ems_.dotnetBrowserUtilsExports.stringToUTF16Ptr(ex.toString()); } function normalizeLocale(locale: string | null) { diff --git a/src/native/libs/System.Native.Browser/native/index.ts b/src/native/libs/System.Native.Browser/native/index.ts index 9bdecaacda58e8..bea996eb7202c5 100644 --- a/src/native/libs/System.Native.Browser/native/index.ts +++ b/src/native/libs/System.Native.Browser/native/index.ts @@ -4,6 +4,7 @@ import type { InternalExchange, NativeBrowserExports, NativeBrowserExportsTable } from "../types"; import { InternalExchangeIndex } from "../types"; +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; import GitHash from "consts:gitHash"; export { SystemJS_RandomBytes } from "./crypto"; @@ -18,13 +19,13 @@ export function dotnetInitializeModule(internals: InternalExchange): void { const runtimeApi = internals[InternalExchangeIndex.RuntimeAPI]; if (typeof runtimeApi !== "object") throw new Error("Expected internals to have RuntimeAPI"); - if (runtimeApi.runtimeBuildInfo.gitHash && runtimeApi.runtimeBuildInfo.gitHash !== DOTNET.gitHash) { - throw new Error(`Mismatched git hashes between loader and runtime. Loader: ${runtimeApi.runtimeBuildInfo.gitHash}, DOTNET: ${DOTNET.gitHash}`); + if (runtimeApi.runtimeBuildInfo.gitHash && runtimeApi.runtimeBuildInfo.gitHash !== _ems_.DOTNET.gitHash) { + throw new Error(`Mismatched git hashes between loader and runtime. Loader: ${runtimeApi.runtimeBuildInfo.gitHash}, DOTNET: ${_ems_.DOTNET.gitHash}`); } internals[InternalExchangeIndex.NativeBrowserExportsTable] = nativeBrowserExportsToTable({ }); - dotnetUpdateInternals(internals, dotnetUpdateInternalsSubscriber); + _ems_.dotnetUpdateInternals(internals, _ems_.dotnetUpdateInternalsSubscriber); // eslint-disable-next-line @typescript-eslint/no-unused-vars function nativeBrowserExportsToTable(map: NativeBrowserExports): NativeBrowserExportsTable { diff --git a/src/native/libs/System.Native.Browser/native/main.ts b/src/native/libs/System.Native.Browser/native/main.ts index cac449056a116a..2c015738ab92c5 100644 --- a/src/native/libs/System.Native.Browser/native/main.ts +++ b/src/native/libs/System.Native.Browser/native/main.ts @@ -1,24 +1,24 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; export function SystemJS_ResolveMainPromise(exitCode: number): void { - if (dotnetLoaderExports.resolveRunMainPromise) { - dotnetLoaderExports.resolveRunMainPromise(exitCode); + if (_ems_.dotnetLoaderExports.resolveRunMainPromise) { + _ems_.dotnetLoaderExports.resolveRunMainPromise(exitCode); } else { // this is for corerun, which does not use the promise - exitJS(exitCode, true); + _ems_.exitJS(exitCode, true); } } export function SystemJS_RejectMainPromise(messagePtr: number, messageLength: number, stackTracePtr: number, stackTraceLength: number): void { - const message = dotnetBrowserUtilsExports.utf16ToString(messagePtr, messagePtr + messageLength * 2); - const stackTrace = dotnetBrowserUtilsExports.utf16ToString(stackTracePtr, stackTracePtr + stackTraceLength * 2); + const message = _ems_.dotnetBrowserUtilsExports.utf16ToString(messagePtr, messagePtr + messageLength * 2); + const stackTrace = _ems_.dotnetBrowserUtilsExports.utf16ToString(stackTracePtr, stackTracePtr + stackTraceLength * 2); const error = new Error(message); error.stack = stackTrace; - if (dotnetLoaderExports.rejectRunMainPromise) { - dotnetLoaderExports.rejectRunMainPromise(error); + if (_ems_.dotnetLoaderExports.rejectRunMainPromise) { + _ems_.dotnetLoaderExports.rejectRunMainPromise(error); } else { // this is for corerun, which does not use the promise throw error; diff --git a/src/native/libs/System.Native.Browser/native/timer.ts b/src/native/libs/System.Native.Browser/native/timer.ts index 67113bedd5f4e1..e195e928818811 100644 --- a/src/native/libs/System.Native.Browser/native/timer.ts +++ b/src/native/libs/System.Native.Browser/native/timer.ts @@ -1,34 +1,33 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; export function SystemJS_ScheduleTimer(shortestDueTimeMs: number): void { - if (DOTNET.lastScheduledTimerId) { - globalThis.clearTimeout(DOTNET.lastScheduledTimerId); - Module.runtimeKeepalivePop(); - DOTNET.lastScheduledTimerId = undefined; + if (_ems_.DOTNET.lastScheduledTimerId) { + globalThis.clearTimeout(_ems_.DOTNET.lastScheduledTimerId); + _ems_.runtimeKeepalivePop(); + _ems_.DOTNET.lastScheduledTimerId = undefined; } - DOTNET.lastScheduledTimerId = safeSetTimeout(SystemJS_ScheduleTimerTick, shortestDueTimeMs); + _ems_.DOTNET.lastScheduledTimerId = _ems_.safeSetTimeout(SystemJS_ScheduleTimerTick, shortestDueTimeMs); function SystemJS_ScheduleTimerTick(): void { - DOTNET.lastScheduledTimerId = undefined; - _SystemJS_ExecuteTimerCallback(); + _ems_.DOTNET.lastScheduledTimerId = undefined; + _ems_._SystemJS_ExecuteTimerCallback(); } } -SystemJS_ScheduleTimer["__deps"] = ["SystemJS_ExecuteTimerCallback"]; export function SystemJS_ScheduleBackgroundJob(): void { - if (DOTNET.lastScheduledThreadPoolId) { - globalThis.clearTimeout(DOTNET.lastScheduledThreadPoolId); - Module.runtimeKeepalivePop(); - DOTNET.lastScheduledThreadPoolId = undefined; + if (_ems_.DOTNET.lastScheduledThreadPoolId) { + globalThis.clearTimeout(_ems_.DOTNET.lastScheduledThreadPoolId); + _ems_.runtimeKeepalivePop(); + _ems_.DOTNET.lastScheduledThreadPoolId = undefined; } - DOTNET.lastScheduledThreadPoolId = safeSetTimeout(SystemJS_ScheduleBackgroundJobTick, 0); + _ems_.DOTNET.lastScheduledThreadPoolId = _ems_.safeSetTimeout(SystemJS_ScheduleBackgroundJobTick, 0); function SystemJS_ScheduleBackgroundJobTick(): void { - DOTNET.lastScheduledThreadPoolId = undefined; - _SystemJS_ExecuteBackgroundJobCallback(); + _ems_.DOTNET.lastScheduledThreadPoolId = undefined; + _ems_._SystemJS_ExecuteBackgroundJobCallback(); } } -SystemJS_ScheduleBackgroundJob["__deps"] = ["SystemJS_ExecuteBackgroundJobCallback"]; + diff --git a/src/native/libs/System.Native.Browser/utils/cdac.ts b/src/native/libs/System.Native.Browser/utils/cdac.ts index 6a080a8fece04c..52b55b4dca8d4b 100644 --- a/src/native/libs/System.Native.Browser/utils/cdac.ts +++ b/src/native/libs/System.Native.Browser/utils/cdac.ts @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. import type { RuntimeAPI } from "./types"; -import { Module } from "./cross-module"; +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; export function registerCDAC(runtimeApi: RuntimeAPI): void { - runtimeApi.INTERNAL.GetDotNetRuntimeContractDescriptor = () => _GetDotNetRuntimeContractDescriptor(); - runtimeApi.INTERNAL.GetDotNetRuntimeHeap = (ptr: number, length: number) => Module.HEAPU8.subarray(ptr >>> 0, (ptr >>> 0) + length); + runtimeApi.INTERNAL.GetDotNetRuntimeContractDescriptor = () => _ems_._GetDotNetRuntimeContractDescriptor(); + runtimeApi.INTERNAL.GetDotNetRuntimeHeap = (ptr: number, length: number) => _ems_.Module.HEAPU8.subarray(ptr >>> 0, (ptr >>> 0) + length); } diff --git a/src/native/libs/System.Native.Browser/utils/cross-linked.ts b/src/native/libs/System.Native.Browser/utils/cross-linked.ts deleted file mode 100644 index 7214ddd74e84af..00000000000000 --- a/src/native/libs/System.Native.Browser/utils/cross-linked.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - - -import { } from "../../Common/JavaScript/cross-linked"; -declare global { - export let ABORT: boolean; - export let EXITSTATUS: number; - export function ExitStatus(exitCode: number): number; -} diff --git a/src/native/libs/System.Native.Browser/utils/cross-module.ts b/src/native/libs/System.Native.Browser/utils/cross-module.ts index 182969d8e7b5e3..8e72db213b830d 100644 --- a/src/native/libs/System.Native.Browser/utils/cross-module.ts +++ b/src/native/libs/System.Native.Browser/utils/cross-module.ts @@ -2,4 +2,3 @@ // The .NET Foundation licenses this file to you under the MIT license. export * from "../../Common/JavaScript/cross-module"; - diff --git a/src/native/libs/System.Native.Browser/utils/host.ts b/src/native/libs/System.Native.Browser/utils/host.ts index a9246e51e2ae75..a30df05a17a2a4 100644 --- a/src/native/libs/System.Native.Browser/utils/host.ts +++ b/src/native/libs/System.Native.Browser/utils/host.ts @@ -2,43 +2,42 @@ // The .NET Foundation licenses this file to you under the MIT license. import BuildConfiguration from "consts:configuration"; -import { Module, dotnetApi } from "./cross-module"; - +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; // eslint-disable-next-line @typescript-eslint/no-unused-vars export function setEnvironmentVariable(name: string, value: string): void { throw new Error("Not implemented"); } export function getExitStatus(): new (exitCode: number) => any { - return ExitStatus as any; + return _ems_.ExitStatus as any; } export function abortTimers(): void { - if (DOTNET.lastScheduledTimerId) { - globalThis.clearTimeout(DOTNET.lastScheduledTimerId); - Module.runtimeKeepalivePop(); - DOTNET.lastScheduledTimerId = undefined; + if (_ems_.DOTNET.lastScheduledTimerId) { + globalThis.clearTimeout(_ems_.DOTNET.lastScheduledTimerId); + _ems_.runtimeKeepalivePop(); + _ems_.DOTNET.lastScheduledTimerId = undefined; } - if (DOTNET.lastScheduledThreadPoolId) { - globalThis.clearTimeout(DOTNET.lastScheduledThreadPoolId); - Module.runtimeKeepalivePop(); - DOTNET.lastScheduledThreadPoolId = undefined; + if (_ems_.DOTNET.lastScheduledThreadPoolId) { + globalThis.clearTimeout(_ems_.DOTNET.lastScheduledThreadPoolId); + _ems_.runtimeKeepalivePop(); + _ems_.DOTNET.lastScheduledThreadPoolId = undefined; } } export function abortPosix(exitCode: number): void { - ABORT = true; - EXITSTATUS = exitCode; + _ems_.ABORT = true; + _ems_.EXITSTATUS = exitCode; try { if (BuildConfiguration === "Debug") { - _exit(exitCode, true); + _ems_._exit(exitCode, true); } else { - _emscripten_force_exit(exitCode); + _ems_._emscripten_force_exit(exitCode); } } catch (error: any) { // do not propagate ExitStatus exception if (error.status === undefined) { - dotnetApi.exit(1, error); + _ems_.dotnetApi.exit(1, error); throw error; } } diff --git a/src/native/libs/System.Native.Browser/utils/index.ts b/src/native/libs/System.Native.Browser/utils/index.ts index 95434eb7bd8ae2..ff24c8eb2c82d5 100644 --- a/src/native/libs/System.Native.Browser/utils/index.ts +++ b/src/native/libs/System.Native.Browser/utils/index.ts @@ -3,7 +3,6 @@ import type { InternalExchange, BrowserUtilsExports, RuntimeAPI, BrowserUtilsExportsTable } from "./types"; import { InternalExchangeIndex } from "../types"; -import { } from "./cross-module"; // ensure ambient symbols are declared import GitHash from "consts:gitHash"; @@ -72,4 +71,4 @@ export function dotnetInitializeModule(internals: InternalExchange): void { } // see also `reserved` in `rollup.config.defines.js` -export * as cross from "./cross-module"; +export * as _ems_ambient_ from "./cross-module"; diff --git a/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/cross-linked.ts b/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/cross-linked.ts deleted file mode 100644 index f2caa4fb684a7b..00000000000000 --- a/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/cross-linked.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -import { } from "../../Common/JavaScript/cross-linked"; - -declare global { - export const DOTNET_INTEROP: any; -} diff --git a/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/index.ts b/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/index.ts index 021eb895af80a0..1c455310cda05f 100644 --- a/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/index.ts +++ b/src/native/libs/System.Runtime.InteropServices.JavaScript.Native/native/index.ts @@ -3,14 +3,14 @@ import type { InternalExchange, InteropJavaScriptExports, InteropJavaScriptExportsTable, JSFnHandle, JSMarshalerArguments } from "../interop/types"; import { InternalExchangeIndex } from "../types"; -import { } from "./cross-linked"; // ensure ambient symbols are declared +import { _ems_ } from "../../Common/JavaScript/ems-ambient"; import GitHash from "consts:gitHash"; // eslint-disable-next-line @typescript-eslint/no-unused-vars export function SystemInteropJS_InvokeJSImportST(function_handle: JSFnHandle, args: JSMarshalerArguments) { // WASM-TODO implementation - dotnetLogger.error("SystemInteropJS_InvokeJSImportST called"); + _ems_.dotnetLogger.error("SystemInteropJS_InvokeJSImportST called"); return - 1; } @@ -20,8 +20,8 @@ export function dotnetInitializeModule(internals: InternalExchange): void { const runtimeApi = internals[InternalExchangeIndex.RuntimeAPI]; if (typeof runtimeApi !== "object") throw new Error("Expected internals to have RuntimeAPI"); - if (runtimeApi.runtimeBuildInfo.gitHash && runtimeApi.runtimeBuildInfo.gitHash !== DOTNET_INTEROP.gitHash) { - throw new Error(`Mismatched git hashes between loader and runtime. Loader: ${runtimeApi.runtimeBuildInfo.gitHash}, DOTNET_INTEROP: ${DOTNET_INTEROP.gitHash}`); + if (runtimeApi.runtimeBuildInfo.gitHash && runtimeApi.runtimeBuildInfo.gitHash !== _ems_.DOTNET_INTEROP.gitHash) { + throw new Error(`Mismatched git hashes between loader and runtime. Loader: ${runtimeApi.runtimeBuildInfo.gitHash}, DOTNET_INTEROP: ${_ems_.DOTNET_INTEROP.gitHash}`); } internals[InternalExchangeIndex.InteropJavaScriptExportsTable] = interopJavaScriptExportsToTable({ @@ -32,5 +32,5 @@ export function dotnetInitializeModule(internals: InternalExchange): void { return [ ]; } - dotnetUpdateInternals(internals, dotnetUpdateInternalsSubscriber); + _ems_.dotnetUpdateInternals(internals, _ems_.dotnetUpdateInternalsSubscriber); } diff --git a/src/native/rollup.config.defines.js b/src/native/rollup.config.defines.js index 96005063aec63b..aa0d31c92e4892 100644 --- a/src/native/rollup.config.defines.js +++ b/src/native/rollup.config.defines.js @@ -22,21 +22,21 @@ export const staticLibDestination = process.env.StaticLibDestination || "../../a console.log(`Rollup configuration: Configuration=${configuration}, ProductVersion=${productVersion}, ContinuousIntegrationBuild=${isContinuousIntegrationBuild}`); -export const banner = "//! Licensed to the .NET Foundation under one or more agreements.\n//! The .NET Foundation licenses this file to you under the MIT license.\n//! This is generated file, see src/native/libs/Browser/rollup.config.defines.js\n\n"; +export const banner = "//! Licensed to the .NET Foundation under one or more agreements.\n//! The .NET Foundation licenses this file to you under the MIT license.\n//! This is generated file, see src/native/rollup.config.js\n\n"; export const banner_dts = banner + "//! This is not considered public API with backward compatibility guarantees. \n"; export const keep_classnames = /(ManagedObject|ManagedError|Span|ArraySegment)/; export const keep_fnames = /(dotnetUpdateInternals|dotnetUpdateInternalsSubscriber)/; export const reserved = [ - "Module", "dotnetApi", - "dotnetInternals", "dotnetLogger", "dotnetAssert", "dotnetJSEngine", - "dotnetUpdateInternals", "dotnetUpdateInternalsSubscriber", "dotnetInitializeModule", + "_ems_", "Module", + "dotnetInternals", "dotnetUpdateInternals", "dotnetUpdateInternalsSubscriber", "dotnetInitializeModule", + "dotnetLogger", "dotnetAssert", "dotnetApi", "dotnetLoaderExports", "dotnetRuntimeExports", "dotnetBrowserHostExports", "dotnetInteropJSExports", "dotnetNativeBrowserExports", "dotnetBrowserUtilsExports", "dotnetDiagnosticsExports", ]; export const externalDependencies = ["module", "process", "perf_hooks", "node:crypto"]; export const artifactsObjDir = "../../artifacts/obj"; -export const isDebug = process.env.Configuration !== "Release"; +export const isDebug = process.env.Configuration !== "Release" && !isContinuousIntegrationBuild; export let gitHash; try { diff --git a/src/native/rollup.config.js b/src/native/rollup.config.js index a0504349a19c18..24ec8ce9f30414 100644 --- a/src/native/rollup.config.js +++ b/src/native/rollup.config.js @@ -10,7 +10,7 @@ import { isDebug, staticLibDestination, keep_classnames, keep_fnames, reserved } from "./rollup.config.defines.js"; -import { terserPlugin, writeOnChangePlugin, consts, onwarn, alwaysLF, iife2fe, sourcemapPathTransform } from "./rollup.config.plugins.js"; +import { terserPlugin, writeOnChangePlugin, consts, onwarn, alwaysLF, iife2fe, emsAmbient, sourcemapPathTransform } from "./rollup.config.plugins.js"; import { promises as fs } from "fs"; const dotnetDTS = { @@ -170,7 +170,7 @@ export default defineConfig([ libBrowserHost, ]); -function configure({ input, output, terser }) { +function configure({ input, output, terser, external }) { return { treeshake: !isDebug, input, @@ -179,14 +179,14 @@ function configure({ input, output, terser }) { banner, format: "es", plugins: isDebug - ? [iife2fe(), writeOnChangePlugin()] - : [terserPlugin(terser), iife2fe(), writeOnChangePlugin()], + ? [emsAmbient(), iife2fe(), writeOnChangePlugin()] + : [emsAmbient(), terserPlugin(terser), iife2fe(), writeOnChangePlugin()], sourcemap: true, //isDebug ? true : "hidden", sourcemapPathTransform, ...o }; }), - external: externalDependencies, + external: external ? [...external, ...externalDependencies] : externalDependencies, plugins: [ nodeResolve(), consts(envConstants), diff --git a/src/native/rollup.config.plugins.js b/src/native/rollup.config.plugins.js index ea9da5b39e292c..7eac65e1df23a8 100644 --- a/src/native/rollup.config.plugins.js +++ b/src/native/rollup.config.plugins.js @@ -48,15 +48,31 @@ export function iife2fe() { //throw new Error("iife2fe " + code); asset.code = code .replace(/}\({}\);/, "};") // }({}); ->}; - .replace(/}\)\({}\);/, "});") // })({}); ->}); - ; + .replace(/}\)\({}\);/, "});"); // })({}); ->}); } }; } +// Drop _ems_ symbol from emscripten libraries +export function emsAmbient() { + return { + name: "emsAmbient", + generateBundle: (options, bundle) => { + const name = Object.keys(bundle)[0]; + if (name.endsWith(".map")) return; + const asset = bundle[name]; + const code = asset.code; + //throw new Error("iife2fe " + code); + asset.code = code + .replace(/_ems_\./g, ""); + } + }; +} + + // force always unix line ending export const alwaysLF = () => ({ - name: "writeOnChange", + name: "alwaysLF", generateBundle: (options, bundle) => { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -103,18 +119,6 @@ function checkFileExists(file) { } export function onwarn(warning) { - if (warning.code === "CIRCULAR_DEPENDENCY") { - return; - } - - if (warning.code === "UNRESOLVED_IMPORT" && warning.exporter === "process") { - return; - } - - if (warning.code === "PLUGIN_WARNING" && warning.message.indexOf("sourcemap") !== -1) { - return; - } - // eslint-disable-next-line no-console console.warn(`(!) ${warning.toString()} ${warning.code}`); } diff --git a/src/native/tsconfig.json b/src/native/tsconfig.json index 9ef2a54d8676bf..16c11eb6e5e496 100644 --- a/src/native/tsconfig.json +++ b/src/native/tsconfig.json @@ -5,7 +5,7 @@ "removeComments": false, "module": "esnext", "sourceMap": true, - // keep in sync with src/native/rollup.config.defines.js + // keep in sync with src/native/rollup.config.js "target": "ES2020", "moduleResolution": "Node", "strict": true,