diff --git a/src/mono/browser/runtime/.eslintignore b/src/mono/browser/runtime/.eslintignore index 682049e38a926..a0de5cad5c0cb 100644 --- a/src/mono/browser/runtime/.eslintignore +++ b/src/mono/browser/runtime/.eslintignore @@ -1,2 +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 5cdee1555241a..0cae796f4016a 100644 --- a/src/mono/browser/runtime/.eslintrc.cjs +++ b/src/mono/browser/runtime/.eslintrc.cjs @@ -22,6 +22,8 @@ module.exports = { "es6/*.js", "jiterpreter-opcodes.ts", "jiterpreter-tables.ts", + "dotnet.d.ts", + "diagnostics-mock.d.ts", ], "rules": { "@typescript-eslint/no-explicit-any": "off", @@ -48,6 +50,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", "always"], + "array-bracket-spacing": ["error"], + "space-infix-ops": ["error"], + "space-before-function-paren": ["error", "always"], } }; diff --git a/src/mono/browser/runtime/assets.ts b/src/mono/browser/runtime/assets.ts index 40dc39349ff56..7cdff19d8a84c 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(); @@ -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 ac0664b78c201..28bf9970ed7f1 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 420586d7097a0..c82cbdacb1960 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 { - // cancelation should not arrive earlier than the promise created by marshaling in mono_wasm_invoke_jsimport_MT +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,15 +63,15 @@ 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 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; } @@ -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; @@ -141,7 +141,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) { @@ -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; @@ -175,14 +175,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 f396b5d833b14..a6642d874ffcb 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 558c230265e23..20ab2c88ca422 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 ca10e3d35ff6c..7f4a05cbd8709 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; diff --git a/src/mono/browser/runtime/debug.ts b/src/mono/browser/runtime/debug.ts index 1cbe85aff718a..99963d964f00c 100644 --- a/src/mono/browser/runtime/debug.ts +++ b/src/mono/browser/runtime/debug.ts @@ -9,7 +9,9 @@ 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,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); @@ -85,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); @@ -99,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) @@ -107,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); } @@ -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)) @@ -276,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}`); @@ -338,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 799972b1fd0e6..0119a9fda984b 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 a9d6f9414267a..f8f93f6781a07 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 0de8c8b7acafc..7e2a8a5918633 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 8130415407133..d320980e454da 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 b6bb8084a2684..6714af0bc4d2a 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 cba9d5fba7d8d..cbc94347a7d20 100644 --- a/src/mono/browser/runtime/diagnostics/server_pthread/index.ts +++ b/src/mono/browser/runtime/diagnostics/server_pthread/index.ts @@ -50,16 +50,20 @@ 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); }; + 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); }; + 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 2129fc76e601c..ddd37a145c089 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 09115d7245bc3..11c846763b25d 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 e7f27b9c6ab1f..9d98130bf84c2 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 765e16718c953..045bb76a4c5e2 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 6b67488c5fdac..558926d8533f0 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 2031de3499bd3..70794014fe8e9 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 b3d07952de76d..48ec5b1adbd9f 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 a255e65fe3c18..f0f7a054bc46d 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 7bd03e0d003a3..049d1525cd32b 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 d02ae16e3403a..fec4a1fc32aab 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 5ab42c2d8b4d9..693082b86b8a2 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 6854261e4d00e..53e30cc594a10 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 16aa6ad85944f..d4ed630494511 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 17af0cbc5bebb..866c0d1292331 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 95b9f965a693a..3c8e6312c5906 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 153ac946010cd..effdc6fb0f890 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 3158b553713e4..074b54a18fcc7 100644 --- a/src/mono/browser/runtime/exports-internal.ts +++ b/src/mono/browser/runtime/exports-internal.ts @@ -25,10 +25,12 @@ 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) => { 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 84e39b446155b..b1d5c0234f565 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: {}, @@ -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 2a4dc08320a0b..d26e3c8b57ce2 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; @@ -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 cf39ddc822a91..30e3f30271451 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,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 ea373eecc0447..7a85513fd5ebd 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 9513254cc55aa..047fcb60c9502 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"); } @@ -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 fe46ca43521ba..8901403b758be 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 6e4f66d0e214a..9591c3c86fed0 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,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 { controller.isAborted = true; @@ -97,13 +96,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 @@ -118,7 +116,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"); @@ -129,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(); @@ -137,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); @@ -145,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(); @@ -191,30 +189,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(); @@ -224,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"); @@ -238,7 +236,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 002c76da1be13..56183658a368e 100644 --- a/src/mono/browser/runtime/hybrid-globalization/calendar.ts +++ b/src/mono/browser/runtime/hybrid-globalization/calendar.ts @@ -14,8 +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 { @@ -57,56 +56,47 @@ 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 -{ +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") - { + if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "yyyy\u5e74M\u6708"; } @@ -118,13 +108,11 @@ function getMonthYearPattern(locale: string | undefined, date: Date): string 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") - { + if (monthName.charAt(monthName.length - 1) == "\u6708") { // Chineese-like patterns: return "M\u6708d\u65e5"; } @@ -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"; @@ -154,18 +140,15 @@ 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 // 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 - { + } else { const yearStr = date.toLocaleDateString(locale, { year: "numeric" }); const yearStrShort = yearStr.substring(yearStr.length - 2, yearStr.length); pattern = pattern.replace(yearStr, YEAR_CODE); @@ -173,25 +156,19 @@ function getShortDatePattern(locale: string | undefined): string 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 - { + } 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 - { + } else { const dayStr = date.toLocaleDateString(locale, { day: "numeric" }); const localizedDayCode = dayStr.length == 1 ? "d" : "dd"; pattern = pattern.replace(dayStr, localizedDayCode); @@ -199,27 +176,22 @@ function getShortDatePattern(locale: string | undefined): string 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(); + 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" }); 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); @@ -228,7 +200,7 @@ function getLongDatePattern(locale: string | undefined, date: Date): string 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 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? @@ -236,14 +208,12 @@ 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 || // 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++) - { + 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,8 +251,7 @@ 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); @@ -295,36 +261,32 @@ function getMonthNames(locale: string | undefined) : { long: string[], abbreviat 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 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 @@ -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 f9d227517b819..f391947803740 100644 --- a/src/mono/browser/runtime/hybrid-globalization/change-case.ts +++ b/src/mono/browser/runtime/hybrid-globalization/change-case.ts @@ -9,15 +9,14 @@ 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 7c1bb5a03da03..03133f17d7971 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 { @@ -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 @@ -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 48c4e47828d09..3b2643646962a 100644 --- a/src/mono/browser/runtime/hybrid-globalization/culture-info.ts +++ b/src/mono/browser/runtime/hybrid-globalization/culture-info.ts @@ -8,8 +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 { @@ -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,8 +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 @@ -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 7322443a86ccd..83bf8619affec 100644 --- a/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts +++ b/src/mono/browser/runtime/hybrid-globalization/grapheme-segmenter.ts @@ -2,7 +2,7 @@ // 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 */ @@ -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,16 +96,16 @@ 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]; + const { before, after, breaks } = this.rules[key]; // match before and after rules if (before && !before.test(previous)) { continue; @@ -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, }; - + 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 4cd1b9f4eb242..0cd2294447226 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 - { + } catch { return undefined; } } -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 5b7c82a8faa58..1a6d68843e81f 100644 --- a/src/mono/browser/runtime/hybrid-globalization/locales.ts +++ b/src/mono/browser/runtime/hybrid-globalization/locales.ts @@ -8,16 +8,14 @@ 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); try { const localeNameOriginal = monoStringToString(localeRoot); const localeName = normalizeLocale(localeNameOriginal); - if (!localeName && localeNameOriginal) - { + if (!localeName && localeNameOriginal) { // handle non-standard or malformed locales by forwarding the locale code stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); wrap_no_error_root(isException, exceptionRoot); @@ -25,7 +23,7 @@ export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoSt } const cultureNameOriginal = monoStringToString(cultureRoot); const cultureName = normalizeLocale(cultureNameOriginal); - + if (!localeName || !cultureName) throw new Error(`Locale or culture name is null or empty. localeName=${localeName}, cultureName=${cultureName}`); @@ -36,27 +34,19 @@ export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoSt // 3) "language-script-region", e.g. "zh-Hans-CN" // 4) "language-script", e.g. "zh-Hans" (served in the catch block below) let languageName, regionName; - try - { + 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); - } - catch (error) - { - if (error instanceof RangeError && error.message === "invalid_argument") - { + 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); - } - catch (error) - { - if (error instanceof RangeError && error.message === "invalid_argument" && localeNameOriginal) - { + try { + 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" stringToUTF16(dst, dst + 2 * localeNameOriginal.length, localeNameOriginal); wrap_no_error_root(isException, exceptionRoot); @@ -64,9 +54,7 @@ export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoSt } throw error; } - } - else - { + } else { throw error; } } @@ -77,26 +65,24 @@ export function mono_wasm_get_locale_info(culture: MonoStringRef, locale: MonoSt const result = Object.values(localeInfo).join(OUTER_SEPARATOR); if (!result) - throw new Error(`Locale info for locale=${localeName} is null or empty.`); - + throw new Error(`Locale info for locale=${localeName} is null or empty.`); + if (result.length > dstLength) throw new Error(`Locale info for locale=${localeName} 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(); } } -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); @@ -105,18 +91,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); @@ -125,47 +109,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 @@ -175,30 +151,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 28aa01ad727cf..16b23871f9871 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 c4214b4fe5d6a..0a5a6e6c72853 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 584785be2750a..f613df56687d4 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`); @@ -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 c6a4dba0fc957..1274a162af7a7 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(); @@ -117,44 +117,39 @@ 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; } } - 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); } @@ -163,15 +158,13 @@ function bind_js_import(signature: JSFunctionSignature): Function { if (monoThreadInfo.isUI) { if (is_async || is_discard_no_wait) { wrapped_fn = async_bound_fn_ui; - } - else { + } else { wrapped_fn = sync_bound_fn_ui; } } else { if (is_async || is_discard_no_wait) { wrapped_fn = async_bound_fn; - } - else { + } else { wrapped_fn = sync_bound_fn; } } @@ -186,8 +179,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; } } @@ -201,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"); @@ -213,19 +205,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"); @@ -234,20 +225,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"); @@ -257,21 +247,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"); @@ -282,14 +271,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; @@ -298,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 { @@ -327,8 +315,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); } @@ -352,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 = {}; @@ -380,12 +367,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(); } @@ -406,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"); @@ -455,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(); @@ -478,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); } @@ -486,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); @@ -496,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"); @@ -505,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"); @@ -517,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(); @@ -532,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 cedf54cdde930..b99917dd2bb0c 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 09018413e24e7..f8da716a59346 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 7c7c35ebfac51..e71c3700e09d8 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 e79be30f55c9a..3e9fba479e1b7 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,12 +163,12 @@ 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; // TODO: Cache this table object instance and reuse it to reduce gc pressure? - const table : number[] = []; + const table: number[] = []; // IP of the start of the trace in U16s, relative to startOfBody. const rbase16 = (ip - startOfBody) / 2; @@ -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,14 +2761,14 @@ function append_call_handler_store_ret_ip( builder.callHandlerReturnAddresses.push(retIp); } -function getBranchDisplacement( +function getBranchDisplacement ( ip: MintOpcodePtr, opcode: MintOpcode -) : number | undefined { +): number | undefined { const opArgType = cwraps.mono_jiterp_get_opcode_info(opcode, OpcodeInfoType.OpArgType), payloadOffset = cwraps.mono_jiterp_get_opcode_info(opcode, OpcodeInfoType.Sregs), payloadAddress = ip + 2 + (payloadOffset * 2); - let result : number; + let result: number; switch (opArgType) { case MintOpArgType.MintOpBranch: result = getI32_unaligned(payloadAddress); @@ -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 188ead0c51e99..bf77f28960384 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 6d7ea7852f8c5..f4da4521010a9 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,11 +56,11 @@ 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[] = []; @@ -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,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); @@ -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 ec6bf96233b5d..1be22cfdd1fde 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 07b7750a2a2c6..1739bc09d1ef6 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; @@ -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; } @@ -300,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; @@ -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 940051627f304..5e76904d55259 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) { @@ -76,8 +76,12 @@ export function setLoaderGlobals( 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 2efc00f398eda..0a7823497aa85 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; @@ -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/libraryInitializers.ts b/src/mono/browser/runtime/loader/libraryInitializers.ts index 216c7fe7180e0..a8a16c543dbcc 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) { @@ -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 723e55201fcc5..668d7e667b6d3 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,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 e60fb2111b8f5..181323b0fe0a8 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: @@ -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,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"; @@ -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) { + } else if (hasFetch) { return globalThis.fetch(url, init || { credentials: "same-origin" }); - } - else if (typeof (read) === "function") { + } 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 b27c8216f4fc3..64917aa385ab4 100644 --- a/src/mono/browser/runtime/loader/promise-controller.ts +++ b/src/mono/browser/runtime/loader/promise-controller.ts @@ -9,7 +9,7 @@ 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 = { @@ -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 e0c9bd3cded56..e6cb897a0c95d 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; @@ -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,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); @@ -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 baeeaf0165f67..d14d862c05aa6 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 7494dae82876a..1d91a870d52fb 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; @@ -35,7 +35,7 @@ export function mono_log_error(msg: string, ...data: any) { } export const wasm_func_map = new Map(); -let wasm_pending_symbol_table : string | undefined; +let wasm_pending_symbol_table: string | undefined; const regexes: any[] = []; // V8 @@ -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,12 +92,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 + ""; @@ -107,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); @@ -145,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 @@ -154,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; @@ -175,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 df99745d6af37..f90fbb049d150 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,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 f408e5bebd2b1..6e954ae983df3 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,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 95cf9043bbf42..1cc4575bf55b8 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) { @@ -329,8 +329,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); @@ -338,11 +337,11 @@ function create_task_holder(res_converter?: MarshalerToJs) { return holder; } -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 +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; @@ -366,8 +365,7 @@ export function mono_wasm_resolve_or_reject_promise_impl(args: JSMarshalerArgume 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); } @@ -380,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; @@ -391,8 +389,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); @@ -403,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; @@ -431,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; @@ -442,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; @@ -485,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; @@ -510,8 +507,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); @@ -521,34 +517,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); @@ -556,20 +547,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); @@ -577,14 +565,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 10896eba1389e..c0ece106f53b2 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 getB8(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"); setB8(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 getB8(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)})`); setB8(arg, value); } -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 3152afe7eea8f..8205e6fd8098f 100644 --- a/src/mono/browser/runtime/memory.ts +++ b/src/mono/browser/runtime/memory.ts @@ -14,7 +14,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); @@ -25,7 +25,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"); @@ -37,12 +37,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"); @@ -50,17 +50,17 @@ 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); } /** note: MonoBoolean is 8 bits not 32 bits when inside a structure or array */ -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") @@ -68,7 +68,7 @@ export function setB32(offset: MemOffset, value: number | boolean): void { Module.HEAP32[offset >>> 2] = boolValue ? 1 : 0; } -export function setB8(offset: MemOffset, value: number | boolean): void { +export function setB8 (offset: MemOffset, value: number | boolean): void { const boolValue = !!value; if (typeof (value) === "number") assert_int_in_range(value, 0, 1); @@ -76,64 +76,64 @@ export function setB8(offset: MemOffset, value: number | boolean): void { Module.HEAPU8[offset] = 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; @@ -150,7 +150,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); @@ -160,7 +160,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(); @@ -168,20 +168,20 @@ 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; @@ -189,8 +189,7 @@ export function setF64(offset: MemOffset, value: number): void { let warnDirtyBool = true; -/** note: MonoBoolean is 8 bits not 32 bits when inside a structure or array */ -export function getB32(offset: MemOffset): boolean { +export function getB32 (offset: MemOffset): boolean { receiveWorkerHeapViews(); const value = (Module.HEAPU32[offset >>> 2]); if (value > 1 && warnDirtyBool) { @@ -200,81 +199,81 @@ export function getB32(offset: MemOffset): boolean { return !!value; } -export function getB8(offset: MemOffset): boolean { +export function getB8 (offset: MemOffset): boolean { receiveWorkerHeapViews(); return !!(Module.HEAPU8[offset]); } -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); @@ -284,24 +283,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]; } @@ -313,7 +312,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 { @@ -325,14 +324,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); @@ -344,7 +343,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); @@ -356,80 +355,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) { @@ -438,7 +437,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. @@ -448,23 +447,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 26150c797c81e..8998dc37c32e5 100644 --- a/src/mono/browser/runtime/polyfills.ts +++ b/src/mono/browser/runtime/polyfills.ts @@ -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; @@ -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 8dce6e31fcba2..a223a7fdbf4a7 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 1020aaf98620d..bb032c2479c0d 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(() => { @@ -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/io-thread.ts b/src/mono/browser/runtime/pthreads/io-thread.ts index ebbd2b82a9b79..011ac7b304fca 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; @@ -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 c83eb3b967e03..efa3be35ceff0 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-" @@ -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 9838615cd2163..fcb010ae3a187 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 { @@ -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 709e1980d82f5..63c108b01f841 100644 --- a/src/mono/browser/runtime/pthreads/worker-events.ts +++ b/src/mono/browser/runtime/pthreads/worker-events.ts @@ -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 5631c2475e652..fa1269c300cb6 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(); @@ -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 b31b4790e86cf..a6ccd00615ca9 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 519879f7d8438..2588ad79d9ea1 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 24958a22e0845..cef2a17f0decb 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 e35c6dc833aec..be412fb9b7023 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); @@ -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 4dcc17407b1e4..713cfb94161f9 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; @@ -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 c9cbf205d42d4..decbc6a2940bf 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 { @@ -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 1ae17e43edf19..2ab5110ec4687 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) { @@ -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 d0d798c161b28..7135694293454 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 16967d26b9d29..b333e254703b0 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"; } @@ -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 6c548d2404eea..e42f6034ead4c 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 bc50b63f1fb39..b4fd0d3950ea5 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 db11d5ef8552b..95093e37c3e97 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 fc69eb8a2b6ed..c9b0e15e9821f 100644 --- a/src/mono/browser/runtime/weak-ref.ts +++ b/src/mono/browser/runtime/weak-ref.ts @@ -5,17 +5,16 @@ 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 c7ebdac242da5..9246c1bbaf2af 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,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,15 +54,14 @@ 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; } @@ -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]) { @@ -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) { @@ -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; @@ -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); }