From f8be1d206d5579c509f688ca6f4fc4e9e765b238 Mon Sep 17 00:00:00 2001 From: Ilona Tomkowicz Date: Tue, 26 Mar 2024 14:41:29 +0100 Subject: [PATCH 1/4] Revert fixes done by code editor plugin, add new rules, check if CI fails. --- src/mono/browser/runtime/.eslintignore | 1 + src/mono/browser/runtime/.eslintrc.cjs | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/mono/browser/runtime/.eslintignore b/src/mono/browser/runtime/.eslintignore index 682049e38a9267..47ac7775dd4acc 100644 --- a/src/mono/browser/runtime/.eslintignore +++ b/src/mono/browser/runtime/.eslintignore @@ -1,2 +1,3 @@ jiterpreter-opcodes.ts jiterpreter-tables.ts +dotnet.d.ts diff --git a/src/mono/browser/runtime/.eslintrc.cjs b/src/mono/browser/runtime/.eslintrc.cjs index 5cdee1555241ad..2e0abed745228c 100644 --- a/src/mono/browser/runtime/.eslintrc.cjs +++ b/src/mono/browser/runtime/.eslintrc.cjs @@ -22,6 +22,7 @@ module.exports = { "es6/*.js", "jiterpreter-opcodes.ts", "jiterpreter-tables.ts", + "dotnet.d.ts", ], "rules": { "@typescript-eslint/no-explicit-any": "off", @@ -48,6 +49,15 @@ module.exports = { "semi": [ "error", "always" - ] + ], + "brace-style": ["error"], + "eol-last": ["error"], + "space-before-blocks": ["error"], + "semi-spacing": ["error", { "before": false, "after": true }], + "no-trailing-spaces": ["error"], + "object-curly-spacing": ["error"], + "array-bracket-spacing": ["error"], + "space-infix-ops": ["error"], + "space-before-function-paren": ["error"], } }; From 904d8e604e239752bc8a7843d2627861209dc982 Mon Sep 17 00:00:00 2001 From: Ilona Tomkowicz Date: Tue, 26 Mar 2024 15:31:46 +0100 Subject: [PATCH 2/4] Result of `npm run format`. --- src/mono/browser/runtime/assets.ts | 41 ++-- src/mono/browser/runtime/base64.ts | 4 +- .../browser/runtime/cancelable-promise.ts | 52 ++--- src/mono/browser/runtime/crypto.ts | 4 +- src/mono/browser/runtime/cuint64.ts | 12 +- src/mono/browser/runtime/cwraps.ts | 12 +- src/mono/browser/runtime/debug.ts | 90 +++---- .../browser/runtime/diagnostics-mock.d.ts | 4 +- .../runtime/diagnostics/browser/controller.ts | 28 +-- src/mono/browser/runtime/diagnostics/index.ts | 22 +- .../runtime/diagnostics/mock/environment.ts | 40 ++-- .../browser/runtime/diagnostics/mock/index.ts | 44 ++-- .../browser/runtime/diagnostics/mock/types.ts | 2 +- .../server_pthread/common-socket.ts | 4 +- .../diagnostics/server_pthread/index.ts | 82 +++---- .../ipc-protocol/base-parser.ts | 28 +-- .../ipc-protocol/base-serializer.ts | 22 +- .../server_pthread/ipc-protocol/magic.ts | 4 +- .../server_pthread/ipc-protocol/parser.ts | 64 ++--- .../server_pthread/ipc-protocol/serializer.ts | 16 +- .../server_pthread/ipc-protocol/types.ts | 2 +- .../diagnostics/server_pthread/mock-remote.ts | 6 +- .../protocol-client-commands.ts | 14 +- .../server_pthread/protocol-socket.ts | 76 +++--- .../server_pthread/socket-connection.ts | 32 +-- .../server_pthread/stream-queue.ts | 26 +-- .../server_pthread/streaming-session.ts | 30 +-- .../diagnostics/shared/controller-commands.ts | 8 +- .../diagnostics/shared/create-session.ts | 16 +- src/mono/browser/runtime/export-api.ts | 16 +- src/mono/browser/runtime/exports-binding.ts | 50 ++-- src/mono/browser/runtime/exports-internal.ts | 54 ++--- src/mono/browser/runtime/exports-linker.ts | 8 +- src/mono/browser/runtime/exports.ts | 37 ++- src/mono/browser/runtime/gc-handles.ts | 55 +++-- src/mono/browser/runtime/gc-lock.ts | 6 +- src/mono/browser/runtime/globals.ts | 22 +- src/mono/browser/runtime/guarded-promise.ts | 2 +- src/mono/browser/runtime/http.ts | 58 +++-- .../runtime/hybrid-globalization/calendar.ts | 192 ++++++--------- .../hybrid-globalization/change-case.ts | 113 ++++----- .../hybrid-globalization/collations.ts | 68 +++--- .../hybrid-globalization/culture-info.ts | 68 +++--- .../grapheme-segmenter.ts | 42 ++-- .../runtime/hybrid-globalization/helpers.ts | 25 +- .../runtime/hybrid-globalization/locales.ts | 71 +++--- src/mono/browser/runtime/icu.ts | 4 +- src/mono/browser/runtime/interp-pgo.ts | 22 +- src/mono/browser/runtime/invoke-cs.ts | 79 +++---- src/mono/browser/runtime/invoke-js.ts | 128 +++++----- .../runtime/jiterpreter-interp-entry.ts | 32 +-- .../browser/runtime/jiterpreter-jit-call.ts | 38 +-- .../browser/runtime/jiterpreter-support.ts | 220 +++++++++--------- .../runtime/jiterpreter-trace-generator.ts | 108 ++++----- src/mono/browser/runtime/jiterpreter.ts | 48 ++-- src/mono/browser/runtime/lazyLoading.ts | 12 +- src/mono/browser/runtime/loader/assets.ts | 98 ++++---- .../browser/runtime/loader/assetsCache.ts | 32 +-- src/mono/browser/runtime/loader/config.ts | 87 ++++--- src/mono/browser/runtime/loader/exit.ts | 64 +++-- src/mono/browser/runtime/loader/globals.ts | 36 +-- src/mono/browser/runtime/loader/icu.ts | 15 +- src/mono/browser/runtime/loader/index.ts | 10 +- .../runtime/loader/libraryInitializers.ts | 22 +- src/mono/browser/runtime/loader/logging.ts | 39 ++-- src/mono/browser/runtime/loader/polyfills.ts | 62 ++--- .../runtime/loader/promise-controller.ts | 14 +- src/mono/browser/runtime/loader/run.ts | 112 +++++---- src/mono/browser/runtime/loader/worker.ts | 16 +- src/mono/browser/runtime/logging.ts | 33 ++- src/mono/browser/runtime/managed-exports.ts | 56 +++-- src/mono/browser/runtime/marshal-to-cs.ts | 218 +++++++---------- src/mono/browser/runtime/marshal-to-js.ts | 131 +++++------ src/mono/browser/runtime/marshal.ts | 170 +++++++------- src/mono/browser/runtime/memory.ts | 150 ++++++------ src/mono/browser/runtime/polyfills.ts | 26 +-- src/mono/browser/runtime/profiler.ts | 28 +-- .../browser/runtime/pthreads/deputy-thread.ts | 20 +- src/mono/browser/runtime/pthreads/index.ts | 4 +- .../browser/runtime/pthreads/io-thread.ts | 17 +- src/mono/browser/runtime/pthreads/shared.ts | 29 ++- .../browser/runtime/pthreads/ui-thread.ts | 59 +++-- .../browser/runtime/pthreads/worker-events.ts | 8 +- .../browser/runtime/pthreads/worker-thread.ts | 56 +++-- src/mono/browser/runtime/queue.ts | 16 +- src/mono/browser/runtime/rollup.config.js | 66 +++--- src/mono/browser/runtime/roots.ts | 116 ++++----- src/mono/browser/runtime/run.ts | 25 +- .../browser/runtime/satelliteAssemblies.ts | 10 +- src/mono/browser/runtime/scheduling.ts | 27 ++- src/mono/browser/runtime/startup.ts | 114 +++++---- src/mono/browser/runtime/strings.ts | 44 ++-- .../browser/runtime/types/export-types.ts | 8 +- src/mono/browser/runtime/types/index.ts | 2 +- src/mono/browser/runtime/types/internal.ts | 20 +- src/mono/browser/runtime/types/node.d.ts | 2 +- src/mono/browser/runtime/types/sidecar.d.ts | 2 +- src/mono/browser/runtime/types/v8.d.ts | 2 +- src/mono/browser/runtime/weak-ref.ts | 11 +- src/mono/browser/runtime/web-socket.ts | 92 ++++---- 100 files changed, 2151 insertions(+), 2381 deletions(-) diff --git a/src/mono/browser/runtime/assets.ts b/src/mono/browser/runtime/assets.ts index 40dc39349ff565..8b7035f2e56136 100644 --- a/src/mono/browser/runtime/assets.ts +++ b/src/mono/browser/runtime/assets.ts @@ -1,20 +1,20 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { AssetEntryInternal } from "./types/internal"; +import type {AssetEntryInternal} from "./types/internal"; import cwraps from "./cwraps"; -import { mono_wasm_load_icu_data } from "./icu"; -import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; -import { mono_log_info, mono_log_debug, parseSymbolMapFile } from "./logging"; -import { mono_wasm_load_bytes_into_heap } from "./memory"; -import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; -import { AssetEntry } from "./types"; -import { VoidPtr } from "./types/emscripten"; -import { setSegmentationRulesFromJson } from "./hybrid-globalization/grapheme-segmenter"; +import {mono_wasm_load_icu_data} from "./icu"; +import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; +import {mono_log_info, mono_log_debug, parseSymbolMapFile} from "./logging"; +import {mono_wasm_load_bytes_into_heap} from "./memory"; +import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; +import {AssetEntry} from "./types"; +import {VoidPtr} from "./types/emscripten"; +import {setSegmentationRulesFromJson} from "./hybrid-globalization/grapheme-segmenter"; // this need to be run only after onRuntimeInitialized event, when the memory is ready -export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Array): void { +export function instantiate_asset (asset: AssetEntry, url: string, bytes: Uint8Array): void { mono_log_debug(`Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); const mark = startMeasure(); @@ -33,7 +33,7 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar case "resource": case "assembly": case "pdb": - loaderHelpers._loaded_files.push({ url: url, file: virtualName }); + loaderHelpers._loaded_files.push({url: url, file: virtualName}); // falls through case "heap": case "icu": @@ -82,22 +82,19 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar const index = loaderHelpers._loaded_files.findIndex(element => element.file == virtualName); loaderHelpers._loaded_files.splice(index, 1); } - } - else if (asset.behavior === "pdb") { + } else if (asset.behavior === "pdb") { cwraps.mono_wasm_add_assembly(virtualName, offset!, bytes.length); - } - else if (asset.behavior === "icu") { + } else if (asset.behavior === "icu") { if (!mono_wasm_load_icu_data(offset!)) Module.err(`Error loading ICU asset ${asset.name}`); - } - else if (asset.behavior === "resource") { + } else if (asset.behavior === "resource") { cwraps.mono_wasm_add_satellite_assembly(virtualName, asset.culture || "", offset!, bytes.length); } endMeasure(mark, MeasuredBlock.instantiateAsset, asset.name); ++loaderHelpers.actual_instantiated_assets_count; } -export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_symbols_asset (pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const text = await response.text(); @@ -107,7 +104,7 @@ export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal } } -export async function instantiate_segmentation_rules_asset(pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_segmentation_rules_asset (pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const json = await response.json(); @@ -117,7 +114,7 @@ export async function instantiate_segmentation_rules_asset(pendingAsset: AssetEn } } -export async function wait_for_all_assets() { +export async function wait_for_all_assets () { // wait for all assets in memory await runtimeHelpers.allAssetsInMemory.promise; if (runtimeHelpers.config.assets) { @@ -129,6 +126,6 @@ export async function wait_for_all_assets() { } // Used by the debugger to enumerate loaded dlls and pdbs -export function mono_wasm_get_loaded_files(): string[] { +export function mono_wasm_get_loaded_files (): string[] { return loaderHelpers.loadedFiles; -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/base64.ts b/src/mono/browser/runtime/base64.ts index ac0664b78c201e..28bf9970ed7f10 100644 --- a/src/mono/browser/runtime/base64.ts +++ b/src/mono/browser/runtime/base64.ts @@ -5,7 +5,7 @@ // https://github.com/sq/JSIL/blob/1d57d5427c87ab92ffa3ca4b82429cd7509796ba/JSIL.Libraries/Includes/Bootstrap/Core/Classes/System.Convert.js#L149 // Thanks to Katelyn Gadd @kg -export function toBase64StringImpl(inArray: Uint8Array, offset?: number, length?: number) : string{ +export function toBase64StringImpl (inArray: Uint8Array, offset?: number, length?: number) : string { const reader = _makeByteReader(inArray, offset, length); let result = ""; let ch1: number | null = 0, ch2: number | null = 0, ch3: number | null = 0; @@ -76,7 +76,7 @@ const _base64Table = [ "+", "/" ]; -function _makeByteReader(bytes: Uint8Array, index?: number, count?: number): { +function _makeByteReader (bytes: Uint8Array, index?: number, count?: number): { read: () => number | null } { let position = (typeof (index) === "number") ? index : 0; diff --git a/src/mono/browser/runtime/cancelable-promise.ts b/src/mono/browser/runtime/cancelable-promise.ts index cf0b048a2c60cd..189cbff75e069b 100644 --- a/src/mono/browser/runtime/cancelable-promise.ts +++ b/src/mono/browser/runtime/cancelable-promise.ts @@ -3,38 +3,38 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { _lookup_js_owned_object, teardown_managed_proxy, upgrade_managed_proxy_to_strong_ref } from "./gc-handles"; -import { createPromiseController, loaderHelpers, mono_assert } from "./globals"; -import { ControllablePromise, GCHandle, MarshalerToCs } from "./types/internal"; -import { ManagedObject } from "./marshal"; -import { compareExchangeI32, forceThreadMemoryViewRefresh } from "./memory"; -import { mono_log_debug } from "./logging"; -import { complete_task } from "./managed-exports"; -import { marshal_cs_object_to_cs } from "./marshal-to-cs"; +import {_lookup_js_owned_object, teardown_managed_proxy, upgrade_managed_proxy_to_strong_ref} from "./gc-handles"; +import {createPromiseController, loaderHelpers, mono_assert} from "./globals"; +import {ControllablePromise, GCHandle, MarshalerToCs} from "./types/internal"; +import {ManagedObject} from "./marshal"; +import {compareExchangeI32, forceThreadMemoryViewRefresh} from "./memory"; +import {mono_log_debug} from "./logging"; +import {complete_task} from "./managed-exports"; +import {marshal_cs_object_to_cs} from "./marshal-to-cs"; export const _are_promises_supported = ((typeof Promise === "object") || (typeof Promise === "function")) && (typeof Promise.resolve === "function"); -export function isThenable(js_obj: any): boolean { +export function isThenable (js_obj: any): boolean { // When using an external Promise library like Bluebird the Promise.resolve may not be sufficient // to identify the object as a Promise. return Promise.resolve(js_obj) === js_obj || ((typeof js_obj === "object" || typeof js_obj === "function") && typeof js_obj.then === "function"); } -export function wrap_as_cancelable_promise(fn: () => Promise): ControllablePromise { - const { promise, promise_control } = createPromiseController(); +export function wrap_as_cancelable_promise (fn: () => Promise): ControllablePromise { + const {promise, promise_control} = createPromiseController(); const inner = fn(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function wrap_as_cancelable(inner: Promise): ControllablePromise { - const { promise, promise_control } = createPromiseController(); +export function wrap_as_cancelable (inner: Promise): ControllablePromise { + const {promise, promise_control} = createPromiseController(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function mono_wasm_cancel_promise(task_holder_gc_handle: GCHandle): void { +export function mono_wasm_cancel_promise (task_holder_gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise can't be canceled, mono runtime already exited."); return; @@ -57,15 +57,15 @@ export class PromiseHolder extends ManagedObject { public isPostponed = false; public data: any = null; public reason: any = null; - public constructor(public promise: Promise, + public constructor (public promise: Promise, private gc_handle: GCHandle, - private promiseHolderPtr: number, // could be null for GCV_handle + private promiseHolderPtr: number, // could be null for GCV_handle private res_converter?: MarshalerToCs) { super(); } // returns false if the promise is being canceled by another thread in managed code - setIsResolving(): boolean { + setIsResolving (): boolean { if (!WasmEnableThreads || this.promiseHolderPtr === 0) { return true; } @@ -76,7 +76,7 @@ export class PromiseHolder extends ManagedObject { return false; } - resolve(data: any) { + resolve (data: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution can't be propagated to managed code, mono runtime already exited."); return; @@ -100,7 +100,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(data, null); } - reject(reason: any) { + reject (reason: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -125,7 +125,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(null, reason); } - cancel() { + cancel () { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise cancelation can't be propagated to managed code, mono runtime already exited."); return; @@ -135,7 +135,7 @@ export class PromiseHolder extends ManagedObject { if (this.isPostponed) { // there was racing resolve/reject which was postponed, to retain valid GCHandle - // in this case we just finish the original resolve/reject + // in this case we just finish the original resolve/reject // and we need to use the postponed data/reason this.isResolved = true; if (this.reason !== undefined) { @@ -156,7 +156,7 @@ export class PromiseHolder extends ManagedObject { } // we can do this just once, because it will be dispose the GCHandle - complete_task_wrapper(data: any, reason: any) { + complete_task_wrapper (data: any, reason: any) { try { mono_assert(!this.isPosted, "Promise is already posted to managed."); this.isPosted = true; @@ -169,14 +169,12 @@ export class PromiseHolder extends ManagedObject { // order of operations with teardown_managed_proxy matters // so that managed user code running in the continuation could allocate the same GCHandle number and the local registry would be already ok with that complete_task(this.gc_handle, reason, data, this.res_converter || marshal_cs_object_to_cs); - } - catch (ex) { + } catch (ex) { try { loaderHelpers.mono_exit(1, ex); - } - catch (ex2) { + } catch (ex2) { // there is no point to propagate the exception into the unhandled promise rejection } } } -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/crypto.ts b/src/mono/browser/runtime/crypto.ts index f396b5d833b147..9bf82e92f0aaa8 100644 --- a/src/mono/browser/runtime/crypto.ts +++ b/src/mono/browser/runtime/crypto.ts @@ -1,11 +1,11 @@ -import { isSharedArrayBuffer, localHeapViewU8 } from "./memory"; +import {isSharedArrayBuffer, localHeapViewU8} from "./memory"; // batchedQuotaMax is the max number of bytes as specified by the api spec. // If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm. // https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues const batchedQuotaMax = 65536; -export function mono_wasm_browser_entropy(bufferPtr: number, bufferLength: number): number { +export function mono_wasm_browser_entropy (bufferPtr: number, bufferLength: number): number { if (!globalThis.crypto || !globalThis.crypto.getRandomValues) { return -1; } diff --git a/src/mono/browser/runtime/cuint64.ts b/src/mono/browser/runtime/cuint64.ts index 558c230265e23c..20ab2c88ca422f 100644 --- a/src/mono/browser/runtime/cuint64.ts +++ b/src/mono/browser/runtime/cuint64.ts @@ -6,11 +6,11 @@ /// and 'import type { CUInt64 } from './cuint64'; export type CUInt64 = readonly [number, number]; -export function toBigInt(x: CUInt64): bigint { +export function toBigInt (x: CUInt64): bigint { return BigInt(x[0]) | BigInt(x[1]) << BigInt(32); } -export function fromBigInt(x: bigint): CUInt64 { +export function fromBigInt (x: bigint): CUInt64 { if (x < BigInt(0)) throw new Error(`${x} is not a valid 64 bit integer`); if (x > BigInt(0xFFFFFFFFFFFFFFFF)) @@ -20,11 +20,11 @@ export function fromBigInt(x: bigint): CUInt64 { return [low, high]; } -export function dangerousToNumber(x: CUInt64): number { +export function dangerousToNumber (x: CUInt64): number { return x[0] | x[1] << 32; } -export function fromNumber(x: number): CUInt64 { +export function fromNumber (x: number): CUInt64 { if (x < 0) throw new Error(`${x} is not a valid 64 bit integer`); if ((x >> 32) > 0xFFFFFFFF) @@ -34,11 +34,11 @@ export function fromNumber(x: number): CUInt64 { return [x & 0xFFFFFFFF, x >> 32]; } -export function pack32(lo: number, hi: number): CUInt64 { +export function pack32 (lo: number, hi: number): CUInt64 { return [lo, hi]; } -export function unpack32(x: CUInt64): [number, number] { +export function unpack32 (x: CUInt64): [number, number] { return [x[0], x[1]]; } diff --git a/src/mono/browser/runtime/cwraps.ts b/src/mono/browser/runtime/cwraps.ts index 11168751ebb3bb..f0f8137bf74067 100644 --- a/src/mono/browser/runtime/cwraps.ts +++ b/src/mono/browser/runtime/cwraps.ts @@ -8,10 +8,10 @@ import type { MonoMethod, MonoObject, MonoType, MonoObjectRef, MonoStringRef, JSMarshalerArguments, PThreadPtr } from "./types/internal"; -import type { VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer } from "./types/emscripten"; -import { Module, runtimeHelpers } from "./globals"; -import { mono_log_error } from "./logging"; -import { mono_assert } from "./globals"; +import type {VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer} from "./types/emscripten"; +import {Module, runtimeHelpers} from "./globals"; +import {mono_log_error} from "./logging"; +import {mono_assert} from "./globals"; type SigLine = [lazyOrSkip: boolean | (() => boolean), name: string, returnType: string | null, argTypes?: string[], opts?: any]; @@ -281,7 +281,7 @@ export const enum I52Error { const fastCwrapTypes = ["void", "number", null]; -function cwrap(name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { +function cwrap (name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { // Attempt to bypass emscripten's generated wrapper if it is safe to do so let fce = // Special cwrap options disable the fast path @@ -312,7 +312,7 @@ function cwrap(name: string, returnType: string | null, argTypes: string[] | und return fce; } -export function init_c_exports(): void { +export function init_c_exports (): void { const fns = [...fn_signatures]; for (const sig of fns) { const wf: any = wrapped_c_functions; diff --git a/src/mono/browser/runtime/debug.ts b/src/mono/browser/runtime/debug.ts index 1cbe85aff718ac..0e880cc110c6d9 100644 --- a/src/mono/browser/runtime/debug.ts +++ b/src/mono/browser/runtime/debug.ts @@ -1,15 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals"; -import { toBase64StringImpl } from "./base64"; +import {INTERNAL, Module, loaderHelpers, runtimeHelpers} from "./globals"; +import {toBase64StringImpl} from "./base64"; import cwraps from "./cwraps"; -import { VoidPtr, CharPtr } from "./types/emscripten"; -import { mono_log_warn } from "./logging"; -import { forceThreadMemoryViewRefresh, localHeapViewU8 } from "./memory"; -import { utf8ToString } from "./strings"; +import {VoidPtr, CharPtr} from "./types/emscripten"; +import {mono_log_warn} from "./logging"; +import {forceThreadMemoryViewRefresh, localHeapViewU8} from "./memory"; +import {utf8ToString} from "./strings"; const commands_received: any = new Map(); -commands_received.remove = function (key: number): CommandResponse { const value = this.get(key); this.delete(key); return value; }; +commands_received.remove = function (key: number): CommandResponse { + const value = this.get(key); this.delete(key); return value; +}; let _call_function_res_cache: any = {}; let _next_call_function_res_id = 0; let _debugger_buffer_len = -1; @@ -17,7 +19,7 @@ let _debugger_buffer: VoidPtr; let _assembly_name_str: string; //keep this variable, it's used by BrowserDebugProxy let _entrypoint_method_token: number; //keep this variable, it's used by BrowserDebugProxy -export function mono_wasm_runtime_ready(): void { +export function mono_wasm_runtime_ready (): void { INTERNAL.mono_wasm_runtime_is_ready = runtimeHelpers.mono_wasm_runtime_is_ready = true; // FIXME: where should this go? @@ -31,7 +33,7 @@ export function mono_wasm_runtime_ready(): void { debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String: string): void { +export function mono_wasm_fire_debugger_agent_message_with_data_to_pause (base64String: string): void { //keep this console.assert, otherwise optimization will remove the assignments // eslint-disable-next-line no-console console.assert(true, `mono_wasm_fire_debugger_agent_message_with_data ${base64String}`); @@ -39,12 +41,12 @@ export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64S debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data(data: number, len: number): void { +export function mono_wasm_fire_debugger_agent_message_with_data (data: number, len: number): void { const base64String = toBase64StringImpl(new Uint8Array(localHeapViewU8().buffer, data, len)); mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String); } -export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number, buffer: number, buffer_len: number): void { +export function mono_wasm_add_dbg_command_received (res_ok: boolean, id: number, buffer: number, buffer_len: number): void { const dbg_command = new Uint8Array(localHeapViewU8().buffer, buffer, buffer_len); const base64String = toBase64StringImpl(dbg_command); const buffer_obj = { @@ -59,7 +61,7 @@ export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number, commands_received.set(id, buffer_obj); } -function mono_wasm_malloc_and_set_debug_buffer(command_parameters: string) { +function mono_wasm_malloc_and_set_debug_buffer (command_parameters: string) { if (command_parameters.length > _debugger_buffer_len) { if (_debugger_buffer) Module._free(_debugger_buffer); @@ -73,25 +75,25 @@ function mono_wasm_malloc_and_set_debug_buffer(command_parameters: string) { } } -export function mono_wasm_send_dbg_command_with_parms(id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { +export function mono_wasm_send_dbg_command_with_parms (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); cwraps.mono_wasm_send_dbg_command_with_parms(id, command_set, command, _debugger_buffer, length, valtype, newvalue.toString()); - const { res_ok, res } = commands_received.remove(id); + const {res_ok, res} = commands_received.remove(id); if (!res_ok) throw new Error("Failed on mono_wasm_send_dbg_command_with_parms"); return res; } -export function mono_wasm_send_dbg_command(id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { +export function mono_wasm_send_dbg_command (id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); cwraps.mono_wasm_send_dbg_command(id, command_set, command, _debugger_buffer, command_parameters.length); - const { res_ok, res } = commands_received.remove(id); + const {res_ok, res} = commands_received.remove(id); if (!res_ok) throw new Error("Failed on mono_wasm_send_dbg_command"); @@ -99,24 +101,24 @@ export function mono_wasm_send_dbg_command(id: number, command_set: number, comm } -export function mono_wasm_get_dbg_command_info(): CommandResponseResult { - const { res_ok, res } = commands_received.remove(0); +export function mono_wasm_get_dbg_command_info (): CommandResponseResult { + const {res_ok, res} = commands_received.remove(0); if (!res_ok) throw new Error("Failed on mono_wasm_get_dbg_command_info"); return res; } -export function mono_wasm_debugger_resume(): void { +export function mono_wasm_debugger_resume (): void { forceThreadMemoryViewRefresh(); } -export function mono_wasm_detach_debugger(): void { +export function mono_wasm_detach_debugger (): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(false); } -export function mono_wasm_change_debugger_log_level(level: number): void { +export function mono_wasm_change_debugger_log_level (level: number): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_change_debugger_log_level(level); } @@ -124,7 +126,7 @@ export function mono_wasm_change_debugger_log_level(level: number): void { /** * Raises an event for the debug proxy */ -export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void { +export function mono_wasm_raise_debug_event (event: WasmEvent, args = {}): void { if (typeof event !== "object") throw new Error(`event must be an object, but got ${JSON.stringify(event)}`); @@ -138,7 +140,7 @@ export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void { console.debug("mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae", JSON.stringify(event), JSON.stringify(args)); } -export function mono_wasm_wait_for_debugger(): Promise { +export function mono_wasm_wait_for_debugger (): Promise { return new Promise((resolve) => { const interval = setInterval(() => { if (runtimeHelpers.waitForDebugger != 1) { @@ -150,14 +152,14 @@ export function mono_wasm_wait_for_debugger(): Promise { }); } -export function mono_wasm_debugger_attached(): void { +export function mono_wasm_debugger_attached (): void { if (runtimeHelpers.waitForDebugger == -1) runtimeHelpers.waitForDebugger = 1; forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(true); } -export function mono_wasm_set_entrypoint_breakpoint(entrypoint_method_token: number): void { +export function mono_wasm_set_entrypoint_breakpoint (entrypoint_method_token: number): void { //keep these assignments, these values are used by BrowserDebugProxy _assembly_name_str = loaderHelpers.config.mainAssemblyName + ".dll"; _entrypoint_method_token = entrypoint_method_token; @@ -170,7 +172,7 @@ export function mono_wasm_set_entrypoint_breakpoint(entrypoint_method_token: num forceThreadMemoryViewRefresh(); } -function _create_proxy_from_object_id(objectId: string, details: any) { +function _create_proxy_from_object_id (objectId: string, details: any) { if (objectId.startsWith("dotnet:array:")) { let ret: Array; if (details.items === undefined) { @@ -190,7 +192,7 @@ function _create_proxy_from_object_id(objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get() { + get () { return mono_wasm_send_dbg_command(prop.get.id, prop.get.commandSet, prop.get.command, prop.get.buffer); }, set: function (newValue) { @@ -202,7 +204,7 @@ function _create_proxy_from_object_id(objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get() { + get () { return prop.value; }, set: function (newValue) { @@ -217,7 +219,7 @@ function _create_proxy_from_object_id(objectId: string, details: any) { return proxy; } -export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { +export function mono_wasm_call_function_on (request: CallRequest): CFOResponse { forceThreadMemoryViewRefresh(); if (request.arguments != undefined && !Array.isArray(request.arguments)) @@ -243,16 +245,16 @@ export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { const fn_res = fn_defn(proxy); if (fn_res === undefined) - return { type: "undefined" }; + return {type: "undefined"}; if (Object(fn_res) !== fn_res) { if (typeof (fn_res) == "object" && fn_res == null) - return { type: typeof (fn_res), subtype: `${fn_res}`, value: null }; - return { type: typeof (fn_res), description: `${fn_res}`, value: `${fn_res}` }; + return {type: typeof (fn_res), subtype: `${fn_res}`, value: null}; + return {type: typeof (fn_res), description: `${fn_res}`, value: `${fn_res}`}; } if (request.returnByValue && fn_res.subtype == undefined) - return { type: "object", value: fn_res }; + return {type: "object", value: fn_res}; if (Object.getPrototypeOf(fn_res) == Array.prototype) { @@ -271,12 +273,12 @@ export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { } if (fn_res == proxy) - return { type: "object", className: "Object", description: "Object", objectId: objId }; + return {type: "object", className: "Object", description: "Object", objectId: objId}; const fn_res_id = _cache_call_function_res(fn_res); - return { type: "object", className: "Object", description: "Object", objectId: fn_res_id }; + return {type: "object", className: "Object", description: "Object", objectId: fn_res_id}; } -function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { +function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { if (!(objectId in _call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); @@ -297,7 +299,7 @@ function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { if (typeof prop_desc.value == "object") { // convert `{value: { type='object', ... }}` // to `{ name: 'foo', value: { type='object', ... }} - new_obj = Object.assign({ name: k }, prop_desc); + new_obj = Object.assign({name: k}, prop_desc); } else if (prop_desc.value !== undefined) { // This is needed for values that were not added by us, // thus are like { value: 5 } @@ -308,7 +310,7 @@ function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { new_obj = { name: k, // merge/add `type` and `description` to `d.value` - value: Object.assign({ type: (typeof prop_desc.value), description: "" + prop_desc.value }, + value: Object.assign({type: (typeof prop_desc.value), description: "" + prop_desc.value}, prop_desc) }; } else if (prop_desc.get !== undefined) { @@ -325,36 +327,36 @@ function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { } }; } else { - new_obj = { name: k, value: { type: "symbol", value: "", description: "" } }; + new_obj = {name: k, value: {type: "symbol", value: "", description: ""}}; } res_details.push(new_obj); }); - return { __value_as_json_string__: JSON.stringify(res_details) }; + return {__value_as_json_string__: JSON.stringify(res_details)}; } type ValueAsJsonString = { __value_as_json_string__: string; } -export function mono_wasm_get_details(objectId: string, args = {}): ValueAsJsonString { +export function mono_wasm_get_details (objectId: string, args = {}): ValueAsJsonString { forceThreadMemoryViewRefresh(); return _get_cfo_res_details(`dotnet:cfo_res:${objectId}`, args); } -function _cache_call_function_res(obj: any) { +function _cache_call_function_res (obj: any) { const id = `dotnet:cfo_res:${_next_call_function_res_id++}`; _call_function_res_cache[id] = obj; return id; } -export function mono_wasm_release_object(objectId: string): void { +export function mono_wasm_release_object (objectId: string): void { if (objectId in _call_function_res_cache) delete _call_function_res_cache[objectId]; } -export function mono_wasm_debugger_log(level: number, message_ptr: CharPtr): void { +export function mono_wasm_debugger_log (level: number, message_ptr: CharPtr): void { forceThreadMemoryViewRefresh(); const message = utf8ToString(message_ptr); diff --git a/src/mono/browser/runtime/diagnostics-mock.d.ts b/src/mono/browser/runtime/diagnostics-mock.d.ts index 59686e8797399e..9ccb36762982d2 100644 --- a/src/mono/browser/runtime/diagnostics-mock.d.ts +++ b/src/mono/browser/runtime/diagnostics-mock.d.ts @@ -3,7 +3,7 @@ //! //! This is generated file, see src/mono/wasm/runtime/rollup.config.js -//! This is not considered public API with backward compatibility guarantees. +//! This is not considered public API with backward compatibility guarantees. interface PromiseController { isDone: boolean; @@ -71,4 +71,4 @@ interface MockEnvironment { expectAdvertise: FilterPredicate; } -export { MockEnvironment, MockScriptConnection, PromiseAndController }; +export {MockEnvironment, MockScriptConnection, PromiseAndController}; diff --git a/src/mono/browser/runtime/diagnostics/browser/controller.ts b/src/mono/browser/runtime/diagnostics/browser/controller.ts index 799972b1fd0e66..948c92d9141602 100644 --- a/src/mono/browser/runtime/diagnostics/browser/controller.ts +++ b/src/mono/browser/runtime/diagnostics/browser/controller.ts @@ -3,14 +3,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { threads_c_functions as cwraps } from "../../cwraps"; -import { INTERNAL, mono_assert } from "../../globals"; -import { mono_log_info, mono_log_debug, mono_log_warn } from "../../logging"; -import { withStackAlloc, getI32 } from "../../memory"; -import { waitForThread } from "../../pthreads"; -import { isDiagnosticMessage, makeDiagnosticServerControlCommand } from "../shared/controller-commands"; +import {threads_c_functions as cwraps} from "../../cwraps"; +import {INTERNAL, mono_assert} from "../../globals"; +import {mono_log_info, mono_log_debug, mono_log_warn} from "../../logging"; +import {withStackAlloc, getI32} from "../../memory"; +import {waitForThread} from "../../pthreads"; +import {isDiagnosticMessage, makeDiagnosticServerControlCommand} from "../shared/controller-commands"; import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import { PThreadPtr, Thread } from "../../types/internal"; +import {PThreadPtr, Thread} from "../../types/internal"; /// An object that can be used to control the diagnostic server. export interface ServerController { @@ -18,23 +18,23 @@ export interface ServerController { } class ServerControllerImpl implements ServerController { - constructor(private server: Thread) { + constructor (private server: Thread) { server.port.addEventListener("message", this.onServerReply.bind(this)); } - start(): void { + start (): void { mono_log_debug("signaling the diagnostic server to start"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("start")); } - stop(): void { + stop (): void { mono_log_debug("signaling the diagnostic server to stop"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("stop")); } - postServerAttachToRuntime(): void { + postServerAttachToRuntime (): void { mono_log_debug("signal the diagnostic server to attach to the runtime"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("attach_to_runtime")); } - onServerReply(event: MessageEvent): void { + onServerReply (event: MessageEvent): void { const d = event.data; if (isDiagnosticMessage(d)) { switch (d.cmd) { @@ -48,13 +48,13 @@ class ServerControllerImpl implements ServerController { let serverController: ServerController | null = null; -export function getController(): ServerController { +export function getController (): ServerController { if (serverController) return serverController; throw new Error("unexpected no server controller"); } -export async function startDiagnosticServer(websocket_url: string): Promise { +export async function startDiagnosticServer (websocket_url: string): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const sizeOfPthreadT = 4; mono_log_info(`starting the diagnostic server url: ${websocket_url}`); diff --git a/src/mono/browser/runtime/diagnostics/index.ts b/src/mono/browser/runtime/diagnostics/index.ts index a9d6f9414267ae..e7b12703657ff7 100644 --- a/src/mono/browser/runtime/diagnostics/index.ts +++ b/src/mono/browser/runtime/diagnostics/index.ts @@ -6,16 +6,16 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import type { DiagnosticOptions, } from "./shared/types"; -import { is_nullish } from "../types/internal"; -import type { VoidPtr } from "../types/emscripten"; -import { getController, startDiagnosticServer } from "./browser/controller"; +import {is_nullish} from "../types/internal"; +import type {VoidPtr} from "../types/emscripten"; +import {getController, startDiagnosticServer} from "./browser/controller"; import * as memory from "../memory"; -import { mono_log_warn } from "../logging"; -import { mono_assert, runtimeHelpers } from "../globals"; +import {mono_log_warn} from "../logging"; +import {mono_assert, runtimeHelpers} from "../globals"; // called from C on the main thread -export function mono_wasm_event_pipe_early_startup_callback(): void { +export function mono_wasm_event_pipe_early_startup_callback (): void { if (WasmEnableThreads) { return; } @@ -36,7 +36,7 @@ let diagnosticsServerEnabled = false; let diagnosticsInitialized = false; -export async function mono_wasm_init_diagnostics(): Promise { +export async function mono_wasm_init_diagnostics (): Promise { if (!WasmEnableThreads) return; if (diagnosticsInitialized) return; @@ -60,7 +60,7 @@ export async function mono_wasm_init_diagnostics(): Promise { } } -function boolsyOption(x: string | boolean): boolean { +function boolsyOption (x: string | boolean): boolean { if (x === true || x === false) return x; if (typeof x === "string") { @@ -77,7 +77,7 @@ function boolsyOption(x: string | boolean): boolean { /// The environment variables are: /// * DOTNET_DiagnosticPorts /// -function diagnostic_options_from_environment(): DiagnosticOptions | null { +function diagnostic_options_from_environment (): DiagnosticOptions | null { const val = runtimeHelpers.config.environmentVariables ? runtimeHelpers.config.environmentVariables["DOTNET_DiagnosticPorts"] : undefined; if (is_nullish(val)) return null; @@ -88,7 +88,7 @@ function diagnostic_options_from_environment(): DiagnosticOptions | null { /// Parse a DOTNET_DiagnosticPorts string and return a DiagnosticOptions object. /// See https://docs.microsoft.com/en-us/dotnet/core/diagnostics/diagnostic-port#configure-additional-diagnostic-ports -function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | null { +function diagnostic_options_from_ports_spec (val: string): DiagnosticOptions | null { if (val === "") return null; const ports = val.split(";"); @@ -140,7 +140,7 @@ function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | nu } -export function mono_wasm_diagnostic_server_on_runtime_server_init(out_options: VoidPtr): void { +export function mono_wasm_diagnostic_server_on_runtime_server_init (out_options: VoidPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); if (diagnosticsServerEnabled) { /* called on the main thread when the runtime is sufficiently initialized */ diff --git a/src/mono/browser/runtime/diagnostics/mock/environment.ts b/src/mono/browser/runtime/diagnostics/mock/environment.ts index 0de8c8b7acafc2..b266042bb470c1 100644 --- a/src/mono/browser/runtime/diagnostics/mock/environment.ts +++ b/src/mono/browser/runtime/diagnostics/mock/environment.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { RemoveCommandSetAndId, EventPipeCommandCollectTracing2, EventPipeCommandStopTracing } from "../server_pthread/protocol-client-commands"; -import type { FilterPredicate, MockEnvironment } from "./types"; +import type {RemoveCommandSetAndId, EventPipeCommandCollectTracing2, EventPipeCommandStopTracing} from "../server_pthread/protocol-client-commands"; +import type {FilterPredicate, MockEnvironment} from "./types"; import Serializer from "../server_pthread/ipc-protocol/base-serializer"; -import { CommandSetId, EventPipeCommandId, ProcessCommandId } from "../server_pthread/ipc-protocol/types"; -import { assertNever } from "../../types/internal"; -import { pthread_self } from "../../pthreads"; -import { createPromiseController, mono_assert } from "../../globals"; +import {CommandSetId, EventPipeCommandId, ProcessCommandId} from "../server_pthread/ipc-protocol/types"; +import {assertNever} from "../../types/internal"; +import {pthread_self} from "../../pthreads"; +import {createPromiseController, mono_assert} from "../../globals"; -function expectAdvertise(data: ArrayBuffer): boolean { +function expectAdvertise (data: ArrayBuffer): boolean { if (typeof (data) === "string") { assertNever(data); } else { @@ -21,7 +21,7 @@ function expectAdvertise(data: ArrayBuffer): boolean { } } -function expectOk(payloadLength?: number): FilterPredicate { +function expectOk (payloadLength?: number): FilterPredicate { return (data) => { if (typeof (data) === "string") { assertNever(data); @@ -33,7 +33,7 @@ function expectOk(payloadLength?: number): FilterPredicate { }; } -function extractOkSessionID(data: ArrayBuffer): number { +function extractOkSessionID (data: ArrayBuffer): number { if (typeof (data) === "string") { assertNever(data); } else { @@ -45,13 +45,13 @@ function extractOkSessionID(data: ArrayBuffer): number { } } -function computeStringByteLength(s: string | null): number { +function computeStringByteLength (s: string | null): number { if (s === undefined || s === null || s === "") return 4; // just length of zero return 4 + 2 * s.length + 2; // length + UTF16 + null } -function computeCollectTracing2PayloadByteLength(payload: RemoveCommandSetAndId): number { +function computeCollectTracing2PayloadByteLength (payload: RemoveCommandSetAndId): number { let len = 0; len += 4; // circularBufferMB len += 4; // format @@ -66,11 +66,11 @@ function computeCollectTracing2PayloadByteLength(payload: RemoveCommandSetAndId< return len; } -function makeEventPipeCollectTracing2(payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeCollectTracing2 (payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = computeCollectTracing2PayloadByteLength(payload); const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = { pos: 0 }; + const pos = {pos: 0}; Serializer.serializeHeader(buffer, pos, CommandSetId.EventPipe, EventPipeCommandId.CollectTracing2, messageLength); Serializer.serializeUint32(buffer, pos, payload.circularBufferMB); Serializer.serializeUint32(buffer, pos, payload.format); @@ -85,40 +85,40 @@ function makeEventPipeCollectTracing2(payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeStopTracing (payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = 8; const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = { pos: 0 }; + const pos = {pos: 0}; Serializer.serializeHeader(buffer, pos, CommandSetId.EventPipe, EventPipeCommandId.StopTracing, messageLength); Serializer.serializeUint32(buffer, pos, payload.sessionID); Serializer.serializeUint32(buffer, pos, 0); return buffer; } -function makeProcessResumeRuntime(): Uint8Array { +function makeProcessResumeRuntime (): Uint8Array { const payloadLength = 0; const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = { pos: 0 }; + const pos = {pos: 0}; Serializer.serializeHeader(buffer, pos, CommandSetId.Process, ProcessCommandId.ResumeRuntime, messageLength); return buffer; } -function postMessageToBrowser(message: any, transferable?: Transferable[]): void { +function postMessageToBrowser (message: any, transferable?: Transferable[]): void { pthread_self.postMessageToBrowser({ type: "diagnostic_server_mock", ...message }, transferable); } -function addEventListenerFromBrowser(cmd: string, listener: (data: any) => void) { +function addEventListenerFromBrowser (cmd: string, listener: (data: any) => void) { pthread_self.addEventListenerFromBrowser((event) => { if (event.data.cmd === cmd) listener(event.data); }); } -export function createMockEnvironment(): MockEnvironment { +export function createMockEnvironment (): MockEnvironment { const command = { makeEventPipeCollectTracing2, makeEventPipeStopTracing, diff --git a/src/mono/browser/runtime/diagnostics/mock/index.ts b/src/mono/browser/runtime/diagnostics/mock/index.ts index 81304154071332..e5928ecef7d41e 100644 --- a/src/mono/browser/runtime/diagnostics/mock/index.ts +++ b/src/mono/browser/runtime/diagnostics/mock/index.ts @@ -3,10 +3,10 @@ import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import { createMockEnvironment } from "./environment"; -import type { MockEnvironment, MockScriptConnection } from "./export-types"; -import { assertNever } from "../../types/internal"; -import { mono_log_debug, mono_log_warn } from "../../logging"; +import {createMockEnvironment} from "./environment"; +import type {MockEnvironment, MockScriptConnection} from "./export-types"; +import {assertNever} from "../../types/internal"; +import {mono_log_debug, mono_log_warn} from "../../logging"; export interface MockRemoteSocket extends EventTarget { addEventListener(type: T, listener: (this: MockRemoteSocket, ev: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void; @@ -25,39 +25,39 @@ type MockConnectionScript = (engine: MockScriptConnection) => Promise; export type MockScript = (env: MockEnvironment) => MockConnectionScript[]; let MockImplConstructor: new (script: MockScript) => Mock; -export function mock(script: MockScript): Mock { +export function mock (script: MockScript): Mock { if (monoDiagnosticsMock) { if (!MockImplConstructor) { class MockScriptEngineSocketImpl implements MockRemoteSocket { - constructor(private readonly engine: MockScriptEngineImpl) { } - send(data: string | ArrayBuffer): void { + constructor (private readonly engine: MockScriptEngineImpl) { } + send (data: string | ArrayBuffer): void { mono_log_debug(`mock ${this.engine.ident} client sent: `, data); let event: MessageEvent | null = null; if (typeof data === "string") { - event = new MessageEvent("message", { data }); + event = new MessageEvent("message", {data}); } else { const message = new ArrayBuffer(data.byteLength); const messageView = new Uint8Array(message); const dataView = new Uint8Array(data); messageView.set(dataView); - event = new MessageEvent("message", { data: message }); + event = new MessageEvent("message", {data: message}); } this.engine.mockReplyEventTarget.dispatchEvent(event); } addEventListener(event: T, listener: (event: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { + addEventListener (event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { mono_log_debug(`mock ${this.engine.ident} client added listener for ${event}`); this.engine.eventTarget.addEventListener(event, listener, options); } - removeEventListener(event: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener (event: string, listener: EventListenerOrEventListenerObject): void { mono_log_debug(`mock ${this.engine.ident} client removed listener for ${event}`); this.engine.eventTarget.removeEventListener(event, listener); } - close(): void { + close (): void { mono_log_debug(`mock ${this.engine.ident} client closed`); this.engine.mockReplyEventTarget.dispatchEvent(new CloseEvent("close")); } - dispatchEvent(ev: Event): boolean { + dispatchEvent (ev: Event): boolean { return this.engine.eventTarget.dispatchEvent(ev); } } @@ -68,11 +68,11 @@ export function mock(script: MockScript): Mock { readonly eventTarget: EventTarget = new EventTarget(); // eventTarget that the MockReplySocket with send() to readonly mockReplyEventTarget: EventTarget = new EventTarget(); - constructor(readonly ident: number) { + constructor (readonly ident: number) { this.socket = new MockScriptEngineSocketImpl(this); } - reply(data: ArrayBuffer | Uint8Array) { + reply (data: ArrayBuffer | Uint8Array) { mono_log_debug(`mock ${this.ident} reply:`, data); let sendData: ArrayBuffer; if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -88,10 +88,10 @@ export function mock(script: MockScript): Mock { mono_log_warn(`mock ${this.ident} reply got wrong kind of reply data, expected ArrayBuffer`, data); assertNever(data); } - this.eventTarget.dispatchEvent(new MessageEvent("message", { data: sendData })); + this.eventTarget.dispatchEvent(new MessageEvent("message", {data: sendData})); } - processSend(onMessage: (data: ArrayBuffer) => any): Promise { + processSend (onMessage: (data: ArrayBuffer) => any): Promise { mono_log_debug(`mock ${this.ident} processSend`); return new Promise((resolve, reject) => { @@ -112,7 +112,7 @@ export function mock(script: MockScript): Mock { }); } - async waitForSend(filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { + async waitForSend (filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { mono_log_debug(`mock ${this.ident} waitForSend`); const data = await new Promise((resolve) => { @@ -125,7 +125,7 @@ export function mock(script: MockScript): Mock { mono_log_debug(`mock ${this.ident} waitForSend got:`, data.byteLength); resolve(data); - }, { once: true }); + }, {once: true}); }); if (!filter(data)) { throw new Error("Unexpected data"); @@ -141,7 +141,7 @@ export function mock(script: MockScript): Mock { openCount: number; engines: MockScriptEngineImpl[]; connectionScripts: MockConnectionScript[]; - constructor(public readonly mockScript: MockScript) { + constructor (public readonly mockScript: MockScript) { const env: MockEnvironment = createMockEnvironment(); this.connectionScripts = mockScript(env); this.openCount = 0; @@ -151,13 +151,13 @@ export function mock(script: MockScript): Mock { this.engines[i] = new MockScriptEngineImpl(i); } } - open(): MockRemoteSocket { + open (): MockRemoteSocket { const i = this.openCount++; mono_log_debug(`mock ${i} open`); return this.engines[i].socket; } - async run(): Promise { + async run (): Promise { const scripts = this.connectionScripts; await Promise.all(scripts.map((script, i) => script(this.engines[i]))); } diff --git a/src/mono/browser/runtime/diagnostics/mock/types.ts b/src/mono/browser/runtime/diagnostics/mock/types.ts index 30c533595413c0..8a2fa4bacfb15c 100644 --- a/src/mono/browser/runtime/diagnostics/mock/types.ts +++ b/src/mono/browser/runtime/diagnostics/mock/types.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. -import type { PromiseAndController } from "../../types/internal"; +import type {PromiseAndController} from "../../types/internal"; import type { RemoveCommandSetAndId, EventPipeCommandCollectTracing2, diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts index b6bb8084a26845..e1b6b7222c0470 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.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. -import { MockRemoteSocket } from "../mock"; +import {MockRemoteSocket} from "../mock"; // the common bits that we depend on from a real WebSocket or a MockRemoteSocket used for testing export interface CommonSocket { @@ -17,7 +17,7 @@ export interface CommonSocket { type AssignableTo = Q extends T ? true : false; -function static_assert(x: Cond): asserts x is Cond { /*empty*/ } +function static_assert (x: Cond): asserts x is Cond { /*empty*/ } { static_assert>(true); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts index cba9d5fba7d8dc..a499c4395233e9 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts @@ -5,19 +5,19 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import { PromiseAndController, assertNever } from "../../types/internal"; -import { pthread_self } from "../../pthreads"; -import { createPromiseController, mono_assert } from "../../globals"; -import { threads_c_functions as cwraps } from "../../cwraps"; -import { EventPipeSessionIDImpl } from "../shared/types"; -import { CharPtr } from "../../types/emscripten"; +import {PromiseAndController, assertNever} from "../../types/internal"; +import {pthread_self} from "../../pthreads"; +import {createPromiseController, mono_assert} from "../../globals"; +import {threads_c_functions as cwraps} from "../../cwraps"; +import {EventPipeSessionIDImpl} from "../shared/types"; +import {CharPtr} from "../../types/emscripten"; import { DiagnosticServerControlCommand, isDiagnosticMessage } from "../shared/controller-commands"; -import { importAndInstantiateMock } from "./mock-remote"; -import type { Mock, MockRemoteSocket } from "../mock"; +import {importAndInstantiateMock} from "./mock-remote"; +import type {Mock, MockRemoteSocket} from "../mock"; import { isEventPipeCommand, isProcessCommand, @@ -29,8 +29,8 @@ import { isProcessCommandResumeRuntime, EventPipeCommandCollectTracing2, } from "./protocol-client-commands"; -import { makeEventPipeStreamingSession } from "./streaming-session"; -import { CommonSocket } from "./common-socket"; +import {makeEventPipeStreamingSession} from "./streaming-session"; +import {CommonSocket} from "./common-socket"; import { createProtocolSocket, dotnetDiagnosticsServerProtocolCommandEvent, ProtocolCommandEvent, @@ -47,20 +47,24 @@ import { createAdvertise, createBinaryCommandOKReply, } from "./ipc-protocol/serializer"; -import { mono_log_error, mono_log_info, mono_log_debug, mono_log_warn } from "../../logging"; -import { utf8ToString } from "../../strings"; +import {mono_log_error, mono_log_info, mono_log_debug, mono_log_warn} from "../../logging"; +import {utf8ToString} from "../../strings"; -function addOneShotProtocolCommandEventListener(src: EventTarget): Promise { +function addOneShotProtocolCommandEventListener (src: EventTarget): Promise { return new Promise((resolve) => { - const listener = (event: Event) => { resolve(event as ProtocolCommandEvent); }; - src.addEventListener(dotnetDiagnosticsServerProtocolCommandEvent, listener, { once: true }); + const listener = (event: Event) => { + resolve(event as ProtocolCommandEvent); + }; + src.addEventListener(dotnetDiagnosticsServerProtocolCommandEvent, listener, {once: true}); }); } -function addOneShotOpenEventListenr(src: EventTarget): Promise { +function addOneShotOpenEventListenr (src: EventTarget): Promise { return new Promise((resolve) => { - const listener = (event: Event) => { resolve(event); }; - src.addEventListener("open", listener, { once: true }); + const listener = (event: Event) => { + resolve(event); + }; + src.addEventListener("open", listener, {once: true}); }); } @@ -73,7 +77,7 @@ class DiagnosticServerImpl implements DiagnosticServer { readonly mocked: Promise | undefined; runtimeResumed = false; - constructor(websocketUrl: string, mockPromise?: Promise) { + constructor (websocketUrl: string, mockPromise?: Promise) { this.websocketUrl = websocketUrl; pthread_self.addEventListenerFromBrowser(this.onMessageFromMainThread.bind(this)); this.mocked = monoDiagnosticsMock ? mockPromise : undefined; @@ -85,21 +89,21 @@ class DiagnosticServerImpl implements DiagnosticServer { private attachToRuntimeController = createPromiseController().promise_control; - start(): void { + start (): void { mono_log_info(`starting diagnostic server with url: ${this.websocketUrl}`); this.startRequestedController.resolve(); } - stop(): void { + stop (): void { this.stopRequested = true; this.stopRequestedController.resolve(); } - attachToRuntime(): void { + attachToRuntime (): void { cwraps.mono_wasm_diagnostic_server_thread_attach_to_runtime(); this.attachToRuntimeController.resolve(); } - async serverLoop(this: DiagnosticServerImpl): Promise { + async serverLoop (this: DiagnosticServerImpl): Promise { await this.startRequestedController.promise; await this.attachToRuntimeController.promise; // can't start tracing until we've attached to the runtime while (!this.stopRequested) { @@ -119,7 +123,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async openSocket(): Promise { + async openSocket (): Promise { if (monoDiagnosticsMock && this.mocked) { return (await this.mocked).open(); } else { @@ -132,7 +136,7 @@ class DiagnosticServerImpl implements DiagnosticServer { private openCount = 0; - async advertiseAndWaitForClient(): Promise { + async advertiseAndWaitForClient (): Promise { try { const connNum = this.openCount++; mono_log_debug("opening websocket and sending ADVR_V1", connNum); @@ -148,7 +152,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async parseAndDispatchMessage(ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { + async parseAndDispatchMessage (ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { try { const cmd = this.parseCommand(message, connNum); if (cmd === null) { @@ -167,7 +171,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - sendAdvertise(ws: CommonSocket) { + sendAdvertise (ws: CommonSocket) { /* FIXME: don't use const fake guid and fake process id. In dotnet-dsrouter the pid is used * as a dictionary key,so if we ever supprt multiple runtimes, this might need to change. */ @@ -178,7 +182,7 @@ class DiagnosticServerImpl implements DiagnosticServer { ws.send(buf); } - parseCommand(message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { + parseCommand (message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { mono_log_debug("parsing byte command: ", message.data, connNum); const result = parseProtocolCommand(message.data); mono_log_debug("parsed byte command: ", result, connNum); @@ -190,7 +194,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - onMessageFromMainThread(this: DiagnosticServerImpl, event: MessageEvent): void { + onMessageFromMainThread (this: DiagnosticServerImpl, event: MessageEvent): void { const d = event.data; if (d && isDiagnosticMessage(d)) { this.controlCommandReceived(d as DiagnosticServerControlCommand); @@ -198,7 +202,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } /// dispatch commands received from the main thread - controlCommandReceived(cmd: DiagnosticServerControlCommand): void { + controlCommandReceived (cmd: DiagnosticServerControlCommand): void { switch (cmd.cmd) { case "start": this.start(); @@ -216,7 +220,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch EventPipe commands received from the diagnostic client - async dispatchEventPipeCommand(ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { + async dispatchEventPipeCommand (ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { if (isEventPipeCommandCollectTracing2(cmd)) { await this.collectTracingEventPipe(ws, cmd); } else if (isEventPipeCommandStopTracing(cmd)) { @@ -226,12 +230,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - postClientReplyOK(ws: CommonSocket, payload?: Uint8Array): void { + postClientReplyOK (ws: CommonSocket, payload?: Uint8Array): void { // FIXME: send a binary response for non-mock sessions! ws.send(createBinaryCommandOKReply(payload)); } - async stopEventPipe(ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { + async stopEventPipe (ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { mono_log_debug("stopEventPipe", sessionID); cwraps.mono_wasm_event_pipe_session_disable(sessionID); // we might send OK before the session is actually stopped since the websocket is async @@ -239,7 +243,7 @@ class DiagnosticServerImpl implements DiagnosticServer { this.postClientReplyOK(ws); } - async collectTracingEventPipe(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { + async collectTracingEventPipe (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { const session = await makeEventPipeStreamingSession(ws, cmd); const sessionIDbuf = new Uint8Array(8); // 64 bit sessionIDbuf[0] = session.sessionID & 0xFF; @@ -253,7 +257,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch Process commands received from the diagnostic client - async dispatchProcessCommand(ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { + async dispatchProcessCommand (ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { if (isProcessCommandResumeRuntime(cmd)) { this.processResumeRuntime(ws); } else { @@ -261,12 +265,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - processResumeRuntime(ws: WebSocket | MockRemoteSocket): void { + processResumeRuntime (ws: WebSocket | MockRemoteSocket): void { this.postClientReplyOK(ws); this.resumeRuntime(); } - resumeRuntime(): void { + resumeRuntime (): void { if (!this.runtimeResumed) { mono_log_debug("resuming runtime startup"); cwraps.mono_wasm_diagnostic_server_post_resume_runtime(); @@ -275,7 +279,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } -function parseProtocolCommand(data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { +function parseProtocolCommand (data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { if (isBinaryProtocolCommand(data)) { return parseBinaryProtocolCommand(data); } else { @@ -284,7 +288,7 @@ function parseProtocolCommand(data: ArrayBuffer | BinaryProtocolCommand): ParseC } /// Called by the runtime to initialize the diagnostic server workers -export function mono_wasm_diagnostic_server_on_server_thread_created(websocketUrlPtr: CharPtr): void { +export function mono_wasm_diagnostic_server_on_server_thread_created (websocketUrlPtr: CharPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const websocketUrl = utf8ToString(websocketUrlPtr); mono_log_debug(`mono_wasm_diagnostic_server_on_server_thread_created, url ${websocketUrl}`); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts index 2129fc76e601c7..fd9142f54b8a33 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. import Magic from "./magic"; -import { BinaryProtocolCommand } from "./types"; +import {BinaryProtocolCommand} from "./types"; -function advancePos(pos: { pos: number }, offset: number): void { +function advancePos (pos: { pos: number }, offset: number): void { pos.pos += offset; } const Parser = { - tryParseHeader(buf: Uint8Array, pos: { pos: number }): boolean { + tryParseHeader (buf: Uint8Array, pos: { pos: number }): boolean { let j = pos.pos; for (let i = 0; i < Magic.DOTNET_IPC_V1.length; i++) { if (buf[j++] !== Magic.DOTNET_IPC_V1[i]) { @@ -19,10 +19,10 @@ const Parser = { advancePos(pos, Magic.DOTNET_IPC_V1.length); return true; }, - tryParseSize(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseSize (buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseUint16(buf, pos); }, - tryParseCommand(buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { + tryParseCommand (buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { const commandSet = Parser.tryParseUint8(buf, pos); if (commandSet === undefined) return undefined; @@ -39,7 +39,7 @@ const Parser = { }; return result; }, - tryParseReserved(buf: Uint8Array, pos: { pos: number }): true | undefined { + tryParseReserved (buf: Uint8Array, pos: { pos: number }): true | undefined { const reservedLength = 2; // 2 bytes reserved, must be 0 for (let i = 0; i < reservedLength; i++) { const reserved = Parser.tryParseUint8(buf, pos); @@ -49,7 +49,7 @@ const Parser = { } return true; }, - tryParseUint8(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint8 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j >= buf.byteLength) { return undefined; @@ -58,7 +58,7 @@ const Parser = { advancePos(pos, 1); return size; }, - tryParseUint16(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint16 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 1 >= buf.byteLength) { return undefined; @@ -67,7 +67,7 @@ const Parser = { advancePos(pos, 2); return size; }, - tryParseUint32(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint32 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 3 >= buf.byteLength) { return undefined; @@ -76,7 +76,7 @@ const Parser = { advancePos(pos, 4); return size; }, - tryParseUint64(buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { + tryParseUint64 (buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { const lo = Parser.tryParseUint32(buf, pos); if (lo === undefined) return undefined; @@ -85,22 +85,22 @@ const Parser = { return undefined; return [lo, hi]; }, - tryParseBool(buf: Uint8Array, pos: { pos: number }): boolean | undefined { + tryParseBool (buf: Uint8Array, pos: { pos: number }): boolean | undefined { const r = Parser.tryParseUint8(buf, pos); if (r === undefined) return undefined; return r !== 0; }, - tryParseArraySize(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseArraySize (buf: Uint8Array, pos: { pos: number }): number | undefined { const r = Parser.tryParseUint32(buf, pos); if (r === undefined) return undefined; return r; }, - tryParseStringLength(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseStringLength (buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseArraySize(buf, pos); }, - tryParseUtf16String(buf: Uint8Array, pos: { pos: number }): string | undefined { + tryParseUtf16String (buf: Uint8Array, pos: { pos: number }): string | undefined { const length = Parser.tryParseStringLength(buf, pos); if (length === undefined) return undefined; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts index 09115d7245bc3b..0ba58ae96c3488 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { CommandSetId, ServerCommandId, EventPipeCommandId, ProcessCommandId } from "./types"; +import {CommandSetId, ServerCommandId, EventPipeCommandId, ProcessCommandId} from "./types"; import Magic from "./magic"; -function advancePos(pos: { pos: number }, count: number): void { +function advancePos (pos: { pos: number }, count: number): void { pos.pos += count; } @@ -12,7 +12,7 @@ function advancePos(pos: { pos: number }, count: number): void { function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.EventPipe, command: EventPipeCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Process, command: ProcessCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Server, command: ServerCommandId, len: number): void; -function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { +function serializeHeader (buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { Serializer.serializeMagic(buf, pos); Serializer.serializeUint16(buf, pos, len); Serializer.serializeUint8(buf, pos, commandSet); @@ -22,7 +22,7 @@ function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: Comm const Serializer = { - computeMessageByteLength(payload?: number | Uint8Array): number { + computeMessageByteLength (payload?: number | Uint8Array): number { const fullHeaderSize = Magic.MinimalHeaderSize // magic, len + 2 // commandSet, command + 2; // reserved ; @@ -30,33 +30,33 @@ const Serializer = { const len = fullHeaderSize + payloadLength; // magic, size, commandSet, command, reserved return len; }, - serializeMagic(buf: Uint8Array, pos: { pos: number }): void { + serializeMagic (buf: Uint8Array, pos: { pos: number }): void { buf.set(Magic.DOTNET_IPC_V1, pos.pos); advancePos(pos, Magic.DOTNET_IPC_V1.byteLength); }, - serializeUint8(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint8 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value; }, - serializeUint16(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint16 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; }, - serializeUint32(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint32 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; buf[pos.pos++] = (value >> 16) & 0xFF; buf[pos.pos++] = (value >> 24) & 0xFF; }, - serializeUint64(buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { + serializeUint64 (buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { Serializer.serializeUint32(buf, pos, value[0]); Serializer.serializeUint32(buf, pos, value[1]); }, serializeHeader, - serializePayload(buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { + serializePayload (buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { buf.set(payload, pos.pos); advancePos(pos, payload.byteLength); }, - serializeString(buf: Uint8Array, pos: { pos: number }, s: string | null): void { + serializeString (buf: Uint8Array, pos: { pos: number }, s: string | null): void { if (s === null || s === undefined || s === "") { Serializer.serializeUint32(buf, pos, 0); } else { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts index e7f27b9c6ab1f2..9d98130bf84c2d 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts @@ -3,7 +3,7 @@ let magic_buf: Uint8Array = null!; const Magic = { - get DOTNET_IPC_V1(): Uint8Array { + get DOTNET_IPC_V1 (): Uint8Array { if (magic_buf === null) { const magic = "DOTNET_IPC_V1"; const magic_len = magic.length + 1; // nul terminated @@ -15,7 +15,7 @@ const Magic = { } return magic_buf; }, - get MinimalHeaderSize(): number { + get MinimalHeaderSize (): number { // we just need to see the magic and the size const sizeOfSize = 2; return Magic.DOTNET_IPC_V1.byteLength + sizeOfSize; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts index 765e16718c9533..a3720f25f3c541 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts @@ -19,7 +19,7 @@ import { EventPipeCommandId, ProcessCommandId, } from "./types"; -import { mono_log_warn } from "../../../logging"; +import {mono_log_warn} from "../../../logging"; interface ParseClientCommandResultOk extends ParseResultOk { readonly result: C; @@ -27,7 +27,7 @@ interface ParseClientCommandResultOk extends Pars export type ParseClientCommandResult = ParseClientCommandResultOk | ParseResultFail; -export function parseBinaryProtocolCommand(cmd: BinaryProtocolCommand): ParseClientCommandResult { +export function parseBinaryProtocolCommand (cmd: BinaryProtocolCommand): ParseClientCommandResult { switch (cmd.commandSet) { case CommandSetId.Reserved: throw new Error("unexpected reserved command_set command"); @@ -40,11 +40,11 @@ export function parseBinaryProtocolCommand(cmd: BinaryProtocolCommand): ParseCli case CommandSetId.Process: return parseProcessCommand(cmd); default: - return { success: false, error: `unexpected command_set ${cmd.commandSet} command` }; + return {success: false, error: `unexpected command_set ${cmd.commandSet} command`}; } } -function parseEventPipeCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { +function parseEventPipeCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { switch (cmd.command) { case EventPipeCommandId.StopTracing: return parseEventPipeStopTracing(cmd); @@ -54,28 +54,28 @@ function parseEventPipeCommand(cmd: BinaryProtocolCommand & { commandSet: Comman return parseEventPipeCollectTracing2(cmd); default: mono_log_warn("unexpected EventPipe command: " + cmd.command); - return { success: false, error: `unexpected EventPipe command ${cmd.command}` }; + return {success: false, error: `unexpected EventPipe command ${cmd.command}`}; } } -function parseEventPipeCollectTracing2(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { - const pos = { pos: 0 }; +function parseEventPipeCollectTracing2 (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { + const pos = {pos: 0}; const buf = cmd.payload; const circularBufferMB = Parser.tryParseUint32(buf, pos); if (circularBufferMB === undefined) { - return { success: false, error: "failed to parse circularBufferMB in EventPipe CollectTracing2 command" }; + return {success: false, error: "failed to parse circularBufferMB in EventPipe CollectTracing2 command"}; } const format = Parser.tryParseUint32(buf, pos); if (format === undefined) { - return { success: false, error: "failed to parse format in EventPipe CollectTracing2 command" }; + return {success: false, error: "failed to parse format in EventPipe CollectTracing2 command"}; } const requestRundown = Parser.tryParseBool(buf, pos); if (requestRundown === undefined) { - return { success: false, error: "failed to parse requestRundown in EventPipe CollectTracing2 command" }; + return {success: false, error: "failed to parse requestRundown in EventPipe CollectTracing2 command"}; } const numProviders = Parser.tryParseArraySize(buf, pos); if (numProviders === undefined) { - return { success: false, error: "failed to parse numProviders in EventPipe CollectTracing2 command" }; + return {success: false, error: "failed to parse numProviders in EventPipe CollectTracing2 command"}; } const providers = new Array(numProviders); for (let i = 0; i < numProviders; i++) { @@ -85,44 +85,44 @@ function parseEventPipeCollectTracing2(cmd: BinaryProtocolCommand & { commandSet } providers[i] = result.result; } - const command: EventPipeCommandCollectTracing2 = { command_set: "EventPipe", command: "CollectTracing2", circularBufferMB, format, requestRundown, providers }; - return { success: true, result: command }; + const command: EventPipeCommandCollectTracing2 = {command_set: "EventPipe", command: "CollectTracing2", circularBufferMB, format, requestRundown, providers}; + return {success: true, result: command}; } -function parseEventPipeCollectTracingCommandProvider(buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { +function parseEventPipeCollectTracingCommandProvider (buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { const keywords = Parser.tryParseUint64(buf, pos); if (keywords === undefined) { - return { success: false, error: "failed to parse keywords in EventPipe CollectTracing provider" }; + return {success: false, error: "failed to parse keywords in EventPipe CollectTracing provider"}; } const logLevel = Parser.tryParseUint32(buf, pos); if (logLevel === undefined) - return { success: false, error: "failed to parse logLevel in EventPipe CollectTracing provider" }; + return {success: false, error: "failed to parse logLevel in EventPipe CollectTracing provider"}; const providerName = Parser.tryParseUtf16String(buf, pos); if (providerName === undefined) - return { success: false, error: "failed to parse providerName in EventPipe CollectTracing provider" }; + return {success: false, error: "failed to parse providerName in EventPipe CollectTracing provider"}; const filterData = Parser.tryParseUtf16String(buf, pos); if (filterData === undefined) - return { success: false, error: "failed to parse filterData in EventPipe CollectTracing provider" }; - const provider: EventPipeCollectTracingCommandProvider = { keywords, logLevel, provider_name: providerName, filter_data: filterData }; - return { success: true, result: provider }; + return {success: false, error: "failed to parse filterData in EventPipe CollectTracing provider"}; + const provider: EventPipeCollectTracingCommandProvider = {keywords, logLevel, provider_name: providerName, filter_data: filterData}; + return {success: true, result: provider}; } -function parseEventPipeStopTracing(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { - const pos = { pos: 0 }; +function parseEventPipeStopTracing (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { + const pos = {pos: 0}; const buf = cmd.payload; const sessionID = Parser.tryParseUint64(buf, pos); if (sessionID === undefined) { - return { success: false, error: "failed to parse sessionID in EventPipe StopTracing command" }; + return {success: false, error: "failed to parse sessionID in EventPipe StopTracing command"}; } const [lo, hi] = sessionID; if (hi !== 0) { - return { success: false, error: "sessionID is too large in EventPipe StopTracing command" }; + return {success: false, error: "sessionID is too large in EventPipe StopTracing command"}; } - const command: EventPipeCommandStopTracing = { command_set: "EventPipe", command: "StopTracing", sessionID: lo }; - return { success: true, result: command }; + const command: EventPipeCommandStopTracing = {command_set: "EventPipe", command: "StopTracing", sessionID: lo}; + return {success: true, result: command}; } -function parseProcessCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { +function parseProcessCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { switch (cmd.command) { case ProcessCommandId.ProcessInfo: throw new Error("TODO"); @@ -134,15 +134,15 @@ function parseProcessCommand(cmd: BinaryProtocolCommand & { commandSet: CommandS throw new Error("TODO"); default: mono_log_warn("unexpected Process command: " + cmd.command); - return { success: false, error: `unexpected Process command ${cmd.command}` }; + return {success: false, error: `unexpected Process command ${cmd.command}`}; } } -function parseProcessResumeRuntime(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { +function parseProcessResumeRuntime (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { const buf = cmd.payload; if (buf.byteLength !== 0) { - return { success: false, error: "unexpected payload in Process ResumeRuntime command" }; + return {success: false, error: "unexpected payload in Process ResumeRuntime command"}; } - const command: ProcessCommandResumeRuntime = { command_set: "Process", command: "ResumeRuntime" }; - return { success: true, result: command }; + const command: ProcessCommandResumeRuntime = {command_set: "Process", command: "ResumeRuntime"}; + return {success: true, result: command}; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts index 6b67488c5fdac7..7876d0d7aedefa 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts @@ -1,14 +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 { mono_assert } from "../../../globals"; +import {mono_assert} from "../../../globals"; import Serializer from "./base-serializer"; -import { CommandSetId, ServerCommandId } from "./types"; +import {CommandSetId, ServerCommandId} from "./types"; -export function createBinaryCommandOKReply(payload?: Uint8Array): Uint8Array { +export function createBinaryCommandOKReply (payload?: Uint8Array): Uint8Array { const len = Serializer.computeMessageByteLength(payload); const buf = new Uint8Array(len); - const pos = { pos: 0 }; + const pos = {pos: 0}; Serializer.serializeHeader(buf, pos, CommandSetId.Server, ServerCommandId.OK, len); if (payload !== undefined) { Serializer.serializePayload(buf, pos, payload); @@ -16,7 +16,7 @@ export function createBinaryCommandOKReply(payload?: Uint8Array): Uint8Array { return buf; } -function serializeGuid(buf: Uint8Array, pos: { pos: number }, guid: string): void { +function serializeGuid (buf: Uint8Array, pos: { pos: number }, guid: string): void { guid.split("-").forEach((part) => { // FIXME: I'm sure the endianness is wrong here for (let i = 0; i < part.length; i += 2) { @@ -26,7 +26,7 @@ function serializeGuid(buf: Uint8Array, pos: { pos: number }, guid: string): voi }); } -function serializeAsciiLiteralString(buf: Uint8Array, pos: { pos: number }, s: string): void { +function serializeAsciiLiteralString (buf: Uint8Array, pos: { pos: number }, s: string): void { const len = s.length; const hasNul = s[len - 1] === "\0"; for (let i = 0; i < len; i++) { @@ -38,10 +38,10 @@ function serializeAsciiLiteralString(buf: Uint8Array, pos: { pos: number }, s: s } -export function createAdvertise(guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { +export function createAdvertise (guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { const BUF_LENGTH = 34; const buf = new Uint8Array(BUF_LENGTH); - const pos = { pos: 0 }; + const pos = {pos: 0}; const advrText = "ADVR_V1\0"; serializeAsciiLiteralString(buf, pos, advrText); serializeGuid(buf, pos, guid); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts index 2031de3499bd3a..70794014fe8e95 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts @@ -8,7 +8,7 @@ export interface BinaryProtocolCommand { payload: Uint8Array; } -export function isBinaryProtocolCommand(x: object): x is BinaryProtocolCommand { +export function isBinaryProtocolCommand (x: object): x is BinaryProtocolCommand { return "commandSet" in x && "command" in x && "payload" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts index b3d07952de76d1..375d3b21959b4b 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import type { Mock } from "../mock"; -import { mock } from "../mock"; +import type {Mock} from "../mock"; +import {mock} from "../mock"; -export function importAndInstantiateMock(mockURL: string): Promise { +export function importAndInstantiateMock (mockURL: string): Promise { if (monoDiagnosticsMock) { const mockPrefix = "mock:"; const scriptURL = mockURL.substring(mockPrefix.length); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts index a255e65fe3c18a..f0f7a054bc46d1 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts @@ -51,32 +51,32 @@ export type RemoveCommandSetAndId = Omitx).providers) && (x).providers.every(isEventPipeCollectTracingCommandProvider); } -export function isEventPipeCommandStopTracing(x: object): x is EventPipeCommandStopTracing { +export function isEventPipeCommandStopTracing (x: object): x is EventPipeCommandStopTracing { return isEventPipeCommand(x) && x.command === "StopTracing" && "sessionID" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts index 7bd03e0d003a34..f1eca8a8ec76b4 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { CommonSocket } from "./common-socket"; +import type {CommonSocket} from "./common-socket"; import { BinaryProtocolCommand, ParseResultFail, @@ -9,8 +9,8 @@ import { } from "./ipc-protocol/types"; import Magic from "./ipc-protocol/magic"; import Parser from "./ipc-protocol/base-parser"; -import { assertNever } from "../../types/internal"; -import { mono_log_debug, mono_log_warn } from "../../logging"; +import {assertNever} from "../../types/internal"; +import {mono_log_debug, mono_log_warn} from "../../logging"; export const dotnetDiagnosticsServerProtocolCommandEvent = "dotnet:diagnostics:protocolCommand" as const; @@ -58,12 +58,12 @@ export type ParseResult = ParseResultBinaryCommandOk | ParseResultFail; /// A helper object that accumulates command data that is received and provides parsed commands class StatefulParser { - private state: State = { state: InState.Idle }; + private state: State = {state: InState.Idle}; - constructor(private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } + constructor (private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } /// process the data in the given buffer and update the state. - receiveBuffer(buf: ArrayBuffer): void { + receiveBuffer (buf: ArrayBuffer): void { if (this.state.state == InState.Error) { return; } @@ -83,22 +83,22 @@ class StatefulParser { } else { mono_log_warn("socket received invalid command header", buf, result.error); // FIXME: dispatch error event? - this.setState({ state: InState.Error }); + this.setState({state: InState.Error}); } } - tryParseHeader(buf: Uint8Array): ParseResult { - const pos = { pos: 0 }; + tryParseHeader (buf: Uint8Array): ParseResult { + const pos = {pos: 0}; if (buf.byteLength < Magic.MinimalHeaderSize) { // TODO: we need to see the magic and the size to make a partial commmand - return { success: false, error: "not enough data" }; + return {success: false, error: "not enough data"}; } if (!Parser.tryParseHeader(buf, pos)) { - return { success: false, error: "invalid header" }; + return {success: false, error: "invalid header"}; } const size = Parser.tryParseSize(buf, pos); if (size === undefined || size < Magic.MinimalHeaderSize) { - return { success: false, error: "invalid size" }; + return {success: false, error: "invalid size"}; } // make a "partially completed" state with a buffer of the right size and just the header upto the size // field filled in. @@ -106,18 +106,18 @@ class StatefulParser { const partialBuf = new ArrayBuffer(size); const partialBufView = new Uint8Array(partialBuf); partialBufView.set(buf.subarray(0, parsedSize)); - const partialState: PartialCommandState = { state: InState.PartialCommand, buf: partialBufView, size: parsedSize }; + const partialState: PartialCommandState = {state: InState.PartialCommand, buf: partialBufView, size: parsedSize}; return this.continueWithBuffer(partialState, buf.subarray(parsedSize)); } - tryAppendBuffer(moreBuf: Uint8Array): ParseResult { + tryAppendBuffer (moreBuf: Uint8Array): ParseResult { if (this.state.state !== InState.PartialCommand) { - return { success: false, error: "not in partial command state" }; + return {success: false, error: "not in partial command state"}; } return this.continueWithBuffer(this.state, moreBuf); } - continueWithBuffer(state: PartialCommandState, moreBuf: Uint8Array): ParseResult { + continueWithBuffer (state: PartialCommandState, moreBuf: Uint8Array): ParseResult { const buf = state.buf; let partialSize = state.size; let overflow: Uint8Array | null = null; @@ -134,15 +134,15 @@ class StatefulParser { overflow.set(moreBuf.subarray(overflowOffset)); } if (partialSize < buf.byteLength) { - const newState = { state: InState.PartialCommand, buf, size: partialSize }; - return { success: true, command: undefined, newState }; + const newState = {state: InState.PartialCommand, buf, size: partialSize}; + return {success: true, command: undefined, newState}; } else { - const pos = { pos: Magic.MinimalHeaderSize }; + const pos = {pos: Magic.MinimalHeaderSize}; let result = this.tryParseCompletedBuffer(buf, pos); if (overflow) { mono_log_warn("additional bytes past command payload", overflow); if (result.success) { - const newResult: ParseResultBinaryCommandOk = { success: true, command: result.command, newState: { state: InState.Error } }; + const newResult: ParseResultBinaryCommandOk = {success: true, command: result.command, newState: {state: InState.Error}}; result = newResult; } } @@ -150,21 +150,21 @@ class StatefulParser { } } - tryParseCompletedBuffer(buf: Uint8Array, pos: { pos: number }): ParseResult { + tryParseCompletedBuffer (buf: Uint8Array, pos: { pos: number }): ParseResult { const command = Parser.tryParseCommand(buf, pos); if (!command) { - this.setState({ state: InState.Error }); - return { success: false, error: "invalid command" }; + this.setState({state: InState.Error}); + return {success: false, error: "invalid command"}; } - return { success: true, command, newState: { state: InState.Idle } }; + return {success: true, command, newState: {state: InState.Idle}}; } - private setState(state: State) { + private setState (state: State) { this.state = state; } - reset() { - this.setState({ state: InState.Idle }); + reset () { + this.setState({state: InState.Idle}); } } @@ -173,9 +173,9 @@ class ProtocolSocketImpl implements ProtocolSocket { private readonly statefulParser = new StatefulParser(this.emitCommandCallback.bind(this)); private protocolListeners = 0; private readonly messageListener: (this: CommonSocket, ev: MessageEvent) => void = this.onMessage.bind(this); - constructor(private readonly sock: CommonSocket) { } + constructor (private readonly sock: CommonSocket) { } - onMessage(this: ProtocolSocketImpl, ev: MessageEvent): void { + onMessage (this: ProtocolSocketImpl, ev: MessageEvent): void { const data = ev.data; mono_log_debug("protocol socket received message", ev.data); if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -190,17 +190,17 @@ class ProtocolSocketImpl implements ProtocolSocket { } } - dispatchEvent(evt: Event): boolean { + dispatchEvent (evt: Event): boolean { return this.sock.dispatchEvent(evt); } - onArrayBuffer(this: ProtocolSocketImpl, buf: ArrayBuffer) { + onArrayBuffer (this: ProtocolSocketImpl, buf: ArrayBuffer) { mono_log_debug("protocol-socket: parsing array buffer", buf); this.statefulParser.receiveBuffer(buf); } // called by the stateful parser when it has a complete command - emitCommandCallback(this: this, command: BinaryProtocolCommand): void { + emitCommandCallback (this: this, command: BinaryProtocolCommand): void { mono_log_debug("protocol-socket: queueing command", command); queueMicrotask(() => { mono_log_debug("dispatching protocol event with command", command); @@ -209,14 +209,14 @@ class ProtocolSocketImpl implements ProtocolSocket { } - dispatchProtocolCommandEvent(cmd: BinaryProtocolCommand): void { + dispatchProtocolCommandEvent (cmd: BinaryProtocolCommand): void { const ev = new Event(dotnetDiagnosticsServerProtocolCommandEvent); (ev).data = cmd; // FIXME: use a proper event subclass this.sock.dispatchEvent(ev); } addEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { + addEventListener (type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { this.sock.addEventListener(type, listener, options); if (type === dotnetDiagnosticsServerProtocolCommandEvent) { if (this.protocolListeners === 0) { @@ -228,7 +228,7 @@ class ProtocolSocketImpl implements ProtocolSocket { } removeEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener (type: string, listener: EventListenerOrEventListenerObject): void { if (type === dotnetDiagnosticsServerProtocolCommandEvent) { mono_log_debug("removing protocol listener and message chaser"); this.protocolListeners--; @@ -240,18 +240,18 @@ class ProtocolSocketImpl implements ProtocolSocket { this.sock.removeEventListener(type, listener); } - send(buf: Uint8Array) { + send (buf: Uint8Array) { this.sock.send(buf); } - close() { + close () { this.sock.close(); this.statefulParser.reset(); } } -export function createProtocolSocket(socket: CommonSocket): ProtocolSocket { +export function createProtocolSocket (socket: CommonSocket): ProtocolSocket { return new ProtocolSocketImpl(socket); } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts index d02ae16e3403a0..bcbdd9c9fe6b2c 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { assertNever } from "../../types/internal"; -import { VoidPtr } from "../../types/emscripten"; -import type { CommonSocket } from "./common-socket"; -import { mono_log_debug, mono_log_warn } from "../../logging"; -import { localHeapViewU8 } from "../../memory"; +import {assertNever} from "../../types/internal"; +import {VoidPtr} from "../../types/emscripten"; +import type {CommonSocket} from "./common-socket"; +import {mono_log_debug, mono_log_warn} from "../../logging"; +import {localHeapViewU8} from "../../memory"; enum ListenerState { Sending, Closed, @@ -13,11 +13,11 @@ enum ListenerState { } class SocketGuts { - constructor(public readonly socket: CommonSocket) { } - close(): void { + constructor (public readonly socket: CommonSocket) { } + close (): void { this.socket.close(); } - write(data: VoidPtr, size: number): void { + write (data: VoidPtr, size: number): void { const buf = new ArrayBuffer(size); const view = new Uint8Array(buf); // Can we avoid this copy? @@ -33,12 +33,12 @@ class SocketGuts { export class EventPipeSocketConnection { private _state: ListenerState; readonly stream: SocketGuts; - constructor(socket: CommonSocket) { + constructor (socket: CommonSocket) { this._state = ListenerState.Sending; this.stream = new SocketGuts(socket); } - close(): void { + close (): void { mono_log_debug("EventPipe session stream closing websocket"); switch (this._state) { case ListenerState.Error: @@ -52,7 +52,7 @@ export class EventPipeSocketConnection { } } - write(ptr: VoidPtr, len: number): boolean { + write (ptr: VoidPtr, len: number): boolean { switch (this._state) { case ListenerState.Sending: this.stream.write(ptr, len); @@ -65,7 +65,7 @@ export class EventPipeSocketConnection { } } - private _onMessage(event: MessageEvent): void { + private _onMessage (event: MessageEvent): void { switch (this._state) { case ListenerState.Sending: /* unexpected message */ @@ -85,7 +85,7 @@ export class EventPipeSocketConnection { } - private _onClose(/*event: CloseEvent*/) { + private _onClose (/*event: CloseEvent*/) { switch (this._state) { case ListenerState.Closed: return; /* do nothing */ @@ -99,14 +99,14 @@ export class EventPipeSocketConnection { } } - private _onError(event: Event) { + private _onError (event: Event) { mono_log_debug("EventPipe session stream websocket error", event); this._state = ListenerState.Error; this.stream.close(); // TODO: notify runtime that connection had an error } - addListeners(): void { + addListeners (): void { const socket = this.stream.socket; socket.addEventListener("message", this._onMessage.bind(this)); addEventListener("close", this._onClose.bind(this)); @@ -116,7 +116,7 @@ export class EventPipeSocketConnection { /// Take over a WebSocket that was used by the diagnostic server to receive the StartCollecting command and /// use it for sending the event pipe data back to the host. -export function takeOverSocket(socket: CommonSocket): EventPipeSocketConnection { +export function takeOverSocket (socket: CommonSocket): EventPipeSocketConnection { const connection = new EventPipeSocketConnection(socket); connection.addListeners(); return connection; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts index 5ab42c2d8b4d96..f3d140021d3ee4 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts @@ -1,8 +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 { VoidPtr } from "../../types/emscripten"; -import { getI32, notifyI32, setI32, storeI32 } from "../../memory"; +import {VoidPtr} from "../../types/emscripten"; +import {getI32, notifyI32, setI32, storeI32} from "../../memory"; /// One-reader, one-writer, size 1 queue for messages from an EventPipe streaming thread to @@ -38,36 +38,36 @@ export class StreamQueue { readonly workAvailable: EventTarget = new globalThis.EventTarget(); readonly signalWorkAvailable = this.signalWorkAvailableImpl.bind(this); - constructor(readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { + constructor (readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { this.workAvailable.addEventListener("workAvailable", this.onWorkAvailable.bind(this)); } - private get buf_addr(): VoidPtr { + private get buf_addr (): VoidPtr { return this.queue_addr + BUF_OFFSET; } - private get count_addr(): VoidPtr { + private get count_addr (): VoidPtr { return this.queue_addr + COUNT_OFFSET; } - private get buf_full_addr(): VoidPtr { + private get buf_full_addr (): VoidPtr { return this.queue_addr + WRITE_DONE_OFFSET; } /// called from native code on the diagnostic thread when the streaming thread queues a call to notify the /// diagnostic thread that it can send the buffer. - wakeup(): void { + wakeup (): void { queueMicrotask(this.signalWorkAvailable); } - workAvailableNow(): void { + workAvailableNow (): void { // process the queue immediately, rather than waiting for the next event loop tick. this.onWorkAvailable(); } - private signalWorkAvailableImpl(this: StreamQueue): void { + private signalWorkAvailableImpl (this: StreamQueue): void { this.workAvailable.dispatchEvent(new Event("workAvailable")); } - private onWorkAvailable(this: StreamQueue /*,event: Event */): void { + private onWorkAvailable (this: StreamQueue /*,event: Event */): void { const buf = getI32(this.buf_addr) as unknown as VoidPtr; const intptr_buf = buf as unknown as number; if (intptr_buf === STREAM_CLOSE_SENTINEL) { @@ -90,19 +90,19 @@ export class StreamQueue { // maps stream queue addresses to StreamQueue instances const streamQueueMap = new Map(); -export function allocateQueue(nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { +export function allocateQueue (nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { const queue = new StreamQueue(nativeQueueAddr, syncSendBuffer, syncSendClose); streamQueueMap.set(nativeQueueAddr, queue); return queue; } -export function closeQueue(nativeQueueAddr: VoidPtr): void { +export function closeQueue (nativeQueueAddr: VoidPtr): void { streamQueueMap.delete(nativeQueueAddr); // TODO: remove the event listener? } // called from native code on the diagnostic thread by queueing a call from the streaming thread. -export function mono_wasm_diagnostic_server_stream_signal_work_available(nativeQueueAddr: VoidPtr, current_thread: number): void { +export function mono_wasm_diagnostic_server_stream_signal_work_available (nativeQueueAddr: VoidPtr, current_thread: number): void { const queue = streamQueueMap.get(nativeQueueAddr); if (queue) { if (current_thread === 0) { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts index 6854261e4d00ed..531aa0cc223bc9 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts @@ -2,29 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import { EventPipeSessionIDImpl } from "../shared/types"; -import { EventPipeSocketConnection, takeOverSocket } from "./socket-connection"; -import { StreamQueue, allocateQueue } from "./stream-queue"; -import type { MockRemoteSocket } from "../mock"; -import type { VoidPtr } from "../../types/emscripten"; -import { threads_c_functions as cwraps } from "../../cwraps"; +import {EventPipeSessionIDImpl} from "../shared/types"; +import {EventPipeSocketConnection, takeOverSocket} from "./socket-connection"; +import {StreamQueue, allocateQueue} from "./stream-queue"; +import type {MockRemoteSocket} from "../mock"; +import type {VoidPtr} from "../../types/emscripten"; +import {threads_c_functions as cwraps} from "../../cwraps"; import { EventPipeCommandCollectTracing2, EventPipeCollectTracingCommandProvider, } from "./protocol-client-commands"; -import { createEventPipeStreamingSession } from "../shared/create-session"; -import { mono_assert } from "../../globals"; +import {createEventPipeStreamingSession} from "../shared/create-session"; +import {mono_assert} from "../../globals"; /// The streaming session holds all the pieces of an event pipe streaming session that the /// diagnostic server knows about: the session ID, a /// queue used by the EventPipe streaming thread to forward events to the diagnostic server thread, /// and a wrapper around the WebSocket object used to send event data back to the host. export class EventPipeStreamingSession { - constructor(readonly sessionID: EventPipeSessionIDImpl, + constructor (readonly sessionID: EventPipeSessionIDImpl, readonly queue: StreamQueue, readonly connection: EventPipeSocketConnection) { } } -export async function makeEventPipeStreamingSession(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { +export async function makeEventPipeStreamingSession (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); // First, create the native IPC stream and get its queue. const ipcStreamAddr = cwraps.mono_wasm_diagnostic_server_create_stream(); // FIXME: this should be a wrapped in a JS object so we can free it when we're done. @@ -46,17 +46,17 @@ export async function makeEventPipeStreamingSession(ws: WebSocket | MockRemoteSo } -function providersStringFromObject(providers: EventPipeCollectTracingCommandProvider[]) { +function providersStringFromObject (providers: EventPipeCollectTracingCommandProvider[]) { const providersString = providers.map(providerToString).join(","); return providersString; - function providerToString(provider: EventPipeCollectTracingCommandProvider): string { + function providerToString (provider: EventPipeCollectTracingCommandProvider): string { const keyword_str = provider.keywords[0] === 0 && provider.keywords[1] === 0 ? "" : keywordsToHexString(provider.keywords); const args_str = provider.filter_data === "" ? "" : ":" + provider.filter_data; return provider.provider_name + ":" + keyword_str + ":" + provider.logLevel + args_str; } - function keywordsToHexString(k: [number, number]): string { + function keywordsToHexString (k: [number, number]): string { const lo = k[0]; const hi = k[1]; const lo_hex = leftPad(lo.toString(16), "0", 8); @@ -64,7 +64,7 @@ function providersStringFromObject(providers: EventPipeCollectTracingCommandProv return hi_hex + lo_hex; } - function leftPad(s: string, fill: string, width: number): string { + function leftPad (s: string, fill: string, width: number): string { if (s.length >= width) return s; const prefix = fill.repeat(width - s.length); @@ -74,6 +74,6 @@ function providersStringFromObject(providers: EventPipeCollectTracingCommandProv const IPC_STREAM_QUEUE_OFFSET = 4; /* keep in sync with mono_wasm_diagnostic_server_create_stream() in C */ -function getQueueAddrFromStreamAddr(streamAddr: VoidPtr): VoidPtr { +function getQueueAddrFromStreamAddr (streamAddr: VoidPtr): VoidPtr { return streamAddr + IPC_STREAM_QUEUE_OFFSET; } diff --git a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts index 16aa6ad85944f2..0241ef294a34fd 100644 --- a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts +++ b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts @@ -1,8 +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 { isMonoThreadMessage } from "../../pthreads"; -import type { MonoThreadMessage } from "../../types/internal"; +import {isMonoThreadMessage} from "../../pthreads"; +import type {MonoThreadMessage} from "../../types/internal"; // Messages from the main thread to the diagnostic server thread export interface DiagnosticMessage extends MonoThreadMessage { @@ -10,7 +10,7 @@ export interface DiagnosticMessage extends MonoThreadMessage { cmd: string; } -export function isDiagnosticMessage(x: unknown): x is DiagnosticMessage { +export function isDiagnosticMessage (x: unknown): x is DiagnosticMessage { return isMonoThreadMessage(x) && x.type === "diagnostic_server"; } @@ -29,7 +29,7 @@ export type DiagnosticServerControlCommandStart = DiagnosticServerControlCommand export type DiagnosticServerControlCommandStop = DiagnosticServerControlCommandSpecific<"stop">; export type DiagnosticServerControlCommandAttachToRuntime = DiagnosticServerControlCommandSpecific<"attach_to_runtime">; -export function makeDiagnosticServerControlCommand(cmd: T): DiagnosticServerControlCommandSpecific { +export function makeDiagnosticServerControlCommand (cmd: T): DiagnosticServerControlCommandSpecific { return { type: "diagnostic_server", cmd: cmd, diff --git a/src/mono/browser/runtime/diagnostics/shared/create-session.ts b/src/mono/browser/runtime/diagnostics/shared/create-session.ts index 17af0cbc5bebba..75e4e01f2721cb 100644 --- a/src/mono/browser/runtime/diagnostics/shared/create-session.ts +++ b/src/mono/browser/runtime/diagnostics/shared/create-session.ts @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. import * as memory from "../../memory"; -import { VoidPtr } from "../../types/emscripten"; -import { threads_c_functions as cwraps } from "../../cwraps"; -import type { EventPipeSessionIDImpl } from "./types"; +import {VoidPtr} from "../../types/emscripten"; +import {threads_c_functions as cwraps} from "../../cwraps"; +import type {EventPipeSessionIDImpl} from "./types"; const sizeOfInt32 = 4; @@ -25,7 +25,7 @@ type SessionType = }; -function createSessionWithPtrCB(sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { +function createSessionWithPtrCB (sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { memory.setI32(sessionIdOutPtr, 0); let tracePath: string | null; let ipcStreamAddr: VoidPtr; @@ -43,10 +43,10 @@ function createSessionWithPtrCB(sessionIdOutPtr: VoidPtr, options: EventPipeCrea } } -export function createEventPipeStreamingSession(ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { - return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "stream", stream: ipcStreamAddr }); +export function createEventPipeStreamingSession (ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { + return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, {type: "stream", stream: ipcStreamAddr}); } -export function createEventPipeFileSession(tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { - return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "file", filePath: tracePath }); +export function createEventPipeFileSession (tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { + return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, {type: "file", filePath: tracePath}); } diff --git a/src/mono/browser/runtime/export-api.ts b/src/mono/browser/runtime/export-api.ts index 623c4222218f01..08aa21df34d7db 100644 --- a/src/mono/browser/runtime/export-api.ts +++ b/src/mono/browser/runtime/export-api.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { MonoConfig, APIType } from "./types"; +import type {MonoConfig, APIType} from "./types"; -import { mono_wasm_get_assembly_exports } from "./invoke-cs"; -import { mono_wasm_set_module_imports } from "./invoke-js"; -import { getB32, getF32, getF64, getI16, getI32, getI52, getI64Big, getI8, getU16, getU32, getU52, getU8, localHeapViewF32, localHeapViewF64, localHeapViewI16, localHeapViewI32, localHeapViewI64Big, localHeapViewI8, localHeapViewU16, localHeapViewU32, localHeapViewU8, setB32, setF32, setF64, setI16, setI32, setI52, setI64Big, setI8, setU16, setU32, setU52, setU8 } from "./memory"; -import { mono_run_main, mono_run_main_and_exit } from "./run"; -import { mono_wasm_setenv } from "./startup"; -import { loaderHelpers, runtimeHelpers } from "./globals"; +import {mono_wasm_get_assembly_exports} from "./invoke-cs"; +import {mono_wasm_set_module_imports} from "./invoke-js"; +import {getB32, getF32, getF64, getI16, getI32, getI52, getI64Big, getI8, getU16, getU32, getU52, getU8, localHeapViewF32, localHeapViewF64, localHeapViewI16, localHeapViewI32, localHeapViewI64Big, localHeapViewI8, localHeapViewU16, localHeapViewU32, localHeapViewU8, setB32, setF32, setF64, setI16, setI32, setI52, setI64Big, setI8, setU16, setU32, setU52, setU8} from "./memory"; +import {mono_run_main, mono_run_main_and_exit} from "./run"; +import {mono_wasm_setenv} from "./startup"; +import {loaderHelpers, runtimeHelpers} from "./globals"; -export function export_api(): any { +export function export_api (): any { const api: APIType = { runMain: mono_run_main, runMainAndExit: mono_run_main_and_exit, diff --git a/src/mono/browser/runtime/exports-binding.ts b/src/mono/browser/runtime/exports-binding.ts index d2ff55bc088a70..eee2c197ba6b69 100644 --- a/src/mono/browser/runtime/exports-binding.ts +++ b/src/mono/browser/runtime/exports-binding.ts @@ -3,35 +3,35 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { mono_wasm_debugger_log, mono_wasm_add_dbg_command_received, mono_wasm_set_entrypoint_breakpoint, mono_wasm_fire_debugger_agent_message_with_data, mono_wasm_fire_debugger_agent_message_with_data_to_pause } from "./debug"; -import { mono_wasm_release_cs_owned_object } from "./gc-handles"; -import { mono_wasm_bind_js_import, mono_wasm_invoke_js_function, mono_wasm_invoke_jsimport, mono_wasm_invoke_jsimport_ST } from "./invoke-js"; -import { mono_interp_tier_prepare_jiterpreter, mono_jiterp_free_method_data_js } from "./jiterpreter"; -import { mono_interp_jit_wasm_entry_trampoline, mono_interp_record_interp_entry } from "./jiterpreter-interp-entry"; -import { mono_interp_jit_wasm_jit_call_trampoline, mono_interp_invoke_wasm_jit_call_trampoline, mono_interp_flush_jitcall_queue } from "./jiterpreter-jit-call"; -import { mono_wasm_resolve_or_reject_promise } from "./marshal-to-js"; -import { mono_wasm_schedule_timer, schedule_background_exec } from "./scheduling"; -import { mono_wasm_asm_loaded } from "./startup"; -import { mono_wasm_diagnostic_server_on_server_thread_created } from "./diagnostics/server_pthread"; -import { mono_wasm_diagnostic_server_on_runtime_server_init, mono_wasm_event_pipe_early_startup_callback } from "./diagnostics"; -import { mono_wasm_diagnostic_server_stream_signal_work_available } from "./diagnostics/server_pthread/stream-queue"; -import { mono_log_warn, mono_wasm_console_clear, mono_wasm_trace_logger } from "./logging"; -import { mono_wasm_profiler_leave, mono_wasm_profiler_enter } from "./profiler"; -import { mono_wasm_change_case, mono_wasm_change_case_invariant } from "./hybrid-globalization/change-case"; -import { mono_wasm_compare_string, mono_wasm_ends_with, mono_wasm_starts_with, mono_wasm_index_of } from "./hybrid-globalization/collations"; -import { mono_wasm_get_calendar_info } from "./hybrid-globalization/calendar"; - -import { mono_wasm_get_culture_info } from "./hybrid-globalization/culture-info"; -import { mono_wasm_get_first_day_of_week, mono_wasm_get_first_week_of_year } from "./hybrid-globalization/locales"; -import { mono_wasm_browser_entropy } from "./crypto"; -import { mono_wasm_cancel_promise } from "./cancelable-promise"; +import {mono_wasm_debugger_log, mono_wasm_add_dbg_command_received, mono_wasm_set_entrypoint_breakpoint, mono_wasm_fire_debugger_agent_message_with_data, mono_wasm_fire_debugger_agent_message_with_data_to_pause} from "./debug"; +import {mono_wasm_release_cs_owned_object} from "./gc-handles"; +import {mono_wasm_bind_js_import, mono_wasm_invoke_js_function, mono_wasm_invoke_jsimport, mono_wasm_invoke_jsimport_ST} from "./invoke-js"; +import {mono_interp_tier_prepare_jiterpreter, mono_jiterp_free_method_data_js} from "./jiterpreter"; +import {mono_interp_jit_wasm_entry_trampoline, mono_interp_record_interp_entry} from "./jiterpreter-interp-entry"; +import {mono_interp_jit_wasm_jit_call_trampoline, mono_interp_invoke_wasm_jit_call_trampoline, mono_interp_flush_jitcall_queue} from "./jiterpreter-jit-call"; +import {mono_wasm_resolve_or_reject_promise} from "./marshal-to-js"; +import {mono_wasm_schedule_timer, schedule_background_exec} from "./scheduling"; +import {mono_wasm_asm_loaded} from "./startup"; +import {mono_wasm_diagnostic_server_on_server_thread_created} from "./diagnostics/server_pthread"; +import {mono_wasm_diagnostic_server_on_runtime_server_init, mono_wasm_event_pipe_early_startup_callback} from "./diagnostics"; +import {mono_wasm_diagnostic_server_stream_signal_work_available} from "./diagnostics/server_pthread/stream-queue"; +import {mono_log_warn, mono_wasm_console_clear, mono_wasm_trace_logger} from "./logging"; +import {mono_wasm_profiler_leave, mono_wasm_profiler_enter} from "./profiler"; +import {mono_wasm_change_case, mono_wasm_change_case_invariant} from "./hybrid-globalization/change-case"; +import {mono_wasm_compare_string, mono_wasm_ends_with, mono_wasm_starts_with, mono_wasm_index_of} from "./hybrid-globalization/collations"; +import {mono_wasm_get_calendar_info} from "./hybrid-globalization/calendar"; + +import {mono_wasm_get_culture_info} from "./hybrid-globalization/culture-info"; +import {mono_wasm_get_first_day_of_week, mono_wasm_get_first_week_of_year} from "./hybrid-globalization/locales"; +import {mono_wasm_browser_entropy} from "./crypto"; +import {mono_wasm_cancel_promise} from "./cancelable-promise"; import { mono_wasm_start_deputy_thread_async, mono_wasm_pthread_on_pthread_attached, mono_wasm_pthread_on_pthread_unregistered, mono_wasm_pthread_on_pthread_registered, mono_wasm_pthread_set_name, mono_wasm_install_js_worker_interop, mono_wasm_uninstall_js_worker_interop, mono_wasm_start_io_thread_async } from "./pthreads"; -import { mono_wasm_dump_threads } from "./pthreads/ui-thread"; +import {mono_wasm_dump_threads} from "./pthreads/ui-thread"; // the JS methods would be visible to EMCC linker and become imports of the WASM module @@ -117,7 +117,7 @@ const wasmImports: Function[] = [ ...mono_wasm_threads_imports, ]; -export function replace_linker_placeholders(imports: WebAssembly.Imports) { +export function replace_linker_placeholders (imports: WebAssembly.Imports) { // the output from emcc contains wrappers for these linker imports which add overhead, // but now we have what we need to replace them with the actual functions // By default the imports all live inside of 'env', but emscripten minification could rename it to 'a'. @@ -135,7 +135,7 @@ export function replace_linker_placeholders(imports: WebAssembly.Imports) { const stub_fn = env[shortName] as Function; if (typeof stub_fn === "function" && stub_fn.toString().indexOf("runtime_idx") !== -1) { try { - const { runtime_idx } = stub_fn(); + const {runtime_idx} = stub_fn(); if (indexToNameMap[runtime_idx] !== undefined) throw new Error(`Duplicate runtime_idx ${runtime_idx}`); indexToNameMap[runtime_idx] = shortName; } catch { diff --git a/src/mono/browser/runtime/exports-internal.ts b/src/mono/browser/runtime/exports-internal.ts index 3158b553713e4f..400f1a7ac461ec 100644 --- a/src/mono/browser/runtime/exports-internal.ts +++ b/src/mono/browser/runtime/exports-internal.ts @@ -3,32 +3,34 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { MonoObjectNull, type MonoObject } from "./types/internal"; -import cwraps, { profiler_c_functions, threads_c_functions as twraps } from "./cwraps"; -import { mono_wasm_send_dbg_command_with_parms, mono_wasm_send_dbg_command, mono_wasm_get_dbg_command_info, mono_wasm_get_details, mono_wasm_release_object, mono_wasm_call_function_on, mono_wasm_debugger_resume, mono_wasm_detach_debugger, mono_wasm_raise_debug_event, mono_wasm_change_debugger_log_level, mono_wasm_debugger_attached } from "./debug"; -import { http_wasm_supports_streaming_request, http_wasm_supports_streaming_response, http_wasm_create_controller, http_wasm_abort_request, http_wasm_abort_response, http_wasm_transform_stream_write, http_wasm_transform_stream_close, http_wasm_fetch, http_wasm_fetch_stream, http_wasm_fetch_bytes, http_wasm_get_response_header_names, http_wasm_get_response_header_values, http_wasm_get_response_bytes, http_wasm_get_response_length, http_wasm_get_streamed_response_bytes, http_wasm_get_response_type, http_wasm_get_response_status } from "./http"; -import { exportedRuntimeAPI, Module, runtimeHelpers } from "./globals"; -import { get_property, set_property, has_property, get_typeof_property, get_global_this, dynamic_import } from "./invoke-js"; -import { mono_wasm_stringify_as_error_with_stack } from "./logging"; -import { ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort, ws_get_state } from "./web-socket"; -import { mono_wasm_get_loaded_files } from "./assets"; -import { jiterpreter_dump_stats } from "./jiterpreter"; -import { interp_pgo_load_data, interp_pgo_save_data } from "./interp-pgo"; -import { getOptions, applyOptions } from "./jiterpreter-support"; -import { mono_wasm_gc_lock, mono_wasm_gc_unlock } from "./gc-lock"; -import { loadLazyAssembly } from "./lazyLoading"; -import { loadSatelliteAssemblies } from "./satelliteAssemblies"; -import { forceDisposeProxies } from "./gc-handles"; -import { mono_wasm_get_func_id_to_name_mappings } from "./logging"; -import { monoStringToStringUnsafe } from "./strings"; -import { mono_wasm_bind_cs_function } from "./invoke-cs"; - -import { mono_wasm_dump_threads, thread_available } from "./pthreads"; - -export function export_internal(): any { +import {MonoObjectNull, type MonoObject} from "./types/internal"; +import cwraps, {profiler_c_functions, threads_c_functions as twraps} from "./cwraps"; +import {mono_wasm_send_dbg_command_with_parms, mono_wasm_send_dbg_command, mono_wasm_get_dbg_command_info, mono_wasm_get_details, mono_wasm_release_object, mono_wasm_call_function_on, mono_wasm_debugger_resume, mono_wasm_detach_debugger, mono_wasm_raise_debug_event, mono_wasm_change_debugger_log_level, mono_wasm_debugger_attached} from "./debug"; +import {http_wasm_supports_streaming_request, http_wasm_supports_streaming_response, http_wasm_create_controller, http_wasm_abort_request, http_wasm_abort_response, http_wasm_transform_stream_write, http_wasm_transform_stream_close, http_wasm_fetch, http_wasm_fetch_stream, http_wasm_fetch_bytes, http_wasm_get_response_header_names, http_wasm_get_response_header_values, http_wasm_get_response_bytes, http_wasm_get_response_length, http_wasm_get_streamed_response_bytes, http_wasm_get_response_type, http_wasm_get_response_status} from "./http"; +import {exportedRuntimeAPI, Module, runtimeHelpers} from "./globals"; +import {get_property, set_property, has_property, get_typeof_property, get_global_this, dynamic_import} from "./invoke-js"; +import {mono_wasm_stringify_as_error_with_stack} from "./logging"; +import {ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort, ws_get_state} from "./web-socket"; +import {mono_wasm_get_loaded_files} from "./assets"; +import {jiterpreter_dump_stats} from "./jiterpreter"; +import {interp_pgo_load_data, interp_pgo_save_data} from "./interp-pgo"; +import {getOptions, applyOptions} from "./jiterpreter-support"; +import {mono_wasm_gc_lock, mono_wasm_gc_unlock} from "./gc-lock"; +import {loadLazyAssembly} from "./lazyLoading"; +import {loadSatelliteAssemblies} from "./satelliteAssemblies"; +import {forceDisposeProxies} from "./gc-handles"; +import {mono_wasm_get_func_id_to_name_mappings} from "./logging"; +import {monoStringToStringUnsafe} from "./strings"; +import {mono_wasm_bind_cs_function} from "./invoke-cs"; + +import {mono_wasm_dump_threads, thread_available} from "./pthreads"; + +export function export_internal (): any { return { // tests - mono_wasm_exit: (exit_code: number) => { Module.err("early exit " + exit_code); }, + mono_wasm_exit: (exit_code: number) => { + Module.err("early exit " + exit_code); + }, forceDisposeProxies, mono_wasm_dump_threads: WasmEnableThreads ? mono_wasm_dump_threads : undefined, @@ -114,7 +116,7 @@ export function export_internal(): any { }; } -export function cwraps_internal(internal: any): void { +export function cwraps_internal (internal: any): void { Object.assign(internal, { mono_wasm_exit: cwraps.mono_wasm_exit, mono_wasm_profiler_init_aot: profiler_c_functions.mono_wasm_profiler_init_aot, @@ -125,7 +127,7 @@ export function cwraps_internal(internal: any): void { } /* @deprecated not GC safe, legacy support for Blazor */ -export function monoObjectAsBoolOrNullUnsafe(obj: MonoObject): boolean | null { +export function monoObjectAsBoolOrNullUnsafe (obj: MonoObject): boolean | null { if (obj === MonoObjectNull) { return null; } diff --git a/src/mono/browser/runtime/exports-linker.ts b/src/mono/browser/runtime/exports-linker.ts index 84e39b446155b8..fa4b2fe4806981 100644 --- a/src/mono/browser/runtime/exports-linker.ts +++ b/src/mono/browser/runtime/exports-linker.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_wasm_imports, mono_wasm_threads_imports } from "./exports-binding"; +import {mono_wasm_imports, mono_wasm_threads_imports} from "./exports-binding"; import gitHash from "consts:gitHash"; -export function export_linker_indexes_as_code(): string { +export function export_linker_indexes_as_code (): string { const indexByName: any = { mono_wasm_imports: {}, mono_wasm_threads_imports: {}, @@ -25,5 +25,5 @@ export function export_linker_indexes_as_code(): string { `; } -// this is running during runtime compile time inside rollup process. -(globalThis as any).export_linker_indexes_as_code = export_linker_indexes_as_code; \ No newline at end of file +// this is running during runtime compile time inside rollup process. +(globalThis as any).export_linker_indexes_as_code = export_linker_indexes_as_code; diff --git a/src/mono/browser/runtime/exports.ts b/src/mono/browser/runtime/exports.ts index 2a4dc08320a0bc..cda4a3098eda10 100644 --- a/src/mono/browser/runtime/exports.ts +++ b/src/mono/browser/runtime/exports.ts @@ -7,26 +7,26 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import WasmEnableSIMD from "consts:wasmEnableSIMD"; import WasmEnableExceptionHandling from "consts:wasmEnableExceptionHandling"; -import type { RuntimeAPI } from "./types"; +import type {RuntimeAPI} from "./types"; -import { Module, exportedRuntimeAPI, loaderHelpers, passEmscriptenInternals, runtimeHelpers, setRuntimeGlobals, } from "./globals"; -import { GlobalObjects, RuntimeHelpers } from "./types/internal"; -import { configureEmscriptenStartup, configureRuntimeStartup, configureWorkerStartup } from "./startup"; +import {Module, exportedRuntimeAPI, loaderHelpers, passEmscriptenInternals, runtimeHelpers, setRuntimeGlobals,} from "./globals"; +import {GlobalObjects, RuntimeHelpers} from "./types/internal"; +import {configureEmscriptenStartup, configureRuntimeStartup, configureWorkerStartup} from "./startup"; -import { create_weak_ref } from "./weak-ref"; -import { export_internal } from "./exports-internal"; -import { export_api } from "./export-api"; -import { initializeReplacements } from "./polyfills"; +import {create_weak_ref} from "./weak-ref"; +import {export_internal} from "./exports-internal"; +import {export_api} from "./export-api"; +import {initializeReplacements} from "./polyfills"; -import { mono_wasm_stringify_as_error_with_stack } from "./logging"; -import { instantiate_asset, instantiate_symbols_asset, instantiate_segmentation_rules_asset } from "./assets"; -import { jiterpreter_dump_stats } from "./jiterpreter"; -import { forceDisposeProxies } from "./gc-handles"; -import { mono_wasm_dump_threads } from "./pthreads"; +import {mono_wasm_stringify_as_error_with_stack} from "./logging"; +import {instantiate_asset, instantiate_symbols_asset, instantiate_segmentation_rules_asset} from "./assets"; +import {jiterpreter_dump_stats} from "./jiterpreter"; +import {forceDisposeProxies} from "./gc-handles"; +import {mono_wasm_dump_threads} from "./pthreads"; export let runtimeList: RuntimeList; -function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { +function initializeExports (globalObjects: GlobalObjects): RuntimeAPI { const module = Module; const globals = globalObjects; const globalThisAny = globalThis as any; @@ -65,8 +65,7 @@ function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { if (!globalThisAny.getDotnetRuntime) { globalThisAny.getDotnetRuntime = (runtimeId: string) => globalThisAny.getDotnetRuntime.__list.getRuntime(runtimeId); globalThisAny.getDotnetRuntime.__list = runtimeList = new RuntimeList(); - } - else { + } else { runtimeList = globalThisAny.getDotnetRuntime.__list; } @@ -76,7 +75,7 @@ function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { class RuntimeList { private list: { [runtimeId: number]: WeakRef } = {}; - public registerRuntime(api: RuntimeAPI): number { + public registerRuntime (api: RuntimeAPI): number { if (api.runtimeId === undefined) { api.runtimeId = Object.keys(this.list).length; } @@ -85,7 +84,7 @@ class RuntimeList { return api.runtimeId; } - public getRuntime(runtimeId: number): RuntimeAPI | undefined { + public getRuntime (runtimeId: number): RuntimeAPI | undefined { const wr = this.list[runtimeId]; return wr ? wr.deref() : undefined; } @@ -94,4 +93,4 @@ class RuntimeList { // export external API export { passEmscriptenInternals, initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals -}; \ No newline at end of file +}; diff --git a/src/mono/browser/runtime/gc-handles.ts b/src/mono/browser/runtime/gc-handles.ts index cf39ddc822a917..323c3826b7ed82 100644 --- a/src/mono/browser/runtime/gc-handles.ts +++ b/src/mono/browser/runtime/gc-handles.ts @@ -4,14 +4,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import { loaderHelpers, mono_assert } from "./globals"; -import { assert_js_interop, js_import_wrapper_by_fn_handle } from "./invoke-js"; -import { mono_log_info, mono_log_warn } from "./logging"; -import { bound_cs_function_symbol, imported_js_function_symbol, proxy_debug_symbol } from "./marshal"; -import { GCHandle, GCHandleNull, JSHandle, WeakRefInternal } from "./types/internal"; -import { _use_weak_ref, create_strong_ref, create_weak_ref } from "./weak-ref"; -import { exportsByAssembly } from "./invoke-cs"; -import { release_js_owned_object_by_gc_handle } from "./managed-exports"; +import {loaderHelpers, mono_assert} from "./globals"; +import {assert_js_interop, js_import_wrapper_by_fn_handle} from "./invoke-js"; +import {mono_log_info, mono_log_warn} from "./logging"; +import {bound_cs_function_symbol, imported_js_function_symbol, proxy_debug_symbol} from "./marshal"; +import {GCHandle, GCHandleNull, JSHandle, WeakRefInternal} from "./types/internal"; +import {_use_weak_ref, create_strong_ref, create_weak_ref} from "./weak-ref"; +import {exportsByAssembly} from "./invoke-cs"; +import {release_js_owned_object_by_gc_handle} from "./managed-exports"; const _use_finalization_registry = typeof globalThis.FinalizationRegistry === "function"; let _js_owned_object_registry: FinalizationRegistry; @@ -31,24 +31,24 @@ let _next_gcv_handle = -2; // GCVHandle is like GCHandle, but it's not tracked and allocated by the mono GC, but just by JS. // It's used when we need to create GCHandle-like identity ahead of time, before calling Mono. // they have negative values, so that they don't collide with GCHandles. -export function alloc_gcv_handle(): GCHandle { +export function alloc_gcv_handle (): GCHandle { const gcv_handle = _gcv_handle_free_list.length ? _gcv_handle_free_list.pop() : _next_gcv_handle--; return gcv_handle as any; } -export function free_gcv_handle(gcv_handle: GCHandle): void { +export function free_gcv_handle (gcv_handle: GCHandle): void { _gcv_handle_free_list.push(gcv_handle); } -export function is_jsv_handle(js_handle: JSHandle): boolean { +export function is_jsv_handle (js_handle: JSHandle): boolean { return (js_handle as any) < -1; } -export function is_js_handle(js_handle: JSHandle): boolean { +export function is_js_handle (js_handle: JSHandle): boolean { return (js_handle as any) > 0; } -export function is_gcv_handle(gc_handle: GCHandle): boolean { +export function is_gcv_handle (gc_handle: GCHandle): boolean { return (gc_handle as any) < -1; } @@ -62,7 +62,7 @@ export const cs_owned_js_handle_symbol = Symbol.for("wasm cs_owned_js_handle"); export const do_not_force_dispose = Symbol.for("wasm do_not_force_dispose"); -export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { +export function mono_wasm_get_jsobj_from_js_handle (js_handle: JSHandle): any { if (is_js_handle(js_handle)) return _cs_owned_objects_by_js_handle[js_handle]; if (is_jsv_handle(js_handle)) @@ -70,7 +70,7 @@ export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { return null; } -export function mono_wasm_get_js_handle(js_obj: any): JSHandle { +export function mono_wasm_get_js_handle (js_obj: any): JSHandle { assert_js_interop(); if (js_obj[cs_owned_js_handle_symbol]) { return js_obj[cs_owned_js_handle_symbol]; @@ -91,7 +91,7 @@ export function mono_wasm_get_js_handle(js_obj: any): JSHandle { return js_handle as JSHandle; } -export function register_with_jsv_handle(js_obj: any, jsv_handle: JSHandle) { +export function register_with_jsv_handle (js_obj: any, jsv_handle: JSHandle) { assert_js_interop(); // note _cs_owned_objects_by_js_handle is list, not Map. That's why we maintain _js_handle_free_list. _cs_owned_objects_by_jsv_handle[0 - jsv_handle] = js_obj; @@ -102,14 +102,13 @@ export function register_with_jsv_handle(js_obj: any, jsv_handle: JSHandle) { } // note: in MT, this is called from locked JSProxyContext. Don't call anything that would need locking. -export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { +export function mono_wasm_release_cs_owned_object (js_handle: JSHandle): void { let obj: any; if (is_js_handle(js_handle)) { obj = _cs_owned_objects_by_js_handle[js_handle]; _cs_owned_objects_by_js_handle[js_handle] = undefined; _js_handle_free_list.push(js_handle); - } - else if (is_jsv_handle(js_handle)) { + } else if (is_jsv_handle(js_handle)) { obj = _cs_owned_objects_by_jsv_handle[0 - js_handle]; _cs_owned_objects_by_jsv_handle[0 - js_handle] = undefined; // see free list in JSProxyContext.FreeJSVHandle @@ -120,7 +119,7 @@ export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { } } -export function setup_managed_proxy(owner: any, gc_handle: GCHandle): void { +export function setup_managed_proxy (owner: any, gc_handle: GCHandle): void { assert_js_interop(); // keep the gc_handle so that we could easily convert it back to original C# object for roundtrip owner[js_owned_gc_handle_symbol] = gc_handle; @@ -137,7 +136,7 @@ export function setup_managed_proxy(owner: any, gc_handle: GCHandle): void { _js_owned_object_table.set(gc_handle, wr); } -export function upgrade_managed_proxy_to_strong_ref(owner: any, gc_handle: GCHandle): void { +export function upgrade_managed_proxy_to_strong_ref (owner: any, gc_handle: GCHandle): void { const sr = create_strong_ref(owner); if (_use_finalization_registry) { _js_owned_object_registry.unregister(owner); @@ -145,7 +144,7 @@ export function upgrade_managed_proxy_to_strong_ref(owner: any, gc_handle: GCHan _js_owned_object_table.set(gc_handle, sr); } -export function teardown_managed_proxy(owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { +export function teardown_managed_proxy (owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { assert_js_interop(); // The JS object associated with this gc_handle has been collected by the JS GC. // As such, it's not possible for this gc_handle to be invoked by JS anymore, so @@ -169,13 +168,13 @@ export function teardown_managed_proxy(owner: any, gc_handle: GCHandle, skipMana } } -export function assert_not_disposed(result: any): GCHandle { +export function assert_not_disposed (result: any): GCHandle { const gc_handle = result[js_owned_gc_handle_symbol]; mono_check(gc_handle != GCHandleNull, "ObjectDisposedException"); return gc_handle; } -function _js_owned_object_finalized(gc_handle: GCHandle): void { +function _js_owned_object_finalized (gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { // We're shutting down, so don't bother doing anything else. return; @@ -183,7 +182,7 @@ function _js_owned_object_finalized(gc_handle: GCHandle): void { teardown_managed_proxy(null, gc_handle); } -export function _lookup_js_owned_object(gc_handle: GCHandle): any { +export function _lookup_js_owned_object (gc_handle: GCHandle): any { if (!gc_handle) return null; const wr = _js_owned_object_table.get(gc_handle); @@ -195,7 +194,7 @@ export function _lookup_js_owned_object(gc_handle: GCHandle): any { return null; } -export function assertNoProxies(): void { +export function assertNoProxies (): void { if (!WasmEnableThreads) return; mono_assert(_js_owned_object_table.size === 0, "There should be no proxies on this thread."); mono_assert(_cs_owned_objects_by_js_handle.length === 1, "There should be no proxies on this thread."); @@ -208,7 +207,7 @@ let force_dispose_proxies_in_progress = false; // when we arrive here from UninstallWebWorkerInterop, the C# will unregister the handles too. // when called from elsewhere, C# side could be unbalanced!! -export function forceDisposeProxies(disposeMethods: boolean, verbose: boolean): void { +export function forceDisposeProxies (disposeMethods: boolean, verbose: boolean): void { let keepSomeCsAlive = false; let keepSomeJsAlive = false; force_dispose_proxies_in_progress = true; @@ -336,4 +335,4 @@ export function forceDisposeProxies(disposeMethods: boolean, verbose: boolean): exportsByAssembly.clear(); } mono_log_info(`forceDisposeProxies done: ${doneImports} imports, ${doneExports} exports, ${doneGCHandles} GCHandles, ${doneJSHandles} JSHandles.`); -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/gc-lock.ts b/src/mono/browser/runtime/gc-lock.ts index ea373eecc0447d..7aef7ef2e6827e 100644 --- a/src/mono/browser/runtime/gc-lock.ts +++ b/src/mono/browser/runtime/gc-lock.ts @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import { ENVIRONMENT_IS_PTHREAD } from "./globals"; +import {ENVIRONMENT_IS_PTHREAD} from "./globals"; import cwraps from "./cwraps"; export let gc_locked = false; -export function mono_wasm_gc_lock(): void { +export function mono_wasm_gc_lock (): void { if (gc_locked) { throw new Error("GC is already locked"); } @@ -20,7 +20,7 @@ export function mono_wasm_gc_lock(): void { gc_locked = true; } -export function mono_wasm_gc_unlock(): void { +export function mono_wasm_gc_unlock (): void { if (!gc_locked) { throw new Error("GC is not locked"); } diff --git a/src/mono/browser/runtime/globals.ts b/src/mono/browser/runtime/globals.ts index 9513254cc55aa4..8653f415b79fb6 100644 --- a/src/mono/browser/runtime/globals.ts +++ b/src/mono/browser/runtime/globals.ts @@ -8,9 +8,9 @@ import gitHash from "consts:gitHash"; -import { RuntimeAPI } from "./types/index"; -import type { GlobalObjects, EmscriptenInternals, RuntimeHelpers, LoaderHelpers, DotnetModuleInternal, PromiseAndController, EmscriptenBuildOptions, GCHandle } from "./types/internal"; -import { mono_log_error } from "./logging"; +import {RuntimeAPI} from "./types/index"; +import type {GlobalObjects, EmscriptenInternals, RuntimeHelpers, LoaderHelpers, DotnetModuleInternal, PromiseAndController, EmscriptenBuildOptions, GCHandle} from "./types/internal"; +import {mono_log_error} from "./logging"; // these are our public API (except internal) export let Module: DotnetModuleInternal; @@ -32,7 +32,7 @@ export let loaderHelpers: LoaderHelpers = null as any; export let _runtimeModuleLoaded = false; // please keep it in place also as rollup guard -export function passEmscriptenInternals(internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { +export function passEmscriptenInternals (internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { runtimeHelpers.emscriptenBuildOptions = emscriptenBuildOptions; ENVIRONMENT_IS_PTHREAD = internals.isPThread; @@ -44,7 +44,7 @@ export function passEmscriptenInternals(internals: EmscriptenInternals, emscript } // NOTE: this is called AFTER the config is loaded -export function setRuntimeGlobals(globalObjects: GlobalObjects) { +export function setRuntimeGlobals (globalObjects: GlobalObjects) { if (_runtimeModuleLoaded) { throw new Error("Runtime module already loaded"); } @@ -68,8 +68,12 @@ export function setRuntimeGlobals(globalObjects: GlobalObjects) { afterIOStarted: createPromiseController(), afterOnRuntimeInitialized: createPromiseController(), afterPostRun: createPromiseController(), - nativeAbort: (reason: any) => { throw reason || new Error("abort"); }, - nativeExit: (code: number) => { throw new Error("exit:" + code); }, + nativeAbort: (reason: any) => { + throw reason || new Error("abort"); + }, + nativeExit: (code: number) => { + throw new Error("exit:" + code); + }, }; Object.assign(runtimeHelpers, rh); @@ -82,14 +86,14 @@ export function setRuntimeGlobals(globalObjects: GlobalObjects) { }); } -export function createPromiseController(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { return loaderHelpers.createPromiseController(afterResolve, afterReject); } // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() diff --git a/src/mono/browser/runtime/guarded-promise.ts b/src/mono/browser/runtime/guarded-promise.ts index fe46ca43521ba2..8901403b758bef 100644 --- a/src/mono/browser/runtime/guarded-promise.ts +++ b/src/mono/browser/runtime/guarded-promise.ts @@ -3,7 +3,7 @@ /// A Promise that guards against multiple-resolve, multiple-reject, reject-after-accept and accept-after-reject. class GuardedPromise extends Promise { - constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { + constructor (executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { super((resolve, reject) => { let resolved = false; let rejected = false; diff --git a/src/mono/browser/runtime/http.ts b/src/mono/browser/runtime/http.ts index 0e45e2ec819752..ccbe131c419131 100644 --- a/src/mono/browser/runtime/http.ts +++ b/src/mono/browser/runtime/http.ts @@ -3,15 +3,15 @@ import BuildConfiguration from "consts:configuration"; -import { wrap_as_cancelable_promise } from "./cancelable-promise"; -import { ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert } from "./globals"; -import { assert_js_interop } from "./invoke-js"; -import { MemoryViewType, Span } from "./marshal"; -import type { VoidPtr } from "./types/emscripten"; -import { ControllablePromise } from "./types/internal"; +import {wrap_as_cancelable_promise} from "./cancelable-promise"; +import {ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert} from "./globals"; +import {assert_js_interop} from "./invoke-js"; +import {MemoryViewType, Span} from "./marshal"; +import type {VoidPtr} from "./types/emscripten"; +import {ControllablePromise} from "./types/internal"; -function verifyEnvironment() { +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. See also https://aka.ms/dotnet-wasm-features" @@ -20,13 +20,13 @@ function verifyEnvironment() { } } -function commonAsserts(controller: HttpController) { +function commonAsserts (controller: HttpController) { assert_js_interop(); mono_assert(controller, "expected controller"); } let http_wasm_supports_streaming_request_cached: boolean | undefined; -export function http_wasm_supports_streaming_request(): boolean { +export function http_wasm_supports_streaming_request (): boolean { if (http_wasm_supports_streaming_request_cached !== undefined) { return http_wasm_supports_streaming_request_cached; } @@ -42,7 +42,7 @@ export function http_wasm_supports_streaming_request(): boolean { const hasContentType = new Request("", { body: new ReadableStream(), method: "POST", - get duplex() { + get duplex () { duplexAccessed = true; return "half"; }, @@ -55,7 +55,7 @@ export function http_wasm_supports_streaming_request(): boolean { } let http_wasm_supports_streaming_response_cached: boolean | undefined; -export function http_wasm_supports_streaming_response(): boolean { +export function http_wasm_supports_streaming_response (): boolean { if (http_wasm_supports_streaming_response_cached !== undefined) { return http_wasm_supports_streaming_response_cached; } @@ -63,7 +63,7 @@ export function http_wasm_supports_streaming_response(): boolean { return http_wasm_supports_streaming_response_cached; } -export function http_wasm_create_controller(): HttpController { +export function http_wasm_create_controller (): HttpController { verifyEnvironment(); assert_js_interop(); const controller: HttpController = { @@ -72,19 +72,18 @@ export function http_wasm_create_controller(): HttpController { return controller; } -export function http_wasm_abort_request(controller: HttpController): void { +export function http_wasm_abort_request (controller: HttpController): void { try { if (controller.streamWriter) { controller.streamWriter.abort(); } - } - catch (err) { + } catch (err) { // ignore } http_wasm_abort_response(controller); } -export function http_wasm_abort_response(controller: HttpController): void { +export function http_wasm_abort_response (controller: HttpController): void { if (BuildConfiguration === "Debug") commonAsserts(controller); try { if (controller.streamReader) { @@ -96,13 +95,12 @@ export function http_wasm_abort_response(controller: HttpController): void { }); } controller.abortController.abort(); - } - catch (err) { + } catch (err) { // ignore } } -export function http_wasm_transform_stream_write(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_transform_stream_write (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(bufferLength > 0, "expected bufferLength > 0"); // the bufferPtr is pinned by the caller @@ -117,7 +115,7 @@ export function http_wasm_transform_stream_write(controller: HttpController, buf }); } -export function http_wasm_transform_stream_close(controller: HttpController): ControllablePromise { +export function http_wasm_transform_stream_close (controller: HttpController): ControllablePromise { mono_assert(controller, "expected controller"); return wrap_as_cancelable_promise(async () => { mono_assert(controller.streamWriter, "expected streamWriter"); @@ -128,7 +126,7 @@ export function http_wasm_transform_stream_close(controller: HttpController): Co }); } -export function http_wasm_fetch_stream(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { +export function http_wasm_fetch_stream (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); const transformStream = new TransformStream(); controller.streamWriter = transformStream.writable.getWriter(); @@ -136,7 +134,7 @@ export function http_wasm_fetch_stream(controller: HttpController, url: string, return fetch_promise; } -export function http_wasm_fetch_bytes(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { +export function http_wasm_fetch_bytes (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bodyPtr is pinned by the caller const view = new Span(bodyPtr, bodyLength, MemoryViewType.Byte); @@ -144,7 +142,7 @@ export function http_wasm_fetch_bytes(controller: HttpController, url: string, h return http_wasm_fetch(controller, url, header_names, header_values, option_names, option_values, copy); } -export function http_wasm_fetch(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { +export function http_wasm_fetch (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); verifyEnvironment(); assert_js_interop(); @@ -190,30 +188,30 @@ export function http_wasm_fetch(controller: HttpController, url: string, header_ return controller.responsePromise; } -export function http_wasm_get_response_type(controller: HttpController): string | undefined { +export function http_wasm_get_response_type (controller: HttpController): string | undefined { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.type; } -export function http_wasm_get_response_status(controller: HttpController): number { +export function http_wasm_get_response_status (controller: HttpController): number { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.status ?? 0; } -export function http_wasm_get_response_header_names(controller: HttpController): string[] { +export function http_wasm_get_response_header_names (controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderNames, "expected responseHeaderNames"); return controller.responseHeaderNames; } -export function http_wasm_get_response_header_values(controller: HttpController): string[] { +export function http_wasm_get_response_header_values (controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderValues, "expected responseHeaderValues"); return controller.responseHeaderValues; } -export function http_wasm_get_response_length(controller: HttpController): ControllablePromise { +export function http_wasm_get_response_length (controller: HttpController): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); return wrap_as_cancelable_promise(async () => { const buffer = await controller.response!.arrayBuffer(); @@ -223,7 +221,7 @@ export function http_wasm_get_response_length(controller: HttpController): Contr }); } -export function http_wasm_get_response_bytes(controller: HttpController, view: Span): number { +export function http_wasm_get_response_bytes (controller: HttpController, view: Span): number { mono_assert(controller, "expected controller"); mono_assert(controller.responseBuffer, "expected resoved arrayBuffer"); mono_assert(controller.currentBufferOffset != undefined, "expected currentBufferOffset"); @@ -237,7 +235,7 @@ export function http_wasm_get_response_bytes(controller: HttpController, view: S return bytes_read; } -export function http_wasm_get_streamed_response_bytes(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_get_streamed_response_bytes (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); diff --git a/src/mono/browser/runtime/hybrid-globalization/calendar.ts b/src/mono/browser/runtime/hybrid-globalization/calendar.ts index 002c76da1be135..0e33ab7ed3eaad 100644 --- a/src/mono/browser/runtime/hybrid-globalization/calendar.ts +++ b/src/mono/browser/runtime/hybrid-globalization/calendar.ts @@ -2,20 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. /* eslint-disable no-inner-declarations */ -import { mono_wasm_new_external_root } from "../roots"; -import { monoStringToString, stringToUTF16 } from "../strings"; -import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; -import { Int32Ptr } from "../types/emscripten"; -import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; -import { INNER_SEPARATOR, OUTER_SEPARATOR, normalizeSpaces } from "./helpers"; +import {mono_wasm_new_external_root} from "../roots"; +import {monoStringToString, stringToUTF16} from "../strings"; +import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; +import {Int32Ptr} from "../types/emscripten"; +import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; +import {INNER_SEPARATOR, OUTER_SEPARATOR, normalizeSpaces} from "./helpers"; const MONTH_CODE = "MMMM"; const YEAR_CODE = "yyyy"; const DAY_CODE = "d"; // this function joins all calendar info with OUTER_SEPARATOR into one string and returns it back to managed code -export function mono_wasm_get_calendar_info(culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number -{ +export function mono_wasm_get_calendar_info (culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -57,78 +56,67 @@ export function mono_wasm_get_calendar_info(culture: MonoStringRef, calendarId: calendarInfo.AbbreviatedEraNames = eraNames.abbreviatedEraNames; const result = Object.values(calendarInfo).join(OUTER_SEPARATOR); - if (result.length > dstLength) - { + if (result.length > dstLength) { throw new Error(`Calendar info exceeds length of ${dstLength}.`); } stringToUTF16(dst, dst + 2 * result.length, result); wrap_no_error_root(isException, exceptionRoot); return result.length; - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(isException, ex, exceptionRoot); return -1; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -function getCalendarName(locale: any){ +function getCalendarName (locale: any) { const calendars = getCalendarInfo(locale); if (!calendars || calendars.length == 0) return ""; return calendars[0]; } -function getCalendarInfo(locale: string) -{ +function getCalendarInfo (locale: string) { try { // most tools have it implemented as a property return (new Intl.Locale(locale) as any).calendars; - } - catch { + } catch { try { // but a few use methods, which is the preferred way return (new Intl.Locale(locale) as any).getCalendars(); - } - catch - { + } catch { return undefined; } } } -function getMonthYearPattern(locale: string | undefined, date: Date): string -{ - let pattern = date.toLocaleDateString(locale, { year: "numeric", month: "long" }).toLowerCase(); +function getMonthYearPattern (locale: string | undefined, date: Date): string { + let pattern = date.toLocaleDateString(locale, {year: "numeric", month: "long"}).toLowerCase(); // pattern has month name as string or as number - const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); - if (monthName.charAt(monthName.length - 1) == "\u6708") - { + const monthName = date.toLocaleString(locale, {month: "long"}).toLowerCase().trim(); + if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "yyyy\u5e74M\u6708"; } pattern = pattern.replace(monthName, MONTH_CODE); pattern = pattern.replace("999", YEAR_CODE); // sometimes the number is localized and the above does not have an effect - const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); + const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); pattern = normalizeSpaces(pattern); return pattern.replace(yearStr, YEAR_CODE); } -function getMonthDayPattern(locale: string | undefined, date: Date): string -{ - let pattern = date.toLocaleDateString(locale, { month: "long", day: "numeric"}).toLowerCase(); +function getMonthDayPattern (locale: string | undefined, date: Date): string { + let pattern = date.toLocaleDateString(locale, {month: "long", day: "numeric"}).toLowerCase(); // pattern has month name as string or as number - const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); - if (monthName.charAt(monthName.length - 1) == "\u6708") - { + const monthName = date.toLocaleString(locale, {month: "long"}).toLowerCase().trim(); + if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "M\u6708d\u65e5"; } - const formatWithoutMonthName = new Intl.DateTimeFormat(locale, { day: "numeric" }); + const formatWithoutMonthName = new Intl.DateTimeFormat(locale, {day: "numeric"}); const replacedMonthName = getGenitiveForName(date, pattern, monthName, formatWithoutMonthName); pattern = pattern.replace(replacedMonthName, MONTH_CODE); pattern = pattern.replace("22", DAY_CODE); @@ -136,10 +124,8 @@ function getMonthDayPattern(locale: string | undefined, date: Date): string return pattern.replace(dayStr, DAY_CODE); } -function getShortDatePattern(locale: string | undefined): string -{ - if (locale?.substring(0, 2) == "fa") - { +function getShortDatePattern (locale: string | undefined): string { + if (locale?.substring(0, 2) == "fa") { // persian calendar is shifted and it has no lapping dates with // arabic and gregorian calendars, so that both day and month would be < 10 return "yyyy/M/d"; @@ -159,91 +145,75 @@ function getShortDatePattern(locale: string | undefined): string // toLocaleDateString returns not compatible data, // e.g. { dateStyle: "short" } sometimes contains localized year number // while { year: "numeric" } contains non-localized year number and vice versa - if (pattern.includes(shortYearStr)) - { + if (pattern.includes(shortYearStr)) { pattern = pattern.replace(longYearStr, YEAR_CODE); pattern = pattern.replace(shortYearStr, YEAR_CODE); - } - else - { - const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); + } else { + const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); const yearStrShort = yearStr.substring(yearStr.length - 2, yearStr.length); pattern = pattern.replace(yearStr, YEAR_CODE); if (yearStrShort) pattern = pattern.replace(yearStrShort, YEAR_CODE); } - if (pattern.includes(shortMonthStr)) - { + if (pattern.includes(shortMonthStr)) { pattern = pattern.replace(longMonthStr, "MM"); pattern = pattern.replace(shortMonthStr, "M"); - } - else - { - const monthStr = date.toLocaleDateString(locale, { month: "numeric" }); + } else { + const monthStr = date.toLocaleDateString(locale, {month: "numeric"}); const localizedMonthCode = monthStr.length == 1 ? "M" : "MM"; pattern = pattern.replace(monthStr, localizedMonthCode); } - if (pattern.includes(shortDayStr)) - { + if (pattern.includes(shortDayStr)) { pattern = pattern.replace(longDayStr, "dd"); pattern = pattern.replace(shortDayStr, "d"); - } - else - { - const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); + } else { + const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); const localizedDayCode = dayStr.length == 1 ? "d" : "dd"; pattern = pattern.replace(dayStr, localizedDayCode); } return normalizeSpaces(pattern); } -function getLongDatePattern(locale: string | undefined, date: Date): string -{ - if (locale == "th-TH") - { +function getLongDatePattern (locale: string | undefined, date: Date): string { + if (locale == "th-TH") { // cannot be caught with regexes return "ddddที่ d MMMM g yyyy"; } - let pattern = new Intl.DateTimeFormat(locale, { weekday: "long", year: "numeric", month: "long", day: "numeric"}).format(date).toLowerCase(); - const monthName = date.toLocaleString(locale, { month: "long" }).trim().toLowerCase(); + let pattern = new Intl.DateTimeFormat(locale, {weekday: "long", year: "numeric", month: "long", day: "numeric"}).format(date).toLowerCase(); + const monthName = date.toLocaleString(locale, {month: "long"}).trim().toLowerCase(); // pattern has month name as string or as number const monthSuffix = monthName.charAt(monthName.length - 1); - if (monthSuffix == "\u6708" || monthSuffix == "\uc6d4") - { + if (monthSuffix == "\u6708" || monthSuffix == "\uc6d4") { // Asian-like patterns: - const shortMonthName = date.toLocaleString(locale, { month: "short" }); + const shortMonthName = date.toLocaleString(locale, {month: "short"}); pattern = pattern.replace(shortMonthName, `M${monthSuffix}`); - } - else - { - const replacedMonthName = getGenitiveForName(date, pattern, monthName, new Intl.DateTimeFormat(locale, { weekday: "long", year: "numeric", day: "numeric"})); + } else { + const replacedMonthName = getGenitiveForName(date, pattern, monthName, new Intl.DateTimeFormat(locale, {weekday: "long", year: "numeric", day: "numeric"})); pattern = pattern.replace(replacedMonthName, MONTH_CODE); } pattern = pattern.replace("999", YEAR_CODE); // sometimes the number is localized and the above does not have an effect, // so additionally, we need to do: - const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); + const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); pattern = pattern.replace(yearStr, YEAR_CODE); - const weekday = date.toLocaleDateString(locale, { weekday: "long" }).toLowerCase(); - const replacedWeekday = getGenitiveForName(date, pattern, weekday, new Intl.DateTimeFormat(locale, { year: "numeric", month: "long", day: "numeric"})); + const weekday = date.toLocaleDateString(locale, {weekday: "long"}).toLowerCase(); + const replacedWeekday = getGenitiveForName(date, pattern, weekday, new Intl.DateTimeFormat(locale, {year: "numeric", month: "long", day: "numeric"})); pattern = pattern.replace(replacedWeekday, "dddd"); pattern = pattern.replace("22", DAY_CODE); - const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); // should we replace it for localized digits? + const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); // should we replace it for localized digits? pattern = normalizeSpaces(pattern); return pattern.replace(dayStr, DAY_CODE); } -function getGenitiveForName(date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) -{ +function getGenitiveForName (date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) { let genitiveName = name; const nameStart = pattern.indexOf(name); if (nameStart == -1 || // genitive month name can include monthName and monthName can include spaces, e.g. "tháng 11":, so we cannot use pattern.includes() or pattern.split(" ").includes() - (nameStart != -1 && pattern.length > nameStart + name.length && pattern[nameStart + name.length] != " " && pattern[nameStart + name.length] != "," && pattern[nameStart + name.length] != "\u060c")) - { + (nameStart != -1 && pattern.length > nameStart + name.length && pattern[nameStart + name.length] != " " && pattern[nameStart + name.length] != "," && pattern[nameStart + name.length] != "\u060c")) { // needs to be in Genitive form to be useful // e.g. // pattern = '999 m. lapkričio 22 d., šeštadienis', @@ -256,24 +226,21 @@ function getGenitiveForName(date: Date, pattern: string, name: string, formatWit return genitiveName; } -function getDayNames(locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } -{ +function getDayNames (locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } { const weekDay = new Date(2023, 5, 25); // Sunday const dayNames = []; const dayNamesAbb = []; const dayNamesSS = []; - for(let i=0; i<7; i++) - { - dayNames[i] = weekDay.toLocaleDateString(locale, { weekday: "long" }); - dayNamesAbb[i] = weekDay.toLocaleDateString(locale, { weekday: "short" }); - dayNamesSS[i] = weekDay.toLocaleDateString(locale, { weekday: "narrow" }); + for(let i = 0; i < 7; i++) { + dayNames[i] = weekDay.toLocaleDateString(locale, {weekday: "long"}); + dayNamesAbb[i] = weekDay.toLocaleDateString(locale, {weekday: "short"}); + dayNamesSS[i] = weekDay.toLocaleDateString(locale, {weekday: "narrow"}); weekDay.setDate(weekDay.getDate() + 1); } - return {long: dayNames, abbreviated: dayNamesAbb, shortest: dayNamesSS }; + return {long: dayNames, abbreviated: dayNamesAbb, shortest: dayNamesSS}; } -function getMonthNames(locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } -{ +function getMonthNames (locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } { // some calendars have the first month on non-0 index in JS // first month: Muharram ("ar") or Farwardin ("fa") or January const localeLang = locale ? locale.split("-")[0] : ""; @@ -284,47 +251,42 @@ function getMonthNames(locale: string | undefined) : { long: string[], abbreviat const monthsGen: string[] = []; const monthsAbbGen: string[] = []; let isChineeseStyle, isShortFormBroken; - for(let i = firstMonthShift; i < 12 + firstMonthShift; i++) - { + for(let i = firstMonthShift; i < 12 + firstMonthShift; i++) { const monthCnt = i % 12; date.setMonth(monthCnt); - const monthNameLong = date.toLocaleDateString(locale, { month: "long" }); - const monthNameShort = date.toLocaleDateString(locale, { month: "short" }); + const monthNameLong = date.toLocaleDateString(locale, {month: "long"}); + const monthNameShort = date.toLocaleDateString(locale, {month: "short"}); months[i - firstMonthShift] = monthNameLong; monthsAbb[i - firstMonthShift] = monthNameShort; // for Genitive forms: isChineeseStyle = isChineeseStyle ?? monthNameLong.charAt(monthNameLong.length - 1) == "\u6708"; - if (isChineeseStyle) - { + if (isChineeseStyle) { // for Chinese-like calendar's Genitive = Nominative monthsGen[i - firstMonthShift] = monthNameLong; monthsAbbGen[i - firstMonthShift] = monthNameShort; continue; } - const formatWithoutMonthName = new Intl.DateTimeFormat(locale, { day: "numeric" }); - const monthWithDayLong = date.toLocaleDateString(locale, { month: "long", day: "numeric"}); + const formatWithoutMonthName = new Intl.DateTimeFormat(locale, {day: "numeric"}); + const monthWithDayLong = date.toLocaleDateString(locale, {month: "long", day: "numeric"}); monthsGen[i - firstMonthShift] = getGenitiveForName(date, monthWithDayLong, monthNameLong, formatWithoutMonthName); isShortFormBroken = isShortFormBroken ?? /^\d+$/.test(monthNameShort); - if (isShortFormBroken) - { + if (isShortFormBroken) { // for buggy locales e.g. lt-LT, short month contains only number instead of string // we leave Genitive = Nominative monthsAbbGen[i - firstMonthShift] = monthNameShort; continue; } - const monthWithDayShort = date.toLocaleDateString(locale, { month: "short", day: "numeric"}); + const monthWithDayShort = date.toLocaleDateString(locale, {month: "short", day: "numeric"}); monthsAbbGen[i - firstMonthShift] = getGenitiveForName(date, monthWithDayShort, monthNameShort, formatWithoutMonthName); } - return {long: months, abbreviated: monthsAbb, longGenitive: monthsGen, abbreviatedGenitive: monthsAbbGen }; + return {long: months, abbreviated: monthsAbb, longGenitive: monthsGen, abbreviatedGenitive: monthsAbbGen}; } // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. -function getEraNames(date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} -{ - if (shouldBePopulatedByManagedCode(calendarId)) - { +function getEraNames (date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} { + if (shouldBePopulatedByManagedCode(calendarId)) { // managed code already handles these calendars, // so empty strings will get overwritten in // InitializeEraNames/InitializeAbbreviatedEraNames @@ -333,10 +295,10 @@ function getEraNames(date: Date, locale: string | undefined, calendarId: number) abbreviatedEraNames: "" }; } - const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); - const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); - const eraDate = date.toLocaleDateString(locale, { era: "short" }); - const shortEraDate = date.toLocaleDateString(locale, { era: "narrow" }); + const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); + const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); + const eraDate = date.toLocaleDateString(locale, {era: "short"}); + const shortEraDate = date.toLocaleDateString(locale, {era: "narrow"}); const eraDateParts = eraDate.includes(yearStr) ? getEraDateParts(yearStr) : @@ -347,13 +309,11 @@ function getEraNames(date: Date, locale: string | undefined, calendarId: number) abbreviatedEraNames: getEraFromDateParts(eraDateParts.abbrEraDateParts, eraDateParts.ignoredPart) }; - function shouldBePopulatedByManagedCode(calendarId: number) - { + function shouldBePopulatedByManagedCode (calendarId: number) { return (calendarId > 1 && calendarId < 15) || calendarId == 22 || calendarId == 23; } - function getEraFromDateParts(dateParts: string[], ignoredPart: string) : string - { + function getEraFromDateParts (dateParts: string[], ignoredPart: string) : string { const regex = new RegExp(`^((?!${ignoredPart}|[0-9]).)*$`); const filteredEra = dateParts.filter(part => regex.test(part)); if (filteredEra.length == 0) @@ -361,10 +321,8 @@ function getEraNames(date: Date, locale: string | undefined, calendarId: number) return filteredEra[0].trim(); } - function getEraDateParts(yearStr: string) - { - if (eraDate.startsWith(yearStr) || eraDate.endsWith(yearStr)) - { + function getEraDateParts (yearStr: string) { + if (eraDate.startsWith(yearStr) || eraDate.endsWith(yearStr)) { return { eraDateParts: eraDate.split(dayStr), abbrEraDateParts: shortEraDate.split(dayStr), diff --git a/src/mono/browser/runtime/hybrid-globalization/change-case.ts b/src/mono/browser/runtime/hybrid-globalization/change-case.ts index f9d227517b819b..d502dd02a301e9 100644 --- a/src/mono/browser/runtime/hybrid-globalization/change-case.ts +++ b/src/mono/browser/runtime/hybrid-globalization/change-case.ts @@ -1,23 +1,22 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_wasm_new_external_root } from "../roots"; -import { monoStringToString, utf16ToStringLoop, stringToUTF16 } from "../strings"; -import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; -import { Int32Ptr } from "../types/emscripten"; -import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; -import { localHeapViewU16, setU16_local } from "../memory"; -import { isSurrogate } from "./helpers"; +import {mono_wasm_new_external_root} from "../roots"; +import {monoStringToString, utf16ToStringLoop, stringToUTF16} from "../strings"; +import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; +import {Int32Ptr} from "../types/emscripten"; +import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; +import {localHeapViewU16, setU16_local} from "../memory"; +import {isSurrogate} from "./helpers"; -export function mono_wasm_change_case_invariant(src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case_invariant (src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const exceptionRoot = mono_wasm_new_external_root(ex_address); try { const input = utf16ToStringLoop(src, src + 2 * srcLength); const result = toUpper ? input.toUpperCase() : input.toLowerCase(); // Unicode defines some codepoints which expand into multiple codepoints, // originally we do not support this expansion - if (result.length <= dstLength) - { + if (result.length <= dstLength) { stringToUTF16(dst, dst + 2 * dstLength, result); wrap_no_error_root(is_exception, exceptionRoot); return; @@ -26,62 +25,49 @@ export function mono_wasm_change_case_invariant(src: number, srcLength: number, // workaround to maintain the ICU-like behavior const heapI16 = localHeapViewU16(); let jump = 1; - if (toUpper) - { - for (let i=0; i < input.length; i+=jump) - { + if (toUpper) { + for (let i = 0; i < input.length; i += jump) { // surrogate parts have to enter ToUpper/ToLower together to give correct output - if (isSurrogate(input, i)) - { + if (isSurrogate(input, i)) { jump = 2; - const surrogate = input.substring(i, i+2); + const surrogate = input.substring(i, i + 2); const upperSurrogate = surrogate.toUpperCase(); const appendedSurrogate = upperSurrogate.length > 2 ? surrogate : upperSurrogate; appendSurrogateToMemory(heapI16, dst, appendedSurrogate, i); - } - else - { + } else { jump = 1; const upperChar = input[i].toUpperCase(); const appendedChar = upperChar.length > 1 ? input[i] : upperChar; - setU16_local(heapI16, dst + i*2, appendedChar.charCodeAt(0)); + setU16_local(heapI16, dst + i * 2, appendedChar.charCodeAt(0)); } } - } - else - { - for (let i=0; i < input.length; i+=jump) - { - if (isSurrogate(input, i)) - { + } else { + for (let i = 0; i < input.length; i += jump) { + if (isSurrogate(input, i)) { jump = 2; - const surrogate = input.substring(i, i+2); + const surrogate = input.substring(i, i + 2); const upperSurrogate = surrogate.toLowerCase(); const appendedSurrogate = upperSurrogate.length > 2 ? surrogate : upperSurrogate; appendSurrogateToMemory(heapI16, dst, appendedSurrogate, i); - } - else - { + } else { jump = 1; const upperChar = input[i].toLowerCase(); const appendedChar = upperChar.length > 1 ? input[i] : upperChar; - setU16_local(heapI16, dst + i*2, appendedChar.charCodeAt(0)); + setU16_local(heapI16, dst + i * 2, appendedChar.charCodeAt(0)); } } } wrap_no_error_root(is_exception, exceptionRoot); - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); - } - finally { + } finally { exceptionRoot.release(); } } -export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case (culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -91,8 +77,7 @@ export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLe const input = utf16ToStringLoop(src, src + 2 * srcLength); const result = toUpper ? input.toLocaleUpperCase(cultureName) : input.toLocaleLowerCase(cultureName); - if (result.length <= input.length) - { + if (result.length <= input.length) { stringToUTF16(dst, dst + 2 * dstLength, result); wrap_no_error_root(is_exception, exceptionRoot); return; @@ -100,64 +85,50 @@ export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLe // workaround to maintain the ICU-like behavior const heapI16 = localHeapViewU16(); let jump = 1; - if (toUpper) - { - for (let i=0; i < input.length; i+=jump) - { + if (toUpper) { + for (let i = 0; i < input.length; i += jump) { // surrogate parts have to enter ToUpper/ToLower together to give correct output - if (isSurrogate(input, i)) - { + if (isSurrogate(input, i)) { jump = 2; - const surrogate = input.substring(i, i+2); + const surrogate = input.substring(i, i + 2); const upperSurrogate = surrogate.toLocaleUpperCase(cultureName); const appendedSurrogate = upperSurrogate.length > 2 ? surrogate : upperSurrogate; appendSurrogateToMemory(heapI16, dst, appendedSurrogate, i); - } - else - { + } else { jump = 1; const upperChar = input[i].toLocaleUpperCase(cultureName); const appendedChar = upperChar.length > 1 ? input[i] : upperChar; - setU16_local(heapI16, dst + i*2, appendedChar.charCodeAt(0)); + setU16_local(heapI16, dst + i * 2, appendedChar.charCodeAt(0)); } } - } - else - { - for (let i=0; i < input.length; i+=jump) - { + } else { + for (let i = 0; i < input.length; i += jump) { // surrogate parts have to enter ToUpper/ToLower together to give correct output - if (isSurrogate(input, i)) - { + if (isSurrogate(input, i)) { jump = 2; - const surrogate = input.substring(i, i+2); + const surrogate = input.substring(i, i + 2); const upperSurrogate = surrogate.toLocaleLowerCase(cultureName); const appendedSurrogate = upperSurrogate.length > 2 ? surrogate : upperSurrogate; appendSurrogateToMemory(heapI16, dst, appendedSurrogate, i); - } - else - { + } else { jump = 1; const lowerChar = input[i].toLocaleLowerCase(cultureName); const appendedChar = lowerChar.length > 1 ? input[i] : lowerChar; - setU16_local(heapI16, dst + i*2, appendedChar.charCodeAt(0)); + setU16_local(heapI16, dst + i * 2, appendedChar.charCodeAt(0)); } } } wrap_no_error_root(is_exception, exceptionRoot); - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -function appendSurrogateToMemory(heapI16: Uint16Array, dst: number, surrogate: string, idx: number) -{ - setU16_local(heapI16, dst + idx*2, surrogate.charCodeAt(0)); - setU16_local(heapI16, dst + (idx+1)*2, surrogate.charCodeAt(1)); +function appendSurrogateToMemory (heapI16: Uint16Array, dst: number, surrogate: string, idx: number) { + setU16_local(heapI16, dst + idx * 2, surrogate.charCodeAt(0)); + setU16_local(heapI16, dst + (idx + 1) * 2, surrogate.charCodeAt(1)); } diff --git a/src/mono/browser/runtime/hybrid-globalization/collations.ts b/src/mono/browser/runtime/hybrid-globalization/collations.ts index 7c1bb5a03da03c..9680fa056704f2 100644 --- a/src/mono/browser/runtime/hybrid-globalization/collations.ts +++ b/src/mono/browser/runtime/hybrid-globalization/collations.ts @@ -1,18 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_wasm_new_external_root } from "../roots"; -import { monoStringToString, utf16ToString } from "../strings"; -import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; -import { Int32Ptr } from "../types/emscripten"; -import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; -import { GraphemeSegmenter } from "./grapheme-segmenter"; +import {mono_wasm_new_external_root} from "../roots"; +import {monoStringToString, utf16ToString} from "../strings"; +import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; +import {Int32Ptr} from "../types/emscripten"; +import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; +import {GraphemeSegmenter} from "./grapheme-segmenter"; const COMPARISON_ERROR = -2; const INDEXING_ERROR = -1; let graphemeSegmenterCached: GraphemeSegmenter | null; -export function mono_wasm_compare_string(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_compare_string (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -23,18 +23,16 @@ export function mono_wasm_compare_string(culture: MonoStringRef, str1: number, s const locale = cultureName ? cultureName : undefined; wrap_no_error_root(is_exception, exceptionRoot); return compareStrings(string1, string2, locale, casePicker); - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); return COMPARISON_ERROR; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -export function mono_wasm_starts_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_starts_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -54,18 +52,16 @@ export function mono_wasm_starts_with(culture: MonoStringRef, str1: number, str1 const result = compareStrings(sourceOfPrefixLength, prefix, locale, casePicker); wrap_no_error_root(is_exception, exceptionRoot); return result === 0 ? 1 : 0; // equals ? true : false - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); return INDEXING_ERROR; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -export function mono_wasm_ends_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_ends_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -85,18 +81,16 @@ export function mono_wasm_ends_with(culture: MonoStringRef, str1: number, str1Le const result = compareStrings(sourceOfSuffixLength, suffix, locale, casePicker); wrap_no_error_root(is_exception, exceptionRoot); return result === 0 ? 1 : 0; // equals ? true : false - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); return INDEXING_ERROR; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -export function mono_wasm_index_of(culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_index_of (culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -156,22 +150,20 @@ export function mono_wasm_index_of(culture: MonoStringRef, needlePtr: number, ne } wrap_no_error_root(is_exception, exceptionRoot); return result; - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(is_exception, ex, exceptionRoot); return INDEXING_ERROR; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } - function checkMatchFound(str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { + function checkMatchFound (str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { return compareStrings(str1, str2, locale, casePicker) === 0; } } -function compareStrings(string1: string, string2: string, locale: string | undefined, casePicker: number): number { +function compareStrings (string1: string, string2: string, locale: string | undefined, casePicker: number): number { switch (casePicker) { case 0: // 0: None - default algorithm for the platform OR @@ -194,30 +186,30 @@ function compareStrings(string1: string, string2: string, locale: string | undef case 12: // 4: IgnoreSymbols // 12: IgnoreKanaType | IgnoreSymbols - return string1.localeCompare(string2, locale, { ignorePunctuation: true }); // by default ignorePunctuation: false + return string1.localeCompare(string2, locale, {ignorePunctuation: true}); // by default ignorePunctuation: false case 5: // 5: IgnoreSymbols | IgnoreCase string1 = string1.toLocaleLowerCase(locale); string2 = string2.toLocaleLowerCase(locale); - return string1.localeCompare(string2, locale, { ignorePunctuation: true }); // a ≠ b, a ≠ á, a ≠ A + return string1.localeCompare(string2, locale, {ignorePunctuation: true}); // a ≠ b, a ≠ á, a ≠ A case 9: // 9: IgnoreKanaType | IgnoreCase - return string1.localeCompare(string2, locale, { sensitivity: "accent" }); // a ≠ b, a ≠ á, a = A + return string1.localeCompare(string2, locale, {sensitivity: "accent"}); // a ≠ b, a ≠ á, a = A case 10: // 10: IgnoreKanaType | IgnoreNonSpace - return string1.localeCompare(string2, locale, { sensitivity: "case" }); // a ≠ b, a = á, a ≠ A + return string1.localeCompare(string2, locale, {sensitivity: "case"}); // a ≠ b, a = á, a ≠ A case 11: // 11: IgnoreKanaType | IgnoreNonSpace | IgnoreCase - return string1.localeCompare(string2, locale, { sensitivity: "base" }); // a ≠ b, a = á, a = A + return string1.localeCompare(string2, locale, {sensitivity: "base"}); // a ≠ b, a = á, a = A case 13: // 13: IgnoreKanaType | IgnoreCase | IgnoreSymbols - return string1.localeCompare(string2, locale, { sensitivity: "accent", ignorePunctuation: true }); // a ≠ b, a ≠ á, a = A + return string1.localeCompare(string2, locale, {sensitivity: "accent", ignorePunctuation: true}); // a ≠ b, a ≠ á, a = A case 14: // 14: IgnoreKanaType | IgnoreSymbols | IgnoreNonSpace - return string1.localeCompare(string2, locale, { sensitivity: "case", ignorePunctuation: true });// a ≠ b, a = á, a ≠ A + return string1.localeCompare(string2, locale, {sensitivity: "case", ignorePunctuation: true});// a ≠ b, a = á, a ≠ A case 15: // 15: IgnoreKanaType | IgnoreSymbols | IgnoreNonSpace | IgnoreCase - return string1.localeCompare(string2, locale, { sensitivity: "base", ignorePunctuation: true }); // a ≠ b, a = á, a = A + return string1.localeCompare(string2, locale, {sensitivity: "base", ignorePunctuation: true}); // a ≠ b, a = á, a = A case 2: case 3: case 6: @@ -263,12 +255,12 @@ function compareStrings(string1: string, string2: string, locale: string | undef } } -function decodeToCleanString(strPtr: number, strLen: number) { +function decodeToCleanString (strPtr: number, strLen: number) { const str = utf16ToString(strPtr, (strPtr + 2 * strLen)); return cleanString(str); } -function cleanString(str: string) { +function cleanString (str: string) { const nStr = str.normalize(); return nStr.replace(/[\u200B-\u200D\uFEFF\0]/g, ""); } diff --git a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts index 48c4e47828d09e..dd32bf19746c20 100644 --- a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts +++ b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts @@ -1,15 +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 { wrap_error_root, wrap_no_error_root } from "../invoke-js"; -import { mono_wasm_new_external_root } from "../roots"; -import { monoStringToString, stringToUTF16 } from "../strings"; -import { Int32Ptr } from "../types/emscripten"; -import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; -import { OUTER_SEPARATOR, normalizeLocale, normalizeSpaces } from "./helpers"; +import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; +import {mono_wasm_new_external_root} from "../roots"; +import {monoStringToString, stringToUTF16} from "../strings"; +import {Int32Ptr} from "../types/emscripten"; +import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; +import {OUTER_SEPARATOR, normalizeLocale, normalizeSpaces} from "./helpers"; -export function mono_wasm_get_culture_info(culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number -{ +export function mono_wasm_get_culture_info (culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -27,26 +26,22 @@ export function mono_wasm_get_culture_info(culture: MonoStringRef, dst: number, cultureInfo.LongTimePattern = getLongTimePattern(canonicalLocale, designators); cultureInfo.ShortTimePattern = getShortTimePattern(cultureInfo.LongTimePattern); const result = Object.values(cultureInfo).join(OUTER_SEPARATOR); - if (result.length > dstLength) - { + if (result.length > dstLength) { throw new Error(`Culture info exceeds length of ${dstLength}.`); } stringToUTF16(dst, dst + 2 * result.length, result); wrap_no_error_root(isException, exceptionRoot); return result.length; - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(isException, ex, exceptionRoot); return -1; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -function getAmPmDesignators(locale: any) -{ +function getAmPmDesignators (locale: any) { const pmTime = new Date("August 19, 1975 12:15:33"); // do not change, some PM hours result in hour digits change, e.g. 13 -> 01 or 1 const amTime = new Date("August 19, 1975 11:15:33"); // do not change, some AM hours result in hour digits change, e.g. 9 -> 09 const pmDesignator = getDesignator(pmTime, locale); @@ -57,19 +52,17 @@ function getAmPmDesignators(locale: any) }; } -function getDesignator(time: Date, locale: string) -{ - let withDesignator = time.toLocaleTimeString(locale, { hourCycle: "h12"}); +function getDesignator (time: Date, locale: string) { + let withDesignator = time.toLocaleTimeString(locale, {hourCycle: "h12"}); const localizedZero = (0).toLocaleString(locale); - if (withDesignator.includes(localizedZero)) - { + if (withDesignator.includes(localizedZero)) { // in v8>=11.8 "12" changes to "0" for ja-JP const localizedTwelve = (12).toLocaleString(locale); withDesignator = withDesignator.replace(localizedZero, localizedTwelve); } - const withoutDesignator = time.toLocaleTimeString(locale, { hourCycle: "h24"}); + const withoutDesignator = time.toLocaleTimeString(locale, {hourCycle: "h24"}); const designator = withDesignator.replace(withoutDesignator, "").trim(); - if (new RegExp("[0-9]$").test(designator)){ + if (new RegExp("[0-9]$").test(designator)) { const designatorParts = withDesignator.split(" ").filter(part => new RegExp("^((?![0-9]).)*$").test(part)); if (!designatorParts || designatorParts.length == 0) return ""; @@ -78,17 +71,16 @@ function getDesignator(time: Date, locale: string) return designator; } -function getLongTimePattern(locale: string | undefined, designators: any) : string -{ +function getLongTimePattern (locale: string | undefined, designators: any): string { const hourIn24Format = 18; // later hours than 18 have night designators in some locales (instead of AM designator) const hourIn12Format = 6; const localizedHour24 = (hourIn24Format).toLocaleString(locale); // not all locales use arabic numbers const localizedHour12 = (hourIn12Format).toLocaleString(locale); const pmTime = new Date(`August 19, 1975 ${hourIn24Format}:15:30`); // in the comments, en-US locale is used: - const shortTime = new Intl.DateTimeFormat(locale, { timeStyle: "medium" }); + const shortTime = new Intl.DateTimeFormat(locale, {timeStyle: "medium"}); const shortPmStyle = shortTime.format(pmTime); // 12:15:30 PM - const minutes = pmTime.toLocaleTimeString(locale, { minute: "numeric" }); // 15 - const seconds = pmTime.toLocaleTimeString(locale, { second: "numeric" }); // 30 + const minutes = pmTime.toLocaleTimeString(locale, {minute: "numeric"}); // 15 + const seconds = pmTime.toLocaleTimeString(locale, {second: "numeric"}); // 30 let pattern = shortPmStyle.replace(designators.pm, "tt").replace(minutes, "mm").replace(seconds, "ss"); // 12:mm:ss tt const isISOStyle = pattern.includes(localizedHour24); // 24h or 12h pattern? @@ -97,14 +89,11 @@ function getLongTimePattern(locale: string | undefined, designators: any) : stri const amTime = new Date(`August 19, 1975 ${hourIn12Format}:15:30`); const h12Style = shortTime.format(amTime); let hourPattern; - if (isISOStyle) // 24h - { + if (isISOStyle) { // 24h const hasPrefix = h12Style.includes(hour12WithPrefix); hourPattern = hasPrefix ? "HH" : "H"; pattern = pattern.replace(localizedHour24, hourPattern); - } - else // 12h - { + } else { // 12h const hasPrefix = h12Style.includes(hour12WithPrefix); hourPattern = hasPrefix ? "hh" : "h"; pattern = pattern.replace(hasPrefix ? hour12WithPrefix : localizedHour12, hourPattern); @@ -112,23 +101,18 @@ function getLongTimePattern(locale: string | undefined, designators: any) : stri return normalizeSpaces(pattern); } -function getShortTimePattern(pattern: string) : string -{ +function getShortTimePattern (pattern: string): string { // remove seconds: // short dotnet pattern does not contain seconds while JS's pattern always contains them const secondsIdx = pattern.indexOf("ss"); - if (secondsIdx > 0) - { + if (secondsIdx > 0) { const secondsWithSeparator = `${pattern[secondsIdx - 1]}ss`; // en-US: 12:mm:ss tt -> 12:mm tt; // fr-CA: 12 h mm min ss s -> 12 h mm min s const shortPatternNoSecondsDigits = pattern.replace(secondsWithSeparator, ""); - if (shortPatternNoSecondsDigits.length > secondsIdx && shortPatternNoSecondsDigits[shortPatternNoSecondsDigits.length - 1] != "t") - { + if (shortPatternNoSecondsDigits.length > secondsIdx && shortPatternNoSecondsDigits[shortPatternNoSecondsDigits.length - 1] != "t") { pattern = pattern.split(secondsWithSeparator)[0]; - } - else - { + } else { pattern = shortPatternNoSecondsDigits; } } diff --git a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts index 7322443a86ccdb..c9ae7f4427694c 100644 --- a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts +++ b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. /** - * This file is partially using code from FormatJS Intl.Segmenter implementation, reference: + * This file is partially using code from FormatJS Intl.Segmenter implementation, reference: * https://github.com/formatjs/formatjs/blob/58d6a7b398d776ca3d2726d72ae1573b65cc3bef/packages/intl-segmenter/src/segmenter.ts * https://github.com/formatjs/formatjs/blob/58d6a7b398d776ca3d2726d72ae1573b65cc3bef/packages/intl-segmenter/src/segmentation-utils.ts */ -import { mono_assert } from "../globals"; -import { isSurrogate } from "./helpers"; +import {mono_assert} from "../globals"; +import {isSurrogate} from "./helpers"; type SegmentationRule = { breaks: boolean @@ -21,7 +21,7 @@ type SegmentationRuleRaw = { before?: string after?: string } - + type SegmentationTypeRaw = { variables: Record rules: Record @@ -29,7 +29,7 @@ type SegmentationTypeRaw = { let segmentationRules: Record; -function replaceVariables(variables: Record, input: string): string { +function replaceVariables (variables: Record, input: string): string { const findVarRegex = /\$[A-Za-z0-9_]+/gm; return input.replaceAll(findVarRegex, match => { if (!(match in variables)) { @@ -43,11 +43,11 @@ function generateRegexRule (rule: string, variables: Record, aft return new RegExp(`${after ? "^" : ""}${replaceVariables(variables, rule)}${after ? "" : "$"}`); } -function isSegmentationTypeRaw(obj: any): obj is SegmentationTypeRaw { +function isSegmentationTypeRaw (obj: any): obj is SegmentationTypeRaw { return obj.variables != null && obj.rules != null; } -export function setSegmentationRulesFromJson(json: string) { +export function setSegmentationRulesFromJson (json: string) { mono_assert(isSegmentationTypeRaw(json), "Provided grapheme segmentation rules are not valid"); segmentationRules = GraphemeSegmenter.prepareSegmentationRules(json); } @@ -56,7 +56,7 @@ export class GraphemeSegmenter { private readonly rules: Record; private readonly ruleSortedKeys: string[]; - public constructor() { + public constructor () { this.rules = segmentationRules; this.ruleSortedKeys = Object.keys(this.rules).sort((a, b) => Number(a) - Number(b)); } @@ -67,25 +67,25 @@ export class GraphemeSegmenter { * @param startIndex - The starting index. * @returns The next grapheme. */ - public nextGrapheme(str: string, startIndex: number): string { + public nextGrapheme (str: string, startIndex: number): string { const breakIdx = this.nextGraphemeBreak(str, startIndex); return str.substring(startIndex, breakIdx); } /** * Finds the index of the next grapheme break in a given string starting from a specified index. - * + * * @param str - The input string. * @param startIndex - The index to start searching from. * @returns The index of the next grapheme break. */ - public nextGraphemeBreak(str: string, startIndex: number): number { + public nextGraphemeBreak (str: string, startIndex: number): number { if (startIndex < 0) return 0; - + if (startIndex >= str.length - 1) return str.length; - + let prev = String.fromCodePoint(str.codePointAt(startIndex)!); for (let i = startIndex + 1; i < str.length; i++) { // Don't break surrogate pairs @@ -96,14 +96,14 @@ export class GraphemeSegmenter { const curr = String.fromCodePoint(str.codePointAt(i)!); if (this.isGraphemeBreak(prev, curr)) return i; - + prev = curr; } - + return str.length; } - private isGraphemeBreak(previous: string, current: string): boolean { + private isGraphemeBreak (previous: string, current: string): boolean { for (const key of this.ruleSortedKeys) { const {before, after, breaks} = this.rules[key]; // match before and after rules @@ -121,20 +121,20 @@ export class GraphemeSegmenter { return true; } - public static prepareSegmentationRules(segmentationRules: SegmentationTypeRaw): Record { + public static prepareSegmentationRules (segmentationRules: SegmentationTypeRaw): Record { const preparedRules: Record = {}; - + for (const key of Object.keys(segmentationRules.rules)) { const ruleValue = segmentationRules.rules[key]; - const preparedRule: SegmentationRule = { breaks: ruleValue.breaks, }; - + const preparedRule: SegmentationRule = {breaks: ruleValue.breaks,}; + if ("before" in ruleValue && ruleValue.before) { preparedRule.before = generateRegexRule(ruleValue.before, segmentationRules.variables, false); } if ("after" in ruleValue && ruleValue.after) { preparedRule.after = generateRegexRule(ruleValue.after, segmentationRules.variables, true); } - + preparedRules[key] = preparedRule; } return preparedRules; diff --git a/src/mono/browser/runtime/hybrid-globalization/helpers.ts b/src/mono/browser/runtime/hybrid-globalization/helpers.ts index 1590936d8eaccc..002b6fdb163f79 100644 --- a/src/mono/browser/runtime/hybrid-globalization/helpers.ts +++ b/src/mono/browser/runtime/hybrid-globalization/helpers.ts @@ -9,30 +9,24 @@ const SURROGATE_LOWER_END = "\uDFFF"; export const OUTER_SEPARATOR = "##"; export const INNER_SEPARATOR = "||"; -export function normalizeLocale(locale: string | null) -{ +export function normalizeLocale (locale: string | null) { if (!locale) return undefined; - try - { + try { locale = locale.toLocaleLowerCase(); - if (locale.includes("zh")) - { + if (locale.includes("zh")) { // browser does not recognize "zh-chs" and "zh-cht" as equivalents of "zh-HANS" "zh-HANT", we are helping, otherwise // it would throw on getCanonicalLocales with "RangeError: Incorrect locale information provided" locale = locale.replace("chs", "HANS").replace("cht", "HANT"); } const canonicalLocales = (Intl as any).getCanonicalLocales(locale.replace("_", "-")); return canonicalLocales.length > 0 ? canonicalLocales[0] : undefined; - } - catch(ex: any) - { + } catch(ex: any) { throw new Error(`Get culture info failed for culture = ${locale} with error: ${ex}`); } } -export function normalizeSpaces(pattern: string) -{ +export function normalizeSpaces (pattern: string) { if (!pattern.includes("\u202F")) return pattern; @@ -41,11 +35,10 @@ export function normalizeSpaces(pattern: string) } -export function isSurrogate(str: string, startIdx: number) : boolean -{ +export function isSurrogate (str: string, startIdx: number) : boolean { return SURROGATE_HIGHER_START <= str[startIdx] && str[startIdx] <= SURROGATE_HIGHER_END && - startIdx+1 < str.length && - SURROGATE_LOWER_START <= str[startIdx+1] && - str[startIdx+1] <= SURROGATE_LOWER_END; + startIdx + 1 < str.length && + SURROGATE_LOWER_START <= str[startIdx + 1] && + str[startIdx + 1] <= SURROGATE_LOWER_END; } diff --git a/src/mono/browser/runtime/hybrid-globalization/locales.ts b/src/mono/browser/runtime/hybrid-globalization/locales.ts index 4330d0977e3606..1d71c1957d8d53 100644 --- a/src/mono/browser/runtime/hybrid-globalization/locales.ts +++ b/src/mono/browser/runtime/hybrid-globalization/locales.ts @@ -1,14 +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 { wrap_error_root, wrap_no_error_root } from "../invoke-js"; -import { mono_wasm_new_external_root } from "../roots"; -import { monoStringToString } from "../strings"; -import { Int32Ptr } from "../types/emscripten"; -import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; -import { normalizeLocale } from "./helpers"; +import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; +import {mono_wasm_new_external_root} from "../roots"; +import {monoStringToString} from "../strings"; +import {Int32Ptr} from "../types/emscripten"; +import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; +import {normalizeLocale} from "./helpers"; -export function mono_wasm_get_first_day_of_week(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number{ +export function mono_wasm_get_first_day_of_week (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -17,18 +17,16 @@ export function mono_wasm_get_first_day_of_week(culture: MonoStringRef, isExcept const canonicalLocale = normalizeLocale(cultureName); wrap_no_error_root(isException, exceptionRoot); return getFirstDayOfWeek(canonicalLocale); - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(isException, ex, exceptionRoot); return -1; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -export function mono_wasm_get_first_week_of_year(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number{ +export function mono_wasm_get_first_week_of_year (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -37,47 +35,39 @@ export function mono_wasm_get_first_week_of_year(culture: MonoStringRef, isExcep const canonicalLocale = normalizeLocale(cultureName); wrap_no_error_root(isException, exceptionRoot); return getFirstWeekOfYear(canonicalLocale); - } - catch (ex: any) { + } catch (ex: any) { wrap_error_root(isException, ex, exceptionRoot); return -1; - } - finally { + } finally { cultureRoot.release(); exceptionRoot.release(); } } -function getFirstDayOfWeek(locale: string) -{ +function getFirstDayOfWeek (locale: string) { const weekInfo = getWeekInfo(locale); - if (weekInfo) - { + if (weekInfo) { // JS's Sunday == 7 while dotnet's Sunday == 0 return weekInfo.firstDay == 7 ? 0 : weekInfo.firstDay; } // Firefox does not support it rn but we can make a temporary workaround for it, // that should be removed when it starts being supported: - const saturdayLocales = [ "en-AE", "en-SD", "fa-IR" ]; - if (saturdayLocales.includes(locale)) - { + const saturdayLocales = ["en-AE", "en-SD", "fa-IR"]; + if (saturdayLocales.includes(locale)) { return 6; } - const sundayLanguages = [ "zh", "th", "pt", "mr", "ml", "ko", "kn", "ja", "id", "hi", "he", "gu", "fil", "bn", "am", "ar" ]; - const sundayLocales = [ "ta-SG", "ta-IN", "sw-KE", "ms-SG", "fr-CA", "es-MX", "en-US", "en-ZW", "en-ZA", "en-WS", "en-VI", "en-UM", "en-TT", "en-SG", "en-PR", "en-PK", "en-PH", "en-MT", "en-MO", "en-MH", "en-KE", "en-JM", "en-IN", "en-IL", "en-HK", "en-GU", "en-DM", "en-CA", "en-BZ", "en-BW", "en-BS", "en-AU", "en-AS", "en-AG" ]; + const sundayLanguages = ["zh", "th", "pt", "mr", "ml", "ko", "kn", "ja", "id", "hi", "he", "gu", "fil", "bn", "am", "ar"]; + const sundayLocales = ["ta-SG", "ta-IN", "sw-KE", "ms-SG", "fr-CA", "es-MX", "en-US", "en-ZW", "en-ZA", "en-WS", "en-VI", "en-UM", "en-TT", "en-SG", "en-PR", "en-PK", "en-PH", "en-MT", "en-MO", "en-MH", "en-KE", "en-JM", "en-IN", "en-IL", "en-HK", "en-GU", "en-DM", "en-CA", "en-BZ", "en-BW", "en-BS", "en-AU", "en-AS", "en-AG"]; const localeLang = locale.split("-")[0]; - if (sundayLanguages.includes(localeLang) || sundayLocales.includes(locale)) - { + if (sundayLanguages.includes(localeLang) || sundayLocales.includes(locale)) { return 0; } return 1; } -function getFirstWeekOfYear(locale: string) -{ +function getFirstWeekOfYear (locale: string) { const weekInfo = getWeekInfo(locale); - if (weekInfo) - { + if (weekInfo) { // enum CalendarWeekRule // FirstDay = 0, // when minimalDays < 4 // FirstFullWeek = 1, // when miminalDays == 7 @@ -87,30 +77,25 @@ function getFirstWeekOfYear(locale: string) } // Firefox does not support it rn but we can make a temporary workaround for it, // that should be removed when it starts being supported: - const firstFourDayWeekLocales = [ "pt-PT", "fr-CH", "fr-FR", "fr-BE", "es-ES", "en-SE", "en-NL", "en-JE", "en-IM", "en-IE", "en-GI", "en-GG", "en-GB", "en-FJ", "en-FI", "en-DK", "en-DE", "en-CH", "en-BE", "en-AT", "el-GR" ]; - const firstFourDayWeekLanguages = [ "sv", "sk", "ru", "pl", "nl", "no", "lt", "it", "hu", "fi", "et", "de", "da", "cs", "ca", "bg" ]; + const firstFourDayWeekLocales = ["pt-PT", "fr-CH", "fr-FR", "fr-BE", "es-ES", "en-SE", "en-NL", "en-JE", "en-IM", "en-IE", "en-GI", "en-GG", "en-GB", "en-FJ", "en-FI", "en-DK", "en-DE", "en-CH", "en-BE", "en-AT", "el-GR"]; + const firstFourDayWeekLanguages = ["sv", "sk", "ru", "pl", "nl", "no", "lt", "it", "hu", "fi", "et", "de", "da", "cs", "ca", "bg"]; const localeLang = locale.split("-")[0]; - if (firstFourDayWeekLocales.includes(locale) || firstFourDayWeekLanguages.includes(localeLang)) - { + if (firstFourDayWeekLocales.includes(locale) || firstFourDayWeekLanguages.includes(localeLang)) { return 2; } return 0; } -function getWeekInfo(locale: string) -{ +function getWeekInfo (locale: string) { try { // most tools have it implemented as property return (new Intl.Locale(locale) as any).weekInfo; - } - catch { + } catch { try { // but a few use methods, which is the preferred way return (new Intl.Locale(locale) as any).getWeekInfo(); - } - catch - { + } catch { return undefined; } } -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/icu.ts b/src/mono/browser/runtime/icu.ts index 28aa01ad727cfd..f55fb3b8e972b0 100644 --- a/src/mono/browser/runtime/icu.ts +++ b/src/mono/browser/runtime/icu.ts @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. import cwraps from "./cwraps"; -import { VoidPtr } from "./types/emscripten"; +import {VoidPtr} from "./types/emscripten"; // @offset must be the address of an ICU data archive in the native heap. // returns true on success. -export function mono_wasm_load_icu_data(offset: VoidPtr): boolean { +export function mono_wasm_load_icu_data (offset: VoidPtr): boolean { return (cwraps.mono_wasm_load_icu_data(offset)) === 1; } diff --git a/src/mono/browser/runtime/interp-pgo.ts b/src/mono/browser/runtime/interp-pgo.ts index c4214b4fe5d6a3..791cee8c3287e6 100644 --- a/src/mono/browser/runtime/interp-pgo.ts +++ b/src/mono/browser/runtime/interp-pgo.ts @@ -3,15 +3,15 @@ import ProductVersion from "consts:productVersion"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import { ENVIRONMENT_IS_WEB, Module, loaderHelpers, runtimeHelpers } from "./globals"; -import { mono_log_info, mono_log_error, mono_log_warn } from "./logging"; -import { localHeapViewU8 } from "./memory"; +import {ENVIRONMENT_IS_WEB, Module, loaderHelpers, runtimeHelpers} from "./globals"; +import {mono_log_info, mono_log_error, mono_log_warn} from "./logging"; +import {localHeapViewU8} from "./memory"; import cwraps from "./cwraps"; -import { MonoConfigInternal } from "./types/internal"; +import {MonoConfigInternal} from "./types/internal"; export const tablePrefix = "https://dotnet.generated.invalid/interp_pgo"; -export async function interp_pgo_save_data() { +export async function interp_pgo_save_data () { if (!loaderHelpers.is_runtime_running()) { mono_log_info("Skipped saving interp_pgo table (already exited)"); return; @@ -53,7 +53,7 @@ export async function interp_pgo_save_data() { } } -export async function interp_pgo_load_data() { +export async function interp_pgo_load_data () { const cacheKey = await getCacheKey(tablePrefix); if (!cacheKey) { mono_log_error("Failed to create cache key for interp_pgo table"); @@ -76,7 +76,7 @@ export async function interp_pgo_load_data() { Module._free(pData); } -async function openCache(): Promise { +async function openCache (): Promise { // 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 (ENVIRONMENT_IS_WEB && globalThis.window.isSecureContext === false) { @@ -113,7 +113,7 @@ async function openCache(): Promise { } } -export async function getCacheEntry(cacheKey: string): Promise { +export async function getCacheEntry (cacheKey: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -130,7 +130,7 @@ export async function getCacheEntry(cacheKey: string): Promise { +export async function storeCacheEntry (cacheKey: string, memory: ArrayBuffer, mimeType: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -157,7 +157,7 @@ export async function storeCacheEntry(cacheKey: string, memory: ArrayBuffer, mim } } -export async function cleanupCache(prefix: string, protectKey: string) { +export async function cleanupCache (prefix: string, protectKey: string) { try { const cache = await openCache(); if (!cache) { @@ -175,7 +175,7 @@ export async function cleanupCache(prefix: string, protectKey: string) { } // calculate hash of things which affect config hash -export async function getCacheKey(prefix: string): Promise { +export async function getCacheKey (prefix: string): Promise { if (!runtimeHelpers.subtle) { return null; } diff --git a/src/mono/browser/runtime/invoke-cs.ts b/src/mono/browser/runtime/invoke-cs.ts index 893245041d27ad..bf20e3daeffa47 100644 --- a/src/mono/browser/runtime/invoke-cs.ts +++ b/src/mono/browser/runtime/invoke-cs.ts @@ -4,20 +4,20 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; -import { bind_arg_marshal_to_cs } from "./marshal-to-cs"; -import { bind_arg_marshal_to_js, end_marshal_task_to_js } from "./marshal-to-js"; +import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; +import {bind_arg_marshal_to_cs} from "./marshal-to-cs"; +import {bind_arg_marshal_to_js, end_marshal_task_to_js} from "./marshal-to-js"; import { get_sig, get_signature_argument_count, bound_cs_function_symbol, get_signature_version, alloc_stack_frame, get_signature_type, } from "./marshal"; -import { MonoMethod, JSFunctionSignature, BoundMarshalerToCs, BoundMarshalerToJs, MarshalerType } from "./types/internal"; -import { assert_js_interop } from "./invoke-js"; -import { startMeasure, MeasuredBlock, endMeasure } from "./profiler"; -import { bind_assembly_exports, invoke_async_jsexport, invoke_sync_jsexport } from "./managed-exports"; -import { mono_log_debug } from "./logging"; +import {MonoMethod, JSFunctionSignature, BoundMarshalerToCs, BoundMarshalerToJs, MarshalerType} from "./types/internal"; +import {assert_js_interop} from "./invoke-js"; +import {startMeasure, MeasuredBlock, endMeasure} from "./profiler"; +import {bind_assembly_exports, invoke_async_jsexport, invoke_sync_jsexport} from "./managed-exports"; +import {mono_log_debug} from "./logging"; -export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { +export function mono_wasm_bind_cs_function (method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { const fullyQualifiedName = `[${assemblyName}] ${namespaceName}.${shortClassName}:${methodName}`; const mark = startMeasure(); mono_log_debug(`Binding [JSExport] ${namespaceName}.${shortClassName}:${methodName} from ${assemblyName} assembly`); @@ -68,11 +68,9 @@ export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: str if (is_async) { if (args_count == 1 && res_converter) { bound_fn = bind_fn_1RA(closure); - } - else if (args_count == 2 && res_converter) { + } else if (args_count == 2 && res_converter) { bound_fn = bind_fn_2RA(closure); - } - else { + } else { bound_fn = bind_fn(closure); } } else if (is_discard_no_wait) { @@ -80,22 +78,18 @@ export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: str } else { if (args_count == 0 && !res_converter) { bound_fn = bind_fn_0V(closure); - } - else if (args_count == 1 && !res_converter) { + } else if (args_count == 1 && !res_converter) { bound_fn = bind_fn_1V(closure); - } - else if (args_count == 1 && res_converter) { + } else if (args_count == 1 && res_converter) { bound_fn = bind_fn_1R(closure); - } - else if (args_count == 2 && res_converter) { + } else if (args_count == 2 && res_converter) { bound_fn = bind_fn_2R(closure); - } - else { + } else { bound_fn = bind_fn(closure); } } - // this is just to make debugging easier. + // this is just to make debugging easier. // It's not CSP compliant and possibly not performant, that's why it's only enabled in debug builds // in Release configuration, it would be a trimmed by rollup if (BuildConfiguration === "Debug" && !runtimeHelpers.cspPolicy) { @@ -103,8 +97,7 @@ export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: str const url = `//# sourceURL=https://dotnet/JSExport/${methodName}`; const body = `return (function JSExport_${methodName}(){ return fn.apply(this, arguments)});`; bound_fn = new Function("fn", url + "\r\n" + body)(bound_fn); - } - catch (ex) { + } catch (ex) { runtimeHelpers.cspPolicy = true; } } @@ -115,11 +108,11 @@ export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: str endMeasure(mark, MeasuredBlock.bindCsFunction, fullyQualifiedName); } -function bind_fn_0V(closure: BindingClosure) { +function bind_fn_0V (closure: BindingClosure) { const method = closure.method; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V() { + return function bound_fn_0V () { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -136,12 +129,12 @@ function bind_fn_0V(closure: BindingClosure) { }; } -function bind_fn_1V(closure: BindingClosure) { +function bind_fn_1V (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V(arg1: any) { + return function bound_fn_1V (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -160,13 +153,13 @@ function bind_fn_1V(closure: BindingClosure) { }; } -function bind_fn_1R(closure: BindingClosure) { +function bind_fn_1R (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R(arg1: any) { + return function bound_fn_1R (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -188,13 +181,13 @@ function bind_fn_1R(closure: BindingClosure) { }; } -function bind_fn_1RA(closure: BindingClosure) { +function bind_fn_1RA (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_1RA(arg1: any) { + return function bind_fn_1RA (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -221,14 +214,14 @@ function bind_fn_1RA(closure: BindingClosure) { }; } -function bind_fn_2R(closure: BindingClosure) { +function bind_fn_2R (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R(arg1: any, arg2: any) { + return function bound_fn_2R (arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -251,14 +244,14 @@ function bind_fn_2R(closure: BindingClosure) { }; } -function bind_fn_2RA(closure: BindingClosure) { +function bind_fn_2RA (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_2RA(arg1: any, arg2: any) { + return function bind_fn_2RA (arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -286,7 +279,7 @@ function bind_fn_2RA(closure: BindingClosure) { }; } -function bind_fn(closure: BindingClosure) { +function bind_fn (closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -295,7 +288,7 @@ function bind_fn(closure: BindingClosure) { const is_async = closure.is_async; const is_discard_no_wait = closure.is_discard_no_wait; if (!WasmEnableThreads) (closure) = null; - return function bound_fn(...js_args: any[]) { + return function bound_fn (...js_args: any[]) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -321,12 +314,10 @@ function bind_fn(closure: BindingClosure) { invoke_async_jsexport(runtimeHelpers.managedThreadTID, method, args, size); // in case the C# side returned synchronously js_result = end_marshal_task_to_js(args, undefined, js_result); - } - else if (is_discard_no_wait) { + } else if (is_discard_no_wait) { // call C# side, fire and forget invoke_async_jsexport(runtimeHelpers.managedThreadTID, method, args, size); - } - else { + } else { invoke_sync_jsexport(method, args); if (res_converter) { js_result = res_converter(args); @@ -352,7 +343,7 @@ type BindingClosure = { } export const exportsByAssembly: Map = new Map(); -function _walk_exports_to_set_function(assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { +function _walk_exports_to_set_function (assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { const parts = `${namespace}.${classname}`.replace(/\//g, ".").split("."); let scope: any = undefined; let assemblyScope = exportsByAssembly.get(assembly); @@ -381,7 +372,7 @@ function _walk_exports_to_set_function(assembly: string, namespace: string, clas scope[`${methodname}.${signature_hash}`] = fn; } -export async function mono_wasm_get_assembly_exports(assembly: string): Promise { +export async function mono_wasm_get_assembly_exports (assembly: string): Promise { assert_js_interop(); const result = exportsByAssembly.get(assembly); if (!result) { diff --git a/src/mono/browser/runtime/invoke-js.ts b/src/mono/browser/runtime/invoke-js.ts index cb26b89a73b79f..327af55901a5df 100644 --- a/src/mono/browser/runtime/invoke-js.ts +++ b/src/mono/browser/runtime/invoke-js.ts @@ -4,23 +4,23 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import { marshal_exception_to_cs, bind_arg_marshal_to_cs } from "./marshal-to-cs"; -import { get_signature_argument_count, bound_js_function_symbol, get_sig, get_signature_version, get_signature_type, imported_js_function_symbol, get_signature_handle, get_signature_function_name, get_signature_module_name, is_receiver_should_free, get_caller_native_tid } from "./marshal"; -import { setI32_unchecked, receiveWorkerHeapViews, forceThreadMemoryViewRefresh } from "./memory"; -import { stringToMonoStringRoot } from "./strings"; -import { MonoObject, MonoObjectRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle, MarshalerType } from "./types/internal"; -import { Int32Ptr } from "./types/emscripten"; -import { INTERNAL, Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; -import { bind_arg_marshal_to_js } from "./marshal-to-js"; -import { mono_wasm_new_external_root } from "./roots"; -import { mono_log_debug, mono_wasm_symbolicate_string } from "./logging"; -import { mono_wasm_get_jsobj_from_js_handle } from "./gc-handles"; -import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; -import { wrap_as_cancelable_promise } from "./cancelable-promise"; +import {marshal_exception_to_cs, bind_arg_marshal_to_cs} from "./marshal-to-cs"; +import {get_signature_argument_count, bound_js_function_symbol, get_sig, get_signature_version, get_signature_type, imported_js_function_symbol, get_signature_handle, get_signature_function_name, get_signature_module_name, is_receiver_should_free, get_caller_native_tid} from "./marshal"; +import {setI32_unchecked, receiveWorkerHeapViews, forceThreadMemoryViewRefresh} from "./memory"; +import {stringToMonoStringRoot} from "./strings"; +import {MonoObject, MonoObjectRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle, MarshalerType} from "./types/internal"; +import {Int32Ptr} from "./types/emscripten"; +import {INTERNAL, Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; +import {bind_arg_marshal_to_js} from "./marshal-to-js"; +import {mono_wasm_new_external_root} from "./roots"; +import {mono_log_debug, mono_wasm_symbolicate_string} from "./logging"; +import {mono_wasm_get_jsobj_from_js_handle} from "./gc-handles"; +import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; +import {wrap_as_cancelable_promise} from "./cancelable-promise"; export const js_import_wrapper_by_fn_handle: Function[] = [null];// 0th slot is dummy, main thread we free them on shutdown. On web worker thread we free them when worker is detached. -export function mono_wasm_bind_js_import(signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { +export function mono_wasm_bind_js_import (signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { if (WasmEnableThreads) return; assert_js_interop(); const resultRoot = mono_wasm_new_external_root(result_address); @@ -35,7 +35,7 @@ export function mono_wasm_bind_js_import(signature: JSFunctionSignature, is_exce } } -export function mono_wasm_invoke_jsimport(signature: JSFunctionSignature, args: JSMarshalerArguments) { +export function mono_wasm_invoke_jsimport (signature: JSFunctionSignature, args: JSMarshalerArguments) { if (!WasmEnableThreads) return; assert_js_interop(); @@ -51,7 +51,7 @@ export function mono_wasm_invoke_jsimport(signature: JSFunctionSignature, args: bound_fn(args); } -export function mono_wasm_invoke_jsimport_ST(function_handle: JSFnHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_jsimport_ST (function_handle: JSFnHandle, args: JSMarshalerArguments): void { if (WasmEnableThreads) return; loaderHelpers.assert_runtime_running(); const bound_fn = js_import_wrapper_by_fn_handle[function_handle]; @@ -59,7 +59,7 @@ export function mono_wasm_invoke_jsimport_ST(function_handle: JSFnHandle, args: bound_fn(args); } -function bind_js_import(signature: JSFunctionSignature): Function { +function bind_js_import (signature: JSFunctionSignature): Function { assert_js_interop(); const mark = startMeasure(); @@ -115,38 +115,33 @@ function bind_js_import(signature: JSFunctionSignature): Function { let bound_fn: WrappedJSFunction; if (is_async || is_discard_no_wait || has_cleanup) { bound_fn = bind_fn(closure); - } - else { + } else { if (args_count == 0 && !res_converter) { bound_fn = bind_fn_0V(closure); - } - else if (args_count == 1 && !res_converter) { + } else if (args_count == 1 && !res_converter) { bound_fn = bind_fn_1V(closure); - } - else if (args_count == 1 && res_converter) { + } else if (args_count == 1 && res_converter) { bound_fn = bind_fn_1R(closure); - } - else if (args_count == 2 && res_converter) { + } else if (args_count == 2 && res_converter) { bound_fn = bind_fn_2R(closure); } else { bound_fn = bind_fn(closure); } } - function async_bound_fn(args: JSMarshalerArguments): void { + function async_bound_fn (args: JSMarshalerArguments): void { forceThreadMemoryViewRefresh(); bound_fn(args); } - function sync_bound_fn(args: JSMarshalerArguments): void { + function sync_bound_fn (args: JSMarshalerArguments): void { const previous = runtimeHelpers.isPendingSynchronousCall; try { forceThreadMemoryViewRefresh(); const caller_tid = get_caller_native_tid(args); runtimeHelpers.isPendingSynchronousCall = runtimeHelpers.managedThreadTID === caller_tid; bound_fn(args); - } - finally { + } finally { runtimeHelpers.isPendingSynchronousCall = previous; } } @@ -155,8 +150,7 @@ function bind_js_import(signature: JSFunctionSignature): Function { if (WasmEnableThreads) { if (is_async || is_discard_no_wait) { wrapped_fn = async_bound_fn; - } - else { + } else { wrapped_fn = sync_bound_fn; } } @@ -170,8 +164,7 @@ function bind_js_import(signature: JSFunctionSignature): Function { const url = `//# sourceURL=https://dotnet/JSImport/${fname}`; const body = `return (function JSImport_${fname}(){ return fn.apply(this, arguments)});`; wrapped_fn = new Function("fn", url + "\r\n" + body)(wrapped_fn); - } - catch (ex) { + } catch (ex) { runtimeHelpers.cspPolicy = true; } } @@ -185,11 +178,11 @@ function bind_js_import(signature: JSFunctionSignature): Function { return wrapped_fn; } -function bind_fn_0V(closure: BindingClosure) { +function bind_fn_0V (closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V(args: JSMarshalerArguments) { + return function bound_fn_0V (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -197,19 +190,18 @@ function bind_fn_0V(closure: BindingClosure) { fn(); } catch (ex) { marshal_exception_to_cs(args, ex); - } - finally { + } finally { endMeasure(mark, MeasuredBlock.callCsFunction, fqn); } }; } -function bind_fn_1V(closure: BindingClosure) { +function bind_fn_1V (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V(args: JSMarshalerArguments) { + return function bound_fn_1V (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -218,20 +210,19 @@ function bind_fn_1V(closure: BindingClosure) { fn(arg1); } catch (ex) { marshal_exception_to_cs(args, ex); - } - finally { + } finally { endMeasure(mark, MeasuredBlock.callCsFunction, fqn); } }; } -function bind_fn_1R(closure: BindingClosure) { +function bind_fn_1R (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R(args: JSMarshalerArguments) { + return function bound_fn_1R (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -241,21 +232,20 @@ function bind_fn_1R(closure: BindingClosure) { res_converter(args, js_result); } catch (ex) { marshal_exception_to_cs(args, ex); - } - finally { + } finally { endMeasure(mark, MeasuredBlock.callCsFunction, fqn); } }; } -function bind_fn_2R(closure: BindingClosure) { +function bind_fn_2R (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R(args: JSMarshalerArguments) { + return function bound_fn_2R (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -266,14 +256,13 @@ function bind_fn_2R(closure: BindingClosure) { res_converter(args, js_result); } catch (ex) { marshal_exception_to_cs(args, ex); - } - finally { + } finally { endMeasure(mark, MeasuredBlock.callCsFunction, fqn); } }; } -function bind_fn(closure: BindingClosure) { +function bind_fn (closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -282,7 +271,7 @@ function bind_fn(closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn(args: JSMarshalerArguments) { + return function bound_fn (args: JSMarshalerArguments) { const receiver_should_free = WasmEnableThreads && is_receiver_should_free(args); const mark = startMeasure(); try { @@ -311,8 +300,7 @@ function bind_fn(closure: BindingClosure) { } } catch (ex) { marshal_exception_to_cs(args, ex); - } - finally { + } finally { if (receiver_should_free) { Module._free(args as any); } @@ -336,19 +324,19 @@ type BindingClosure = { arg_cleanup: (Function | undefined)[] } -export function mono_wasm_invoke_js_function(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_js_function (bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { loaderHelpers.assert_runtime_running(); const bound_fn = mono_wasm_get_jsobj_from_js_handle(bound_function_js_handle); mono_assert(bound_fn && typeof (bound_fn) === "function" && bound_fn[bound_js_function_symbol], () => `Bound function handle expected ${bound_function_js_handle}`); bound_fn(args); } -export function mono_wasm_set_module_imports(module_name: string, moduleImports: any) { +export function mono_wasm_set_module_imports (module_name: string, moduleImports: any) { importedModules.set(module_name, moduleImports); mono_log_debug(`added module imports '${module_name}'`); } -function mono_wasm_lookup_js_import(function_name: string, js_module_name: string | null): Function { +function mono_wasm_lookup_js_import (function_name: string, js_module_name: string | null): Function { mono_assert(function_name && typeof function_name === "string", "function_name must be string"); let scope: any = {}; @@ -360,12 +348,10 @@ function mono_wasm_lookup_js_import(function_name: string, js_module_name: strin } else { mono_assert(scope, () => `ES6 module ${js_module_name} was not imported yet, please call JSHost.ImportAsync() first.`); } - } - else if (parts[0] === "INTERNAL") { + } else if (parts[0] === "INTERNAL") { scope = INTERNAL; parts.shift(); - } - else if (parts[0] === "globalThis") { + } else if (parts[0] === "globalThis") { scope = globalThis; parts.shift(); } @@ -386,34 +372,34 @@ function mono_wasm_lookup_js_import(function_name: string, js_module_name: strin return fn.bind(scope); } -export function set_property(self: any, name: string, value: any): void { +export function set_property (self: any, name: string, value: any): void { mono_check(self, "Null reference"); self[name] = value; } -export function get_property(self: any, name: string): any { +export function get_property (self: any, name: string): any { mono_check(self, "Null reference"); return self[name]; } -export function has_property(self: any, name: string): boolean { +export function has_property (self: any, name: string): boolean { mono_check(self, "Null reference"); return name in self; } -export function get_typeof_property(self: any, name: string): string { +export function get_typeof_property (self: any, name: string): string { mono_check(self, "Null reference"); return typeof self[name]; } -export function get_global_this(): any { +export function get_global_this (): any { return globalThis; } export const importedModulesPromises: Map> = new Map(); export const importedModules: Map> = new Map(); -export function dynamic_import(module_name: string, module_url: string): Promise { +export function dynamic_import (module_name: string, module_url: string): Promise { assert_js_interop(); mono_assert(module_name && typeof module_name === "string", "module_name must be string"); mono_assert(module_url && typeof module_url === "string", "module_url must be string"); @@ -435,7 +421,7 @@ export function dynamic_import(module_name: string, module_url: string): Promise }); } -function _wrap_error_flag(is_exception: Int32Ptr | null, ex: any): string { +function _wrap_error_flag (is_exception: Int32Ptr | null, ex: any): string { let res = "unknown exception"; if (ex) { res = ex.toString(); @@ -458,7 +444,7 @@ function _wrap_error_flag(is_exception: Int32Ptr | null, ex: any): string { return res; } -export function wrap_error_root(is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { +export function wrap_error_root (is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { const res = _wrap_error_flag(is_exception, ex); stringToMonoStringRoot(res, result); } @@ -466,7 +452,7 @@ export function wrap_error_root(is_exception: Int32Ptr | null, ex: any, result: // to set out parameters of icalls // TODO replace it with replace it with UTF8 char*, no GC root needed // https://github.com/dotnet/runtime/issues/98365 -export function wrap_no_error_root(is_exception: Int32Ptr | null, result?: WasmRoot): void { +export function wrap_no_error_root (is_exception: Int32Ptr | null, result?: WasmRoot): void { if (is_exception) { receiveWorkerHeapViews(); setI32_unchecked(is_exception, 0); @@ -476,7 +462,7 @@ export function wrap_no_error_root(is_exception: Int32Ptr | null, result?: WasmR } } -export function assert_js_interop(): void { +export function assert_js_interop (): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready && runtimeHelpers.proxyGCHandle, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -485,7 +471,7 @@ export function assert_js_interop(): void { } } -export function assert_c_interop(): void { +export function assert_c_interop (): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); diff --git a/src/mono/browser/runtime/jiterpreter-interp-entry.ts b/src/mono/browser/runtime/jiterpreter-interp-entry.ts index cedf54cdde9306..7e072eb27f2675 100644 --- a/src/mono/browser/runtime/jiterpreter-interp-entry.ts +++ b/src/mono/browser/runtime/jiterpreter-interp-entry.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { MonoMethod, MonoType } from "./types/internal"; -import { NativePointer } from "./types/emscripten"; -import { Module, mono_assert } from "./globals"; +import {MonoMethod, MonoType} from "./types/internal"; +import {NativePointer} from "./types/emscripten"; +import {Module, mono_assert} from "./globals"; import { setI32, getU32_unaligned, _zero_region } from "./memory"; -import { WasmOpcode } from "./jiterpreter-opcodes"; +import {WasmOpcode} from "./jiterpreter-opcodes"; import cwraps from "./cwraps"; import { WasmBuilder, addWasmFunctionPointer, @@ -16,9 +16,9 @@ import { JiterpreterOptions, getMemberOffset, getCounter, modifyCounter } from "./jiterpreter-support"; -import { WasmValtype } from "./jiterpreter-opcodes"; -import { mono_log_error, mono_log_info } from "./logging"; -import { utf8ToString } from "./strings"; +import {WasmValtype} from "./jiterpreter-opcodes"; +import {mono_log_error, mono_log_info} from "./logging"; +import {utf8ToString} from "./strings"; import { JiterpreterTable, JiterpCounter, JiterpMember, JitQueue } from "./jiterpreter-enums"; @@ -68,7 +68,7 @@ const enum WasmReftype { } */ -function getTrampImports() { +function getTrampImports () { if (trampImports) return trampImports; @@ -98,7 +98,7 @@ class TrampolineInfo { result: number; hitCount: number; - constructor( + constructor ( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: string, defaultImplementation: number @@ -137,12 +137,12 @@ let mostRecentOptions: JiterpreterOptions | undefined = undefined; // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_interp_entry(imethod: number) { +export function mono_jiterp_free_method_data_interp_entry (imethod: number) { delete infoTable[imethod]; } // FIXME: move this counter into C and make it thread safe -export function mono_interp_record_interp_entry(imethod: number) { +export function mono_interp_record_interp_entry (imethod: number) { // clear the unbox bit imethod = imethod & ~0x1; @@ -168,7 +168,7 @@ export function mono_interp_record_interp_entry(imethod: number) { } // returns function pointer -export function mono_interp_jit_wasm_entry_trampoline( +export function mono_interp_jit_wasm_entry_trampoline ( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: NativePointer, defaultImplementation: number @@ -208,7 +208,7 @@ export function mono_interp_jit_wasm_entry_trampoline( return info.result; } -function ensure_jit_is_scheduled() { +function ensure_jit_is_scheduled () { if (jitQueueTimeout > 0) return; @@ -227,7 +227,7 @@ function ensure_jit_is_scheduled() { }, queueFlushDelayMs); } -function flush_wasm_entry_trampoline_jit_queue() { +function flush_wasm_entry_trampoline_jit_queue () { const jitQueue : TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.InterpEntry)) != 0) { @@ -447,7 +447,7 @@ function flush_wasm_entry_trampoline_jit_queue() { } } -function append_stackval_from_data( +function append_stackval_from_data ( builder: WasmBuilder, imethod: number, type: MonoType, valueName: string, argIndex: number ) { const rawSize = cwraps.mono_jiterp_type_get_raw_value_size(type); @@ -520,7 +520,7 @@ function append_stackval_from_data( } } -function generate_wasm_body( +function generate_wasm_body ( builder: WasmBuilder, info: TrampolineInfo ): boolean { // FIXME: This is not thread-safe, but the alternative of alloca makes the trampoline diff --git a/src/mono/browser/runtime/jiterpreter-jit-call.ts b/src/mono/browser/runtime/jiterpreter-jit-call.ts index 09018413e24e75..fdf1852833d77b 100644 --- a/src/mono/browser/runtime/jiterpreter-jit-call.ts +++ b/src/mono/browser/runtime/jiterpreter-jit-call.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { MonoType, MonoMethod } from "./types/internal"; -import { NativePointer, VoidPtr } from "./types/emscripten"; -import { Module, mono_assert, runtimeHelpers } from "./globals"; +import {MonoType, MonoMethod} from "./types/internal"; +import {NativePointer, VoidPtr} from "./types/emscripten"; +import {Module, mono_assert, runtimeHelpers} from "./globals"; import { getU8, getI32_unaligned, getU32_unaligned, setU32_unchecked, receiveWorkerHeapViews } from "./memory"; -import { WasmOpcode, WasmValtype } from "./jiterpreter-opcodes"; +import {WasmOpcode, WasmValtype} from "./jiterpreter-opcodes"; import { WasmBuilder, addWasmFunctionPointer, _now, getWasmFunctionTable, applyOptions, @@ -15,10 +15,10 @@ import { getCounter, modifyCounter, getRawCwrap } from "./jiterpreter-support"; -import { JiterpreterTable, JiterpCounter, JitQueue } from "./jiterpreter-enums"; +import {JiterpreterTable, JiterpCounter, JitQueue} from "./jiterpreter-enums"; import cwraps from "./cwraps"; -import { mono_log_error, mono_log_info } from "./logging"; -import { utf8ToString } from "./strings"; +import {mono_log_error, mono_log_info} from "./logging"; +import {utf8ToString} from "./strings"; // Controls miscellaneous diagnostic output. const trace = 0; @@ -95,7 +95,7 @@ class TrampolineInfo { wasmNativeSignature: WasmValtype[]; enableDirect: boolean; - constructor( + constructor ( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: boolean ) { @@ -166,7 +166,7 @@ class TrampolineInfo { // this is cached replacements for Module.getWasmTableEntry(); // we could add and // if we need to export the original -function getWasmTableEntry(index: number) { +function getWasmTableEntry (index: number) { let result = fnCache[index]; if (!result) { if (index >= fnCache.length) @@ -179,7 +179,7 @@ function getWasmTableEntry(index: number) { return result; } -export function mono_interp_invoke_wasm_jit_call_trampoline( +export function mono_interp_invoke_wasm_jit_call_trampoline ( thunkIndex: number, ret_sp: number, sp: number, ftndesc: number, thrown: NativePointer ) { const thunk = getWasmTableEntry(thunkIndex); @@ -218,7 +218,7 @@ export function mono_interp_invoke_wasm_jit_call_trampoline( // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_jit_call(method: MonoMethod) { +export function mono_jiterp_free_method_data_jit_call (method: MonoMethod) { // FIXME const infoArray = infosByMethod[method]; if (!infoArray) @@ -230,7 +230,7 @@ export function mono_jiterp_free_method_data_jit_call(method: MonoMethod) { delete infosByMethod[method]; } -export function mono_interp_jit_wasm_jit_call_trampoline( +export function mono_interp_jit_wasm_jit_call_trampoline ( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: number ): void { @@ -276,7 +276,7 @@ export function mono_interp_jit_wasm_jit_call_trampoline( mono_interp_flush_jitcall_queue(); } -function getIsWasmEhSupported(): boolean { +function getIsWasmEhSupported (): boolean { if (wasmEhSupported !== undefined) return wasmEhSupported; @@ -288,7 +288,7 @@ function getIsWasmEhSupported(): boolean { return wasmEhSupported; } -export function mono_interp_flush_jitcall_queue(): void { +export function mono_interp_flush_jitcall_queue (): void { const jitQueue: TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.JitCall)) != 0) { @@ -338,7 +338,7 @@ export function mono_interp_flush_jitcall_queue(): void { if (builder.options.enableWasmEh) { if (!getIsWasmEhSupported()) { // The user requested to enable wasm EH but it's not supported, so turn the option back off - applyOptions({ enableWasmEh: false }); + applyOptions({enableWasmEh: false}); builder.options.enableWasmEh = false; } } @@ -432,7 +432,7 @@ export function mono_interp_flush_jitcall_queue(): void { builder.appendULeb(jitQueue.length); for (let i = 0; i < jitQueue.length; i++) { const info = jitQueue[i]; - builder.beginFunction("trampoline", { "old_sp": WasmValtype.i32 }); + builder.beginFunction("trampoline", {"old_sp": WasmValtype.i32}); const ok = generate_wasm_body(builder, info); // FIXME @@ -624,19 +624,19 @@ const wasmOpcodeFromCilOpcode = { [CilOpcodes.STIND_I]: WasmOpcode.i32_store, }; -function append_ldloc(builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { +function append_ldloc (builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { builder.local("sp"); builder.appendU8(opcode); builder.appendMemarg(offsetBytes, 0); } -function append_ldloca(builder: WasmBuilder, offsetBytes: number) { +function append_ldloca (builder: WasmBuilder, offsetBytes: number) { builder.local("sp"); builder.i32_const(offsetBytes); builder.appendU8(WasmOpcode.i32_add); } -function generate_wasm_body( +function generate_wasm_body ( builder: WasmBuilder, info: TrampolineInfo ): boolean { let stack_index = 0; diff --git a/src/mono/browser/runtime/jiterpreter-support.ts b/src/mono/browser/runtime/jiterpreter-support.ts index 1dbbac2eaaf649..30c3e0e9e47eea 100644 --- a/src/mono/browser/runtime/jiterpreter-support.ts +++ b/src/mono/browser/runtime/jiterpreter-support.ts @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import { NativePointer, ManagedPointer, VoidPtr } from "./types/emscripten"; -import { Module, mono_assert, runtimeHelpers } from "./globals"; -import { WasmOpcode, WasmSimdOpcode, WasmValtype } from "./jiterpreter-opcodes"; -import { MintOpcode } from "./mintops"; +import {NativePointer, ManagedPointer, VoidPtr} from "./types/emscripten"; +import {Module, mono_assert, runtimeHelpers} from "./globals"; +import {WasmOpcode, WasmSimdOpcode, WasmValtype} from "./jiterpreter-opcodes"; +import {MintOpcode} from "./mintops"; import cwraps from "./cwraps"; -import { mono_log_error, mono_log_info } from "./logging"; -import { localHeapViewU8, localHeapViewU32 } from "./memory"; -import { utf8ToString } from "./strings"; +import {mono_log_error, mono_log_info} from "./logging"; +import {localHeapViewU8, localHeapViewU32} from "./memory"; +import {utf8ToString} from "./strings"; import { JiterpNumberMode, BailoutReason, JiterpreterTable, JiterpCounter, JiterpMember, OpcodeInfoType @@ -109,14 +109,14 @@ export class WasmBuilder { compressImportNames = false; lockImports = false; - constructor(constantSlotCount: number) { + constructor (constantSlotCount: number) { this.stack = [new BlobBuilder()]; this.clear(constantSlotCount); this.cfg = new Cfg(this); - this.defineType("__cpp_exception", { "ptr": WasmValtype.i32 }, WasmValtype.void, true); + this.defineType("__cpp_exception", {"ptr": WasmValtype.i32}, WasmValtype.void, true); } - clear(constantSlotCount: number) { + clear (constantSlotCount: number) { this.options = getOptions(); this.stackSize = 1; this.inSection = false; @@ -156,14 +156,14 @@ export class WasmBuilder { this.allowNullCheckOptimization = this.options.eliminateNullChecks; } - _push() { + _push () { this.stackSize++; if (this.stackSize >= this.stack.length) this.stack.push(new BlobBuilder()); this.current.clear(); } - _pop(writeToOutput: boolean) { + _pop (writeToOutput: boolean) { if (this.stackSize <= 1) throw new Error("Stack empty"); @@ -178,31 +178,31 @@ export class WasmBuilder { return current.getArrayView(false).slice(0, current.size); } - setImportFunction(name: string, value: Function) { + setImportFunction (name: string, value: Function) { const imp = this.importedFunctions[name]; if (!imp) throw new Error("No import named " + name); imp.func = value; } - getExceptionTag(): any { + getExceptionTag (): any { const exceptionTag = (Module)["asm"]["__cpp_exception"]; if (typeof (exceptionTag) !== "undefined") mono_assert(exceptionTag instanceof (WebAssembly).Tag, () => `expected __cpp_exception export from dotnet.wasm to be WebAssembly.Tag but was ${exceptionTag}`); return exceptionTag; } - getWasmImports(): WebAssembly.Imports { + getWasmImports (): WebAssembly.Imports { const memory = runtimeHelpers.getMemory(); mono_assert(memory instanceof WebAssembly.Memory, () => `expected heap import to be WebAssembly.Memory but was ${memory}`); const exceptionTag = this.getExceptionTag(); const result: any = { c: this.getConstants(), - m: { h: memory }, + m: {h: memory}, }; if (exceptionTag) - result.x = { e: exceptionTag }; + result.x = {e: exceptionTag}; const importsToEmit = this.getImportsToEmit(); @@ -225,7 +225,7 @@ export class WasmBuilder { // HACK: Approximate amount of space we need to generate the full module at present // FIXME: This does not take into account any other functions already generated if they weren't // emitted into the module immediately - get bytesGeneratedSoFar() { + get bytesGeneratedSoFar () { const importSize = this.compressImportNames // mod (2 bytes) name (2-3 bytes) type (1 byte) typeidx (1-2 bytes) ? 8 @@ -242,74 +242,74 @@ export class WasmBuilder { this.estimatedExportBytes; } - get current() { + get current () { return this.stack[this.stackSize - 1]; } - get size() { + get size () { return this.current.size; } - appendU8(value: number | WasmOpcode) { + appendU8 (value: number | WasmOpcode) { if ((value != value >>> 0) || (value > 255)) throw new Error(`Byte out of range: ${value}`); return this.current.appendU8(value); } - appendSimd(value: WasmSimdOpcode, allowLoad?: boolean) { + appendSimd (value: WasmSimdOpcode, allowLoad?: boolean) { this.current.appendU8(WasmOpcode.PREFIX_simd); // Yes that's right. We're using LEB128 to encode 8-bit opcodes. Why? I don't know mono_assert(((value | 0) !== 0) || ((value === WasmSimdOpcode.v128_load) && (allowLoad === true)), "Expected non-v128_load simd opcode or allowLoad==true"); return this.current.appendULeb(value); } - appendU32(value: number) { + appendU32 (value: number) { return this.current.appendU32(value); } - appendF32(value: number) { + appendF32 (value: number) { return this.current.appendF32(value); } - appendF64(value: number) { + appendF64 (value: number) { return this.current.appendF64(value); } - appendBoundaryValue(bits: number, sign: number) { + appendBoundaryValue (bits: number, sign: number) { return this.current.appendBoundaryValue(bits, sign); } - appendULeb(value: number | MintOpcodePtr) { + appendULeb (value: number | MintOpcodePtr) { return this.current.appendULeb(value); } - appendLeb(value: number) { + appendLeb (value: number) { return this.current.appendLeb(value); } - appendLebRef(sourceAddress: VoidPtr, signed: boolean) { + appendLebRef (sourceAddress: VoidPtr, signed: boolean) { return this.current.appendLebRef(sourceAddress, signed); } - appendBytes(bytes: Uint8Array) { + appendBytes (bytes: Uint8Array) { return this.current.appendBytes(bytes); } - appendName(text: string) { + appendName (text: string) { return this.current.appendName(text); } - ret(ip: MintOpcodePtr) { + ret (ip: MintOpcodePtr) { this.ip_const(ip); this.appendU8(WasmOpcode.return_); } - i32_const(value: number | ManagedPointer | NativePointer) { + i32_const (value: number | ManagedPointer | NativePointer) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value); } - ptr_const(pointer: number | ManagedPointer | NativePointer) { + ptr_const (pointer: number | ManagedPointer | NativePointer) { let idx = this.options.useConstants ? this.constantSlots.indexOf(pointer) : -1; if ( this.options.useConstants && @@ -328,17 +328,17 @@ export class WasmBuilder { } } - ip_const(value: MintOpcodePtr) { + ip_const (value: MintOpcodePtr) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value - this.base); } - i52_const(value: number) { + i52_const (value: number) { this.appendU8(WasmOpcode.i64_const); this.appendLeb(value); } - v128_const(value: 0 | Uint8Array) { + v128_const (value: 0 | Uint8Array) { if (value === 0) { // This encoding is much smaller than a v128_const // But v8 doesn't optimize it :-(((((( @@ -367,7 +367,7 @@ export class WasmBuilder { } } - defineType( + defineType ( name: string, parameters: { [name: string]: WasmValtype }, returnType: WasmValtype, permanent: boolean ) { @@ -416,7 +416,7 @@ export class WasmBuilder { return index; } - generateTypeSection() { + generateTypeSection () { this.beginSection(1); this.appendULeb(this.functionTypeCount); /* @@ -442,7 +442,7 @@ export class WasmBuilder { this.endSection(); } - getImportedFunctionTable(): any { + getImportedFunctionTable (): any { const imports: any = {}; for (const k in this.importedFunctions) { const f = this.importedFunctions[k]; @@ -452,7 +452,7 @@ export class WasmBuilder { return imports; } - getCompressedName(ifi: ImportedFunctionInfo) { + getCompressedName (ifi: ImportedFunctionInfo) { if (!this.compressImportNames || typeof (ifi.index) !== "number") return ifi.name; @@ -462,7 +462,7 @@ export class WasmBuilder { return result; } - getImportsToEmit() { + getImportsToEmit () { const result = []; for (const k in this.importedFunctions) { const v = this.importedFunctions[k]; @@ -475,7 +475,7 @@ export class WasmBuilder { return result; } - _generateImportSection(includeFunctionTable?: boolean) { + _generateImportSection (includeFunctionTable?: boolean) { const importsToEmit = this.getImportsToEmit(); this.lockImports = true; @@ -554,7 +554,7 @@ export class WasmBuilder { } } - defineImportedFunction( + defineImportedFunction ( module: string, name: string, functionTypeName: string, permanent: boolean, func?: Function | number ): ImportedFunctionInfo { @@ -583,7 +583,7 @@ export class WasmBuilder { return result; } - markImportAsUsed(name: string) { + markImportAsUsed (name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -591,14 +591,14 @@ export class WasmBuilder { func.index = this.importedFunctionCount++; } - getTypeIndex(name: string) { + getTypeIndex (name: string) { const type = this.functionTypes[name]; if (!type) throw new Error("No type named " + name); return type[0]; } - defineFunction( + defineFunction ( options: { type: string, name: string, @@ -623,7 +623,7 @@ export class WasmBuilder { return rec; } - emitImportsAndFunctions(includeFunctionTable?: boolean) { + emitImportsAndFunctions (includeFunctionTable?: boolean) { let exportCount = 0; for (let i = 0; i < this.functions.length; i++) { const func = this.functions[i]; @@ -682,7 +682,7 @@ export class WasmBuilder { this.endSection(); } - call_indirect(/* functionTypeName: string, tableIndex: number */) { + call_indirect (/* functionTypeName: string, tableIndex: number */) { throw new Error("call_indirect unavailable"); /* const type = this.functionTypes[functionTypeName]; @@ -695,7 +695,7 @@ export class WasmBuilder { */ } - callImport(name: string) { + callImport (name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -708,7 +708,7 @@ export class WasmBuilder { this.appendULeb(func.index); } - beginSection(type: number) { + beginSection (type: number) { if (this.inSection) this._pop(true); this.appendU8(type); @@ -716,7 +716,7 @@ export class WasmBuilder { this.inSection = true; } - endSection() { + endSection () { if (!this.inSection) throw new Error("Not in section"); if (this.inFunction) @@ -735,7 +735,7 @@ export class WasmBuilder { return result; }; - _assignLocalIndices( + _assignLocalIndices ( counts: any, locals: { [name: string]: WasmValtype }, base: number, localGroupCount: number ) { @@ -794,7 +794,7 @@ export class WasmBuilder { return localGroupCount; } - beginFunction( + beginFunction ( type: string, locals?: { [name: string]: WasmValtype } ) { @@ -838,7 +838,7 @@ export class WasmBuilder { this.inFunction = true; } - endFunction(writeToOutput: boolean) { + endFunction (writeToOutput: boolean) { if (!this.inFunction) throw new Error("Not in function"); if (this.activeBlocks > 0) @@ -848,7 +848,7 @@ export class WasmBuilder { return result; } - block(type?: WasmValtype, opcode?: WasmOpcode) { + block (type?: WasmValtype, opcode?: WasmOpcode) { const result = this.appendU8(opcode || WasmOpcode.block); if (type) this.appendU8(type); @@ -858,14 +858,14 @@ export class WasmBuilder { return result; } - endBlock() { + endBlock () { if (this.activeBlocks <= 0) throw new Error("No blocks active"); this.activeBlocks--; this.appendU8(WasmOpcode.end); } - arg(name: string | number, opcode?: WasmOpcode) { + arg (name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name; @@ -876,7 +876,7 @@ export class WasmBuilder { this.appendULeb(index); } - local(name: string | number, opcode?: WasmOpcode) { + local (name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name + this.argumentCount; @@ -889,7 +889,7 @@ export class WasmBuilder { this.appendULeb(index); } - appendMemarg(offset: number, alignPower: number) { + appendMemarg (offset: number, alignPower: number) { this.appendULeb(alignPower); this.appendULeb(offset); } @@ -897,7 +897,7 @@ export class WasmBuilder { /* generates either (u32)get_local(ptr) + offset or (u32)ptr1 + offset */ - lea(ptr1: string | number, offset: number) { + lea (ptr1: string | number, offset: number) { if (typeof (ptr1) === "string") this.local(ptr1); else @@ -908,13 +908,13 @@ export class WasmBuilder { this.appendU8(WasmOpcode.i32_add); } - getArrayView(fullCapacity?: boolean) { + getArrayView (fullCapacity?: boolean) { if (this.stackSize > 1) throw new Error("Jiterpreter block stack not empty"); return this.stack[0].getArrayView(fullCapacity); } - getConstants() { + getConstants () { const result: { [key: string]: number } = {}; for (let i = 0; i < this.constantSlots.length; i++) result[i.toString(shortNameBase)] = this.constantSlots[i]; @@ -929,7 +929,7 @@ export class BlobBuilder { encoder?: TextEncoder; textBuf = new Uint8Array(1024); - constructor() { + constructor () { this.capacity = 16 * 1024; this.buffer = Module._malloc(this.capacity); localHeapViewU8().fill(0, this.buffer, this.buffer + this.capacity); @@ -939,11 +939,11 @@ export class BlobBuilder { this.encoder = new TextEncoder(); } - clear() { + clear () { this.size = 0; } - appendU8(value: number | WasmOpcode) { + appendU8 (value: number | WasmOpcode) { if (this.size >= this.capacity) throw new Error("Buffer full"); @@ -952,35 +952,35 @@ export class BlobBuilder { return result; } - appendU32(value: number) { + appendU32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.U32); this.size += 4; return result; } - appendI32(value: number) { + appendI32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.I32); this.size += 4; return result; } - appendF32(value: number) { + appendF32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F32); this.size += 4; return result; } - appendF64(value: number) { + appendF64 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F64); this.size += 8; return result; } - appendBoundaryValue(bits: number, sign: number) { + appendBoundaryValue (bits: number, sign: number) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -991,7 +991,7 @@ export class BlobBuilder { return bytesWritten; } - appendULeb(value: number) { + appendULeb (value: number) { mono_assert(typeof (value) === "number", () => `appendULeb expected number but got ${value}`); mono_assert(value >= 0, "cannot pass negative value to appendULeb"); if (value < 0x7F) { @@ -1012,7 +1012,7 @@ export class BlobBuilder { return bytesWritten; } - appendLeb(value: number) { + appendLeb (value: number) { mono_assert(typeof (value) === "number", () => `appendLeb expected number but got ${value}`); if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1024,7 +1024,7 @@ export class BlobBuilder { return bytesWritten; } - appendLebRef(sourceAddress: VoidPtr, signed: boolean) { + appendLebRef (sourceAddress: VoidPtr, signed: boolean) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1035,7 +1035,7 @@ export class BlobBuilder { return bytesWritten; } - copyTo(destination: BlobBuilder, count?: number) { + copyTo (destination: BlobBuilder, count?: number) { if (typeof (count) !== "number") count = this.size; @@ -1043,7 +1043,7 @@ export class BlobBuilder { destination.size += count; } - appendBytes(bytes: Uint8Array, count?: number) { + appendBytes (bytes: Uint8Array, count?: number) { const result = this.size; const heapU8 = localHeapViewU8(); if (bytes.buffer === heapU8.buffer) { @@ -1063,7 +1063,7 @@ export class BlobBuilder { return result; } - appendName(text: string) { + appendName (text: string) { let count = text.length; // TextEncoder overhead is significant for short strings, and lots of our strings // are single-character import names, so add a fast path for single characters @@ -1098,7 +1098,7 @@ export class BlobBuilder { this.appendBytes(this.textBuf, count); } - getArrayView(fullCapacity?: boolean) { + getArrayView (fullCapacity?: boolean) { return new Uint8Array(localHeapViewU8().buffer, this.buffer, fullCapacity ? this.capacity : this.size); } } @@ -1155,11 +1155,11 @@ class Cfg { observedBackBranchTargets = new Set(); trace = 0; - constructor(builder: WasmBuilder) { + constructor (builder: WasmBuilder) { this.builder = builder; } - initialize(startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { + initialize (startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { this.segments.length = 0; this.blockStack.length = 0; this.startOfBody = startOfBody; @@ -1175,7 +1175,7 @@ class Cfg { } // We have a header containing the table of locals and we need to preserve it - entry(ip: MintOpcodePtr) { + entry (ip: MintOpcodePtr) { this.entryIp = ip; // Skip over the enter opcode const enterSizeU16 = cwraps.mono_jiterp_get_opcode_info(MintOpcode.MINT_TIER_ENTER_JITERPRETER, OpcodeInfoType.Length); @@ -1193,7 +1193,7 @@ class Cfg { return this.firstOpcodeIp; } - appendBlob() { + appendBlob () { if (this.builder.current.size === this.lastSegmentEnd) return; @@ -1209,7 +1209,7 @@ class Cfg { this.overheadBytes += 2; } - startBranchBlock(ip: MintOpcodePtr, isBackBranchTarget: boolean) { + startBranchBlock (ip: MintOpcodePtr, isBackBranchTarget: boolean) { this.appendBlob(); this.segments.push({ type: "branch-block-header", @@ -1219,7 +1219,7 @@ class Cfg { this.overheadBytes += 1; // each branch block just costs us an end } - branch(target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { + branch (target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { if (isBackward) this.observedBackBranchTargets.add(target); @@ -1252,13 +1252,13 @@ class Cfg { } } - emitBlob(segment: CfgBlob, source: Uint8Array) { + emitBlob (segment: CfgBlob, source: Uint8Array) { // mono_log_info(`segment @${(segment.ip).toString(16)} ${segment.start}-${segment.start + segment.length}`); const view = source.subarray(segment.start, segment.start + segment.length); this.builder.appendBytes(view); } - generate(): Uint8Array { + generate (): Uint8Array { // HACK: Make sure any remaining bytes are inserted into a trailing segment this.appendBlob(); @@ -1517,7 +1517,7 @@ export const _now = (globalThis.performance && globalThis.performance.now) let scratchBuffer: NativePointer = 0; -export function append_safepoint(builder: WasmBuilder, ip: MintOpcodePtr) { +export function append_safepoint (builder: WasmBuilder, ip: MintOpcodePtr) { // safepoints are never triggered in a single-threaded build if (!WasmEnableThreads) return; @@ -1534,7 +1534,7 @@ export function append_safepoint(builder: WasmBuilder, ip: MintOpcodePtr) { builder.endBlock(); } -export function append_bailout(builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { +export function append_bailout (builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { builder.ip_const(ip); if (builder.options.countBailouts) { builder.i32_const(builder.traceIndex); @@ -1545,7 +1545,7 @@ export function append_bailout(builder: WasmBuilder, ip: MintOpcodePtr, reason: } // generate a bailout that is recorded for the monitoring phase as a possible early exit. -export function append_exit(builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { +export function append_exit (builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { /* * disp will always be nonzero once we've taken at least one backward branch. * if (cinfo) { @@ -1581,7 +1581,7 @@ export function append_exit(builder: WasmBuilder, ip: MintOpcodePtr, opcodeCount builder.appendU8(WasmOpcode.return_); } -export function copyIntoScratchBuffer(src: NativePointer, size: number): NativePointer { +export function copyIntoScratchBuffer (src: NativePointer, size: number): NativePointer { if (!scratchBuffer) scratchBuffer = Module._malloc(64); if (size > 64) @@ -1591,7 +1591,7 @@ export function copyIntoScratchBuffer(src: NativePointer, size: number): NativeP return scratchBuffer; } -export function getWasmFunctionTable() { +export function getWasmFunctionTable () { if (!wasmTable) wasmTable = runtimeHelpers.getWasmIndirectFunctionTable(); if (!wasmTable) @@ -1599,7 +1599,7 @@ export function getWasmFunctionTable() { return wasmTable; } -export function addWasmFunctionPointer(table: JiterpreterTable, f: Function) { +export function addWasmFunctionPointer (table: JiterpreterTable, f: Function) { mono_assert(f, "Attempting to set null function into table"); const index = cwraps.mono_jiterp_allocate_table_entry(table); @@ -1613,7 +1613,7 @@ export function addWasmFunctionPointer(table: JiterpreterTable, f: Function) { return index; } -export function try_append_memset_fast(builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { +export function try_append_memset_fast (builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { if (count <= 0) { if (destOnStack) builder.appendU8(WasmOpcode.drop); @@ -1684,7 +1684,7 @@ export function try_append_memset_fast(builder: WasmBuilder, localOffset: number return true; } -export function append_memset_dest(builder: WasmBuilder, value: number, count: number) { +export function append_memset_dest (builder: WasmBuilder, value: number, count: number) { // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val if (try_append_memset_fast(builder, 0, value, count, true)) return; @@ -1696,7 +1696,7 @@ export function append_memset_dest(builder: WasmBuilder, value: number, count: n builder.appendU8(0); } -export function try_append_memmove_fast( +export function try_append_memmove_fast ( builder: WasmBuilder, destLocalOffset: number, srcLocalOffset: number, count: number, addressesOnStack: boolean, destLocal?: string, srcLocal?: string ) { @@ -1796,7 +1796,7 @@ export function try_append_memmove_fast( } // expects dest then source to have been pushed onto wasm stack -export function append_memmove_dest_src(builder: WasmBuilder, count: number) { +export function append_memmove_dest_src (builder: WasmBuilder, count: number) { if (try_append_memmove_fast(builder, 0, 0, count, true)) return true; @@ -1810,7 +1810,7 @@ export function append_memmove_dest_src(builder: WasmBuilder, count: number) { return true; } -export function recordFailure(): void { +export function recordFailure (): void { const result = modifyCounter(JiterpCounter.Failures, 1); if (result >= maxFailures) { mono_log_info(`Disabling jiterpreter after ${result} failures`); @@ -1824,7 +1824,7 @@ export function recordFailure(): void { const memberOffsets: { [index: number]: number } = {}; -export function getMemberOffset(member: JiterpMember) { +export function getMemberOffset (member: JiterpMember) { const cached = memberOffsets[member]; if (cached === undefined) return memberOffsets[member] = cwraps.mono_jiterp_get_member_offset(member); @@ -1832,7 +1832,7 @@ export function getMemberOffset(member: JiterpMember) { return cached; } -export function getRawCwrap(name: string): Function { +export function getRawCwrap (name: string): Function { const result = (Module)["asm"][name]; if (typeof (result) !== "function") throw new Error(`raw cwrap ${name} not found`); @@ -1841,18 +1841,18 @@ export function getRawCwrap(name: string): Function { const opcodeTableCache: { [opcode: number]: number } = {}; -export function getOpcodeTableValue(opcode: MintOpcode) { +export function getOpcodeTableValue (opcode: MintOpcode) { let result = opcodeTableCache[opcode]; if (typeof (result) !== "number") result = opcodeTableCache[opcode] = cwraps.mono_jiterp_get_opcode_value_table_entry(opcode); return result; } -export function importDef(name: string, fn: Function): [string, string, Function] { +export function importDef (name: string, fn: Function): [string, string, Function] { return [name, name, fn]; } -export function bytesFromHex(hex: string): Uint8Array { +export function bytesFromHex (hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16); @@ -1861,7 +1861,7 @@ export function bytesFromHex(hex: string): Uint8Array { let observedTaintedZeroPage: boolean | undefined; -export function isZeroPageReserved(): boolean { +export function isZeroPageReserved (): boolean { // FIXME: This check will always return true on worker threads. // Right now the jiterpreter is disabled when threading is active, so that's not an issue. if (WasmEnableThreads) @@ -1976,7 +1976,7 @@ let optionsVersion = -1; let optionTable: JiterpreterOptions = {}; // applies one or more jiterpreter options to change the current jiterpreter configuration. -export function applyOptions(options: JiterpreterOptions) { +export function applyOptions (options: JiterpreterOptions) { for (const k in options) { const info = optionNames[k]; if (!info) { @@ -1994,16 +1994,16 @@ export function applyOptions(options: JiterpreterOptions) { } } -export function getCounter(counter: JiterpCounter): number { +export function getCounter (counter: JiterpCounter): number { return cwraps.mono_jiterp_get_counter(counter); } -export function modifyCounter(counter: JiterpCounter, delta: number): number { +export function modifyCounter (counter: JiterpCounter, delta: number): number { return cwraps.mono_jiterp_modify_counter(counter, delta); } // returns the current jiterpreter configuration. do not mutate the return value! -export function getOptions() { +export function getOptions () { const currentVersion = cwraps.mono_jiterp_get_options_version(); if (currentVersion !== optionsVersion) { updateOptions(); @@ -2012,7 +2012,7 @@ export function getOptions() { return optionTable; } -function updateOptions() { +function updateOptions () { const pJson = cwraps.mono_jiterp_get_options_as_json(); const json = utf8ToString(pJson); Module._free(pJson); @@ -2025,7 +2025,7 @@ function updateOptions() { } } -function jiterpreter_allocate_table(type: JiterpreterTable, base: number, size: number, fillValue: Function) { +function jiterpreter_allocate_table (type: JiterpreterTable, base: number, size: number, fillValue: Function) { const wasmTable = getWasmFunctionTable(); const firstIndex = base, lastIndex = firstIndex + size - 1; mono_assert(lastIndex < wasmTable.length, () => `Last index out of range: ${lastIndex} >= ${wasmTable.length}`); @@ -2049,7 +2049,7 @@ function jiterpreter_allocate_table(type: JiterpreterTable, base: number, size: // we need to ensure we only ever initialize tables once on each js worker. let jiterpreter_tables_allocated = false; -export function jiterpreter_allocate_tables() { +export function jiterpreter_allocate_tables () { if (jiterpreter_tables_allocated) return; jiterpreter_tables_allocated = true; diff --git a/src/mono/browser/runtime/jiterpreter-trace-generator.ts b/src/mono/browser/runtime/jiterpreter-trace-generator.ts index 1a629223b3a96b..f822de0a3b4403 100644 --- a/src/mono/browser/runtime/jiterpreter-trace-generator.ts +++ b/src/mono/browser/runtime/jiterpreter-trace-generator.ts @@ -1,8 +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 { MonoMethod } from "./types/internal"; -import { NativePointer } from "./types/emscripten"; +import {MonoMethod} from "./types/internal"; +import {NativePointer} from "./types/emscripten"; import { getU16, getI16, getU32_unaligned, getI32_unaligned, getF32_unaligned, getF64_unaligned, localHeapViewU8, @@ -55,54 +55,54 @@ import { simdExtractTable, simdReplaceTable, simdLoadTable, simdStoreTable, } from "./jiterpreter-tables"; -import { mono_log_error, mono_log_info } from "./logging"; -import { mono_assert, runtimeHelpers } from "./globals"; +import {mono_log_error, mono_log_info} from "./logging"; +import {mono_assert, runtimeHelpers} from "./globals"; // indexPlusOne so that ip[1] in the interpreter becomes getArgU16(ip, 1) -function getArgU16(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgU16 (ip: MintOpcodePtr, indexPlusOne: number) { return getU16(ip + (2 * indexPlusOne)); } -function getArgI16(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI16 (ip: MintOpcodePtr, indexPlusOne: number) { return getI16(ip + (2 * indexPlusOne)); } -function getArgI32(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI32 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getI32_unaligned(src); } -function getArgF32(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF32 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF32_unaligned(src); } -function getArgF64(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF64 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF64_unaligned(src); } -function get_imethod(frame: NativePointer) { +function get_imethod (frame: NativePointer) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const iMethod = getU32_unaligned(frame + getMemberOffset(JiterpMember.Imethod)); return iMethod; } -function get_imethod_data(frame: NativePointer, index: number) { +function get_imethod_data (frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.DataItems)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function get_imethod_clause_data_offset(frame: NativePointer, index: number) { +function get_imethod_clause_data_offset (frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.ClauseDataOffsets)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function is_backward_branch_target( +function is_backward_branch_target ( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, backwardBranchTable: Uint16Array | null ) { @@ -122,7 +122,7 @@ function is_backward_branch_target( type KnownConstantValue = number | Uint8Array; const knownConstantValues = new Map(); -function get_known_constant_value(builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { +function get_known_constant_value (builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { if (isAddressTaken(builder, localOffset)) return undefined; @@ -133,7 +133,7 @@ function get_known_constant_value(builder: WasmBuilder, localOffset: number): Kn // backwards branch targets, compatible with the layout of the old one that was generated in C. // We do this here to match the exact way that the jiterp calculates branch targets, since // there were previously corner cases where jiterp and interp disagreed. -export function generateBackwardBranchTable( +export function generateBackwardBranchTable ( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, ): Uint16Array | null { const endOfBody = startOfBody + sizeOfBody; @@ -206,7 +206,7 @@ export function generateBackwardBranchTable( return new Uint16Array(table); } -export function generateWasmBody( +export function generateWasmBody ( frame: NativePointer, traceName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, endOfBody: MintOpcodePtr, builder: WasmBuilder, instrumentedTraceId: number, @@ -1709,29 +1709,29 @@ export function generateWasmBody( const notNullSince: Map = new Map(); let cknullOffset = -1; -function eraseInferredState() { +function eraseInferredState () { cknullOffset = -1; notNullSince.clear(); knownConstantValues.clear(); } -function invalidate_local(offset: number) { +function invalidate_local (offset: number) { if (cknullOffset === offset) cknullOffset = -1; notNullSince.delete(offset); knownConstantValues.delete(offset); } -function invalidate_local_range(start: number, bytes: number) { +function invalidate_local_range (start: number, bytes: number) { for (let i = 0; i < bytes; i += 1) invalidate_local(start + i); } -function append_branch_target_block(builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { +function append_branch_target_block (builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { builder.cfg.startBranchBlock(ip, isBackBranchTarget); } -function computeMemoryAlignment(offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function computeMemoryAlignment (offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { // First, compute the best possible alignment let alignment = 0; if (offset % 16 === 0) @@ -1792,7 +1792,7 @@ function computeMemoryAlignment(offset: number, opcodeOrPrefix: WasmOpcode, simd return alignment; } -function append_ldloc(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_ldloc (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { builder.local("pLocals"); mono_assert(opcodeOrPrefix >= WasmOpcode.i32_load, () => `Expected load opcode but got ${opcodeOrPrefix}`); builder.appendU8(opcodeOrPrefix); @@ -1811,7 +1811,7 @@ function append_ldloc(builder: WasmBuilder, offset: number, opcodeOrPrefix: Wasm // where the offset+alignment pair is referred to as a 'memarg' by the spec. // The actual store operation is equivalent to `pBase[offset] = value` (alignment has no // observable impact on behavior, other than causing compilation failures if out of range) -function append_stloc_tail(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_stloc_tail (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { mono_assert(opcodeOrPrefix >= WasmOpcode.i32_store, () => `Expected store opcode but got ${opcodeOrPrefix}`); builder.appendU8(opcodeOrPrefix); if (simdOpcode !== undefined) { @@ -1830,7 +1830,7 @@ function append_stloc_tail(builder: WasmBuilder, offset: number, opcodeOrPrefix: // used for writes // Pass transient=true if the address will not persist after use (so it can't be used to later // modify the contents of this local) -function append_ldloca(builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { +function append_ldloca (builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { if (typeof (bytesInvalidated) !== "number") bytesInvalidated = 512; // FIXME: We need to know how big this variable is so we can invalidate the whole space it occupies @@ -1839,7 +1839,7 @@ function append_ldloca(builder: WasmBuilder, localOffset: number, bytesInvalidat builder.lea("pLocals", localOffset); } -function append_memset_local(builder: WasmBuilder, localOffset: number, value: number, count: number) { +function append_memset_local (builder: WasmBuilder, localOffset: number, value: number, count: number) { invalidate_local_range(localOffset, count); // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val @@ -1851,7 +1851,7 @@ function append_memset_local(builder: WasmBuilder, localOffset: number, value: n append_memset_dest(builder, value, count); } -function append_memmove_local_local(builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { +function append_memmove_local_local (builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { invalidate_local_range(destLocalOffset, count); if (try_append_memmove_fast(builder, destLocalOffset, sourceLocalOffset, count, false)) @@ -1863,12 +1863,12 @@ function append_memmove_local_local(builder: WasmBuilder, destLocalOffset: numbe append_memmove_dest_src(builder, count); } -function isAddressTaken(builder: WasmBuilder, localOffset: number) { +function isAddressTaken (builder: WasmBuilder, localOffset: number) { return cwraps.mono_jiterp_is_imethod_var_address_taken(get_imethod(builder.frame), localOffset) !== 0; } // Loads the specified i32 value and then bails out if it is null, leaving it in the cknull_ptr local. -function append_ldloc_cknull(builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { +function append_ldloc_cknull (builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { const optimize = builder.allowNullCheckOptimization && notNullSince.has(localOffset) && !isAddressTaken(builder, localOffset); @@ -1920,7 +1920,7 @@ function append_ldloc_cknull(builder: WasmBuilder, localOffset: number, ip: Mint cknullOffset = -1; } -function emit_ldc(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_ldc (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let storeType = WasmOpcode.i32_store; let value: number | undefined; @@ -1992,7 +1992,7 @@ function emit_ldc(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function emit_mov(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_mov (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let loadOp = WasmOpcode.i32_load, storeOp = WasmOpcode.i32_store; switch (opcode) { case MintOpcode.MINT_MOV_I4_I1: @@ -2055,7 +2055,7 @@ function emit_mov(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function append_vtable_initialize(builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { +function append_vtable_initialize (builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { // TODO: Actually initialize the vtable instead of just checking and bailing out? builder.block(); // FIXME: This will prevent us from reusing traces between runs since the vtables can move @@ -2070,7 +2070,7 @@ function append_vtable_initialize(builder: WasmBuilder, pVtable: NativePointer, builder.endBlock(); } -function emit_fieldop( +function emit_fieldop ( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2264,7 +2264,7 @@ function emit_fieldop( } } -function emit_sfieldop( +function emit_sfieldop ( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2371,7 +2371,7 @@ function emit_sfieldop( } } -function emit_binop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_binop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right let lhsLoadOp: WasmOpcode, rhsLoadOp: WasmOpcode, storeOp: WasmOpcode, lhsVar = "math_lhs32", rhsVar = "math_rhs32", @@ -2523,7 +2523,7 @@ function emit_binop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode) return true; } -function emit_unop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_unop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right const info = unopTable[opcode]; if (!info) @@ -2662,7 +2662,7 @@ function emit_unop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function append_call_handler_store_ret_ip( +function append_call_handler_store_ret_ip ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ) { @@ -2682,7 +2682,7 @@ function append_call_handler_store_ret_ip( builder.callHandlerReturnAddresses.push(retIp); } -function getBranchDisplacement( +function getBranchDisplacement ( ip: MintOpcodePtr, opcode: MintOpcode ) : number | undefined { const opArgType = cwraps.mono_jiterp_get_opcode_info(opcode, OpcodeInfoType.OpArgType), @@ -2710,7 +2710,7 @@ function getBranchDisplacement( return result; } -function emit_branch( +function emit_branch ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2851,7 +2851,7 @@ function emit_branch( return true; } -function emit_relop_branch( +function emit_relop_branch ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2906,7 +2906,7 @@ function emit_relop_branch( return emit_branch(builder, ip, frame, opcode); } -function emit_math_intrinsic(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_math_intrinsic (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let isUnary: boolean, isF32: boolean, name: string | undefined; let wasmOp: WasmOpcode | undefined; const destOffset = getArgU16(ip, 1), @@ -2954,7 +2954,7 @@ function emit_math_intrinsic(builder: WasmBuilder, ip: MintOpcodePtr, opcode: Mi } } -function emit_indirectop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_indirectop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = (opcode >= MintOpcode.MINT_LDIND_I1) && (opcode <= MintOpcode.MINT_LDIND_OFFSET_ADD_MUL_IMM_I8); const isAddMul = ( @@ -3152,7 +3152,7 @@ function emit_indirectop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOp return true; } -function append_getelema1( +function append_getelema1 ( builder: WasmBuilder, ip: MintOpcodePtr, objectOffset: number, indexOffset: number, elementSize: number ) { @@ -3211,7 +3211,7 @@ function append_getelema1( // append_getelema1 leaves the address on the stack } -function emit_arrayop(builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_arrayop (builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = ((opcode <= MintOpcode.MINT_LDELEMA_TC) && (opcode >= MintOpcode.MINT_LDELEM_I1)) || (opcode === MintOpcode.MINT_LDLEN), objectOffset = getArgU16(ip, isLoad ? 2 : 1), @@ -3375,7 +3375,7 @@ function emit_arrayop(builder: WasmBuilder, frame: NativePointer, ip: MintOpcode let wasmSimdSupported: boolean | undefined; -function getIsWasmSimdSupported(): boolean { +function getIsWasmSimdSupported (): boolean { if (wasmSimdSupported !== undefined) return wasmSimdSupported; @@ -3386,7 +3386,7 @@ function getIsWasmSimdSupported(): boolean { return wasmSimdSupported; } -function get_import_name( +function get_import_name ( builder: WasmBuilder, typeName: string, functionPtr: number ): string { @@ -3397,7 +3397,7 @@ function get_import_name( return name; } -function emit_simd( +function emit_simd ( builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode, opname: string, argCount: number, index: number @@ -3498,31 +3498,31 @@ function emit_simd( } } -function append_simd_store(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_store (builder: WasmBuilder, ip: MintOpcodePtr) { append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_store); } -function append_simd_2_load(builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { +function append_simd_2_load (builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { builder.local("pLocals"); // This || is harmless since v128_load is 0 append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, loadOp || WasmSimdOpcode.v128_load); } -function append_simd_3_load(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_3_load (builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); // FIXME: Can rhs be a scalar? We handle shifts separately already append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function append_simd_4_load(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_4_load (builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 4), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function emit_simd_2(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { +function emit_simd_2 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(1, index); if (simple >= 0) { if (simdLoadTable.has(index)) { @@ -3589,7 +3589,7 @@ function emit_simd_2(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrins } } -function emit_simd_3(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { +function emit_simd_3 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(2, index); if (simple >= 0) { const isShift = simdShiftTable.has(index), @@ -3710,7 +3710,7 @@ function emit_simd_3(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrins // implement i16 and i32 shuffles on top of wasm's only shuffle opcode by expanding the // element shuffle indices into byte indices -function emit_shuffle(builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { +function emit_shuffle (builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { const elementSize = 16 / elementCount, indicesOffset = getArgU16(ip, 3), constantIndices = get_known_constant_value(builder, indicesOffset); @@ -3771,7 +3771,7 @@ function emit_shuffle(builder: WasmBuilder, ip: MintOpcodePtr, elementCount: num return true; } -function emit_simd_4(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { +function emit_simd_4 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(3, index); if (simple >= 0) { // [lane count, value load opcode] diff --git a/src/mono/browser/runtime/jiterpreter.ts b/src/mono/browser/runtime/jiterpreter.ts index 188ead0c51e99c..3d498308d1e1dd 100644 --- a/src/mono/browser/runtime/jiterpreter.ts +++ b/src/mono/browser/runtime/jiterpreter.ts @@ -1,12 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { MonoMethod } from "./types/internal"; -import { NativePointer } from "./types/emscripten"; -import { Module, mono_assert, runtimeHelpers } from "./globals"; -import { getU16 } from "./memory"; -import { WasmValtype, WasmOpcode, getOpcodeName } from "./jiterpreter-opcodes"; -import { MintOpcode } from "./mintops"; +import {MonoMethod} from "./types/internal"; +import {NativePointer} from "./types/emscripten"; +import {Module, mono_assert, runtimeHelpers} from "./globals"; +import {getU16} from "./memory"; +import {WasmValtype, WasmOpcode, getOpcodeName} from "./jiterpreter-opcodes"; +import {MintOpcode} from "./mintops"; import cwraps from "./cwraps"; import { MintOpcodePtr, WasmBuilder, addWasmFunctionPointer, @@ -22,10 +22,10 @@ import { import { generateWasmBody, generateBackwardBranchTable } from "./jiterpreter-trace-generator"; -import { mono_jiterp_free_method_data_interp_entry } from "./jiterpreter-interp-entry"; -import { mono_jiterp_free_method_data_jit_call } from "./jiterpreter-jit-call"; -import { mono_log_error, mono_log_info, mono_log_warn } from "./logging"; -import { utf8ToString } from "./strings"; +import {mono_jiterp_free_method_data_interp_entry} from "./jiterpreter-interp-entry"; +import {mono_jiterp_free_method_data_jit_call} from "./jiterpreter-jit-call"; +import {mono_log_error, mono_log_info, mono_log_warn} from "./logging"; +import {utf8ToString} from "./strings"; // Controls miscellaneous diagnostic output. export const trace = 0; @@ -98,7 +98,7 @@ export class InstrumentedTraceState { operand1: number | undefined; operand2: number | undefined; - constructor(name: string) { + constructor (name: string) { this.name = name; this.eip = 0; } @@ -114,13 +114,13 @@ export class TraceInfo { bailoutCount: number | undefined; isVerbose: boolean; - constructor(ip: MintOpcodePtr, index: number, isVerbose: number) { + constructor (ip: MintOpcodePtr, index: number, isVerbose: number) { this.ip = ip; this.index = index; this.isVerbose = !!isVerbose; } - get hitCount() { + get hitCount () { return cwraps.mono_jiterp_get_trace_hit_count(this.index); } } @@ -225,7 +225,7 @@ const mathOps1d = "powf", ]; -function recordBailout(ip: number, traceIndex: number, reason: BailoutReason) { +function recordBailout (ip: number, traceIndex: number, reason: BailoutReason) { cwraps.mono_jiterp_trace_bailout(reason); // Counting these is not meaningful and messes up the end of run statistics if (reason === BailoutReason.Return) @@ -251,7 +251,7 @@ function recordBailout(ip: number, traceIndex: number, reason: BailoutReason) { return ip; } -function getTraceImports() { +function getTraceImports () { if (traceImports) return traceImports; @@ -313,7 +313,7 @@ function getTraceImports() { return traceImports; } -function initialize_builder(builder: WasmBuilder) { +function initialize_builder (builder: WasmBuilder) { // Function type for compiled traces builder.defineType( "trace", @@ -694,7 +694,7 @@ function initialize_builder(builder: WasmBuilder) { } } -function assert_not_null( +function assert_not_null ( value: number, expectedValue: number, traceIndex: number, ip: MintOpcodePtr ) { if (value && (value === expectedValue)) @@ -704,7 +704,7 @@ function assert_not_null( } // returns function id -function generate_wasm( +function generate_wasm ( frame: NativePointer, methodName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, traceIndex: number, methodFullName: string | undefined, @@ -948,7 +948,7 @@ function generate_wasm( } } -export function trace_current_ip(traceId: number, eip: MintOpcodePtr) { +export function trace_current_ip (traceId: number, eip: MintOpcodePtr) { const tup = instrumentedTraces[traceId]; if (!tup) throw new Error(`Unrecognized instrumented trace id ${traceId}`); @@ -956,14 +956,14 @@ export function trace_current_ip(traceId: number, eip: MintOpcodePtr) { mostRecentTrace = tup; } -export function trace_operands(a: number, b: number) { +export function trace_operands (a: number, b: number) { if (!mostRecentTrace) throw new Error("No trace active"); mostRecentTrace.operand1 = a >>> 0; mostRecentTrace.operand2 = b >>> 0; } -export function record_abort(traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { +export function record_abort (traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { if (typeof (reason) === "number") { cwraps.mono_jiterp_adjust_abort_count(reason, 1); reason = getOpcodeName(reason); @@ -986,7 +986,7 @@ export function record_abort(traceIndex: number, ip: MintOpcodePtr, traceName: s const JITERPRETER_TRAINING = 0; const JITERPRETER_NOT_JITTED = 1; -export function mono_interp_tier_prepare_jiterpreter( +export function mono_interp_tier_prepare_jiterpreter ( frame: NativePointer, method: MonoMethod, ip: MintOpcodePtr, index: number, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, isVerbose: number, presetFunctionPointer: number @@ -1061,7 +1061,7 @@ export function mono_interp_tier_prepare_jiterpreter( // NOTE: This will potentially be called once for every trace entry point // in a given method, not just once per method -export function mono_jiterp_free_method_data_js( +export function mono_jiterp_free_method_data_js ( method: MonoMethod, imethod: number, traceIndex: number ) { // TODO: Uninstall the trace function pointer from the function pointer table, @@ -1073,7 +1073,7 @@ export function mono_jiterp_free_method_data_js( mono_jiterp_free_method_data_jit_call(method); } -export function jiterpreter_dump_stats(concise?: boolean): void { +export function jiterpreter_dump_stats (concise?: boolean): void { if (!runtimeHelpers.runtimeReady) { return; } diff --git a/src/mono/browser/runtime/lazyLoading.ts b/src/mono/browser/runtime/lazyLoading.ts index 6d7ea7852f8c52..8aed4ddc3f8fdd 100644 --- a/src/mono/browser/runtime/lazyLoading.ts +++ b/src/mono/browser/runtime/lazyLoading.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { loaderHelpers } from "./globals"; -import { load_lazy_assembly } from "./managed-exports"; -import { AssetEntry } from "./types"; +import {loaderHelpers} from "./globals"; +import {load_lazy_assembly} from "./managed-exports"; +import {AssetEntry} from "./types"; -export async function loadLazyAssembly(assemblyNameToLoad: string): Promise { +export async function loadLazyAssembly (assemblyNameToLoad: string): Promise { const resources = loaderHelpers.config.resources!; const lazyAssemblies = resources.lazyAssembly; if (!lazyAssemblies) { @@ -56,11 +56,11 @@ export async function loadLazyAssembly(assemblyNameToLoad: string): Promise | undefined; @@ -91,11 +91,11 @@ const loadIntoWorker: { "segmentation-rules": true, }; -export function shouldLoadIcuAsset(asset: AssetEntryInternal): boolean { +export function shouldLoadIcuAsset (asset: AssetEntryInternal): boolean { return !(asset.behavior == "icu" && asset.name != loaderHelpers.preferredIcuAsset); } -function convert_single_asset(assetsCollection: AssetEntryInternal[], resource: ResourceList | undefined, behavior: SingleAssetBehaviors): AssetEntryInternal { +function convert_single_asset (assetsCollection: AssetEntryInternal[], resource: ResourceList | undefined, behavior: SingleAssetBehaviors): AssetEntryInternal { const keys = Object.keys(resource || {}); mono_assert(keys.length == 1, `Expect to have one ${behavior} asset in resources`); @@ -114,20 +114,20 @@ function convert_single_asset(assetsCollection: AssetEntryInternal[], resource: return asset; } -function set_single_asset(asset: AssetEntryInternal) { +function set_single_asset (asset: AssetEntryInternal) { if (singleAssetTypes[asset.behavior]) { singleAssets.set(asset.behavior, asset); } } -function get_single_asset(behavior: SingleAssetBehaviors): AssetEntryInternal { +function get_single_asset (behavior: SingleAssetBehaviors): AssetEntryInternal { mono_assert(singleAssetTypes[behavior], `Unknown single asset behavior ${behavior}`); const asset = singleAssets.get(behavior); mono_assert(asset, `Single asset for ${behavior} not found`); return asset; } -export function resolve_single_asset_path(behavior: SingleAssetBehaviors): AssetEntryInternal { +export function resolve_single_asset_path (behavior: SingleAssetBehaviors): AssetEntryInternal { const asset = get_single_asset(behavior); if (!asset.resolvedUrl) { asset.resolvedUrl = loaderHelpers.locateFile(asset.name); @@ -148,7 +148,7 @@ export function resolve_single_asset_path(behavior: SingleAssetBehaviors): Asset return asset; } -export async function mono_download_assets(): Promise { +export async function mono_download_assets (): Promise { mono_log_debug("mono_download_assets"); try { const promises_of_assets: Promise[] = []; @@ -237,7 +237,7 @@ export async function mono_download_assets(): Promise { } } -export function prepareAssets() { +export function prepareAssets () { const config = loaderHelpers.config; const modulesAssets: AssetEntryInternal[] = []; @@ -365,7 +365,7 @@ export function prepareAssets() { config.assets = [...assetsToLoad, ...modulesAssets]; } -export function prepareAssetsWorker() { +export function prepareAssetsWorker () { const config = loaderHelpers.config; mono_assert(config.assets, "config.assets must be defined"); @@ -377,18 +377,18 @@ export function prepareAssetsWorker() { } } -export function delay(ms: number): Promise { +export function delay (ms: number): Promise { return new Promise(resolve => globalThis.setTimeout(resolve, ms)); } -export async function retrieve_asset_download(asset: AssetEntry): Promise { +export async function retrieve_asset_download (asset: AssetEntry): Promise { const pendingAsset = await start_asset_download(asset); await pendingAsset.pendingDownloadInternal!.response; return pendingAsset.buffer!; } // FIXME: Connection reset is probably the only good one for which we should retry -export async function start_asset_download(asset: AssetEntryInternal): Promise { +export async function start_asset_download (asset: AssetEntryInternal): Promise { try { return await start_asset_download_with_throttle(asset); } catch (err: any) { @@ -429,7 +429,7 @@ export async function start_asset_download(asset: AssetEntryInternal): Promise { +async function start_asset_download_with_throttle (asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! while (throttlingPromise) { await throttlingPromise.promise; @@ -452,8 +452,7 @@ async function start_asset_download_with_throttle(asset: AssetEntryInternal): Pr asset.buffer = await response.arrayBuffer(); ++loaderHelpers.actual_downloaded_assets_count; return asset; - } - finally { + } finally { --parallel_count; if (throttlingPromise && parallel_count == loaderHelpers.maxParallelDownloads - 1) { mono_log_debug("Resuming more parallel downloads"); @@ -464,7 +463,7 @@ async function start_asset_download_with_throttle(asset: AssetEntryInternal): Pr } } -async function start_asset_download_sources(asset: AssetEntryInternal): Promise { +async function start_asset_download_sources (asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! if (asset.pendingDownload) { asset.pendingDownloadInternal = asset.pendingDownload; @@ -484,7 +483,9 @@ async function start_asset_download_sources(asset: AssetEntryInternal): Promise< ok: true, arrayBuffer: () => buffer, json: () => JSON.parse(new TextDecoder("utf-8").decode(buffer)), - text: () => { throw new Error("NotImplementedException"); }, + text: () => { + throw new Error("NotImplementedException"); + }, headers: { get: () => undefined, } @@ -516,8 +517,7 @@ async function start_asset_download_sources(asset: AssetEntryInternal): Promise< continue;// next source } return response; - } - catch (err) { + } catch (err) { if (!response) { response = { ok: false, @@ -541,34 +541,31 @@ async function start_asset_download_sources(asset: AssetEntryInternal): Promise< } } -function resolve_path(asset: AssetEntry, sourcePrefix: string): string { +function resolve_path (asset: AssetEntry, sourcePrefix: string): string { mono_assert(sourcePrefix !== null && sourcePrefix !== undefined, () => `sourcePrefix must be provided for ${asset.name}`); let attemptUrl; if (!asset.resolvedUrl) { if (sourcePrefix === "") { if (asset.behavior === "assembly" || asset.behavior === "pdb") { attemptUrl = asset.name; - } - else if (asset.behavior === "resource") { + } else if (asset.behavior === "resource") { const path = asset.culture && asset.culture !== "" ? `${asset.culture}/${asset.name}` : asset.name; attemptUrl = path; - } - else { + } else { attemptUrl = asset.name; } } else { attemptUrl = sourcePrefix + asset.name; } attemptUrl = appendUniqueQuery(loaderHelpers.locateFile(attemptUrl), asset.behavior); - } - else { + } else { attemptUrl = asset.resolvedUrl; } mono_assert(attemptUrl && typeof attemptUrl == "string", "attemptUrl need to be path or url string"); return attemptUrl; } -export function appendUniqueQuery(attemptUrl: string, behavior: AssetBehaviors): string { +export function appendUniqueQuery (attemptUrl: string, behavior: AssetBehaviors): string { // apply unique query to js modules to make the module state independent of the other runtime instances if (loaderHelpers.modulesUniqueQuery && appendQueryAssetTypes[behavior]) { attemptUrl = attemptUrl + loaderHelpers.modulesUniqueQuery; @@ -580,11 +577,11 @@ export function appendUniqueQuery(attemptUrl: string, behavior: AssetBehaviors): let resourcesLoaded = 0; const totalResources = new Set(); -function download_resource(asset: AssetEntryInternal): LoadingResource { +function download_resource (asset: AssetEntryInternal): LoadingResource { try { mono_assert(asset.resolvedUrl, "Request's resolvedUrl must be set"); const fetchResponse = download_resource_with_cache(asset); - const response = { name: asset.name, url: asset.resolvedUrl, response: fetchResponse }; + const response = {name: asset.name, url: asset.resolvedUrl, response: fetchResponse}; totalResources.add(asset.name!); response.response.then(() => { @@ -603,8 +600,12 @@ function download_resource(asset: AssetEntryInternal): LoadingResource { url: asset.resolvedUrl, status: 500, statusText: "ERR29: " + err, - arrayBuffer: () => { throw err; }, - json: () => { throw err; } + arrayBuffer: () => { + throw err; + }, + json: () => { + throw err; + } }; return { name: asset.name, url: asset.resolvedUrl!, response: Promise.resolve(response) @@ -612,7 +613,7 @@ function download_resource(asset: AssetEntryInternal): LoadingResource { } } -async function download_resource_with_cache(asset: AssetEntryInternal): Promise { +async function download_resource_with_cache (asset: AssetEntryInternal): Promise { let response = await findCachedResponse(asset); if (!response) { response = await fetchResource(asset); @@ -622,7 +623,7 @@ async function download_resource_with_cache(asset: AssetEntryInternal): Promise< return response; } -function fetchResource(asset: AssetEntryInternal): Promise { +function fetchResource (asset: AssetEntryInternal): Promise { // Allow developers to override how the resource is loaded let url = asset.resolvedUrl!; if (loaderHelpers.loadBootResource) { @@ -646,7 +647,7 @@ function fetchResource(asset: AssetEntryInternal): Promise { // Include credentials so the server can allow download / provide user specific file fetchOptions.credentials = "include"; } else { - // `disableIntegrityCheck` is to give developers an easy opt-out from the integrity check + // `disableIntegrityCheck` is to give developers an easy opt-out from the integrity check if (!loaderHelpers.config.disableIntegrityCheck && asset.hash) { // Any other resource than configuration should provide integrity check fetchOptions.integrity = asset.hash; @@ -670,7 +671,7 @@ const monoToBlazorAssetTypeMap: { [key: string]: WebAssemblyBootResourceType | u "js-module-threads": "dotnetjs" }; -function invokeLoadBootResource(asset: AssetEntryInternal): string | Promise | null | undefined { +function invokeLoadBootResource (asset: AssetEntryInternal): string | Promise | null | undefined { if (loaderHelpers.loadBootResource) { const requestHash = asset.hash ?? ""; const url = asset.resolvedUrl!; @@ -688,7 +689,7 @@ function invokeLoadBootResource(asset: AssetEntryInternal): string | Promise= 0) { lastIndexOfSlash++; @@ -704,7 +705,7 @@ function fileName(name: string) { return name.substring(lastIndexOfSlash); } -export async function streamingCompileWasm() { +export async function streamingCompileWasm () { try { const wasmModuleAsset = resolve_single_asset_path("dotnetwasm"); await start_asset_download(wasmModuleAsset); @@ -732,12 +733,11 @@ export async function streamingCompileWasm() { wasmModuleAsset.buffer = null as any; // GC wasmModuleAsset.moduleExports = null as any; // GC loaderHelpers.wasmCompilePromise.promise_control.resolve(compiledModule); - } - catch (err) { + } catch (err) { loaderHelpers.wasmCompilePromise.promise_control.reject(err); } } -export function preloadWorkers() { +export function preloadWorkers () { if (!WasmEnableThreads) return; const jsModuleWorker = resolve_single_asset_path("js-module-threads"); for (let i = 0; i < loaderHelpers.config.pthreadPoolInitialSize!; i++) { diff --git a/src/mono/browser/runtime/loader/assetsCache.ts b/src/mono/browser/runtime/loader/assetsCache.ts index ec6bf96233b5d5..182e103c28cb71 100644 --- a/src/mono/browser/runtime/loader/assetsCache.ts +++ b/src/mono/browser/runtime/loader/assetsCache.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { MonoConfig } from "../types"; -import type { AssetEntryInternal } from "../types/internal"; -import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals"; +import type {MonoConfig} from "../types"; +import type {AssetEntryInternal} from "../types/internal"; +import {ENVIRONMENT_IS_WEB, loaderHelpers} from "./globals"; const usedCacheKeys: { [key: string]: boolean } = {}; const networkLoads: { [name: string]: LoadLogEntry } = {}; const cacheLoads: { [name: string]: LoadLogEntry } = {}; let cacheIfUsed: Cache | null; -export function logDownloadStatsToConsole(): void { +export function logDownloadStatsToConsole (): void { const cacheLoadsEntries = Object.values(cacheLoads); const networkLoadsEntries = Object.values(networkLoads); const cacheResponseBytes = countTotalBytes(cacheLoadsEntries); @@ -51,7 +51,7 @@ export function logDownloadStatsToConsole(): void { console.groupEnd(); } -export async function purgeUnusedCacheEntriesAsync(): Promise { +export async function purgeUnusedCacheEntriesAsync (): Promise { // We want to keep the cache small because, even though the browser will evict entries if it // gets too big, we don't want to be considered problematic by the end user viewing storage stats const cache = cacheIfUsed; @@ -67,7 +67,7 @@ export async function purgeUnusedCacheEntriesAsync(): Promise { } } -export async function findCachedResponse(asset: AssetEntryInternal): Promise { +export async function findCachedResponse (asset: AssetEntryInternal): Promise { const cache = cacheIfUsed; if (!cache || asset.noCache || !asset.hash || asset.hash.length === 0) { return undefined; @@ -90,11 +90,11 @@ export async function findCachedResponse(asset: AssetEntryInternal): Promise { +export async function initCacheToUseIfEnabled (): Promise { cacheIfUsed = await getCacheToUseIfEnabled(loaderHelpers.config); } -async function getCacheToUseIfEnabled(config: MonoConfig): Promise { +async function getCacheToUseIfEnabled (config: MonoConfig): Promise { // caches will be undefined if we're running on an insecure origin (secure means https or localhost) if (!config.cacheBootResources || typeof globalThis.caches === "undefined" || typeof globalThis.document === "undefined") { return null; @@ -180,15 +180,15 @@ async function getCacheToUseIfEnabled(config: MonoConfig): Promise } } -function countTotalBytes(loads: LoadLogEntry[]) { +function countTotalBytes (loads: LoadLogEntry[]) { return loads.reduce((prev, item) => prev + (item.responseBytes || 0), 0); } -function toDataSizeString(byteCount: number) { +function toDataSizeString (byteCount: number) { return `${(byteCount / (1024 * 1024)).toFixed(2)} MB`; } -function getPerformanceEntry(url: string): PerformanceResourceTiming | undefined { +function getPerformanceEntry (url: string): PerformanceResourceTiming | undefined { if (typeof performance !== "undefined") { return performance.getEntriesByName(url)[0] as PerformanceResourceTiming; } diff --git a/src/mono/browser/runtime/loader/config.ts b/src/mono/browser/runtime/loader/config.ts index 07b7750a2a2c65..8960bf2d48742b 100644 --- a/src/mono/browser/runtime/loader/config.ts +++ b/src/mono/browser/runtime/loader/config.ts @@ -4,22 +4,22 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import { MainThreadingMode, type DotnetModuleInternal, type MonoConfigInternal, JSThreadBlockingMode, JSThreadInteropMode } from "../types/internal"; -import type { DotnetModuleConfig, MonoConfig, ResourceGroups, ResourceList } from "../types"; -import { exportedRuntimeAPI, loaderHelpers, runtimeHelpers } from "./globals"; -import { mono_log_error, mono_log_debug } from "./logging"; -import { importLibraryInitializers, invokeLibraryInitializers } from "./libraryInitializers"; -import { mono_exit } from "./exit"; -import { makeURLAbsoluteWithApplicationBase } from "./polyfills"; -import { appendUniqueQuery } from "./assets"; -import { mono_log_warn } from "./logging"; - -export function deep_merge_config(target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { +import {MainThreadingMode, type DotnetModuleInternal, type MonoConfigInternal, JSThreadBlockingMode, JSThreadInteropMode} from "../types/internal"; +import type {DotnetModuleConfig, MonoConfig, ResourceGroups, ResourceList} from "../types"; +import {exportedRuntimeAPI, loaderHelpers, runtimeHelpers} from "./globals"; +import {mono_log_error, mono_log_debug} from "./logging"; +import {importLibraryInitializers, invokeLibraryInitializers} from "./libraryInitializers"; +import {mono_exit} from "./exit"; +import {makeURLAbsoluteWithApplicationBase} from "./polyfills"; +import {appendUniqueQuery} from "./assets"; +import {mono_log_warn} from "./logging"; + +export function deep_merge_config (target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { // no need to merge the same object if (target === source) return target; // If source has collection fields set to null (produced by boot config for example), we should maintain the target values - const providedConfig: MonoConfigInternal = { ...source }; + const providedConfig: MonoConfigInternal = {...source}; if (providedConfig.assets !== undefined && providedConfig.assets !== target.assets) { providedConfig.assets = [...(target.assets || []), ...(providedConfig.assets || [])]; } @@ -32,7 +32,7 @@ export function deep_merge_config(target: MonoConfigInternal, source: MonoConfig }, providedConfig.resources); } if (providedConfig.environmentVariables !== undefined) { - providedConfig.environmentVariables = { ...(target.environmentVariables || {}), ...(providedConfig.environmentVariables || {}) }; + providedConfig.environmentVariables = {...(target.environmentVariables || {}), ...(providedConfig.environmentVariables || {})}; } if (providedConfig.runtimeOptions !== undefined && providedConfig.runtimeOptions !== target.runtimeOptions) { providedConfig.runtimeOptions = [...(target.runtimeOptions || []), ...(providedConfig.runtimeOptions || [])]; @@ -40,11 +40,11 @@ export function deep_merge_config(target: MonoConfigInternal, source: MonoConfig return Object.assign(target, providedConfig); } -export function deep_merge_module(target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { +export function deep_merge_module (target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { // no need to merge the same object if (target === source) return target; - const providedConfig: DotnetModuleConfig = { ...source }; + const providedConfig: DotnetModuleConfig = {...source}; if (providedConfig.config) { if (!target.config) target.config = {}; providedConfig.config = deep_merge_config(target.config, providedConfig.config); @@ -52,49 +52,49 @@ export function deep_merge_module(target: DotnetModuleInternal, source: DotnetMo return Object.assign(target, providedConfig); } -function deep_merge_resources(target: ResourceGroups, source: ResourceGroups): ResourceGroups { +function deep_merge_resources (target: ResourceGroups, source: ResourceGroups): ResourceGroups { // no need to merge the same object if (target === source) return target; - const providedResources: ResourceGroups = { ...source }; + const providedResources: ResourceGroups = {...source}; if (providedResources.assembly !== undefined) { - providedResources.assembly = { ...(target.assembly || {}), ...(providedResources.assembly || {}) }; + providedResources.assembly = {...(target.assembly || {}), ...(providedResources.assembly || {})}; } if (providedResources.lazyAssembly !== undefined) { - providedResources.lazyAssembly = { ...(target.lazyAssembly || {}), ...(providedResources.lazyAssembly || {}) }; + providedResources.lazyAssembly = {...(target.lazyAssembly || {}), ...(providedResources.lazyAssembly || {})}; } if (providedResources.pdb !== undefined) { - providedResources.pdb = { ...(target.pdb || {}), ...(providedResources.pdb || {}) }; + providedResources.pdb = {...(target.pdb || {}), ...(providedResources.pdb || {})}; } if (providedResources.jsModuleWorker !== undefined) { - providedResources.jsModuleWorker = { ...(target.jsModuleWorker || {}), ...(providedResources.jsModuleWorker || {}) }; + providedResources.jsModuleWorker = {...(target.jsModuleWorker || {}), ...(providedResources.jsModuleWorker || {})}; } if (providedResources.jsModuleNative !== undefined) { - providedResources.jsModuleNative = { ...(target.jsModuleNative || {}), ...(providedResources.jsModuleNative || {}) }; + providedResources.jsModuleNative = {...(target.jsModuleNative || {}), ...(providedResources.jsModuleNative || {})}; } if (providedResources.jsModuleRuntime !== undefined) { - providedResources.jsModuleRuntime = { ...(target.jsModuleRuntime || {}), ...(providedResources.jsModuleRuntime || {}) }; + providedResources.jsModuleRuntime = {...(target.jsModuleRuntime || {}), ...(providedResources.jsModuleRuntime || {})}; } if (providedResources.wasmSymbols !== undefined) { - providedResources.wasmSymbols = { ...(target.wasmSymbols || {}), ...(providedResources.wasmSymbols || {}) }; + providedResources.wasmSymbols = {...(target.wasmSymbols || {}), ...(providedResources.wasmSymbols || {})}; } if (providedResources.wasmNative !== undefined) { - providedResources.wasmNative = { ...(target.wasmNative || {}), ...(providedResources.wasmNative || {}) }; + providedResources.wasmNative = {...(target.wasmNative || {}), ...(providedResources.wasmNative || {})}; } if (providedResources.icu !== undefined) { - providedResources.icu = { ...(target.icu || {}), ...(providedResources.icu || {}) }; + providedResources.icu = {...(target.icu || {}), ...(providedResources.icu || {})}; } if (providedResources.satelliteResources !== undefined) { providedResources.satelliteResources = deep_merge_dict(target.satelliteResources || {}, providedResources.satelliteResources || {}); } if (providedResources.modulesAfterConfigLoaded !== undefined) { - providedResources.modulesAfterConfigLoaded = { ...(target.modulesAfterConfigLoaded || {}), ...(providedResources.modulesAfterConfigLoaded || {}) }; + providedResources.modulesAfterConfigLoaded = {...(target.modulesAfterConfigLoaded || {}), ...(providedResources.modulesAfterConfigLoaded || {})}; } if (providedResources.modulesAfterRuntimeReady !== undefined) { - providedResources.modulesAfterRuntimeReady = { ...(target.modulesAfterRuntimeReady || {}), ...(providedResources.modulesAfterRuntimeReady || {}) }; + providedResources.modulesAfterRuntimeReady = {...(target.modulesAfterRuntimeReady || {}), ...(providedResources.modulesAfterRuntimeReady || {})}; } if (providedResources.extensions !== undefined) { - providedResources.extensions = { ...(target.extensions || {}), ...(providedResources.extensions || {}) }; + providedResources.extensions = {...(target.extensions || {}), ...(providedResources.extensions || {})}; } if (providedResources.vfs !== undefined) { providedResources.vfs = deep_merge_dict(target.vfs || {}, providedResources.vfs || {}); @@ -102,18 +102,18 @@ function deep_merge_resources(target: ResourceGroups, source: ResourceGroups): R return Object.assign(target, providedResources); } -function deep_merge_dict(target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { +function deep_merge_dict (target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { // no need to merge the same object if (target === source) return target; for (const key in source) { - target[key] = { ...target[key], ...source[key] }; + target[key] = {...target[key], ...source[key]}; } return target; } // NOTE: this is called before setRuntimeGlobals -export function normalizeConfig() { +export function normalizeConfig () { // normalize const config = loaderHelpers.config; @@ -213,14 +213,12 @@ export function normalizeConfig() { && config.jsThreadInteropMode == JSThreadInteropMode.SimpleSynchronousJSInterop ) { validModes = true; - } - else if (config.mainThreadingMode == MainThreadingMode.DeputyAndIOThreads + } else if (config.mainThreadingMode == MainThreadingMode.DeputyAndIOThreads && config.jsThreadBlockingMode == JSThreadBlockingMode.AllowBlockingWaitInAsyncCode && config.jsThreadInteropMode == JSThreadInteropMode.SimpleSynchronousJSInterop ) { validModes = true; - } - else if (config.mainThreadingMode == MainThreadingMode.DeputyThread + } else if (config.mainThreadingMode == MainThreadingMode.DeputyThread && config.jsThreadBlockingMode == JSThreadBlockingMode.AllowBlockingWait && config.jsThreadInteropMode == JSThreadInteropMode.SimpleSynchronousJSInterop ) { @@ -261,7 +259,7 @@ export function normalizeConfig() { } let configLoaded = false; -export async function mono_wasm_load_config(module: DotnetModuleInternal): Promise { +export async function mono_wasm_load_config (module: DotnetModuleInternal): Promise { const configFilePath = module.configSrc; if (configLoaded) { await loaderHelpers.afterConfigLoaded.promise; @@ -284,8 +282,7 @@ export async function mono_wasm_load_config(module: DotnetModuleInternal): Promi try { await module.onConfigLoaded(loaderHelpers.config, exportedRuntimeAPI); normalizeConfig(); - } - catch (err: any) { + } catch (err: any) { mono_log_error("onConfigLoaded() failed", err); throw err; } @@ -294,13 +291,13 @@ export async function mono_wasm_load_config(module: DotnetModuleInternal): Promi normalizeConfig(); } catch (err) { const errMessage = `Failed to load config file ${configFilePath} ${err} ${(err as Error)?.stack}`; - loaderHelpers.config = module.config = Object.assign(loaderHelpers.config, { message: errMessage, error: err, isError: true }); + loaderHelpers.config = module.config = Object.assign(loaderHelpers.config, {message: errMessage, error: err, isError: true}); mono_exit(1, new Error(errMessage)); throw err; } } -export function isDebuggingSupported(): boolean { +export function isDebuggingSupported (): boolean { // Copied from blazor MonoDebugger.ts/attachDebuggerHotkey if (!globalThis.navigator) { return false; @@ -309,7 +306,7 @@ export function isDebuggingSupported(): boolean { return loaderHelpers.isChromium || loaderHelpers.isFirefox; } -async function loadBootConfig(module: DotnetModuleInternal): Promise { +async function loadBootConfig (module: DotnetModuleInternal): Promise { const defaultConfigSrc = loaderHelpers.locateFile(module.configSrc!); const loaderResponse = loaderHelpers.loadBootResource !== undefined ? @@ -329,7 +326,7 @@ async function loadBootConfig(module: DotnetModuleInternal): Promise { const loadedConfig: MonoConfig = await readBootConfigResponse(loadConfigResponse); deep_merge_config(loaderHelpers.config, loadedConfig); - function defaultLoadBootConfig(url: string): Promise { + function defaultLoadBootConfig (url: string): Promise { return loaderHelpers.fetch_like(url, { method: "GET", credentials: "include", @@ -338,7 +335,7 @@ async function loadBootConfig(module: DotnetModuleInternal): Promise { } } -async function readBootConfigResponse(loadConfigResponse: Response): Promise { +async function readBootConfigResponse (loadConfigResponse: Response): Promise { const config = loaderHelpers.config; const loadedConfig: MonoConfig = await loadConfigResponse.json(); @@ -362,4 +359,4 @@ async function readBootConfigResponse(loadConfigResponse: Response): Promise `.NET runtime already exited with ${loaderHelpers.exitCode} ${loaderHelpers.exitReason}. You can use runtime.runMain() which doesn't exit the runtime.`); if (WasmEnableThreads && ENVIRONMENT_IS_WORKER) { mono_assert(runtimeHelpers.runtimeReady, "The WebWorker is not attached to the runtime. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -24,7 +24,7 @@ export function assert_runtime_running() { } -export function installUnhandledErrorHandler() { +export function installUnhandledErrorHandler () { // it seems that emscripten already does the right thing for NodeJs and that there is no good solution for V8 shell. if (ENVIRONMENT_IS_WEB) { globalThis.addEventListener("unhandledrejection", unhandledrejection_handler); @@ -32,14 +32,14 @@ export function installUnhandledErrorHandler() { } } -export function uninstallUnhandledErrorHandler() { +export function uninstallUnhandledErrorHandler () { if (ENVIRONMENT_IS_WEB) { globalThis.removeEventListener("unhandledrejection", unhandledrejection_handler); globalThis.removeEventListener("error", error_handler); } } -export function registerEmscriptenExitHandlers() { +export function registerEmscriptenExitHandlers () { if (!emscriptenModule.onAbort) { emscriptenModule.onAbort = onAbort; } @@ -48,7 +48,7 @@ export function registerEmscriptenExitHandlers() { } } -function unregisterEmscriptenExitHandlers() { +function unregisterEmscriptenExitHandlers () { if (emscriptenModule.onAbort == onAbort) { emscriptenModule.onAbort = undefined; } @@ -56,16 +56,16 @@ function unregisterEmscriptenExitHandlers() { emscriptenModule.onExit = undefined; } } -function onExit(code: number) { +function onExit (code: number) { mono_exit(code, loaderHelpers.exitReason); } -function onAbort(reason: any) { +function onAbort (reason: any) { mono_exit(1, loaderHelpers.exitReason || reason); } // this will also call mono_wasm_exit if available, which will call exitJS -> _proc_exit -> terminateAllThreads -export function mono_exit(exit_code: number, reason?: any): void { +export function mono_exit (exit_code: number, reason?: any): void { unregisterEmscriptenExitHandlers(); uninstallUnhandledErrorHandler(); @@ -113,8 +113,7 @@ export function mono_exit(exit_code: number, reason?: any): void { runtimeHelpers.dumpThreads(); } } - } - catch (err) { + } catch (err) { mono_log_warn("mono_exit failed", err); // don't propagate any failures } @@ -122,8 +121,7 @@ export function mono_exit(exit_code: number, reason?: any): void { try { logOnExit(exit_code, reason); appendElementOnExit(exit_code); - } - catch (err) { + } catch (err) { mono_log_warn("mono_exit failed", err); // don't propagate any failures } @@ -141,8 +139,7 @@ export function mono_exit(exit_code: number, reason?: any): void { (async () => { try { await flush_node_streams(); - } - finally { + } finally { set_exit_code_and_quit_now(exit_code, reason); } })(); @@ -154,7 +151,7 @@ export function mono_exit(exit_code: number, reason?: any): void { } } -function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { +function set_exit_code_and_quit_now (exit_code: number, reason?: any): void { if (WasmEnableThreads && ENVIRONMENT_IS_WORKER && runtimeHelpers.runtimeReady && runtimeHelpers.nativeAbort) { // note that the reason is not passed to UI thread runtimeHelpers.runtimeReady = false; @@ -166,8 +163,7 @@ function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { runtimeHelpers.runtimeReady = false; try { runtimeHelpers.nativeExit(exit_code); - } - catch (error: any) { + } catch (error: any) { if (runtimeHelpers.ExitStatus && !(error instanceof runtimeHelpers.ExitStatus)) { mono_log_warn("mono_wasm_exit failed: " + error.toString()); } @@ -177,15 +173,14 @@ function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { if (exit_code !== 0 || !ENVIRONMENT_IS_WEB) { if (ENVIRONMENT_IS_NODE && INTERNAL.process) { INTERNAL.process.exit(exit_code); - } - else if (runtimeHelpers.quit) { + } else if (runtimeHelpers.quit) { runtimeHelpers.quit(exit_code, reason); } throw reason; } } -async function flush_node_streams() { +async function flush_node_streams () { try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -209,7 +204,7 @@ async function flush_node_streams() { } } -function abort_promises(reason: any) { +function abort_promises (reason: any) { loaderHelpers.exitReason = reason; loaderHelpers.allDownloadsQueued.promise_control.reject(reason); loaderHelpers.afterConfigLoaded.promise_control.reject(reason); @@ -227,7 +222,7 @@ function abort_promises(reason: any) { } } -function appendElementOnExit(exit_code: number) { +function appendElementOnExit (exit_code: number) { if (ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER && loaderHelpers.config && loaderHelpers.config.appendElementOnExit && document) { //Tell xharness WasmBrowserTestRunner what was the exit code const tests_done_elem = document.createElement("label"); @@ -238,7 +233,7 @@ function appendElementOnExit(exit_code: number) { } } -function logOnExit(exit_code: number, reason: any) { +function logOnExit (exit_code: number, reason: any) { if (exit_code !== 0 && reason) { // ExitStatus usually is not real JS error and so stack strace is not very useful. // We will use debug level for it, which will print only when diagnosticTracing is set. @@ -247,8 +242,7 @@ function logOnExit(exit_code: number, reason: any) { : mono_log_error; if (typeof reason == "string") { mono_log(reason); - } - else { + } else { if (reason.stack === undefined) { reason.stack = new Error().stack + ""; } @@ -257,8 +251,7 @@ function logOnExit(exit_code: number, reason: any) { ? runtimeHelpers.stringify_as_error_with_stack(reason.message + "\n" + reason.stack) : reason.message + "\n" + reason.stack; mono_log(message); - } - else { + } else { mono_log(JSON.stringify(reason)); } } @@ -270,21 +263,20 @@ function logOnExit(exit_code: number, reason: any) { } else { mono_log_info_no_prefix("WASM EXIT " + exit_code); } - } - else if (loaderHelpers.config.forwardConsoleLogsToWS) { + } else if (loaderHelpers.config.forwardConsoleLogsToWS) { teardown_proxy_console(); } } } -function unhandledrejection_handler(event: any) { +function unhandledrejection_handler (event: any) { fatal_handler(event, event.reason, "rejection"); } -function error_handler(event: any) { +function error_handler (event: any) { fatal_handler(event, event.error, "error"); } -function fatal_handler(event: any, reason: any, type: string) { +function fatal_handler (event: any, reason: any, type: string) { event.preventDefault(); try { if (!reason) { diff --git a/src/mono/browser/runtime/loader/globals.ts b/src/mono/browser/runtime/loader/globals.ts index 940051627f3046..f451f0da9a79f8 100644 --- a/src/mono/browser/runtime/loader/globals.ts +++ b/src/mono/browser/runtime/loader/globals.ts @@ -4,19 +4,19 @@ /* eslint-disable @typescript-eslint/triple-slash-reference */ /// -import { exceptions, simd } from "wasm-feature-detect"; +import {exceptions, simd} from "wasm-feature-detect"; import gitHash from "consts:gitHash"; -import type { DotnetModuleInternal, GlobalObjects, LoaderHelpers, MonoConfigInternal, RuntimeHelpers } from "../types/internal"; -import type { MonoConfig, RuntimeAPI } from "../types"; -import { assert_runtime_running, installUnhandledErrorHandler, 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 { mono_log_error, set_thread_prefix, setup_proxy_console } from "./logging"; -import { invokeLibraryInitializers } from "./libraryInitializers"; -import { deep_merge_config, isDebuggingSupported } from "./config"; -import { logDownloadStatsToConsole, purgeUnusedCacheEntriesAsync } from "./assetsCache"; +import type {DotnetModuleInternal, GlobalObjects, LoaderHelpers, MonoConfigInternal, RuntimeHelpers} from "../types/internal"; +import type {MonoConfig, RuntimeAPI} from "../types"; +import {assert_runtime_running, installUnhandledErrorHandler, 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 {mono_log_error, set_thread_prefix, setup_proxy_console} from "./logging"; +import {invokeLibraryInitializers} from "./libraryInitializers"; +import {deep_merge_config, isDebuggingSupported} 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 if (typeof importScripts === "function" && !globalThis.onmessage) { @@ -53,7 +53,7 @@ export const globalObjectsRoot: GlobalObjects = { setLoaderGlobals(globalObjectsRoot); -export function setLoaderGlobals( +export function setLoaderGlobals ( globalObjects: GlobalObjects, ) { if (_loaderModuleLoaded) { @@ -70,14 +70,18 @@ export function setLoaderGlobals( }); Object.assign(globalObjects.module, { - config: deep_merge_config(monoConfig, { environmentVariables: {} }), + config: deep_merge_config(monoConfig, {environmentVariables: {}}), }); const rh: Partial = { mono_wasm_bindings_is_ready: false, config: globalObjects.module.config, diagnosticTracing: false, - nativeAbort: (reason: any) => { throw reason || new Error("abort"); }, - nativeExit: (code: number) => { throw new Error("exit:" + code); } + nativeAbort: (reason: any) => { + throw reason || new Error("abort"); + }, + nativeExit: (code: number) => { + throw new Error("exit:" + code); + } }; const lh: Partial = { gitHash, @@ -133,7 +137,7 @@ export function setLoaderGlobals( // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() @@ -141,4 +145,4 @@ export function mono_assert(condition: unknown, messageFactory: string | (() => const error = new Error(message); mono_log_error(message, error); runtimeHelpers.nativeAbort(error); -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/loader/icu.ts b/src/mono/browser/runtime/loader/icu.ts index 2efc00f398eda5..7a49a38291a850 100644 --- a/src/mono/browser/runtime/loader/icu.ts +++ b/src/mono/browser/runtime/loader/icu.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { GlobalizationMode, MonoConfig } from "../types"; -import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals"; -import { mono_log_info, mono_log_debug } from "./logging"; +import {GlobalizationMode, MonoConfig} from "../types"; +import {ENVIRONMENT_IS_WEB, loaderHelpers} from "./globals"; +import {mono_log_info, mono_log_debug} from "./logging"; -export function init_globalization() { +export function init_globalization () { loaderHelpers.preferredIcuAsset = getIcuResourceName(loaderHelpers.config); let invariantMode = loaderHelpers.config.globalizationMode == GlobalizationMode.Invariant; @@ -28,8 +28,7 @@ export function init_globalization() { const env_variables = loaderHelpers.config.environmentVariables!; if (env_variables[hybridEnv] === undefined && loaderHelpers.config.globalizationMode === GlobalizationMode.Hybrid) { env_variables[hybridEnv] = "1"; - } - else if (env_variables[invariantEnv] === undefined && invariantMode) { + } else if (env_variables[invariantEnv] === undefined && invariantMode) { env_variables[invariantEnv] = "1"; } if (env_variables["TZ"] === undefined) { @@ -45,7 +44,7 @@ export function init_globalization() { } } -export function getIcuResourceName(config: MonoConfig): string | null { +export function getIcuResourceName (config: MonoConfig): string | null { if (config.resources?.icu && config.globalizationMode != GlobalizationMode.Invariant) { // 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); @@ -74,7 +73,7 @@ export function getIcuResourceName(config: MonoConfig): string | null { return null; } -function getShardedIcuResourceName(culture: string): string { +function getShardedIcuResourceName (culture: string): string { const prefix = culture.split("-")[0]; if (prefix === "en" || ["fr", "fr-FR", "it", "it-IT", "de", "de-DE", "es", "es-ES"].includes(culture)) { return "icudt_EFIGS.dat"; diff --git a/src/mono/browser/runtime/loader/index.ts b/src/mono/browser/runtime/loader/index.ts index 6818186c36a028..d319b28fdf99b0 100644 --- a/src/mono/browser/runtime/loader/index.ts +++ b/src/mono/browser/runtime/loader/index.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { DotnetHostBuilder } from "../types"; -import { mono_exit } from "./exit"; -import { verifyEnvironment } from "./polyfills"; -import { HostBuilder, createEmscripten } from "./run"; +import type {DotnetHostBuilder} from "../types"; +import {mono_exit} from "./exit"; +import {verifyEnvironment} from "./polyfills"; +import {HostBuilder, createEmscripten} from "./run"; // export external API const dotnet: DotnetHostBuilder = new HostBuilder(); @@ -13,5 +13,5 @@ const legacyEntrypoint = createEmscripten; verifyEnvironment(); -export { dotnet, exit }; +export {dotnet, exit}; export default legacyEntrypoint; diff --git a/src/mono/browser/runtime/loader/libraryInitializers.ts b/src/mono/browser/runtime/loader/libraryInitializers.ts index 216c7fe7180e0f..55d363632aa055 100644 --- a/src/mono/browser/runtime/loader/libraryInitializers.ts +++ b/src/mono/browser/runtime/loader/libraryInitializers.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_log_debug, mono_log_warn } from "./logging"; -import { appendUniqueQuery } from "./assets"; -import { loaderHelpers } from "./globals"; -import { mono_exit } from "./exit"; -import { ResourceList } from "../types"; +import {mono_log_debug, mono_log_warn} from "./logging"; +import {appendUniqueQuery} from "./assets"; +import {loaderHelpers} from "./globals"; +import {mono_exit} from "./exit"; +import {ResourceList} from "../types"; -export async function importLibraryInitializers(libraryInitializers: ResourceList | undefined): Promise { +export async function importLibraryInitializers (libraryInitializers: ResourceList | undefined): Promise { if (!libraryInitializers) { return; } @@ -15,20 +15,20 @@ export async function importLibraryInitializers(libraryInitializers: ResourceLis const initializerFiles = Object.keys(libraryInitializers); await Promise.all(initializerFiles.map(f => importInitializer(f))); - async function importInitializer(path: string): Promise { + async function importInitializer (path: string): Promise { try { const adjustedPath = appendUniqueQuery(loaderHelpers.locateFile(path), "js-module-library-initializer"); mono_log_debug(`Attempting to import '${adjustedPath}' for ${path}`); const initializer = await import(/*! webpackIgnore: true */ adjustedPath); - loaderHelpers.libraryInitializers!.push({ scriptName: path, exports: initializer }); + loaderHelpers.libraryInitializers!.push({scriptName: path, exports: initializer}); } catch (error) { mono_log_warn(`Failed to import library initializer '${path}': ${error}`); } } } -export async function invokeLibraryInitializers(functionName: string, args: any[]) { +export async function invokeLibraryInitializers (functionName: string, args: any[]) { if (!loaderHelpers.libraryInitializers) { return; } @@ -44,7 +44,7 @@ export async function invokeLibraryInitializers(functionName: string, args: any[ await Promise.all(promises); } -async function abortStartupOnError(scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { +async function abortStartupOnError (scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { try { await callback(); } catch (err) { @@ -52,4 +52,4 @@ async function abortStartupOnError(scriptName: string, methodName: string, callb mono_exit(1, err); throw err; } -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/loader/logging.ts b/src/mono/browser/runtime/loader/logging.ts index 723e55201fcc53..2940b20e3edb4f 100644 --- a/src/mono/browser/runtime/loader/logging.ts +++ b/src/mono/browser/runtime/loader/logging.ts @@ -5,7 +5,7 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { ENVIRONMENT_IS_WORKER, loaderHelpers } from "./globals"; +import {ENVIRONMENT_IS_WORKER, loaderHelpers} from "./globals"; const methods = ["debug", "log", "trace", "warn", "info", "error"]; const prefix = "MONO_WASM: "; @@ -14,29 +14,29 @@ let theConsoleApi: any; let originalConsoleMethods: any; let threadNamePrefix: string; -export function set_thread_prefix(threadPrefix: string) { +export function set_thread_prefix (threadPrefix: string) { threadNamePrefix = threadPrefix; } -export function mono_log_debug(msg: string, ...data: any[]) { +export function mono_log_debug (msg: string, ...data: any[]) { if (loaderHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info(msg: string, ...data: any) { +export function mono_log_info (msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_info_no_prefix(msg: string, ...data: any) { +export function mono_log_info_no_prefix (msg: string, ...data: any) { console.info(msg, ...data); } -export function mono_log_warn(msg: string, ...data: any) { +export function mono_log_warn (msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error(msg: string, ...data: any) { +export function mono_log_error (msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object") { // don't log silent errors if (data[0].silent) { @@ -54,7 +54,7 @@ export function mono_log_error(msg: string, ...data: any) { } let tick = ""; let last = new Date().valueOf(); -function proxyConsoleMethod(prefix: string, func: any, asJson: boolean) { +function proxyConsoleMethod (prefix: string, func: any, asJson: boolean) { return function (...args: any[]) { try { let payload = args[0]; @@ -101,7 +101,7 @@ function proxyConsoleMethod(prefix: string, func: any, asJson: boolean) { }; } -export function setup_proxy_console(id: string, console: Console, origin: string): void { +export function setup_proxy_console (id: string, console: Console, origin: string): void { theConsoleApi = console as any; threadNamePrefix = id; originalConsoleMethods = { @@ -117,14 +117,13 @@ export function setup_proxy_console(id: string, console: Console, origin: string setupWS(); } -export function teardown_proxy_console(message?: string) { +export function teardown_proxy_console (message?: string) { const stop_when_ws_buffer_empty = () => { if (!consoleWebSocket) { if (message && originalConsoleMethods) { originalConsoleMethods.log(message); } - } - else if (consoleWebSocket.bufferedAmount == 0) { + } else if (consoleWebSocket.bufferedAmount == 0) { if (message) { // tell xharness WasmTestMessagesProcessor we are done. // note this sends last few bytes into the same WS @@ -136,38 +135,36 @@ export function teardown_proxy_console(message?: string) { consoleWebSocket.removeEventListener("close", logWSClose); consoleWebSocket.close(1000, message); (consoleWebSocket as any) = undefined; - } - else { + } else { globalThis.setTimeout(stop_when_ws_buffer_empty, 100); } }; stop_when_ws_buffer_empty(); } -function send(msg: string) { +function send (msg: string) { if (consoleWebSocket && consoleWebSocket.readyState === WebSocket.OPEN) { consoleWebSocket.send(msg); - } - else { + } else { originalConsoleMethods.log(msg); } } -function logWSError(event: Event) { +function logWSError (event: Event) { originalConsoleMethods.error(`[${threadNamePrefix}] proxy console websocket error: ${event}`, event); } -function logWSClose(event: Event) { +function logWSClose (event: Event) { originalConsoleMethods.debug(`[${threadNamePrefix}] proxy console websocket closed: ${event}`, event); } -function setupWS() { +function setupWS () { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, send, true); } } -function setupOriginal() { +function setupOriginal () { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, originalConsoleMethods.log, false); } diff --git a/src/mono/browser/runtime/loader/polyfills.ts b/src/mono/browser/runtime/loader/polyfills.ts index e60fb2111b8f5f..c355b2155a8440 100644 --- a/src/mono/browser/runtime/loader/polyfills.ts +++ b/src/mono/browser/runtime/loader/polyfills.ts @@ -3,22 +3,22 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import type { DotnetModuleInternal } from "../types/internal"; -import { INTERNAL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, loaderHelpers, ENVIRONMENT_IS_WEB, mono_assert } from "./globals"; +import type {DotnetModuleInternal} from "../types/internal"; +import {INTERNAL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, loaderHelpers, ENVIRONMENT_IS_WEB, mono_assert} from "./globals"; let node_fs: any | undefined = undefined; let node_url: any | undefined = undefined; const URLPolyfill = class URL { private url; - constructor(url: string) { + constructor (url: string) { this.url = url; } - toString() { + toString () { return this.url; } }; -export function verifyEnvironment() { +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. 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 (WasmEnableThreads) { @@ -28,7 +28,7 @@ export function verifyEnvironment() { } } -export async function detect_features_and_polyfill(module: DotnetModuleInternal): Promise { +export async function detect_features_and_polyfill (module: DotnetModuleInternal): Promise { if (ENVIRONMENT_IS_NODE) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -39,7 +39,7 @@ export async function detect_features_and_polyfill(module: DotnetModuleInternal) } } - const scriptUrlQuery =/*! webpackIgnore: true */import.meta.url; + const scriptUrlQuery = /*! webpackIgnore: true */import.meta.url; const queryIndex = scriptUrlQuery.indexOf("?"); if (queryIndex > 0) { loaderHelpers.modulesUniqueQuery = scriptUrlQuery.substring(queryIndex); @@ -66,8 +66,7 @@ export async function detect_features_and_polyfill(module: DotnetModuleInternal) const brands = navigator.userAgentData && navigator.userAgentData.brands; if (brands && brands.length > 0) { loaderHelpers.isChromium = brands.some((b: any) => b.brand === "Google Chrome" || b.brand === "Microsoft Edge" || b.brand === "Chromium"); - } - else if (navigator.userAgent) { + } else if (navigator.userAgent) { loaderHelpers.isChromium = navigator.userAgent.includes("Chrome"); loaderHelpers.isFirefox = navigator.userAgent.includes("Firefox"); } @@ -78,7 +77,9 @@ export async function detect_features_and_polyfill(module: DotnetModuleInternal) // @ts-ignore: INTERNAL.require = await import(/*! webpackIgnore: true */"module").then(mod => mod.createRequire(/*! webpackIgnore: true */import.meta.url)); } else { - INTERNAL.require = Promise.resolve(() => { throw new Error("require not supported"); }); + INTERNAL.require = Promise.resolve(() => { + throw new Error("require not supported"); + }); } if (typeof globalThis.URL === "undefined") { @@ -86,14 +87,14 @@ export async function detect_features_and_polyfill(module: DotnetModuleInternal) } } -export async function fetch_like(url: string, init?: RequestInit): Promise { +export async function fetch_like (url: string, init?: RequestInit): Promise { try { // this need to be detected only after we import node modules in onConfigLoaded const hasFetch = typeof (globalThis.fetch) === "function"; if (ENVIRONMENT_IS_NODE) { const isFileUrl = url.startsWith("file://"); if (!isFileUrl && hasFetch) { - return globalThis.fetch(url, init || { credentials: "same-origin" }); + return globalThis.fetch(url, init || {credentials: "same-origin"}); } if (!node_fs) { node_url = INTERNAL.require("url"); @@ -113,13 +114,13 @@ export async function fetch_like(url: string, init?: RequestInit): Promise arrayBuffer, json: () => JSON.parse(arrayBuffer), - text: () => { throw new Error("NotImplementedException"); } + text: () => { + throw new Error("NotImplementedException"); + } }; - } - else if (hasFetch) { - return globalThis.fetch(url, init || { credentials: "same-origin" }); - } - else if (typeof (read) === "function") { + } else if (hasFetch) { + return globalThis.fetch(url, init || {credentials: "same-origin"}); + } else if (typeof (read) === "function") { // note that it can't open files with unicode names, like Strae.xml // https://bugs.chromium.org/p/v8/issues/detail?id=12541 return { @@ -138,8 +139,7 @@ export async function fetch_like(url: string, init?: RequestInit): Promise read(url, "utf8") }; } - } - catch (e: any) { + } catch (e: any) { return { ok: false, url, @@ -149,19 +149,25 @@ export async function fetch_like(url: string, init?: RequestInit): Promise null }, statusText: "ERR28: " + e, - arrayBuffer: () => { throw e; }, - json: () => { throw e; }, - text: () => { throw e; } + arrayBuffer: () => { + throw e; + }, + json: () => { + throw e; + }, + text: () => { + throw e; + } }; } throw new Error("No fetch implementation available"); } -// context: the loadBootResource extension point can return URL/string which is unqualified. +// context: the loadBootResource extension point can return URL/string which is unqualified. // For example `xxx/a.js` and we have to make it absolute // For compatibility reasons, it's based of document.baseURI even for JS modules like `./xxx/a.js`, which normally use script directory of a caller of `import` // Script directory in general doesn't match document.baseURI -export function makeURLAbsoluteWithApplicationBase(url: string) { +export function makeURLAbsoluteWithApplicationBase (url: string) { mono_assert(typeof url === "string", "url must be a string"); if (!isPathAbsolute(url) && url.indexOf("./") !== 0 && url.indexOf("../") !== 0 && globalThis.URL && globalThis.document && globalThis.document.baseURI) { url = (new URL(url, globalThis.document.baseURI)).toString(); @@ -169,19 +175,19 @@ export function makeURLAbsoluteWithApplicationBase(url: string) { return url; } -function normalizeFileUrl(filename: string) { +function normalizeFileUrl (filename: string) { // unix vs windows // remove query string return filename.replace(/\\/g, "/").replace(/[?#].*/, ""); } -function normalizeDirectoryUrl(dir: string) { +function normalizeDirectoryUrl (dir: string) { return dir.slice(0, dir.lastIndexOf("/")) + "/"; } const protocolRx = /^[a-zA-Z][a-zA-Z\d+\-.]*?:\/\//; const windowsAbsoluteRx = /[a-zA-Z]:[\\/]/; -function isPathAbsolute(path: string): boolean { +function isPathAbsolute (path: string): boolean { if (ENVIRONMENT_IS_NODE || ENVIRONMENT_IS_SHELL) { // unix /x.json // windows \x.json diff --git a/src/mono/browser/runtime/loader/promise-controller.ts b/src/mono/browser/runtime/loader/promise-controller.ts index b27c8216f4fc37..86035b9b2ad635 100644 --- a/src/mono/browser/runtime/loader/promise-controller.ts +++ b/src/mono/browser/runtime/loader/promise-controller.ts @@ -1,15 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { ControllablePromise, PromiseAndController, PromiseController } from "../types/internal"; -import { mono_assert } from "./globals"; +import type {ControllablePromise, PromiseAndController, PromiseController} from "../types/internal"; +import {mono_assert} from "./globals"; /// a unique symbol used to mark a promise as controllable export const promise_control_symbol = Symbol.for("wasm promise_control"); /// Creates a new promise together with a controller that can be used to resolve or reject that promise. /// Optionally takes callbacks to be called immediately after a promise is resolved or rejected. -export function createPromiseController(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { let promise_control: PromiseController = null as unknown as PromiseController; const promise = new Promise(function (resolve, reject) { promise_control = { @@ -38,18 +38,18 @@ export function createPromiseController(afterResolve?: () => void, afterRejec (promise_control).promise = promise; const controllablePromise = promise as ControllablePromise; (controllablePromise as any)[promise_control_symbol] = promise_control; - return { promise: controllablePromise, promise_control: promise_control }; + return {promise: controllablePromise, promise_control: promise_control}; } export function getPromiseController(promise: ControllablePromise): PromiseController; -export function getPromiseController(promise: Promise): PromiseController | undefined { +export function getPromiseController (promise: Promise): PromiseController | undefined { return (promise as any)[promise_control_symbol]; } -export function isControllablePromise(promise: Promise): promise is ControllablePromise { +export function isControllablePromise (promise: Promise): promise is ControllablePromise { return (promise as any)[promise_control_symbol] !== undefined; } -export function assertIsControllablePromise(promise: Promise): asserts promise is ControllablePromise { +export function assertIsControllablePromise (promise: Promise): asserts promise is ControllablePromise { mono_assert(promise && isControllablePromise(promise), "Promise is not controllable"); } diff --git a/src/mono/browser/runtime/loader/run.ts b/src/mono/browser/runtime/loader/run.ts index e0c9bd3cded56f..6f3167d713ac9e 100644 --- a/src/mono/browser/runtime/loader/run.ts +++ b/src/mono/browser/runtime/loader/run.ts @@ -3,27 +3,27 @@ import BuildConfiguration from "consts:configuration"; -import type { MonoConfig, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, LoadBootResourceCallback } from "../types"; -import type { EmscriptenModuleInternal, RuntimeModuleExportsInternal, NativeModuleExportsInternal, } from "../types/internal"; - -import { ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, emscriptenModule, exportedRuntimeAPI, globalObjectsRoot, monoConfig, mono_assert } from "./globals"; -import { deep_merge_config, deep_merge_module, mono_wasm_load_config } from "./config"; -import { installUnhandledErrorHandler, mono_exit, registerEmscriptenExitHandlers } from "./exit"; -import { setup_proxy_console, mono_log_info, mono_log_debug } from "./logging"; -import { mono_download_assets, preloadWorkers, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm } from "./assets"; -import { detect_features_and_polyfill } from "./polyfills"; -import { runtimeHelpers, loaderHelpers } from "./globals"; -import { init_globalization } from "./icu"; -import { setupPreloadChannelToMainThread } from "./worker"; -import { importLibraryInitializers, invokeLibraryInitializers } from "./libraryInitializers"; -import { initCacheToUseIfEnabled } from "./assetsCache"; +import type {MonoConfig, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, LoadBootResourceCallback} from "../types"; +import type {EmscriptenModuleInternal, RuntimeModuleExportsInternal, NativeModuleExportsInternal,} from "../types/internal"; + +import {ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, emscriptenModule, exportedRuntimeAPI, globalObjectsRoot, monoConfig, mono_assert} from "./globals"; +import {deep_merge_config, deep_merge_module, mono_wasm_load_config} from "./config"; +import {installUnhandledErrorHandler, mono_exit, registerEmscriptenExitHandlers} from "./exit"; +import {setup_proxy_console, mono_log_info, mono_log_debug} from "./logging"; +import {mono_download_assets, preloadWorkers, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm} from "./assets"; +import {detect_features_and_polyfill} from "./polyfills"; +import {runtimeHelpers, loaderHelpers} from "./globals"; +import {init_globalization} from "./icu"; +import {setupPreloadChannelToMainThread} from "./worker"; +import {importLibraryInitializers, invokeLibraryInitializers} from "./libraryInitializers"; +import {initCacheToUseIfEnabled} from "./assetsCache"; export class HostBuilder implements DotnetHostBuilder { private instance?: RuntimeAPI; // internal - withModuleConfig(moduleConfig: DotnetModuleConfig): DotnetHostBuilder { + withModuleConfig (moduleConfig: DotnetModuleConfig): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, moduleConfig); return this; @@ -34,7 +34,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withOnConfigLoaded(onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { + withOnConfigLoaded (onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, { onConfigLoaded @@ -47,7 +47,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withConsoleForwarding(): DotnetHostBuilder { + withConsoleForwarding (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { forwardConsoleLogsToWS: true @@ -60,7 +60,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitOnUnhandledError(): DotnetHostBuilder { + withExitOnUnhandledError (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { exitOnUnhandledError: true @@ -74,7 +74,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withAsyncFlushOnExit(): DotnetHostBuilder { + withAsyncFlushOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { asyncFlushOnExit: true @@ -87,7 +87,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitCodeLogging(): DotnetHostBuilder { + withExitCodeLogging (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { logExitCode: true @@ -100,7 +100,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withElementOnExit(): DotnetHostBuilder { + withElementOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { appendElementOnExit: true @@ -113,7 +113,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withInteropCleanupOnExit(): DotnetHostBuilder { + withInteropCleanupOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interopCleanupOnExit: true @@ -126,7 +126,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withDumpThreadsOnNonZeroExit(): DotnetHostBuilder { + withDumpThreadsOnNonZeroExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { dumpThreadsOnNonZeroExit: true @@ -140,7 +140,7 @@ export class HostBuilder implements DotnetHostBuilder { // internal // todo fallback later by debugLevel - withWaitingForDebugger(level: number): DotnetHostBuilder { + withWaitingForDebugger (level: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { waitForDebugger: level @@ -152,7 +152,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withInterpreterPgo(value: boolean, autoSaveDelay?: number): DotnetHostBuilder { + withInterpreterPgo (value: boolean, autoSaveDelay?: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interpreterPgo: value, @@ -165,7 +165,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfig(config: MonoConfig): DotnetHostBuilder { + withConfig (config: MonoConfig): DotnetHostBuilder { try { deep_merge_config(monoConfig, config); return this; @@ -175,10 +175,10 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfigSrc(configSrc: string): DotnetHostBuilder { + withConfigSrc (configSrc: string): DotnetHostBuilder { try { mono_assert(configSrc && typeof configSrc === "string", "must be file path or URL"); - deep_merge_module(emscriptenModule, { configSrc }); + deep_merge_module(emscriptenModule, {configSrc}); return this; } catch (err) { mono_exit(1, err); @@ -186,7 +186,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withVirtualWorkingDirectory(vfsPath: string): DotnetHostBuilder { + withVirtualWorkingDirectory (vfsPath: string): DotnetHostBuilder { try { mono_assert(vfsPath && typeof vfsPath === "string", "must be directory path"); deep_merge_config(monoConfig, { @@ -199,7 +199,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariable(name: string, value: string): DotnetHostBuilder { + withEnvironmentVariable (name: string, value: string): DotnetHostBuilder { try { const environmentVariables: { [key: string]: string } = {}; environmentVariables[name] = value; @@ -213,7 +213,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariables(variables: { [i: string]: string; }): DotnetHostBuilder { + withEnvironmentVariables (variables: { [i: string]: string; }): DotnetHostBuilder { try { mono_assert(variables && typeof variables === "object", "must be dictionary object"); deep_merge_config(monoConfig, { @@ -226,7 +226,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDiagnosticTracing(enabled: boolean): DotnetHostBuilder { + withDiagnosticTracing (enabled: boolean): DotnetHostBuilder { try { mono_assert(typeof enabled === "boolean", "must be boolean"); deep_merge_config(monoConfig, { @@ -239,7 +239,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDebugging(level: number): DotnetHostBuilder { + withDebugging (level: number): DotnetHostBuilder { try { mono_assert(level !== undefined && level !== null && typeof level === "number", "must be number"); deep_merge_config(monoConfig, { @@ -252,7 +252,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArguments(...args: string[]): DotnetHostBuilder { + withApplicationArguments (...args: string[]): DotnetHostBuilder { try { mono_assert(args && Array.isArray(args), "must be array of strings"); deep_merge_config(monoConfig, { @@ -265,7 +265,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withRuntimeOptions(runtimeOptions: string[]): DotnetHostBuilder { + withRuntimeOptions (runtimeOptions: string[]): DotnetHostBuilder { try { mono_assert(runtimeOptions && Array.isArray(runtimeOptions), "must be array of strings"); deep_merge_config(monoConfig, { @@ -278,7 +278,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withMainAssembly(mainAssemblyName: string): DotnetHostBuilder { + withMainAssembly (mainAssemblyName: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { mainAssemblyName @@ -290,7 +290,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArgumentsFromQuery(): DotnetHostBuilder { + withApplicationArgumentsFromQuery (): DotnetHostBuilder { try { if (!globalThis.window) { throw new Error("Missing window to the query parameters from"); @@ -309,7 +309,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationEnvironment(applicationEnvironment?: string): DotnetHostBuilder { + withApplicationEnvironment (applicationEnvironment?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationEnvironment, @@ -321,7 +321,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationCulture(applicationCulture?: string): DotnetHostBuilder { + withApplicationCulture (applicationCulture?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationCulture, @@ -333,7 +333,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withResourceLoader(loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { + withResourceLoader (loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { try { loaderHelpers.loadBootResource = loadBootResource; return this; @@ -343,7 +343,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async create(): Promise { + async create (): Promise { try { if (!this.instance) { this.instance = await createApi(); @@ -355,7 +355,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async run(): Promise { + async run (): Promise { try { mono_assert(emscriptenModule.config, "Null moduleConfig.config"); if (!this.instance) { @@ -369,7 +369,7 @@ export class HostBuilder implements DotnetHostBuilder { } } -export async function createApi(): Promise { +export async function createApi (): Promise { if (ENVIRONMENT_IS_WEB && loaderHelpers.config.forwardConsoleLogsToWS && typeof globalThis.WebSocket != "undefined") { setup_proxy_console("main", globalThis.console, globalThis.location.origin); } @@ -379,7 +379,7 @@ export async function createApi(): Promise { return globalObjectsRoot.api; } -export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { +export async function createEmscripten (moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { // extract ModuleConfig if (typeof moduleFactory === "function") { const extension = moduleFactory(globalObjectsRoot.api) as any; @@ -388,11 +388,9 @@ export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api } Object.assign(emscriptenModule, extension); deep_merge_module(emscriptenModule, extension); - } - else if (typeof moduleFactory === "object") { + } else if (typeof moduleFactory === "object") { deep_merge_module(emscriptenModule, moduleFactory); - } - else { + } else { throw new Error("Can't use moduleFactory callback of createDotnetRuntime function."); } @@ -410,7 +408,7 @@ export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api } // in the future we can use feature detection to load different flavors -function importModules() { +function importModules () { const jsModuleRuntimeAsset = resolve_single_asset_path("js-module-runtime"); const jsModuleNativeAsset = resolve_single_asset_path("js-module-native"); @@ -434,9 +432,9 @@ function importModules() { return [jsModuleRuntimePromise, jsModuleNativePromise]; } -async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { - const { initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals } = es6Modules[0]; - const { default: emscriptenFactory } = es6Modules[1]; +async function initializeModules (es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { + const {initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals} = es6Modules[0]; + const {default: emscriptenFactory} = es6Modules[1]; setRuntimeGlobals(globalObjectsRoot); initializeExports(globalObjectsRoot); await configureRuntimeStartup(); @@ -454,7 +452,7 @@ async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, Nati }); } -async function createEmscriptenMain(): Promise { +async function createEmscriptenMain (): Promise { if (!emscriptenModule.configSrc && (!loaderHelpers.config || Object.keys(loaderHelpers.config).length === 0 || (!loaderHelpers.config.assets && !loaderHelpers.config.resources))) { // if config file location nor assets are provided emscriptenModule.configSrc = "./blazor.boot.json"; @@ -476,8 +474,7 @@ async function createEmscriptenMain(): Promise { init_globalization(); preloadWorkers(); await mono_download_assets(); - } - catch (err) { + } catch (err) { mono_exit(1, err); } }, 0); @@ -494,7 +491,7 @@ async function createEmscriptenMain(): Promise { return exportedRuntimeAPI; } -async function createEmscriptenWorker(): Promise { +async function createEmscriptenWorker (): Promise { setupPreloadChannelToMainThread(); await loaderHelpers.afterConfigLoaded.promise; @@ -505,8 +502,7 @@ async function createEmscriptenWorker(): Promise { try { // load subset which is on JS heap rather than in WASM linear memory await mono_download_assets(); - } - catch (err) { + } catch (err) { mono_exit(1, err); } }, 0); diff --git a/src/mono/browser/runtime/loader/worker.ts b/src/mono/browser/runtime/loader/worker.ts index baeeaf0165f673..cb4fdaead86fbd 100644 --- a/src/mono/browser/runtime/loader/worker.ts +++ b/src/mono/browser/runtime/loader/worker.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { MonoConfigInternal, PThreadInfo, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal"; -import { MonoConfig } from "../types"; -import { deep_merge_config, normalizeConfig } from "./config"; -import { ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers } from "./globals"; -import { mono_log_debug } from "./logging"; +import {MonoConfigInternal, PThreadInfo, WorkerToMainMessageType, monoMessageSymbol} from "../types/internal"; +import {MonoConfig} from "../types"; +import {deep_merge_config, normalizeConfig} from "./config"; +import {ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers} from "./globals"; +import {mono_log_debug} from "./logging"; -export function setupPreloadChannelToMainThread() { +export function setupPreloadChannelToMainThread () { const channel = new MessageChannel(); const workerPort = channel.port1; const mainPort = channel.port2; @@ -17,7 +17,7 @@ export function setupPreloadChannelToMainThread() { onMonoConfigReceived(config, monoThreadInfo); workerPort.close(); mainPort.close(); - }, { once: true }); + }, {once: true}); workerPort.start(); // ask for config even before WASM is loaded self.postMessage({ @@ -31,7 +31,7 @@ export function setupPreloadChannelToMainThread() { let workerMonoConfigReceived = false; // called when the main thread sends us the mono config -function onMonoConfigReceived(config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { +function onMonoConfigReceived (config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { if (workerMonoConfigReceived) { mono_log_debug("mono config already received"); return; diff --git a/src/mono/browser/runtime/logging.ts b/src/mono/browser/runtime/logging.ts index 4e9229796138c7..fe03d331608d5c 100644 --- a/src/mono/browser/runtime/logging.ts +++ b/src/mono/browser/runtime/logging.ts @@ -2,31 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. /* eslint-disable no-console */ -import { INTERNAL, runtimeHelpers } from "./globals"; -import { utf8ToString } from "./strings"; -import { CharPtr, VoidPtr } from "./types/emscripten"; +import {INTERNAL, runtimeHelpers} from "./globals"; +import {utf8ToString} from "./strings"; +import {CharPtr, VoidPtr} from "./types/emscripten"; let prefix = "MONO_WASM: "; -export function set_thread_prefix(threadPrefix: string) { +export function set_thread_prefix (threadPrefix: string) { prefix = `[${threadPrefix}] MONO_WASM: `; } -export function mono_log_debug(msg: string, ...data: any) { +export function mono_log_debug (msg: string, ...data: any) { if (runtimeHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info(msg: string, ...data: any) { +export function mono_log_info (msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_warn(msg: string, ...data: any) { +export function mono_log_warn (msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error(msg: string, ...data: any) { +export function mono_log_error (msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object" && data[0].silent) { // don't log silent errors return; @@ -52,7 +52,7 @@ regexes.push(/(?[a-z]+:\/\/[^ )]*:wasm-function\[(?\d+) //# .wasm-function[8962] regexes.push(/(?<[^ >]+>[.:]wasm-function\[(?[0-9]+)\])/); -export function mono_wasm_symbolicate_string(message: string): string { +export function mono_wasm_symbolicate_string (message: string): string { try { if (wasm_func_map.size == 0) return message; @@ -89,12 +89,11 @@ export function mono_wasm_symbolicate_string(message: string): string { } } -export function mono_wasm_stringify_as_error_with_stack(reason: any): string { +export function mono_wasm_stringify_as_error_with_stack (reason: any): string { let stack: string; if (typeof reason === "string") { stack = reason; - } - else if (reason === undefined || reason === null || reason.stack === undefined) { + } else if (reason === undefined || reason === null || reason.stack === undefined) { stack = new Error().stack + ""; } else { stack = reason.stack + ""; @@ -104,7 +103,7 @@ export function mono_wasm_stringify_as_error_with_stack(reason: any): string { return mono_wasm_symbolicate_string(stack); } -export function mono_wasm_trace_logger(log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { +export function mono_wasm_trace_logger (log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { const origMessage = utf8ToString(message_ptr); const isFatal = !!fatal; const domain = utf8ToString(log_domain_ptr); @@ -142,7 +141,7 @@ export function mono_wasm_trace_logger(log_domain_ptr: CharPtr, log_level_ptr: C } -export function parseSymbolMapFile(text: string) { +export function parseSymbolMapFile (text: string) { text.split(/[\r\n]/).forEach((line: string) => { const parts: string[] = line.split(/:/); if (parts.length < 2) @@ -155,10 +154,10 @@ export function parseSymbolMapFile(text: string) { mono_log_debug(`Loaded ${wasm_func_map.size} symbols`); } -export function mono_wasm_get_func_id_to_name_mappings() { +export function mono_wasm_get_func_id_to_name_mappings () { return [...wasm_func_map.values()]; } -export function mono_wasm_console_clear() { +export function mono_wasm_console_clear () { console.clear(); -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/managed-exports.ts b/src/mono/browser/runtime/managed-exports.ts index df99745d6af376..1fb7db988c7570 100644 --- a/src/mono/browser/runtime/managed-exports.ts +++ b/src/mono/browser/runtime/managed-exports.ts @@ -3,22 +3,22 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { GCHandle, GCHandleNull, JSMarshalerArguments, JSThreadInteropMode, MarshalerToCs, MarshalerToJs, MarshalerType, MonoMethod, PThreadPtr } from "./types/internal"; -import cwraps, { threads_c_functions as twraps } from "./cwraps"; -import { runtimeHelpers, Module, loaderHelpers, mono_assert } from "./globals"; -import { JavaScriptMarshalerArgSize, alloc_stack_frame, get_arg, get_arg_gc_handle, is_args_exception, set_arg_i32, set_arg_intptr, set_arg_type, set_gc_handle, set_receiver_should_free } from "./marshal"; -import { marshal_array_to_cs, marshal_array_to_cs_impl, marshal_bool_to_cs, marshal_exception_to_cs, marshal_intptr_to_cs, marshal_string_to_cs } from "./marshal-to-cs"; -import { marshal_int32_to_js, end_marshal_task_to_js, marshal_string_to_js, begin_marshal_task_to_js, marshal_exception_to_js } from "./marshal-to-js"; -import { do_not_force_dispose, is_gcv_handle } from "./gc-handles"; -import { assert_c_interop, assert_js_interop } from "./invoke-js"; -import { monoThreadInfo, mono_wasm_main_thread_ptr } from "./pthreads"; -import { _zero_region, copyBytes } from "./memory"; -import { stringToUTF8Ptr } from "./strings"; -import { mono_log_debug } from "./logging"; +import {GCHandle, GCHandleNull, JSMarshalerArguments, JSThreadInteropMode, MarshalerToCs, MarshalerToJs, MarshalerType, MonoMethod, PThreadPtr} from "./types/internal"; +import cwraps, {threads_c_functions as twraps} from "./cwraps"; +import {runtimeHelpers, Module, loaderHelpers, mono_assert} from "./globals"; +import {JavaScriptMarshalerArgSize, alloc_stack_frame, get_arg, get_arg_gc_handle, is_args_exception, set_arg_i32, set_arg_intptr, set_arg_type, set_gc_handle, set_receiver_should_free} from "./marshal"; +import {marshal_array_to_cs, marshal_array_to_cs_impl, marshal_bool_to_cs, marshal_exception_to_cs, marshal_intptr_to_cs, marshal_string_to_cs} from "./marshal-to-cs"; +import {marshal_int32_to_js, end_marshal_task_to_js, marshal_string_to_js, begin_marshal_task_to_js, marshal_exception_to_js} from "./marshal-to-js"; +import {do_not_force_dispose, is_gcv_handle} from "./gc-handles"; +import {assert_c_interop, assert_js_interop} from "./invoke-js"; +import {monoThreadInfo, mono_wasm_main_thread_ptr} from "./pthreads"; +import {_zero_region, copyBytes} from "./memory"; +import {stringToUTF8Ptr} from "./strings"; +import {mono_log_debug} from "./logging"; const managedExports: ManagedExports = {} as any; -export function init_managed_exports(): void { +export function init_managed_exports (): void { const exports_fqn_asm = "System.Runtime.InteropServices.JavaScript"; // TODO https://github.com/dotnet/runtime/issues/98366 runtimeHelpers.runtime_interop_module = cwraps.mono_wasm_assembly_load(exports_fqn_asm); @@ -44,7 +44,7 @@ export function init_managed_exports(): void { } // the marshaled signature is: Task? CallEntrypoint(char* mainAssemblyName, string[] args) -export function call_entry_point(main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { +export function call_entry_point (main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -79,7 +79,7 @@ export function call_entry_point(main_assembly_name: string, program_args: strin } // the marshaled signature is: void LoadSatelliteAssembly(byte[] dll) -export function load_satellite_assembly(dll: Uint8Array): void { +export function load_satellite_assembly (dll: Uint8Array): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -95,7 +95,7 @@ export function load_satellite_assembly(dll: Uint8Array): void { } // the marshaled signature is: void LoadLazyAssembly(byte[] dll, byte[] pdb) -export function load_lazy_assembly(dll: Uint8Array, pdb: Uint8Array | null): void { +export function load_lazy_assembly (dll: Uint8Array, pdb: Uint8Array | null): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -114,7 +114,7 @@ export function load_lazy_assembly(dll: Uint8Array, pdb: Uint8Array | null): voi } // the marshaled signature is: void ReleaseJSOwnedObjectByGCHandle(GCHandle gcHandle) -export function release_js_owned_object_by_gc_handle(gc_handle: GCHandle) { +export function release_js_owned_object_by_gc_handle (gc_handle: GCHandle) { mono_assert(gc_handle, "Must be valid gc_handle"); loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); @@ -137,7 +137,7 @@ export function release_js_owned_object_by_gc_handle(gc_handle: GCHandle) { } // the marshaled signature is: void CompleteTask(GCHandle holder, Exception? exceptionResult, T? result) -export function complete_task(holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { +export function complete_task (holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -162,13 +162,12 @@ export function complete_task(holder_gc_handle: GCHandle, error?: any, data?: an } // the marshaled signature is: TRes? CallDelegate(GCHandle callback, T1? arg1, T2? arg2, T3? arg3) -export function call_delegate(callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { +export function call_delegate (callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { if (runtimeHelpers.config.jsThreadInteropMode == JSThreadInteropMode.NoSyncJSInterop) { throw new Error("Cannot call synchronous C# methods."); - } - else if (runtimeHelpers.isPendingSynchronousCall) { + } else if (runtimeHelpers.isPendingSynchronousCall) { throw new Error("Cannot call synchronous C# method from inside a synchronous call to a JS method."); } } @@ -207,7 +206,7 @@ export function call_delegate(callback_gc_handle: GCHandle, arg1_js: any, arg2_j } // the marshaled signature is: string GetManagedStackTrace(GCHandle exception) -export function get_managed_stack_trace(exception_gc_handle: GCHandle) { +export function get_managed_stack_trace (exception_gc_handle: GCHandle) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -227,7 +226,7 @@ export function get_managed_stack_trace(exception_gc_handle: GCHandle) { } // GCHandle InstallMainSynchronizationContext(nint jsNativeTID, JSThreadBlockingMode jsThreadBlockingMode, JSThreadInteropMode jsThreadInteropMode, MainThreadingMode mainThreadingMode) -export function install_main_synchronization_context(jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { +export function install_main_synchronization_context (jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { if (!WasmEnableThreads) return GCHandleNull; assert_c_interop(); @@ -260,7 +259,7 @@ export function install_main_synchronization_context(jsThreadBlockingMode: numbe } } -export function invoke_async_jsexport(managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { +export function invoke_async_jsexport (managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { assert_js_interop(); if (!WasmEnableThreads || runtimeHelpers.isManagedRunningOnCurrentThread) { cwraps.mono_wasm_invoke_jsexport(method, args as any); @@ -277,15 +276,14 @@ export function invoke_async_jsexport(managedTID: PThreadPtr, method: MonoMethod } } -export function invoke_sync_jsexport(method: MonoMethod, args: JSMarshalerArguments): void { +export function invoke_sync_jsexport (method: MonoMethod, args: JSMarshalerArguments): void { assert_js_interop(); if (!WasmEnableThreads) { cwraps.mono_wasm_invoke_jsexport(method, args as any); } else { if (runtimeHelpers.config.jsThreadInteropMode == JSThreadInteropMode.NoSyncJSInterop) { throw new Error("Cannot call synchronous C# methods."); - } - else if (runtimeHelpers.isPendingSynchronousCall) { + } else if (runtimeHelpers.isPendingSynchronousCall) { throw new Error("Cannot call synchronous C# method from inside a synchronous call to a JS method."); } if (runtimeHelpers.isManagedRunningOnCurrentThread) { @@ -303,7 +301,7 @@ export function invoke_sync_jsexport(method: MonoMethod, args: JSMarshalerArgume } // the marshaled signature is: Task BindAssemblyExports(string assemblyName) -export function bind_assembly_exports(assemblyName: string): Promise { +export function bind_assembly_exports (assemblyName: string): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -331,7 +329,7 @@ export function bind_assembly_exports(assemblyName: string): Promise { } -function get_method(method_name: string): MonoMethod { +function get_method (method_name: string): MonoMethod { // TODO https://github.com/dotnet/runtime/issues/98366 const res = cwraps.mono_wasm_assembly_find_method(runtimeHelpers.runtime_interop_exports_class, method_name, -1); if (!res) diff --git a/src/mono/browser/runtime/marshal-to-cs.ts b/src/mono/browser/runtime/marshal-to-cs.ts index f408e5bebd2b1c..03247fe0f42e2b 100644 --- a/src/mono/browser/runtime/marshal-to-cs.ts +++ b/src/mono/browser/runtime/marshal-to-cs.ts @@ -5,10 +5,10 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; import WasmEnableJsInteropByValue from "consts:wasmEnableJsInteropByValue"; -import { PromiseHolder, isThenable } from "./cancelable-promise"; +import {PromiseHolder, isThenable} from "./cancelable-promise"; import cwraps from "./cwraps"; -import { alloc_gcv_handle, assert_not_disposed, cs_owned_js_handle_symbol, js_owned_gc_handle_symbol, mono_wasm_get_js_handle, setup_managed_proxy } from "./gc-handles"; -import { Module, mono_assert, runtimeHelpers } from "./globals"; +import {alloc_gcv_handle, assert_not_disposed, cs_owned_js_handle_symbol, js_owned_gc_handle_symbol, mono_wasm_get_js_handle, setup_managed_proxy} from "./gc-handles"; +import {Module, mono_assert, runtimeHelpers} from "./globals"; import { ManagedError, set_gc_handle, set_js_handle, set_arg_type, set_arg_i32, set_arg_f64, set_arg_i52, set_arg_f32, set_arg_i16, set_arg_u8, set_arg_bool, set_arg_date, @@ -17,16 +17,16 @@ import { get_string_root, Span, ArraySegment, MemoryViewType, get_signature_arg3_type, set_arg_i64_big, set_arg_intptr, set_arg_element_type, ManagedObject, JavaScriptMarshalerArgSize, proxy_debug_symbol, get_arg_gc_handle, get_arg_type, set_arg_proxy_context, get_arg_intptr } from "./marshal"; -import { get_marshaler_to_js_by_type } from "./marshal-to-js"; -import { _zero_region, localHeapViewF64, localHeapViewI32, localHeapViewU8 } from "./memory"; -import { stringToMonoStringRoot, stringToUTF16 } from "./strings"; -import { JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToCs, MarshalerType } from "./types/internal"; -import { TypedArray } from "./types/emscripten"; -import { gc_locked } from "./gc-lock"; +import {get_marshaler_to_js_by_type} from "./marshal-to-js"; +import {_zero_region, localHeapViewF64, localHeapViewI32, localHeapViewU8} from "./memory"; +import {stringToMonoStringRoot, stringToUTF16} from "./strings"; +import {JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToCs, MarshalerType} from "./types/internal"; +import {TypedArray} from "./types/emscripten"; +import {gc_locked} from "./gc-lock"; export const jsinteropDoc = "For more information see https://aka.ms/dotnet-wasm-jsinterop"; -export function initialize_marshalers_to_cs(): void { +export function initialize_marshalers_to_cs (): void { if (js_to_cs_marshalers.size == 0) { js_to_cs_marshalers.set(MarshalerType.Array, marshal_array_to_cs); js_to_cs_marshalers.set(MarshalerType.Span, _marshal_span_to_cs); @@ -60,7 +60,7 @@ export function initialize_marshalers_to_cs(): void { } } -export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { +export function bind_arg_marshal_to_cs (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -87,7 +87,7 @@ export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: Mar }; } -export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): MarshalerToCs | undefined { +export function get_marshaler_to_cs_by_type (marshaler_type: MarshalerType): MarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -96,140 +96,127 @@ export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): Mars return converter; } -export function marshal_bool_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_bool_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Boolean); set_arg_bool(arg, value); } } -function _marshal_byte_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_byte_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Byte); set_arg_u8(arg, value); } } -function _marshal_char_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_char_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Char); set_arg_u16(arg, value); } } -function _marshal_int16_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int16_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Int16); set_arg_i16(arg, value); } } -function _marshal_int32_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int32_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Int32); set_arg_i32(arg, value); } } -function _marshal_int52_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int52_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Int52); set_arg_i52(arg, value); } } -function _marshal_bigint64_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_bigint64_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.BigInt64); set_arg_i64_big(arg, value); } } -function _marshal_double_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_double_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Double); set_arg_f64(arg, value); } } -function _marshal_float_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_float_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.Single); set_arg_f32(arg, value); } } -export function marshal_intptr_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_intptr_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.IntPtr); set_arg_intptr(arg, value); } } -function _marshal_date_time_to_cs(arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_to_cs (arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { mono_check(value instanceof Date, "Value is not a Date"); set_arg_type(arg, MarshalerType.DateTime); set_arg_date(arg, value); } } -function _marshal_date_time_offset_to_cs(arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_offset_to_cs (arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { mono_check(value instanceof Date, "Value is not a Date"); set_arg_type(arg, MarshalerType.DateTimeOffset); set_arg_date(arg, value); } } -export function marshal_string_to_cs(arg: JSMarshalerArgument, value: string) { +export function marshal_string_to_cs (arg: JSMarshalerArgument, value: string) { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { set_arg_type(arg, MarshalerType.String); mono_check(typeof value === "string", "Value is not a String"); _marshal_string_to_cs_impl(arg, value); } } -function _marshal_string_to_cs_impl(arg: JSMarshalerArgument, value: string) { +function _marshal_string_to_cs_impl (arg: JSMarshalerArgument, value: string) { if (WasmEnableJsInteropByValue) { const bufferLen = value.length * 2; const buffer = Module._malloc(bufferLen);// together with Marshal.FreeHGlobal @@ -240,18 +227,17 @@ function _marshal_string_to_cs_impl(arg: JSMarshalerArgument, value: string) { const root = get_string_root(arg); try { stringToMonoStringRoot(value, root); - } - finally { + } finally { root.release(); } } } -function _marshal_null_to_cs(arg: JSMarshalerArgument) { +function _marshal_null_to_cs (arg: JSMarshalerArgument) { set_arg_type(arg, MarshalerType.None); } -function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { +function _marshal_function_to_cs (arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); return; @@ -259,7 +245,7 @@ function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: mono_check(value && value instanceof Function, "Value is not a Function"); // TODO: we could try to cache value -> existing JSHandle - const wrapper: any = function delegate_wrapper(args: JSMarshalerArguments) { + const wrapper: any = function delegate_wrapper (args: JSMarshalerArguments) { const exc = get_arg(args, 0); const res = get_arg(args, 1); const arg1 = get_arg(args, 2); @@ -297,7 +283,9 @@ function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: wrapper[bound_js_function_symbol] = true; wrapper.isDisposed = false; - wrapper.dispose = () => { wrapper.isDisposed = true; }; + wrapper.dispose = () => { + wrapper.isDisposed = true; + }; const bound_function_handle = mono_wasm_get_js_handle(wrapper)!; if (BuildConfiguration === "Debug") { wrapper[proxy_debug_symbol] = `Proxy of JS Function with JSHandle ${bound_function_handle}: ${value.toString()}`; @@ -307,7 +295,7 @@ function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: } -function _marshal_task_to_cs(arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { +function _marshal_task_to_cs (arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { const handleIsPreallocated = get_arg_type(arg) == MarshalerType.TaskPreCreated; if (value === null || value === undefined) { if (WasmEnableThreads && handleIsPreallocated) { @@ -341,17 +329,15 @@ function _marshal_task_to_cs(arg: JSMarshalerArgument, value: Promise, _?: value.then(data => holder.resolve(data), reason => holder.reject(reason)); } -export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_exception_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else if (value instanceof ManagedError) { + } else if (value instanceof ManagedError) { set_arg_type(arg, MarshalerType.Exception); // this is managed exception round-trip const gc_handle = assert_not_disposed(value); set_gc_handle(arg, gc_handle); - } - else { + } else { mono_check(typeof value === "object" || typeof value === "string", () => `Value is not an Error ${typeof value}`); set_arg_type(arg, MarshalerType.JSException); const message = value.toString(); @@ -359,8 +345,7 @@ export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): v const known_js_handle = value[cs_owned_js_handle_symbol]; if (known_js_handle) { set_js_handle(arg, known_js_handle); - } - else { + } else { const js_handle = mono_wasm_get_js_handle(value)!; if (BuildConfiguration === "Debug" && Object.isExtensible(value)) { value[proxy_debug_symbol] = `JS Error with JSHandle ${js_handle}`; @@ -370,12 +355,11 @@ export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_js_object_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_js_object_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); - } - else { + } else { // if value was ManagedObject, it would be double proxied, but the C# signature requires that mono_check(value[js_owned_gc_handle_symbol] === undefined, () => `JSObject proxy of ManagedObject proxy is not supported. ${jsinteropDoc}`); mono_check(typeof value === "function" || typeof value === "object", () => `JSObject proxy of ${typeof value} is not supported`); @@ -389,51 +373,40 @@ export function marshal_js_object_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_cs_object_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); - } - else { + } else { const gc_handle = value[js_owned_gc_handle_symbol]; const js_type = typeof (value); if (gc_handle === undefined) { if (js_type === "string" || js_type === "symbol") { set_arg_type(arg, MarshalerType.String); _marshal_string_to_cs_impl(arg, value); - } - else if (js_type === "number") { + } else if (js_type === "number") { set_arg_type(arg, MarshalerType.Double); set_arg_f64(arg, value); - } - else if (js_type === "bigint") { + } else if (js_type === "bigint") { // we do it because not all bigint values could fit into Int64 throw new Error("NotImplementedException: bigint"); - } - else if (js_type === "boolean") { + } else if (js_type === "boolean") { set_arg_type(arg, MarshalerType.Boolean); set_arg_bool(arg, value); - } - else if (value instanceof Date) { + } else if (value instanceof Date) { set_arg_type(arg, MarshalerType.DateTime); set_arg_date(arg, value); - } - else if (value instanceof Error) { + } else if (value instanceof Error) { marshal_exception_to_cs(arg, value); - } - else if (value instanceof Uint8Array) { + } else if (value instanceof Uint8Array) { marshal_array_to_cs_impl(arg, value, MarshalerType.Byte); - } - else if (value instanceof Float64Array) { + } else if (value instanceof Float64Array) { marshal_array_to_cs_impl(arg, value, MarshalerType.Double); - } - else if (value instanceof Int32Array) { + } else if (value instanceof Int32Array) { marshal_array_to_cs_impl(arg, value, MarshalerType.Int32); - } - else if (Array.isArray(value)) { + } else if (Array.isArray(value)) { marshal_array_to_cs_impl(arg, value, MarshalerType.Object); - } - else if (value instanceof Int16Array + } else if (value instanceof Int16Array || value instanceof Int8Array || value instanceof Uint8ClampedArray || value instanceof Uint16Array @@ -441,35 +414,28 @@ export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): v || value instanceof Float32Array ) { throw new Error("NotImplementedException: TypedArray"); - } - else if (isThenable(value)) { + } else if (isThenable(value)) { _marshal_task_to_cs(arg, value); - } - else if (value instanceof Span) { + } else if (value instanceof Span) { throw new Error("NotImplementedException: Span"); - } - else if (js_type == "object") { + } else if (js_type == "object") { const js_handle = mono_wasm_get_js_handle(value); set_arg_type(arg, MarshalerType.JSObject); if (BuildConfiguration === "Debug" && Object.isExtensible(value)) { value[proxy_debug_symbol] = `JS Object with JSHandle ${js_handle}`; } set_js_handle(arg, js_handle); - } - else { + } else { throw new Error(`JSObject proxy is not supported for ${js_type} ${value}`); } - } - else { + } else { assert_not_disposed(value); if (value instanceof ArraySegment) { throw new Error("NotImplementedException: ArraySegment. " + jsinteropDoc); - } - else if (value instanceof ManagedError) { + } else if (value instanceof ManagedError) { set_arg_type(arg, MarshalerType.Exception); set_gc_handle(arg, gc_handle); - } - else if (value instanceof ManagedObject) { + } else if (value instanceof ManagedObject) { set_arg_type(arg, MarshalerType.Object); set_gc_handle(arg, gc_handle); } else { @@ -479,16 +445,15 @@ export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_array_to_cs(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { +export function marshal_array_to_cs (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); marshal_array_to_cs_impl(arg, value, element_type); } -export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { +export function marshal_array_to_cs_impl (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); - } - else { + } else { const element_size = array_element_size(element_type); mono_assert(element_size != -1, () => `Element type ${MarshalerType[element_type]} not supported`); const length = value.length; @@ -505,8 +470,7 @@ export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array< const element_arg = get_arg(buffer_ptr, index); marshal_string_to_cs(element_arg, value[index]); } - } - else if (element_type == MarshalerType.Object) { + } else if (element_type == MarshalerType.Object) { mono_check(Array.isArray(value), "Value is not an Array"); _zero_region(buffer_ptr, buffer_length); if (!WasmEnableJsInteropByValue) { @@ -517,31 +481,26 @@ export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array< const element_arg = get_arg(buffer_ptr, index); marshal_cs_object_to_cs(element_arg, value[index]); } - } - else if (element_type == MarshalerType.JSObject) { + } else if (element_type == MarshalerType.JSObject) { mono_check(Array.isArray(value), "Value is not an Array"); _zero_region(buffer_ptr, buffer_length); for (let index = 0; index < length; index++) { const element_arg = get_arg(buffer_ptr, index); marshal_js_object_to_cs(element_arg, value[index]); } - } - else if (element_type == MarshalerType.Byte) { + } else if (element_type == MarshalerType.Byte) { mono_check(Array.isArray(value) || value instanceof Uint8Array, "Value is not an Array or Uint8Array"); const targetView = localHeapViewU8().subarray(buffer_ptr, buffer_ptr + length); targetView.set(value); - } - else if (element_type == MarshalerType.Int32) { + } else if (element_type == MarshalerType.Int32) { mono_check(Array.isArray(value) || value instanceof Int32Array, "Value is not an Array or Int32Array"); const targetView = localHeapViewI32().subarray(buffer_ptr >> 2, (buffer_ptr >> 2) + length); targetView.set(value); - } - else if (element_type == MarshalerType.Double) { + } else if (element_type == MarshalerType.Double) { mono_check(Array.isArray(value) || value instanceof Float64Array, "Value is not an Array or Float64Array"); const targetView = localHeapViewF64().subarray(buffer_ptr >> 3, (buffer_ptr >> 3) + length); targetView.set(value); - } - else { + } else { throw new Error("not implemented"); } set_arg_intptr(arg, buffer_ptr); @@ -551,7 +510,7 @@ export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array< } } -function _marshal_span_to_cs(arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { +function _marshal_span_to_cs (arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); mono_check(!value.isDisposed, "ObjectDisposedException"); checkViewType(element_type, value._viewType); @@ -562,7 +521,7 @@ function _marshal_span_to_cs(arg: JSMarshalerArgument, value: Span, element_type } // this only supports round-trip -function _marshal_array_segment_to_cs(arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { +function _marshal_array_segment_to_cs (arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); const gc_handle = assert_not_disposed(value); mono_assert(gc_handle, "Only roundtrip of ArraySegment instance created by C#"); @@ -573,17 +532,14 @@ function _marshal_array_segment_to_cs(arg: JSMarshalerArgument, value: ArraySegm set_gc_handle(arg, gc_handle); } -function checkViewType(element_type: MarshalerType, viewType: MemoryViewType) { +function checkViewType (element_type: MarshalerType, viewType: MemoryViewType) { if (element_type == MarshalerType.Byte) { mono_check(MemoryViewType.Byte == viewType, "Expected MemoryViewType.Byte"); - } - else if (element_type == MarshalerType.Int32) { + } else if (element_type == MarshalerType.Int32) { mono_check(MemoryViewType.Int32 == viewType, "Expected MemoryViewType.Int32"); - } - else if (element_type == MarshalerType.Double) { + } else if (element_type == MarshalerType.Double) { mono_check(MemoryViewType.Double == viewType, "Expected MemoryViewType.Double"); - } - else { + } else { throw new Error(`NotImplementedException ${MarshalerType[element_type]} `); } } diff --git a/src/mono/browser/runtime/marshal-to-js.ts b/src/mono/browser/runtime/marshal-to-js.ts index db6c36fe9927e0..e4670e6a4848f2 100644 --- a/src/mono/browser/runtime/marshal-to-js.ts +++ b/src/mono/browser/runtime/marshal-to-js.ts @@ -6,8 +6,8 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableJsInteropByValue from "consts:wasmEnableJsInteropByValue"; import cwraps from "./cwraps"; -import { _lookup_js_owned_object, mono_wasm_get_js_handle, mono_wasm_get_jsobj_from_js_handle, mono_wasm_release_cs_owned_object, register_with_jsv_handle, setup_managed_proxy, teardown_managed_proxy } from "./gc-handles"; -import { Module, loaderHelpers, mono_assert } from "./globals"; +import {_lookup_js_owned_object, mono_wasm_get_js_handle, mono_wasm_get_jsobj_from_js_handle, mono_wasm_release_cs_owned_object, register_with_jsv_handle, setup_managed_proxy, teardown_managed_proxy} from "./gc-handles"; +import {Module, loaderHelpers, mono_assert} from "./globals"; import { ManagedObject, ManagedError, get_arg_gc_handle, get_arg_js_handle, get_arg_type, get_arg_i32, get_arg_f64, get_arg_i52, get_arg_i16, get_arg_u8, get_arg_f32, @@ -16,16 +16,16 @@ import { get_signature_res_type, get_arg_u16, array_element_size, get_string_root, ArraySegment, Span, MemoryViewType, get_signature_arg3_type, get_arg_i64_big, get_arg_intptr, get_arg_element_type, JavaScriptMarshalerArgSize, proxy_debug_symbol, set_js_handle, is_receiver_should_free } from "./marshal"; -import { monoStringToString, utf16ToString } from "./strings"; -import { GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToJs, MarshalerType, JSHandle } from "./types/internal"; -import { TypedArray } from "./types/emscripten"; -import { get_marshaler_to_cs_by_type, jsinteropDoc, marshal_exception_to_cs } from "./marshal-to-cs"; -import { localHeapViewF64, localHeapViewI32, localHeapViewU8 } from "./memory"; -import { call_delegate } from "./managed-exports"; -import { gc_locked } from "./gc-lock"; -import { mono_log_debug } from "./logging"; - -export function initialize_marshalers_to_js(): void { +import {monoStringToString, utf16ToString} from "./strings"; +import {GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToJs, MarshalerType, JSHandle} from "./types/internal"; +import {TypedArray} from "./types/emscripten"; +import {get_marshaler_to_cs_by_type, jsinteropDoc, marshal_exception_to_cs} from "./marshal-to-cs"; +import {localHeapViewF64, localHeapViewI32, localHeapViewU8} from "./memory"; +import {call_delegate} from "./managed-exports"; +import {gc_locked} from "./gc-lock"; +import {mono_log_debug} from "./logging"; + +export function initialize_marshalers_to_js (): void { if (cs_to_js_marshalers.size == 0) { cs_to_js_marshalers.set(MarshalerType.Array, _marshal_array_to_js); cs_to_js_marshalers.set(MarshalerType.Span, _marshal_span_to_js); @@ -60,7 +60,7 @@ export function initialize_marshalers_to_js(): void { } } -export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { +export function bind_arg_marshal_to_js (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -88,7 +88,7 @@ export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: Mar }; } -export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): MarshalerToJs | undefined { +export function get_marshaler_to_js_by_type (marshaler_type: MarshalerType): MarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -97,7 +97,7 @@ export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): Mars return converter; } -function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { +function _marshal_bool_to_js (arg: JSMarshalerArgument): boolean | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -105,7 +105,7 @@ function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { return get_arg_bool(arg); } -function _marshal_byte_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_byte_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -113,7 +113,7 @@ function _marshal_byte_to_js(arg: JSMarshalerArgument): number | null { return get_arg_u8(arg); } -function _marshal_char_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_char_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -121,7 +121,7 @@ function _marshal_char_to_js(arg: JSMarshalerArgument): number | null { return get_arg_u16(arg); } -function _marshal_int16_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_int16_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -129,7 +129,7 @@ function _marshal_int16_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i16(arg); } -export function marshal_int32_to_js(arg: JSMarshalerArgument): number | null { +export function marshal_int32_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -137,7 +137,7 @@ export function marshal_int32_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i32(arg); } -function _marshal_int52_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_int52_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -145,7 +145,7 @@ function _marshal_int52_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i52(arg); } -function _marshal_bigint64_to_js(arg: JSMarshalerArgument): bigint | null { +function _marshal_bigint64_to_js (arg: JSMarshalerArgument): bigint | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -153,7 +153,7 @@ function _marshal_bigint64_to_js(arg: JSMarshalerArgument): bigint | null { return get_arg_i64_big(arg); } -function _marshal_float_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_float_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -161,7 +161,7 @@ function _marshal_float_to_js(arg: JSMarshalerArgument): number | null { return get_arg_f32(arg); } -function _marshal_double_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_double_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -169,7 +169,7 @@ function _marshal_double_to_js(arg: JSMarshalerArgument): number | null { return get_arg_f64(arg); } -function _marshal_intptr_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_intptr_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -177,11 +177,11 @@ function _marshal_intptr_to_js(arg: JSMarshalerArgument): number | null { return get_arg_intptr(arg); } -function _marshal_null_to_js(): null { +function _marshal_null_to_js (): null { return null; } -function _marshal_datetime_to_js(arg: JSMarshalerArgument): Date | null { +function _marshal_datetime_to_js (arg: JSMarshalerArgument): Date | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -190,7 +190,7 @@ function _marshal_datetime_to_js(arg: JSMarshalerArgument): Date | null { } // NOTE: at the moment, this can't dispatch async calls (with Task/Promise return type). Therefore we don't have to worry about pre-created Task. -function _marshal_delegate_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { +function _marshal_delegate_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -222,11 +222,11 @@ function _marshal_delegate_to_js(arg: JSMarshalerArgument, _?: MarshalerType, re } export class TaskHolder { - constructor(public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { + constructor (public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { } } -export function marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { const type = get_arg_type(arg); // this path is used only when Task is passed as argument to JSImport and virtual JSHandle would be used mono_assert(type != MarshalerType.TaskPreCreated, "Unexpected Task type: TaskPreCreated"); @@ -247,7 +247,7 @@ export function marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, return holder.promise; } -export function begin_marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function begin_marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { // this path is used when Task is returned from JSExport/call_entry_point const holder = create_task_holder(res_converter); const js_handle = mono_wasm_get_js_handle(holder); @@ -259,7 +259,7 @@ export function begin_marshal_task_to_js(arg: JSMarshalerArgument, _?: Marshaler return holder.promise; } -export function end_marshal_task_to_js(args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { +export function end_marshal_task_to_js (args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { // this path is used when Task is returned from JSExport/call_entry_point const res = get_arg(args, 1); const type = get_arg_type(res); @@ -282,7 +282,7 @@ export function end_marshal_task_to_js(args: JSMarshalerArguments, res_converter return promise; } -function try_marshal_sync_task_to_js(arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { +function try_marshal_sync_task_to_js (arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { if (type === MarshalerType.None) { return null; } @@ -308,8 +308,8 @@ function try_marshal_sync_task_to_js(arg: JSMarshalerArgument, type: MarshalerTy return false; } -function create_task_holder(res_converter?: MarshalerToJs) { - const { promise, promise_control } = loaderHelpers.createPromiseController(); +function create_task_holder (res_converter?: MarshalerToJs) { + const {promise, promise_control} = loaderHelpers.createPromiseController(); const holder = new TaskHolder(promise, (type, js_handle, argInner) => { if (type === MarshalerType.TaskRejected) { const reason = marshal_exception_to_js(argInner); @@ -328,8 +328,7 @@ function create_task_holder(res_converter?: MarshalerToJs) { const js_value = res_converter!(argInner); promise_control.resolve(js_value); } - } - else { + } else { mono_assert(false, () => `Unexpected type ${MarshalerType[type]}`); } mono_wasm_release_cs_owned_object(js_handle); @@ -337,7 +336,7 @@ function create_task_holder(res_converter?: MarshalerToJs) { return holder; } -export function mono_wasm_resolve_or_reject_promise(args: JSMarshalerArguments): void { +export function mono_wasm_resolve_or_reject_promise (args: JSMarshalerArguments): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution/rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -361,8 +360,7 @@ export function mono_wasm_resolve_or_reject_promise(args: JSMarshalerArguments): if (receiver_should_free) { // this works together with AllocHGlobal in JSFunctionBinding.ResolveOrRejectPromise Module._free(args as any); - } - else { + } else { set_arg_type(res, MarshalerType.Void); set_arg_type(exc, MarshalerType.None); } @@ -375,7 +373,7 @@ export function mono_wasm_resolve_or_reject_promise(args: JSMarshalerArguments): } } -export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { +export function marshal_string_to_js (arg: JSMarshalerArgument): string | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -386,8 +384,7 @@ export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { const value = utf16ToString(buffer, buffer + len); Module._free(buffer as any); return value; - } - else { + } else { const root = get_string_root(arg); try { const value = monoStringToString(root); @@ -398,7 +395,7 @@ export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { } } -export function marshal_exception_to_js(arg: JSMarshalerArgument): Error | null { +export function marshal_exception_to_js (arg: JSMarshalerArgument): Error | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -426,7 +423,7 @@ export function marshal_exception_to_js(arg: JSMarshalerArgument): Error | null return result; } -function _marshal_js_object_to_js(arg: JSMarshalerArgument): any { +function _marshal_js_object_to_js (arg: JSMarshalerArgument): any { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -437,7 +434,7 @@ function _marshal_js_object_to_js(arg: JSMarshalerArgument): any { return js_obj; } -function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { +function _marshal_cs_object_to_js (arg: JSMarshalerArgument): any { const marshaler_type = get_arg_type(arg); if (marshaler_type == MarshalerType.None) { return null; @@ -480,12 +477,12 @@ function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { return converter(arg); } -function _marshal_array_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { mono_assert(!!element_type, "Expected valid element_type parameter"); return _marshal_array_to_js_impl(arg, element_type); } -function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js_impl (arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -505,8 +502,7 @@ function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: Marsh mono_assert(!WasmEnableThreads || !gc_locked, "GC must not be locked when disposing a GC root"); cwraps.mono_wasm_deregister_root(buffer_ptr); } - } - else if (element_type == MarshalerType.Object) { + } else if (element_type == MarshalerType.Object) { result = new Array(length); for (let index = 0; index < length; index++) { const element_arg = get_arg(buffer_ptr, index); @@ -516,34 +512,29 @@ function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: Marsh mono_assert(!WasmEnableThreads || !gc_locked, "GC must not be locked when disposing a GC root"); cwraps.mono_wasm_deregister_root(buffer_ptr); } - } - else if (element_type == MarshalerType.JSObject) { + } else if (element_type == MarshalerType.JSObject) { result = new Array(length); for (let index = 0; index < length; index++) { const element_arg = get_arg(buffer_ptr, index); result[index] = _marshal_js_object_to_js(element_arg); } - } - else if (element_type == MarshalerType.Byte) { + } else if (element_type == MarshalerType.Byte) { const sourceView = localHeapViewU8().subarray(buffer_ptr, buffer_ptr + length); result = sourceView.slice();//copy - } - else if (element_type == MarshalerType.Int32) { + } else if (element_type == MarshalerType.Int32) { const sourceView = localHeapViewI32().subarray(buffer_ptr >> 2, (buffer_ptr >> 2) + length); result = sourceView.slice();//copy - } - else if (element_type == MarshalerType.Double) { + } else if (element_type == MarshalerType.Double) { const sourceView = localHeapViewF64().subarray(buffer_ptr >> 3, (buffer_ptr >> 3) + length); result = sourceView.slice();//copy - } - else { + } else { throw new Error(`NotImplementedException ${MarshalerType[element_type]}. ${jsinteropDoc}`); } Module._free(buffer_ptr); return result; } -function _marshal_span_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Span { +function _marshal_span_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Span { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); @@ -551,20 +542,17 @@ function _marshal_span_to_js(arg: JSMarshalerArgument, element_type?: MarshalerT let result: Span | null = null; if (element_type == MarshalerType.Byte) { result = new Span(buffer_ptr, length, MemoryViewType.Byte); - } - else if (element_type == MarshalerType.Int32) { + } else if (element_type == MarshalerType.Int32) { result = new Span(buffer_ptr, length, MemoryViewType.Int32); - } - else if (element_type == MarshalerType.Double) { + } else if (element_type == MarshalerType.Double) { result = new Span(buffer_ptr, length, MemoryViewType.Double); - } - else { + } else { throw new Error(`NotImplementedException ${MarshalerType[element_type]}. ${jsinteropDoc}`); } return result; } -function _marshal_array_segment_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { +function _marshal_array_segment_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); @@ -572,14 +560,11 @@ function _marshal_array_segment_to_js(arg: JSMarshalerArgument, element_type?: M let result: ArraySegment | null = null; if (element_type == MarshalerType.Byte) { result = new ArraySegment(buffer_ptr, length, MemoryViewType.Byte); - } - else if (element_type == MarshalerType.Int32) { + } else if (element_type == MarshalerType.Int32) { result = new ArraySegment(buffer_ptr, length, MemoryViewType.Int32); - } - else if (element_type == MarshalerType.Double) { + } else if (element_type == MarshalerType.Double) { result = new ArraySegment(buffer_ptr, length, MemoryViewType.Double); - } - else { + } else { throw new Error(`NotImplementedException ${MarshalerType[element_type]}. ${jsinteropDoc}`); } const gc_handle = get_arg_gc_handle(arg); diff --git a/src/mono/browser/runtime/marshal.ts b/src/mono/browser/runtime/marshal.ts index 4c531eec070097..b1c9dc3fe8307b 100644 --- a/src/mono/browser/runtime/marshal.ts +++ b/src/mono/browser/runtime/marshal.ts @@ -3,14 +3,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { js_owned_gc_handle_symbol, teardown_managed_proxy } from "./gc-handles"; -import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; -import { getF32, getF64, getI16, getI32, getI64Big, getU16, getU32, getU8, setF32, setF64, setI16, setI32, setI64Big, setU16, setU32, setU8, localHeapViewF64, localHeapViewI32, localHeapViewU8, _zero_region, getB32, setB32, forceThreadMemoryViewRefresh } from "./memory"; -import { mono_wasm_new_external_root } from "./roots"; -import { GCHandle, JSHandle, MonoObject, MonoString, GCHandleNull, JSMarshalerArguments, JSFunctionSignature, JSMarshalerType, JSMarshalerArgument, MarshalerToJs, MarshalerToCs, WasmRoot, MarshalerType, PThreadPtr, PThreadPtrNull } from "./types/internal"; -import { TypedArray, VoidPtr } from "./types/emscripten"; -import { utf16ToString } from "./strings"; -import { get_managed_stack_trace } from "./managed-exports"; +import {js_owned_gc_handle_symbol, teardown_managed_proxy} from "./gc-handles"; +import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; +import {getF32, getF64, getI16, getI32, getI64Big, getU16, getU32, getU8, setF32, setF64, setI16, setI32, setI64Big, setU16, setU32, setU8, localHeapViewF64, localHeapViewI32, localHeapViewU8, _zero_region, getB32, setB32, forceThreadMemoryViewRefresh} from "./memory"; +import {mono_wasm_new_external_root} from "./roots"; +import {GCHandle, JSHandle, MonoObject, MonoString, GCHandleNull, JSMarshalerArguments, JSFunctionSignature, JSMarshalerType, JSMarshalerArgument, MarshalerToJs, MarshalerToCs, WasmRoot, MarshalerType, PThreadPtr, PThreadPtrNull} from "./types/internal"; +import {TypedArray, VoidPtr} from "./types/emscripten"; +import {utf16ToString} from "./strings"; +import {get_managed_stack_trace} from "./managed-exports"; export const cs_to_js_marshalers = new Map(); export const js_to_cs_marshalers = new Map(); @@ -63,7 +63,7 @@ const enum JSBindingHeaderOffsets { Result = 64, } -export function alloc_stack_frame(size: number): JSMarshalerArguments { +export function alloc_stack_frame (size: number): JSMarshalerArguments { if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); } @@ -74,35 +74,35 @@ export function alloc_stack_frame(size: number): JSMarshalerArguments { return args; } -export function get_arg(args: JSMarshalerArguments, index: number): JSMarshalerArgument { +export function get_arg (args: JSMarshalerArguments, index: number): JSMarshalerArgument { mono_assert(args, "Null args"); return args + (index * JavaScriptMarshalerArgSize); } -export function is_args_exception(args: JSMarshalerArguments): boolean { +export function is_args_exception (args: JSMarshalerArguments): boolean { mono_assert(args, "Null args"); const exceptionType = get_arg_type(args); return exceptionType !== MarshalerType.None; } -export function is_receiver_should_free(args: JSMarshalerArguments): boolean { +export function is_receiver_should_free (args: JSMarshalerArguments): boolean { if (!WasmEnableThreads) return false; mono_assert(args, "Null args"); return getB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree); } -export function get_caller_native_tid(args: JSMarshalerArguments): PThreadPtr { +export function get_caller_native_tid (args: JSMarshalerArguments): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; mono_assert(args, "Null args"); return getI32(args + JSMarshalerArgumentOffsets.CallerNativeTID) as any; } -export function set_receiver_should_free(args: JSMarshalerArguments): void { +export function set_receiver_should_free (args: JSMarshalerArguments): void { mono_assert(args, "Null args"); setB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree, true); } -export function set_args_context(args: JSMarshalerArguments): void { +export function set_args_context (args: JSMarshalerArguments): void { if (!WasmEnableThreads) return; mono_assert(args, "Null args"); const exc = get_arg(args, 0); @@ -111,52 +111,52 @@ export function set_args_context(args: JSMarshalerArguments): void { set_arg_proxy_context(res); } -export function get_sig(signature: JSFunctionSignature, index: number): JSMarshalerType { +export function get_sig (signature: JSFunctionSignature, index: number): JSMarshalerType { mono_assert(signature, "Null signatures"); return signature + (index * JSMarshalerTypeSize) + JSMarshalerSignatureHeaderSize; } -export function get_signature_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Type); } -export function get_signature_res_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_res_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.ResultMarshalerType); } -export function get_signature_arg1_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg1_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg1MarshalerType); } -export function get_signature_arg2_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg2_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_arg3_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg3_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_argument_count(signature: JSFunctionSignature): number { +export function get_signature_argument_count (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ArgumentCount); } -export function get_signature_version(signature: JSFunctionSignature): number { +export function get_signature_version (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.Version); } -export function get_signature_handle(signature: JSFunctionSignature): number { +export function get_signature_handle (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ImportHandle); } -export function get_signature_function_name(signature: JSFunctionSignature): string | null { +export function get_signature_function_name (signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const functionNameOffset = getI32(signature + JSBindingHeaderOffsets.FunctionNameOffset); if (functionNameOffset === 0) return null; @@ -165,7 +165,7 @@ export function get_signature_function_name(signature: JSFunctionSignature): str return utf16ToString(signature + functionNameOffset, signature + functionNameOffset + functionNameLength); } -export function get_signature_module_name(signature: JSFunctionSignature): string | null { +export function get_signature_module_name (signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const moduleNameOffset = getI32(signature + JSBindingHeaderOffsets.ModuleNameOffset); if (moduleNameOffset === 0) return null; @@ -173,195 +173,195 @@ export function get_signature_module_name(signature: JSFunctionSignature): strin return utf16ToString(signature + moduleNameOffset, signature + moduleNameOffset + moduleNameLength); } -export function get_sig_type(sig: JSMarshalerType): MarshalerType { +export function get_sig_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null signatures"); return getU8(sig); } -export function get_arg_type(arg: JSMarshalerArgument): MarshalerType { +export function get_arg_type (arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.Type); return type; } -export function get_arg_element_type(arg: JSMarshalerArgument): MarshalerType { +export function get_arg_element_type (arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.ElementType); return type; } -export function set_arg_type(arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_type (arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.Type, type); } -export function set_arg_element_type(arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_element_type (arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.ElementType, type); } -export function get_arg_bool(arg: JSMarshalerArgument): boolean { +export function get_arg_bool (arg: JSMarshalerArgument): boolean { mono_assert(arg, "Null arg"); return !!getU8(arg); } -export function get_arg_u8(arg: JSMarshalerArgument): number { +export function get_arg_u8 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU8(arg); } -export function get_arg_u16(arg: JSMarshalerArgument): number { +export function get_arg_u16 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU16(arg); } -export function get_arg_i16(arg: JSMarshalerArgument): number { +export function get_arg_i16 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI16(arg); } -export function get_arg_i32(arg: JSMarshalerArgument): number { +export function get_arg_i32 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_intptr(arg: JSMarshalerArgument): number { +export function get_arg_intptr (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_i52(arg: JSMarshalerArgument): number { +export function get_arg_i52 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); // we know that the range check and conversion from Int64 was be done on C# side return getF64(arg); } -export function get_arg_i64_big(arg: JSMarshalerArgument): bigint { +export function get_arg_i64_big (arg: JSMarshalerArgument): bigint { mono_assert(arg, "Null arg"); return getI64Big(arg); } -export function get_arg_date(arg: JSMarshalerArgument): Date { +export function get_arg_date (arg: JSMarshalerArgument): Date { mono_assert(arg, "Null arg"); const unixTime = getF64(arg); const date = new Date(unixTime); return date; } -export function get_arg_f32(arg: JSMarshalerArgument): number { +export function get_arg_f32 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF32(arg); } -export function get_arg_f64(arg: JSMarshalerArgument): number { +export function get_arg_f64 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF64(arg); } -export function set_arg_bool(arg: JSMarshalerArgument, value: boolean): void { +export function set_arg_bool (arg: JSMarshalerArgument, value: boolean): void { mono_assert(arg, "Null arg"); mono_check(typeof value === "boolean", () => `Value is not a Boolean: ${value} (${typeof (value)})`); setB32(arg, value ? 1 : 0); } -export function set_arg_u8(arg: JSMarshalerArgument, value: number): void { +export function set_arg_u8 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU8(arg, value); } -export function set_arg_u16(arg: JSMarshalerArgument, value: number): void { +export function set_arg_u16 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU16(arg, value); } -export function set_arg_i16(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i16 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI16(arg, value); } -export function set_arg_i32(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i32 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_intptr(arg: JSMarshalerArgument, value: VoidPtr): void { +export function set_arg_intptr (arg: JSMarshalerArgument, value: VoidPtr): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_i52(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i52 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); // we know that conversion to Int64 would be done on C# side setF64(arg, value); } -export function set_arg_i64_big(arg: JSMarshalerArgument, value: bigint): void { +export function set_arg_i64_big (arg: JSMarshalerArgument, value: bigint): void { mono_assert(arg, "Null arg"); setI64Big(arg, value); } -export function set_arg_date(arg: JSMarshalerArgument, value: Date): void { +export function set_arg_date (arg: JSMarshalerArgument, value: Date): void { mono_assert(arg, "Null arg"); // getTime() is always UTC const unixTime = value.getTime(); setF64(arg, unixTime); } -export function set_arg_f64(arg: JSMarshalerArgument, value: number): void { +export function set_arg_f64 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF64(arg, value); } -export function set_arg_f32(arg: JSMarshalerArgument, value: number): void { +export function set_arg_f32 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF32(arg, value); } -export function get_arg_js_handle(arg: JSMarshalerArgument): JSHandle { +export function get_arg_js_handle (arg: JSMarshalerArgument): JSHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.JSHandle); } -export function set_arg_proxy_context(arg: JSMarshalerArgument): void { +export function set_arg_proxy_context (arg: JSMarshalerArgument): void { if (!WasmEnableThreads) return; mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.ContextHandle, runtimeHelpers.proxyGCHandle); } -export function set_js_handle(arg: JSMarshalerArgument, jsHandle: JSHandle): void { +export function set_js_handle (arg: JSMarshalerArgument, jsHandle: JSHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.JSHandle, jsHandle); set_arg_proxy_context(arg); } -export function get_arg_gc_handle(arg: JSMarshalerArgument): GCHandle { +export function get_arg_gc_handle (arg: JSMarshalerArgument): GCHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.GCHandle); } -export function set_gc_handle(arg: JSMarshalerArgument, gcHandle: GCHandle): void { +export function set_gc_handle (arg: JSMarshalerArgument, gcHandle: GCHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.GCHandle, gcHandle); set_arg_proxy_context(arg); } -export function get_string_root(arg: JSMarshalerArgument): WasmRoot { +export function get_string_root (arg: JSMarshalerArgument): WasmRoot { mono_assert(arg, "Null arg"); return mono_wasm_new_external_root(arg); } -export function get_arg_length(arg: JSMarshalerArgument): number { +export function get_arg_length (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.Length); } -export function set_arg_length(arg: JSMarshalerArgument, size: number): void { +export function set_arg_length (arg: JSMarshalerArgument, size: number): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.Length, size); } -export function set_root(arg: JSMarshalerArgument, root: WasmRoot): void { +export function set_root (arg: JSMarshalerArgument, root: WasmRoot): void { mono_assert(arg, "Null arg"); setU32(arg + 0, root.get_address()); } @@ -372,15 +372,15 @@ export interface IDisposable { } export class ManagedObject implements IDisposable { - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } - toString(): string { + toString (): string { return `CsObject(gc_handle: ${(this)[js_owned_gc_handle_symbol]})`; } } @@ -388,7 +388,7 @@ export class ManagedObject implements IDisposable { export class ManagedError extends Error implements IDisposable { private superStack: any; private managed_stack: any; - constructor(message: string) { + constructor (message: string) { super(message); this.superStack = Object.getOwnPropertyDescriptor(this, "stack"); // this works on Chrome Object.defineProperty(this, "stack", { @@ -396,7 +396,7 @@ export class ManagedError extends Error implements IDisposable { }); } - getSuperStack() { + getSuperStack () { if (this.superStack) { if (this.superStack.value !== undefined) return this.superStack.value; @@ -406,7 +406,7 @@ export class ManagedError extends Error implements IDisposable { return super.stack; // this works on FF } - getManageStack() { + getManageStack () { if (this.managed_stack) { return this.managed_stack; } @@ -427,23 +427,23 @@ export class ManagedError extends Error implements IDisposable { return this.getSuperStack(); } - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } -export function get_signature_marshaler(signature: JSFunctionSignature, index: number): JSHandle { +export function get_signature_marshaler (signature: JSFunctionSignature, index: number): JSHandle { mono_assert(signature, "Null signatures"); const sig = get_sig(signature, index); return getU32(sig + JSBindingHeaderOffsets.ImportHandle); } -export function array_element_size(element_type: MarshalerType): number { +export function array_element_size (element_type: MarshalerType): number { return element_type == MarshalerType.Byte ? 1 : element_type == MarshalerType.Int32 ? 4 : element_type == MarshalerType.Int52 ? 8 @@ -461,13 +461,13 @@ export const enum MemoryViewType { } abstract class MemoryView implements IMemoryView { - protected constructor(public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { + protected constructor (public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { } abstract dispose(): void; abstract get isDisposed(): boolean; - _unsafe_create_view(): TypedArray { + _unsafe_create_view (): TypedArray { // this view must be short lived so that it doesn't fail after wasm memory growth // for that reason we also don't give the view out to end user and provide set/slice/copyTo API instead const view = this._viewType == MemoryViewType.Byte ? new Uint8Array(localHeapViewU8().buffer, this._pointer, this._length) @@ -478,7 +478,7 @@ abstract class MemoryView implements IMemoryView { return view; } - set(source: TypedArray, targetOffset?: number): void { + set (source: TypedArray, targetOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const targetView = this._unsafe_create_view(); mono_check(source && targetView && source.constructor === targetView.constructor, () => `Expected ${targetView.constructor}`); @@ -486,7 +486,7 @@ abstract class MemoryView implements IMemoryView { // TODO consider memory write barrier } - copyTo(target: TypedArray, sourceOffset?: number): void { + copyTo (target: TypedArray, sourceOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); mono_check(target && sourceView && target.constructor === sourceView.constructor, () => `Expected ${sourceView.constructor}`); @@ -495,19 +495,19 @@ abstract class MemoryView implements IMemoryView { target.set(trimmedSource); } - slice(start?: number, end?: number): TypedArray { + slice (start?: number, end?: number): TypedArray { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); // TODO consider memory read barrier return sourceView.slice(start, end); } - get length(): number { + get length (): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._length; } - get byteLength(): number { + get byteLength (): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._viewType == MemoryViewType.Byte ? this._length : this._viewType == MemoryViewType.Int32 ? this._length << 2 @@ -539,27 +539,27 @@ export interface IMemoryView extends IDisposable { export class Span extends MemoryView { private is_disposed = false; - public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose(): void { + dispose (): void { this.is_disposed = true; } - get isDisposed(): boolean { + get isDisposed (): boolean { return this.is_disposed; } } export class ArraySegment extends MemoryView { - public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } diff --git a/src/mono/browser/runtime/memory.ts b/src/mono/browser/runtime/memory.ts index 585c6e377a1c1e..523bed90d549ce 100644 --- a/src/mono/browser/runtime/memory.ts +++ b/src/mono/browser/runtime/memory.ts @@ -3,17 +3,17 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { MemOffset, NumberOrPointer } from "./types/internal"; -import { VoidPtr, CharPtr } from "./types/emscripten"; -import cwraps, { I52Error } from "./cwraps"; -import { Module, mono_assert, runtimeHelpers } from "./globals"; -import { utf8ToString } from "./strings"; +import {MemOffset, NumberOrPointer} from "./types/internal"; +import {VoidPtr, CharPtr} from "./types/emscripten"; +import cwraps, {I52Error} from "./cwraps"; +import {Module, mono_assert, runtimeHelpers} from "./globals"; +import {utf8ToString} from "./strings"; const alloca_stack: Array = []; const alloca_buffer_size = 32 * 1024; let alloca_base: VoidPtr, alloca_offset: VoidPtr, alloca_limit: VoidPtr; -function _ensure_allocated(): void { +function _ensure_allocated (): void { if (alloca_base) return; alloca_base = Module._malloc(alloca_buffer_size); @@ -24,7 +24,7 @@ function _ensure_allocated(): void { const max_int64_big = BigInt("9223372036854775807"); const min_int64_big = BigInt("-9223372036854775808"); -export function temp_malloc(size: number): VoidPtr { +export function temp_malloc (size: number): VoidPtr { _ensure_allocated(); if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -36,12 +36,12 @@ export function temp_malloc(size: number): VoidPtr { return result; } -export function _create_temp_frame(): void { +export function _create_temp_frame (): void { _ensure_allocated(); alloca_stack.push(alloca_offset); } -export function _release_temp_frame(): void { +export function _release_temp_frame (): void { if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -49,16 +49,16 @@ export function _release_temp_frame(): void { } -function assert_int_in_range(value: Number, min: Number, max: Number) { +function assert_int_in_range (value: Number, min: Number, max: Number) { mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); mono_check(value >= min && value <= max, () => `Overflow: value ${value} is out of ${min} ${max} range`); } -export function _zero_region(byteOffset: VoidPtr, sizeBytes: number): void { +export function _zero_region (byteOffset: VoidPtr, sizeBytes: number): void { localHeapViewU8().fill(0, byteOffset, byteOffset + sizeBytes); } -export function setB32(offset: MemOffset, value: number | boolean): void { +export function setB32 (offset: MemOffset, value: number | boolean): void { receiveWorkerHeapViews(); const boolValue = !!value; if (typeof (value) === "number") @@ -66,64 +66,64 @@ export function setB32(offset: MemOffset, value: number | boolean): void { Module.HEAP32[offset >>> 2] = boolValue ? 1 : 0; } -export function setU8(offset: MemOffset, value: number): void { +export function setU8 (offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFF); receiveWorkerHeapViews(); Module.HEAPU8[offset] = value; } -export function setU16(offset: MemOffset, value: number): void { +export function setU16 (offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); receiveWorkerHeapViews(); Module.HEAPU16[offset >>> 1] = value; } // does not check for growable heap -export function setU16_local(localView: Uint16Array, offset: MemOffset, value: number): void { +export function setU16_local (localView: Uint16Array, offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); localView[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU16_unchecked(offset: MemOffset, value: number): void { +export function setU16_unchecked (offset: MemOffset, value: number): void { Module.HEAPU16[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU32_unchecked(offset: MemOffset, value: NumberOrPointer): void { +export function setU32_unchecked (offset: MemOffset, value: NumberOrPointer): void { Module.HEAPU32[offset >>> 2] = value; } -export function setU32(offset: MemOffset, value: NumberOrPointer): void { +export function setU32 (offset: MemOffset, value: NumberOrPointer): void { assert_int_in_range(value, 0, 0xFFFF_FFFF); receiveWorkerHeapViews(); Module.HEAPU32[offset >>> 2] = value; } -export function setI8(offset: MemOffset, value: number): void { +export function setI8 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x80, 0x7F); receiveWorkerHeapViews(); Module.HEAP8[offset] = value; } -export function setI16(offset: MemOffset, value: number): void { +export function setI16 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000, 0x7FFF); receiveWorkerHeapViews(); Module.HEAP16[offset >>> 1] = value; } -export function setI32_unchecked(offset: MemOffset, value: number): void { +export function setI32_unchecked (offset: MemOffset, value: number): void { receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -export function setI32(offset: MemOffset, value: number): void { +export function setI32 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000_0000, 0x7FFF_FFFF); receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -function autoThrowI52(error: I52Error) { +function autoThrowI52 (error: I52Error) { if (error === I52Error.NONE) return; @@ -140,7 +140,7 @@ function autoThrowI52(error: I52Error) { /** * Throws for values which are not 52 bit integer. See Number.isSafeInteger() */ -export function setI52(offset: MemOffset, value: number): void { +export function setI52 (offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); const error = cwraps.mono_wasm_f64_to_i52(offset, value); @@ -150,7 +150,7 @@ export function setI52(offset: MemOffset, value: number): void { /** * Throws for values which are not 52 bit integer or are negative. See Number.isSafeInteger(). */ -export function setU52(offset: MemOffset, value: number): void { +export function setU52 (offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); mono_check(value >= 0, "Can't convert negative Number into UInt64"); receiveWorkerHeapViews(); @@ -158,101 +158,101 @@ export function setU52(offset: MemOffset, value: number): void { autoThrowI52(error); } -export function setI64Big(offset: MemOffset, value: bigint): void { +export function setI64Big (offset: MemOffset, value: bigint): void { mono_check(typeof value === "bigint", () => `Value is not an bigint: ${value} (${typeof (value)})`); mono_check(value >= min_int64_big && value <= max_int64_big, () => `Overflow: value ${value} is out of ${min_int64_big} ${max_int64_big} range`); Module.HEAP64[offset >>> 3] = value; } -export function setF32(offset: MemOffset, value: number): void { +export function setF32 (offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF32[offset >>> 2] = value; } -export function setF64(offset: MemOffset, value: number): void { +export function setF64 (offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF64[offset >>> 3] = value; } -export function getB32(offset: MemOffset): boolean { +export function getB32 (offset: MemOffset): boolean { receiveWorkerHeapViews(); return !!(Module.HEAP32[offset >>> 2]); } -export function getU8(offset: MemOffset): number { +export function getU8 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU8[offset]; } -export function getU16(offset: MemOffset): number { +export function getU16 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU16[offset >>> 1]; } // does not check for growable heap -export function getU16_local(localView: Uint16Array, offset: MemOffset): number { +export function getU16_local (localView: Uint16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getU32(offset: MemOffset): number { +export function getU32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU32[offset >>> 2]; } // does not check for growable heap -export function getU32_local(localView: Uint32Array, offset: MemOffset): number { +export function getU32_local (localView: Uint32Array, offset: MemOffset): number { return localView[offset >>> 2]; } -export function getI32_unaligned(offset: MemOffset): number { +export function getI32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset); } -export function getU32_unaligned(offset: MemOffset): number { +export function getU32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset) >>> 0; } -export function getF32_unaligned(offset: MemOffset): number { +export function getF32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_f32_unaligned(offset); } -export function getF64_unaligned(offset: MemOffset): number { +export function getF64_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_f64_unaligned(offset); } -export function getI8(offset: MemOffset): number { +export function getI8 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP8[offset]; } -export function getI16(offset: MemOffset): number { +export function getI16 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP16[offset >>> 1]; } // does not check for growable heap -export function getI16_local(localView: Int16Array, offset: MemOffset): number { +export function getI16_local (localView: Int16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getI32(offset: MemOffset): number { +export function getI32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP32[offset >>> 2]; } // does not check for growable heap -export function getI32_local(localView: Int32Array, offset: MemOffset): number { +export function getI32_local (localView: Int32Array, offset: MemOffset): number { return localView[offset >>> 2]; } /** * Throws for Number.MIN_SAFE_INTEGER > value > Number.MAX_SAFE_INTEGER */ -export function getI52(offset: MemOffset): number { +export function getI52 (offset: MemOffset): number { const result = cwraps.mono_wasm_i52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); @@ -262,24 +262,24 @@ export function getI52(offset: MemOffset): number { /** * Throws for 0 > value > Number.MAX_SAFE_INTEGER */ -export function getU52(offset: MemOffset): number { +export function getU52 (offset: MemOffset): number { const result = cwraps.mono_wasm_u52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); return result; } -export function getI64Big(offset: MemOffset): bigint { +export function getI64Big (offset: MemOffset): bigint { receiveWorkerHeapViews(); return Module.HEAP64[offset >>> 3]; } -export function getF32(offset: MemOffset): number { +export function getF32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF32[offset >>> 2]; } -export function getF64(offset: MemOffset): number { +export function getF64 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF64[offset >>> 3]; } @@ -291,7 +291,7 @@ export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr) = export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1) => TResult, ud1: T1): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2) => TResult, ud1: T1, ud2: T2): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2, ud3: T3) => TResult, ud1: T1, ud2: T2, ud3: T3): TResult; -export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { +export function withStackAlloc (bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { const sp = Module.stackSave(); const ptr = Module.stackAlloc(bytesWanted); try { @@ -303,14 +303,14 @@ export function withStackAlloc(bytesWanted: number, f: (ptr // @bytes must be a typed array. space is allocated for it in the native heap // and it is copied to that location. returns the address of the allocation. -export function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr { +export function mono_wasm_load_bytes_into_heap (bytes: Uint8Array): VoidPtr { const memoryOffset = Module._malloc(bytes.length); const heapBytes = new Uint8Array(localHeapViewU8().buffer, memoryOffset, bytes.length); heapBytes.set(bytes); return memoryOffset; } -export function getEnv(name: string): string | null { +export function getEnv (name: string): string | null { let charPtr: CharPtr = 0; try { charPtr = cwraps.mono_wasm_getenv(name); @@ -322,7 +322,7 @@ export function getEnv(name: string): string | null { } } -export function compareExchangeI32(offset: MemOffset, value: number, expected: number): number { +export function compareExchangeI32 (offset: MemOffset, value: number, expected: number): number { mono_assert((offset & 3) === 0, () => `compareExchangeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) { const actual = getI32(offset); @@ -334,80 +334,80 @@ export function compareExchangeI32(offset: MemOffset, value: number, expected: n return globalThis.Atomics.compareExchange(localHeapViewI32(), offset >>> 2, expected, value); } -export function storeI32(offset: MemOffset, value: number): void { +export function storeI32 (offset: MemOffset, value: number): void { mono_assert((offset & 3) === 0, () => `storeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return setI32(offset, value); globalThis.Atomics.store(localHeapViewI32(), offset >>> 2, value); } -export function notifyI32(offset: MemOffset, count: number): void { +export function notifyI32 (offset: MemOffset, count: number): void { mono_assert((offset & 3) === 0, () => `notifyI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return; globalThis.Atomics.notify(localHeapViewI32(), offset >>> 2, count); } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI8(): Int8Array { +export function localHeapViewI8 (): Int8Array { receiveWorkerHeapViews(); return Module.HEAP8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI16(): Int16Array { +export function localHeapViewI16 (): Int16Array { receiveWorkerHeapViews(); return Module.HEAP16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI32(): Int32Array { +export function localHeapViewI32 (): Int32Array { receiveWorkerHeapViews(); return Module.HEAP32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI64Big(): BigInt64Array { +export function localHeapViewI64Big (): BigInt64Array { receiveWorkerHeapViews(); return Module.HEAP64; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU8(): Uint8Array { +export function localHeapViewU8 (): Uint8Array { receiveWorkerHeapViews(); return Module.HEAPU8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU16(): Uint16Array { +export function localHeapViewU16 (): Uint16Array { receiveWorkerHeapViews(); return Module.HEAPU16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU32(): Uint32Array { +export function localHeapViewU32 (): Uint32Array { receiveWorkerHeapViews(); return Module.HEAPU32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF32(): Float32Array { +export function localHeapViewF32 (): Float32Array { receiveWorkerHeapViews(); return Module.HEAPF32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF64(): Float64Array { +export function localHeapViewF64 (): Float64Array { receiveWorkerHeapViews(); return Module.HEAPF64; } -export function copyBytes(srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { +export function copyBytes (srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { const heap = localHeapViewU8(); heap.copyWithin(dstPtr as any, srcPtr as any, srcPtr as any + bytes); } // when we run with multithreading enabled, we need to make sure that the memory views are updated on each worker // on non-MT build, this will be a no-op trimmed by rollup -export function receiveWorkerHeapViews() { +export function receiveWorkerHeapViews () { if (!WasmEnableThreads) return; const memory = runtimeHelpers.getMemory(); if (memory.buffer !== Module.HEAPU8.buffer) { @@ -416,7 +416,7 @@ export function receiveWorkerHeapViews() { } const sharedArrayBufferDefined = typeof SharedArrayBuffer !== "undefined"; -export function isSharedArrayBuffer(buffer: any): buffer is SharedArrayBuffer { +export function isSharedArrayBuffer (buffer: any): buffer is SharedArrayBuffer { // this condition should be eliminated by rollup on non-threading builds if (!WasmEnableThreads) return false; // BEWARE: In some cases, `instanceof SharedArrayBuffer` returns false even though buffer is an SAB. @@ -426,23 +426,23 @@ export function isSharedArrayBuffer(buffer: any): buffer is SharedArrayBuffer { } /* -Problem: When WebWorker is suspended in the browser, the other running threads could `grow` the linear memory in the meantime. -After the thread is un-suspended C code may to try to de-reference pointer which is beyond it's known view. +Problem: When WebWorker is suspended in the browser, the other running threads could `grow` the linear memory in the meantime. +After the thread is un-suspended C code may to try to de-reference pointer which is beyond it's known view. This is likely V8 bug. We don't have direct evidence, just failed debugger unit tests with MT runtime. */ -export function forceThreadMemoryViewRefresh() { +export function forceThreadMemoryViewRefresh () { // this condition should be eliminated by rollup on non-threading builds and it would become empty method. if (!WasmEnableThreads) return; const wasmMemory = runtimeHelpers.getMemory(); /* - Normally when wasm memory grows in v8, this size change is broadcast to other web workers via an 'interrupt', which works by setting a thread-local flag that needs to be checked. - It's possible that at this point in execution the flag has not been checked yet (because this worker was suspended by the debugger in an unknown location), - which means the size change has not taken effect in this worker. - wasmMemory.grow's implementation in v8 checks to see whether other workers have already grown the buffer, - and will update the current worker's knowledge of the buffer's size. - After that we should be able to safely updateMemoryViews and get a correctly sized view. + Normally when wasm memory grows in v8, this size change is broadcast to other web workers via an 'interrupt', which works by setting a thread-local flag that needs to be checked. + It's possible that at this point in execution the flag has not been checked yet (because this worker was suspended by the debugger in an unknown location), + which means the size change has not taken effect in this worker. + wasmMemory.grow's implementation in v8 checks to see whether other workers have already grown the buffer, + and will update the current worker's knowledge of the buffer's size. + After that we should be able to safely updateMemoryViews and get a correctly sized view. This only works because their implementation does not skip doing work even when you ask to grow by 0 pages. */ wasmMemory.grow(0); diff --git a/src/mono/browser/runtime/polyfills.ts b/src/mono/browser/runtime/polyfills.ts index 26150c797c81ea..61a89bec1513be 100644 --- a/src/mono/browser/runtime/polyfills.ts +++ b/src/mono/browser/runtime/polyfills.ts @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import type { EmscriptenReplacements } from "./types/internal"; -import type { TypedArray } from "./types/emscripten"; -import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WORKER, INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals"; -import { replaceEmscriptenTLSInit } from "./pthreads"; -import { replaceEmscriptenPThreadUI } from "./pthreads"; +import type {EmscriptenReplacements} from "./types/internal"; +import type {TypedArray} from "./types/emscripten"; +import {ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WORKER, INTERNAL, Module, loaderHelpers, runtimeHelpers} from "./globals"; +import {replaceEmscriptenTLSInit} from "./pthreads"; +import {replaceEmscriptenPThreadUI} from "./pthreads"; const dummyPerformance = { now: function () { @@ -14,7 +14,7 @@ const dummyPerformance = { } }; -export function initializeReplacements(replacements: EmscriptenReplacements): void { +export function initializeReplacements (replacements: EmscriptenReplacements): void { // performance.now() is used by emscripten and doesn't work in JSC if (typeof globalThis.performance === "undefined") { globalThis.performance = dummyPerformance as any; @@ -43,12 +43,12 @@ export function initializeReplacements(replacements: EmscriptenReplacements): vo } } -export async function init_polyfills_async(): Promise { +export async function init_polyfills_async (): Promise { // v8 shell doesn't have Event and EventTarget if (WasmEnableThreads && typeof globalThis.Event === "undefined") { globalThis.Event = class Event { readonly type: string; - constructor(type: string) { + constructor (type: string) { this.type = type; } } as any; @@ -56,7 +56,7 @@ export async function init_polyfills_async(): Promise { if (WasmEnableThreads && typeof globalThis.EventTarget === "undefined") { globalThis.EventTarget = class EventTarget { private subscribers = new Map>(); - addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { + addEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { if (listener === undefined || listener == null) return; let oneShot = false; @@ -76,9 +76,9 @@ export async function init_polyfills_async(): Promise { if (listeners === undefined) { throw new Error("can't happen"); } - listeners.push({ listener, oneShot }); + listeners.push({listener, oneShot}); } - removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { + removeEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { if (listener === undefined || listener == null) return; if (options !== undefined) { @@ -102,7 +102,7 @@ export async function init_polyfills_async(): Promise { subscribers.splice(index, 1); } } - dispatchEvent(event: Event) { + dispatchEvent (event: Event) { if (!this.subscribers.has(event.type)) { return true; } @@ -138,7 +138,7 @@ export async function init_polyfills_async(): Promise { if (ENVIRONMENT_IS_NODE) { // wait for locateFile setup on NodeJs if (globalThis.performance === dummyPerformance) { - const { performance } = INTERNAL.require("perf_hooks"); + const {performance} = INTERNAL.require("perf_hooks"); globalThis.performance = performance; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment diff --git a/src/mono/browser/runtime/profiler.ts b/src/mono/browser/runtime/profiler.ts index 8dce6e31fcba2e..64b1e8c93ed5ce 100644 --- a/src/mono/browser/runtime/profiler.ts +++ b/src/mono/browser/runtime/profiler.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { ENVIRONMENT_IS_WEB, mono_assert, runtimeHelpers } from "./globals"; -import { MonoMethod, AOTProfilerOptions, BrowserProfilerOptions } from "./types/internal"; -import { profiler_c_functions as cwraps } from "./cwraps"; -import { utf8ToString } from "./strings"; +import {ENVIRONMENT_IS_WEB, mono_assert, runtimeHelpers} from "./globals"; +import {MonoMethod, AOTProfilerOptions, BrowserProfilerOptions} from "./types/internal"; +import {profiler_c_functions as cwraps} from "./cwraps"; +import {utf8ToString} from "./strings"; // Initialize the AOT profiler with OPTIONS. // Requires the AOT profiler to be linked into the app. @@ -14,7 +14,7 @@ import { utf8ToString } from "./strings"; // sendTo defaults to 'WebAssembly.Runtime::DumpAotProfileData'. // DumpAotProfileData stores the data into INTERNAL.aotProfileData. // -export function mono_wasm_init_aot_profiler(options: AOTProfilerOptions): void { +export function mono_wasm_init_aot_profiler (options: AOTProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableAotProfiler, "AOT profiler is not enabled, please use aot; in your project file."); if (options == null) options = {}; @@ -26,7 +26,7 @@ export function mono_wasm_init_aot_profiler(options: AOTProfilerOptions): void { cwraps.mono_wasm_profiler_init_aot(arg); } -export function mono_wasm_init_browser_profiler(options: BrowserProfilerOptions): void { +export function mono_wasm_init_browser_profiler (options: BrowserProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableBrowserProfiler, "Browser profiler is not enabled, please use browser; in your project file."); if (options == null) options = {}; @@ -59,37 +59,37 @@ export type TimeStamp = { __brand: "TimeStamp" } -export function startMeasure(): TimeStamp { +export function startMeasure (): TimeStamp { if (runtimeHelpers.enablePerfMeasure) { return globalThis.performance.now() as any; } return undefined as any; } -export function endMeasure(start: TimeStamp, block: string, id?: string) { +export function endMeasure (start: TimeStamp, block: string, id?: string) { if (runtimeHelpers.enablePerfMeasure && start) { const options = ENVIRONMENT_IS_WEB - ? { start: start as any } - : { startTime: start as any }; + ? {start: start as any} + : {startTime: start as any}; const name = id ? `${block}${id} ` : block; globalThis.performance.measure(name, options); } } const stackFrames: number[] = []; -export function mono_wasm_profiler_enter(): void { +export function mono_wasm_profiler_enter (): void { if (runtimeHelpers.enablePerfMeasure) { stackFrames.push(globalThis.performance.now()); } } const methodNames: Map = new Map(); -export function mono_wasm_profiler_leave(method: MonoMethod): void { +export function mono_wasm_profiler_leave (method: MonoMethod): void { if (runtimeHelpers.enablePerfMeasure) { const start = stackFrames.pop(); const options = ENVIRONMENT_IS_WEB - ? { start: start } - : { startTime: start }; + ? {start: start} + : {startTime: start}; let methodName = methodNames.get(method as any); if (!methodName) { const chars = cwraps.mono_wasm_method_get_name(method); diff --git a/src/mono/browser/runtime/pthreads/deputy-thread.ts b/src/mono/browser/runtime/pthreads/deputy-thread.ts index 1020aaf98620d1..78ef0e588a1b6a 100644 --- a/src/mono/browser/runtime/pthreads/deputy-thread.ts +++ b/src/mono/browser/runtime/pthreads/deputy-thread.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import { mono_log_error, mono_log_info } from "../logging"; -import { monoThreadInfo, postMessageToMain, update_thread_info } from "./shared"; -import { Module, loaderHelpers, runtimeHelpers } from "../globals"; -import { start_runtime } from "../startup"; -import { WorkerToMainMessageType } from "../types/internal"; +import {mono_log_error, mono_log_info} from "../logging"; +import {monoThreadInfo, postMessageToMain, update_thread_info} from "./shared"; +import {Module, loaderHelpers, runtimeHelpers} from "../globals"; +import {start_runtime} from "../startup"; +import {WorkerToMainMessageType} from "../types/internal"; -export function mono_wasm_start_deputy_thread_async() { +export function mono_wasm_start_deputy_thread_async () { if (!WasmEnableThreads) return; if (BuildConfiguration === "Debug" && globalThis.setInterval) globalThis.setInterval(() => { @@ -36,8 +36,7 @@ export function mono_wasm_start_deputy_thread_async() { info: monoThreadInfo, deputyProxyGCHandle: runtimeHelpers.proxyGCHandle, }); - } - catch (err) { + } catch (err) { postMessageToMain({ monoCmd: WorkerToMainMessageType.deputyFailed, info: monoThreadInfo, @@ -48,8 +47,7 @@ export function mono_wasm_start_deputy_thread_async() { throw err; } }, 0); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_start_deputy_thread_async() failed", err); loaderHelpers.mono_exit(1, err); throw err; @@ -57,4 +55,4 @@ export function mono_wasm_start_deputy_thread_async() { // same as emscripten_exit_with_live_runtime() throw "unwind"; -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/pthreads/index.ts b/src/mono/browser/runtime/pthreads/index.ts index 0a5911605282d0..b243911f236ae2 100644 --- a/src/mono/browser/runtime/pthreads/index.ts +++ b/src/mono/browser/runtime/pthreads/index.ts @@ -16,5 +16,5 @@ export { dotnetPthreadCreated, initWorkerThreadEvents, replaceEmscriptenTLSInit, pthread_self } from "./worker-thread"; -export { mono_wasm_start_deputy_thread_async } from "./deputy-thread"; -export { mono_wasm_start_io_thread_async } from "./io-thread"; +export {mono_wasm_start_deputy_thread_async} from "./deputy-thread"; +export {mono_wasm_start_io_thread_async} from "./io-thread"; diff --git a/src/mono/browser/runtime/pthreads/io-thread.ts b/src/mono/browser/runtime/pthreads/io-thread.ts index ebbd2b82a9b791..f216ec2aeab756 100644 --- a/src/mono/browser/runtime/pthreads/io-thread.ts +++ b/src/mono/browser/runtime/pthreads/io-thread.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import { mono_log_error, mono_log_info } from "../logging"; -import { monoThreadInfo, postMessageToMain, update_thread_info } from "./shared"; -import { Module, loaderHelpers } from "../globals"; -import { WorkerToMainMessageType } from "../types/internal"; -import { threads_c_functions as tcwraps } from "../cwraps"; +import {mono_log_error, mono_log_info} from "../logging"; +import {monoThreadInfo, postMessageToMain, update_thread_info} from "./shared"; +import {Module, loaderHelpers} from "../globals"; +import {WorkerToMainMessageType} from "../types/internal"; +import {threads_c_functions as tcwraps} from "../cwraps"; -export function mono_wasm_start_io_thread_async() { +export function mono_wasm_start_io_thread_async () { if (!WasmEnableThreads) return; @@ -28,8 +28,7 @@ export function mono_wasm_start_io_thread_async() { info: monoThreadInfo, }); Module.runtimeKeepalivePush(); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_start_io_thread_async() failed", err); loaderHelpers.mono_exit(1, err); throw err; @@ -37,4 +36,4 @@ export function mono_wasm_start_io_thread_async() { // same as emscripten_exit_with_live_runtime() throw "unwind"; -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/pthreads/shared.ts b/src/mono/browser/runtime/pthreads/shared.ts index c83eb3b967e038..f2b98433145ba3 100644 --- a/src/mono/browser/runtime/pthreads/shared.ts +++ b/src/mono/browser/runtime/pthreads/shared.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import type { GCHandle, MonoThreadMessage, PThreadInfo, PThreadPtr } from "../types/internal"; +import type {GCHandle, MonoThreadMessage, PThreadInfo, PThreadPtr} from "../types/internal"; -import { ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; -import { set_thread_prefix } from "../logging"; -import { bindings_init } from "../startup"; -import { forceDisposeProxies } from "../gc-handles"; -import { monoMessageSymbol, GCHandleNull, PThreadPtrNull, WorkerToMainMessageType } from "../types/internal"; +import {ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; +import {set_thread_prefix} from "../logging"; +import {bindings_init} from "../startup"; +import {forceDisposeProxies} from "../gc-handles"; +import {monoMessageSymbol, GCHandleNull, PThreadPtrNull, WorkerToMainMessageType} from "../types/internal"; // A duplicate in loader/assets.ts export const worker_empty_prefix = " - "; @@ -24,7 +24,7 @@ const monoThreadInfoPartial: Partial = { }; export const monoThreadInfo: PThreadInfo = monoThreadInfoPartial as PThreadInfo; -export function isMonoThreadMessage(x: unknown): x is MonoThreadMessage { +export function isMonoThreadMessage (x: unknown): x is MonoThreadMessage { if (typeof (x) !== "object" || x === null) { return false; } @@ -32,7 +32,7 @@ export function isMonoThreadMessage(x: unknown): x is MonoThreadMessage { return typeof (xmsg.type) === "string" && typeof (xmsg.cmd) === "string"; } -export function mono_wasm_install_js_worker_interop(context_gc_handle: GCHandle): void { +export function mono_wasm_install_js_worker_interop (context_gc_handle: GCHandle): void { if (!WasmEnableThreads) return; bindings_init(); mono_assert(!runtimeHelpers.proxyGCHandle, "JS interop should not be already installed on this worker."); @@ -52,7 +52,7 @@ export function mono_wasm_install_js_worker_interop(context_gc_handle: GCHandle) } } -export function mono_wasm_uninstall_js_worker_interop(): void { +export function mono_wasm_uninstall_js_worker_interop (): void { if (!WasmEnableThreads) return; mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "JS interop is not installed on this worker."); mono_assert(runtimeHelpers.proxyGCHandle, "JSSynchronizationContext is not installed on this worker."); @@ -66,7 +66,7 @@ export function mono_wasm_uninstall_js_worker_interop(): void { } // this is just for Debug build of the runtime, making it easier to debug worker threads -export function update_thread_info(): void { +export function update_thread_info (): void { if (!WasmEnableThreads) return; const threadType = !monoThreadInfo.isRegistered ? "emsc" : monoThreadInfo.isUI ? "-UI-" @@ -99,24 +99,23 @@ export function update_thread_info(): void { const infoJson = JSON.stringify(monoThreadInfo, null, 2); const body = `const monoThreadInfo=${infoJson};\r\nconsole.log(monoThreadInfo);`; (globalThis as any).monoThreadInfoFn = new Function(body + "\r\n" + url); - } - catch (ex) { + } catch (ex) { runtimeHelpers.cspPolicy = true; } } } -export function mono_wasm_pthread_ptr(): PThreadPtr { +export function mono_wasm_pthread_ptr (): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_pthread_self"](); } -export function mono_wasm_main_thread_ptr(): PThreadPtr { +export function mono_wasm_main_thread_ptr (): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_emscripten_main_runtime_thread_id"](); } -export function postMessageToMain(message: MonoWorkerToMainMessage, transfer?: Transferable[]) { +export function postMessageToMain (message: MonoWorkerToMainMessage, transfer?: Transferable[]) { self.postMessage({ [monoMessageSymbol]: message }, transfer ? transfer : []); diff --git a/src/mono/browser/runtime/pthreads/ui-thread.ts b/src/mono/browser/runtime/pthreads/ui-thread.ts index 9838615cd21636..5102672737d82d 100644 --- a/src/mono/browser/runtime/pthreads/ui-thread.ts +++ b/src/mono/browser/runtime/pthreads/ui-thread.ts @@ -5,24 +5,24 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; import { } from "../globals"; -import { mono_log_debug, mono_log_warn } from "../logging"; -import { MonoWorkerToMainMessage, monoThreadInfo, mono_wasm_pthread_ptr, update_thread_info, worker_empty_prefix } from "./shared"; -import { Module, ENVIRONMENT_IS_WORKER, createPromiseController, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; -import { PThreadLibrary, MainToWorkerMessageType, MonoThreadMessage, PThreadInfo, PThreadPtr, PThreadPtrNull, PThreadWorker, PromiseAndController, PromiseController, Thread, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal"; -import { mono_log_error, mono_log_info } from "../logging"; -import { threads_c_functions as cwraps } from "../cwraps"; +import {mono_log_debug, mono_log_warn} from "../logging"; +import {MonoWorkerToMainMessage, monoThreadInfo, mono_wasm_pthread_ptr, update_thread_info, worker_empty_prefix} from "./shared"; +import {Module, ENVIRONMENT_IS_WORKER, createPromiseController, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; +import {PThreadLibrary, MainToWorkerMessageType, MonoThreadMessage, PThreadInfo, PThreadPtr, PThreadPtrNull, PThreadWorker, PromiseAndController, PromiseController, Thread, WorkerToMainMessageType, monoMessageSymbol} from "../types/internal"; +import {mono_log_error, mono_log_info} from "../logging"; +import {threads_c_functions as cwraps} from "../cwraps"; const threadPromises: Map[]> = new Map(); class ThreadImpl implements Thread { - constructor(readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } - postMessageToWorker(message: T): void { + constructor (readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } + postMessageToWorker (message: T): void { this.port.postMessage(message); } } /// wait until the thread with the given id has set up a message port to the runtime -export function waitForThread(pthreadPtr: PThreadPtr): Promise { +export function waitForThread (pthreadPtr: PThreadPtr): Promise { if (!WasmEnableThreads) return null as any; mono_assert(!ENVIRONMENT_IS_WORKER, "waitForThread should only be called from the UI thread"); const worker = getWorker(pthreadPtr); @@ -39,7 +39,7 @@ export function waitForThread(pthreadPtr: PThreadPtr): Promise { return promiseAndController.promise; } -export function resolveThreadPromises(pthreadPtr: PThreadPtr, thread?: Thread): void { +export function resolveThreadPromises (pthreadPtr: PThreadPtr, thread?: Thread): void { if (!WasmEnableThreads) return; const arr = threadPromises.get(pthreadPtr); if (arr !== undefined) { @@ -55,7 +55,7 @@ export function resolveThreadPromises(pthreadPtr: PThreadPtr, thread?: Thread): } // handler that runs in the main thread when a message is received from a pthread worker -function monoWorkerMessageHandler(worker: PThreadWorker, ev: MessageEvent): void { +function monoWorkerMessageHandler (worker: PThreadWorker, ev: MessageEvent): void { if (!WasmEnableThreads) return; let pthreadId: PThreadPtr; // this is emscripten message @@ -123,7 +123,7 @@ let pendingWorkerLoad: PromiseAndController | undefined; /// Called by Emscripten internals on the browser thread when a new pthread worker is created and added to the pthread worker pool. /// At this point the worker doesn't have any pthread assigned to it, yet. -export function onWorkerLoadInitiated(worker: PThreadWorker, loaded: Promise): void { +export function onWorkerLoadInitiated (worker: PThreadWorker, loaded: Promise): void { if (!WasmEnableThreads) return; worker.addEventListener("message", (ev) => monoWorkerMessageHandler(worker, ev)); if (pendingWorkerLoad == undefined) { @@ -138,7 +138,7 @@ export function onWorkerLoadInitiated(worker: PThreadWorker, loaded: Promise { +export function thread_available (): Promise { if (!WasmEnableThreads) return null as any; if (pendingWorkerLoad == undefined) { return Promise.resolve(); @@ -146,7 +146,7 @@ export function thread_available(): Promise { return pendingWorkerLoad.promise; } -export function populateEmscriptenPool(): void { +export function populateEmscriptenPool (): void { if (!WasmEnableThreads) return; const unused = getUnusedWorkerPool(); for (const worker of loaderHelpers.loadingWorkers) { @@ -155,7 +155,7 @@ export function populateEmscriptenPool(): void { loaderHelpers.loadingWorkers = []; } -export async function mono_wasm_init_threads() { +export async function mono_wasm_init_threads () { if (!WasmEnableThreads) return; // setup the UI thread @@ -175,17 +175,17 @@ export async function mono_wasm_init_threads() { } // when we create threads with browser event loop, it's not able to be joined by mono's thread join during shutdown and blocks process exit -export function cancelThreads() { +export function cancelThreads () { if (!WasmEnableThreads) return; const workers: PThreadWorker[] = getRunningWorkers(); for (const worker of workers) { if (worker.info.isExternalEventLoop) { - worker.postMessage({ cmd: "cancel" }); + worker.postMessage({cmd: "cancel"}); } } } -export function mono_wasm_dump_threads(): void { +export function mono_wasm_dump_threads (): void { if (!WasmEnableThreads) return; mono_log_info("Dumping web worker info as seen by UI thread, it could be stale: "); const emptyInfo: PThreadInfo = { @@ -219,7 +219,7 @@ export function mono_wasm_dump_threads(): void { }); } -export function init_finalizer_thread() { +export function init_finalizer_thread () { // we don't need it immediately, so we can wait a bit, to keep CPU working on normal startup setTimeout(() => { try { @@ -228,15 +228,14 @@ export function init_finalizer_thread() { } else { mono_log_debug("init_finalizer_thread skipped"); } - } - catch (err) { + } catch (err) { mono_log_error("init_finalizer_thread() failed", err); loaderHelpers.mono_exit(1, err); } }, loaderHelpers.config.finalizerThreadStartDelayMs); } -export function replaceEmscriptenPThreadUI(modulePThread: PThreadLibrary): void { +export function replaceEmscriptenPThreadUI (modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalLoadWasmModuleToWorker = modulePThread.loadWasmModuleToWorker; @@ -287,12 +286,12 @@ export function replaceEmscriptenPThreadUI(modulePThread: PThreadLibrary): void } let availableThreadCount = 0; -export function is_thread_available() { +export function is_thread_available () { if (!WasmEnableThreads) return true; return availableThreadCount > 0; } -function getNewWorker(modulePThread: PThreadLibrary): PThreadWorker { +function getNewWorker (modulePThread: PThreadLibrary): PThreadWorker { if (!WasmEnableThreads) return null as any; if (modulePThread.unusedWorkers.length == 0) { @@ -323,7 +322,7 @@ function getNewWorker(modulePThread: PThreadLibrary): PThreadWorker { } /// We replace Module["PThreads"].allocateUnusedWorker with this version that knows about assets -function allocateUnusedWorker(): PThreadWorker { +function allocateUnusedWorker (): PThreadWorker { if (!WasmEnableThreads) return null as any; const asset = loaderHelpers.resolve_single_asset_path("js-module-threads"); @@ -346,22 +345,22 @@ function allocateUnusedWorker(): PThreadWorker { return worker; } -export function getWorker(pthreadPtr: PThreadPtr): PThreadWorker | undefined { +export function getWorker (pthreadPtr: PThreadPtr): PThreadWorker | undefined { return getModulePThread().pthreads[pthreadPtr as any]; } -export function getUnusedWorkerPool(): PThreadWorker[] { +export function getUnusedWorkerPool (): PThreadWorker[] { return getModulePThread().unusedWorkers; } -export function getRunningWorkers(): PThreadWorker[] { +export function getRunningWorkers (): PThreadWorker[] { return getModulePThread().runningWorkers; } -export function loadWasmModuleToWorker(worker: PThreadWorker): Promise { +export function loadWasmModuleToWorker (worker: PThreadWorker): Promise { return getModulePThread().loadWasmModuleToWorker(worker); } -export function getModulePThread(): PThreadLibrary { +export function getModulePThread (): PThreadLibrary { return (Module).PThread as PThreadLibrary; } diff --git a/src/mono/browser/runtime/pthreads/worker-events.ts b/src/mono/browser/runtime/pthreads/worker-events.ts index 709e1980d82f58..d3df55677d3272 100644 --- a/src/mono/browser/runtime/pthreads/worker-events.ts +++ b/src/mono/browser/runtime/pthreads/worker-events.ts @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import { PThreadSelf } from "./shared"; +import {PThreadSelf} from "./shared"; export const dotnetPthreadCreated = "dotnet:pthread:created" as const; export const dotnetPthreadAttached = "dotnet:pthread:attached" as const; @@ -30,10 +30,12 @@ export interface WorkerThreadEventTarget extends EventTarget { let WorkerThreadEventClassConstructor: new (type: keyof WorkerThreadEventMap, pthread_self: PThreadSelf) => WorkerThreadEvent; export const makeWorkerThreadEvent: (type: keyof WorkerThreadEventMap, pthread_self: PThreadSelf) => WorkerThreadEvent = !WasmEnableThreads - ? (() => { throw new Error("threads support disabled"); }) + ? (() => { + throw new Error("threads support disabled"); + }) : ((type: keyof WorkerThreadEventMap, pthread_self: PThreadSelf) => { if (!WorkerThreadEventClassConstructor) WorkerThreadEventClassConstructor = class WorkerThreadEventImpl extends Event implements WorkerThreadEvent { - constructor(type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { + constructor (type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { super(type); } }; diff --git a/src/mono/browser/runtime/pthreads/worker-thread.ts b/src/mono/browser/runtime/pthreads/worker-thread.ts index 5631c2475e6528..6f6b4c165e16f5 100644 --- a/src/mono/browser/runtime/pthreads/worker-thread.ts +++ b/src/mono/browser/runtime/pthreads/worker-thread.ts @@ -5,20 +5,20 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; -import { PThreadSelf, monoThreadInfo, mono_wasm_pthread_ptr, postMessageToMain, update_thread_info } from "./shared"; -import { PThreadLibrary, MonoThreadMessage, PThreadInfo, PThreadPtr, WorkerToMainMessageType } from "../types/internal"; +import {ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; +import {PThreadSelf, monoThreadInfo, mono_wasm_pthread_ptr, postMessageToMain, update_thread_info} from "./shared"; +import {PThreadLibrary, MonoThreadMessage, PThreadInfo, PThreadPtr, WorkerToMainMessageType} from "../types/internal"; import { makeWorkerThreadEvent, dotnetPthreadCreated, dotnetPthreadAttached, WorkerThreadEventTarget } from "./worker-events"; -import { postRunWorker, preRunWorker } from "../startup"; -import { mono_log_debug, mono_log_error } from "../logging"; -import { CharPtr } from "../types/emscripten"; -import { utf8ToString } from "../strings"; -import { forceThreadMemoryViewRefresh } from "../memory"; +import {postRunWorker, preRunWorker} from "../startup"; +import {mono_log_debug, mono_log_error} from "../logging"; +import {CharPtr} from "../types/emscripten"; +import {utf8ToString} from "../strings"; +import {forceThreadMemoryViewRefresh} from "../memory"; // re-export some of the events types export { @@ -32,17 +32,17 @@ export { export let pthread_self: PThreadSelf = null as any as PThreadSelf; class WorkerSelf implements PThreadSelf { - constructor(public info: PThreadInfo, public portToBrowser: MessagePort) { + constructor (public info: PThreadInfo, public portToBrowser: MessagePort) { } - postMessageToBrowser(message: MonoThreadMessage, transfer?: Transferable[]) { + postMessageToBrowser (message: MonoThreadMessage, transfer?: Transferable[]) { if (transfer) { this.portToBrowser.postMessage(message, transfer); } else { this.portToBrowser.postMessage(message); } } - addEventListenerFromBrowser(listener: (event: MessageEvent) => void) { + addEventListenerFromBrowser (listener: (event: MessageEvent) => void) { this.portToBrowser.addEventListener("message", listener); } } @@ -56,7 +56,7 @@ class WorkerSelf implements PThreadSelf { export let currentWorkerThreadEvents: WorkerThreadEventTarget = undefined as any; // this is very very early in the worker startup -export function initWorkerThreadEvents() { +export function initWorkerThreadEvents () { // treeshake if threads are disabled currentWorkerThreadEvents = WasmEnableThreads ? new globalThis.EventTarget() : null as any as WorkerThreadEventTarget; Object.assign(monoThreadInfo, runtimeHelpers.monoThreadInfo); @@ -64,11 +64,11 @@ export function initWorkerThreadEvents() { // this is the message handler for the worker that receives messages from the main thread // extend this with new cases as needed -function monoDedicatedChannelMessageFromMainToWorker(event: MessageEvent): void { +function monoDedicatedChannelMessageFromMainToWorker (event: MessageEvent): void { mono_log_debug("got message from main on the dedicated channel", event.data); } -export function on_emscripten_thread_init(pthread_ptr: PThreadPtr) { +export function on_emscripten_thread_init (pthread_ptr: PThreadPtr) { runtimeHelpers.currentThreadTID = monoThreadInfo.pthreadId = pthread_ptr; forceThreadMemoryViewRefresh(); } @@ -76,7 +76,7 @@ export function on_emscripten_thread_init(pthread_ptr: PThreadPtr) { /// Called by emscripten when a pthread is setup to run on a worker. Can be called multiple times /// for the same webworker, since emscripten can reuse workers. /// This is an implementation detail, that shouldn't be used directly. -export function mono_wasm_pthread_on_pthread_created(): void { +export function mono_wasm_pthread_on_pthread_created (): void { if (!WasmEnableThreads) return; try { forceThreadMemoryViewRefresh(); @@ -110,8 +110,7 @@ export function mono_wasm_pthread_on_pthread_created(): void { info: monoThreadInfo, port: mainPort, }, [mainPort]); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_pthread_on_pthread_created () failed", err); loaderHelpers.mono_exit(1, err); throw err; @@ -119,7 +118,7 @@ export function mono_wasm_pthread_on_pthread_created(): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes registered to the mono runtime. -export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_registered (pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when registering"); @@ -130,8 +129,7 @@ export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): info: monoThreadInfo, }); preRunWorker(); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_pthread_on_pthread_registered () failed", err); loaderHelpers.mono_exit(1, err); throw err; @@ -139,7 +137,7 @@ export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): } /// Called in the worker thread (not main thread) from mono when a pthread becomes attached to the mono runtime. -export function mono_wasm_pthread_on_pthread_attached(pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { +export function mono_wasm_pthread_on_pthread_attached (pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when attaching"); @@ -162,15 +160,14 @@ export function mono_wasm_pthread_on_pthread_attached(pthread_id: PThreadPtr, th monoCmd: WorkerToMainMessageType.monoAttached, info: monoThreadInfo, }); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_pthread_on_pthread_attached () failed", err); loaderHelpers.mono_exit(1, err); throw err; } } -export function mono_wasm_pthread_set_name(name: CharPtr): void { +export function mono_wasm_pthread_set_name (name: CharPtr): void { if (!WasmEnableThreads) return; if (!ENVIRONMENT_IS_PTHREAD) return; monoThreadInfo.threadName = utf8ToString(name); @@ -182,7 +179,7 @@ export function mono_wasm_pthread_set_name(name: CharPtr): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes detached from the mono runtime. -export function mono_wasm_pthread_on_pthread_unregistered(pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_unregistered (pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(pthread_id === monoThreadInfo.pthreadId, "expected pthread_id to match when un-registering"); @@ -195,15 +192,14 @@ export function mono_wasm_pthread_on_pthread_unregistered(pthread_id: PThreadPtr monoCmd: WorkerToMainMessageType.monoUnRegistered, info: monoThreadInfo, }); - } - catch (err) { + } catch (err) { mono_log_error("mono_wasm_pthread_on_pthread_unregistered () failed", err); loaderHelpers.mono_exit(1, err); throw err; } } -export function replaceEmscriptenTLSInit(modulePThread: PThreadLibrary): void { +export function replaceEmscriptenTLSInit (modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalThreadInitTLS = modulePThread.threadInitTLS; @@ -214,9 +210,9 @@ export function replaceEmscriptenTLSInit(modulePThread: PThreadLibrary): void { }; } -export function replaceEmscriptenPThreadInit(): void { +export function replaceEmscriptenPThreadInit (): void { const original_emscripten_thread_init = Module["__emscripten_thread_init"]; - function emscripten_thread_init_wrapper(pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { + function emscripten_thread_init_wrapper (pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { on_emscripten_thread_init(pthread_ptr); original_emscripten_thread_init(pthread_ptr, isMainBrowserThread, isMainRuntimeThread, canBlock); // re-install self diff --git a/src/mono/browser/runtime/queue.ts b/src/mono/browser/runtime/queue.ts index b31b4790e86cf9..a6ccd00615ca9e 100644 --- a/src/mono/browser/runtime/queue.ts +++ b/src/mono/browser/runtime/queue.ts @@ -6,19 +6,19 @@ export class Queue { private queue: T[]; private offset: number; - constructor() { + constructor () { this.queue = []; this.offset = 0; } // initialise the queue and offset // Returns the length of the queue. - getLength(): number { + getLength (): number { return (this.queue.length - this.offset); } // Returns true if the queue is empty, and false otherwise. - isEmpty(): boolean { + isEmpty (): boolean { return (this.queue.length == 0); } @@ -26,14 +26,14 @@ export class Queue { * * item - the item to enqueue */ - enqueue(item: T): void { + enqueue (item: T): void { this.queue.push(item); } /* Dequeues an item and returns it. If the queue is empty, the value * 'undefined' is returned. */ - dequeue(): T | undefined { + dequeue (): T | undefined { // if the queue is empty, return immediately if (this.queue.length === 0) return undefined; @@ -57,14 +57,14 @@ export class Queue { /* Returns the item at the front of the queue (without dequeuing it). If the * queue is empty then undefined is returned. */ - peek(): T | undefined { + peek (): T | undefined { return (this.queue.length > 0 ? this.queue[this.offset] : undefined); } - drain(onEach: (item: T) => void): void { + drain (onEach: (item: T) => void): void { while (this.getLength()) { const item = this.dequeue()!; onEach(item); } } -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/rollup.config.js b/src/mono/browser/runtime/rollup.config.js index 519879f7d8438e..1a8397afa44ea7 100644 --- a/src/mono/browser/runtime/rollup.config.js +++ b/src/mono/browser/runtime/rollup.config.js @@ -1,14 +1,14 @@ -import { defineConfig } from "rollup"; +import {defineConfig} from "rollup"; import typescript from "@rollup/plugin-typescript"; import terser from "@rollup/plugin-terser"; import virtual from "@rollup/plugin-virtual"; -import { nodeResolve } from "@rollup/plugin-node-resolve"; -import { readFile, writeFile, mkdir } from "fs/promises"; +import {nodeResolve} from "@rollup/plugin-node-resolve"; +import {readFile, writeFile, mkdir} from "fs/promises"; import * as fs from "fs"; import * as path from "path"; -import { createHash } from "crypto"; +import {createHash} from "crypto"; import dts from "rollup-plugin-dts"; -import { createFilter } from "@rollup/pluginutils"; +import {createFilter} from "@rollup/pluginutils"; import fast_glob from "fast-glob"; import gitCommitInfo from "git-commit-info"; import MagicString from "magic-string"; @@ -107,7 +107,7 @@ const envConstants = { }; const locationCache = {}; -function sourcemapPathTransform(relativeSourcePath, sourcemapPath) { +function sourcemapPathTransform (relativeSourcePath, sourcemapPath) { let res = locationCache[relativeSourcePath]; if (res === undefined) { if (!isContinuousIntegrationBuild) { @@ -125,7 +125,7 @@ function sourcemapPathTransform(relativeSourcePath, sourcemapPath) { return res; } -function consts(dict) { +function consts (dict) { // implement rollup-plugin-const in terms of @rollup/plugin-virtual // It's basically the same thing except "consts" names all its modules with a "consts:" prefix, // and the virtual module always exports a single default binding (the const value). @@ -245,7 +245,7 @@ if (isDebug) { } /* Web Workers */ -function makeWorkerConfig(workerName, workerInputSourcePath) { +function makeWorkerConfig (workerName, workerInputSourcePath) { const workerConfig = { input: workerInputSourcePath, output: [ @@ -273,14 +273,14 @@ const allConfigs = [ .concat(diagnosticMockTypesConfig ? [diagnosticMockTypesConfig] : []); export default defineConfig(allConfigs); -function evalCodePlugin() { +function evalCodePlugin () { return { name: "evalCode", generateBundle: evalCode }; } -async function evalCode(options, bundle) { +async function evalCode (options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -296,7 +296,7 @@ async function evalCode(options, bundle) { // this would create .sha256 file next to the output file, so that we do not touch datetime of the file if it's same -> faster incremental build. -function writeOnChangePlugin() { +function writeOnChangePlugin () { return { name: "writeOnChange", generateBundle: writeWhenChanged @@ -304,7 +304,7 @@ function writeOnChangePlugin() { } // force always unix line ending -function alwaysLF() { +function alwaysLF () { return { name: "writeOnChange", generateBundle: (options, bundle) => { @@ -316,7 +316,7 @@ function alwaysLF() { }; } -async function writeWhenChanged(options, bundle) { +async function writeWhenChanged (options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -329,13 +329,13 @@ async function writeWhenChanged(options, bundle) { let isOutputChanged = true; if (oldHashExists && oldFileExists) { - const oldHash = await readFile(hashFileName, { encoding: "ascii" }); + const oldHash = await readFile(hashFileName, {encoding: "ascii"}); isOutputChanged = oldHash !== newHash; } if (isOutputChanged) { const dir = path.dirname(options.file); if (!await checkFileExists(dir)) { - await mkdir(dir, { recursive: true }); + await mkdir(dir, {recursive: true}); } await writeFile(hashFileName, newHash); } else { @@ -347,34 +347,34 @@ async function writeWhenChanged(options, bundle) { } } -function checkFileExists(file) { +function checkFileExists (file) { return fs.promises.access(file, fs.constants.F_OK) .then(() => true) .catch(() => false); } -function regexCheck(checks = []) { +function regexCheck (checks = []) { const filter = createFilter("**/*.ts"); return { name: "regexCheck", - renderChunk(code, chunk) { + renderChunk (code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeCheck(this, code, id); }, - transform(code, id) { + transform (code, id) { if (!filter(id)) return null; return executeCheck(this, code, id); } }; - function executeCheck(self, code, id) { + function executeCheck (self, code, id) { // self.warn("executeCheck" + id); for (const rep of checks) { - const { pattern, failure } = rep; + const {pattern, failure} = rep; const match = pattern.test(code); if (match) { self.error(failure + " " + id); @@ -387,40 +387,40 @@ function regexCheck(checks = []) { } -function regexReplace(replacements = []) { +function regexReplace (replacements = []) { const filter = createFilter("**/*.ts"); return { name: "regexReplace", - renderChunk(code, chunk) { + renderChunk (code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeReplacement(this, code, id); }, - transform(code, id) { + transform (code, id) { if (!filter(id)) return null; return executeReplacement(this, code, id); } }; - function executeReplacement(_, code, id) { + function executeReplacement (_, code, id) { const magicString = new MagicString(code); if (!codeHasReplacements(code, id, magicString)) { return null; } - const result = { code: magicString.toString() }; - result.map = magicString.generateMap({ hires: true }); + const result = {code: magicString.toString()}; + result.map = magicString.generateMap({hires: true}); return result; } - function codeHasReplacements(code, id, magicString) { + function codeHasReplacements (code, id, magicString) { let result = false; let match; for (const rep of replacements) { - const { pattern, replacement } = rep; + const {pattern, replacement} = rep; const rx = new RegExp(pattern, "gm"); while ((match = rx.exec(code))) { result = true; @@ -441,9 +441,9 @@ function regexReplace(replacements = []) { // Returns an array of objects {"workerName": "foo", "path": "/path/dotnet-foo-worker.ts"} // // A file looks like a webworker toplevel input if it's `dotnet-{name}-worker.ts` or `.js` -function findWebWorkerInputs(basePath) { +function findWebWorkerInputs (basePath) { const glob = "dotnet-*-worker.[tj]s"; - const files = fast_glob.sync(glob, { cwd: basePath }); + const files = fast_glob.sync(glob, {cwd: basePath}); if (files.length == 0) { return []; } @@ -452,13 +452,13 @@ function findWebWorkerInputs(basePath) { for (const file of files) { const match = file.match(re); if (match) { - results.push({ "workerName": match[1], "path": path.join(basePath, file) }); + results.push({"workerName": match[1], "path": path.join(basePath, file)}); } } return results; } -function onwarn(warning) { +function onwarn (warning) { if (warning.code === "CIRCULAR_DEPENDENCY") { return; } diff --git a/src/mono/browser/runtime/roots.ts b/src/mono/browser/runtime/roots.ts index 24958a22e08458..c1d29d56ad92d9 100644 --- a/src/mono/browser/runtime/roots.ts +++ b/src/mono/browser/runtime/roots.ts @@ -4,11 +4,11 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import cwraps from "./cwraps"; -import { Module, mono_assert } from "./globals"; -import { VoidPtr, ManagedPointer, NativePointer } from "./types/emscripten"; -import { MonoObjectRef, MonoObjectRefNull, MonoObject, is_nullish, WasmRoot, WasmRootBuffer } from "./types/internal"; -import { _zero_region, localHeapViewU32 } from "./memory"; -import { gc_locked } from "./gc-lock"; +import {Module, mono_assert} from "./globals"; +import {VoidPtr, ManagedPointer, NativePointer} from "./types/emscripten"; +import {MonoObjectRef, MonoObjectRefNull, MonoObject, is_nullish, WasmRoot, WasmRootBuffer} from "./types/internal"; +import {_zero_region, localHeapViewU32} from "./memory"; +import {gc_locked} from "./gc-lock"; const maxScratchRoots = 8192; let _scratch_root_buffer: WasmRootBuffer | null = null; @@ -23,7 +23,7 @@ const _external_root_free_instances: WasmExternalRoot[] = []; * Once you are done using the root buffer, you must call its release() method. * For small numbers of roots, it is preferable to use the mono_wasm_new_root and mono_wasm_new_roots APIs instead. */ -export function mono_wasm_new_root_buffer(capacity: number, name?: string): WasmRootBuffer { +export function mono_wasm_new_root_buffer (capacity: number, name?: string): WasmRootBuffer { if (capacity <= 0) throw new Error("capacity >= 1"); @@ -43,7 +43,7 @@ export function mono_wasm_new_root_buffer(capacity: number, name?: string): Wasm * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. * Releasing this root will not de-allocate the root space. You still need to call .release(). */ -export function mono_wasm_new_external_root(address: VoidPtr | MonoObjectRef): WasmRoot { +export function mono_wasm_new_external_root (address: VoidPtr | MonoObjectRef): WasmRoot { let result: WasmExternalRoot; if (!address) @@ -66,7 +66,7 @@ export function mono_wasm_new_external_root(address: VoidP * The result object has get() and set(value) methods, along with a .value property. * When you are done using the root you must call its .release() method. */ -export function mono_wasm_new_root(value: T | undefined = undefined): WasmRoot { +export function mono_wasm_new_root (value: T | undefined = undefined): WasmRoot { let result: WasmRoot; if (_scratch_root_free_instances.length > 0) { @@ -96,7 +96,7 @@ export function mono_wasm_new_root(value: T | undefined = * mono_wasm_new_roots([a, b, ...]) returns an array of new roots initialized with each element. * Each root must be released with its release method, or using the mono_wasm_release_roots API. */ -export function mono_wasm_new_roots(count_or_values: number | T[]): WasmRoot[] { +export function mono_wasm_new_roots (count_or_values: number | T[]): WasmRoot[] { let result; if (Array.isArray(count_or_values)) { @@ -121,7 +121,7 @@ export function mono_wasm_new_roots(count_or_values: numbe * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ -export function mono_wasm_release_roots(...args: WasmRoot[]): void { +export function mono_wasm_release_roots (...args: WasmRoot[]): void { for (let i = 0; i < args.length; i++) { if (is_nullish(args[i])) continue; @@ -130,7 +130,7 @@ export function mono_wasm_release_roots(...args: WasmRoot[]): void { } } -function _mono_wasm_release_scratch_index(index: number) { +function _mono_wasm_release_scratch_index (index: number) { if (index === undefined) return; @@ -139,7 +139,7 @@ function _mono_wasm_release_scratch_index(index: number) { _scratch_root_free_indices_count++; } -function _mono_wasm_claim_scratch_index() { +function _mono_wasm_claim_scratch_index () { if (is_nullish(_scratch_root_buffer) || !_scratch_root_free_indices) { _scratch_root_buffer = mono_wasm_new_root_buffer(maxScratchRoots, "js roots"); @@ -165,7 +165,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { private __handle: number; private __ownsAllocation: boolean; - constructor(offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { + constructor (offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { const capacityBytes = capacity * 4; this.__offset = offset; @@ -177,21 +177,21 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__ownsAllocation = ownsAllocation; } - _throw_index_out_of_range(): void { + _throw_index_out_of_range (): void { throw new Error("index out of range"); } - _check_in_range(index: number): void { + _check_in_range (index: number): void { if ((index >= this.__count) || (index < 0)) this._throw_index_out_of_range(); } - get_address(index: number): MonoObjectRef { + get_address (index: number): MonoObjectRef { this._check_in_range(index); return this.__offset + (index * 4); } - get_address_32(index: number): number { + get_address_32 (index: number): number { this._check_in_range(index); return this.__offset32 + index; } @@ -199,38 +199,38 @@ export class WasmRootBufferImpl implements WasmRootBuffer { // NOTE: These functions do not use the helpers from memory.ts because WasmRoot.get and WasmRoot.set // are hot-spots when you profile any application that uses the bindings extensively. - get(index: number): ManagedPointer { + get (index: number): ManagedPointer { this._check_in_range(index); const offset = this.get_address_32(index); return localHeapViewU32()[offset]; } - set(index: number, value: ManagedPointer): ManagedPointer { + set (index: number, value: ManagedPointer): ManagedPointer { const address = this.get_address(index); cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); return value; } - copy_value_from_address(index: number, sourceAddress: MonoObjectRef): void { + copy_value_from_address (index: number, sourceAddress: MonoObjectRef): void { const destinationAddress = this.get_address(index); cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - _unsafe_get(index: number): number { + _unsafe_get (index: number): number { return localHeapViewU32()[this.__offset32 + index]; } - _unsafe_set(index: number, value: ManagedPointer | NativePointer): void { + _unsafe_set (index: number, value: ManagedPointer | NativePointer): void { const address = this.__offset + index; cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); } - clear(): void { + clear (): void { if (this.__offset) _zero_region(this.__offset, this.__count * 4); } - release(): void { + release (): void { if (this.__offset && this.__ownsAllocation) { mono_assert(!WasmEnableThreads || !gc_locked, "GC must not be locked when disposing a GC root"); cwraps.mono_wasm_deregister_root(this.__offset); @@ -241,7 +241,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__handle = (this.__offset) = this.__count = this.__offset32 = 0; } - toString(): string { + toString (): string { return `[root buffer @${this.get_address(0)}, size ${this.__count} ]`; } } @@ -250,76 +250,76 @@ class WasmJsOwnedRoot implements WasmRoot { private __buffer: WasmRootBuffer; private __index: number; - constructor(buffer: WasmRootBuffer, index: number) { + constructor (buffer: WasmRootBuffer, index: number) { this.__buffer = buffer;//TODO this.__index = index; } - get_address(): MonoObjectRef { + get_address (): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get_address_32(): number { + get_address_32 (): number { return this.__buffer.get_address_32(this.__index); } - get address(): MonoObjectRef { + get address (): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get(): T { + get (): T { const result = (this.__buffer)._unsafe_get(this.__index); return result; } - set(value: T): T { + set (value: T): T { const destinationAddress = this.__buffer.get_address(this.__index); cwraps.mono_wasm_write_managed_pointer_unsafe(destinationAddress, value); return value; } - copy_from(source: WasmRoot): void { + copy_from (source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to(destination: WasmRoot): void { + copy_to (destination: WasmRoot): void { const sourceAddress = this.address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address(source: MonoObjectRef): void { + copy_from_address (source: MonoObjectRef): void { const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address(destination: MonoObjectRef): void { + copy_to_address (destination: MonoObjectRef): void { const sourceAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value(): T { + get value (): T { return this.get(); } - set value(value: T) { + set value (value: T) { this.set(value); } - valueOf(): T { + valueOf (): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear(): void { + clear (): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC const address32 = this.__buffer.get_address_32(this.__index); localHeapViewU32()[address32] = 0; } - release(): void { + release (): void { if (!this.__buffer) throw new Error("No buffer"); @@ -334,7 +334,7 @@ class WasmJsOwnedRoot implements WasmRoot { } } - toString(): string { + toString (): string { return `[root @${this.address}]`; } } @@ -343,84 +343,84 @@ class WasmExternalRoot implements WasmRoot { private __external_address: MonoObjectRef = MonoObjectRefNull; private __external_address_32: number = 0; - constructor(address: NativePointer | ManagedPointer) { + constructor (address: NativePointer | ManagedPointer) { this._set_address(address); } - _set_address(address: NativePointer | ManagedPointer): void { + _set_address (address: NativePointer | ManagedPointer): void { this.__external_address = address; this.__external_address_32 = address >>> 2; } - get address(): MonoObjectRef { + get address (): MonoObjectRef { return this.__external_address; } - get_address(): MonoObjectRef { + get_address (): MonoObjectRef { return this.__external_address; } - get_address_32(): number { + get_address_32 (): number { return this.__external_address_32; } - get(): T { + get (): T { const result = localHeapViewU32()[this.__external_address_32]; return result; } - set(value: T): T { + set (value: T): T { cwraps.mono_wasm_write_managed_pointer_unsafe(this.__external_address, value); return value; } - copy_from(source: WasmRoot): void { + copy_from (source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to(destination: WasmRoot): void { + copy_to (destination: WasmRoot): void { const sourceAddress = this.__external_address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address(source: MonoObjectRef): void { + copy_from_address (source: MonoObjectRef): void { const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address(destination: MonoObjectRef): void { + copy_to_address (destination: MonoObjectRef): void { const sourceAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value(): T { + get value (): T { return this.get(); } - set value(value: T) { + set value (value: T) { this.set(value); } - valueOf(): T { + valueOf (): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear(): void { + clear (): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC localHeapViewU32()[this.__external_address >>> 2] = 0; } - release(): void { + release (): void { const maxPooledInstances = 128; if (_external_root_free_instances.length < maxPooledInstances) _external_root_free_instances.push(this); } - toString(): string { + toString (): string { return `[external root @${this.address}]`; } } diff --git a/src/mono/browser/runtime/run.ts b/src/mono/browser/runtime/run.ts index e35c6dc833aecd..e2fdf8f5e20920 100644 --- a/src/mono/browser/runtime/run.ts +++ b/src/mono/browser/runtime/run.ts @@ -3,18 +3,18 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; -import { mono_wasm_wait_for_debugger } from "./debug"; -import { mono_wasm_set_main_args } from "./startup"; +import {ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; +import {mono_wasm_wait_for_debugger} from "./debug"; +import {mono_wasm_set_main_args} from "./startup"; import cwraps from "./cwraps"; -import { mono_log_info } from "./logging"; -import { cancelThreads } from "./pthreads"; -import { call_entry_point } from "./managed-exports"; +import {mono_log_info} from "./logging"; +import {cancelThreads} from "./pthreads"; +import {call_entry_point} from "./managed-exports"; /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main_and_exit(main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main_and_exit (main_assembly_name?: string, args?: string[]): Promise { try { const result = await mono_run_main(main_assembly_name, args); loaderHelpers.mono_exit(result); @@ -22,8 +22,7 @@ export async function mono_run_main_and_exit(main_assembly_name?: string, args?: } catch (error: any) { try { loaderHelpers.mono_exit(1, error); - } - catch (e) { + } catch (e) { // ignore } if (error && typeof error.status === "number") { @@ -36,7 +35,7 @@ export async function mono_run_main_and_exit(main_assembly_name?: string, args?: /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main(main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main (main_assembly_name?: string, args?: string[]): Promise { if (main_assembly_name === undefined || main_assembly_name === null || main_assembly_name === "") { main_assembly_name = loaderHelpers.config.mainAssemblyName; mono_assert(main_assembly_name, "Null or empty config.mainAssemblyName"); @@ -77,17 +76,17 @@ export async function mono_run_main(main_assembly_name?: string, args?: string[] -export function nativeExit(code: number) { +export function nativeExit (code: number) { if (WasmEnableThreads) { cancelThreads(); } cwraps.mono_wasm_exit(code); } -export function nativeAbort(reason: any) { +export function nativeAbort (reason: any) { loaderHelpers.exitReason = reason; if (!loaderHelpers.is_exited()) { cwraps.mono_wasm_abort(); } throw reason; -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/satelliteAssemblies.ts b/src/mono/browser/runtime/satelliteAssemblies.ts index 4dcc17407b1e4e..d2030e24abe1c0 100644 --- a/src/mono/browser/runtime/satelliteAssemblies.ts +++ b/src/mono/browser/runtime/satelliteAssemblies.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { loaderHelpers } from "./globals"; -import { load_satellite_assembly } from "./managed-exports"; -import { AssetEntry } from "./types"; +import {loaderHelpers} from "./globals"; +import {load_satellite_assembly} from "./managed-exports"; +import {AssetEntry} from "./types"; -export async function loadSatelliteAssemblies(culturesToLoad: string[]): Promise { +export async function loadSatelliteAssemblies (culturesToLoad: string[]): Promise { const satelliteResources = loaderHelpers.config.resources!.satelliteResources; if (!satelliteResources) { return; @@ -33,4 +33,4 @@ export async function loadSatelliteAssemblies(culturesToLoad: string[]): Promise const bytes = await bytesPromise; load_satellite_assembly(new Uint8Array(bytes)); })); -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/scheduling.ts b/src/mono/browser/runtime/scheduling.ts index c9cbf205d42d41..d0b3820358a17f 100644 --- a/src/mono/browser/runtime/scheduling.ts +++ b/src/mono/browser/runtime/scheduling.ts @@ -4,14 +4,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import cwraps from "./cwraps"; -import { ENVIRONMENT_IS_WORKER, Module, loaderHelpers } from "./globals"; -import { forceThreadMemoryViewRefresh } from "./memory"; -import { is_thread_available } from "./pthreads"; +import {ENVIRONMENT_IS_WORKER, Module, loaderHelpers} from "./globals"; +import {forceThreadMemoryViewRefresh} from "./memory"; +import {is_thread_available} from "./pthreads"; let spread_timers_maximum = 0; let pump_count = 0; -export function prevent_timer_throttling(): void { +export function prevent_timer_throttling (): void { if (!loaderHelpers.isChromium) { return; } @@ -29,7 +29,7 @@ export function prevent_timer_throttling(): void { spread_timers_maximum = desired_reach_time; } -function prevent_timer_throttling_tick() { +function prevent_timer_throttling_tick () { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -42,7 +42,7 @@ function prevent_timer_throttling_tick() { mono_background_exec_until_done(); } -function mono_background_exec_until_done() { +function mono_background_exec_until_done () { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -56,10 +56,10 @@ function mono_background_exec_until_done() { } } -export function schedule_background_exec(): void { +export function schedule_background_exec (): void { ++pump_count; let max_postpone_count = 10; - function postpone_schedule_background() { + function postpone_schedule_background () { if (max_postpone_count < 0 || is_thread_available()) { Module.safeSetTimeout(mono_background_exec_until_done, 0); } else { @@ -71,26 +71,25 @@ export function schedule_background_exec(): void { if (WasmEnableThreads && !ENVIRONMENT_IS_WORKER) { // give threads chance to load before we run more synchronous code on UI thread postpone_schedule_background(); - } - else { + } else { Module.safeSetTimeout(mono_background_exec_until_done, 0); } } let lastScheduledTimeoutId: any = undefined; -export function mono_wasm_schedule_timer(shortestDueTimeMs: number): void { +export function mono_wasm_schedule_timer (shortestDueTimeMs: number): void { if (lastScheduledTimeoutId) { globalThis.clearTimeout(lastScheduledTimeoutId); lastScheduledTimeoutId = undefined; - // NOTE: Multi-threaded Module.safeSetTimeout() does the runtimeKeepalivePush() - // and non-Multi-threaded Module.safeSetTimeout does not runtimeKeepalivePush() + // NOTE: Multi-threaded Module.safeSetTimeout() does the runtimeKeepalivePush() + // and non-Multi-threaded Module.safeSetTimeout does not runtimeKeepalivePush() // but clearTimeout does not runtimeKeepalivePop() so we need to do it here in MT only. if (WasmEnableThreads) Module.runtimeKeepalivePop(); } lastScheduledTimeoutId = Module.safeSetTimeout(mono_wasm_schedule_timer_tick, shortestDueTimeMs); } -function mono_wasm_schedule_timer_tick() { +function mono_wasm_schedule_timer_tick () { Module.maybeExit(); if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); diff --git a/src/mono/browser/runtime/startup.ts b/src/mono/browser/runtime/startup.ts index 1ae17e43edf191..69176b29602795 100644 --- a/src/mono/browser/runtime/startup.ts +++ b/src/mono/browser/runtime/startup.ts @@ -4,44 +4,44 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import { DotnetModuleInternal, CharPtrNull, MainThreadingMode } from "./types/internal"; -import { exportedRuntimeAPI, INTERNAL, loaderHelpers, Module, runtimeHelpers, createPromiseController, mono_assert } from "./globals"; -import cwraps, { init_c_exports, threads_c_functions as tcwraps } from "./cwraps"; -import { mono_wasm_raise_debug_event, mono_wasm_runtime_ready } from "./debug"; -import { toBase64StringImpl } from "./base64"; -import { mono_wasm_init_aot_profiler, mono_wasm_init_browser_profiler } from "./profiler"; -import { initialize_marshalers_to_cs } from "./marshal-to-cs"; -import { initialize_marshalers_to_js } from "./marshal-to-js"; -import { init_polyfills_async } from "./polyfills"; -import { strings_init, utf8ToString } from "./strings"; -import { init_managed_exports, install_main_synchronization_context } from "./managed-exports"; -import { cwraps_internal } from "./exports-internal"; -import { CharPtr, InstantiateWasmCallBack, InstantiateWasmSuccessCallback } from "./types/emscripten"; -import { wait_for_all_assets } from "./assets"; -import { replace_linker_placeholders } from "./exports-binding"; -import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; -import { interp_pgo_load_data, interp_pgo_save_data } from "./interp-pgo"; -import { mono_log_debug, mono_log_error, mono_log_info, mono_log_warn } from "./logging"; +import {DotnetModuleInternal, CharPtrNull, MainThreadingMode} from "./types/internal"; +import {exportedRuntimeAPI, INTERNAL, loaderHelpers, Module, runtimeHelpers, createPromiseController, mono_assert} from "./globals"; +import cwraps, {init_c_exports, threads_c_functions as tcwraps} from "./cwraps"; +import {mono_wasm_raise_debug_event, mono_wasm_runtime_ready} from "./debug"; +import {toBase64StringImpl} from "./base64"; +import {mono_wasm_init_aot_profiler, mono_wasm_init_browser_profiler} from "./profiler"; +import {initialize_marshalers_to_cs} from "./marshal-to-cs"; +import {initialize_marshalers_to_js} from "./marshal-to-js"; +import {init_polyfills_async} from "./polyfills"; +import {strings_init, utf8ToString} from "./strings"; +import {init_managed_exports, install_main_synchronization_context} from "./managed-exports"; +import {cwraps_internal} from "./exports-internal"; +import {CharPtr, InstantiateWasmCallBack, InstantiateWasmSuccessCallback} from "./types/emscripten"; +import {wait_for_all_assets} from "./assets"; +import {replace_linker_placeholders} from "./exports-binding"; +import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; +import {interp_pgo_load_data, interp_pgo_save_data} from "./interp-pgo"; +import {mono_log_debug, mono_log_error, mono_log_info, mono_log_warn} from "./logging"; // threads -import { populateEmscriptenPool, mono_wasm_init_threads, init_finalizer_thread } from "./pthreads"; -import { currentWorkerThreadEvents, dotnetPthreadCreated, initWorkerThreadEvents, monoThreadInfo } from "./pthreads"; -import { mono_wasm_pthread_ptr, update_thread_info } from "./pthreads"; -import { jiterpreter_allocate_tables } from "./jiterpreter-support"; -import { localHeapViewU8 } from "./memory"; -import { assertNoProxies } from "./gc-handles"; -import { runtimeList } from "./exports"; -import { nativeAbort, nativeExit } from "./run"; -import { mono_wasm_init_diagnostics } from "./diagnostics"; -import { replaceEmscriptenPThreadInit } from "./pthreads/worker-thread"; - -export async function configureRuntimeStartup(): Promise { +import {populateEmscriptenPool, mono_wasm_init_threads, init_finalizer_thread} from "./pthreads"; +import {currentWorkerThreadEvents, dotnetPthreadCreated, initWorkerThreadEvents, monoThreadInfo} from "./pthreads"; +import {mono_wasm_pthread_ptr, update_thread_info} from "./pthreads"; +import {jiterpreter_allocate_tables} from "./jiterpreter-support"; +import {localHeapViewU8} from "./memory"; +import {assertNoProxies} from "./gc-handles"; +import {runtimeList} from "./exports"; +import {nativeAbort, nativeExit} from "./run"; +import {mono_wasm_init_diagnostics} from "./diagnostics"; +import {replaceEmscriptenPThreadInit} from "./pthreads/worker-thread"; + +export async function configureRuntimeStartup (): Promise { await init_polyfills_async(); } // we are making emscripten startup async friendly // emscripten is executing the events without awaiting it and so we need to block progress via PromiseControllers above -export function configureEmscriptenStartup(module: DotnetModuleInternal): void { +export function configureEmscriptenStartup (module: DotnetModuleInternal): void { const mark = startMeasure(); if (!module.locateFile) { @@ -98,7 +98,7 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { module.ready = runtimeHelpers.dotnetReady.promise; } -function instantiateWasm( +function instantiateWasm ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, userInstantiateWasm?: InstantiateWasmCallBack): any[] { @@ -118,7 +118,7 @@ function instantiateWasm( return []; // No exports } -async function instantiateWasmWorker( +async function instantiateWasmWorker ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback ): Promise { @@ -136,7 +136,7 @@ async function instantiateWasmWorker( Module.wasmModule = null; } -function preInit(userPreInit: (() => void)[]) { +function preInit (userPreInit: (() => void)[]) { Module.addRunDependency("mono_pre_init"); const mark = startMeasure(); try { @@ -169,7 +169,7 @@ function preInit(userPreInit: (() => void)[]) { })(); } -async function preInitWorkerAsync() { +async function preInitWorkerAsync () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -193,7 +193,7 @@ async function preInitWorkerAsync() { } // runs for each re-attached worker -export function preRunWorker() { +export function preRunWorker () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -209,7 +209,7 @@ export function preRunWorker() { } } -async function preRunAsync(userPreRun: (() => void)[]) { +async function preRunAsync (userPreRun: (() => void)[]) { Module.addRunDependency("mono_pre_run_async"); // wait for previous stages try { @@ -230,7 +230,7 @@ async function preRunAsync(userPreRun: (() => void)[]) { Module.removeRunDependency("mono_pre_run_async"); } -async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { +async function onRuntimeInitializedAsync (userOnRuntimeInitialized: () => void) { try { // wait for previous stage await runtimeHelpers.afterPreRun.promise; @@ -320,8 +320,7 @@ async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { // call user code try { userOnRuntimeInitialized(); - } - catch (err: any) { + } catch (err: any) { mono_log_error("user callback onRuntimeInitialized() failed", err); throw err; } @@ -338,7 +337,7 @@ async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { runtimeHelpers.afterOnRuntimeInitialized.promise_control.resolve(); } -async function postRunAsync(userpostRun: (() => void)[]) { +async function postRunAsync (userpostRun: (() => void)[]) { // wait for previous stage try { await runtimeHelpers.afterOnRuntimeInitialized.promise; @@ -362,7 +361,7 @@ async function postRunAsync(userpostRun: (() => void)[]) { } // runs for each re-detached worker -export function postRunWorker() { +export function postRunWorker () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -383,7 +382,7 @@ export function postRunWorker() { } } -function mono_wasm_pre_init_essential(isWorker: boolean): void { +function mono_wasm_pre_init_essential (isWorker: boolean): void { if (!isWorker) Module.addRunDependency("mono_wasm_pre_init_essential"); @@ -410,7 +409,7 @@ function mono_wasm_pre_init_essential(isWorker: boolean): void { Module.removeRunDependency("mono_wasm_pre_init_essential"); } -async function mono_wasm_pre_init_essential_async(): Promise { +async function mono_wasm_pre_init_essential_async (): Promise { mono_log_debug("mono_wasm_pre_init_essential_async"); Module.addRunDependency("mono_wasm_pre_init_essential_async"); @@ -421,14 +420,13 @@ async function mono_wasm_pre_init_essential_async(): Promise { Module.removeRunDependency("mono_wasm_pre_init_essential_async"); } -async function mono_wasm_after_user_runtime_initialized(): Promise { +async function mono_wasm_after_user_runtime_initialized (): Promise { mono_log_debug("mono_wasm_after_user_runtime_initialized"); try { if (Module.onDotnetReady) { try { await Module.onDotnetReady(); - } - catch (err: any) { + } catch (err: any) { mono_log_error("onDotnetReady () failed", err); throw err; } @@ -441,11 +439,11 @@ async function mono_wasm_after_user_runtime_initialized(): Promise { // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases -export function mono_wasm_setenv(name: string, value: string): void { +export function mono_wasm_setenv (name: string, value: string): void { cwraps.mono_wasm_setenv(name, value); } -export function mono_wasm_set_runtime_options(options: string[]): void { +export function mono_wasm_set_runtime_options (options: string[]): void { if (!Array.isArray(options)) throw new Error("Expected runtimeOptions to be an array of strings"); @@ -461,7 +459,7 @@ export function mono_wasm_set_runtime_options(options: string[]): void { cwraps.mono_wasm_parse_runtime_options(options.length, argv); } -async function instantiate_wasm_module( +async function instantiate_wasm_module ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, ): Promise { @@ -491,7 +489,7 @@ async function instantiate_wasm_module( Module.removeRunDependency("instantiate_wasm_module"); } -async function ensureUsedWasmFeatures() { +async function ensureUsedWasmFeatures () { runtimeHelpers.featureWasmSimd = await loaderHelpers.simd(); runtimeHelpers.featureWasmEh = await loaderHelpers.exceptions(); if (runtimeHelpers.emscriptenBuildOptions.wasmEnableSIMD) { @@ -502,7 +500,7 @@ async function ensureUsedWasmFeatures() { } } -export async function start_runtime() { +export async function start_runtime () { try { const mark = startMeasure(); mono_log_debug("Initializing mono runtime"); @@ -566,7 +564,7 @@ export async function start_runtime() { } } -async function maybeSaveInterpPgoTable() { +async function maybeSaveInterpPgoTable () { // If the application exited abnormally, don't save the table. It probably doesn't contain useful data, // and saving would overwrite any existing table from a previous successful run. // We treat exiting with a code of 0 as equivalent to if the app is still running - it's perfectly fine @@ -577,7 +575,7 @@ async function maybeSaveInterpPgoTable() { await interp_pgo_save_data(); } -export function mono_wasm_load_runtime(): void { +export function mono_wasm_load_runtime (): void { mono_log_debug("mono_wasm_load_runtime"); try { const mark = startMeasure(); @@ -601,7 +599,7 @@ export function mono_wasm_load_runtime(): void { } } -export function bindings_init(): void { +export function bindings_init (): void { if (runtimeHelpers.mono_wasm_bindings_is_ready) { return; } @@ -622,7 +620,7 @@ export function bindings_init(): void { } -export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { +export function mono_wasm_asm_loaded (assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (runtimeHelpers.mono_wasm_runtime_is_ready !== true) return; @@ -645,7 +643,7 @@ export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: numbe }); } -export function mono_wasm_set_main_args(name: string, allRuntimeArguments: string[]): void { +export function mono_wasm_set_main_args (name: string, allRuntimeArguments: string[]): void { const main_argc = allRuntimeArguments.length + 1; const main_argv = Module._malloc(main_argc * 4); let aindex = 0; @@ -665,7 +663,7 @@ export function mono_wasm_set_main_args(name: string, allRuntimeArguments: strin /// 1. Emscripten skips a lot of initialization on the pthread workers, Module may not have everything you expect. /// 2. Emscripten does not run any event but preInit in the workers. /// 3. At the point when this executes there is no pthread assigned to the worker yet. -export async function configureWorkerStartup(module: DotnetModuleInternal): Promise { +export async function configureWorkerStartup (module: DotnetModuleInternal): Promise { if (!WasmEnableThreads) return; initWorkerThreadEvents(); diff --git a/src/mono/browser/runtime/strings.ts b/src/mono/browser/runtime/strings.ts index d0d798c161b28f..b57fcca62e5e0a 100644 --- a/src/mono/browser/runtime/strings.ts +++ b/src/mono/browser/runtime/strings.ts @@ -1,12 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_wasm_new_root, mono_wasm_new_root_buffer } from "./roots"; -import { MonoString, MonoStringNull, WasmRoot, WasmRootBuffer } from "./types/internal"; -import { Module } from "./globals"; +import {mono_wasm_new_root, mono_wasm_new_root_buffer} from "./roots"; +import {MonoString, MonoStringNull, WasmRoot, WasmRootBuffer} from "./types/internal"; +import {Module} from "./globals"; import cwraps from "./cwraps"; -import { isSharedArrayBuffer, localHeapViewU8, getU32_local, setU16_local, localHeapViewU32, getU16_local, localHeapViewU16, _zero_region } from "./memory"; -import { NativePointer, CharPtr } from "./types/emscripten"; +import {isSharedArrayBuffer, localHeapViewU8, getU32_local, setU16_local, localHeapViewU32, getU16_local, localHeapViewU16, _zero_region} from "./memory"; +import {NativePointer, CharPtr} from "./types/emscripten"; export const interned_js_string_table = new Map(); export const mono_wasm_empty_string = ""; @@ -21,11 +21,11 @@ let _text_decoder_utf8_relaxed: TextDecoder | undefined = undefined; let _text_decoder_utf8_validating: TextDecoder | undefined = undefined; let _text_encoder_utf8: TextEncoder | undefined = undefined; -export function strings_init(): void { +export function strings_init (): void { if (!mono_wasm_string_decoder_buffer) { if (typeof TextDecoder !== "undefined") { _text_decoder_utf16 = new TextDecoder("utf-16le"); - _text_decoder_utf8_relaxed = new TextDecoder("utf-8", { fatal: false }); + _text_decoder_utf8_relaxed = new TextDecoder("utf-8", {fatal: false}); _text_decoder_utf8_validating = new TextDecoder("utf-8"); _text_encoder_utf8 = new TextEncoder(); } @@ -35,7 +35,7 @@ export function strings_init(): void { mono_wasm_string_root = mono_wasm_new_root(); } -export function stringToUTF8(str: string): Uint8Array { +export function stringToUTF8 (str: string): Uint8Array { if (_text_encoder_utf8 === undefined) { const buffer = new Uint8Array(str.length * 2); Module.stringToUTF8Array(str, buffer, 0, str.length * 2); @@ -44,7 +44,7 @@ export function stringToUTF8(str: string): Uint8Array { return _text_encoder_utf8.encode(str); } -export function stringToUTF8Ptr(str: string): CharPtr { +export function stringToUTF8Ptr (str: string): CharPtr { const bytes = str.length * 2; const ptr = Module._malloc(bytes) as any; _zero_region(ptr, str.length * 2); @@ -53,19 +53,19 @@ export function stringToUTF8Ptr(str: string): CharPtr { return ptr; } -export function utf8ToStringRelaxed(buffer: Uint8Array): string { +export function utf8ToStringRelaxed (buffer: Uint8Array): string { if (_text_decoder_utf8_relaxed === undefined) { return Module.UTF8ArrayToString(buffer, 0, buffer.byteLength); } return _text_decoder_utf8_relaxed.decode(buffer); } -export function utf8ToString(ptr: CharPtr): string { +export function utf8ToString (ptr: CharPtr): string { const heapU8 = localHeapViewU8(); return utf8BufferToString(heapU8, ptr as any, heapU8.length - (ptr as any)); } -export function utf8BufferToString(heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { +export function utf8BufferToString (heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { const endIdx = idx + maxBytesToRead; let endPtr = idx; while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; @@ -79,7 +79,7 @@ export function utf8BufferToString(heapOrArray: Uint8Array, idx: number, maxByte return _text_decoder_utf8_validating.decode(view); } -export function utf16ToString(startPtr: number, endPtr: number): string { +export function utf16ToString (startPtr: number, endPtr: number): string { if (_text_decoder_utf16) { const subArray = viewOrCopy(localHeapViewU8(), startPtr as any, endPtr as any); return _text_decoder_utf16.decode(subArray); @@ -88,7 +88,7 @@ export function utf16ToString(startPtr: number, endPtr: number): string { } } -export function utf16ToStringLoop(startPtr: number, endPtr: number): string { +export function utf16ToStringLoop (startPtr: number, endPtr: number): string { let str = ""; const heapU16 = localHeapViewU16(); for (let i = startPtr; i < endPtr; i += 2) { @@ -98,7 +98,7 @@ export function utf16ToStringLoop(startPtr: number, endPtr: number): string { return str; } -export function stringToUTF16(dstPtr: number, endPtr: number, text: string) { +export function stringToUTF16 (dstPtr: number, endPtr: number, text: string) { const heapI16 = localHeapViewU16(); const len = text.length; for (let i = 0; i < len; i++) { @@ -108,7 +108,7 @@ export function stringToUTF16(dstPtr: number, endPtr: number, text: string) { } } -export function monoStringToString(root: WasmRoot): string | null { +export function monoStringToString (root: WasmRoot): string | null { if (root.value === MonoStringNull) return null; @@ -142,7 +142,7 @@ export function monoStringToString(root: WasmRoot): string | null { return result; } -export function stringToMonoStringRoot(string: string, result: WasmRoot): void { +export function stringToMonoStringRoot (string: string, result: WasmRoot): void { result.clear(); if (string === null) @@ -171,7 +171,7 @@ export function stringToMonoStringRoot(string: string, result: WasmRoot): void { +function stringToInternedMonoStringRoot (string: string | symbol, result: WasmRoot): void { let text: string | undefined; if (typeof (string) === "symbol") { text = string.description; @@ -204,7 +204,7 @@ function stringToInternedMonoStringRoot(string: string | symbol, result: WasmRoo storeStringInInternTable(text, result, true); } -function storeStringInInternTable(string: string, root: WasmRoot, internIt: boolean): void { +function storeStringInInternTable (string: string, root: WasmRoot, internIt: boolean): void { if (!root.value) throw new Error("null pointer passed to _store_string_in_intern_table"); @@ -242,7 +242,7 @@ function storeStringInInternTable(string: string, root: WasmRoot, in rootBuffer.copy_value_from_address(index, root.address); } -function stringToMonoStringNewRoot(string: string, result: WasmRoot): void { +function stringToMonoStringNewRoot (string: string, result: WasmRoot): void { const bufferLen = (string.length + 1) * 2; // TODO this could be stack allocated for small strings // or temp_malloc/alloca for large strings @@ -256,7 +256,7 @@ function stringToMonoStringNewRoot(string: string, result: WasmRoot) // When threading is enabled, TextDecoder does not accept a view of a // SharedArrayBuffer, we must make a copy of the array first. // See https://github.com/whatwg/encoding/issues/172 -export function viewOrCopy(view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { +export function viewOrCopy (view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { // this condition should be eliminated by rollup on non-threading builds const needsCopy = isSharedArrayBuffer(view.buffer); return needsCopy @@ -268,7 +268,7 @@ export function viewOrCopy(view: Uint8Array, start: CharPtr, end: CharPtr): Uint let mono_wasm_string_root: any; /* @deprecated not GC safe, use monoStringToString */ -export function monoStringToStringUnsafe(mono_string: MonoString): string | null { +export function monoStringToStringUnsafe (mono_string: MonoString): string | null { if (mono_string === MonoStringNull) return null; diff --git a/src/mono/browser/runtime/types/export-types.ts b/src/mono/browser/runtime/types/export-types.ts index cdd34f35178ab5..cb2cee31ed8cd2 100644 --- a/src/mono/browser/runtime/types/export-types.ts +++ b/src/mono/browser/runtime/types/export-types.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { IMemoryView } from "../marshal"; -import type { CreateDotnetRuntimeType, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, MonoConfig, ModuleAPI, AssetEntry, GlobalizationMode, AssetBehaviors } from "."; -import type { EmscriptenModule } from "./emscripten"; -import type { dotnet, exit } from "../loader/index"; +import type {IMemoryView} from "../marshal"; +import type {CreateDotnetRuntimeType, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, MonoConfig, ModuleAPI, AssetEntry, GlobalizationMode, AssetBehaviors} from "."; +import type {EmscriptenModule} from "./emscripten"; +import type {dotnet, exit} from "../loader/index"; // ----------------------------------------------------------- // this files has all public exports from the dotnet.js module diff --git a/src/mono/browser/runtime/types/index.ts b/src/mono/browser/runtime/types/index.ts index c5754f6c89e8fc..047019dc8e7455 100644 --- a/src/mono/browser/runtime/types/index.ts +++ b/src/mono/browser/runtime/types/index.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type { EmscriptenModule, NativePointer } from "./emscripten"; +import type {EmscriptenModule, NativePointer} from "./emscripten"; export interface DotnetHostBuilder { /** diff --git a/src/mono/browser/runtime/types/internal.ts b/src/mono/browser/runtime/types/internal.ts index 16967d26b9d299..c5bb3c61b764e8 100644 --- a/src/mono/browser/runtime/types/internal.ts +++ b/src/mono/browser/runtime/types/internal.ts @@ -1,8 +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 type { AssetEntry, DotnetModuleConfig, LoadBootResourceCallback, LoadingResource, MonoConfig, RuntimeAPI, SingleAssetBehaviors } from "."; -import type { CharPtr, EmscriptenModule, ManagedPointer, NativePointer, VoidPtr, Int32Ptr } from "./emscripten"; +import type {AssetEntry, DotnetModuleConfig, LoadBootResourceCallback, LoadingResource, MonoConfig, RuntimeAPI, SingleAssetBehaviors} from "."; +import type {CharPtr, EmscriptenModule, ManagedPointer, NativePointer, VoidPtr, Int32Ptr} from "./emscripten"; export type GCHandle = { __brand: "GCHandle" @@ -64,7 +64,7 @@ export const CharPtrNull: CharPtr = 0; export const NativePointerNull: NativePointer = 0; export const PThreadPtrNull: PThreadPtr = 0; -export function coerceNull(ptr: T | null | undefined): T { +export function coerceNull (ptr: T | null | undefined): T { if ((ptr === null) || (ptr === undefined)) return (0 as any) as T; else @@ -254,7 +254,7 @@ export type DotnetModuleInternal = EmscriptenModule & DotnetModuleConfig & Emscr // Evaluates whether a value is nullish (same definition used as the ?? operator, // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) -export function is_nullish(value: T | null | undefined): value is null | undefined { +export function is_nullish (value: T | null | undefined): value is null | undefined { return (value === undefined) || (value === null); } @@ -299,14 +299,14 @@ export interface ExitStatusError { /// Always throws. Used to handle unreachable switch branches when TypeScript refines the type of a variable /// to 'never' after you handle all the cases it knows about. -export function assertNever(x: never): never { +export function assertNever (x: never): never { throw new Error("Unexpected value: " + x); } /// returns true if the given value is not Thenable /// /// Useful if some function returns a value or a promise of a value. -export function notThenable(x: T | PromiseLike): x is T { +export function notThenable (x: T | PromiseLike): x is T { return typeof x !== "object" || typeof ((>x).then) !== "function"; } @@ -571,8 +571,8 @@ export interface MonoThreadMessage { // keep in sync with JSHostImplementation.Types.cs export const enum MainThreadingMode { - // Running the managed main thread on UI thread. - // Managed GC and similar scenarios could be blocking the UI. + // Running the managed main thread on UI thread. + // Managed GC and similar scenarios could be blocking the UI. // Easy to deadlock. Not recommended for production. UIThread = 0, // Running the managed main thread on dedicated WebWorker. Marshaling all JavaScript calls to and from the main thread. @@ -588,7 +588,7 @@ export const enum JSThreadBlockingMode { NoBlockingWait = 0, // TODO comment AllowBlockingWaitInAsyncCode = 1, - // allow .Wait on all threads. + // allow .Wait on all threads. // Could cause deadlocks with blocking .Wait on a pending JS Task/Promise on the same thread or similar Task/Promise chain. AllowBlockingWait = 100, } @@ -601,4 +601,4 @@ export const enum JSThreadInteropMode { // allow non-re-entrant synchronous blocking calls to and from JS on JSWebWorker on threads with JS interop, like JSWebWorker and Main thread. // calling synchronous JSImport on thread pool or new threads is allowed. SimpleSynchronousJSInterop = 1, -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/types/node.d.ts b/src/mono/browser/runtime/types/node.d.ts index 6c548d2404eeac..e42f6034ead4c7 100644 --- a/src/mono/browser/runtime/types/node.d.ts +++ b/src/mono/browser/runtime/types/node.d.ts @@ -5,4 +5,4 @@ declare const __filename: string; declare const __dirname: string; declare type Buffer = {} -declare const process: any; \ No newline at end of file +declare const process: any; diff --git a/src/mono/browser/runtime/types/sidecar.d.ts b/src/mono/browser/runtime/types/sidecar.d.ts index bc50b63f1fb39b..b4fd0d3950ea55 100644 --- a/src/mono/browser/runtime/types/sidecar.d.ts +++ b/src/mono/browser/runtime/types/sidecar.d.ts @@ -1,4 +1,4 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -declare let dotnetSidecar: boolean | undefined; \ No newline at end of file +declare let dotnetSidecar: boolean | undefined; diff --git a/src/mono/browser/runtime/types/v8.d.ts b/src/mono/browser/runtime/types/v8.d.ts index db11d5ef8552b6..95093e37c3e974 100644 --- a/src/mono/browser/runtime/types/v8.d.ts +++ b/src/mono/browser/runtime/types/v8.d.ts @@ -2,4 +2,4 @@ // The .NET Foundation licenses this file to you under the MIT license. // read is a v8 debugger command -declare function read(name: string, mode?: string): any; \ No newline at end of file +declare function read(name: string, mode?: string): any; diff --git a/src/mono/browser/runtime/weak-ref.ts b/src/mono/browser/runtime/weak-ref.ts index fc69eb8a2b6ed5..d0ea943dcbf505 100644 --- a/src/mono/browser/runtime/weak-ref.ts +++ b/src/mono/browser/runtime/weak-ref.ts @@ -1,21 +1,20 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { WeakRefInternal } from "./types/internal"; +import {WeakRefInternal} from "./types/internal"; export const _use_weak_ref = typeof globalThis.WeakRef === "function"; -export function create_weak_ref(js_obj: T): WeakRefInternal { +export function create_weak_ref (js_obj: T): WeakRefInternal { if (_use_weak_ref) { return new WeakRef(js_obj); - } - else { + } else { // this is trivial WeakRef replacement, which holds strong refrence, instead of weak one, when the browser doesn't support it return create_strong_ref(js_obj); } } -export function create_strong_ref(js_obj: T): WeakRefInternal { +export function create_strong_ref (js_obj: T): WeakRefInternal { return { deref: () => { return js_obj; @@ -24,4 +23,4 @@ export function create_strong_ref(js_obj: T): WeakRefInternal< js_obj = null!; } }; -} \ No newline at end of file +} diff --git a/src/mono/browser/runtime/web-socket.ts b/src/mono/browser/runtime/web-socket.ts index c7ebdac242da58..21209088f88466 100644 --- a/src/mono/browser/runtime/web-socket.ts +++ b/src/mono/browser/runtime/web-socket.ts @@ -3,16 +3,16 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import { prevent_timer_throttling } from "./scheduling"; -import { Queue } from "./queue"; -import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, createPromiseController, loaderHelpers, mono_assert } from "./globals"; -import { setI32, localHeapViewU8, forceThreadMemoryViewRefresh } from "./memory"; -import { VoidPtr } from "./types/emscripten"; -import { PromiseController } from "./types/internal"; -import { mono_log_warn } from "./logging"; -import { viewOrCopy, utf8ToStringRelaxed, stringToUTF8 } from "./strings"; -import { wrap_as_cancelable } from "./cancelable-promise"; -import { assert_js_interop } from "./invoke-js"; +import {prevent_timer_throttling} from "./scheduling"; +import {Queue} from "./queue"; +import {ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, createPromiseController, loaderHelpers, mono_assert} from "./globals"; +import {setI32, localHeapViewU8, forceThreadMemoryViewRefresh} from "./memory"; +import {VoidPtr} from "./types/emscripten"; +import {PromiseController} from "./types/internal"; +import {mono_log_warn} from "./logging"; +import {viewOrCopy, utf8ToStringRelaxed, stringToUTF8} from "./strings"; +import {wrap_as_cancelable} from "./cancelable-promise"; +import {assert_js_interop} from "./invoke-js"; const wasm_ws_pending_send_buffer = Symbol.for("wasm ws_pending_send_buffer"); const wasm_ws_pending_send_buffer_offset = Symbol.for("wasm ws_pending_send_buffer_offset"); @@ -32,7 +32,7 @@ const wasm_ws_receive_status_ptr = Symbol.for("wasm ws_receive_status_ptr"); const ws_send_buffer_blocking_threshold = 65536; const emptyBuffer = new Uint8Array(); -function verifyEnvironment() { +function verifyEnvironment () { if (ENVIRONMENT_IS_SHELL) { throw new Error("WebSockets are not supported in shell JS engine."); } @@ -44,8 +44,7 @@ function verifyEnvironment() { } } -export function ws_get_state(ws: WebSocketExtension) : number -{ +export function ws_get_state (ws: WebSocketExtension) : number { if (ws.readyState != WebSocket.CLOSED) return ws.readyState ?? -1; const receive_event_queue = ws[wasm_ws_pending_receive_event_queue]; @@ -55,19 +54,18 @@ export function ws_get_state(ws: WebSocketExtension) : number return WebSocket.OPEN; } -export function ws_wasm_create(uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { +export function ws_wasm_create (uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { verifyEnvironment(); assert_js_interop(); mono_assert(uri && typeof uri === "string", () => `ERR12: Invalid uri ${typeof uri}`); let ws: WebSocketExtension; try { ws = new globalThis.WebSocket(uri, sub_protocols || undefined) as WebSocketExtension; - } - catch (error: any) { + } catch (error: any) { mono_log_warn("WebSocket error in ws_wasm_create: " + error.toString()); throw error; } - const { promise_control: open_promise_control } = createPromiseController(); + const {promise_control: open_promise_control} = createPromiseController(); ws[wasm_ws_pending_receive_event_queue] = new Queue(); ws[wasm_ws_pending_receive_promise_queue] = new Queue(); @@ -154,9 +152,9 @@ export function ws_wasm_create(uri: string, sub_protocols: string[] | null, rece } }; ws.addEventListener("message", local_on_message); - ws.addEventListener("open", local_on_open, { once: true }); - ws.addEventListener("close", local_on_close, { once: true }); - ws.addEventListener("error", local_on_error, { once: true }); + ws.addEventListener("open", local_on_open, {once: true}); + ws.addEventListener("close", local_on_close, {once: true}); + ws.addEventListener("error", local_on_error, {once: true}); ws.dispose = () => { ws.removeEventListener("message", local_on_message); ws.removeEventListener("open", local_on_open); @@ -168,7 +166,7 @@ export function ws_wasm_create(uri: string, sub_protocols: string[] | null, rece return ws; } -export function ws_wasm_open(ws: WebSocketExtension): Promise | null { +export function ws_wasm_open (ws: WebSocketExtension): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { return rejectedPromise(ws[wasm_ws_pending_error]); @@ -178,7 +176,7 @@ export function ws_wasm_open(ws: WebSocketExtension): Promise | null { +export function ws_wasm_send (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number, message_type: number, end_of_message: boolean): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -203,7 +201,7 @@ export function ws_wasm_send(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer return web_socket_send_and_wait(ws, whole_buffer); } -export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { +export function ws_wasm_receive (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -239,7 +237,7 @@ export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buf return resolvedPromise(); } - const { promise, promise_control } = createPromiseController(); + const {promise, promise_control} = createPromiseController(); const receive_promise_control = promise_control as ReceivePromiseControl; receive_promise_control.buffer_ptr = buffer_ptr; receive_promise_control.buffer_length = buffer_length; @@ -248,7 +246,7 @@ export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buf return promise; } -export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { +export function ws_wasm_close (ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { mono_assert(!!ws, "ERR19: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent] || ws.readyState == WebSocket.CLOSED) { @@ -259,7 +257,7 @@ export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: stri } ws[wasm_ws_close_sent] = true; if (wait_for_close_received) { - const { promise, promise_control } = createPromiseController(); + const {promise, promise_control} = createPromiseController(); ws[wasm_ws_pending_close_promises].push(promise_control); if (typeof reason === "string") { @@ -268,8 +266,7 @@ export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: stri ws.close(code); } return promise; - } - else { + } else { if (typeof reason === "string") { ws.close(code, reason); } else { @@ -279,7 +276,7 @@ export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: stri } } -export function ws_wasm_abort(ws: WebSocketExtension): void { +export function ws_wasm_abort (ws: WebSocketExtension): void { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent]) { @@ -297,7 +294,7 @@ export function ws_wasm_abort(ws: WebSocketExtension): void { } } -function reject_promises(ws: WebSocketExtension, error: Error) { +function reject_promises (ws: WebSocketExtension, error: Error) { const open_promise_control = ws[wasm_ws_pending_open_promise]; const open_promise_used = ws[wasm_ws_pending_open_promise_used]; @@ -320,7 +317,7 @@ function reject_promises(ws: WebSocketExtension, error: Error) { } // send and return promise -function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { +function web_socket_send_and_wait (ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { ws.send(buffer_view); ws[wasm_ws_pending_send_buffer] = null; @@ -332,7 +329,7 @@ function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Arra } // block the promise/task until the browser passed the buffer to OS - const { promise, promise_control } = createPromiseController(); + const {promise, promise_control} = createPromiseController(); const pending = ws[wasm_ws_pending_send_promises]; pending.push(promise_control); @@ -342,15 +339,13 @@ function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Arra // was it all sent yet ? if (ws.bufferedAmount === 0) { promise_control.resolve(); - } - else { + } else { const readyState = ws.readyState; if (readyState != WebSocket.OPEN && readyState != WebSocket.CLOSING) { // only reject if the data were not sent // bufferedAmount does not reset to zero once the connection closes promise_control.reject(new Error(`InvalidState: ${readyState} The WebSocket is not connected.`)); - } - else if (!promise_control.isDone) { + } else if (!promise_control.isDone) { globalThis.setTimeout(polling_check, nextDelay); // exponentially longer delays, up to 1000ms nextDelay = Math.min(nextDelay * 1.5, 1000); @@ -362,8 +357,7 @@ function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Arra if (index > -1) { pending.splice(index, 1); } - } - catch (error: any) { + } catch (error: any) { mono_log_warn("WebSocket error in web_socket_send_and_wait: " + error.toString()); promise_control.reject(error); } @@ -374,7 +368,7 @@ function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Arra return promise; } -function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { +function web_socket_on_message (ws: WebSocketExtension, event: MessageEvent) { const event_queue = ws[wasm_ws_pending_receive_event_queue]; const promise_queue = ws[wasm_ws_pending_receive_promise_queue]; @@ -387,8 +381,7 @@ function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { data: stringToUTF8(event.data), offset: 0 }); - } - else { + } else { if (event.data.constructor.name !== "ArrayBuffer") { throw new Error("ERR19: WebSocket receive expected ArrayBuffer"); } @@ -410,7 +403,7 @@ function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { prevent_timer_throttling(); } -function web_socket_receive_buffering(ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { +function web_socket_receive_buffering (ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { const event = event_queue.peek(); const count = Math.min(buffer_length, event.data.length - event.offset); @@ -430,7 +423,7 @@ function web_socket_receive_buffering(ws: WebSocketExtension, event_queue: Queue setI32(response_ptr + 8, end_of_message); } -function web_socket_send_buffering(ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { +function web_socket_send_buffering (ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { let buffer = ws[wasm_ws_pending_send_buffer]; let offset = 0; const length = buffer_view.byteLength; @@ -446,15 +439,13 @@ function web_socket_send_buffering(ws: WebSocketExtension, buffer_view: Uint8Arr newbuffer.set(buffer, 0);// copy previous buffer newbuffer.subarray(offset).set(buffer_view);// append copy at the end ws[wasm_ws_pending_send_buffer] = buffer = newbuffer; - } - else { + } else { buffer.subarray(offset).set(buffer_view);// append copy at the end } offset += length; ws[wasm_ws_pending_send_buffer_offset] = offset; } - } - else if (!end_of_message) { + } else if (!end_of_message) { // create new buffer if (length !== 0) { buffer = buffer_view.slice(); // copy @@ -463,8 +454,7 @@ function web_socket_send_buffering(ws: WebSocketExtension, buffer_view: Uint8Arr ws[wasm_ws_pending_send_buffer] = buffer; } ws[wasm_ws_pending_send_buffer_type] = message_type; - } - else { + } else { if (length !== 0) { // we could use the un-pinned view, because it will be immediately used in ws.send() if (WasmEnableThreads) { @@ -525,7 +515,7 @@ type Message = { offset: number } -function resolvedPromise(): Promise | null { +function resolvedPromise (): Promise | null { if (!WasmEnableThreads) { // signal that we are finished synchronously // this is optimization, which doesn't allocate and doesn't require to marshal resolve() call to C# side. @@ -540,7 +530,7 @@ function resolvedPromise(): Promise | null { } } -function rejectedPromise(message: string): Promise | null { +function rejectedPromise (message: string): Promise | null { const resolved = Promise.reject(new Error(message)); return wrap_as_cancelable(resolved); } From 526da56e9ed3ed8e9a1af11d5213a7451406a3b8 Mon Sep 17 00:00:00 2001 From: Ilona Tomkowicz Date: Tue, 26 Mar 2024 16:14:18 +0100 Subject: [PATCH 3/4] Correct the rule set. --- src/mono/browser/runtime/.eslintrc.cjs | 4 +- src/mono/browser/runtime/assets.ts | 30 +-- src/mono/browser/runtime/base64.ts | 8 +- .../browser/runtime/cancelable-promise.ts | 44 ++-- src/mono/browser/runtime/crypto.ts | 4 +- src/mono/browser/runtime/cuint64.ts | 12 +- src/mono/browser/runtime/cwraps.ts | 14 +- src/mono/browser/runtime/debug.ts | 92 ++++---- .../browser/runtime/diagnostics-mock.d.ts | 2 +- .../runtime/diagnostics/browser/controller.ts | 28 +-- src/mono/browser/runtime/diagnostics/index.ts | 22 +- .../runtime/diagnostics/mock/environment.ts | 40 ++-- .../browser/runtime/diagnostics/mock/index.ts | 44 ++-- .../browser/runtime/diagnostics/mock/types.ts | 2 +- .../server_pthread/common-socket.ts | 4 +- .../diagnostics/server_pthread/index.ts | 76 +++--- .../ipc-protocol/base-parser.ts | 28 +-- .../ipc-protocol/base-serializer.ts | 22 +- .../server_pthread/ipc-protocol/magic.ts | 4 +- .../server_pthread/ipc-protocol/parser.ts | 64 ++--- .../server_pthread/ipc-protocol/serializer.ts | 16 +- .../server_pthread/ipc-protocol/types.ts | 2 +- .../diagnostics/server_pthread/mock-remote.ts | 6 +- .../protocol-client-commands.ts | 14 +- .../server_pthread/protocol-socket.ts | 76 +++--- .../server_pthread/socket-connection.ts | 32 +-- .../server_pthread/stream-queue.ts | 26 +-- .../server_pthread/streaming-session.ts | 30 +-- .../diagnostics/shared/controller-commands.ts | 8 +- .../diagnostics/shared/create-session.ts | 16 +- src/mono/browser/runtime/export-api.ts | 16 +- src/mono/browser/runtime/exports-binding.ts | 50 ++-- src/mono/browser/runtime/exports-internal.ts | 50 ++-- src/mono/browser/runtime/exports-linker.ts | 4 +- src/mono/browser/runtime/exports.ts | 32 +-- src/mono/browser/runtime/gc-handles.ts | 50 ++-- src/mono/browser/runtime/gc-lock.ts | 6 +- src/mono/browser/runtime/globals.ts | 14 +- src/mono/browser/runtime/guarded-promise.ts | 2 +- src/mono/browser/runtime/http.ts | 60 ++--- .../runtime/hybrid-globalization/calendar.ts | 104 ++++----- .../hybrid-globalization/change-case.ts | 20 +- .../hybrid-globalization/collations.ts | 44 ++-- .../hybrid-globalization/culture-info.ts | 32 +-- .../grapheme-segmenter.ts | 26 +-- .../runtime/hybrid-globalization/helpers.ts | 6 +- .../runtime/hybrid-globalization/locales.ts | 30 +-- src/mono/browser/runtime/icu.ts | 4 +- src/mono/browser/runtime/interp-pgo.ts | 22 +- src/mono/browser/runtime/invoke-cs.ts | 50 ++-- src/mono/browser/runtime/invoke-js.ts | 102 ++++---- .../runtime/jiterpreter-interp-entry.ts | 32 +-- .../browser/runtime/jiterpreter-jit-call.ts | 38 +-- .../browser/runtime/jiterpreter-support.ts | 220 +++++++++--------- .../runtime/jiterpreter-trace-generator.ts | 118 +++++----- src/mono/browser/runtime/jiterpreter.ts | 48 ++-- src/mono/browser/runtime/lazyLoading.ts | 10 +- src/mono/browser/runtime/loader/assets.ts | 68 +++--- .../browser/runtime/loader/assetsCache.ts | 32 +-- src/mono/browser/runtime/loader/config.ts | 76 +++--- src/mono/browser/runtime/loader/exit.ts | 42 ++-- src/mono/browser/runtime/loader/globals.ts | 26 +-- src/mono/browser/runtime/loader/icu.ts | 12 +- src/mono/browser/runtime/loader/index.ts | 10 +- .../runtime/loader/libraryInitializers.ts | 20 +- src/mono/browser/runtime/loader/logging.ts | 32 +-- src/mono/browser/runtime/loader/polyfills.ts | 26 +-- .../runtime/loader/promise-controller.ts | 16 +- src/mono/browser/runtime/loader/run.ts | 104 ++++----- src/mono/browser/runtime/loader/worker.ts | 16 +- src/mono/browser/runtime/logging.ts | 30 +-- src/mono/browser/runtime/managed-exports.ts | 50 ++-- src/mono/browser/runtime/marshal-to-cs.ts | 76 +++--- src/mono/browser/runtime/marshal-to-js.ts | 90 +++---- src/mono/browser/runtime/marshal.ts | 172 +++++++------- src/mono/browser/runtime/memory.ts | 134 +++++------ src/mono/browser/runtime/polyfills.ts | 28 +-- src/mono/browser/runtime/profiler.ts | 28 +-- .../browser/runtime/pthreads/deputy-thread.ts | 14 +- src/mono/browser/runtime/pthreads/index.ts | 4 +- .../browser/runtime/pthreads/io-thread.ts | 12 +- src/mono/browser/runtime/pthreads/shared.ts | 26 +-- .../browser/runtime/pthreads/ui-thread.ts | 56 ++--- .../browser/runtime/pthreads/worker-events.ts | 4 +- .../browser/runtime/pthreads/worker-thread.ts | 44 ++-- src/mono/browser/runtime/queue.ts | 14 +- src/mono/browser/runtime/rollup.config.js | 66 +++--- src/mono/browser/runtime/roots.ts | 116 ++++----- src/mono/browser/runtime/run.ts | 20 +- .../browser/runtime/satelliteAssemblies.ts | 8 +- src/mono/browser/runtime/scheduling.ts | 20 +- src/mono/browser/runtime/startup.ts | 112 ++++----- src/mono/browser/runtime/strings.ts | 44 ++-- .../browser/runtime/types/export-types.ts | 8 +- src/mono/browser/runtime/types/index.ts | 2 +- src/mono/browser/runtime/types/internal.ts | 12 +- src/mono/browser/runtime/weak-ref.ts | 6 +- src/mono/browser/runtime/web-socket.ts | 64 ++--- 98 files changed, 1850 insertions(+), 1850 deletions(-) diff --git a/src/mono/browser/runtime/.eslintrc.cjs b/src/mono/browser/runtime/.eslintrc.cjs index 2e0abed745228c..c7b3283419f90b 100644 --- a/src/mono/browser/runtime/.eslintrc.cjs +++ b/src/mono/browser/runtime/.eslintrc.cjs @@ -55,9 +55,9 @@ module.exports = { "space-before-blocks": ["error"], "semi-spacing": ["error", { "before": false, "after": true }], "no-trailing-spaces": ["error"], - "object-curly-spacing": ["error"], + "object-curly-spacing": ["error", "always"], "array-bracket-spacing": ["error"], "space-infix-ops": ["error"], - "space-before-function-paren": ["error"], + "space-before-function-paren": ["error", "never"], } }; diff --git a/src/mono/browser/runtime/assets.ts b/src/mono/browser/runtime/assets.ts index 8b7035f2e56136..c2ebda35861de5 100644 --- a/src/mono/browser/runtime/assets.ts +++ b/src/mono/browser/runtime/assets.ts @@ -1,20 +1,20 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {AssetEntryInternal} from "./types/internal"; +import type { AssetEntryInternal } from "./types/internal"; import cwraps from "./cwraps"; -import {mono_wasm_load_icu_data} from "./icu"; -import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {mono_log_info, mono_log_debug, parseSymbolMapFile} from "./logging"; -import {mono_wasm_load_bytes_into_heap} from "./memory"; -import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; -import {AssetEntry} from "./types"; -import {VoidPtr} from "./types/emscripten"; -import {setSegmentationRulesFromJson} from "./hybrid-globalization/grapheme-segmenter"; +import { mono_wasm_load_icu_data } from "./icu"; +import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { mono_log_info, mono_log_debug, parseSymbolMapFile } from "./logging"; +import { mono_wasm_load_bytes_into_heap } from "./memory"; +import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; +import { AssetEntry } from "./types"; +import { VoidPtr } from "./types/emscripten"; +import { setSegmentationRulesFromJson } from "./hybrid-globalization/grapheme-segmenter"; // this need to be run only after onRuntimeInitialized event, when the memory is ready -export function instantiate_asset (asset: AssetEntry, url: string, bytes: Uint8Array): void { +export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Array): void { mono_log_debug(`Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); const mark = startMeasure(); @@ -33,7 +33,7 @@ export function instantiate_asset (asset: AssetEntry, url: string, bytes: Uint8A case "resource": case "assembly": case "pdb": - loaderHelpers._loaded_files.push({url: url, file: virtualName}); + loaderHelpers._loaded_files.push({ url: url, file: virtualName }); // falls through case "heap": case "icu": @@ -94,7 +94,7 @@ export function instantiate_asset (asset: AssetEntry, url: string, bytes: Uint8A ++loaderHelpers.actual_instantiated_assets_count; } -export async function instantiate_symbols_asset (pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const text = await response.text(); @@ -104,7 +104,7 @@ export async function instantiate_symbols_asset (pendingAsset: AssetEntryInterna } } -export async function instantiate_segmentation_rules_asset (pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_segmentation_rules_asset(pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const json = await response.json(); @@ -114,7 +114,7 @@ export async function instantiate_segmentation_rules_asset (pendingAsset: AssetE } } -export async function wait_for_all_assets () { +export async function wait_for_all_assets() { // wait for all assets in memory await runtimeHelpers.allAssetsInMemory.promise; if (runtimeHelpers.config.assets) { @@ -126,6 +126,6 @@ export async function wait_for_all_assets () { } // Used by the debugger to enumerate loaded dlls and pdbs -export function mono_wasm_get_loaded_files (): string[] { +export function mono_wasm_get_loaded_files(): string[] { return loaderHelpers.loadedFiles; } diff --git a/src/mono/browser/runtime/base64.ts b/src/mono/browser/runtime/base64.ts index 28bf9970ed7f10..e86fbc2ced58e4 100644 --- a/src/mono/browser/runtime/base64.ts +++ b/src/mono/browser/runtime/base64.ts @@ -5,7 +5,7 @@ // https://github.com/sq/JSIL/blob/1d57d5427c87ab92ffa3ca4b82429cd7509796ba/JSIL.Libraries/Includes/Bootstrap/Core/Classes/System.Convert.js#L149 // Thanks to Katelyn Gadd @kg -export function toBase64StringImpl (inArray: Uint8Array, offset?: number, length?: number) : string { +export function toBase64StringImpl(inArray: Uint8Array, offset?: number, length?: number) : string { const reader = _makeByteReader(inArray, offset, length); let result = ""; let ch1: number | null = 0, ch2: number | null = 0, ch3: number | null = 0; @@ -76,7 +76,7 @@ const _base64Table = [ "+", "/" ]; -function _makeByteReader (bytes: Uint8Array, index?: number, count?: number): { +function _makeByteReader(bytes: Uint8Array, index?: number, count?: number): { read: () => number | null } { let position = (typeof (index) === "number") ? index : 0; @@ -88,7 +88,7 @@ function _makeByteReader (bytes: Uint8Array, index?: number, count?: number): { endpoint = (bytes.length - position); const result = { - read: function () { + read: function() { if (position >= endpoint) return null; @@ -99,7 +99,7 @@ function _makeByteReader (bytes: Uint8Array, index?: number, count?: number): { }; Object.defineProperty(result, "eof", { - get: function () { + get: function() { return (position >= endpoint); }, configurable: true, diff --git a/src/mono/browser/runtime/cancelable-promise.ts b/src/mono/browser/runtime/cancelable-promise.ts index ca73f2f114d2d0..6a3d1924b5296c 100644 --- a/src/mono/browser/runtime/cancelable-promise.ts +++ b/src/mono/browser/runtime/cancelable-promise.ts @@ -3,44 +3,44 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {_lookup_js_owned_object, teardown_managed_proxy, upgrade_managed_proxy_to_strong_ref} from "./gc-handles"; -import {createPromiseController, loaderHelpers, mono_assert} from "./globals"; -import {ControllablePromise, GCHandle, MarshalerToCs} from "./types/internal"; -import {ManagedObject} from "./marshal"; -import {compareExchangeI32, forceThreadMemoryViewRefresh} from "./memory"; -import {mono_log_debug} from "./logging"; -import {complete_task} from "./managed-exports"; -import {marshal_cs_object_to_cs} from "./marshal-to-cs"; -import {invoke_later_when_on_ui_thread_async} from "./invoke-js"; +import { _lookup_js_owned_object, teardown_managed_proxy, upgrade_managed_proxy_to_strong_ref } from "./gc-handles"; +import { createPromiseController, loaderHelpers, mono_assert } from "./globals"; +import { ControllablePromise, GCHandle, MarshalerToCs } from "./types/internal"; +import { ManagedObject } from "./marshal"; +import { compareExchangeI32, forceThreadMemoryViewRefresh } from "./memory"; +import { mono_log_debug } from "./logging"; +import { complete_task } from "./managed-exports"; +import { marshal_cs_object_to_cs } from "./marshal-to-cs"; +import { invoke_later_when_on_ui_thread_async } from "./invoke-js"; export const _are_promises_supported = ((typeof Promise === "object") || (typeof Promise === "function")) && (typeof Promise.resolve === "function"); -export function isThenable (js_obj: any): boolean { +export function isThenable(js_obj: any): boolean { // When using an external Promise library like Bluebird the Promise.resolve may not be sufficient // to identify the object as a Promise. return Promise.resolve(js_obj) === js_obj || ((typeof js_obj === "object" || typeof js_obj === "function") && typeof js_obj.then === "function"); } -export function wrap_as_cancelable_promise (fn: () => Promise): ControllablePromise { - const {promise, promise_control} = createPromiseController(); +export function wrap_as_cancelable_promise(fn: () => Promise): ControllablePromise { + const { promise, promise_control } = createPromiseController(); const inner = fn(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function wrap_as_cancelable (inner: Promise): ControllablePromise { - const {promise, promise_control} = createPromiseController(); +export function wrap_as_cancelable(inner: Promise): ControllablePromise { + const { promise, promise_control } = createPromiseController(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function mono_wasm_cancel_promise (task_holder_gc_handle: GCHandle): void { +export function mono_wasm_cancel_promise(task_holder_gc_handle: GCHandle): void { // cancelation should not arrive earlier than the promise created by marshaling in mono_wasm_invoke_jsimport_MT invoke_later_when_on_ui_thread_async(() => mono_wasm_cancel_promise_impl(task_holder_gc_handle)); } -export function mono_wasm_cancel_promise_impl (task_holder_gc_handle: GCHandle): void { +export function mono_wasm_cancel_promise_impl(task_holder_gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise can't be canceled, mono runtime already exited."); return; @@ -63,7 +63,7 @@ export class PromiseHolder extends ManagedObject { public isPostponed = false; public data: any = null; public reason: any = undefined; - public constructor (public promise: Promise, + public constructor(public promise: Promise, private gc_handle: GCHandle, private promiseHolderPtr: number, // could be null for GCV_handle private res_converter?: MarshalerToCs) { @@ -71,7 +71,7 @@ export class PromiseHolder extends ManagedObject { } // returns false if the promise is being canceled by another thread in managed code - setIsResolving (): boolean { + setIsResolving(): boolean { if (!WasmEnableThreads || this.promiseHolderPtr === 0) { return true; } @@ -82,7 +82,7 @@ export class PromiseHolder extends ManagedObject { return false; } - resolve (data: any) { + resolve(data: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution can't be propagated to managed code, mono runtime already exited."); return; @@ -106,7 +106,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(data, null); } - reject (reason: any) { + reject(reason: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -131,7 +131,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(null, reason); } - cancel () { + cancel() { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise cancelation can't be propagated to managed code, mono runtime already exited."); return; @@ -162,7 +162,7 @@ export class PromiseHolder extends ManagedObject { } // we can do this just once, because it will be dispose the GCHandle - complete_task_wrapper (data: any, reason: any) { + complete_task_wrapper(data: any, reason: any) { try { mono_assert(!this.isPosted, "Promise is already posted to managed."); this.isPosted = true; diff --git a/src/mono/browser/runtime/crypto.ts b/src/mono/browser/runtime/crypto.ts index 9bf82e92f0aaa8..f396b5d833b147 100644 --- a/src/mono/browser/runtime/crypto.ts +++ b/src/mono/browser/runtime/crypto.ts @@ -1,11 +1,11 @@ -import {isSharedArrayBuffer, localHeapViewU8} from "./memory"; +import { isSharedArrayBuffer, localHeapViewU8 } from "./memory"; // batchedQuotaMax is the max number of bytes as specified by the api spec. // If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm. // https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues const batchedQuotaMax = 65536; -export function mono_wasm_browser_entropy (bufferPtr: number, bufferLength: number): number { +export function mono_wasm_browser_entropy(bufferPtr: number, bufferLength: number): number { if (!globalThis.crypto || !globalThis.crypto.getRandomValues) { return -1; } diff --git a/src/mono/browser/runtime/cuint64.ts b/src/mono/browser/runtime/cuint64.ts index 20ab2c88ca422f..558c230265e23c 100644 --- a/src/mono/browser/runtime/cuint64.ts +++ b/src/mono/browser/runtime/cuint64.ts @@ -6,11 +6,11 @@ /// and 'import type { CUInt64 } from './cuint64'; export type CUInt64 = readonly [number, number]; -export function toBigInt (x: CUInt64): bigint { +export function toBigInt(x: CUInt64): bigint { return BigInt(x[0]) | BigInt(x[1]) << BigInt(32); } -export function fromBigInt (x: bigint): CUInt64 { +export function fromBigInt(x: bigint): CUInt64 { if (x < BigInt(0)) throw new Error(`${x} is not a valid 64 bit integer`); if (x > BigInt(0xFFFFFFFFFFFFFFFF)) @@ -20,11 +20,11 @@ export function fromBigInt (x: bigint): CUInt64 { return [low, high]; } -export function dangerousToNumber (x: CUInt64): number { +export function dangerousToNumber(x: CUInt64): number { return x[0] | x[1] << 32; } -export function fromNumber (x: number): CUInt64 { +export function fromNumber(x: number): CUInt64 { if (x < 0) throw new Error(`${x} is not a valid 64 bit integer`); if ((x >> 32) > 0xFFFFFFFF) @@ -34,11 +34,11 @@ export function fromNumber (x: number): CUInt64 { return [x & 0xFFFFFFFF, x >> 32]; } -export function pack32 (lo: number, hi: number): CUInt64 { +export function pack32(lo: number, hi: number): CUInt64 { return [lo, hi]; } -export function unpack32 (x: CUInt64): [number, number] { +export function unpack32(x: CUInt64): [number, number] { return [x[0], x[1]]; } diff --git a/src/mono/browser/runtime/cwraps.ts b/src/mono/browser/runtime/cwraps.ts index d6a24b65d13279..c5eb62422725f5 100644 --- a/src/mono/browser/runtime/cwraps.ts +++ b/src/mono/browser/runtime/cwraps.ts @@ -8,10 +8,10 @@ import type { MonoMethod, MonoObject, MonoType, MonoObjectRef, MonoStringRef, JSMarshalerArguments, PThreadPtr } from "./types/internal"; -import type {VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer} from "./types/emscripten"; -import {Module, runtimeHelpers} from "./globals"; -import {mono_log_error} from "./logging"; -import {mono_assert} from "./globals"; +import type { VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer } from "./types/emscripten"; +import { Module, runtimeHelpers } from "./globals"; +import { mono_log_error } from "./logging"; +import { mono_assert } from "./globals"; type SigLine = [lazyOrSkip: boolean | (() => boolean), name: string, returnType: string | null, argTypes?: string[], opts?: any]; @@ -283,7 +283,7 @@ export const enum I52Error { const fastCwrapTypes = ["void", "number", null]; -function cwrap (name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { +function cwrap(name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { // Attempt to bypass emscripten's generated wrapper if it is safe to do so let fce = // Special cwrap options disable the fast path @@ -314,7 +314,7 @@ function cwrap (name: string, returnType: string | null, argTypes: string[] | un return fce; } -export function init_c_exports (): void { +export function init_c_exports(): void { const fns = [...fn_signatures]; for (const sig of fns) { const wf: any = wrapped_c_functions; @@ -322,7 +322,7 @@ export function init_c_exports (): void { const maybeSkip = typeof lazyOrSkip === "function"; if (lazyOrSkip === true || maybeSkip) { // lazy init on first run - wf[name] = function (...args: any[]) { + wf[name] = function(...args: any[]) { const isNotSkipped = !maybeSkip || !lazyOrSkip(); mono_assert(isNotSkipped, () => `cwrap ${name} should not be called when binding was skipped`); const fce = cwrap(name, returnType, argTypes, opts); diff --git a/src/mono/browser/runtime/debug.ts b/src/mono/browser/runtime/debug.ts index 0e880cc110c6d9..b86b0347ba7af1 100644 --- a/src/mono/browser/runtime/debug.ts +++ b/src/mono/browser/runtime/debug.ts @@ -1,15 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {INTERNAL, Module, loaderHelpers, runtimeHelpers} from "./globals"; -import {toBase64StringImpl} from "./base64"; +import { INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals"; +import { toBase64StringImpl } from "./base64"; import cwraps from "./cwraps"; -import {VoidPtr, CharPtr} from "./types/emscripten"; -import {mono_log_warn} from "./logging"; -import {forceThreadMemoryViewRefresh, localHeapViewU8} from "./memory"; -import {utf8ToString} from "./strings"; +import { VoidPtr, CharPtr } from "./types/emscripten"; +import { mono_log_warn } from "./logging"; +import { forceThreadMemoryViewRefresh, localHeapViewU8 } from "./memory"; +import { utf8ToString } from "./strings"; const commands_received: any = new Map(); -commands_received.remove = function (key: number): CommandResponse { +commands_received.remove = function(key: number): CommandResponse { const value = this.get(key); this.delete(key); return value; }; let _call_function_res_cache: any = {}; @@ -19,7 +19,7 @@ let _debugger_buffer: VoidPtr; let _assembly_name_str: string; //keep this variable, it's used by BrowserDebugProxy let _entrypoint_method_token: number; //keep this variable, it's used by BrowserDebugProxy -export function mono_wasm_runtime_ready (): void { +export function mono_wasm_runtime_ready(): void { INTERNAL.mono_wasm_runtime_is_ready = runtimeHelpers.mono_wasm_runtime_is_ready = true; // FIXME: where should this go? @@ -33,7 +33,7 @@ export function mono_wasm_runtime_ready (): void { debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data_to_pause (base64String: string): void { +export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String: string): void { //keep this console.assert, otherwise optimization will remove the assignments // eslint-disable-next-line no-console console.assert(true, `mono_wasm_fire_debugger_agent_message_with_data ${base64String}`); @@ -41,12 +41,12 @@ export function mono_wasm_fire_debugger_agent_message_with_data_to_pause (base64 debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data (data: number, len: number): void { +export function mono_wasm_fire_debugger_agent_message_with_data(data: number, len: number): void { const base64String = toBase64StringImpl(new Uint8Array(localHeapViewU8().buffer, data, len)); mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String); } -export function mono_wasm_add_dbg_command_received (res_ok: boolean, id: number, buffer: number, buffer_len: number): void { +export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number, buffer: number, buffer_len: number): void { const dbg_command = new Uint8Array(localHeapViewU8().buffer, buffer, buffer_len); const base64String = toBase64StringImpl(dbg_command); const buffer_obj = { @@ -61,7 +61,7 @@ export function mono_wasm_add_dbg_command_received (res_ok: boolean, id: number, commands_received.set(id, buffer_obj); } -function mono_wasm_malloc_and_set_debug_buffer (command_parameters: string) { +function mono_wasm_malloc_and_set_debug_buffer(command_parameters: string) { if (command_parameters.length > _debugger_buffer_len) { if (_debugger_buffer) Module._free(_debugger_buffer); @@ -75,25 +75,25 @@ function mono_wasm_malloc_and_set_debug_buffer (command_parameters: string) { } } -export function mono_wasm_send_dbg_command_with_parms (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { +export function mono_wasm_send_dbg_command_with_parms(id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); cwraps.mono_wasm_send_dbg_command_with_parms(id, command_set, command, _debugger_buffer, length, valtype, newvalue.toString()); - const {res_ok, res} = commands_received.remove(id); + const { res_ok, res } = commands_received.remove(id); if (!res_ok) throw new Error("Failed on mono_wasm_send_dbg_command_with_parms"); return res; } -export function mono_wasm_send_dbg_command (id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { +export function mono_wasm_send_dbg_command(id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); cwraps.mono_wasm_send_dbg_command(id, command_set, command, _debugger_buffer, command_parameters.length); - const {res_ok, res} = commands_received.remove(id); + const { res_ok, res } = commands_received.remove(id); if (!res_ok) throw new Error("Failed on mono_wasm_send_dbg_command"); @@ -101,24 +101,24 @@ export function mono_wasm_send_dbg_command (id: number, command_set: number, com } -export function mono_wasm_get_dbg_command_info (): CommandResponseResult { - const {res_ok, res} = commands_received.remove(0); +export function mono_wasm_get_dbg_command_info(): CommandResponseResult { + const { res_ok, res } = commands_received.remove(0); if (!res_ok) throw new Error("Failed on mono_wasm_get_dbg_command_info"); return res; } -export function mono_wasm_debugger_resume (): void { +export function mono_wasm_debugger_resume(): void { forceThreadMemoryViewRefresh(); } -export function mono_wasm_detach_debugger (): void { +export function mono_wasm_detach_debugger(): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(false); } -export function mono_wasm_change_debugger_log_level (level: number): void { +export function mono_wasm_change_debugger_log_level(level: number): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_change_debugger_log_level(level); } @@ -126,7 +126,7 @@ export function mono_wasm_change_debugger_log_level (level: number): void { /** * Raises an event for the debug proxy */ -export function mono_wasm_raise_debug_event (event: WasmEvent, args = {}): void { +export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void { if (typeof event !== "object") throw new Error(`event must be an object, but got ${JSON.stringify(event)}`); @@ -140,7 +140,7 @@ export function mono_wasm_raise_debug_event (event: WasmEvent, args = {}): void console.debug("mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae", JSON.stringify(event), JSON.stringify(args)); } -export function mono_wasm_wait_for_debugger (): Promise { +export function mono_wasm_wait_for_debugger(): Promise { return new Promise((resolve) => { const interval = setInterval(() => { if (runtimeHelpers.waitForDebugger != 1) { @@ -152,14 +152,14 @@ export function mono_wasm_wait_for_debugger (): Promise { }); } -export function mono_wasm_debugger_attached (): void { +export function mono_wasm_debugger_attached(): void { if (runtimeHelpers.waitForDebugger == -1) runtimeHelpers.waitForDebugger = 1; forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(true); } -export function mono_wasm_set_entrypoint_breakpoint (entrypoint_method_token: number): void { +export function mono_wasm_set_entrypoint_breakpoint(entrypoint_method_token: number): void { //keep these assignments, these values are used by BrowserDebugProxy _assembly_name_str = loaderHelpers.config.mainAssemblyName + ".dll"; _entrypoint_method_token = entrypoint_method_token; @@ -172,7 +172,7 @@ export function mono_wasm_set_entrypoint_breakpoint (entrypoint_method_token: nu forceThreadMemoryViewRefresh(); } -function _create_proxy_from_object_id (objectId: string, details: any) { +function _create_proxy_from_object_id(objectId: string, details: any) { if (objectId.startsWith("dotnet:array:")) { let ret: Array; if (details.items === undefined) { @@ -192,10 +192,10 @@ function _create_proxy_from_object_id (objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get () { + get() { return mono_wasm_send_dbg_command(prop.get.id, prop.get.commandSet, prop.get.command, prop.get.buffer); }, - set: function (newValue) { + set: function(newValue) { mono_wasm_send_dbg_command_with_parms(prop.set.id, prop.set.commandSet, prop.set.command, prop.set.buffer, prop.set.length, prop.set.valtype, newValue); return true; } } @@ -204,10 +204,10 @@ function _create_proxy_from_object_id (objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get () { + get() { return prop.value; }, - set: function (newValue) { + set: function(newValue) { mono_wasm_send_dbg_command_with_parms(prop.set.id, prop.set.commandSet, prop.set.command, prop.set.buffer, prop.set.length, prop.set.valtype, newValue); return true; } } @@ -219,7 +219,7 @@ function _create_proxy_from_object_id (objectId: string, details: any) { return proxy; } -export function mono_wasm_call_function_on (request: CallRequest): CFOResponse { +export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { forceThreadMemoryViewRefresh(); if (request.arguments != undefined && !Array.isArray(request.arguments)) @@ -245,16 +245,16 @@ export function mono_wasm_call_function_on (request: CallRequest): CFOResponse { const fn_res = fn_defn(proxy); if (fn_res === undefined) - return {type: "undefined"}; + return { type: "undefined" }; if (Object(fn_res) !== fn_res) { if (typeof (fn_res) == "object" && fn_res == null) - return {type: typeof (fn_res), subtype: `${fn_res}`, value: null}; - return {type: typeof (fn_res), description: `${fn_res}`, value: `${fn_res}`}; + return { type: typeof (fn_res), subtype: `${fn_res}`, value: null }; + return { type: typeof (fn_res), description: `${fn_res}`, value: `${fn_res}` }; } if (request.returnByValue && fn_res.subtype == undefined) - return {type: "object", value: fn_res}; + return { type: "object", value: fn_res }; if (Object.getPrototypeOf(fn_res) == Array.prototype) { @@ -273,12 +273,12 @@ export function mono_wasm_call_function_on (request: CallRequest): CFOResponse { } if (fn_res == proxy) - return {type: "object", className: "Object", description: "Object", objectId: objId}; + return { type: "object", className: "Object", description: "Object", objectId: objId }; const fn_res_id = _cache_call_function_res(fn_res); - return {type: "object", className: "Object", description: "Object", objectId: fn_res_id}; + return { type: "object", className: "Object", description: "Object", objectId: fn_res_id }; } -function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { +function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { if (!(objectId in _call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); @@ -299,7 +299,7 @@ function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { if (typeof prop_desc.value == "object") { // convert `{value: { type='object', ... }}` // to `{ name: 'foo', value: { type='object', ... }} - new_obj = Object.assign({name: k}, prop_desc); + new_obj = Object.assign({ name: k }, prop_desc); } else if (prop_desc.value !== undefined) { // This is needed for values that were not added by us, // thus are like { value: 5 } @@ -310,7 +310,7 @@ function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { new_obj = { name: k, // merge/add `type` and `description` to `d.value` - value: Object.assign({type: (typeof prop_desc.value), description: "" + prop_desc.value}, + value: Object.assign({ type: (typeof prop_desc.value), description: "" + prop_desc.value }, prop_desc) }; } else if (prop_desc.get !== undefined) { @@ -327,36 +327,36 @@ function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { } }; } else { - new_obj = {name: k, value: {type: "symbol", value: "", description: ""}}; + new_obj = { name: k, value: { type: "symbol", value: "", description: "" } }; } res_details.push(new_obj); }); - return {__value_as_json_string__: JSON.stringify(res_details)}; + return { __value_as_json_string__: JSON.stringify(res_details) }; } type ValueAsJsonString = { __value_as_json_string__: string; } -export function mono_wasm_get_details (objectId: string, args = {}): ValueAsJsonString { +export function mono_wasm_get_details(objectId: string, args = {}): ValueAsJsonString { forceThreadMemoryViewRefresh(); return _get_cfo_res_details(`dotnet:cfo_res:${objectId}`, args); } -function _cache_call_function_res (obj: any) { +function _cache_call_function_res(obj: any) { const id = `dotnet:cfo_res:${_next_call_function_res_id++}`; _call_function_res_cache[id] = obj; return id; } -export function mono_wasm_release_object (objectId: string): void { +export function mono_wasm_release_object(objectId: string): void { if (objectId in _call_function_res_cache) delete _call_function_res_cache[objectId]; } -export function mono_wasm_debugger_log (level: number, message_ptr: CharPtr): void { +export function mono_wasm_debugger_log(level: number, message_ptr: CharPtr): void { forceThreadMemoryViewRefresh(); const message = utf8ToString(message_ptr); diff --git a/src/mono/browser/runtime/diagnostics-mock.d.ts b/src/mono/browser/runtime/diagnostics-mock.d.ts index 9ccb36762982d2..8cf424b6a9d12d 100644 --- a/src/mono/browser/runtime/diagnostics-mock.d.ts +++ b/src/mono/browser/runtime/diagnostics-mock.d.ts @@ -71,4 +71,4 @@ interface MockEnvironment { expectAdvertise: FilterPredicate; } -export {MockEnvironment, MockScriptConnection, PromiseAndController}; +export { MockEnvironment, MockScriptConnection, PromiseAndController }; diff --git a/src/mono/browser/runtime/diagnostics/browser/controller.ts b/src/mono/browser/runtime/diagnostics/browser/controller.ts index 948c92d9141602..799972b1fd0e66 100644 --- a/src/mono/browser/runtime/diagnostics/browser/controller.ts +++ b/src/mono/browser/runtime/diagnostics/browser/controller.ts @@ -3,14 +3,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {threads_c_functions as cwraps} from "../../cwraps"; -import {INTERNAL, mono_assert} from "../../globals"; -import {mono_log_info, mono_log_debug, mono_log_warn} from "../../logging"; -import {withStackAlloc, getI32} from "../../memory"; -import {waitForThread} from "../../pthreads"; -import {isDiagnosticMessage, makeDiagnosticServerControlCommand} from "../shared/controller-commands"; +import { threads_c_functions as cwraps } from "../../cwraps"; +import { INTERNAL, mono_assert } from "../../globals"; +import { mono_log_info, mono_log_debug, mono_log_warn } from "../../logging"; +import { withStackAlloc, getI32 } from "../../memory"; +import { waitForThread } from "../../pthreads"; +import { isDiagnosticMessage, makeDiagnosticServerControlCommand } from "../shared/controller-commands"; import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import {PThreadPtr, Thread} from "../../types/internal"; +import { PThreadPtr, Thread } from "../../types/internal"; /// An object that can be used to control the diagnostic server. export interface ServerController { @@ -18,23 +18,23 @@ export interface ServerController { } class ServerControllerImpl implements ServerController { - constructor (private server: Thread) { + constructor(private server: Thread) { server.port.addEventListener("message", this.onServerReply.bind(this)); } - start (): void { + start(): void { mono_log_debug("signaling the diagnostic server to start"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("start")); } - stop (): void { + stop(): void { mono_log_debug("signaling the diagnostic server to stop"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("stop")); } - postServerAttachToRuntime (): void { + postServerAttachToRuntime(): void { mono_log_debug("signal the diagnostic server to attach to the runtime"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("attach_to_runtime")); } - onServerReply (event: MessageEvent): void { + onServerReply(event: MessageEvent): void { const d = event.data; if (isDiagnosticMessage(d)) { switch (d.cmd) { @@ -48,13 +48,13 @@ class ServerControllerImpl implements ServerController { let serverController: ServerController | null = null; -export function getController (): ServerController { +export function getController(): ServerController { if (serverController) return serverController; throw new Error("unexpected no server controller"); } -export async function startDiagnosticServer (websocket_url: string): Promise { +export async function startDiagnosticServer(websocket_url: string): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const sizeOfPthreadT = 4; mono_log_info(`starting the diagnostic server url: ${websocket_url}`); diff --git a/src/mono/browser/runtime/diagnostics/index.ts b/src/mono/browser/runtime/diagnostics/index.ts index e7b12703657ff7..a9d6f9414267ae 100644 --- a/src/mono/browser/runtime/diagnostics/index.ts +++ b/src/mono/browser/runtime/diagnostics/index.ts @@ -6,16 +6,16 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import type { DiagnosticOptions, } from "./shared/types"; -import {is_nullish} from "../types/internal"; -import type {VoidPtr} from "../types/emscripten"; -import {getController, startDiagnosticServer} from "./browser/controller"; +import { is_nullish } from "../types/internal"; +import type { VoidPtr } from "../types/emscripten"; +import { getController, startDiagnosticServer } from "./browser/controller"; import * as memory from "../memory"; -import {mono_log_warn} from "../logging"; -import {mono_assert, runtimeHelpers} from "../globals"; +import { mono_log_warn } from "../logging"; +import { mono_assert, runtimeHelpers } from "../globals"; // called from C on the main thread -export function mono_wasm_event_pipe_early_startup_callback (): void { +export function mono_wasm_event_pipe_early_startup_callback(): void { if (WasmEnableThreads) { return; } @@ -36,7 +36,7 @@ let diagnosticsServerEnabled = false; let diagnosticsInitialized = false; -export async function mono_wasm_init_diagnostics (): Promise { +export async function mono_wasm_init_diagnostics(): Promise { if (!WasmEnableThreads) return; if (diagnosticsInitialized) return; @@ -60,7 +60,7 @@ export async function mono_wasm_init_diagnostics (): Promise { } } -function boolsyOption (x: string | boolean): boolean { +function boolsyOption(x: string | boolean): boolean { if (x === true || x === false) return x; if (typeof x === "string") { @@ -77,7 +77,7 @@ function boolsyOption (x: string | boolean): boolean { /// The environment variables are: /// * DOTNET_DiagnosticPorts /// -function diagnostic_options_from_environment (): DiagnosticOptions | null { +function diagnostic_options_from_environment(): DiagnosticOptions | null { const val = runtimeHelpers.config.environmentVariables ? runtimeHelpers.config.environmentVariables["DOTNET_DiagnosticPorts"] : undefined; if (is_nullish(val)) return null; @@ -88,7 +88,7 @@ function diagnostic_options_from_environment (): DiagnosticOptions | null { /// Parse a DOTNET_DiagnosticPorts string and return a DiagnosticOptions object. /// See https://docs.microsoft.com/en-us/dotnet/core/diagnostics/diagnostic-port#configure-additional-diagnostic-ports -function diagnostic_options_from_ports_spec (val: string): DiagnosticOptions | null { +function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | null { if (val === "") return null; const ports = val.split(";"); @@ -140,7 +140,7 @@ function diagnostic_options_from_ports_spec (val: string): DiagnosticOptions | n } -export function mono_wasm_diagnostic_server_on_runtime_server_init (out_options: VoidPtr): void { +export function mono_wasm_diagnostic_server_on_runtime_server_init(out_options: VoidPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); if (diagnosticsServerEnabled) { /* called on the main thread when the runtime is sufficiently initialized */ diff --git a/src/mono/browser/runtime/diagnostics/mock/environment.ts b/src/mono/browser/runtime/diagnostics/mock/environment.ts index b266042bb470c1..0de8c8b7acafc2 100644 --- a/src/mono/browser/runtime/diagnostics/mock/environment.ts +++ b/src/mono/browser/runtime/diagnostics/mock/environment.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {RemoveCommandSetAndId, EventPipeCommandCollectTracing2, EventPipeCommandStopTracing} from "../server_pthread/protocol-client-commands"; -import type {FilterPredicate, MockEnvironment} from "./types"; +import type { RemoveCommandSetAndId, EventPipeCommandCollectTracing2, EventPipeCommandStopTracing } from "../server_pthread/protocol-client-commands"; +import type { FilterPredicate, MockEnvironment } from "./types"; import Serializer from "../server_pthread/ipc-protocol/base-serializer"; -import {CommandSetId, EventPipeCommandId, ProcessCommandId} from "../server_pthread/ipc-protocol/types"; -import {assertNever} from "../../types/internal"; -import {pthread_self} from "../../pthreads"; -import {createPromiseController, mono_assert} from "../../globals"; +import { CommandSetId, EventPipeCommandId, ProcessCommandId } from "../server_pthread/ipc-protocol/types"; +import { assertNever } from "../../types/internal"; +import { pthread_self } from "../../pthreads"; +import { createPromiseController, mono_assert } from "../../globals"; -function expectAdvertise (data: ArrayBuffer): boolean { +function expectAdvertise(data: ArrayBuffer): boolean { if (typeof (data) === "string") { assertNever(data); } else { @@ -21,7 +21,7 @@ function expectAdvertise (data: ArrayBuffer): boolean { } } -function expectOk (payloadLength?: number): FilterPredicate { +function expectOk(payloadLength?: number): FilterPredicate { return (data) => { if (typeof (data) === "string") { assertNever(data); @@ -33,7 +33,7 @@ function expectOk (payloadLength?: number): FilterPredicate { }; } -function extractOkSessionID (data: ArrayBuffer): number { +function extractOkSessionID(data: ArrayBuffer): number { if (typeof (data) === "string") { assertNever(data); } else { @@ -45,13 +45,13 @@ function extractOkSessionID (data: ArrayBuffer): number { } } -function computeStringByteLength (s: string | null): number { +function computeStringByteLength(s: string | null): number { if (s === undefined || s === null || s === "") return 4; // just length of zero return 4 + 2 * s.length + 2; // length + UTF16 + null } -function computeCollectTracing2PayloadByteLength (payload: RemoveCommandSetAndId): number { +function computeCollectTracing2PayloadByteLength(payload: RemoveCommandSetAndId): number { let len = 0; len += 4; // circularBufferMB len += 4; // format @@ -66,11 +66,11 @@ function computeCollectTracing2PayloadByteLength (payload: RemoveCommandSetAndId return len; } -function makeEventPipeCollectTracing2 (payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeCollectTracing2(payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = computeCollectTracing2PayloadByteLength(payload); const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = {pos: 0}; + const pos = { pos: 0 }; Serializer.serializeHeader(buffer, pos, CommandSetId.EventPipe, EventPipeCommandId.CollectTracing2, messageLength); Serializer.serializeUint32(buffer, pos, payload.circularBufferMB); Serializer.serializeUint32(buffer, pos, payload.format); @@ -85,40 +85,40 @@ function makeEventPipeCollectTracing2 (payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeStopTracing(payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = 8; const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = {pos: 0}; + const pos = { pos: 0 }; Serializer.serializeHeader(buffer, pos, CommandSetId.EventPipe, EventPipeCommandId.StopTracing, messageLength); Serializer.serializeUint32(buffer, pos, payload.sessionID); Serializer.serializeUint32(buffer, pos, 0); return buffer; } -function makeProcessResumeRuntime (): Uint8Array { +function makeProcessResumeRuntime(): Uint8Array { const payloadLength = 0; const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); - const pos = {pos: 0}; + const pos = { pos: 0 }; Serializer.serializeHeader(buffer, pos, CommandSetId.Process, ProcessCommandId.ResumeRuntime, messageLength); return buffer; } -function postMessageToBrowser (message: any, transferable?: Transferable[]): void { +function postMessageToBrowser(message: any, transferable?: Transferable[]): void { pthread_self.postMessageToBrowser({ type: "diagnostic_server_mock", ...message }, transferable); } -function addEventListenerFromBrowser (cmd: string, listener: (data: any) => void) { +function addEventListenerFromBrowser(cmd: string, listener: (data: any) => void) { pthread_self.addEventListenerFromBrowser((event) => { if (event.data.cmd === cmd) listener(event.data); }); } -export function createMockEnvironment (): MockEnvironment { +export function createMockEnvironment(): MockEnvironment { const command = { makeEventPipeCollectTracing2, makeEventPipeStopTracing, diff --git a/src/mono/browser/runtime/diagnostics/mock/index.ts b/src/mono/browser/runtime/diagnostics/mock/index.ts index e5928ecef7d41e..81304154071332 100644 --- a/src/mono/browser/runtime/diagnostics/mock/index.ts +++ b/src/mono/browser/runtime/diagnostics/mock/index.ts @@ -3,10 +3,10 @@ import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import {createMockEnvironment} from "./environment"; -import type {MockEnvironment, MockScriptConnection} from "./export-types"; -import {assertNever} from "../../types/internal"; -import {mono_log_debug, mono_log_warn} from "../../logging"; +import { createMockEnvironment } from "./environment"; +import type { MockEnvironment, MockScriptConnection } from "./export-types"; +import { assertNever } from "../../types/internal"; +import { mono_log_debug, mono_log_warn } from "../../logging"; export interface MockRemoteSocket extends EventTarget { addEventListener(type: T, listener: (this: MockRemoteSocket, ev: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void; @@ -25,39 +25,39 @@ type MockConnectionScript = (engine: MockScriptConnection) => Promise; export type MockScript = (env: MockEnvironment) => MockConnectionScript[]; let MockImplConstructor: new (script: MockScript) => Mock; -export function mock (script: MockScript): Mock { +export function mock(script: MockScript): Mock { if (monoDiagnosticsMock) { if (!MockImplConstructor) { class MockScriptEngineSocketImpl implements MockRemoteSocket { - constructor (private readonly engine: MockScriptEngineImpl) { } - send (data: string | ArrayBuffer): void { + constructor(private readonly engine: MockScriptEngineImpl) { } + send(data: string | ArrayBuffer): void { mono_log_debug(`mock ${this.engine.ident} client sent: `, data); let event: MessageEvent | null = null; if (typeof data === "string") { - event = new MessageEvent("message", {data}); + event = new MessageEvent("message", { data }); } else { const message = new ArrayBuffer(data.byteLength); const messageView = new Uint8Array(message); const dataView = new Uint8Array(data); messageView.set(dataView); - event = new MessageEvent("message", {data: message}); + event = new MessageEvent("message", { data: message }); } this.engine.mockReplyEventTarget.dispatchEvent(event); } addEventListener(event: T, listener: (event: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener (event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { + addEventListener(event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { mono_log_debug(`mock ${this.engine.ident} client added listener for ${event}`); this.engine.eventTarget.addEventListener(event, listener, options); } - removeEventListener (event: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener(event: string, listener: EventListenerOrEventListenerObject): void { mono_log_debug(`mock ${this.engine.ident} client removed listener for ${event}`); this.engine.eventTarget.removeEventListener(event, listener); } - close (): void { + close(): void { mono_log_debug(`mock ${this.engine.ident} client closed`); this.engine.mockReplyEventTarget.dispatchEvent(new CloseEvent("close")); } - dispatchEvent (ev: Event): boolean { + dispatchEvent(ev: Event): boolean { return this.engine.eventTarget.dispatchEvent(ev); } } @@ -68,11 +68,11 @@ export function mock (script: MockScript): Mock { readonly eventTarget: EventTarget = new EventTarget(); // eventTarget that the MockReplySocket with send() to readonly mockReplyEventTarget: EventTarget = new EventTarget(); - constructor (readonly ident: number) { + constructor(readonly ident: number) { this.socket = new MockScriptEngineSocketImpl(this); } - reply (data: ArrayBuffer | Uint8Array) { + reply(data: ArrayBuffer | Uint8Array) { mono_log_debug(`mock ${this.ident} reply:`, data); let sendData: ArrayBuffer; if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -88,10 +88,10 @@ export function mock (script: MockScript): Mock { mono_log_warn(`mock ${this.ident} reply got wrong kind of reply data, expected ArrayBuffer`, data); assertNever(data); } - this.eventTarget.dispatchEvent(new MessageEvent("message", {data: sendData})); + this.eventTarget.dispatchEvent(new MessageEvent("message", { data: sendData })); } - processSend (onMessage: (data: ArrayBuffer) => any): Promise { + processSend(onMessage: (data: ArrayBuffer) => any): Promise { mono_log_debug(`mock ${this.ident} processSend`); return new Promise((resolve, reject) => { @@ -112,7 +112,7 @@ export function mock (script: MockScript): Mock { }); } - async waitForSend (filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { + async waitForSend(filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { mono_log_debug(`mock ${this.ident} waitForSend`); const data = await new Promise((resolve) => { @@ -125,7 +125,7 @@ export function mock (script: MockScript): Mock { mono_log_debug(`mock ${this.ident} waitForSend got:`, data.byteLength); resolve(data); - }, {once: true}); + }, { once: true }); }); if (!filter(data)) { throw new Error("Unexpected data"); @@ -141,7 +141,7 @@ export function mock (script: MockScript): Mock { openCount: number; engines: MockScriptEngineImpl[]; connectionScripts: MockConnectionScript[]; - constructor (public readonly mockScript: MockScript) { + constructor(public readonly mockScript: MockScript) { const env: MockEnvironment = createMockEnvironment(); this.connectionScripts = mockScript(env); this.openCount = 0; @@ -151,13 +151,13 @@ export function mock (script: MockScript): Mock { this.engines[i] = new MockScriptEngineImpl(i); } } - open (): MockRemoteSocket { + open(): MockRemoteSocket { const i = this.openCount++; mono_log_debug(`mock ${i} open`); return this.engines[i].socket; } - async run (): Promise { + async run(): Promise { const scripts = this.connectionScripts; await Promise.all(scripts.map((script, i) => script(this.engines[i]))); } diff --git a/src/mono/browser/runtime/diagnostics/mock/types.ts b/src/mono/browser/runtime/diagnostics/mock/types.ts index 8a2fa4bacfb15c..30c533595413c0 100644 --- a/src/mono/browser/runtime/diagnostics/mock/types.ts +++ b/src/mono/browser/runtime/diagnostics/mock/types.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. -import type {PromiseAndController} from "../../types/internal"; +import type { PromiseAndController } from "../../types/internal"; import type { RemoveCommandSetAndId, EventPipeCommandCollectTracing2, diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts index e1b6b7222c0470..b6bb8084a26845 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.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. -import {MockRemoteSocket} from "../mock"; +import { MockRemoteSocket } from "../mock"; // the common bits that we depend on from a real WebSocket or a MockRemoteSocket used for testing export interface CommonSocket { @@ -17,7 +17,7 @@ export interface CommonSocket { type AssignableTo = Q extends T ? true : false; -function static_assert (x: Cond): asserts x is Cond { /*empty*/ } +function static_assert(x: Cond): asserts x is Cond { /*empty*/ } { static_assert>(true); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts index a499c4395233e9..4da6b11b69ce31 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts @@ -5,19 +5,19 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import {PromiseAndController, assertNever} from "../../types/internal"; -import {pthread_self} from "../../pthreads"; -import {createPromiseController, mono_assert} from "../../globals"; -import {threads_c_functions as cwraps} from "../../cwraps"; -import {EventPipeSessionIDImpl} from "../shared/types"; -import {CharPtr} from "../../types/emscripten"; +import { PromiseAndController, assertNever } from "../../types/internal"; +import { pthread_self } from "../../pthreads"; +import { createPromiseController, mono_assert } from "../../globals"; +import { threads_c_functions as cwraps } from "../../cwraps"; +import { EventPipeSessionIDImpl } from "../shared/types"; +import { CharPtr } from "../../types/emscripten"; import { DiagnosticServerControlCommand, isDiagnosticMessage } from "../shared/controller-commands"; -import {importAndInstantiateMock} from "./mock-remote"; -import type {Mock, MockRemoteSocket} from "../mock"; +import { importAndInstantiateMock } from "./mock-remote"; +import type { Mock, MockRemoteSocket } from "../mock"; import { isEventPipeCommand, isProcessCommand, @@ -29,8 +29,8 @@ import { isProcessCommandResumeRuntime, EventPipeCommandCollectTracing2, } from "./protocol-client-commands"; -import {makeEventPipeStreamingSession} from "./streaming-session"; -import {CommonSocket} from "./common-socket"; +import { makeEventPipeStreamingSession } from "./streaming-session"; +import { CommonSocket } from "./common-socket"; import { createProtocolSocket, dotnetDiagnosticsServerProtocolCommandEvent, ProtocolCommandEvent, @@ -47,24 +47,24 @@ import { createAdvertise, createBinaryCommandOKReply, } from "./ipc-protocol/serializer"; -import {mono_log_error, mono_log_info, mono_log_debug, mono_log_warn} from "../../logging"; -import {utf8ToString} from "../../strings"; +import { mono_log_error, mono_log_info, mono_log_debug, mono_log_warn } from "../../logging"; +import { utf8ToString } from "../../strings"; -function addOneShotProtocolCommandEventListener (src: EventTarget): Promise { +function addOneShotProtocolCommandEventListener(src: EventTarget): Promise { return new Promise((resolve) => { const listener = (event: Event) => { resolve(event as ProtocolCommandEvent); }; - src.addEventListener(dotnetDiagnosticsServerProtocolCommandEvent, listener, {once: true}); + src.addEventListener(dotnetDiagnosticsServerProtocolCommandEvent, listener, { once: true }); }); } -function addOneShotOpenEventListenr (src: EventTarget): Promise { +function addOneShotOpenEventListenr(src: EventTarget): Promise { return new Promise((resolve) => { const listener = (event: Event) => { resolve(event); }; - src.addEventListener("open", listener, {once: true}); + src.addEventListener("open", listener, { once: true }); }); } @@ -77,7 +77,7 @@ class DiagnosticServerImpl implements DiagnosticServer { readonly mocked: Promise | undefined; runtimeResumed = false; - constructor (websocketUrl: string, mockPromise?: Promise) { + constructor(websocketUrl: string, mockPromise?: Promise) { this.websocketUrl = websocketUrl; pthread_self.addEventListenerFromBrowser(this.onMessageFromMainThread.bind(this)); this.mocked = monoDiagnosticsMock ? mockPromise : undefined; @@ -89,21 +89,21 @@ class DiagnosticServerImpl implements DiagnosticServer { private attachToRuntimeController = createPromiseController().promise_control; - start (): void { + start(): void { mono_log_info(`starting diagnostic server with url: ${this.websocketUrl}`); this.startRequestedController.resolve(); } - stop (): void { + stop(): void { this.stopRequested = true; this.stopRequestedController.resolve(); } - attachToRuntime (): void { + attachToRuntime(): void { cwraps.mono_wasm_diagnostic_server_thread_attach_to_runtime(); this.attachToRuntimeController.resolve(); } - async serverLoop (this: DiagnosticServerImpl): Promise { + async serverLoop(this: DiagnosticServerImpl): Promise { await this.startRequestedController.promise; await this.attachToRuntimeController.promise; // can't start tracing until we've attached to the runtime while (!this.stopRequested) { @@ -123,7 +123,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async openSocket (): Promise { + async openSocket(): Promise { if (monoDiagnosticsMock && this.mocked) { return (await this.mocked).open(); } else { @@ -136,7 +136,7 @@ class DiagnosticServerImpl implements DiagnosticServer { private openCount = 0; - async advertiseAndWaitForClient (): Promise { + async advertiseAndWaitForClient(): Promise { try { const connNum = this.openCount++; mono_log_debug("opening websocket and sending ADVR_V1", connNum); @@ -152,7 +152,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async parseAndDispatchMessage (ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { + async parseAndDispatchMessage(ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { try { const cmd = this.parseCommand(message, connNum); if (cmd === null) { @@ -171,7 +171,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - sendAdvertise (ws: CommonSocket) { + sendAdvertise(ws: CommonSocket) { /* FIXME: don't use const fake guid and fake process id. In dotnet-dsrouter the pid is used * as a dictionary key,so if we ever supprt multiple runtimes, this might need to change. */ @@ -182,7 +182,7 @@ class DiagnosticServerImpl implements DiagnosticServer { ws.send(buf); } - parseCommand (message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { + parseCommand(message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { mono_log_debug("parsing byte command: ", message.data, connNum); const result = parseProtocolCommand(message.data); mono_log_debug("parsed byte command: ", result, connNum); @@ -194,7 +194,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - onMessageFromMainThread (this: DiagnosticServerImpl, event: MessageEvent): void { + onMessageFromMainThread(this: DiagnosticServerImpl, event: MessageEvent): void { const d = event.data; if (d && isDiagnosticMessage(d)) { this.controlCommandReceived(d as DiagnosticServerControlCommand); @@ -202,7 +202,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } /// dispatch commands received from the main thread - controlCommandReceived (cmd: DiagnosticServerControlCommand): void { + controlCommandReceived(cmd: DiagnosticServerControlCommand): void { switch (cmd.cmd) { case "start": this.start(); @@ -220,7 +220,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch EventPipe commands received from the diagnostic client - async dispatchEventPipeCommand (ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { + async dispatchEventPipeCommand(ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { if (isEventPipeCommandCollectTracing2(cmd)) { await this.collectTracingEventPipe(ws, cmd); } else if (isEventPipeCommandStopTracing(cmd)) { @@ -230,12 +230,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - postClientReplyOK (ws: CommonSocket, payload?: Uint8Array): void { + postClientReplyOK(ws: CommonSocket, payload?: Uint8Array): void { // FIXME: send a binary response for non-mock sessions! ws.send(createBinaryCommandOKReply(payload)); } - async stopEventPipe (ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { + async stopEventPipe(ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { mono_log_debug("stopEventPipe", sessionID); cwraps.mono_wasm_event_pipe_session_disable(sessionID); // we might send OK before the session is actually stopped since the websocket is async @@ -243,7 +243,7 @@ class DiagnosticServerImpl implements DiagnosticServer { this.postClientReplyOK(ws); } - async collectTracingEventPipe (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { + async collectTracingEventPipe(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { const session = await makeEventPipeStreamingSession(ws, cmd); const sessionIDbuf = new Uint8Array(8); // 64 bit sessionIDbuf[0] = session.sessionID & 0xFF; @@ -257,7 +257,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch Process commands received from the diagnostic client - async dispatchProcessCommand (ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { + async dispatchProcessCommand(ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { if (isProcessCommandResumeRuntime(cmd)) { this.processResumeRuntime(ws); } else { @@ -265,12 +265,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - processResumeRuntime (ws: WebSocket | MockRemoteSocket): void { + processResumeRuntime(ws: WebSocket | MockRemoteSocket): void { this.postClientReplyOK(ws); this.resumeRuntime(); } - resumeRuntime (): void { + resumeRuntime(): void { if (!this.runtimeResumed) { mono_log_debug("resuming runtime startup"); cwraps.mono_wasm_diagnostic_server_post_resume_runtime(); @@ -279,7 +279,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } -function parseProtocolCommand (data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { +function parseProtocolCommand(data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { if (isBinaryProtocolCommand(data)) { return parseBinaryProtocolCommand(data); } else { @@ -288,14 +288,14 @@ function parseProtocolCommand (data: ArrayBuffer | BinaryProtocolCommand): Parse } /// Called by the runtime to initialize the diagnostic server workers -export function mono_wasm_diagnostic_server_on_server_thread_created (websocketUrlPtr: CharPtr): void { +export function mono_wasm_diagnostic_server_on_server_thread_created(websocketUrlPtr: CharPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const websocketUrl = utf8ToString(websocketUrlPtr); mono_log_debug(`mono_wasm_diagnostic_server_on_server_thread_created, url ${websocketUrl}`); let mock: PromiseAndController | undefined = undefined; if (monoDiagnosticsMock && websocketUrl.startsWith("mock:")) { mock = createPromiseController(); - queueMicrotask(async () => { + queueMicrotask(async() => { const m = await importAndInstantiateMock(websocketUrl); mock!.promise_control.resolve(m); m.run(); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts index fd9142f54b8a33..2129fc76e601c7 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. import Magic from "./magic"; -import {BinaryProtocolCommand} from "./types"; +import { BinaryProtocolCommand } from "./types"; -function advancePos (pos: { pos: number }, offset: number): void { +function advancePos(pos: { pos: number }, offset: number): void { pos.pos += offset; } const Parser = { - tryParseHeader (buf: Uint8Array, pos: { pos: number }): boolean { + tryParseHeader(buf: Uint8Array, pos: { pos: number }): boolean { let j = pos.pos; for (let i = 0; i < Magic.DOTNET_IPC_V1.length; i++) { if (buf[j++] !== Magic.DOTNET_IPC_V1[i]) { @@ -19,10 +19,10 @@ const Parser = { advancePos(pos, Magic.DOTNET_IPC_V1.length); return true; }, - tryParseSize (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseSize(buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseUint16(buf, pos); }, - tryParseCommand (buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { + tryParseCommand(buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { const commandSet = Parser.tryParseUint8(buf, pos); if (commandSet === undefined) return undefined; @@ -39,7 +39,7 @@ const Parser = { }; return result; }, - tryParseReserved (buf: Uint8Array, pos: { pos: number }): true | undefined { + tryParseReserved(buf: Uint8Array, pos: { pos: number }): true | undefined { const reservedLength = 2; // 2 bytes reserved, must be 0 for (let i = 0; i < reservedLength; i++) { const reserved = Parser.tryParseUint8(buf, pos); @@ -49,7 +49,7 @@ const Parser = { } return true; }, - tryParseUint8 (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint8(buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j >= buf.byteLength) { return undefined; @@ -58,7 +58,7 @@ const Parser = { advancePos(pos, 1); return size; }, - tryParseUint16 (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint16(buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 1 >= buf.byteLength) { return undefined; @@ -67,7 +67,7 @@ const Parser = { advancePos(pos, 2); return size; }, - tryParseUint32 (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint32(buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 3 >= buf.byteLength) { return undefined; @@ -76,7 +76,7 @@ const Parser = { advancePos(pos, 4); return size; }, - tryParseUint64 (buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { + tryParseUint64(buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { const lo = Parser.tryParseUint32(buf, pos); if (lo === undefined) return undefined; @@ -85,22 +85,22 @@ const Parser = { return undefined; return [lo, hi]; }, - tryParseBool (buf: Uint8Array, pos: { pos: number }): boolean | undefined { + tryParseBool(buf: Uint8Array, pos: { pos: number }): boolean | undefined { const r = Parser.tryParseUint8(buf, pos); if (r === undefined) return undefined; return r !== 0; }, - tryParseArraySize (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseArraySize(buf: Uint8Array, pos: { pos: number }): number | undefined { const r = Parser.tryParseUint32(buf, pos); if (r === undefined) return undefined; return r; }, - tryParseStringLength (buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseStringLength(buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseArraySize(buf, pos); }, - tryParseUtf16String (buf: Uint8Array, pos: { pos: number }): string | undefined { + tryParseUtf16String(buf: Uint8Array, pos: { pos: number }): string | undefined { const length = Parser.tryParseStringLength(buf, pos); if (length === undefined) return undefined; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts index 0ba58ae96c3488..09115d7245bc3b 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {CommandSetId, ServerCommandId, EventPipeCommandId, ProcessCommandId} from "./types"; +import { CommandSetId, ServerCommandId, EventPipeCommandId, ProcessCommandId } from "./types"; import Magic from "./magic"; -function advancePos (pos: { pos: number }, count: number): void { +function advancePos(pos: { pos: number }, count: number): void { pos.pos += count; } @@ -12,7 +12,7 @@ function advancePos (pos: { pos: number }, count: number): void { function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.EventPipe, command: EventPipeCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Process, command: ProcessCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Server, command: ServerCommandId, len: number): void; -function serializeHeader (buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { +function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { Serializer.serializeMagic(buf, pos); Serializer.serializeUint16(buf, pos, len); Serializer.serializeUint8(buf, pos, commandSet); @@ -22,7 +22,7 @@ function serializeHeader (buf: Uint8Array, pos: { pos: number }, commandSet: Com const Serializer = { - computeMessageByteLength (payload?: number | Uint8Array): number { + computeMessageByteLength(payload?: number | Uint8Array): number { const fullHeaderSize = Magic.MinimalHeaderSize // magic, len + 2 // commandSet, command + 2; // reserved ; @@ -30,33 +30,33 @@ const Serializer = { const len = fullHeaderSize + payloadLength; // magic, size, commandSet, command, reserved return len; }, - serializeMagic (buf: Uint8Array, pos: { pos: number }): void { + serializeMagic(buf: Uint8Array, pos: { pos: number }): void { buf.set(Magic.DOTNET_IPC_V1, pos.pos); advancePos(pos, Magic.DOTNET_IPC_V1.byteLength); }, - serializeUint8 (buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint8(buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value; }, - serializeUint16 (buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint16(buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; }, - serializeUint32 (buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint32(buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; buf[pos.pos++] = (value >> 16) & 0xFF; buf[pos.pos++] = (value >> 24) & 0xFF; }, - serializeUint64 (buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { + serializeUint64(buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { Serializer.serializeUint32(buf, pos, value[0]); Serializer.serializeUint32(buf, pos, value[1]); }, serializeHeader, - serializePayload (buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { + serializePayload(buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { buf.set(payload, pos.pos); advancePos(pos, payload.byteLength); }, - serializeString (buf: Uint8Array, pos: { pos: number }, s: string | null): void { + serializeString(buf: Uint8Array, pos: { pos: number }, s: string | null): void { if (s === null || s === undefined || s === "") { Serializer.serializeUint32(buf, pos, 0); } else { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts index 9d98130bf84c2d..e7f27b9c6ab1f2 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts @@ -3,7 +3,7 @@ let magic_buf: Uint8Array = null!; const Magic = { - get DOTNET_IPC_V1 (): Uint8Array { + get DOTNET_IPC_V1(): Uint8Array { if (magic_buf === null) { const magic = "DOTNET_IPC_V1"; const magic_len = magic.length + 1; // nul terminated @@ -15,7 +15,7 @@ const Magic = { } return magic_buf; }, - get MinimalHeaderSize (): number { + get MinimalHeaderSize(): number { // we just need to see the magic and the size const sizeOfSize = 2; return Magic.DOTNET_IPC_V1.byteLength + sizeOfSize; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts index a3720f25f3c541..765e16718c9533 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts @@ -19,7 +19,7 @@ import { EventPipeCommandId, ProcessCommandId, } from "./types"; -import {mono_log_warn} from "../../../logging"; +import { mono_log_warn } from "../../../logging"; interface ParseClientCommandResultOk extends ParseResultOk { readonly result: C; @@ -27,7 +27,7 @@ interface ParseClientCommandResultOk extends Pars export type ParseClientCommandResult = ParseClientCommandResultOk | ParseResultFail; -export function parseBinaryProtocolCommand (cmd: BinaryProtocolCommand): ParseClientCommandResult { +export function parseBinaryProtocolCommand(cmd: BinaryProtocolCommand): ParseClientCommandResult { switch (cmd.commandSet) { case CommandSetId.Reserved: throw new Error("unexpected reserved command_set command"); @@ -40,11 +40,11 @@ export function parseBinaryProtocolCommand (cmd: BinaryProtocolCommand): ParseCl case CommandSetId.Process: return parseProcessCommand(cmd); default: - return {success: false, error: `unexpected command_set ${cmd.commandSet} command`}; + return { success: false, error: `unexpected command_set ${cmd.commandSet} command` }; } } -function parseEventPipeCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { +function parseEventPipeCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { switch (cmd.command) { case EventPipeCommandId.StopTracing: return parseEventPipeStopTracing(cmd); @@ -54,28 +54,28 @@ function parseEventPipeCommand (cmd: BinaryProtocolCommand & { commandSet: Comma return parseEventPipeCollectTracing2(cmd); default: mono_log_warn("unexpected EventPipe command: " + cmd.command); - return {success: false, error: `unexpected EventPipe command ${cmd.command}`}; + return { success: false, error: `unexpected EventPipe command ${cmd.command}` }; } } -function parseEventPipeCollectTracing2 (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { - const pos = {pos: 0}; +function parseEventPipeCollectTracing2(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { + const pos = { pos: 0 }; const buf = cmd.payload; const circularBufferMB = Parser.tryParseUint32(buf, pos); if (circularBufferMB === undefined) { - return {success: false, error: "failed to parse circularBufferMB in EventPipe CollectTracing2 command"}; + return { success: false, error: "failed to parse circularBufferMB in EventPipe CollectTracing2 command" }; } const format = Parser.tryParseUint32(buf, pos); if (format === undefined) { - return {success: false, error: "failed to parse format in EventPipe CollectTracing2 command"}; + return { success: false, error: "failed to parse format in EventPipe CollectTracing2 command" }; } const requestRundown = Parser.tryParseBool(buf, pos); if (requestRundown === undefined) { - return {success: false, error: "failed to parse requestRundown in EventPipe CollectTracing2 command"}; + return { success: false, error: "failed to parse requestRundown in EventPipe CollectTracing2 command" }; } const numProviders = Parser.tryParseArraySize(buf, pos); if (numProviders === undefined) { - return {success: false, error: "failed to parse numProviders in EventPipe CollectTracing2 command"}; + return { success: false, error: "failed to parse numProviders in EventPipe CollectTracing2 command" }; } const providers = new Array(numProviders); for (let i = 0; i < numProviders; i++) { @@ -85,44 +85,44 @@ function parseEventPipeCollectTracing2 (cmd: BinaryProtocolCommand & { commandSe } providers[i] = result.result; } - const command: EventPipeCommandCollectTracing2 = {command_set: "EventPipe", command: "CollectTracing2", circularBufferMB, format, requestRundown, providers}; - return {success: true, result: command}; + const command: EventPipeCommandCollectTracing2 = { command_set: "EventPipe", command: "CollectTracing2", circularBufferMB, format, requestRundown, providers }; + return { success: true, result: command }; } -function parseEventPipeCollectTracingCommandProvider (buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { +function parseEventPipeCollectTracingCommandProvider(buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { const keywords = Parser.tryParseUint64(buf, pos); if (keywords === undefined) { - return {success: false, error: "failed to parse keywords in EventPipe CollectTracing provider"}; + return { success: false, error: "failed to parse keywords in EventPipe CollectTracing provider" }; } const logLevel = Parser.tryParseUint32(buf, pos); if (logLevel === undefined) - return {success: false, error: "failed to parse logLevel in EventPipe CollectTracing provider"}; + return { success: false, error: "failed to parse logLevel in EventPipe CollectTracing provider" }; const providerName = Parser.tryParseUtf16String(buf, pos); if (providerName === undefined) - return {success: false, error: "failed to parse providerName in EventPipe CollectTracing provider"}; + return { success: false, error: "failed to parse providerName in EventPipe CollectTracing provider" }; const filterData = Parser.tryParseUtf16String(buf, pos); if (filterData === undefined) - return {success: false, error: "failed to parse filterData in EventPipe CollectTracing provider"}; - const provider: EventPipeCollectTracingCommandProvider = {keywords, logLevel, provider_name: providerName, filter_data: filterData}; - return {success: true, result: provider}; + return { success: false, error: "failed to parse filterData in EventPipe CollectTracing provider" }; + const provider: EventPipeCollectTracingCommandProvider = { keywords, logLevel, provider_name: providerName, filter_data: filterData }; + return { success: true, result: provider }; } -function parseEventPipeStopTracing (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { - const pos = {pos: 0}; +function parseEventPipeStopTracing(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { + const pos = { pos: 0 }; const buf = cmd.payload; const sessionID = Parser.tryParseUint64(buf, pos); if (sessionID === undefined) { - return {success: false, error: "failed to parse sessionID in EventPipe StopTracing command"}; + return { success: false, error: "failed to parse sessionID in EventPipe StopTracing command" }; } const [lo, hi] = sessionID; if (hi !== 0) { - return {success: false, error: "sessionID is too large in EventPipe StopTracing command"}; + return { success: false, error: "sessionID is too large in EventPipe StopTracing command" }; } - const command: EventPipeCommandStopTracing = {command_set: "EventPipe", command: "StopTracing", sessionID: lo}; - return {success: true, result: command}; + const command: EventPipeCommandStopTracing = { command_set: "EventPipe", command: "StopTracing", sessionID: lo }; + return { success: true, result: command }; } -function parseProcessCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { +function parseProcessCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { switch (cmd.command) { case ProcessCommandId.ProcessInfo: throw new Error("TODO"); @@ -134,15 +134,15 @@ function parseProcessCommand (cmd: BinaryProtocolCommand & { commandSet: Command throw new Error("TODO"); default: mono_log_warn("unexpected Process command: " + cmd.command); - return {success: false, error: `unexpected Process command ${cmd.command}`}; + return { success: false, error: `unexpected Process command ${cmd.command}` }; } } -function parseProcessResumeRuntime (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { +function parseProcessResumeRuntime(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { const buf = cmd.payload; if (buf.byteLength !== 0) { - return {success: false, error: "unexpected payload in Process ResumeRuntime command"}; + return { success: false, error: "unexpected payload in Process ResumeRuntime command" }; } - const command: ProcessCommandResumeRuntime = {command_set: "Process", command: "ResumeRuntime"}; - return {success: true, result: command}; + const command: ProcessCommandResumeRuntime = { command_set: "Process", command: "ResumeRuntime" }; + return { success: true, result: command }; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts index 7876d0d7aedefa..6b67488c5fdac7 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts @@ -1,14 +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 {mono_assert} from "../../../globals"; +import { mono_assert } from "../../../globals"; import Serializer from "./base-serializer"; -import {CommandSetId, ServerCommandId} from "./types"; +import { CommandSetId, ServerCommandId } from "./types"; -export function createBinaryCommandOKReply (payload?: Uint8Array): Uint8Array { +export function createBinaryCommandOKReply(payload?: Uint8Array): Uint8Array { const len = Serializer.computeMessageByteLength(payload); const buf = new Uint8Array(len); - const pos = {pos: 0}; + const pos = { pos: 0 }; Serializer.serializeHeader(buf, pos, CommandSetId.Server, ServerCommandId.OK, len); if (payload !== undefined) { Serializer.serializePayload(buf, pos, payload); @@ -16,7 +16,7 @@ export function createBinaryCommandOKReply (payload?: Uint8Array): Uint8Array { return buf; } -function serializeGuid (buf: Uint8Array, pos: { pos: number }, guid: string): void { +function serializeGuid(buf: Uint8Array, pos: { pos: number }, guid: string): void { guid.split("-").forEach((part) => { // FIXME: I'm sure the endianness is wrong here for (let i = 0; i < part.length; i += 2) { @@ -26,7 +26,7 @@ function serializeGuid (buf: Uint8Array, pos: { pos: number }, guid: string): vo }); } -function serializeAsciiLiteralString (buf: Uint8Array, pos: { pos: number }, s: string): void { +function serializeAsciiLiteralString(buf: Uint8Array, pos: { pos: number }, s: string): void { const len = s.length; const hasNul = s[len - 1] === "\0"; for (let i = 0; i < len; i++) { @@ -38,10 +38,10 @@ function serializeAsciiLiteralString (buf: Uint8Array, pos: { pos: number }, s: } -export function createAdvertise (guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { +export function createAdvertise(guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { const BUF_LENGTH = 34; const buf = new Uint8Array(BUF_LENGTH); - const pos = {pos: 0}; + const pos = { pos: 0 }; const advrText = "ADVR_V1\0"; serializeAsciiLiteralString(buf, pos, advrText); serializeGuid(buf, pos, guid); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts index 70794014fe8e95..2031de3499bd3a 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts @@ -8,7 +8,7 @@ export interface BinaryProtocolCommand { payload: Uint8Array; } -export function isBinaryProtocolCommand (x: object): x is BinaryProtocolCommand { +export function isBinaryProtocolCommand(x: object): x is BinaryProtocolCommand { return "commandSet" in x && "command" in x && "payload" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts index 375d3b21959b4b..b3d07952de76d1 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; -import type {Mock} from "../mock"; -import {mock} from "../mock"; +import type { Mock } from "../mock"; +import { mock } from "../mock"; -export function importAndInstantiateMock (mockURL: string): Promise { +export function importAndInstantiateMock(mockURL: string): Promise { if (monoDiagnosticsMock) { const mockPrefix = "mock:"; const scriptURL = mockURL.substring(mockPrefix.length); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts index f0f7a054bc46d1..a255e65fe3c18a 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts @@ -51,32 +51,32 @@ export type RemoveCommandSetAndId = Omitx).providers) && (x).providers.every(isEventPipeCollectTracingCommandProvider); } -export function isEventPipeCommandStopTracing (x: object): x is EventPipeCommandStopTracing { +export function isEventPipeCommandStopTracing(x: object): x is EventPipeCommandStopTracing { return isEventPipeCommand(x) && x.command === "StopTracing" && "sessionID" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts index f1eca8a8ec76b4..7bd03e0d003a34 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {CommonSocket} from "./common-socket"; +import type { CommonSocket } from "./common-socket"; import { BinaryProtocolCommand, ParseResultFail, @@ -9,8 +9,8 @@ import { } from "./ipc-protocol/types"; import Magic from "./ipc-protocol/magic"; import Parser from "./ipc-protocol/base-parser"; -import {assertNever} from "../../types/internal"; -import {mono_log_debug, mono_log_warn} from "../../logging"; +import { assertNever } from "../../types/internal"; +import { mono_log_debug, mono_log_warn } from "../../logging"; export const dotnetDiagnosticsServerProtocolCommandEvent = "dotnet:diagnostics:protocolCommand" as const; @@ -58,12 +58,12 @@ export type ParseResult = ParseResultBinaryCommandOk | ParseResultFail; /// A helper object that accumulates command data that is received and provides parsed commands class StatefulParser { - private state: State = {state: InState.Idle}; + private state: State = { state: InState.Idle }; - constructor (private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } + constructor(private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } /// process the data in the given buffer and update the state. - receiveBuffer (buf: ArrayBuffer): void { + receiveBuffer(buf: ArrayBuffer): void { if (this.state.state == InState.Error) { return; } @@ -83,22 +83,22 @@ class StatefulParser { } else { mono_log_warn("socket received invalid command header", buf, result.error); // FIXME: dispatch error event? - this.setState({state: InState.Error}); + this.setState({ state: InState.Error }); } } - tryParseHeader (buf: Uint8Array): ParseResult { - const pos = {pos: 0}; + tryParseHeader(buf: Uint8Array): ParseResult { + const pos = { pos: 0 }; if (buf.byteLength < Magic.MinimalHeaderSize) { // TODO: we need to see the magic and the size to make a partial commmand - return {success: false, error: "not enough data"}; + return { success: false, error: "not enough data" }; } if (!Parser.tryParseHeader(buf, pos)) { - return {success: false, error: "invalid header"}; + return { success: false, error: "invalid header" }; } const size = Parser.tryParseSize(buf, pos); if (size === undefined || size < Magic.MinimalHeaderSize) { - return {success: false, error: "invalid size"}; + return { success: false, error: "invalid size" }; } // make a "partially completed" state with a buffer of the right size and just the header upto the size // field filled in. @@ -106,18 +106,18 @@ class StatefulParser { const partialBuf = new ArrayBuffer(size); const partialBufView = new Uint8Array(partialBuf); partialBufView.set(buf.subarray(0, parsedSize)); - const partialState: PartialCommandState = {state: InState.PartialCommand, buf: partialBufView, size: parsedSize}; + const partialState: PartialCommandState = { state: InState.PartialCommand, buf: partialBufView, size: parsedSize }; return this.continueWithBuffer(partialState, buf.subarray(parsedSize)); } - tryAppendBuffer (moreBuf: Uint8Array): ParseResult { + tryAppendBuffer(moreBuf: Uint8Array): ParseResult { if (this.state.state !== InState.PartialCommand) { - return {success: false, error: "not in partial command state"}; + return { success: false, error: "not in partial command state" }; } return this.continueWithBuffer(this.state, moreBuf); } - continueWithBuffer (state: PartialCommandState, moreBuf: Uint8Array): ParseResult { + continueWithBuffer(state: PartialCommandState, moreBuf: Uint8Array): ParseResult { const buf = state.buf; let partialSize = state.size; let overflow: Uint8Array | null = null; @@ -134,15 +134,15 @@ class StatefulParser { overflow.set(moreBuf.subarray(overflowOffset)); } if (partialSize < buf.byteLength) { - const newState = {state: InState.PartialCommand, buf, size: partialSize}; - return {success: true, command: undefined, newState}; + const newState = { state: InState.PartialCommand, buf, size: partialSize }; + return { success: true, command: undefined, newState }; } else { - const pos = {pos: Magic.MinimalHeaderSize}; + const pos = { pos: Magic.MinimalHeaderSize }; let result = this.tryParseCompletedBuffer(buf, pos); if (overflow) { mono_log_warn("additional bytes past command payload", overflow); if (result.success) { - const newResult: ParseResultBinaryCommandOk = {success: true, command: result.command, newState: {state: InState.Error}}; + const newResult: ParseResultBinaryCommandOk = { success: true, command: result.command, newState: { state: InState.Error } }; result = newResult; } } @@ -150,21 +150,21 @@ class StatefulParser { } } - tryParseCompletedBuffer (buf: Uint8Array, pos: { pos: number }): ParseResult { + tryParseCompletedBuffer(buf: Uint8Array, pos: { pos: number }): ParseResult { const command = Parser.tryParseCommand(buf, pos); if (!command) { - this.setState({state: InState.Error}); - return {success: false, error: "invalid command"}; + this.setState({ state: InState.Error }); + return { success: false, error: "invalid command" }; } - return {success: true, command, newState: {state: InState.Idle}}; + return { success: true, command, newState: { state: InState.Idle } }; } - private setState (state: State) { + private setState(state: State) { this.state = state; } - reset () { - this.setState({state: InState.Idle}); + reset() { + this.setState({ state: InState.Idle }); } } @@ -173,9 +173,9 @@ class ProtocolSocketImpl implements ProtocolSocket { private readonly statefulParser = new StatefulParser(this.emitCommandCallback.bind(this)); private protocolListeners = 0; private readonly messageListener: (this: CommonSocket, ev: MessageEvent) => void = this.onMessage.bind(this); - constructor (private readonly sock: CommonSocket) { } + constructor(private readonly sock: CommonSocket) { } - onMessage (this: ProtocolSocketImpl, ev: MessageEvent): void { + onMessage(this: ProtocolSocketImpl, ev: MessageEvent): void { const data = ev.data; mono_log_debug("protocol socket received message", ev.data); if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -190,17 +190,17 @@ class ProtocolSocketImpl implements ProtocolSocket { } } - dispatchEvent (evt: Event): boolean { + dispatchEvent(evt: Event): boolean { return this.sock.dispatchEvent(evt); } - onArrayBuffer (this: ProtocolSocketImpl, buf: ArrayBuffer) { + onArrayBuffer(this: ProtocolSocketImpl, buf: ArrayBuffer) { mono_log_debug("protocol-socket: parsing array buffer", buf); this.statefulParser.receiveBuffer(buf); } // called by the stateful parser when it has a complete command - emitCommandCallback (this: this, command: BinaryProtocolCommand): void { + emitCommandCallback(this: this, command: BinaryProtocolCommand): void { mono_log_debug("protocol-socket: queueing command", command); queueMicrotask(() => { mono_log_debug("dispatching protocol event with command", command); @@ -209,14 +209,14 @@ class ProtocolSocketImpl implements ProtocolSocket { } - dispatchProtocolCommandEvent (cmd: BinaryProtocolCommand): void { + dispatchProtocolCommandEvent(cmd: BinaryProtocolCommand): void { const ev = new Event(dotnetDiagnosticsServerProtocolCommandEvent); (ev).data = cmd; // FIXME: use a proper event subclass this.sock.dispatchEvent(ev); } addEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void; - addEventListener (type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { this.sock.addEventListener(type, listener, options); if (type === dotnetDiagnosticsServerProtocolCommandEvent) { if (this.protocolListeners === 0) { @@ -228,7 +228,7 @@ class ProtocolSocketImpl implements ProtocolSocket { } removeEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any): void; - removeEventListener (type: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void { if (type === dotnetDiagnosticsServerProtocolCommandEvent) { mono_log_debug("removing protocol listener and message chaser"); this.protocolListeners--; @@ -240,18 +240,18 @@ class ProtocolSocketImpl implements ProtocolSocket { this.sock.removeEventListener(type, listener); } - send (buf: Uint8Array) { + send(buf: Uint8Array) { this.sock.send(buf); } - close () { + close() { this.sock.close(); this.statefulParser.reset(); } } -export function createProtocolSocket (socket: CommonSocket): ProtocolSocket { +export function createProtocolSocket(socket: CommonSocket): ProtocolSocket { return new ProtocolSocketImpl(socket); } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts index bcbdd9c9fe6b2c..d02ae16e3403a0 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {assertNever} from "../../types/internal"; -import {VoidPtr} from "../../types/emscripten"; -import type {CommonSocket} from "./common-socket"; -import {mono_log_debug, mono_log_warn} from "../../logging"; -import {localHeapViewU8} from "../../memory"; +import { assertNever } from "../../types/internal"; +import { VoidPtr } from "../../types/emscripten"; +import type { CommonSocket } from "./common-socket"; +import { mono_log_debug, mono_log_warn } from "../../logging"; +import { localHeapViewU8 } from "../../memory"; enum ListenerState { Sending, Closed, @@ -13,11 +13,11 @@ enum ListenerState { } class SocketGuts { - constructor (public readonly socket: CommonSocket) { } - close (): void { + constructor(public readonly socket: CommonSocket) { } + close(): void { this.socket.close(); } - write (data: VoidPtr, size: number): void { + write(data: VoidPtr, size: number): void { const buf = new ArrayBuffer(size); const view = new Uint8Array(buf); // Can we avoid this copy? @@ -33,12 +33,12 @@ class SocketGuts { export class EventPipeSocketConnection { private _state: ListenerState; readonly stream: SocketGuts; - constructor (socket: CommonSocket) { + constructor(socket: CommonSocket) { this._state = ListenerState.Sending; this.stream = new SocketGuts(socket); } - close (): void { + close(): void { mono_log_debug("EventPipe session stream closing websocket"); switch (this._state) { case ListenerState.Error: @@ -52,7 +52,7 @@ export class EventPipeSocketConnection { } } - write (ptr: VoidPtr, len: number): boolean { + write(ptr: VoidPtr, len: number): boolean { switch (this._state) { case ListenerState.Sending: this.stream.write(ptr, len); @@ -65,7 +65,7 @@ export class EventPipeSocketConnection { } } - private _onMessage (event: MessageEvent): void { + private _onMessage(event: MessageEvent): void { switch (this._state) { case ListenerState.Sending: /* unexpected message */ @@ -85,7 +85,7 @@ export class EventPipeSocketConnection { } - private _onClose (/*event: CloseEvent*/) { + private _onClose(/*event: CloseEvent*/) { switch (this._state) { case ListenerState.Closed: return; /* do nothing */ @@ -99,14 +99,14 @@ export class EventPipeSocketConnection { } } - private _onError (event: Event) { + private _onError(event: Event) { mono_log_debug("EventPipe session stream websocket error", event); this._state = ListenerState.Error; this.stream.close(); // TODO: notify runtime that connection had an error } - addListeners (): void { + addListeners(): void { const socket = this.stream.socket; socket.addEventListener("message", this._onMessage.bind(this)); addEventListener("close", this._onClose.bind(this)); @@ -116,7 +116,7 @@ export class EventPipeSocketConnection { /// Take over a WebSocket that was used by the diagnostic server to receive the StartCollecting command and /// use it for sending the event pipe data back to the host. -export function takeOverSocket (socket: CommonSocket): EventPipeSocketConnection { +export function takeOverSocket(socket: CommonSocket): EventPipeSocketConnection { const connection = new EventPipeSocketConnection(socket); connection.addListeners(); return connection; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts index f3d140021d3ee4..5ab42c2d8b4d96 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts @@ -1,8 +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 {VoidPtr} from "../../types/emscripten"; -import {getI32, notifyI32, setI32, storeI32} from "../../memory"; +import { VoidPtr } from "../../types/emscripten"; +import { getI32, notifyI32, setI32, storeI32 } from "../../memory"; /// One-reader, one-writer, size 1 queue for messages from an EventPipe streaming thread to @@ -38,36 +38,36 @@ export class StreamQueue { readonly workAvailable: EventTarget = new globalThis.EventTarget(); readonly signalWorkAvailable = this.signalWorkAvailableImpl.bind(this); - constructor (readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { + constructor(readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { this.workAvailable.addEventListener("workAvailable", this.onWorkAvailable.bind(this)); } - private get buf_addr (): VoidPtr { + private get buf_addr(): VoidPtr { return this.queue_addr + BUF_OFFSET; } - private get count_addr (): VoidPtr { + private get count_addr(): VoidPtr { return this.queue_addr + COUNT_OFFSET; } - private get buf_full_addr (): VoidPtr { + private get buf_full_addr(): VoidPtr { return this.queue_addr + WRITE_DONE_OFFSET; } /// called from native code on the diagnostic thread when the streaming thread queues a call to notify the /// diagnostic thread that it can send the buffer. - wakeup (): void { + wakeup(): void { queueMicrotask(this.signalWorkAvailable); } - workAvailableNow (): void { + workAvailableNow(): void { // process the queue immediately, rather than waiting for the next event loop tick. this.onWorkAvailable(); } - private signalWorkAvailableImpl (this: StreamQueue): void { + private signalWorkAvailableImpl(this: StreamQueue): void { this.workAvailable.dispatchEvent(new Event("workAvailable")); } - private onWorkAvailable (this: StreamQueue /*,event: Event */): void { + private onWorkAvailable(this: StreamQueue /*,event: Event */): void { const buf = getI32(this.buf_addr) as unknown as VoidPtr; const intptr_buf = buf as unknown as number; if (intptr_buf === STREAM_CLOSE_SENTINEL) { @@ -90,19 +90,19 @@ export class StreamQueue { // maps stream queue addresses to StreamQueue instances const streamQueueMap = new Map(); -export function allocateQueue (nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { +export function allocateQueue(nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { const queue = new StreamQueue(nativeQueueAddr, syncSendBuffer, syncSendClose); streamQueueMap.set(nativeQueueAddr, queue); return queue; } -export function closeQueue (nativeQueueAddr: VoidPtr): void { +export function closeQueue(nativeQueueAddr: VoidPtr): void { streamQueueMap.delete(nativeQueueAddr); // TODO: remove the event listener? } // called from native code on the diagnostic thread by queueing a call from the streaming thread. -export function mono_wasm_diagnostic_server_stream_signal_work_available (nativeQueueAddr: VoidPtr, current_thread: number): void { +export function mono_wasm_diagnostic_server_stream_signal_work_available(nativeQueueAddr: VoidPtr, current_thread: number): void { const queue = streamQueueMap.get(nativeQueueAddr); if (queue) { if (current_thread === 0) { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts index 531aa0cc223bc9..6854261e4d00ed 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts @@ -2,29 +2,29 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import {EventPipeSessionIDImpl} from "../shared/types"; -import {EventPipeSocketConnection, takeOverSocket} from "./socket-connection"; -import {StreamQueue, allocateQueue} from "./stream-queue"; -import type {MockRemoteSocket} from "../mock"; -import type {VoidPtr} from "../../types/emscripten"; -import {threads_c_functions as cwraps} from "../../cwraps"; +import { EventPipeSessionIDImpl } from "../shared/types"; +import { EventPipeSocketConnection, takeOverSocket } from "./socket-connection"; +import { StreamQueue, allocateQueue } from "./stream-queue"; +import type { MockRemoteSocket } from "../mock"; +import type { VoidPtr } from "../../types/emscripten"; +import { threads_c_functions as cwraps } from "../../cwraps"; import { EventPipeCommandCollectTracing2, EventPipeCollectTracingCommandProvider, } from "./protocol-client-commands"; -import {createEventPipeStreamingSession} from "../shared/create-session"; -import {mono_assert} from "../../globals"; +import { createEventPipeStreamingSession } from "../shared/create-session"; +import { mono_assert } from "../../globals"; /// The streaming session holds all the pieces of an event pipe streaming session that the /// diagnostic server knows about: the session ID, a /// queue used by the EventPipe streaming thread to forward events to the diagnostic server thread, /// and a wrapper around the WebSocket object used to send event data back to the host. export class EventPipeStreamingSession { - constructor (readonly sessionID: EventPipeSessionIDImpl, + constructor(readonly sessionID: EventPipeSessionIDImpl, readonly queue: StreamQueue, readonly connection: EventPipeSocketConnection) { } } -export async function makeEventPipeStreamingSession (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { +export async function makeEventPipeStreamingSession(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); // First, create the native IPC stream and get its queue. const ipcStreamAddr = cwraps.mono_wasm_diagnostic_server_create_stream(); // FIXME: this should be a wrapped in a JS object so we can free it when we're done. @@ -46,17 +46,17 @@ export async function makeEventPipeStreamingSession (ws: WebSocket | MockRemoteS } -function providersStringFromObject (providers: EventPipeCollectTracingCommandProvider[]) { +function providersStringFromObject(providers: EventPipeCollectTracingCommandProvider[]) { const providersString = providers.map(providerToString).join(","); return providersString; - function providerToString (provider: EventPipeCollectTracingCommandProvider): string { + function providerToString(provider: EventPipeCollectTracingCommandProvider): string { const keyword_str = provider.keywords[0] === 0 && provider.keywords[1] === 0 ? "" : keywordsToHexString(provider.keywords); const args_str = provider.filter_data === "" ? "" : ":" + provider.filter_data; return provider.provider_name + ":" + keyword_str + ":" + provider.logLevel + args_str; } - function keywordsToHexString (k: [number, number]): string { + function keywordsToHexString(k: [number, number]): string { const lo = k[0]; const hi = k[1]; const lo_hex = leftPad(lo.toString(16), "0", 8); @@ -64,7 +64,7 @@ function providersStringFromObject (providers: EventPipeCollectTracingCommandPro return hi_hex + lo_hex; } - function leftPad (s: string, fill: string, width: number): string { + function leftPad(s: string, fill: string, width: number): string { if (s.length >= width) return s; const prefix = fill.repeat(width - s.length); @@ -74,6 +74,6 @@ function providersStringFromObject (providers: EventPipeCollectTracingCommandPro const IPC_STREAM_QUEUE_OFFSET = 4; /* keep in sync with mono_wasm_diagnostic_server_create_stream() in C */ -function getQueueAddrFromStreamAddr (streamAddr: VoidPtr): VoidPtr { +function getQueueAddrFromStreamAddr(streamAddr: VoidPtr): VoidPtr { return streamAddr + IPC_STREAM_QUEUE_OFFSET; } diff --git a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts index 0241ef294a34fd..16aa6ad85944f2 100644 --- a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts +++ b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts @@ -1,8 +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 {isMonoThreadMessage} from "../../pthreads"; -import type {MonoThreadMessage} from "../../types/internal"; +import { isMonoThreadMessage } from "../../pthreads"; +import type { MonoThreadMessage } from "../../types/internal"; // Messages from the main thread to the diagnostic server thread export interface DiagnosticMessage extends MonoThreadMessage { @@ -10,7 +10,7 @@ export interface DiagnosticMessage extends MonoThreadMessage { cmd: string; } -export function isDiagnosticMessage (x: unknown): x is DiagnosticMessage { +export function isDiagnosticMessage(x: unknown): x is DiagnosticMessage { return isMonoThreadMessage(x) && x.type === "diagnostic_server"; } @@ -29,7 +29,7 @@ export type DiagnosticServerControlCommandStart = DiagnosticServerControlCommand export type DiagnosticServerControlCommandStop = DiagnosticServerControlCommandSpecific<"stop">; export type DiagnosticServerControlCommandAttachToRuntime = DiagnosticServerControlCommandSpecific<"attach_to_runtime">; -export function makeDiagnosticServerControlCommand (cmd: T): DiagnosticServerControlCommandSpecific { +export function makeDiagnosticServerControlCommand(cmd: T): DiagnosticServerControlCommandSpecific { return { type: "diagnostic_server", cmd: cmd, diff --git a/src/mono/browser/runtime/diagnostics/shared/create-session.ts b/src/mono/browser/runtime/diagnostics/shared/create-session.ts index 75e4e01f2721cb..17af0cbc5bebba 100644 --- a/src/mono/browser/runtime/diagnostics/shared/create-session.ts +++ b/src/mono/browser/runtime/diagnostics/shared/create-session.ts @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. import * as memory from "../../memory"; -import {VoidPtr} from "../../types/emscripten"; -import {threads_c_functions as cwraps} from "../../cwraps"; -import type {EventPipeSessionIDImpl} from "./types"; +import { VoidPtr } from "../../types/emscripten"; +import { threads_c_functions as cwraps } from "../../cwraps"; +import type { EventPipeSessionIDImpl } from "./types"; const sizeOfInt32 = 4; @@ -25,7 +25,7 @@ type SessionType = }; -function createSessionWithPtrCB (sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { +function createSessionWithPtrCB(sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { memory.setI32(sessionIdOutPtr, 0); let tracePath: string | null; let ipcStreamAddr: VoidPtr; @@ -43,10 +43,10 @@ function createSessionWithPtrCB (sessionIdOutPtr: VoidPtr, options: EventPipeCre } } -export function createEventPipeStreamingSession (ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { - return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, {type: "stream", stream: ipcStreamAddr}); +export function createEventPipeStreamingSession(ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { + return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "stream", stream: ipcStreamAddr }); } -export function createEventPipeFileSession (tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { - return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, {type: "file", filePath: tracePath}); +export function createEventPipeFileSession(tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { + return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "file", filePath: tracePath }); } diff --git a/src/mono/browser/runtime/export-api.ts b/src/mono/browser/runtime/export-api.ts index 08aa21df34d7db..623c4222218f01 100644 --- a/src/mono/browser/runtime/export-api.ts +++ b/src/mono/browser/runtime/export-api.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {MonoConfig, APIType} from "./types"; +import type { MonoConfig, APIType } from "./types"; -import {mono_wasm_get_assembly_exports} from "./invoke-cs"; -import {mono_wasm_set_module_imports} from "./invoke-js"; -import {getB32, getF32, getF64, getI16, getI32, getI52, getI64Big, getI8, getU16, getU32, getU52, getU8, localHeapViewF32, localHeapViewF64, localHeapViewI16, localHeapViewI32, localHeapViewI64Big, localHeapViewI8, localHeapViewU16, localHeapViewU32, localHeapViewU8, setB32, setF32, setF64, setI16, setI32, setI52, setI64Big, setI8, setU16, setU32, setU52, setU8} from "./memory"; -import {mono_run_main, mono_run_main_and_exit} from "./run"; -import {mono_wasm_setenv} from "./startup"; -import {loaderHelpers, runtimeHelpers} from "./globals"; +import { mono_wasm_get_assembly_exports } from "./invoke-cs"; +import { mono_wasm_set_module_imports } from "./invoke-js"; +import { getB32, getF32, getF64, getI16, getI32, getI52, getI64Big, getI8, getU16, getU32, getU52, getU8, localHeapViewF32, localHeapViewF64, localHeapViewI16, localHeapViewI32, localHeapViewI64Big, localHeapViewI8, localHeapViewU16, localHeapViewU32, localHeapViewU8, setB32, setF32, setF64, setI16, setI32, setI52, setI64Big, setI8, setU16, setU32, setU52, setU8 } from "./memory"; +import { mono_run_main, mono_run_main_and_exit } from "./run"; +import { mono_wasm_setenv } from "./startup"; +import { loaderHelpers, runtimeHelpers } from "./globals"; -export function export_api (): any { +export function export_api(): any { const api: APIType = { runMain: mono_run_main, runMainAndExit: mono_run_main_and_exit, diff --git a/src/mono/browser/runtime/exports-binding.ts b/src/mono/browser/runtime/exports-binding.ts index d023984c23b40a..153ac946010cdb 100644 --- a/src/mono/browser/runtime/exports-binding.ts +++ b/src/mono/browser/runtime/exports-binding.ts @@ -3,35 +3,35 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {mono_wasm_debugger_log, mono_wasm_add_dbg_command_received, mono_wasm_set_entrypoint_breakpoint, mono_wasm_fire_debugger_agent_message_with_data, mono_wasm_fire_debugger_agent_message_with_data_to_pause} from "./debug"; -import {mono_wasm_release_cs_owned_object} from "./gc-handles"; -import {mono_wasm_bind_js_import, mono_wasm_invoke_js_function, mono_wasm_invoke_jsimport_MT, mono_wasm_invoke_jsimport_ST} from "./invoke-js"; -import {mono_interp_tier_prepare_jiterpreter, mono_jiterp_free_method_data_js} from "./jiterpreter"; -import {mono_interp_jit_wasm_entry_trampoline, mono_interp_record_interp_entry} from "./jiterpreter-interp-entry"; -import {mono_interp_jit_wasm_jit_call_trampoline, mono_interp_invoke_wasm_jit_call_trampoline, mono_interp_flush_jitcall_queue} from "./jiterpreter-jit-call"; -import {mono_wasm_resolve_or_reject_promise} from "./marshal-to-js"; -import {mono_wasm_schedule_timer, schedule_background_exec} from "./scheduling"; -import {mono_wasm_asm_loaded} from "./startup"; -import {mono_wasm_diagnostic_server_on_server_thread_created} from "./diagnostics/server_pthread"; -import {mono_wasm_diagnostic_server_on_runtime_server_init, mono_wasm_event_pipe_early_startup_callback} from "./diagnostics"; -import {mono_wasm_diagnostic_server_stream_signal_work_available} from "./diagnostics/server_pthread/stream-queue"; -import {mono_log_warn, mono_wasm_console_clear, mono_wasm_trace_logger} from "./logging"; -import {mono_wasm_profiler_leave, mono_wasm_profiler_enter} from "./profiler"; -import {mono_wasm_change_case, mono_wasm_change_case_invariant} from "./hybrid-globalization/change-case"; -import {mono_wasm_compare_string, mono_wasm_ends_with, mono_wasm_starts_with, mono_wasm_index_of} from "./hybrid-globalization/collations"; -import {mono_wasm_get_calendar_info} from "./hybrid-globalization/calendar"; - -import {mono_wasm_get_culture_info} from "./hybrid-globalization/culture-info"; -import {mono_wasm_get_locale_info, mono_wasm_get_first_day_of_week, mono_wasm_get_first_week_of_year} from "./hybrid-globalization/locales"; -import {mono_wasm_browser_entropy} from "./crypto"; -import {mono_wasm_cancel_promise} from "./cancelable-promise"; +import { mono_wasm_debugger_log, mono_wasm_add_dbg_command_received, mono_wasm_set_entrypoint_breakpoint, mono_wasm_fire_debugger_agent_message_with_data, mono_wasm_fire_debugger_agent_message_with_data_to_pause } from "./debug"; +import { mono_wasm_release_cs_owned_object } from "./gc-handles"; +import { mono_wasm_bind_js_import, mono_wasm_invoke_js_function, mono_wasm_invoke_jsimport_MT, mono_wasm_invoke_jsimport_ST } from "./invoke-js"; +import { mono_interp_tier_prepare_jiterpreter, mono_jiterp_free_method_data_js } from "./jiterpreter"; +import { mono_interp_jit_wasm_entry_trampoline, mono_interp_record_interp_entry } from "./jiterpreter-interp-entry"; +import { mono_interp_jit_wasm_jit_call_trampoline, mono_interp_invoke_wasm_jit_call_trampoline, mono_interp_flush_jitcall_queue } from "./jiterpreter-jit-call"; +import { mono_wasm_resolve_or_reject_promise } from "./marshal-to-js"; +import { mono_wasm_schedule_timer, schedule_background_exec } from "./scheduling"; +import { mono_wasm_asm_loaded } from "./startup"; +import { mono_wasm_diagnostic_server_on_server_thread_created } from "./diagnostics/server_pthread"; +import { mono_wasm_diagnostic_server_on_runtime_server_init, mono_wasm_event_pipe_early_startup_callback } from "./diagnostics"; +import { mono_wasm_diagnostic_server_stream_signal_work_available } from "./diagnostics/server_pthread/stream-queue"; +import { mono_log_warn, mono_wasm_console_clear, mono_wasm_trace_logger } from "./logging"; +import { mono_wasm_profiler_leave, mono_wasm_profiler_enter } from "./profiler"; +import { mono_wasm_change_case, mono_wasm_change_case_invariant } from "./hybrid-globalization/change-case"; +import { mono_wasm_compare_string, mono_wasm_ends_with, mono_wasm_starts_with, mono_wasm_index_of } from "./hybrid-globalization/collations"; +import { mono_wasm_get_calendar_info } from "./hybrid-globalization/calendar"; + +import { mono_wasm_get_culture_info } from "./hybrid-globalization/culture-info"; +import { mono_wasm_get_locale_info, mono_wasm_get_first_day_of_week, mono_wasm_get_first_week_of_year } from "./hybrid-globalization/locales"; +import { mono_wasm_browser_entropy } from "./crypto"; +import { mono_wasm_cancel_promise } from "./cancelable-promise"; import { mono_wasm_start_deputy_thread_async, mono_wasm_pthread_on_pthread_attached, mono_wasm_pthread_on_pthread_unregistered, mono_wasm_pthread_on_pthread_registered, mono_wasm_pthread_set_name, mono_wasm_install_js_worker_interop, mono_wasm_uninstall_js_worker_interop, mono_wasm_start_io_thread_async } from "./pthreads"; -import {mono_wasm_dump_threads} from "./pthreads/ui-thread"; +import { mono_wasm_dump_threads } from "./pthreads/ui-thread"; // the JS methods would be visible to EMCC linker and become imports of the WASM module @@ -118,7 +118,7 @@ const wasmImports: Function[] = [ ...mono_wasm_threads_imports, ]; -export function replace_linker_placeholders (imports: WebAssembly.Imports) { +export function replace_linker_placeholders(imports: WebAssembly.Imports) { // the output from emcc contains wrappers for these linker imports which add overhead, // but now we have what we need to replace them with the actual functions // By default the imports all live inside of 'env', but emscripten minification could rename it to 'a'. @@ -136,7 +136,7 @@ export function replace_linker_placeholders (imports: WebAssembly.Imports) { const stub_fn = env[shortName] as Function; if (typeof stub_fn === "function" && stub_fn.toString().indexOf("runtime_idx") !== -1) { try { - const {runtime_idx} = stub_fn(); + const { runtime_idx } = stub_fn(); if (indexToNameMap[runtime_idx] !== undefined) throw new Error(`Duplicate runtime_idx ${runtime_idx}`); indexToNameMap[runtime_idx] = shortName; } catch { diff --git a/src/mono/browser/runtime/exports-internal.ts b/src/mono/browser/runtime/exports-internal.ts index 400f1a7ac461ec..d22da712d25e4a 100644 --- a/src/mono/browser/runtime/exports-internal.ts +++ b/src/mono/browser/runtime/exports-internal.ts @@ -3,29 +3,29 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {MonoObjectNull, type MonoObject} from "./types/internal"; -import cwraps, {profiler_c_functions, threads_c_functions as twraps} from "./cwraps"; -import {mono_wasm_send_dbg_command_with_parms, mono_wasm_send_dbg_command, mono_wasm_get_dbg_command_info, mono_wasm_get_details, mono_wasm_release_object, mono_wasm_call_function_on, mono_wasm_debugger_resume, mono_wasm_detach_debugger, mono_wasm_raise_debug_event, mono_wasm_change_debugger_log_level, mono_wasm_debugger_attached} from "./debug"; -import {http_wasm_supports_streaming_request, http_wasm_supports_streaming_response, http_wasm_create_controller, http_wasm_abort_request, http_wasm_abort_response, http_wasm_transform_stream_write, http_wasm_transform_stream_close, http_wasm_fetch, http_wasm_fetch_stream, http_wasm_fetch_bytes, http_wasm_get_response_header_names, http_wasm_get_response_header_values, http_wasm_get_response_bytes, http_wasm_get_response_length, http_wasm_get_streamed_response_bytes, http_wasm_get_response_type, http_wasm_get_response_status} from "./http"; -import {exportedRuntimeAPI, Module, runtimeHelpers} from "./globals"; -import {get_property, set_property, has_property, get_typeof_property, get_global_this, dynamic_import} from "./invoke-js"; -import {mono_wasm_stringify_as_error_with_stack} from "./logging"; -import {ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort, ws_get_state} from "./web-socket"; -import {mono_wasm_get_loaded_files} from "./assets"; -import {jiterpreter_dump_stats} from "./jiterpreter"; -import {interp_pgo_load_data, interp_pgo_save_data} from "./interp-pgo"; -import {getOptions, applyOptions} from "./jiterpreter-support"; -import {mono_wasm_gc_lock, mono_wasm_gc_unlock} from "./gc-lock"; -import {loadLazyAssembly} from "./lazyLoading"; -import {loadSatelliteAssemblies} from "./satelliteAssemblies"; -import {forceDisposeProxies} from "./gc-handles"; -import {mono_wasm_get_func_id_to_name_mappings} from "./logging"; -import {monoStringToStringUnsafe} from "./strings"; -import {mono_wasm_bind_cs_function} from "./invoke-cs"; - -import {mono_wasm_dump_threads, thread_available} from "./pthreads"; - -export function export_internal (): any { +import { MonoObjectNull, type MonoObject } from "./types/internal"; +import cwraps, { profiler_c_functions, threads_c_functions as twraps } from "./cwraps"; +import { mono_wasm_send_dbg_command_with_parms, mono_wasm_send_dbg_command, mono_wasm_get_dbg_command_info, mono_wasm_get_details, mono_wasm_release_object, mono_wasm_call_function_on, mono_wasm_debugger_resume, mono_wasm_detach_debugger, mono_wasm_raise_debug_event, mono_wasm_change_debugger_log_level, mono_wasm_debugger_attached } from "./debug"; +import { http_wasm_supports_streaming_request, http_wasm_supports_streaming_response, http_wasm_create_controller, http_wasm_abort_request, http_wasm_abort_response, http_wasm_transform_stream_write, http_wasm_transform_stream_close, http_wasm_fetch, http_wasm_fetch_stream, http_wasm_fetch_bytes, http_wasm_get_response_header_names, http_wasm_get_response_header_values, http_wasm_get_response_bytes, http_wasm_get_response_length, http_wasm_get_streamed_response_bytes, http_wasm_get_response_type, http_wasm_get_response_status } from "./http"; +import { exportedRuntimeAPI, Module, runtimeHelpers } from "./globals"; +import { get_property, set_property, has_property, get_typeof_property, get_global_this, dynamic_import } from "./invoke-js"; +import { mono_wasm_stringify_as_error_with_stack } from "./logging"; +import { ws_wasm_create, ws_wasm_open, ws_wasm_send, ws_wasm_receive, ws_wasm_close, ws_wasm_abort, ws_get_state } from "./web-socket"; +import { mono_wasm_get_loaded_files } from "./assets"; +import { jiterpreter_dump_stats } from "./jiterpreter"; +import { interp_pgo_load_data, interp_pgo_save_data } from "./interp-pgo"; +import { getOptions, applyOptions } from "./jiterpreter-support"; +import { mono_wasm_gc_lock, mono_wasm_gc_unlock } from "./gc-lock"; +import { loadLazyAssembly } from "./lazyLoading"; +import { loadSatelliteAssemblies } from "./satelliteAssemblies"; +import { forceDisposeProxies } from "./gc-handles"; +import { mono_wasm_get_func_id_to_name_mappings } from "./logging"; +import { monoStringToStringUnsafe } from "./strings"; +import { mono_wasm_bind_cs_function } from "./invoke-cs"; + +import { mono_wasm_dump_threads, thread_available } from "./pthreads"; + +export function export_internal(): any { return { // tests mono_wasm_exit: (exit_code: number) => { @@ -116,7 +116,7 @@ export function export_internal (): any { }; } -export function cwraps_internal (internal: any): void { +export function cwraps_internal(internal: any): void { Object.assign(internal, { mono_wasm_exit: cwraps.mono_wasm_exit, mono_wasm_profiler_init_aot: profiler_c_functions.mono_wasm_profiler_init_aot, @@ -127,7 +127,7 @@ export function cwraps_internal (internal: any): void { } /* @deprecated not GC safe, legacy support for Blazor */ -export function monoObjectAsBoolOrNullUnsafe (obj: MonoObject): boolean | null { +export function monoObjectAsBoolOrNullUnsafe(obj: MonoObject): boolean | null { if (obj === MonoObjectNull) { return null; } diff --git a/src/mono/browser/runtime/exports-linker.ts b/src/mono/browser/runtime/exports-linker.ts index fa4b2fe4806981..3d8bb179c78689 100644 --- a/src/mono/browser/runtime/exports-linker.ts +++ b/src/mono/browser/runtime/exports-linker.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {mono_wasm_imports, mono_wasm_threads_imports} from "./exports-binding"; +import { mono_wasm_imports, mono_wasm_threads_imports } from "./exports-binding"; import gitHash from "consts:gitHash"; -export function export_linker_indexes_as_code (): string { +export function export_linker_indexes_as_code(): string { const indexByName: any = { mono_wasm_imports: {}, mono_wasm_threads_imports: {}, diff --git a/src/mono/browser/runtime/exports.ts b/src/mono/browser/runtime/exports.ts index cda4a3098eda10..2a0489632f955e 100644 --- a/src/mono/browser/runtime/exports.ts +++ b/src/mono/browser/runtime/exports.ts @@ -7,26 +7,26 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import WasmEnableSIMD from "consts:wasmEnableSIMD"; import WasmEnableExceptionHandling from "consts:wasmEnableExceptionHandling"; -import type {RuntimeAPI} from "./types"; +import type { RuntimeAPI } from "./types"; -import {Module, exportedRuntimeAPI, loaderHelpers, passEmscriptenInternals, runtimeHelpers, setRuntimeGlobals,} from "./globals"; -import {GlobalObjects, RuntimeHelpers} from "./types/internal"; -import {configureEmscriptenStartup, configureRuntimeStartup, configureWorkerStartup} from "./startup"; +import { Module, exportedRuntimeAPI, loaderHelpers, passEmscriptenInternals, runtimeHelpers, setRuntimeGlobals, } from "./globals"; +import { GlobalObjects, RuntimeHelpers } from "./types/internal"; +import { configureEmscriptenStartup, configureRuntimeStartup, configureWorkerStartup } from "./startup"; -import {create_weak_ref} from "./weak-ref"; -import {export_internal} from "./exports-internal"; -import {export_api} from "./export-api"; -import {initializeReplacements} from "./polyfills"; +import { create_weak_ref } from "./weak-ref"; +import { export_internal } from "./exports-internal"; +import { export_api } from "./export-api"; +import { initializeReplacements } from "./polyfills"; -import {mono_wasm_stringify_as_error_with_stack} from "./logging"; -import {instantiate_asset, instantiate_symbols_asset, instantiate_segmentation_rules_asset} from "./assets"; -import {jiterpreter_dump_stats} from "./jiterpreter"; -import {forceDisposeProxies} from "./gc-handles"; -import {mono_wasm_dump_threads} from "./pthreads"; +import { mono_wasm_stringify_as_error_with_stack } from "./logging"; +import { instantiate_asset, instantiate_symbols_asset, instantiate_segmentation_rules_asset } from "./assets"; +import { jiterpreter_dump_stats } from "./jiterpreter"; +import { forceDisposeProxies } from "./gc-handles"; +import { mono_wasm_dump_threads } from "./pthreads"; export let runtimeList: RuntimeList; -function initializeExports (globalObjects: GlobalObjects): RuntimeAPI { +function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { const module = Module; const globals = globalObjects; const globalThisAny = globalThis as any; @@ -75,7 +75,7 @@ function initializeExports (globalObjects: GlobalObjects): RuntimeAPI { class RuntimeList { private list: { [runtimeId: number]: WeakRef } = {}; - public registerRuntime (api: RuntimeAPI): number { + public registerRuntime(api: RuntimeAPI): number { if (api.runtimeId === undefined) { api.runtimeId = Object.keys(this.list).length; } @@ -84,7 +84,7 @@ class RuntimeList { return api.runtimeId; } - public getRuntime (runtimeId: number): RuntimeAPI | undefined { + public getRuntime(runtimeId: number): RuntimeAPI | undefined { const wr = this.list[runtimeId]; return wr ? wr.deref() : undefined; } diff --git a/src/mono/browser/runtime/gc-handles.ts b/src/mono/browser/runtime/gc-handles.ts index 323c3826b7ed82..976fc05406c943 100644 --- a/src/mono/browser/runtime/gc-handles.ts +++ b/src/mono/browser/runtime/gc-handles.ts @@ -4,14 +4,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import {loaderHelpers, mono_assert} from "./globals"; -import {assert_js_interop, js_import_wrapper_by_fn_handle} from "./invoke-js"; -import {mono_log_info, mono_log_warn} from "./logging"; -import {bound_cs_function_symbol, imported_js_function_symbol, proxy_debug_symbol} from "./marshal"; -import {GCHandle, GCHandleNull, JSHandle, WeakRefInternal} from "./types/internal"; -import {_use_weak_ref, create_strong_ref, create_weak_ref} from "./weak-ref"; -import {exportsByAssembly} from "./invoke-cs"; -import {release_js_owned_object_by_gc_handle} from "./managed-exports"; +import { loaderHelpers, mono_assert } from "./globals"; +import { assert_js_interop, js_import_wrapper_by_fn_handle } from "./invoke-js"; +import { mono_log_info, mono_log_warn } from "./logging"; +import { bound_cs_function_symbol, imported_js_function_symbol, proxy_debug_symbol } from "./marshal"; +import { GCHandle, GCHandleNull, JSHandle, WeakRefInternal } from "./types/internal"; +import { _use_weak_ref, create_strong_ref, create_weak_ref } from "./weak-ref"; +import { exportsByAssembly } from "./invoke-cs"; +import { release_js_owned_object_by_gc_handle } from "./managed-exports"; const _use_finalization_registry = typeof globalThis.FinalizationRegistry === "function"; let _js_owned_object_registry: FinalizationRegistry; @@ -31,24 +31,24 @@ let _next_gcv_handle = -2; // GCVHandle is like GCHandle, but it's not tracked and allocated by the mono GC, but just by JS. // It's used when we need to create GCHandle-like identity ahead of time, before calling Mono. // they have negative values, so that they don't collide with GCHandles. -export function alloc_gcv_handle (): GCHandle { +export function alloc_gcv_handle(): GCHandle { const gcv_handle = _gcv_handle_free_list.length ? _gcv_handle_free_list.pop() : _next_gcv_handle--; return gcv_handle as any; } -export function free_gcv_handle (gcv_handle: GCHandle): void { +export function free_gcv_handle(gcv_handle: GCHandle): void { _gcv_handle_free_list.push(gcv_handle); } -export function is_jsv_handle (js_handle: JSHandle): boolean { +export function is_jsv_handle(js_handle: JSHandle): boolean { return (js_handle as any) < -1; } -export function is_js_handle (js_handle: JSHandle): boolean { +export function is_js_handle(js_handle: JSHandle): boolean { return (js_handle as any) > 0; } -export function is_gcv_handle (gc_handle: GCHandle): boolean { +export function is_gcv_handle(gc_handle: GCHandle): boolean { return (gc_handle as any) < -1; } @@ -62,7 +62,7 @@ export const cs_owned_js_handle_symbol = Symbol.for("wasm cs_owned_js_handle"); export const do_not_force_dispose = Symbol.for("wasm do_not_force_dispose"); -export function mono_wasm_get_jsobj_from_js_handle (js_handle: JSHandle): any { +export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { if (is_js_handle(js_handle)) return _cs_owned_objects_by_js_handle[js_handle]; if (is_jsv_handle(js_handle)) @@ -70,7 +70,7 @@ export function mono_wasm_get_jsobj_from_js_handle (js_handle: JSHandle): any { return null; } -export function mono_wasm_get_js_handle (js_obj: any): JSHandle { +export function mono_wasm_get_js_handle(js_obj: any): JSHandle { assert_js_interop(); if (js_obj[cs_owned_js_handle_symbol]) { return js_obj[cs_owned_js_handle_symbol]; @@ -91,7 +91,7 @@ export function mono_wasm_get_js_handle (js_obj: any): JSHandle { return js_handle as JSHandle; } -export function register_with_jsv_handle (js_obj: any, jsv_handle: JSHandle) { +export function register_with_jsv_handle(js_obj: any, jsv_handle: JSHandle) { assert_js_interop(); // note _cs_owned_objects_by_js_handle is list, not Map. That's why we maintain _js_handle_free_list. _cs_owned_objects_by_jsv_handle[0 - jsv_handle] = js_obj; @@ -102,7 +102,7 @@ export function register_with_jsv_handle (js_obj: any, jsv_handle: JSHandle) { } // note: in MT, this is called from locked JSProxyContext. Don't call anything that would need locking. -export function mono_wasm_release_cs_owned_object (js_handle: JSHandle): void { +export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { let obj: any; if (is_js_handle(js_handle)) { obj = _cs_owned_objects_by_js_handle[js_handle]; @@ -119,7 +119,7 @@ export function mono_wasm_release_cs_owned_object (js_handle: JSHandle): void { } } -export function setup_managed_proxy (owner: any, gc_handle: GCHandle): void { +export function setup_managed_proxy(owner: any, gc_handle: GCHandle): void { assert_js_interop(); // keep the gc_handle so that we could easily convert it back to original C# object for roundtrip owner[js_owned_gc_handle_symbol] = gc_handle; @@ -136,7 +136,7 @@ export function setup_managed_proxy (owner: any, gc_handle: GCHandle): void { _js_owned_object_table.set(gc_handle, wr); } -export function upgrade_managed_proxy_to_strong_ref (owner: any, gc_handle: GCHandle): void { +export function upgrade_managed_proxy_to_strong_ref(owner: any, gc_handle: GCHandle): void { const sr = create_strong_ref(owner); if (_use_finalization_registry) { _js_owned_object_registry.unregister(owner); @@ -144,7 +144,7 @@ export function upgrade_managed_proxy_to_strong_ref (owner: any, gc_handle: GCHa _js_owned_object_table.set(gc_handle, sr); } -export function teardown_managed_proxy (owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { +export function teardown_managed_proxy(owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { assert_js_interop(); // The JS object associated with this gc_handle has been collected by the JS GC. // As such, it's not possible for this gc_handle to be invoked by JS anymore, so @@ -168,13 +168,13 @@ export function teardown_managed_proxy (owner: any, gc_handle: GCHandle, skipMan } } -export function assert_not_disposed (result: any): GCHandle { +export function assert_not_disposed(result: any): GCHandle { const gc_handle = result[js_owned_gc_handle_symbol]; mono_check(gc_handle != GCHandleNull, "ObjectDisposedException"); return gc_handle; } -function _js_owned_object_finalized (gc_handle: GCHandle): void { +function _js_owned_object_finalized(gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { // We're shutting down, so don't bother doing anything else. return; @@ -182,7 +182,7 @@ function _js_owned_object_finalized (gc_handle: GCHandle): void { teardown_managed_proxy(null, gc_handle); } -export function _lookup_js_owned_object (gc_handle: GCHandle): any { +export function _lookup_js_owned_object(gc_handle: GCHandle): any { if (!gc_handle) return null; const wr = _js_owned_object_table.get(gc_handle); @@ -194,7 +194,7 @@ export function _lookup_js_owned_object (gc_handle: GCHandle): any { return null; } -export function assertNoProxies (): void { +export function assertNoProxies(): void { if (!WasmEnableThreads) return; mono_assert(_js_owned_object_table.size === 0, "There should be no proxies on this thread."); mono_assert(_cs_owned_objects_by_js_handle.length === 1, "There should be no proxies on this thread."); @@ -207,7 +207,7 @@ let force_dispose_proxies_in_progress = false; // when we arrive here from UninstallWebWorkerInterop, the C# will unregister the handles too. // when called from elsewhere, C# side could be unbalanced!! -export function forceDisposeProxies (disposeMethods: boolean, verbose: boolean): void { +export function forceDisposeProxies(disposeMethods: boolean, verbose: boolean): void { let keepSomeCsAlive = false; let keepSomeJsAlive = false; force_dispose_proxies_in_progress = true; diff --git a/src/mono/browser/runtime/gc-lock.ts b/src/mono/browser/runtime/gc-lock.ts index 7aef7ef2e6827e..ea373eecc0447d 100644 --- a/src/mono/browser/runtime/gc-lock.ts +++ b/src/mono/browser/runtime/gc-lock.ts @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_PTHREAD} from "./globals"; +import { ENVIRONMENT_IS_PTHREAD } from "./globals"; import cwraps from "./cwraps"; export let gc_locked = false; -export function mono_wasm_gc_lock (): void { +export function mono_wasm_gc_lock(): void { if (gc_locked) { throw new Error("GC is already locked"); } @@ -20,7 +20,7 @@ export function mono_wasm_gc_lock (): void { gc_locked = true; } -export function mono_wasm_gc_unlock (): void { +export function mono_wasm_gc_unlock(): void { if (!gc_locked) { throw new Error("GC is not locked"); } diff --git a/src/mono/browser/runtime/globals.ts b/src/mono/browser/runtime/globals.ts index 8653f415b79fb6..06baa02735c1be 100644 --- a/src/mono/browser/runtime/globals.ts +++ b/src/mono/browser/runtime/globals.ts @@ -8,9 +8,9 @@ import gitHash from "consts:gitHash"; -import {RuntimeAPI} from "./types/index"; -import type {GlobalObjects, EmscriptenInternals, RuntimeHelpers, LoaderHelpers, DotnetModuleInternal, PromiseAndController, EmscriptenBuildOptions, GCHandle} from "./types/internal"; -import {mono_log_error} from "./logging"; +import { RuntimeAPI } from "./types/index"; +import type { GlobalObjects, EmscriptenInternals, RuntimeHelpers, LoaderHelpers, DotnetModuleInternal, PromiseAndController, EmscriptenBuildOptions, GCHandle } from "./types/internal"; +import { mono_log_error } from "./logging"; // these are our public API (except internal) export let Module: DotnetModuleInternal; @@ -32,7 +32,7 @@ export let loaderHelpers: LoaderHelpers = null as any; export let _runtimeModuleLoaded = false; // please keep it in place also as rollup guard -export function passEmscriptenInternals (internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { +export function passEmscriptenInternals(internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { runtimeHelpers.emscriptenBuildOptions = emscriptenBuildOptions; ENVIRONMENT_IS_PTHREAD = internals.isPThread; @@ -44,7 +44,7 @@ export function passEmscriptenInternals (internals: EmscriptenInternals, emscrip } // NOTE: this is called AFTER the config is loaded -export function setRuntimeGlobals (globalObjects: GlobalObjects) { +export function setRuntimeGlobals(globalObjects: GlobalObjects) { if (_runtimeModuleLoaded) { throw new Error("Runtime module already loaded"); } @@ -86,14 +86,14 @@ export function setRuntimeGlobals (globalObjects: GlobalObjects) { }); } -export function createPromiseController (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { return loaderHelpers.createPromiseController(afterResolve, afterReject); } // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() diff --git a/src/mono/browser/runtime/guarded-promise.ts b/src/mono/browser/runtime/guarded-promise.ts index 8901403b758bef..fe46ca43521ba2 100644 --- a/src/mono/browser/runtime/guarded-promise.ts +++ b/src/mono/browser/runtime/guarded-promise.ts @@ -3,7 +3,7 @@ /// A Promise that guards against multiple-resolve, multiple-reject, reject-after-accept and accept-after-reject. class GuardedPromise extends Promise { - constructor (executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { + constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { super((resolve, reject) => { let resolved = false; let rejected = false; diff --git a/src/mono/browser/runtime/http.ts b/src/mono/browser/runtime/http.ts index 91504530826cae..120ed4ab0a785e 100644 --- a/src/mono/browser/runtime/http.ts +++ b/src/mono/browser/runtime/http.ts @@ -3,15 +3,15 @@ import BuildConfiguration from "consts:configuration"; -import {wrap_as_cancelable_promise} from "./cancelable-promise"; -import {ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert} from "./globals"; -import {assert_js_interop} from "./invoke-js"; -import {MemoryViewType, Span} from "./marshal"; -import type {VoidPtr} from "./types/emscripten"; -import {ControllablePromise} from "./types/internal"; +import { wrap_as_cancelable_promise } from "./cancelable-promise"; +import { ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert } from "./globals"; +import { assert_js_interop } from "./invoke-js"; +import { MemoryViewType, Span } from "./marshal"; +import type { VoidPtr } from "./types/emscripten"; +import { ControllablePromise } from "./types/internal"; -function verifyEnvironment () { +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. See also https://aka.ms/dotnet-wasm-features" @@ -20,13 +20,13 @@ function verifyEnvironment () { } } -function commonAsserts (controller: HttpController) { +function commonAsserts(controller: HttpController) { assert_js_interop(); mono_assert(controller, "expected controller"); } let http_wasm_supports_streaming_request_cached: boolean | undefined; -export function http_wasm_supports_streaming_request (): boolean { +export function http_wasm_supports_streaming_request(): boolean { if (http_wasm_supports_streaming_request_cached !== undefined) { return http_wasm_supports_streaming_request_cached; } @@ -42,7 +42,7 @@ export function http_wasm_supports_streaming_request (): boolean { const hasContentType = new Request("", { body: new ReadableStream(), method: "POST", - get duplex () { + get duplex() { duplexAccessed = true; return "half"; }, @@ -55,7 +55,7 @@ export function http_wasm_supports_streaming_request (): boolean { } let http_wasm_supports_streaming_response_cached: boolean | undefined; -export function http_wasm_supports_streaming_response (): boolean { +export function http_wasm_supports_streaming_response(): boolean { if (http_wasm_supports_streaming_response_cached !== undefined) { return http_wasm_supports_streaming_response_cached; } @@ -63,7 +63,7 @@ export function http_wasm_supports_streaming_response (): boolean { return http_wasm_supports_streaming_response_cached; } -export function http_wasm_create_controller (): HttpController { +export function http_wasm_create_controller(): HttpController { verifyEnvironment(); assert_js_interop(); const controller: HttpController = { @@ -72,7 +72,7 @@ export function http_wasm_create_controller (): HttpController { return controller; } -export function http_wasm_abort_request (controller: HttpController): void { +export function http_wasm_abort_request(controller: HttpController): void { try { if (controller.streamWriter) { controller.streamWriter.abort(); @@ -83,7 +83,7 @@ export function http_wasm_abort_request (controller: HttpController): void { http_wasm_abort_response(controller); } -export function http_wasm_abort_response (controller: HttpController): void { +export function http_wasm_abort_response(controller: HttpController): void { if (BuildConfiguration === "Debug") commonAsserts(controller); try { controller.isAborted = true; @@ -101,13 +101,13 @@ export function http_wasm_abort_response (controller: HttpController): void { } } -export function http_wasm_transform_stream_write (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_transform_stream_write(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(bufferLength > 0, "expected bufferLength > 0"); // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); const copy = view.slice() as Uint8Array; - return wrap_as_cancelable_promise(async () => { + return wrap_as_cancelable_promise(async() => { mono_assert(controller.streamWriter, "expected streamWriter"); mono_assert(controller.responsePromise, "expected fetch promise"); // race with fetch because fetch does not cancel the ReadableStream see https://bugs.chromium.org/p/chromium/issues/detail?id=1480250 @@ -116,9 +116,9 @@ export function http_wasm_transform_stream_write (controller: HttpController, bu }); } -export function http_wasm_transform_stream_close (controller: HttpController): ControllablePromise { +export function http_wasm_transform_stream_close(controller: HttpController): ControllablePromise { mono_assert(controller, "expected controller"); - return wrap_as_cancelable_promise(async () => { + return wrap_as_cancelable_promise(async() => { mono_assert(controller.streamWriter, "expected streamWriter"); mono_assert(controller.responsePromise, "expected fetch promise"); // race with fetch because fetch does not cancel the ReadableStream see https://bugs.chromium.org/p/chromium/issues/detail?id=1480250 @@ -127,7 +127,7 @@ export function http_wasm_transform_stream_close (controller: HttpController): C }); } -export function http_wasm_fetch_stream (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { +export function http_wasm_fetch_stream(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); const transformStream = new TransformStream(); controller.streamWriter = transformStream.writable.getWriter(); @@ -135,7 +135,7 @@ export function http_wasm_fetch_stream (controller: HttpController, url: string, return fetch_promise; } -export function http_wasm_fetch_bytes (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { +export function http_wasm_fetch_bytes(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bodyPtr is pinned by the caller const view = new Span(bodyPtr, bodyLength, MemoryViewType.Byte); @@ -143,7 +143,7 @@ export function http_wasm_fetch_bytes (controller: HttpController, url: string, return http_wasm_fetch(controller, url, header_names, header_values, option_names, option_values, copy); } -export function http_wasm_fetch (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { +export function http_wasm_fetch(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); verifyEnvironment(); assert_js_interop(); @@ -189,32 +189,32 @@ export function http_wasm_fetch (controller: HttpController, url: string, header return controller.responsePromise; } -export function http_wasm_get_response_type (controller: HttpController): string | undefined { +export function http_wasm_get_response_type(controller: HttpController): string | undefined { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.type; } -export function http_wasm_get_response_status (controller: HttpController): number { +export function http_wasm_get_response_status(controller: HttpController): number { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.status ?? 0; } -export function http_wasm_get_response_header_names (controller: HttpController): string[] { +export function http_wasm_get_response_header_names(controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderNames, "expected responseHeaderNames"); return controller.responseHeaderNames; } -export function http_wasm_get_response_header_values (controller: HttpController): string[] { +export function http_wasm_get_response_header_values(controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderValues, "expected responseHeaderValues"); return controller.responseHeaderValues; } -export function http_wasm_get_response_length (controller: HttpController): ControllablePromise { +export function http_wasm_get_response_length(controller: HttpController): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); - return wrap_as_cancelable_promise(async () => { + return wrap_as_cancelable_promise(async() => { const buffer = await controller.response!.arrayBuffer(); controller.responseBuffer = buffer; controller.currentBufferOffset = 0; @@ -222,7 +222,7 @@ export function http_wasm_get_response_length (controller: HttpController): Cont }); } -export function http_wasm_get_response_bytes (controller: HttpController, view: Span): number { +export function http_wasm_get_response_bytes(controller: HttpController, view: Span): number { mono_assert(controller, "expected controller"); mono_assert(controller.responseBuffer, "expected resoved arrayBuffer"); mono_assert(controller.currentBufferOffset != undefined, "expected currentBufferOffset"); @@ -236,11 +236,11 @@ export function http_wasm_get_response_bytes (controller: HttpController, view: return bytes_read; } -export function http_wasm_get_streamed_response_bytes (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_get_streamed_response_bytes(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); - return wrap_as_cancelable_promise(async () => { + return wrap_as_cancelable_promise(async() => { mono_assert(controller.response, "expected response"); if (!controller.streamReader) { controller.streamReader = controller.response.body!.getReader(); diff --git a/src/mono/browser/runtime/hybrid-globalization/calendar.ts b/src/mono/browser/runtime/hybrid-globalization/calendar.ts index 0e33ab7ed3eaad..38bc3f33da9299 100644 --- a/src/mono/browser/runtime/hybrid-globalization/calendar.ts +++ b/src/mono/browser/runtime/hybrid-globalization/calendar.ts @@ -2,19 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. /* eslint-disable no-inner-declarations */ -import {mono_wasm_new_external_root} from "../roots"; -import {monoStringToString, stringToUTF16} from "../strings"; -import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; -import {Int32Ptr} from "../types/emscripten"; -import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; -import {INNER_SEPARATOR, OUTER_SEPARATOR, normalizeSpaces} from "./helpers"; +import { mono_wasm_new_external_root } from "../roots"; +import { monoStringToString, stringToUTF16 } from "../strings"; +import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; +import { Int32Ptr } from "../types/emscripten"; +import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; +import { INNER_SEPARATOR, OUTER_SEPARATOR, normalizeSpaces } from "./helpers"; const MONTH_CODE = "MMMM"; const YEAR_CODE = "yyyy"; const DAY_CODE = "d"; // this function joins all calendar info with OUTER_SEPARATOR into one string and returns it back to managed code -export function mono_wasm_get_calendar_info (culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_calendar_info(culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -71,14 +71,14 @@ export function mono_wasm_get_calendar_info (culture: MonoStringRef, calendarId: } } -function getCalendarName (locale: any) { +function getCalendarName(locale: any) { const calendars = getCalendarInfo(locale); if (!calendars || calendars.length == 0) return ""; return calendars[0]; } -function getCalendarInfo (locale: string) { +function getCalendarInfo(locale: string) { try { // most tools have it implemented as a property return (new Intl.Locale(locale) as any).calendars; @@ -92,10 +92,10 @@ function getCalendarInfo (locale: string) { } } -function getMonthYearPattern (locale: string | undefined, date: Date): string { - let pattern = date.toLocaleDateString(locale, {year: "numeric", month: "long"}).toLowerCase(); +function getMonthYearPattern(locale: string | undefined, date: Date): string { + let pattern = date.toLocaleDateString(locale, { year: "numeric", month: "long" }).toLowerCase(); // pattern has month name as string or as number - const monthName = date.toLocaleString(locale, {month: "long"}).toLowerCase().trim(); + const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "yyyy\u5e74M\u6708"; @@ -103,20 +103,20 @@ function getMonthYearPattern (locale: string | undefined, date: Date): string { pattern = pattern.replace(monthName, MONTH_CODE); pattern = pattern.replace("999", YEAR_CODE); // sometimes the number is localized and the above does not have an effect - const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); + const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); pattern = normalizeSpaces(pattern); return pattern.replace(yearStr, YEAR_CODE); } -function getMonthDayPattern (locale: string | undefined, date: Date): string { - let pattern = date.toLocaleDateString(locale, {month: "long", day: "numeric"}).toLowerCase(); +function getMonthDayPattern(locale: string | undefined, date: Date): string { + let pattern = date.toLocaleDateString(locale, { month: "long", day: "numeric" }).toLowerCase(); // pattern has month name as string or as number - const monthName = date.toLocaleString(locale, {month: "long"}).toLowerCase().trim(); + const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "M\u6708d\u65e5"; } - const formatWithoutMonthName = new Intl.DateTimeFormat(locale, {day: "numeric"}); + const formatWithoutMonthName = new Intl.DateTimeFormat(locale, { day: "numeric" }); const replacedMonthName = getGenitiveForName(date, pattern, monthName, formatWithoutMonthName); pattern = pattern.replace(replacedMonthName, MONTH_CODE); pattern = pattern.replace("22", DAY_CODE); @@ -124,7 +124,7 @@ function getMonthDayPattern (locale: string | undefined, date: Date): string { return pattern.replace(dayStr, DAY_CODE); } -function getShortDatePattern (locale: string | undefined): string { +function getShortDatePattern(locale: string | undefined): string { if (locale?.substring(0, 2) == "fa") { // persian calendar is shifted and it has no lapping dates with // arabic and gregorian calendars, so that both day and month would be < 10 @@ -140,7 +140,7 @@ function getShortDatePattern (locale: string | undefined): string { const shortMonthStr = "1"; const longDayStr = "02"; const shortDayStr = "2"; - let pattern = date.toLocaleDateString(locale, {dateStyle: "short"}); + let pattern = date.toLocaleDateString(locale, { dateStyle: "short" }); // each date part might be in localized numbers or standard arabic numbers // toLocaleDateString returns not compatible data, // e.g. { dateStyle: "short" } sometimes contains localized year number @@ -149,7 +149,7 @@ function getShortDatePattern (locale: string | undefined): string { pattern = pattern.replace(longYearStr, YEAR_CODE); pattern = pattern.replace(shortYearStr, YEAR_CODE); } else { - const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); + const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); const yearStrShort = yearStr.substring(yearStr.length - 2, yearStr.length); pattern = pattern.replace(yearStr, YEAR_CODE); if (yearStrShort) @@ -160,7 +160,7 @@ function getShortDatePattern (locale: string | undefined): string { pattern = pattern.replace(longMonthStr, "MM"); pattern = pattern.replace(shortMonthStr, "M"); } else { - const monthStr = date.toLocaleDateString(locale, {month: "numeric"}); + const monthStr = date.toLocaleDateString(locale, { month: "numeric" }); const localizedMonthCode = monthStr.length == 1 ? "M" : "MM"; pattern = pattern.replace(monthStr, localizedMonthCode); } @@ -169,46 +169,46 @@ function getShortDatePattern (locale: string | undefined): string { pattern = pattern.replace(longDayStr, "dd"); pattern = pattern.replace(shortDayStr, "d"); } else { - const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); + const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); const localizedDayCode = dayStr.length == 1 ? "d" : "dd"; pattern = pattern.replace(dayStr, localizedDayCode); } return normalizeSpaces(pattern); } -function getLongDatePattern (locale: string | undefined, date: Date): string { +function getLongDatePattern(locale: string | undefined, date: Date): string { if (locale == "th-TH") { // cannot be caught with regexes return "ddddที่ d MMMM g yyyy"; } - let pattern = new Intl.DateTimeFormat(locale, {weekday: "long", year: "numeric", month: "long", day: "numeric"}).format(date).toLowerCase(); - const monthName = date.toLocaleString(locale, {month: "long"}).trim().toLowerCase(); + let pattern = new Intl.DateTimeFormat(locale, { weekday: "long", year: "numeric", month: "long", day: "numeric" }).format(date).toLowerCase(); + const monthName = date.toLocaleString(locale, { month: "long" }).trim().toLowerCase(); // pattern has month name as string or as number const monthSuffix = monthName.charAt(monthName.length - 1); if (monthSuffix == "\u6708" || monthSuffix == "\uc6d4") { // Asian-like patterns: - const shortMonthName = date.toLocaleString(locale, {month: "short"}); + const shortMonthName = date.toLocaleString(locale, { month: "short" }); pattern = pattern.replace(shortMonthName, `M${monthSuffix}`); } else { - const replacedMonthName = getGenitiveForName(date, pattern, monthName, new Intl.DateTimeFormat(locale, {weekday: "long", year: "numeric", day: "numeric"})); + const replacedMonthName = getGenitiveForName(date, pattern, monthName, new Intl.DateTimeFormat(locale, { weekday: "long", year: "numeric", day: "numeric" })); pattern = pattern.replace(replacedMonthName, MONTH_CODE); } pattern = pattern.replace("999", YEAR_CODE); // sometimes the number is localized and the above does not have an effect, // so additionally, we need to do: - const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); + const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); pattern = pattern.replace(yearStr, YEAR_CODE); - const weekday = date.toLocaleDateString(locale, {weekday: "long"}).toLowerCase(); - const replacedWeekday = getGenitiveForName(date, pattern, weekday, new Intl.DateTimeFormat(locale, {year: "numeric", month: "long", day: "numeric"})); + const weekday = date.toLocaleDateString(locale, { weekday: "long" }).toLowerCase(); + const replacedWeekday = getGenitiveForName(date, pattern, weekday, new Intl.DateTimeFormat(locale, { year: "numeric", month: "long", day: "numeric" })); pattern = pattern.replace(replacedWeekday, "dddd"); pattern = pattern.replace("22", DAY_CODE); - const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); // should we replace it for localized digits? + const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); // should we replace it for localized digits? pattern = normalizeSpaces(pattern); return pattern.replace(dayStr, DAY_CODE); } -function getGenitiveForName (date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) { +function getGenitiveForName(date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) { let genitiveName = name; const nameStart = pattern.indexOf(name); if (nameStart == -1 || @@ -226,21 +226,21 @@ function getGenitiveForName (date: Date, pattern: string, name: string, formatWi return genitiveName; } -function getDayNames (locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } { +function getDayNames(locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } { const weekDay = new Date(2023, 5, 25); // Sunday const dayNames = []; const dayNamesAbb = []; const dayNamesSS = []; for(let i = 0; i < 7; i++) { - dayNames[i] = weekDay.toLocaleDateString(locale, {weekday: "long"}); - dayNamesAbb[i] = weekDay.toLocaleDateString(locale, {weekday: "short"}); - dayNamesSS[i] = weekDay.toLocaleDateString(locale, {weekday: "narrow"}); + dayNames[i] = weekDay.toLocaleDateString(locale, { weekday: "long" }); + dayNamesAbb[i] = weekDay.toLocaleDateString(locale, { weekday: "short" }); + dayNamesSS[i] = weekDay.toLocaleDateString(locale, { weekday: "narrow" }); weekDay.setDate(weekDay.getDate() + 1); } - return {long: dayNames, abbreviated: dayNamesAbb, shortest: dayNamesSS}; + return { long: dayNames, abbreviated: dayNamesAbb, shortest: dayNamesSS }; } -function getMonthNames (locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } { +function getMonthNames(locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } { // some calendars have the first month on non-0 index in JS // first month: Muharram ("ar") or Farwardin ("fa") or January const localeLang = locale ? locale.split("-")[0] : ""; @@ -255,8 +255,8 @@ function getMonthNames (locale: string | undefined) : { long: string[], abbrevia const monthCnt = i % 12; date.setMonth(monthCnt); - const monthNameLong = date.toLocaleDateString(locale, {month: "long"}); - const monthNameShort = date.toLocaleDateString(locale, {month: "short"}); + const monthNameLong = date.toLocaleDateString(locale, { month: "long" }); + const monthNameShort = date.toLocaleDateString(locale, { month: "short" }); months[i - firstMonthShift] = monthNameLong; monthsAbb[i - firstMonthShift] = monthNameShort; // for Genitive forms: @@ -267,8 +267,8 @@ function getMonthNames (locale: string | undefined) : { long: string[], abbrevia monthsAbbGen[i - firstMonthShift] = monthNameShort; continue; } - const formatWithoutMonthName = new Intl.DateTimeFormat(locale, {day: "numeric"}); - const monthWithDayLong = date.toLocaleDateString(locale, {month: "long", day: "numeric"}); + const formatWithoutMonthName = new Intl.DateTimeFormat(locale, { day: "numeric" }); + const monthWithDayLong = date.toLocaleDateString(locale, { month: "long", day: "numeric" }); monthsGen[i - firstMonthShift] = getGenitiveForName(date, monthWithDayLong, monthNameLong, formatWithoutMonthName); isShortFormBroken = isShortFormBroken ?? /^\d+$/.test(monthNameShort); if (isShortFormBroken) { @@ -277,15 +277,15 @@ function getMonthNames (locale: string | undefined) : { long: string[], abbrevia monthsAbbGen[i - firstMonthShift] = monthNameShort; continue; } - const monthWithDayShort = date.toLocaleDateString(locale, {month: "short", day: "numeric"}); + const monthWithDayShort = date.toLocaleDateString(locale, { month: "short", day: "numeric" }); monthsAbbGen[i - firstMonthShift] = getGenitiveForName(date, monthWithDayShort, monthNameShort, formatWithoutMonthName); } - return {long: months, abbreviated: monthsAbb, longGenitive: monthsGen, abbreviatedGenitive: monthsAbbGen}; + return { long: months, abbreviated: monthsAbb, longGenitive: monthsGen, abbreviatedGenitive: monthsAbbGen }; } // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. -function getEraNames (date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} { +function getEraNames(date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} { if (shouldBePopulatedByManagedCode(calendarId)) { // managed code already handles these calendars, // so empty strings will get overwritten in @@ -295,10 +295,10 @@ function getEraNames (date: Date, locale: string | undefined, calendarId: number abbreviatedEraNames: "" }; } - const yearStr = date.toLocaleDateString(locale, {year: "numeric"}); - const dayStr = date.toLocaleDateString(locale, {day: "numeric"}); - const eraDate = date.toLocaleDateString(locale, {era: "short"}); - const shortEraDate = date.toLocaleDateString(locale, {era: "narrow"}); + const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); + const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); + const eraDate = date.toLocaleDateString(locale, { era: "short" }); + const shortEraDate = date.toLocaleDateString(locale, { era: "narrow" }); const eraDateParts = eraDate.includes(yearStr) ? getEraDateParts(yearStr) : @@ -309,11 +309,11 @@ function getEraNames (date: Date, locale: string | undefined, calendarId: number abbreviatedEraNames: getEraFromDateParts(eraDateParts.abbrEraDateParts, eraDateParts.ignoredPart) }; - function shouldBePopulatedByManagedCode (calendarId: number) { + function shouldBePopulatedByManagedCode(calendarId: number) { return (calendarId > 1 && calendarId < 15) || calendarId == 22 || calendarId == 23; } - function getEraFromDateParts (dateParts: string[], ignoredPart: string) : string { + function getEraFromDateParts(dateParts: string[], ignoredPart: string) : string { const regex = new RegExp(`^((?!${ignoredPart}|[0-9]).)*$`); const filteredEra = dateParts.filter(part => regex.test(part)); if (filteredEra.length == 0) @@ -321,7 +321,7 @@ function getEraNames (date: Date, locale: string | undefined, calendarId: number return filteredEra[0].trim(); } - function getEraDateParts (yearStr: string) { + function getEraDateParts(yearStr: string) { if (eraDate.startsWith(yearStr) || eraDate.endsWith(yearStr)) { return { eraDateParts: eraDate.split(dayStr), diff --git a/src/mono/browser/runtime/hybrid-globalization/change-case.ts b/src/mono/browser/runtime/hybrid-globalization/change-case.ts index d502dd02a301e9..3ed5182dfa5530 100644 --- a/src/mono/browser/runtime/hybrid-globalization/change-case.ts +++ b/src/mono/browser/runtime/hybrid-globalization/change-case.ts @@ -1,15 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {mono_wasm_new_external_root} from "../roots"; -import {monoStringToString, utf16ToStringLoop, stringToUTF16} from "../strings"; -import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; -import {Int32Ptr} from "../types/emscripten"; -import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; -import {localHeapViewU16, setU16_local} from "../memory"; -import {isSurrogate} from "./helpers"; +import { mono_wasm_new_external_root } from "../roots"; +import { monoStringToString, utf16ToStringLoop, stringToUTF16 } from "../strings"; +import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; +import { Int32Ptr } from "../types/emscripten"; +import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; +import { localHeapViewU16, setU16_local } from "../memory"; +import { isSurrogate } from "./helpers"; -export function mono_wasm_change_case_invariant (src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case_invariant(src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const exceptionRoot = mono_wasm_new_external_root(ex_address); try { const input = utf16ToStringLoop(src, src + 2 * srcLength); @@ -67,7 +67,7 @@ export function mono_wasm_change_case_invariant (src: number, srcLength: number, } } -export function mono_wasm_change_case (culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -128,7 +128,7 @@ export function mono_wasm_change_case (culture: MonoStringRef, src: number, srcL } } -function appendSurrogateToMemory (heapI16: Uint16Array, dst: number, surrogate: string, idx: number) { +function appendSurrogateToMemory(heapI16: Uint16Array, dst: number, surrogate: string, idx: number) { setU16_local(heapI16, dst + idx * 2, surrogate.charCodeAt(0)); setU16_local(heapI16, dst + (idx + 1) * 2, surrogate.charCodeAt(1)); } diff --git a/src/mono/browser/runtime/hybrid-globalization/collations.ts b/src/mono/browser/runtime/hybrid-globalization/collations.ts index 9680fa056704f2..080544801697e1 100644 --- a/src/mono/browser/runtime/hybrid-globalization/collations.ts +++ b/src/mono/browser/runtime/hybrid-globalization/collations.ts @@ -1,18 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {mono_wasm_new_external_root} from "../roots"; -import {monoStringToString, utf16ToString} from "../strings"; -import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; -import {Int32Ptr} from "../types/emscripten"; -import {wrap_error_root, wrap_no_error_root} from "../invoke-js"; -import {GraphemeSegmenter} from "./grapheme-segmenter"; +import { mono_wasm_new_external_root } from "../roots"; +import { monoStringToString, utf16ToString } from "../strings"; +import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; +import { Int32Ptr } from "../types/emscripten"; +import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; +import { GraphemeSegmenter } from "./grapheme-segmenter"; const COMPARISON_ERROR = -2; const INDEXING_ERROR = -1; let graphemeSegmenterCached: GraphemeSegmenter | null; -export function mono_wasm_compare_string (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_compare_string(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -32,7 +32,7 @@ export function mono_wasm_compare_string (culture: MonoStringRef, str1: number, } } -export function mono_wasm_starts_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_starts_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -61,7 +61,7 @@ export function mono_wasm_starts_with (culture: MonoStringRef, str1: number, str } } -export function mono_wasm_ends_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_ends_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -90,7 +90,7 @@ export function mono_wasm_ends_with (culture: MonoStringRef, str1: number, str1L } } -export function mono_wasm_index_of (culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_index_of(culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -158,12 +158,12 @@ export function mono_wasm_index_of (culture: MonoStringRef, needlePtr: number, n exceptionRoot.release(); } - function checkMatchFound (str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { + function checkMatchFound(str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { return compareStrings(str1, str2, locale, casePicker) === 0; } } -function compareStrings (string1: string, string2: string, locale: string | undefined, casePicker: number): number { +function compareStrings(string1: string, string2: string, locale: string | undefined, casePicker: number): number { switch (casePicker) { case 0: // 0: None - default algorithm for the platform OR @@ -186,30 +186,30 @@ function compareStrings (string1: string, string2: string, locale: string | unde case 12: // 4: IgnoreSymbols // 12: IgnoreKanaType | IgnoreSymbols - return string1.localeCompare(string2, locale, {ignorePunctuation: true}); // by default ignorePunctuation: false + return string1.localeCompare(string2, locale, { ignorePunctuation: true }); // by default ignorePunctuation: false case 5: // 5: IgnoreSymbols | IgnoreCase string1 = string1.toLocaleLowerCase(locale); string2 = string2.toLocaleLowerCase(locale); - return string1.localeCompare(string2, locale, {ignorePunctuation: true}); // a ≠ b, a ≠ á, a ≠ A + return string1.localeCompare(string2, locale, { ignorePunctuation: true }); // a ≠ b, a ≠ á, a ≠ A case 9: // 9: IgnoreKanaType | IgnoreCase - return string1.localeCompare(string2, locale, {sensitivity: "accent"}); // a ≠ b, a ≠ á, a = A + return string1.localeCompare(string2, locale, { sensitivity: "accent" }); // a ≠ b, a ≠ á, a = A case 10: // 10: IgnoreKanaType | IgnoreNonSpace - return string1.localeCompare(string2, locale, {sensitivity: "case"}); // a ≠ b, a = á, a ≠ A + return string1.localeCompare(string2, locale, { sensitivity: "case" }); // a ≠ b, a = á, a ≠ A case 11: // 11: IgnoreKanaType | IgnoreNonSpace | IgnoreCase - return string1.localeCompare(string2, locale, {sensitivity: "base"}); // a ≠ b, a = á, a = A + return string1.localeCompare(string2, locale, { sensitivity: "base" }); // a ≠ b, a = á, a = A case 13: // 13: IgnoreKanaType | IgnoreCase | IgnoreSymbols - return string1.localeCompare(string2, locale, {sensitivity: "accent", ignorePunctuation: true}); // a ≠ b, a ≠ á, a = A + return string1.localeCompare(string2, locale, { sensitivity: "accent", ignorePunctuation: true }); // a ≠ b, a ≠ á, a = A case 14: // 14: IgnoreKanaType | IgnoreSymbols | IgnoreNonSpace - return string1.localeCompare(string2, locale, {sensitivity: "case", ignorePunctuation: true});// a ≠ b, a = á, a ≠ A + return string1.localeCompare(string2, locale, { sensitivity: "case", ignorePunctuation: true });// a ≠ b, a = á, a ≠ A case 15: // 15: IgnoreKanaType | IgnoreSymbols | IgnoreNonSpace | IgnoreCase - return string1.localeCompare(string2, locale, {sensitivity: "base", ignorePunctuation: true}); // a ≠ b, a = á, a = A + return string1.localeCompare(string2, locale, { sensitivity: "base", ignorePunctuation: true }); // a ≠ b, a = á, a = A case 2: case 3: case 6: @@ -255,12 +255,12 @@ function compareStrings (string1: string, string2: string, locale: string | unde } } -function decodeToCleanString (strPtr: number, strLen: number) { +function decodeToCleanString(strPtr: number, strLen: number) { const str = utf16ToString(strPtr, (strPtr + 2 * strLen)); return cleanString(str); } -function cleanString (str: string) { +function cleanString(str: string) { const nStr = str.normalize(); return nStr.replace(/[\u200B-\u200D\uFEFF\0]/g, ""); } diff --git a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts index dd32bf19746c20..d6d095a3effee4 100644 --- a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts +++ b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts @@ -1,14 +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 {wrap_error_root, wrap_no_error_root} from "../invoke-js"; -import {mono_wasm_new_external_root} from "../roots"; -import {monoStringToString, stringToUTF16} from "../strings"; -import {Int32Ptr} from "../types/emscripten"; -import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; -import {OUTER_SEPARATOR, normalizeLocale, normalizeSpaces} from "./helpers"; +import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; +import { mono_wasm_new_external_root } from "../roots"; +import { monoStringToString, stringToUTF16 } from "../strings"; +import { Int32Ptr } from "../types/emscripten"; +import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; +import { OUTER_SEPARATOR, normalizeLocale, normalizeSpaces } from "./helpers"; -export function mono_wasm_get_culture_info (culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_culture_info(culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -41,7 +41,7 @@ export function mono_wasm_get_culture_info (culture: MonoStringRef, dst: number, } } -function getAmPmDesignators (locale: any) { +function getAmPmDesignators(locale: any) { const pmTime = new Date("August 19, 1975 12:15:33"); // do not change, some PM hours result in hour digits change, e.g. 13 -> 01 or 1 const amTime = new Date("August 19, 1975 11:15:33"); // do not change, some AM hours result in hour digits change, e.g. 9 -> 09 const pmDesignator = getDesignator(pmTime, locale); @@ -52,15 +52,15 @@ function getAmPmDesignators (locale: any) { }; } -function getDesignator (time: Date, locale: string) { - let withDesignator = time.toLocaleTimeString(locale, {hourCycle: "h12"}); +function getDesignator(time: Date, locale: string) { + let withDesignator = time.toLocaleTimeString(locale, { hourCycle: "h12" }); const localizedZero = (0).toLocaleString(locale); if (withDesignator.includes(localizedZero)) { // in v8>=11.8 "12" changes to "0" for ja-JP const localizedTwelve = (12).toLocaleString(locale); withDesignator = withDesignator.replace(localizedZero, localizedTwelve); } - const withoutDesignator = time.toLocaleTimeString(locale, {hourCycle: "h24"}); + const withoutDesignator = time.toLocaleTimeString(locale, { hourCycle: "h24" }); const designator = withDesignator.replace(withoutDesignator, "").trim(); if (new RegExp("[0-9]$").test(designator)) { const designatorParts = withDesignator.split(" ").filter(part => new RegExp("^((?![0-9]).)*$").test(part)); @@ -71,16 +71,16 @@ function getDesignator (time: Date, locale: string) { return designator; } -function getLongTimePattern (locale: string | undefined, designators: any): string { +function getLongTimePattern(locale: string | undefined, designators: any): string { const hourIn24Format = 18; // later hours than 18 have night designators in some locales (instead of AM designator) const hourIn12Format = 6; const localizedHour24 = (hourIn24Format).toLocaleString(locale); // not all locales use arabic numbers const localizedHour12 = (hourIn12Format).toLocaleString(locale); const pmTime = new Date(`August 19, 1975 ${hourIn24Format}:15:30`); // in the comments, en-US locale is used: - const shortTime = new Intl.DateTimeFormat(locale, {timeStyle: "medium"}); + const shortTime = new Intl.DateTimeFormat(locale, { timeStyle: "medium" }); const shortPmStyle = shortTime.format(pmTime); // 12:15:30 PM - const minutes = pmTime.toLocaleTimeString(locale, {minute: "numeric"}); // 15 - const seconds = pmTime.toLocaleTimeString(locale, {second: "numeric"}); // 30 + const minutes = pmTime.toLocaleTimeString(locale, { minute: "numeric" }); // 15 + const seconds = pmTime.toLocaleTimeString(locale, { second: "numeric" }); // 30 let pattern = shortPmStyle.replace(designators.pm, "tt").replace(minutes, "mm").replace(seconds, "ss"); // 12:mm:ss tt const isISOStyle = pattern.includes(localizedHour24); // 24h or 12h pattern? @@ -101,7 +101,7 @@ function getLongTimePattern (locale: string | undefined, designators: any): stri return normalizeSpaces(pattern); } -function getShortTimePattern (pattern: string): string { +function getShortTimePattern(pattern: string): string { // remove seconds: // short dotnet pattern does not contain seconds while JS's pattern always contains them const secondsIdx = pattern.indexOf("ss"); diff --git a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts index c9ae7f4427694c..18547a0d359128 100644 --- a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts +++ b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts @@ -7,8 +7,8 @@ * https://github.com/formatjs/formatjs/blob/58d6a7b398d776ca3d2726d72ae1573b65cc3bef/packages/intl-segmenter/src/segmentation-utils.ts */ -import {mono_assert} from "../globals"; -import {isSurrogate} from "./helpers"; +import { mono_assert } from "../globals"; +import { isSurrogate } from "./helpers"; type SegmentationRule = { breaks: boolean @@ -29,7 +29,7 @@ type SegmentationTypeRaw = { let segmentationRules: Record; -function replaceVariables (variables: Record, input: string): string { +function replaceVariables(variables: Record, input: string): string { const findVarRegex = /\$[A-Za-z0-9_]+/gm; return input.replaceAll(findVarRegex, match => { if (!(match in variables)) { @@ -39,15 +39,15 @@ function replaceVariables (variables: Record, input: string): st }); } -function generateRegexRule (rule: string, variables: Record, after: boolean): RegExp { +function generateRegexRule(rule: string, variables: Record, after: boolean): RegExp { return new RegExp(`${after ? "^" : ""}${replaceVariables(variables, rule)}${after ? "" : "$"}`); } -function isSegmentationTypeRaw (obj: any): obj is SegmentationTypeRaw { +function isSegmentationTypeRaw(obj: any): obj is SegmentationTypeRaw { return obj.variables != null && obj.rules != null; } -export function setSegmentationRulesFromJson (json: string) { +export function setSegmentationRulesFromJson(json: string) { mono_assert(isSegmentationTypeRaw(json), "Provided grapheme segmentation rules are not valid"); segmentationRules = GraphemeSegmenter.prepareSegmentationRules(json); } @@ -56,7 +56,7 @@ export class GraphemeSegmenter { private readonly rules: Record; private readonly ruleSortedKeys: string[]; - public constructor () { + public constructor() { this.rules = segmentationRules; this.ruleSortedKeys = Object.keys(this.rules).sort((a, b) => Number(a) - Number(b)); } @@ -67,7 +67,7 @@ export class GraphemeSegmenter { * @param startIndex - The starting index. * @returns The next grapheme. */ - public nextGrapheme (str: string, startIndex: number): string { + public nextGrapheme(str: string, startIndex: number): string { const breakIdx = this.nextGraphemeBreak(str, startIndex); return str.substring(startIndex, breakIdx); } @@ -79,7 +79,7 @@ export class GraphemeSegmenter { * @param startIndex - The index to start searching from. * @returns The index of the next grapheme break. */ - public nextGraphemeBreak (str: string, startIndex: number): number { + public nextGraphemeBreak(str: string, startIndex: number): number { if (startIndex < 0) return 0; @@ -103,9 +103,9 @@ export class GraphemeSegmenter { return str.length; } - private isGraphemeBreak (previous: string, current: string): boolean { + private isGraphemeBreak(previous: string, current: string): boolean { for (const key of this.ruleSortedKeys) { - const {before, after, breaks} = this.rules[key]; + const { before, after, breaks } = this.rules[key]; // match before and after rules if (before && !before.test(previous)) { continue; @@ -121,12 +121,12 @@ export class GraphemeSegmenter { return true; } - public static prepareSegmentationRules (segmentationRules: SegmentationTypeRaw): Record { + public static prepareSegmentationRules(segmentationRules: SegmentationTypeRaw): Record { const preparedRules: Record = {}; for (const key of Object.keys(segmentationRules.rules)) { const ruleValue = segmentationRules.rules[key]; - const preparedRule: SegmentationRule = {breaks: ruleValue.breaks,}; + const preparedRule: SegmentationRule = { breaks: ruleValue.breaks, }; if ("before" in ruleValue && ruleValue.before) { preparedRule.before = generateRegexRule(ruleValue.before, segmentationRules.variables, false); diff --git a/src/mono/browser/runtime/hybrid-globalization/helpers.ts b/src/mono/browser/runtime/hybrid-globalization/helpers.ts index 0cd2294447226f..b6542eeedc69cb 100644 --- a/src/mono/browser/runtime/hybrid-globalization/helpers.ts +++ b/src/mono/browser/runtime/hybrid-globalization/helpers.ts @@ -9,7 +9,7 @@ const SURROGATE_LOWER_END = "\uDFFF"; export const OUTER_SEPARATOR = "##"; export const INNER_SEPARATOR = "||"; -export function normalizeLocale (locale: string | null) { +export function normalizeLocale(locale: string | null) { if (!locale) return undefined; try { @@ -26,7 +26,7 @@ export function normalizeLocale (locale: string | null) { } } -export function normalizeSpaces (pattern: string) { +export function normalizeSpaces(pattern: string) { if (!pattern.includes("\u202F")) return pattern; @@ -35,7 +35,7 @@ export function normalizeSpaces (pattern: string) { } -export function isSurrogate (str: string, startIdx: number): boolean { +export function isSurrogate(str: string, startIdx: number): boolean { return SURROGATE_HIGHER_START <= str[startIdx] && str[startIdx] <= SURROGATE_HIGHER_END && startIdx + 1 < str.length && diff --git a/src/mono/browser/runtime/hybrid-globalization/locales.ts b/src/mono/browser/runtime/hybrid-globalization/locales.ts index 93ddeaa9389bb4..55f3bc4983b7c0 100644 --- a/src/mono/browser/runtime/hybrid-globalization/locales.ts +++ b/src/mono/browser/runtime/hybrid-globalization/locales.ts @@ -1,14 +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 {wrap_error_root, wrap_no_error_root} from "../invoke-js"; -import {mono_wasm_new_external_root} from "../roots"; -import {monoStringToString, stringToUTF16} from "../strings"; -import {Int32Ptr} from "../types/emscripten"; -import {MonoObject, MonoObjectRef, MonoString, MonoStringRef} from "../types/internal"; -import {OUTER_SEPARATOR, normalizeLocale} from "./helpers"; +import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; +import { mono_wasm_new_external_root } from "../roots"; +import { monoStringToString, stringToUTF16 } from "../strings"; +import { Int32Ptr } from "../types/emscripten"; +import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; +import { OUTER_SEPARATOR, normalizeLocale } from "./helpers"; -export function mono_wasm_get_locale_info (culture: MonoStringRef, locale: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const localeRoot = mono_wasm_new_external_root(locale), cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -37,14 +37,14 @@ export function mono_wasm_get_locale_info (culture: MonoStringRef, locale: MonoS try { const region = localeParts.length > 1 ? localeParts.pop() : undefined; // this line might fail if form 4 from the comment above is used: - regionName = region ? new Intl.DisplayNames([cultureName], {type: "region"}).of(region) : undefined; + regionName = region ? new Intl.DisplayNames([cultureName], { type: "region" }).of(region) : undefined; const language = localeParts.join("-"); - languageName = new Intl.DisplayNames([cultureName], {type: "language"}).of(language); + languageName = new Intl.DisplayNames([cultureName], { type: "language" }).of(language); } catch (error) { if (error instanceof RangeError && error.message === "invalid_argument") { // if it failed from this reason then cultureName is in a form "language-script", without region try { - languageName = new Intl.DisplayNames([cultureName], {type: "language"}).of(localeName); + languageName = new Intl.DisplayNames([cultureName], { type: "language" }).of(localeName); } catch (error) { if (error instanceof RangeError && error.message === "invalid_argument" && localeNameOriginal) { // handle non-standard or malformed locales by forwarding the locale code, e.g. "xx-u-xx" @@ -82,7 +82,7 @@ export function mono_wasm_get_locale_info (culture: MonoStringRef, locale: MonoS } } -export function mono_wasm_get_first_day_of_week (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_first_day_of_week(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -100,7 +100,7 @@ export function mono_wasm_get_first_day_of_week (culture: MonoStringRef, isExcep } } -export function mono_wasm_get_first_week_of_year (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_first_week_of_year(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -118,7 +118,7 @@ export function mono_wasm_get_first_week_of_year (culture: MonoStringRef, isExce } } -function getFirstDayOfWeek (locale: string) { +function getFirstDayOfWeek(locale: string) { const weekInfo = getWeekInfo(locale); if (weekInfo) { // JS's Sunday == 7 while dotnet's Sunday == 0 @@ -139,7 +139,7 @@ function getFirstDayOfWeek (locale: string) { return 1; } -function getFirstWeekOfYear (locale: string) { +function getFirstWeekOfYear(locale: string) { const weekInfo = getWeekInfo(locale); if (weekInfo) { // enum CalendarWeekRule @@ -160,7 +160,7 @@ function getFirstWeekOfYear (locale: string) { return 0; } -function getWeekInfo (locale: string) { +function getWeekInfo(locale: string) { try { // most tools have it implemented as property return (new Intl.Locale(locale) as any).weekInfo; diff --git a/src/mono/browser/runtime/icu.ts b/src/mono/browser/runtime/icu.ts index f55fb3b8e972b0..28aa01ad727cfd 100644 --- a/src/mono/browser/runtime/icu.ts +++ b/src/mono/browser/runtime/icu.ts @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. import cwraps from "./cwraps"; -import {VoidPtr} from "./types/emscripten"; +import { VoidPtr } from "./types/emscripten"; // @offset must be the address of an ICU data archive in the native heap. // returns true on success. -export function mono_wasm_load_icu_data (offset: VoidPtr): boolean { +export function mono_wasm_load_icu_data(offset: VoidPtr): boolean { return (cwraps.mono_wasm_load_icu_data(offset)) === 1; } diff --git a/src/mono/browser/runtime/interp-pgo.ts b/src/mono/browser/runtime/interp-pgo.ts index 791cee8c3287e6..c4214b4fe5d6a3 100644 --- a/src/mono/browser/runtime/interp-pgo.ts +++ b/src/mono/browser/runtime/interp-pgo.ts @@ -3,15 +3,15 @@ import ProductVersion from "consts:productVersion"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_WEB, Module, loaderHelpers, runtimeHelpers} from "./globals"; -import {mono_log_info, mono_log_error, mono_log_warn} from "./logging"; -import {localHeapViewU8} from "./memory"; +import { ENVIRONMENT_IS_WEB, Module, loaderHelpers, runtimeHelpers } from "./globals"; +import { mono_log_info, mono_log_error, mono_log_warn } from "./logging"; +import { localHeapViewU8 } from "./memory"; import cwraps from "./cwraps"; -import {MonoConfigInternal} from "./types/internal"; +import { MonoConfigInternal } from "./types/internal"; export const tablePrefix = "https://dotnet.generated.invalid/interp_pgo"; -export async function interp_pgo_save_data () { +export async function interp_pgo_save_data() { if (!loaderHelpers.is_runtime_running()) { mono_log_info("Skipped saving interp_pgo table (already exited)"); return; @@ -53,7 +53,7 @@ export async function interp_pgo_save_data () { } } -export async function interp_pgo_load_data () { +export async function interp_pgo_load_data() { const cacheKey = await getCacheKey(tablePrefix); if (!cacheKey) { mono_log_error("Failed to create cache key for interp_pgo table"); @@ -76,7 +76,7 @@ export async function interp_pgo_load_data () { Module._free(pData); } -async function openCache (): Promise { +async function openCache(): Promise { // 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 (ENVIRONMENT_IS_WEB && globalThis.window.isSecureContext === false) { @@ -113,7 +113,7 @@ async function openCache (): Promise { } } -export async function getCacheEntry (cacheKey: string): Promise { +export async function getCacheEntry(cacheKey: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -130,7 +130,7 @@ export async function getCacheEntry (cacheKey: string): Promise { +export async function storeCacheEntry(cacheKey: string, memory: ArrayBuffer, mimeType: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -157,7 +157,7 @@ export async function storeCacheEntry (cacheKey: string, memory: ArrayBuffer, mi } } -export async function cleanupCache (prefix: string, protectKey: string) { +export async function cleanupCache(prefix: string, protectKey: string) { try { const cache = await openCache(); if (!cache) { @@ -175,7 +175,7 @@ export async function cleanupCache (prefix: string, protectKey: string) { } // calculate hash of things which affect config hash -export async function getCacheKey (prefix: string): Promise { +export async function getCacheKey(prefix: string): Promise { if (!runtimeHelpers.subtle) { return null; } diff --git a/src/mono/browser/runtime/invoke-cs.ts b/src/mono/browser/runtime/invoke-cs.ts index 0ce30b62a8d4f5..7f2913cb86ec3d 100644 --- a/src/mono/browser/runtime/invoke-cs.ts +++ b/src/mono/browser/runtime/invoke-cs.ts @@ -4,20 +4,20 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {bind_arg_marshal_to_cs} from "./marshal-to-cs"; -import {bind_arg_marshal_to_js, end_marshal_task_to_js} from "./marshal-to-js"; +import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { bind_arg_marshal_to_cs } from "./marshal-to-cs"; +import { bind_arg_marshal_to_js, end_marshal_task_to_js } from "./marshal-to-js"; import { get_sig, get_signature_argument_count, bound_cs_function_symbol, get_signature_version, alloc_stack_frame, get_signature_type, } from "./marshal"; -import {MonoMethod, JSFunctionSignature, BoundMarshalerToCs, BoundMarshalerToJs, MarshalerType} from "./types/internal"; -import {assert_js_interop} from "./invoke-js"; -import {startMeasure, MeasuredBlock, endMeasure} from "./profiler"; -import {bind_assembly_exports, invoke_async_jsexport, invoke_sync_jsexport} from "./managed-exports"; -import {mono_log_debug} from "./logging"; +import { MonoMethod, JSFunctionSignature, BoundMarshalerToCs, BoundMarshalerToJs, MarshalerType } from "./types/internal"; +import { assert_js_interop } from "./invoke-js"; +import { startMeasure, MeasuredBlock, endMeasure } from "./profiler"; +import { bind_assembly_exports, invoke_async_jsexport, invoke_sync_jsexport } from "./managed-exports"; +import { mono_log_debug } from "./logging"; -export function mono_wasm_bind_cs_function (method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { +export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { const fullyQualifiedName = `[${assemblyName}] ${namespaceName}.${shortClassName}:${methodName}`; const mark = startMeasure(); mono_log_debug(`Binding [JSExport] ${namespaceName}.${shortClassName}:${methodName} from ${assemblyName} assembly`); @@ -108,11 +108,11 @@ export function mono_wasm_bind_cs_function (method: MonoMethod, assemblyName: st endMeasure(mark, MeasuredBlock.bindCsFunction, fullyQualifiedName); } -function bind_fn_0V (closure: BindingClosure) { +function bind_fn_0V(closure: BindingClosure) { const method = closure.method; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V () { + return function bound_fn_0V() { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -129,12 +129,12 @@ function bind_fn_0V (closure: BindingClosure) { }; } -function bind_fn_1V (closure: BindingClosure) { +function bind_fn_1V(closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V (arg1: any) { + return function bound_fn_1V(arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -153,13 +153,13 @@ function bind_fn_1V (closure: BindingClosure) { }; } -function bind_fn_1R (closure: BindingClosure) { +function bind_fn_1R(closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R (arg1: any) { + return function bound_fn_1R(arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -181,13 +181,13 @@ function bind_fn_1R (closure: BindingClosure) { }; } -function bind_fn_1RA (closure: BindingClosure) { +function bind_fn_1RA(closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_1RA (arg1: any) { + return function bind_fn_1RA(arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -214,14 +214,14 @@ function bind_fn_1RA (closure: BindingClosure) { }; } -function bind_fn_2R (closure: BindingClosure) { +function bind_fn_2R(closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R (arg1: any, arg2: any) { + return function bound_fn_2R(arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -244,14 +244,14 @@ function bind_fn_2R (closure: BindingClosure) { }; } -function bind_fn_2RA (closure: BindingClosure) { +function bind_fn_2RA(closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_2RA (arg1: any, arg2: any) { + return function bind_fn_2RA(arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -279,7 +279,7 @@ function bind_fn_2RA (closure: BindingClosure) { }; } -function bind_fn (closure: BindingClosure) { +function bind_fn(closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -288,7 +288,7 @@ function bind_fn (closure: BindingClosure) { const is_async = closure.is_async; const is_discard_no_wait = closure.is_discard_no_wait; if (!WasmEnableThreads) (closure) = null; - return function bound_fn (...js_args: any[]) { + return function bound_fn(...js_args: any[]) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -343,7 +343,7 @@ type BindingClosure = { } export const exportsByAssembly: Map = new Map(); -function _walk_exports_to_set_function (assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { +function _walk_exports_to_set_function(assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { const parts = `${namespace}.${classname}`.replace(/\//g, ".").split("."); let scope: any = undefined; let assemblyScope = exportsByAssembly.get(assembly); @@ -372,7 +372,7 @@ function _walk_exports_to_set_function (assembly: string, namespace: string, cla scope[`${methodname}.${signature_hash}`] = fn; } -export async function mono_wasm_get_assembly_exports (assembly: string): Promise { +export async function mono_wasm_get_assembly_exports(assembly: string): Promise { assert_js_interop(); const result = exportsByAssembly.get(assembly); if (!result) { diff --git a/src/mono/browser/runtime/invoke-js.ts b/src/mono/browser/runtime/invoke-js.ts index 0c67c7e17cad23..154bddbf4fc285 100644 --- a/src/mono/browser/runtime/invoke-js.ts +++ b/src/mono/browser/runtime/invoke-js.ts @@ -4,25 +4,25 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import {marshal_exception_to_cs, bind_arg_marshal_to_cs} from "./marshal-to-cs"; -import {get_signature_argument_count, bound_js_function_symbol, get_sig, get_signature_version, get_signature_type, imported_js_function_symbol, get_signature_handle, get_signature_function_name, get_signature_module_name, is_receiver_should_free, get_caller_native_tid, get_sync_done_semaphore_ptr} from "./marshal"; -import {setI32_unchecked, receiveWorkerHeapViews, forceThreadMemoryViewRefresh} from "./memory"; -import {stringToMonoStringRoot} from "./strings"; -import {MonoObject, MonoObjectRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle, MarshalerType} from "./types/internal"; -import {Int32Ptr} from "./types/emscripten"; -import {INTERNAL, Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {bind_arg_marshal_to_js} from "./marshal-to-js"; -import {mono_wasm_new_external_root} from "./roots"; -import {mono_log_debug, mono_wasm_symbolicate_string} from "./logging"; -import {mono_wasm_get_jsobj_from_js_handle} from "./gc-handles"; -import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; -import {wrap_as_cancelable_promise} from "./cancelable-promise"; -import {threads_c_functions as tcwraps} from "./cwraps"; -import {monoThreadInfo} from "./pthreads"; +import { marshal_exception_to_cs, bind_arg_marshal_to_cs } from "./marshal-to-cs"; +import { get_signature_argument_count, bound_js_function_symbol, get_sig, get_signature_version, get_signature_type, imported_js_function_symbol, get_signature_handle, get_signature_function_name, get_signature_module_name, is_receiver_should_free, get_caller_native_tid, get_sync_done_semaphore_ptr } from "./marshal"; +import { setI32_unchecked, receiveWorkerHeapViews, forceThreadMemoryViewRefresh } from "./memory"; +import { stringToMonoStringRoot } from "./strings"; +import { MonoObject, MonoObjectRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle, MarshalerType } from "./types/internal"; +import { Int32Ptr } from "./types/emscripten"; +import { INTERNAL, Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { bind_arg_marshal_to_js } from "./marshal-to-js"; +import { mono_wasm_new_external_root } from "./roots"; +import { mono_log_debug, mono_wasm_symbolicate_string } from "./logging"; +import { mono_wasm_get_jsobj_from_js_handle } from "./gc-handles"; +import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; +import { wrap_as_cancelable_promise } from "./cancelable-promise"; +import { threads_c_functions as tcwraps } from "./cwraps"; +import { monoThreadInfo } from "./pthreads"; export const js_import_wrapper_by_fn_handle: Function[] = [null];// 0th slot is dummy, main thread we free them on shutdown. On web worker thread we free them when worker is detached. -export function mono_wasm_bind_js_import (signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { +export function mono_wasm_bind_js_import(signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { if (WasmEnableThreads) return; assert_js_interop(); const resultRoot = mono_wasm_new_external_root(result_address); @@ -37,7 +37,7 @@ export function mono_wasm_bind_js_import (signature: JSFunctionSignature, is_exc } } -export function mono_wasm_invoke_jsimport_MT (signature: JSFunctionSignature, args: JSMarshalerArguments) { +export function mono_wasm_invoke_jsimport_MT(signature: JSFunctionSignature, args: JSMarshalerArguments) { if (!WasmEnableThreads) return; assert_js_interop(); @@ -53,7 +53,7 @@ export function mono_wasm_invoke_jsimport_MT (signature: JSFunctionSignature, ar bound_fn(args); } -export function mono_wasm_invoke_jsimport_ST (function_handle: JSFnHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_jsimport_ST(function_handle: JSFnHandle, args: JSMarshalerArguments): void { if (WasmEnableThreads) return; loaderHelpers.assert_runtime_running(); const bound_fn = js_import_wrapper_by_fn_handle[function_handle]; @@ -61,7 +61,7 @@ export function mono_wasm_invoke_jsimport_ST (function_handle: JSFnHandle, args: bound_fn(args); } -function bind_js_import (signature: JSFunctionSignature): Function { +function bind_js_import(signature: JSFunctionSignature): Function { assert_js_interop(); const mark = startMeasure(); @@ -131,11 +131,11 @@ function bind_js_import (signature: JSFunctionSignature): Function { } } - function async_bound_fn (args: JSMarshalerArguments): void { + function async_bound_fn(args: JSMarshalerArguments): void { forceThreadMemoryViewRefresh(); bound_fn(args); } - function sync_bound_fn (args: JSMarshalerArguments): void { + function sync_bound_fn(args: JSMarshalerArguments): void { const previous = runtimeHelpers.isPendingSynchronousCall; try { forceThreadMemoryViewRefresh(); @@ -146,10 +146,10 @@ function bind_js_import (signature: JSFunctionSignature): Function { runtimeHelpers.isPendingSynchronousCall = previous; } } - function async_bound_fn_ui (args: JSMarshalerArguments): void { + function async_bound_fn_ui(args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_async(() => async_bound_fn(args)); } - function sync_bound_fn_ui (args: JSMarshalerArguments): void { + function sync_bound_fn_ui(args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_sync(() => sync_bound_fn(args), args); } @@ -193,11 +193,11 @@ function bind_js_import (signature: JSFunctionSignature): Function { return wrapped_fn; } -function bind_fn_0V (closure: BindingClosure) { +function bind_fn_0V(closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V (args: JSMarshalerArguments) { + return function bound_fn_0V(args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -211,12 +211,12 @@ function bind_fn_0V (closure: BindingClosure) { }; } -function bind_fn_1V (closure: BindingClosure) { +function bind_fn_1V(closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V (args: JSMarshalerArguments) { + return function bound_fn_1V(args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -231,13 +231,13 @@ function bind_fn_1V (closure: BindingClosure) { }; } -function bind_fn_1R (closure: BindingClosure) { +function bind_fn_1R(closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R (args: JSMarshalerArguments) { + return function bound_fn_1R(args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -253,14 +253,14 @@ function bind_fn_1R (closure: BindingClosure) { }; } -function bind_fn_2R (closure: BindingClosure) { +function bind_fn_2R(closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R (args: JSMarshalerArguments) { + return function bound_fn_2R(args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -277,7 +277,7 @@ function bind_fn_2R (closure: BindingClosure) { }; } -function bind_fn (closure: BindingClosure) { +function bind_fn(closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -286,7 +286,7 @@ function bind_fn (closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn (args: JSMarshalerArguments) { + return function bound_fn(args: JSMarshalerArguments) { const receiver_should_free = WasmEnableThreads && is_receiver_should_free(args); const mark = startMeasure(); try { @@ -339,23 +339,23 @@ type BindingClosure = { arg_cleanup: (Function | undefined)[] } -export function mono_wasm_invoke_js_function (bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_js_function(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_sync(() => mono_wasm_invoke_js_function_impl(bound_function_js_handle, args), args); } -export function mono_wasm_invoke_js_function_impl (bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_js_function_impl(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { loaderHelpers.assert_runtime_running(); const bound_fn = mono_wasm_get_jsobj_from_js_handle(bound_function_js_handle); mono_assert(bound_fn && typeof (bound_fn) === "function" && bound_fn[bound_js_function_symbol], () => `Bound function handle expected ${bound_function_js_handle}`); bound_fn(args); } -export function mono_wasm_set_module_imports (module_name: string, moduleImports: any) { +export function mono_wasm_set_module_imports(module_name: string, moduleImports: any) { importedModules.set(module_name, moduleImports); mono_log_debug(`added module imports '${module_name}'`); } -function mono_wasm_lookup_js_import (function_name: string, js_module_name: string | null): Function { +function mono_wasm_lookup_js_import(function_name: string, js_module_name: string | null): Function { mono_assert(function_name && typeof function_name === "string", "function_name must be string"); let scope: any = {}; @@ -391,34 +391,34 @@ function mono_wasm_lookup_js_import (function_name: string, js_module_name: stri return fn.bind(scope); } -export function set_property (self: any, name: string, value: any): void { +export function set_property(self: any, name: string, value: any): void { mono_check(self, "Null reference"); self[name] = value; } -export function get_property (self: any, name: string): any { +export function get_property(self: any, name: string): any { mono_check(self, "Null reference"); return self[name]; } -export function has_property (self: any, name: string): boolean { +export function has_property(self: any, name: string): boolean { mono_check(self, "Null reference"); return name in self; } -export function get_typeof_property (self: any, name: string): string { +export function get_typeof_property(self: any, name: string): string { mono_check(self, "Null reference"); return typeof self[name]; } -export function get_global_this (): any { +export function get_global_this(): any { return globalThis; } export const importedModulesPromises: Map> = new Map(); export const importedModules: Map> = new Map(); -export function dynamic_import (module_name: string, module_url: string): Promise { +export function dynamic_import(module_name: string, module_url: string): Promise { assert_js_interop(); mono_assert(module_name && typeof module_name === "string", "module_name must be string"); mono_assert(module_url && typeof module_url === "string", "module_url must be string"); @@ -430,7 +430,7 @@ export function dynamic_import (module_name: string, module_url: string): Promis importedModulesPromises.set(module_name, promise); } - return wrap_as_cancelable_promise(async () => { + return wrap_as_cancelable_promise(async() => { const module = await promise; if (newPromise) { importedModules.set(module_name, module); @@ -440,7 +440,7 @@ export function dynamic_import (module_name: string, module_url: string): Promis }); } -function _wrap_error_flag (is_exception: Int32Ptr | null, ex: any): string { +function _wrap_error_flag(is_exception: Int32Ptr | null, ex: any): string { let res = "unknown exception"; if (ex) { res = ex.toString(); @@ -463,7 +463,7 @@ function _wrap_error_flag (is_exception: Int32Ptr | null, ex: any): string { return res; } -export function wrap_error_root (is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { +export function wrap_error_root(is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { const res = _wrap_error_flag(is_exception, ex); stringToMonoStringRoot(res, result); } @@ -471,7 +471,7 @@ export function wrap_error_root (is_exception: Int32Ptr | null, ex: any, result: // to set out parameters of icalls // TODO replace it with replace it with UTF8 char*, no GC root needed // https://github.com/dotnet/runtime/issues/98365 -export function wrap_no_error_root (is_exception: Int32Ptr | null, result?: WasmRoot): void { +export function wrap_no_error_root(is_exception: Int32Ptr | null, result?: WasmRoot): void { if (is_exception) { receiveWorkerHeapViews(); setI32_unchecked(is_exception, 0); @@ -481,7 +481,7 @@ export function wrap_no_error_root (is_exception: Int32Ptr | null, result?: Wasm } } -export function assert_js_interop (): void { +export function assert_js_interop(): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready && runtimeHelpers.proxyGCHandle, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -490,7 +490,7 @@ export function assert_js_interop (): void { } } -export function assert_c_interop (): void { +export function assert_c_interop(): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -502,7 +502,7 @@ export function assert_c_interop (): void { // make sure we are not blocking em_task_queue_execute up the call stack // so that when we call back to managed, the FS calls could still be processed by the UI thread // see also emscripten_yield which can process the FS calls inside the spin wait -export function invoke_later_when_on_ui_thread_sync (fn: Function, args: JSMarshalerArguments) { +export function invoke_later_when_on_ui_thread_sync(fn: Function, args: JSMarshalerArguments) { if (WasmEnableThreads && monoThreadInfo.isUI) { Module.safeSetTimeout(() => { fn(); @@ -517,7 +517,7 @@ export function invoke_later_when_on_ui_thread_sync (fn: Function, args: JSMarsh // make sure we are not blocking em_task_queue_execute up the call stack // so that when we call back to managed, the FS calls could still be processed by the UI thread -export function invoke_later_when_on_ui_thread_async (fn: Function) { +export function invoke_later_when_on_ui_thread_async(fn: Function) { if (WasmEnableThreads && monoThreadInfo.isUI) { Module.safeSetTimeout(fn, 0); } else { diff --git a/src/mono/browser/runtime/jiterpreter-interp-entry.ts b/src/mono/browser/runtime/jiterpreter-interp-entry.ts index 7e072eb27f2675..cedf54cdde9306 100644 --- a/src/mono/browser/runtime/jiterpreter-interp-entry.ts +++ b/src/mono/browser/runtime/jiterpreter-interp-entry.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {MonoMethod, MonoType} from "./types/internal"; -import {NativePointer} from "./types/emscripten"; -import {Module, mono_assert} from "./globals"; +import { MonoMethod, MonoType } from "./types/internal"; +import { NativePointer } from "./types/emscripten"; +import { Module, mono_assert } from "./globals"; import { setI32, getU32_unaligned, _zero_region } from "./memory"; -import {WasmOpcode} from "./jiterpreter-opcodes"; +import { WasmOpcode } from "./jiterpreter-opcodes"; import cwraps from "./cwraps"; import { WasmBuilder, addWasmFunctionPointer, @@ -16,9 +16,9 @@ import { JiterpreterOptions, getMemberOffset, getCounter, modifyCounter } from "./jiterpreter-support"; -import {WasmValtype} from "./jiterpreter-opcodes"; -import {mono_log_error, mono_log_info} from "./logging"; -import {utf8ToString} from "./strings"; +import { WasmValtype } from "./jiterpreter-opcodes"; +import { mono_log_error, mono_log_info } from "./logging"; +import { utf8ToString } from "./strings"; import { JiterpreterTable, JiterpCounter, JiterpMember, JitQueue } from "./jiterpreter-enums"; @@ -68,7 +68,7 @@ const enum WasmReftype { } */ -function getTrampImports () { +function getTrampImports() { if (trampImports) return trampImports; @@ -98,7 +98,7 @@ class TrampolineInfo { result: number; hitCount: number; - constructor ( + constructor( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: string, defaultImplementation: number @@ -137,12 +137,12 @@ let mostRecentOptions: JiterpreterOptions | undefined = undefined; // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_interp_entry (imethod: number) { +export function mono_jiterp_free_method_data_interp_entry(imethod: number) { delete infoTable[imethod]; } // FIXME: move this counter into C and make it thread safe -export function mono_interp_record_interp_entry (imethod: number) { +export function mono_interp_record_interp_entry(imethod: number) { // clear the unbox bit imethod = imethod & ~0x1; @@ -168,7 +168,7 @@ export function mono_interp_record_interp_entry (imethod: number) { } // returns function pointer -export function mono_interp_jit_wasm_entry_trampoline ( +export function mono_interp_jit_wasm_entry_trampoline( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: NativePointer, defaultImplementation: number @@ -208,7 +208,7 @@ export function mono_interp_jit_wasm_entry_trampoline ( return info.result; } -function ensure_jit_is_scheduled () { +function ensure_jit_is_scheduled() { if (jitQueueTimeout > 0) return; @@ -227,7 +227,7 @@ function ensure_jit_is_scheduled () { }, queueFlushDelayMs); } -function flush_wasm_entry_trampoline_jit_queue () { +function flush_wasm_entry_trampoline_jit_queue() { const jitQueue : TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.InterpEntry)) != 0) { @@ -447,7 +447,7 @@ function flush_wasm_entry_trampoline_jit_queue () { } } -function append_stackval_from_data ( +function append_stackval_from_data( builder: WasmBuilder, imethod: number, type: MonoType, valueName: string, argIndex: number ) { const rawSize = cwraps.mono_jiterp_type_get_raw_value_size(type); @@ -520,7 +520,7 @@ function append_stackval_from_data ( } } -function generate_wasm_body ( +function generate_wasm_body( builder: WasmBuilder, info: TrampolineInfo ): boolean { // FIXME: This is not thread-safe, but the alternative of alloca makes the trampoline diff --git a/src/mono/browser/runtime/jiterpreter-jit-call.ts b/src/mono/browser/runtime/jiterpreter-jit-call.ts index fdf1852833d77b..09018413e24e75 100644 --- a/src/mono/browser/runtime/jiterpreter-jit-call.ts +++ b/src/mono/browser/runtime/jiterpreter-jit-call.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {MonoType, MonoMethod} from "./types/internal"; -import {NativePointer, VoidPtr} from "./types/emscripten"; -import {Module, mono_assert, runtimeHelpers} from "./globals"; +import { MonoType, MonoMethod } from "./types/internal"; +import { NativePointer, VoidPtr } from "./types/emscripten"; +import { Module, mono_assert, runtimeHelpers } from "./globals"; import { getU8, getI32_unaligned, getU32_unaligned, setU32_unchecked, receiveWorkerHeapViews } from "./memory"; -import {WasmOpcode, WasmValtype} from "./jiterpreter-opcodes"; +import { WasmOpcode, WasmValtype } from "./jiterpreter-opcodes"; import { WasmBuilder, addWasmFunctionPointer, _now, getWasmFunctionTable, applyOptions, @@ -15,10 +15,10 @@ import { getCounter, modifyCounter, getRawCwrap } from "./jiterpreter-support"; -import {JiterpreterTable, JiterpCounter, JitQueue} from "./jiterpreter-enums"; +import { JiterpreterTable, JiterpCounter, JitQueue } from "./jiterpreter-enums"; import cwraps from "./cwraps"; -import {mono_log_error, mono_log_info} from "./logging"; -import {utf8ToString} from "./strings"; +import { mono_log_error, mono_log_info } from "./logging"; +import { utf8ToString } from "./strings"; // Controls miscellaneous diagnostic output. const trace = 0; @@ -95,7 +95,7 @@ class TrampolineInfo { wasmNativeSignature: WasmValtype[]; enableDirect: boolean; - constructor ( + constructor( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: boolean ) { @@ -166,7 +166,7 @@ class TrampolineInfo { // this is cached replacements for Module.getWasmTableEntry(); // we could add and // if we need to export the original -function getWasmTableEntry (index: number) { +function getWasmTableEntry(index: number) { let result = fnCache[index]; if (!result) { if (index >= fnCache.length) @@ -179,7 +179,7 @@ function getWasmTableEntry (index: number) { return result; } -export function mono_interp_invoke_wasm_jit_call_trampoline ( +export function mono_interp_invoke_wasm_jit_call_trampoline( thunkIndex: number, ret_sp: number, sp: number, ftndesc: number, thrown: NativePointer ) { const thunk = getWasmTableEntry(thunkIndex); @@ -218,7 +218,7 @@ export function mono_interp_invoke_wasm_jit_call_trampoline ( // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_jit_call (method: MonoMethod) { +export function mono_jiterp_free_method_data_jit_call(method: MonoMethod) { // FIXME const infoArray = infosByMethod[method]; if (!infoArray) @@ -230,7 +230,7 @@ export function mono_jiterp_free_method_data_jit_call (method: MonoMethod) { delete infosByMethod[method]; } -export function mono_interp_jit_wasm_jit_call_trampoline ( +export function mono_interp_jit_wasm_jit_call_trampoline( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: number ): void { @@ -276,7 +276,7 @@ export function mono_interp_jit_wasm_jit_call_trampoline ( mono_interp_flush_jitcall_queue(); } -function getIsWasmEhSupported (): boolean { +function getIsWasmEhSupported(): boolean { if (wasmEhSupported !== undefined) return wasmEhSupported; @@ -288,7 +288,7 @@ function getIsWasmEhSupported (): boolean { return wasmEhSupported; } -export function mono_interp_flush_jitcall_queue (): void { +export function mono_interp_flush_jitcall_queue(): void { const jitQueue: TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.JitCall)) != 0) { @@ -338,7 +338,7 @@ export function mono_interp_flush_jitcall_queue (): void { if (builder.options.enableWasmEh) { if (!getIsWasmEhSupported()) { // The user requested to enable wasm EH but it's not supported, so turn the option back off - applyOptions({enableWasmEh: false}); + applyOptions({ enableWasmEh: false }); builder.options.enableWasmEh = false; } } @@ -432,7 +432,7 @@ export function mono_interp_flush_jitcall_queue (): void { builder.appendULeb(jitQueue.length); for (let i = 0; i < jitQueue.length; i++) { const info = jitQueue[i]; - builder.beginFunction("trampoline", {"old_sp": WasmValtype.i32}); + builder.beginFunction("trampoline", { "old_sp": WasmValtype.i32 }); const ok = generate_wasm_body(builder, info); // FIXME @@ -624,19 +624,19 @@ const wasmOpcodeFromCilOpcode = { [CilOpcodes.STIND_I]: WasmOpcode.i32_store, }; -function append_ldloc (builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { +function append_ldloc(builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { builder.local("sp"); builder.appendU8(opcode); builder.appendMemarg(offsetBytes, 0); } -function append_ldloca (builder: WasmBuilder, offsetBytes: number) { +function append_ldloca(builder: WasmBuilder, offsetBytes: number) { builder.local("sp"); builder.i32_const(offsetBytes); builder.appendU8(WasmOpcode.i32_add); } -function generate_wasm_body ( +function generate_wasm_body( builder: WasmBuilder, info: TrampolineInfo ): boolean { let stack_index = 0; diff --git a/src/mono/browser/runtime/jiterpreter-support.ts b/src/mono/browser/runtime/jiterpreter-support.ts index 012949b1b3d8a6..7c7c35ebfac510 100644 --- a/src/mono/browser/runtime/jiterpreter-support.ts +++ b/src/mono/browser/runtime/jiterpreter-support.ts @@ -2,14 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import {NativePointer, ManagedPointer, VoidPtr} from "./types/emscripten"; -import {Module, mono_assert, runtimeHelpers} from "./globals"; -import {WasmOpcode, WasmSimdOpcode, WasmValtype} from "./jiterpreter-opcodes"; -import {MintOpcode} from "./mintops"; +import { NativePointer, ManagedPointer, VoidPtr } from "./types/emscripten"; +import { Module, mono_assert, runtimeHelpers } from "./globals"; +import { WasmOpcode, WasmSimdOpcode, WasmValtype } from "./jiterpreter-opcodes"; +import { MintOpcode } from "./mintops"; import cwraps from "./cwraps"; -import {mono_log_error, mono_log_info} from "./logging"; -import {localHeapViewU8, localHeapViewU32} from "./memory"; -import {utf8ToString} from "./strings"; +import { mono_log_error, mono_log_info } from "./logging"; +import { localHeapViewU8, localHeapViewU32 } from "./memory"; +import { utf8ToString } from "./strings"; import { JiterpNumberMode, BailoutReason, JiterpreterTable, JiterpCounter, JiterpMember, OpcodeInfoType @@ -109,14 +109,14 @@ export class WasmBuilder { compressImportNames = false; lockImports = false; - constructor (constantSlotCount: number) { + constructor(constantSlotCount: number) { this.stack = [new BlobBuilder()]; this.clear(constantSlotCount); this.cfg = new Cfg(this); - this.defineType("__cpp_exception", {"ptr": WasmValtype.i32}, WasmValtype.void, true); + this.defineType("__cpp_exception", { "ptr": WasmValtype.i32 }, WasmValtype.void, true); } - clear (constantSlotCount: number) { + clear(constantSlotCount: number) { this.options = getOptions(); this.stackSize = 1; this.inSection = false; @@ -156,14 +156,14 @@ export class WasmBuilder { this.allowNullCheckOptimization = this.options.eliminateNullChecks; } - _push () { + _push() { this.stackSize++; if (this.stackSize >= this.stack.length) this.stack.push(new BlobBuilder()); this.current.clear(); } - _pop (writeToOutput: boolean) { + _pop(writeToOutput: boolean) { if (this.stackSize <= 1) throw new Error("Stack empty"); @@ -178,31 +178,31 @@ export class WasmBuilder { return current.getArrayView(false).slice(0, current.size); } - setImportFunction (name: string, value: Function) { + setImportFunction(name: string, value: Function) { const imp = this.importedFunctions[name]; if (!imp) throw new Error("No import named " + name); imp.func = value; } - getExceptionTag (): any { + getExceptionTag(): any { const exceptionTag = (Module)["asm"]["__cpp_exception"]; if (typeof (exceptionTag) !== "undefined") mono_assert(exceptionTag instanceof (WebAssembly).Tag, () => `expected __cpp_exception export from dotnet.wasm to be WebAssembly.Tag but was ${exceptionTag}`); return exceptionTag; } - getWasmImports (): WebAssembly.Imports { + getWasmImports(): WebAssembly.Imports { const memory = runtimeHelpers.getMemory(); mono_assert(memory instanceof WebAssembly.Memory, () => `expected heap import to be WebAssembly.Memory but was ${memory}`); const exceptionTag = this.getExceptionTag(); const result: any = { c: this.getConstants(), - m: {h: memory}, + m: { h: memory }, }; if (exceptionTag) - result.x = {e: exceptionTag}; + result.x = { e: exceptionTag }; const importsToEmit = this.getImportsToEmit(); @@ -225,7 +225,7 @@ export class WasmBuilder { // HACK: Approximate amount of space we need to generate the full module at present // FIXME: This does not take into account any other functions already generated if they weren't // emitted into the module immediately - get bytesGeneratedSoFar () { + get bytesGeneratedSoFar() { const importSize = this.compressImportNames // mod (2 bytes) name (2-3 bytes) type (1 byte) typeidx (1-2 bytes) ? 8 @@ -242,74 +242,74 @@ export class WasmBuilder { this.estimatedExportBytes; } - get current () { + get current() { return this.stack[this.stackSize - 1]; } - get size () { + get size() { return this.current.size; } - appendU8 (value: number | WasmOpcode) { + appendU8(value: number | WasmOpcode) { if ((value != value >>> 0) || (value > 255)) throw new Error(`Byte out of range: ${value}`); return this.current.appendU8(value); } - appendSimd (value: WasmSimdOpcode, allowLoad?: boolean) { + appendSimd(value: WasmSimdOpcode, allowLoad?: boolean) { this.current.appendU8(WasmOpcode.PREFIX_simd); // Yes that's right. We're using LEB128 to encode 8-bit opcodes. Why? I don't know mono_assert(((value | 0) !== 0) || ((value === WasmSimdOpcode.v128_load) && (allowLoad === true)), "Expected non-v128_load simd opcode or allowLoad==true"); return this.current.appendULeb(value); } - appendU32 (value: number) { + appendU32(value: number) { return this.current.appendU32(value); } - appendF32 (value: number) { + appendF32(value: number) { return this.current.appendF32(value); } - appendF64 (value: number) { + appendF64(value: number) { return this.current.appendF64(value); } - appendBoundaryValue (bits: number, sign: number) { + appendBoundaryValue(bits: number, sign: number) { return this.current.appendBoundaryValue(bits, sign); } - appendULeb (value: number | MintOpcodePtr) { + appendULeb(value: number | MintOpcodePtr) { return this.current.appendULeb(value); } - appendLeb (value: number) { + appendLeb(value: number) { return this.current.appendLeb(value); } - appendLebRef (sourceAddress: VoidPtr, signed: boolean) { + appendLebRef(sourceAddress: VoidPtr, signed: boolean) { return this.current.appendLebRef(sourceAddress, signed); } - appendBytes (bytes: Uint8Array) { + appendBytes(bytes: Uint8Array) { return this.current.appendBytes(bytes); } - appendName (text: string) { + appendName(text: string) { return this.current.appendName(text); } - ret (ip: MintOpcodePtr) { + ret(ip: MintOpcodePtr) { this.ip_const(ip); this.appendU8(WasmOpcode.return_); } - i32_const (value: number | ManagedPointer | NativePointer) { + i32_const(value: number | ManagedPointer | NativePointer) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value); } - ptr_const (pointer: number | ManagedPointer | NativePointer) { + ptr_const(pointer: number | ManagedPointer | NativePointer) { let idx = this.options.useConstants ? this.constantSlots.indexOf(pointer) : -1; if ( this.options.useConstants && @@ -328,17 +328,17 @@ export class WasmBuilder { } } - ip_const (value: MintOpcodePtr) { + ip_const(value: MintOpcodePtr) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value - this.base); } - i52_const (value: number) { + i52_const(value: number) { this.appendU8(WasmOpcode.i64_const); this.appendLeb(value); } - v128_const (value: 0 | Uint8Array) { + v128_const(value: 0 | Uint8Array) { if (value === 0) { // This encoding is much smaller than a v128_const // But v8 doesn't optimize it :-(((((( @@ -367,7 +367,7 @@ export class WasmBuilder { } } - defineType ( + defineType( name: string, parameters: { [name: string]: WasmValtype }, returnType: WasmValtype, permanent: boolean ) { @@ -416,7 +416,7 @@ export class WasmBuilder { return index; } - generateTypeSection () { + generateTypeSection() { this.beginSection(1); this.appendULeb(this.functionTypeCount); /* @@ -442,7 +442,7 @@ export class WasmBuilder { this.endSection(); } - getImportedFunctionTable (): any { + getImportedFunctionTable(): any { const imports: any = {}; for (const k in this.importedFunctions) { const f = this.importedFunctions[k]; @@ -452,7 +452,7 @@ export class WasmBuilder { return imports; } - getCompressedName (ifi: ImportedFunctionInfo) { + getCompressedName(ifi: ImportedFunctionInfo) { if (!this.compressImportNames || typeof (ifi.index) !== "number") return ifi.name; @@ -462,7 +462,7 @@ export class WasmBuilder { return result; } - getImportsToEmit () { + getImportsToEmit() { const result = []; for (const k in this.importedFunctions) { const v = this.importedFunctions[k]; @@ -475,7 +475,7 @@ export class WasmBuilder { return result; } - _generateImportSection (includeFunctionTable?: boolean) { + _generateImportSection(includeFunctionTable?: boolean) { const importsToEmit = this.getImportsToEmit(); this.lockImports = true; @@ -554,7 +554,7 @@ export class WasmBuilder { } } - defineImportedFunction ( + defineImportedFunction( module: string, name: string, functionTypeName: string, permanent: boolean, func?: Function | number ): ImportedFunctionInfo { @@ -583,7 +583,7 @@ export class WasmBuilder { return result; } - markImportAsUsed (name: string) { + markImportAsUsed(name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -591,14 +591,14 @@ export class WasmBuilder { func.index = this.importedFunctionCount++; } - getTypeIndex (name: string) { + getTypeIndex(name: string) { const type = this.functionTypes[name]; if (!type) throw new Error("No type named " + name); return type[0]; } - defineFunction ( + defineFunction( options: { type: string, name: string, @@ -623,7 +623,7 @@ export class WasmBuilder { return rec; } - emitImportsAndFunctions (includeFunctionTable?: boolean) { + emitImportsAndFunctions(includeFunctionTable?: boolean) { let exportCount = 0; for (let i = 0; i < this.functions.length; i++) { const func = this.functions[i]; @@ -682,7 +682,7 @@ export class WasmBuilder { this.endSection(); } - call_indirect (/* functionTypeName: string, tableIndex: number */) { + call_indirect(/* functionTypeName: string, tableIndex: number */) { throw new Error("call_indirect unavailable"); /* const type = this.functionTypes[functionTypeName]; @@ -695,7 +695,7 @@ export class WasmBuilder { */ } - callImport (name: string) { + callImport(name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -708,7 +708,7 @@ export class WasmBuilder { this.appendULeb(func.index); } - beginSection (type: number) { + beginSection(type: number) { if (this.inSection) this._pop(true); this.appendU8(type); @@ -716,7 +716,7 @@ export class WasmBuilder { this.inSection = true; } - endSection () { + endSection() { if (!this.inSection) throw new Error("Not in section"); if (this.inFunction) @@ -735,7 +735,7 @@ export class WasmBuilder { return result; }; - _assignLocalIndices ( + _assignLocalIndices( counts: any, locals: { [name: string]: WasmValtype }, base: number, localGroupCount: number ) { @@ -794,7 +794,7 @@ export class WasmBuilder { return localGroupCount; } - beginFunction ( + beginFunction( type: string, locals?: { [name: string]: WasmValtype } ) { @@ -838,7 +838,7 @@ export class WasmBuilder { this.inFunction = true; } - endFunction (writeToOutput: boolean) { + endFunction(writeToOutput: boolean) { if (!this.inFunction) throw new Error("Not in function"); if (this.activeBlocks > 0) @@ -848,7 +848,7 @@ export class WasmBuilder { return result; } - block (type?: WasmValtype, opcode?: WasmOpcode) { + block(type?: WasmValtype, opcode?: WasmOpcode) { const result = this.appendU8(opcode || WasmOpcode.block); if (type) this.appendU8(type); @@ -858,14 +858,14 @@ export class WasmBuilder { return result; } - endBlock () { + endBlock() { if (this.activeBlocks <= 0) throw new Error("No blocks active"); this.activeBlocks--; this.appendU8(WasmOpcode.end); } - arg (name: string | number, opcode?: WasmOpcode) { + arg(name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name; @@ -876,7 +876,7 @@ export class WasmBuilder { this.appendULeb(index); } - local (name: string | number, opcode?: WasmOpcode) { + local(name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name + this.argumentCount; @@ -889,7 +889,7 @@ export class WasmBuilder { this.appendULeb(index); } - appendMemarg (offset: number, alignPower: number) { + appendMemarg(offset: number, alignPower: number) { this.appendULeb(alignPower); this.appendULeb(offset); } @@ -897,7 +897,7 @@ export class WasmBuilder { /* generates either (u32)get_local(ptr) + offset or (u32)ptr1 + offset */ - lea (ptr1: string | number, offset: number) { + lea(ptr1: string | number, offset: number) { if (typeof (ptr1) === "string") this.local(ptr1); else @@ -908,13 +908,13 @@ export class WasmBuilder { this.appendU8(WasmOpcode.i32_add); } - getArrayView (fullCapacity?: boolean) { + getArrayView(fullCapacity?: boolean) { if (this.stackSize > 1) throw new Error("Jiterpreter block stack not empty"); return this.stack[0].getArrayView(fullCapacity); } - getConstants () { + getConstants() { const result: { [key: string]: number } = {}; for (let i = 0; i < this.constantSlots.length; i++) result[i.toString(shortNameBase)] = this.constantSlots[i]; @@ -929,7 +929,7 @@ export class BlobBuilder { encoder?: TextEncoder; textBuf = new Uint8Array(1024); - constructor () { + constructor() { this.capacity = 16 * 1024; this.buffer = Module._malloc(this.capacity); localHeapViewU8().fill(0, this.buffer, this.buffer + this.capacity); @@ -939,11 +939,11 @@ export class BlobBuilder { this.encoder = new TextEncoder(); } - clear () { + clear() { this.size = 0; } - appendU8 (value: number | WasmOpcode) { + appendU8(value: number | WasmOpcode) { if (this.size >= this.capacity) throw new Error("Buffer full"); @@ -952,35 +952,35 @@ export class BlobBuilder { return result; } - appendU32 (value: number) { + appendU32(value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.U32); this.size += 4; return result; } - appendI32 (value: number) { + appendI32(value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.I32); this.size += 4; return result; } - appendF32 (value: number) { + appendF32(value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F32); this.size += 4; return result; } - appendF64 (value: number) { + appendF64(value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F64); this.size += 8; return result; } - appendBoundaryValue (bits: number, sign: number) { + appendBoundaryValue(bits: number, sign: number) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -991,7 +991,7 @@ export class BlobBuilder { return bytesWritten; } - appendULeb (value: number) { + appendULeb(value: number) { mono_assert(typeof (value) === "number", () => `appendULeb expected number but got ${value}`); mono_assert(value >= 0, "cannot pass negative value to appendULeb"); if (value < 0x7F) { @@ -1012,7 +1012,7 @@ export class BlobBuilder { return bytesWritten; } - appendLeb (value: number) { + appendLeb(value: number) { mono_assert(typeof (value) === "number", () => `appendLeb expected number but got ${value}`); if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1024,7 +1024,7 @@ export class BlobBuilder { return bytesWritten; } - appendLebRef (sourceAddress: VoidPtr, signed: boolean) { + appendLebRef(sourceAddress: VoidPtr, signed: boolean) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1035,7 +1035,7 @@ export class BlobBuilder { return bytesWritten; } - copyTo (destination: BlobBuilder, count?: number) { + copyTo(destination: BlobBuilder, count?: number) { if (typeof (count) !== "number") count = this.size; @@ -1043,7 +1043,7 @@ export class BlobBuilder { destination.size += count; } - appendBytes (bytes: Uint8Array, count?: number) { + appendBytes(bytes: Uint8Array, count?: number) { const result = this.size; const heapU8 = localHeapViewU8(); if (bytes.buffer === heapU8.buffer) { @@ -1063,7 +1063,7 @@ export class BlobBuilder { return result; } - appendName (text: string) { + appendName(text: string) { let count = text.length; // TextEncoder overhead is significant for short strings, and lots of our strings // are single-character import names, so add a fast path for single characters @@ -1098,7 +1098,7 @@ export class BlobBuilder { this.appendBytes(this.textBuf, count); } - getArrayView (fullCapacity?: boolean) { + getArrayView(fullCapacity?: boolean) { return new Uint8Array(localHeapViewU8().buffer, this.buffer, fullCapacity ? this.capacity : this.size); } } @@ -1155,11 +1155,11 @@ class Cfg { observedBackBranchTargets = new Set(); trace = 0; - constructor (builder: WasmBuilder) { + constructor(builder: WasmBuilder) { this.builder = builder; } - initialize (startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { + initialize(startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { this.segments.length = 0; this.blockStack.length = 0; this.startOfBody = startOfBody; @@ -1175,7 +1175,7 @@ class Cfg { } // We have a header containing the table of locals and we need to preserve it - entry (ip: MintOpcodePtr) { + entry(ip: MintOpcodePtr) { this.entryIp = ip; // Skip over the enter opcode const enterSizeU16 = cwraps.mono_jiterp_get_opcode_info(MintOpcode.MINT_TIER_ENTER_JITERPRETER, OpcodeInfoType.Length); @@ -1193,7 +1193,7 @@ class Cfg { return this.firstOpcodeIp; } - appendBlob () { + appendBlob() { if (this.builder.current.size === this.lastSegmentEnd) return; @@ -1209,7 +1209,7 @@ class Cfg { this.overheadBytes += 2; } - startBranchBlock (ip: MintOpcodePtr, isBackBranchTarget: boolean) { + startBranchBlock(ip: MintOpcodePtr, isBackBranchTarget: boolean) { this.appendBlob(); this.segments.push({ type: "branch-block-header", @@ -1219,7 +1219,7 @@ class Cfg { this.overheadBytes += 1; // each branch block just costs us an end } - branch (target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { + branch(target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { if (isBackward) this.observedBackBranchTargets.add(target); @@ -1252,13 +1252,13 @@ class Cfg { } } - emitBlob (segment: CfgBlob, source: Uint8Array) { + emitBlob(segment: CfgBlob, source: Uint8Array) { // mono_log_info(`segment @${(segment.ip).toString(16)} ${segment.start}-${segment.start + segment.length}`); const view = source.subarray(segment.start, segment.start + segment.length); this.builder.appendBytes(view); } - generate (): Uint8Array { + generate(): Uint8Array { // HACK: Make sure any remaining bytes are inserted into a trailing segment this.appendBlob(); @@ -1517,7 +1517,7 @@ export const _now = (globalThis.performance && globalThis.performance.now) let scratchBuffer: NativePointer = 0; -export function append_safepoint (builder: WasmBuilder, ip: MintOpcodePtr) { +export function append_safepoint(builder: WasmBuilder, ip: MintOpcodePtr) { // safepoints are never triggered in a single-threaded build if (!WasmEnableThreads) return; @@ -1534,7 +1534,7 @@ export function append_safepoint (builder: WasmBuilder, ip: MintOpcodePtr) { builder.endBlock(); } -export function append_bailout (builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { +export function append_bailout(builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { builder.ip_const(ip); if (builder.options.countBailouts) { builder.i32_const(builder.traceIndex); @@ -1545,7 +1545,7 @@ export function append_bailout (builder: WasmBuilder, ip: MintOpcodePtr, reason: } // generate a bailout that is recorded for the monitoring phase as a possible early exit. -export function append_exit (builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { +export function append_exit(builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { /* * disp will always be nonzero once we've taken at least one backward branch. * if (cinfo) { @@ -1581,7 +1581,7 @@ export function append_exit (builder: WasmBuilder, ip: MintOpcodePtr, opcodeCoun builder.appendU8(WasmOpcode.return_); } -export function copyIntoScratchBuffer (src: NativePointer, size: number): NativePointer { +export function copyIntoScratchBuffer(src: NativePointer, size: number): NativePointer { if (!scratchBuffer) scratchBuffer = Module._malloc(64); if (size > 64) @@ -1591,7 +1591,7 @@ export function copyIntoScratchBuffer (src: NativePointer, size: number): Native return scratchBuffer; } -export function getWasmFunctionTable () { +export function getWasmFunctionTable() { if (!wasmTable) wasmTable = runtimeHelpers.getWasmIndirectFunctionTable(); if (!wasmTable) @@ -1599,7 +1599,7 @@ export function getWasmFunctionTable () { return wasmTable; } -export function addWasmFunctionPointer (table: JiterpreterTable, f: Function) { +export function addWasmFunctionPointer(table: JiterpreterTable, f: Function) { mono_assert(f, "Attempting to set null function into table"); const index = cwraps.mono_jiterp_allocate_table_entry(table); @@ -1613,7 +1613,7 @@ export function addWasmFunctionPointer (table: JiterpreterTable, f: Function) { return index; } -export function try_append_memset_fast (builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { +export function try_append_memset_fast(builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { if (count <= 0) { if (destOnStack) builder.appendU8(WasmOpcode.drop); @@ -1684,7 +1684,7 @@ export function try_append_memset_fast (builder: WasmBuilder, localOffset: numbe return true; } -export function append_memset_dest (builder: WasmBuilder, value: number, count: number) { +export function append_memset_dest(builder: WasmBuilder, value: number, count: number) { // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val if (try_append_memset_fast(builder, 0, value, count, true)) return; @@ -1696,7 +1696,7 @@ export function append_memset_dest (builder: WasmBuilder, value: number, count: builder.appendU8(0); } -export function try_append_memmove_fast ( +export function try_append_memmove_fast( builder: WasmBuilder, destLocalOffset: number, srcLocalOffset: number, count: number, addressesOnStack: boolean, destLocal?: string, srcLocal?: string ) { @@ -1796,7 +1796,7 @@ export function try_append_memmove_fast ( } // expects dest then source to have been pushed onto wasm stack -export function append_memmove_dest_src (builder: WasmBuilder, count: number) { +export function append_memmove_dest_src(builder: WasmBuilder, count: number) { if (try_append_memmove_fast(builder, 0, 0, count, true)) return true; @@ -1810,7 +1810,7 @@ export function append_memmove_dest_src (builder: WasmBuilder, count: number) { return true; } -export function recordFailure (): void { +export function recordFailure(): void { const result = modifyCounter(JiterpCounter.Failures, 1); if (result >= maxFailures) { mono_log_info(`Disabling jiterpreter after ${result} failures`); @@ -1824,7 +1824,7 @@ export function recordFailure (): void { const memberOffsets: { [index: number]: number } = {}; -export function getMemberOffset (member: JiterpMember) { +export function getMemberOffset(member: JiterpMember) { const cached = memberOffsets[member]; if (cached === undefined) return memberOffsets[member] = cwraps.mono_jiterp_get_member_offset(member); @@ -1832,7 +1832,7 @@ export function getMemberOffset (member: JiterpMember) { return cached; } -export function getRawCwrap (name: string): Function { +export function getRawCwrap(name: string): Function { const result = (Module)["asm"][name]; if (typeof (result) !== "function") throw new Error(`raw cwrap ${name} not found`); @@ -1841,18 +1841,18 @@ export function getRawCwrap (name: string): Function { const opcodeTableCache: { [opcode: number]: number } = {}; -export function getOpcodeTableValue (opcode: MintOpcode) { +export function getOpcodeTableValue(opcode: MintOpcode) { let result = opcodeTableCache[opcode]; if (typeof (result) !== "number") result = opcodeTableCache[opcode] = cwraps.mono_jiterp_get_opcode_value_table_entry(opcode); return result; } -export function importDef (name: string, fn: Function): [string, string, Function] { +export function importDef(name: string, fn: Function): [string, string, Function] { return [name, name, fn]; } -export function bytesFromHex (hex: string): Uint8Array { +export function bytesFromHex(hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16); @@ -1861,7 +1861,7 @@ export function bytesFromHex (hex: string): Uint8Array { let observedTaintedZeroPage: boolean | undefined; -export function isZeroPageReserved (): boolean { +export function isZeroPageReserved(): boolean { // FIXME: This check will always return true on worker threads. // Right now the jiterpreter is disabled when threading is active, so that's not an issue. if (WasmEnableThreads) @@ -1978,7 +1978,7 @@ let optionsVersion = -1; let optionTable: JiterpreterOptions = {}; // applies one or more jiterpreter options to change the current jiterpreter configuration. -export function applyOptions (options: JiterpreterOptions) { +export function applyOptions(options: JiterpreterOptions) { for (const k in options) { const info = optionNames[k]; if (!info) { @@ -1996,16 +1996,16 @@ export function applyOptions (options: JiterpreterOptions) { } } -export function getCounter (counter: JiterpCounter): number { +export function getCounter(counter: JiterpCounter): number { return cwraps.mono_jiterp_get_counter(counter); } -export function modifyCounter (counter: JiterpCounter, delta: number): number { +export function modifyCounter(counter: JiterpCounter, delta: number): number { return cwraps.mono_jiterp_modify_counter(counter, delta); } // returns the current jiterpreter configuration. do not mutate the return value! -export function getOptions () { +export function getOptions() { const currentVersion = cwraps.mono_jiterp_get_options_version(); if (currentVersion !== optionsVersion) { updateOptions(); @@ -2014,7 +2014,7 @@ export function getOptions () { return optionTable; } -function updateOptions () { +function updateOptions() { const pJson = cwraps.mono_jiterp_get_options_as_json(); const json = utf8ToString(pJson); Module._free(pJson); @@ -2027,7 +2027,7 @@ function updateOptions () { } } -function jiterpreter_allocate_table (type: JiterpreterTable, base: number, size: number, fillValue: Function) { +function jiterpreter_allocate_table(type: JiterpreterTable, base: number, size: number, fillValue: Function) { const wasmTable = getWasmFunctionTable(); const firstIndex = base, lastIndex = firstIndex + size - 1; mono_assert(lastIndex < wasmTable.length, () => `Last index out of range: ${lastIndex} >= ${wasmTable.length}`); @@ -2051,7 +2051,7 @@ function jiterpreter_allocate_table (type: JiterpreterTable, base: number, size: // we need to ensure we only ever initialize tables once on each js worker. let jiterpreter_tables_allocated = false; -export function jiterpreter_allocate_tables () { +export function jiterpreter_allocate_tables() { if (jiterpreter_tables_allocated) return; jiterpreter_tables_allocated = true; diff --git a/src/mono/browser/runtime/jiterpreter-trace-generator.ts b/src/mono/browser/runtime/jiterpreter-trace-generator.ts index 582f047febc3e2..ffb24bddcb1e6d 100644 --- a/src/mono/browser/runtime/jiterpreter-trace-generator.ts +++ b/src/mono/browser/runtime/jiterpreter-trace-generator.ts @@ -1,8 +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 {MonoMethod} from "./types/internal"; -import {NativePointer} from "./types/emscripten"; +import { MonoMethod } from "./types/internal"; +import { NativePointer } from "./types/emscripten"; import { getU16, getI16, getU32_unaligned, getI32_unaligned, getF32_unaligned, getF64_unaligned, localHeapViewU8, @@ -55,54 +55,54 @@ import { simdExtractTable, simdReplaceTable, simdLoadTable, simdStoreTable, } from "./jiterpreter-tables"; -import {mono_log_error, mono_log_info} from "./logging"; -import {mono_assert, runtimeHelpers} from "./globals"; +import { mono_log_error, mono_log_info } from "./logging"; +import { mono_assert, runtimeHelpers } from "./globals"; // indexPlusOne so that ip[1] in the interpreter becomes getArgU16(ip, 1) -function getArgU16 (ip: MintOpcodePtr, indexPlusOne: number) { +function getArgU16(ip: MintOpcodePtr, indexPlusOne: number) { return getU16(ip + (2 * indexPlusOne)); } -function getArgI16 (ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI16(ip: MintOpcodePtr, indexPlusOne: number) { return getI16(ip + (2 * indexPlusOne)); } -function getArgI32 (ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI32(ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getI32_unaligned(src); } -function getArgF32 (ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF32(ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF32_unaligned(src); } -function getArgF64 (ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF64(ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF64_unaligned(src); } -function get_imethod (frame: NativePointer) { +function get_imethod(frame: NativePointer) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const iMethod = getU32_unaligned(frame + getMemberOffset(JiterpMember.Imethod)); return iMethod; } -function get_imethod_data (frame: NativePointer, index: number) { +function get_imethod_data(frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.DataItems)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function get_imethod_clause_data_offset (frame: NativePointer, index: number) { +function get_imethod_clause_data_offset(frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.ClauseDataOffsets)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function is_backward_branch_target ( +function is_backward_branch_target( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, backwardBranchTable: Uint16Array | null ) { @@ -138,14 +138,14 @@ type KnownConstant = KnownConstantI32 | KnownConstantV128 | KnownConstantLdloca; type KnownConstantValue = number | Uint8Array; const knownConstants = new Map(); -function get_known_constant (builder: WasmBuilder, localOffset: number): KnownConstant | undefined { +function get_known_constant(builder: WasmBuilder, localOffset: number): KnownConstant | undefined { if (isAddressTaken(builder, localOffset)) return undefined; return knownConstants.get(localOffset); } -function get_known_constant_value (builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { +function get_known_constant_value(builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { const kc = get_known_constant(builder, localOffset); if (kc === undefined) return undefined; @@ -163,7 +163,7 @@ function get_known_constant_value (builder: WasmBuilder, localOffset: number): K // backwards branch targets, compatible with the layout of the old one that was generated in C. // We do this here to match the exact way that the jiterp calculates branch targets, since // there were previously corner cases where jiterp and interp disagreed. -export function generateBackwardBranchTable ( +export function generateBackwardBranchTable( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, ): Uint16Array | null { const endOfBody = startOfBody + sizeOfBody; @@ -236,7 +236,7 @@ export function generateBackwardBranchTable ( return new Uint16Array(table); } -export function generateWasmBody ( +export function generateWasmBody( frame: NativePointer, traceName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, endOfBody: MintOpcodePtr, builder: WasmBuilder, instrumentedTraceId: number, @@ -594,7 +594,7 @@ export function generateWasmBody ( // to have code that does '&x + c', which (if this optimization works) should // turn into '&locals + offsetof(x) + c' and get constant folded to have the same cost // as a regular ldloc - knownConstants.set(destOffset, {type: "ldloca", offset: offset}); + knownConstants.set(destOffset, { type: "ldloca", offset: offset }); // dreg invalidation would blow the known constant away, so disable it skipDregInvalidation = true; break; @@ -1748,29 +1748,29 @@ export function generateWasmBody ( const notNullSince: Map = new Map(); let cknullOffset = -1; -function eraseInferredState () { +function eraseInferredState() { cknullOffset = -1; notNullSince.clear(); knownConstants.clear(); } -function invalidate_local (offset: number) { +function invalidate_local(offset: number) { if (cknullOffset === offset) cknullOffset = -1; notNullSince.delete(offset); knownConstants.delete(offset); } -function invalidate_local_range (start: number, bytes: number) { +function invalidate_local_range(start: number, bytes: number) { for (let i = 0; i < bytes; i += 1) invalidate_local(start + i); } -function append_branch_target_block (builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { +function append_branch_target_block(builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { builder.cfg.startBranchBlock(ip, isBackBranchTarget); } -function computeMemoryAlignment (offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function computeMemoryAlignment(offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { // First, compute the best possible alignment let alignment = 0; if (offset % 16 === 0) @@ -1831,7 +1831,7 @@ function computeMemoryAlignment (offset: number, opcodeOrPrefix: WasmOpcode, sim return alignment; } -function try_append_ldloc_cprop ( +function try_append_ldloc_cprop( builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, dryRun: boolean, requireNonzero?: boolean ) { @@ -1868,7 +1868,7 @@ function try_append_ldloc_cprop ( return false; } -function append_ldloc (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_ldloc(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { if (try_append_ldloc_cprop(builder, offset, opcodeOrPrefix, false)) return; @@ -1890,7 +1890,7 @@ function append_ldloc (builder: WasmBuilder, offset: number, opcodeOrPrefix: Was // where the offset+alignment pair is referred to as a 'memarg' by the spec. // The actual store operation is equivalent to `pBase[offset] = value` (alignment has no // observable impact on behavior, other than causing compilation failures if out of range) -function append_stloc_tail (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_stloc_tail(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { mono_assert(opcodeOrPrefix >= WasmOpcode.i32_store, () => `Expected store opcode but got ${opcodeOrPrefix}`); builder.appendU8(opcodeOrPrefix); if (simdOpcode !== undefined) { @@ -1907,7 +1907,7 @@ function append_stloc_tail (builder: WasmBuilder, offset: number, opcodeOrPrefix // Pass bytesInvalidated=0 if you are reading from the local and the address will never be // used for writes -function append_ldloca (builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { +function append_ldloca(builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { if (typeof (bytesInvalidated) !== "number") bytesInvalidated = 512; // FIXME: We need to know how big this variable is so we can invalidate the whole space it occupies @@ -1916,7 +1916,7 @@ function append_ldloca (builder: WasmBuilder, localOffset: number, bytesInvalida builder.lea("pLocals", localOffset); } -function append_memset_local (builder: WasmBuilder, localOffset: number, value: number, count: number) { +function append_memset_local(builder: WasmBuilder, localOffset: number, value: number, count: number) { invalidate_local_range(localOffset, count); // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val @@ -1928,7 +1928,7 @@ function append_memset_local (builder: WasmBuilder, localOffset: number, value: append_memset_dest(builder, value, count); } -function append_memmove_local_local (builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { +function append_memmove_local_local(builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { invalidate_local_range(destLocalOffset, count); if (try_append_memmove_fast(builder, destLocalOffset, sourceLocalOffset, count, false)) @@ -1940,12 +1940,12 @@ function append_memmove_local_local (builder: WasmBuilder, destLocalOffset: numb append_memmove_dest_src(builder, count); } -function isAddressTaken (builder: WasmBuilder, localOffset: number) { +function isAddressTaken(builder: WasmBuilder, localOffset: number) { return cwraps.mono_jiterp_is_imethod_var_address_taken(get_imethod(builder.frame), localOffset) !== 0; } // Loads the specified i32 value and then bails out if it is null, leaving it in the cknull_ptr local. -function append_ldloc_cknull (builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { +function append_ldloc_cknull(builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { const optimize = builder.allowNullCheckOptimization && notNullSince.has(localOffset) && !isAddressTaken(builder, localOffset); @@ -1997,7 +1997,7 @@ function append_ldloc_cknull (builder: WasmBuilder, localOffset: number, ip: Min cknullOffset = -1; } -function emit_ldc (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_ldc(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let storeType = WasmOpcode.i32_store; let value: number | undefined; @@ -2062,14 +2062,14 @@ function emit_ldc (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): invalidate_local(localOffset); if (typeof (value) === "number") - knownConstants.set(localOffset, {type: "i32", value: value}); + knownConstants.set(localOffset, { type: "i32", value: value }); else knownConstants.delete(localOffset); return true; } -function emit_mov (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_mov(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let loadOp = WasmOpcode.i32_load, storeOp = WasmOpcode.i32_store; switch (opcode) { case MintOpcode.MINT_MOV_I4_I1: @@ -2132,7 +2132,7 @@ function emit_mov (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function append_vtable_initialize (builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { +function append_vtable_initialize(builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { // TODO: Actually initialize the vtable instead of just checking and bailing out? builder.block(); // FIXME: This will prevent us from reusing traces between runs since the vtables can move @@ -2147,7 +2147,7 @@ function append_vtable_initialize (builder: WasmBuilder, pVtable: NativePointer, builder.endBlock(); } -function emit_fieldop ( +function emit_fieldop( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2343,7 +2343,7 @@ function emit_fieldop ( } } -function emit_sfieldop ( +function emit_sfieldop( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2450,7 +2450,7 @@ function emit_sfieldop ( } } -function emit_binop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_binop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right let lhsLoadOp: WasmOpcode, rhsLoadOp: WasmOpcode, storeOp: WasmOpcode, lhsVar = "math_lhs32", rhsVar = "math_rhs32", @@ -2602,7 +2602,7 @@ function emit_binop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode return true; } -function emit_unop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_unop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right const info = unopTable[opcode]; if (!info) @@ -2741,7 +2741,7 @@ function emit_unop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode) return true; } -function append_call_handler_store_ret_ip ( +function append_call_handler_store_ret_ip( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ) { @@ -2761,7 +2761,7 @@ function append_call_handler_store_ret_ip ( builder.callHandlerReturnAddresses.push(retIp); } -function getBranchDisplacement ( +function getBranchDisplacement( ip: MintOpcodePtr, opcode: MintOpcode ): number | undefined { const opArgType = cwraps.mono_jiterp_get_opcode_info(opcode, OpcodeInfoType.OpArgType), @@ -2789,7 +2789,7 @@ function getBranchDisplacement ( return result; } -function emit_branch ( +function emit_branch( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2930,7 +2930,7 @@ function emit_branch ( return true; } -function emit_relop_branch ( +function emit_relop_branch( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2985,7 +2985,7 @@ function emit_relop_branch ( return emit_branch(builder, ip, frame, opcode); } -function emit_math_intrinsic (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_math_intrinsic(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let isUnary: boolean, isF32: boolean, name: string | undefined; let wasmOp: WasmOpcode | undefined; const destOffset = getArgU16(ip, 1), @@ -3033,7 +3033,7 @@ function emit_math_intrinsic (builder: WasmBuilder, ip: MintOpcodePtr, opcode: M } } -function emit_indirectop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_indirectop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = (opcode >= MintOpcode.MINT_LDIND_I1) && (opcode <= MintOpcode.MINT_LDIND_OFFSET_ADD_MUL_IMM_I8); const isAddMul = ( @@ -3247,7 +3247,7 @@ function emit_indirectop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintO return true; } -function append_getelema1 ( +function append_getelema1( builder: WasmBuilder, ip: MintOpcodePtr, objectOffset: number, indexOffset: number, elementSize: number ) { @@ -3306,7 +3306,7 @@ function append_getelema1 ( // append_getelema1 leaves the address on the stack } -function emit_arrayop (builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_arrayop(builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = ((opcode <= MintOpcode.MINT_LDELEMA_TC) && (opcode >= MintOpcode.MINT_LDELEM_I1)) || (opcode === MintOpcode.MINT_LDLEN), objectOffset = getArgU16(ip, isLoad ? 2 : 1), @@ -3470,7 +3470,7 @@ function emit_arrayop (builder: WasmBuilder, frame: NativePointer, ip: MintOpcod let wasmSimdSupported: boolean | undefined; -function getIsWasmSimdSupported (): boolean { +function getIsWasmSimdSupported(): boolean { if (wasmSimdSupported !== undefined) return wasmSimdSupported; @@ -3481,7 +3481,7 @@ function getIsWasmSimdSupported (): boolean { return wasmSimdSupported; } -function get_import_name ( +function get_import_name( builder: WasmBuilder, typeName: string, functionPtr: number ): string { @@ -3492,7 +3492,7 @@ function get_import_name ( return name; } -function emit_simd ( +function emit_simd( builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode, opname: string, argCount: number, index: number @@ -3524,7 +3524,7 @@ function emit_simd ( const view = localHeapViewU8().slice(ip + 4, ip + 4 + sizeOfV128); builder.v128_const(view); append_simd_store(builder, ip); - knownConstants.set(getArgU16(ip, 1), {type: "v128", value: view}); + knownConstants.set(getArgU16(ip, 1), { type: "v128", value: view }); } else { // dest append_ldloca(builder, getArgU16(ip, 1), sizeOfV128); @@ -3593,31 +3593,31 @@ function emit_simd ( } } -function append_simd_store (builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_store(builder: WasmBuilder, ip: MintOpcodePtr) { append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_store); } -function append_simd_2_load (builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { +function append_simd_2_load(builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { builder.local("pLocals"); // This || is harmless since v128_load is 0 append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, loadOp || WasmSimdOpcode.v128_load); } -function append_simd_3_load (builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_3_load(builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); // FIXME: Can rhs be a scalar? We handle shifts separately already append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function append_simd_4_load (builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_4_load(builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 4), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function emit_simd_2 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { +function emit_simd_2(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(1, index); if (simple >= 0) { if (simdLoadTable.has(index)) { @@ -3684,7 +3684,7 @@ function emit_simd_2 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrin } } -function emit_simd_3 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { +function emit_simd_3(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(2, index); if (simple >= 0) { const isShift = simdShiftTable.has(index), @@ -3805,7 +3805,7 @@ function emit_simd_3 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrin // implement i16 and i32 shuffles on top of wasm's only shuffle opcode by expanding the // element shuffle indices into byte indices -function emit_shuffle (builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { +function emit_shuffle(builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { const elementSize = 16 / elementCount, indicesOffset = getArgU16(ip, 3), constantIndices = get_known_constant_value(builder, indicesOffset); @@ -3866,7 +3866,7 @@ function emit_shuffle (builder: WasmBuilder, ip: MintOpcodePtr, elementCount: nu return true; } -function emit_simd_4 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { +function emit_simd_4(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(3, index); if (simple >= 0) { // [lane count, value load opcode] diff --git a/src/mono/browser/runtime/jiterpreter.ts b/src/mono/browser/runtime/jiterpreter.ts index 3d498308d1e1dd..188ead0c51e99c 100644 --- a/src/mono/browser/runtime/jiterpreter.ts +++ b/src/mono/browser/runtime/jiterpreter.ts @@ -1,12 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {MonoMethod} from "./types/internal"; -import {NativePointer} from "./types/emscripten"; -import {Module, mono_assert, runtimeHelpers} from "./globals"; -import {getU16} from "./memory"; -import {WasmValtype, WasmOpcode, getOpcodeName} from "./jiterpreter-opcodes"; -import {MintOpcode} from "./mintops"; +import { MonoMethod } from "./types/internal"; +import { NativePointer } from "./types/emscripten"; +import { Module, mono_assert, runtimeHelpers } from "./globals"; +import { getU16 } from "./memory"; +import { WasmValtype, WasmOpcode, getOpcodeName } from "./jiterpreter-opcodes"; +import { MintOpcode } from "./mintops"; import cwraps from "./cwraps"; import { MintOpcodePtr, WasmBuilder, addWasmFunctionPointer, @@ -22,10 +22,10 @@ import { import { generateWasmBody, generateBackwardBranchTable } from "./jiterpreter-trace-generator"; -import {mono_jiterp_free_method_data_interp_entry} from "./jiterpreter-interp-entry"; -import {mono_jiterp_free_method_data_jit_call} from "./jiterpreter-jit-call"; -import {mono_log_error, mono_log_info, mono_log_warn} from "./logging"; -import {utf8ToString} from "./strings"; +import { mono_jiterp_free_method_data_interp_entry } from "./jiterpreter-interp-entry"; +import { mono_jiterp_free_method_data_jit_call } from "./jiterpreter-jit-call"; +import { mono_log_error, mono_log_info, mono_log_warn } from "./logging"; +import { utf8ToString } from "./strings"; // Controls miscellaneous diagnostic output. export const trace = 0; @@ -98,7 +98,7 @@ export class InstrumentedTraceState { operand1: number | undefined; operand2: number | undefined; - constructor (name: string) { + constructor(name: string) { this.name = name; this.eip = 0; } @@ -114,13 +114,13 @@ export class TraceInfo { bailoutCount: number | undefined; isVerbose: boolean; - constructor (ip: MintOpcodePtr, index: number, isVerbose: number) { + constructor(ip: MintOpcodePtr, index: number, isVerbose: number) { this.ip = ip; this.index = index; this.isVerbose = !!isVerbose; } - get hitCount () { + get hitCount() { return cwraps.mono_jiterp_get_trace_hit_count(this.index); } } @@ -225,7 +225,7 @@ const mathOps1d = "powf", ]; -function recordBailout (ip: number, traceIndex: number, reason: BailoutReason) { +function recordBailout(ip: number, traceIndex: number, reason: BailoutReason) { cwraps.mono_jiterp_trace_bailout(reason); // Counting these is not meaningful and messes up the end of run statistics if (reason === BailoutReason.Return) @@ -251,7 +251,7 @@ function recordBailout (ip: number, traceIndex: number, reason: BailoutReason) { return ip; } -function getTraceImports () { +function getTraceImports() { if (traceImports) return traceImports; @@ -313,7 +313,7 @@ function getTraceImports () { return traceImports; } -function initialize_builder (builder: WasmBuilder) { +function initialize_builder(builder: WasmBuilder) { // Function type for compiled traces builder.defineType( "trace", @@ -694,7 +694,7 @@ function initialize_builder (builder: WasmBuilder) { } } -function assert_not_null ( +function assert_not_null( value: number, expectedValue: number, traceIndex: number, ip: MintOpcodePtr ) { if (value && (value === expectedValue)) @@ -704,7 +704,7 @@ function assert_not_null ( } // returns function id -function generate_wasm ( +function generate_wasm( frame: NativePointer, methodName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, traceIndex: number, methodFullName: string | undefined, @@ -948,7 +948,7 @@ function generate_wasm ( } } -export function trace_current_ip (traceId: number, eip: MintOpcodePtr) { +export function trace_current_ip(traceId: number, eip: MintOpcodePtr) { const tup = instrumentedTraces[traceId]; if (!tup) throw new Error(`Unrecognized instrumented trace id ${traceId}`); @@ -956,14 +956,14 @@ export function trace_current_ip (traceId: number, eip: MintOpcodePtr) { mostRecentTrace = tup; } -export function trace_operands (a: number, b: number) { +export function trace_operands(a: number, b: number) { if (!mostRecentTrace) throw new Error("No trace active"); mostRecentTrace.operand1 = a >>> 0; mostRecentTrace.operand2 = b >>> 0; } -export function record_abort (traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { +export function record_abort(traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { if (typeof (reason) === "number") { cwraps.mono_jiterp_adjust_abort_count(reason, 1); reason = getOpcodeName(reason); @@ -986,7 +986,7 @@ export function record_abort (traceIndex: number, ip: MintOpcodePtr, traceName: const JITERPRETER_TRAINING = 0; const JITERPRETER_NOT_JITTED = 1; -export function mono_interp_tier_prepare_jiterpreter ( +export function mono_interp_tier_prepare_jiterpreter( frame: NativePointer, method: MonoMethod, ip: MintOpcodePtr, index: number, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, isVerbose: number, presetFunctionPointer: number @@ -1061,7 +1061,7 @@ export function mono_interp_tier_prepare_jiterpreter ( // NOTE: This will potentially be called once for every trace entry point // in a given method, not just once per method -export function mono_jiterp_free_method_data_js ( +export function mono_jiterp_free_method_data_js( method: MonoMethod, imethod: number, traceIndex: number ) { // TODO: Uninstall the trace function pointer from the function pointer table, @@ -1073,7 +1073,7 @@ export function mono_jiterp_free_method_data_js ( mono_jiterp_free_method_data_jit_call(method); } -export function jiterpreter_dump_stats (concise?: boolean): void { +export function jiterpreter_dump_stats(concise?: boolean): void { if (!runtimeHelpers.runtimeReady) { return; } diff --git a/src/mono/browser/runtime/lazyLoading.ts b/src/mono/browser/runtime/lazyLoading.ts index 8aed4ddc3f8fdd..86b0431e5400b8 100644 --- a/src/mono/browser/runtime/lazyLoading.ts +++ b/src/mono/browser/runtime/lazyLoading.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {loaderHelpers} from "./globals"; -import {load_lazy_assembly} from "./managed-exports"; -import {AssetEntry} from "./types"; +import { loaderHelpers } from "./globals"; +import { load_lazy_assembly } from "./managed-exports"; +import { AssetEntry } from "./types"; -export async function loadLazyAssembly (assemblyNameToLoad: string): Promise { +export async function loadLazyAssembly(assemblyNameToLoad: string): Promise { const resources = loaderHelpers.config.resources!; const lazyAssemblies = resources.lazyAssembly; if (!lazyAssemblies) { @@ -56,7 +56,7 @@ export async function loadLazyAssembly (assemblyNameToLoad: string): Promise | undefined; @@ -91,11 +91,11 @@ const loadIntoWorker: { "segmentation-rules": true, }; -export function shouldLoadIcuAsset (asset: AssetEntryInternal): boolean { +export function shouldLoadIcuAsset(asset: AssetEntryInternal): boolean { return !(asset.behavior == "icu" && asset.name != loaderHelpers.preferredIcuAsset); } -function convert_single_asset (assetsCollection: AssetEntryInternal[], resource: ResourceList | undefined, behavior: SingleAssetBehaviors): AssetEntryInternal { +function convert_single_asset(assetsCollection: AssetEntryInternal[], resource: ResourceList | undefined, behavior: SingleAssetBehaviors): AssetEntryInternal { const keys = Object.keys(resource || {}); mono_assert(keys.length == 1, `Expect to have one ${behavior} asset in resources`); @@ -114,20 +114,20 @@ function convert_single_asset (assetsCollection: AssetEntryInternal[], resource: return asset; } -function set_single_asset (asset: AssetEntryInternal) { +function set_single_asset(asset: AssetEntryInternal) { if (singleAssetTypes[asset.behavior]) { singleAssets.set(asset.behavior, asset); } } -function get_single_asset (behavior: SingleAssetBehaviors): AssetEntryInternal { +function get_single_asset(behavior: SingleAssetBehaviors): AssetEntryInternal { mono_assert(singleAssetTypes[behavior], `Unknown single asset behavior ${behavior}`); const asset = singleAssets.get(behavior); mono_assert(asset, `Single asset for ${behavior} not found`); return asset; } -export function resolve_single_asset_path (behavior: SingleAssetBehaviors): AssetEntryInternal { +export function resolve_single_asset_path(behavior: SingleAssetBehaviors): AssetEntryInternal { const asset = get_single_asset(behavior); if (!asset.resolvedUrl) { asset.resolvedUrl = loaderHelpers.locateFile(asset.name); @@ -148,7 +148,7 @@ export function resolve_single_asset_path (behavior: SingleAssetBehaviors): Asse return asset; } -export async function mono_download_assets (): Promise { +export async function mono_download_assets(): Promise { mono_log_debug("mono_download_assets"); try { const promises_of_assets: Promise[] = []; @@ -175,7 +175,7 @@ export async function mono_download_assets (): Promise { const promises_of_asset_instantiation: Promise[] = []; for (const downloadPromise of promises_of_assets) { - promises_of_asset_instantiation.push((async () => { + promises_of_asset_instantiation.push((async() => { const asset = await downloadPromise; if (asset.buffer) { if (!skipInstantiateByAssetTypes[asset.behavior]) { @@ -237,7 +237,7 @@ export async function mono_download_assets (): Promise { } } -export function prepareAssets () { +export function prepareAssets() { const config = loaderHelpers.config; const modulesAssets: AssetEntryInternal[] = []; @@ -365,7 +365,7 @@ export function prepareAssets () { config.assets = [...assetsToLoad, ...modulesAssets]; } -export function prepareAssetsWorker () { +export function prepareAssetsWorker() { const config = loaderHelpers.config; mono_assert(config.assets, "config.assets must be defined"); @@ -377,18 +377,18 @@ export function prepareAssetsWorker () { } } -export function delay (ms: number): Promise { +export function delay(ms: number): Promise { return new Promise(resolve => globalThis.setTimeout(resolve, ms)); } -export async function retrieve_asset_download (asset: AssetEntry): Promise { +export async function retrieve_asset_download(asset: AssetEntry): Promise { const pendingAsset = await start_asset_download(asset); await pendingAsset.pendingDownloadInternal!.response; return pendingAsset.buffer!; } // FIXME: Connection reset is probably the only good one for which we should retry -export async function start_asset_download (asset: AssetEntryInternal): Promise { +export async function start_asset_download(asset: AssetEntryInternal): Promise { try { return await start_asset_download_with_throttle(asset); } catch (err: any) { @@ -429,7 +429,7 @@ export async function start_asset_download (asset: AssetEntryInternal): Promise< } } -async function start_asset_download_with_throttle (asset: AssetEntryInternal): Promise { +async function start_asset_download_with_throttle(asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! while (throttlingPromise) { await throttlingPromise.promise; @@ -463,7 +463,7 @@ async function start_asset_download_with_throttle (asset: AssetEntryInternal): P } } -async function start_asset_download_sources (asset: AssetEntryInternal): Promise { +async function start_asset_download_sources(asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! if (asset.pendingDownload) { asset.pendingDownloadInternal = asset.pendingDownload; @@ -541,7 +541,7 @@ async function start_asset_download_sources (asset: AssetEntryInternal): Promise } } -function resolve_path (asset: AssetEntry, sourcePrefix: string): string { +function resolve_path(asset: AssetEntry, sourcePrefix: string): string { mono_assert(sourcePrefix !== null && sourcePrefix !== undefined, () => `sourcePrefix must be provided for ${asset.name}`); let attemptUrl; if (!asset.resolvedUrl) { @@ -565,7 +565,7 @@ function resolve_path (asset: AssetEntry, sourcePrefix: string): string { return attemptUrl; } -export function appendUniqueQuery (attemptUrl: string, behavior: AssetBehaviors): string { +export function appendUniqueQuery(attemptUrl: string, behavior: AssetBehaviors): string { // apply unique query to js modules to make the module state independent of the other runtime instances if (loaderHelpers.modulesUniqueQuery && appendQueryAssetTypes[behavior]) { attemptUrl = attemptUrl + loaderHelpers.modulesUniqueQuery; @@ -577,11 +577,11 @@ export function appendUniqueQuery (attemptUrl: string, behavior: AssetBehaviors) let resourcesLoaded = 0; const totalResources = new Set(); -function download_resource (asset: AssetEntryInternal): LoadingResource { +function download_resource(asset: AssetEntryInternal): LoadingResource { try { mono_assert(asset.resolvedUrl, "Request's resolvedUrl must be set"); const fetchResponse = download_resource_with_cache(asset); - const response = {name: asset.name, url: asset.resolvedUrl, response: fetchResponse}; + const response = { name: asset.name, url: asset.resolvedUrl, response: fetchResponse }; totalResources.add(asset.name!); response.response.then(() => { @@ -613,7 +613,7 @@ function download_resource (asset: AssetEntryInternal): LoadingResource { } } -async function download_resource_with_cache (asset: AssetEntryInternal): Promise { +async function download_resource_with_cache(asset: AssetEntryInternal): Promise { let response = await findCachedResponse(asset); if (!response) { response = await fetchResource(asset); @@ -623,7 +623,7 @@ async function download_resource_with_cache (asset: AssetEntryInternal): Promise return response; } -function fetchResource (asset: AssetEntryInternal): Promise { +function fetchResource(asset: AssetEntryInternal): Promise { // Allow developers to override how the resource is loaded let url = asset.resolvedUrl!; if (loaderHelpers.loadBootResource) { @@ -671,7 +671,7 @@ const monoToBlazorAssetTypeMap: { [key: string]: WebAssemblyBootResourceType | u "js-module-threads": "dotnetjs" }; -function invokeLoadBootResource (asset: AssetEntryInternal): string | Promise | null | undefined { +function invokeLoadBootResource(asset: AssetEntryInternal): string | Promise | null | undefined { if (loaderHelpers.loadBootResource) { const requestHash = asset.hash ?? ""; const url = asset.resolvedUrl!; @@ -689,7 +689,7 @@ function invokeLoadBootResource (asset: AssetEntryInternal): string | Promise= 0) { lastIndexOfSlash++; @@ -705,7 +705,7 @@ function fileName (name: string) { return name.substring(lastIndexOfSlash); } -export async function streamingCompileWasm () { +export async function streamingCompileWasm() { try { const wasmModuleAsset = resolve_single_asset_path("dotnetwasm"); await start_asset_download(wasmModuleAsset); @@ -737,7 +737,7 @@ export async function streamingCompileWasm () { loaderHelpers.wasmCompilePromise.promise_control.reject(err); } } -export function preloadWorkers () { +export function preloadWorkers() { if (!WasmEnableThreads) return; const jsModuleWorker = resolve_single_asset_path("js-module-threads"); for (let i = 0; i < loaderHelpers.config.pthreadPoolInitialSize!; i++) { diff --git a/src/mono/browser/runtime/loader/assetsCache.ts b/src/mono/browser/runtime/loader/assetsCache.ts index 182e103c28cb71..ec6bf96233b5d5 100644 --- a/src/mono/browser/runtime/loader/assetsCache.ts +++ b/src/mono/browser/runtime/loader/assetsCache.ts @@ -1,16 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {MonoConfig} from "../types"; -import type {AssetEntryInternal} from "../types/internal"; -import {ENVIRONMENT_IS_WEB, loaderHelpers} from "./globals"; +import type { MonoConfig } from "../types"; +import type { AssetEntryInternal } from "../types/internal"; +import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals"; const usedCacheKeys: { [key: string]: boolean } = {}; const networkLoads: { [name: string]: LoadLogEntry } = {}; const cacheLoads: { [name: string]: LoadLogEntry } = {}; let cacheIfUsed: Cache | null; -export function logDownloadStatsToConsole (): void { +export function logDownloadStatsToConsole(): void { const cacheLoadsEntries = Object.values(cacheLoads); const networkLoadsEntries = Object.values(networkLoads); const cacheResponseBytes = countTotalBytes(cacheLoadsEntries); @@ -51,7 +51,7 @@ export function logDownloadStatsToConsole (): void { console.groupEnd(); } -export async function purgeUnusedCacheEntriesAsync (): Promise { +export async function purgeUnusedCacheEntriesAsync(): Promise { // We want to keep the cache small because, even though the browser will evict entries if it // gets too big, we don't want to be considered problematic by the end user viewing storage stats const cache = cacheIfUsed; @@ -67,7 +67,7 @@ export async function purgeUnusedCacheEntriesAsync (): Promise { } } -export async function findCachedResponse (asset: AssetEntryInternal): Promise { +export async function findCachedResponse(asset: AssetEntryInternal): Promise { const cache = cacheIfUsed; if (!cache || asset.noCache || !asset.hash || asset.hash.length === 0) { return undefined; @@ -90,11 +90,11 @@ export async function findCachedResponse (asset: AssetEntryInternal): Promise { +export async function initCacheToUseIfEnabled(): Promise { cacheIfUsed = await getCacheToUseIfEnabled(loaderHelpers.config); } -async function getCacheToUseIfEnabled (config: MonoConfig): Promise { +async function getCacheToUseIfEnabled(config: MonoConfig): Promise { // caches will be undefined if we're running on an insecure origin (secure means https or localhost) if (!config.cacheBootResources || typeof globalThis.caches === "undefined" || typeof globalThis.document === "undefined") { return null; @@ -180,15 +180,15 @@ async function getCacheToUseIfEnabled (config: MonoConfig): Promise prev + (item.responseBytes || 0), 0); } -function toDataSizeString (byteCount: number) { +function toDataSizeString(byteCount: number) { return `${(byteCount / (1024 * 1024)).toFixed(2)} MB`; } -function getPerformanceEntry (url: string): PerformanceResourceTiming | undefined { +function getPerformanceEntry(url: string): PerformanceResourceTiming | undefined { if (typeof performance !== "undefined") { return performance.getEntriesByName(url)[0] as PerformanceResourceTiming; } diff --git a/src/mono/browser/runtime/loader/config.ts b/src/mono/browser/runtime/loader/config.ts index 8960bf2d48742b..5648285166c5e6 100644 --- a/src/mono/browser/runtime/loader/config.ts +++ b/src/mono/browser/runtime/loader/config.ts @@ -4,22 +4,22 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableThreads from "consts:wasmEnableThreads"; -import {MainThreadingMode, type DotnetModuleInternal, type MonoConfigInternal, JSThreadBlockingMode, JSThreadInteropMode} from "../types/internal"; -import type {DotnetModuleConfig, MonoConfig, ResourceGroups, ResourceList} from "../types"; -import {exportedRuntimeAPI, loaderHelpers, runtimeHelpers} from "./globals"; -import {mono_log_error, mono_log_debug} from "./logging"; -import {importLibraryInitializers, invokeLibraryInitializers} from "./libraryInitializers"; -import {mono_exit} from "./exit"; -import {makeURLAbsoluteWithApplicationBase} from "./polyfills"; -import {appendUniqueQuery} from "./assets"; -import {mono_log_warn} from "./logging"; - -export function deep_merge_config (target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { +import { MainThreadingMode, type DotnetModuleInternal, type MonoConfigInternal, JSThreadBlockingMode, JSThreadInteropMode } from "../types/internal"; +import type { DotnetModuleConfig, MonoConfig, ResourceGroups, ResourceList } from "../types"; +import { exportedRuntimeAPI, loaderHelpers, runtimeHelpers } from "./globals"; +import { mono_log_error, mono_log_debug } from "./logging"; +import { importLibraryInitializers, invokeLibraryInitializers } from "./libraryInitializers"; +import { mono_exit } from "./exit"; +import { makeURLAbsoluteWithApplicationBase } from "./polyfills"; +import { appendUniqueQuery } from "./assets"; +import { mono_log_warn } from "./logging"; + +export function deep_merge_config(target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { // no need to merge the same object if (target === source) return target; // If source has collection fields set to null (produced by boot config for example), we should maintain the target values - const providedConfig: MonoConfigInternal = {...source}; + const providedConfig: MonoConfigInternal = { ...source }; if (providedConfig.assets !== undefined && providedConfig.assets !== target.assets) { providedConfig.assets = [...(target.assets || []), ...(providedConfig.assets || [])]; } @@ -32,7 +32,7 @@ export function deep_merge_config (target: MonoConfigInternal, source: MonoConfi }, providedConfig.resources); } if (providedConfig.environmentVariables !== undefined) { - providedConfig.environmentVariables = {...(target.environmentVariables || {}), ...(providedConfig.environmentVariables || {})}; + providedConfig.environmentVariables = { ...(target.environmentVariables || {}), ...(providedConfig.environmentVariables || {}) }; } if (providedConfig.runtimeOptions !== undefined && providedConfig.runtimeOptions !== target.runtimeOptions) { providedConfig.runtimeOptions = [...(target.runtimeOptions || []), ...(providedConfig.runtimeOptions || [])]; @@ -40,11 +40,11 @@ export function deep_merge_config (target: MonoConfigInternal, source: MonoConfi return Object.assign(target, providedConfig); } -export function deep_merge_module (target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { +export function deep_merge_module(target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { // no need to merge the same object if (target === source) return target; - const providedConfig: DotnetModuleConfig = {...source}; + const providedConfig: DotnetModuleConfig = { ...source }; if (providedConfig.config) { if (!target.config) target.config = {}; providedConfig.config = deep_merge_config(target.config, providedConfig.config); @@ -52,49 +52,49 @@ export function deep_merge_module (target: DotnetModuleInternal, source: DotnetM return Object.assign(target, providedConfig); } -function deep_merge_resources (target: ResourceGroups, source: ResourceGroups): ResourceGroups { +function deep_merge_resources(target: ResourceGroups, source: ResourceGroups): ResourceGroups { // no need to merge the same object if (target === source) return target; - const providedResources: ResourceGroups = {...source}; + const providedResources: ResourceGroups = { ...source }; if (providedResources.assembly !== undefined) { - providedResources.assembly = {...(target.assembly || {}), ...(providedResources.assembly || {})}; + providedResources.assembly = { ...(target.assembly || {}), ...(providedResources.assembly || {}) }; } if (providedResources.lazyAssembly !== undefined) { - providedResources.lazyAssembly = {...(target.lazyAssembly || {}), ...(providedResources.lazyAssembly || {})}; + providedResources.lazyAssembly = { ...(target.lazyAssembly || {}), ...(providedResources.lazyAssembly || {}) }; } if (providedResources.pdb !== undefined) { - providedResources.pdb = {...(target.pdb || {}), ...(providedResources.pdb || {})}; + providedResources.pdb = { ...(target.pdb || {}), ...(providedResources.pdb || {}) }; } if (providedResources.jsModuleWorker !== undefined) { - providedResources.jsModuleWorker = {...(target.jsModuleWorker || {}), ...(providedResources.jsModuleWorker || {})}; + providedResources.jsModuleWorker = { ...(target.jsModuleWorker || {}), ...(providedResources.jsModuleWorker || {}) }; } if (providedResources.jsModuleNative !== undefined) { - providedResources.jsModuleNative = {...(target.jsModuleNative || {}), ...(providedResources.jsModuleNative || {})}; + providedResources.jsModuleNative = { ...(target.jsModuleNative || {}), ...(providedResources.jsModuleNative || {}) }; } if (providedResources.jsModuleRuntime !== undefined) { - providedResources.jsModuleRuntime = {...(target.jsModuleRuntime || {}), ...(providedResources.jsModuleRuntime || {})}; + providedResources.jsModuleRuntime = { ...(target.jsModuleRuntime || {}), ...(providedResources.jsModuleRuntime || {}) }; } if (providedResources.wasmSymbols !== undefined) { - providedResources.wasmSymbols = {...(target.wasmSymbols || {}), ...(providedResources.wasmSymbols || {})}; + providedResources.wasmSymbols = { ...(target.wasmSymbols || {}), ...(providedResources.wasmSymbols || {}) }; } if (providedResources.wasmNative !== undefined) { - providedResources.wasmNative = {...(target.wasmNative || {}), ...(providedResources.wasmNative || {})}; + providedResources.wasmNative = { ...(target.wasmNative || {}), ...(providedResources.wasmNative || {}) }; } if (providedResources.icu !== undefined) { - providedResources.icu = {...(target.icu || {}), ...(providedResources.icu || {})}; + providedResources.icu = { ...(target.icu || {}), ...(providedResources.icu || {}) }; } if (providedResources.satelliteResources !== undefined) { providedResources.satelliteResources = deep_merge_dict(target.satelliteResources || {}, providedResources.satelliteResources || {}); } if (providedResources.modulesAfterConfigLoaded !== undefined) { - providedResources.modulesAfterConfigLoaded = {...(target.modulesAfterConfigLoaded || {}), ...(providedResources.modulesAfterConfigLoaded || {})}; + providedResources.modulesAfterConfigLoaded = { ...(target.modulesAfterConfigLoaded || {}), ...(providedResources.modulesAfterConfigLoaded || {}) }; } if (providedResources.modulesAfterRuntimeReady !== undefined) { - providedResources.modulesAfterRuntimeReady = {...(target.modulesAfterRuntimeReady || {}), ...(providedResources.modulesAfterRuntimeReady || {})}; + providedResources.modulesAfterRuntimeReady = { ...(target.modulesAfterRuntimeReady || {}), ...(providedResources.modulesAfterRuntimeReady || {}) }; } if (providedResources.extensions !== undefined) { - providedResources.extensions = {...(target.extensions || {}), ...(providedResources.extensions || {})}; + providedResources.extensions = { ...(target.extensions || {}), ...(providedResources.extensions || {}) }; } if (providedResources.vfs !== undefined) { providedResources.vfs = deep_merge_dict(target.vfs || {}, providedResources.vfs || {}); @@ -102,18 +102,18 @@ function deep_merge_resources (target: ResourceGroups, source: ResourceGroups): return Object.assign(target, providedResources); } -function deep_merge_dict (target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { +function deep_merge_dict(target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { // no need to merge the same object if (target === source) return target; for (const key in source) { - target[key] = {...target[key], ...source[key]}; + target[key] = { ...target[key], ...source[key] }; } return target; } // NOTE: this is called before setRuntimeGlobals -export function normalizeConfig () { +export function normalizeConfig() { // normalize const config = loaderHelpers.config; @@ -259,7 +259,7 @@ export function normalizeConfig () { } let configLoaded = false; -export async function mono_wasm_load_config (module: DotnetModuleInternal): Promise { +export async function mono_wasm_load_config(module: DotnetModuleInternal): Promise { const configFilePath = module.configSrc; if (configLoaded) { await loaderHelpers.afterConfigLoaded.promise; @@ -291,13 +291,13 @@ export async function mono_wasm_load_config (module: DotnetModuleInternal): Prom normalizeConfig(); } catch (err) { const errMessage = `Failed to load config file ${configFilePath} ${err} ${(err as Error)?.stack}`; - loaderHelpers.config = module.config = Object.assign(loaderHelpers.config, {message: errMessage, error: err, isError: true}); + loaderHelpers.config = module.config = Object.assign(loaderHelpers.config, { message: errMessage, error: err, isError: true }); mono_exit(1, new Error(errMessage)); throw err; } } -export function isDebuggingSupported (): boolean { +export function isDebuggingSupported(): boolean { // Copied from blazor MonoDebugger.ts/attachDebuggerHotkey if (!globalThis.navigator) { return false; @@ -306,7 +306,7 @@ export function isDebuggingSupported (): boolean { return loaderHelpers.isChromium || loaderHelpers.isFirefox; } -async function loadBootConfig (module: DotnetModuleInternal): Promise { +async function loadBootConfig(module: DotnetModuleInternal): Promise { const defaultConfigSrc = loaderHelpers.locateFile(module.configSrc!); const loaderResponse = loaderHelpers.loadBootResource !== undefined ? @@ -326,7 +326,7 @@ async function loadBootConfig (module: DotnetModuleInternal): Promise { const loadedConfig: MonoConfig = await readBootConfigResponse(loadConfigResponse); deep_merge_config(loaderHelpers.config, loadedConfig); - function defaultLoadBootConfig (url: string): Promise { + function defaultLoadBootConfig(url: string): Promise { return loaderHelpers.fetch_like(url, { method: "GET", credentials: "include", @@ -335,7 +335,7 @@ async function loadBootConfig (module: DotnetModuleInternal): Promise { } } -async function readBootConfigResponse (loadConfigResponse: Response): Promise { +async function readBootConfigResponse(loadConfigResponse: Response): Promise { const config = loaderHelpers.config; const loadedConfig: MonoConfig = await loadConfigResponse.json(); diff --git a/src/mono/browser/runtime/loader/exit.ts b/src/mono/browser/runtime/loader/exit.ts index 84e0bea422eaf2..da22c198f12016 100644 --- a/src/mono/browser/runtime/loader/exit.ts +++ b/src/mono/browser/runtime/loader/exit.ts @@ -3,18 +3,18 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, INTERNAL, emscriptenModule, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {mono_log_debug, mono_log_error, mono_log_info_no_prefix, mono_log_warn, teardown_proxy_console} from "./logging"; +import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, INTERNAL, emscriptenModule, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { mono_log_debug, mono_log_error, mono_log_info_no_prefix, mono_log_warn, teardown_proxy_console } from "./logging"; -export function is_exited () { +export function is_exited() { return loaderHelpers.exitCode !== undefined; } -export function is_runtime_running () { +export function is_runtime_running() { return runtimeHelpers.runtimeReady && !is_exited(); } -export function assert_runtime_running () { +export function assert_runtime_running() { mono_assert(!is_exited(), () => `.NET runtime already exited with ${loaderHelpers.exitCode} ${loaderHelpers.exitReason}. You can use runtime.runMain() which doesn't exit the runtime.`); if (WasmEnableThreads && ENVIRONMENT_IS_WORKER) { mono_assert(runtimeHelpers.runtimeReady, "The WebWorker is not attached to the runtime. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -24,7 +24,7 @@ export function assert_runtime_running () { } -export function installUnhandledErrorHandler () { +export function installUnhandledErrorHandler() { // it seems that emscripten already does the right thing for NodeJs and that there is no good solution for V8 shell. if (ENVIRONMENT_IS_WEB) { globalThis.addEventListener("unhandledrejection", unhandledrejection_handler); @@ -32,14 +32,14 @@ export function installUnhandledErrorHandler () { } } -export function uninstallUnhandledErrorHandler () { +export function uninstallUnhandledErrorHandler() { if (ENVIRONMENT_IS_WEB) { globalThis.removeEventListener("unhandledrejection", unhandledrejection_handler); globalThis.removeEventListener("error", error_handler); } } -export function registerEmscriptenExitHandlers () { +export function registerEmscriptenExitHandlers() { if (!emscriptenModule.onAbort) { emscriptenModule.onAbort = onAbort; } @@ -48,7 +48,7 @@ export function registerEmscriptenExitHandlers () { } } -function unregisterEmscriptenExitHandlers () { +function unregisterEmscriptenExitHandlers() { if (emscriptenModule.onAbort == onAbort) { emscriptenModule.onAbort = undefined; } @@ -56,16 +56,16 @@ function unregisterEmscriptenExitHandlers () { emscriptenModule.onExit = undefined; } } -function onExit (code: number) { +function onExit(code: number) { mono_exit(code, loaderHelpers.exitReason); } -function onAbort (reason: any) { +function onAbort(reason: any) { mono_exit(1, loaderHelpers.exitReason || reason); } // this will also call mono_wasm_exit if available, which will call exitJS -> _proc_exit -> terminateAllThreads -export function mono_exit (exit_code: number, reason?: any): void { +export function mono_exit(exit_code: number, reason?: any): void { unregisterEmscriptenExitHandlers(); uninstallUnhandledErrorHandler(); @@ -136,7 +136,7 @@ export function mono_exit (exit_code: number, reason?: any): void { if (loaderHelpers.config && loaderHelpers.config.asyncFlushOnExit && exit_code === 0) { // this would NOT call Node's exit() immediately, it's a hanging promise - (async () => { + (async() => { try { await flush_node_streams(); } finally { @@ -151,7 +151,7 @@ export function mono_exit (exit_code: number, reason?: any): void { } } -function set_exit_code_and_quit_now (exit_code: number, reason?: any): void { +function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { if (WasmEnableThreads && ENVIRONMENT_IS_WORKER && runtimeHelpers.runtimeReady && runtimeHelpers.nativeAbort) { // note that the reason is not passed to UI thread runtimeHelpers.runtimeReady = false; @@ -180,7 +180,7 @@ function set_exit_code_and_quit_now (exit_code: number, reason?: any): void { } } -async function flush_node_streams () { +async function flush_node_streams() { try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -204,7 +204,7 @@ async function flush_node_streams () { } } -function abort_promises (reason: any) { +function abort_promises(reason: any) { loaderHelpers.exitReason = reason; loaderHelpers.allDownloadsQueued.promise_control.reject(reason); loaderHelpers.afterConfigLoaded.promise_control.reject(reason); @@ -222,7 +222,7 @@ function abort_promises (reason: any) { } } -function appendElementOnExit (exit_code: number) { +function appendElementOnExit(exit_code: number) { if (ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER && loaderHelpers.config && loaderHelpers.config.appendElementOnExit && document) { //Tell xharness WasmBrowserTestRunner what was the exit code const tests_done_elem = document.createElement("label"); @@ -233,7 +233,7 @@ function appendElementOnExit (exit_code: number) { } } -function logOnExit (exit_code: number, reason: any) { +function logOnExit(exit_code: number, reason: any) { if (exit_code !== 0 && reason) { // ExitStatus usually is not real JS error and so stack strace is not very useful. // We will use debug level for it, which will print only when diagnosticTracing is set. @@ -268,15 +268,15 @@ function logOnExit (exit_code: number, reason: any) { } } } -function unhandledrejection_handler (event: any) { +function unhandledrejection_handler(event: any) { fatal_handler(event, event.reason, "rejection"); } -function error_handler (event: any) { +function error_handler(event: any) { fatal_handler(event, event.error, "error"); } -function fatal_handler (event: any, reason: any, type: string) { +function fatal_handler(event: any, reason: any, type: string) { event.preventDefault(); try { if (!reason) { diff --git a/src/mono/browser/runtime/loader/globals.ts b/src/mono/browser/runtime/loader/globals.ts index f451f0da9a79f8..4bf317bb66a07c 100644 --- a/src/mono/browser/runtime/loader/globals.ts +++ b/src/mono/browser/runtime/loader/globals.ts @@ -4,19 +4,19 @@ /* eslint-disable @typescript-eslint/triple-slash-reference */ /// -import {exceptions, simd} from "wasm-feature-detect"; +import { exceptions, simd } from "wasm-feature-detect"; import gitHash from "consts:gitHash"; -import type {DotnetModuleInternal, GlobalObjects, LoaderHelpers, MonoConfigInternal, RuntimeHelpers} from "../types/internal"; -import type {MonoConfig, RuntimeAPI} from "../types"; -import {assert_runtime_running, installUnhandledErrorHandler, 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 {mono_log_error, set_thread_prefix, setup_proxy_console} from "./logging"; -import {invokeLibraryInitializers} from "./libraryInitializers"; -import {deep_merge_config, isDebuggingSupported} from "./config"; -import {logDownloadStatsToConsole, purgeUnusedCacheEntriesAsync} from "./assetsCache"; +import type { DotnetModuleInternal, GlobalObjects, LoaderHelpers, MonoConfigInternal, RuntimeHelpers } from "../types/internal"; +import type { MonoConfig, RuntimeAPI } from "../types"; +import { assert_runtime_running, installUnhandledErrorHandler, 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 { mono_log_error, set_thread_prefix, setup_proxy_console } from "./logging"; +import { invokeLibraryInitializers } from "./libraryInitializers"; +import { deep_merge_config, isDebuggingSupported } 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 if (typeof importScripts === "function" && !globalThis.onmessage) { @@ -53,7 +53,7 @@ export const globalObjectsRoot: GlobalObjects = { setLoaderGlobals(globalObjectsRoot); -export function setLoaderGlobals ( +export function setLoaderGlobals( globalObjects: GlobalObjects, ) { if (_loaderModuleLoaded) { @@ -70,7 +70,7 @@ export function setLoaderGlobals ( }); Object.assign(globalObjects.module, { - config: deep_merge_config(monoConfig, {environmentVariables: {}}), + config: deep_merge_config(monoConfig, { environmentVariables: {} }), }); const rh: Partial = { mono_wasm_bindings_is_ready: false, @@ -137,7 +137,7 @@ export function setLoaderGlobals ( // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() diff --git a/src/mono/browser/runtime/loader/icu.ts b/src/mono/browser/runtime/loader/icu.ts index 7a49a38291a850..8cb39f2e0b2bd6 100644 --- a/src/mono/browser/runtime/loader/icu.ts +++ b/src/mono/browser/runtime/loader/icu.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {GlobalizationMode, MonoConfig} from "../types"; -import {ENVIRONMENT_IS_WEB, loaderHelpers} from "./globals"; -import {mono_log_info, mono_log_debug} from "./logging"; +import { GlobalizationMode, MonoConfig } from "../types"; +import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals"; +import { mono_log_info, mono_log_debug } from "./logging"; -export function init_globalization () { +export function init_globalization() { loaderHelpers.preferredIcuAsset = getIcuResourceName(loaderHelpers.config); let invariantMode = loaderHelpers.config.globalizationMode == GlobalizationMode.Invariant; @@ -44,7 +44,7 @@ export function init_globalization () { } } -export function getIcuResourceName (config: MonoConfig): string | null { +export function getIcuResourceName(config: MonoConfig): string | null { if (config.resources?.icu && config.globalizationMode != GlobalizationMode.Invariant) { // 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); @@ -73,7 +73,7 @@ export function getIcuResourceName (config: MonoConfig): string | null { return null; } -function getShardedIcuResourceName (culture: string): string { +function getShardedIcuResourceName(culture: string): string { const prefix = culture.split("-")[0]; if (prefix === "en" || ["fr", "fr-FR", "it", "it-IT", "de", "de-DE", "es", "es-ES"].includes(culture)) { return "icudt_EFIGS.dat"; diff --git a/src/mono/browser/runtime/loader/index.ts b/src/mono/browser/runtime/loader/index.ts index d319b28fdf99b0..6818186c36a028 100644 --- a/src/mono/browser/runtime/loader/index.ts +++ b/src/mono/browser/runtime/loader/index.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {DotnetHostBuilder} from "../types"; -import {mono_exit} from "./exit"; -import {verifyEnvironment} from "./polyfills"; -import {HostBuilder, createEmscripten} from "./run"; +import type { DotnetHostBuilder } from "../types"; +import { mono_exit } from "./exit"; +import { verifyEnvironment } from "./polyfills"; +import { HostBuilder, createEmscripten } from "./run"; // export external API const dotnet: DotnetHostBuilder = new HostBuilder(); @@ -13,5 +13,5 @@ const legacyEntrypoint = createEmscripten; verifyEnvironment(); -export {dotnet, exit}; +export { dotnet, exit }; export default legacyEntrypoint; diff --git a/src/mono/browser/runtime/loader/libraryInitializers.ts b/src/mono/browser/runtime/loader/libraryInitializers.ts index 55d363632aa055..27c5d783a40222 100644 --- a/src/mono/browser/runtime/loader/libraryInitializers.ts +++ b/src/mono/browser/runtime/loader/libraryInitializers.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {mono_log_debug, mono_log_warn} from "./logging"; -import {appendUniqueQuery} from "./assets"; -import {loaderHelpers} from "./globals"; -import {mono_exit} from "./exit"; -import {ResourceList} from "../types"; +import { mono_log_debug, mono_log_warn } from "./logging"; +import { appendUniqueQuery } from "./assets"; +import { loaderHelpers } from "./globals"; +import { mono_exit } from "./exit"; +import { ResourceList } from "../types"; -export async function importLibraryInitializers (libraryInitializers: ResourceList | undefined): Promise { +export async function importLibraryInitializers(libraryInitializers: ResourceList | undefined): Promise { if (!libraryInitializers) { return; } @@ -15,20 +15,20 @@ export async function importLibraryInitializers (libraryInitializers: ResourceLi const initializerFiles = Object.keys(libraryInitializers); await Promise.all(initializerFiles.map(f => importInitializer(f))); - async function importInitializer (path: string): Promise { + async function importInitializer(path: string): Promise { try { const adjustedPath = appendUniqueQuery(loaderHelpers.locateFile(path), "js-module-library-initializer"); mono_log_debug(`Attempting to import '${adjustedPath}' for ${path}`); const initializer = await import(/*! webpackIgnore: true */ adjustedPath); - loaderHelpers.libraryInitializers!.push({scriptName: path, exports: initializer}); + loaderHelpers.libraryInitializers!.push({ scriptName: path, exports: initializer }); } catch (error) { mono_log_warn(`Failed to import library initializer '${path}': ${error}`); } } } -export async function invokeLibraryInitializers (functionName: string, args: any[]) { +export async function invokeLibraryInitializers(functionName: string, args: any[]) { if (!loaderHelpers.libraryInitializers) { return; } @@ -44,7 +44,7 @@ export async function invokeLibraryInitializers (functionName: string, args: any await Promise.all(promises); } -async function abortStartupOnError (scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { +async function abortStartupOnError(scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { try { await callback(); } catch (err) { diff --git a/src/mono/browser/runtime/loader/logging.ts b/src/mono/browser/runtime/loader/logging.ts index 2940b20e3edb4f..7c4d509f6b6e2d 100644 --- a/src/mono/browser/runtime/loader/logging.ts +++ b/src/mono/browser/runtime/loader/logging.ts @@ -5,7 +5,7 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_WORKER, loaderHelpers} from "./globals"; +import { ENVIRONMENT_IS_WORKER, loaderHelpers } from "./globals"; const methods = ["debug", "log", "trace", "warn", "info", "error"]; const prefix = "MONO_WASM: "; @@ -14,29 +14,29 @@ let theConsoleApi: any; let originalConsoleMethods: any; let threadNamePrefix: string; -export function set_thread_prefix (threadPrefix: string) { +export function set_thread_prefix(threadPrefix: string) { threadNamePrefix = threadPrefix; } -export function mono_log_debug (msg: string, ...data: any[]) { +export function mono_log_debug(msg: string, ...data: any[]) { if (loaderHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info (msg: string, ...data: any) { +export function mono_log_info(msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_info_no_prefix (msg: string, ...data: any) { +export function mono_log_info_no_prefix(msg: string, ...data: any) { console.info(msg, ...data); } -export function mono_log_warn (msg: string, ...data: any) { +export function mono_log_warn(msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error (msg: string, ...data: any) { +export function mono_log_error(msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object") { // don't log silent errors if (data[0].silent) { @@ -54,8 +54,8 @@ export function mono_log_error (msg: string, ...data: any) { } let tick = ""; let last = new Date().valueOf(); -function proxyConsoleMethod (prefix: string, func: any, asJson: boolean) { - return function (...args: any[]) { +function proxyConsoleMethod(prefix: string, func: any, asJson: boolean) { + return function(...args: any[]) { try { let payload = args[0]; if (payload === undefined) payload = "undefined"; @@ -101,7 +101,7 @@ function proxyConsoleMethod (prefix: string, func: any, asJson: boolean) { }; } -export function setup_proxy_console (id: string, console: Console, origin: string): void { +export function setup_proxy_console(id: string, console: Console, origin: string): void { theConsoleApi = console as any; threadNamePrefix = id; originalConsoleMethods = { @@ -117,7 +117,7 @@ export function setup_proxy_console (id: string, console: Console, origin: strin setupWS(); } -export function teardown_proxy_console (message?: string) { +export function teardown_proxy_console(message?: string) { const stop_when_ws_buffer_empty = () => { if (!consoleWebSocket) { if (message && originalConsoleMethods) { @@ -142,7 +142,7 @@ export function teardown_proxy_console (message?: string) { stop_when_ws_buffer_empty(); } -function send (msg: string) { +function send(msg: string) { if (consoleWebSocket && consoleWebSocket.readyState === WebSocket.OPEN) { consoleWebSocket.send(msg); } else { @@ -150,21 +150,21 @@ function send (msg: string) { } } -function logWSError (event: Event) { +function logWSError(event: Event) { originalConsoleMethods.error(`[${threadNamePrefix}] proxy console websocket error: ${event}`, event); } -function logWSClose (event: Event) { +function logWSClose(event: Event) { originalConsoleMethods.debug(`[${threadNamePrefix}] proxy console websocket closed: ${event}`, event); } -function setupWS () { +function setupWS() { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, send, true); } } -function setupOriginal () { +function setupOriginal() { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, originalConsoleMethods.log, false); } diff --git a/src/mono/browser/runtime/loader/polyfills.ts b/src/mono/browser/runtime/loader/polyfills.ts index c355b2155a8440..4d9743049f2122 100644 --- a/src/mono/browser/runtime/loader/polyfills.ts +++ b/src/mono/browser/runtime/loader/polyfills.ts @@ -3,22 +3,22 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import type {DotnetModuleInternal} from "../types/internal"; -import {INTERNAL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, loaderHelpers, ENVIRONMENT_IS_WEB, mono_assert} from "./globals"; +import type { DotnetModuleInternal } from "../types/internal"; +import { INTERNAL, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, loaderHelpers, ENVIRONMENT_IS_WEB, mono_assert } from "./globals"; let node_fs: any | undefined = undefined; let node_url: any | undefined = undefined; const URLPolyfill = class URL { private url; - constructor (url: string) { + constructor(url: string) { this.url = url; } - toString () { + toString() { return this.url; } }; -export function verifyEnvironment () { +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. 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 (WasmEnableThreads) { @@ -28,7 +28,7 @@ export function verifyEnvironment () { } } -export async function detect_features_and_polyfill (module: DotnetModuleInternal): Promise { +export async function detect_features_and_polyfill(module: DotnetModuleInternal): Promise { if (ENVIRONMENT_IS_NODE) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -87,14 +87,14 @@ export async function detect_features_and_polyfill (module: DotnetModuleInternal } } -export async function fetch_like (url: string, init?: RequestInit): Promise { +export async function fetch_like(url: string, init?: RequestInit): Promise { try { // this need to be detected only after we import node modules in onConfigLoaded const hasFetch = typeof (globalThis.fetch) === "function"; if (ENVIRONMENT_IS_NODE) { const isFileUrl = url.startsWith("file://"); if (!isFileUrl && hasFetch) { - return globalThis.fetch(url, init || {credentials: "same-origin"}); + return globalThis.fetch(url, init || { credentials: "same-origin" }); } if (!node_fs) { node_url = INTERNAL.require("url"); @@ -119,7 +119,7 @@ export async function fetch_like (url: string, init?: RequestInit): Promisee.xml // https://bugs.chromium.org/p/v8/issues/detail?id=12541 @@ -167,7 +167,7 @@ export async function fetch_like (url: string, init?: RequestInit): Promise (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { let promise_control: PromiseController = null as unknown as PromiseController; - const promise = new Promise(function (resolve, reject) { + const promise = new Promise(function(resolve, reject) { promise_control = { isDone: false, promise: null as unknown as Promise, @@ -38,18 +38,18 @@ export function createPromiseController (afterResolve?: () => void, afterReje (promise_control).promise = promise; const controllablePromise = promise as ControllablePromise; (controllablePromise as any)[promise_control_symbol] = promise_control; - return {promise: controllablePromise, promise_control: promise_control}; + return { promise: controllablePromise, promise_control: promise_control }; } export function getPromiseController(promise: ControllablePromise): PromiseController; -export function getPromiseController (promise: Promise): PromiseController | undefined { +export function getPromiseController(promise: Promise): PromiseController | undefined { return (promise as any)[promise_control_symbol]; } -export function isControllablePromise (promise: Promise): promise is ControllablePromise { +export function isControllablePromise(promise: Promise): promise is ControllablePromise { return (promise as any)[promise_control_symbol] !== undefined; } -export function assertIsControllablePromise (promise: Promise): asserts promise is ControllablePromise { +export function assertIsControllablePromise(promise: Promise): asserts promise is ControllablePromise { mono_assert(promise && isControllablePromise(promise), "Promise is not controllable"); } diff --git a/src/mono/browser/runtime/loader/run.ts b/src/mono/browser/runtime/loader/run.ts index 6f3167d713ac9e..992994211050fa 100644 --- a/src/mono/browser/runtime/loader/run.ts +++ b/src/mono/browser/runtime/loader/run.ts @@ -3,27 +3,27 @@ import BuildConfiguration from "consts:configuration"; -import type {MonoConfig, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, LoadBootResourceCallback} from "../types"; -import type {EmscriptenModuleInternal, RuntimeModuleExportsInternal, NativeModuleExportsInternal,} from "../types/internal"; - -import {ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, emscriptenModule, exportedRuntimeAPI, globalObjectsRoot, monoConfig, mono_assert} from "./globals"; -import {deep_merge_config, deep_merge_module, mono_wasm_load_config} from "./config"; -import {installUnhandledErrorHandler, mono_exit, registerEmscriptenExitHandlers} from "./exit"; -import {setup_proxy_console, mono_log_info, mono_log_debug} from "./logging"; -import {mono_download_assets, preloadWorkers, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm} from "./assets"; -import {detect_features_and_polyfill} from "./polyfills"; -import {runtimeHelpers, loaderHelpers} from "./globals"; -import {init_globalization} from "./icu"; -import {setupPreloadChannelToMainThread} from "./worker"; -import {importLibraryInitializers, invokeLibraryInitializers} from "./libraryInitializers"; -import {initCacheToUseIfEnabled} from "./assetsCache"; +import type { MonoConfig, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, LoadBootResourceCallback } from "../types"; +import type { EmscriptenModuleInternal, RuntimeModuleExportsInternal, NativeModuleExportsInternal, } from "../types/internal"; + +import { ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, emscriptenModule, exportedRuntimeAPI, globalObjectsRoot, monoConfig, mono_assert } from "./globals"; +import { deep_merge_config, deep_merge_module, mono_wasm_load_config } from "./config"; +import { installUnhandledErrorHandler, mono_exit, registerEmscriptenExitHandlers } from "./exit"; +import { setup_proxy_console, mono_log_info, mono_log_debug } from "./logging"; +import { mono_download_assets, preloadWorkers, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm } from "./assets"; +import { detect_features_and_polyfill } from "./polyfills"; +import { runtimeHelpers, loaderHelpers } from "./globals"; +import { init_globalization } from "./icu"; +import { setupPreloadChannelToMainThread } from "./worker"; +import { importLibraryInitializers, invokeLibraryInitializers } from "./libraryInitializers"; +import { initCacheToUseIfEnabled } from "./assetsCache"; export class HostBuilder implements DotnetHostBuilder { private instance?: RuntimeAPI; // internal - withModuleConfig (moduleConfig: DotnetModuleConfig): DotnetHostBuilder { + withModuleConfig(moduleConfig: DotnetModuleConfig): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, moduleConfig); return this; @@ -34,7 +34,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withOnConfigLoaded (onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { + withOnConfigLoaded(onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, { onConfigLoaded @@ -47,7 +47,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withConsoleForwarding (): DotnetHostBuilder { + withConsoleForwarding(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { forwardConsoleLogsToWS: true @@ -60,7 +60,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitOnUnhandledError (): DotnetHostBuilder { + withExitOnUnhandledError(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { exitOnUnhandledError: true @@ -74,7 +74,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withAsyncFlushOnExit (): DotnetHostBuilder { + withAsyncFlushOnExit(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { asyncFlushOnExit: true @@ -87,7 +87,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitCodeLogging (): DotnetHostBuilder { + withExitCodeLogging(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { logExitCode: true @@ -100,7 +100,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withElementOnExit (): DotnetHostBuilder { + withElementOnExit(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { appendElementOnExit: true @@ -113,7 +113,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withInteropCleanupOnExit (): DotnetHostBuilder { + withInteropCleanupOnExit(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interopCleanupOnExit: true @@ -126,7 +126,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withDumpThreadsOnNonZeroExit (): DotnetHostBuilder { + withDumpThreadsOnNonZeroExit(): DotnetHostBuilder { try { deep_merge_config(monoConfig, { dumpThreadsOnNonZeroExit: true @@ -140,7 +140,7 @@ export class HostBuilder implements DotnetHostBuilder { // internal // todo fallback later by debugLevel - withWaitingForDebugger (level: number): DotnetHostBuilder { + withWaitingForDebugger(level: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { waitForDebugger: level @@ -152,7 +152,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withInterpreterPgo (value: boolean, autoSaveDelay?: number): DotnetHostBuilder { + withInterpreterPgo(value: boolean, autoSaveDelay?: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interpreterPgo: value, @@ -165,7 +165,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfig (config: MonoConfig): DotnetHostBuilder { + withConfig(config: MonoConfig): DotnetHostBuilder { try { deep_merge_config(monoConfig, config); return this; @@ -175,10 +175,10 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfigSrc (configSrc: string): DotnetHostBuilder { + withConfigSrc(configSrc: string): DotnetHostBuilder { try { mono_assert(configSrc && typeof configSrc === "string", "must be file path or URL"); - deep_merge_module(emscriptenModule, {configSrc}); + deep_merge_module(emscriptenModule, { configSrc }); return this; } catch (err) { mono_exit(1, err); @@ -186,7 +186,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withVirtualWorkingDirectory (vfsPath: string): DotnetHostBuilder { + withVirtualWorkingDirectory(vfsPath: string): DotnetHostBuilder { try { mono_assert(vfsPath && typeof vfsPath === "string", "must be directory path"); deep_merge_config(monoConfig, { @@ -199,7 +199,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariable (name: string, value: string): DotnetHostBuilder { + withEnvironmentVariable(name: string, value: string): DotnetHostBuilder { try { const environmentVariables: { [key: string]: string } = {}; environmentVariables[name] = value; @@ -213,7 +213,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariables (variables: { [i: string]: string; }): DotnetHostBuilder { + withEnvironmentVariables(variables: { [i: string]: string; }): DotnetHostBuilder { try { mono_assert(variables && typeof variables === "object", "must be dictionary object"); deep_merge_config(monoConfig, { @@ -226,7 +226,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDiagnosticTracing (enabled: boolean): DotnetHostBuilder { + withDiagnosticTracing(enabled: boolean): DotnetHostBuilder { try { mono_assert(typeof enabled === "boolean", "must be boolean"); deep_merge_config(monoConfig, { @@ -239,7 +239,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDebugging (level: number): DotnetHostBuilder { + withDebugging(level: number): DotnetHostBuilder { try { mono_assert(level !== undefined && level !== null && typeof level === "number", "must be number"); deep_merge_config(monoConfig, { @@ -252,7 +252,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArguments (...args: string[]): DotnetHostBuilder { + withApplicationArguments(...args: string[]): DotnetHostBuilder { try { mono_assert(args && Array.isArray(args), "must be array of strings"); deep_merge_config(monoConfig, { @@ -265,7 +265,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withRuntimeOptions (runtimeOptions: string[]): DotnetHostBuilder { + withRuntimeOptions(runtimeOptions: string[]): DotnetHostBuilder { try { mono_assert(runtimeOptions && Array.isArray(runtimeOptions), "must be array of strings"); deep_merge_config(monoConfig, { @@ -278,7 +278,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withMainAssembly (mainAssemblyName: string): DotnetHostBuilder { + withMainAssembly(mainAssemblyName: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { mainAssemblyName @@ -290,7 +290,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArgumentsFromQuery (): DotnetHostBuilder { + withApplicationArgumentsFromQuery(): DotnetHostBuilder { try { if (!globalThis.window) { throw new Error("Missing window to the query parameters from"); @@ -309,7 +309,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationEnvironment (applicationEnvironment?: string): DotnetHostBuilder { + withApplicationEnvironment(applicationEnvironment?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationEnvironment, @@ -321,7 +321,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationCulture (applicationCulture?: string): DotnetHostBuilder { + withApplicationCulture(applicationCulture?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationCulture, @@ -333,7 +333,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withResourceLoader (loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { + withResourceLoader(loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { try { loaderHelpers.loadBootResource = loadBootResource; return this; @@ -343,7 +343,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async create (): Promise { + async create(): Promise { try { if (!this.instance) { this.instance = await createApi(); @@ -355,7 +355,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async run (): Promise { + async run(): Promise { try { mono_assert(emscriptenModule.config, "Null moduleConfig.config"); if (!this.instance) { @@ -369,7 +369,7 @@ export class HostBuilder implements DotnetHostBuilder { } } -export async function createApi (): Promise { +export async function createApi(): Promise { if (ENVIRONMENT_IS_WEB && loaderHelpers.config.forwardConsoleLogsToWS && typeof globalThis.WebSocket != "undefined") { setup_proxy_console("main", globalThis.console, globalThis.location.origin); } @@ -379,7 +379,7 @@ export async function createApi (): Promise { return globalObjectsRoot.api; } -export async function createEmscripten (moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { +export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { // extract ModuleConfig if (typeof moduleFactory === "function") { const extension = moduleFactory(globalObjectsRoot.api) as any; @@ -408,7 +408,7 @@ export async function createEmscripten (moduleFactory: DotnetModuleConfig | ((ap } // in the future we can use feature detection to load different flavors -function importModules () { +function importModules() { const jsModuleRuntimeAsset = resolve_single_asset_path("js-module-runtime"); const jsModuleNativeAsset = resolve_single_asset_path("js-module-native"); @@ -432,9 +432,9 @@ function importModules () { return [jsModuleRuntimePromise, jsModuleNativePromise]; } -async function initializeModules (es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { - const {initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals} = es6Modules[0]; - const {default: emscriptenFactory} = es6Modules[1]; +async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { + const { initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals } = es6Modules[0]; + const { default: emscriptenFactory } = es6Modules[1]; setRuntimeGlobals(globalObjectsRoot); initializeExports(globalObjectsRoot); await configureRuntimeStartup(); @@ -452,7 +452,7 @@ async function initializeModules (es6Modules: [RuntimeModuleExportsInternal, Nat }); } -async function createEmscriptenMain (): Promise { +async function createEmscriptenMain(): Promise { if (!emscriptenModule.configSrc && (!loaderHelpers.config || Object.keys(loaderHelpers.config).length === 0 || (!loaderHelpers.config.assets && !loaderHelpers.config.resources))) { // if config file location nor assets are provided emscriptenModule.configSrc = "./blazor.boot.json"; @@ -469,7 +469,7 @@ async function createEmscriptenMain (): Promise { streamingCompileWasm(); // intentionally not awaited - setTimeout(async () => { + setTimeout(async() => { try { init_globalization(); preloadWorkers(); @@ -491,14 +491,14 @@ async function createEmscriptenMain (): Promise { return exportedRuntimeAPI; } -async function createEmscriptenWorker (): Promise { +async function createEmscriptenWorker(): Promise { setupPreloadChannelToMainThread(); await loaderHelpers.afterConfigLoaded.promise; prepareAssetsWorker(); - setTimeout(async () => { + setTimeout(async() => { try { // load subset which is on JS heap rather than in WASM linear memory await mono_download_assets(); diff --git a/src/mono/browser/runtime/loader/worker.ts b/src/mono/browser/runtime/loader/worker.ts index cb4fdaead86fbd..baeeaf0165f673 100644 --- a/src/mono/browser/runtime/loader/worker.ts +++ b/src/mono/browser/runtime/loader/worker.ts @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {MonoConfigInternal, PThreadInfo, WorkerToMainMessageType, monoMessageSymbol} from "../types/internal"; -import {MonoConfig} from "../types"; -import {deep_merge_config, normalizeConfig} from "./config"; -import {ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers} from "./globals"; -import {mono_log_debug} from "./logging"; +import { MonoConfigInternal, PThreadInfo, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal"; +import { MonoConfig } from "../types"; +import { deep_merge_config, normalizeConfig } from "./config"; +import { ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers } from "./globals"; +import { mono_log_debug } from "./logging"; -export function setupPreloadChannelToMainThread () { +export function setupPreloadChannelToMainThread() { const channel = new MessageChannel(); const workerPort = channel.port1; const mainPort = channel.port2; @@ -17,7 +17,7 @@ export function setupPreloadChannelToMainThread () { onMonoConfigReceived(config, monoThreadInfo); workerPort.close(); mainPort.close(); - }, {once: true}); + }, { once: true }); workerPort.start(); // ask for config even before WASM is loaded self.postMessage({ @@ -31,7 +31,7 @@ export function setupPreloadChannelToMainThread () { let workerMonoConfigReceived = false; // called when the main thread sends us the mono config -function onMonoConfigReceived (config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { +function onMonoConfigReceived(config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { if (workerMonoConfigReceived) { mono_log_debug("mono config already received"); return; diff --git a/src/mono/browser/runtime/logging.ts b/src/mono/browser/runtime/logging.ts index a84f8e2a1f75ba..8e6dbfa67ff48c 100644 --- a/src/mono/browser/runtime/logging.ts +++ b/src/mono/browser/runtime/logging.ts @@ -2,31 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. /* eslint-disable no-console */ -import {INTERNAL, runtimeHelpers, mono_assert} from "./globals"; -import {utf8ToString} from "./strings"; -import {CharPtr, VoidPtr} from "./types/emscripten"; +import { INTERNAL, runtimeHelpers, mono_assert } from "./globals"; +import { utf8ToString } from "./strings"; +import { CharPtr, VoidPtr } from "./types/emscripten"; let prefix = "MONO_WASM: "; -export function set_thread_prefix (threadPrefix: string) { +export function set_thread_prefix(threadPrefix: string) { prefix = `[${threadPrefix}] MONO_WASM: `; } -export function mono_log_debug (msg: string, ...data: any) { +export function mono_log_debug(msg: string, ...data: any) { if (runtimeHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info (msg: string, ...data: any) { +export function mono_log_info(msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_warn (msg: string, ...data: any) { +export function mono_log_warn(msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error (msg: string, ...data: any) { +export function mono_log_error(msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object" && data[0].silent) { // don't log silent errors return; @@ -53,7 +53,7 @@ regexes.push(/(?[a-z]+:\/\/[^ )]*:wasm-function\[(?\d+) //# .wasm-function[8962] regexes.push(/(?<[^ >]+>[.:]wasm-function\[(?[0-9]+)\])/); -export function mono_wasm_symbolicate_string (message: string): string { +export function mono_wasm_symbolicate_string(message: string): string { try { performDeferredSymbolMapParsing(); @@ -92,7 +92,7 @@ export function mono_wasm_symbolicate_string (message: string): string { } } -export function mono_wasm_stringify_as_error_with_stack (reason: any): string { +export function mono_wasm_stringify_as_error_with_stack(reason: any): string { let stack: string; if (typeof reason === "string") { stack = reason; @@ -106,7 +106,7 @@ export function mono_wasm_stringify_as_error_with_stack (reason: any): string { return mono_wasm_symbolicate_string(stack); } -export function mono_wasm_trace_logger (log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { +export function mono_wasm_trace_logger(log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { const origMessage = utf8ToString(message_ptr); const isFatal = !!fatal; const domain = utf8ToString(log_domain_ptr); @@ -144,7 +144,7 @@ export function mono_wasm_trace_logger (log_domain_ptr: CharPtr, log_level_ptr: } -export function parseSymbolMapFile (text: string) { +export function parseSymbolMapFile(text: string) { // Symbol map parsing is very expensive, so doing it during startup is wasteful // instead, we defer it until the first time the symbol map is needed - which // may be never @@ -153,7 +153,7 @@ export function parseSymbolMapFile (text: string) { mono_log_debug(`Deferred loading of ${text.length}ch symbol map`); } -function performDeferredSymbolMapParsing () { +function performDeferredSymbolMapParsing() { if (!wasm_pending_symbol_table) return; @@ -174,11 +174,11 @@ function performDeferredSymbolMapParsing () { } } -export function mono_wasm_get_func_id_to_name_mappings () { +export function mono_wasm_get_func_id_to_name_mappings() { performDeferredSymbolMapParsing(); return [...wasm_func_map.values()]; } -export function mono_wasm_console_clear () { +export function mono_wasm_console_clear() { console.clear(); } diff --git a/src/mono/browser/runtime/managed-exports.ts b/src/mono/browser/runtime/managed-exports.ts index 1fb7db988c7570..52b6391f1cc18a 100644 --- a/src/mono/browser/runtime/managed-exports.ts +++ b/src/mono/browser/runtime/managed-exports.ts @@ -3,22 +3,22 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {GCHandle, GCHandleNull, JSMarshalerArguments, JSThreadInteropMode, MarshalerToCs, MarshalerToJs, MarshalerType, MonoMethod, PThreadPtr} from "./types/internal"; -import cwraps, {threads_c_functions as twraps} from "./cwraps"; -import {runtimeHelpers, Module, loaderHelpers, mono_assert} from "./globals"; -import {JavaScriptMarshalerArgSize, alloc_stack_frame, get_arg, get_arg_gc_handle, is_args_exception, set_arg_i32, set_arg_intptr, set_arg_type, set_gc_handle, set_receiver_should_free} from "./marshal"; -import {marshal_array_to_cs, marshal_array_to_cs_impl, marshal_bool_to_cs, marshal_exception_to_cs, marshal_intptr_to_cs, marshal_string_to_cs} from "./marshal-to-cs"; -import {marshal_int32_to_js, end_marshal_task_to_js, marshal_string_to_js, begin_marshal_task_to_js, marshal_exception_to_js} from "./marshal-to-js"; -import {do_not_force_dispose, is_gcv_handle} from "./gc-handles"; -import {assert_c_interop, assert_js_interop} from "./invoke-js"; -import {monoThreadInfo, mono_wasm_main_thread_ptr} from "./pthreads"; -import {_zero_region, copyBytes} from "./memory"; -import {stringToUTF8Ptr} from "./strings"; -import {mono_log_debug} from "./logging"; +import { GCHandle, GCHandleNull, JSMarshalerArguments, JSThreadInteropMode, MarshalerToCs, MarshalerToJs, MarshalerType, MonoMethod, PThreadPtr } from "./types/internal"; +import cwraps, { threads_c_functions as twraps } from "./cwraps"; +import { runtimeHelpers, Module, loaderHelpers, mono_assert } from "./globals"; +import { JavaScriptMarshalerArgSize, alloc_stack_frame, get_arg, get_arg_gc_handle, is_args_exception, set_arg_i32, set_arg_intptr, set_arg_type, set_gc_handle, set_receiver_should_free } from "./marshal"; +import { marshal_array_to_cs, marshal_array_to_cs_impl, marshal_bool_to_cs, marshal_exception_to_cs, marshal_intptr_to_cs, marshal_string_to_cs } from "./marshal-to-cs"; +import { marshal_int32_to_js, end_marshal_task_to_js, marshal_string_to_js, begin_marshal_task_to_js, marshal_exception_to_js } from "./marshal-to-js"; +import { do_not_force_dispose, is_gcv_handle } from "./gc-handles"; +import { assert_c_interop, assert_js_interop } from "./invoke-js"; +import { monoThreadInfo, mono_wasm_main_thread_ptr } from "./pthreads"; +import { _zero_region, copyBytes } from "./memory"; +import { stringToUTF8Ptr } from "./strings"; +import { mono_log_debug } from "./logging"; const managedExports: ManagedExports = {} as any; -export function init_managed_exports (): void { +export function init_managed_exports(): void { const exports_fqn_asm = "System.Runtime.InteropServices.JavaScript"; // TODO https://github.com/dotnet/runtime/issues/98366 runtimeHelpers.runtime_interop_module = cwraps.mono_wasm_assembly_load(exports_fqn_asm); @@ -44,7 +44,7 @@ export function init_managed_exports (): void { } // the marshaled signature is: Task? CallEntrypoint(char* mainAssemblyName, string[] args) -export function call_entry_point (main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { +export function call_entry_point(main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -79,7 +79,7 @@ export function call_entry_point (main_assembly_name: string, program_args: stri } // the marshaled signature is: void LoadSatelliteAssembly(byte[] dll) -export function load_satellite_assembly (dll: Uint8Array): void { +export function load_satellite_assembly(dll: Uint8Array): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -95,7 +95,7 @@ export function load_satellite_assembly (dll: Uint8Array): void { } // the marshaled signature is: void LoadLazyAssembly(byte[] dll, byte[] pdb) -export function load_lazy_assembly (dll: Uint8Array, pdb: Uint8Array | null): void { +export function load_lazy_assembly(dll: Uint8Array, pdb: Uint8Array | null): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -114,7 +114,7 @@ export function load_lazy_assembly (dll: Uint8Array, pdb: Uint8Array | null): vo } // the marshaled signature is: void ReleaseJSOwnedObjectByGCHandle(GCHandle gcHandle) -export function release_js_owned_object_by_gc_handle (gc_handle: GCHandle) { +export function release_js_owned_object_by_gc_handle(gc_handle: GCHandle) { mono_assert(gc_handle, "Must be valid gc_handle"); loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); @@ -137,7 +137,7 @@ export function release_js_owned_object_by_gc_handle (gc_handle: GCHandle) { } // the marshaled signature is: void CompleteTask(GCHandle holder, Exception? exceptionResult, T? result) -export function complete_task (holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { +export function complete_task(holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -162,7 +162,7 @@ export function complete_task (holder_gc_handle: GCHandle, error?: any, data?: a } // the marshaled signature is: TRes? CallDelegate(GCHandle callback, T1? arg1, T2? arg2, T3? arg3) -export function call_delegate (callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { +export function call_delegate(callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { if (runtimeHelpers.config.jsThreadInteropMode == JSThreadInteropMode.NoSyncJSInterop) { @@ -206,7 +206,7 @@ export function call_delegate (callback_gc_handle: GCHandle, arg1_js: any, arg2_ } // the marshaled signature is: string GetManagedStackTrace(GCHandle exception) -export function get_managed_stack_trace (exception_gc_handle: GCHandle) { +export function get_managed_stack_trace(exception_gc_handle: GCHandle) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -226,7 +226,7 @@ export function get_managed_stack_trace (exception_gc_handle: GCHandle) { } // GCHandle InstallMainSynchronizationContext(nint jsNativeTID, JSThreadBlockingMode jsThreadBlockingMode, JSThreadInteropMode jsThreadInteropMode, MainThreadingMode mainThreadingMode) -export function install_main_synchronization_context (jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { +export function install_main_synchronization_context(jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { if (!WasmEnableThreads) return GCHandleNull; assert_c_interop(); @@ -259,7 +259,7 @@ export function install_main_synchronization_context (jsThreadBlockingMode: numb } } -export function invoke_async_jsexport (managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { +export function invoke_async_jsexport(managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { assert_js_interop(); if (!WasmEnableThreads || runtimeHelpers.isManagedRunningOnCurrentThread) { cwraps.mono_wasm_invoke_jsexport(method, args as any); @@ -276,7 +276,7 @@ export function invoke_async_jsexport (managedTID: PThreadPtr, method: MonoMetho } } -export function invoke_sync_jsexport (method: MonoMethod, args: JSMarshalerArguments): void { +export function invoke_sync_jsexport(method: MonoMethod, args: JSMarshalerArguments): void { assert_js_interop(); if (!WasmEnableThreads) { cwraps.mono_wasm_invoke_jsexport(method, args as any); @@ -301,7 +301,7 @@ export function invoke_sync_jsexport (method: MonoMethod, args: JSMarshalerArgum } // the marshaled signature is: Task BindAssemblyExports(string assemblyName) -export function bind_assembly_exports (assemblyName: string): Promise { +export function bind_assembly_exports(assemblyName: string): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -329,7 +329,7 @@ export function bind_assembly_exports (assemblyName: string): Promise { } -function get_method (method_name: string): MonoMethod { +function get_method(method_name: string): MonoMethod { // TODO https://github.com/dotnet/runtime/issues/98366 const res = cwraps.mono_wasm_assembly_find_method(runtimeHelpers.runtime_interop_exports_class, method_name, -1); if (!res) diff --git a/src/mono/browser/runtime/marshal-to-cs.ts b/src/mono/browser/runtime/marshal-to-cs.ts index 03247fe0f42e2b..6254e3f20b4844 100644 --- a/src/mono/browser/runtime/marshal-to-cs.ts +++ b/src/mono/browser/runtime/marshal-to-cs.ts @@ -5,10 +5,10 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; import WasmEnableJsInteropByValue from "consts:wasmEnableJsInteropByValue"; -import {PromiseHolder, isThenable} from "./cancelable-promise"; +import { PromiseHolder, isThenable } from "./cancelable-promise"; import cwraps from "./cwraps"; -import {alloc_gcv_handle, assert_not_disposed, cs_owned_js_handle_symbol, js_owned_gc_handle_symbol, mono_wasm_get_js_handle, setup_managed_proxy} from "./gc-handles"; -import {Module, mono_assert, runtimeHelpers} from "./globals"; +import { alloc_gcv_handle, assert_not_disposed, cs_owned_js_handle_symbol, js_owned_gc_handle_symbol, mono_wasm_get_js_handle, setup_managed_proxy } from "./gc-handles"; +import { Module, mono_assert, runtimeHelpers } from "./globals"; import { ManagedError, set_gc_handle, set_js_handle, set_arg_type, set_arg_i32, set_arg_f64, set_arg_i52, set_arg_f32, set_arg_i16, set_arg_u8, set_arg_bool, set_arg_date, @@ -17,16 +17,16 @@ import { get_string_root, Span, ArraySegment, MemoryViewType, get_signature_arg3_type, set_arg_i64_big, set_arg_intptr, set_arg_element_type, ManagedObject, JavaScriptMarshalerArgSize, proxy_debug_symbol, get_arg_gc_handle, get_arg_type, set_arg_proxy_context, get_arg_intptr } from "./marshal"; -import {get_marshaler_to_js_by_type} from "./marshal-to-js"; -import {_zero_region, localHeapViewF64, localHeapViewI32, localHeapViewU8} from "./memory"; -import {stringToMonoStringRoot, stringToUTF16} from "./strings"; -import {JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToCs, MarshalerType} from "./types/internal"; -import {TypedArray} from "./types/emscripten"; -import {gc_locked} from "./gc-lock"; +import { get_marshaler_to_js_by_type } from "./marshal-to-js"; +import { _zero_region, localHeapViewF64, localHeapViewI32, localHeapViewU8 } from "./memory"; +import { stringToMonoStringRoot, stringToUTF16 } from "./strings"; +import { JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToCs, MarshalerType } from "./types/internal"; +import { TypedArray } from "./types/emscripten"; +import { gc_locked } from "./gc-lock"; export const jsinteropDoc = "For more information see https://aka.ms/dotnet-wasm-jsinterop"; -export function initialize_marshalers_to_cs (): void { +export function initialize_marshalers_to_cs(): void { if (js_to_cs_marshalers.size == 0) { js_to_cs_marshalers.set(MarshalerType.Array, marshal_array_to_cs); js_to_cs_marshalers.set(MarshalerType.Span, _marshal_span_to_cs); @@ -60,7 +60,7 @@ export function initialize_marshalers_to_cs (): void { } } -export function bind_arg_marshal_to_cs (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { +export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -87,7 +87,7 @@ export function bind_arg_marshal_to_cs (sig: JSMarshalerType, marshaler_type: Ma }; } -export function get_marshaler_to_cs_by_type (marshaler_type: MarshalerType): MarshalerToCs | undefined { +export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): MarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -96,7 +96,7 @@ export function get_marshaler_to_cs_by_type (marshaler_type: MarshalerType): Mar return converter; } -export function marshal_bool_to_cs (arg: JSMarshalerArgument, value: any): void { +export function marshal_bool_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -105,7 +105,7 @@ export function marshal_bool_to_cs (arg: JSMarshalerArgument, value: any): void } } -function _marshal_byte_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_byte_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -114,7 +114,7 @@ function _marshal_byte_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_char_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_char_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -123,7 +123,7 @@ function _marshal_char_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int16_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_int16_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -132,7 +132,7 @@ function _marshal_int16_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int32_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_int32_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -141,7 +141,7 @@ function _marshal_int32_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int52_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_int52_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -150,7 +150,7 @@ function _marshal_int52_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_bigint64_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_bigint64_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -159,7 +159,7 @@ function _marshal_bigint64_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_double_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_double_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -168,7 +168,7 @@ function _marshal_double_to_cs (arg: JSMarshalerArgument, value: any): void { } } -function _marshal_float_to_cs (arg: JSMarshalerArgument, value: any): void { +function _marshal_float_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -177,7 +177,7 @@ function _marshal_float_to_cs (arg: JSMarshalerArgument, value: any): void { } } -export function marshal_intptr_to_cs (arg: JSMarshalerArgument, value: any): void { +export function marshal_intptr_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -186,7 +186,7 @@ export function marshal_intptr_to_cs (arg: JSMarshalerArgument, value: any): voi } } -function _marshal_date_time_to_cs (arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_to_cs(arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -196,7 +196,7 @@ function _marshal_date_time_to_cs (arg: JSMarshalerArgument, value: Date): void } } -function _marshal_date_time_offset_to_cs (arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_offset_to_cs(arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -206,7 +206,7 @@ function _marshal_date_time_offset_to_cs (arg: JSMarshalerArgument, value: Date) } } -export function marshal_string_to_cs (arg: JSMarshalerArgument, value: string) { +export function marshal_string_to_cs(arg: JSMarshalerArgument, value: string) { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -216,7 +216,7 @@ export function marshal_string_to_cs (arg: JSMarshalerArgument, value: string) { } } -function _marshal_string_to_cs_impl (arg: JSMarshalerArgument, value: string) { +function _marshal_string_to_cs_impl(arg: JSMarshalerArgument, value: string) { if (WasmEnableJsInteropByValue) { const bufferLen = value.length * 2; const buffer = Module._malloc(bufferLen);// together with Marshal.FreeHGlobal @@ -233,11 +233,11 @@ function _marshal_string_to_cs_impl (arg: JSMarshalerArgument, value: string) { } } -function _marshal_null_to_cs (arg: JSMarshalerArgument) { +function _marshal_null_to_cs(arg: JSMarshalerArgument) { set_arg_type(arg, MarshalerType.None); } -function _marshal_function_to_cs (arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { +function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); return; @@ -245,7 +245,7 @@ function _marshal_function_to_cs (arg: JSMarshalerArgument, value: Function, _?: mono_check(value && value instanceof Function, "Value is not a Function"); // TODO: we could try to cache value -> existing JSHandle - const wrapper: any = function delegate_wrapper (args: JSMarshalerArguments) { + const wrapper: any = function delegate_wrapper(args: JSMarshalerArguments) { const exc = get_arg(args, 0); const res = get_arg(args, 1); const arg1 = get_arg(args, 2); @@ -295,7 +295,7 @@ function _marshal_function_to_cs (arg: JSMarshalerArgument, value: Function, _?: } -function _marshal_task_to_cs (arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { +function _marshal_task_to_cs(arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { const handleIsPreallocated = get_arg_type(arg) == MarshalerType.TaskPreCreated; if (value === null || value === undefined) { if (WasmEnableThreads && handleIsPreallocated) { @@ -329,7 +329,7 @@ function _marshal_task_to_cs (arg: JSMarshalerArgument, value: Promise, _?: value.then(data => holder.resolve(data), reason => holder.reject(reason)); } -export function marshal_exception_to_cs (arg: JSMarshalerArgument, value: any): void { +export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else if (value instanceof ManagedError) { @@ -355,7 +355,7 @@ export function marshal_exception_to_cs (arg: JSMarshalerArgument, value: any): } } -export function marshal_js_object_to_cs (arg: JSMarshalerArgument, value: any): void { +export function marshal_js_object_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); @@ -373,7 +373,7 @@ export function marshal_js_object_to_cs (arg: JSMarshalerArgument, value: any): } } -export function marshal_cs_object_to_cs (arg: JSMarshalerArgument, value: any): void { +export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); @@ -445,12 +445,12 @@ export function marshal_cs_object_to_cs (arg: JSMarshalerArgument, value: any): } } -export function marshal_array_to_cs (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { +export function marshal_array_to_cs(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); marshal_array_to_cs_impl(arg, value, element_type); } -export function marshal_array_to_cs_impl (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { +export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -510,7 +510,7 @@ export function marshal_array_to_cs_impl (arg: JSMarshalerArgument, value: Array } } -function _marshal_span_to_cs (arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { +function _marshal_span_to_cs(arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); mono_check(!value.isDisposed, "ObjectDisposedException"); checkViewType(element_type, value._viewType); @@ -521,7 +521,7 @@ function _marshal_span_to_cs (arg: JSMarshalerArgument, value: Span, element_typ } // this only supports round-trip -function _marshal_array_segment_to_cs (arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { +function _marshal_array_segment_to_cs(arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); const gc_handle = assert_not_disposed(value); mono_assert(gc_handle, "Only roundtrip of ArraySegment instance created by C#"); @@ -532,7 +532,7 @@ function _marshal_array_segment_to_cs (arg: JSMarshalerArgument, value: ArraySeg set_gc_handle(arg, gc_handle); } -function checkViewType (element_type: MarshalerType, viewType: MemoryViewType) { +function checkViewType(element_type: MarshalerType, viewType: MemoryViewType) { if (element_type == MarshalerType.Byte) { mono_check(MemoryViewType.Byte == viewType, "Expected MemoryViewType.Byte"); } else if (element_type == MarshalerType.Int32) { diff --git a/src/mono/browser/runtime/marshal-to-js.ts b/src/mono/browser/runtime/marshal-to-js.ts index c58713520315e7..fc965f81c4978b 100644 --- a/src/mono/browser/runtime/marshal-to-js.ts +++ b/src/mono/browser/runtime/marshal-to-js.ts @@ -6,8 +6,8 @@ import BuildConfiguration from "consts:configuration"; import WasmEnableJsInteropByValue from "consts:wasmEnableJsInteropByValue"; import cwraps from "./cwraps"; -import {_lookup_js_owned_object, mono_wasm_get_js_handle, mono_wasm_get_jsobj_from_js_handle, mono_wasm_release_cs_owned_object, register_with_jsv_handle, setup_managed_proxy, teardown_managed_proxy} from "./gc-handles"; -import {Module, loaderHelpers, mono_assert} from "./globals"; +import { _lookup_js_owned_object, mono_wasm_get_js_handle, mono_wasm_get_jsobj_from_js_handle, mono_wasm_release_cs_owned_object, register_with_jsv_handle, setup_managed_proxy, teardown_managed_proxy } from "./gc-handles"; +import { Module, loaderHelpers, mono_assert } from "./globals"; import { ManagedObject, ManagedError, get_arg_gc_handle, get_arg_js_handle, get_arg_type, get_arg_i32, get_arg_f64, get_arg_i52, get_arg_i16, get_arg_u8, get_arg_f32, @@ -16,17 +16,17 @@ import { get_signature_res_type, get_arg_u16, array_element_size, get_string_root, ArraySegment, Span, MemoryViewType, get_signature_arg3_type, get_arg_i64_big, get_arg_intptr, get_arg_element_type, JavaScriptMarshalerArgSize, proxy_debug_symbol, set_js_handle, is_receiver_should_free } from "./marshal"; -import {monoStringToString, utf16ToString} from "./strings"; -import {GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToJs, MarshalerType, JSHandle} from "./types/internal"; -import {TypedArray} from "./types/emscripten"; -import {get_marshaler_to_cs_by_type, jsinteropDoc, marshal_exception_to_cs} from "./marshal-to-cs"; -import {localHeapViewF64, localHeapViewI32, localHeapViewU8} from "./memory"; -import {call_delegate} from "./managed-exports"; -import {gc_locked} from "./gc-lock"; -import {mono_log_debug} from "./logging"; -import {invoke_later_when_on_ui_thread_async} from "./invoke-js"; - -export function initialize_marshalers_to_js (): void { +import { monoStringToString, utf16ToString } from "./strings"; +import { GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToJs, MarshalerType, JSHandle } from "./types/internal"; +import { TypedArray } from "./types/emscripten"; +import { get_marshaler_to_cs_by_type, jsinteropDoc, marshal_exception_to_cs } from "./marshal-to-cs"; +import { localHeapViewF64, localHeapViewI32, localHeapViewU8 } from "./memory"; +import { call_delegate } from "./managed-exports"; +import { gc_locked } from "./gc-lock"; +import { mono_log_debug } from "./logging"; +import { invoke_later_when_on_ui_thread_async } from "./invoke-js"; + +export function initialize_marshalers_to_js(): void { if (cs_to_js_marshalers.size == 0) { cs_to_js_marshalers.set(MarshalerType.Array, _marshal_array_to_js); cs_to_js_marshalers.set(MarshalerType.Span, _marshal_span_to_js); @@ -61,7 +61,7 @@ export function initialize_marshalers_to_js (): void { } } -export function bind_arg_marshal_to_js (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { +export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -89,7 +89,7 @@ export function bind_arg_marshal_to_js (sig: JSMarshalerType, marshaler_type: Ma }; } -export function get_marshaler_to_js_by_type (marshaler_type: MarshalerType): MarshalerToJs | undefined { +export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): MarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -98,7 +98,7 @@ export function get_marshaler_to_js_by_type (marshaler_type: MarshalerType): Mar return converter; } -function _marshal_bool_to_js (arg: JSMarshalerArgument): boolean | null { +function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -106,7 +106,7 @@ function _marshal_bool_to_js (arg: JSMarshalerArgument): boolean | null { return get_arg_bool(arg); } -function _marshal_byte_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_byte_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -114,7 +114,7 @@ function _marshal_byte_to_js (arg: JSMarshalerArgument): number | null { return get_arg_u8(arg); } -function _marshal_char_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_char_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -122,7 +122,7 @@ function _marshal_char_to_js (arg: JSMarshalerArgument): number | null { return get_arg_u16(arg); } -function _marshal_int16_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_int16_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -130,7 +130,7 @@ function _marshal_int16_to_js (arg: JSMarshalerArgument): number | null { return get_arg_i16(arg); } -export function marshal_int32_to_js (arg: JSMarshalerArgument): number | null { +export function marshal_int32_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -138,7 +138,7 @@ export function marshal_int32_to_js (arg: JSMarshalerArgument): number | null { return get_arg_i32(arg); } -function _marshal_int52_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_int52_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -146,7 +146,7 @@ function _marshal_int52_to_js (arg: JSMarshalerArgument): number | null { return get_arg_i52(arg); } -function _marshal_bigint64_to_js (arg: JSMarshalerArgument): bigint | null { +function _marshal_bigint64_to_js(arg: JSMarshalerArgument): bigint | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -154,7 +154,7 @@ function _marshal_bigint64_to_js (arg: JSMarshalerArgument): bigint | null { return get_arg_i64_big(arg); } -function _marshal_float_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_float_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -162,7 +162,7 @@ function _marshal_float_to_js (arg: JSMarshalerArgument): number | null { return get_arg_f32(arg); } -function _marshal_double_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_double_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -170,7 +170,7 @@ function _marshal_double_to_js (arg: JSMarshalerArgument): number | null { return get_arg_f64(arg); } -function _marshal_intptr_to_js (arg: JSMarshalerArgument): number | null { +function _marshal_intptr_to_js(arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -178,11 +178,11 @@ function _marshal_intptr_to_js (arg: JSMarshalerArgument): number | null { return get_arg_intptr(arg); } -function _marshal_null_to_js (): null { +function _marshal_null_to_js(): null { return null; } -function _marshal_datetime_to_js (arg: JSMarshalerArgument): Date | null { +function _marshal_datetime_to_js(arg: JSMarshalerArgument): Date | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -191,7 +191,7 @@ function _marshal_datetime_to_js (arg: JSMarshalerArgument): Date | null { } // NOTE: at the moment, this can't dispatch async calls (with Task/Promise return type). Therefore we don't have to worry about pre-created Task. -function _marshal_delegate_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { +function _marshal_delegate_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -223,11 +223,11 @@ function _marshal_delegate_to_js (arg: JSMarshalerArgument, _?: MarshalerType, r } export class TaskHolder { - constructor (public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { + constructor(public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { } } -export function marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { const type = get_arg_type(arg); // this path is used only when Task is passed as argument to JSImport and virtual JSHandle would be used mono_assert(type != MarshalerType.TaskPreCreated, "Unexpected Task type: TaskPreCreated"); @@ -248,7 +248,7 @@ export function marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, return holder.promise; } -export function begin_marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function begin_marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { // this path is used when Task is returned from JSExport/call_entry_point const holder = create_task_holder(res_converter); const js_handle = mono_wasm_get_js_handle(holder); @@ -260,7 +260,7 @@ export function begin_marshal_task_to_js (arg: JSMarshalerArgument, _?: Marshale return holder.promise; } -export function end_marshal_task_to_js (args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { +export function end_marshal_task_to_js(args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { // this path is used when Task is returned from JSExport/call_entry_point const res = get_arg(args, 1); const type = get_arg_type(res); @@ -283,7 +283,7 @@ export function end_marshal_task_to_js (args: JSMarshalerArguments, res_converte return promise; } -function try_marshal_sync_task_to_js (arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { +function try_marshal_sync_task_to_js(arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { if (type === MarshalerType.None) { return null; } @@ -309,8 +309,8 @@ function try_marshal_sync_task_to_js (arg: JSMarshalerArgument, type: MarshalerT return false; } -function create_task_holder (res_converter?: MarshalerToJs) { - const {promise, promise_control} = loaderHelpers.createPromiseController(); +function create_task_holder(res_converter?: MarshalerToJs) { + const { promise, promise_control } = loaderHelpers.createPromiseController(); const holder = new TaskHolder(promise, (type, js_handle, argInner) => { if (type === MarshalerType.TaskRejected) { const reason = marshal_exception_to_js(argInner); @@ -337,11 +337,11 @@ function create_task_holder (res_converter?: MarshalerToJs) { return holder; } -export function mono_wasm_resolve_or_reject_promise (args: JSMarshalerArguments): void { +export function mono_wasm_resolve_or_reject_promise(args: JSMarshalerArguments): void { // rejection/resolution should not arrive earlier than the promise created by marshaling in mono_wasm_invoke_jsimport_MT invoke_later_when_on_ui_thread_async(() => mono_wasm_resolve_or_reject_promise_impl(args)); } -export function mono_wasm_resolve_or_reject_promise_impl (args: JSMarshalerArguments): void { +export function mono_wasm_resolve_or_reject_promise_impl(args: JSMarshalerArguments): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution/rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -378,7 +378,7 @@ export function mono_wasm_resolve_or_reject_promise_impl (args: JSMarshalerArgum } } -export function marshal_string_to_js (arg: JSMarshalerArgument): string | null { +export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -400,7 +400,7 @@ export function marshal_string_to_js (arg: JSMarshalerArgument): string | null { } } -export function marshal_exception_to_js (arg: JSMarshalerArgument): Error | null { +export function marshal_exception_to_js(arg: JSMarshalerArgument): Error | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -428,7 +428,7 @@ export function marshal_exception_to_js (arg: JSMarshalerArgument): Error | null return result; } -function _marshal_js_object_to_js (arg: JSMarshalerArgument): any { +function _marshal_js_object_to_js(arg: JSMarshalerArgument): any { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -439,7 +439,7 @@ function _marshal_js_object_to_js (arg: JSMarshalerArgument): any { return js_obj; } -function _marshal_cs_object_to_js (arg: JSMarshalerArgument): any { +function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { const marshaler_type = get_arg_type(arg); if (marshaler_type == MarshalerType.None) { return null; @@ -482,12 +482,12 @@ function _marshal_cs_object_to_js (arg: JSMarshalerArgument): any { return converter(arg); } -function _marshal_array_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { mono_assert(!!element_type, "Expected valid element_type parameter"); return _marshal_array_to_js_impl(arg, element_type); } -function _marshal_array_to_js_impl (arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -539,7 +539,7 @@ function _marshal_array_to_js_impl (arg: JSMarshalerArgument, element_type: Mars return result; } -function _marshal_span_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Span { +function _marshal_span_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Span { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); @@ -557,7 +557,7 @@ function _marshal_span_to_js (arg: JSMarshalerArgument, element_type?: Marshaler return result; } -function _marshal_array_segment_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { +function _marshal_array_segment_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); diff --git a/src/mono/browser/runtime/marshal.ts b/src/mono/browser/runtime/marshal.ts index 23aab97b1510ba..c2afc7ae6a57c7 100644 --- a/src/mono/browser/runtime/marshal.ts +++ b/src/mono/browser/runtime/marshal.ts @@ -3,14 +3,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {js_owned_gc_handle_symbol, teardown_managed_proxy} from "./gc-handles"; -import {Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {getF32, getF64, getI16, getI32, getI64Big, getU16, getU32, getU8, setF32, setF64, setI16, setI32, setI64Big, setU16, setU32, setU8, localHeapViewF64, localHeapViewI32, localHeapViewU8, _zero_region, getB32, setB32, forceThreadMemoryViewRefresh} from "./memory"; -import {mono_wasm_new_external_root} from "./roots"; -import {GCHandle, JSHandle, MonoObject, MonoString, GCHandleNull, JSMarshalerArguments, JSFunctionSignature, JSMarshalerType, JSMarshalerArgument, MarshalerToJs, MarshalerToCs, WasmRoot, MarshalerType, PThreadPtr, PThreadPtrNull, VoidPtrNull} from "./types/internal"; -import {TypedArray, VoidPtr} from "./types/emscripten"; -import {utf16ToString} from "./strings"; -import {get_managed_stack_trace} from "./managed-exports"; +import { js_owned_gc_handle_symbol, teardown_managed_proxy } from "./gc-handles"; +import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { getF32, getF64, getI16, getI32, getI64Big, getU16, getU32, getU8, setF32, setF64, setI16, setI32, setI64Big, setU16, setU32, setU8, localHeapViewF64, localHeapViewI32, localHeapViewU8, _zero_region, getB32, setB32, forceThreadMemoryViewRefresh } from "./memory"; +import { mono_wasm_new_external_root } from "./roots"; +import { GCHandle, JSHandle, MonoObject, MonoString, GCHandleNull, JSMarshalerArguments, JSFunctionSignature, JSMarshalerType, JSMarshalerArgument, MarshalerToJs, MarshalerToCs, WasmRoot, MarshalerType, PThreadPtr, PThreadPtrNull, VoidPtrNull } from "./types/internal"; +import { TypedArray, VoidPtr } from "./types/emscripten"; +import { utf16ToString } from "./strings"; +import { get_managed_stack_trace } from "./managed-exports"; export const cs_to_js_marshalers = new Map(); export const js_to_cs_marshalers = new Map(); @@ -64,7 +64,7 @@ const enum JSBindingHeaderOffsets { Result = 64, } -export function alloc_stack_frame (size: number): JSMarshalerArguments { +export function alloc_stack_frame(size: number): JSMarshalerArguments { if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); } @@ -75,41 +75,41 @@ export function alloc_stack_frame (size: number): JSMarshalerArguments { return args; } -export function get_arg (args: JSMarshalerArguments, index: number): JSMarshalerArgument { +export function get_arg(args: JSMarshalerArguments, index: number): JSMarshalerArgument { mono_assert(args, "Null args"); return args + (index * JavaScriptMarshalerArgSize); } -export function is_args_exception (args: JSMarshalerArguments): boolean { +export function is_args_exception(args: JSMarshalerArguments): boolean { mono_assert(args, "Null args"); const exceptionType = get_arg_type(args); return exceptionType !== MarshalerType.None; } -export function is_receiver_should_free (args: JSMarshalerArguments): boolean { +export function is_receiver_should_free(args: JSMarshalerArguments): boolean { if (!WasmEnableThreads) return false; mono_assert(args, "Null args"); return getB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree); } -export function get_sync_done_semaphore_ptr (args: JSMarshalerArguments): VoidPtr { +export function get_sync_done_semaphore_ptr(args: JSMarshalerArguments): VoidPtr { if (!WasmEnableThreads) return VoidPtrNull; mono_assert(args, "Null args"); return getI32(args + JSMarshalerArgumentOffsets.SyncDoneSemaphorePtr) as any; } -export function get_caller_native_tid (args: JSMarshalerArguments): PThreadPtr { +export function get_caller_native_tid(args: JSMarshalerArguments): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; mono_assert(args, "Null args"); return getI32(args + JSMarshalerArgumentOffsets.CallerNativeTID) as any; } -export function set_receiver_should_free (args: JSMarshalerArguments): void { +export function set_receiver_should_free(args: JSMarshalerArguments): void { mono_assert(args, "Null args"); setB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree, true); } -export function set_args_context (args: JSMarshalerArguments): void { +export function set_args_context(args: JSMarshalerArguments): void { if (!WasmEnableThreads) return; mono_assert(args, "Null args"); const exc = get_arg(args, 0); @@ -118,52 +118,52 @@ export function set_args_context (args: JSMarshalerArguments): void { set_arg_proxy_context(res); } -export function get_sig (signature: JSFunctionSignature, index: number): JSMarshalerType { +export function get_sig(signature: JSFunctionSignature, index: number): JSMarshalerType { mono_assert(signature, "Null signatures"); return signature + (index * JSMarshalerTypeSize) + JSMarshalerSignatureHeaderSize; } -export function get_signature_type (sig: JSMarshalerType): MarshalerType { +export function get_signature_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Type); } -export function get_signature_res_type (sig: JSMarshalerType): MarshalerType { +export function get_signature_res_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.ResultMarshalerType); } -export function get_signature_arg1_type (sig: JSMarshalerType): MarshalerType { +export function get_signature_arg1_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg1MarshalerType); } -export function get_signature_arg2_type (sig: JSMarshalerType): MarshalerType { +export function get_signature_arg2_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_arg3_type (sig: JSMarshalerType): MarshalerType { +export function get_signature_arg3_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_argument_count (signature: JSFunctionSignature): number { +export function get_signature_argument_count(signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ArgumentCount); } -export function get_signature_version (signature: JSFunctionSignature): number { +export function get_signature_version(signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.Version); } -export function get_signature_handle (signature: JSFunctionSignature): number { +export function get_signature_handle(signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ImportHandle); } -export function get_signature_function_name (signature: JSFunctionSignature): string | null { +export function get_signature_function_name(signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const functionNameOffset = getI32(signature + JSBindingHeaderOffsets.FunctionNameOffset); if (functionNameOffset === 0) return null; @@ -172,7 +172,7 @@ export function get_signature_function_name (signature: JSFunctionSignature): st return utf16ToString(signature + functionNameOffset, signature + functionNameOffset + functionNameLength); } -export function get_signature_module_name (signature: JSFunctionSignature): string | null { +export function get_signature_module_name(signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const moduleNameOffset = getI32(signature + JSBindingHeaderOffsets.ModuleNameOffset); if (moduleNameOffset === 0) return null; @@ -180,195 +180,195 @@ export function get_signature_module_name (signature: JSFunctionSignature): stri return utf16ToString(signature + moduleNameOffset, signature + moduleNameOffset + moduleNameLength); } -export function get_sig_type (sig: JSMarshalerType): MarshalerType { +export function get_sig_type(sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null signatures"); return getU8(sig); } -export function get_arg_type (arg: JSMarshalerArgument): MarshalerType { +export function get_arg_type(arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.Type); return type; } -export function get_arg_element_type (arg: JSMarshalerArgument): MarshalerType { +export function get_arg_element_type(arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.ElementType); return type; } -export function set_arg_type (arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_type(arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.Type, type); } -export function set_arg_element_type (arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_element_type(arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.ElementType, type); } -export function get_arg_bool (arg: JSMarshalerArgument): boolean { +export function get_arg_bool(arg: JSMarshalerArgument): boolean { mono_assert(arg, "Null arg"); return !!getU8(arg); } -export function get_arg_u8 (arg: JSMarshalerArgument): number { +export function get_arg_u8(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU8(arg); } -export function get_arg_u16 (arg: JSMarshalerArgument): number { +export function get_arg_u16(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU16(arg); } -export function get_arg_i16 (arg: JSMarshalerArgument): number { +export function get_arg_i16(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI16(arg); } -export function get_arg_i32 (arg: JSMarshalerArgument): number { +export function get_arg_i32(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_intptr (arg: JSMarshalerArgument): number { +export function get_arg_intptr(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_i52 (arg: JSMarshalerArgument): number { +export function get_arg_i52(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); // we know that the range check and conversion from Int64 was be done on C# side return getF64(arg); } -export function get_arg_i64_big (arg: JSMarshalerArgument): bigint { +export function get_arg_i64_big(arg: JSMarshalerArgument): bigint { mono_assert(arg, "Null arg"); return getI64Big(arg); } -export function get_arg_date (arg: JSMarshalerArgument): Date { +export function get_arg_date(arg: JSMarshalerArgument): Date { mono_assert(arg, "Null arg"); const unixTime = getF64(arg); const date = new Date(unixTime); return date; } -export function get_arg_f32 (arg: JSMarshalerArgument): number { +export function get_arg_f32(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF32(arg); } -export function get_arg_f64 (arg: JSMarshalerArgument): number { +export function get_arg_f64(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF64(arg); } -export function set_arg_bool (arg: JSMarshalerArgument, value: boolean): void { +export function set_arg_bool(arg: JSMarshalerArgument, value: boolean): void { mono_assert(arg, "Null arg"); mono_check(typeof value === "boolean", () => `Value is not a Boolean: ${value} (${typeof (value)})`); setB32(arg, value ? 1 : 0); } -export function set_arg_u8 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_u8(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU8(arg, value); } -export function set_arg_u16 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_u16(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU16(arg, value); } -export function set_arg_i16 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_i16(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI16(arg, value); } -export function set_arg_i32 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_i32(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_intptr (arg: JSMarshalerArgument, value: VoidPtr): void { +export function set_arg_intptr(arg: JSMarshalerArgument, value: VoidPtr): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_i52 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_i52(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); // we know that conversion to Int64 would be done on C# side setF64(arg, value); } -export function set_arg_i64_big (arg: JSMarshalerArgument, value: bigint): void { +export function set_arg_i64_big(arg: JSMarshalerArgument, value: bigint): void { mono_assert(arg, "Null arg"); setI64Big(arg, value); } -export function set_arg_date (arg: JSMarshalerArgument, value: Date): void { +export function set_arg_date(arg: JSMarshalerArgument, value: Date): void { mono_assert(arg, "Null arg"); // getTime() is always UTC const unixTime = value.getTime(); setF64(arg, unixTime); } -export function set_arg_f64 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_f64(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF64(arg, value); } -export function set_arg_f32 (arg: JSMarshalerArgument, value: number): void { +export function set_arg_f32(arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF32(arg, value); } -export function get_arg_js_handle (arg: JSMarshalerArgument): JSHandle { +export function get_arg_js_handle(arg: JSMarshalerArgument): JSHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.JSHandle); } -export function set_arg_proxy_context (arg: JSMarshalerArgument): void { +export function set_arg_proxy_context(arg: JSMarshalerArgument): void { if (!WasmEnableThreads) return; mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.ContextHandle, runtimeHelpers.proxyGCHandle); } -export function set_js_handle (arg: JSMarshalerArgument, jsHandle: JSHandle): void { +export function set_js_handle(arg: JSMarshalerArgument, jsHandle: JSHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.JSHandle, jsHandle); set_arg_proxy_context(arg); } -export function get_arg_gc_handle (arg: JSMarshalerArgument): GCHandle { +export function get_arg_gc_handle(arg: JSMarshalerArgument): GCHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.GCHandle); } -export function set_gc_handle (arg: JSMarshalerArgument, gcHandle: GCHandle): void { +export function set_gc_handle(arg: JSMarshalerArgument, gcHandle: GCHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.GCHandle, gcHandle); set_arg_proxy_context(arg); } -export function get_string_root (arg: JSMarshalerArgument): WasmRoot { +export function get_string_root(arg: JSMarshalerArgument): WasmRoot { mono_assert(arg, "Null arg"); return mono_wasm_new_external_root(arg); } -export function get_arg_length (arg: JSMarshalerArgument): number { +export function get_arg_length(arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.Length); } -export function set_arg_length (arg: JSMarshalerArgument, size: number): void { +export function set_arg_length(arg: JSMarshalerArgument, size: number): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.Length, size); } -export function set_root (arg: JSMarshalerArgument, root: WasmRoot): void { +export function set_root(arg: JSMarshalerArgument, root: WasmRoot): void { mono_assert(arg, "Null arg"); setU32(arg + 0, root.get_address()); } @@ -379,15 +379,15 @@ export interface IDisposable { } export class ManagedObject implements IDisposable { - dispose (): void { + dispose(): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed (): boolean { + get isDisposed(): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } - toString (): string { + toString(): string { return `CsObject(gc_handle: ${(this)[js_owned_gc_handle_symbol]})`; } } @@ -395,7 +395,7 @@ export class ManagedObject implements IDisposable { export class ManagedError extends Error implements IDisposable { private superStack: any; private managed_stack: any; - constructor (message: string) { + constructor(message: string) { super(message); this.superStack = Object.getOwnPropertyDescriptor(this, "stack"); // this works on Chrome Object.defineProperty(this, "stack", { @@ -403,7 +403,7 @@ export class ManagedError extends Error implements IDisposable { }); } - getSuperStack () { + getSuperStack() { if (this.superStack) { if (this.superStack.value !== undefined) return this.superStack.value; @@ -413,7 +413,7 @@ export class ManagedError extends Error implements IDisposable { return super.stack; // this works on FF } - getManageStack () { + getManageStack() { if (this.managed_stack) { return this.managed_stack; } @@ -434,23 +434,23 @@ export class ManagedError extends Error implements IDisposable { return this.getSuperStack(); } - dispose (): void { + dispose(): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed (): boolean { + get isDisposed(): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } -export function get_signature_marshaler (signature: JSFunctionSignature, index: number): JSHandle { +export function get_signature_marshaler(signature: JSFunctionSignature, index: number): JSHandle { mono_assert(signature, "Null signatures"); const sig = get_sig(signature, index); return getU32(sig + JSBindingHeaderOffsets.ImportHandle); } -export function array_element_size (element_type: MarshalerType): number { +export function array_element_size(element_type: MarshalerType): number { return element_type == MarshalerType.Byte ? 1 : element_type == MarshalerType.Int32 ? 4 : element_type == MarshalerType.Int52 ? 8 @@ -468,13 +468,13 @@ export const enum MemoryViewType { } abstract class MemoryView implements IMemoryView { - protected constructor (public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { + protected constructor(public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { } abstract dispose(): void; abstract get isDisposed(): boolean; - _unsafe_create_view (): TypedArray { + _unsafe_create_view(): TypedArray { // this view must be short lived so that it doesn't fail after wasm memory growth // for that reason we also don't give the view out to end user and provide set/slice/copyTo API instead const view = this._viewType == MemoryViewType.Byte ? new Uint8Array(localHeapViewU8().buffer, this._pointer, this._length) @@ -485,7 +485,7 @@ abstract class MemoryView implements IMemoryView { return view; } - set (source: TypedArray, targetOffset?: number): void { + set(source: TypedArray, targetOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const targetView = this._unsafe_create_view(); mono_check(source && targetView && source.constructor === targetView.constructor, () => `Expected ${targetView.constructor}`); @@ -493,7 +493,7 @@ abstract class MemoryView implements IMemoryView { // TODO consider memory write barrier } - copyTo (target: TypedArray, sourceOffset?: number): void { + copyTo(target: TypedArray, sourceOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); mono_check(target && sourceView && target.constructor === sourceView.constructor, () => `Expected ${sourceView.constructor}`); @@ -502,19 +502,19 @@ abstract class MemoryView implements IMemoryView { target.set(trimmedSource); } - slice (start?: number, end?: number): TypedArray { + slice(start?: number, end?: number): TypedArray { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); // TODO consider memory read barrier return sourceView.slice(start, end); } - get length (): number { + get length(): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._length; } - get byteLength (): number { + get byteLength(): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._viewType == MemoryViewType.Byte ? this._length : this._viewType == MemoryViewType.Int32 ? this._length << 2 @@ -546,27 +546,27 @@ export interface IMemoryView extends IDisposable { export class Span extends MemoryView { private is_disposed = false; - public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose (): void { + dispose(): void { this.is_disposed = true; } - get isDisposed (): boolean { + get isDisposed(): boolean { return this.is_disposed; } } export class ArraySegment extends MemoryView { - public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose (): void { + dispose(): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed (): boolean { + get isDisposed(): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } diff --git a/src/mono/browser/runtime/memory.ts b/src/mono/browser/runtime/memory.ts index 523bed90d549ce..f3fefb4aca39f6 100644 --- a/src/mono/browser/runtime/memory.ts +++ b/src/mono/browser/runtime/memory.ts @@ -3,17 +3,17 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {MemOffset, NumberOrPointer} from "./types/internal"; -import {VoidPtr, CharPtr} from "./types/emscripten"; -import cwraps, {I52Error} from "./cwraps"; -import {Module, mono_assert, runtimeHelpers} from "./globals"; -import {utf8ToString} from "./strings"; +import { MemOffset, NumberOrPointer } from "./types/internal"; +import { VoidPtr, CharPtr } from "./types/emscripten"; +import cwraps, { I52Error } from "./cwraps"; +import { Module, mono_assert, runtimeHelpers } from "./globals"; +import { utf8ToString } from "./strings"; const alloca_stack: Array = []; const alloca_buffer_size = 32 * 1024; let alloca_base: VoidPtr, alloca_offset: VoidPtr, alloca_limit: VoidPtr; -function _ensure_allocated (): void { +function _ensure_allocated(): void { if (alloca_base) return; alloca_base = Module._malloc(alloca_buffer_size); @@ -24,7 +24,7 @@ function _ensure_allocated (): void { const max_int64_big = BigInt("9223372036854775807"); const min_int64_big = BigInt("-9223372036854775808"); -export function temp_malloc (size: number): VoidPtr { +export function temp_malloc(size: number): VoidPtr { _ensure_allocated(); if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -36,12 +36,12 @@ export function temp_malloc (size: number): VoidPtr { return result; } -export function _create_temp_frame (): void { +export function _create_temp_frame(): void { _ensure_allocated(); alloca_stack.push(alloca_offset); } -export function _release_temp_frame (): void { +export function _release_temp_frame(): void { if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -49,16 +49,16 @@ export function _release_temp_frame (): void { } -function assert_int_in_range (value: Number, min: Number, max: Number) { +function assert_int_in_range(value: Number, min: Number, max: Number) { mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); mono_check(value >= min && value <= max, () => `Overflow: value ${value} is out of ${min} ${max} range`); } -export function _zero_region (byteOffset: VoidPtr, sizeBytes: number): void { +export function _zero_region(byteOffset: VoidPtr, sizeBytes: number): void { localHeapViewU8().fill(0, byteOffset, byteOffset + sizeBytes); } -export function setB32 (offset: MemOffset, value: number | boolean): void { +export function setB32(offset: MemOffset, value: number | boolean): void { receiveWorkerHeapViews(); const boolValue = !!value; if (typeof (value) === "number") @@ -66,64 +66,64 @@ export function setB32 (offset: MemOffset, value: number | boolean): void { Module.HEAP32[offset >>> 2] = boolValue ? 1 : 0; } -export function setU8 (offset: MemOffset, value: number): void { +export function setU8(offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFF); receiveWorkerHeapViews(); Module.HEAPU8[offset] = value; } -export function setU16 (offset: MemOffset, value: number): void { +export function setU16(offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); receiveWorkerHeapViews(); Module.HEAPU16[offset >>> 1] = value; } // does not check for growable heap -export function setU16_local (localView: Uint16Array, offset: MemOffset, value: number): void { +export function setU16_local(localView: Uint16Array, offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); localView[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU16_unchecked (offset: MemOffset, value: number): void { +export function setU16_unchecked(offset: MemOffset, value: number): void { Module.HEAPU16[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU32_unchecked (offset: MemOffset, value: NumberOrPointer): void { +export function setU32_unchecked(offset: MemOffset, value: NumberOrPointer): void { Module.HEAPU32[offset >>> 2] = value; } -export function setU32 (offset: MemOffset, value: NumberOrPointer): void { +export function setU32(offset: MemOffset, value: NumberOrPointer): void { assert_int_in_range(value, 0, 0xFFFF_FFFF); receiveWorkerHeapViews(); Module.HEAPU32[offset >>> 2] = value; } -export function setI8 (offset: MemOffset, value: number): void { +export function setI8(offset: MemOffset, value: number): void { assert_int_in_range(value, -0x80, 0x7F); receiveWorkerHeapViews(); Module.HEAP8[offset] = value; } -export function setI16 (offset: MemOffset, value: number): void { +export function setI16(offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000, 0x7FFF); receiveWorkerHeapViews(); Module.HEAP16[offset >>> 1] = value; } -export function setI32_unchecked (offset: MemOffset, value: number): void { +export function setI32_unchecked(offset: MemOffset, value: number): void { receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -export function setI32 (offset: MemOffset, value: number): void { +export function setI32(offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000_0000, 0x7FFF_FFFF); receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -function autoThrowI52 (error: I52Error) { +function autoThrowI52(error: I52Error) { if (error === I52Error.NONE) return; @@ -140,7 +140,7 @@ function autoThrowI52 (error: I52Error) { /** * Throws for values which are not 52 bit integer. See Number.isSafeInteger() */ -export function setI52 (offset: MemOffset, value: number): void { +export function setI52(offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); const error = cwraps.mono_wasm_f64_to_i52(offset, value); @@ -150,7 +150,7 @@ export function setI52 (offset: MemOffset, value: number): void { /** * Throws for values which are not 52 bit integer or are negative. See Number.isSafeInteger(). */ -export function setU52 (offset: MemOffset, value: number): void { +export function setU52(offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); mono_check(value >= 0, "Can't convert negative Number into UInt64"); receiveWorkerHeapViews(); @@ -158,101 +158,101 @@ export function setU52 (offset: MemOffset, value: number): void { autoThrowI52(error); } -export function setI64Big (offset: MemOffset, value: bigint): void { +export function setI64Big(offset: MemOffset, value: bigint): void { mono_check(typeof value === "bigint", () => `Value is not an bigint: ${value} (${typeof (value)})`); mono_check(value >= min_int64_big && value <= max_int64_big, () => `Overflow: value ${value} is out of ${min_int64_big} ${max_int64_big} range`); Module.HEAP64[offset >>> 3] = value; } -export function setF32 (offset: MemOffset, value: number): void { +export function setF32(offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF32[offset >>> 2] = value; } -export function setF64 (offset: MemOffset, value: number): void { +export function setF64(offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF64[offset >>> 3] = value; } -export function getB32 (offset: MemOffset): boolean { +export function getB32(offset: MemOffset): boolean { receiveWorkerHeapViews(); return !!(Module.HEAP32[offset >>> 2]); } -export function getU8 (offset: MemOffset): number { +export function getU8(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU8[offset]; } -export function getU16 (offset: MemOffset): number { +export function getU16(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU16[offset >>> 1]; } // does not check for growable heap -export function getU16_local (localView: Uint16Array, offset: MemOffset): number { +export function getU16_local(localView: Uint16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getU32 (offset: MemOffset): number { +export function getU32(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU32[offset >>> 2]; } // does not check for growable heap -export function getU32_local (localView: Uint32Array, offset: MemOffset): number { +export function getU32_local(localView: Uint32Array, offset: MemOffset): number { return localView[offset >>> 2]; } -export function getI32_unaligned (offset: MemOffset): number { +export function getI32_unaligned(offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset); } -export function getU32_unaligned (offset: MemOffset): number { +export function getU32_unaligned(offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset) >>> 0; } -export function getF32_unaligned (offset: MemOffset): number { +export function getF32_unaligned(offset: MemOffset): number { return cwraps.mono_wasm_get_f32_unaligned(offset); } -export function getF64_unaligned (offset: MemOffset): number { +export function getF64_unaligned(offset: MemOffset): number { return cwraps.mono_wasm_get_f64_unaligned(offset); } -export function getI8 (offset: MemOffset): number { +export function getI8(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP8[offset]; } -export function getI16 (offset: MemOffset): number { +export function getI16(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP16[offset >>> 1]; } // does not check for growable heap -export function getI16_local (localView: Int16Array, offset: MemOffset): number { +export function getI16_local(localView: Int16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getI32 (offset: MemOffset): number { +export function getI32(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP32[offset >>> 2]; } // does not check for growable heap -export function getI32_local (localView: Int32Array, offset: MemOffset): number { +export function getI32_local(localView: Int32Array, offset: MemOffset): number { return localView[offset >>> 2]; } /** * Throws for Number.MIN_SAFE_INTEGER > value > Number.MAX_SAFE_INTEGER */ -export function getI52 (offset: MemOffset): number { +export function getI52(offset: MemOffset): number { const result = cwraps.mono_wasm_i52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); @@ -262,24 +262,24 @@ export function getI52 (offset: MemOffset): number { /** * Throws for 0 > value > Number.MAX_SAFE_INTEGER */ -export function getU52 (offset: MemOffset): number { +export function getU52(offset: MemOffset): number { const result = cwraps.mono_wasm_u52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); return result; } -export function getI64Big (offset: MemOffset): bigint { +export function getI64Big(offset: MemOffset): bigint { receiveWorkerHeapViews(); return Module.HEAP64[offset >>> 3]; } -export function getF32 (offset: MemOffset): number { +export function getF32(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF32[offset >>> 2]; } -export function getF64 (offset: MemOffset): number { +export function getF64(offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF64[offset >>> 3]; } @@ -291,7 +291,7 @@ export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr) = export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1) => TResult, ud1: T1): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2) => TResult, ud1: T1, ud2: T2): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2, ud3: T3) => TResult, ud1: T1, ud2: T2, ud3: T3): TResult; -export function withStackAlloc (bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { +export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { const sp = Module.stackSave(); const ptr = Module.stackAlloc(bytesWanted); try { @@ -303,14 +303,14 @@ export function withStackAlloc (bytesWanted: number, f: (pt // @bytes must be a typed array. space is allocated for it in the native heap // and it is copied to that location. returns the address of the allocation. -export function mono_wasm_load_bytes_into_heap (bytes: Uint8Array): VoidPtr { +export function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr { const memoryOffset = Module._malloc(bytes.length); const heapBytes = new Uint8Array(localHeapViewU8().buffer, memoryOffset, bytes.length); heapBytes.set(bytes); return memoryOffset; } -export function getEnv (name: string): string | null { +export function getEnv(name: string): string | null { let charPtr: CharPtr = 0; try { charPtr = cwraps.mono_wasm_getenv(name); @@ -322,7 +322,7 @@ export function getEnv (name: string): string | null { } } -export function compareExchangeI32 (offset: MemOffset, value: number, expected: number): number { +export function compareExchangeI32(offset: MemOffset, value: number, expected: number): number { mono_assert((offset & 3) === 0, () => `compareExchangeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) { const actual = getI32(offset); @@ -334,80 +334,80 @@ export function compareExchangeI32 (offset: MemOffset, value: number, expected: return globalThis.Atomics.compareExchange(localHeapViewI32(), offset >>> 2, expected, value); } -export function storeI32 (offset: MemOffset, value: number): void { +export function storeI32(offset: MemOffset, value: number): void { mono_assert((offset & 3) === 0, () => `storeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return setI32(offset, value); globalThis.Atomics.store(localHeapViewI32(), offset >>> 2, value); } -export function notifyI32 (offset: MemOffset, count: number): void { +export function notifyI32(offset: MemOffset, count: number): void { mono_assert((offset & 3) === 0, () => `notifyI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return; globalThis.Atomics.notify(localHeapViewI32(), offset >>> 2, count); } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI8 (): Int8Array { +export function localHeapViewI8(): Int8Array { receiveWorkerHeapViews(); return Module.HEAP8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI16 (): Int16Array { +export function localHeapViewI16(): Int16Array { receiveWorkerHeapViews(); return Module.HEAP16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI32 (): Int32Array { +export function localHeapViewI32(): Int32Array { receiveWorkerHeapViews(); return Module.HEAP32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI64Big (): BigInt64Array { +export function localHeapViewI64Big(): BigInt64Array { receiveWorkerHeapViews(); return Module.HEAP64; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU8 (): Uint8Array { +export function localHeapViewU8(): Uint8Array { receiveWorkerHeapViews(); return Module.HEAPU8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU16 (): Uint16Array { +export function localHeapViewU16(): Uint16Array { receiveWorkerHeapViews(); return Module.HEAPU16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU32 (): Uint32Array { +export function localHeapViewU32(): Uint32Array { receiveWorkerHeapViews(); return Module.HEAPU32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF32 (): Float32Array { +export function localHeapViewF32(): Float32Array { receiveWorkerHeapViews(); return Module.HEAPF32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF64 (): Float64Array { +export function localHeapViewF64(): Float64Array { receiveWorkerHeapViews(); return Module.HEAPF64; } -export function copyBytes (srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { +export function copyBytes(srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { const heap = localHeapViewU8(); heap.copyWithin(dstPtr as any, srcPtr as any, srcPtr as any + bytes); } // when we run with multithreading enabled, we need to make sure that the memory views are updated on each worker // on non-MT build, this will be a no-op trimmed by rollup -export function receiveWorkerHeapViews () { +export function receiveWorkerHeapViews() { if (!WasmEnableThreads) return; const memory = runtimeHelpers.getMemory(); if (memory.buffer !== Module.HEAPU8.buffer) { @@ -416,7 +416,7 @@ export function receiveWorkerHeapViews () { } const sharedArrayBufferDefined = typeof SharedArrayBuffer !== "undefined"; -export function isSharedArrayBuffer (buffer: any): buffer is SharedArrayBuffer { +export function isSharedArrayBuffer(buffer: any): buffer is SharedArrayBuffer { // this condition should be eliminated by rollup on non-threading builds if (!WasmEnableThreads) return false; // BEWARE: In some cases, `instanceof SharedArrayBuffer` returns false even though buffer is an SAB. @@ -430,7 +430,7 @@ Problem: When WebWorker is suspended in the browser, the other running threads c After the thread is un-suspended C code may to try to de-reference pointer which is beyond it's known view. This is likely V8 bug. We don't have direct evidence, just failed debugger unit tests with MT runtime. */ -export function forceThreadMemoryViewRefresh () { +export function forceThreadMemoryViewRefresh() { // this condition should be eliminated by rollup on non-threading builds and it would become empty method. if (!WasmEnableThreads) return; diff --git a/src/mono/browser/runtime/polyfills.ts b/src/mono/browser/runtime/polyfills.ts index 61a89bec1513be..06762b21245501 100644 --- a/src/mono/browser/runtime/polyfills.ts +++ b/src/mono/browser/runtime/polyfills.ts @@ -2,19 +2,19 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import type {EmscriptenReplacements} from "./types/internal"; -import type {TypedArray} from "./types/emscripten"; -import {ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WORKER, INTERNAL, Module, loaderHelpers, runtimeHelpers} from "./globals"; -import {replaceEmscriptenTLSInit} from "./pthreads"; -import {replaceEmscriptenPThreadUI} from "./pthreads"; +import type { EmscriptenReplacements } from "./types/internal"; +import type { TypedArray } from "./types/emscripten"; +import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WORKER, INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals"; +import { replaceEmscriptenTLSInit } from "./pthreads"; +import { replaceEmscriptenPThreadUI } from "./pthreads"; const dummyPerformance = { - now: function () { + now: function() { return Date.now(); } }; -export function initializeReplacements (replacements: EmscriptenReplacements): void { +export function initializeReplacements(replacements: EmscriptenReplacements): void { // performance.now() is used by emscripten and doesn't work in JSC if (typeof globalThis.performance === "undefined") { globalThis.performance = dummyPerformance as any; @@ -43,12 +43,12 @@ export function initializeReplacements (replacements: EmscriptenReplacements): v } } -export async function init_polyfills_async (): Promise { +export async function init_polyfills_async(): Promise { // v8 shell doesn't have Event and EventTarget if (WasmEnableThreads && typeof globalThis.Event === "undefined") { globalThis.Event = class Event { readonly type: string; - constructor (type: string) { + constructor(type: string) { this.type = type; } } as any; @@ -56,7 +56,7 @@ export async function init_polyfills_async (): Promise { if (WasmEnableThreads && typeof globalThis.EventTarget === "undefined") { globalThis.EventTarget = class EventTarget { private subscribers = new Map>(); - addEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { + addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { if (listener === undefined || listener == null) return; let oneShot = false; @@ -76,9 +76,9 @@ export async function init_polyfills_async (): Promise { if (listeners === undefined) { throw new Error("can't happen"); } - listeners.push({listener, oneShot}); + listeners.push({ listener, oneShot }); } - removeEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { + removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { if (listener === undefined || listener == null) return; if (options !== undefined) { @@ -102,7 +102,7 @@ export async function init_polyfills_async (): Promise { subscribers.splice(index, 1); } } - dispatchEvent (event: Event) { + dispatchEvent(event: Event) { if (!this.subscribers.has(event.type)) { return true; } @@ -138,7 +138,7 @@ export async function init_polyfills_async (): Promise { if (ENVIRONMENT_IS_NODE) { // wait for locateFile setup on NodeJs if (globalThis.performance === dummyPerformance) { - const {performance} = INTERNAL.require("perf_hooks"); + const { performance } = INTERNAL.require("perf_hooks"); globalThis.performance = performance; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment diff --git a/src/mono/browser/runtime/profiler.ts b/src/mono/browser/runtime/profiler.ts index 64b1e8c93ed5ce..8dce6e31fcba2e 100644 --- a/src/mono/browser/runtime/profiler.ts +++ b/src/mono/browser/runtime/profiler.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {ENVIRONMENT_IS_WEB, mono_assert, runtimeHelpers} from "./globals"; -import {MonoMethod, AOTProfilerOptions, BrowserProfilerOptions} from "./types/internal"; -import {profiler_c_functions as cwraps} from "./cwraps"; -import {utf8ToString} from "./strings"; +import { ENVIRONMENT_IS_WEB, mono_assert, runtimeHelpers } from "./globals"; +import { MonoMethod, AOTProfilerOptions, BrowserProfilerOptions } from "./types/internal"; +import { profiler_c_functions as cwraps } from "./cwraps"; +import { utf8ToString } from "./strings"; // Initialize the AOT profiler with OPTIONS. // Requires the AOT profiler to be linked into the app. @@ -14,7 +14,7 @@ import {utf8ToString} from "./strings"; // sendTo defaults to 'WebAssembly.Runtime::DumpAotProfileData'. // DumpAotProfileData stores the data into INTERNAL.aotProfileData. // -export function mono_wasm_init_aot_profiler (options: AOTProfilerOptions): void { +export function mono_wasm_init_aot_profiler(options: AOTProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableAotProfiler, "AOT profiler is not enabled, please use aot; in your project file."); if (options == null) options = {}; @@ -26,7 +26,7 @@ export function mono_wasm_init_aot_profiler (options: AOTProfilerOptions): void cwraps.mono_wasm_profiler_init_aot(arg); } -export function mono_wasm_init_browser_profiler (options: BrowserProfilerOptions): void { +export function mono_wasm_init_browser_profiler(options: BrowserProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableBrowserProfiler, "Browser profiler is not enabled, please use browser; in your project file."); if (options == null) options = {}; @@ -59,37 +59,37 @@ export type TimeStamp = { __brand: "TimeStamp" } -export function startMeasure (): TimeStamp { +export function startMeasure(): TimeStamp { if (runtimeHelpers.enablePerfMeasure) { return globalThis.performance.now() as any; } return undefined as any; } -export function endMeasure (start: TimeStamp, block: string, id?: string) { +export function endMeasure(start: TimeStamp, block: string, id?: string) { if (runtimeHelpers.enablePerfMeasure && start) { const options = ENVIRONMENT_IS_WEB - ? {start: start as any} - : {startTime: start as any}; + ? { start: start as any } + : { startTime: start as any }; const name = id ? `${block}${id} ` : block; globalThis.performance.measure(name, options); } } const stackFrames: number[] = []; -export function mono_wasm_profiler_enter (): void { +export function mono_wasm_profiler_enter(): void { if (runtimeHelpers.enablePerfMeasure) { stackFrames.push(globalThis.performance.now()); } } const methodNames: Map = new Map(); -export function mono_wasm_profiler_leave (method: MonoMethod): void { +export function mono_wasm_profiler_leave(method: MonoMethod): void { if (runtimeHelpers.enablePerfMeasure) { const start = stackFrames.pop(); const options = ENVIRONMENT_IS_WEB - ? {start: start} - : {startTime: start}; + ? { start: start } + : { startTime: start }; let methodName = methodNames.get(method as any); if (!methodName) { const chars = cwraps.mono_wasm_method_get_name(method); diff --git a/src/mono/browser/runtime/pthreads/deputy-thread.ts b/src/mono/browser/runtime/pthreads/deputy-thread.ts index 78ef0e588a1b6a..eafb8f943f927d 100644 --- a/src/mono/browser/runtime/pthreads/deputy-thread.ts +++ b/src/mono/browser/runtime/pthreads/deputy-thread.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import {mono_log_error, mono_log_info} from "../logging"; -import {monoThreadInfo, postMessageToMain, update_thread_info} from "./shared"; -import {Module, loaderHelpers, runtimeHelpers} from "../globals"; -import {start_runtime} from "../startup"; -import {WorkerToMainMessageType} from "../types/internal"; +import { mono_log_error, mono_log_info } from "../logging"; +import { monoThreadInfo, postMessageToMain, update_thread_info } from "./shared"; +import { Module, loaderHelpers, runtimeHelpers } from "../globals"; +import { start_runtime } from "../startup"; +import { WorkerToMainMessageType } from "../types/internal"; -export function mono_wasm_start_deputy_thread_async () { +export function mono_wasm_start_deputy_thread_async() { if (!WasmEnableThreads) return; if (BuildConfiguration === "Debug" && globalThis.setInterval) globalThis.setInterval(() => { @@ -26,7 +26,7 @@ export function mono_wasm_start_deputy_thread_async () { info: monoThreadInfo, }); Module.runtimeKeepalivePush(); - Module.safeSetTimeout(async () => { + Module.safeSetTimeout(async() => { try { await start_runtime(); diff --git a/src/mono/browser/runtime/pthreads/index.ts b/src/mono/browser/runtime/pthreads/index.ts index b243911f236ae2..0a5911605282d0 100644 --- a/src/mono/browser/runtime/pthreads/index.ts +++ b/src/mono/browser/runtime/pthreads/index.ts @@ -16,5 +16,5 @@ export { dotnetPthreadCreated, initWorkerThreadEvents, replaceEmscriptenTLSInit, pthread_self } from "./worker-thread"; -export {mono_wasm_start_deputy_thread_async} from "./deputy-thread"; -export {mono_wasm_start_io_thread_async} from "./io-thread"; +export { mono_wasm_start_deputy_thread_async } from "./deputy-thread"; +export { mono_wasm_start_io_thread_async } from "./io-thread"; diff --git a/src/mono/browser/runtime/pthreads/io-thread.ts b/src/mono/browser/runtime/pthreads/io-thread.ts index f216ec2aeab756..1cecaf72e445a5 100644 --- a/src/mono/browser/runtime/pthreads/io-thread.ts +++ b/src/mono/browser/runtime/pthreads/io-thread.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import {mono_log_error, mono_log_info} from "../logging"; -import {monoThreadInfo, postMessageToMain, update_thread_info} from "./shared"; -import {Module, loaderHelpers} from "../globals"; -import {WorkerToMainMessageType} from "../types/internal"; -import {threads_c_functions as tcwraps} from "../cwraps"; +import { mono_log_error, mono_log_info } from "../logging"; +import { monoThreadInfo, postMessageToMain, update_thread_info } from "./shared"; +import { Module, loaderHelpers } from "../globals"; +import { WorkerToMainMessageType } from "../types/internal"; +import { threads_c_functions as tcwraps } from "../cwraps"; -export function mono_wasm_start_io_thread_async () { +export function mono_wasm_start_io_thread_async() { if (!WasmEnableThreads) return; diff --git a/src/mono/browser/runtime/pthreads/shared.ts b/src/mono/browser/runtime/pthreads/shared.ts index f2b98433145ba3..883259c85e04c8 100644 --- a/src/mono/browser/runtime/pthreads/shared.ts +++ b/src/mono/browser/runtime/pthreads/shared.ts @@ -4,13 +4,13 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import type {GCHandle, MonoThreadMessage, PThreadInfo, PThreadPtr} from "../types/internal"; +import type { GCHandle, MonoThreadMessage, PThreadInfo, PThreadPtr } from "../types/internal"; -import {ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; -import {set_thread_prefix} from "../logging"; -import {bindings_init} from "../startup"; -import {forceDisposeProxies} from "../gc-handles"; -import {monoMessageSymbol, GCHandleNull, PThreadPtrNull, WorkerToMainMessageType} from "../types/internal"; +import { ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; +import { set_thread_prefix } from "../logging"; +import { bindings_init } from "../startup"; +import { forceDisposeProxies } from "../gc-handles"; +import { monoMessageSymbol, GCHandleNull, PThreadPtrNull, WorkerToMainMessageType } from "../types/internal"; // A duplicate in loader/assets.ts export const worker_empty_prefix = " - "; @@ -24,7 +24,7 @@ const monoThreadInfoPartial: Partial = { }; export const monoThreadInfo: PThreadInfo = monoThreadInfoPartial as PThreadInfo; -export function isMonoThreadMessage (x: unknown): x is MonoThreadMessage { +export function isMonoThreadMessage(x: unknown): x is MonoThreadMessage { if (typeof (x) !== "object" || x === null) { return false; } @@ -32,7 +32,7 @@ export function isMonoThreadMessage (x: unknown): x is MonoThreadMessage { return typeof (xmsg.type) === "string" && typeof (xmsg.cmd) === "string"; } -export function mono_wasm_install_js_worker_interop (context_gc_handle: GCHandle): void { +export function mono_wasm_install_js_worker_interop(context_gc_handle: GCHandle): void { if (!WasmEnableThreads) return; bindings_init(); mono_assert(!runtimeHelpers.proxyGCHandle, "JS interop should not be already installed on this worker."); @@ -52,7 +52,7 @@ export function mono_wasm_install_js_worker_interop (context_gc_handle: GCHandle } } -export function mono_wasm_uninstall_js_worker_interop (): void { +export function mono_wasm_uninstall_js_worker_interop(): void { if (!WasmEnableThreads) return; mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "JS interop is not installed on this worker."); mono_assert(runtimeHelpers.proxyGCHandle, "JSSynchronizationContext is not installed on this worker."); @@ -66,7 +66,7 @@ export function mono_wasm_uninstall_js_worker_interop (): void { } // this is just for Debug build of the runtime, making it easier to debug worker threads -export function update_thread_info (): void { +export function update_thread_info(): void { if (!WasmEnableThreads) return; const threadType = !monoThreadInfo.isRegistered ? "emsc" : monoThreadInfo.isUI ? "-UI-" @@ -105,17 +105,17 @@ export function update_thread_info (): void { } } -export function mono_wasm_pthread_ptr (): PThreadPtr { +export function mono_wasm_pthread_ptr(): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_pthread_self"](); } -export function mono_wasm_main_thread_ptr (): PThreadPtr { +export function mono_wasm_main_thread_ptr(): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_emscripten_main_runtime_thread_id"](); } -export function postMessageToMain (message: MonoWorkerToMainMessage, transfer?: Transferable[]) { +export function postMessageToMain(message: MonoWorkerToMainMessage, transfer?: Transferable[]) { self.postMessage({ [monoMessageSymbol]: message }, transfer ? transfer : []); diff --git a/src/mono/browser/runtime/pthreads/ui-thread.ts b/src/mono/browser/runtime/pthreads/ui-thread.ts index 5102672737d82d..134a396636d2ed 100644 --- a/src/mono/browser/runtime/pthreads/ui-thread.ts +++ b/src/mono/browser/runtime/pthreads/ui-thread.ts @@ -5,24 +5,24 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; import { } from "../globals"; -import {mono_log_debug, mono_log_warn} from "../logging"; -import {MonoWorkerToMainMessage, monoThreadInfo, mono_wasm_pthread_ptr, update_thread_info, worker_empty_prefix} from "./shared"; -import {Module, ENVIRONMENT_IS_WORKER, createPromiseController, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; -import {PThreadLibrary, MainToWorkerMessageType, MonoThreadMessage, PThreadInfo, PThreadPtr, PThreadPtrNull, PThreadWorker, PromiseAndController, PromiseController, Thread, WorkerToMainMessageType, monoMessageSymbol} from "../types/internal"; -import {mono_log_error, mono_log_info} from "../logging"; -import {threads_c_functions as cwraps} from "../cwraps"; +import { mono_log_debug, mono_log_warn } from "../logging"; +import { MonoWorkerToMainMessage, monoThreadInfo, mono_wasm_pthread_ptr, update_thread_info, worker_empty_prefix } from "./shared"; +import { Module, ENVIRONMENT_IS_WORKER, createPromiseController, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; +import { PThreadLibrary, MainToWorkerMessageType, MonoThreadMessage, PThreadInfo, PThreadPtr, PThreadPtrNull, PThreadWorker, PromiseAndController, PromiseController, Thread, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal"; +import { mono_log_error, mono_log_info } from "../logging"; +import { threads_c_functions as cwraps } from "../cwraps"; const threadPromises: Map[]> = new Map(); class ThreadImpl implements Thread { - constructor (readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } - postMessageToWorker (message: T): void { + constructor(readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } + postMessageToWorker(message: T): void { this.port.postMessage(message); } } /// wait until the thread with the given id has set up a message port to the runtime -export function waitForThread (pthreadPtr: PThreadPtr): Promise { +export function waitForThread(pthreadPtr: PThreadPtr): Promise { if (!WasmEnableThreads) return null as any; mono_assert(!ENVIRONMENT_IS_WORKER, "waitForThread should only be called from the UI thread"); const worker = getWorker(pthreadPtr); @@ -39,7 +39,7 @@ export function waitForThread (pthreadPtr: PThreadPtr): Promise { return promiseAndController.promise; } -export function resolveThreadPromises (pthreadPtr: PThreadPtr, thread?: Thread): void { +export function resolveThreadPromises(pthreadPtr: PThreadPtr, thread?: Thread): void { if (!WasmEnableThreads) return; const arr = threadPromises.get(pthreadPtr); if (arr !== undefined) { @@ -55,7 +55,7 @@ export function resolveThreadPromises (pthreadPtr: PThreadPtr, thread?: Thread): } // handler that runs in the main thread when a message is received from a pthread worker -function monoWorkerMessageHandler (worker: PThreadWorker, ev: MessageEvent): void { +function monoWorkerMessageHandler(worker: PThreadWorker, ev: MessageEvent): void { if (!WasmEnableThreads) return; let pthreadId: PThreadPtr; // this is emscripten message @@ -123,7 +123,7 @@ let pendingWorkerLoad: PromiseAndController | undefined; /// Called by Emscripten internals on the browser thread when a new pthread worker is created and added to the pthread worker pool. /// At this point the worker doesn't have any pthread assigned to it, yet. -export function onWorkerLoadInitiated (worker: PThreadWorker, loaded: Promise): void { +export function onWorkerLoadInitiated(worker: PThreadWorker, loaded: Promise): void { if (!WasmEnableThreads) return; worker.addEventListener("message", (ev) => monoWorkerMessageHandler(worker, ev)); if (pendingWorkerLoad == undefined) { @@ -138,7 +138,7 @@ export function onWorkerLoadInitiated (worker: PThreadWorker, loaded: Promise { +export function thread_available(): Promise { if (!WasmEnableThreads) return null as any; if (pendingWorkerLoad == undefined) { return Promise.resolve(); @@ -146,7 +146,7 @@ export function thread_available (): Promise { return pendingWorkerLoad.promise; } -export function populateEmscriptenPool (): void { +export function populateEmscriptenPool(): void { if (!WasmEnableThreads) return; const unused = getUnusedWorkerPool(); for (const worker of loaderHelpers.loadingWorkers) { @@ -155,7 +155,7 @@ export function populateEmscriptenPool (): void { loaderHelpers.loadingWorkers = []; } -export async function mono_wasm_init_threads () { +export async function mono_wasm_init_threads() { if (!WasmEnableThreads) return; // setup the UI thread @@ -175,17 +175,17 @@ export async function mono_wasm_init_threads () { } // when we create threads with browser event loop, it's not able to be joined by mono's thread join during shutdown and blocks process exit -export function cancelThreads () { +export function cancelThreads() { if (!WasmEnableThreads) return; const workers: PThreadWorker[] = getRunningWorkers(); for (const worker of workers) { if (worker.info.isExternalEventLoop) { - worker.postMessage({cmd: "cancel"}); + worker.postMessage({ cmd: "cancel" }); } } } -export function mono_wasm_dump_threads (): void { +export function mono_wasm_dump_threads(): void { if (!WasmEnableThreads) return; mono_log_info("Dumping web worker info as seen by UI thread, it could be stale: "); const emptyInfo: PThreadInfo = { @@ -219,7 +219,7 @@ export function mono_wasm_dump_threads (): void { }); } -export function init_finalizer_thread () { +export function init_finalizer_thread() { // we don't need it immediately, so we can wait a bit, to keep CPU working on normal startup setTimeout(() => { try { @@ -235,7 +235,7 @@ export function init_finalizer_thread () { }, loaderHelpers.config.finalizerThreadStartDelayMs); } -export function replaceEmscriptenPThreadUI (modulePThread: PThreadLibrary): void { +export function replaceEmscriptenPThreadUI(modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalLoadWasmModuleToWorker = modulePThread.loadWasmModuleToWorker; @@ -286,12 +286,12 @@ export function replaceEmscriptenPThreadUI (modulePThread: PThreadLibrary): void } let availableThreadCount = 0; -export function is_thread_available () { +export function is_thread_available() { if (!WasmEnableThreads) return true; return availableThreadCount > 0; } -function getNewWorker (modulePThread: PThreadLibrary): PThreadWorker { +function getNewWorker(modulePThread: PThreadLibrary): PThreadWorker { if (!WasmEnableThreads) return null as any; if (modulePThread.unusedWorkers.length == 0) { @@ -322,7 +322,7 @@ function getNewWorker (modulePThread: PThreadLibrary): PThreadWorker { } /// We replace Module["PThreads"].allocateUnusedWorker with this version that knows about assets -function allocateUnusedWorker (): PThreadWorker { +function allocateUnusedWorker(): PThreadWorker { if (!WasmEnableThreads) return null as any; const asset = loaderHelpers.resolve_single_asset_path("js-module-threads"); @@ -345,22 +345,22 @@ function allocateUnusedWorker (): PThreadWorker { return worker; } -export function getWorker (pthreadPtr: PThreadPtr): PThreadWorker | undefined { +export function getWorker(pthreadPtr: PThreadPtr): PThreadWorker | undefined { return getModulePThread().pthreads[pthreadPtr as any]; } -export function getUnusedWorkerPool (): PThreadWorker[] { +export function getUnusedWorkerPool(): PThreadWorker[] { return getModulePThread().unusedWorkers; } -export function getRunningWorkers (): PThreadWorker[] { +export function getRunningWorkers(): PThreadWorker[] { return getModulePThread().runningWorkers; } -export function loadWasmModuleToWorker (worker: PThreadWorker): Promise { +export function loadWasmModuleToWorker(worker: PThreadWorker): Promise { return getModulePThread().loadWasmModuleToWorker(worker); } -export function getModulePThread (): PThreadLibrary { +export function getModulePThread(): PThreadLibrary { return (Module).PThread as PThreadLibrary; } diff --git a/src/mono/browser/runtime/pthreads/worker-events.ts b/src/mono/browser/runtime/pthreads/worker-events.ts index d3df55677d3272..e0d40a1a7e3110 100644 --- a/src/mono/browser/runtime/pthreads/worker-events.ts +++ b/src/mono/browser/runtime/pthreads/worker-events.ts @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. import WasmEnableThreads from "consts:wasmEnableThreads"; -import {PThreadSelf} from "./shared"; +import { PThreadSelf } from "./shared"; export const dotnetPthreadCreated = "dotnet:pthread:created" as const; export const dotnetPthreadAttached = "dotnet:pthread:attached" as const; @@ -35,7 +35,7 @@ export const makeWorkerThreadEvent: (type: keyof WorkerThreadEventMap, pthread_s }) : ((type: keyof WorkerThreadEventMap, pthread_self: PThreadSelf) => { if (!WorkerThreadEventClassConstructor) WorkerThreadEventClassConstructor = class WorkerThreadEventImpl extends Event implements WorkerThreadEvent { - constructor (type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { + constructor(type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { super(type); } }; diff --git a/src/mono/browser/runtime/pthreads/worker-thread.ts b/src/mono/browser/runtime/pthreads/worker-thread.ts index 6f6b4c165e16f5..edf09d3ea2e0fa 100644 --- a/src/mono/browser/runtime/pthreads/worker-thread.ts +++ b/src/mono/browser/runtime/pthreads/worker-thread.ts @@ -5,20 +5,20 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers} from "../globals"; -import {PThreadSelf, monoThreadInfo, mono_wasm_pthread_ptr, postMessageToMain, update_thread_info} from "./shared"; -import {PThreadLibrary, MonoThreadMessage, PThreadInfo, PThreadPtr, WorkerToMainMessageType} from "../types/internal"; +import { ENVIRONMENT_IS_PTHREAD, Module, loaderHelpers, mono_assert, runtimeHelpers } from "../globals"; +import { PThreadSelf, monoThreadInfo, mono_wasm_pthread_ptr, postMessageToMain, update_thread_info } from "./shared"; +import { PThreadLibrary, MonoThreadMessage, PThreadInfo, PThreadPtr, WorkerToMainMessageType } from "../types/internal"; import { makeWorkerThreadEvent, dotnetPthreadCreated, dotnetPthreadAttached, WorkerThreadEventTarget } from "./worker-events"; -import {postRunWorker, preRunWorker} from "../startup"; -import {mono_log_debug, mono_log_error} from "../logging"; -import {CharPtr} from "../types/emscripten"; -import {utf8ToString} from "../strings"; -import {forceThreadMemoryViewRefresh} from "../memory"; +import { postRunWorker, preRunWorker } from "../startup"; +import { mono_log_debug, mono_log_error } from "../logging"; +import { CharPtr } from "../types/emscripten"; +import { utf8ToString } from "../strings"; +import { forceThreadMemoryViewRefresh } from "../memory"; // re-export some of the events types export { @@ -32,17 +32,17 @@ export { export let pthread_self: PThreadSelf = null as any as PThreadSelf; class WorkerSelf implements PThreadSelf { - constructor (public info: PThreadInfo, public portToBrowser: MessagePort) { + constructor(public info: PThreadInfo, public portToBrowser: MessagePort) { } - postMessageToBrowser (message: MonoThreadMessage, transfer?: Transferable[]) { + postMessageToBrowser(message: MonoThreadMessage, transfer?: Transferable[]) { if (transfer) { this.portToBrowser.postMessage(message, transfer); } else { this.portToBrowser.postMessage(message); } } - addEventListenerFromBrowser (listener: (event: MessageEvent) => void) { + addEventListenerFromBrowser(listener: (event: MessageEvent) => void) { this.portToBrowser.addEventListener("message", listener); } } @@ -56,7 +56,7 @@ class WorkerSelf implements PThreadSelf { export let currentWorkerThreadEvents: WorkerThreadEventTarget = undefined as any; // this is very very early in the worker startup -export function initWorkerThreadEvents () { +export function initWorkerThreadEvents() { // treeshake if threads are disabled currentWorkerThreadEvents = WasmEnableThreads ? new globalThis.EventTarget() : null as any as WorkerThreadEventTarget; Object.assign(monoThreadInfo, runtimeHelpers.monoThreadInfo); @@ -64,11 +64,11 @@ export function initWorkerThreadEvents () { // this is the message handler for the worker that receives messages from the main thread // extend this with new cases as needed -function monoDedicatedChannelMessageFromMainToWorker (event: MessageEvent): void { +function monoDedicatedChannelMessageFromMainToWorker(event: MessageEvent): void { mono_log_debug("got message from main on the dedicated channel", event.data); } -export function on_emscripten_thread_init (pthread_ptr: PThreadPtr) { +export function on_emscripten_thread_init(pthread_ptr: PThreadPtr) { runtimeHelpers.currentThreadTID = monoThreadInfo.pthreadId = pthread_ptr; forceThreadMemoryViewRefresh(); } @@ -76,7 +76,7 @@ export function on_emscripten_thread_init (pthread_ptr: PThreadPtr) { /// Called by emscripten when a pthread is setup to run on a worker. Can be called multiple times /// for the same webworker, since emscripten can reuse workers. /// This is an implementation detail, that shouldn't be used directly. -export function mono_wasm_pthread_on_pthread_created (): void { +export function mono_wasm_pthread_on_pthread_created(): void { if (!WasmEnableThreads) return; try { forceThreadMemoryViewRefresh(); @@ -118,7 +118,7 @@ export function mono_wasm_pthread_on_pthread_created (): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes registered to the mono runtime. -export function mono_wasm_pthread_on_pthread_registered (pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when registering"); @@ -137,7 +137,7 @@ export function mono_wasm_pthread_on_pthread_registered (pthread_id: PThreadPtr) } /// Called in the worker thread (not main thread) from mono when a pthread becomes attached to the mono runtime. -export function mono_wasm_pthread_on_pthread_attached (pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { +export function mono_wasm_pthread_on_pthread_attached(pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when attaching"); @@ -167,7 +167,7 @@ export function mono_wasm_pthread_on_pthread_attached (pthread_id: PThreadPtr, t } } -export function mono_wasm_pthread_set_name (name: CharPtr): void { +export function mono_wasm_pthread_set_name(name: CharPtr): void { if (!WasmEnableThreads) return; if (!ENVIRONMENT_IS_PTHREAD) return; monoThreadInfo.threadName = utf8ToString(name); @@ -179,7 +179,7 @@ export function mono_wasm_pthread_set_name (name: CharPtr): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes detached from the mono runtime. -export function mono_wasm_pthread_on_pthread_unregistered (pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_unregistered(pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(pthread_id === monoThreadInfo.pthreadId, "expected pthread_id to match when un-registering"); @@ -199,7 +199,7 @@ export function mono_wasm_pthread_on_pthread_unregistered (pthread_id: PThreadPt } } -export function replaceEmscriptenTLSInit (modulePThread: PThreadLibrary): void { +export function replaceEmscriptenTLSInit(modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalThreadInitTLS = modulePThread.threadInitTLS; @@ -210,9 +210,9 @@ export function replaceEmscriptenTLSInit (modulePThread: PThreadLibrary): void { }; } -export function replaceEmscriptenPThreadInit (): void { +export function replaceEmscriptenPThreadInit(): void { const original_emscripten_thread_init = Module["__emscripten_thread_init"]; - function emscripten_thread_init_wrapper (pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { + function emscripten_thread_init_wrapper(pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { on_emscripten_thread_init(pthread_ptr); original_emscripten_thread_init(pthread_ptr, isMainBrowserThread, isMainRuntimeThread, canBlock); // re-install self diff --git a/src/mono/browser/runtime/queue.ts b/src/mono/browser/runtime/queue.ts index a6ccd00615ca9e..74f507671ff98c 100644 --- a/src/mono/browser/runtime/queue.ts +++ b/src/mono/browser/runtime/queue.ts @@ -6,19 +6,19 @@ export class Queue { private queue: T[]; private offset: number; - constructor () { + constructor() { this.queue = []; this.offset = 0; } // initialise the queue and offset // Returns the length of the queue. - getLength (): number { + getLength(): number { return (this.queue.length - this.offset); } // Returns true if the queue is empty, and false otherwise. - isEmpty (): boolean { + isEmpty(): boolean { return (this.queue.length == 0); } @@ -26,14 +26,14 @@ export class Queue { * * item - the item to enqueue */ - enqueue (item: T): void { + enqueue(item: T): void { this.queue.push(item); } /* Dequeues an item and returns it. If the queue is empty, the value * 'undefined' is returned. */ - dequeue (): T | undefined { + dequeue(): T | undefined { // if the queue is empty, return immediately if (this.queue.length === 0) return undefined; @@ -57,11 +57,11 @@ export class Queue { /* Returns the item at the front of the queue (without dequeuing it). If the * queue is empty then undefined is returned. */ - peek (): T | undefined { + peek(): T | undefined { return (this.queue.length > 0 ? this.queue[this.offset] : undefined); } - drain (onEach: (item: T) => void): void { + drain(onEach: (item: T) => void): void { while (this.getLength()) { const item = this.dequeue()!; onEach(item); diff --git a/src/mono/browser/runtime/rollup.config.js b/src/mono/browser/runtime/rollup.config.js index 1a8397afa44ea7..519879f7d8438e 100644 --- a/src/mono/browser/runtime/rollup.config.js +++ b/src/mono/browser/runtime/rollup.config.js @@ -1,14 +1,14 @@ -import {defineConfig} from "rollup"; +import { defineConfig } from "rollup"; import typescript from "@rollup/plugin-typescript"; import terser from "@rollup/plugin-terser"; import virtual from "@rollup/plugin-virtual"; -import {nodeResolve} from "@rollup/plugin-node-resolve"; -import {readFile, writeFile, mkdir} from "fs/promises"; +import { nodeResolve } from "@rollup/plugin-node-resolve"; +import { readFile, writeFile, mkdir } from "fs/promises"; import * as fs from "fs"; import * as path from "path"; -import {createHash} from "crypto"; +import { createHash } from "crypto"; import dts from "rollup-plugin-dts"; -import {createFilter} from "@rollup/pluginutils"; +import { createFilter } from "@rollup/pluginutils"; import fast_glob from "fast-glob"; import gitCommitInfo from "git-commit-info"; import MagicString from "magic-string"; @@ -107,7 +107,7 @@ const envConstants = { }; const locationCache = {}; -function sourcemapPathTransform (relativeSourcePath, sourcemapPath) { +function sourcemapPathTransform(relativeSourcePath, sourcemapPath) { let res = locationCache[relativeSourcePath]; if (res === undefined) { if (!isContinuousIntegrationBuild) { @@ -125,7 +125,7 @@ function sourcemapPathTransform (relativeSourcePath, sourcemapPath) { return res; } -function consts (dict) { +function consts(dict) { // implement rollup-plugin-const in terms of @rollup/plugin-virtual // It's basically the same thing except "consts" names all its modules with a "consts:" prefix, // and the virtual module always exports a single default binding (the const value). @@ -245,7 +245,7 @@ if (isDebug) { } /* Web Workers */ -function makeWorkerConfig (workerName, workerInputSourcePath) { +function makeWorkerConfig(workerName, workerInputSourcePath) { const workerConfig = { input: workerInputSourcePath, output: [ @@ -273,14 +273,14 @@ const allConfigs = [ .concat(diagnosticMockTypesConfig ? [diagnosticMockTypesConfig] : []); export default defineConfig(allConfigs); -function evalCodePlugin () { +function evalCodePlugin() { return { name: "evalCode", generateBundle: evalCode }; } -async function evalCode (options, bundle) { +async function evalCode(options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -296,7 +296,7 @@ async function evalCode (options, bundle) { // this would create .sha256 file next to the output file, so that we do not touch datetime of the file if it's same -> faster incremental build. -function writeOnChangePlugin () { +function writeOnChangePlugin() { return { name: "writeOnChange", generateBundle: writeWhenChanged @@ -304,7 +304,7 @@ function writeOnChangePlugin () { } // force always unix line ending -function alwaysLF () { +function alwaysLF() { return { name: "writeOnChange", generateBundle: (options, bundle) => { @@ -316,7 +316,7 @@ function alwaysLF () { }; } -async function writeWhenChanged (options, bundle) { +async function writeWhenChanged(options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -329,13 +329,13 @@ async function writeWhenChanged (options, bundle) { let isOutputChanged = true; if (oldHashExists && oldFileExists) { - const oldHash = await readFile(hashFileName, {encoding: "ascii"}); + const oldHash = await readFile(hashFileName, { encoding: "ascii" }); isOutputChanged = oldHash !== newHash; } if (isOutputChanged) { const dir = path.dirname(options.file); if (!await checkFileExists(dir)) { - await mkdir(dir, {recursive: true}); + await mkdir(dir, { recursive: true }); } await writeFile(hashFileName, newHash); } else { @@ -347,34 +347,34 @@ async function writeWhenChanged (options, bundle) { } } -function checkFileExists (file) { +function checkFileExists(file) { return fs.promises.access(file, fs.constants.F_OK) .then(() => true) .catch(() => false); } -function regexCheck (checks = []) { +function regexCheck(checks = []) { const filter = createFilter("**/*.ts"); return { name: "regexCheck", - renderChunk (code, chunk) { + renderChunk(code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeCheck(this, code, id); }, - transform (code, id) { + transform(code, id) { if (!filter(id)) return null; return executeCheck(this, code, id); } }; - function executeCheck (self, code, id) { + function executeCheck(self, code, id) { // self.warn("executeCheck" + id); for (const rep of checks) { - const {pattern, failure} = rep; + const { pattern, failure } = rep; const match = pattern.test(code); if (match) { self.error(failure + " " + id); @@ -387,40 +387,40 @@ function regexCheck (checks = []) { } -function regexReplace (replacements = []) { +function regexReplace(replacements = []) { const filter = createFilter("**/*.ts"); return { name: "regexReplace", - renderChunk (code, chunk) { + renderChunk(code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeReplacement(this, code, id); }, - transform (code, id) { + transform(code, id) { if (!filter(id)) return null; return executeReplacement(this, code, id); } }; - function executeReplacement (_, code, id) { + function executeReplacement(_, code, id) { const magicString = new MagicString(code); if (!codeHasReplacements(code, id, magicString)) { return null; } - const result = {code: magicString.toString()}; - result.map = magicString.generateMap({hires: true}); + const result = { code: magicString.toString() }; + result.map = magicString.generateMap({ hires: true }); return result; } - function codeHasReplacements (code, id, magicString) { + function codeHasReplacements(code, id, magicString) { let result = false; let match; for (const rep of replacements) { - const {pattern, replacement} = rep; + const { pattern, replacement } = rep; const rx = new RegExp(pattern, "gm"); while ((match = rx.exec(code))) { result = true; @@ -441,9 +441,9 @@ function regexReplace (replacements = []) { // Returns an array of objects {"workerName": "foo", "path": "/path/dotnet-foo-worker.ts"} // // A file looks like a webworker toplevel input if it's `dotnet-{name}-worker.ts` or `.js` -function findWebWorkerInputs (basePath) { +function findWebWorkerInputs(basePath) { const glob = "dotnet-*-worker.[tj]s"; - const files = fast_glob.sync(glob, {cwd: basePath}); + const files = fast_glob.sync(glob, { cwd: basePath }); if (files.length == 0) { return []; } @@ -452,13 +452,13 @@ function findWebWorkerInputs (basePath) { for (const file of files) { const match = file.match(re); if (match) { - results.push({"workerName": match[1], "path": path.join(basePath, file)}); + results.push({ "workerName": match[1], "path": path.join(basePath, file) }); } } return results; } -function onwarn (warning) { +function onwarn(warning) { if (warning.code === "CIRCULAR_DEPENDENCY") { return; } diff --git a/src/mono/browser/runtime/roots.ts b/src/mono/browser/runtime/roots.ts index c1d29d56ad92d9..24958a22e08458 100644 --- a/src/mono/browser/runtime/roots.ts +++ b/src/mono/browser/runtime/roots.ts @@ -4,11 +4,11 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import cwraps from "./cwraps"; -import {Module, mono_assert} from "./globals"; -import {VoidPtr, ManagedPointer, NativePointer} from "./types/emscripten"; -import {MonoObjectRef, MonoObjectRefNull, MonoObject, is_nullish, WasmRoot, WasmRootBuffer} from "./types/internal"; -import {_zero_region, localHeapViewU32} from "./memory"; -import {gc_locked} from "./gc-lock"; +import { Module, mono_assert } from "./globals"; +import { VoidPtr, ManagedPointer, NativePointer } from "./types/emscripten"; +import { MonoObjectRef, MonoObjectRefNull, MonoObject, is_nullish, WasmRoot, WasmRootBuffer } from "./types/internal"; +import { _zero_region, localHeapViewU32 } from "./memory"; +import { gc_locked } from "./gc-lock"; const maxScratchRoots = 8192; let _scratch_root_buffer: WasmRootBuffer | null = null; @@ -23,7 +23,7 @@ const _external_root_free_instances: WasmExternalRoot[] = []; * Once you are done using the root buffer, you must call its release() method. * For small numbers of roots, it is preferable to use the mono_wasm_new_root and mono_wasm_new_roots APIs instead. */ -export function mono_wasm_new_root_buffer (capacity: number, name?: string): WasmRootBuffer { +export function mono_wasm_new_root_buffer(capacity: number, name?: string): WasmRootBuffer { if (capacity <= 0) throw new Error("capacity >= 1"); @@ -43,7 +43,7 @@ export function mono_wasm_new_root_buffer (capacity: number, name?: string): Was * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. * Releasing this root will not de-allocate the root space. You still need to call .release(). */ -export function mono_wasm_new_external_root (address: VoidPtr | MonoObjectRef): WasmRoot { +export function mono_wasm_new_external_root(address: VoidPtr | MonoObjectRef): WasmRoot { let result: WasmExternalRoot; if (!address) @@ -66,7 +66,7 @@ export function mono_wasm_new_external_root (address: Void * The result object has get() and set(value) methods, along with a .value property. * When you are done using the root you must call its .release() method. */ -export function mono_wasm_new_root (value: T | undefined = undefined): WasmRoot { +export function mono_wasm_new_root(value: T | undefined = undefined): WasmRoot { let result: WasmRoot; if (_scratch_root_free_instances.length > 0) { @@ -96,7 +96,7 @@ export function mono_wasm_new_root (value: T | undefined = * mono_wasm_new_roots([a, b, ...]) returns an array of new roots initialized with each element. * Each root must be released with its release method, or using the mono_wasm_release_roots API. */ -export function mono_wasm_new_roots (count_or_values: number | T[]): WasmRoot[] { +export function mono_wasm_new_roots(count_or_values: number | T[]): WasmRoot[] { let result; if (Array.isArray(count_or_values)) { @@ -121,7 +121,7 @@ export function mono_wasm_new_roots (count_or_values: numb * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ -export function mono_wasm_release_roots (...args: WasmRoot[]): void { +export function mono_wasm_release_roots(...args: WasmRoot[]): void { for (let i = 0; i < args.length; i++) { if (is_nullish(args[i])) continue; @@ -130,7 +130,7 @@ export function mono_wasm_release_roots (...args: WasmRoot[]): void { } } -function _mono_wasm_release_scratch_index (index: number) { +function _mono_wasm_release_scratch_index(index: number) { if (index === undefined) return; @@ -139,7 +139,7 @@ function _mono_wasm_release_scratch_index (index: number) { _scratch_root_free_indices_count++; } -function _mono_wasm_claim_scratch_index () { +function _mono_wasm_claim_scratch_index() { if (is_nullish(_scratch_root_buffer) || !_scratch_root_free_indices) { _scratch_root_buffer = mono_wasm_new_root_buffer(maxScratchRoots, "js roots"); @@ -165,7 +165,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { private __handle: number; private __ownsAllocation: boolean; - constructor (offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { + constructor(offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { const capacityBytes = capacity * 4; this.__offset = offset; @@ -177,21 +177,21 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__ownsAllocation = ownsAllocation; } - _throw_index_out_of_range (): void { + _throw_index_out_of_range(): void { throw new Error("index out of range"); } - _check_in_range (index: number): void { + _check_in_range(index: number): void { if ((index >= this.__count) || (index < 0)) this._throw_index_out_of_range(); } - get_address (index: number): MonoObjectRef { + get_address(index: number): MonoObjectRef { this._check_in_range(index); return this.__offset + (index * 4); } - get_address_32 (index: number): number { + get_address_32(index: number): number { this._check_in_range(index); return this.__offset32 + index; } @@ -199,38 +199,38 @@ export class WasmRootBufferImpl implements WasmRootBuffer { // NOTE: These functions do not use the helpers from memory.ts because WasmRoot.get and WasmRoot.set // are hot-spots when you profile any application that uses the bindings extensively. - get (index: number): ManagedPointer { + get(index: number): ManagedPointer { this._check_in_range(index); const offset = this.get_address_32(index); return localHeapViewU32()[offset]; } - set (index: number, value: ManagedPointer): ManagedPointer { + set(index: number, value: ManagedPointer): ManagedPointer { const address = this.get_address(index); cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); return value; } - copy_value_from_address (index: number, sourceAddress: MonoObjectRef): void { + copy_value_from_address(index: number, sourceAddress: MonoObjectRef): void { const destinationAddress = this.get_address(index); cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - _unsafe_get (index: number): number { + _unsafe_get(index: number): number { return localHeapViewU32()[this.__offset32 + index]; } - _unsafe_set (index: number, value: ManagedPointer | NativePointer): void { + _unsafe_set(index: number, value: ManagedPointer | NativePointer): void { const address = this.__offset + index; cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); } - clear (): void { + clear(): void { if (this.__offset) _zero_region(this.__offset, this.__count * 4); } - release (): void { + release(): void { if (this.__offset && this.__ownsAllocation) { mono_assert(!WasmEnableThreads || !gc_locked, "GC must not be locked when disposing a GC root"); cwraps.mono_wasm_deregister_root(this.__offset); @@ -241,7 +241,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__handle = (this.__offset) = this.__count = this.__offset32 = 0; } - toString (): string { + toString(): string { return `[root buffer @${this.get_address(0)}, size ${this.__count} ]`; } } @@ -250,76 +250,76 @@ class WasmJsOwnedRoot implements WasmRoot { private __buffer: WasmRootBuffer; private __index: number; - constructor (buffer: WasmRootBuffer, index: number) { + constructor(buffer: WasmRootBuffer, index: number) { this.__buffer = buffer;//TODO this.__index = index; } - get_address (): MonoObjectRef { + get_address(): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get_address_32 (): number { + get_address_32(): number { return this.__buffer.get_address_32(this.__index); } - get address (): MonoObjectRef { + get address(): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get (): T { + get(): T { const result = (this.__buffer)._unsafe_get(this.__index); return result; } - set (value: T): T { + set(value: T): T { const destinationAddress = this.__buffer.get_address(this.__index); cwraps.mono_wasm_write_managed_pointer_unsafe(destinationAddress, value); return value; } - copy_from (source: WasmRoot): void { + copy_from(source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to (destination: WasmRoot): void { + copy_to(destination: WasmRoot): void { const sourceAddress = this.address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address (source: MonoObjectRef): void { + copy_from_address(source: MonoObjectRef): void { const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address (destination: MonoObjectRef): void { + copy_to_address(destination: MonoObjectRef): void { const sourceAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value (): T { + get value(): T { return this.get(); } - set value (value: T) { + set value(value: T) { this.set(value); } - valueOf (): T { + valueOf(): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear (): void { + clear(): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC const address32 = this.__buffer.get_address_32(this.__index); localHeapViewU32()[address32] = 0; } - release (): void { + release(): void { if (!this.__buffer) throw new Error("No buffer"); @@ -334,7 +334,7 @@ class WasmJsOwnedRoot implements WasmRoot { } } - toString (): string { + toString(): string { return `[root @${this.address}]`; } } @@ -343,84 +343,84 @@ class WasmExternalRoot implements WasmRoot { private __external_address: MonoObjectRef = MonoObjectRefNull; private __external_address_32: number = 0; - constructor (address: NativePointer | ManagedPointer) { + constructor(address: NativePointer | ManagedPointer) { this._set_address(address); } - _set_address (address: NativePointer | ManagedPointer): void { + _set_address(address: NativePointer | ManagedPointer): void { this.__external_address = address; this.__external_address_32 = address >>> 2; } - get address (): MonoObjectRef { + get address(): MonoObjectRef { return this.__external_address; } - get_address (): MonoObjectRef { + get_address(): MonoObjectRef { return this.__external_address; } - get_address_32 (): number { + get_address_32(): number { return this.__external_address_32; } - get (): T { + get(): T { const result = localHeapViewU32()[this.__external_address_32]; return result; } - set (value: T): T { + set(value: T): T { cwraps.mono_wasm_write_managed_pointer_unsafe(this.__external_address, value); return value; } - copy_from (source: WasmRoot): void { + copy_from(source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to (destination: WasmRoot): void { + copy_to(destination: WasmRoot): void { const sourceAddress = this.__external_address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address (source: MonoObjectRef): void { + copy_from_address(source: MonoObjectRef): void { const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address (destination: MonoObjectRef): void { + copy_to_address(destination: MonoObjectRef): void { const sourceAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value (): T { + get value(): T { return this.get(); } - set value (value: T) { + set value(value: T) { this.set(value); } - valueOf (): T { + valueOf(): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear (): void { + clear(): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC localHeapViewU32()[this.__external_address >>> 2] = 0; } - release (): void { + release(): void { const maxPooledInstances = 128; if (_external_root_free_instances.length < maxPooledInstances) _external_root_free_instances.push(this); } - toString (): string { + toString(): string { return `[external root @${this.address}]`; } } diff --git a/src/mono/browser/runtime/run.ts b/src/mono/browser/runtime/run.ts index e2fdf8f5e20920..a107f754556276 100644 --- a/src/mono/browser/runtime/run.ts +++ b/src/mono/browser/runtime/run.ts @@ -3,18 +3,18 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert, runtimeHelpers} from "./globals"; -import {mono_wasm_wait_for_debugger} from "./debug"; -import {mono_wasm_set_main_args} from "./startup"; +import { ENVIRONMENT_IS_NODE, Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; +import { mono_wasm_wait_for_debugger } from "./debug"; +import { mono_wasm_set_main_args } from "./startup"; import cwraps from "./cwraps"; -import {mono_log_info} from "./logging"; -import {cancelThreads} from "./pthreads"; -import {call_entry_point} from "./managed-exports"; +import { mono_log_info } from "./logging"; +import { cancelThreads } from "./pthreads"; +import { call_entry_point } from "./managed-exports"; /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main_and_exit (main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main_and_exit(main_assembly_name?: string, args?: string[]): Promise { try { const result = await mono_run_main(main_assembly_name, args); loaderHelpers.mono_exit(result); @@ -35,7 +35,7 @@ export async function mono_run_main_and_exit (main_assembly_name?: string, args? /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main (main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main(main_assembly_name?: string, args?: string[]): Promise { if (main_assembly_name === undefined || main_assembly_name === null || main_assembly_name === "") { main_assembly_name = loaderHelpers.config.mainAssemblyName; mono_assert(main_assembly_name, "Null or empty config.mainAssemblyName"); @@ -76,14 +76,14 @@ export async function mono_run_main (main_assembly_name?: string, args?: string[ -export function nativeExit (code: number) { +export function nativeExit(code: number) { if (WasmEnableThreads) { cancelThreads(); } cwraps.mono_wasm_exit(code); } -export function nativeAbort (reason: any) { +export function nativeAbort(reason: any) { loaderHelpers.exitReason = reason; if (!loaderHelpers.is_exited()) { cwraps.mono_wasm_abort(); diff --git a/src/mono/browser/runtime/satelliteAssemblies.ts b/src/mono/browser/runtime/satelliteAssemblies.ts index d2030e24abe1c0..3cd534bf4e533f 100644 --- a/src/mono/browser/runtime/satelliteAssemblies.ts +++ b/src/mono/browser/runtime/satelliteAssemblies.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {loaderHelpers} from "./globals"; -import {load_satellite_assembly} from "./managed-exports"; -import {AssetEntry} from "./types"; +import { loaderHelpers } from "./globals"; +import { load_satellite_assembly } from "./managed-exports"; +import { AssetEntry } from "./types"; -export async function loadSatelliteAssemblies (culturesToLoad: string[]): Promise { +export async function loadSatelliteAssemblies(culturesToLoad: string[]): Promise { const satelliteResources = loaderHelpers.config.resources!.satelliteResources; if (!satelliteResources) { return; diff --git a/src/mono/browser/runtime/scheduling.ts b/src/mono/browser/runtime/scheduling.ts index d0b3820358a17f..1a537645a3da94 100644 --- a/src/mono/browser/runtime/scheduling.ts +++ b/src/mono/browser/runtime/scheduling.ts @@ -4,14 +4,14 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import cwraps from "./cwraps"; -import {ENVIRONMENT_IS_WORKER, Module, loaderHelpers} from "./globals"; -import {forceThreadMemoryViewRefresh} from "./memory"; -import {is_thread_available} from "./pthreads"; +import { ENVIRONMENT_IS_WORKER, Module, loaderHelpers } from "./globals"; +import { forceThreadMemoryViewRefresh } from "./memory"; +import { is_thread_available } from "./pthreads"; let spread_timers_maximum = 0; let pump_count = 0; -export function prevent_timer_throttling (): void { +export function prevent_timer_throttling(): void { if (!loaderHelpers.isChromium) { return; } @@ -29,7 +29,7 @@ export function prevent_timer_throttling (): void { spread_timers_maximum = desired_reach_time; } -function prevent_timer_throttling_tick () { +function prevent_timer_throttling_tick() { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -42,7 +42,7 @@ function prevent_timer_throttling_tick () { mono_background_exec_until_done(); } -function mono_background_exec_until_done () { +function mono_background_exec_until_done() { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -56,10 +56,10 @@ function mono_background_exec_until_done () { } } -export function schedule_background_exec (): void { +export function schedule_background_exec(): void { ++pump_count; let max_postpone_count = 10; - function postpone_schedule_background () { + function postpone_schedule_background() { if (max_postpone_count < 0 || is_thread_available()) { Module.safeSetTimeout(mono_background_exec_until_done, 0); } else { @@ -77,7 +77,7 @@ export function schedule_background_exec (): void { } let lastScheduledTimeoutId: any = undefined; -export function mono_wasm_schedule_timer (shortestDueTimeMs: number): void { +export function mono_wasm_schedule_timer(shortestDueTimeMs: number): void { if (lastScheduledTimeoutId) { globalThis.clearTimeout(lastScheduledTimeoutId); lastScheduledTimeoutId = undefined; @@ -89,7 +89,7 @@ export function mono_wasm_schedule_timer (shortestDueTimeMs: number): void { lastScheduledTimeoutId = Module.safeSetTimeout(mono_wasm_schedule_timer_tick, shortestDueTimeMs); } -function mono_wasm_schedule_timer_tick () { +function mono_wasm_schedule_timer_tick() { Module.maybeExit(); if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); diff --git a/src/mono/browser/runtime/startup.ts b/src/mono/browser/runtime/startup.ts index 69176b29602795..dd3ddaeffbf71a 100644 --- a/src/mono/browser/runtime/startup.ts +++ b/src/mono/browser/runtime/startup.ts @@ -4,44 +4,44 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import BuildConfiguration from "consts:configuration"; -import {DotnetModuleInternal, CharPtrNull, MainThreadingMode} from "./types/internal"; -import {exportedRuntimeAPI, INTERNAL, loaderHelpers, Module, runtimeHelpers, createPromiseController, mono_assert} from "./globals"; -import cwraps, {init_c_exports, threads_c_functions as tcwraps} from "./cwraps"; -import {mono_wasm_raise_debug_event, mono_wasm_runtime_ready} from "./debug"; -import {toBase64StringImpl} from "./base64"; -import {mono_wasm_init_aot_profiler, mono_wasm_init_browser_profiler} from "./profiler"; -import {initialize_marshalers_to_cs} from "./marshal-to-cs"; -import {initialize_marshalers_to_js} from "./marshal-to-js"; -import {init_polyfills_async} from "./polyfills"; -import {strings_init, utf8ToString} from "./strings"; -import {init_managed_exports, install_main_synchronization_context} from "./managed-exports"; -import {cwraps_internal} from "./exports-internal"; -import {CharPtr, InstantiateWasmCallBack, InstantiateWasmSuccessCallback} from "./types/emscripten"; -import {wait_for_all_assets} from "./assets"; -import {replace_linker_placeholders} from "./exports-binding"; -import {endMeasure, MeasuredBlock, startMeasure} from "./profiler"; -import {interp_pgo_load_data, interp_pgo_save_data} from "./interp-pgo"; -import {mono_log_debug, mono_log_error, mono_log_info, mono_log_warn} from "./logging"; +import { DotnetModuleInternal, CharPtrNull, MainThreadingMode } from "./types/internal"; +import { exportedRuntimeAPI, INTERNAL, loaderHelpers, Module, runtimeHelpers, createPromiseController, mono_assert } from "./globals"; +import cwraps, { init_c_exports, threads_c_functions as tcwraps } from "./cwraps"; +import { mono_wasm_raise_debug_event, mono_wasm_runtime_ready } from "./debug"; +import { toBase64StringImpl } from "./base64"; +import { mono_wasm_init_aot_profiler, mono_wasm_init_browser_profiler } from "./profiler"; +import { initialize_marshalers_to_cs } from "./marshal-to-cs"; +import { initialize_marshalers_to_js } from "./marshal-to-js"; +import { init_polyfills_async } from "./polyfills"; +import { strings_init, utf8ToString } from "./strings"; +import { init_managed_exports, install_main_synchronization_context } from "./managed-exports"; +import { cwraps_internal } from "./exports-internal"; +import { CharPtr, InstantiateWasmCallBack, InstantiateWasmSuccessCallback } from "./types/emscripten"; +import { wait_for_all_assets } from "./assets"; +import { replace_linker_placeholders } from "./exports-binding"; +import { endMeasure, MeasuredBlock, startMeasure } from "./profiler"; +import { interp_pgo_load_data, interp_pgo_save_data } from "./interp-pgo"; +import { mono_log_debug, mono_log_error, mono_log_info, mono_log_warn } from "./logging"; // threads -import {populateEmscriptenPool, mono_wasm_init_threads, init_finalizer_thread} from "./pthreads"; -import {currentWorkerThreadEvents, dotnetPthreadCreated, initWorkerThreadEvents, monoThreadInfo} from "./pthreads"; -import {mono_wasm_pthread_ptr, update_thread_info} from "./pthreads"; -import {jiterpreter_allocate_tables} from "./jiterpreter-support"; -import {localHeapViewU8} from "./memory"; -import {assertNoProxies} from "./gc-handles"; -import {runtimeList} from "./exports"; -import {nativeAbort, nativeExit} from "./run"; -import {mono_wasm_init_diagnostics} from "./diagnostics"; -import {replaceEmscriptenPThreadInit} from "./pthreads/worker-thread"; - -export async function configureRuntimeStartup (): Promise { +import { populateEmscriptenPool, mono_wasm_init_threads, init_finalizer_thread } from "./pthreads"; +import { currentWorkerThreadEvents, dotnetPthreadCreated, initWorkerThreadEvents, monoThreadInfo } from "./pthreads"; +import { mono_wasm_pthread_ptr, update_thread_info } from "./pthreads"; +import { jiterpreter_allocate_tables } from "./jiterpreter-support"; +import { localHeapViewU8 } from "./memory"; +import { assertNoProxies } from "./gc-handles"; +import { runtimeList } from "./exports"; +import { nativeAbort, nativeExit } from "./run"; +import { mono_wasm_init_diagnostics } from "./diagnostics"; +import { replaceEmscriptenPThreadInit } from "./pthreads/worker-thread"; + +export async function configureRuntimeStartup(): Promise { await init_polyfills_async(); } // we are making emscripten startup async friendly // emscripten is executing the events without awaiting it and so we need to block progress via PromiseControllers above -export function configureEmscriptenStartup (module: DotnetModuleInternal): void { +export function configureEmscriptenStartup(module: DotnetModuleInternal): void { const mark = startMeasure(); if (!module.locateFile) { @@ -84,7 +84,7 @@ export function configureEmscriptenStartup (module: DotnetModuleInternal): void module.postRun = [() => postRunAsync(userpostRun)]; // execution order == [6] == - module.ready.then(async () => { + module.ready.then(async() => { // wait for previous stage await runtimeHelpers.afterPostRun.promise; // startup end @@ -98,7 +98,7 @@ export function configureEmscriptenStartup (module: DotnetModuleInternal): void module.ready = runtimeHelpers.dotnetReady.promise; } -function instantiateWasm ( +function instantiateWasm( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, userInstantiateWasm?: InstantiateWasmCallBack): any[] { @@ -118,7 +118,7 @@ function instantiateWasm ( return []; // No exports } -async function instantiateWasmWorker ( +async function instantiateWasmWorker( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback ): Promise { @@ -136,7 +136,7 @@ async function instantiateWasmWorker ( Module.wasmModule = null; } -function preInit (userPreInit: (() => void)[]) { +function preInit(userPreInit: (() => void)[]) { Module.addRunDependency("mono_pre_init"); const mark = startMeasure(); try { @@ -153,7 +153,7 @@ function preInit (userPreInit: (() => void)[]) { // this will start immediately but return on first await. // It will block our `preRun` by afterPreInit promise // It will block emscripten `userOnRuntimeInitialized` by pending addRunDependency("mono_pre_init") - (async () => { + (async() => { try { // - init the rest of the polyfills await mono_wasm_pre_init_essential_async(); @@ -169,7 +169,7 @@ function preInit (userPreInit: (() => void)[]) { })(); } -async function preInitWorkerAsync () { +async function preInitWorkerAsync() { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -193,7 +193,7 @@ async function preInitWorkerAsync () { } // runs for each re-attached worker -export function preRunWorker () { +export function preRunWorker() { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -209,7 +209,7 @@ export function preRunWorker () { } } -async function preRunAsync (userPreRun: (() => void)[]) { +async function preRunAsync(userPreRun: (() => void)[]) { Module.addRunDependency("mono_pre_run_async"); // wait for previous stages try { @@ -230,7 +230,7 @@ async function preRunAsync (userPreRun: (() => void)[]) { Module.removeRunDependency("mono_pre_run_async"); } -async function onRuntimeInitializedAsync (userOnRuntimeInitialized: () => void) { +async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { try { // wait for previous stage await runtimeHelpers.afterPreRun.promise; @@ -337,7 +337,7 @@ async function onRuntimeInitializedAsync (userOnRuntimeInitialized: () => void) runtimeHelpers.afterOnRuntimeInitialized.promise_control.resolve(); } -async function postRunAsync (userpostRun: (() => void)[]) { +async function postRunAsync(userpostRun: (() => void)[]) { // wait for previous stage try { await runtimeHelpers.afterOnRuntimeInitialized.promise; @@ -361,7 +361,7 @@ async function postRunAsync (userpostRun: (() => void)[]) { } // runs for each re-detached worker -export function postRunWorker () { +export function postRunWorker() { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -382,7 +382,7 @@ export function postRunWorker () { } } -function mono_wasm_pre_init_essential (isWorker: boolean): void { +function mono_wasm_pre_init_essential(isWorker: boolean): void { if (!isWorker) Module.addRunDependency("mono_wasm_pre_init_essential"); @@ -409,7 +409,7 @@ function mono_wasm_pre_init_essential (isWorker: boolean): void { Module.removeRunDependency("mono_wasm_pre_init_essential"); } -async function mono_wasm_pre_init_essential_async (): Promise { +async function mono_wasm_pre_init_essential_async(): Promise { mono_log_debug("mono_wasm_pre_init_essential_async"); Module.addRunDependency("mono_wasm_pre_init_essential_async"); @@ -420,7 +420,7 @@ async function mono_wasm_pre_init_essential_async (): Promise { Module.removeRunDependency("mono_wasm_pre_init_essential_async"); } -async function mono_wasm_after_user_runtime_initialized (): Promise { +async function mono_wasm_after_user_runtime_initialized(): Promise { mono_log_debug("mono_wasm_after_user_runtime_initialized"); try { if (Module.onDotnetReady) { @@ -439,11 +439,11 @@ async function mono_wasm_after_user_runtime_initialized (): Promise { // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases -export function mono_wasm_setenv (name: string, value: string): void { +export function mono_wasm_setenv(name: string, value: string): void { cwraps.mono_wasm_setenv(name, value); } -export function mono_wasm_set_runtime_options (options: string[]): void { +export function mono_wasm_set_runtime_options(options: string[]): void { if (!Array.isArray(options)) throw new Error("Expected runtimeOptions to be an array of strings"); @@ -459,7 +459,7 @@ export function mono_wasm_set_runtime_options (options: string[]): void { cwraps.mono_wasm_parse_runtime_options(options.length, argv); } -async function instantiate_wasm_module ( +async function instantiate_wasm_module( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, ): Promise { @@ -489,7 +489,7 @@ async function instantiate_wasm_module ( Module.removeRunDependency("instantiate_wasm_module"); } -async function ensureUsedWasmFeatures () { +async function ensureUsedWasmFeatures() { runtimeHelpers.featureWasmSimd = await loaderHelpers.simd(); runtimeHelpers.featureWasmEh = await loaderHelpers.exceptions(); if (runtimeHelpers.emscriptenBuildOptions.wasmEnableSIMD) { @@ -500,7 +500,7 @@ async function ensureUsedWasmFeatures () { } } -export async function start_runtime () { +export async function start_runtime() { try { const mark = startMeasure(); mono_log_debug("Initializing mono runtime"); @@ -564,7 +564,7 @@ export async function start_runtime () { } } -async function maybeSaveInterpPgoTable () { +async function maybeSaveInterpPgoTable() { // If the application exited abnormally, don't save the table. It probably doesn't contain useful data, // and saving would overwrite any existing table from a previous successful run. // We treat exiting with a code of 0 as equivalent to if the app is still running - it's perfectly fine @@ -575,7 +575,7 @@ async function maybeSaveInterpPgoTable () { await interp_pgo_save_data(); } -export function mono_wasm_load_runtime (): void { +export function mono_wasm_load_runtime(): void { mono_log_debug("mono_wasm_load_runtime"); try { const mark = startMeasure(); @@ -599,7 +599,7 @@ export function mono_wasm_load_runtime (): void { } } -export function bindings_init (): void { +export function bindings_init(): void { if (runtimeHelpers.mono_wasm_bindings_is_ready) { return; } @@ -620,7 +620,7 @@ export function bindings_init (): void { } -export function mono_wasm_asm_loaded (assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { +export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (runtimeHelpers.mono_wasm_runtime_is_ready !== true) return; @@ -643,7 +643,7 @@ export function mono_wasm_asm_loaded (assembly_name: CharPtr, assembly_ptr: numb }); } -export function mono_wasm_set_main_args (name: string, allRuntimeArguments: string[]): void { +export function mono_wasm_set_main_args(name: string, allRuntimeArguments: string[]): void { const main_argc = allRuntimeArguments.length + 1; const main_argv = Module._malloc(main_argc * 4); let aindex = 0; @@ -663,7 +663,7 @@ export function mono_wasm_set_main_args (name: string, allRuntimeArguments: stri /// 1. Emscripten skips a lot of initialization on the pthread workers, Module may not have everything you expect. /// 2. Emscripten does not run any event but preInit in the workers. /// 3. At the point when this executes there is no pthread assigned to the worker yet. -export async function configureWorkerStartup (module: DotnetModuleInternal): Promise { +export async function configureWorkerStartup(module: DotnetModuleInternal): Promise { if (!WasmEnableThreads) return; initWorkerThreadEvents(); diff --git a/src/mono/browser/runtime/strings.ts b/src/mono/browser/runtime/strings.ts index b57fcca62e5e0a..d0d798c161b28f 100644 --- a/src/mono/browser/runtime/strings.ts +++ b/src/mono/browser/runtime/strings.ts @@ -1,12 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {mono_wasm_new_root, mono_wasm_new_root_buffer} from "./roots"; -import {MonoString, MonoStringNull, WasmRoot, WasmRootBuffer} from "./types/internal"; -import {Module} from "./globals"; +import { mono_wasm_new_root, mono_wasm_new_root_buffer } from "./roots"; +import { MonoString, MonoStringNull, WasmRoot, WasmRootBuffer } from "./types/internal"; +import { Module } from "./globals"; import cwraps from "./cwraps"; -import {isSharedArrayBuffer, localHeapViewU8, getU32_local, setU16_local, localHeapViewU32, getU16_local, localHeapViewU16, _zero_region} from "./memory"; -import {NativePointer, CharPtr} from "./types/emscripten"; +import { isSharedArrayBuffer, localHeapViewU8, getU32_local, setU16_local, localHeapViewU32, getU16_local, localHeapViewU16, _zero_region } from "./memory"; +import { NativePointer, CharPtr } from "./types/emscripten"; export const interned_js_string_table = new Map(); export const mono_wasm_empty_string = ""; @@ -21,11 +21,11 @@ let _text_decoder_utf8_relaxed: TextDecoder | undefined = undefined; let _text_decoder_utf8_validating: TextDecoder | undefined = undefined; let _text_encoder_utf8: TextEncoder | undefined = undefined; -export function strings_init (): void { +export function strings_init(): void { if (!mono_wasm_string_decoder_buffer) { if (typeof TextDecoder !== "undefined") { _text_decoder_utf16 = new TextDecoder("utf-16le"); - _text_decoder_utf8_relaxed = new TextDecoder("utf-8", {fatal: false}); + _text_decoder_utf8_relaxed = new TextDecoder("utf-8", { fatal: false }); _text_decoder_utf8_validating = new TextDecoder("utf-8"); _text_encoder_utf8 = new TextEncoder(); } @@ -35,7 +35,7 @@ export function strings_init (): void { mono_wasm_string_root = mono_wasm_new_root(); } -export function stringToUTF8 (str: string): Uint8Array { +export function stringToUTF8(str: string): Uint8Array { if (_text_encoder_utf8 === undefined) { const buffer = new Uint8Array(str.length * 2); Module.stringToUTF8Array(str, buffer, 0, str.length * 2); @@ -44,7 +44,7 @@ export function stringToUTF8 (str: string): Uint8Array { return _text_encoder_utf8.encode(str); } -export function stringToUTF8Ptr (str: string): CharPtr { +export function stringToUTF8Ptr(str: string): CharPtr { const bytes = str.length * 2; const ptr = Module._malloc(bytes) as any; _zero_region(ptr, str.length * 2); @@ -53,19 +53,19 @@ export function stringToUTF8Ptr (str: string): CharPtr { return ptr; } -export function utf8ToStringRelaxed (buffer: Uint8Array): string { +export function utf8ToStringRelaxed(buffer: Uint8Array): string { if (_text_decoder_utf8_relaxed === undefined) { return Module.UTF8ArrayToString(buffer, 0, buffer.byteLength); } return _text_decoder_utf8_relaxed.decode(buffer); } -export function utf8ToString (ptr: CharPtr): string { +export function utf8ToString(ptr: CharPtr): string { const heapU8 = localHeapViewU8(); return utf8BufferToString(heapU8, ptr as any, heapU8.length - (ptr as any)); } -export function utf8BufferToString (heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { +export function utf8BufferToString(heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { const endIdx = idx + maxBytesToRead; let endPtr = idx; while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; @@ -79,7 +79,7 @@ export function utf8BufferToString (heapOrArray: Uint8Array, idx: number, maxByt return _text_decoder_utf8_validating.decode(view); } -export function utf16ToString (startPtr: number, endPtr: number): string { +export function utf16ToString(startPtr: number, endPtr: number): string { if (_text_decoder_utf16) { const subArray = viewOrCopy(localHeapViewU8(), startPtr as any, endPtr as any); return _text_decoder_utf16.decode(subArray); @@ -88,7 +88,7 @@ export function utf16ToString (startPtr: number, endPtr: number): string { } } -export function utf16ToStringLoop (startPtr: number, endPtr: number): string { +export function utf16ToStringLoop(startPtr: number, endPtr: number): string { let str = ""; const heapU16 = localHeapViewU16(); for (let i = startPtr; i < endPtr; i += 2) { @@ -98,7 +98,7 @@ export function utf16ToStringLoop (startPtr: number, endPtr: number): string { return str; } -export function stringToUTF16 (dstPtr: number, endPtr: number, text: string) { +export function stringToUTF16(dstPtr: number, endPtr: number, text: string) { const heapI16 = localHeapViewU16(); const len = text.length; for (let i = 0; i < len; i++) { @@ -108,7 +108,7 @@ export function stringToUTF16 (dstPtr: number, endPtr: number, text: string) { } } -export function monoStringToString (root: WasmRoot): string | null { +export function monoStringToString(root: WasmRoot): string | null { if (root.value === MonoStringNull) return null; @@ -142,7 +142,7 @@ export function monoStringToString (root: WasmRoot): string | null { return result; } -export function stringToMonoStringRoot (string: string, result: WasmRoot): void { +export function stringToMonoStringRoot(string: string, result: WasmRoot): void { result.clear(); if (string === null) @@ -171,7 +171,7 @@ export function stringToMonoStringRoot (string: string, result: WasmRoot): void { +function stringToInternedMonoStringRoot(string: string | symbol, result: WasmRoot): void { let text: string | undefined; if (typeof (string) === "symbol") { text = string.description; @@ -204,7 +204,7 @@ function stringToInternedMonoStringRoot (string: string | symbol, result: WasmRo storeStringInInternTable(text, result, true); } -function storeStringInInternTable (string: string, root: WasmRoot, internIt: boolean): void { +function storeStringInInternTable(string: string, root: WasmRoot, internIt: boolean): void { if (!root.value) throw new Error("null pointer passed to _store_string_in_intern_table"); @@ -242,7 +242,7 @@ function storeStringInInternTable (string: string, root: WasmRoot, i rootBuffer.copy_value_from_address(index, root.address); } -function stringToMonoStringNewRoot (string: string, result: WasmRoot): void { +function stringToMonoStringNewRoot(string: string, result: WasmRoot): void { const bufferLen = (string.length + 1) * 2; // TODO this could be stack allocated for small strings // or temp_malloc/alloca for large strings @@ -256,7 +256,7 @@ function stringToMonoStringNewRoot (string: string, result: WasmRoot // When threading is enabled, TextDecoder does not accept a view of a // SharedArrayBuffer, we must make a copy of the array first. // See https://github.com/whatwg/encoding/issues/172 -export function viewOrCopy (view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { +export function viewOrCopy(view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { // this condition should be eliminated by rollup on non-threading builds const needsCopy = isSharedArrayBuffer(view.buffer); return needsCopy @@ -268,7 +268,7 @@ export function viewOrCopy (view: Uint8Array, start: CharPtr, end: CharPtr): Uin let mono_wasm_string_root: any; /* @deprecated not GC safe, use monoStringToString */ -export function monoStringToStringUnsafe (mono_string: MonoString): string | null { +export function monoStringToStringUnsafe(mono_string: MonoString): string | null { if (mono_string === MonoStringNull) return null; diff --git a/src/mono/browser/runtime/types/export-types.ts b/src/mono/browser/runtime/types/export-types.ts index cb2cee31ed8cd2..cdd34f35178ab5 100644 --- a/src/mono/browser/runtime/types/export-types.ts +++ b/src/mono/browser/runtime/types/export-types.ts @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {IMemoryView} from "../marshal"; -import type {CreateDotnetRuntimeType, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, MonoConfig, ModuleAPI, AssetEntry, GlobalizationMode, AssetBehaviors} from "."; -import type {EmscriptenModule} from "./emscripten"; -import type {dotnet, exit} from "../loader/index"; +import type { IMemoryView } from "../marshal"; +import type { CreateDotnetRuntimeType, DotnetHostBuilder, DotnetModuleConfig, RuntimeAPI, MonoConfig, ModuleAPI, AssetEntry, GlobalizationMode, AssetBehaviors } from "."; +import type { EmscriptenModule } from "./emscripten"; +import type { dotnet, exit } from "../loader/index"; // ----------------------------------------------------------- // this files has all public exports from the dotnet.js module diff --git a/src/mono/browser/runtime/types/index.ts b/src/mono/browser/runtime/types/index.ts index 047019dc8e7455..c5754f6c89e8fc 100644 --- a/src/mono/browser/runtime/types/index.ts +++ b/src/mono/browser/runtime/types/index.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import type {EmscriptenModule, NativePointer} from "./emscripten"; +import type { EmscriptenModule, NativePointer } from "./emscripten"; export interface DotnetHostBuilder { /** diff --git a/src/mono/browser/runtime/types/internal.ts b/src/mono/browser/runtime/types/internal.ts index c5bb3c61b764e8..1189ef4f63b575 100644 --- a/src/mono/browser/runtime/types/internal.ts +++ b/src/mono/browser/runtime/types/internal.ts @@ -1,8 +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 type {AssetEntry, DotnetModuleConfig, LoadBootResourceCallback, LoadingResource, MonoConfig, RuntimeAPI, SingleAssetBehaviors} from "."; -import type {CharPtr, EmscriptenModule, ManagedPointer, NativePointer, VoidPtr, Int32Ptr} from "./emscripten"; +import type { AssetEntry, DotnetModuleConfig, LoadBootResourceCallback, LoadingResource, MonoConfig, RuntimeAPI, SingleAssetBehaviors } from "."; +import type { CharPtr, EmscriptenModule, ManagedPointer, NativePointer, VoidPtr, Int32Ptr } from "./emscripten"; export type GCHandle = { __brand: "GCHandle" @@ -64,7 +64,7 @@ export const CharPtrNull: CharPtr = 0; export const NativePointerNull: NativePointer = 0; export const PThreadPtrNull: PThreadPtr = 0; -export function coerceNull (ptr: T | null | undefined): T { +export function coerceNull(ptr: T | null | undefined): T { if ((ptr === null) || (ptr === undefined)) return (0 as any) as T; else @@ -254,7 +254,7 @@ export type DotnetModuleInternal = EmscriptenModule & DotnetModuleConfig & Emscr // Evaluates whether a value is nullish (same definition used as the ?? operator, // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) -export function is_nullish (value: T | null | undefined): value is null | undefined { +export function is_nullish(value: T | null | undefined): value is null | undefined { return (value === undefined) || (value === null); } @@ -299,14 +299,14 @@ export interface ExitStatusError { /// Always throws. Used to handle unreachable switch branches when TypeScript refines the type of a variable /// to 'never' after you handle all the cases it knows about. -export function assertNever (x: never): never { +export function assertNever(x: never): never { throw new Error("Unexpected value: " + x); } /// returns true if the given value is not Thenable /// /// Useful if some function returns a value or a promise of a value. -export function notThenable (x: T | PromiseLike): x is T { +export function notThenable(x: T | PromiseLike): x is T { return typeof x !== "object" || typeof ((>x).then) !== "function"; } diff --git a/src/mono/browser/runtime/weak-ref.ts b/src/mono/browser/runtime/weak-ref.ts index d0ea943dcbf505..fee25ef8712dd8 100644 --- a/src/mono/browser/runtime/weak-ref.ts +++ b/src/mono/browser/runtime/weak-ref.ts @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import {WeakRefInternal} from "./types/internal"; +import { WeakRefInternal } from "./types/internal"; export const _use_weak_ref = typeof globalThis.WeakRef === "function"; -export function create_weak_ref (js_obj: T): WeakRefInternal { +export function create_weak_ref(js_obj: T): WeakRefInternal { if (_use_weak_ref) { return new WeakRef(js_obj); } else { @@ -14,7 +14,7 @@ export function create_weak_ref (js_obj: T): WeakRefInternal (js_obj: T): WeakRefInternal { +export function create_strong_ref(js_obj: T): WeakRefInternal { return { deref: () => { return js_obj; diff --git a/src/mono/browser/runtime/web-socket.ts b/src/mono/browser/runtime/web-socket.ts index 21209088f88466..f83def338f8922 100644 --- a/src/mono/browser/runtime/web-socket.ts +++ b/src/mono/browser/runtime/web-socket.ts @@ -3,16 +3,16 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; -import {prevent_timer_throttling} from "./scheduling"; -import {Queue} from "./queue"; -import {ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, createPromiseController, loaderHelpers, mono_assert} from "./globals"; -import {setI32, localHeapViewU8, forceThreadMemoryViewRefresh} from "./memory"; -import {VoidPtr} from "./types/emscripten"; -import {PromiseController} from "./types/internal"; -import {mono_log_warn} from "./logging"; -import {viewOrCopy, utf8ToStringRelaxed, stringToUTF8} from "./strings"; -import {wrap_as_cancelable} from "./cancelable-promise"; -import {assert_js_interop} from "./invoke-js"; +import { prevent_timer_throttling } from "./scheduling"; +import { Queue } from "./queue"; +import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, createPromiseController, loaderHelpers, mono_assert } from "./globals"; +import { setI32, localHeapViewU8, forceThreadMemoryViewRefresh } from "./memory"; +import { VoidPtr } from "./types/emscripten"; +import { PromiseController } from "./types/internal"; +import { mono_log_warn } from "./logging"; +import { viewOrCopy, utf8ToStringRelaxed, stringToUTF8 } from "./strings"; +import { wrap_as_cancelable } from "./cancelable-promise"; +import { assert_js_interop } from "./invoke-js"; const wasm_ws_pending_send_buffer = Symbol.for("wasm ws_pending_send_buffer"); const wasm_ws_pending_send_buffer_offset = Symbol.for("wasm ws_pending_send_buffer_offset"); @@ -32,7 +32,7 @@ const wasm_ws_receive_status_ptr = Symbol.for("wasm ws_receive_status_ptr"); const ws_send_buffer_blocking_threshold = 65536; const emptyBuffer = new Uint8Array(); -function verifyEnvironment () { +function verifyEnvironment() { if (ENVIRONMENT_IS_SHELL) { throw new Error("WebSockets are not supported in shell JS engine."); } @@ -44,7 +44,7 @@ function verifyEnvironment () { } } -export function ws_get_state (ws: WebSocketExtension) : number { +export function ws_get_state(ws: WebSocketExtension) : number { if (ws.readyState != WebSocket.CLOSED) return ws.readyState ?? -1; const receive_event_queue = ws[wasm_ws_pending_receive_event_queue]; @@ -54,7 +54,7 @@ export function ws_get_state (ws: WebSocketExtension) : number { return WebSocket.OPEN; } -export function ws_wasm_create (uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { +export function ws_wasm_create(uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { verifyEnvironment(); assert_js_interop(); mono_assert(uri && typeof uri === "string", () => `ERR12: Invalid uri ${typeof uri}`); @@ -65,7 +65,7 @@ export function ws_wasm_create (uri: string, sub_protocols: string[] | null, rec mono_log_warn("WebSocket error in ws_wasm_create: " + error.toString()); throw error; } - const {promise_control: open_promise_control} = createPromiseController(); + const { promise_control: open_promise_control } = createPromiseController(); ws[wasm_ws_pending_receive_event_queue] = new Queue(); ws[wasm_ws_pending_receive_promise_queue] = new Queue(); @@ -152,9 +152,9 @@ export function ws_wasm_create (uri: string, sub_protocols: string[] | null, rec } }; ws.addEventListener("message", local_on_message); - ws.addEventListener("open", local_on_open, {once: true}); - ws.addEventListener("close", local_on_close, {once: true}); - ws.addEventListener("error", local_on_error, {once: true}); + ws.addEventListener("open", local_on_open, { once: true }); + ws.addEventListener("close", local_on_close, { once: true }); + ws.addEventListener("error", local_on_error, { once: true }); ws.dispose = () => { ws.removeEventListener("message", local_on_message); ws.removeEventListener("open", local_on_open); @@ -166,7 +166,7 @@ export function ws_wasm_create (uri: string, sub_protocols: string[] | null, rec return ws; } -export function ws_wasm_open (ws: WebSocketExtension): Promise | null { +export function ws_wasm_open(ws: WebSocketExtension): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { return rejectedPromise(ws[wasm_ws_pending_error]); @@ -176,7 +176,7 @@ export function ws_wasm_open (ws: WebSocketExtension): Promise | null { +export function ws_wasm_send(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number, message_type: number, end_of_message: boolean): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -201,7 +201,7 @@ export function ws_wasm_send (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffe return web_socket_send_and_wait(ws, whole_buffer); } -export function ws_wasm_receive (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { +export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -237,7 +237,7 @@ export function ws_wasm_receive (ws: WebSocketExtension, buffer_ptr: VoidPtr, bu return resolvedPromise(); } - const {promise, promise_control} = createPromiseController(); + const { promise, promise_control } = createPromiseController(); const receive_promise_control = promise_control as ReceivePromiseControl; receive_promise_control.buffer_ptr = buffer_ptr; receive_promise_control.buffer_length = buffer_length; @@ -246,7 +246,7 @@ export function ws_wasm_receive (ws: WebSocketExtension, buffer_ptr: VoidPtr, bu return promise; } -export function ws_wasm_close (ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { +export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { mono_assert(!!ws, "ERR19: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent] || ws.readyState == WebSocket.CLOSED) { @@ -257,7 +257,7 @@ export function ws_wasm_close (ws: WebSocketExtension, code: number, reason: str } ws[wasm_ws_close_sent] = true; if (wait_for_close_received) { - const {promise, promise_control} = createPromiseController(); + const { promise, promise_control } = createPromiseController(); ws[wasm_ws_pending_close_promises].push(promise_control); if (typeof reason === "string") { @@ -276,7 +276,7 @@ export function ws_wasm_close (ws: WebSocketExtension, code: number, reason: str } } -export function ws_wasm_abort (ws: WebSocketExtension): void { +export function ws_wasm_abort(ws: WebSocketExtension): void { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent]) { @@ -294,7 +294,7 @@ export function ws_wasm_abort (ws: WebSocketExtension): void { } } -function reject_promises (ws: WebSocketExtension, error: Error) { +function reject_promises(ws: WebSocketExtension, error: Error) { const open_promise_control = ws[wasm_ws_pending_open_promise]; const open_promise_used = ws[wasm_ws_pending_open_promise_used]; @@ -317,7 +317,7 @@ function reject_promises (ws: WebSocketExtension, error: Error) { } // send and return promise -function web_socket_send_and_wait (ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { +function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { ws.send(buffer_view); ws[wasm_ws_pending_send_buffer] = null; @@ -329,7 +329,7 @@ function web_socket_send_and_wait (ws: WebSocketExtension, buffer_view: Uint8Arr } // block the promise/task until the browser passed the buffer to OS - const {promise, promise_control} = createPromiseController(); + const { promise, promise_control } = createPromiseController(); const pending = ws[wasm_ws_pending_send_promises]; pending.push(promise_control); @@ -368,7 +368,7 @@ function web_socket_send_and_wait (ws: WebSocketExtension, buffer_view: Uint8Arr return promise; } -function web_socket_on_message (ws: WebSocketExtension, event: MessageEvent) { +function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { const event_queue = ws[wasm_ws_pending_receive_event_queue]; const promise_queue = ws[wasm_ws_pending_receive_promise_queue]; @@ -403,7 +403,7 @@ function web_socket_on_message (ws: WebSocketExtension, event: MessageEvent) { prevent_timer_throttling(); } -function web_socket_receive_buffering (ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { +function web_socket_receive_buffering(ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { const event = event_queue.peek(); const count = Math.min(buffer_length, event.data.length - event.offset); @@ -423,7 +423,7 @@ function web_socket_receive_buffering (ws: WebSocketExtension, event_queue: Queu setI32(response_ptr + 8, end_of_message); } -function web_socket_send_buffering (ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { +function web_socket_send_buffering(ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { let buffer = ws[wasm_ws_pending_send_buffer]; let offset = 0; const length = buffer_view.byteLength; @@ -515,7 +515,7 @@ type Message = { offset: number } -function resolvedPromise (): Promise | null { +function resolvedPromise(): Promise | null { if (!WasmEnableThreads) { // signal that we are finished synchronously // this is optimization, which doesn't allocate and doesn't require to marshal resolve() call to C# side. @@ -530,7 +530,7 @@ function resolvedPromise (): Promise | null { } } -function rejectedPromise (message: string): Promise | null { +function rejectedPromise(message: string): Promise | null { const resolved = Promise.reject(new Error(message)); return wrap_as_cancelable(resolved); } From a57606c5be78d15ef0a2ea23a1c013e1db0423f0 Mon Sep 17 00:00:00 2001 From: Ilona Tomkowicz Date: Tue, 26 Mar 2024 17:17:17 +0100 Subject: [PATCH 4/4] Add empty space before the bracket. --- src/mono/browser/runtime/.eslintignore | 1 + src/mono/browser/runtime/.eslintrc.cjs | 3 +- src/mono/browser/runtime/assets.ts | 10 +- src/mono/browser/runtime/base64.ts | 8 +- .../browser/runtime/cancelable-promise.ts | 22 +- src/mono/browser/runtime/crypto.ts | 2 +- src/mono/browser/runtime/cuint64.ts | 12 +- src/mono/browser/runtime/cwraps.ts | 6 +- src/mono/browser/runtime/debug.ts | 54 ++--- .../runtime/diagnostics/browser/controller.ts | 14 +- src/mono/browser/runtime/diagnostics/index.ts | 12 +- .../runtime/diagnostics/mock/environment.ts | 22 +- .../browser/runtime/diagnostics/mock/index.ts | 28 +-- .../server_pthread/common-socket.ts | 2 +- .../diagnostics/server_pthread/index.ts | 48 ++--- .../ipc-protocol/base-parser.ts | 26 +-- .../ipc-protocol/base-serializer.ts | 20 +- .../server_pthread/ipc-protocol/magic.ts | 4 +- .../server_pthread/ipc-protocol/parser.ts | 14 +- .../server_pthread/ipc-protocol/serializer.ts | 8 +- .../server_pthread/ipc-protocol/types.ts | 2 +- .../diagnostics/server_pthread/mock-remote.ts | 2 +- .../protocol-client-commands.ts | 14 +- .../server_pthread/protocol-socket.ts | 38 ++-- .../server_pthread/socket-connection.ts | 22 +- .../server_pthread/stream-queue.ts | 22 +- .../server_pthread/streaming-session.ts | 14 +- .../diagnostics/shared/controller-commands.ts | 4 +- .../diagnostics/shared/create-session.ts | 6 +- src/mono/browser/runtime/export-api.ts | 2 +- src/mono/browser/runtime/exports-binding.ts | 2 +- src/mono/browser/runtime/exports-internal.ts | 6 +- src/mono/browser/runtime/exports-linker.ts | 2 +- src/mono/browser/runtime/exports.ts | 6 +- src/mono/browser/runtime/gc-handles.ts | 34 +-- src/mono/browser/runtime/gc-lock.ts | 4 +- src/mono/browser/runtime/globals.ts | 8 +- src/mono/browser/runtime/guarded-promise.ts | 2 +- src/mono/browser/runtime/http.ts | 48 ++--- .../runtime/hybrid-globalization/calendar.ts | 28 +-- .../hybrid-globalization/change-case.ts | 6 +- .../hybrid-globalization/collations.ts | 16 +- .../hybrid-globalization/culture-info.ts | 10 +- .../grapheme-segmenter.ts | 18 +- .../runtime/hybrid-globalization/helpers.ts | 6 +- .../runtime/hybrid-globalization/locales.ts | 12 +- src/mono/browser/runtime/icu.ts | 2 +- src/mono/browser/runtime/interp-pgo.ts | 14 +- src/mono/browser/runtime/invoke-cs.ts | 34 +-- src/mono/browser/runtime/invoke-js.ts | 72 +++---- .../runtime/jiterpreter-interp-entry.ts | 18 +- .../browser/runtime/jiterpreter-jit-call.ts | 20 +- .../browser/runtime/jiterpreter-support.ts | 200 +++++++++--------- .../runtime/jiterpreter-trace-generator.ts | 104 ++++----- src/mono/browser/runtime/jiterpreter.ts | 28 +-- src/mono/browser/runtime/lazyLoading.ts | 4 +- src/mono/browser/runtime/loader/assets.ts | 48 ++--- .../browser/runtime/loader/assetsCache.ts | 22 +- src/mono/browser/runtime/loader/config.ts | 20 +- src/mono/browser/runtime/loader/exit.ts | 38 ++-- src/mono/browser/runtime/loader/globals.ts | 4 +- src/mono/browser/runtime/loader/icu.ts | 6 +- .../runtime/loader/libraryInitializers.ts | 8 +- src/mono/browser/runtime/loader/logging.ts | 30 +-- src/mono/browser/runtime/loader/polyfills.ts | 18 +- .../runtime/loader/promise-controller.ts | 10 +- src/mono/browser/runtime/loader/run.ts | 70 +++--- src/mono/browser/runtime/loader/worker.ts | 4 +- src/mono/browser/runtime/logging.ts | 24 +-- src/mono/browser/runtime/managed-exports.ts | 26 +-- src/mono/browser/runtime/marshal-to-cs.ts | 58 ++--- src/mono/browser/runtime/marshal-to-js.ts | 64 +++--- src/mono/browser/runtime/marshal.ts | 156 +++++++------- src/mono/browser/runtime/memory.ts | 124 +++++------ src/mono/browser/runtime/polyfills.ts | 14 +- src/mono/browser/runtime/profiler.ts | 12 +- .../browser/runtime/pthreads/deputy-thread.ts | 4 +- .../browser/runtime/pthreads/io-thread.ts | 2 +- src/mono/browser/runtime/pthreads/shared.ts | 14 +- .../browser/runtime/pthreads/ui-thread.ts | 42 ++-- .../browser/runtime/pthreads/worker-events.ts | 2 +- .../browser/runtime/pthreads/worker-thread.ts | 28 +-- src/mono/browser/runtime/queue.ts | 14 +- src/mono/browser/runtime/rollup.config.js | 40 ++-- src/mono/browser/runtime/roots.ts | 106 +++++----- src/mono/browser/runtime/run.ts | 8 +- .../browser/runtime/satelliteAssemblies.ts | 2 +- src/mono/browser/runtime/scheduling.ts | 14 +- src/mono/browser/runtime/startup.ts | 54 ++--- src/mono/browser/runtime/strings.ts | 32 +-- src/mono/browser/runtime/types/internal.ts | 8 +- src/mono/browser/runtime/weak-ref.ts | 4 +- src/mono/browser/runtime/web-socket.ts | 30 +-- 93 files changed, 1154 insertions(+), 1152 deletions(-) diff --git a/src/mono/browser/runtime/.eslintignore b/src/mono/browser/runtime/.eslintignore index 47ac7775dd4acc..a0de5cad5c0cb9 100644 --- a/src/mono/browser/runtime/.eslintignore +++ b/src/mono/browser/runtime/.eslintignore @@ -1,3 +1,4 @@ jiterpreter-opcodes.ts jiterpreter-tables.ts dotnet.d.ts +diagnostics-mock.d.ts diff --git a/src/mono/browser/runtime/.eslintrc.cjs b/src/mono/browser/runtime/.eslintrc.cjs index c7b3283419f90b..0cae796f4016aa 100644 --- a/src/mono/browser/runtime/.eslintrc.cjs +++ b/src/mono/browser/runtime/.eslintrc.cjs @@ -23,6 +23,7 @@ module.exports = { "jiterpreter-opcodes.ts", "jiterpreter-tables.ts", "dotnet.d.ts", + "diagnostics-mock.d.ts", ], "rules": { "@typescript-eslint/no-explicit-any": "off", @@ -58,6 +59,6 @@ module.exports = { "object-curly-spacing": ["error", "always"], "array-bracket-spacing": ["error"], "space-infix-ops": ["error"], - "space-before-function-paren": ["error", "never"], + "space-before-function-paren": ["error", "always"], } }; diff --git a/src/mono/browser/runtime/assets.ts b/src/mono/browser/runtime/assets.ts index c2ebda35861de5..7cdff19d8a84c9 100644 --- a/src/mono/browser/runtime/assets.ts +++ b/src/mono/browser/runtime/assets.ts @@ -14,7 +14,7 @@ import { VoidPtr } from "./types/emscripten"; import { setSegmentationRulesFromJson } from "./hybrid-globalization/grapheme-segmenter"; // this need to be run only after onRuntimeInitialized event, when the memory is ready -export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Array): void { +export function instantiate_asset (asset: AssetEntry, url: string, bytes: Uint8Array): void { mono_log_debug(`Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); const mark = startMeasure(); @@ -94,7 +94,7 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar ++loaderHelpers.actual_instantiated_assets_count; } -export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_symbols_asset (pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const text = await response.text(); @@ -104,7 +104,7 @@ export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal } } -export async function instantiate_segmentation_rules_asset(pendingAsset: AssetEntryInternal): Promise { +export async function instantiate_segmentation_rules_asset (pendingAsset: AssetEntryInternal): Promise { try { const response = await pendingAsset.pendingDownloadInternal!.response; const json = await response.json(); @@ -114,7 +114,7 @@ export async function instantiate_segmentation_rules_asset(pendingAsset: AssetEn } } -export async function wait_for_all_assets() { +export async function wait_for_all_assets () { // wait for all assets in memory await runtimeHelpers.allAssetsInMemory.promise; if (runtimeHelpers.config.assets) { @@ -126,6 +126,6 @@ export async function wait_for_all_assets() { } // Used by the debugger to enumerate loaded dlls and pdbs -export function mono_wasm_get_loaded_files(): string[] { +export function mono_wasm_get_loaded_files (): string[] { return loaderHelpers.loadedFiles; } diff --git a/src/mono/browser/runtime/base64.ts b/src/mono/browser/runtime/base64.ts index e86fbc2ced58e4..28bf9970ed7f10 100644 --- a/src/mono/browser/runtime/base64.ts +++ b/src/mono/browser/runtime/base64.ts @@ -5,7 +5,7 @@ // https://github.com/sq/JSIL/blob/1d57d5427c87ab92ffa3ca4b82429cd7509796ba/JSIL.Libraries/Includes/Bootstrap/Core/Classes/System.Convert.js#L149 // Thanks to Katelyn Gadd @kg -export function toBase64StringImpl(inArray: Uint8Array, offset?: number, length?: number) : string { +export function toBase64StringImpl (inArray: Uint8Array, offset?: number, length?: number) : string { const reader = _makeByteReader(inArray, offset, length); let result = ""; let ch1: number | null = 0, ch2: number | null = 0, ch3: number | null = 0; @@ -76,7 +76,7 @@ const _base64Table = [ "+", "/" ]; -function _makeByteReader(bytes: Uint8Array, index?: number, count?: number): { +function _makeByteReader (bytes: Uint8Array, index?: number, count?: number): { read: () => number | null } { let position = (typeof (index) === "number") ? index : 0; @@ -88,7 +88,7 @@ function _makeByteReader(bytes: Uint8Array, index?: number, count?: number): { endpoint = (bytes.length - position); const result = { - read: function() { + read: function () { if (position >= endpoint) return null; @@ -99,7 +99,7 @@ function _makeByteReader(bytes: Uint8Array, index?: number, count?: number): { }; Object.defineProperty(result, "eof", { - get: function() { + get: function () { return (position >= endpoint); }, configurable: true, diff --git a/src/mono/browser/runtime/cancelable-promise.ts b/src/mono/browser/runtime/cancelable-promise.ts index 6a3d1924b5296c..c82cbdacb19609 100644 --- a/src/mono/browser/runtime/cancelable-promise.ts +++ b/src/mono/browser/runtime/cancelable-promise.ts @@ -15,32 +15,32 @@ import { invoke_later_when_on_ui_thread_async } from "./invoke-js"; export const _are_promises_supported = ((typeof Promise === "object") || (typeof Promise === "function")) && (typeof Promise.resolve === "function"); -export function isThenable(js_obj: any): boolean { +export function isThenable (js_obj: any): boolean { // When using an external Promise library like Bluebird the Promise.resolve may not be sufficient // to identify the object as a Promise. return Promise.resolve(js_obj) === js_obj || ((typeof js_obj === "object" || typeof js_obj === "function") && typeof js_obj.then === "function"); } -export function wrap_as_cancelable_promise(fn: () => Promise): ControllablePromise { +export function wrap_as_cancelable_promise (fn: () => Promise): ControllablePromise { const { promise, promise_control } = createPromiseController(); const inner = fn(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function wrap_as_cancelable(inner: Promise): ControllablePromise { +export function wrap_as_cancelable (inner: Promise): ControllablePromise { const { promise, promise_control } = createPromiseController(); inner.then((data) => promise_control.resolve(data)).catch((reason) => promise_control.reject(reason)); return promise; } -export function mono_wasm_cancel_promise(task_holder_gc_handle: GCHandle): void { +export function mono_wasm_cancel_promise (task_holder_gc_handle: GCHandle): void { // cancelation should not arrive earlier than the promise created by marshaling in mono_wasm_invoke_jsimport_MT invoke_later_when_on_ui_thread_async(() => mono_wasm_cancel_promise_impl(task_holder_gc_handle)); } -export function mono_wasm_cancel_promise_impl(task_holder_gc_handle: GCHandle): void { +export function mono_wasm_cancel_promise_impl (task_holder_gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise can't be canceled, mono runtime already exited."); return; @@ -63,7 +63,7 @@ export class PromiseHolder extends ManagedObject { public isPostponed = false; public data: any = null; public reason: any = undefined; - public constructor(public promise: Promise, + public constructor (public promise: Promise, private gc_handle: GCHandle, private promiseHolderPtr: number, // could be null for GCV_handle private res_converter?: MarshalerToCs) { @@ -71,7 +71,7 @@ export class PromiseHolder extends ManagedObject { } // returns false if the promise is being canceled by another thread in managed code - setIsResolving(): boolean { + setIsResolving (): boolean { if (!WasmEnableThreads || this.promiseHolderPtr === 0) { return true; } @@ -82,7 +82,7 @@ export class PromiseHolder extends ManagedObject { return false; } - resolve(data: any) { + resolve (data: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution can't be propagated to managed code, mono runtime already exited."); return; @@ -106,7 +106,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(data, null); } - reject(reason: any) { + reject (reason: any) { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -131,7 +131,7 @@ export class PromiseHolder extends ManagedObject { this.complete_task_wrapper(null, reason); } - cancel() { + cancel () { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise cancelation can't be propagated to managed code, mono runtime already exited."); return; @@ -162,7 +162,7 @@ export class PromiseHolder extends ManagedObject { } // we can do this just once, because it will be dispose the GCHandle - complete_task_wrapper(data: any, reason: any) { + complete_task_wrapper (data: any, reason: any) { try { mono_assert(!this.isPosted, "Promise is already posted to managed."); this.isPosted = true; diff --git a/src/mono/browser/runtime/crypto.ts b/src/mono/browser/runtime/crypto.ts index f396b5d833b147..a6642d874ffcbb 100644 --- a/src/mono/browser/runtime/crypto.ts +++ b/src/mono/browser/runtime/crypto.ts @@ -5,7 +5,7 @@ import { isSharedArrayBuffer, localHeapViewU8 } from "./memory"; // https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues const batchedQuotaMax = 65536; -export function mono_wasm_browser_entropy(bufferPtr: number, bufferLength: number): number { +export function mono_wasm_browser_entropy (bufferPtr: number, bufferLength: number): number { if (!globalThis.crypto || !globalThis.crypto.getRandomValues) { return -1; } diff --git a/src/mono/browser/runtime/cuint64.ts b/src/mono/browser/runtime/cuint64.ts index 558c230265e23c..20ab2c88ca422f 100644 --- a/src/mono/browser/runtime/cuint64.ts +++ b/src/mono/browser/runtime/cuint64.ts @@ -6,11 +6,11 @@ /// and 'import type { CUInt64 } from './cuint64'; export type CUInt64 = readonly [number, number]; -export function toBigInt(x: CUInt64): bigint { +export function toBigInt (x: CUInt64): bigint { return BigInt(x[0]) | BigInt(x[1]) << BigInt(32); } -export function fromBigInt(x: bigint): CUInt64 { +export function fromBigInt (x: bigint): CUInt64 { if (x < BigInt(0)) throw new Error(`${x} is not a valid 64 bit integer`); if (x > BigInt(0xFFFFFFFFFFFFFFFF)) @@ -20,11 +20,11 @@ export function fromBigInt(x: bigint): CUInt64 { return [low, high]; } -export function dangerousToNumber(x: CUInt64): number { +export function dangerousToNumber (x: CUInt64): number { return x[0] | x[1] << 32; } -export function fromNumber(x: number): CUInt64 { +export function fromNumber (x: number): CUInt64 { if (x < 0) throw new Error(`${x} is not a valid 64 bit integer`); if ((x >> 32) > 0xFFFFFFFF) @@ -34,11 +34,11 @@ export function fromNumber(x: number): CUInt64 { return [x & 0xFFFFFFFF, x >> 32]; } -export function pack32(lo: number, hi: number): CUInt64 { +export function pack32 (lo: number, hi: number): CUInt64 { return [lo, hi]; } -export function unpack32(x: CUInt64): [number, number] { +export function unpack32 (x: CUInt64): [number, number] { return [x[0], x[1]]; } diff --git a/src/mono/browser/runtime/cwraps.ts b/src/mono/browser/runtime/cwraps.ts index c5eb62422725f5..7f4a05cbd87098 100644 --- a/src/mono/browser/runtime/cwraps.ts +++ b/src/mono/browser/runtime/cwraps.ts @@ -283,7 +283,7 @@ export const enum I52Error { const fastCwrapTypes = ["void", "number", null]; -function cwrap(name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { +function cwrap (name: string, returnType: string | null, argTypes: string[] | undefined, opts: any): Function { // Attempt to bypass emscripten's generated wrapper if it is safe to do so let fce = // Special cwrap options disable the fast path @@ -314,7 +314,7 @@ function cwrap(name: string, returnType: string | null, argTypes: string[] | und return fce; } -export function init_c_exports(): void { +export function init_c_exports (): void { const fns = [...fn_signatures]; for (const sig of fns) { const wf: any = wrapped_c_functions; @@ -322,7 +322,7 @@ export function init_c_exports(): void { const maybeSkip = typeof lazyOrSkip === "function"; if (lazyOrSkip === true || maybeSkip) { // lazy init on first run - wf[name] = function(...args: any[]) { + wf[name] = function (...args: any[]) { const isNotSkipped = !maybeSkip || !lazyOrSkip(); mono_assert(isNotSkipped, () => `cwrap ${name} should not be called when binding was skipped`); const fce = cwrap(name, returnType, argTypes, opts); diff --git a/src/mono/browser/runtime/debug.ts b/src/mono/browser/runtime/debug.ts index b86b0347ba7af1..99963d964f00cc 100644 --- a/src/mono/browser/runtime/debug.ts +++ b/src/mono/browser/runtime/debug.ts @@ -9,7 +9,7 @@ import { mono_log_warn } from "./logging"; import { forceThreadMemoryViewRefresh, localHeapViewU8 } from "./memory"; import { utf8ToString } from "./strings"; const commands_received: any = new Map(); -commands_received.remove = function(key: number): CommandResponse { +commands_received.remove = function (key: number): CommandResponse { const value = this.get(key); this.delete(key); return value; }; let _call_function_res_cache: any = {}; @@ -19,7 +19,7 @@ let _debugger_buffer: VoidPtr; let _assembly_name_str: string; //keep this variable, it's used by BrowserDebugProxy let _entrypoint_method_token: number; //keep this variable, it's used by BrowserDebugProxy -export function mono_wasm_runtime_ready(): void { +export function mono_wasm_runtime_ready (): void { INTERNAL.mono_wasm_runtime_is_ready = runtimeHelpers.mono_wasm_runtime_is_ready = true; // FIXME: where should this go? @@ -33,7 +33,7 @@ export function mono_wasm_runtime_ready(): void { debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String: string): void { +export function mono_wasm_fire_debugger_agent_message_with_data_to_pause (base64String: string): void { //keep this console.assert, otherwise optimization will remove the assignments // eslint-disable-next-line no-console console.assert(true, `mono_wasm_fire_debugger_agent_message_with_data ${base64String}`); @@ -41,12 +41,12 @@ export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64S debugger; } -export function mono_wasm_fire_debugger_agent_message_with_data(data: number, len: number): void { +export function mono_wasm_fire_debugger_agent_message_with_data (data: number, len: number): void { const base64String = toBase64StringImpl(new Uint8Array(localHeapViewU8().buffer, data, len)); mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String); } -export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number, buffer: number, buffer_len: number): void { +export function mono_wasm_add_dbg_command_received (res_ok: boolean, id: number, buffer: number, buffer_len: number): void { const dbg_command = new Uint8Array(localHeapViewU8().buffer, buffer, buffer_len); const base64String = toBase64StringImpl(dbg_command); const buffer_obj = { @@ -61,7 +61,7 @@ export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number, commands_received.set(id, buffer_obj); } -function mono_wasm_malloc_and_set_debug_buffer(command_parameters: string) { +function mono_wasm_malloc_and_set_debug_buffer (command_parameters: string) { if (command_parameters.length > _debugger_buffer_len) { if (_debugger_buffer) Module._free(_debugger_buffer); @@ -75,7 +75,7 @@ function mono_wasm_malloc_and_set_debug_buffer(command_parameters: string) { } } -export function mono_wasm_send_dbg_command_with_parms(id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { +export function mono_wasm_send_dbg_command_with_parms (id: number, command_set: number, command: number, command_parameters: string, length: number, valtype: number, newvalue: number): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); @@ -87,7 +87,7 @@ export function mono_wasm_send_dbg_command_with_parms(id: number, command_set: n return res; } -export function mono_wasm_send_dbg_command(id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { +export function mono_wasm_send_dbg_command (id: number, command_set: number, command: number, command_parameters: string): CommandResponseResult { forceThreadMemoryViewRefresh(); mono_wasm_malloc_and_set_debug_buffer(command_parameters); @@ -101,7 +101,7 @@ export function mono_wasm_send_dbg_command(id: number, command_set: number, comm } -export function mono_wasm_get_dbg_command_info(): CommandResponseResult { +export function mono_wasm_get_dbg_command_info (): CommandResponseResult { const { res_ok, res } = commands_received.remove(0); if (!res_ok) @@ -109,16 +109,16 @@ export function mono_wasm_get_dbg_command_info(): CommandResponseResult { return res; } -export function mono_wasm_debugger_resume(): void { +export function mono_wasm_debugger_resume (): void { forceThreadMemoryViewRefresh(); } -export function mono_wasm_detach_debugger(): void { +export function mono_wasm_detach_debugger (): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(false); } -export function mono_wasm_change_debugger_log_level(level: number): void { +export function mono_wasm_change_debugger_log_level (level: number): void { forceThreadMemoryViewRefresh(); cwraps.mono_wasm_change_debugger_log_level(level); } @@ -126,7 +126,7 @@ export function mono_wasm_change_debugger_log_level(level: number): void { /** * Raises an event for the debug proxy */ -export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void { +export function mono_wasm_raise_debug_event (event: WasmEvent, args = {}): void { if (typeof event !== "object") throw new Error(`event must be an object, but got ${JSON.stringify(event)}`); @@ -140,7 +140,7 @@ export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void { console.debug("mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae", JSON.stringify(event), JSON.stringify(args)); } -export function mono_wasm_wait_for_debugger(): Promise { +export function mono_wasm_wait_for_debugger (): Promise { return new Promise((resolve) => { const interval = setInterval(() => { if (runtimeHelpers.waitForDebugger != 1) { @@ -152,14 +152,14 @@ export function mono_wasm_wait_for_debugger(): Promise { }); } -export function mono_wasm_debugger_attached(): void { +export function mono_wasm_debugger_attached (): void { if (runtimeHelpers.waitForDebugger == -1) runtimeHelpers.waitForDebugger = 1; forceThreadMemoryViewRefresh(); cwraps.mono_wasm_set_is_debugger_attached(true); } -export function mono_wasm_set_entrypoint_breakpoint(entrypoint_method_token: number): void { +export function mono_wasm_set_entrypoint_breakpoint (entrypoint_method_token: number): void { //keep these assignments, these values are used by BrowserDebugProxy _assembly_name_str = loaderHelpers.config.mainAssemblyName + ".dll"; _entrypoint_method_token = entrypoint_method_token; @@ -172,7 +172,7 @@ export function mono_wasm_set_entrypoint_breakpoint(entrypoint_method_token: num forceThreadMemoryViewRefresh(); } -function _create_proxy_from_object_id(objectId: string, details: any) { +function _create_proxy_from_object_id (objectId: string, details: any) { if (objectId.startsWith("dotnet:array:")) { let ret: Array; if (details.items === undefined) { @@ -192,10 +192,10 @@ function _create_proxy_from_object_id(objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get() { + get () { return mono_wasm_send_dbg_command(prop.get.id, prop.get.commandSet, prop.get.command, prop.get.buffer); }, - set: function(newValue) { + set: function (newValue) { mono_wasm_send_dbg_command_with_parms(prop.set.id, prop.set.commandSet, prop.set.command, prop.set.buffer, prop.set.length, prop.set.valtype, newValue); return true; } } @@ -204,10 +204,10 @@ function _create_proxy_from_object_id(objectId: string, details: any) { Object.defineProperty(proxy, prop.name, { - get() { + get () { return prop.value; }, - set: function(newValue) { + set: function (newValue) { mono_wasm_send_dbg_command_with_parms(prop.set.id, prop.set.commandSet, prop.set.command, prop.set.buffer, prop.set.length, prop.set.valtype, newValue); return true; } } @@ -219,7 +219,7 @@ function _create_proxy_from_object_id(objectId: string, details: any) { return proxy; } -export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { +export function mono_wasm_call_function_on (request: CallRequest): CFOResponse { forceThreadMemoryViewRefresh(); if (request.arguments != undefined && !Array.isArray(request.arguments)) @@ -278,7 +278,7 @@ export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { return { type: "object", className: "Object", description: "Object", objectId: fn_res_id }; } -function _get_cfo_res_details(objectId: string, args: any): ValueAsJsonString { +function _get_cfo_res_details (objectId: string, args: any): ValueAsJsonString { if (!(objectId in _call_function_res_cache)) throw new Error(`Could not find any object with id ${objectId}`); @@ -340,23 +340,23 @@ type ValueAsJsonString = { __value_as_json_string__: string; } -export function mono_wasm_get_details(objectId: string, args = {}): ValueAsJsonString { +export function mono_wasm_get_details (objectId: string, args = {}): ValueAsJsonString { forceThreadMemoryViewRefresh(); return _get_cfo_res_details(`dotnet:cfo_res:${objectId}`, args); } -function _cache_call_function_res(obj: any) { +function _cache_call_function_res (obj: any) { const id = `dotnet:cfo_res:${_next_call_function_res_id++}`; _call_function_res_cache[id] = obj; return id; } -export function mono_wasm_release_object(objectId: string): void { +export function mono_wasm_release_object (objectId: string): void { if (objectId in _call_function_res_cache) delete _call_function_res_cache[objectId]; } -export function mono_wasm_debugger_log(level: number, message_ptr: CharPtr): void { +export function mono_wasm_debugger_log (level: number, message_ptr: CharPtr): void { forceThreadMemoryViewRefresh(); const message = utf8ToString(message_ptr); diff --git a/src/mono/browser/runtime/diagnostics/browser/controller.ts b/src/mono/browser/runtime/diagnostics/browser/controller.ts index 799972b1fd0e66..0119a9fda984bf 100644 --- a/src/mono/browser/runtime/diagnostics/browser/controller.ts +++ b/src/mono/browser/runtime/diagnostics/browser/controller.ts @@ -18,23 +18,23 @@ export interface ServerController { } class ServerControllerImpl implements ServerController { - constructor(private server: Thread) { + constructor (private server: Thread) { server.port.addEventListener("message", this.onServerReply.bind(this)); } - start(): void { + start (): void { mono_log_debug("signaling the diagnostic server to start"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("start")); } - stop(): void { + stop (): void { mono_log_debug("signaling the diagnostic server to stop"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("stop")); } - postServerAttachToRuntime(): void { + postServerAttachToRuntime (): void { mono_log_debug("signal the diagnostic server to attach to the runtime"); this.server.postMessageToWorker(makeDiagnosticServerControlCommand("attach_to_runtime")); } - onServerReply(event: MessageEvent): void { + onServerReply (event: MessageEvent): void { const d = event.data; if (isDiagnosticMessage(d)) { switch (d.cmd) { @@ -48,13 +48,13 @@ class ServerControllerImpl implements ServerController { let serverController: ServerController | null = null; -export function getController(): ServerController { +export function getController (): ServerController { if (serverController) return serverController; throw new Error("unexpected no server controller"); } -export async function startDiagnosticServer(websocket_url: string): Promise { +export async function startDiagnosticServer (websocket_url: string): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const sizeOfPthreadT = 4; mono_log_info(`starting the diagnostic server url: ${websocket_url}`); diff --git a/src/mono/browser/runtime/diagnostics/index.ts b/src/mono/browser/runtime/diagnostics/index.ts index a9d6f9414267ae..f8f93f6781a07c 100644 --- a/src/mono/browser/runtime/diagnostics/index.ts +++ b/src/mono/browser/runtime/diagnostics/index.ts @@ -15,7 +15,7 @@ import { mono_assert, runtimeHelpers } from "../globals"; // called from C on the main thread -export function mono_wasm_event_pipe_early_startup_callback(): void { +export function mono_wasm_event_pipe_early_startup_callback (): void { if (WasmEnableThreads) { return; } @@ -36,7 +36,7 @@ let diagnosticsServerEnabled = false; let diagnosticsInitialized = false; -export async function mono_wasm_init_diagnostics(): Promise { +export async function mono_wasm_init_diagnostics (): Promise { if (!WasmEnableThreads) return; if (diagnosticsInitialized) return; @@ -60,7 +60,7 @@ export async function mono_wasm_init_diagnostics(): Promise { } } -function boolsyOption(x: string | boolean): boolean { +function boolsyOption (x: string | boolean): boolean { if (x === true || x === false) return x; if (typeof x === "string") { @@ -77,7 +77,7 @@ function boolsyOption(x: string | boolean): boolean { /// The environment variables are: /// * DOTNET_DiagnosticPorts /// -function diagnostic_options_from_environment(): DiagnosticOptions | null { +function diagnostic_options_from_environment (): DiagnosticOptions | null { const val = runtimeHelpers.config.environmentVariables ? runtimeHelpers.config.environmentVariables["DOTNET_DiagnosticPorts"] : undefined; if (is_nullish(val)) return null; @@ -88,7 +88,7 @@ function diagnostic_options_from_environment(): DiagnosticOptions | null { /// Parse a DOTNET_DiagnosticPorts string and return a DiagnosticOptions object. /// See https://docs.microsoft.com/en-us/dotnet/core/diagnostics/diagnostic-port#configure-additional-diagnostic-ports -function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | null { +function diagnostic_options_from_ports_spec (val: string): DiagnosticOptions | null { if (val === "") return null; const ports = val.split(";"); @@ -140,7 +140,7 @@ function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | nu } -export function mono_wasm_diagnostic_server_on_runtime_server_init(out_options: VoidPtr): void { +export function mono_wasm_diagnostic_server_on_runtime_server_init (out_options: VoidPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); if (diagnosticsServerEnabled) { /* called on the main thread when the runtime is sufficiently initialized */ diff --git a/src/mono/browser/runtime/diagnostics/mock/environment.ts b/src/mono/browser/runtime/diagnostics/mock/environment.ts index 0de8c8b7acafc2..7e2a8a5918633f 100644 --- a/src/mono/browser/runtime/diagnostics/mock/environment.ts +++ b/src/mono/browser/runtime/diagnostics/mock/environment.ts @@ -10,7 +10,7 @@ import { pthread_self } from "../../pthreads"; import { createPromiseController, mono_assert } from "../../globals"; -function expectAdvertise(data: ArrayBuffer): boolean { +function expectAdvertise (data: ArrayBuffer): boolean { if (typeof (data) === "string") { assertNever(data); } else { @@ -21,7 +21,7 @@ function expectAdvertise(data: ArrayBuffer): boolean { } } -function expectOk(payloadLength?: number): FilterPredicate { +function expectOk (payloadLength?: number): FilterPredicate { return (data) => { if (typeof (data) === "string") { assertNever(data); @@ -33,7 +33,7 @@ function expectOk(payloadLength?: number): FilterPredicate { }; } -function extractOkSessionID(data: ArrayBuffer): number { +function extractOkSessionID (data: ArrayBuffer): number { if (typeof (data) === "string") { assertNever(data); } else { @@ -45,13 +45,13 @@ function extractOkSessionID(data: ArrayBuffer): number { } } -function computeStringByteLength(s: string | null): number { +function computeStringByteLength (s: string | null): number { if (s === undefined || s === null || s === "") return 4; // just length of zero return 4 + 2 * s.length + 2; // length + UTF16 + null } -function computeCollectTracing2PayloadByteLength(payload: RemoveCommandSetAndId): number { +function computeCollectTracing2PayloadByteLength (payload: RemoveCommandSetAndId): number { let len = 0; len += 4; // circularBufferMB len += 4; // format @@ -66,7 +66,7 @@ function computeCollectTracing2PayloadByteLength(payload: RemoveCommandSetAndId< return len; } -function makeEventPipeCollectTracing2(payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeCollectTracing2 (payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = computeCollectTracing2PayloadByteLength(payload); const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); @@ -85,7 +85,7 @@ function makeEventPipeCollectTracing2(payload: RemoveCommandSetAndId): Uint8Array { +function makeEventPipeStopTracing (payload: RemoveCommandSetAndId): Uint8Array { const payloadLength = 8; const messageLength = Serializer.computeMessageByteLength(payloadLength); const buffer = new Uint8Array(messageLength); @@ -96,7 +96,7 @@ function makeEventPipeStopTracing(payload: RemoveCommandSetAndId void) { +function addEventListenerFromBrowser (cmd: string, listener: (data: any) => void) { pthread_self.addEventListenerFromBrowser((event) => { if (event.data.cmd === cmd) listener(event.data); }); } -export function createMockEnvironment(): MockEnvironment { +export function createMockEnvironment (): MockEnvironment { const command = { makeEventPipeCollectTracing2, makeEventPipeStopTracing, diff --git a/src/mono/browser/runtime/diagnostics/mock/index.ts b/src/mono/browser/runtime/diagnostics/mock/index.ts index 81304154071332..d320980e454da4 100644 --- a/src/mono/browser/runtime/diagnostics/mock/index.ts +++ b/src/mono/browser/runtime/diagnostics/mock/index.ts @@ -25,12 +25,12 @@ type MockConnectionScript = (engine: MockScriptConnection) => Promise; export type MockScript = (env: MockEnvironment) => MockConnectionScript[]; let MockImplConstructor: new (script: MockScript) => Mock; -export function mock(script: MockScript): Mock { +export function mock (script: MockScript): Mock { if (monoDiagnosticsMock) { if (!MockImplConstructor) { class MockScriptEngineSocketImpl implements MockRemoteSocket { - constructor(private readonly engine: MockScriptEngineImpl) { } - send(data: string | ArrayBuffer): void { + constructor (private readonly engine: MockScriptEngineImpl) { } + send (data: string | ArrayBuffer): void { mono_log_debug(`mock ${this.engine.ident} client sent: `, data); let event: MessageEvent | null = null; if (typeof data === "string") { @@ -45,19 +45,19 @@ export function mock(script: MockScript): Mock { this.engine.mockReplyEventTarget.dispatchEvent(event); } addEventListener(event: T, listener: (event: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void; - addEventListener(event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { + addEventListener (event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void { mono_log_debug(`mock ${this.engine.ident} client added listener for ${event}`); this.engine.eventTarget.addEventListener(event, listener, options); } - removeEventListener(event: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener (event: string, listener: EventListenerOrEventListenerObject): void { mono_log_debug(`mock ${this.engine.ident} client removed listener for ${event}`); this.engine.eventTarget.removeEventListener(event, listener); } - close(): void { + close (): void { mono_log_debug(`mock ${this.engine.ident} client closed`); this.engine.mockReplyEventTarget.dispatchEvent(new CloseEvent("close")); } - dispatchEvent(ev: Event): boolean { + dispatchEvent (ev: Event): boolean { return this.engine.eventTarget.dispatchEvent(ev); } } @@ -68,11 +68,11 @@ export function mock(script: MockScript): Mock { readonly eventTarget: EventTarget = new EventTarget(); // eventTarget that the MockReplySocket with send() to readonly mockReplyEventTarget: EventTarget = new EventTarget(); - constructor(readonly ident: number) { + constructor (readonly ident: number) { this.socket = new MockScriptEngineSocketImpl(this); } - reply(data: ArrayBuffer | Uint8Array) { + reply (data: ArrayBuffer | Uint8Array) { mono_log_debug(`mock ${this.ident} reply:`, data); let sendData: ArrayBuffer; if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -91,7 +91,7 @@ export function mock(script: MockScript): Mock { this.eventTarget.dispatchEvent(new MessageEvent("message", { data: sendData })); } - processSend(onMessage: (data: ArrayBuffer) => any): Promise { + processSend (onMessage: (data: ArrayBuffer) => any): Promise { mono_log_debug(`mock ${this.ident} processSend`); return new Promise((resolve, reject) => { @@ -112,7 +112,7 @@ export function mock(script: MockScript): Mock { }); } - async waitForSend(filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { + async waitForSend (filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise { mono_log_debug(`mock ${this.ident} waitForSend`); const data = await new Promise((resolve) => { @@ -141,7 +141,7 @@ export function mock(script: MockScript): Mock { openCount: number; engines: MockScriptEngineImpl[]; connectionScripts: MockConnectionScript[]; - constructor(public readonly mockScript: MockScript) { + constructor (public readonly mockScript: MockScript) { const env: MockEnvironment = createMockEnvironment(); this.connectionScripts = mockScript(env); this.openCount = 0; @@ -151,13 +151,13 @@ export function mock(script: MockScript): Mock { this.engines[i] = new MockScriptEngineImpl(i); } } - open(): MockRemoteSocket { + open (): MockRemoteSocket { const i = this.openCount++; mono_log_debug(`mock ${i} open`); return this.engines[i].socket; } - async run(): Promise { + async run (): Promise { const scripts = this.connectionScripts; await Promise.all(scripts.map((script, i) => script(this.engines[i]))); } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts index b6bb8084a26845..6714af0bc4d2a2 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/common-socket.ts @@ -17,7 +17,7 @@ export interface CommonSocket { type AssignableTo = Q extends T ? true : false; -function static_assert(x: Cond): asserts x is Cond { /*empty*/ } +function static_assert (x: Cond): asserts x is Cond { /*empty*/ } { static_assert>(true); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts index 4da6b11b69ce31..cbc94347a7d20e 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts @@ -50,7 +50,7 @@ import { import { mono_log_error, mono_log_info, mono_log_debug, mono_log_warn } from "../../logging"; import { utf8ToString } from "../../strings"; -function addOneShotProtocolCommandEventListener(src: EventTarget): Promise { +function addOneShotProtocolCommandEventListener (src: EventTarget): Promise { return new Promise((resolve) => { const listener = (event: Event) => { resolve(event as ProtocolCommandEvent); @@ -59,7 +59,7 @@ function addOneShotProtocolCommandEventListener(src: EventTarget): Promise { +function addOneShotOpenEventListenr (src: EventTarget): Promise { return new Promise((resolve) => { const listener = (event: Event) => { resolve(event); @@ -77,7 +77,7 @@ class DiagnosticServerImpl implements DiagnosticServer { readonly mocked: Promise | undefined; runtimeResumed = false; - constructor(websocketUrl: string, mockPromise?: Promise) { + constructor (websocketUrl: string, mockPromise?: Promise) { this.websocketUrl = websocketUrl; pthread_self.addEventListenerFromBrowser(this.onMessageFromMainThread.bind(this)); this.mocked = monoDiagnosticsMock ? mockPromise : undefined; @@ -89,21 +89,21 @@ class DiagnosticServerImpl implements DiagnosticServer { private attachToRuntimeController = createPromiseController().promise_control; - start(): void { + start (): void { mono_log_info(`starting diagnostic server with url: ${this.websocketUrl}`); this.startRequestedController.resolve(); } - stop(): void { + stop (): void { this.stopRequested = true; this.stopRequestedController.resolve(); } - attachToRuntime(): void { + attachToRuntime (): void { cwraps.mono_wasm_diagnostic_server_thread_attach_to_runtime(); this.attachToRuntimeController.resolve(); } - async serverLoop(this: DiagnosticServerImpl): Promise { + async serverLoop (this: DiagnosticServerImpl): Promise { await this.startRequestedController.promise; await this.attachToRuntimeController.promise; // can't start tracing until we've attached to the runtime while (!this.stopRequested) { @@ -123,7 +123,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async openSocket(): Promise { + async openSocket (): Promise { if (monoDiagnosticsMock && this.mocked) { return (await this.mocked).open(); } else { @@ -136,7 +136,7 @@ class DiagnosticServerImpl implements DiagnosticServer { private openCount = 0; - async advertiseAndWaitForClient(): Promise { + async advertiseAndWaitForClient (): Promise { try { const connNum = this.openCount++; mono_log_debug("opening websocket and sending ADVR_V1", connNum); @@ -152,7 +152,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - async parseAndDispatchMessage(ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { + async parseAndDispatchMessage (ws: CommonSocket, connNum: number, message: ProtocolCommandEvent): Promise { try { const cmd = this.parseCommand(message, connNum); if (cmd === null) { @@ -171,7 +171,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - sendAdvertise(ws: CommonSocket) { + sendAdvertise (ws: CommonSocket) { /* FIXME: don't use const fake guid and fake process id. In dotnet-dsrouter the pid is used * as a dictionary key,so if we ever supprt multiple runtimes, this might need to change. */ @@ -182,7 +182,7 @@ class DiagnosticServerImpl implements DiagnosticServer { ws.send(buf); } - parseCommand(message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { + parseCommand (message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null { mono_log_debug("parsing byte command: ", message.data, connNum); const result = parseProtocolCommand(message.data); mono_log_debug("parsed byte command: ", result, connNum); @@ -194,7 +194,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - onMessageFromMainThread(this: DiagnosticServerImpl, event: MessageEvent): void { + onMessageFromMainThread (this: DiagnosticServerImpl, event: MessageEvent): void { const d = event.data; if (d && isDiagnosticMessage(d)) { this.controlCommandReceived(d as DiagnosticServerControlCommand); @@ -202,7 +202,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } /// dispatch commands received from the main thread - controlCommandReceived(cmd: DiagnosticServerControlCommand): void { + controlCommandReceived (cmd: DiagnosticServerControlCommand): void { switch (cmd.cmd) { case "start": this.start(); @@ -220,7 +220,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch EventPipe commands received from the diagnostic client - async dispatchEventPipeCommand(ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { + async dispatchEventPipeCommand (ws: CommonSocket, cmd: EventPipeClientCommandBase): Promise { if (isEventPipeCommandCollectTracing2(cmd)) { await this.collectTracingEventPipe(ws, cmd); } else if (isEventPipeCommandStopTracing(cmd)) { @@ -230,12 +230,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - postClientReplyOK(ws: CommonSocket, payload?: Uint8Array): void { + postClientReplyOK (ws: CommonSocket, payload?: Uint8Array): void { // FIXME: send a binary response for non-mock sessions! ws.send(createBinaryCommandOKReply(payload)); } - async stopEventPipe(ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { + async stopEventPipe (ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise { mono_log_debug("stopEventPipe", sessionID); cwraps.mono_wasm_event_pipe_session_disable(sessionID); // we might send OK before the session is actually stopped since the websocket is async @@ -243,7 +243,7 @@ class DiagnosticServerImpl implements DiagnosticServer { this.postClientReplyOK(ws); } - async collectTracingEventPipe(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { + async collectTracingEventPipe (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { const session = await makeEventPipeStreamingSession(ws, cmd); const sessionIDbuf = new Uint8Array(8); // 64 bit sessionIDbuf[0] = session.sessionID & 0xFF; @@ -257,7 +257,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } // dispatch Process commands received from the diagnostic client - async dispatchProcessCommand(ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { + async dispatchProcessCommand (ws: WebSocket | MockRemoteSocket, cmd: ProcessClientCommandBase): Promise { if (isProcessCommandResumeRuntime(cmd)) { this.processResumeRuntime(ws); } else { @@ -265,12 +265,12 @@ class DiagnosticServerImpl implements DiagnosticServer { } } - processResumeRuntime(ws: WebSocket | MockRemoteSocket): void { + processResumeRuntime (ws: WebSocket | MockRemoteSocket): void { this.postClientReplyOK(ws); this.resumeRuntime(); } - resumeRuntime(): void { + resumeRuntime (): void { if (!this.runtimeResumed) { mono_log_debug("resuming runtime startup"); cwraps.mono_wasm_diagnostic_server_post_resume_runtime(); @@ -279,7 +279,7 @@ class DiagnosticServerImpl implements DiagnosticServer { } } -function parseProtocolCommand(data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { +function parseProtocolCommand (data: ArrayBuffer | BinaryProtocolCommand): ParseClientCommandResult { if (isBinaryProtocolCommand(data)) { return parseBinaryProtocolCommand(data); } else { @@ -288,14 +288,14 @@ function parseProtocolCommand(data: ArrayBuffer | BinaryProtocolCommand): ParseC } /// Called by the runtime to initialize the diagnostic server workers -export function mono_wasm_diagnostic_server_on_server_thread_created(websocketUrlPtr: CharPtr): void { +export function mono_wasm_diagnostic_server_on_server_thread_created (websocketUrlPtr: CharPtr): void { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); const websocketUrl = utf8ToString(websocketUrlPtr); mono_log_debug(`mono_wasm_diagnostic_server_on_server_thread_created, url ${websocketUrl}`); let mock: PromiseAndController | undefined = undefined; if (monoDiagnosticsMock && websocketUrl.startsWith("mock:")) { mock = createPromiseController(); - queueMicrotask(async() => { + queueMicrotask(async () => { const m = await importAndInstantiateMock(websocketUrl); mock!.promise_control.resolve(m); m.run(); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts index 2129fc76e601c7..ddd37a145c089d 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-parser.ts @@ -4,12 +4,12 @@ import Magic from "./magic"; import { BinaryProtocolCommand } from "./types"; -function advancePos(pos: { pos: number }, offset: number): void { +function advancePos (pos: { pos: number }, offset: number): void { pos.pos += offset; } const Parser = { - tryParseHeader(buf: Uint8Array, pos: { pos: number }): boolean { + tryParseHeader (buf: Uint8Array, pos: { pos: number }): boolean { let j = pos.pos; for (let i = 0; i < Magic.DOTNET_IPC_V1.length; i++) { if (buf[j++] !== Magic.DOTNET_IPC_V1[i]) { @@ -19,10 +19,10 @@ const Parser = { advancePos(pos, Magic.DOTNET_IPC_V1.length); return true; }, - tryParseSize(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseSize (buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseUint16(buf, pos); }, - tryParseCommand(buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { + tryParseCommand (buf: Uint8Array, pos: { pos: number }): BinaryProtocolCommand | undefined { const commandSet = Parser.tryParseUint8(buf, pos); if (commandSet === undefined) return undefined; @@ -39,7 +39,7 @@ const Parser = { }; return result; }, - tryParseReserved(buf: Uint8Array, pos: { pos: number }): true | undefined { + tryParseReserved (buf: Uint8Array, pos: { pos: number }): true | undefined { const reservedLength = 2; // 2 bytes reserved, must be 0 for (let i = 0; i < reservedLength; i++) { const reserved = Parser.tryParseUint8(buf, pos); @@ -49,7 +49,7 @@ const Parser = { } return true; }, - tryParseUint8(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint8 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j >= buf.byteLength) { return undefined; @@ -58,7 +58,7 @@ const Parser = { advancePos(pos, 1); return size; }, - tryParseUint16(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint16 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 1 >= buf.byteLength) { return undefined; @@ -67,7 +67,7 @@ const Parser = { advancePos(pos, 2); return size; }, - tryParseUint32(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseUint32 (buf: Uint8Array, pos: { pos: number }): number | undefined { const j = pos.pos; if (j + 3 >= buf.byteLength) { return undefined; @@ -76,7 +76,7 @@ const Parser = { advancePos(pos, 4); return size; }, - tryParseUint64(buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { + tryParseUint64 (buf: Uint8Array, pos: { pos: number }): [number, number] | undefined { const lo = Parser.tryParseUint32(buf, pos); if (lo === undefined) return undefined; @@ -85,22 +85,22 @@ const Parser = { return undefined; return [lo, hi]; }, - tryParseBool(buf: Uint8Array, pos: { pos: number }): boolean | undefined { + tryParseBool (buf: Uint8Array, pos: { pos: number }): boolean | undefined { const r = Parser.tryParseUint8(buf, pos); if (r === undefined) return undefined; return r !== 0; }, - tryParseArraySize(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseArraySize (buf: Uint8Array, pos: { pos: number }): number | undefined { const r = Parser.tryParseUint32(buf, pos); if (r === undefined) return undefined; return r; }, - tryParseStringLength(buf: Uint8Array, pos: { pos: number }): number | undefined { + tryParseStringLength (buf: Uint8Array, pos: { pos: number }): number | undefined { return Parser.tryParseArraySize(buf, pos); }, - tryParseUtf16String(buf: Uint8Array, pos: { pos: number }): string | undefined { + tryParseUtf16String (buf: Uint8Array, pos: { pos: number }): string | undefined { const length = Parser.tryParseStringLength(buf, pos); if (length === undefined) return undefined; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts index 09115d7245bc3b..11c846763b25d2 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/base-serializer.ts @@ -4,7 +4,7 @@ import { CommandSetId, ServerCommandId, EventPipeCommandId, ProcessCommandId } from "./types"; import Magic from "./magic"; -function advancePos(pos: { pos: number }, count: number): void { +function advancePos (pos: { pos: number }, count: number): void { pos.pos += count; } @@ -12,7 +12,7 @@ function advancePos(pos: { pos: number }, count: number): void { function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.EventPipe, command: EventPipeCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Process, command: ProcessCommandId, len: number): void; function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId.Server, command: ServerCommandId, len: number): void; -function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { +function serializeHeader (buf: Uint8Array, pos: { pos: number }, commandSet: CommandSetId, command: EventPipeCommandId | ProcessCommandId | ServerCommandId, len: number): void { Serializer.serializeMagic(buf, pos); Serializer.serializeUint16(buf, pos, len); Serializer.serializeUint8(buf, pos, commandSet); @@ -22,7 +22,7 @@ function serializeHeader(buf: Uint8Array, pos: { pos: number }, commandSet: Comm const Serializer = { - computeMessageByteLength(payload?: number | Uint8Array): number { + computeMessageByteLength (payload?: number | Uint8Array): number { const fullHeaderSize = Magic.MinimalHeaderSize // magic, len + 2 // commandSet, command + 2; // reserved ; @@ -30,33 +30,33 @@ const Serializer = { const len = fullHeaderSize + payloadLength; // magic, size, commandSet, command, reserved return len; }, - serializeMagic(buf: Uint8Array, pos: { pos: number }): void { + serializeMagic (buf: Uint8Array, pos: { pos: number }): void { buf.set(Magic.DOTNET_IPC_V1, pos.pos); advancePos(pos, Magic.DOTNET_IPC_V1.byteLength); }, - serializeUint8(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint8 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value; }, - serializeUint16(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint16 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; }, - serializeUint32(buf: Uint8Array, pos: { pos: number }, value: number): void { + serializeUint32 (buf: Uint8Array, pos: { pos: number }, value: number): void { buf[pos.pos++] = value & 0xFF; buf[pos.pos++] = (value >> 8) & 0xFF; buf[pos.pos++] = (value >> 16) & 0xFF; buf[pos.pos++] = (value >> 24) & 0xFF; }, - serializeUint64(buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { + serializeUint64 (buf: Uint8Array, pos: { pos: number }, value: [number, number]): void { Serializer.serializeUint32(buf, pos, value[0]); Serializer.serializeUint32(buf, pos, value[1]); }, serializeHeader, - serializePayload(buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { + serializePayload (buf: Uint8Array, pos: { pos: number }, payload: Uint8Array): void { buf.set(payload, pos.pos); advancePos(pos, payload.byteLength); }, - serializeString(buf: Uint8Array, pos: { pos: number }, s: string | null): void { + serializeString (buf: Uint8Array, pos: { pos: number }, s: string | null): void { if (s === null || s === undefined || s === "") { Serializer.serializeUint32(buf, pos, 0); } else { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts index e7f27b9c6ab1f2..9d98130bf84c2d 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/magic.ts @@ -3,7 +3,7 @@ let magic_buf: Uint8Array = null!; const Magic = { - get DOTNET_IPC_V1(): Uint8Array { + get DOTNET_IPC_V1 (): Uint8Array { if (magic_buf === null) { const magic = "DOTNET_IPC_V1"; const magic_len = magic.length + 1; // nul terminated @@ -15,7 +15,7 @@ const Magic = { } return magic_buf; }, - get MinimalHeaderSize(): number { + get MinimalHeaderSize (): number { // we just need to see the magic and the size const sizeOfSize = 2; return Magic.DOTNET_IPC_V1.byteLength + sizeOfSize; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts index 765e16718c9533..045bb76a4c5e22 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/parser.ts @@ -27,7 +27,7 @@ interface ParseClientCommandResultOk extends Pars export type ParseClientCommandResult = ParseClientCommandResultOk | ParseResultFail; -export function parseBinaryProtocolCommand(cmd: BinaryProtocolCommand): ParseClientCommandResult { +export function parseBinaryProtocolCommand (cmd: BinaryProtocolCommand): ParseClientCommandResult { switch (cmd.commandSet) { case CommandSetId.Reserved: throw new Error("unexpected reserved command_set command"); @@ -44,7 +44,7 @@ export function parseBinaryProtocolCommand(cmd: BinaryProtocolCommand): ParseCli } } -function parseEventPipeCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { +function parseEventPipeCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe }): ParseClientCommandResult { switch (cmd.command) { case EventPipeCommandId.StopTracing: return parseEventPipeStopTracing(cmd); @@ -58,7 +58,7 @@ function parseEventPipeCommand(cmd: BinaryProtocolCommand & { commandSet: Comman } } -function parseEventPipeCollectTracing2(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { +function parseEventPipeCollectTracing2 (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.CollectTracing2 }): ParseClientCommandResult { const pos = { pos: 0 }; const buf = cmd.payload; const circularBufferMB = Parser.tryParseUint32(buf, pos); @@ -89,7 +89,7 @@ function parseEventPipeCollectTracing2(cmd: BinaryProtocolCommand & { commandSet return { success: true, result: command }; } -function parseEventPipeCollectTracingCommandProvider(buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { +function parseEventPipeCollectTracingCommandProvider (buf: Uint8Array, pos: { pos: number }): ParseClientCommandResult { const keywords = Parser.tryParseUint64(buf, pos); if (keywords === undefined) { return { success: false, error: "failed to parse keywords in EventPipe CollectTracing provider" }; @@ -107,7 +107,7 @@ function parseEventPipeCollectTracingCommandProvider(buf: Uint8Array, pos: { pos return { success: true, result: provider }; } -function parseEventPipeStopTracing(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { +function parseEventPipeStopTracing (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.EventPipe, command: EventPipeCommandId.StopTracing }): ParseClientCommandResult { const pos = { pos: 0 }; const buf = cmd.payload; const sessionID = Parser.tryParseUint64(buf, pos); @@ -122,7 +122,7 @@ function parseEventPipeStopTracing(cmd: BinaryProtocolCommand & { commandSet: Co return { success: true, result: command }; } -function parseProcessCommand(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { +function parseProcessCommand (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process }): ParseClientCommandResult { switch (cmd.command) { case ProcessCommandId.ProcessInfo: throw new Error("TODO"); @@ -138,7 +138,7 @@ function parseProcessCommand(cmd: BinaryProtocolCommand & { commandSet: CommandS } } -function parseProcessResumeRuntime(cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { +function parseProcessResumeRuntime (cmd: BinaryProtocolCommand & { commandSet: CommandSetId.Process, command: ProcessCommandId.ResumeRuntime }): ParseClientCommandResult { const buf = cmd.payload; if (buf.byteLength !== 0) { return { success: false, error: "unexpected payload in Process ResumeRuntime command" }; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts index 6b67488c5fdac7..558926d8533f09 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/serializer.ts @@ -5,7 +5,7 @@ import { mono_assert } from "../../../globals"; import Serializer from "./base-serializer"; import { CommandSetId, ServerCommandId } from "./types"; -export function createBinaryCommandOKReply(payload?: Uint8Array): Uint8Array { +export function createBinaryCommandOKReply (payload?: Uint8Array): Uint8Array { const len = Serializer.computeMessageByteLength(payload); const buf = new Uint8Array(len); const pos = { pos: 0 }; @@ -16,7 +16,7 @@ export function createBinaryCommandOKReply(payload?: Uint8Array): Uint8Array { return buf; } -function serializeGuid(buf: Uint8Array, pos: { pos: number }, guid: string): void { +function serializeGuid (buf: Uint8Array, pos: { pos: number }, guid: string): void { guid.split("-").forEach((part) => { // FIXME: I'm sure the endianness is wrong here for (let i = 0; i < part.length; i += 2) { @@ -26,7 +26,7 @@ function serializeGuid(buf: Uint8Array, pos: { pos: number }, guid: string): voi }); } -function serializeAsciiLiteralString(buf: Uint8Array, pos: { pos: number }, s: string): void { +function serializeAsciiLiteralString (buf: Uint8Array, pos: { pos: number }, s: string): void { const len = s.length; const hasNul = s[len - 1] === "\0"; for (let i = 0; i < len; i++) { @@ -38,7 +38,7 @@ function serializeAsciiLiteralString(buf: Uint8Array, pos: { pos: number }, s: s } -export function createAdvertise(guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { +export function createAdvertise (guid: string, processId: [/*lo*/ number, /*hi*/number]): Uint8Array { const BUF_LENGTH = 34; const buf = new Uint8Array(BUF_LENGTH); const pos = { pos: 0 }; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts index 2031de3499bd3a..70794014fe8e95 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/ipc-protocol/types.ts @@ -8,7 +8,7 @@ export interface BinaryProtocolCommand { payload: Uint8Array; } -export function isBinaryProtocolCommand(x: object): x is BinaryProtocolCommand { +export function isBinaryProtocolCommand (x: object): x is BinaryProtocolCommand { return "commandSet" in x && "command" in x && "payload" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts index b3d07952de76d1..48ec5b1adbd9f2 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/mock-remote.ts @@ -5,7 +5,7 @@ import monoDiagnosticsMock from "consts:monoDiagnosticsMock"; import type { Mock } from "../mock"; import { mock } from "../mock"; -export function importAndInstantiateMock(mockURL: string): Promise { +export function importAndInstantiateMock (mockURL: string): Promise { if (monoDiagnosticsMock) { const mockPrefix = "mock:"; const scriptURL = mockURL.substring(mockPrefix.length); diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts index a255e65fe3c18a..f0f7a054bc46d1 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-client-commands.ts @@ -51,32 +51,32 @@ export type RemoveCommandSetAndId = Omitx).providers) && (x).providers.every(isEventPipeCollectTracingCommandProvider); } -export function isEventPipeCommandStopTracing(x: object): x is EventPipeCommandStopTracing { +export function isEventPipeCommandStopTracing (x: object): x is EventPipeCommandStopTracing { return isEventPipeCommand(x) && x.command === "StopTracing" && "sessionID" in x; } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts index 7bd03e0d003a34..049d1525cd32bd 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/protocol-socket.ts @@ -60,10 +60,10 @@ export type ParseResult = ParseResultBinaryCommandOk | ParseResultFail; class StatefulParser { private state: State = { state: InState.Idle }; - constructor(private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } + constructor (private readonly emitCommandCallback: (command: BinaryProtocolCommand) => void) { } /// process the data in the given buffer and update the state. - receiveBuffer(buf: ArrayBuffer): void { + receiveBuffer (buf: ArrayBuffer): void { if (this.state.state == InState.Error) { return; } @@ -87,7 +87,7 @@ class StatefulParser { } } - tryParseHeader(buf: Uint8Array): ParseResult { + tryParseHeader (buf: Uint8Array): ParseResult { const pos = { pos: 0 }; if (buf.byteLength < Magic.MinimalHeaderSize) { // TODO: we need to see the magic and the size to make a partial commmand @@ -110,14 +110,14 @@ class StatefulParser { return this.continueWithBuffer(partialState, buf.subarray(parsedSize)); } - tryAppendBuffer(moreBuf: Uint8Array): ParseResult { + tryAppendBuffer (moreBuf: Uint8Array): ParseResult { if (this.state.state !== InState.PartialCommand) { return { success: false, error: "not in partial command state" }; } return this.continueWithBuffer(this.state, moreBuf); } - continueWithBuffer(state: PartialCommandState, moreBuf: Uint8Array): ParseResult { + continueWithBuffer (state: PartialCommandState, moreBuf: Uint8Array): ParseResult { const buf = state.buf; let partialSize = state.size; let overflow: Uint8Array | null = null; @@ -150,7 +150,7 @@ class StatefulParser { } } - tryParseCompletedBuffer(buf: Uint8Array, pos: { pos: number }): ParseResult { + tryParseCompletedBuffer (buf: Uint8Array, pos: { pos: number }): ParseResult { const command = Parser.tryParseCommand(buf, pos); if (!command) { this.setState({ state: InState.Error }); @@ -159,11 +159,11 @@ class StatefulParser { return { success: true, command, newState: { state: InState.Idle } }; } - private setState(state: State) { + private setState (state: State) { this.state = state; } - reset() { + reset () { this.setState({ state: InState.Idle }); } @@ -173,9 +173,9 @@ class ProtocolSocketImpl implements ProtocolSocket { private readonly statefulParser = new StatefulParser(this.emitCommandCallback.bind(this)); private protocolListeners = 0; private readonly messageListener: (this: CommonSocket, ev: MessageEvent) => void = this.onMessage.bind(this); - constructor(private readonly sock: CommonSocket) { } + constructor (private readonly sock: CommonSocket) { } - onMessage(this: ProtocolSocketImpl, ev: MessageEvent): void { + onMessage (this: ProtocolSocketImpl, ev: MessageEvent): void { const data = ev.data; mono_log_debug("protocol socket received message", ev.data); if (typeof data === "object" && data instanceof ArrayBuffer) { @@ -190,17 +190,17 @@ class ProtocolSocketImpl implements ProtocolSocket { } } - dispatchEvent(evt: Event): boolean { + dispatchEvent (evt: Event): boolean { return this.sock.dispatchEvent(evt); } - onArrayBuffer(this: ProtocolSocketImpl, buf: ArrayBuffer) { + onArrayBuffer (this: ProtocolSocketImpl, buf: ArrayBuffer) { mono_log_debug("protocol-socket: parsing array buffer", buf); this.statefulParser.receiveBuffer(buf); } // called by the stateful parser when it has a complete command - emitCommandCallback(this: this, command: BinaryProtocolCommand): void { + emitCommandCallback (this: this, command: BinaryProtocolCommand): void { mono_log_debug("protocol-socket: queueing command", command); queueMicrotask(() => { mono_log_debug("dispatching protocol event with command", command); @@ -209,14 +209,14 @@ class ProtocolSocketImpl implements ProtocolSocket { } - dispatchProtocolCommandEvent(cmd: BinaryProtocolCommand): void { + dispatchProtocolCommandEvent (cmd: BinaryProtocolCommand): void { const ev = new Event(dotnetDiagnosticsServerProtocolCommandEvent); (ev).data = cmd; // FIXME: use a proper event subclass this.sock.dispatchEvent(ev); } addEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { + addEventListener (type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void { this.sock.addEventListener(type, listener, options); if (type === dotnetDiagnosticsServerProtocolCommandEvent) { if (this.protocolListeners === 0) { @@ -228,7 +228,7 @@ class ProtocolSocketImpl implements ProtocolSocket { } removeEventListener(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any): void; - removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void { + removeEventListener (type: string, listener: EventListenerOrEventListenerObject): void { if (type === dotnetDiagnosticsServerProtocolCommandEvent) { mono_log_debug("removing protocol listener and message chaser"); this.protocolListeners--; @@ -240,18 +240,18 @@ class ProtocolSocketImpl implements ProtocolSocket { this.sock.removeEventListener(type, listener); } - send(buf: Uint8Array) { + send (buf: Uint8Array) { this.sock.send(buf); } - close() { + close () { this.sock.close(); this.statefulParser.reset(); } } -export function createProtocolSocket(socket: CommonSocket): ProtocolSocket { +export function createProtocolSocket (socket: CommonSocket): ProtocolSocket { return new ProtocolSocketImpl(socket); } diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts index d02ae16e3403a0..fec4a1fc32aabd 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/socket-connection.ts @@ -13,11 +13,11 @@ enum ListenerState { } class SocketGuts { - constructor(public readonly socket: CommonSocket) { } - close(): void { + constructor (public readonly socket: CommonSocket) { } + close (): void { this.socket.close(); } - write(data: VoidPtr, size: number): void { + write (data: VoidPtr, size: number): void { const buf = new ArrayBuffer(size); const view = new Uint8Array(buf); // Can we avoid this copy? @@ -33,12 +33,12 @@ class SocketGuts { export class EventPipeSocketConnection { private _state: ListenerState; readonly stream: SocketGuts; - constructor(socket: CommonSocket) { + constructor (socket: CommonSocket) { this._state = ListenerState.Sending; this.stream = new SocketGuts(socket); } - close(): void { + close (): void { mono_log_debug("EventPipe session stream closing websocket"); switch (this._state) { case ListenerState.Error: @@ -52,7 +52,7 @@ export class EventPipeSocketConnection { } } - write(ptr: VoidPtr, len: number): boolean { + write (ptr: VoidPtr, len: number): boolean { switch (this._state) { case ListenerState.Sending: this.stream.write(ptr, len); @@ -65,7 +65,7 @@ export class EventPipeSocketConnection { } } - private _onMessage(event: MessageEvent): void { + private _onMessage (event: MessageEvent): void { switch (this._state) { case ListenerState.Sending: /* unexpected message */ @@ -85,7 +85,7 @@ export class EventPipeSocketConnection { } - private _onClose(/*event: CloseEvent*/) { + private _onClose (/*event: CloseEvent*/) { switch (this._state) { case ListenerState.Closed: return; /* do nothing */ @@ -99,14 +99,14 @@ export class EventPipeSocketConnection { } } - private _onError(event: Event) { + private _onError (event: Event) { mono_log_debug("EventPipe session stream websocket error", event); this._state = ListenerState.Error; this.stream.close(); // TODO: notify runtime that connection had an error } - addListeners(): void { + addListeners (): void { const socket = this.stream.socket; socket.addEventListener("message", this._onMessage.bind(this)); addEventListener("close", this._onClose.bind(this)); @@ -116,7 +116,7 @@ export class EventPipeSocketConnection { /// Take over a WebSocket that was used by the diagnostic server to receive the StartCollecting command and /// use it for sending the event pipe data back to the host. -export function takeOverSocket(socket: CommonSocket): EventPipeSocketConnection { +export function takeOverSocket (socket: CommonSocket): EventPipeSocketConnection { const connection = new EventPipeSocketConnection(socket); connection.addListeners(); return connection; diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts index 5ab42c2d8b4d96..693082b86b8a20 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/stream-queue.ts @@ -38,36 +38,36 @@ export class StreamQueue { readonly workAvailable: EventTarget = new globalThis.EventTarget(); readonly signalWorkAvailable = this.signalWorkAvailableImpl.bind(this); - constructor(readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { + constructor (readonly queue_addr: VoidPtr, readonly syncSendBuffer: SyncSendBuffer, readonly syncSendClose: SyncSendClose) { this.workAvailable.addEventListener("workAvailable", this.onWorkAvailable.bind(this)); } - private get buf_addr(): VoidPtr { + private get buf_addr (): VoidPtr { return this.queue_addr + BUF_OFFSET; } - private get count_addr(): VoidPtr { + private get count_addr (): VoidPtr { return this.queue_addr + COUNT_OFFSET; } - private get buf_full_addr(): VoidPtr { + private get buf_full_addr (): VoidPtr { return this.queue_addr + WRITE_DONE_OFFSET; } /// called from native code on the diagnostic thread when the streaming thread queues a call to notify the /// diagnostic thread that it can send the buffer. - wakeup(): void { + wakeup (): void { queueMicrotask(this.signalWorkAvailable); } - workAvailableNow(): void { + workAvailableNow (): void { // process the queue immediately, rather than waiting for the next event loop tick. this.onWorkAvailable(); } - private signalWorkAvailableImpl(this: StreamQueue): void { + private signalWorkAvailableImpl (this: StreamQueue): void { this.workAvailable.dispatchEvent(new Event("workAvailable")); } - private onWorkAvailable(this: StreamQueue /*,event: Event */): void { + private onWorkAvailable (this: StreamQueue /*,event: Event */): void { const buf = getI32(this.buf_addr) as unknown as VoidPtr; const intptr_buf = buf as unknown as number; if (intptr_buf === STREAM_CLOSE_SENTINEL) { @@ -90,19 +90,19 @@ export class StreamQueue { // maps stream queue addresses to StreamQueue instances const streamQueueMap = new Map(); -export function allocateQueue(nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { +export function allocateQueue (nativeQueueAddr: VoidPtr, syncSendBuffer: SyncSendBuffer, syncSendClose: SyncSendClose): StreamQueue { const queue = new StreamQueue(nativeQueueAddr, syncSendBuffer, syncSendClose); streamQueueMap.set(nativeQueueAddr, queue); return queue; } -export function closeQueue(nativeQueueAddr: VoidPtr): void { +export function closeQueue (nativeQueueAddr: VoidPtr): void { streamQueueMap.delete(nativeQueueAddr); // TODO: remove the event listener? } // called from native code on the diagnostic thread by queueing a call from the streaming thread. -export function mono_wasm_diagnostic_server_stream_signal_work_available(nativeQueueAddr: VoidPtr, current_thread: number): void { +export function mono_wasm_diagnostic_server_stream_signal_work_available (nativeQueueAddr: VoidPtr, current_thread: number): void { const queue = streamQueueMap.get(nativeQueueAddr); if (queue) { if (current_thread === 0) { diff --git a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts index 6854261e4d00ed..53e30cc594a10f 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/streaming-session.ts @@ -20,11 +20,11 @@ import { mono_assert } from "../../globals"; /// queue used by the EventPipe streaming thread to forward events to the diagnostic server thread, /// and a wrapper around the WebSocket object used to send event data back to the host. export class EventPipeStreamingSession { - constructor(readonly sessionID: EventPipeSessionIDImpl, + constructor (readonly sessionID: EventPipeSessionIDImpl, readonly queue: StreamQueue, readonly connection: EventPipeSocketConnection) { } } -export async function makeEventPipeStreamingSession(ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { +export async function makeEventPipeStreamingSession (ws: WebSocket | MockRemoteSocket, cmd: EventPipeCommandCollectTracing2): Promise { mono_assert(WasmEnableThreads, "The diagnostic server requires threads to be enabled during build time."); // First, create the native IPC stream and get its queue. const ipcStreamAddr = cwraps.mono_wasm_diagnostic_server_create_stream(); // FIXME: this should be a wrapped in a JS object so we can free it when we're done. @@ -46,17 +46,17 @@ export async function makeEventPipeStreamingSession(ws: WebSocket | MockRemoteSo } -function providersStringFromObject(providers: EventPipeCollectTracingCommandProvider[]) { +function providersStringFromObject (providers: EventPipeCollectTracingCommandProvider[]) { const providersString = providers.map(providerToString).join(","); return providersString; - function providerToString(provider: EventPipeCollectTracingCommandProvider): string { + function providerToString (provider: EventPipeCollectTracingCommandProvider): string { const keyword_str = provider.keywords[0] === 0 && provider.keywords[1] === 0 ? "" : keywordsToHexString(provider.keywords); const args_str = provider.filter_data === "" ? "" : ":" + provider.filter_data; return provider.provider_name + ":" + keyword_str + ":" + provider.logLevel + args_str; } - function keywordsToHexString(k: [number, number]): string { + function keywordsToHexString (k: [number, number]): string { const lo = k[0]; const hi = k[1]; const lo_hex = leftPad(lo.toString(16), "0", 8); @@ -64,7 +64,7 @@ function providersStringFromObject(providers: EventPipeCollectTracingCommandProv return hi_hex + lo_hex; } - function leftPad(s: string, fill: string, width: number): string { + function leftPad (s: string, fill: string, width: number): string { if (s.length >= width) return s; const prefix = fill.repeat(width - s.length); @@ -74,6 +74,6 @@ function providersStringFromObject(providers: EventPipeCollectTracingCommandProv const IPC_STREAM_QUEUE_OFFSET = 4; /* keep in sync with mono_wasm_diagnostic_server_create_stream() in C */ -function getQueueAddrFromStreamAddr(streamAddr: VoidPtr): VoidPtr { +function getQueueAddrFromStreamAddr (streamAddr: VoidPtr): VoidPtr { return streamAddr + IPC_STREAM_QUEUE_OFFSET; } diff --git a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts index 16aa6ad85944f2..d4ed6304945118 100644 --- a/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts +++ b/src/mono/browser/runtime/diagnostics/shared/controller-commands.ts @@ -10,7 +10,7 @@ export interface DiagnosticMessage extends MonoThreadMessage { cmd: string; } -export function isDiagnosticMessage(x: unknown): x is DiagnosticMessage { +export function isDiagnosticMessage (x: unknown): x is DiagnosticMessage { return isMonoThreadMessage(x) && x.type === "diagnostic_server"; } @@ -29,7 +29,7 @@ export type DiagnosticServerControlCommandStart = DiagnosticServerControlCommand export type DiagnosticServerControlCommandStop = DiagnosticServerControlCommandSpecific<"stop">; export type DiagnosticServerControlCommandAttachToRuntime = DiagnosticServerControlCommandSpecific<"attach_to_runtime">; -export function makeDiagnosticServerControlCommand(cmd: T): DiagnosticServerControlCommandSpecific { +export function makeDiagnosticServerControlCommand (cmd: T): DiagnosticServerControlCommandSpecific { return { type: "diagnostic_server", cmd: cmd, diff --git a/src/mono/browser/runtime/diagnostics/shared/create-session.ts b/src/mono/browser/runtime/diagnostics/shared/create-session.ts index 17af0cbc5bebba..866c0d1292331d 100644 --- a/src/mono/browser/runtime/diagnostics/shared/create-session.ts +++ b/src/mono/browser/runtime/diagnostics/shared/create-session.ts @@ -25,7 +25,7 @@ type SessionType = }; -function createSessionWithPtrCB(sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { +function createSessionWithPtrCB (sessionIdOutPtr: VoidPtr, options: EventPipeCreateSessionOptions, sessionType: SessionType): false | EventPipeSessionIDImpl { memory.setI32(sessionIdOutPtr, 0); let tracePath: string | null; let ipcStreamAddr: VoidPtr; @@ -43,10 +43,10 @@ function createSessionWithPtrCB(sessionIdOutPtr: VoidPtr, options: EventPipeCrea } } -export function createEventPipeStreamingSession(ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { +export function createEventPipeStreamingSession (ipcStreamAddr: VoidPtr, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "stream", stream: ipcStreamAddr }); } -export function createEventPipeFileSession(tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { +export function createEventPipeFileSession (tracePath: string, options: EventPipeCreateSessionOptions): EventPipeSessionIDImpl | false { return memory.withStackAlloc(sizeOfInt32, createSessionWithPtrCB, options, { type: "file", filePath: tracePath }); } diff --git a/src/mono/browser/runtime/export-api.ts b/src/mono/browser/runtime/export-api.ts index 623c4222218f01..77ada43fd13d52 100644 --- a/src/mono/browser/runtime/export-api.ts +++ b/src/mono/browser/runtime/export-api.ts @@ -10,7 +10,7 @@ import { mono_run_main, mono_run_main_and_exit } from "./run"; import { mono_wasm_setenv } from "./startup"; import { loaderHelpers, runtimeHelpers } from "./globals"; -export function export_api(): any { +export function export_api (): any { const api: APIType = { runMain: mono_run_main, runMainAndExit: mono_run_main_and_exit, diff --git a/src/mono/browser/runtime/exports-binding.ts b/src/mono/browser/runtime/exports-binding.ts index 153ac946010cdb..effdc6fb0f8906 100644 --- a/src/mono/browser/runtime/exports-binding.ts +++ b/src/mono/browser/runtime/exports-binding.ts @@ -118,7 +118,7 @@ const wasmImports: Function[] = [ ...mono_wasm_threads_imports, ]; -export function replace_linker_placeholders(imports: WebAssembly.Imports) { +export function replace_linker_placeholders (imports: WebAssembly.Imports) { // the output from emcc contains wrappers for these linker imports which add overhead, // but now we have what we need to replace them with the actual functions // By default the imports all live inside of 'env', but emscripten minification could rename it to 'a'. diff --git a/src/mono/browser/runtime/exports-internal.ts b/src/mono/browser/runtime/exports-internal.ts index d22da712d25e4a..074b54a18fcc7e 100644 --- a/src/mono/browser/runtime/exports-internal.ts +++ b/src/mono/browser/runtime/exports-internal.ts @@ -25,7 +25,7 @@ import { mono_wasm_bind_cs_function } from "./invoke-cs"; import { mono_wasm_dump_threads, thread_available } from "./pthreads"; -export function export_internal(): any { +export function export_internal (): any { return { // tests mono_wasm_exit: (exit_code: number) => { @@ -116,7 +116,7 @@ export function export_internal(): any { }; } -export function cwraps_internal(internal: any): void { +export function cwraps_internal (internal: any): void { Object.assign(internal, { mono_wasm_exit: cwraps.mono_wasm_exit, mono_wasm_profiler_init_aot: profiler_c_functions.mono_wasm_profiler_init_aot, @@ -127,7 +127,7 @@ export function cwraps_internal(internal: any): void { } /* @deprecated not GC safe, legacy support for Blazor */ -export function monoObjectAsBoolOrNullUnsafe(obj: MonoObject): boolean | null { +export function monoObjectAsBoolOrNullUnsafe (obj: MonoObject): boolean | null { if (obj === MonoObjectNull) { return null; } diff --git a/src/mono/browser/runtime/exports-linker.ts b/src/mono/browser/runtime/exports-linker.ts index 3d8bb179c78689..b1d5c0234f565d 100644 --- a/src/mono/browser/runtime/exports-linker.ts +++ b/src/mono/browser/runtime/exports-linker.ts @@ -4,7 +4,7 @@ import { mono_wasm_imports, mono_wasm_threads_imports } from "./exports-binding"; import gitHash from "consts:gitHash"; -export function export_linker_indexes_as_code(): string { +export function export_linker_indexes_as_code (): string { const indexByName: any = { mono_wasm_imports: {}, mono_wasm_threads_imports: {}, diff --git a/src/mono/browser/runtime/exports.ts b/src/mono/browser/runtime/exports.ts index 2a0489632f955e..d26e3c8b57ce20 100644 --- a/src/mono/browser/runtime/exports.ts +++ b/src/mono/browser/runtime/exports.ts @@ -26,7 +26,7 @@ import { mono_wasm_dump_threads } from "./pthreads"; export let runtimeList: RuntimeList; -function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { +function initializeExports (globalObjects: GlobalObjects): RuntimeAPI { const module = Module; const globals = globalObjects; const globalThisAny = globalThis as any; @@ -75,7 +75,7 @@ function initializeExports(globalObjects: GlobalObjects): RuntimeAPI { class RuntimeList { private list: { [runtimeId: number]: WeakRef } = {}; - public registerRuntime(api: RuntimeAPI): number { + public registerRuntime (api: RuntimeAPI): number { if (api.runtimeId === undefined) { api.runtimeId = Object.keys(this.list).length; } @@ -84,7 +84,7 @@ class RuntimeList { return api.runtimeId; } - public getRuntime(runtimeId: number): RuntimeAPI | undefined { + public getRuntime (runtimeId: number): RuntimeAPI | undefined { const wr = this.list[runtimeId]; return wr ? wr.deref() : undefined; } diff --git a/src/mono/browser/runtime/gc-handles.ts b/src/mono/browser/runtime/gc-handles.ts index 976fc05406c943..30e3f30271451b 100644 --- a/src/mono/browser/runtime/gc-handles.ts +++ b/src/mono/browser/runtime/gc-handles.ts @@ -31,24 +31,24 @@ let _next_gcv_handle = -2; // GCVHandle is like GCHandle, but it's not tracked and allocated by the mono GC, but just by JS. // It's used when we need to create GCHandle-like identity ahead of time, before calling Mono. // they have negative values, so that they don't collide with GCHandles. -export function alloc_gcv_handle(): GCHandle { +export function alloc_gcv_handle (): GCHandle { const gcv_handle = _gcv_handle_free_list.length ? _gcv_handle_free_list.pop() : _next_gcv_handle--; return gcv_handle as any; } -export function free_gcv_handle(gcv_handle: GCHandle): void { +export function free_gcv_handle (gcv_handle: GCHandle): void { _gcv_handle_free_list.push(gcv_handle); } -export function is_jsv_handle(js_handle: JSHandle): boolean { +export function is_jsv_handle (js_handle: JSHandle): boolean { return (js_handle as any) < -1; } -export function is_js_handle(js_handle: JSHandle): boolean { +export function is_js_handle (js_handle: JSHandle): boolean { return (js_handle as any) > 0; } -export function is_gcv_handle(gc_handle: GCHandle): boolean { +export function is_gcv_handle (gc_handle: GCHandle): boolean { return (gc_handle as any) < -1; } @@ -62,7 +62,7 @@ export const cs_owned_js_handle_symbol = Symbol.for("wasm cs_owned_js_handle"); export const do_not_force_dispose = Symbol.for("wasm do_not_force_dispose"); -export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { +export function mono_wasm_get_jsobj_from_js_handle (js_handle: JSHandle): any { if (is_js_handle(js_handle)) return _cs_owned_objects_by_js_handle[js_handle]; if (is_jsv_handle(js_handle)) @@ -70,7 +70,7 @@ export function mono_wasm_get_jsobj_from_js_handle(js_handle: JSHandle): any { return null; } -export function mono_wasm_get_js_handle(js_obj: any): JSHandle { +export function mono_wasm_get_js_handle (js_obj: any): JSHandle { assert_js_interop(); if (js_obj[cs_owned_js_handle_symbol]) { return js_obj[cs_owned_js_handle_symbol]; @@ -91,7 +91,7 @@ export function mono_wasm_get_js_handle(js_obj: any): JSHandle { return js_handle as JSHandle; } -export function register_with_jsv_handle(js_obj: any, jsv_handle: JSHandle) { +export function register_with_jsv_handle (js_obj: any, jsv_handle: JSHandle) { assert_js_interop(); // note _cs_owned_objects_by_js_handle is list, not Map. That's why we maintain _js_handle_free_list. _cs_owned_objects_by_jsv_handle[0 - jsv_handle] = js_obj; @@ -102,7 +102,7 @@ export function register_with_jsv_handle(js_obj: any, jsv_handle: JSHandle) { } // note: in MT, this is called from locked JSProxyContext. Don't call anything that would need locking. -export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { +export function mono_wasm_release_cs_owned_object (js_handle: JSHandle): void { let obj: any; if (is_js_handle(js_handle)) { obj = _cs_owned_objects_by_js_handle[js_handle]; @@ -119,7 +119,7 @@ export function mono_wasm_release_cs_owned_object(js_handle: JSHandle): void { } } -export function setup_managed_proxy(owner: any, gc_handle: GCHandle): void { +export function setup_managed_proxy (owner: any, gc_handle: GCHandle): void { assert_js_interop(); // keep the gc_handle so that we could easily convert it back to original C# object for roundtrip owner[js_owned_gc_handle_symbol] = gc_handle; @@ -136,7 +136,7 @@ export function setup_managed_proxy(owner: any, gc_handle: GCHandle): void { _js_owned_object_table.set(gc_handle, wr); } -export function upgrade_managed_proxy_to_strong_ref(owner: any, gc_handle: GCHandle): void { +export function upgrade_managed_proxy_to_strong_ref (owner: any, gc_handle: GCHandle): void { const sr = create_strong_ref(owner); if (_use_finalization_registry) { _js_owned_object_registry.unregister(owner); @@ -144,7 +144,7 @@ export function upgrade_managed_proxy_to_strong_ref(owner: any, gc_handle: GCHan _js_owned_object_table.set(gc_handle, sr); } -export function teardown_managed_proxy(owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { +export function teardown_managed_proxy (owner: any, gc_handle: GCHandle, skipManaged?: boolean): void { assert_js_interop(); // The JS object associated with this gc_handle has been collected by the JS GC. // As such, it's not possible for this gc_handle to be invoked by JS anymore, so @@ -168,13 +168,13 @@ export function teardown_managed_proxy(owner: any, gc_handle: GCHandle, skipMana } } -export function assert_not_disposed(result: any): GCHandle { +export function assert_not_disposed (result: any): GCHandle { const gc_handle = result[js_owned_gc_handle_symbol]; mono_check(gc_handle != GCHandleNull, "ObjectDisposedException"); return gc_handle; } -function _js_owned_object_finalized(gc_handle: GCHandle): void { +function _js_owned_object_finalized (gc_handle: GCHandle): void { if (!loaderHelpers.is_runtime_running()) { // We're shutting down, so don't bother doing anything else. return; @@ -182,7 +182,7 @@ function _js_owned_object_finalized(gc_handle: GCHandle): void { teardown_managed_proxy(null, gc_handle); } -export function _lookup_js_owned_object(gc_handle: GCHandle): any { +export function _lookup_js_owned_object (gc_handle: GCHandle): any { if (!gc_handle) return null; const wr = _js_owned_object_table.get(gc_handle); @@ -194,7 +194,7 @@ export function _lookup_js_owned_object(gc_handle: GCHandle): any { return null; } -export function assertNoProxies(): void { +export function assertNoProxies (): void { if (!WasmEnableThreads) return; mono_assert(_js_owned_object_table.size === 0, "There should be no proxies on this thread."); mono_assert(_cs_owned_objects_by_js_handle.length === 1, "There should be no proxies on this thread."); @@ -207,7 +207,7 @@ let force_dispose_proxies_in_progress = false; // when we arrive here from UninstallWebWorkerInterop, the C# will unregister the handles too. // when called from elsewhere, C# side could be unbalanced!! -export function forceDisposeProxies(disposeMethods: boolean, verbose: boolean): void { +export function forceDisposeProxies (disposeMethods: boolean, verbose: boolean): void { let keepSomeCsAlive = false; let keepSomeJsAlive = false; force_dispose_proxies_in_progress = true; diff --git a/src/mono/browser/runtime/gc-lock.ts b/src/mono/browser/runtime/gc-lock.ts index ea373eecc0447d..7a85513fd5ebde 100644 --- a/src/mono/browser/runtime/gc-lock.ts +++ b/src/mono/browser/runtime/gc-lock.ts @@ -7,7 +7,7 @@ import cwraps from "./cwraps"; export let gc_locked = false; -export function mono_wasm_gc_lock(): void { +export function mono_wasm_gc_lock (): void { if (gc_locked) { throw new Error("GC is already locked"); } @@ -20,7 +20,7 @@ export function mono_wasm_gc_lock(): void { gc_locked = true; } -export function mono_wasm_gc_unlock(): void { +export function mono_wasm_gc_unlock (): void { if (!gc_locked) { throw new Error("GC is not locked"); } diff --git a/src/mono/browser/runtime/globals.ts b/src/mono/browser/runtime/globals.ts index 06baa02735c1be..047fcb60c95027 100644 --- a/src/mono/browser/runtime/globals.ts +++ b/src/mono/browser/runtime/globals.ts @@ -32,7 +32,7 @@ export let loaderHelpers: LoaderHelpers = null as any; export let _runtimeModuleLoaded = false; // please keep it in place also as rollup guard -export function passEmscriptenInternals(internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { +export function passEmscriptenInternals (internals: EmscriptenInternals, emscriptenBuildOptions: EmscriptenBuildOptions): void { runtimeHelpers.emscriptenBuildOptions = emscriptenBuildOptions; ENVIRONMENT_IS_PTHREAD = internals.isPThread; @@ -44,7 +44,7 @@ export function passEmscriptenInternals(internals: EmscriptenInternals, emscript } // NOTE: this is called AFTER the config is loaded -export function setRuntimeGlobals(globalObjects: GlobalObjects) { +export function setRuntimeGlobals (globalObjects: GlobalObjects) { if (_runtimeModuleLoaded) { throw new Error("Runtime module already loaded"); } @@ -86,14 +86,14 @@ export function setRuntimeGlobals(globalObjects: GlobalObjects) { }); } -export function createPromiseController(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { return loaderHelpers.createPromiseController(afterResolve, afterReject); } // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() diff --git a/src/mono/browser/runtime/guarded-promise.ts b/src/mono/browser/runtime/guarded-promise.ts index fe46ca43521ba2..8901403b758bef 100644 --- a/src/mono/browser/runtime/guarded-promise.ts +++ b/src/mono/browser/runtime/guarded-promise.ts @@ -3,7 +3,7 @@ /// A Promise that guards against multiple-resolve, multiple-reject, reject-after-accept and accept-after-reject. class GuardedPromise extends Promise { - constructor(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { + constructor (executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void) { super((resolve, reject) => { let resolved = false; let rejected = false; diff --git a/src/mono/browser/runtime/http.ts b/src/mono/browser/runtime/http.ts index 120ed4ab0a785e..9591c3c86fed06 100644 --- a/src/mono/browser/runtime/http.ts +++ b/src/mono/browser/runtime/http.ts @@ -11,7 +11,7 @@ import type { VoidPtr } from "./types/emscripten"; import { ControllablePromise } from "./types/internal"; -function verifyEnvironment() { +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. See also https://aka.ms/dotnet-wasm-features" @@ -20,13 +20,13 @@ function verifyEnvironment() { } } -function commonAsserts(controller: HttpController) { +function commonAsserts (controller: HttpController) { assert_js_interop(); mono_assert(controller, "expected controller"); } let http_wasm_supports_streaming_request_cached: boolean | undefined; -export function http_wasm_supports_streaming_request(): boolean { +export function http_wasm_supports_streaming_request (): boolean { if (http_wasm_supports_streaming_request_cached !== undefined) { return http_wasm_supports_streaming_request_cached; } @@ -42,7 +42,7 @@ export function http_wasm_supports_streaming_request(): boolean { const hasContentType = new Request("", { body: new ReadableStream(), method: "POST", - get duplex() { + get duplex () { duplexAccessed = true; return "half"; }, @@ -55,7 +55,7 @@ export function http_wasm_supports_streaming_request(): boolean { } let http_wasm_supports_streaming_response_cached: boolean | undefined; -export function http_wasm_supports_streaming_response(): boolean { +export function http_wasm_supports_streaming_response (): boolean { if (http_wasm_supports_streaming_response_cached !== undefined) { return http_wasm_supports_streaming_response_cached; } @@ -63,7 +63,7 @@ export function http_wasm_supports_streaming_response(): boolean { return http_wasm_supports_streaming_response_cached; } -export function http_wasm_create_controller(): HttpController { +export function http_wasm_create_controller (): HttpController { verifyEnvironment(); assert_js_interop(); const controller: HttpController = { @@ -72,7 +72,7 @@ export function http_wasm_create_controller(): HttpController { return controller; } -export function http_wasm_abort_request(controller: HttpController): void { +export function http_wasm_abort_request (controller: HttpController): void { try { if (controller.streamWriter) { controller.streamWriter.abort(); @@ -83,7 +83,7 @@ export function http_wasm_abort_request(controller: HttpController): void { http_wasm_abort_response(controller); } -export function http_wasm_abort_response(controller: HttpController): void { +export function http_wasm_abort_response (controller: HttpController): void { if (BuildConfiguration === "Debug") commonAsserts(controller); try { controller.isAborted = true; @@ -101,13 +101,13 @@ export function http_wasm_abort_response(controller: HttpController): void { } } -export function http_wasm_transform_stream_write(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_transform_stream_write (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(bufferLength > 0, "expected bufferLength > 0"); // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); const copy = view.slice() as Uint8Array; - return wrap_as_cancelable_promise(async() => { + return wrap_as_cancelable_promise(async () => { mono_assert(controller.streamWriter, "expected streamWriter"); mono_assert(controller.responsePromise, "expected fetch promise"); // race with fetch because fetch does not cancel the ReadableStream see https://bugs.chromium.org/p/chromium/issues/detail?id=1480250 @@ -116,9 +116,9 @@ export function http_wasm_transform_stream_write(controller: HttpController, buf }); } -export function http_wasm_transform_stream_close(controller: HttpController): ControllablePromise { +export function http_wasm_transform_stream_close (controller: HttpController): ControllablePromise { mono_assert(controller, "expected controller"); - return wrap_as_cancelable_promise(async() => { + return wrap_as_cancelable_promise(async () => { mono_assert(controller.streamWriter, "expected streamWriter"); mono_assert(controller.responsePromise, "expected fetch promise"); // race with fetch because fetch does not cancel the ReadableStream see https://bugs.chromium.org/p/chromium/issues/detail?id=1480250 @@ -127,7 +127,7 @@ export function http_wasm_transform_stream_close(controller: HttpController): Co }); } -export function http_wasm_fetch_stream(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { +export function http_wasm_fetch_stream (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[]): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); const transformStream = new TransformStream(); controller.streamWriter = transformStream.writable.getWriter(); @@ -135,7 +135,7 @@ export function http_wasm_fetch_stream(controller: HttpController, url: string, return fetch_promise; } -export function http_wasm_fetch_bytes(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { +export function http_wasm_fetch_bytes (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], bodyPtr: VoidPtr, bodyLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bodyPtr is pinned by the caller const view = new Span(bodyPtr, bodyLength, MemoryViewType.Byte); @@ -143,7 +143,7 @@ export function http_wasm_fetch_bytes(controller: HttpController, url: string, h return http_wasm_fetch(controller, url, header_names, header_values, option_names, option_values, copy); } -export function http_wasm_fetch(controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { +export function http_wasm_fetch (controller: HttpController, url: string, header_names: string[], header_values: string[], option_names: string[], option_values: any[], body: Uint8Array | ReadableStream | null): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); verifyEnvironment(); assert_js_interop(); @@ -189,32 +189,32 @@ export function http_wasm_fetch(controller: HttpController, url: string, header_ return controller.responsePromise; } -export function http_wasm_get_response_type(controller: HttpController): string | undefined { +export function http_wasm_get_response_type (controller: HttpController): string | undefined { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.type; } -export function http_wasm_get_response_status(controller: HttpController): number { +export function http_wasm_get_response_status (controller: HttpController): number { if (BuildConfiguration === "Debug") commonAsserts(controller); return controller.response?.status ?? 0; } -export function http_wasm_get_response_header_names(controller: HttpController): string[] { +export function http_wasm_get_response_header_names (controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderNames, "expected responseHeaderNames"); return controller.responseHeaderNames; } -export function http_wasm_get_response_header_values(controller: HttpController): string[] { +export function http_wasm_get_response_header_values (controller: HttpController): string[] { if (BuildConfiguration === "Debug") commonAsserts(controller); mono_assert(controller.responseHeaderValues, "expected responseHeaderValues"); return controller.responseHeaderValues; } -export function http_wasm_get_response_length(controller: HttpController): ControllablePromise { +export function http_wasm_get_response_length (controller: HttpController): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); - return wrap_as_cancelable_promise(async() => { + return wrap_as_cancelable_promise(async () => { const buffer = await controller.response!.arrayBuffer(); controller.responseBuffer = buffer; controller.currentBufferOffset = 0; @@ -222,7 +222,7 @@ export function http_wasm_get_response_length(controller: HttpController): Contr }); } -export function http_wasm_get_response_bytes(controller: HttpController, view: Span): number { +export function http_wasm_get_response_bytes (controller: HttpController, view: Span): number { mono_assert(controller, "expected controller"); mono_assert(controller.responseBuffer, "expected resoved arrayBuffer"); mono_assert(controller.currentBufferOffset != undefined, "expected currentBufferOffset"); @@ -236,11 +236,11 @@ export function http_wasm_get_response_bytes(controller: HttpController, view: S return bytes_read; } -export function http_wasm_get_streamed_response_bytes(controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { +export function http_wasm_get_streamed_response_bytes (controller: HttpController, bufferPtr: VoidPtr, bufferLength: number): ControllablePromise { if (BuildConfiguration === "Debug") commonAsserts(controller); // the bufferPtr is pinned by the caller const view = new Span(bufferPtr, bufferLength, MemoryViewType.Byte); - return wrap_as_cancelable_promise(async() => { + return wrap_as_cancelable_promise(async () => { mono_assert(controller.response, "expected response"); if (!controller.streamReader) { controller.streamReader = controller.response.body!.getReader(); diff --git a/src/mono/browser/runtime/hybrid-globalization/calendar.ts b/src/mono/browser/runtime/hybrid-globalization/calendar.ts index 38bc3f33da9299..56183658a368ed 100644 --- a/src/mono/browser/runtime/hybrid-globalization/calendar.ts +++ b/src/mono/browser/runtime/hybrid-globalization/calendar.ts @@ -14,7 +14,7 @@ const YEAR_CODE = "yyyy"; const DAY_CODE = "d"; // this function joins all calendar info with OUTER_SEPARATOR into one string and returns it back to managed code -export function mono_wasm_get_calendar_info(culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_calendar_info (culture: MonoStringRef, calendarId: number, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -71,14 +71,14 @@ export function mono_wasm_get_calendar_info(culture: MonoStringRef, calendarId: } } -function getCalendarName(locale: any) { +function getCalendarName (locale: any) { const calendars = getCalendarInfo(locale); if (!calendars || calendars.length == 0) return ""; return calendars[0]; } -function getCalendarInfo(locale: string) { +function getCalendarInfo (locale: string) { try { // most tools have it implemented as a property return (new Intl.Locale(locale) as any).calendars; @@ -92,7 +92,7 @@ function getCalendarInfo(locale: string) { } } -function getMonthYearPattern(locale: string | undefined, date: Date): string { +function getMonthYearPattern (locale: string | undefined, date: Date): string { let pattern = date.toLocaleDateString(locale, { year: "numeric", month: "long" }).toLowerCase(); // pattern has month name as string or as number const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); @@ -108,7 +108,7 @@ function getMonthYearPattern(locale: string | undefined, date: Date): string { return pattern.replace(yearStr, YEAR_CODE); } -function getMonthDayPattern(locale: string | undefined, date: Date): string { +function getMonthDayPattern (locale: string | undefined, date: Date): string { let pattern = date.toLocaleDateString(locale, { month: "long", day: "numeric" }).toLowerCase(); // pattern has month name as string or as number const monthName = date.toLocaleString(locale, { month: "long" }).toLowerCase().trim(); @@ -124,7 +124,7 @@ function getMonthDayPattern(locale: string | undefined, date: Date): string { return pattern.replace(dayStr, DAY_CODE); } -function getShortDatePattern(locale: string | undefined): string { +function getShortDatePattern (locale: string | undefined): string { if (locale?.substring(0, 2) == "fa") { // persian calendar is shifted and it has no lapping dates with // arabic and gregorian calendars, so that both day and month would be < 10 @@ -176,7 +176,7 @@ function getShortDatePattern(locale: string | undefined): string { return normalizeSpaces(pattern); } -function getLongDatePattern(locale: string | undefined, date: Date): string { +function getLongDatePattern (locale: string | undefined, date: Date): string { if (locale == "th-TH") { // cannot be caught with regexes return "ddddที่ d MMMM g yyyy"; @@ -208,7 +208,7 @@ function getLongDatePattern(locale: string | undefined, date: Date): string { return pattern.replace(dayStr, DAY_CODE); } -function getGenitiveForName(date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) { +function getGenitiveForName (date: Date, pattern: string, name: string, formatWithoutName: Intl.DateTimeFormat) { let genitiveName = name; const nameStart = pattern.indexOf(name); if (nameStart == -1 || @@ -226,7 +226,7 @@ function getGenitiveForName(date: Date, pattern: string, name: string, formatWit return genitiveName; } -function getDayNames(locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } { +function getDayNames (locale: string | undefined) : { long: string[], abbreviated: string[], shortest: string[] } { const weekDay = new Date(2023, 5, 25); // Sunday const dayNames = []; const dayNamesAbb = []; @@ -240,7 +240,7 @@ function getDayNames(locale: string | undefined) : { long: string[], abbreviated return { long: dayNames, abbreviated: dayNamesAbb, shortest: dayNamesSS }; } -function getMonthNames(locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } { +function getMonthNames (locale: string | undefined) : { long: string[], abbreviated: string[], longGenitive: string[], abbreviatedGenitive: string[] } { // some calendars have the first month on non-0 index in JS // first month: Muharram ("ar") or Farwardin ("fa") or January const localeLang = locale ? locale.split("-")[0] : ""; @@ -285,7 +285,7 @@ function getMonthNames(locale: string | undefined) : { long: string[], abbreviat // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. -function getEraNames(date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} { +function getEraNames (date: Date, locale: string | undefined, calendarId: number) : { eraNames: string, abbreviatedEraNames: string} { if (shouldBePopulatedByManagedCode(calendarId)) { // managed code already handles these calendars, // so empty strings will get overwritten in @@ -309,11 +309,11 @@ function getEraNames(date: Date, locale: string | undefined, calendarId: number) abbreviatedEraNames: getEraFromDateParts(eraDateParts.abbrEraDateParts, eraDateParts.ignoredPart) }; - function shouldBePopulatedByManagedCode(calendarId: number) { + function shouldBePopulatedByManagedCode (calendarId: number) { return (calendarId > 1 && calendarId < 15) || calendarId == 22 || calendarId == 23; } - function getEraFromDateParts(dateParts: string[], ignoredPart: string) : string { + function getEraFromDateParts (dateParts: string[], ignoredPart: string) : string { const regex = new RegExp(`^((?!${ignoredPart}|[0-9]).)*$`); const filteredEra = dateParts.filter(part => regex.test(part)); if (filteredEra.length == 0) @@ -321,7 +321,7 @@ function getEraNames(date: Date, locale: string | undefined, calendarId: number) return filteredEra[0].trim(); } - function getEraDateParts(yearStr: string) { + function getEraDateParts (yearStr: string) { if (eraDate.startsWith(yearStr) || eraDate.endsWith(yearStr)) { return { eraDateParts: eraDate.split(dayStr), diff --git a/src/mono/browser/runtime/hybrid-globalization/change-case.ts b/src/mono/browser/runtime/hybrid-globalization/change-case.ts index 3ed5182dfa5530..f391947803740f 100644 --- a/src/mono/browser/runtime/hybrid-globalization/change-case.ts +++ b/src/mono/browser/runtime/hybrid-globalization/change-case.ts @@ -9,7 +9,7 @@ import { wrap_error_root, wrap_no_error_root } from "../invoke-js"; import { localHeapViewU16, setU16_local } from "../memory"; import { isSurrogate } from "./helpers"; -export function mono_wasm_change_case_invariant(src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case_invariant (src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const exceptionRoot = mono_wasm_new_external_root(ex_address); try { const input = utf16ToStringLoop(src, src + 2 * srcLength); @@ -67,7 +67,7 @@ export function mono_wasm_change_case_invariant(src: number, srcLength: number, } } -export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { +export function mono_wasm_change_case (culture: MonoStringRef, src: number, srcLength: number, dst: number, dstLength: number, toUpper: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): void { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -128,7 +128,7 @@ export function mono_wasm_change_case(culture: MonoStringRef, src: number, srcLe } } -function appendSurrogateToMemory(heapI16: Uint16Array, dst: number, surrogate: string, idx: number) { +function appendSurrogateToMemory (heapI16: Uint16Array, dst: number, surrogate: string, idx: number) { setU16_local(heapI16, dst + idx * 2, surrogate.charCodeAt(0)); setU16_local(heapI16, dst + (idx + 1) * 2, surrogate.charCodeAt(1)); } diff --git a/src/mono/browser/runtime/hybrid-globalization/collations.ts b/src/mono/browser/runtime/hybrid-globalization/collations.ts index 080544801697e1..03133f17d79711 100644 --- a/src/mono/browser/runtime/hybrid-globalization/collations.ts +++ b/src/mono/browser/runtime/hybrid-globalization/collations.ts @@ -12,7 +12,7 @@ const COMPARISON_ERROR = -2; const INDEXING_ERROR = -1; let graphemeSegmenterCached: GraphemeSegmenter | null; -export function mono_wasm_compare_string(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_compare_string (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -32,7 +32,7 @@ export function mono_wasm_compare_string(culture: MonoStringRef, str1: number, s } } -export function mono_wasm_starts_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_starts_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -61,7 +61,7 @@ export function mono_wasm_starts_with(culture: MonoStringRef, str1: number, str1 } } -export function mono_wasm_ends_with(culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_ends_with (culture: MonoStringRef, str1: number, str1Length: number, str2: number, str2Length: number, options: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -90,7 +90,7 @@ export function mono_wasm_ends_with(culture: MonoStringRef, str1: number, str1Le } } -export function mono_wasm_index_of(culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { +export function mono_wasm_index_of (culture: MonoStringRef, needlePtr: number, needleLength: number, srcPtr: number, srcLength: number, options: number, fromBeginning: number, is_exception: Int32Ptr, ex_address: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(ex_address); try { @@ -158,12 +158,12 @@ export function mono_wasm_index_of(culture: MonoStringRef, needlePtr: number, ne exceptionRoot.release(); } - function checkMatchFound(str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { + function checkMatchFound (str1: string, str2: string, locale: string | undefined, casePicker: number): boolean { return compareStrings(str1, str2, locale, casePicker) === 0; } } -function compareStrings(string1: string, string2: string, locale: string | undefined, casePicker: number): number { +function compareStrings (string1: string, string2: string, locale: string | undefined, casePicker: number): number { switch (casePicker) { case 0: // 0: None - default algorithm for the platform OR @@ -255,12 +255,12 @@ function compareStrings(string1: string, string2: string, locale: string | undef } } -function decodeToCleanString(strPtr: number, strLen: number) { +function decodeToCleanString (strPtr: number, strLen: number) { const str = utf16ToString(strPtr, (strPtr + 2 * strLen)); return cleanString(str); } -function cleanString(str: string) { +function cleanString (str: string) { const nStr = str.normalize(); return nStr.replace(/[\u200B-\u200D\uFEFF\0]/g, ""); } diff --git a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts index d6d095a3effee4..3b2643646962af 100644 --- a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts +++ b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts @@ -8,7 +8,7 @@ import { Int32Ptr } from "../types/emscripten"; import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; import { OUTER_SEPARATOR, normalizeLocale, normalizeSpaces } from "./helpers"; -export function mono_wasm_get_culture_info(culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_culture_info (culture: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); try { @@ -41,7 +41,7 @@ export function mono_wasm_get_culture_info(culture: MonoStringRef, dst: number, } } -function getAmPmDesignators(locale: any) { +function getAmPmDesignators (locale: any) { const pmTime = new Date("August 19, 1975 12:15:33"); // do not change, some PM hours result in hour digits change, e.g. 13 -> 01 or 1 const amTime = new Date("August 19, 1975 11:15:33"); // do not change, some AM hours result in hour digits change, e.g. 9 -> 09 const pmDesignator = getDesignator(pmTime, locale); @@ -52,7 +52,7 @@ function getAmPmDesignators(locale: any) { }; } -function getDesignator(time: Date, locale: string) { +function getDesignator (time: Date, locale: string) { let withDesignator = time.toLocaleTimeString(locale, { hourCycle: "h12" }); const localizedZero = (0).toLocaleString(locale); if (withDesignator.includes(localizedZero)) { @@ -71,7 +71,7 @@ function getDesignator(time: Date, locale: string) { return designator; } -function getLongTimePattern(locale: string | undefined, designators: any): string { +function getLongTimePattern (locale: string | undefined, designators: any): string { const hourIn24Format = 18; // later hours than 18 have night designators in some locales (instead of AM designator) const hourIn12Format = 6; const localizedHour24 = (hourIn24Format).toLocaleString(locale); // not all locales use arabic numbers @@ -101,7 +101,7 @@ function getLongTimePattern(locale: string | undefined, designators: any): strin return normalizeSpaces(pattern); } -function getShortTimePattern(pattern: string): string { +function getShortTimePattern (pattern: string): string { // remove seconds: // short dotnet pattern does not contain seconds while JS's pattern always contains them const secondsIdx = pattern.indexOf("ss"); diff --git a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts index 18547a0d359128..83bf8619affec8 100644 --- a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts +++ b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts @@ -29,7 +29,7 @@ type SegmentationTypeRaw = { let segmentationRules: Record; -function replaceVariables(variables: Record, input: string): string { +function replaceVariables (variables: Record, input: string): string { const findVarRegex = /\$[A-Za-z0-9_]+/gm; return input.replaceAll(findVarRegex, match => { if (!(match in variables)) { @@ -39,15 +39,15 @@ function replaceVariables(variables: Record, input: string): str }); } -function generateRegexRule(rule: string, variables: Record, after: boolean): RegExp { +function generateRegexRule (rule: string, variables: Record, after: boolean): RegExp { return new RegExp(`${after ? "^" : ""}${replaceVariables(variables, rule)}${after ? "" : "$"}`); } -function isSegmentationTypeRaw(obj: any): obj is SegmentationTypeRaw { +function isSegmentationTypeRaw (obj: any): obj is SegmentationTypeRaw { return obj.variables != null && obj.rules != null; } -export function setSegmentationRulesFromJson(json: string) { +export function setSegmentationRulesFromJson (json: string) { mono_assert(isSegmentationTypeRaw(json), "Provided grapheme segmentation rules are not valid"); segmentationRules = GraphemeSegmenter.prepareSegmentationRules(json); } @@ -56,7 +56,7 @@ export class GraphemeSegmenter { private readonly rules: Record; private readonly ruleSortedKeys: string[]; - public constructor() { + public constructor () { this.rules = segmentationRules; this.ruleSortedKeys = Object.keys(this.rules).sort((a, b) => Number(a) - Number(b)); } @@ -67,7 +67,7 @@ export class GraphemeSegmenter { * @param startIndex - The starting index. * @returns The next grapheme. */ - public nextGrapheme(str: string, startIndex: number): string { + public nextGrapheme (str: string, startIndex: number): string { const breakIdx = this.nextGraphemeBreak(str, startIndex); return str.substring(startIndex, breakIdx); } @@ -79,7 +79,7 @@ export class GraphemeSegmenter { * @param startIndex - The index to start searching from. * @returns The index of the next grapheme break. */ - public nextGraphemeBreak(str: string, startIndex: number): number { + public nextGraphemeBreak (str: string, startIndex: number): number { if (startIndex < 0) return 0; @@ -103,7 +103,7 @@ export class GraphemeSegmenter { return str.length; } - private isGraphemeBreak(previous: string, current: string): boolean { + private isGraphemeBreak (previous: string, current: string): boolean { for (const key of this.ruleSortedKeys) { const { before, after, breaks } = this.rules[key]; // match before and after rules @@ -121,7 +121,7 @@ export class GraphemeSegmenter { return true; } - public static prepareSegmentationRules(segmentationRules: SegmentationTypeRaw): Record { + public static prepareSegmentationRules (segmentationRules: SegmentationTypeRaw): Record { const preparedRules: Record = {}; for (const key of Object.keys(segmentationRules.rules)) { diff --git a/src/mono/browser/runtime/hybrid-globalization/helpers.ts b/src/mono/browser/runtime/hybrid-globalization/helpers.ts index b6542eeedc69cb..0cd2294447226f 100644 --- a/src/mono/browser/runtime/hybrid-globalization/helpers.ts +++ b/src/mono/browser/runtime/hybrid-globalization/helpers.ts @@ -9,7 +9,7 @@ const SURROGATE_LOWER_END = "\uDFFF"; export const OUTER_SEPARATOR = "##"; export const INNER_SEPARATOR = "||"; -export function normalizeLocale(locale: string | null) { +export function normalizeLocale (locale: string | null) { if (!locale) return undefined; try { @@ -26,7 +26,7 @@ export function normalizeLocale(locale: string | null) { } } -export function normalizeSpaces(pattern: string) { +export function normalizeSpaces (pattern: string) { if (!pattern.includes("\u202F")) return pattern; @@ -35,7 +35,7 @@ export function normalizeSpaces(pattern: string) { } -export function isSurrogate(str: string, startIdx: number): boolean { +export function isSurrogate (str: string, startIdx: number): boolean { return SURROGATE_HIGHER_START <= str[startIdx] && str[startIdx] <= SURROGATE_HIGHER_END && startIdx + 1 < str.length && diff --git a/src/mono/browser/runtime/hybrid-globalization/locales.ts b/src/mono/browser/runtime/hybrid-globalization/locales.ts index 55f3bc4983b7c0..1a6d68843e81fc 100644 --- a/src/mono/browser/runtime/hybrid-globalization/locales.ts +++ b/src/mono/browser/runtime/hybrid-globalization/locales.ts @@ -8,7 +8,7 @@ import { Int32Ptr } from "../types/emscripten"; import { MonoObject, MonoObjectRef, MonoString, MonoStringRef } from "../types/internal"; import { OUTER_SEPARATOR, normalizeLocale } from "./helpers"; -export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_locale_info (culture: MonoStringRef, locale: MonoStringRef, dst: number, dstLength: number, isException: Int32Ptr, exAddress: MonoObjectRef): number { const localeRoot = mono_wasm_new_external_root(locale), cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -82,7 +82,7 @@ export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoSt } } -export function mono_wasm_get_first_day_of_week(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_first_day_of_week (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -100,7 +100,7 @@ export function mono_wasm_get_first_day_of_week(culture: MonoStringRef, isExcept } } -export function mono_wasm_get_first_week_of_year(culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { +export function mono_wasm_get_first_week_of_year (culture: MonoStringRef, isException: Int32Ptr, exAddress: MonoObjectRef): number { const cultureRoot = mono_wasm_new_external_root(culture), exceptionRoot = mono_wasm_new_external_root(exAddress); @@ -118,7 +118,7 @@ export function mono_wasm_get_first_week_of_year(culture: MonoStringRef, isExcep } } -function getFirstDayOfWeek(locale: string) { +function getFirstDayOfWeek (locale: string) { const weekInfo = getWeekInfo(locale); if (weekInfo) { // JS's Sunday == 7 while dotnet's Sunday == 0 @@ -139,7 +139,7 @@ function getFirstDayOfWeek(locale: string) { return 1; } -function getFirstWeekOfYear(locale: string) { +function getFirstWeekOfYear (locale: string) { const weekInfo = getWeekInfo(locale); if (weekInfo) { // enum CalendarWeekRule @@ -160,7 +160,7 @@ function getFirstWeekOfYear(locale: string) { return 0; } -function getWeekInfo(locale: string) { +function getWeekInfo (locale: string) { try { // most tools have it implemented as property return (new Intl.Locale(locale) as any).weekInfo; diff --git a/src/mono/browser/runtime/icu.ts b/src/mono/browser/runtime/icu.ts index 28aa01ad727cfd..16b23871f98718 100644 --- a/src/mono/browser/runtime/icu.ts +++ b/src/mono/browser/runtime/icu.ts @@ -6,6 +6,6 @@ import { VoidPtr } from "./types/emscripten"; // @offset must be the address of an ICU data archive in the native heap. // returns true on success. -export function mono_wasm_load_icu_data(offset: VoidPtr): boolean { +export function mono_wasm_load_icu_data (offset: VoidPtr): boolean { return (cwraps.mono_wasm_load_icu_data(offset)) === 1; } diff --git a/src/mono/browser/runtime/interp-pgo.ts b/src/mono/browser/runtime/interp-pgo.ts index c4214b4fe5d6a3..0a5a6e6c728534 100644 --- a/src/mono/browser/runtime/interp-pgo.ts +++ b/src/mono/browser/runtime/interp-pgo.ts @@ -11,7 +11,7 @@ import { MonoConfigInternal } from "./types/internal"; export const tablePrefix = "https://dotnet.generated.invalid/interp_pgo"; -export async function interp_pgo_save_data() { +export async function interp_pgo_save_data () { if (!loaderHelpers.is_runtime_running()) { mono_log_info("Skipped saving interp_pgo table (already exited)"); return; @@ -53,7 +53,7 @@ export async function interp_pgo_save_data() { } } -export async function interp_pgo_load_data() { +export async function interp_pgo_load_data () { const cacheKey = await getCacheKey(tablePrefix); if (!cacheKey) { mono_log_error("Failed to create cache key for interp_pgo table"); @@ -76,7 +76,7 @@ export async function interp_pgo_load_data() { Module._free(pData); } -async function openCache(): Promise { +async function openCache (): Promise { // 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 (ENVIRONMENT_IS_WEB && globalThis.window.isSecureContext === false) { @@ -113,7 +113,7 @@ async function openCache(): Promise { } } -export async function getCacheEntry(cacheKey: string): Promise { +export async function getCacheEntry (cacheKey: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -130,7 +130,7 @@ export async function getCacheEntry(cacheKey: string): Promise { +export async function storeCacheEntry (cacheKey: string, memory: ArrayBuffer, mimeType: string): Promise { try { const cache = await openCache(); if (!cache) { @@ -157,7 +157,7 @@ export async function storeCacheEntry(cacheKey: string, memory: ArrayBuffer, mim } } -export async function cleanupCache(prefix: string, protectKey: string) { +export async function cleanupCache (prefix: string, protectKey: string) { try { const cache = await openCache(); if (!cache) { @@ -175,7 +175,7 @@ export async function cleanupCache(prefix: string, protectKey: string) { } // calculate hash of things which affect config hash -export async function getCacheKey(prefix: string): Promise { +export async function getCacheKey (prefix: string): Promise { if (!runtimeHelpers.subtle) { return null; } diff --git a/src/mono/browser/runtime/invoke-cs.ts b/src/mono/browser/runtime/invoke-cs.ts index 7f2913cb86ec3d..f613df56687d4b 100644 --- a/src/mono/browser/runtime/invoke-cs.ts +++ b/src/mono/browser/runtime/invoke-cs.ts @@ -17,7 +17,7 @@ import { startMeasure, MeasuredBlock, endMeasure } from "./profiler"; import { bind_assembly_exports, invoke_async_jsexport, invoke_sync_jsexport } from "./managed-exports"; import { mono_log_debug } from "./logging"; -export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { +export function mono_wasm_bind_cs_function (method: MonoMethod, assemblyName: string, namespaceName: string, shortClassName: string, methodName: string, signatureHash: number, signature: JSFunctionSignature): void { const fullyQualifiedName = `[${assemblyName}] ${namespaceName}.${shortClassName}:${methodName}`; const mark = startMeasure(); mono_log_debug(`Binding [JSExport] ${namespaceName}.${shortClassName}:${methodName} from ${assemblyName} assembly`); @@ -108,11 +108,11 @@ export function mono_wasm_bind_cs_function(method: MonoMethod, assemblyName: str endMeasure(mark, MeasuredBlock.bindCsFunction, fullyQualifiedName); } -function bind_fn_0V(closure: BindingClosure) { +function bind_fn_0V (closure: BindingClosure) { const method = closure.method; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V() { + return function bound_fn_0V () { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -129,12 +129,12 @@ function bind_fn_0V(closure: BindingClosure) { }; } -function bind_fn_1V(closure: BindingClosure) { +function bind_fn_1V (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V(arg1: any) { + return function bound_fn_1V (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -153,13 +153,13 @@ function bind_fn_1V(closure: BindingClosure) { }; } -function bind_fn_1R(closure: BindingClosure) { +function bind_fn_1R (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R(arg1: any) { + return function bound_fn_1R (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -181,13 +181,13 @@ function bind_fn_1R(closure: BindingClosure) { }; } -function bind_fn_1RA(closure: BindingClosure) { +function bind_fn_1RA (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_1RA(arg1: any) { + return function bind_fn_1RA (arg1: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -214,14 +214,14 @@ function bind_fn_1RA(closure: BindingClosure) { }; } -function bind_fn_2R(closure: BindingClosure) { +function bind_fn_2R (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R(arg1: any, arg2: any) { + return function bound_fn_2R (arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -244,14 +244,14 @@ function bind_fn_2R(closure: BindingClosure) { }; } -function bind_fn_2RA(closure: BindingClosure) { +function bind_fn_2RA (closure: BindingClosure) { const method = closure.method; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fullyQualifiedName; if (!WasmEnableThreads) (closure) = null; - return function bind_fn_2RA(arg1: any, arg2: any) { + return function bind_fn_2RA (arg1: any, arg2: any) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -279,7 +279,7 @@ function bind_fn_2RA(closure: BindingClosure) { }; } -function bind_fn(closure: BindingClosure) { +function bind_fn (closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -288,7 +288,7 @@ function bind_fn(closure: BindingClosure) { const is_async = closure.is_async; const is_discard_no_wait = closure.is_discard_no_wait; if (!WasmEnableThreads) (closure) = null; - return function bound_fn(...js_args: any[]) { + return function bound_fn (...js_args: any[]) { const mark = startMeasure(); loaderHelpers.assert_runtime_running(); mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -343,7 +343,7 @@ type BindingClosure = { } export const exportsByAssembly: Map = new Map(); -function _walk_exports_to_set_function(assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { +function _walk_exports_to_set_function (assembly: string, namespace: string, classname: string, methodname: string, signature_hash: number, fn: Function): void { const parts = `${namespace}.${classname}`.replace(/\//g, ".").split("."); let scope: any = undefined; let assemblyScope = exportsByAssembly.get(assembly); @@ -372,7 +372,7 @@ function _walk_exports_to_set_function(assembly: string, namespace: string, clas scope[`${methodname}.${signature_hash}`] = fn; } -export async function mono_wasm_get_assembly_exports(assembly: string): Promise { +export async function mono_wasm_get_assembly_exports (assembly: string): Promise { assert_js_interop(); const result = exportsByAssembly.get(assembly); if (!result) { diff --git a/src/mono/browser/runtime/invoke-js.ts b/src/mono/browser/runtime/invoke-js.ts index 154bddbf4fc285..1274a162af7a73 100644 --- a/src/mono/browser/runtime/invoke-js.ts +++ b/src/mono/browser/runtime/invoke-js.ts @@ -22,7 +22,7 @@ import { monoThreadInfo } from "./pthreads"; export const js_import_wrapper_by_fn_handle: Function[] = [null];// 0th slot is dummy, main thread we free them on shutdown. On web worker thread we free them when worker is detached. -export function mono_wasm_bind_js_import(signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { +export function mono_wasm_bind_js_import (signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { if (WasmEnableThreads) return; assert_js_interop(); const resultRoot = mono_wasm_new_external_root(result_address); @@ -37,7 +37,7 @@ export function mono_wasm_bind_js_import(signature: JSFunctionSignature, is_exce } } -export function mono_wasm_invoke_jsimport_MT(signature: JSFunctionSignature, args: JSMarshalerArguments) { +export function mono_wasm_invoke_jsimport_MT (signature: JSFunctionSignature, args: JSMarshalerArguments) { if (!WasmEnableThreads) return; assert_js_interop(); @@ -53,7 +53,7 @@ export function mono_wasm_invoke_jsimport_MT(signature: JSFunctionSignature, arg bound_fn(args); } -export function mono_wasm_invoke_jsimport_ST(function_handle: JSFnHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_jsimport_ST (function_handle: JSFnHandle, args: JSMarshalerArguments): void { if (WasmEnableThreads) return; loaderHelpers.assert_runtime_running(); const bound_fn = js_import_wrapper_by_fn_handle[function_handle]; @@ -61,7 +61,7 @@ export function mono_wasm_invoke_jsimport_ST(function_handle: JSFnHandle, args: bound_fn(args); } -function bind_js_import(signature: JSFunctionSignature): Function { +function bind_js_import (signature: JSFunctionSignature): Function { assert_js_interop(); const mark = startMeasure(); @@ -131,11 +131,11 @@ function bind_js_import(signature: JSFunctionSignature): Function { } } - function async_bound_fn(args: JSMarshalerArguments): void { + function async_bound_fn (args: JSMarshalerArguments): void { forceThreadMemoryViewRefresh(); bound_fn(args); } - function sync_bound_fn(args: JSMarshalerArguments): void { + function sync_bound_fn (args: JSMarshalerArguments): void { const previous = runtimeHelpers.isPendingSynchronousCall; try { forceThreadMemoryViewRefresh(); @@ -146,10 +146,10 @@ function bind_js_import(signature: JSFunctionSignature): Function { runtimeHelpers.isPendingSynchronousCall = previous; } } - function async_bound_fn_ui(args: JSMarshalerArguments): void { + function async_bound_fn_ui (args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_async(() => async_bound_fn(args)); } - function sync_bound_fn_ui(args: JSMarshalerArguments): void { + function sync_bound_fn_ui (args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_sync(() => sync_bound_fn(args), args); } @@ -193,11 +193,11 @@ function bind_js_import(signature: JSFunctionSignature): Function { return wrapped_fn; } -function bind_fn_0V(closure: BindingClosure) { +function bind_fn_0V (closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_0V(args: JSMarshalerArguments) { + return function bound_fn_0V (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -211,12 +211,12 @@ function bind_fn_0V(closure: BindingClosure) { }; } -function bind_fn_1V(closure: BindingClosure) { +function bind_fn_1V (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1V(args: JSMarshalerArguments) { + return function bound_fn_1V (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -231,13 +231,13 @@ function bind_fn_1V(closure: BindingClosure) { }; } -function bind_fn_1R(closure: BindingClosure) { +function bind_fn_1R (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_1R(args: JSMarshalerArguments) { + return function bound_fn_1R (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -253,14 +253,14 @@ function bind_fn_1R(closure: BindingClosure) { }; } -function bind_fn_2R(closure: BindingClosure) { +function bind_fn_2R (closure: BindingClosure) { const fn = closure.fn; const marshaler1 = closure.arg_marshalers[0]!; const marshaler2 = closure.arg_marshalers[1]!; const res_converter = closure.res_converter!; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn_2R(args: JSMarshalerArguments) { + return function bound_fn_2R (args: JSMarshalerArguments) { const mark = startMeasure(); try { mono_assert(!WasmEnableThreads || !closure.isDisposed, "The function was already disposed"); @@ -277,7 +277,7 @@ function bind_fn_2R(closure: BindingClosure) { }; } -function bind_fn(closure: BindingClosure) { +function bind_fn (closure: BindingClosure) { const args_count = closure.args_count; const arg_marshalers = closure.arg_marshalers; const res_converter = closure.res_converter; @@ -286,7 +286,7 @@ function bind_fn(closure: BindingClosure) { const fn = closure.fn; const fqn = closure.fqn; if (!WasmEnableThreads) (closure) = null; - return function bound_fn(args: JSMarshalerArguments) { + return function bound_fn (args: JSMarshalerArguments) { const receiver_should_free = WasmEnableThreads && is_receiver_should_free(args); const mark = startMeasure(); try { @@ -339,23 +339,23 @@ type BindingClosure = { arg_cleanup: (Function | undefined)[] } -export function mono_wasm_invoke_js_function(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_js_function (bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { invoke_later_when_on_ui_thread_sync(() => mono_wasm_invoke_js_function_impl(bound_function_js_handle, args), args); } -export function mono_wasm_invoke_js_function_impl(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { +export function mono_wasm_invoke_js_function_impl (bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { loaderHelpers.assert_runtime_running(); const bound_fn = mono_wasm_get_jsobj_from_js_handle(bound_function_js_handle); mono_assert(bound_fn && typeof (bound_fn) === "function" && bound_fn[bound_js_function_symbol], () => `Bound function handle expected ${bound_function_js_handle}`); bound_fn(args); } -export function mono_wasm_set_module_imports(module_name: string, moduleImports: any) { +export function mono_wasm_set_module_imports (module_name: string, moduleImports: any) { importedModules.set(module_name, moduleImports); mono_log_debug(`added module imports '${module_name}'`); } -function mono_wasm_lookup_js_import(function_name: string, js_module_name: string | null): Function { +function mono_wasm_lookup_js_import (function_name: string, js_module_name: string | null): Function { mono_assert(function_name && typeof function_name === "string", "function_name must be string"); let scope: any = {}; @@ -391,34 +391,34 @@ function mono_wasm_lookup_js_import(function_name: string, js_module_name: strin return fn.bind(scope); } -export function set_property(self: any, name: string, value: any): void { +export function set_property (self: any, name: string, value: any): void { mono_check(self, "Null reference"); self[name] = value; } -export function get_property(self: any, name: string): any { +export function get_property (self: any, name: string): any { mono_check(self, "Null reference"); return self[name]; } -export function has_property(self: any, name: string): boolean { +export function has_property (self: any, name: string): boolean { mono_check(self, "Null reference"); return name in self; } -export function get_typeof_property(self: any, name: string): string { +export function get_typeof_property (self: any, name: string): string { mono_check(self, "Null reference"); return typeof self[name]; } -export function get_global_this(): any { +export function get_global_this (): any { return globalThis; } export const importedModulesPromises: Map> = new Map(); export const importedModules: Map> = new Map(); -export function dynamic_import(module_name: string, module_url: string): Promise { +export function dynamic_import (module_name: string, module_url: string): Promise { assert_js_interop(); mono_assert(module_name && typeof module_name === "string", "module_name must be string"); mono_assert(module_url && typeof module_url === "string", "module_url must be string"); @@ -430,7 +430,7 @@ export function dynamic_import(module_name: string, module_url: string): Promise importedModulesPromises.set(module_name, promise); } - return wrap_as_cancelable_promise(async() => { + return wrap_as_cancelable_promise(async () => { const module = await promise; if (newPromise) { importedModules.set(module_name, module); @@ -440,7 +440,7 @@ export function dynamic_import(module_name: string, module_url: string): Promise }); } -function _wrap_error_flag(is_exception: Int32Ptr | null, ex: any): string { +function _wrap_error_flag (is_exception: Int32Ptr | null, ex: any): string { let res = "unknown exception"; if (ex) { res = ex.toString(); @@ -463,7 +463,7 @@ function _wrap_error_flag(is_exception: Int32Ptr | null, ex: any): string { return res; } -export function wrap_error_root(is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { +export function wrap_error_root (is_exception: Int32Ptr | null, ex: any, result: WasmRoot): void { const res = _wrap_error_flag(is_exception, ex); stringToMonoStringRoot(res, result); } @@ -471,7 +471,7 @@ export function wrap_error_root(is_exception: Int32Ptr | null, ex: any, result: // to set out parameters of icalls // TODO replace it with replace it with UTF8 char*, no GC root needed // https://github.com/dotnet/runtime/issues/98365 -export function wrap_no_error_root(is_exception: Int32Ptr | null, result?: WasmRoot): void { +export function wrap_no_error_root (is_exception: Int32Ptr | null, result?: WasmRoot): void { if (is_exception) { receiveWorkerHeapViews(); setI32_unchecked(is_exception, 0); @@ -481,7 +481,7 @@ export function wrap_no_error_root(is_exception: Int32Ptr | null, result?: WasmR } } -export function assert_js_interop(): void { +export function assert_js_interop (): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready && runtimeHelpers.proxyGCHandle, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -490,7 +490,7 @@ export function assert_js_interop(): void { } } -export function assert_c_interop(): void { +export function assert_c_interop (): void { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "Please use dedicated worker for working with JavaScript interop. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -502,7 +502,7 @@ export function assert_c_interop(): void { // make sure we are not blocking em_task_queue_execute up the call stack // so that when we call back to managed, the FS calls could still be processed by the UI thread // see also emscripten_yield which can process the FS calls inside the spin wait -export function invoke_later_when_on_ui_thread_sync(fn: Function, args: JSMarshalerArguments) { +export function invoke_later_when_on_ui_thread_sync (fn: Function, args: JSMarshalerArguments) { if (WasmEnableThreads && monoThreadInfo.isUI) { Module.safeSetTimeout(() => { fn(); @@ -517,7 +517,7 @@ export function invoke_later_when_on_ui_thread_sync(fn: Function, args: JSMarsha // make sure we are not blocking em_task_queue_execute up the call stack // so that when we call back to managed, the FS calls could still be processed by the UI thread -export function invoke_later_when_on_ui_thread_async(fn: Function) { +export function invoke_later_when_on_ui_thread_async (fn: Function) { if (WasmEnableThreads && monoThreadInfo.isUI) { Module.safeSetTimeout(fn, 0); } else { diff --git a/src/mono/browser/runtime/jiterpreter-interp-entry.ts b/src/mono/browser/runtime/jiterpreter-interp-entry.ts index cedf54cdde9306..b99917dd2bb0c8 100644 --- a/src/mono/browser/runtime/jiterpreter-interp-entry.ts +++ b/src/mono/browser/runtime/jiterpreter-interp-entry.ts @@ -68,7 +68,7 @@ const enum WasmReftype { } */ -function getTrampImports() { +function getTrampImports () { if (trampImports) return trampImports; @@ -98,7 +98,7 @@ class TrampolineInfo { result: number; hitCount: number; - constructor( + constructor ( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: string, defaultImplementation: number @@ -137,12 +137,12 @@ let mostRecentOptions: JiterpreterOptions | undefined = undefined; // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_interp_entry(imethod: number) { +export function mono_jiterp_free_method_data_interp_entry (imethod: number) { delete infoTable[imethod]; } // FIXME: move this counter into C and make it thread safe -export function mono_interp_record_interp_entry(imethod: number) { +export function mono_interp_record_interp_entry (imethod: number) { // clear the unbox bit imethod = imethod & ~0x1; @@ -168,7 +168,7 @@ export function mono_interp_record_interp_entry(imethod: number) { } // returns function pointer -export function mono_interp_jit_wasm_entry_trampoline( +export function mono_interp_jit_wasm_entry_trampoline ( imethod: number, method: MonoMethod, argumentCount: number, pParamTypes: NativePointer, unbox: boolean, hasThisReference: boolean, hasReturnValue: boolean, name: NativePointer, defaultImplementation: number @@ -208,7 +208,7 @@ export function mono_interp_jit_wasm_entry_trampoline( return info.result; } -function ensure_jit_is_scheduled() { +function ensure_jit_is_scheduled () { if (jitQueueTimeout > 0) return; @@ -227,7 +227,7 @@ function ensure_jit_is_scheduled() { }, queueFlushDelayMs); } -function flush_wasm_entry_trampoline_jit_queue() { +function flush_wasm_entry_trampoline_jit_queue () { const jitQueue : TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.InterpEntry)) != 0) { @@ -447,7 +447,7 @@ function flush_wasm_entry_trampoline_jit_queue() { } } -function append_stackval_from_data( +function append_stackval_from_data ( builder: WasmBuilder, imethod: number, type: MonoType, valueName: string, argIndex: number ) { const rawSize = cwraps.mono_jiterp_type_get_raw_value_size(type); @@ -520,7 +520,7 @@ function append_stackval_from_data( } } -function generate_wasm_body( +function generate_wasm_body ( builder: WasmBuilder, info: TrampolineInfo ): boolean { // FIXME: This is not thread-safe, but the alternative of alloca makes the trampoline diff --git a/src/mono/browser/runtime/jiterpreter-jit-call.ts b/src/mono/browser/runtime/jiterpreter-jit-call.ts index 09018413e24e75..f8da716a593467 100644 --- a/src/mono/browser/runtime/jiterpreter-jit-call.ts +++ b/src/mono/browser/runtime/jiterpreter-jit-call.ts @@ -95,7 +95,7 @@ class TrampolineInfo { wasmNativeSignature: WasmValtype[]; enableDirect: boolean; - constructor( + constructor ( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: boolean ) { @@ -166,7 +166,7 @@ class TrampolineInfo { // this is cached replacements for Module.getWasmTableEntry(); // we could add and // if we need to export the original -function getWasmTableEntry(index: number) { +function getWasmTableEntry (index: number) { let result = fnCache[index]; if (!result) { if (index >= fnCache.length) @@ -179,7 +179,7 @@ function getWasmTableEntry(index: number) { return result; } -export function mono_interp_invoke_wasm_jit_call_trampoline( +export function mono_interp_invoke_wasm_jit_call_trampoline ( thunkIndex: number, ret_sp: number, sp: number, ftndesc: number, thrown: NativePointer ) { const thunk = getWasmTableEntry(thunkIndex); @@ -218,7 +218,7 @@ export function mono_interp_invoke_wasm_jit_call_trampoline( // If a method is freed we need to remove its info (just in case another one gets // allocated at that exact memory offset later) and more importantly, ensure it is // not waiting in the jit queue -export function mono_jiterp_free_method_data_jit_call(method: MonoMethod) { +export function mono_jiterp_free_method_data_jit_call (method: MonoMethod) { // FIXME const infoArray = infosByMethod[method]; if (!infoArray) @@ -230,7 +230,7 @@ export function mono_jiterp_free_method_data_jit_call(method: MonoMethod) { delete infosByMethod[method]; } -export function mono_interp_jit_wasm_jit_call_trampoline( +export function mono_interp_jit_wasm_jit_call_trampoline ( method: MonoMethod, rmethod: VoidPtr, cinfo: VoidPtr, arg_offsets: VoidPtr, catch_exceptions: number ): void { @@ -276,7 +276,7 @@ export function mono_interp_jit_wasm_jit_call_trampoline( mono_interp_flush_jitcall_queue(); } -function getIsWasmEhSupported(): boolean { +function getIsWasmEhSupported (): boolean { if (wasmEhSupported !== undefined) return wasmEhSupported; @@ -288,7 +288,7 @@ function getIsWasmEhSupported(): boolean { return wasmEhSupported; } -export function mono_interp_flush_jitcall_queue(): void { +export function mono_interp_flush_jitcall_queue (): void { const jitQueue: TrampolineInfo[] = []; let methodPtr = 0; while ((methodPtr = cwraps.mono_jiterp_tlqueue_next(JitQueue.JitCall)) != 0) { @@ -624,19 +624,19 @@ const wasmOpcodeFromCilOpcode = { [CilOpcodes.STIND_I]: WasmOpcode.i32_store, }; -function append_ldloc(builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { +function append_ldloc (builder: WasmBuilder, offsetBytes: number, opcode: WasmOpcode) { builder.local("sp"); builder.appendU8(opcode); builder.appendMemarg(offsetBytes, 0); } -function append_ldloca(builder: WasmBuilder, offsetBytes: number) { +function append_ldloca (builder: WasmBuilder, offsetBytes: number) { builder.local("sp"); builder.i32_const(offsetBytes); builder.appendU8(WasmOpcode.i32_add); } -function generate_wasm_body( +function generate_wasm_body ( builder: WasmBuilder, info: TrampolineInfo ): boolean { let stack_index = 0; diff --git a/src/mono/browser/runtime/jiterpreter-support.ts b/src/mono/browser/runtime/jiterpreter-support.ts index 7c7c35ebfac510..e71c3700e09d88 100644 --- a/src/mono/browser/runtime/jiterpreter-support.ts +++ b/src/mono/browser/runtime/jiterpreter-support.ts @@ -109,14 +109,14 @@ export class WasmBuilder { compressImportNames = false; lockImports = false; - constructor(constantSlotCount: number) { + constructor (constantSlotCount: number) { this.stack = [new BlobBuilder()]; this.clear(constantSlotCount); this.cfg = new Cfg(this); this.defineType("__cpp_exception", { "ptr": WasmValtype.i32 }, WasmValtype.void, true); } - clear(constantSlotCount: number) { + clear (constantSlotCount: number) { this.options = getOptions(); this.stackSize = 1; this.inSection = false; @@ -156,14 +156,14 @@ export class WasmBuilder { this.allowNullCheckOptimization = this.options.eliminateNullChecks; } - _push() { + _push () { this.stackSize++; if (this.stackSize >= this.stack.length) this.stack.push(new BlobBuilder()); this.current.clear(); } - _pop(writeToOutput: boolean) { + _pop (writeToOutput: boolean) { if (this.stackSize <= 1) throw new Error("Stack empty"); @@ -178,21 +178,21 @@ export class WasmBuilder { return current.getArrayView(false).slice(0, current.size); } - setImportFunction(name: string, value: Function) { + setImportFunction (name: string, value: Function) { const imp = this.importedFunctions[name]; if (!imp) throw new Error("No import named " + name); imp.func = value; } - getExceptionTag(): any { + getExceptionTag (): any { const exceptionTag = (Module)["asm"]["__cpp_exception"]; if (typeof (exceptionTag) !== "undefined") mono_assert(exceptionTag instanceof (WebAssembly).Tag, () => `expected __cpp_exception export from dotnet.wasm to be WebAssembly.Tag but was ${exceptionTag}`); return exceptionTag; } - getWasmImports(): WebAssembly.Imports { + getWasmImports (): WebAssembly.Imports { const memory = runtimeHelpers.getMemory(); mono_assert(memory instanceof WebAssembly.Memory, () => `expected heap import to be WebAssembly.Memory but was ${memory}`); @@ -225,7 +225,7 @@ export class WasmBuilder { // HACK: Approximate amount of space we need to generate the full module at present // FIXME: This does not take into account any other functions already generated if they weren't // emitted into the module immediately - get bytesGeneratedSoFar() { + get bytesGeneratedSoFar () { const importSize = this.compressImportNames // mod (2 bytes) name (2-3 bytes) type (1 byte) typeidx (1-2 bytes) ? 8 @@ -242,74 +242,74 @@ export class WasmBuilder { this.estimatedExportBytes; } - get current() { + get current () { return this.stack[this.stackSize - 1]; } - get size() { + get size () { return this.current.size; } - appendU8(value: number | WasmOpcode) { + appendU8 (value: number | WasmOpcode) { if ((value != value >>> 0) || (value > 255)) throw new Error(`Byte out of range: ${value}`); return this.current.appendU8(value); } - appendSimd(value: WasmSimdOpcode, allowLoad?: boolean) { + appendSimd (value: WasmSimdOpcode, allowLoad?: boolean) { this.current.appendU8(WasmOpcode.PREFIX_simd); // Yes that's right. We're using LEB128 to encode 8-bit opcodes. Why? I don't know mono_assert(((value | 0) !== 0) || ((value === WasmSimdOpcode.v128_load) && (allowLoad === true)), "Expected non-v128_load simd opcode or allowLoad==true"); return this.current.appendULeb(value); } - appendU32(value: number) { + appendU32 (value: number) { return this.current.appendU32(value); } - appendF32(value: number) { + appendF32 (value: number) { return this.current.appendF32(value); } - appendF64(value: number) { + appendF64 (value: number) { return this.current.appendF64(value); } - appendBoundaryValue(bits: number, sign: number) { + appendBoundaryValue (bits: number, sign: number) { return this.current.appendBoundaryValue(bits, sign); } - appendULeb(value: number | MintOpcodePtr) { + appendULeb (value: number | MintOpcodePtr) { return this.current.appendULeb(value); } - appendLeb(value: number) { + appendLeb (value: number) { return this.current.appendLeb(value); } - appendLebRef(sourceAddress: VoidPtr, signed: boolean) { + appendLebRef (sourceAddress: VoidPtr, signed: boolean) { return this.current.appendLebRef(sourceAddress, signed); } - appendBytes(bytes: Uint8Array) { + appendBytes (bytes: Uint8Array) { return this.current.appendBytes(bytes); } - appendName(text: string) { + appendName (text: string) { return this.current.appendName(text); } - ret(ip: MintOpcodePtr) { + ret (ip: MintOpcodePtr) { this.ip_const(ip); this.appendU8(WasmOpcode.return_); } - i32_const(value: number | ManagedPointer | NativePointer) { + i32_const (value: number | ManagedPointer | NativePointer) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value); } - ptr_const(pointer: number | ManagedPointer | NativePointer) { + ptr_const (pointer: number | ManagedPointer | NativePointer) { let idx = this.options.useConstants ? this.constantSlots.indexOf(pointer) : -1; if ( this.options.useConstants && @@ -328,17 +328,17 @@ export class WasmBuilder { } } - ip_const(value: MintOpcodePtr) { + ip_const (value: MintOpcodePtr) { this.appendU8(WasmOpcode.i32_const); this.appendLeb(value - this.base); } - i52_const(value: number) { + i52_const (value: number) { this.appendU8(WasmOpcode.i64_const); this.appendLeb(value); } - v128_const(value: 0 | Uint8Array) { + v128_const (value: 0 | Uint8Array) { if (value === 0) { // This encoding is much smaller than a v128_const // But v8 doesn't optimize it :-(((((( @@ -367,7 +367,7 @@ export class WasmBuilder { } } - defineType( + defineType ( name: string, parameters: { [name: string]: WasmValtype }, returnType: WasmValtype, permanent: boolean ) { @@ -416,7 +416,7 @@ export class WasmBuilder { return index; } - generateTypeSection() { + generateTypeSection () { this.beginSection(1); this.appendULeb(this.functionTypeCount); /* @@ -442,7 +442,7 @@ export class WasmBuilder { this.endSection(); } - getImportedFunctionTable(): any { + getImportedFunctionTable (): any { const imports: any = {}; for (const k in this.importedFunctions) { const f = this.importedFunctions[k]; @@ -452,7 +452,7 @@ export class WasmBuilder { return imports; } - getCompressedName(ifi: ImportedFunctionInfo) { + getCompressedName (ifi: ImportedFunctionInfo) { if (!this.compressImportNames || typeof (ifi.index) !== "number") return ifi.name; @@ -462,7 +462,7 @@ export class WasmBuilder { return result; } - getImportsToEmit() { + getImportsToEmit () { const result = []; for (const k in this.importedFunctions) { const v = this.importedFunctions[k]; @@ -475,7 +475,7 @@ export class WasmBuilder { return result; } - _generateImportSection(includeFunctionTable?: boolean) { + _generateImportSection (includeFunctionTable?: boolean) { const importsToEmit = this.getImportsToEmit(); this.lockImports = true; @@ -554,7 +554,7 @@ export class WasmBuilder { } } - defineImportedFunction( + defineImportedFunction ( module: string, name: string, functionTypeName: string, permanent: boolean, func?: Function | number ): ImportedFunctionInfo { @@ -583,7 +583,7 @@ export class WasmBuilder { return result; } - markImportAsUsed(name: string) { + markImportAsUsed (name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -591,14 +591,14 @@ export class WasmBuilder { func.index = this.importedFunctionCount++; } - getTypeIndex(name: string) { + getTypeIndex (name: string) { const type = this.functionTypes[name]; if (!type) throw new Error("No type named " + name); return type[0]; } - defineFunction( + defineFunction ( options: { type: string, name: string, @@ -623,7 +623,7 @@ export class WasmBuilder { return rec; } - emitImportsAndFunctions(includeFunctionTable?: boolean) { + emitImportsAndFunctions (includeFunctionTable?: boolean) { let exportCount = 0; for (let i = 0; i < this.functions.length; i++) { const func = this.functions[i]; @@ -682,7 +682,7 @@ export class WasmBuilder { this.endSection(); } - call_indirect(/* functionTypeName: string, tableIndex: number */) { + call_indirect (/* functionTypeName: string, tableIndex: number */) { throw new Error("call_indirect unavailable"); /* const type = this.functionTypes[functionTypeName]; @@ -695,7 +695,7 @@ export class WasmBuilder { */ } - callImport(name: string) { + callImport (name: string) { const func = this.importedFunctions[name]; if (!func) throw new Error("No imported function named " + name); @@ -708,7 +708,7 @@ export class WasmBuilder { this.appendULeb(func.index); } - beginSection(type: number) { + beginSection (type: number) { if (this.inSection) this._pop(true); this.appendU8(type); @@ -716,7 +716,7 @@ export class WasmBuilder { this.inSection = true; } - endSection() { + endSection () { if (!this.inSection) throw new Error("Not in section"); if (this.inFunction) @@ -735,7 +735,7 @@ export class WasmBuilder { return result; }; - _assignLocalIndices( + _assignLocalIndices ( counts: any, locals: { [name: string]: WasmValtype }, base: number, localGroupCount: number ) { @@ -794,7 +794,7 @@ export class WasmBuilder { return localGroupCount; } - beginFunction( + beginFunction ( type: string, locals?: { [name: string]: WasmValtype } ) { @@ -838,7 +838,7 @@ export class WasmBuilder { this.inFunction = true; } - endFunction(writeToOutput: boolean) { + endFunction (writeToOutput: boolean) { if (!this.inFunction) throw new Error("Not in function"); if (this.activeBlocks > 0) @@ -848,7 +848,7 @@ export class WasmBuilder { return result; } - block(type?: WasmValtype, opcode?: WasmOpcode) { + block (type?: WasmValtype, opcode?: WasmOpcode) { const result = this.appendU8(opcode || WasmOpcode.block); if (type) this.appendU8(type); @@ -858,14 +858,14 @@ export class WasmBuilder { return result; } - endBlock() { + endBlock () { if (this.activeBlocks <= 0) throw new Error("No blocks active"); this.activeBlocks--; this.appendU8(WasmOpcode.end); } - arg(name: string | number, opcode?: WasmOpcode) { + arg (name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name; @@ -876,7 +876,7 @@ export class WasmBuilder { this.appendULeb(index); } - local(name: string | number, opcode?: WasmOpcode) { + local (name: string | number, opcode?: WasmOpcode) { const index = typeof (name) === "string" ? (this.locals.has(name) ? this.locals.get(name)! : undefined) : name + this.argumentCount; @@ -889,7 +889,7 @@ export class WasmBuilder { this.appendULeb(index); } - appendMemarg(offset: number, alignPower: number) { + appendMemarg (offset: number, alignPower: number) { this.appendULeb(alignPower); this.appendULeb(offset); } @@ -897,7 +897,7 @@ export class WasmBuilder { /* generates either (u32)get_local(ptr) + offset or (u32)ptr1 + offset */ - lea(ptr1: string | number, offset: number) { + lea (ptr1: string | number, offset: number) { if (typeof (ptr1) === "string") this.local(ptr1); else @@ -908,13 +908,13 @@ export class WasmBuilder { this.appendU8(WasmOpcode.i32_add); } - getArrayView(fullCapacity?: boolean) { + getArrayView (fullCapacity?: boolean) { if (this.stackSize > 1) throw new Error("Jiterpreter block stack not empty"); return this.stack[0].getArrayView(fullCapacity); } - getConstants() { + getConstants () { const result: { [key: string]: number } = {}; for (let i = 0; i < this.constantSlots.length; i++) result[i.toString(shortNameBase)] = this.constantSlots[i]; @@ -929,7 +929,7 @@ export class BlobBuilder { encoder?: TextEncoder; textBuf = new Uint8Array(1024); - constructor() { + constructor () { this.capacity = 16 * 1024; this.buffer = Module._malloc(this.capacity); localHeapViewU8().fill(0, this.buffer, this.buffer + this.capacity); @@ -939,11 +939,11 @@ export class BlobBuilder { this.encoder = new TextEncoder(); } - clear() { + clear () { this.size = 0; } - appendU8(value: number | WasmOpcode) { + appendU8 (value: number | WasmOpcode) { if (this.size >= this.capacity) throw new Error("Buffer full"); @@ -952,35 +952,35 @@ export class BlobBuilder { return result; } - appendU32(value: number) { + appendU32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.U32); this.size += 4; return result; } - appendI32(value: number) { + appendI32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.I32); this.size += 4; return result; } - appendF32(value: number) { + appendF32 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F32); this.size += 4; return result; } - appendF64(value: number) { + appendF64 (value: number) { const result = this.size; cwraps.mono_jiterp_write_number_unaligned(this.buffer + this.size, value, JiterpNumberMode.F64); this.size += 8; return result; } - appendBoundaryValue(bits: number, sign: number) { + appendBoundaryValue (bits: number, sign: number) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -991,7 +991,7 @@ export class BlobBuilder { return bytesWritten; } - appendULeb(value: number) { + appendULeb (value: number) { mono_assert(typeof (value) === "number", () => `appendULeb expected number but got ${value}`); mono_assert(value >= 0, "cannot pass negative value to appendULeb"); if (value < 0x7F) { @@ -1012,7 +1012,7 @@ export class BlobBuilder { return bytesWritten; } - appendLeb(value: number) { + appendLeb (value: number) { mono_assert(typeof (value) === "number", () => `appendLeb expected number but got ${value}`); if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1024,7 +1024,7 @@ export class BlobBuilder { return bytesWritten; } - appendLebRef(sourceAddress: VoidPtr, signed: boolean) { + appendLebRef (sourceAddress: VoidPtr, signed: boolean) { if (this.size + 8 >= this.capacity) throw new Error("Buffer full"); @@ -1035,7 +1035,7 @@ export class BlobBuilder { return bytesWritten; } - copyTo(destination: BlobBuilder, count?: number) { + copyTo (destination: BlobBuilder, count?: number) { if (typeof (count) !== "number") count = this.size; @@ -1043,7 +1043,7 @@ export class BlobBuilder { destination.size += count; } - appendBytes(bytes: Uint8Array, count?: number) { + appendBytes (bytes: Uint8Array, count?: number) { const result = this.size; const heapU8 = localHeapViewU8(); if (bytes.buffer === heapU8.buffer) { @@ -1063,7 +1063,7 @@ export class BlobBuilder { return result; } - appendName(text: string) { + appendName (text: string) { let count = text.length; // TextEncoder overhead is significant for short strings, and lots of our strings // are single-character import names, so add a fast path for single characters @@ -1098,7 +1098,7 @@ export class BlobBuilder { this.appendBytes(this.textBuf, count); } - getArrayView(fullCapacity?: boolean) { + getArrayView (fullCapacity?: boolean) { return new Uint8Array(localHeapViewU8().buffer, this.buffer, fullCapacity ? this.capacity : this.size); } } @@ -1155,11 +1155,11 @@ class Cfg { observedBackBranchTargets = new Set(); trace = 0; - constructor(builder: WasmBuilder) { + constructor (builder: WasmBuilder) { this.builder = builder; } - initialize(startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { + initialize (startOfBody: MintOpcodePtr, backBranchTargets: Uint16Array | null, trace: number) { this.segments.length = 0; this.blockStack.length = 0; this.startOfBody = startOfBody; @@ -1175,7 +1175,7 @@ class Cfg { } // We have a header containing the table of locals and we need to preserve it - entry(ip: MintOpcodePtr) { + entry (ip: MintOpcodePtr) { this.entryIp = ip; // Skip over the enter opcode const enterSizeU16 = cwraps.mono_jiterp_get_opcode_info(MintOpcode.MINT_TIER_ENTER_JITERPRETER, OpcodeInfoType.Length); @@ -1193,7 +1193,7 @@ class Cfg { return this.firstOpcodeIp; } - appendBlob() { + appendBlob () { if (this.builder.current.size === this.lastSegmentEnd) return; @@ -1209,7 +1209,7 @@ class Cfg { this.overheadBytes += 2; } - startBranchBlock(ip: MintOpcodePtr, isBackBranchTarget: boolean) { + startBranchBlock (ip: MintOpcodePtr, isBackBranchTarget: boolean) { this.appendBlob(); this.segments.push({ type: "branch-block-header", @@ -1219,7 +1219,7 @@ class Cfg { this.overheadBytes += 1; // each branch block just costs us an end } - branch(target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { + branch (target: MintOpcodePtr, isBackward: boolean, branchType: CfgBranchType) { if (isBackward) this.observedBackBranchTargets.add(target); @@ -1252,13 +1252,13 @@ class Cfg { } } - emitBlob(segment: CfgBlob, source: Uint8Array) { + emitBlob (segment: CfgBlob, source: Uint8Array) { // mono_log_info(`segment @${(segment.ip).toString(16)} ${segment.start}-${segment.start + segment.length}`); const view = source.subarray(segment.start, segment.start + segment.length); this.builder.appendBytes(view); } - generate(): Uint8Array { + generate (): Uint8Array { // HACK: Make sure any remaining bytes are inserted into a trailing segment this.appendBlob(); @@ -1517,7 +1517,7 @@ export const _now = (globalThis.performance && globalThis.performance.now) let scratchBuffer: NativePointer = 0; -export function append_safepoint(builder: WasmBuilder, ip: MintOpcodePtr) { +export function append_safepoint (builder: WasmBuilder, ip: MintOpcodePtr) { // safepoints are never triggered in a single-threaded build if (!WasmEnableThreads) return; @@ -1534,7 +1534,7 @@ export function append_safepoint(builder: WasmBuilder, ip: MintOpcodePtr) { builder.endBlock(); } -export function append_bailout(builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { +export function append_bailout (builder: WasmBuilder, ip: MintOpcodePtr, reason: BailoutReason) { builder.ip_const(ip); if (builder.options.countBailouts) { builder.i32_const(builder.traceIndex); @@ -1545,7 +1545,7 @@ export function append_bailout(builder: WasmBuilder, ip: MintOpcodePtr, reason: } // generate a bailout that is recorded for the monitoring phase as a possible early exit. -export function append_exit(builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { +export function append_exit (builder: WasmBuilder, ip: MintOpcodePtr, opcodeCounter: number, reason: BailoutReason) { /* * disp will always be nonzero once we've taken at least one backward branch. * if (cinfo) { @@ -1581,7 +1581,7 @@ export function append_exit(builder: WasmBuilder, ip: MintOpcodePtr, opcodeCount builder.appendU8(WasmOpcode.return_); } -export function copyIntoScratchBuffer(src: NativePointer, size: number): NativePointer { +export function copyIntoScratchBuffer (src: NativePointer, size: number): NativePointer { if (!scratchBuffer) scratchBuffer = Module._malloc(64); if (size > 64) @@ -1591,7 +1591,7 @@ export function copyIntoScratchBuffer(src: NativePointer, size: number): NativeP return scratchBuffer; } -export function getWasmFunctionTable() { +export function getWasmFunctionTable () { if (!wasmTable) wasmTable = runtimeHelpers.getWasmIndirectFunctionTable(); if (!wasmTable) @@ -1599,7 +1599,7 @@ export function getWasmFunctionTable() { return wasmTable; } -export function addWasmFunctionPointer(table: JiterpreterTable, f: Function) { +export function addWasmFunctionPointer (table: JiterpreterTable, f: Function) { mono_assert(f, "Attempting to set null function into table"); const index = cwraps.mono_jiterp_allocate_table_entry(table); @@ -1613,7 +1613,7 @@ export function addWasmFunctionPointer(table: JiterpreterTable, f: Function) { return index; } -export function try_append_memset_fast(builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { +export function try_append_memset_fast (builder: WasmBuilder, localOffset: number, value: number, count: number, destOnStack: boolean) { if (count <= 0) { if (destOnStack) builder.appendU8(WasmOpcode.drop); @@ -1684,7 +1684,7 @@ export function try_append_memset_fast(builder: WasmBuilder, localOffset: number return true; } -export function append_memset_dest(builder: WasmBuilder, value: number, count: number) { +export function append_memset_dest (builder: WasmBuilder, value: number, count: number) { // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val if (try_append_memset_fast(builder, 0, value, count, true)) return; @@ -1696,7 +1696,7 @@ export function append_memset_dest(builder: WasmBuilder, value: number, count: n builder.appendU8(0); } -export function try_append_memmove_fast( +export function try_append_memmove_fast ( builder: WasmBuilder, destLocalOffset: number, srcLocalOffset: number, count: number, addressesOnStack: boolean, destLocal?: string, srcLocal?: string ) { @@ -1796,7 +1796,7 @@ export function try_append_memmove_fast( } // expects dest then source to have been pushed onto wasm stack -export function append_memmove_dest_src(builder: WasmBuilder, count: number) { +export function append_memmove_dest_src (builder: WasmBuilder, count: number) { if (try_append_memmove_fast(builder, 0, 0, count, true)) return true; @@ -1810,7 +1810,7 @@ export function append_memmove_dest_src(builder: WasmBuilder, count: number) { return true; } -export function recordFailure(): void { +export function recordFailure (): void { const result = modifyCounter(JiterpCounter.Failures, 1); if (result >= maxFailures) { mono_log_info(`Disabling jiterpreter after ${result} failures`); @@ -1824,7 +1824,7 @@ export function recordFailure(): void { const memberOffsets: { [index: number]: number } = {}; -export function getMemberOffset(member: JiterpMember) { +export function getMemberOffset (member: JiterpMember) { const cached = memberOffsets[member]; if (cached === undefined) return memberOffsets[member] = cwraps.mono_jiterp_get_member_offset(member); @@ -1832,7 +1832,7 @@ export function getMemberOffset(member: JiterpMember) { return cached; } -export function getRawCwrap(name: string): Function { +export function getRawCwrap (name: string): Function { const result = (Module)["asm"][name]; if (typeof (result) !== "function") throw new Error(`raw cwrap ${name} not found`); @@ -1841,18 +1841,18 @@ export function getRawCwrap(name: string): Function { const opcodeTableCache: { [opcode: number]: number } = {}; -export function getOpcodeTableValue(opcode: MintOpcode) { +export function getOpcodeTableValue (opcode: MintOpcode) { let result = opcodeTableCache[opcode]; if (typeof (result) !== "number") result = opcodeTableCache[opcode] = cwraps.mono_jiterp_get_opcode_value_table_entry(opcode); return result; } -export function importDef(name: string, fn: Function): [string, string, Function] { +export function importDef (name: string, fn: Function): [string, string, Function] { return [name, name, fn]; } -export function bytesFromHex(hex: string): Uint8Array { +export function bytesFromHex (hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16); @@ -1861,7 +1861,7 @@ export function bytesFromHex(hex: string): Uint8Array { let observedTaintedZeroPage: boolean | undefined; -export function isZeroPageReserved(): boolean { +export function isZeroPageReserved (): boolean { // FIXME: This check will always return true on worker threads. // Right now the jiterpreter is disabled when threading is active, so that's not an issue. if (WasmEnableThreads) @@ -1978,7 +1978,7 @@ let optionsVersion = -1; let optionTable: JiterpreterOptions = {}; // applies one or more jiterpreter options to change the current jiterpreter configuration. -export function applyOptions(options: JiterpreterOptions) { +export function applyOptions (options: JiterpreterOptions) { for (const k in options) { const info = optionNames[k]; if (!info) { @@ -1996,16 +1996,16 @@ export function applyOptions(options: JiterpreterOptions) { } } -export function getCounter(counter: JiterpCounter): number { +export function getCounter (counter: JiterpCounter): number { return cwraps.mono_jiterp_get_counter(counter); } -export function modifyCounter(counter: JiterpCounter, delta: number): number { +export function modifyCounter (counter: JiterpCounter, delta: number): number { return cwraps.mono_jiterp_modify_counter(counter, delta); } // returns the current jiterpreter configuration. do not mutate the return value! -export function getOptions() { +export function getOptions () { const currentVersion = cwraps.mono_jiterp_get_options_version(); if (currentVersion !== optionsVersion) { updateOptions(); @@ -2014,7 +2014,7 @@ export function getOptions() { return optionTable; } -function updateOptions() { +function updateOptions () { const pJson = cwraps.mono_jiterp_get_options_as_json(); const json = utf8ToString(pJson); Module._free(pJson); @@ -2027,7 +2027,7 @@ function updateOptions() { } } -function jiterpreter_allocate_table(type: JiterpreterTable, base: number, size: number, fillValue: Function) { +function jiterpreter_allocate_table (type: JiterpreterTable, base: number, size: number, fillValue: Function) { const wasmTable = getWasmFunctionTable(); const firstIndex = base, lastIndex = firstIndex + size - 1; mono_assert(lastIndex < wasmTable.length, () => `Last index out of range: ${lastIndex} >= ${wasmTable.length}`); @@ -2051,7 +2051,7 @@ function jiterpreter_allocate_table(type: JiterpreterTable, base: number, size: // we need to ensure we only ever initialize tables once on each js worker. let jiterpreter_tables_allocated = false; -export function jiterpreter_allocate_tables() { +export function jiterpreter_allocate_tables () { if (jiterpreter_tables_allocated) return; jiterpreter_tables_allocated = true; diff --git a/src/mono/browser/runtime/jiterpreter-trace-generator.ts b/src/mono/browser/runtime/jiterpreter-trace-generator.ts index ffb24bddcb1e6d..3e9fba479e1b72 100644 --- a/src/mono/browser/runtime/jiterpreter-trace-generator.ts +++ b/src/mono/browser/runtime/jiterpreter-trace-generator.ts @@ -59,50 +59,50 @@ import { mono_log_error, mono_log_info } from "./logging"; import { mono_assert, runtimeHelpers } from "./globals"; // indexPlusOne so that ip[1] in the interpreter becomes getArgU16(ip, 1) -function getArgU16(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgU16 (ip: MintOpcodePtr, indexPlusOne: number) { return getU16(ip + (2 * indexPlusOne)); } -function getArgI16(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI16 (ip: MintOpcodePtr, indexPlusOne: number) { return getI16(ip + (2 * indexPlusOne)); } -function getArgI32(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgI32 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getI32_unaligned(src); } -function getArgF32(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF32 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF32_unaligned(src); } -function getArgF64(ip: MintOpcodePtr, indexPlusOne: number) { +function getArgF64 (ip: MintOpcodePtr, indexPlusOne: number) { const src = ip + (2 * indexPlusOne); return getF64_unaligned(src); } -function get_imethod(frame: NativePointer) { +function get_imethod (frame: NativePointer) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const iMethod = getU32_unaligned(frame + getMemberOffset(JiterpMember.Imethod)); return iMethod; } -function get_imethod_data(frame: NativePointer, index: number) { +function get_imethod_data (frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.DataItems)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function get_imethod_clause_data_offset(frame: NativePointer, index: number) { +function get_imethod_clause_data_offset (frame: NativePointer, index: number) { // FIXME: Encoding this data directly into the trace will prevent trace reuse const pData = getU32_unaligned(get_imethod(frame) + getMemberOffset(JiterpMember.ClauseDataOffsets)); const dataOffset = pData + (index * sizeOfDataItem); return getU32_unaligned(dataOffset); } -function is_backward_branch_target( +function is_backward_branch_target ( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, backwardBranchTable: Uint16Array | null ) { @@ -138,14 +138,14 @@ type KnownConstant = KnownConstantI32 | KnownConstantV128 | KnownConstantLdloca; type KnownConstantValue = number | Uint8Array; const knownConstants = new Map(); -function get_known_constant(builder: WasmBuilder, localOffset: number): KnownConstant | undefined { +function get_known_constant (builder: WasmBuilder, localOffset: number): KnownConstant | undefined { if (isAddressTaken(builder, localOffset)) return undefined; return knownConstants.get(localOffset); } -function get_known_constant_value(builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { +function get_known_constant_value (builder: WasmBuilder, localOffset: number): KnownConstantValue | undefined { const kc = get_known_constant(builder, localOffset); if (kc === undefined) return undefined; @@ -163,7 +163,7 @@ function get_known_constant_value(builder: WasmBuilder, localOffset: number): Kn // backwards branch targets, compatible with the layout of the old one that was generated in C. // We do this here to match the exact way that the jiterp calculates branch targets, since // there were previously corner cases where jiterp and interp disagreed. -export function generateBackwardBranchTable( +export function generateBackwardBranchTable ( ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, ): Uint16Array | null { const endOfBody = startOfBody + sizeOfBody; @@ -236,7 +236,7 @@ export function generateBackwardBranchTable( return new Uint16Array(table); } -export function generateWasmBody( +export function generateWasmBody ( frame: NativePointer, traceName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, endOfBody: MintOpcodePtr, builder: WasmBuilder, instrumentedTraceId: number, @@ -1748,29 +1748,29 @@ export function generateWasmBody( const notNullSince: Map = new Map(); let cknullOffset = -1; -function eraseInferredState() { +function eraseInferredState () { cknullOffset = -1; notNullSince.clear(); knownConstants.clear(); } -function invalidate_local(offset: number) { +function invalidate_local (offset: number) { if (cknullOffset === offset) cknullOffset = -1; notNullSince.delete(offset); knownConstants.delete(offset); } -function invalidate_local_range(start: number, bytes: number) { +function invalidate_local_range (start: number, bytes: number) { for (let i = 0; i < bytes; i += 1) invalidate_local(start + i); } -function append_branch_target_block(builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { +function append_branch_target_block (builder: WasmBuilder, ip: MintOpcodePtr, isBackBranchTarget: boolean) { builder.cfg.startBranchBlock(ip, isBackBranchTarget); } -function computeMemoryAlignment(offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function computeMemoryAlignment (offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { // First, compute the best possible alignment let alignment = 0; if (offset % 16 === 0) @@ -1831,7 +1831,7 @@ function computeMemoryAlignment(offset: number, opcodeOrPrefix: WasmOpcode, simd return alignment; } -function try_append_ldloc_cprop( +function try_append_ldloc_cprop ( builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, dryRun: boolean, requireNonzero?: boolean ) { @@ -1868,7 +1868,7 @@ function try_append_ldloc_cprop( return false; } -function append_ldloc(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_ldloc (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { if (try_append_ldloc_cprop(builder, offset, opcodeOrPrefix, false)) return; @@ -1890,7 +1890,7 @@ function append_ldloc(builder: WasmBuilder, offset: number, opcodeOrPrefix: Wasm // where the offset+alignment pair is referred to as a 'memarg' by the spec. // The actual store operation is equivalent to `pBase[offset] = value` (alignment has no // observable impact on behavior, other than causing compilation failures if out of range) -function append_stloc_tail(builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { +function append_stloc_tail (builder: WasmBuilder, offset: number, opcodeOrPrefix: WasmOpcode, simdOpcode?: WasmSimdOpcode) { mono_assert(opcodeOrPrefix >= WasmOpcode.i32_store, () => `Expected store opcode but got ${opcodeOrPrefix}`); builder.appendU8(opcodeOrPrefix); if (simdOpcode !== undefined) { @@ -1907,7 +1907,7 @@ function append_stloc_tail(builder: WasmBuilder, offset: number, opcodeOrPrefix: // Pass bytesInvalidated=0 if you are reading from the local and the address will never be // used for writes -function append_ldloca(builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { +function append_ldloca (builder: WasmBuilder, localOffset: number, bytesInvalidated?: number) { if (typeof (bytesInvalidated) !== "number") bytesInvalidated = 512; // FIXME: We need to know how big this variable is so we can invalidate the whole space it occupies @@ -1916,7 +1916,7 @@ function append_ldloca(builder: WasmBuilder, localOffset: number, bytesInvalidat builder.lea("pLocals", localOffset); } -function append_memset_local(builder: WasmBuilder, localOffset: number, value: number, count: number) { +function append_memset_local (builder: WasmBuilder, localOffset: number, value: number, count: number) { invalidate_local_range(localOffset, count); // spec: pop n, pop val, pop d, fill from d[0] to d[n] with value val @@ -1928,7 +1928,7 @@ function append_memset_local(builder: WasmBuilder, localOffset: number, value: n append_memset_dest(builder, value, count); } -function append_memmove_local_local(builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { +function append_memmove_local_local (builder: WasmBuilder, destLocalOffset: number, sourceLocalOffset: number, count: number) { invalidate_local_range(destLocalOffset, count); if (try_append_memmove_fast(builder, destLocalOffset, sourceLocalOffset, count, false)) @@ -1940,12 +1940,12 @@ function append_memmove_local_local(builder: WasmBuilder, destLocalOffset: numbe append_memmove_dest_src(builder, count); } -function isAddressTaken(builder: WasmBuilder, localOffset: number) { +function isAddressTaken (builder: WasmBuilder, localOffset: number) { return cwraps.mono_jiterp_is_imethod_var_address_taken(get_imethod(builder.frame), localOffset) !== 0; } // Loads the specified i32 value and then bails out if it is null, leaving it in the cknull_ptr local. -function append_ldloc_cknull(builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { +function append_ldloc_cknull (builder: WasmBuilder, localOffset: number, ip: MintOpcodePtr, leaveOnStack: boolean) { const optimize = builder.allowNullCheckOptimization && notNullSince.has(localOffset) && !isAddressTaken(builder, localOffset); @@ -1997,7 +1997,7 @@ function append_ldloc_cknull(builder: WasmBuilder, localOffset: number, ip: Mint cknullOffset = -1; } -function emit_ldc(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_ldc (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let storeType = WasmOpcode.i32_store; let value: number | undefined; @@ -2069,7 +2069,7 @@ function emit_ldc(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function emit_mov(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_mov (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let loadOp = WasmOpcode.i32_load, storeOp = WasmOpcode.i32_store; switch (opcode) { case MintOpcode.MINT_MOV_I4_I1: @@ -2132,7 +2132,7 @@ function emit_mov(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function append_vtable_initialize(builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { +function append_vtable_initialize (builder: WasmBuilder, pVtable: NativePointer, ip: MintOpcodePtr) { // TODO: Actually initialize the vtable instead of just checking and bailing out? builder.block(); // FIXME: This will prevent us from reusing traces between runs since the vtables can move @@ -2147,7 +2147,7 @@ function append_vtable_initialize(builder: WasmBuilder, pVtable: NativePointer, builder.endBlock(); } -function emit_fieldop( +function emit_fieldop ( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2343,7 +2343,7 @@ function emit_fieldop( } } -function emit_sfieldop( +function emit_sfieldop ( builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode ): boolean { @@ -2450,7 +2450,7 @@ function emit_sfieldop( } } -function emit_binop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_binop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right let lhsLoadOp: WasmOpcode, rhsLoadOp: WasmOpcode, storeOp: WasmOpcode, lhsVar = "math_lhs32", rhsVar = "math_rhs32", @@ -2602,7 +2602,7 @@ function emit_binop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode) return true; } -function emit_unop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_unop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { // operands are popped right to left, which means you build the arg list left to right const info = unopTable[opcode]; if (!info) @@ -2741,7 +2741,7 @@ function emit_unop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): return true; } -function append_call_handler_store_ret_ip( +function append_call_handler_store_ret_ip ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ) { @@ -2761,7 +2761,7 @@ function append_call_handler_store_ret_ip( builder.callHandlerReturnAddresses.push(retIp); } -function getBranchDisplacement( +function getBranchDisplacement ( ip: MintOpcodePtr, opcode: MintOpcode ): number | undefined { const opArgType = cwraps.mono_jiterp_get_opcode_info(opcode, OpcodeInfoType.OpArgType), @@ -2789,7 +2789,7 @@ function getBranchDisplacement( return result; } -function emit_branch( +function emit_branch ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2930,7 +2930,7 @@ function emit_branch( return true; } -function emit_relop_branch( +function emit_relop_branch ( builder: WasmBuilder, ip: MintOpcodePtr, frame: NativePointer, opcode: MintOpcode ): boolean { @@ -2985,7 +2985,7 @@ function emit_relop_branch( return emit_branch(builder, ip, frame, opcode); } -function emit_math_intrinsic(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_math_intrinsic (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { let isUnary: boolean, isF32: boolean, name: string | undefined; let wasmOp: WasmOpcode | undefined; const destOffset = getArgU16(ip, 1), @@ -3033,7 +3033,7 @@ function emit_math_intrinsic(builder: WasmBuilder, ip: MintOpcodePtr, opcode: Mi } } -function emit_indirectop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_indirectop (builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = (opcode >= MintOpcode.MINT_LDIND_I1) && (opcode <= MintOpcode.MINT_LDIND_OFFSET_ADD_MUL_IMM_I8); const isAddMul = ( @@ -3247,7 +3247,7 @@ function emit_indirectop(builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOp return true; } -function append_getelema1( +function append_getelema1 ( builder: WasmBuilder, ip: MintOpcodePtr, objectOffset: number, indexOffset: number, elementSize: number ) { @@ -3306,7 +3306,7 @@ function append_getelema1( // append_getelema1 leaves the address on the stack } -function emit_arrayop(builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { +function emit_arrayop (builder: WasmBuilder, frame: NativePointer, ip: MintOpcodePtr, opcode: MintOpcode): boolean { const isLoad = ((opcode <= MintOpcode.MINT_LDELEMA_TC) && (opcode >= MintOpcode.MINT_LDELEM_I1)) || (opcode === MintOpcode.MINT_LDLEN), objectOffset = getArgU16(ip, isLoad ? 2 : 1), @@ -3470,7 +3470,7 @@ function emit_arrayop(builder: WasmBuilder, frame: NativePointer, ip: MintOpcode let wasmSimdSupported: boolean | undefined; -function getIsWasmSimdSupported(): boolean { +function getIsWasmSimdSupported (): boolean { if (wasmSimdSupported !== undefined) return wasmSimdSupported; @@ -3481,7 +3481,7 @@ function getIsWasmSimdSupported(): boolean { return wasmSimdSupported; } -function get_import_name( +function get_import_name ( builder: WasmBuilder, typeName: string, functionPtr: number ): string { @@ -3492,7 +3492,7 @@ function get_import_name( return name; } -function emit_simd( +function emit_simd ( builder: WasmBuilder, ip: MintOpcodePtr, opcode: MintOpcode, opname: string, argCount: number, index: number @@ -3593,31 +3593,31 @@ function emit_simd( } } -function append_simd_store(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_store (builder: WasmBuilder, ip: MintOpcodePtr) { append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_store); } -function append_simd_2_load(builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { +function append_simd_2_load (builder: WasmBuilder, ip: MintOpcodePtr, loadOp?: WasmSimdOpcode) { builder.local("pLocals"); // This || is harmless since v128_load is 0 append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, loadOp || WasmSimdOpcode.v128_load); } -function append_simd_3_load(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_3_load (builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); // FIXME: Can rhs be a scalar? We handle shifts separately already append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function append_simd_4_load(builder: WasmBuilder, ip: MintOpcodePtr) { +function append_simd_4_load (builder: WasmBuilder, ip: MintOpcodePtr) { builder.local("pLocals"); append_ldloc(builder, getArgU16(ip, 2), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 3), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); append_ldloc(builder, getArgU16(ip, 4), WasmOpcode.PREFIX_simd, WasmSimdOpcode.v128_load); } -function emit_simd_2(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { +function emit_simd_2 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic2): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(1, index); if (simple >= 0) { if (simdLoadTable.has(index)) { @@ -3684,7 +3684,7 @@ function emit_simd_2(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrins } } -function emit_simd_3(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { +function emit_simd_3 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic3): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(2, index); if (simple >= 0) { const isShift = simdShiftTable.has(index), @@ -3805,7 +3805,7 @@ function emit_simd_3(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrins // implement i16 and i32 shuffles on top of wasm's only shuffle opcode by expanding the // element shuffle indices into byte indices -function emit_shuffle(builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { +function emit_shuffle (builder: WasmBuilder, ip: MintOpcodePtr, elementCount: number): boolean { const elementSize = 16 / elementCount, indicesOffset = getArgU16(ip, 3), constantIndices = get_known_constant_value(builder, indicesOffset); @@ -3866,7 +3866,7 @@ function emit_shuffle(builder: WasmBuilder, ip: MintOpcodePtr, elementCount: num return true; } -function emit_simd_4(builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { +function emit_simd_4 (builder: WasmBuilder, ip: MintOpcodePtr, index: SimdIntrinsic4): boolean { const simple = cwraps.mono_jiterp_get_simd_opcode(3, index); if (simple >= 0) { // [lane count, value load opcode] diff --git a/src/mono/browser/runtime/jiterpreter.ts b/src/mono/browser/runtime/jiterpreter.ts index 188ead0c51e99c..bf77f289603845 100644 --- a/src/mono/browser/runtime/jiterpreter.ts +++ b/src/mono/browser/runtime/jiterpreter.ts @@ -98,7 +98,7 @@ export class InstrumentedTraceState { operand1: number | undefined; operand2: number | undefined; - constructor(name: string) { + constructor (name: string) { this.name = name; this.eip = 0; } @@ -114,13 +114,13 @@ export class TraceInfo { bailoutCount: number | undefined; isVerbose: boolean; - constructor(ip: MintOpcodePtr, index: number, isVerbose: number) { + constructor (ip: MintOpcodePtr, index: number, isVerbose: number) { this.ip = ip; this.index = index; this.isVerbose = !!isVerbose; } - get hitCount() { + get hitCount () { return cwraps.mono_jiterp_get_trace_hit_count(this.index); } } @@ -225,7 +225,7 @@ const mathOps1d = "powf", ]; -function recordBailout(ip: number, traceIndex: number, reason: BailoutReason) { +function recordBailout (ip: number, traceIndex: number, reason: BailoutReason) { cwraps.mono_jiterp_trace_bailout(reason); // Counting these is not meaningful and messes up the end of run statistics if (reason === BailoutReason.Return) @@ -251,7 +251,7 @@ function recordBailout(ip: number, traceIndex: number, reason: BailoutReason) { return ip; } -function getTraceImports() { +function getTraceImports () { if (traceImports) return traceImports; @@ -313,7 +313,7 @@ function getTraceImports() { return traceImports; } -function initialize_builder(builder: WasmBuilder) { +function initialize_builder (builder: WasmBuilder) { // Function type for compiled traces builder.defineType( "trace", @@ -694,7 +694,7 @@ function initialize_builder(builder: WasmBuilder) { } } -function assert_not_null( +function assert_not_null ( value: number, expectedValue: number, traceIndex: number, ip: MintOpcodePtr ) { if (value && (value === expectedValue)) @@ -704,7 +704,7 @@ function assert_not_null( } // returns function id -function generate_wasm( +function generate_wasm ( frame: NativePointer, methodName: string, ip: MintOpcodePtr, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, traceIndex: number, methodFullName: string | undefined, @@ -948,7 +948,7 @@ function generate_wasm( } } -export function trace_current_ip(traceId: number, eip: MintOpcodePtr) { +export function trace_current_ip (traceId: number, eip: MintOpcodePtr) { const tup = instrumentedTraces[traceId]; if (!tup) throw new Error(`Unrecognized instrumented trace id ${traceId}`); @@ -956,14 +956,14 @@ export function trace_current_ip(traceId: number, eip: MintOpcodePtr) { mostRecentTrace = tup; } -export function trace_operands(a: number, b: number) { +export function trace_operands (a: number, b: number) { if (!mostRecentTrace) throw new Error("No trace active"); mostRecentTrace.operand1 = a >>> 0; mostRecentTrace.operand2 = b >>> 0; } -export function record_abort(traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { +export function record_abort (traceIndex: number, ip: MintOpcodePtr, traceName: string, reason: string | MintOpcode) { if (typeof (reason) === "number") { cwraps.mono_jiterp_adjust_abort_count(reason, 1); reason = getOpcodeName(reason); @@ -986,7 +986,7 @@ export function record_abort(traceIndex: number, ip: MintOpcodePtr, traceName: s const JITERPRETER_TRAINING = 0; const JITERPRETER_NOT_JITTED = 1; -export function mono_interp_tier_prepare_jiterpreter( +export function mono_interp_tier_prepare_jiterpreter ( frame: NativePointer, method: MonoMethod, ip: MintOpcodePtr, index: number, startOfBody: MintOpcodePtr, sizeOfBody: MintOpcodePtr, isVerbose: number, presetFunctionPointer: number @@ -1061,7 +1061,7 @@ export function mono_interp_tier_prepare_jiterpreter( // NOTE: This will potentially be called once for every trace entry point // in a given method, not just once per method -export function mono_jiterp_free_method_data_js( +export function mono_jiterp_free_method_data_js ( method: MonoMethod, imethod: number, traceIndex: number ) { // TODO: Uninstall the trace function pointer from the function pointer table, @@ -1073,7 +1073,7 @@ export function mono_jiterp_free_method_data_js( mono_jiterp_free_method_data_jit_call(method); } -export function jiterpreter_dump_stats(concise?: boolean): void { +export function jiterpreter_dump_stats (concise?: boolean): void { if (!runtimeHelpers.runtimeReady) { return; } diff --git a/src/mono/browser/runtime/lazyLoading.ts b/src/mono/browser/runtime/lazyLoading.ts index 86b0431e5400b8..f4da4521010a91 100644 --- a/src/mono/browser/runtime/lazyLoading.ts +++ b/src/mono/browser/runtime/lazyLoading.ts @@ -5,7 +5,7 @@ import { loaderHelpers } from "./globals"; import { load_lazy_assembly } from "./managed-exports"; import { AssetEntry } from "./types"; -export async function loadLazyAssembly(assemblyNameToLoad: string): Promise { +export async function loadLazyAssembly (assemblyNameToLoad: string): Promise { const resources = loaderHelpers.config.resources!; const lazyAssemblies = resources.lazyAssembly; if (!lazyAssemblies) { @@ -56,7 +56,7 @@ export async function loadLazyAssembly(assemblyNameToLoad: string): Promise { +export async function mono_download_assets (): Promise { mono_log_debug("mono_download_assets"); try { const promises_of_assets: Promise[] = []; @@ -175,7 +175,7 @@ export async function mono_download_assets(): Promise { const promises_of_asset_instantiation: Promise[] = []; for (const downloadPromise of promises_of_assets) { - promises_of_asset_instantiation.push((async() => { + promises_of_asset_instantiation.push((async () => { const asset = await downloadPromise; if (asset.buffer) { if (!skipInstantiateByAssetTypes[asset.behavior]) { @@ -237,7 +237,7 @@ export async function mono_download_assets(): Promise { } } -export function prepareAssets() { +export function prepareAssets () { const config = loaderHelpers.config; const modulesAssets: AssetEntryInternal[] = []; @@ -365,7 +365,7 @@ export function prepareAssets() { config.assets = [...assetsToLoad, ...modulesAssets]; } -export function prepareAssetsWorker() { +export function prepareAssetsWorker () { const config = loaderHelpers.config; mono_assert(config.assets, "config.assets must be defined"); @@ -377,18 +377,18 @@ export function prepareAssetsWorker() { } } -export function delay(ms: number): Promise { +export function delay (ms: number): Promise { return new Promise(resolve => globalThis.setTimeout(resolve, ms)); } -export async function retrieve_asset_download(asset: AssetEntry): Promise { +export async function retrieve_asset_download (asset: AssetEntry): Promise { const pendingAsset = await start_asset_download(asset); await pendingAsset.pendingDownloadInternal!.response; return pendingAsset.buffer!; } // FIXME: Connection reset is probably the only good one for which we should retry -export async function start_asset_download(asset: AssetEntryInternal): Promise { +export async function start_asset_download (asset: AssetEntryInternal): Promise { try { return await start_asset_download_with_throttle(asset); } catch (err: any) { @@ -429,7 +429,7 @@ export async function start_asset_download(asset: AssetEntryInternal): Promise { +async function start_asset_download_with_throttle (asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! while (throttlingPromise) { await throttlingPromise.promise; @@ -463,7 +463,7 @@ async function start_asset_download_with_throttle(asset: AssetEntryInternal): Pr } } -async function start_asset_download_sources(asset: AssetEntryInternal): Promise { +async function start_asset_download_sources (asset: AssetEntryInternal): Promise { // we don't addRunDependency to allow download in parallel with onRuntimeInitialized event! if (asset.pendingDownload) { asset.pendingDownloadInternal = asset.pendingDownload; @@ -541,7 +541,7 @@ async function start_asset_download_sources(asset: AssetEntryInternal): Promise< } } -function resolve_path(asset: AssetEntry, sourcePrefix: string): string { +function resolve_path (asset: AssetEntry, sourcePrefix: string): string { mono_assert(sourcePrefix !== null && sourcePrefix !== undefined, () => `sourcePrefix must be provided for ${asset.name}`); let attemptUrl; if (!asset.resolvedUrl) { @@ -565,7 +565,7 @@ function resolve_path(asset: AssetEntry, sourcePrefix: string): string { return attemptUrl; } -export function appendUniqueQuery(attemptUrl: string, behavior: AssetBehaviors): string { +export function appendUniqueQuery (attemptUrl: string, behavior: AssetBehaviors): string { // apply unique query to js modules to make the module state independent of the other runtime instances if (loaderHelpers.modulesUniqueQuery && appendQueryAssetTypes[behavior]) { attemptUrl = attemptUrl + loaderHelpers.modulesUniqueQuery; @@ -577,7 +577,7 @@ export function appendUniqueQuery(attemptUrl: string, behavior: AssetBehaviors): let resourcesLoaded = 0; const totalResources = new Set(); -function download_resource(asset: AssetEntryInternal): LoadingResource { +function download_resource (asset: AssetEntryInternal): LoadingResource { try { mono_assert(asset.resolvedUrl, "Request's resolvedUrl must be set"); const fetchResponse = download_resource_with_cache(asset); @@ -613,7 +613,7 @@ function download_resource(asset: AssetEntryInternal): LoadingResource { } } -async function download_resource_with_cache(asset: AssetEntryInternal): Promise { +async function download_resource_with_cache (asset: AssetEntryInternal): Promise { let response = await findCachedResponse(asset); if (!response) { response = await fetchResource(asset); @@ -623,7 +623,7 @@ async function download_resource_with_cache(asset: AssetEntryInternal): Promise< return response; } -function fetchResource(asset: AssetEntryInternal): Promise { +function fetchResource (asset: AssetEntryInternal): Promise { // Allow developers to override how the resource is loaded let url = asset.resolvedUrl!; if (loaderHelpers.loadBootResource) { @@ -671,7 +671,7 @@ const monoToBlazorAssetTypeMap: { [key: string]: WebAssemblyBootResourceType | u "js-module-threads": "dotnetjs" }; -function invokeLoadBootResource(asset: AssetEntryInternal): string | Promise | null | undefined { +function invokeLoadBootResource (asset: AssetEntryInternal): string | Promise | null | undefined { if (loaderHelpers.loadBootResource) { const requestHash = asset.hash ?? ""; const url = asset.resolvedUrl!; @@ -689,7 +689,7 @@ function invokeLoadBootResource(asset: AssetEntryInternal): string | Promise= 0) { lastIndexOfSlash++; @@ -705,7 +705,7 @@ function fileName(name: string) { return name.substring(lastIndexOfSlash); } -export async function streamingCompileWasm() { +export async function streamingCompileWasm () { try { const wasmModuleAsset = resolve_single_asset_path("dotnetwasm"); await start_asset_download(wasmModuleAsset); @@ -737,7 +737,7 @@ export async function streamingCompileWasm() { loaderHelpers.wasmCompilePromise.promise_control.reject(err); } } -export function preloadWorkers() { +export function preloadWorkers () { if (!WasmEnableThreads) return; const jsModuleWorker = resolve_single_asset_path("js-module-threads"); for (let i = 0; i < loaderHelpers.config.pthreadPoolInitialSize!; i++) { diff --git a/src/mono/browser/runtime/loader/assetsCache.ts b/src/mono/browser/runtime/loader/assetsCache.ts index ec6bf96233b5d5..1be22cfdd1fde5 100644 --- a/src/mono/browser/runtime/loader/assetsCache.ts +++ b/src/mono/browser/runtime/loader/assetsCache.ts @@ -10,7 +10,7 @@ const networkLoads: { [name: string]: LoadLogEntry } = {}; const cacheLoads: { [name: string]: LoadLogEntry } = {}; let cacheIfUsed: Cache | null; -export function logDownloadStatsToConsole(): void { +export function logDownloadStatsToConsole (): void { const cacheLoadsEntries = Object.values(cacheLoads); const networkLoadsEntries = Object.values(networkLoads); const cacheResponseBytes = countTotalBytes(cacheLoadsEntries); @@ -51,7 +51,7 @@ export function logDownloadStatsToConsole(): void { console.groupEnd(); } -export async function purgeUnusedCacheEntriesAsync(): Promise { +export async function purgeUnusedCacheEntriesAsync (): Promise { // We want to keep the cache small because, even though the browser will evict entries if it // gets too big, we don't want to be considered problematic by the end user viewing storage stats const cache = cacheIfUsed; @@ -67,7 +67,7 @@ export async function purgeUnusedCacheEntriesAsync(): Promise { } } -export async function findCachedResponse(asset: AssetEntryInternal): Promise { +export async function findCachedResponse (asset: AssetEntryInternal): Promise { const cache = cacheIfUsed; if (!cache || asset.noCache || !asset.hash || asset.hash.length === 0) { return undefined; @@ -94,7 +94,7 @@ export async function findCachedResponse(asset: AssetEntryInternal): Promise { +export async function initCacheToUseIfEnabled (): Promise { cacheIfUsed = await getCacheToUseIfEnabled(loaderHelpers.config); } -async function getCacheToUseIfEnabled(config: MonoConfig): Promise { +async function getCacheToUseIfEnabled (config: MonoConfig): Promise { // caches will be undefined if we're running on an insecure origin (secure means https or localhost) if (!config.cacheBootResources || typeof globalThis.caches === "undefined" || typeof globalThis.document === "undefined") { return null; @@ -180,15 +180,15 @@ async function getCacheToUseIfEnabled(config: MonoConfig): Promise } } -function countTotalBytes(loads: LoadLogEntry[]) { +function countTotalBytes (loads: LoadLogEntry[]) { return loads.reduce((prev, item) => prev + (item.responseBytes || 0), 0); } -function toDataSizeString(byteCount: number) { +function toDataSizeString (byteCount: number) { return `${(byteCount / (1024 * 1024)).toFixed(2)} MB`; } -function getPerformanceEntry(url: string): PerformanceResourceTiming | undefined { +function getPerformanceEntry (url: string): PerformanceResourceTiming | undefined { if (typeof performance !== "undefined") { return performance.getEntriesByName(url)[0] as PerformanceResourceTiming; } diff --git a/src/mono/browser/runtime/loader/config.ts b/src/mono/browser/runtime/loader/config.ts index 5648285166c5e6..1739bc09d1ef67 100644 --- a/src/mono/browser/runtime/loader/config.ts +++ b/src/mono/browser/runtime/loader/config.ts @@ -14,7 +14,7 @@ import { makeURLAbsoluteWithApplicationBase } from "./polyfills"; import { appendUniqueQuery } from "./assets"; import { mono_log_warn } from "./logging"; -export function deep_merge_config(target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { +export function deep_merge_config (target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal { // no need to merge the same object if (target === source) return target; @@ -40,7 +40,7 @@ export function deep_merge_config(target: MonoConfigInternal, source: MonoConfig return Object.assign(target, providedConfig); } -export function deep_merge_module(target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { +export function deep_merge_module (target: DotnetModuleInternal, source: DotnetModuleConfig): DotnetModuleInternal { // no need to merge the same object if (target === source) return target; @@ -52,7 +52,7 @@ export function deep_merge_module(target: DotnetModuleInternal, source: DotnetMo return Object.assign(target, providedConfig); } -function deep_merge_resources(target: ResourceGroups, source: ResourceGroups): ResourceGroups { +function deep_merge_resources (target: ResourceGroups, source: ResourceGroups): ResourceGroups { // no need to merge the same object if (target === source) return target; @@ -102,7 +102,7 @@ function deep_merge_resources(target: ResourceGroups, source: ResourceGroups): R return Object.assign(target, providedResources); } -function deep_merge_dict(target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { +function deep_merge_dict (target: { [key: string]: ResourceList }, source: { [key: string]: ResourceList }) { // no need to merge the same object if (target === source) return target; @@ -113,7 +113,7 @@ function deep_merge_dict(target: { [key: string]: ResourceList }, source: { [key } // NOTE: this is called before setRuntimeGlobals -export function normalizeConfig() { +export function normalizeConfig () { // normalize const config = loaderHelpers.config; @@ -259,7 +259,7 @@ export function normalizeConfig() { } let configLoaded = false; -export async function mono_wasm_load_config(module: DotnetModuleInternal): Promise { +export async function mono_wasm_load_config (module: DotnetModuleInternal): Promise { const configFilePath = module.configSrc; if (configLoaded) { await loaderHelpers.afterConfigLoaded.promise; @@ -297,7 +297,7 @@ export async function mono_wasm_load_config(module: DotnetModuleInternal): Promi } } -export function isDebuggingSupported(): boolean { +export function isDebuggingSupported (): boolean { // Copied from blazor MonoDebugger.ts/attachDebuggerHotkey if (!globalThis.navigator) { return false; @@ -306,7 +306,7 @@ export function isDebuggingSupported(): boolean { return loaderHelpers.isChromium || loaderHelpers.isFirefox; } -async function loadBootConfig(module: DotnetModuleInternal): Promise { +async function loadBootConfig (module: DotnetModuleInternal): Promise { const defaultConfigSrc = loaderHelpers.locateFile(module.configSrc!); const loaderResponse = loaderHelpers.loadBootResource !== undefined ? @@ -326,7 +326,7 @@ async function loadBootConfig(module: DotnetModuleInternal): Promise { const loadedConfig: MonoConfig = await readBootConfigResponse(loadConfigResponse); deep_merge_config(loaderHelpers.config, loadedConfig); - function defaultLoadBootConfig(url: string): Promise { + function defaultLoadBootConfig (url: string): Promise { return loaderHelpers.fetch_like(url, { method: "GET", credentials: "include", @@ -335,7 +335,7 @@ async function loadBootConfig(module: DotnetModuleInternal): Promise { } } -async function readBootConfigResponse(loadConfigResponse: Response): Promise { +async function readBootConfigResponse (loadConfigResponse: Response): Promise { const config = loaderHelpers.config; const loadedConfig: MonoConfig = await loadConfigResponse.json(); diff --git a/src/mono/browser/runtime/loader/exit.ts b/src/mono/browser/runtime/loader/exit.ts index da22c198f12016..2264cd086fbd7a 100644 --- a/src/mono/browser/runtime/loader/exit.ts +++ b/src/mono/browser/runtime/loader/exit.ts @@ -6,15 +6,15 @@ import WasmEnableThreads from "consts:wasmEnableThreads"; import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, INTERNAL, emscriptenModule, loaderHelpers, mono_assert, runtimeHelpers } from "./globals"; import { mono_log_debug, mono_log_error, mono_log_info_no_prefix, mono_log_warn, teardown_proxy_console } from "./logging"; -export function is_exited() { +export function is_exited () { return loaderHelpers.exitCode !== undefined; } -export function is_runtime_running() { +export function is_runtime_running () { return runtimeHelpers.runtimeReady && !is_exited(); } -export function assert_runtime_running() { +export function assert_runtime_running () { mono_assert(!is_exited(), () => `.NET runtime already exited with ${loaderHelpers.exitCode} ${loaderHelpers.exitReason}. You can use runtime.runMain() which doesn't exit the runtime.`); if (WasmEnableThreads && ENVIRONMENT_IS_WORKER) { mono_assert(runtimeHelpers.runtimeReady, "The WebWorker is not attached to the runtime. See https://github.com/dotnet/runtime/blob/main/src/mono/wasm/threads.md#JS-interop-on-dedicated-threads"); @@ -24,7 +24,7 @@ export function assert_runtime_running() { } -export function installUnhandledErrorHandler() { +export function installUnhandledErrorHandler () { // it seems that emscripten already does the right thing for NodeJs and that there is no good solution for V8 shell. if (ENVIRONMENT_IS_WEB) { globalThis.addEventListener("unhandledrejection", unhandledrejection_handler); @@ -32,14 +32,14 @@ export function installUnhandledErrorHandler() { } } -export function uninstallUnhandledErrorHandler() { +export function uninstallUnhandledErrorHandler () { if (ENVIRONMENT_IS_WEB) { globalThis.removeEventListener("unhandledrejection", unhandledrejection_handler); globalThis.removeEventListener("error", error_handler); } } -export function registerEmscriptenExitHandlers() { +export function registerEmscriptenExitHandlers () { if (!emscriptenModule.onAbort) { emscriptenModule.onAbort = onAbort; } @@ -48,7 +48,7 @@ export function registerEmscriptenExitHandlers() { } } -function unregisterEmscriptenExitHandlers() { +function unregisterEmscriptenExitHandlers () { if (emscriptenModule.onAbort == onAbort) { emscriptenModule.onAbort = undefined; } @@ -56,16 +56,16 @@ function unregisterEmscriptenExitHandlers() { emscriptenModule.onExit = undefined; } } -function onExit(code: number) { +function onExit (code: number) { mono_exit(code, loaderHelpers.exitReason); } -function onAbort(reason: any) { +function onAbort (reason: any) { mono_exit(1, loaderHelpers.exitReason || reason); } // this will also call mono_wasm_exit if available, which will call exitJS -> _proc_exit -> terminateAllThreads -export function mono_exit(exit_code: number, reason?: any): void { +export function mono_exit (exit_code: number, reason?: any): void { unregisterEmscriptenExitHandlers(); uninstallUnhandledErrorHandler(); @@ -136,7 +136,7 @@ export function mono_exit(exit_code: number, reason?: any): void { if (loaderHelpers.config && loaderHelpers.config.asyncFlushOnExit && exit_code === 0) { // this would NOT call Node's exit() immediately, it's a hanging promise - (async() => { + (async () => { try { await flush_node_streams(); } finally { @@ -151,7 +151,7 @@ export function mono_exit(exit_code: number, reason?: any): void { } } -function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { +function set_exit_code_and_quit_now (exit_code: number, reason?: any): void { if (WasmEnableThreads && ENVIRONMENT_IS_WORKER && runtimeHelpers.runtimeReady && runtimeHelpers.nativeAbort) { // note that the reason is not passed to UI thread runtimeHelpers.runtimeReady = false; @@ -180,7 +180,7 @@ function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { } } -async function flush_node_streams() { +async function flush_node_streams () { try { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -204,7 +204,7 @@ async function flush_node_streams() { } } -function abort_promises(reason: any) { +function abort_promises (reason: any) { loaderHelpers.exitReason = reason; loaderHelpers.allDownloadsQueued.promise_control.reject(reason); loaderHelpers.afterConfigLoaded.promise_control.reject(reason); @@ -222,7 +222,7 @@ function abort_promises(reason: any) { } } -function appendElementOnExit(exit_code: number) { +function appendElementOnExit (exit_code: number) { if (ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER && loaderHelpers.config && loaderHelpers.config.appendElementOnExit && document) { //Tell xharness WasmBrowserTestRunner what was the exit code const tests_done_elem = document.createElement("label"); @@ -233,7 +233,7 @@ function appendElementOnExit(exit_code: number) { } } -function logOnExit(exit_code: number, reason: any) { +function logOnExit (exit_code: number, reason: any) { if (exit_code !== 0 && reason) { // ExitStatus usually is not real JS error and so stack strace is not very useful. // We will use debug level for it, which will print only when diagnosticTracing is set. @@ -268,15 +268,15 @@ function logOnExit(exit_code: number, reason: any) { } } } -function unhandledrejection_handler(event: any) { +function unhandledrejection_handler (event: any) { fatal_handler(event, event.reason, "rejection"); } -function error_handler(event: any) { +function error_handler (event: any) { fatal_handler(event, event.error, "error"); } -function fatal_handler(event: any, reason: any, type: string) { +function fatal_handler (event: any, reason: any, type: string) { event.preventDefault(); try { if (!reason) { diff --git a/src/mono/browser/runtime/loader/globals.ts b/src/mono/browser/runtime/loader/globals.ts index 4bf317bb66a07c..5e76904d55259b 100644 --- a/src/mono/browser/runtime/loader/globals.ts +++ b/src/mono/browser/runtime/loader/globals.ts @@ -53,7 +53,7 @@ export const globalObjectsRoot: GlobalObjects = { setLoaderGlobals(globalObjectsRoot); -export function setLoaderGlobals( +export function setLoaderGlobals ( globalObjects: GlobalObjects, ) { if (_loaderModuleLoaded) { @@ -137,7 +137,7 @@ export function setLoaderGlobals( // this will abort the program if the condition is false // see src\mono\browser\runtime\rollup.config.js // we inline the condition, because the lambda could allocate closure on hot path otherwise -export function mono_assert(condition: unknown, messageFactory: string | (() => string)): asserts condition { +export function mono_assert (condition: unknown, messageFactory: string | (() => string)): asserts condition { if (condition) return; const message = "Assert failed: " + (typeof messageFactory === "function" ? messageFactory() diff --git a/src/mono/browser/runtime/loader/icu.ts b/src/mono/browser/runtime/loader/icu.ts index 8cb39f2e0b2bd6..0a7823497aa853 100644 --- a/src/mono/browser/runtime/loader/icu.ts +++ b/src/mono/browser/runtime/loader/icu.ts @@ -5,7 +5,7 @@ import { GlobalizationMode, MonoConfig } from "../types"; import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals"; import { mono_log_info, mono_log_debug } from "./logging"; -export function init_globalization() { +export function init_globalization () { loaderHelpers.preferredIcuAsset = getIcuResourceName(loaderHelpers.config); let invariantMode = loaderHelpers.config.globalizationMode == GlobalizationMode.Invariant; @@ -44,7 +44,7 @@ export function init_globalization() { } } -export function getIcuResourceName(config: MonoConfig): string | null { +export function getIcuResourceName (config: MonoConfig): string | null { if (config.resources?.icu && config.globalizationMode != GlobalizationMode.Invariant) { // 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); @@ -73,7 +73,7 @@ export function getIcuResourceName(config: MonoConfig): string | null { return null; } -function getShardedIcuResourceName(culture: string): string { +function getShardedIcuResourceName (culture: string): string { const prefix = culture.split("-")[0]; if (prefix === "en" || ["fr", "fr-FR", "it", "it-IT", "de", "de-DE", "es", "es-ES"].includes(culture)) { return "icudt_EFIGS.dat"; diff --git a/src/mono/browser/runtime/loader/libraryInitializers.ts b/src/mono/browser/runtime/loader/libraryInitializers.ts index 27c5d783a40222..a8a16c543dbccf 100644 --- a/src/mono/browser/runtime/loader/libraryInitializers.ts +++ b/src/mono/browser/runtime/loader/libraryInitializers.ts @@ -7,7 +7,7 @@ import { loaderHelpers } from "./globals"; import { mono_exit } from "./exit"; import { ResourceList } from "../types"; -export async function importLibraryInitializers(libraryInitializers: ResourceList | undefined): Promise { +export async function importLibraryInitializers (libraryInitializers: ResourceList | undefined): Promise { if (!libraryInitializers) { return; } @@ -15,7 +15,7 @@ export async function importLibraryInitializers(libraryInitializers: ResourceLis const initializerFiles = Object.keys(libraryInitializers); await Promise.all(initializerFiles.map(f => importInitializer(f))); - async function importInitializer(path: string): Promise { + async function importInitializer (path: string): Promise { try { const adjustedPath = appendUniqueQuery(loaderHelpers.locateFile(path), "js-module-library-initializer"); mono_log_debug(`Attempting to import '${adjustedPath}' for ${path}`); @@ -28,7 +28,7 @@ export async function importLibraryInitializers(libraryInitializers: ResourceLis } } -export async function invokeLibraryInitializers(functionName: string, args: any[]) { +export async function invokeLibraryInitializers (functionName: string, args: any[]) { if (!loaderHelpers.libraryInitializers) { return; } @@ -44,7 +44,7 @@ export async function invokeLibraryInitializers(functionName: string, args: any[ await Promise.all(promises); } -async function abortStartupOnError(scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { +async function abortStartupOnError (scriptName: string, methodName: string, callback: () => Promise | undefined): Promise { try { await callback(); } catch (err) { diff --git a/src/mono/browser/runtime/loader/logging.ts b/src/mono/browser/runtime/loader/logging.ts index 7c4d509f6b6e2d..668d7e667b6d3f 100644 --- a/src/mono/browser/runtime/loader/logging.ts +++ b/src/mono/browser/runtime/loader/logging.ts @@ -14,29 +14,29 @@ let theConsoleApi: any; let originalConsoleMethods: any; let threadNamePrefix: string; -export function set_thread_prefix(threadPrefix: string) { +export function set_thread_prefix (threadPrefix: string) { threadNamePrefix = threadPrefix; } -export function mono_log_debug(msg: string, ...data: any[]) { +export function mono_log_debug (msg: string, ...data: any[]) { if (loaderHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info(msg: string, ...data: any) { +export function mono_log_info (msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_info_no_prefix(msg: string, ...data: any) { +export function mono_log_info_no_prefix (msg: string, ...data: any) { console.info(msg, ...data); } -export function mono_log_warn(msg: string, ...data: any) { +export function mono_log_warn (msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error(msg: string, ...data: any) { +export function mono_log_error (msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object") { // don't log silent errors if (data[0].silent) { @@ -54,8 +54,8 @@ export function mono_log_error(msg: string, ...data: any) { } let tick = ""; let last = new Date().valueOf(); -function proxyConsoleMethod(prefix: string, func: any, asJson: boolean) { - return function(...args: any[]) { +function proxyConsoleMethod (prefix: string, func: any, asJson: boolean) { + return function (...args: any[]) { try { let payload = args[0]; if (payload === undefined) payload = "undefined"; @@ -101,7 +101,7 @@ function proxyConsoleMethod(prefix: string, func: any, asJson: boolean) { }; } -export function setup_proxy_console(id: string, console: Console, origin: string): void { +export function setup_proxy_console (id: string, console: Console, origin: string): void { theConsoleApi = console as any; threadNamePrefix = id; originalConsoleMethods = { @@ -117,7 +117,7 @@ export function setup_proxy_console(id: string, console: Console, origin: string setupWS(); } -export function teardown_proxy_console(message?: string) { +export function teardown_proxy_console (message?: string) { const stop_when_ws_buffer_empty = () => { if (!consoleWebSocket) { if (message && originalConsoleMethods) { @@ -142,7 +142,7 @@ export function teardown_proxy_console(message?: string) { stop_when_ws_buffer_empty(); } -function send(msg: string) { +function send (msg: string) { if (consoleWebSocket && consoleWebSocket.readyState === WebSocket.OPEN) { consoleWebSocket.send(msg); } else { @@ -150,21 +150,21 @@ function send(msg: string) { } } -function logWSError(event: Event) { +function logWSError (event: Event) { originalConsoleMethods.error(`[${threadNamePrefix}] proxy console websocket error: ${event}`, event); } -function logWSClose(event: Event) { +function logWSClose (event: Event) { originalConsoleMethods.debug(`[${threadNamePrefix}] proxy console websocket closed: ${event}`, event); } -function setupWS() { +function setupWS () { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, send, true); } } -function setupOriginal() { +function setupOriginal () { for (const m of methods) { theConsoleApi[m] = proxyConsoleMethod(`console.${m}`, originalConsoleMethods.log, false); } diff --git a/src/mono/browser/runtime/loader/polyfills.ts b/src/mono/browser/runtime/loader/polyfills.ts index 4d9743049f2122..181323b0fe0a87 100644 --- a/src/mono/browser/runtime/loader/polyfills.ts +++ b/src/mono/browser/runtime/loader/polyfills.ts @@ -10,15 +10,15 @@ let node_fs: any | undefined = undefined; let node_url: any | undefined = undefined; const URLPolyfill = class URL { private url; - constructor(url: string) { + constructor (url: string) { this.url = url; } - toString() { + toString () { return this.url; } }; -export function verifyEnvironment() { +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. 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 (WasmEnableThreads) { @@ -28,7 +28,7 @@ export function verifyEnvironment() { } } -export async function detect_features_and_polyfill(module: DotnetModuleInternal): Promise { +export async function detect_features_and_polyfill (module: DotnetModuleInternal): Promise { if (ENVIRONMENT_IS_NODE) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore: @@ -87,7 +87,7 @@ export async function detect_features_and_polyfill(module: DotnetModuleInternal) } } -export async function fetch_like(url: string, init?: RequestInit): Promise { +export async function fetch_like (url: string, init?: RequestInit): Promise { try { // this need to be detected only after we import node modules in onConfigLoaded const hasFetch = typeof (globalThis.fetch) === "function"; @@ -167,7 +167,7 @@ export async function fetch_like(url: string, init?: RequestInit): Promise(afterResolve?: () => void, afterReject?: () => void): PromiseAndController { +export function createPromiseController (afterResolve?: () => void, afterReject?: () => void): PromiseAndController { let promise_control: PromiseController = null as unknown as PromiseController; - const promise = new Promise(function(resolve, reject) { + const promise = new Promise(function (resolve, reject) { promise_control = { isDone: false, promise: null as unknown as Promise, @@ -42,14 +42,14 @@ export function createPromiseController(afterResolve?: () => void, afterRejec } export function getPromiseController(promise: ControllablePromise): PromiseController; -export function getPromiseController(promise: Promise): PromiseController | undefined { +export function getPromiseController (promise: Promise): PromiseController | undefined { return (promise as any)[promise_control_symbol]; } -export function isControllablePromise(promise: Promise): promise is ControllablePromise { +export function isControllablePromise (promise: Promise): promise is ControllablePromise { return (promise as any)[promise_control_symbol] !== undefined; } -export function assertIsControllablePromise(promise: Promise): asserts promise is ControllablePromise { +export function assertIsControllablePromise (promise: Promise): asserts promise is ControllablePromise { mono_assert(promise && isControllablePromise(promise), "Promise is not controllable"); } diff --git a/src/mono/browser/runtime/loader/run.ts b/src/mono/browser/runtime/loader/run.ts index 992994211050fa..e6cb897a0c95d9 100644 --- a/src/mono/browser/runtime/loader/run.ts +++ b/src/mono/browser/runtime/loader/run.ts @@ -23,7 +23,7 @@ export class HostBuilder implements DotnetHostBuilder { private instance?: RuntimeAPI; // internal - withModuleConfig(moduleConfig: DotnetModuleConfig): DotnetHostBuilder { + withModuleConfig (moduleConfig: DotnetModuleConfig): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, moduleConfig); return this; @@ -34,7 +34,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withOnConfigLoaded(onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { + withOnConfigLoaded (onConfigLoaded: (config: MonoConfig) => void | Promise): DotnetHostBuilder { try { deep_merge_module(emscriptenModule, { onConfigLoaded @@ -47,7 +47,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withConsoleForwarding(): DotnetHostBuilder { + withConsoleForwarding (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { forwardConsoleLogsToWS: true @@ -60,7 +60,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitOnUnhandledError(): DotnetHostBuilder { + withExitOnUnhandledError (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { exitOnUnhandledError: true @@ -74,7 +74,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withAsyncFlushOnExit(): DotnetHostBuilder { + withAsyncFlushOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { asyncFlushOnExit: true @@ -87,7 +87,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withExitCodeLogging(): DotnetHostBuilder { + withExitCodeLogging (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { logExitCode: true @@ -100,7 +100,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withElementOnExit(): DotnetHostBuilder { + withElementOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { appendElementOnExit: true @@ -113,7 +113,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withInteropCleanupOnExit(): DotnetHostBuilder { + withInteropCleanupOnExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interopCleanupOnExit: true @@ -126,7 +126,7 @@ export class HostBuilder implements DotnetHostBuilder { } // internal - withDumpThreadsOnNonZeroExit(): DotnetHostBuilder { + withDumpThreadsOnNonZeroExit (): DotnetHostBuilder { try { deep_merge_config(monoConfig, { dumpThreadsOnNonZeroExit: true @@ -140,7 +140,7 @@ export class HostBuilder implements DotnetHostBuilder { // internal // todo fallback later by debugLevel - withWaitingForDebugger(level: number): DotnetHostBuilder { + withWaitingForDebugger (level: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { waitForDebugger: level @@ -152,7 +152,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withInterpreterPgo(value: boolean, autoSaveDelay?: number): DotnetHostBuilder { + withInterpreterPgo (value: boolean, autoSaveDelay?: number): DotnetHostBuilder { try { deep_merge_config(monoConfig, { interpreterPgo: value, @@ -165,7 +165,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfig(config: MonoConfig): DotnetHostBuilder { + withConfig (config: MonoConfig): DotnetHostBuilder { try { deep_merge_config(monoConfig, config); return this; @@ -175,7 +175,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withConfigSrc(configSrc: string): DotnetHostBuilder { + withConfigSrc (configSrc: string): DotnetHostBuilder { try { mono_assert(configSrc && typeof configSrc === "string", "must be file path or URL"); deep_merge_module(emscriptenModule, { configSrc }); @@ -186,7 +186,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withVirtualWorkingDirectory(vfsPath: string): DotnetHostBuilder { + withVirtualWorkingDirectory (vfsPath: string): DotnetHostBuilder { try { mono_assert(vfsPath && typeof vfsPath === "string", "must be directory path"); deep_merge_config(monoConfig, { @@ -199,7 +199,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariable(name: string, value: string): DotnetHostBuilder { + withEnvironmentVariable (name: string, value: string): DotnetHostBuilder { try { const environmentVariables: { [key: string]: string } = {}; environmentVariables[name] = value; @@ -213,7 +213,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withEnvironmentVariables(variables: { [i: string]: string; }): DotnetHostBuilder { + withEnvironmentVariables (variables: { [i: string]: string; }): DotnetHostBuilder { try { mono_assert(variables && typeof variables === "object", "must be dictionary object"); deep_merge_config(monoConfig, { @@ -226,7 +226,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDiagnosticTracing(enabled: boolean): DotnetHostBuilder { + withDiagnosticTracing (enabled: boolean): DotnetHostBuilder { try { mono_assert(typeof enabled === "boolean", "must be boolean"); deep_merge_config(monoConfig, { @@ -239,7 +239,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withDebugging(level: number): DotnetHostBuilder { + withDebugging (level: number): DotnetHostBuilder { try { mono_assert(level !== undefined && level !== null && typeof level === "number", "must be number"); deep_merge_config(monoConfig, { @@ -252,7 +252,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArguments(...args: string[]): DotnetHostBuilder { + withApplicationArguments (...args: string[]): DotnetHostBuilder { try { mono_assert(args && Array.isArray(args), "must be array of strings"); deep_merge_config(monoConfig, { @@ -265,7 +265,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withRuntimeOptions(runtimeOptions: string[]): DotnetHostBuilder { + withRuntimeOptions (runtimeOptions: string[]): DotnetHostBuilder { try { mono_assert(runtimeOptions && Array.isArray(runtimeOptions), "must be array of strings"); deep_merge_config(monoConfig, { @@ -278,7 +278,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withMainAssembly(mainAssemblyName: string): DotnetHostBuilder { + withMainAssembly (mainAssemblyName: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { mainAssemblyName @@ -290,7 +290,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationArgumentsFromQuery(): DotnetHostBuilder { + withApplicationArgumentsFromQuery (): DotnetHostBuilder { try { if (!globalThis.window) { throw new Error("Missing window to the query parameters from"); @@ -309,7 +309,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationEnvironment(applicationEnvironment?: string): DotnetHostBuilder { + withApplicationEnvironment (applicationEnvironment?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationEnvironment, @@ -321,7 +321,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withApplicationCulture(applicationCulture?: string): DotnetHostBuilder { + withApplicationCulture (applicationCulture?: string): DotnetHostBuilder { try { deep_merge_config(monoConfig, { applicationCulture, @@ -333,7 +333,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - withResourceLoader(loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { + withResourceLoader (loadBootResource?: LoadBootResourceCallback): DotnetHostBuilder { try { loaderHelpers.loadBootResource = loadBootResource; return this; @@ -343,7 +343,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async create(): Promise { + async create (): Promise { try { if (!this.instance) { this.instance = await createApi(); @@ -355,7 +355,7 @@ export class HostBuilder implements DotnetHostBuilder { } } - async run(): Promise { + async run (): Promise { try { mono_assert(emscriptenModule.config, "Null moduleConfig.config"); if (!this.instance) { @@ -369,7 +369,7 @@ export class HostBuilder implements DotnetHostBuilder { } } -export async function createApi(): Promise { +export async function createApi (): Promise { if (ENVIRONMENT_IS_WEB && loaderHelpers.config.forwardConsoleLogsToWS && typeof globalThis.WebSocket != "undefined") { setup_proxy_console("main", globalThis.console, globalThis.location.origin); } @@ -379,7 +379,7 @@ export async function createApi(): Promise { return globalObjectsRoot.api; } -export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { +export async function createEmscripten (moduleFactory: DotnetModuleConfig | ((api: RuntimeAPI) => DotnetModuleConfig)): Promise { // extract ModuleConfig if (typeof moduleFactory === "function") { const extension = moduleFactory(globalObjectsRoot.api) as any; @@ -408,7 +408,7 @@ export async function createEmscripten(moduleFactory: DotnetModuleConfig | ((api } // in the future we can use feature detection to load different flavors -function importModules() { +function importModules () { const jsModuleRuntimeAsset = resolve_single_asset_path("js-module-runtime"); const jsModuleNativeAsset = resolve_single_asset_path("js-module-native"); @@ -432,7 +432,7 @@ function importModules() { return [jsModuleRuntimePromise, jsModuleNativePromise]; } -async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { +async function initializeModules (es6Modules: [RuntimeModuleExportsInternal, NativeModuleExportsInternal]) { const { initializeExports, initializeReplacements, configureRuntimeStartup, configureEmscriptenStartup, configureWorkerStartup, setRuntimeGlobals, passEmscriptenInternals } = es6Modules[0]; const { default: emscriptenFactory } = es6Modules[1]; setRuntimeGlobals(globalObjectsRoot); @@ -452,7 +452,7 @@ async function initializeModules(es6Modules: [RuntimeModuleExportsInternal, Nati }); } -async function createEmscriptenMain(): Promise { +async function createEmscriptenMain (): Promise { if (!emscriptenModule.configSrc && (!loaderHelpers.config || Object.keys(loaderHelpers.config).length === 0 || (!loaderHelpers.config.assets && !loaderHelpers.config.resources))) { // if config file location nor assets are provided emscriptenModule.configSrc = "./blazor.boot.json"; @@ -469,7 +469,7 @@ async function createEmscriptenMain(): Promise { streamingCompileWasm(); // intentionally not awaited - setTimeout(async() => { + setTimeout(async () => { try { init_globalization(); preloadWorkers(); @@ -491,14 +491,14 @@ async function createEmscriptenMain(): Promise { return exportedRuntimeAPI; } -async function createEmscriptenWorker(): Promise { +async function createEmscriptenWorker (): Promise { setupPreloadChannelToMainThread(); await loaderHelpers.afterConfigLoaded.promise; prepareAssetsWorker(); - setTimeout(async() => { + setTimeout(async () => { try { // load subset which is on JS heap rather than in WASM linear memory await mono_download_assets(); diff --git a/src/mono/browser/runtime/loader/worker.ts b/src/mono/browser/runtime/loader/worker.ts index baeeaf0165f673..d14d862c05aa6c 100644 --- a/src/mono/browser/runtime/loader/worker.ts +++ b/src/mono/browser/runtime/loader/worker.ts @@ -7,7 +7,7 @@ import { deep_merge_config, normalizeConfig } from "./config"; import { ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers } from "./globals"; import { mono_log_debug } from "./logging"; -export function setupPreloadChannelToMainThread() { +export function setupPreloadChannelToMainThread () { const channel = new MessageChannel(); const workerPort = channel.port1; const mainPort = channel.port2; @@ -31,7 +31,7 @@ export function setupPreloadChannelToMainThread() { let workerMonoConfigReceived = false; // called when the main thread sends us the mono config -function onMonoConfigReceived(config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { +function onMonoConfigReceived (config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void { if (workerMonoConfigReceived) { mono_log_debug("mono config already received"); return; diff --git a/src/mono/browser/runtime/logging.ts b/src/mono/browser/runtime/logging.ts index 8e6dbfa67ff48c..1d91a870d52fb4 100644 --- a/src/mono/browser/runtime/logging.ts +++ b/src/mono/browser/runtime/logging.ts @@ -8,25 +8,25 @@ import { CharPtr, VoidPtr } from "./types/emscripten"; let prefix = "MONO_WASM: "; -export function set_thread_prefix(threadPrefix: string) { +export function set_thread_prefix (threadPrefix: string) { prefix = `[${threadPrefix}] MONO_WASM: `; } -export function mono_log_debug(msg: string, ...data: any) { +export function mono_log_debug (msg: string, ...data: any) { if (runtimeHelpers.diagnosticTracing) { console.debug(prefix + msg, ...data); } } -export function mono_log_info(msg: string, ...data: any) { +export function mono_log_info (msg: string, ...data: any) { console.info(prefix + msg, ...data); } -export function mono_log_warn(msg: string, ...data: any) { +export function mono_log_warn (msg: string, ...data: any) { console.warn(prefix + msg, ...data); } -export function mono_log_error(msg: string, ...data: any) { +export function mono_log_error (msg: string, ...data: any) { if (data && data.length > 0 && data[0] && typeof data[0] === "object" && data[0].silent) { // don't log silent errors return; @@ -53,7 +53,7 @@ regexes.push(/(?[a-z]+:\/\/[^ )]*:wasm-function\[(?\d+) //# .wasm-function[8962] regexes.push(/(?<[^ >]+>[.:]wasm-function\[(?[0-9]+)\])/); -export function mono_wasm_symbolicate_string(message: string): string { +export function mono_wasm_symbolicate_string (message: string): string { try { performDeferredSymbolMapParsing(); @@ -92,7 +92,7 @@ export function mono_wasm_symbolicate_string(message: string): string { } } -export function mono_wasm_stringify_as_error_with_stack(reason: any): string { +export function mono_wasm_stringify_as_error_with_stack (reason: any): string { let stack: string; if (typeof reason === "string") { stack = reason; @@ -106,7 +106,7 @@ export function mono_wasm_stringify_as_error_with_stack(reason: any): string { return mono_wasm_symbolicate_string(stack); } -export function mono_wasm_trace_logger(log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { +export function mono_wasm_trace_logger (log_domain_ptr: CharPtr, log_level_ptr: CharPtr, message_ptr: CharPtr, fatal: number, user_data: VoidPtr): void { const origMessage = utf8ToString(message_ptr); const isFatal = !!fatal; const domain = utf8ToString(log_domain_ptr); @@ -144,7 +144,7 @@ export function mono_wasm_trace_logger(log_domain_ptr: CharPtr, log_level_ptr: C } -export function parseSymbolMapFile(text: string) { +export function parseSymbolMapFile (text: string) { // Symbol map parsing is very expensive, so doing it during startup is wasteful // instead, we defer it until the first time the symbol map is needed - which // may be never @@ -153,7 +153,7 @@ export function parseSymbolMapFile(text: string) { mono_log_debug(`Deferred loading of ${text.length}ch symbol map`); } -function performDeferredSymbolMapParsing() { +function performDeferredSymbolMapParsing () { if (!wasm_pending_symbol_table) return; @@ -174,11 +174,11 @@ function performDeferredSymbolMapParsing() { } } -export function mono_wasm_get_func_id_to_name_mappings() { +export function mono_wasm_get_func_id_to_name_mappings () { performDeferredSymbolMapParsing(); return [...wasm_func_map.values()]; } -export function mono_wasm_console_clear() { +export function mono_wasm_console_clear () { console.clear(); } diff --git a/src/mono/browser/runtime/managed-exports.ts b/src/mono/browser/runtime/managed-exports.ts index 52b6391f1cc18a..f90fbb049d1504 100644 --- a/src/mono/browser/runtime/managed-exports.ts +++ b/src/mono/browser/runtime/managed-exports.ts @@ -18,7 +18,7 @@ import { mono_log_debug } from "./logging"; const managedExports: ManagedExports = {} as any; -export function init_managed_exports(): void { +export function init_managed_exports (): void { const exports_fqn_asm = "System.Runtime.InteropServices.JavaScript"; // TODO https://github.com/dotnet/runtime/issues/98366 runtimeHelpers.runtime_interop_module = cwraps.mono_wasm_assembly_load(exports_fqn_asm); @@ -44,7 +44,7 @@ export function init_managed_exports(): void { } // the marshaled signature is: Task? CallEntrypoint(char* mainAssemblyName, string[] args) -export function call_entry_point(main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { +export function call_entry_point (main_assembly_name: string, program_args: string[] | undefined, waitForDebugger: boolean): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -79,7 +79,7 @@ export function call_entry_point(main_assembly_name: string, program_args: strin } // the marshaled signature is: void LoadSatelliteAssembly(byte[] dll) -export function load_satellite_assembly(dll: Uint8Array): void { +export function load_satellite_assembly (dll: Uint8Array): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -95,7 +95,7 @@ export function load_satellite_assembly(dll: Uint8Array): void { } // the marshaled signature is: void LoadLazyAssembly(byte[] dll, byte[] pdb) -export function load_lazy_assembly(dll: Uint8Array, pdb: Uint8Array | null): void { +export function load_lazy_assembly (dll: Uint8Array, pdb: Uint8Array | null): void { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -114,7 +114,7 @@ export function load_lazy_assembly(dll: Uint8Array, pdb: Uint8Array | null): voi } // the marshaled signature is: void ReleaseJSOwnedObjectByGCHandle(GCHandle gcHandle) -export function release_js_owned_object_by_gc_handle(gc_handle: GCHandle) { +export function release_js_owned_object_by_gc_handle (gc_handle: GCHandle) { mono_assert(gc_handle, "Must be valid gc_handle"); loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); @@ -137,7 +137,7 @@ export function release_js_owned_object_by_gc_handle(gc_handle: GCHandle) { } // the marshaled signature is: void CompleteTask(GCHandle holder, Exception? exceptionResult, T? result) -export function complete_task(holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { +export function complete_task (holder_gc_handle: GCHandle, error?: any, data?: any, res_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -162,7 +162,7 @@ export function complete_task(holder_gc_handle: GCHandle, error?: any, data?: an } // the marshaled signature is: TRes? CallDelegate(GCHandle callback, T1? arg1, T2? arg2, T3? arg3) -export function call_delegate(callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { +export function call_delegate (callback_gc_handle: GCHandle, arg1_js: any, arg2_js: any, arg3_js: any, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) { loaderHelpers.assert_runtime_running(); if (WasmEnableThreads) { if (runtimeHelpers.config.jsThreadInteropMode == JSThreadInteropMode.NoSyncJSInterop) { @@ -206,7 +206,7 @@ export function call_delegate(callback_gc_handle: GCHandle, arg1_js: any, arg2_j } // the marshaled signature is: string GetManagedStackTrace(GCHandle exception) -export function get_managed_stack_trace(exception_gc_handle: GCHandle) { +export function get_managed_stack_trace (exception_gc_handle: GCHandle) { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -226,7 +226,7 @@ export function get_managed_stack_trace(exception_gc_handle: GCHandle) { } // GCHandle InstallMainSynchronizationContext(nint jsNativeTID, JSThreadBlockingMode jsThreadBlockingMode, JSThreadInteropMode jsThreadInteropMode, MainThreadingMode mainThreadingMode) -export function install_main_synchronization_context(jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { +export function install_main_synchronization_context (jsThreadBlockingMode: number, jsThreadInteropMode: number, mainThreadingMode: number): GCHandle { if (!WasmEnableThreads) return GCHandleNull; assert_c_interop(); @@ -259,7 +259,7 @@ export function install_main_synchronization_context(jsThreadBlockingMode: numbe } } -export function invoke_async_jsexport(managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { +export function invoke_async_jsexport (managedTID: PThreadPtr, method: MonoMethod, args: JSMarshalerArguments, size: number): void { assert_js_interop(); if (!WasmEnableThreads || runtimeHelpers.isManagedRunningOnCurrentThread) { cwraps.mono_wasm_invoke_jsexport(method, args as any); @@ -276,7 +276,7 @@ export function invoke_async_jsexport(managedTID: PThreadPtr, method: MonoMethod } } -export function invoke_sync_jsexport(method: MonoMethod, args: JSMarshalerArguments): void { +export function invoke_sync_jsexport (method: MonoMethod, args: JSMarshalerArguments): void { assert_js_interop(); if (!WasmEnableThreads) { cwraps.mono_wasm_invoke_jsexport(method, args as any); @@ -301,7 +301,7 @@ export function invoke_sync_jsexport(method: MonoMethod, args: JSMarshalerArgume } // the marshaled signature is: Task BindAssemblyExports(string assemblyName) -export function bind_assembly_exports(assemblyName: string): Promise { +export function bind_assembly_exports (assemblyName: string): Promise { loaderHelpers.assert_runtime_running(); const sp = Module.stackSave(); try { @@ -329,7 +329,7 @@ export function bind_assembly_exports(assemblyName: string): Promise { } -function get_method(method_name: string): MonoMethod { +function get_method (method_name: string): MonoMethod { // TODO https://github.com/dotnet/runtime/issues/98366 const res = cwraps.mono_wasm_assembly_find_method(runtimeHelpers.runtime_interop_exports_class, method_name, -1); if (!res) diff --git a/src/mono/browser/runtime/marshal-to-cs.ts b/src/mono/browser/runtime/marshal-to-cs.ts index 6254e3f20b4844..6e954ae983df39 100644 --- a/src/mono/browser/runtime/marshal-to-cs.ts +++ b/src/mono/browser/runtime/marshal-to-cs.ts @@ -26,7 +26,7 @@ import { gc_locked } from "./gc-lock"; export const jsinteropDoc = "For more information see https://aka.ms/dotnet-wasm-jsinterop"; -export function initialize_marshalers_to_cs(): void { +export function initialize_marshalers_to_cs (): void { if (js_to_cs_marshalers.size == 0) { js_to_cs_marshalers.set(MarshalerType.Array, marshal_array_to_cs); js_to_cs_marshalers.set(MarshalerType.Span, _marshal_span_to_cs); @@ -60,7 +60,7 @@ export function initialize_marshalers_to_cs(): void { } } -export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { +export function bind_arg_marshal_to_cs (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -87,7 +87,7 @@ export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: Mar }; } -export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): MarshalerToCs | undefined { +export function get_marshaler_to_cs_by_type (marshaler_type: MarshalerType): MarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -96,7 +96,7 @@ export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): Mars return converter; } -export function marshal_bool_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_bool_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -105,7 +105,7 @@ export function marshal_bool_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_byte_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_byte_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -114,7 +114,7 @@ function _marshal_byte_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_char_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_char_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -123,7 +123,7 @@ function _marshal_char_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int16_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int16_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -132,7 +132,7 @@ function _marshal_int16_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int32_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int32_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -141,7 +141,7 @@ function _marshal_int32_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_int52_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_int52_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -150,7 +150,7 @@ function _marshal_int52_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_bigint64_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_bigint64_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -159,7 +159,7 @@ function _marshal_bigint64_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_double_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_double_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -168,7 +168,7 @@ function _marshal_double_to_cs(arg: JSMarshalerArgument, value: any): void { } } -function _marshal_float_to_cs(arg: JSMarshalerArgument, value: any): void { +function _marshal_float_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -177,7 +177,7 @@ function _marshal_float_to_cs(arg: JSMarshalerArgument, value: any): void { } } -export function marshal_intptr_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_intptr_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -186,7 +186,7 @@ export function marshal_intptr_to_cs(arg: JSMarshalerArgument, value: any): void } } -function _marshal_date_time_to_cs(arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_to_cs (arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -196,7 +196,7 @@ function _marshal_date_time_to_cs(arg: JSMarshalerArgument, value: Date): void { } } -function _marshal_date_time_offset_to_cs(arg: JSMarshalerArgument, value: Date): void { +function _marshal_date_time_offset_to_cs (arg: JSMarshalerArgument, value: Date): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -206,7 +206,7 @@ function _marshal_date_time_offset_to_cs(arg: JSMarshalerArgument, value: Date): } } -export function marshal_string_to_cs(arg: JSMarshalerArgument, value: string) { +export function marshal_string_to_cs (arg: JSMarshalerArgument, value: string) { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -216,7 +216,7 @@ export function marshal_string_to_cs(arg: JSMarshalerArgument, value: string) { } } -function _marshal_string_to_cs_impl(arg: JSMarshalerArgument, value: string) { +function _marshal_string_to_cs_impl (arg: JSMarshalerArgument, value: string) { if (WasmEnableJsInteropByValue) { const bufferLen = value.length * 2; const buffer = Module._malloc(bufferLen);// together with Marshal.FreeHGlobal @@ -233,11 +233,11 @@ function _marshal_string_to_cs_impl(arg: JSMarshalerArgument, value: string) { } } -function _marshal_null_to_cs(arg: JSMarshalerArgument) { +function _marshal_null_to_cs (arg: JSMarshalerArgument) { set_arg_type(arg, MarshalerType.None); } -function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { +function _marshal_function_to_cs (arg: JSMarshalerArgument, value: Function, _?: MarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); return; @@ -245,7 +245,7 @@ function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: mono_check(value && value instanceof Function, "Value is not a Function"); // TODO: we could try to cache value -> existing JSHandle - const wrapper: any = function delegate_wrapper(args: JSMarshalerArguments) { + const wrapper: any = function delegate_wrapper (args: JSMarshalerArguments) { const exc = get_arg(args, 0); const res = get_arg(args, 1); const arg1 = get_arg(args, 2); @@ -295,7 +295,7 @@ function _marshal_function_to_cs(arg: JSMarshalerArgument, value: Function, _?: } -function _marshal_task_to_cs(arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { +function _marshal_task_to_cs (arg: JSMarshalerArgument, value: Promise, _?: MarshalerType, res_converter?: MarshalerToCs) { const handleIsPreallocated = get_arg_type(arg) == MarshalerType.TaskPreCreated; if (value === null || value === undefined) { if (WasmEnableThreads && handleIsPreallocated) { @@ -329,7 +329,7 @@ function _marshal_task_to_cs(arg: JSMarshalerArgument, value: Promise, _?: value.then(data => holder.resolve(data), reason => holder.reject(reason)); } -export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_exception_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else if (value instanceof ManagedError) { @@ -355,7 +355,7 @@ export function marshal_exception_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_js_object_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_js_object_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); @@ -373,7 +373,7 @@ export function marshal_js_object_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): void { +export function marshal_cs_object_to_cs (arg: JSMarshalerArgument, value: any): void { if (value === undefined || value === null) { set_arg_type(arg, MarshalerType.None); set_arg_proxy_context(arg); @@ -445,12 +445,12 @@ export function marshal_cs_object_to_cs(arg: JSMarshalerArgument, value: any): v } } -export function marshal_array_to_cs(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { +export function marshal_array_to_cs (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); marshal_array_to_cs_impl(arg, value, element_type); } -export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { +export function marshal_array_to_cs_impl (arg: JSMarshalerArgument, value: Array | TypedArray | undefined | null, element_type: MarshalerType): void { if (value === null || value === undefined) { set_arg_type(arg, MarshalerType.None); } else { @@ -510,7 +510,7 @@ export function marshal_array_to_cs_impl(arg: JSMarshalerArgument, value: Array< } } -function _marshal_span_to_cs(arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { +function _marshal_span_to_cs (arg: JSMarshalerArgument, value: Span, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); mono_check(!value.isDisposed, "ObjectDisposedException"); checkViewType(element_type, value._viewType); @@ -521,7 +521,7 @@ function _marshal_span_to_cs(arg: JSMarshalerArgument, value: Span, element_type } // this only supports round-trip -function _marshal_array_segment_to_cs(arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { +function _marshal_array_segment_to_cs (arg: JSMarshalerArgument, value: ArraySegment, element_type?: MarshalerType): void { mono_assert(!!element_type, "Expected valid element_type parameter"); const gc_handle = assert_not_disposed(value); mono_assert(gc_handle, "Only roundtrip of ArraySegment instance created by C#"); @@ -532,7 +532,7 @@ function _marshal_array_segment_to_cs(arg: JSMarshalerArgument, value: ArraySegm set_gc_handle(arg, gc_handle); } -function checkViewType(element_type: MarshalerType, viewType: MemoryViewType) { +function checkViewType (element_type: MarshalerType, viewType: MemoryViewType) { if (element_type == MarshalerType.Byte) { mono_check(MemoryViewType.Byte == viewType, "Expected MemoryViewType.Byte"); } else if (element_type == MarshalerType.Int32) { diff --git a/src/mono/browser/runtime/marshal-to-js.ts b/src/mono/browser/runtime/marshal-to-js.ts index fc965f81c4978b..1cc4575bf55b87 100644 --- a/src/mono/browser/runtime/marshal-to-js.ts +++ b/src/mono/browser/runtime/marshal-to-js.ts @@ -26,7 +26,7 @@ import { gc_locked } from "./gc-lock"; import { mono_log_debug } from "./logging"; import { invoke_later_when_on_ui_thread_async } from "./invoke-js"; -export function initialize_marshalers_to_js(): void { +export function initialize_marshalers_to_js (): void { if (cs_to_js_marshalers.size == 0) { cs_to_js_marshalers.set(MarshalerType.Array, _marshal_array_to_js); cs_to_js_marshalers.set(MarshalerType.Span, _marshal_span_to_js); @@ -61,7 +61,7 @@ export function initialize_marshalers_to_js(): void { } } -export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { +export function bind_arg_marshal_to_js (sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void || marshaler_type === MarshalerType.Discard || marshaler_type === MarshalerType.DiscardNoWait) { return undefined; } @@ -89,7 +89,7 @@ export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: Mar }; } -export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): MarshalerToJs | undefined { +export function get_marshaler_to_js_by_type (marshaler_type: MarshalerType): MarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { return undefined; } @@ -98,7 +98,7 @@ export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): Mars return converter; } -function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { +function _marshal_bool_to_js (arg: JSMarshalerArgument): boolean | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -106,7 +106,7 @@ function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { return get_arg_bool(arg); } -function _marshal_byte_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_byte_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -114,7 +114,7 @@ function _marshal_byte_to_js(arg: JSMarshalerArgument): number | null { return get_arg_u8(arg); } -function _marshal_char_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_char_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -122,7 +122,7 @@ function _marshal_char_to_js(arg: JSMarshalerArgument): number | null { return get_arg_u16(arg); } -function _marshal_int16_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_int16_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -130,7 +130,7 @@ function _marshal_int16_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i16(arg); } -export function marshal_int32_to_js(arg: JSMarshalerArgument): number | null { +export function marshal_int32_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -138,7 +138,7 @@ export function marshal_int32_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i32(arg); } -function _marshal_int52_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_int52_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -146,7 +146,7 @@ function _marshal_int52_to_js(arg: JSMarshalerArgument): number | null { return get_arg_i52(arg); } -function _marshal_bigint64_to_js(arg: JSMarshalerArgument): bigint | null { +function _marshal_bigint64_to_js (arg: JSMarshalerArgument): bigint | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -154,7 +154,7 @@ function _marshal_bigint64_to_js(arg: JSMarshalerArgument): bigint | null { return get_arg_i64_big(arg); } -function _marshal_float_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_float_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -162,7 +162,7 @@ function _marshal_float_to_js(arg: JSMarshalerArgument): number | null { return get_arg_f32(arg); } -function _marshal_double_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_double_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -170,7 +170,7 @@ function _marshal_double_to_js(arg: JSMarshalerArgument): number | null { return get_arg_f64(arg); } -function _marshal_intptr_to_js(arg: JSMarshalerArgument): number | null { +function _marshal_intptr_to_js (arg: JSMarshalerArgument): number | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -178,11 +178,11 @@ function _marshal_intptr_to_js(arg: JSMarshalerArgument): number | null { return get_arg_intptr(arg); } -function _marshal_null_to_js(): null { +function _marshal_null_to_js (): null { return null; } -function _marshal_datetime_to_js(arg: JSMarshalerArgument): Date | null { +function _marshal_datetime_to_js (arg: JSMarshalerArgument): Date | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -191,7 +191,7 @@ function _marshal_datetime_to_js(arg: JSMarshalerArgument): Date | null { } // NOTE: at the moment, this can't dispatch async calls (with Task/Promise return type). Therefore we don't have to worry about pre-created Task. -function _marshal_delegate_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { +function _marshal_delegate_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs): Function | null { const type = get_arg_type(arg); if (type === MarshalerType.None) { return null; @@ -223,11 +223,11 @@ function _marshal_delegate_to_js(arg: JSMarshalerArgument, _?: MarshalerType, re } export class TaskHolder { - constructor(public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { + constructor (public promise: Promise, public resolve_or_reject: (type: MarshalerType, js_handle: JSHandle, argInner: JSMarshalerArgument) => void) { } } -export function marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { const type = get_arg_type(arg); // this path is used only when Task is passed as argument to JSImport and virtual JSHandle would be used mono_assert(type != MarshalerType.TaskPreCreated, "Unexpected Task type: TaskPreCreated"); @@ -248,7 +248,7 @@ export function marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, return holder.promise; } -export function begin_marshal_task_to_js(arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { +export function begin_marshal_task_to_js (arg: JSMarshalerArgument, _?: MarshalerType, res_converter?: MarshalerToJs): Promise | null { // this path is used when Task is returned from JSExport/call_entry_point const holder = create_task_holder(res_converter); const js_handle = mono_wasm_get_js_handle(holder); @@ -260,7 +260,7 @@ export function begin_marshal_task_to_js(arg: JSMarshalerArgument, _?: Marshaler return holder.promise; } -export function end_marshal_task_to_js(args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { +export function end_marshal_task_to_js (args: JSMarshalerArguments, res_converter: MarshalerToJs | undefined, eagerPromise: Promise | null) { // this path is used when Task is returned from JSExport/call_entry_point const res = get_arg(args, 1); const type = get_arg_type(res); @@ -283,7 +283,7 @@ export function end_marshal_task_to_js(args: JSMarshalerArguments, res_converter return promise; } -function try_marshal_sync_task_to_js(arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { +function try_marshal_sync_task_to_js (arg: JSMarshalerArgument, type: MarshalerType, res_converter?: MarshalerToJs): Promise | null | false { if (type === MarshalerType.None) { return null; } @@ -309,7 +309,7 @@ function try_marshal_sync_task_to_js(arg: JSMarshalerArgument, type: MarshalerTy return false; } -function create_task_holder(res_converter?: MarshalerToJs) { +function create_task_holder (res_converter?: MarshalerToJs) { const { promise, promise_control } = loaderHelpers.createPromiseController(); const holder = new TaskHolder(promise, (type, js_handle, argInner) => { if (type === MarshalerType.TaskRejected) { @@ -337,11 +337,11 @@ function create_task_holder(res_converter?: MarshalerToJs) { return holder; } -export function mono_wasm_resolve_or_reject_promise(args: JSMarshalerArguments): void { +export function mono_wasm_resolve_or_reject_promise (args: JSMarshalerArguments): void { // rejection/resolution should not arrive earlier than the promise created by marshaling in mono_wasm_invoke_jsimport_MT invoke_later_when_on_ui_thread_async(() => mono_wasm_resolve_or_reject_promise_impl(args)); } -export function mono_wasm_resolve_or_reject_promise_impl(args: JSMarshalerArguments): void { +export function mono_wasm_resolve_or_reject_promise_impl (args: JSMarshalerArguments): void { if (!loaderHelpers.is_runtime_running()) { mono_log_debug("This promise resolution/rejection can't be propagated to managed code, mono runtime already exited."); return; @@ -378,7 +378,7 @@ export function mono_wasm_resolve_or_reject_promise_impl(args: JSMarshalerArgume } } -export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { +export function marshal_string_to_js (arg: JSMarshalerArgument): string | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -400,7 +400,7 @@ export function marshal_string_to_js(arg: JSMarshalerArgument): string | null { } } -export function marshal_exception_to_js(arg: JSMarshalerArgument): Error | null { +export function marshal_exception_to_js (arg: JSMarshalerArgument): Error | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -428,7 +428,7 @@ export function marshal_exception_to_js(arg: JSMarshalerArgument): Error | null return result; } -function _marshal_js_object_to_js(arg: JSMarshalerArgument): any { +function _marshal_js_object_to_js (arg: JSMarshalerArgument): any { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -439,7 +439,7 @@ function _marshal_js_object_to_js(arg: JSMarshalerArgument): any { return js_obj; } -function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { +function _marshal_cs_object_to_js (arg: JSMarshalerArgument): any { const marshaler_type = get_arg_type(arg); if (marshaler_type == MarshalerType.None) { return null; @@ -482,12 +482,12 @@ function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { return converter(arg); } -function _marshal_array_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Array | TypedArray | null { mono_assert(!!element_type, "Expected valid element_type parameter"); return _marshal_array_to_js_impl(arg, element_type); } -function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { +function _marshal_array_to_js_impl (arg: JSMarshalerArgument, element_type: MarshalerType): Array | TypedArray | null { const type = get_arg_type(arg); if (type == MarshalerType.None) { return null; @@ -539,7 +539,7 @@ function _marshal_array_to_js_impl(arg: JSMarshalerArgument, element_type: Marsh return result; } -function _marshal_span_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): Span { +function _marshal_span_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): Span { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); @@ -557,7 +557,7 @@ function _marshal_span_to_js(arg: JSMarshalerArgument, element_type?: MarshalerT return result; } -function _marshal_array_segment_to_js(arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { +function _marshal_array_segment_to_js (arg: JSMarshalerArgument, element_type?: MarshalerType): ArraySegment { mono_assert(!!element_type, "Expected valid element_type parameter"); const buffer_ptr = get_arg_intptr(arg); diff --git a/src/mono/browser/runtime/marshal.ts b/src/mono/browser/runtime/marshal.ts index c2afc7ae6a57c7..7ea48993b04104 100644 --- a/src/mono/browser/runtime/marshal.ts +++ b/src/mono/browser/runtime/marshal.ts @@ -64,7 +64,7 @@ const enum JSBindingHeaderOffsets { Result = 64, } -export function alloc_stack_frame(size: number): JSMarshalerArguments { +export function alloc_stack_frame (size: number): JSMarshalerArguments { if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); } @@ -75,41 +75,41 @@ export function alloc_stack_frame(size: number): JSMarshalerArguments { return args; } -export function get_arg(args: JSMarshalerArguments, index: number): JSMarshalerArgument { +export function get_arg (args: JSMarshalerArguments, index: number): JSMarshalerArgument { mono_assert(args, "Null args"); return args + (index * JavaScriptMarshalerArgSize); } -export function is_args_exception(args: JSMarshalerArguments): boolean { +export function is_args_exception (args: JSMarshalerArguments): boolean { mono_assert(args, "Null args"); const exceptionType = get_arg_type(args); return exceptionType !== MarshalerType.None; } -export function is_receiver_should_free(args: JSMarshalerArguments): boolean { +export function is_receiver_should_free (args: JSMarshalerArguments): boolean { if (!WasmEnableThreads) return false; mono_assert(args, "Null args"); return getB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree); } -export function get_sync_done_semaphore_ptr(args: JSMarshalerArguments): VoidPtr { +export function get_sync_done_semaphore_ptr (args: JSMarshalerArguments): VoidPtr { if (!WasmEnableThreads) return VoidPtrNull; mono_assert(args, "Null args"); return getI32(args + JSMarshalerArgumentOffsets.SyncDoneSemaphorePtr) as any; } -export function get_caller_native_tid(args: JSMarshalerArguments): PThreadPtr { +export function get_caller_native_tid (args: JSMarshalerArguments): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; mono_assert(args, "Null args"); return getI32(args + JSMarshalerArgumentOffsets.CallerNativeTID) as any; } -export function set_receiver_should_free(args: JSMarshalerArguments): void { +export function set_receiver_should_free (args: JSMarshalerArguments): void { mono_assert(args, "Null args"); setB32(args + JSMarshalerArgumentOffsets.ReceiverShouldFree, true); } -export function set_args_context(args: JSMarshalerArguments): void { +export function set_args_context (args: JSMarshalerArguments): void { if (!WasmEnableThreads) return; mono_assert(args, "Null args"); const exc = get_arg(args, 0); @@ -118,52 +118,52 @@ export function set_args_context(args: JSMarshalerArguments): void { set_arg_proxy_context(res); } -export function get_sig(signature: JSFunctionSignature, index: number): JSMarshalerType { +export function get_sig (signature: JSFunctionSignature, index: number): JSMarshalerType { mono_assert(signature, "Null signatures"); return signature + (index * JSMarshalerTypeSize) + JSMarshalerSignatureHeaderSize; } -export function get_signature_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Type); } -export function get_signature_res_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_res_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.ResultMarshalerType); } -export function get_signature_arg1_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg1_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg1MarshalerType); } -export function get_signature_arg2_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg2_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_arg3_type(sig: JSMarshalerType): MarshalerType { +export function get_signature_arg3_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null sig"); return getU8(sig + JSBindingTypeOffsets.Arg2MarshalerType); } -export function get_signature_argument_count(signature: JSFunctionSignature): number { +export function get_signature_argument_count (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ArgumentCount); } -export function get_signature_version(signature: JSFunctionSignature): number { +export function get_signature_version (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.Version); } -export function get_signature_handle(signature: JSFunctionSignature): number { +export function get_signature_handle (signature: JSFunctionSignature): number { mono_assert(signature, "Null signatures"); return getI32(signature + JSBindingHeaderOffsets.ImportHandle); } -export function get_signature_function_name(signature: JSFunctionSignature): string | null { +export function get_signature_function_name (signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const functionNameOffset = getI32(signature + JSBindingHeaderOffsets.FunctionNameOffset); if (functionNameOffset === 0) return null; @@ -172,7 +172,7 @@ export function get_signature_function_name(signature: JSFunctionSignature): str return utf16ToString(signature + functionNameOffset, signature + functionNameOffset + functionNameLength); } -export function get_signature_module_name(signature: JSFunctionSignature): string | null { +export function get_signature_module_name (signature: JSFunctionSignature): string | null { mono_assert(signature, "Null signatures"); const moduleNameOffset = getI32(signature + JSBindingHeaderOffsets.ModuleNameOffset); if (moduleNameOffset === 0) return null; @@ -180,195 +180,195 @@ export function get_signature_module_name(signature: JSFunctionSignature): strin return utf16ToString(signature + moduleNameOffset, signature + moduleNameOffset + moduleNameLength); } -export function get_sig_type(sig: JSMarshalerType): MarshalerType { +export function get_sig_type (sig: JSMarshalerType): MarshalerType { mono_assert(sig, "Null signatures"); return getU8(sig); } -export function get_arg_type(arg: JSMarshalerArgument): MarshalerType { +export function get_arg_type (arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.Type); return type; } -export function get_arg_element_type(arg: JSMarshalerArgument): MarshalerType { +export function get_arg_element_type (arg: JSMarshalerArgument): MarshalerType { mono_assert(arg, "Null arg"); const type = getU8(arg + JSMarshalerArgumentOffsets.ElementType); return type; } -export function set_arg_type(arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_type (arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.Type, type); } -export function set_arg_element_type(arg: JSMarshalerArgument, type: MarshalerType): void { +export function set_arg_element_type (arg: JSMarshalerArgument, type: MarshalerType): void { mono_assert(arg, "Null arg"); setU8(arg + JSMarshalerArgumentOffsets.ElementType, type); } -export function get_arg_bool(arg: JSMarshalerArgument): boolean { +export function get_arg_bool (arg: JSMarshalerArgument): boolean { mono_assert(arg, "Null arg"); return !!getU8(arg); } -export function get_arg_u8(arg: JSMarshalerArgument): number { +export function get_arg_u8 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU8(arg); } -export function get_arg_u16(arg: JSMarshalerArgument): number { +export function get_arg_u16 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getU16(arg); } -export function get_arg_i16(arg: JSMarshalerArgument): number { +export function get_arg_i16 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI16(arg); } -export function get_arg_i32(arg: JSMarshalerArgument): number { +export function get_arg_i32 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_intptr(arg: JSMarshalerArgument): number { +export function get_arg_intptr (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg); } -export function get_arg_i52(arg: JSMarshalerArgument): number { +export function get_arg_i52 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); // we know that the range check and conversion from Int64 was be done on C# side return getF64(arg); } -export function get_arg_i64_big(arg: JSMarshalerArgument): bigint { +export function get_arg_i64_big (arg: JSMarshalerArgument): bigint { mono_assert(arg, "Null arg"); return getI64Big(arg); } -export function get_arg_date(arg: JSMarshalerArgument): Date { +export function get_arg_date (arg: JSMarshalerArgument): Date { mono_assert(arg, "Null arg"); const unixTime = getF64(arg); const date = new Date(unixTime); return date; } -export function get_arg_f32(arg: JSMarshalerArgument): number { +export function get_arg_f32 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF32(arg); } -export function get_arg_f64(arg: JSMarshalerArgument): number { +export function get_arg_f64 (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getF64(arg); } -export function set_arg_bool(arg: JSMarshalerArgument, value: boolean): void { +export function set_arg_bool (arg: JSMarshalerArgument, value: boolean): void { mono_assert(arg, "Null arg"); mono_check(typeof value === "boolean", () => `Value is not a Boolean: ${value} (${typeof (value)})`); setB32(arg, value ? 1 : 0); } -export function set_arg_u8(arg: JSMarshalerArgument, value: number): void { +export function set_arg_u8 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU8(arg, value); } -export function set_arg_u16(arg: JSMarshalerArgument, value: number): void { +export function set_arg_u16 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setU16(arg, value); } -export function set_arg_i16(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i16 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI16(arg, value); } -export function set_arg_i32(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i32 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_intptr(arg: JSMarshalerArgument, value: VoidPtr): void { +export function set_arg_intptr (arg: JSMarshalerArgument, value: VoidPtr): void { mono_assert(arg, "Null arg"); setI32(arg, value); } -export function set_arg_i52(arg: JSMarshalerArgument, value: number): void { +export function set_arg_i52 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); // we know that conversion to Int64 would be done on C# side setF64(arg, value); } -export function set_arg_i64_big(arg: JSMarshalerArgument, value: bigint): void { +export function set_arg_i64_big (arg: JSMarshalerArgument, value: bigint): void { mono_assert(arg, "Null arg"); setI64Big(arg, value); } -export function set_arg_date(arg: JSMarshalerArgument, value: Date): void { +export function set_arg_date (arg: JSMarshalerArgument, value: Date): void { mono_assert(arg, "Null arg"); // getTime() is always UTC const unixTime = value.getTime(); setF64(arg, unixTime); } -export function set_arg_f64(arg: JSMarshalerArgument, value: number): void { +export function set_arg_f64 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF64(arg, value); } -export function set_arg_f32(arg: JSMarshalerArgument, value: number): void { +export function set_arg_f32 (arg: JSMarshalerArgument, value: number): void { mono_assert(arg, "Null arg"); setF32(arg, value); } -export function get_arg_js_handle(arg: JSMarshalerArgument): JSHandle { +export function get_arg_js_handle (arg: JSMarshalerArgument): JSHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.JSHandle); } -export function set_arg_proxy_context(arg: JSMarshalerArgument): void { +export function set_arg_proxy_context (arg: JSMarshalerArgument): void { if (!WasmEnableThreads) return; mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.ContextHandle, runtimeHelpers.proxyGCHandle); } -export function set_js_handle(arg: JSMarshalerArgument, jsHandle: JSHandle): void { +export function set_js_handle (arg: JSMarshalerArgument, jsHandle: JSHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.JSHandle, jsHandle); set_arg_proxy_context(arg); } -export function get_arg_gc_handle(arg: JSMarshalerArgument): GCHandle { +export function get_arg_gc_handle (arg: JSMarshalerArgument): GCHandle { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.GCHandle); } -export function set_gc_handle(arg: JSMarshalerArgument, gcHandle: GCHandle): void { +export function set_gc_handle (arg: JSMarshalerArgument, gcHandle: GCHandle): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.GCHandle, gcHandle); set_arg_proxy_context(arg); } -export function get_string_root(arg: JSMarshalerArgument): WasmRoot { +export function get_string_root (arg: JSMarshalerArgument): WasmRoot { mono_assert(arg, "Null arg"); return mono_wasm_new_external_root(arg); } -export function get_arg_length(arg: JSMarshalerArgument): number { +export function get_arg_length (arg: JSMarshalerArgument): number { mono_assert(arg, "Null arg"); return getI32(arg + JSMarshalerArgumentOffsets.Length); } -export function set_arg_length(arg: JSMarshalerArgument, size: number): void { +export function set_arg_length (arg: JSMarshalerArgument, size: number): void { mono_assert(arg, "Null arg"); setI32(arg + JSMarshalerArgumentOffsets.Length, size); } -export function set_root(arg: JSMarshalerArgument, root: WasmRoot): void { +export function set_root (arg: JSMarshalerArgument, root: WasmRoot): void { mono_assert(arg, "Null arg"); setU32(arg + 0, root.get_address()); } @@ -379,15 +379,15 @@ export interface IDisposable { } export class ManagedObject implements IDisposable { - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } - toString(): string { + toString (): string { return `CsObject(gc_handle: ${(this)[js_owned_gc_handle_symbol]})`; } } @@ -395,7 +395,7 @@ export class ManagedObject implements IDisposable { export class ManagedError extends Error implements IDisposable { private superStack: any; private managed_stack: any; - constructor(message: string) { + constructor (message: string) { super(message); this.superStack = Object.getOwnPropertyDescriptor(this, "stack"); // this works on Chrome Object.defineProperty(this, "stack", { @@ -403,7 +403,7 @@ export class ManagedError extends Error implements IDisposable { }); } - getSuperStack() { + getSuperStack () { if (this.superStack) { if (this.superStack.value !== undefined) return this.superStack.value; @@ -413,7 +413,7 @@ export class ManagedError extends Error implements IDisposable { return super.stack; // this works on FF } - getManageStack() { + getManageStack () { if (this.managed_stack) { return this.managed_stack; } @@ -434,23 +434,23 @@ export class ManagedError extends Error implements IDisposable { return this.getSuperStack(); } - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } -export function get_signature_marshaler(signature: JSFunctionSignature, index: number): JSHandle { +export function get_signature_marshaler (signature: JSFunctionSignature, index: number): JSHandle { mono_assert(signature, "Null signatures"); const sig = get_sig(signature, index); return getU32(sig + JSBindingHeaderOffsets.ImportHandle); } -export function array_element_size(element_type: MarshalerType): number { +export function array_element_size (element_type: MarshalerType): number { return element_type == MarshalerType.Byte ? 1 : element_type == MarshalerType.Int32 ? 4 : element_type == MarshalerType.Int52 ? 8 @@ -468,13 +468,13 @@ export const enum MemoryViewType { } abstract class MemoryView implements IMemoryView { - protected constructor(public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { + protected constructor (public _pointer: VoidPtr, public _length: number, public _viewType: MemoryViewType) { } abstract dispose(): void; abstract get isDisposed(): boolean; - _unsafe_create_view(): TypedArray { + _unsafe_create_view (): TypedArray { // this view must be short lived so that it doesn't fail after wasm memory growth // for that reason we also don't give the view out to end user and provide set/slice/copyTo API instead const view = this._viewType == MemoryViewType.Byte ? new Uint8Array(localHeapViewU8().buffer, this._pointer, this._length) @@ -485,7 +485,7 @@ abstract class MemoryView implements IMemoryView { return view; } - set(source: TypedArray, targetOffset?: number): void { + set (source: TypedArray, targetOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const targetView = this._unsafe_create_view(); mono_check(source && targetView && source.constructor === targetView.constructor, () => `Expected ${targetView.constructor}`); @@ -493,7 +493,7 @@ abstract class MemoryView implements IMemoryView { // TODO consider memory write barrier } - copyTo(target: TypedArray, sourceOffset?: number): void { + copyTo (target: TypedArray, sourceOffset?: number): void { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); mono_check(target && sourceView && target.constructor === sourceView.constructor, () => `Expected ${sourceView.constructor}`); @@ -502,19 +502,19 @@ abstract class MemoryView implements IMemoryView { target.set(trimmedSource); } - slice(start?: number, end?: number): TypedArray { + slice (start?: number, end?: number): TypedArray { mono_check(!this.isDisposed, "ObjectDisposedException"); const sourceView = this._unsafe_create_view(); // TODO consider memory read barrier return sourceView.slice(start, end); } - get length(): number { + get length (): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._length; } - get byteLength(): number { + get byteLength (): number { mono_check(!this.isDisposed, "ObjectDisposedException"); return this._viewType == MemoryViewType.Byte ? this._length : this._viewType == MemoryViewType.Int32 ? this._length << 2 @@ -546,27 +546,27 @@ export interface IMemoryView extends IDisposable { export class Span extends MemoryView { private is_disposed = false; - public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose(): void { + dispose (): void { this.is_disposed = true; } - get isDisposed(): boolean { + get isDisposed (): boolean { return this.is_disposed; } } export class ArraySegment extends MemoryView { - public constructor(pointer: VoidPtr, length: number, viewType: MemoryViewType) { + public constructor (pointer: VoidPtr, length: number, viewType: MemoryViewType) { super(pointer, length, viewType); } - dispose(): void { + dispose (): void { teardown_managed_proxy(this, GCHandleNull); } - get isDisposed(): boolean { + get isDisposed (): boolean { return (this)[js_owned_gc_handle_symbol] === GCHandleNull; } } diff --git a/src/mono/browser/runtime/memory.ts b/src/mono/browser/runtime/memory.ts index f3fefb4aca39f6..af0d950d8637d8 100644 --- a/src/mono/browser/runtime/memory.ts +++ b/src/mono/browser/runtime/memory.ts @@ -13,7 +13,7 @@ const alloca_stack: Array = []; const alloca_buffer_size = 32 * 1024; let alloca_base: VoidPtr, alloca_offset: VoidPtr, alloca_limit: VoidPtr; -function _ensure_allocated(): void { +function _ensure_allocated (): void { if (alloca_base) return; alloca_base = Module._malloc(alloca_buffer_size); @@ -24,7 +24,7 @@ function _ensure_allocated(): void { const max_int64_big = BigInt("9223372036854775807"); const min_int64_big = BigInt("-9223372036854775808"); -export function temp_malloc(size: number): VoidPtr { +export function temp_malloc (size: number): VoidPtr { _ensure_allocated(); if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -36,12 +36,12 @@ export function temp_malloc(size: number): VoidPtr { return result; } -export function _create_temp_frame(): void { +export function _create_temp_frame (): void { _ensure_allocated(); alloca_stack.push(alloca_offset); } -export function _release_temp_frame(): void { +export function _release_temp_frame (): void { if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); @@ -49,16 +49,16 @@ export function _release_temp_frame(): void { } -function assert_int_in_range(value: Number, min: Number, max: Number) { +function assert_int_in_range (value: Number, min: Number, max: Number) { mono_check(Number.isSafeInteger(value), () => `Value is not an integer: ${value} (${typeof (value)})`); mono_check(value >= min && value <= max, () => `Overflow: value ${value} is out of ${min} ${max} range`); } -export function _zero_region(byteOffset: VoidPtr, sizeBytes: number): void { +export function _zero_region (byteOffset: VoidPtr, sizeBytes: number): void { localHeapViewU8().fill(0, byteOffset, byteOffset + sizeBytes); } -export function setB32(offset: MemOffset, value: number | boolean): void { +export function setB32 (offset: MemOffset, value: number | boolean): void { receiveWorkerHeapViews(); const boolValue = !!value; if (typeof (value) === "number") @@ -66,64 +66,64 @@ export function setB32(offset: MemOffset, value: number | boolean): void { Module.HEAP32[offset >>> 2] = boolValue ? 1 : 0; } -export function setU8(offset: MemOffset, value: number): void { +export function setU8 (offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFF); receiveWorkerHeapViews(); Module.HEAPU8[offset] = value; } -export function setU16(offset: MemOffset, value: number): void { +export function setU16 (offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); receiveWorkerHeapViews(); Module.HEAPU16[offset >>> 1] = value; } // does not check for growable heap -export function setU16_local(localView: Uint16Array, offset: MemOffset, value: number): void { +export function setU16_local (localView: Uint16Array, offset: MemOffset, value: number): void { assert_int_in_range(value, 0, 0xFFFF); localView[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU16_unchecked(offset: MemOffset, value: number): void { +export function setU16_unchecked (offset: MemOffset, value: number): void { Module.HEAPU16[offset >>> 1] = value; } // does not check for overflow nor growable heap -export function setU32_unchecked(offset: MemOffset, value: NumberOrPointer): void { +export function setU32_unchecked (offset: MemOffset, value: NumberOrPointer): void { Module.HEAPU32[offset >>> 2] = value; } -export function setU32(offset: MemOffset, value: NumberOrPointer): void { +export function setU32 (offset: MemOffset, value: NumberOrPointer): void { assert_int_in_range(value, 0, 0xFFFF_FFFF); receiveWorkerHeapViews(); Module.HEAPU32[offset >>> 2] = value; } -export function setI8(offset: MemOffset, value: number): void { +export function setI8 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x80, 0x7F); receiveWorkerHeapViews(); Module.HEAP8[offset] = value; } -export function setI16(offset: MemOffset, value: number): void { +export function setI16 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000, 0x7FFF); receiveWorkerHeapViews(); Module.HEAP16[offset >>> 1] = value; } -export function setI32_unchecked(offset: MemOffset, value: number): void { +export function setI32_unchecked (offset: MemOffset, value: number): void { receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -export function setI32(offset: MemOffset, value: number): void { +export function setI32 (offset: MemOffset, value: number): void { assert_int_in_range(value, -0x8000_0000, 0x7FFF_FFFF); receiveWorkerHeapViews(); Module.HEAP32[offset >>> 2] = value; } -function autoThrowI52(error: I52Error) { +function autoThrowI52 (error: I52Error) { if (error === I52Error.NONE) return; @@ -140,7 +140,7 @@ function autoThrowI52(error: I52Error) { /** * Throws for values which are not 52 bit integer. See Number.isSafeInteger() */ -export function setI52(offset: MemOffset, value: number): void { +export function setI52 (offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); const error = cwraps.mono_wasm_f64_to_i52(offset, value); @@ -150,7 +150,7 @@ export function setI52(offset: MemOffset, value: number): void { /** * Throws for values which are not 52 bit integer or are negative. See Number.isSafeInteger(). */ -export function setU52(offset: MemOffset, value: number): void { +export function setU52 (offset: MemOffset, value: number): void { mono_check(Number.isSafeInteger(value), () => `Value is not a safe integer: ${value} (${typeof (value)})`); mono_check(value >= 0, "Can't convert negative Number into UInt64"); receiveWorkerHeapViews(); @@ -158,101 +158,101 @@ export function setU52(offset: MemOffset, value: number): void { autoThrowI52(error); } -export function setI64Big(offset: MemOffset, value: bigint): void { +export function setI64Big (offset: MemOffset, value: bigint): void { mono_check(typeof value === "bigint", () => `Value is not an bigint: ${value} (${typeof (value)})`); mono_check(value >= min_int64_big && value <= max_int64_big, () => `Overflow: value ${value} is out of ${min_int64_big} ${max_int64_big} range`); Module.HEAP64[offset >>> 3] = value; } -export function setF32(offset: MemOffset, value: number): void { +export function setF32 (offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF32[offset >>> 2] = value; } -export function setF64(offset: MemOffset, value: number): void { +export function setF64 (offset: MemOffset, value: number): void { mono_check(typeof value === "number", () => `Value is not a Number: ${value} (${typeof (value)})`); receiveWorkerHeapViews(); Module.HEAPF64[offset >>> 3] = value; } -export function getB32(offset: MemOffset): boolean { +export function getB32 (offset: MemOffset): boolean { receiveWorkerHeapViews(); return !!(Module.HEAP32[offset >>> 2]); } -export function getU8(offset: MemOffset): number { +export function getU8 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU8[offset]; } -export function getU16(offset: MemOffset): number { +export function getU16 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU16[offset >>> 1]; } // does not check for growable heap -export function getU16_local(localView: Uint16Array, offset: MemOffset): number { +export function getU16_local (localView: Uint16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getU32(offset: MemOffset): number { +export function getU32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPU32[offset >>> 2]; } // does not check for growable heap -export function getU32_local(localView: Uint32Array, offset: MemOffset): number { +export function getU32_local (localView: Uint32Array, offset: MemOffset): number { return localView[offset >>> 2]; } -export function getI32_unaligned(offset: MemOffset): number { +export function getI32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset); } -export function getU32_unaligned(offset: MemOffset): number { +export function getU32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_i32_unaligned(offset) >>> 0; } -export function getF32_unaligned(offset: MemOffset): number { +export function getF32_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_f32_unaligned(offset); } -export function getF64_unaligned(offset: MemOffset): number { +export function getF64_unaligned (offset: MemOffset): number { return cwraps.mono_wasm_get_f64_unaligned(offset); } -export function getI8(offset: MemOffset): number { +export function getI8 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP8[offset]; } -export function getI16(offset: MemOffset): number { +export function getI16 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP16[offset >>> 1]; } // does not check for growable heap -export function getI16_local(localView: Int16Array, offset: MemOffset): number { +export function getI16_local (localView: Int16Array, offset: MemOffset): number { return localView[offset >>> 1]; } -export function getI32(offset: MemOffset): number { +export function getI32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAP32[offset >>> 2]; } // does not check for growable heap -export function getI32_local(localView: Int32Array, offset: MemOffset): number { +export function getI32_local (localView: Int32Array, offset: MemOffset): number { return localView[offset >>> 2]; } /** * Throws for Number.MIN_SAFE_INTEGER > value > Number.MAX_SAFE_INTEGER */ -export function getI52(offset: MemOffset): number { +export function getI52 (offset: MemOffset): number { const result = cwraps.mono_wasm_i52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); @@ -262,24 +262,24 @@ export function getI52(offset: MemOffset): number { /** * Throws for 0 > value > Number.MAX_SAFE_INTEGER */ -export function getU52(offset: MemOffset): number { +export function getU52 (offset: MemOffset): number { const result = cwraps.mono_wasm_u52_to_f64(offset, runtimeHelpers._i52_error_scratch_buffer); const error = getI32(runtimeHelpers._i52_error_scratch_buffer); autoThrowI52(error); return result; } -export function getI64Big(offset: MemOffset): bigint { +export function getI64Big (offset: MemOffset): bigint { receiveWorkerHeapViews(); return Module.HEAP64[offset >>> 3]; } -export function getF32(offset: MemOffset): number { +export function getF32 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF32[offset >>> 2]; } -export function getF64(offset: MemOffset): number { +export function getF64 (offset: MemOffset): number { receiveWorkerHeapViews(); return Module.HEAPF64[offset >>> 3]; } @@ -291,7 +291,7 @@ export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr) = export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1) => TResult, ud1: T1): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2) => TResult, ud1: T1, ud2: T2): TResult; export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1: T1, ud2: T2, ud3: T3) => TResult, ud1: T1, ud2: T2, ud3: T3): TResult; -export function withStackAlloc(bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { +export function withStackAlloc (bytesWanted: number, f: (ptr: VoidPtr, ud1?: T1, ud2?: T2, ud3?: T3) => TResult, ud1?: T1, ud2?: T2, ud3?: T3): TResult { const sp = Module.stackSave(); const ptr = Module.stackAlloc(bytesWanted); try { @@ -303,14 +303,14 @@ export function withStackAlloc(bytesWanted: number, f: (ptr // @bytes must be a typed array. space is allocated for it in the native heap // and it is copied to that location. returns the address of the allocation. -export function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr { +export function mono_wasm_load_bytes_into_heap (bytes: Uint8Array): VoidPtr { const memoryOffset = Module._malloc(bytes.length); const heapBytes = new Uint8Array(localHeapViewU8().buffer, memoryOffset, bytes.length); heapBytes.set(bytes); return memoryOffset; } -export function getEnv(name: string): string | null { +export function getEnv (name: string): string | null { let charPtr: CharPtr = 0; try { charPtr = cwraps.mono_wasm_getenv(name); @@ -322,7 +322,7 @@ export function getEnv(name: string): string | null { } } -export function compareExchangeI32(offset: MemOffset, value: number, expected: number): number { +export function compareExchangeI32 (offset: MemOffset, value: number, expected: number): number { mono_assert((offset & 3) === 0, () => `compareExchangeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) { const actual = getI32(offset); @@ -334,80 +334,80 @@ export function compareExchangeI32(offset: MemOffset, value: number, expected: n return globalThis.Atomics.compareExchange(localHeapViewI32(), offset >>> 2, expected, value); } -export function storeI32(offset: MemOffset, value: number): void { +export function storeI32 (offset: MemOffset, value: number): void { mono_assert((offset & 3) === 0, () => `storeI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return setI32(offset, value); globalThis.Atomics.store(localHeapViewI32(), offset >>> 2, value); } -export function notifyI32(offset: MemOffset, count: number): void { +export function notifyI32 (offset: MemOffset, count: number): void { mono_assert((offset & 3) === 0, () => `notifyI32: offset must be 4-byte aligned, got ${offset}`); if (!WasmEnableThreads) return; globalThis.Atomics.notify(localHeapViewI32(), offset >>> 2, count); } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI8(): Int8Array { +export function localHeapViewI8 (): Int8Array { receiveWorkerHeapViews(); return Module.HEAP8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI16(): Int16Array { +export function localHeapViewI16 (): Int16Array { receiveWorkerHeapViews(); return Module.HEAP16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI32(): Int32Array { +export function localHeapViewI32 (): Int32Array { receiveWorkerHeapViews(); return Module.HEAP32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewI64Big(): BigInt64Array { +export function localHeapViewI64Big (): BigInt64Array { receiveWorkerHeapViews(); return Module.HEAP64; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU8(): Uint8Array { +export function localHeapViewU8 (): Uint8Array { receiveWorkerHeapViews(); return Module.HEAPU8; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU16(): Uint16Array { +export function localHeapViewU16 (): Uint16Array { receiveWorkerHeapViews(); return Module.HEAPU16; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewU32(): Uint32Array { +export function localHeapViewU32 (): Uint32Array { receiveWorkerHeapViews(); return Module.HEAPU32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF32(): Float32Array { +export function localHeapViewF32 (): Float32Array { receiveWorkerHeapViews(); return Module.HEAPF32; } // returns memory view which is valid within current synchronous call stack -export function localHeapViewF64(): Float64Array { +export function localHeapViewF64 (): Float64Array { receiveWorkerHeapViews(); return Module.HEAPF64; } -export function copyBytes(srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { +export function copyBytes (srcPtr: VoidPtr, dstPtr: VoidPtr, bytes: number): void { const heap = localHeapViewU8(); heap.copyWithin(dstPtr as any, srcPtr as any, srcPtr as any + bytes); } // when we run with multithreading enabled, we need to make sure that the memory views are updated on each worker // on non-MT build, this will be a no-op trimmed by rollup -export function receiveWorkerHeapViews() { +export function receiveWorkerHeapViews () { if (!WasmEnableThreads) return; const memory = runtimeHelpers.getMemory(); if (memory.buffer !== Module.HEAPU8.buffer) { @@ -416,7 +416,7 @@ export function receiveWorkerHeapViews() { } const sharedArrayBufferDefined = typeof SharedArrayBuffer !== "undefined"; -export function isSharedArrayBuffer(buffer: any): buffer is SharedArrayBuffer { +export function isSharedArrayBuffer (buffer: any): buffer is SharedArrayBuffer { // this condition should be eliminated by rollup on non-threading builds if (!WasmEnableThreads) return false; // BEWARE: In some cases, `instanceof SharedArrayBuffer` returns false even though buffer is an SAB. @@ -430,7 +430,7 @@ Problem: When WebWorker is suspended in the browser, the other running threads c After the thread is un-suspended C code may to try to de-reference pointer which is beyond it's known view. This is likely V8 bug. We don't have direct evidence, just failed debugger unit tests with MT runtime. */ -export function forceThreadMemoryViewRefresh() { +export function forceThreadMemoryViewRefresh () { // this condition should be eliminated by rollup on non-threading builds and it would become empty method. if (!WasmEnableThreads) return; diff --git a/src/mono/browser/runtime/polyfills.ts b/src/mono/browser/runtime/polyfills.ts index 06762b21245501..8998dc37c32e5f 100644 --- a/src/mono/browser/runtime/polyfills.ts +++ b/src/mono/browser/runtime/polyfills.ts @@ -9,12 +9,12 @@ import { replaceEmscriptenTLSInit } from "./pthreads"; import { replaceEmscriptenPThreadUI } from "./pthreads"; const dummyPerformance = { - now: function() { + now: function () { return Date.now(); } }; -export function initializeReplacements(replacements: EmscriptenReplacements): void { +export function initializeReplacements (replacements: EmscriptenReplacements): void { // performance.now() is used by emscripten and doesn't work in JSC if (typeof globalThis.performance === "undefined") { globalThis.performance = dummyPerformance as any; @@ -43,12 +43,12 @@ export function initializeReplacements(replacements: EmscriptenReplacements): vo } } -export async function init_polyfills_async(): Promise { +export async function init_polyfills_async (): Promise { // v8 shell doesn't have Event and EventTarget if (WasmEnableThreads && typeof globalThis.Event === "undefined") { globalThis.Event = class Event { readonly type: string; - constructor(type: string) { + constructor (type: string) { this.type = type; } } as any; @@ -56,7 +56,7 @@ export async function init_polyfills_async(): Promise { if (WasmEnableThreads && typeof globalThis.EventTarget === "undefined") { globalThis.EventTarget = class EventTarget { private subscribers = new Map>(); - addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { + addEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions) { if (listener === undefined || listener == null) return; let oneShot = false; @@ -78,7 +78,7 @@ export async function init_polyfills_async(): Promise { } listeners.push({ listener, oneShot }); } - removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { + removeEventListener (type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions) { if (listener === undefined || listener == null) return; if (options !== undefined) { @@ -102,7 +102,7 @@ export async function init_polyfills_async(): Promise { subscribers.splice(index, 1); } } - dispatchEvent(event: Event) { + dispatchEvent (event: Event) { if (!this.subscribers.has(event.type)) { return true; } diff --git a/src/mono/browser/runtime/profiler.ts b/src/mono/browser/runtime/profiler.ts index 8dce6e31fcba2e..a223a7fdbf4a76 100644 --- a/src/mono/browser/runtime/profiler.ts +++ b/src/mono/browser/runtime/profiler.ts @@ -14,7 +14,7 @@ import { utf8ToString } from "./strings"; // sendTo defaults to 'WebAssembly.Runtime::DumpAotProfileData'. // DumpAotProfileData stores the data into INTERNAL.aotProfileData. // -export function mono_wasm_init_aot_profiler(options: AOTProfilerOptions): void { +export function mono_wasm_init_aot_profiler (options: AOTProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableAotProfiler, "AOT profiler is not enabled, please use aot; in your project file."); if (options == null) options = {}; @@ -26,7 +26,7 @@ export function mono_wasm_init_aot_profiler(options: AOTProfilerOptions): void { cwraps.mono_wasm_profiler_init_aot(arg); } -export function mono_wasm_init_browser_profiler(options: BrowserProfilerOptions): void { +export function mono_wasm_init_browser_profiler (options: BrowserProfilerOptions): void { mono_assert(runtimeHelpers.emscriptenBuildOptions.enableBrowserProfiler, "Browser profiler is not enabled, please use browser; in your project file."); if (options == null) options = {}; @@ -59,14 +59,14 @@ export type TimeStamp = { __brand: "TimeStamp" } -export function startMeasure(): TimeStamp { +export function startMeasure (): TimeStamp { if (runtimeHelpers.enablePerfMeasure) { return globalThis.performance.now() as any; } return undefined as any; } -export function endMeasure(start: TimeStamp, block: string, id?: string) { +export function endMeasure (start: TimeStamp, block: string, id?: string) { if (runtimeHelpers.enablePerfMeasure && start) { const options = ENVIRONMENT_IS_WEB ? { start: start as any } @@ -77,14 +77,14 @@ export function endMeasure(start: TimeStamp, block: string, id?: string) { } const stackFrames: number[] = []; -export function mono_wasm_profiler_enter(): void { +export function mono_wasm_profiler_enter (): void { if (runtimeHelpers.enablePerfMeasure) { stackFrames.push(globalThis.performance.now()); } } const methodNames: Map = new Map(); -export function mono_wasm_profiler_leave(method: MonoMethod): void { +export function mono_wasm_profiler_leave (method: MonoMethod): void { if (runtimeHelpers.enablePerfMeasure) { const start = stackFrames.pop(); const options = ENVIRONMENT_IS_WEB diff --git a/src/mono/browser/runtime/pthreads/deputy-thread.ts b/src/mono/browser/runtime/pthreads/deputy-thread.ts index eafb8f943f927d..bb032c2479c0d6 100644 --- a/src/mono/browser/runtime/pthreads/deputy-thread.ts +++ b/src/mono/browser/runtime/pthreads/deputy-thread.ts @@ -10,7 +10,7 @@ import { Module, loaderHelpers, runtimeHelpers } from "../globals"; import { start_runtime } from "../startup"; import { WorkerToMainMessageType } from "../types/internal"; -export function mono_wasm_start_deputy_thread_async() { +export function mono_wasm_start_deputy_thread_async () { if (!WasmEnableThreads) return; if (BuildConfiguration === "Debug" && globalThis.setInterval) globalThis.setInterval(() => { @@ -26,7 +26,7 @@ export function mono_wasm_start_deputy_thread_async() { info: monoThreadInfo, }); Module.runtimeKeepalivePush(); - Module.safeSetTimeout(async() => { + Module.safeSetTimeout(async () => { try { await start_runtime(); diff --git a/src/mono/browser/runtime/pthreads/io-thread.ts b/src/mono/browser/runtime/pthreads/io-thread.ts index 1cecaf72e445a5..011ac7b304fca9 100644 --- a/src/mono/browser/runtime/pthreads/io-thread.ts +++ b/src/mono/browser/runtime/pthreads/io-thread.ts @@ -10,7 +10,7 @@ import { Module, loaderHelpers } from "../globals"; import { WorkerToMainMessageType } from "../types/internal"; import { threads_c_functions as tcwraps } from "../cwraps"; -export function mono_wasm_start_io_thread_async() { +export function mono_wasm_start_io_thread_async () { if (!WasmEnableThreads) return; diff --git a/src/mono/browser/runtime/pthreads/shared.ts b/src/mono/browser/runtime/pthreads/shared.ts index 883259c85e04c8..efa3be35ceff04 100644 --- a/src/mono/browser/runtime/pthreads/shared.ts +++ b/src/mono/browser/runtime/pthreads/shared.ts @@ -24,7 +24,7 @@ const monoThreadInfoPartial: Partial = { }; export const monoThreadInfo: PThreadInfo = monoThreadInfoPartial as PThreadInfo; -export function isMonoThreadMessage(x: unknown): x is MonoThreadMessage { +export function isMonoThreadMessage (x: unknown): x is MonoThreadMessage { if (typeof (x) !== "object" || x === null) { return false; } @@ -32,7 +32,7 @@ export function isMonoThreadMessage(x: unknown): x is MonoThreadMessage { return typeof (xmsg.type) === "string" && typeof (xmsg.cmd) === "string"; } -export function mono_wasm_install_js_worker_interop(context_gc_handle: GCHandle): void { +export function mono_wasm_install_js_worker_interop (context_gc_handle: GCHandle): void { if (!WasmEnableThreads) return; bindings_init(); mono_assert(!runtimeHelpers.proxyGCHandle, "JS interop should not be already installed on this worker."); @@ -52,7 +52,7 @@ export function mono_wasm_install_js_worker_interop(context_gc_handle: GCHandle) } } -export function mono_wasm_uninstall_js_worker_interop(): void { +export function mono_wasm_uninstall_js_worker_interop (): void { if (!WasmEnableThreads) return; mono_assert(runtimeHelpers.mono_wasm_bindings_is_ready, "JS interop is not installed on this worker."); mono_assert(runtimeHelpers.proxyGCHandle, "JSSynchronizationContext is not installed on this worker."); @@ -66,7 +66,7 @@ export function mono_wasm_uninstall_js_worker_interop(): void { } // this is just for Debug build of the runtime, making it easier to debug worker threads -export function update_thread_info(): void { +export function update_thread_info (): void { if (!WasmEnableThreads) return; const threadType = !monoThreadInfo.isRegistered ? "emsc" : monoThreadInfo.isUI ? "-UI-" @@ -105,17 +105,17 @@ export function update_thread_info(): void { } } -export function mono_wasm_pthread_ptr(): PThreadPtr { +export function mono_wasm_pthread_ptr (): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_pthread_self"](); } -export function mono_wasm_main_thread_ptr(): PThreadPtr { +export function mono_wasm_main_thread_ptr (): PThreadPtr { if (!WasmEnableThreads) return PThreadPtrNull; return (Module)["_emscripten_main_runtime_thread_id"](); } -export function postMessageToMain(message: MonoWorkerToMainMessage, transfer?: Transferable[]) { +export function postMessageToMain (message: MonoWorkerToMainMessage, transfer?: Transferable[]) { self.postMessage({ [monoMessageSymbol]: message }, transfer ? transfer : []); diff --git a/src/mono/browser/runtime/pthreads/ui-thread.ts b/src/mono/browser/runtime/pthreads/ui-thread.ts index 134a396636d2ed..fcb010ae3a187c 100644 --- a/src/mono/browser/runtime/pthreads/ui-thread.ts +++ b/src/mono/browser/runtime/pthreads/ui-thread.ts @@ -15,14 +15,14 @@ import { threads_c_functions as cwraps } from "../cwraps"; const threadPromises: Map[]> = new Map(); class ThreadImpl implements Thread { - constructor(readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } - postMessageToWorker(message: T): void { + constructor (readonly pthreadPtr: PThreadPtr, readonly worker: Worker, readonly port: MessagePort) { } + postMessageToWorker (message: T): void { this.port.postMessage(message); } } /// wait until the thread with the given id has set up a message port to the runtime -export function waitForThread(pthreadPtr: PThreadPtr): Promise { +export function waitForThread (pthreadPtr: PThreadPtr): Promise { if (!WasmEnableThreads) return null as any; mono_assert(!ENVIRONMENT_IS_WORKER, "waitForThread should only be called from the UI thread"); const worker = getWorker(pthreadPtr); @@ -39,7 +39,7 @@ export function waitForThread(pthreadPtr: PThreadPtr): Promise { return promiseAndController.promise; } -export function resolveThreadPromises(pthreadPtr: PThreadPtr, thread?: Thread): void { +export function resolveThreadPromises (pthreadPtr: PThreadPtr, thread?: Thread): void { if (!WasmEnableThreads) return; const arr = threadPromises.get(pthreadPtr); if (arr !== undefined) { @@ -55,7 +55,7 @@ export function resolveThreadPromises(pthreadPtr: PThreadPtr, thread?: Thread): } // handler that runs in the main thread when a message is received from a pthread worker -function monoWorkerMessageHandler(worker: PThreadWorker, ev: MessageEvent): void { +function monoWorkerMessageHandler (worker: PThreadWorker, ev: MessageEvent): void { if (!WasmEnableThreads) return; let pthreadId: PThreadPtr; // this is emscripten message @@ -123,7 +123,7 @@ let pendingWorkerLoad: PromiseAndController | undefined; /// Called by Emscripten internals on the browser thread when a new pthread worker is created and added to the pthread worker pool. /// At this point the worker doesn't have any pthread assigned to it, yet. -export function onWorkerLoadInitiated(worker: PThreadWorker, loaded: Promise): void { +export function onWorkerLoadInitiated (worker: PThreadWorker, loaded: Promise): void { if (!WasmEnableThreads) return; worker.addEventListener("message", (ev) => monoWorkerMessageHandler(worker, ev)); if (pendingWorkerLoad == undefined) { @@ -138,7 +138,7 @@ export function onWorkerLoadInitiated(worker: PThreadWorker, loaded: Promise { +export function thread_available (): Promise { if (!WasmEnableThreads) return null as any; if (pendingWorkerLoad == undefined) { return Promise.resolve(); @@ -146,7 +146,7 @@ export function thread_available(): Promise { return pendingWorkerLoad.promise; } -export function populateEmscriptenPool(): void { +export function populateEmscriptenPool (): void { if (!WasmEnableThreads) return; const unused = getUnusedWorkerPool(); for (const worker of loaderHelpers.loadingWorkers) { @@ -155,7 +155,7 @@ export function populateEmscriptenPool(): void { loaderHelpers.loadingWorkers = []; } -export async function mono_wasm_init_threads() { +export async function mono_wasm_init_threads () { if (!WasmEnableThreads) return; // setup the UI thread @@ -175,7 +175,7 @@ export async function mono_wasm_init_threads() { } // when we create threads with browser event loop, it's not able to be joined by mono's thread join during shutdown and blocks process exit -export function cancelThreads() { +export function cancelThreads () { if (!WasmEnableThreads) return; const workers: PThreadWorker[] = getRunningWorkers(); for (const worker of workers) { @@ -185,7 +185,7 @@ export function cancelThreads() { } } -export function mono_wasm_dump_threads(): void { +export function mono_wasm_dump_threads (): void { if (!WasmEnableThreads) return; mono_log_info("Dumping web worker info as seen by UI thread, it could be stale: "); const emptyInfo: PThreadInfo = { @@ -219,7 +219,7 @@ export function mono_wasm_dump_threads(): void { }); } -export function init_finalizer_thread() { +export function init_finalizer_thread () { // we don't need it immediately, so we can wait a bit, to keep CPU working on normal startup setTimeout(() => { try { @@ -235,7 +235,7 @@ export function init_finalizer_thread() { }, loaderHelpers.config.finalizerThreadStartDelayMs); } -export function replaceEmscriptenPThreadUI(modulePThread: PThreadLibrary): void { +export function replaceEmscriptenPThreadUI (modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalLoadWasmModuleToWorker = modulePThread.loadWasmModuleToWorker; @@ -286,12 +286,12 @@ export function replaceEmscriptenPThreadUI(modulePThread: PThreadLibrary): void } let availableThreadCount = 0; -export function is_thread_available() { +export function is_thread_available () { if (!WasmEnableThreads) return true; return availableThreadCount > 0; } -function getNewWorker(modulePThread: PThreadLibrary): PThreadWorker { +function getNewWorker (modulePThread: PThreadLibrary): PThreadWorker { if (!WasmEnableThreads) return null as any; if (modulePThread.unusedWorkers.length == 0) { @@ -322,7 +322,7 @@ function getNewWorker(modulePThread: PThreadLibrary): PThreadWorker { } /// We replace Module["PThreads"].allocateUnusedWorker with this version that knows about assets -function allocateUnusedWorker(): PThreadWorker { +function allocateUnusedWorker (): PThreadWorker { if (!WasmEnableThreads) return null as any; const asset = loaderHelpers.resolve_single_asset_path("js-module-threads"); @@ -345,22 +345,22 @@ function allocateUnusedWorker(): PThreadWorker { return worker; } -export function getWorker(pthreadPtr: PThreadPtr): PThreadWorker | undefined { +export function getWorker (pthreadPtr: PThreadPtr): PThreadWorker | undefined { return getModulePThread().pthreads[pthreadPtr as any]; } -export function getUnusedWorkerPool(): PThreadWorker[] { +export function getUnusedWorkerPool (): PThreadWorker[] { return getModulePThread().unusedWorkers; } -export function getRunningWorkers(): PThreadWorker[] { +export function getRunningWorkers (): PThreadWorker[] { return getModulePThread().runningWorkers; } -export function loadWasmModuleToWorker(worker: PThreadWorker): Promise { +export function loadWasmModuleToWorker (worker: PThreadWorker): Promise { return getModulePThread().loadWasmModuleToWorker(worker); } -export function getModulePThread(): PThreadLibrary { +export function getModulePThread (): PThreadLibrary { return (Module).PThread as PThreadLibrary; } diff --git a/src/mono/browser/runtime/pthreads/worker-events.ts b/src/mono/browser/runtime/pthreads/worker-events.ts index e0d40a1a7e3110..63c108b01f841d 100644 --- a/src/mono/browser/runtime/pthreads/worker-events.ts +++ b/src/mono/browser/runtime/pthreads/worker-events.ts @@ -35,7 +35,7 @@ export const makeWorkerThreadEvent: (type: keyof WorkerThreadEventMap, pthread_s }) : ((type: keyof WorkerThreadEventMap, pthread_self: PThreadSelf) => { if (!WorkerThreadEventClassConstructor) WorkerThreadEventClassConstructor = class WorkerThreadEventImpl extends Event implements WorkerThreadEvent { - constructor(type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { + constructor (type: keyof WorkerThreadEventMap, readonly pthread_self: PThreadSelf) { super(type); } }; diff --git a/src/mono/browser/runtime/pthreads/worker-thread.ts b/src/mono/browser/runtime/pthreads/worker-thread.ts index edf09d3ea2e0fa..fa1269c300cb6f 100644 --- a/src/mono/browser/runtime/pthreads/worker-thread.ts +++ b/src/mono/browser/runtime/pthreads/worker-thread.ts @@ -32,17 +32,17 @@ export { export let pthread_self: PThreadSelf = null as any as PThreadSelf; class WorkerSelf implements PThreadSelf { - constructor(public info: PThreadInfo, public portToBrowser: MessagePort) { + constructor (public info: PThreadInfo, public portToBrowser: MessagePort) { } - postMessageToBrowser(message: MonoThreadMessage, transfer?: Transferable[]) { + postMessageToBrowser (message: MonoThreadMessage, transfer?: Transferable[]) { if (transfer) { this.portToBrowser.postMessage(message, transfer); } else { this.portToBrowser.postMessage(message); } } - addEventListenerFromBrowser(listener: (event: MessageEvent) => void) { + addEventListenerFromBrowser (listener: (event: MessageEvent) => void) { this.portToBrowser.addEventListener("message", listener); } } @@ -56,7 +56,7 @@ class WorkerSelf implements PThreadSelf { export let currentWorkerThreadEvents: WorkerThreadEventTarget = undefined as any; // this is very very early in the worker startup -export function initWorkerThreadEvents() { +export function initWorkerThreadEvents () { // treeshake if threads are disabled currentWorkerThreadEvents = WasmEnableThreads ? new globalThis.EventTarget() : null as any as WorkerThreadEventTarget; Object.assign(monoThreadInfo, runtimeHelpers.monoThreadInfo); @@ -64,11 +64,11 @@ export function initWorkerThreadEvents() { // this is the message handler for the worker that receives messages from the main thread // extend this with new cases as needed -function monoDedicatedChannelMessageFromMainToWorker(event: MessageEvent): void { +function monoDedicatedChannelMessageFromMainToWorker (event: MessageEvent): void { mono_log_debug("got message from main on the dedicated channel", event.data); } -export function on_emscripten_thread_init(pthread_ptr: PThreadPtr) { +export function on_emscripten_thread_init (pthread_ptr: PThreadPtr) { runtimeHelpers.currentThreadTID = monoThreadInfo.pthreadId = pthread_ptr; forceThreadMemoryViewRefresh(); } @@ -76,7 +76,7 @@ export function on_emscripten_thread_init(pthread_ptr: PThreadPtr) { /// Called by emscripten when a pthread is setup to run on a worker. Can be called multiple times /// for the same webworker, since emscripten can reuse workers. /// This is an implementation detail, that shouldn't be used directly. -export function mono_wasm_pthread_on_pthread_created(): void { +export function mono_wasm_pthread_on_pthread_created (): void { if (!WasmEnableThreads) return; try { forceThreadMemoryViewRefresh(); @@ -118,7 +118,7 @@ export function mono_wasm_pthread_on_pthread_created(): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes registered to the mono runtime. -export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_registered (pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when registering"); @@ -137,7 +137,7 @@ export function mono_wasm_pthread_on_pthread_registered(pthread_id: PThreadPtr): } /// Called in the worker thread (not main thread) from mono when a pthread becomes attached to the mono runtime. -export function mono_wasm_pthread_on_pthread_attached(pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { +export function mono_wasm_pthread_on_pthread_attached (pthread_id: PThreadPtr, thread_name: CharPtr, background_thread: number, threadpool_thread: number, external_eventloop: number, debugger_thread: number): void { if (!WasmEnableThreads) return; try { mono_assert(monoThreadInfo !== null && monoThreadInfo.pthreadId == pthread_id, "expected monoThreadInfo to be set already when attaching"); @@ -167,7 +167,7 @@ export function mono_wasm_pthread_on_pthread_attached(pthread_id: PThreadPtr, th } } -export function mono_wasm_pthread_set_name(name: CharPtr): void { +export function mono_wasm_pthread_set_name (name: CharPtr): void { if (!WasmEnableThreads) return; if (!ENVIRONMENT_IS_PTHREAD) return; monoThreadInfo.threadName = utf8ToString(name); @@ -179,7 +179,7 @@ export function mono_wasm_pthread_set_name(name: CharPtr): void { } /// Called in the worker thread (not main thread) from mono when a pthread becomes detached from the mono runtime. -export function mono_wasm_pthread_on_pthread_unregistered(pthread_id: PThreadPtr): void { +export function mono_wasm_pthread_on_pthread_unregistered (pthread_id: PThreadPtr): void { if (!WasmEnableThreads) return; try { mono_assert(pthread_id === monoThreadInfo.pthreadId, "expected pthread_id to match when un-registering"); @@ -199,7 +199,7 @@ export function mono_wasm_pthread_on_pthread_unregistered(pthread_id: PThreadPtr } } -export function replaceEmscriptenTLSInit(modulePThread: PThreadLibrary): void { +export function replaceEmscriptenTLSInit (modulePThread: PThreadLibrary): void { if (!WasmEnableThreads) return; const originalThreadInitTLS = modulePThread.threadInitTLS; @@ -210,9 +210,9 @@ export function replaceEmscriptenTLSInit(modulePThread: PThreadLibrary): void { }; } -export function replaceEmscriptenPThreadInit(): void { +export function replaceEmscriptenPThreadInit (): void { const original_emscripten_thread_init = Module["__emscripten_thread_init"]; - function emscripten_thread_init_wrapper(pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { + function emscripten_thread_init_wrapper (pthread_ptr: PThreadPtr, isMainBrowserThread: number, isMainRuntimeThread: number, canBlock: number) { on_emscripten_thread_init(pthread_ptr); original_emscripten_thread_init(pthread_ptr, isMainBrowserThread, isMainRuntimeThread, canBlock); // re-install self diff --git a/src/mono/browser/runtime/queue.ts b/src/mono/browser/runtime/queue.ts index 74f507671ff98c..a6ccd00615ca9e 100644 --- a/src/mono/browser/runtime/queue.ts +++ b/src/mono/browser/runtime/queue.ts @@ -6,19 +6,19 @@ export class Queue { private queue: T[]; private offset: number; - constructor() { + constructor () { this.queue = []; this.offset = 0; } // initialise the queue and offset // Returns the length of the queue. - getLength(): number { + getLength (): number { return (this.queue.length - this.offset); } // Returns true if the queue is empty, and false otherwise. - isEmpty(): boolean { + isEmpty (): boolean { return (this.queue.length == 0); } @@ -26,14 +26,14 @@ export class Queue { * * item - the item to enqueue */ - enqueue(item: T): void { + enqueue (item: T): void { this.queue.push(item); } /* Dequeues an item and returns it. If the queue is empty, the value * 'undefined' is returned. */ - dequeue(): T | undefined { + dequeue (): T | undefined { // if the queue is empty, return immediately if (this.queue.length === 0) return undefined; @@ -57,11 +57,11 @@ export class Queue { /* Returns the item at the front of the queue (without dequeuing it). If the * queue is empty then undefined is returned. */ - peek(): T | undefined { + peek (): T | undefined { return (this.queue.length > 0 ? this.queue[this.offset] : undefined); } - drain(onEach: (item: T) => void): void { + drain (onEach: (item: T) => void): void { while (this.getLength()) { const item = this.dequeue()!; onEach(item); diff --git a/src/mono/browser/runtime/rollup.config.js b/src/mono/browser/runtime/rollup.config.js index 519879f7d8438e..2588ad79d9ea19 100644 --- a/src/mono/browser/runtime/rollup.config.js +++ b/src/mono/browser/runtime/rollup.config.js @@ -107,7 +107,7 @@ const envConstants = { }; const locationCache = {}; -function sourcemapPathTransform(relativeSourcePath, sourcemapPath) { +function sourcemapPathTransform (relativeSourcePath, sourcemapPath) { let res = locationCache[relativeSourcePath]; if (res === undefined) { if (!isContinuousIntegrationBuild) { @@ -125,7 +125,7 @@ function sourcemapPathTransform(relativeSourcePath, sourcemapPath) { return res; } -function consts(dict) { +function consts (dict) { // implement rollup-plugin-const in terms of @rollup/plugin-virtual // It's basically the same thing except "consts" names all its modules with a "consts:" prefix, // and the virtual module always exports a single default binding (the const value). @@ -245,7 +245,7 @@ if (isDebug) { } /* Web Workers */ -function makeWorkerConfig(workerName, workerInputSourcePath) { +function makeWorkerConfig (workerName, workerInputSourcePath) { const workerConfig = { input: workerInputSourcePath, output: [ @@ -273,14 +273,14 @@ const allConfigs = [ .concat(diagnosticMockTypesConfig ? [diagnosticMockTypesConfig] : []); export default defineConfig(allConfigs); -function evalCodePlugin() { +function evalCodePlugin () { return { name: "evalCode", generateBundle: evalCode }; } -async function evalCode(options, bundle) { +async function evalCode (options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -296,7 +296,7 @@ async function evalCode(options, bundle) { // this would create .sha256 file next to the output file, so that we do not touch datetime of the file if it's same -> faster incremental build. -function writeOnChangePlugin() { +function writeOnChangePlugin () { return { name: "writeOnChange", generateBundle: writeWhenChanged @@ -304,7 +304,7 @@ function writeOnChangePlugin() { } // force always unix line ending -function alwaysLF() { +function alwaysLF () { return { name: "writeOnChange", generateBundle: (options, bundle) => { @@ -316,7 +316,7 @@ function alwaysLF() { }; } -async function writeWhenChanged(options, bundle) { +async function writeWhenChanged (options, bundle) { try { const name = Object.keys(bundle)[0]; const asset = bundle[name]; @@ -347,31 +347,31 @@ async function writeWhenChanged(options, bundle) { } } -function checkFileExists(file) { +function checkFileExists (file) { return fs.promises.access(file, fs.constants.F_OK) .then(() => true) .catch(() => false); } -function regexCheck(checks = []) { +function regexCheck (checks = []) { const filter = createFilter("**/*.ts"); return { name: "regexCheck", - renderChunk(code, chunk) { + renderChunk (code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeCheck(this, code, id); }, - transform(code, id) { + transform (code, id) { if (!filter(id)) return null; return executeCheck(this, code, id); } }; - function executeCheck(self, code, id) { + function executeCheck (self, code, id) { // self.warn("executeCheck" + id); for (const rep of checks) { const { pattern, failure } = rep; @@ -387,25 +387,25 @@ function regexCheck(checks = []) { } -function regexReplace(replacements = []) { +function regexReplace (replacements = []) { const filter = createFilter("**/*.ts"); return { name: "regexReplace", - renderChunk(code, chunk) { + renderChunk (code, chunk) { const id = chunk.fileName; if (!filter(id)) return null; return executeReplacement(this, code, id); }, - transform(code, id) { + transform (code, id) { if (!filter(id)) return null; return executeReplacement(this, code, id); } }; - function executeReplacement(_, code, id) { + function executeReplacement (_, code, id) { const magicString = new MagicString(code); if (!codeHasReplacements(code, id, magicString)) { return null; @@ -416,7 +416,7 @@ function regexReplace(replacements = []) { return result; } - function codeHasReplacements(code, id, magicString) { + function codeHasReplacements (code, id, magicString) { let result = false; let match; for (const rep of replacements) { @@ -441,7 +441,7 @@ function regexReplace(replacements = []) { // Returns an array of objects {"workerName": "foo", "path": "/path/dotnet-foo-worker.ts"} // // A file looks like a webworker toplevel input if it's `dotnet-{name}-worker.ts` or `.js` -function findWebWorkerInputs(basePath) { +function findWebWorkerInputs (basePath) { const glob = "dotnet-*-worker.[tj]s"; const files = fast_glob.sync(glob, { cwd: basePath }); if (files.length == 0) { @@ -458,7 +458,7 @@ function findWebWorkerInputs(basePath) { return results; } -function onwarn(warning) { +function onwarn (warning) { if (warning.code === "CIRCULAR_DEPENDENCY") { return; } diff --git a/src/mono/browser/runtime/roots.ts b/src/mono/browser/runtime/roots.ts index 24958a22e08458..cef2a17f0decbe 100644 --- a/src/mono/browser/runtime/roots.ts +++ b/src/mono/browser/runtime/roots.ts @@ -23,7 +23,7 @@ const _external_root_free_instances: WasmExternalRoot[] = []; * Once you are done using the root buffer, you must call its release() method. * For small numbers of roots, it is preferable to use the mono_wasm_new_root and mono_wasm_new_roots APIs instead. */ -export function mono_wasm_new_root_buffer(capacity: number, name?: string): WasmRootBuffer { +export function mono_wasm_new_root_buffer (capacity: number, name?: string): WasmRootBuffer { if (capacity <= 0) throw new Error("capacity >= 1"); @@ -43,7 +43,7 @@ export function mono_wasm_new_root_buffer(capacity: number, name?: string): Wasm * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. * Releasing this root will not de-allocate the root space. You still need to call .release(). */ -export function mono_wasm_new_external_root(address: VoidPtr | MonoObjectRef): WasmRoot { +export function mono_wasm_new_external_root (address: VoidPtr | MonoObjectRef): WasmRoot { let result: WasmExternalRoot; if (!address) @@ -66,7 +66,7 @@ export function mono_wasm_new_external_root(address: VoidP * The result object has get() and set(value) methods, along with a .value property. * When you are done using the root you must call its .release() method. */ -export function mono_wasm_new_root(value: T | undefined = undefined): WasmRoot { +export function mono_wasm_new_root (value: T | undefined = undefined): WasmRoot { let result: WasmRoot; if (_scratch_root_free_instances.length > 0) { @@ -96,7 +96,7 @@ export function mono_wasm_new_root(value: T | undefined = * mono_wasm_new_roots([a, b, ...]) returns an array of new roots initialized with each element. * Each root must be released with its release method, or using the mono_wasm_release_roots API. */ -export function mono_wasm_new_roots(count_or_values: number | T[]): WasmRoot[] { +export function mono_wasm_new_roots (count_or_values: number | T[]): WasmRoot[] { let result; if (Array.isArray(count_or_values)) { @@ -121,7 +121,7 @@ export function mono_wasm_new_roots(count_or_values: numbe * even if you are not sure all of your roots have been created yet. * @param {... WasmRoot} roots */ -export function mono_wasm_release_roots(...args: WasmRoot[]): void { +export function mono_wasm_release_roots (...args: WasmRoot[]): void { for (let i = 0; i < args.length; i++) { if (is_nullish(args[i])) continue; @@ -130,7 +130,7 @@ export function mono_wasm_release_roots(...args: WasmRoot[]): void { } } -function _mono_wasm_release_scratch_index(index: number) { +function _mono_wasm_release_scratch_index (index: number) { if (index === undefined) return; @@ -139,7 +139,7 @@ function _mono_wasm_release_scratch_index(index: number) { _scratch_root_free_indices_count++; } -function _mono_wasm_claim_scratch_index() { +function _mono_wasm_claim_scratch_index () { if (is_nullish(_scratch_root_buffer) || !_scratch_root_free_indices) { _scratch_root_buffer = mono_wasm_new_root_buffer(maxScratchRoots, "js roots"); @@ -165,7 +165,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { private __handle: number; private __ownsAllocation: boolean; - constructor(offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { + constructor (offset: VoidPtr, capacity: number, ownsAllocation: boolean, name?: string) { const capacityBytes = capacity * 4; this.__offset = offset; @@ -177,21 +177,21 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__ownsAllocation = ownsAllocation; } - _throw_index_out_of_range(): void { + _throw_index_out_of_range (): void { throw new Error("index out of range"); } - _check_in_range(index: number): void { + _check_in_range (index: number): void { if ((index >= this.__count) || (index < 0)) this._throw_index_out_of_range(); } - get_address(index: number): MonoObjectRef { + get_address (index: number): MonoObjectRef { this._check_in_range(index); return this.__offset + (index * 4); } - get_address_32(index: number): number { + get_address_32 (index: number): number { this._check_in_range(index); return this.__offset32 + index; } @@ -199,38 +199,38 @@ export class WasmRootBufferImpl implements WasmRootBuffer { // NOTE: These functions do not use the helpers from memory.ts because WasmRoot.get and WasmRoot.set // are hot-spots when you profile any application that uses the bindings extensively. - get(index: number): ManagedPointer { + get (index: number): ManagedPointer { this._check_in_range(index); const offset = this.get_address_32(index); return localHeapViewU32()[offset]; } - set(index: number, value: ManagedPointer): ManagedPointer { + set (index: number, value: ManagedPointer): ManagedPointer { const address = this.get_address(index); cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); return value; } - copy_value_from_address(index: number, sourceAddress: MonoObjectRef): void { + copy_value_from_address (index: number, sourceAddress: MonoObjectRef): void { const destinationAddress = this.get_address(index); cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - _unsafe_get(index: number): number { + _unsafe_get (index: number): number { return localHeapViewU32()[this.__offset32 + index]; } - _unsafe_set(index: number, value: ManagedPointer | NativePointer): void { + _unsafe_set (index: number, value: ManagedPointer | NativePointer): void { const address = this.__offset + index; cwraps.mono_wasm_write_managed_pointer_unsafe(address, value); } - clear(): void { + clear (): void { if (this.__offset) _zero_region(this.__offset, this.__count * 4); } - release(): void { + release (): void { if (this.__offset && this.__ownsAllocation) { mono_assert(!WasmEnableThreads || !gc_locked, "GC must not be locked when disposing a GC root"); cwraps.mono_wasm_deregister_root(this.__offset); @@ -241,7 +241,7 @@ export class WasmRootBufferImpl implements WasmRootBuffer { this.__handle = (this.__offset) = this.__count = this.__offset32 = 0; } - toString(): string { + toString (): string { return `[root buffer @${this.get_address(0)}, size ${this.__count} ]`; } } @@ -250,76 +250,76 @@ class WasmJsOwnedRoot implements WasmRoot { private __buffer: WasmRootBuffer; private __index: number; - constructor(buffer: WasmRootBuffer, index: number) { + constructor (buffer: WasmRootBuffer, index: number) { this.__buffer = buffer;//TODO this.__index = index; } - get_address(): MonoObjectRef { + get_address (): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get_address_32(): number { + get_address_32 (): number { return this.__buffer.get_address_32(this.__index); } - get address(): MonoObjectRef { + get address (): MonoObjectRef { return this.__buffer.get_address(this.__index); } - get(): T { + get (): T { const result = (this.__buffer)._unsafe_get(this.__index); return result; } - set(value: T): T { + set (value: T): T { const destinationAddress = this.__buffer.get_address(this.__index); cwraps.mono_wasm_write_managed_pointer_unsafe(destinationAddress, value); return value; } - copy_from(source: WasmRoot): void { + copy_from (source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to(destination: WasmRoot): void { + copy_to (destination: WasmRoot): void { const sourceAddress = this.address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address(source: MonoObjectRef): void { + copy_from_address (source: MonoObjectRef): void { const destinationAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address(destination: MonoObjectRef): void { + copy_to_address (destination: MonoObjectRef): void { const sourceAddress = this.address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value(): T { + get value (): T { return this.get(); } - set value(value: T) { + set value (value: T) { this.set(value); } - valueOf(): T { + valueOf (): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear(): void { + clear (): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC const address32 = this.__buffer.get_address_32(this.__index); localHeapViewU32()[address32] = 0; } - release(): void { + release (): void { if (!this.__buffer) throw new Error("No buffer"); @@ -334,7 +334,7 @@ class WasmJsOwnedRoot implements WasmRoot { } } - toString(): string { + toString (): string { return `[root @${this.address}]`; } } @@ -343,84 +343,84 @@ class WasmExternalRoot implements WasmRoot { private __external_address: MonoObjectRef = MonoObjectRefNull; private __external_address_32: number = 0; - constructor(address: NativePointer | ManagedPointer) { + constructor (address: NativePointer | ManagedPointer) { this._set_address(address); } - _set_address(address: NativePointer | ManagedPointer): void { + _set_address (address: NativePointer | ManagedPointer): void { this.__external_address = address; this.__external_address_32 = address >>> 2; } - get address(): MonoObjectRef { + get address (): MonoObjectRef { return this.__external_address; } - get_address(): MonoObjectRef { + get_address (): MonoObjectRef { return this.__external_address; } - get_address_32(): number { + get_address_32 (): number { return this.__external_address_32; } - get(): T { + get (): T { const result = localHeapViewU32()[this.__external_address_32]; return result; } - set(value: T): T { + set (value: T): T { cwraps.mono_wasm_write_managed_pointer_unsafe(this.__external_address, value); return value; } - copy_from(source: WasmRoot): void { + copy_from (source: WasmRoot): void { const sourceAddress = source.address; const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_to(destination: WasmRoot): void { + copy_to (destination: WasmRoot): void { const sourceAddress = this.__external_address; const destinationAddress = destination.address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, sourceAddress); } - copy_from_address(source: MonoObjectRef): void { + copy_from_address (source: MonoObjectRef): void { const destinationAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destinationAddress, source); } - copy_to_address(destination: MonoObjectRef): void { + copy_to_address (destination: MonoObjectRef): void { const sourceAddress = this.__external_address; cwraps.mono_wasm_copy_managed_pointer(destination, sourceAddress); } - get value(): T { + get value (): T { return this.get(); } - set value(value: T) { + set value (value: T) { this.set(value); } - valueOf(): T { + valueOf (): T { throw new Error("Implicit conversion of roots to pointers is no longer supported. Use .value or .address as appropriate"); } - clear(): void { + clear (): void { // .set performs an expensive write barrier, and that is not necessary in most cases // for clear since clearing a root cannot cause new objects to survive a GC localHeapViewU32()[this.__external_address >>> 2] = 0; } - release(): void { + release (): void { const maxPooledInstances = 128; if (_external_root_free_instances.length < maxPooledInstances) _external_root_free_instances.push(this); } - toString(): string { + toString (): string { return `[external root @${this.address}]`; } } diff --git a/src/mono/browser/runtime/run.ts b/src/mono/browser/runtime/run.ts index a107f754556276..be412fb9b70230 100644 --- a/src/mono/browser/runtime/run.ts +++ b/src/mono/browser/runtime/run.ts @@ -14,7 +14,7 @@ import { call_entry_point } from "./managed-exports"; /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main_and_exit(main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main_and_exit (main_assembly_name?: string, args?: string[]): Promise { try { const result = await mono_run_main(main_assembly_name, args); loaderHelpers.mono_exit(result); @@ -35,7 +35,7 @@ export async function mono_run_main_and_exit(main_assembly_name?: string, args?: /** * Possible signatures are described here https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line */ -export async function mono_run_main(main_assembly_name?: string, args?: string[]): Promise { +export async function mono_run_main (main_assembly_name?: string, args?: string[]): Promise { if (main_assembly_name === undefined || main_assembly_name === null || main_assembly_name === "") { main_assembly_name = loaderHelpers.config.mainAssemblyName; mono_assert(main_assembly_name, "Null or empty config.mainAssemblyName"); @@ -76,14 +76,14 @@ export async function mono_run_main(main_assembly_name?: string, args?: string[] -export function nativeExit(code: number) { +export function nativeExit (code: number) { if (WasmEnableThreads) { cancelThreads(); } cwraps.mono_wasm_exit(code); } -export function nativeAbort(reason: any) { +export function nativeAbort (reason: any) { loaderHelpers.exitReason = reason; if (!loaderHelpers.is_exited()) { cwraps.mono_wasm_abort(); diff --git a/src/mono/browser/runtime/satelliteAssemblies.ts b/src/mono/browser/runtime/satelliteAssemblies.ts index 3cd534bf4e533f..713cfb94161f9b 100644 --- a/src/mono/browser/runtime/satelliteAssemblies.ts +++ b/src/mono/browser/runtime/satelliteAssemblies.ts @@ -5,7 +5,7 @@ import { loaderHelpers } from "./globals"; import { load_satellite_assembly } from "./managed-exports"; import { AssetEntry } from "./types"; -export async function loadSatelliteAssemblies(culturesToLoad: string[]): Promise { +export async function loadSatelliteAssemblies (culturesToLoad: string[]): Promise { const satelliteResources = loaderHelpers.config.resources!.satelliteResources; if (!satelliteResources) { return; diff --git a/src/mono/browser/runtime/scheduling.ts b/src/mono/browser/runtime/scheduling.ts index 1a537645a3da94..decbc6a2940bf6 100644 --- a/src/mono/browser/runtime/scheduling.ts +++ b/src/mono/browser/runtime/scheduling.ts @@ -11,7 +11,7 @@ import { is_thread_available } from "./pthreads"; let spread_timers_maximum = 0; let pump_count = 0; -export function prevent_timer_throttling(): void { +export function prevent_timer_throttling (): void { if (!loaderHelpers.isChromium) { return; } @@ -29,7 +29,7 @@ export function prevent_timer_throttling(): void { spread_timers_maximum = desired_reach_time; } -function prevent_timer_throttling_tick() { +function prevent_timer_throttling_tick () { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -42,7 +42,7 @@ function prevent_timer_throttling_tick() { mono_background_exec_until_done(); } -function mono_background_exec_until_done() { +function mono_background_exec_until_done () { Module.maybeExit(); if (!loaderHelpers.is_runtime_running()) { return; @@ -56,10 +56,10 @@ function mono_background_exec_until_done() { } } -export function schedule_background_exec(): void { +export function schedule_background_exec (): void { ++pump_count; let max_postpone_count = 10; - function postpone_schedule_background() { + function postpone_schedule_background () { if (max_postpone_count < 0 || is_thread_available()) { Module.safeSetTimeout(mono_background_exec_until_done, 0); } else { @@ -77,7 +77,7 @@ export function schedule_background_exec(): void { } let lastScheduledTimeoutId: any = undefined; -export function mono_wasm_schedule_timer(shortestDueTimeMs: number): void { +export function mono_wasm_schedule_timer (shortestDueTimeMs: number): void { if (lastScheduledTimeoutId) { globalThis.clearTimeout(lastScheduledTimeoutId); lastScheduledTimeoutId = undefined; @@ -89,7 +89,7 @@ export function mono_wasm_schedule_timer(shortestDueTimeMs: number): void { lastScheduledTimeoutId = Module.safeSetTimeout(mono_wasm_schedule_timer_tick, shortestDueTimeMs); } -function mono_wasm_schedule_timer_tick() { +function mono_wasm_schedule_timer_tick () { Module.maybeExit(); if (WasmEnableThreads) { forceThreadMemoryViewRefresh(); diff --git a/src/mono/browser/runtime/startup.ts b/src/mono/browser/runtime/startup.ts index dd3ddaeffbf71a..2ab5110ec46875 100644 --- a/src/mono/browser/runtime/startup.ts +++ b/src/mono/browser/runtime/startup.ts @@ -35,13 +35,13 @@ import { nativeAbort, nativeExit } from "./run"; import { mono_wasm_init_diagnostics } from "./diagnostics"; import { replaceEmscriptenPThreadInit } from "./pthreads/worker-thread"; -export async function configureRuntimeStartup(): Promise { +export async function configureRuntimeStartup (): Promise { await init_polyfills_async(); } // we are making emscripten startup async friendly // emscripten is executing the events without awaiting it and so we need to block progress via PromiseControllers above -export function configureEmscriptenStartup(module: DotnetModuleInternal): void { +export function configureEmscriptenStartup (module: DotnetModuleInternal): void { const mark = startMeasure(); if (!module.locateFile) { @@ -84,7 +84,7 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { module.postRun = [() => postRunAsync(userpostRun)]; // execution order == [6] == - module.ready.then(async() => { + module.ready.then(async () => { // wait for previous stage await runtimeHelpers.afterPostRun.promise; // startup end @@ -98,7 +98,7 @@ export function configureEmscriptenStartup(module: DotnetModuleInternal): void { module.ready = runtimeHelpers.dotnetReady.promise; } -function instantiateWasm( +function instantiateWasm ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, userInstantiateWasm?: InstantiateWasmCallBack): any[] { @@ -118,7 +118,7 @@ function instantiateWasm( return []; // No exports } -async function instantiateWasmWorker( +async function instantiateWasmWorker ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback ): Promise { @@ -136,7 +136,7 @@ async function instantiateWasmWorker( Module.wasmModule = null; } -function preInit(userPreInit: (() => void)[]) { +function preInit (userPreInit: (() => void)[]) { Module.addRunDependency("mono_pre_init"); const mark = startMeasure(); try { @@ -153,7 +153,7 @@ function preInit(userPreInit: (() => void)[]) { // this will start immediately but return on first await. // It will block our `preRun` by afterPreInit promise // It will block emscripten `userOnRuntimeInitialized` by pending addRunDependency("mono_pre_init") - (async() => { + (async () => { try { // - init the rest of the polyfills await mono_wasm_pre_init_essential_async(); @@ -169,7 +169,7 @@ function preInit(userPreInit: (() => void)[]) { })(); } -async function preInitWorkerAsync() { +async function preInitWorkerAsync () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -193,7 +193,7 @@ async function preInitWorkerAsync() { } // runs for each re-attached worker -export function preRunWorker() { +export function preRunWorker () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -209,7 +209,7 @@ export function preRunWorker() { } } -async function preRunAsync(userPreRun: (() => void)[]) { +async function preRunAsync (userPreRun: (() => void)[]) { Module.addRunDependency("mono_pre_run_async"); // wait for previous stages try { @@ -230,7 +230,7 @@ async function preRunAsync(userPreRun: (() => void)[]) { Module.removeRunDependency("mono_pre_run_async"); } -async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { +async function onRuntimeInitializedAsync (userOnRuntimeInitialized: () => void) { try { // wait for previous stage await runtimeHelpers.afterPreRun.promise; @@ -337,7 +337,7 @@ async function onRuntimeInitializedAsync(userOnRuntimeInitialized: () => void) { runtimeHelpers.afterOnRuntimeInitialized.promise_control.resolve(); } -async function postRunAsync(userpostRun: (() => void)[]) { +async function postRunAsync (userpostRun: (() => void)[]) { // wait for previous stage try { await runtimeHelpers.afterOnRuntimeInitialized.promise; @@ -361,7 +361,7 @@ async function postRunAsync(userpostRun: (() => void)[]) { } // runs for each re-detached worker -export function postRunWorker() { +export function postRunWorker () { if (!WasmEnableThreads) return; const mark = startMeasure(); try { @@ -382,7 +382,7 @@ export function postRunWorker() { } } -function mono_wasm_pre_init_essential(isWorker: boolean): void { +function mono_wasm_pre_init_essential (isWorker: boolean): void { if (!isWorker) Module.addRunDependency("mono_wasm_pre_init_essential"); @@ -409,7 +409,7 @@ function mono_wasm_pre_init_essential(isWorker: boolean): void { Module.removeRunDependency("mono_wasm_pre_init_essential"); } -async function mono_wasm_pre_init_essential_async(): Promise { +async function mono_wasm_pre_init_essential_async (): Promise { mono_log_debug("mono_wasm_pre_init_essential_async"); Module.addRunDependency("mono_wasm_pre_init_essential_async"); @@ -420,7 +420,7 @@ async function mono_wasm_pre_init_essential_async(): Promise { Module.removeRunDependency("mono_wasm_pre_init_essential_async"); } -async function mono_wasm_after_user_runtime_initialized(): Promise { +async function mono_wasm_after_user_runtime_initialized (): Promise { mono_log_debug("mono_wasm_after_user_runtime_initialized"); try { if (Module.onDotnetReady) { @@ -439,11 +439,11 @@ async function mono_wasm_after_user_runtime_initialized(): Promise { // Set environment variable NAME to VALUE // Should be called before mono_load_runtime_and_bcl () in most cases -export function mono_wasm_setenv(name: string, value: string): void { +export function mono_wasm_setenv (name: string, value: string): void { cwraps.mono_wasm_setenv(name, value); } -export function mono_wasm_set_runtime_options(options: string[]): void { +export function mono_wasm_set_runtime_options (options: string[]): void { if (!Array.isArray(options)) throw new Error("Expected runtimeOptions to be an array of strings"); @@ -459,7 +459,7 @@ export function mono_wasm_set_runtime_options(options: string[]): void { cwraps.mono_wasm_parse_runtime_options(options.length, argv); } -async function instantiate_wasm_module( +async function instantiate_wasm_module ( imports: WebAssembly.Imports, successCallback: InstantiateWasmSuccessCallback, ): Promise { @@ -489,7 +489,7 @@ async function instantiate_wasm_module( Module.removeRunDependency("instantiate_wasm_module"); } -async function ensureUsedWasmFeatures() { +async function ensureUsedWasmFeatures () { runtimeHelpers.featureWasmSimd = await loaderHelpers.simd(); runtimeHelpers.featureWasmEh = await loaderHelpers.exceptions(); if (runtimeHelpers.emscriptenBuildOptions.wasmEnableSIMD) { @@ -500,7 +500,7 @@ async function ensureUsedWasmFeatures() { } } -export async function start_runtime() { +export async function start_runtime () { try { const mark = startMeasure(); mono_log_debug("Initializing mono runtime"); @@ -564,7 +564,7 @@ export async function start_runtime() { } } -async function maybeSaveInterpPgoTable() { +async function maybeSaveInterpPgoTable () { // If the application exited abnormally, don't save the table. It probably doesn't contain useful data, // and saving would overwrite any existing table from a previous successful run. // We treat exiting with a code of 0 as equivalent to if the app is still running - it's perfectly fine @@ -575,7 +575,7 @@ async function maybeSaveInterpPgoTable() { await interp_pgo_save_data(); } -export function mono_wasm_load_runtime(): void { +export function mono_wasm_load_runtime (): void { mono_log_debug("mono_wasm_load_runtime"); try { const mark = startMeasure(); @@ -599,7 +599,7 @@ export function mono_wasm_load_runtime(): void { } } -export function bindings_init(): void { +export function bindings_init (): void { if (runtimeHelpers.mono_wasm_bindings_is_ready) { return; } @@ -620,7 +620,7 @@ export function bindings_init(): void { } -export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { +export function mono_wasm_asm_loaded (assembly_name: CharPtr, assembly_ptr: number, assembly_len: number, pdb_ptr: number, pdb_len: number): void { // Only trigger this codepath for assemblies loaded after app is ready if (runtimeHelpers.mono_wasm_runtime_is_ready !== true) return; @@ -643,7 +643,7 @@ export function mono_wasm_asm_loaded(assembly_name: CharPtr, assembly_ptr: numbe }); } -export function mono_wasm_set_main_args(name: string, allRuntimeArguments: string[]): void { +export function mono_wasm_set_main_args (name: string, allRuntimeArguments: string[]): void { const main_argc = allRuntimeArguments.length + 1; const main_argv = Module._malloc(main_argc * 4); let aindex = 0; @@ -663,7 +663,7 @@ export function mono_wasm_set_main_args(name: string, allRuntimeArguments: strin /// 1. Emscripten skips a lot of initialization on the pthread workers, Module may not have everything you expect. /// 2. Emscripten does not run any event but preInit in the workers. /// 3. At the point when this executes there is no pthread assigned to the worker yet. -export async function configureWorkerStartup(module: DotnetModuleInternal): Promise { +export async function configureWorkerStartup (module: DotnetModuleInternal): Promise { if (!WasmEnableThreads) return; initWorkerThreadEvents(); diff --git a/src/mono/browser/runtime/strings.ts b/src/mono/browser/runtime/strings.ts index d0d798c161b28f..71356942934549 100644 --- a/src/mono/browser/runtime/strings.ts +++ b/src/mono/browser/runtime/strings.ts @@ -21,7 +21,7 @@ let _text_decoder_utf8_relaxed: TextDecoder | undefined = undefined; let _text_decoder_utf8_validating: TextDecoder | undefined = undefined; let _text_encoder_utf8: TextEncoder | undefined = undefined; -export function strings_init(): void { +export function strings_init (): void { if (!mono_wasm_string_decoder_buffer) { if (typeof TextDecoder !== "undefined") { _text_decoder_utf16 = new TextDecoder("utf-16le"); @@ -35,7 +35,7 @@ export function strings_init(): void { mono_wasm_string_root = mono_wasm_new_root(); } -export function stringToUTF8(str: string): Uint8Array { +export function stringToUTF8 (str: string): Uint8Array { if (_text_encoder_utf8 === undefined) { const buffer = new Uint8Array(str.length * 2); Module.stringToUTF8Array(str, buffer, 0, str.length * 2); @@ -44,7 +44,7 @@ export function stringToUTF8(str: string): Uint8Array { return _text_encoder_utf8.encode(str); } -export function stringToUTF8Ptr(str: string): CharPtr { +export function stringToUTF8Ptr (str: string): CharPtr { const bytes = str.length * 2; const ptr = Module._malloc(bytes) as any; _zero_region(ptr, str.length * 2); @@ -53,19 +53,19 @@ export function stringToUTF8Ptr(str: string): CharPtr { return ptr; } -export function utf8ToStringRelaxed(buffer: Uint8Array): string { +export function utf8ToStringRelaxed (buffer: Uint8Array): string { if (_text_decoder_utf8_relaxed === undefined) { return Module.UTF8ArrayToString(buffer, 0, buffer.byteLength); } return _text_decoder_utf8_relaxed.decode(buffer); } -export function utf8ToString(ptr: CharPtr): string { +export function utf8ToString (ptr: CharPtr): string { const heapU8 = localHeapViewU8(); return utf8BufferToString(heapU8, ptr as any, heapU8.length - (ptr as any)); } -export function utf8BufferToString(heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { +export function utf8BufferToString (heapOrArray: Uint8Array, idx: number, maxBytesToRead: number): string { const endIdx = idx + maxBytesToRead; let endPtr = idx; while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; @@ -79,7 +79,7 @@ export function utf8BufferToString(heapOrArray: Uint8Array, idx: number, maxByte return _text_decoder_utf8_validating.decode(view); } -export function utf16ToString(startPtr: number, endPtr: number): string { +export function utf16ToString (startPtr: number, endPtr: number): string { if (_text_decoder_utf16) { const subArray = viewOrCopy(localHeapViewU8(), startPtr as any, endPtr as any); return _text_decoder_utf16.decode(subArray); @@ -88,7 +88,7 @@ export function utf16ToString(startPtr: number, endPtr: number): string { } } -export function utf16ToStringLoop(startPtr: number, endPtr: number): string { +export function utf16ToStringLoop (startPtr: number, endPtr: number): string { let str = ""; const heapU16 = localHeapViewU16(); for (let i = startPtr; i < endPtr; i += 2) { @@ -98,7 +98,7 @@ export function utf16ToStringLoop(startPtr: number, endPtr: number): string { return str; } -export function stringToUTF16(dstPtr: number, endPtr: number, text: string) { +export function stringToUTF16 (dstPtr: number, endPtr: number, text: string) { const heapI16 = localHeapViewU16(); const len = text.length; for (let i = 0; i < len; i++) { @@ -108,7 +108,7 @@ export function stringToUTF16(dstPtr: number, endPtr: number, text: string) { } } -export function monoStringToString(root: WasmRoot): string | null { +export function monoStringToString (root: WasmRoot): string | null { if (root.value === MonoStringNull) return null; @@ -142,7 +142,7 @@ export function monoStringToString(root: WasmRoot): string | null { return result; } -export function stringToMonoStringRoot(string: string, result: WasmRoot): void { +export function stringToMonoStringRoot (string: string, result: WasmRoot): void { result.clear(); if (string === null) @@ -171,7 +171,7 @@ export function stringToMonoStringRoot(string: string, result: WasmRoot): void { +function stringToInternedMonoStringRoot (string: string | symbol, result: WasmRoot): void { let text: string | undefined; if (typeof (string) === "symbol") { text = string.description; @@ -204,7 +204,7 @@ function stringToInternedMonoStringRoot(string: string | symbol, result: WasmRoo storeStringInInternTable(text, result, true); } -function storeStringInInternTable(string: string, root: WasmRoot, internIt: boolean): void { +function storeStringInInternTable (string: string, root: WasmRoot, internIt: boolean): void { if (!root.value) throw new Error("null pointer passed to _store_string_in_intern_table"); @@ -242,7 +242,7 @@ function storeStringInInternTable(string: string, root: WasmRoot, in rootBuffer.copy_value_from_address(index, root.address); } -function stringToMonoStringNewRoot(string: string, result: WasmRoot): void { +function stringToMonoStringNewRoot (string: string, result: WasmRoot): void { const bufferLen = (string.length + 1) * 2; // TODO this could be stack allocated for small strings // or temp_malloc/alloca for large strings @@ -256,7 +256,7 @@ function stringToMonoStringNewRoot(string: string, result: WasmRoot) // When threading is enabled, TextDecoder does not accept a view of a // SharedArrayBuffer, we must make a copy of the array first. // See https://github.com/whatwg/encoding/issues/172 -export function viewOrCopy(view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { +export function viewOrCopy (view: Uint8Array, start: CharPtr, end: CharPtr): Uint8Array { // this condition should be eliminated by rollup on non-threading builds const needsCopy = isSharedArrayBuffer(view.buffer); return needsCopy @@ -268,7 +268,7 @@ export function viewOrCopy(view: Uint8Array, start: CharPtr, end: CharPtr): Uint let mono_wasm_string_root: any; /* @deprecated not GC safe, use monoStringToString */ -export function monoStringToStringUnsafe(mono_string: MonoString): string | null { +export function monoStringToStringUnsafe (mono_string: MonoString): string | null { if (mono_string === MonoStringNull) return null; diff --git a/src/mono/browser/runtime/types/internal.ts b/src/mono/browser/runtime/types/internal.ts index 1189ef4f63b575..b333e254703b02 100644 --- a/src/mono/browser/runtime/types/internal.ts +++ b/src/mono/browser/runtime/types/internal.ts @@ -64,7 +64,7 @@ export const CharPtrNull: CharPtr = 0; export const NativePointerNull: NativePointer = 0; export const PThreadPtrNull: PThreadPtr = 0; -export function coerceNull(ptr: T | null | undefined): T { +export function coerceNull (ptr: T | null | undefined): T { if ((ptr === null) || (ptr === undefined)) return (0 as any) as T; else @@ -254,7 +254,7 @@ export type DotnetModuleInternal = EmscriptenModule & DotnetModuleConfig & Emscr // Evaluates whether a value is nullish (same definition used as the ?? operator, // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) -export function is_nullish(value: T | null | undefined): value is null | undefined { +export function is_nullish (value: T | null | undefined): value is null | undefined { return (value === undefined) || (value === null); } @@ -299,14 +299,14 @@ export interface ExitStatusError { /// Always throws. Used to handle unreachable switch branches when TypeScript refines the type of a variable /// to 'never' after you handle all the cases it knows about. -export function assertNever(x: never): never { +export function assertNever (x: never): never { throw new Error("Unexpected value: " + x); } /// returns true if the given value is not Thenable /// /// Useful if some function returns a value or a promise of a value. -export function notThenable(x: T | PromiseLike): x is T { +export function notThenable (x: T | PromiseLike): x is T { return typeof x !== "object" || typeof ((>x).then) !== "function"; } diff --git a/src/mono/browser/runtime/weak-ref.ts b/src/mono/browser/runtime/weak-ref.ts index fee25ef8712dd8..c9b0e15e9821fa 100644 --- a/src/mono/browser/runtime/weak-ref.ts +++ b/src/mono/browser/runtime/weak-ref.ts @@ -5,7 +5,7 @@ import { WeakRefInternal } from "./types/internal"; export const _use_weak_ref = typeof globalThis.WeakRef === "function"; -export function create_weak_ref(js_obj: T): WeakRefInternal { +export function create_weak_ref (js_obj: T): WeakRefInternal { if (_use_weak_ref) { return new WeakRef(js_obj); } else { @@ -14,7 +14,7 @@ export function create_weak_ref(js_obj: T): WeakRefInternal } } -export function create_strong_ref(js_obj: T): WeakRefInternal { +export function create_strong_ref (js_obj: T): WeakRefInternal { return { deref: () => { return js_obj; diff --git a/src/mono/browser/runtime/web-socket.ts b/src/mono/browser/runtime/web-socket.ts index f83def338f8922..9246c1bbaf2af6 100644 --- a/src/mono/browser/runtime/web-socket.ts +++ b/src/mono/browser/runtime/web-socket.ts @@ -32,7 +32,7 @@ const wasm_ws_receive_status_ptr = Symbol.for("wasm ws_receive_status_ptr"); const ws_send_buffer_blocking_threshold = 65536; const emptyBuffer = new Uint8Array(); -function verifyEnvironment() { +function verifyEnvironment () { if (ENVIRONMENT_IS_SHELL) { throw new Error("WebSockets are not supported in shell JS engine."); } @@ -44,7 +44,7 @@ function verifyEnvironment() { } } -export function ws_get_state(ws: WebSocketExtension) : number { +export function ws_get_state (ws: WebSocketExtension) : number { if (ws.readyState != WebSocket.CLOSED) return ws.readyState ?? -1; const receive_event_queue = ws[wasm_ws_pending_receive_event_queue]; @@ -54,7 +54,7 @@ export function ws_get_state(ws: WebSocketExtension) : number { return WebSocket.OPEN; } -export function ws_wasm_create(uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { +export function ws_wasm_create (uri: string, sub_protocols: string[] | null, receive_status_ptr: VoidPtr): WebSocketExtension { verifyEnvironment(); assert_js_interop(); mono_assert(uri && typeof uri === "string", () => `ERR12: Invalid uri ${typeof uri}`); @@ -166,7 +166,7 @@ export function ws_wasm_create(uri: string, sub_protocols: string[] | null, rece return ws; } -export function ws_wasm_open(ws: WebSocketExtension): Promise | null { +export function ws_wasm_open (ws: WebSocketExtension): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { return rejectedPromise(ws[wasm_ws_pending_error]); @@ -176,7 +176,7 @@ export function ws_wasm_open(ws: WebSocketExtension): Promise | null { +export function ws_wasm_send (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number, message_type: number, end_of_message: boolean): Promise | null { mono_assert(!!ws, "ERR17: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -201,7 +201,7 @@ export function ws_wasm_send(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer return web_socket_send_and_wait(ws, whole_buffer); } -export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { +export function ws_wasm_receive (ws: WebSocketExtension, buffer_ptr: VoidPtr, buffer_length: number): Promise | null { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_pending_error]) { @@ -246,7 +246,7 @@ export function ws_wasm_receive(ws: WebSocketExtension, buffer_ptr: VoidPtr, buf return promise; } -export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { +export function ws_wasm_close (ws: WebSocketExtension, code: number, reason: string | null, wait_for_close_received: boolean): Promise | null { mono_assert(!!ws, "ERR19: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent] || ws.readyState == WebSocket.CLOSED) { @@ -276,7 +276,7 @@ export function ws_wasm_close(ws: WebSocketExtension, code: number, reason: stri } } -export function ws_wasm_abort(ws: WebSocketExtension): void { +export function ws_wasm_abort (ws: WebSocketExtension): void { mono_assert(!!ws, "ERR18: expected ws instance"); if (ws[wasm_ws_is_aborted] || ws[wasm_ws_close_sent]) { @@ -294,7 +294,7 @@ export function ws_wasm_abort(ws: WebSocketExtension): void { } } -function reject_promises(ws: WebSocketExtension, error: Error) { +function reject_promises (ws: WebSocketExtension, error: Error) { const open_promise_control = ws[wasm_ws_pending_open_promise]; const open_promise_used = ws[wasm_ws_pending_open_promise_used]; @@ -317,7 +317,7 @@ function reject_promises(ws: WebSocketExtension, error: Error) { } // send and return promise -function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { +function web_socket_send_and_wait (ws: WebSocketExtension, buffer_view: Uint8Array | string): Promise | null { ws.send(buffer_view); ws[wasm_ws_pending_send_buffer] = null; @@ -368,7 +368,7 @@ function web_socket_send_and_wait(ws: WebSocketExtension, buffer_view: Uint8Arra return promise; } -function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { +function web_socket_on_message (ws: WebSocketExtension, event: MessageEvent) { const event_queue = ws[wasm_ws_pending_receive_event_queue]; const promise_queue = ws[wasm_ws_pending_receive_promise_queue]; @@ -403,7 +403,7 @@ function web_socket_on_message(ws: WebSocketExtension, event: MessageEvent) { prevent_timer_throttling(); } -function web_socket_receive_buffering(ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { +function web_socket_receive_buffering (ws: WebSocketExtension, event_queue: Queue, buffer_ptr: VoidPtr, buffer_length: number) { const event = event_queue.peek(); const count = Math.min(buffer_length, event.data.length - event.offset); @@ -423,7 +423,7 @@ function web_socket_receive_buffering(ws: WebSocketExtension, event_queue: Queue setI32(response_ptr + 8, end_of_message); } -function web_socket_send_buffering(ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { +function web_socket_send_buffering (ws: WebSocketExtension, buffer_view: Uint8Array, message_type: number, end_of_message: boolean): Uint8Array | string | null { let buffer = ws[wasm_ws_pending_send_buffer]; let offset = 0; const length = buffer_view.byteLength; @@ -515,7 +515,7 @@ type Message = { offset: number } -function resolvedPromise(): Promise | null { +function resolvedPromise (): Promise | null { if (!WasmEnableThreads) { // signal that we are finished synchronously // this is optimization, which doesn't allocate and doesn't require to marshal resolve() call to C# side. @@ -530,7 +530,7 @@ function resolvedPromise(): Promise | null { } } -function rejectedPromise(message: string): Promise | null { +function rejectedPromise (message: string): Promise | null { const resolved = Promise.reject(new Error(message)); return wrap_as_cancelable(resolved); }