}
],
"no-multi-spaces": ["error"],
+ "no-console": ["error"],
"arrow-spacing": ["error"],
"block-spacing": ["error"],
"comma-spacing": ["error"],
import cwraps from "./cwraps";
import { mono_wasm_load_icu_data } from "./icu";
import { ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_WEB, Module, loaderHelpers, runtimeHelpers } from "./globals";
-import { parseSymbolMapFile } from "./logging";
+import { mono_log_info, mono_log_debug, mono_log_warn, parseSymbolMapFile } from "./logging";
import { mono_wasm_load_bytes_into_heap } from "./memory";
import { endMeasure, MeasuredBlock, startMeasure } from "./profiler";
import { AssetEntryInternal } from "./types/internal";
// 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 {
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`);
+ mono_log_debug(`Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`);
const mark = startMeasure();
const virtualName: string = typeof (asset.virtualPath) === "string"
if (fileName.startsWith("/"))
fileName = fileName.substr(1);
if (parentDirectory) {
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: Creating directory '${parentDirectory}'`);
+ mono_log_debug(`Creating directory '${parentDirectory}'`);
Module.FS_createPath(
"/", parentDirectory, true, true // fixme: should canWrite be false?
parentDirectory = "/";
}
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: Creating file '${fileName}' in directory '${parentDirectory}'`);
+ mono_log_debug(`Creating file '${fileName}' in directory '${parentDirectory}'`);
if (!mono_wasm_load_data_archive(bytes, parentDirectory)) {
Module.FS_createDataFile(
}
else if (asset.behavior === "icu") {
if (!mono_wasm_load_icu_data(offset!))
- Module.err(`MONO_WASM: Error loading ICU asset ${asset.name}`);
+ Module.err(`Error loading ICU asset ${asset.name}`);
}
else if (asset.behavior === "resource") {
cwraps.mono_wasm_add_satellite_assembly(virtualName, asset.culture || "", offset!, bytes.length);
let compiledInstance: WebAssembly.Instance;
let compiledModule: WebAssembly.Module;
if (typeof WebAssembly.instantiateStreaming === "function" && contentType === "application/wasm") {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: instantiate_wasm_module streaming");
+ mono_log_debug("instantiate_wasm_module streaming");
const streamingResult = await WebAssembly.instantiateStreaming(response, wasmModuleImports!);
compiledInstance = streamingResult.instance;
compiledModule = streamingResult.module;
} else {
if (ENVIRONMENT_IS_WEB && contentType !== "application/wasm") {
- console.warn("MONO_WASM: WebAssembly resource does not have the expected content type \"application/wasm\", so falling back to slower ArrayBuffer instantiation.");
+ mono_log_warn("WebAssembly resource does not have the expected content type \"application/wasm\", so falling back to slower ArrayBuffer instantiation.");
}
const arrayBuffer = await response.arrayBuffer();
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: instantiate_wasm_module buffered");
+ mono_log_debug("instantiate_wasm_module buffered");
if (ENVIRONMENT_IS_SHELL) {
// workaround for old versions of V8 with https://bugs.chromium.org/p/v8/issues/detail?id=13823
compiledModule = new WebAssembly.Module(arrayBuffer);
const text = await response.text();
parseSymbolMapFile(text);
} catch (error: any) {
- console.log(`MONO_WASM: Error loading symbol file ${pendingAsset.name}: ${JSON.stringify(error)}`);
+ mono_log_info(`Error loading symbol file ${pendingAsset.name}: ${JSON.stringify(error)}`);
}
}
mono_assert(loaderHelpers.actual_downloaded_assets_count == loaderHelpers.expected_downloaded_assets_count, () => `Expected ${loaderHelpers.expected_downloaded_assets_count} assets to be downloaded, but only finished ${loaderHelpers.actual_downloaded_assets_count}`);
mono_assert(loaderHelpers.actual_instantiated_assets_count == loaderHelpers.expected_instantiated_assets_count, () => `Expected ${loaderHelpers.expected_instantiated_assets_count} assets to be in memory, but only instantiated ${loaderHelpers.actual_instantiated_assets_count}`);
loaderHelpers._loaded_files.forEach(value => loaderHelpers.loadedFiles.push(value.url));
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: all assets are loaded in wasm memory");
+ mono_log_debug("all assets are loaded in wasm memory");
}
}
import type { VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer } from "./types/emscripten";
import WasmEnableLegacyJsInterop from "consts:WasmEnableLegacyJsInterop";
import { disableLegacyJsInterop, Module } from "./globals";
+import { mono_log_error } from "./logging";
type SigLine = [lazy: boolean, name: string, returnType: string | null, argTypes?: string[], opts?: any];
mono_jiterp_get_opcode_value_table_entry(opcode: number): number;
mono_jiterp_get_simd_intrinsic(arity: number, index: number): VoidPtr;
mono_jiterp_get_simd_opcode(arity: number, index: number): number;
- mono_jiterp_get_arg_offset (imethod: number, sig: number, index: number): number;
+ mono_jiterp_get_arg_offset(imethod: number, sig: number, index: number): number;
mono_jiterp_get_opcode_info(opcode: number, type: number): number;
}
const fastCwrapTypes = ["void", "number", null];
-function cwrap (name: string, returnType: string | null, argTypes: string[] | undefined, opts: any, throwOnError: boolean) : Function {
+function cwrap(name: string, returnType: string | null, argTypes: string[] | undefined, opts: any, throwOnError: boolean): Function {
// Attempt to bypass emscripten's generated wrapper if it is safe to do so
let fce =
// Special cwrap options disable the fast path
(typeof (opts) === "undefined") &&
- // Only attempt to do fast calls if all the args and the return type are either number or void
- (fastCwrapTypes.indexOf(returnType) >= 0) &&
- (!argTypes || argTypes.every(atype => fastCwrapTypes.indexOf(atype) >= 0)) &&
- // Module["asm"] may not be defined yet if we are early enough in the startup process
- // in that case, we need to rely on emscripten's lazy wrappers
- Module["asm"]
+ // Only attempt to do fast calls if all the args and the return type are either number or void
+ (fastCwrapTypes.indexOf(returnType) >= 0) &&
+ (!argTypes || argTypes.every(atype => fastCwrapTypes.indexOf(atype) >= 0)) &&
+ // Module["asm"] may not be defined yet if we are early enough in the startup process
+ // in that case, we need to rely on emscripten's lazy wrappers
+ Module["asm"]
? <Function>((<any>Module["asm"])[name])
: undefined;
// If the argument count for the wasm function doesn't match the signature, fall back to cwrap
if (fce && argTypes && (fce.length !== argTypes.length)) {
- console.error(`MONO_WASM: argument count mismatch for cwrap ${name}`);
+ mono_log_error(`argument count mismatch for cwrap ${name}`);
fce = undefined;
}
if (throwOnError)
throw new Error(msg);
else
- console.error("MONO_WASM: " + msg);
+ mono_log_error("" + msg);
}
return fce;
}
import { toBase64StringImpl } from "./base64";
import cwraps from "./cwraps";
import { VoidPtr, CharPtr } from "./types/emscripten";
+import { mono_log_warn } from "./logging";
const commands_received: any = new Map<number, CommandResponse>();
commands_received.remove = function (key: number): CommandResponse { const value = this.get(key); this.delete(key); return value; };
let _call_function_res_cache: any = {};
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}`);
// eslint-disable-next-line no-debugger
debugger;
}
};
if (commands_received.has(id))
- console.warn(`MONO_WASM: Adding an id (${id}) that already exists in commands_received`);
+ mono_log_warn(`Adding an id (${id}) that already exists in commands_received`);
commands_received.set(id, buffer_obj);
}
if (typeof args !== "object")
throw new Error(`args must be an object, but got ${JSON.stringify(args)}`);
+ // eslint-disable-next-line no-console
console.debug("mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae", JSON.stringify(event), JSON.stringify(args));
}
_assembly_name_str = Module.UTF8ToString(assembly_name).concat(".dll");
_entrypoint_method_token = entrypoint_method_token;
//keep this console.assert, otherwise optimization will remove the assignments
+ // eslint-disable-next-line no-console
console.assert(true, `Adding an entrypoint breakpoint ${_assembly_name_str} at method token ${_entrypoint_method_token}`);
// eslint-disable-next-line no-debugger
debugger;
}
if (BuildConfiguration === "Debug") {
- console.debug(`MONO_WASM: Debugger.Debug: ${message}`);
+ // eslint-disable-next-line no-console
+ console.debug(`Debugger.Debug: ${message}`);
}
}
import cwraps from "../../cwraps";
import { INTERNAL } from "../../globals";
+import { mono_log_info, mono_log_debug, mono_log_warn } from "../../logging";
import { withStackAlloc, getI32 } from "../../memory";
import { Thread, waitForThread } from "../../pthreads/browser";
import { isDiagnosticMessage, makeDiagnosticServerControlCommand } from "../shared/controller-commands";
server.port.addEventListener("message", this.onServerReply.bind(this));
}
start(): void {
- console.debug("MONO_WASM: signaling the diagnostic server to start");
+ mono_log_debug("signaling the diagnostic server to start");
this.server.postMessageToWorker(makeDiagnosticServerControlCommand("start"));
}
stop(): void {
- console.debug("MONO_WASM: signaling the diagnostic server to stop");
+ mono_log_debug("signaling the diagnostic server to stop");
this.server.postMessageToWorker(makeDiagnosticServerControlCommand("stop"));
}
postServerAttachToRuntime(): void {
- console.debug("MONO_WASM: signal the diagnostic server to attach to the runtime");
+ mono_log_debug("signal the diagnostic server to attach to the runtime");
this.server.postMessageToWorker(makeDiagnosticServerControlCommand("attach_to_runtime"));
}
if (isDiagnosticMessage(d)) {
switch (d.cmd) {
default:
- console.warn("MONO_WASM: Unknown control reply command: ", <any>d);
+ mono_log_warn("Unknown control reply command: ", <any>d);
break;
}
}
export async function startDiagnosticServer(websocket_url: string): Promise<ServerController | null> {
const sizeOfPthreadT = 4;
- console.info(`MONO_WASM: starting the diagnostic server url: ${websocket_url}`);
+ mono_log_info(`starting the diagnostic server url: ${websocket_url}`);
const result: number | undefined = withStackAlloc(sizeOfPthreadT, (pthreadIdPtr) => {
if (!cwraps.mono_wasm_diagnostic_server_create_thread(websocket_url, pthreadIdPtr))
return undefined;
return pthreadId;
});
if (result === undefined) {
- console.warn("MONO_WASM: diagnostic server failed to start");
+ mono_log_warn("diagnostic server failed to start");
return null;
}
// have to wait until the message port is created
import type { VoidPtr } from "../types/emscripten";
import { getController, startDiagnosticServer } from "./browser/controller";
import * as memory from "../memory";
+import { mono_log_warn } from "../logging";
// called from C on the main thread
if (diagnosticsInitialized)
return;
if (!monoWasmThreads) {
- console.warn("MONO_WASM: ignoring diagnostics options because this runtime does not support diagnostics");
+ mono_log_warn("ignoring diagnostics options because this runtime does not support diagnostics");
return;
} else {
const options = diagnostic_options_from_environment();
if (ports.length === 0)
return null;
if (ports.length !== 1) {
- console.warn("MONO_WASM: multiple diagnostic ports specified, only the last one will be used");
+ mono_log_warn("multiple diagnostic ports specified, only the last one will be used");
}
const portSpec = ports[ports.length - 1];
const components = portSpec.split(",");
if (components.length < 1 || components.length > 3) {
- console.warn("MONO_WASM: invalid diagnostic port specification, should be of the form <port>[,<connect>],[<nosuspend|suspend>]");
+ mono_log_warn("invalid diagnostic port specification, should be of the form <port>[,<connect>],[<nosuspend|suspend>]");
return null;
}
const uri: string = components[0];
connect = true;
break;
default:
- console.warn(`MONO_WASM: invalid diagnostic port specification component: ${component}`);
+ mono_log_warn(`invalid diagnostic port specification component: ${component}`);
break;
}
}
if (!connect) {
- console.warn("MONO_WASM: this runtime does not support listening on a diagnostic port; no diagnostic server started");
+ mono_log_warn("this runtime does not support listening on a diagnostic port; no diagnostic server started");
return null;
}
return {
import { createMockEnvironment } from "./environment";
import type { MockEnvironment, MockScriptConnection } from "./export-types";
import { assertNever } from "../../types/internal";
+import { mono_log_debug, mono_log_warn } from "../../logging";
export interface MockRemoteSocket extends EventTarget {
addEventListener<T extends keyof WebSocketEventMap>(type: T, listener: (this: MockRemoteSocket, ev: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void;
run(): Promise<void>;
}
-interface MockOptions {
- readonly trace: boolean;
-}
-
type MockConnectionScript = (engine: MockScriptConnection) => Promise<void>;
export type MockScript = (env: MockEnvironment) => MockConnectionScript[];
-let MockImplConstructor: new (script: MockScript, options?: MockOptions) => Mock;
-export function mock(script: MockScript, options?: MockOptions): Mock {
+let MockImplConstructor: new (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 {
- if (this.engine.trace) {
- console.debug(`mock ${this.engine.ident} client sent: `, data);
- }
+ mono_log_debug(`mock ${this.engine.ident} client sent: `, data);
let event: MessageEvent<string | ArrayBuffer> | null = null;
if (typeof data === "string") {
event = new MessageEvent("message", { data });
}
addEventListener<T extends keyof WebSocketEventMap>(event: T, listener: (event: WebSocketEventMap[T]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(event: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void {
- if (this.engine.trace) {
- console.debug(`mock ${this.engine.ident} client added listener for ${event}`);
- }
+ 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 {
- if (this.engine.trace) {
- console.debug(`mock ${this.engine.ident} client removed listener for ${event}`);
- }
+ mono_log_debug(`mock ${this.engine.ident} client removed listener for ${event}`);
this.engine.eventTarget.removeEventListener(event, listener);
}
close(): void {
- if (this.engine.trace) {
- console.debug(`mock ${this.engine.ident} client closed`);
- }
+ mono_log_debug(`mock ${this.engine.ident} client closed`);
this.engine.mockReplyEventTarget.dispatchEvent(new CloseEvent("close"));
}
dispatchEvent(ev: Event): boolean {
readonly eventTarget: EventTarget = new EventTarget();
// eventTarget that the MockReplySocket with send() to
readonly mockReplyEventTarget: EventTarget = new EventTarget();
- constructor(readonly trace: boolean, readonly ident: number) {
+ constructor(readonly ident: number) {
this.socket = new MockScriptEngineSocketImpl(this);
}
reply(data: ArrayBuffer | Uint8Array) {
- if (this.trace) {
- console.debug(`mock ${this.ident} reply:`, data);
- }
+ mono_log_debug(`mock ${this.ident} reply:`, data);
let sendData: ArrayBuffer;
if (typeof data === "object" && data instanceof ArrayBuffer) {
sendData = new ArrayBuffer(data.byteLength);
const sendDataView = new Uint8Array(sendData);
sendDataView.set(data);
} else {
- console.warn(`mock ${this.ident} reply got wrong kind of reply data, expected ArrayBuffer`, data);
+ mono_log_warn(`mock ${this.ident} reply got wrong kind of reply data, expected ArrayBuffer`, data);
assertNever(data);
}
this.eventTarget.dispatchEvent(new MessageEvent("message", { data: sendData }));
}
processSend(onMessage: (data: ArrayBuffer) => any): Promise<void> {
- const trace = this.trace;
- if (trace) {
- console.debug(`mock ${this.ident} processSend`);
- }
+ mono_log_debug(`mock ${this.ident} processSend`);
+
return new Promise<void>((resolve, reject) => {
this.mockReplyEventTarget.addEventListener("close", () => {
resolve();
this.mockReplyEventTarget.addEventListener("message", (event: any) => {
const data = event.data;
if (typeof data === "string") {
- console.warn(`mock ${this.ident} waitForSend got string:`, data);
+ mono_log_warn(`mock ${this.ident} waitForSend got string:`, data);
reject(new Error("mock script connection received string data"));
}
- if (trace) {
- console.debug(`mock ${this.ident} processSend got:`, data.byteLength);
- }
+ mono_log_debug(`mock ${this.ident} processSend got:`, data.byteLength);
+
onMessage(data);
});
});
}
async waitForSend<T = void>(filter: (data: ArrayBuffer) => boolean, extract?: (data: ArrayBuffer) => T): Promise<T> {
- const trace = this.trace;
- if (trace) {
- console.debug(`mock ${this.ident} waitForSend`);
- }
+ mono_log_debug(`mock ${this.ident} waitForSend`);
+
const data = await new Promise<ArrayBuffer>((resolve) => {
this.mockReplyEventTarget.addEventListener("message", (event: any) => {
const data = event.data;
if (typeof data === "string") {
- console.warn(`mock ${this.ident} waitForSend got string:`, data);
+ mono_log_warn(`mock ${this.ident} waitForSend got string:`, data);
throw new Error("mock script connection received string data");
}
- if (trace) {
- console.debug(`mock ${this.ident} waitForSend got:`, data.byteLength);
- }
+ mono_log_debug(`mock ${this.ident} waitForSend got:`, data.byteLength);
+
resolve(data);
}, { once: true });
});
openCount: number;
engines: MockScriptEngineImpl[];
connectionScripts: MockConnectionScript[];
- readonly trace: boolean;
- constructor(public readonly mockScript: MockScript, options?: MockOptions) {
+ constructor(public readonly mockScript: MockScript) {
const env: MockEnvironment = createMockEnvironment();
this.connectionScripts = mockScript(env);
this.openCount = 0;
- this.trace = options?.trace ?? false;
const count = this.connectionScripts.length;
this.engines = new Array<MockScriptEngineImpl>(count);
for (let i = 0; i < count; ++i) {
- this.engines[i] = new MockScriptEngineImpl(this.trace, i);
+ this.engines[i] = new MockScriptEngineImpl(i);
}
}
open(): MockRemoteSocket {
const i = this.openCount++;
- if (this.trace) {
- console.debug(`mock ${i} open`);
- }
+ mono_log_debug(`mock ${i} open`);
return this.engines[i].socket;
}
}
};
}
- return new MockImplConstructor(script, options);
+ return new MockImplConstructor(script);
} else {
return undefined as unknown as Mock;
}
createAdvertise,
createBinaryCommandOKReply,
} from "./ipc-protocol/serializer";
+import { mono_log_error, mono_log_info, mono_log_debug, mono_log_warn } from "../../logging";
function addOneShotProtocolCommandEventListener(src: EventTarget): Promise<ProtocolCommandEvent> {
return new Promise((resolve) => {
private attachToRuntimeController = createPromiseController<void>().promise_control;
start(): void {
- console.log(`MONO_WASM: starting diagnostic server with url: ${this.websocketUrl}`);
+ mono_log_info(`starting diagnostic server with url: ${this.websocketUrl}`);
this.startRequestedController.resolve();
}
stop(): void {
await this.startRequestedController.promise;
await this.attachToRuntimeController.promise; // can't start tracing until we've attached to the runtime
while (!this.stopRequested) {
- console.debug("MONO_WASM: diagnostic server: advertising and waiting for client");
+ mono_log_debug("diagnostic server: advertising and waiting for client");
const p1: Promise<"first" | "second"> = this.advertiseAndWaitForClient().then(() => "first");
const p2: Promise<"first" | "second"> = this.stopRequestedController.promise.then(() => "second");
const result = await Promise.race([p1, p2]);
case "first":
break;
case "second":
- console.debug("MONO_WASM: stop requested");
+ mono_log_debug("stop requested");
break;
default:
assertNever(result);
async advertiseAndWaitForClient(): Promise<void> {
try {
const connNum = this.openCount++;
- console.debug("MONO_WASM: opening websocket and sending ADVR_V1", connNum);
+ mono_log_debug("opening websocket and sending ADVR_V1", connNum);
const ws = await this.openSocket();
const p = addOneShotProtocolCommandEventListener(createProtocolSocket(ws));
this.sendAdvertise(ws);
const message = await p;
- console.debug("MONO_WASM: received advertising response: ", message, connNum);
+ mono_log_debug("received advertising response: ", message, connNum);
queueMicrotask(() => this.parseAndDispatchMessage(ws, connNum, message));
} finally {
// if there were errors, resume the runtime anyway
try {
const cmd = this.parseCommand(message, connNum);
if (cmd === null) {
- console.error("MONO_WASM: unexpected message from client", message, connNum);
+ mono_log_error("unexpected message from client", message, connNum);
return;
} else if (isEventPipeCommand(cmd)) {
await this.dispatchEventPipeCommand(ws, cmd);
} else if (isProcessCommand(cmd)) {
await this.dispatchProcessCommand(ws, cmd); // resume
} else {
- console.warn("MONO_WASM Client sent unknown command", cmd);
+ mono_log_warn("MONO_WASM Client sent unknown command", cmd);
}
} finally {
// if there were errors, resume the runtime anyway
}
parseCommand(message: ProtocolCommandEvent, connNum: number): ProtocolClientCommandBase | null {
- console.debug("MONO_WASM: parsing byte command: ", message.data, connNum);
+ mono_log_debug("parsing byte command: ", message.data, connNum);
const result = parseProtocolCommand(message.data);
- console.debug("MONO_WASM: parsed byte command: ", result, connNum);
+ mono_log_debug("parsed byte command: ", result, connNum);
if (result.success) {
return result.result;
} else {
- console.warn("MONO_WASM: failed to parse command: ", result.error, connNum);
+ mono_log_warn("failed to parse command: ", result.error, connNum);
return null;
}
}
this.attachToRuntime();
break;
default:
- console.warn("MONO_WASM: Unknown control command: ", <any>cmd);
+ mono_log_warn("Unknown control command: ", <any>cmd);
break;
}
}
} else if (isEventPipeCommandStopTracing(cmd)) {
await this.stopEventPipe(ws, cmd.sessionID);
} else {
- console.warn("MONO_WASM: unknown EventPipe command: ", cmd);
+ mono_log_warn("unknown EventPipe command: ", cmd);
}
}
}
async stopEventPipe(ws: WebSocket | MockRemoteSocket, sessionID: EventPipeSessionIDImpl): Promise<void> {
- console.debug("MONO_WASM: stopEventPipe", sessionID);
+ 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
// but the client end should be robust to that.
sessionIDbuf[3] = (session.sessionID >> 24) & 0xFF;
// sessionIDbuf[4..7] is 0 because all our session IDs are 32-bit
this.postClientReplyOK(ws, sessionIDbuf);
- console.debug("MONO_WASM: created session, now streaming: ", session);
+ mono_log_debug("created session, now streaming: ", session);
cwraps.mono_wasm_event_pipe_session_start_streaming(session.sessionID);
}
if (isProcessCommandResumeRuntime(cmd)) {
this.processResumeRuntime(ws);
} else {
- console.warn("MONO_WASM: unknown Process command", cmd);
+ mono_log_warn("unknown Process command", cmd);
}
}
resumeRuntime(): void {
if (!this.runtimeResumed) {
- console.debug("MONO_WASM: resuming runtime startup");
+ mono_log_debug("resuming runtime startup");
cwraps.mono_wasm_diagnostic_server_post_resume_runtime();
this.runtimeResumed = true;
}
/// Called by the runtime to initialize the diagnostic server workers
export function mono_wasm_diagnostic_server_on_server_thread_created(websocketUrlPtr: CharPtr): void {
const websocketUrl = Module.UTF8ToString(websocketUrlPtr);
- console.debug(`mono_wasm_diagnostic_server_on_server_thread_created, url ${websocketUrl}`);
+ mono_log_debug(`mono_wasm_diagnostic_server_on_server_thread_created, url ${websocketUrl}`);
let mock: PromiseAndController<Mock> | undefined = undefined;
if (monoDiagnosticsMock && websocketUrl.startsWith("mock:")) {
mock = createPromiseController<Mock>();
EventPipeCommandId,
ProcessCommandId,
} from "./types";
+import { mono_log_warn } from "../../../logging";
interface ParseClientCommandResultOk<C = ProtocolClientCommandBase> extends ParseResultOk {
readonly result: C;
case EventPipeCommandId.CollectTracing2:
return parseEventPipeCollectTracing2(cmd);
default:
- console.warn("MONO_WASM: unexpected EventPipe command: " + cmd.command);
+ mono_log_warn("unexpected EventPipe command: " + cmd.command);
return { success: false, error: `unexpected EventPipe command ${cmd.command}` };
}
}
case ProcessCommandId.ProcessInfo2:
throw new Error("TODO");
default:
- console.warn("MMONO_WASM: unexpected Process command: " + cmd.command);
+ mono_log_warn("unexpected Process command: " + cmd.command);
return { success: false, error: `unexpected Process command ${cmd.command}` };
}
}
import monoDiagnosticsMock from "consts:monoDiagnosticsMock";
import type { Mock } from "../mock";
import { mock } from "../mock";
-import { runtimeHelpers } from "../../globals";
export function importAndInstantiateMock(mockURL: string): Promise<Mock> {
if (monoDiagnosticsMock) {
const scriptURL = mockURL.substring(mockPrefix.length);
return import(scriptURL).then((mockModule) => {
const script = mockModule.default;
- return mock(script, { trace: runtimeHelpers.diagnosticTracing });
+ return mock(script);
});
} else {
return Promise.resolve(undefined as unknown as Mock);
import Magic from "./ipc-protocol/magic";
import Parser from "./ipc-protocol/base-parser";
import { assertNever } from "../../types/internal";
+import { mono_log_debug, mono_log_warn } from "../../logging";
export const dotnetDiagnosticsServerProtocolCommandEvent = "dotnet:diagnostics:protocolCommand" as const;
result = this.tryAppendBuffer(new Uint8Array(buf));
}
if (result.success) {
- console.debug("MONO_WASM: protocol-socket: got result", result);
+ mono_log_debug("protocol-socket: got result", result);
this.setState(result.newState);
if (result.command) {
const command = result.command;
this.emitCommandCallback(command);
}
} else {
- console.warn("MONO_WASM: socket received invalid command header", buf, result.error);
+ mono_log_warn("socket received invalid command header", buf, result.error);
// FIXME: dispatch error event?
this.setState({ state: InState.Error });
}
const pos = { pos: Magic.MinimalHeaderSize };
let result = this.tryParseCompletedBuffer(buf, pos);
if (overflow) {
- console.warn("MONO_WASM: additional bytes past command payload", overflow);
+ mono_log_warn("additional bytes past command payload", overflow);
if (result.success) {
const newResult: ParseResultBinaryCommandOk = { success: true, command: result.command, newState: { state: InState.Error } };
result = newResult;
onMessage(this: ProtocolSocketImpl, ev: MessageEvent<ArrayBuffer | Blob | string>): void {
const data = ev.data;
- console.debug("MONO_WASM: protocol socket received message", ev.data);
+ mono_log_debug("protocol socket received message", ev.data);
if (typeof data === "object" && data instanceof ArrayBuffer) {
this.onArrayBuffer(data);
} else if (typeof data === "object" && data instanceof Blob) {
data.arrayBuffer().then(this.onArrayBuffer.bind(this));
} else if (typeof data === "string") {
// otherwise it's string, ignore it.
- console.debug("MONO_WASM: protocol socket received string message; ignoring it", ev.data);
+ mono_log_debug("protocol socket received string message; ignoring it", ev.data);
} else {
assertNever(data);
}
}
onArrayBuffer(this: ProtocolSocketImpl, buf: ArrayBuffer) {
- console.debug("MONO_WASM: protocol-socket: parsing array buffer", buf);
+ 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 {
- console.debug("MONO_WASM: protocol-socket: queueing command", command);
+ mono_log_debug("protocol-socket: queueing command", command);
queueMicrotask(() => {
- console.debug("MONO_WASM: dispatching protocol event with command", command);
+ mono_log_debug("dispatching protocol event with command", command);
this.dispatchProtocolCommandEvent(command);
});
}
this.sock.addEventListener(type, listener, options);
if (type === dotnetDiagnosticsServerProtocolCommandEvent) {
if (this.protocolListeners === 0) {
- console.debug("MONO_WASM: adding protocol listener, with a message chaser");
+ mono_log_debug("adding protocol listener, with a message chaser");
this.sock.addEventListener("message", this.messageListener);
}
this.protocolListeners++;
removeEventListener<K extends keyof ProtocolSocketEventMap>(type: K, listener: (this: ProtocolSocket, ev: ProtocolSocketEventMap[K]) => any): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void {
if (type === dotnetDiagnosticsServerProtocolCommandEvent) {
- console.debug("MONO_WASM: removing protocol listener and message chaser");
+ mono_log_debug("removing protocol listener and message chaser");
this.protocolListeners--;
if (this.protocolListeners === 0) {
this.sock.removeEventListener("message", this.messageListener);
import { VoidPtr } from "../../types/emscripten";
import { Module } from "../../globals";
import type { CommonSocket } from "./common-socket";
+import { mono_log_debug, mono_log_warn } from "../../logging";
enum ListenerState {
Sending,
Closed,
}
close(): void {
- console.debug("MONO_WASM: EventPipe session stream closing websocket");
+ mono_log_debug("EventPipe session stream closing websocket");
switch (this._state) {
case ListenerState.Error:
return;
switch (this._state) {
case ListenerState.Sending:
/* unexpected message */
- console.warn("MONO_WASM: EventPipe session stream received unexpected message from websocket", event);
+ mono_log_warn("EventPipe session stream received unexpected message from websocket", event);
// TODO notify runtime that the connection had an error
this._state = ListenerState.Error;
break;
}
private _onError(event: Event) {
- console.debug("MONO_WASM: EventPipe session stream websocket error", 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
export function export_internal(): any {
return {
// tests
- mono_wasm_exit: (exit_code: number) => { Module.err("MONO_WASM: early exit " + exit_code); },
+ mono_wasm_exit: (exit_code: number) => { Module.err("early exit " + exit_code); },
mono_wasm_enable_on_demand_gc: cwraps.mono_wasm_enable_on_demand_gc,
mono_wasm_profiler_init_aot: cwraps.mono_wasm_profiler_init_aot,
mono_wasm_profiler_init_browser: cwraps.mono_wasm_profiler_init_browser,
import { mono_bind_static_method } from "./net6-legacy/method-calls";
import { export_binding_api, export_internal_api, export_mono_api } from "./net6-legacy/exports-legacy";
import { initializeLegacyExports } from "./net6-legacy/globals";
-import { mono_wasm_stringify_as_error_with_stack } from "./logging";
+import { mono_log_warn, mono_wasm_stringify_as_error_with_stack } from "./logging";
import { instantiate_asset, instantiate_symbols_asset } from "./assets";
import { jiterpreter_dump_stats } from "./jiterpreter";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
module.mono_bind_static_method = (fqn: string, signature: string/*ArgsMarshalString*/): Function => {
- console.warn("MONO_WASM: Module.mono_bind_static_method is obsolete, please use [JSExportAttribute] interop instead");
+ mono_log_warn("Module.mono_bind_static_method is obsolete, please use [JSExportAttribute] interop instead");
return mono_bind_static_method(fqn, signature);
};
}
if (is_nullish(value)) {
const stack = (new Error()).stack;
const nextLine = stack ? stack.substr(stack.indexOf("\n", 8) + 1) : "";
- console.warn(`MONO_WASM: global ${name} is obsolete, please use Module.${name} instead ${nextLine}`);
+ mono_log_warn(`global ${name} is obsolete, please use Module.${name} instead ${nextLine}`);
value = provider();
}
return value;
if (res.__reader) {
res.__reader.cancel().catch((err) => {
if (err && err.name !== "AbortError") {
- Module.err("MONO_WASM: Error in http_wasm_abort_response: " + err);
+ Module.err("Error in http_wasm_abort_response: " + err);
}
// otherwise, it's expected
});
import { assembly_load } from "./class-loader";
import { wrap_error_root, wrap_no_error_root } from "./invoke-js";
import { startMeasure, MeasuredBlock, endMeasure } from "./profiler";
+import { mono_log_debug } from "./logging";
export function mono_wasm_bind_cs_function(fully_qualified_name: MonoStringRef, signature_hash: number, signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void {
const fqn_root = mono_wasm_new_external_root<MonoString>(fully_qualified_name), resultRoot = mono_wasm_new_external_root<MonoObject>(result_address);
const js_fqn = conv_string_root(fqn_root)!;
mono_assert(js_fqn, "fully_qualified_name must be string");
- if (runtimeHelpers.diagnosticTracing) {
- console.debug(`MONO_WASM: Binding [JSExport] ${js_fqn}`);
- }
+ mono_log_debug(`Binding [JSExport] ${js_fqn}`);
const { assembly, namespace, classname, methodname } = parseFQN(js_fqn);
import { conv_string_root, js_string_to_mono_string_root } from "./strings";
import { MonoObject, MonoObjectRef, MonoString, MonoStringRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle, MarshalerType } from "./types/internal";
import { Int32Ptr } from "./types/emscripten";
-import { INTERNAL, Module, runtimeHelpers } from "./globals";
+import { INTERNAL, Module } from "./globals";
import { bind_arg_marshal_to_js } from "./marshal-to-js";
import { mono_wasm_new_external_root } from "./roots";
-import { mono_wasm_symbolicate_string } from "./logging";
+import { mono_log_debug, mono_wasm_symbolicate_string } from "./logging";
import { mono_wasm_get_jsobj_from_js_handle } from "./gc-handles";
import { endMeasure, MeasuredBlock, startMeasure } from "./profiler";
import { wrap_as_cancelable_promise } from "./cancelable-promise";
const js_function_name = conv_string_root(function_name_root)!;
const mark = startMeasure();
const js_module_name = conv_string_root(module_name_root)!;
- if (runtimeHelpers.diagnosticTracing) {
- console.debug(`MONO_WASM: Binding [JSImport] ${js_function_name} from ${js_module_name}`);
- }
+ mono_log_debug(`Binding [JSImport] ${js_function_name} from ${js_module_name}`);
+
const fn = mono_wasm_lookup_function(js_function_name, js_module_name);
const args_count = get_signature_argument_count(signature);
export function mono_wasm_set_module_imports(module_name: string, moduleImports: any) {
importedModules.set(module_name, moduleImports);
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: added module imports '${module_name}'`);
+ mono_log_debug(`added module imports '${module_name}'`);
}
function mono_wasm_lookup_function(function_name: string, js_module_name: string): Function {
let promise = importedModulesPromises.get(module_name);
const newPromise = !promise;
if (newPromise) {
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: importing ES6 module '${module_name}' from '${module_url}'`);
+ mono_log_debug(`importing ES6 module '${module_name}' from '${module_url}'`);
promise = import(/* webpackIgnore: true */module_url);
importedModulesPromises.set(module_name, promise);
}
const module = await promise;
if (newPromise) {
importedModules.set(module_name, module);
- if (runtimeHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: imported ES6 module '${module_name}' from '${module_url}'`);
+ mono_log_debug(`imported ES6 module '${module_name}' from '${module_url}'`);
}
return module;
});
getWasmFunctionTable, recordFailure, getOptions,
JiterpreterOptions, getMemberOffset, JiterpMember
} from "./jiterpreter-support";
+import { mono_log_error, mono_log_info } from "./logging";
// Controls miscellaneous diagnostic output.
const trace = 0;
compileStarted = _now();
const buffer = builder.getArrayView();
if (trace > 0)
- console.log(`jit queue generated ${buffer.length} byte(s) of wasm`);
+ mono_log_info(`jit queue generated ${buffer.length} byte(s) of wasm`);
counters.bytesGenerated += buffer.length;
const traceModule = new WebAssembly.Module(buffer);
const wasmImports = builder.getWasmImports();
rejected = false;
// console.error(`${traceName} failed: ${exc} ${exc.stack}`);
// HACK: exc.stack is enormous garbage in v8 console
- console.error(`MONO_WASM: interp_entry code generation failed: ${exc}`);
+ mono_log_error(`interp_entry code generation failed: ${exc}`);
recordFailure();
} finally {
const finished = _now();
}
if (threw || (!rejected && ((trace >= 2) || dumpWrappers))) {
- console.log(`// MONO_WASM: ${jitQueue.length} trampolines generated, blob follows //`);
+ mono_log_info(`// ${jitQueue.length} trampolines generated, blob follows //`);
let s = "", j = 0;
try {
if (builder.inSection)
s += b.toString(16);
s += " ";
if ((s.length % 10) === 0) {
- console.log(`${j}\t${s}`);
+ mono_log_info(`${j}\t${s}`);
s = "";
j = i + 1;
}
}
- console.log(`${j}\t${s}`);
- console.log("// end blob //");
+ mono_log_info(`${j}\t${s}`);
+ mono_log_info("// end blob //");
} else if (rejected && !threw) {
- console.error("MONO_WASM: failed to generate trampoline for unknown reason");
+ mono_log_error("failed to generate trampoline for unknown reason");
}
jitQueue.length = 0;
recordFailure, getOptions, bytesFromHex
} from "./jiterpreter-support";
import cwraps from "./cwraps";
+import { mono_log_error, mono_log_info } from "./logging";
// Controls miscellaneous diagnostic output.
const trace = 0;
doJitCallModule = new WebAssembly.Module(bytes);
wasmEhSupported = true;
} catch (exc) {
- console.log("MONO_WASM: Disabling WASM EH support due to JIT failure", exc);
+ mono_log_info("Disabling WASM EH support due to JIT failure", exc);
wasmEhSupported = false;
}
cwraps.mono_jiterp_update_jit_call_dispatcher(result);
failed = false;
} catch (exc) {
- console.error("MONO_WASM: failed to compile do_jit_call handler", exc);
+ mono_log_error("failed to compile do_jit_call handler", exc);
failed = true;
}
// If wasm EH support was detected, a native wasm implementation of the dispatcher was already registered.
compileStarted = _now();
const buffer = builder.getArrayView();
if (trace > 0)
- console.log(`do_jit_call queue flush generated ${buffer.length} byte(s) of wasm`);
+ mono_log_info(`do_jit_call queue flush generated ${buffer.length} byte(s) of wasm`);
counters.bytesGenerated += buffer.length;
const traceModule = new WebAssembly.Module(buffer);
const wasmImports = builder.getWasmImports();
if (!idx)
throw new Error("add_function_pointer returned a 0 index");
else if (trace >= 2)
- console.log(`${info.name} -> fn index ${idx}`);
+ mono_log_info(`${info.name} -> fn index ${idx}`);
info.result = idx;
cwraps.mono_jiterp_register_jit_call_thunk(<any>info.cinfo, idx);
rejected = false;
// console.error(`${traceName} failed: ${exc} ${exc.stack}`);
// HACK: exc.stack is enormous garbage in v8 console
- console.error(`MONO_WASM: jit_call code generation failed: ${exc}`);
+ mono_log_error(`jit_call code generation failed: ${exc}`);
recordFailure();
} finally {
const finished = _now();
// FIXME
if (threw || (!rejected && ((trace >= 2) || dumpWrappers))) {
- console.log(`// MONO_WASM: ${jitQueue.length} jit call wrappers generated, blob follows //`);
+ mono_log_info(`// ${jitQueue.length} jit call wrappers generated, blob follows //`);
for (let i = 0; i < jitQueue.length; i++)
- console.log(`// #${i} === ${jitQueue[i].name} hasThis=${jitQueue[i].hasThisReference} hasRet=${jitQueue[i].hasReturnValue} wasmArgTypes=${jitQueue[i].wasmNativeSignature}`);
+ mono_log_info(`// #${i} === ${jitQueue[i].name} hasThis=${jitQueue[i].hasThisReference} hasRet=${jitQueue[i].hasReturnValue} wasmArgTypes=${jitQueue[i].wasmNativeSignature}`);
let s = "", j = 0;
try {
s += b.toString(16);
s += " ";
if ((s.length % 10) === 0) {
- console.log(`${j}\t${s}`);
+ mono_log_info(`${j}\t${s}`);
s = "";
j = i + 1;
}
}
- console.log(`${j}\t${s}`);
- console.log("// end blob //");
+ mono_log_info(`${j}\t${s}`);
+ mono_log_info("// end blob //");
} else if (rejected && !threw) {
- console.error("MONO_WASM: failed to generate trampoline for unknown reason");
+ mono_log_error("failed to generate trampoline for unknown reason");
}
jitQueue.length = 0;
} else {
const loadWasmOp = (wasmOpcodeFromCilOpcode as any)[loadCilOp];
if (!loadWasmOp) {
- console.error(`No wasm load op for arg #${i} type ${info.paramTypes[i]} cil opcode ${loadCilOp}`);
+ mono_log_error(`No wasm load op for arg #${i} type ${info.paramTypes[i]} cil opcode ${loadCilOp}`);
return false;
}
const storeCilOp = cwraps.mono_jiterp_type_to_stind(info.returnType);
const storeWasmOp = (wasmOpcodeFromCilOpcode as any)[storeCilOp];
if (!storeWasmOp) {
- console.error(`No wasm store op for return type ${info.returnType} cil opcode ${storeCilOp}`);
+ mono_log_error(`No wasm store op for return type ${info.returnType} cil opcode ${storeCilOp}`);
return false;
}
import { WasmOpcode, WasmSimdOpcode } from "./jiterpreter-opcodes";
import { MintOpcode } from "./mintops";
import cwraps from "./cwraps";
+import { mono_log_error, mono_log_info } from "./logging";
export const maxFailures = 2,
maxMemsetSize = 64,
return current.getArrayView(false).slice(0, current.size);
}
- getWasmImports () : WebAssembly.Imports {
- const result : any = {
+ getWasmImports(): WebAssembly.Imports {
+ const result: any = {
c: <any>this.getConstants(),
m: { h: (<any>Module).asm.memory },
f: { f: getWasmFunctionTable() },
// 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
return this.current.appendU8(value);
}
- appendSimd (value: WasmSimdOpcode) {
+ appendSimd(value: WasmSimdOpcode) {
this.current.appendU8(WasmOpcode.PREFIX_simd);
// Yes that's right. We're using LEB128 to encode 8-bit opcodes. Why? I don't know
return this.current.appendULeb(value);
}
- appendU32 (value: number) {
+ appendU32(value: number) {
return this.current.appendU32(value);
}
this.appendU8(WasmOpcode.get_global);
this.appendLeb(idx);
} else {
- // console.log(`Warning: no constant slot for ${pointer} (${this.nextConstantSlot} slots used)`);
+ // mono_log_info(`Warning: no constant slot for ${pointer} (${this.nextConstantSlot} slots used)`);
this.i32_const(pointer);
}
}
this.appendULeb(this.functionTypeCount);
/*
if (trace > 1)
- console.log(`Generated ${this.functionTypeCount} wasm type(s) from ${Object.keys(this.functionTypes).length} named function types`);
+ mono_log_info(`Generated ${this.functionTypeCount} wasm type(s) from ${Object.keys(this.functionTypes).length} named function types`);
*/
for (let i = 0; i < this.functionTypeCount; i++) {
const parameters = this.functionTypesByIndex[i][0],
return imports;
}
- getCompressedName (ifi: ImportedFunctionInfo) {
- if (!this.compressImportNames || typeof(ifi.index) !== "number")
+ getCompressedName(ifi: ImportedFunctionInfo) {
+ if (!this.compressImportNames || typeof (ifi.index) !== "number")
return ifi.name;
let result = compressedNameCache[ifi.index!];
return result;
}
- getImportsToEmit () {
+ getImportsToEmit() {
const result = [];
for (const k in this.importedFunctions) {
const v = this.importedFunctions[k];
result.push(v);
}
result.sort((lhs, rhs) => lhs.index! - rhs.index!);
- // console.log("result=[" + result.map(f => `#${f.index} ${f.module}.${f.name}`) + "]");
+ // mono_log_info("result=[" + result.map(f => `#${f.index} ${f.module}.${f.name}`) + "]");
return result;
}
- _generateImportSection () {
+ _generateImportSection() {
const importsToEmit = this.getImportsToEmit();
this.lockImports = true;
this.beginSection(2);
this.appendULeb(2 + importsToEmit.length + this.constantSlots.length);
- // console.log(`referenced ${importsToEmit.length} import(s)`);
+ // mono_log_info(`referenced ${importsToEmit.length} import(s)`);
for (let i = 0; i < importsToEmit.length; i++) {
const ifi = importsToEmit[i];
- // console.log(` #${ifi.index} ${ifi.module}.${ifi.name} = ${ifi.func}. typeIndex=${ifi.typeIndex}`);
+ // mono_log_info(` #${ifi.index} ${ifi.module}.${ifi.name} = ${ifi.func}. typeIndex=${ifi.typeIndex}`);
this.appendName(ifi.module);
this.appendName(this.getCompressedName(ifi));
this.appendU8(0x0); // function
defineImportedFunction(
module: string, name: string, functionTypeName: string,
permanent: boolean, func: Function | number
- ) : ImportedFunctionInfo {
+ ): ImportedFunctionInfo {
if (this.lockImports)
throw new Error("Import section already generated");
if (permanent && (this.importedFunctionCount > 0))
this.endSection();
}
- call_indirect (functionTypeName: string, tableIndex: number) {
+ call_indirect(functionTypeName: string, tableIndex: number) {
const type = this.functionTypes[functionTypeName];
if (!type)
throw new Error("No function type named " + functionTypeName);
this.appendULeb(tableIndex);
}
- callImport (name: string) {
+ callImport(name: string) {
const func = this.importedFunctions[name];
if (!func)
throw new Error("No imported function named " + name);
let result = 0;
for (const k in parms) {
this.locals.set(k, result);
- // console.log(`parm ${k} -> ${result}`);
+ // mono_log_info(`parm ${k} -> ${result}`);
result++;
}
return result;
this.locals.set(k, idx);
break;
}
- // console.log(`local ${k} ${locals[k]} -> ${idx}`);
+ // mono_log_info(`local ${k} ${locals[k]} -> ${idx}`);
}
return localGroupCount;
const c = counts[k];
if (!c)
continue;
- // console.log(`${k} x${c}`);
+ // mono_log_info(`${k} x${c}`);
this.appendULeb(c);
this.appendU8(<any>k);
}
}
emitBlob(segment: CfgBlob, source: Uint8Array) {
- // console.log(`segment @${(<any>segment.ip).toString(16)} ${segment.start}-${segment.start + segment.length}`);
+ // mono_log_info(`segment @${(<any>segment.ip).toString(16)} ${segment.start}-${segment.start + segment.length}`);
const view = source.subarray(segment.start, segment.start + segment.length);
this.builder.appendBytes(view);
}
if (this.backDispatchOffsets.length === 0) {
if (this.trace > 0)
- console.log("No back branch targets were reachable after filtering");
+ mono_log_info("No back branch targets were reachable after filtering");
} else if (this.backDispatchOffsets.length === 1) {
if (this.trace > 0) {
if (this.backDispatchOffsets[0] === this.entryIp)
- console.log(`Exactly one back dispatch offset and it was the entry point 0x${(<any>this.entryIp).toString(16)}`);
+ mono_log_info(`Exactly one back dispatch offset and it was the entry point 0x${(<any>this.entryIp).toString(16)}`);
else
- console.log(`Exactly one back dispatch offset and it was 0x${(<any>this.backDispatchOffsets[0]).toString(16)}`);
+ mono_log_info(`Exactly one back dispatch offset and it was 0x${(<any>this.backDispatchOffsets[0]).toString(16)}`);
}
// if (disp) goto back_branch_target else fallthrough
}
if (this.trace > 1)
- console.log(`blockStack=${this.blockStack}`);
+ mono_log_info(`blockStack=${this.blockStack}`);
for (let i = 0; i < this.segments.length; i++) {
const segment = this.segments[i];
if (this.dispatchTable.has(segment.target)) {
const disp = this.dispatchTable.get(segment.target)!;
if (this.trace > 1)
- console.log(`backward br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)}: disp=${disp}`);
+ mono_log_info(`backward br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)}: disp=${disp}`);
// Set the back branch taken flag local so it will get flushed on monitoring exit
this.builder.i32_const(1);
successfulBackBranch = true;
} else {
if (this.trace > 0)
- console.log(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed: back branch target not in dispatch table`);
+ mono_log_info(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed: back branch target not in dispatch table`);
indexInStack = -1;
}
}
this.builder.appendU8(WasmOpcode.br);
this.builder.appendULeb(offset + indexInStack);
if (this.trace > 1)
- console.log(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} breaking out ${offset + indexInStack + 1} level(s)`);
+ mono_log_info(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} breaking out ${offset + indexInStack + 1} level(s)`);
} else {
if (this.trace > 0) {
const base = <any>this.base;
if ((segment.target >= base) && (segment.target < this.exitIp))
- console.log(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed (inside of trace!)`);
+ mono_log_info(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed (inside of trace!)`);
else if (this.trace > 1)
- console.log(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed (outside of trace 0x${base.toString(16)} - 0x${(<any>this.exitIp).toString(16)})`);
+ mono_log_info(`br from ${(<any>segment.from).toString(16)} to ${(<any>segment.target).toString(16)} failed (outside of trace 0x${base.toString(16)} - 0x${(<any>this.exitIp).toString(16)})`);
}
append_bailout(this.builder, segment.target, BailoutReason.Branch);
}
compilation: 0
};
-export const simdFallbackCounters : { [name: string] : number } = {
+export const simdFallbackCounters: { [name: string]: number } = {
};
export const counters = {
export function recordFailure(): void {
counters.failures++;
if (counters.failures >= maxFailures) {
- console.log(`MONO_WASM: Disabling jiterpreter after ${counters.failures} failures`);
+ mono_log_info(`Disabling jiterpreter after ${counters.failures} failures`);
applyOptions(<any>{
enableTraces: false,
enableInterpEntry: false,
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);
for (const k in options) {
const info = optionNames[k];
if (!info) {
- console.error(`Unrecognized jiterpreter option: ${k}`);
+ mono_log_error(`Unrecognized jiterpreter option: ${k}`);
continue;
}
else if (typeof (v) === "number")
cwraps.mono_jiterp_parse_option(`--${info}=${v}`);
else
- console.error(`Jiterpreter option must be a boolean or a number but was ${typeof (v)} '${v}'`);
+ mono_log_error(`Jiterpreter option must be a boolean or a number but was ${typeof (v)} '${v}'`);
}
}
simdCreateLoadOps, simdCreateSizes,
simdCreateStoreOps, simdShiftTable,
} from "./jiterpreter-tables";
+import { mono_log_error, mono_log_info } from "./logging";
/*
struct MonoVTable {
if (ip >= endOfBody) {
record_abort(traceIp, ip, traceName, "end-of-body");
if (instrumentedTraceId)
- console.log(`instrumented trace ${traceName} exited at end of body @${(<any>ip).toString(16)}`);
+ mono_log_info(`instrumented trace ${traceName} exited at end of body @${(<any>ip).toString(16)}`);
break;
}
const maxBytesGenerated = 3840,
spaceLeft = maxBytesGenerated - builder.bytesGeneratedSoFar - builder.cfg.overheadBytes;
if (builder.size >= spaceLeft) {
- // console.log(`trace too big, estimated size is ${builder.size + builder.bytesGeneratedSoFar}`);
+ // mono_log_info(`trace too big, estimated size is ${builder.size + builder.bytesGeneratedSoFar}`);
record_abort(traceIp, ip, traceName, "trace-too-big");
if (instrumentedTraceId)
- console.log(`instrumented trace ${traceName} exited because of size limit at @${(<any>ip).toString(16)} (spaceLeft=${spaceLeft}b)`);
+ mono_log_info(`instrumented trace ${traceName} exited because of size limit at @${(<any>ip).toString(16)} (spaceLeft=${spaceLeft}b)`);
break;
}
// opcodes know that it's available by branching to the top of the dispatch loop
if (isBackBranchTarget) {
if (traceBackBranches > 1)
- console.log(`${traceName} recording back branch target 0x${(<any>ip).toString(16)}`);
+ mono_log_info(`${traceName} recording back branch target 0x${(<any>ip).toString(16)}`);
builder.backBranchOffsets.push(ip);
}
// We will have bailed out if the object was null
if (builder.allowNullCheckOptimization) {
if (traceNullCheckOptimizations)
- console.log(`(0x${(<any>ip).toString(16)}) locals[${dest}] passed cknull`);
+ mono_log_info(`(0x${(<any>ip).toString(16)}) locals[${dest}] passed cknull`);
notNullSince.set(dest, <any>ip);
}
skipDregInvalidation = true;
const offset = getArgU16(ip, 2),
flag = isAddressTaken(builder, offset);
if (!flag)
- console.error(`MONO_WASM: ${traceName}: Expected local ${offset} to have address taken flag`);
+ mono_log_error(`${traceName}: Expected local ${offset} to have address taken flag`);
append_ldloca(builder, offset);
append_stloc_tail(builder, getArgU16(ip, 1), WasmOpcode.i32_store);
break;
(builder.callHandlerReturnAddresses.length > 0) &&
(builder.callHandlerReturnAddresses.length <= maxCallHandlerReturnAddresses)
) {
- // console.log(`endfinally @0x${(<any>ip).toString(16)}. return addresses:`, builder.callHandlerReturnAddresses.map(ra => (<any>ra).toString(16)));
+ // mono_log_info(`endfinally @0x${(<any>ip).toString(16)}. return addresses:`, builder.callHandlerReturnAddresses.map(ra => (<any>ra).toString(16)));
// FIXME: Clean this codegen up
// Load ret_ip
const clauseIndex = getArgU16(ip, 1),
} else {
/*
if (opcodeValue > 0)
- console.log(`JITERP: aborting trace for opcode ${opname} with value ${opcodeValue}`);
+ mono_log_info(`JITERP: aborting trace for opcode ${opname} with value ${opcodeValue}`);
*/
ip = abort;
}
prologueOpcodeCounter++;
result += opcodeValue;
} else if (opcodeValue < 0) {
- // console.log(`JITERP: opcode ${opname} did not abort but had value ${opcodeValue}`);
+ // mono_log_info(`JITERP: opcode ${opname} did not abort but had value ${opcodeValue}`);
}
ip += <any>(opLengthU16 * 2);
builder.appendU8(WasmOpcode.nop);
} else {
if (instrumentedTraceId)
- console.log(`instrumented trace ${traceName} aborted for opcode ${opname} @${(<any>_ip).toString(16)}`);
+ mono_log_info(`instrumented trace ${traceName} aborted for opcode ${opname} @${(<any>_ip).toString(16)}`);
record_abort(traceIp, _ip, traceName, opcode);
}
}
builder.cfg.exitIp = rip;
- // console.log(`estimated size: ${builder.size + builder.cfg.overheadBytes + builder.bytesGeneratedSoFar}`);
+ // mono_log_info(`estimated size: ${builder.size + builder.cfg.overheadBytes + builder.bytesGeneratedSoFar}`);
// HACK: Traces containing simd will be *much* shorter than non-simd traces,
// which will cause both the heuristic and our length requirement outside
counters.nullChecksEliminated++;
if (nullCheckCaching && (cknullOffset === localOffset)) {
if (traceNullCheckOptimizations)
- console.log(`(0x${(<any>ip).toString(16)}) cknull_ptr == locals[${localOffset}], not null since 0x${notNullSince.get(localOffset)!.toString(16)}`);
+ mono_log_info(`(0x${(<any>ip).toString(16)}) cknull_ptr == locals[${localOffset}], not null since 0x${notNullSince.get(localOffset)!.toString(16)}`);
if (leaveOnStack)
builder.local("cknull_ptr");
} else {
- // console.log(`skipping null check for ${localOffset}`);
+ // mono_log_info(`skipping null check for ${localOffset}`);
append_ldloc(builder, localOffset, WasmOpcode.i32_load);
builder.local("cknull_ptr", leaveOnStack ? WasmOpcode.tee_local : WasmOpcode.set_local);
if (traceNullCheckOptimizations)
- console.log(`(0x${(<any>ip).toString(16)}) cknull_ptr := locals[${localOffset}] (fresh load, already null checked at 0x${notNullSince.get(localOffset)!.toString(16)})`);
+ mono_log_info(`(0x${(<any>ip).toString(16)}) cknull_ptr := locals[${localOffset}] (fresh load, already null checked at 0x${notNullSince.get(localOffset)!.toString(16)})`);
cknullOffset = localOffset;
}
) {
notNullSince.set(localOffset, <any>ip);
if (traceNullCheckOptimizations)
- console.log(`(0x${(<any>ip).toString(16)}) cknull_ptr := locals[${localOffset}] (fresh load, fresh null check)`);
+ mono_log_info(`(0x${(<any>ip).toString(16)}) cknull_ptr := locals[${localOffset}] (fresh load, fresh null check)`);
cknullOffset = localOffset;
} else
cknullOffset = -1;
builder.endBlock();
} else {
if (traceNullCheckOptimizations)
- console.log(`(0x${(<any>ip).toString(16)}) locals[${objectOffset}] not null since 0x${notNullSince.get(objectOffset)!.toString(16)}`);
+ mono_log_info(`(0x${(<any>ip).toString(16)}) locals[${objectOffset}] not null since 0x${notNullSince.get(objectOffset)!.toString(16)}`);
builder.appendU8(WasmOpcode.drop);
counters.nullChecksEliminated++;
builder.appendU8(WasmOpcode.i32_store);
builder.appendMemarg(clauseDataOffset, 0); // FIXME: 32-bit alignment?
- // console.log(`call_handler @0x${(<any>ip).toString(16)} retIp=0x${retIp.toString(16)}`);
+ // mono_log_info(`call_handler @0x${(<any>ip).toString(16)} retIp=0x${retIp.toString(16)}`);
builder.callHandlerReturnAddresses.push(retIp);
}
: getArgI16(ip, 1);
if (traceBranchDisplacements)
- console.log(`br.s @${ip} displacement=${displacement}`);
+ mono_log_info(`br.s @${ip} displacement=${displacement}`);
const destination = <any>ip + (displacement * 2);
if (displacement <= 0) {
// to the top of the loop body
// append_safepoint(builder, ip);
if (traceBackBranches > 1)
- console.log(`performing backward branch to 0x${destination.toString(16)}`);
+ mono_log_info(`performing backward branch to 0x${destination.toString(16)}`);
if (isCallHandler)
append_call_handler_store_ret_ip(builder, ip, frame, opcode);
builder.cfg.branch(destination, true, false);
} else {
if (destination < builder.cfg.entryIp) {
if ((traceBackBranches > 1) || (builder.cfg.trace > 1))
- console.log(`${getOpcodeName(opcode)} target 0x${destination.toString(16)} before start of trace`);
+ mono_log_info(`${getOpcodeName(opcode)} target 0x${destination.toString(16)} before start of trace`);
} else if ((traceBackBranches > 0) || (builder.cfg.trace > 0))
- console.log(`0x${(<any>ip).toString(16)} ${getOpcodeName(opcode)} target 0x${destination.toString(16)} not found in list ` +
+ mono_log_info(`0x${(<any>ip).toString(16)} ${getOpcodeName(opcode)} target 0x${destination.toString(16)} not found in list ` +
builder.backBranchOffsets.map(bbo => "0x" + (<any>bbo).toString(16)).join(", ")
);
if (!displacement)
throw new Error("Branch had no displacement");
else if (traceBranchDisplacements)
- console.log(`${getOpcodeName(opcode)} @${ip} displacement=${displacement}`);
+ mono_log_info(`${getOpcodeName(opcode)} @${ip} displacement=${displacement}`);
const destination = <any>ip + (displacement * 2);
// We found a backwards branch target we can reach via our outer trace loop, so
// we update eip and branch out to the top of the loop block
if (traceBackBranches > 1)
- console.log(`performing conditional backward branch to 0x${destination.toString(16)}`);
+ mono_log_info(`performing conditional backward branch to 0x${destination.toString(16)}`);
builder.cfg.branch(destination, true, true);
counters.backBranchesEmitted++;
} else {
if (destination < builder.cfg.entryIp) {
if ((traceBackBranches > 1) || (builder.cfg.trace > 1))
- console.log(`${getOpcodeName(opcode)} target 0x${destination.toString(16)} before start of trace`);
+ mono_log_info(`${getOpcodeName(opcode)} target 0x${destination.toString(16)} before start of trace`);
} else if ((traceBackBranches > 0) || (builder.cfg.trace > 0))
- console.log(`0x${(<any>ip).toString(16)} ${getOpcodeName(opcode)} target 0x${destination.toString(16)} not found in list ` +
+ mono_log_info(`0x${(<any>ip).toString(16)} ${getOpcodeName(opcode)} target 0x${destination.toString(16)} not found in list ` +
builder.backBranchOffsets.map(bbo => "0x" + (<any>bbo).toString(16)).join(", ")
);
// We didn't find a loop to branch to, so bail out
builder.block();
const displacement = getArgI16(ip, 3);
if (traceBranchDisplacements)
- console.log(`relop @${ip} displacement=${displacement}`);
+ mono_log_info(`relop @${ip} displacement=${displacement}`);
const operandLoadOp = relopInfo
? relopInfo[1]
new WebAssembly.Module(bytes);
wasmSimdSupported = true;
} catch (exc) {
- console.log("MONO_WASM: Disabling WASM SIMD support due to JIT failure", exc);
+ mono_log_info("Disabling WASM SIMD support due to JIT failure", exc);
wasmSimdSupported = false;
}
return true;
}
default:
- console.log(`MONO_WASM: jiterpreter emit_simd failed for ${opname}`);
+ mono_log_info(`jiterpreter emit_simd failed for ${opname}`);
return false;
}
}
import {
generateWasmBody
} from "./jiterpreter-trace-generator";
+import { mono_log_error, mono_log_info, mono_log_warn } from "./logging";
// Controls miscellaneous diagnostic output.
export const trace = 0;
const info = traceInfo[<any>base];
if (!info) {
- console.error(`trace info not found for ${base}`);
+ mono_log_error(`trace info not found for ${base}`);
return;
}
let table = info.bailoutCounts;
if (useDebugCount) {
if (cwraps.mono_jiterp_debug_count() === 0) {
if (countLimitedPrintCounter-- >= 0)
- console.log(`COUNT limited: ${methodFullName || methodName} @${(traceOffset).toString(16)}`);
+ mono_log_info(`COUNT limited: ${methodFullName || methodName} @${(traceOffset).toString(16)}`);
return 0;
}
}
);
const instrumentedTraceId = instrument ? nextInstrumentedTraceId++ : 0;
if (instrument) {
- console.log(`instrumenting: ${methodFullName}`);
+ mono_log_info(`instrumenting: ${methodFullName}`);
instrumentedTraces[instrumentedTraceId] = new InstrumentedTraceState(methodFullName);
}
builder.compressImportNames = compressImportNames && !instrument;
ti.abortReason = "trace-too-small";
if (traceTooSmall && (traceValue > 1))
- console.log(`${traceName} too small: value=${traceValue}, ${builder.current.size} wasm bytes`);
+ mono_log_info(`${traceName} too small: value=${traceValue}, ${builder.current.size} wasm bytes`);
return 0;
}
compileStarted = _now();
const buffer = builder.getArrayView();
- // console.log(`bytes generated: ${buffer.length}`);
+ // mono_log_info(`bytes generated: ${buffer.length}`);
if (trace > 0)
- console.log(`${(<any>(builder.base)).toString(16)} ${methodFullName || traceName} generated ${buffer.length} byte(s) of wasm`);
+ mono_log_info(`${(<any>(builder.base)).toString(16)} ${methodFullName || traceName} generated ${buffer.length} byte(s) of wasm`);
counters.bytesGenerated += buffer.length;
if (buffer.length >= maxModuleSize) {
- console.warn(`MONO_WASM: Jiterpreter generated too much code (${buffer.length} bytes) for trace ${traceName}. Please report this issue.`);
+ mono_log_warn(`Jiterpreter generated too much code (${buffer.length} bytes) for trace ${traceName}. Please report this issue.`);
return 0;
}
if (!idx)
throw new Error("add_function_pointer returned a 0 index");
else if (trace >= 2)
- console.log(`${traceName} -> fn index ${idx}`);
+ mono_log_info(`${traceName} -> fn index ${idx}`);
// Ensure that a bit of ongoing diagnostic output is printed for very long-running test
// suites or benchmarks if you've enabled stats
} catch (exc: any) {
threw = true;
rejected = false;
- console.error(`MONO_WASM: ${methodFullName || traceName} code generation failed: ${exc} ${exc.stack}`);
+ mono_log_error(`${methodFullName || traceName} code generation failed: ${exc} ${exc.stack}`);
recordFailure();
return 0;
} finally {
if (threw || (!rejected && ((trace >= 2) || mostRecentOptions!.dumpTraces)) || instrument) {
if (threw || (trace >= 3) || mostRecentOptions!.dumpTraces || instrument) {
for (let i = 0; i < builder.traceBuf.length; i++)
- console.log(builder.traceBuf[i]);
+ mono_log_info(builder.traceBuf[i]);
}
- console.log(`// MONO_WASM: ${methodFullName || traceName} generated, blob follows //`);
+ mono_log_info(`// ${methodFullName || traceName} generated, blob follows //`);
let s = "", j = 0;
try {
// We may have thrown an uncaught exception while inside a block,
s += b.toString(16);
s += " ";
if ((s.length % 10) === 0) {
- console.log(`${j}\t${s}`);
+ mono_log_info(`${j}\t${s}`);
s = "";
j = i + 1;
}
}
- console.log(`${j}\t${s}`);
- console.log("// end blob //");
+ mono_log_info(`${j}\t${s}`);
+ mono_log_info("// end blob //");
}
}
}
}
if ((traceAbortLocations && (reason !== "end-of-body")) || (trace >= 2))
- console.log(`abort ${traceIp} ${traceName}@${ip} ${reason}`);
+ mono_log_info(`abort ${traceIp} ${traceName}@${ip} ${reason}`);
traceInfo[<any>traceIp].abortReason = reason;
}
if (!mostRecentOptions.enableStats && (b !== undefined))
return;
- console.log(`// jitted ${counters.bytesGenerated} bytes; ${counters.tracesCompiled} traces (${counters.traceCandidates} candidates, ${(counters.tracesCompiled / counters.traceCandidates * 100).toFixed(1)}%); ${counters.jitCallsCompiled} jit_calls (${(counters.directJitCallsCompiled / counters.jitCallsCompiled * 100).toFixed(1)}% direct); ${counters.entryWrappersCompiled} interp_entries`);
+ mono_log_info(`// jitted ${counters.bytesGenerated} bytes; ${counters.tracesCompiled} traces (${counters.traceCandidates} candidates, ${(counters.tracesCompiled / counters.traceCandidates * 100).toFixed(1)}%); ${counters.jitCallsCompiled} jit_calls (${(counters.directJitCallsCompiled / counters.jitCallsCompiled * 100).toFixed(1)}% direct); ${counters.entryWrappersCompiled} interp_entries`);
const backBranchHitRate = (counters.backBranchesEmitted / (counters.backBranchesEmitted + counters.backBranchesNotEmitted)) * 100;
const tracesRejected = cwraps.mono_jiterp_get_rejected_trace_count();
- console.log(`// time: ${elapsedTimes.generation | 0}ms generating, ${elapsedTimes.compilation | 0}ms compiling wasm. ${counters.nullChecksEliminated} cknulls removed. ${counters.backBranchesEmitted} back-branches (${counters.backBranchesNotEmitted} failed, ${backBranchHitRate.toFixed(1)}%), ${tracesRejected} traces rejected`);
+ mono_log_info(`// time: ${elapsedTimes.generation | 0}ms generating, ${elapsedTimes.compilation | 0}ms compiling wasm. ${counters.nullChecksEliminated} cknulls removed. ${counters.backBranchesEmitted} back-branches (${counters.backBranchesNotEmitted} failed, ${backBranchHitRate.toFixed(1)}%), ${tracesRejected} traces rejected`);
if (concise)
return;
for (let i = 0; i < BailoutReasonNames.length; i++) {
const bailoutCount = cwraps.mono_jiterp_get_trace_bailout_count(i);
if (bailoutCount)
- console.log(`// traces bailed out ${bailoutCount} time(s) due to ${BailoutReasonNames[i]}`);
+ mono_log_info(`// traces bailed out ${bailoutCount} time(s) due to ${BailoutReasonNames[i]}`);
}
for (let i = 0, c = 0; i < traces.length && c < summaryStatCount; i++) {
if (!trace.bailoutCount)
continue;
c++;
- console.log(`${trace.name}: ${trace.bailoutCount} bailout(s)`);
+ mono_log_info(`${trace.name}: ${trace.bailoutCount} bailout(s)`);
for (const k in trace.bailoutCounts)
- console.log(` ${BailoutReasonNames[<any>k]} x${trace.bailoutCounts[<any>k]}`);
+ mono_log_info(` ${BailoutReasonNames[<any>k]} x${trace.bailoutCounts[<any>k]}`);
}
}
}
if (countCallTargets) {
- console.log("// hottest call targets:");
+ mono_log_info("// hottest call targets:");
const targetPointers = Object.keys(callTargetCounts);
targetPointers.sort((l, r) => callTargetCounts[Number(r)] - callTargetCounts[Number(l)]);
for (let i = 0, c = Math.min(summaryStatCount, targetPointers.length); i < c; i++) {
const targetMethodName = Module.UTF8ToString(pMethodName);
const hitCount = callTargetCounts[<any>targetMethod];
Module._free(<any>pMethodName);
- console.log(`${targetMethodName} ${hitCount}`);
+ mono_log_info(`${targetMethodName} ${hitCount}`);
}
}
traces.sort((l, r) => r.hitCount - l.hitCount);
- console.log("// hottest failed traces:");
+ mono_log_info("// hottest failed traces:");
for (let i = 0, c = 0; i < traces.length && c < summaryStatCount; i++) {
// this means the trace has a low hit count and we don't know its identity. no value in
// logging it.
}
c++;
- console.log(`${traces[i].name} @${traces[i].ip} (${traces[i].hitCount} hits) ${traces[i].abortReason}`);
+ mono_log_info(`${traces[i].name} @${traces[i].ip} (${traces[i].hitCount} hits) ${traces[i].abortReason}`);
}
const tuples: Array<[string, number]> = [];
tuples.sort((l, r) => r[1] - l[1]);
- console.log("// heat:");
+ mono_log_info("// heat:");
for (let i = 0; i < tuples.length; i++)
- console.log(`// ${tuples[i][0]}: ${tuples[i][1]}`);
+ mono_log_info(`// ${tuples[i][0]}: ${tuples[i][1]}`);
} else {
for (let i = 0; i < MintOpcode.MINT_LASTOP; i++) {
const opname = getOpcodeName(i);
const keys = Object.keys(abortCounts);
keys.sort((l, r) => abortCounts[r] - abortCounts[l]);
for (let i = 0; i < keys.length; i++)
- console.log(`// ${keys[i]}: ${abortCounts[keys[i]]} abort(s)`);
+ mono_log_info(`// ${keys[i]}: ${abortCounts[keys[i]]} abort(s)`);
}
for (const k in counters.simdFallback)
- console.log(`// simd ${k}: ${counters.simdFallback[k]} fallback insn(s)`);
+ mono_log_info(`// simd ${k}: ${counters.simdFallback[k]} fallback insn(s)`);
if ((typeof (globalThis.setTimeout) === "function") && (b !== undefined))
setTimeout(
import type { AssetBehaviours, AssetEntry, LoadingResource, ResourceRequest } from "../types";
import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, loaderHelpers, runtimeHelpers } from "./globals";
import { createPromiseController } from "./promise-controller";
+import { mono_log_debug } from "./logging";
let throttlingPromise: PromiseAndController<void> | undefined;
return asset;
}
export async function mono_download_assets(): Promise<void> {
- if (loaderHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_download_assets");
+ mono_log_debug("mono_download_assets");
loaderHelpers.maxParallelDownloads = loaderHelpers.config.maxParallelDownloads || loaderHelpers.maxParallelDownloads;
loaderHelpers.enableDownloadRetry = loaderHelpers.config.enableDownloadRetry || loaderHelpers.enableDownloadRetry;
try {
Promise.all(promises_of_asset_instantiation).then(() => {
runtimeHelpers.allAssetsInMemory.promise_control.resolve();
}).catch(e => {
- loaderHelpers.err("MONO_WASM: Error in mono_download_assets: " + e);
+ loaderHelpers.err("Error in mono_download_assets: " + e);
loaderHelpers.abort_startup(e, true);
});
// OPTIMIZATION explained:
// spreading in time
// rather than to block all downloads after onRuntimeInitialized or block onRuntimeInitialized after all downloads are done. That would create allocation burst.
} catch (e: any) {
- loaderHelpers.err("MONO_WASM: Error in mono_download_assets: " + e);
+ loaderHelpers.err("Error in mono_download_assets: " + e);
throw e;
}
}
try {
++parallel_count;
if (parallel_count == loaderHelpers.maxParallelDownloads) {
- if (loaderHelpers.diagnosticTracing)
- console.debug("MONO_WASM: Throttling further parallel downloads");
+ mono_log_debug("Throttling further parallel downloads");
throttlingPromise = createPromiseController<void>();
}
finally {
--parallel_count;
if (throttlingPromise && parallel_count == loaderHelpers.maxParallelDownloads - 1) {
- if (loaderHelpers.diagnosticTracing)
- console.debug("MONO_WASM: Resuming more parallel downloads");
+ mono_log_debug("Resuming more parallel downloads");
const old_throttling = throttlingPromise;
throttlingPromise = undefined;
old_throttling.promise_control.resolve();
const attemptUrl = resolve_path(asset, sourcePrefix);
if (asset.name === attemptUrl) {
- if (loaderHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: Attempting to download '${attemptUrl}'`);
+ mono_log_debug(`Attempting to download '${attemptUrl}'`);
} else {
- if (loaderHelpers.diagnosticTracing)
- console.debug(`MONO_WASM: Attempting to download '${attemptUrl}' for ${asset.name}`);
+ mono_log_debug(`Attempting to download '${attemptUrl}' for ${asset.name}`);
}
try {
asset.resolvedUrl = attemptUrl;
const isOkToFail = asset.isOptional || (asset.name.match(/\.pdb$/) && loaderHelpers.config.ignorePdbLoadErrors);
mono_assert(response, () => `Response undefined ${asset.name}`);
if (!isOkToFail) {
- const err: any = new Error(`MONO_WASM: download '${response.url}' for ${asset.name} failed ${response.status} ${response.statusText}`);
+ const err: any = new Error(`download '${response.url}' for ${asset.name} failed ${response.status} ${response.statusText}`);
err.status = response.status;
throw err;
} else {
- loaderHelpers.out(`MONO_WASM: optional download '${response.url}' for ${asset.name} failed ${response.status} ${response.statusText}`);
+ loaderHelpers.out(`optional download '${response.url}' for ${asset.name} failed ${response.status} ${response.statusText}`);
return undefined;
}
}
}
const linkerDisabledWarning = this.bootConfig.linkerEnabled ? "%c" : "\n%cThis application was built with linking (tree shaking) disabled. Published applications will be significantly smaller.";
+ // eslint-disable-next-line no-console
console.groupCollapsed(`%cdotnet%c Loaded ${toDataSizeString(totalResponseBytes)} resources${linkerDisabledWarning}`, "background: purple; color: white; padding: 1px 3px; border-radius: 3px;", "font-weight: bold;", "font-weight: normal;");
if (cacheLoadsEntries.length) {
+ // eslint-disable-next-line no-console
console.groupCollapsed(`Loaded ${toDataSizeString(cacheResponseBytes)} resources from cache`);
+ // eslint-disable-next-line no-console
console.table(this.cacheLoads);
+ // eslint-disable-next-line no-console
console.groupEnd();
}
if (networkLoadsEntries.length) {
+ // eslint-disable-next-line no-console
console.groupCollapsed(`Loaded ${toDataSizeString(networkResponseBytes)} resources from network`);
+ // eslint-disable-next-line no-console
console.table(this.networkLoads);
+ // eslint-disable-next-line no-console
console.groupEnd();
}
+ // eslint-disable-next-line no-console
console.groupEnd();
}
import { initializeBootConfig, loadBootConfig } from "./blazor/_Integration";
import { BootConfigResult } from "./blazor/BootConfig";
import { BootJsonData } from "../types/blazor";
+import { mono_log_error, mono_log_debug } from "./logging";
export function deep_merge_config(target: MonoConfigInternal, source: MonoConfigInternal): MonoConfigInternal {
const providedConfig: MonoConfigInternal = { ...source };
runtimeHelpers.waitForDebugger = config.waitForDebugger;
config.startupMemoryCache = !!config.startupMemoryCache;
if (config.startupMemoryCache && runtimeHelpers.waitForDebugger) {
- if (loaderHelpers.diagnosticTracing) console.info("MONO_WASM: Disabling startupMemoryCache because waitForDebugger is set");
+ mono_log_debug("Disabling startupMemoryCache because waitForDebugger is set");
config.startupMemoryCache = false;
}
loaderHelpers.afterConfigLoaded.promise_control.resolve(loaderHelpers.config);
return;
}
- if (loaderHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_load_config");
+ mono_log_debug("mono_wasm_load_config");
try {
loaderHelpers.config.applicationEnvironment = loaderHelpers.config.applicationEnvironment ?? loaderHelpers.config.startupOptions?.environment ?? "Production";
normalizeConfig();
}
catch (err: any) {
- console.error("MONO_WASM: onConfigLoaded() failed", err);
+ mono_log_error("onConfigLoaded() failed", err);
throw err;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_WEB, INTERNAL, loaderHelpers, runtimeHelpers } from "./globals";
-import { consoleWebSocket } from "./logging";
+import { mono_log_debug, consoleWebSocket, mono_log_error, mono_log_info_no_prefix } from "./logging";
export function abort_startup(reason: any, should_exit: boolean): void {
- if (loaderHelpers.diagnosticTracing) console.trace("MONO_WASM: abort_startup");
+ mono_log_debug("abort_startup");
loaderHelpers.allDownloadsQueued.promise_control.reject(reason);
loaderHelpers.afterConfigLoaded.promise_control.reject(reason);
loaderHelpers.wasmDownloadPromise.promise_control.reject(reason);
const stdoutFlushed = flushStream(process.stdout);
await Promise.all([stdoutFlushed, stderrFlushed]);
} catch (err) {
- console.error(`flushing std* streams failed: ${err}`);
+ mono_log_error(`flushing std* streams failed: ${err}`);
}
}
if (loaderHelpers.config && loaderHelpers.config.logExitCode) {
if (exit_code != 0 && reason) {
if (reason instanceof Error && runtimeHelpers.stringify_as_error_with_stack)
- console.error(runtimeHelpers.stringify_as_error_with_stack(reason));
+ mono_log_error(runtimeHelpers.stringify_as_error_with_stack(reason));
else if (typeof reason == "string")
- console.error(reason);
+ mono_log_error(reason);
else
- console.error(JSON.stringify(reason));
+ mono_log_error(JSON.stringify(reason));
}
if (consoleWebSocket) {
const stop_when_ws_buffer_empty = () => {
if (consoleWebSocket.bufferedAmount == 0) {
// tell xharness WasmTestMessagesProcessor we are done.
// note this sends last few bytes into the same WS
- console.log("WASM EXIT " + exit_code);
+ mono_log_info_no_prefix("WASM EXIT " + exit_code);
}
else {
setTimeout(stop_when_ws_buffer_empty, 100);
};
stop_when_ws_buffer_empty();
} else {
- console.log("WASM EXIT " + exit_code);
+ mono_log_info_no_prefix("WASM EXIT " + exit_code);
}
}
}
// The .NET Foundation licenses this file to you under the MIT license.
import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals";
+import { mono_log_info, mono_log_debug } from "./logging";
export function init_globalization() {
loaderHelpers.invariantMode = loaderHelpers.config.globalizationMode === "invariant";
if (!loaderHelpers.invariantMode) {
if (loaderHelpers.preferredIcuAsset) {
- if (loaderHelpers.diagnosticTracing) console.debug("MONO_WASM: ICU data archive(s) available, disabling invariant mode");
+ mono_log_debug("ICU data archive(s) available, disabling invariant mode");
} else if (loaderHelpers.config.globalizationMode !== "icu") {
- if (loaderHelpers.diagnosticTracing) console.debug("MONO_WASM: ICU data archive(s) not available, using invariant globalization mode");
+ mono_log_debug("ICU data archive(s) not available, using invariant globalization mode");
loaderHelpers.invariantMode = true;
loaderHelpers.preferredIcuAsset = null;
} else {
const msg = "invariant globalization mode is inactive and no ICU data archives are available";
- loaderHelpers.err(`MONO_WASM: ERROR: ${msg}`);
+ loaderHelpers.err(`ERROR: ${msg}`);
throw new Error(msg);
}
}
env_variables!["TZ"] = timezone;
}
} catch {
- console.info("MONO_WASM: failed to detect timezone, will fallback to UTC");
+ mono_log_info("failed to detect timezone, will fallback to UTC");
}
}
}
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+/* eslint-disable no-console */
+import { loaderHelpers } from "./globals";
+
+const prefix = "MONO_WASM: ";
+
+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) {
+ console.info(prefix + msg, ...data);
+}
+
+export function mono_log_info_no_prefix(msg: string, ...data: any) {
+ console.info(msg, ...data);
+}
+
+export function mono_log_warn(msg: string, ...data: any) {
+ console.warn(prefix + msg, ...data);
+}
+
+export function mono_log_error(msg: string, ...data: any) {
+ console.error(prefix + msg, ...data);
+}
export let consoleWebSocket: WebSocket;
export function setup_proxy_console(id: string, console: Console, origin: string): void {
};
loaderHelpers.downloadResource = module.downloadResource;
loaderHelpers.fetch_like = fetch_like;
+ // eslint-disable-next-line no-console
loaderHelpers.out = console.log;
+ // eslint-disable-next-line no-console
loaderHelpers.err = console.error;
loaderHelpers.getApplicationEnvironment = module.getApplicationEnvironment;
if (typeof moduleFactory === "function") {
const extension = moduleFactory(globalObjectsRoot.api) as any;
if (extension.ready) {
- throw new Error("MONO_WASM: Module.ready couldn't be redefined.");
+ throw new Error("Module.ready couldn't be redefined.");
}
Object.assign(module, extension);
deep_merge_module(module, extension);
deep_merge_module(module, moduleFactory);
}
else {
- throw new Error("MONO_WASM: Can't use moduleFactory callback of createDotnetRuntime function.");
+ throw new Error("Can't use moduleFactory callback of createDotnetRuntime function.");
}
return module.ENVIRONMENT_IS_PTHREAD
import { MonoConfigInternal } from "../types/internal";
import { deep_merge_config } from "./config";
import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals";
+import { mono_log_debug } from "./logging";
export const monoSymbol = "__mono_message_please_dont_collide__"; //Symbol("mono");
// called when the main thread sends us the mono config
function onMonoConfigReceived(config: MonoConfigInternal): void {
if (workerMonoConfigReceived) {
- console.debug("MONO_WASM: mono config already received");
+ mono_log_debug("mono config already received");
return;
}
deep_merge_config(loaderHelpers.config, config);
- console.debug("MONO_WASM: mono config received");
+ mono_log_debug("mono config received");
workerMonoConfigReceived = true;
loaderHelpers.afterConfigLoaded.promise_control.resolve(loaderHelpers.config);
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+/* eslint-disable no-console */
import { INTERNAL, Module, runtimeHelpers } from "./globals";
import { CharPtr, VoidPtr } from "./types/emscripten";
+const prefix = "MONO_WASM: ";
+
+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) {
+ console.info(prefix + msg, ...data);
+}
+
+export function mono_log_warn(msg: string, ...data: any) {
+ console.warn(prefix + msg, ...data);
+}
+
+export function mono_log_error(msg: string, ...data: any) {
+ console.error(prefix + msg, ...data);
+}
+
export const wasm_func_map = new Map<number, string>();
const regexes: any[] = [];
return origMessage;
} catch (error) {
- console.debug(`MONO_WASM: failed to symbolicate: ${error}`);
+ console.debug(`failed to symbolicate: ${error}`);
return message;
}
}
wasm_func_map.set(Number(parts[0]), parts[1]);
});
- if (runtimeHelpers.diagnosticTracing) console.debug(`MONO_WASM: Loaded ${wasm_func_map.size} symbols`);
+ mono_log_debug(`Loaded ${wasm_func_map.size} symbols`);
}
\ No newline at end of file
}
const js_handle = get_arg_js_handle(arg);
- // console.log("_marshal_task_to_js A" + js_handle);
if (js_handle == JSHandleNull) {
// this is already resolved void
return new Promise((resolve) => resolve(undefined));
const orig_resolve = promise_control.resolve;
promise_control.resolve = (argInner: JSMarshalerArgument) => {
- // console.log("_marshal_task_to_js R" + js_handle);
const type = get_arg_type(argInner);
if (type === MarshalerType.None) {
orig_resolve(null);
import { legacyHelpers } from "./globals";
import { js_to_mono_obj_root, _js_to_mono_uri_root, js_to_mono_enum } from "./js-to-cs";
import { _teardown_after_call } from "./method-calls";
+import { mono_log_warn } from "../logging";
const escapeRE = /[^A-Za-z0-9_$]/g;
converter.compiled_function = <ConverterFunction>compiledFunction;
} catch (exc) {
converter.compiled_function = null;
- console.warn("MONO_WASM: compiling converter failed for", bodyJs, "with error", exc);
+ mono_log_warn("compiling converter failed for", bodyJs, "with error", exc);
throw exc;
}
converter.compiled_variadic_function = <VariadicConverterFunction>compiledVariadicFunction;
} catch (exc) {
converter.compiled_variadic_function = null;
- console.warn("MONO_WASM: compiling converter failed for", bodyJs, "with error", exc);
+ mono_log_warn("compiling converter failed for", bodyJs, "with error", exc);
throw exc;
}
if (converter.has_warned_about_signature)
return;
- console.warn("MONO_WASM: Deprecated raw return value signature: '" + converter.args_marshal + "'. End the signature with '!' instead of 'm'.");
+ mono_log_warn("Deprecated raw return value signature: '" + converter.args_marshal + "'. End the signature with '!' instead of 'm'.");
converter.has_warned_about_signature = true;
}
import type { TypedArray } from "./types/emscripten";
import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WEB, INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals";
import { replaceEmscriptenPThreadLibrary } from "./pthreads/shared/emscripten-replacements";
+import { mono_log_info } from "./logging";
const dummyPerformance = {
now: function () {
}
if (BuildConfiguration === "Debug") {
- console.debug(`MONO_WASM: starting script ${loaderHelpers.scriptUrl}`);
- console.debug(`MONO_WASM: starting in ${loaderHelpers.scriptDirectory}`);
+ mono_log_info(`starting script ${loaderHelpers.scriptUrl}`);
+ mono_log_info(`starting in ${loaderHelpers.scriptDirectory}`);
}
// prefer fetch_like over global fetch for assets
import { createPromiseController, runtimeHelpers } from "../../globals";
import { PromiseController } from "../../types/internal";
import { MonoConfig } from "../../types";
+import { mono_log_debug } from "../../logging";
const threads: Map<pthread_ptr, Thread> = new Map();
function monoDedicatedChannelMessageFromWorkerToMain(event: MessageEvent<unknown>, thread: Thread): void {
// TODO: add callbacks that will be called from here
- console.debug("MONO_WASM: got message from worker on the dedicated channel", event.data, thread);
+ mono_log_debug("got message from worker on the dedicated channel", event.data, thread);
}
// handler that runs in the main thread when a message is received from a pthread worker
port.postMessage(makeMonoThreadMessageApplyMonoConfig(runtimeHelpers.config));
}
else if (isMonoWorkerMessageChannelCreated(data)) {
- console.debug("MONO_WASM: received the channel created message", data, worker);
+ mono_log_debug("received the channel created message", data, worker);
const port = data[monoSymbol].port;
const pthread_id = data[monoSymbol].thread_id;
const thread = addThread(pthread_id, worker, port);
/// At this point the worker doesn't have any pthread assigned to it, yet.
export function afterLoadWasmModuleToWorker(worker: Worker): void {
worker.addEventListener("message", (ev) => monoWorkerMessageHandler(worker, ev));
- console.debug("MONO_WASM: afterLoadWasmModuleToWorker added message event handler", worker);
+ mono_log_debug("afterLoadWasmModuleToWorker added message event handler", worker);
}
/// We call on the main thread this during startup to pre-allocate a pool of pthread workers.
import { afterLoadWasmModuleToWorker } from "../browser";
import { afterThreadInitTLS } from "../worker";
import Internals from "./emscripten-internals";
-import { loaderHelpers, runtimeHelpers } from "../../globals";
+import { loaderHelpers } from "../../globals";
import { PThreadReplacements } from "../../types/internal";
+import { mono_log_debug } from "../../logging";
/** @module emscripten-replacements Replacements for individual functions in the emscripten PThreads library.
* These have a hard dependency on the version of Emscripten that we are using and may need to be kept in sync with
/// We replace Module["PThreads"].allocateUnusedWorker with this version that knows about assets
function replacementAllocateUnusedWorker(): void {
- if (runtimeHelpers.diagnosticTracing)
- console.debug("MONO_WASM: replacementAllocateUnusedWorker");
+ mono_log_debug("replacementAllocateUnusedWorker");
const asset = loaderHelpers.resolve_asset_path("js-module-threads");
const uri = asset.resolvedUrl;
mono_assert(uri !== undefined, "could not resolve the uri for the js-module-threads asset");
/// <reference lib="webworker" />
import MonoWasmThreads from "consts:monoWasmThreads";
-import { Module, ENVIRONMENT_IS_PTHREAD, runtimeHelpers } from "../../globals";
+import { Module, ENVIRONMENT_IS_PTHREAD } from "../../globals";
import { makeChannelCreatedMonoMessage } from "../shared";
import type { pthread_ptr } from "../shared/types";
import { is_nullish } from "../../types/internal";
WorkerThreadEventTarget
} from "./events";
import { preRunWorker } from "../../startup";
+import { mono_log_debug } from "../../logging";
// re-export some of the events types
export {
/// pthreads that are running on the current worker.
/// Example:
/// currentWorkerThreadEvents.addEventListener(dotnetPthreadCreated, (ev: WorkerThreadEvent) => {
-/// console.debug("MONO_WASM: thread created on worker with id", ev.pthread_ptr);
+/// mono_trace("thread created on worker with id", ev.pthread_ptr);
/// });
export const currentWorkerThreadEvents: WorkerThreadEventTarget =
MonoWasmThreads ? new EventTarget() : null as any as WorkerThreadEventTarget; // treeshake if threads are disabled
// 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<string>): void {
- console.debug("MONO_WASM: got message from main on the dedicated channel", event.data);
+ mono_log_debug("got message from main on the dedicated channel", event.data);
}
function setupChannelToMainThread(pthread_ptr: pthread_ptr): PThreadSelf {
- console.debug("MONO_WASM: creating a channel", pthread_ptr);
+ mono_log_debug("creating a channel", pthread_ptr);
const channel = new MessageChannel();
const workerPort = channel.port1;
const mainPort = channel.port2;
export function mono_wasm_pthread_on_pthread_attached(pthread_id: pthread_ptr): void {
const self = pthread_self;
mono_assert(self !== null && self.pthread_id == pthread_id, "expected pthread_self to be set already when attaching");
- if (runtimeHelpers.diagnosticTracing)
- console.debug("MONO_WASM: attaching pthread to runtime 0x" + pthread_id.toString(16));
+ mono_log_debug("attaching pthread to runtime 0x" + pthread_id.toString(16));
preRunWorker();
currentWorkerThreadEvents.dispatchEvent(makeWorkerThreadEvent(dotnetPthreadAttached, self));
}
if (ENVIRONMENT_IS_PTHREAD) {
const pthread_ptr = (<any>Module)["_pthread_self"]();
mono_assert(!is_nullish(pthread_ptr), "pthread_self() returned null");
- if (runtimeHelpers.diagnosticTracing)
- console.debug("MONO_WASM: after thread init, pthread ptr 0x" + pthread_ptr.toString(16));
+ mono_log_debug("after thread init, pthread ptr 0x" + pthread_ptr.toString(16));
const self = setupChannelToMainThread(pthread_ptr);
currentWorkerThreadEvents.dispatchEvent(makeWorkerThreadEvent(dotnetPthreadCreated, self));
}
return;
}
+ // eslint-disable-next-line no-console
console.warn(`(!) ${warning.toString()}`);
}
import { mono_wasm_set_main_args } from "./startup";
import cwraps from "./cwraps";
import { assembly_load } from "./class-loader";
+import { mono_log_info } from "./logging";
/**
* 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<number> {
mono_wasm_set_main_args(main_assembly_name, args);
if (runtimeHelpers.waitForDebugger == -1) {
- console.log("MONO_WASM: waiting for debugger...");
+ mono_log_info("waiting for debugger...");
await mono_wasm_wait_for_debugger();
}
const method = find_entry_point(main_assembly_name);
import GitHash from "consts:gitHash";
import MonoWasmThreads from "consts:monoWasmThreads";
import { ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers } from "./globals";
+import { mono_log_warn } from "./logging";
const memoryPrefix = "https://dotnet.generated.invalid/wasm-memory";
} catch {
// There's no known scenario where we should get an exception here, but considering the
// Chromium bug above, let's tolerate it and treat as "proceed without caching".
- console.warn("MONO_WASM: Failed to open cache");
+ mono_log_warn("Failed to open cache");
return null;
}
}
const contentLength = res?.headers.get("content-length");
return contentLength ? parseInt(contentLength) : undefined;
} catch (ex) {
- console.warn("MONO_WASM: Failed find memory snapshot in the cache", ex);
+ mono_log_warn("Failed find memory snapshot in the cache", ex);
return undefined;
}
}
}
return res.arrayBuffer();
} catch (ex) {
- console.warn("MONO_WASM: Failed load memory snapshot from the cache", ex);
+ mono_log_warn("Failed load memory snapshot from the cache", ex);
return undefined;
}
}
cleanupMemorySnapshots(cacheKey); // no await
} catch (ex) {
- console.warn("MONO_WASM: Failed to store memory snapshot in the cache", ex);
+ mono_log_warn("Failed to store memory snapshot in the cache", ex);
return;
}
}
import { init_legacy_exports } from "./net6-legacy/corebindings";
import { cwraps_binding_api, cwraps_mono_api } from "./net6-legacy/exports-legacy";
import { BINDING, MONO } from "./net6-legacy/globals";
+import { mono_log_debug, mono_log_warn } from "./logging";
// default size if MonoConfig.pthreadPoolSize is undefined
}
if (!module.out) {
+ // eslint-disable-next-line no-console
module.out = console.log.bind(console);
}
if (!module.err) {
+ // eslint-disable-next-line no-console
module.err = console.error.bind(console);
}
loaderHelpers.out = module.out;
const mark = startMeasure();
try {
mono_wasm_pre_init_essential(false);
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: preInit");
+ mono_log_debug("preInit");
runtimeHelpers.beforePreInit.promise_control.resolve();
// all user Module.preInit callbacks
userPreInit.forEach(fn => fn());
} catch (err) {
- _print_error("MONO_WASM: user preInint() failed", err);
+ _print_error("user preInint() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
}
async function preInitWorkerAsync() {
- console.debug("MONO_WASM: worker initializing essential C exports and APIs");
+ mono_log_debug("worker initializing essential C exports and APIs");
const mark = startMeasure();
try {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: preInitWorker");
+ mono_log_debug("preInitWorker");
runtimeHelpers.beforePreInit.promise_control.resolve();
mono_wasm_pre_init_essential(true);
await init_polyfills_async();
runtimeHelpers.afterPreInit.promise_control.resolve();
endMeasure(mark, MeasuredBlock.preInitWorker);
} catch (err) {
- _print_error("MONO_WASM: user preInitWorker() failed", err);
+ _print_error("user preInitWorker() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
try {
await runtimeHelpers.afterInstantiateWasm.promise;
await runtimeHelpers.afterPreInit.promise;
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: preRunAsync");
+ mono_log_debug("preRunAsync");
const mark = startMeasure();
// all user Module.preRun callbacks
userPreRun.map(fn => fn());
endMeasure(mark, MeasuredBlock.preRun);
} catch (err) {
- _print_error("MONO_WASM: user callback preRun() failed", err);
+ _print_error("user callback preRun() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
try {
// wait for previous stage
await runtimeHelpers.afterPreRun.promise;
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: onRuntimeInitialized");
+ mono_log_debug("onRuntimeInitialized");
const mark = startMeasure();
// signal this stage, this will allow pending assets to allocate memory
runtimeHelpers.beforeOnRuntimeInitialized.promise_control.resolve();
userOnRuntimeInitialized();
}
catch (err: any) {
- _print_error("MONO_WASM: user callback onRuntimeInitialized() failed", err);
+ _print_error("user callback onRuntimeInitialized() failed", err);
throw err;
}
// finish
await mono_wasm_after_user_runtime_initialized();
endMeasure(mark, MeasuredBlock.onRuntimeInitialized);
} catch (err) {
- _print_error("MONO_WASM: onRuntimeInitializedAsync() failed", err);
+ _print_error("onRuntimeInitializedAsync() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
// wait for previous stage
try {
await runtimeHelpers.afterOnRuntimeInitialized.promise;
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: postRunAsync");
+ mono_log_debug("postRunAsync");
const mark = startMeasure();
// create /usr/share folder which is SpecialFolder.CommonApplicationData
userpostRun.map(fn => fn());
endMeasure(mark, MeasuredBlock.postRun);
} catch (err) {
- _print_error("MONO_WASM: user callback posRun() failed", err);
+ _print_error("user callback posRun() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
if (!isWorker)
Module.addRunDependency("mono_wasm_pre_init_essential");
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_pre_init_essential");
+ mono_log_debug("mono_wasm_pre_init_essential");
init_c_exports();
cwraps_internal(INTERNAL);
}
async function mono_wasm_pre_init_essential_async(): Promise<void> {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_pre_init_essential_async");
+ mono_log_debug("mono_wasm_pre_init_essential_async");
Module.addRunDependency("mono_wasm_pre_init_essential_async");
await init_polyfills_async();
}
async function mono_wasm_pre_init_full(): Promise<void> {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_pre_init_full");
+ mono_log_debug("mono_wasm_pre_init_full");
Module.addRunDependency("mono_wasm_pre_init_full");
await loaderHelpers.mono_download_assets();
}
async function mono_wasm_after_user_runtime_initialized(): Promise<void> {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_after_user_runtime_initialized");
+ mono_log_debug("mono_wasm_after_user_runtime_initialized");
try {
if (!Module.disableDotnet6Compatibility && Module.exports) {
// Export emscripten defined in module through EXPORTED_RUNTIME_METHODS
globalThisAny[exportName] = exportValue;
}
else {
- console.warn(`MONO_WASM: The exported symbol ${exportName} could not be found in the emscripten module`);
+ mono_log_warn(`The exported symbol ${exportName} could not be found in the emscripten module`);
}
}
}
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: Initializing mono runtime");
+ mono_log_debug("Initializing mono runtime");
if (Module.onDotnetReady) {
try {
await Module.onDotnetReady();
}
catch (err: any) {
- _print_error("MONO_WASM: onDotnetReady () failed", err);
+ _print_error("onDotnetReady () failed", err);
throw err;
}
}
} catch (err: any) {
- _print_error("MONO_WASM: Error in mono_wasm_after_user_runtime_initialized", err);
+ _print_error("Error in mono_wasm_after_user_runtime_initialized", err);
throw err;
}
}
}
Module.err(`${message}: ${JSON.stringify(err)}`);
if (typeof err === "object" && err.stack) {
- Module.err("MONO_WASM: Stacktrace: \n");
+ Module.err("Stacktrace: \n");
Module.err(err.stack);
}
}
try {
let memorySize: number | undefined = undefined;
await loaderHelpers.afterConfigLoaded;
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: instantiate_wasm_module");
+ mono_log_debug("instantiate_wasm_module");
if (runtimeHelpers.config.startupMemoryCache) {
memorySize = await getMemorySnapshotSize();
assetToLoad.pendingDownload = null as any; // GC
assetToLoad.buffer = null as any; // GC
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: instantiate_wasm_module done");
+ mono_log_debug("instantiate_wasm_module done");
if (runtimeHelpers.loadedMemorySnapshot) {
try {
wasmMemory.grow((memorySize! - wasmMemory.buffer.byteLength + 65535) >>> 16);
runtimeHelpers.updateMemoryViews();
} catch (err) {
- console.warn("MONO_WASM: failed to resize memory for the snapshot", err);
+ mono_log_warn("failed to resize memory for the snapshot", err);
runtimeHelpers.loadedMemorySnapshot = false;
}
// now we know if the loading of memory succeeded or not, we can start loading the rest of the assets
}
runtimeHelpers.afterInstantiateWasm.promise_control.resolve();
} catch (err) {
- _print_error("MONO_WASM: instantiate_wasm_module() failed", err);
+ _print_error("instantiate_wasm_module() failed", err);
loaderHelpers.abort_startup(err, true);
throw err;
}
if (runtimeHelpers.loadedMemorySnapshot) {
// get the bytes after we re-sized the memory, so that we don't have too much memory in use at the same time
const memoryBytes = await getMemorySnapshot();
- mono_assert(memoryBytes!.byteLength === Module.HEAP8.byteLength, "MONO_WASM: Loaded memory is not the expected size");
+ mono_assert(memoryBytes!.byteLength === Module.HEAP8.byteLength, "Loaded memory is not the expected size");
Module.HEAP8.set(new Int8Array(memoryBytes!), 0);
- if (runtimeHelpers.diagnosticTracing) console.info("MONO_WASM: Loaded WASM linear memory from browser cache");
+ mono_log_debug("Loaded WASM linear memory from browser cache");
// all things below are loaded from the snapshot
return;
}
export function mono_wasm_load_runtime(unused?: string, debugLevel?: number): void {
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: mono_wasm_load_runtime");
+ mono_log_debug("mono_wasm_load_runtime");
try {
const mark = startMeasure();
if (debugLevel == undefined) {
endMeasure(mark, MeasuredBlock.loadRuntime);
} catch (err: any) {
- _print_error("MONO_WASM: mono_wasm_load_runtime () failed", err);
+ _print_error("mono_wasm_load_runtime () failed", err);
loaderHelpers.abort_startup(err, false);
}
}
if (runtimeHelpers.mono_wasm_bindings_is_ready) {
return;
}
- if (runtimeHelpers.diagnosticTracing) console.debug("MONO_WASM: bindings_init");
+ mono_log_debug("bindings_init");
runtimeHelpers.mono_wasm_bindings_is_ready = true;
try {
const mark = startMeasure();
runtimeHelpers._i52_error_scratch_buffer = <any>Module._malloc(4);
endMeasure(mark, MeasuredBlock.bindingsInit);
} catch (err) {
- _print_error("MONO_WASM: Error in bindings_init", err);
+ _print_error("Error in bindings_init", err);
throw err;
}
}
export async function configureWorkerStartup(module: DotnetModuleInternal): Promise<void> {
// This is a good place for subsystems to attach listeners for pthreads_worker.currentWorkerThreadEvents
pthreads_worker.currentWorkerThreadEvents.addEventListener(pthreads_worker.dotnetPthreadCreated, (ev) => {
- if (runtimeHelpers.diagnosticTracing)
- console.debug("MONO_WASM: pthread created 0x" + ev.pthread_self.pthread_id.toString(16));
+ mono_log_debug("pthread created 0x" + ev.pthread_self.pthread_id.toString(16));
});
// these are the only events which are called on worker
import { setI32 } from "./memory";
import { VoidPtr } from "./types/emscripten";
import { PromiseController } from "./types/internal";
+import { mono_log_warn } from "./logging";
const wasm_ws_pending_send_buffer = Symbol.for("wasm ws_pending_send_buffer");
const wasm_ws_pending_send_buffer_offset = Symbol.for("wasm ws_pending_send_buffer_offset");
else {
if (!mono_wasm_web_socket_close_warning) {
mono_wasm_web_socket_close_warning = true;
- console.warn("WARNING: Web browsers do not support closing the output side of a WebSocket. CloseOutputAsync has closed the socket and discarded any incoming messages.");
+ mono_log_warn("WARNING: Web browsers do not support closing the output side of a WebSocket. CloseOutputAsync has closed the socket and discarded any incoming messages.");
}
if (typeof reason === "string") {
ws.close(code, reason);