Skip to content

Commit

Permalink
[browser] logging cleanup (#86431)
Browse files Browse the repository at this point in the history
* introduce logging functions
  • Loading branch information
pavelsavara authored May 18, 2023
1 parent 60f8edf commit 003b5ea
Show file tree
Hide file tree
Showing 43 changed files with 390 additions and 341 deletions.
1 change: 1 addition & 0 deletions src/mono/wasm/runtime/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ module.exports = {
}
],
"no-multi-spaces": ["error"],
"no-console": ["error"],
"arrow-spacing": ["error"],
"block-spacing": ["error"],
"comma-spacing": ["error"],
Expand Down
23 changes: 10 additions & 13 deletions src/mono/wasm/runtime/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
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";
Expand All @@ -13,8 +13,7 @@ import { InstantiateWasmSuccessCallback, VoidPtr } from "./types/emscripten";

// 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"
Expand Down Expand Up @@ -50,8 +49,7 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar
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?
Expand All @@ -60,8 +58,7 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar
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(
Expand Down Expand Up @@ -90,7 +87,7 @@ export function instantiate_asset(asset: AssetEntry, url: string, bytes: Uint8Ar
}
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);
Expand All @@ -110,16 +107,16 @@ export async function instantiate_wasm_asset(
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);
Expand All @@ -139,7 +136,7 @@ export async function instantiate_symbols_asset(pendingAsset: AssetEntryInternal
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)}`);
}
}

Expand Down Expand Up @@ -199,7 +196,7 @@ export async function wait_for_all_assets() {
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");
}
}

Expand Down
21 changes: 11 additions & 10 deletions src/mono/wasm/runtime/cwraps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
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];

Expand Down Expand Up @@ -252,7 +253,7 @@ export interface t_Cwraps {
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;
}

Expand All @@ -270,23 +271,23 @@ export const enum I52Error {

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;
}

Expand All @@ -299,7 +300,7 @@ function cwrap (name: string, returnType: string | null, argTypes: string[] | un
if (throwOnError)
throw new Error(msg);
else
console.error("MONO_WASM: " + msg);
mono_log_error("" + msg);
}
return fce;
}
Expand Down
9 changes: 7 additions & 2 deletions src/mono/wasm/runtime/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { INTERNAL, Module, runtimeHelpers } from "./globals";
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 = {};
Expand All @@ -31,6 +32,7 @@ export function mono_wasm_runtime_ready(): void {

export function mono_wasm_fire_debugger_agent_message_with_data_to_pause(base64String: string): void {
//keep this console.assert, otherwise optimization will remove the assignments
// eslint-disable-next-line no-console
console.assert(true, `mono_wasm_fire_debugger_agent_message_with_data ${base64String}`);
// eslint-disable-next-line no-debugger
debugger;
Expand All @@ -52,7 +54,7 @@ export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number,
}
};
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);
}

Expand Down Expand Up @@ -124,6 +126,7 @@ export function mono_wasm_raise_debug_event(event: WasmEvent, args = {}): void {
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));
}

Expand All @@ -150,6 +153,7 @@ export function mono_wasm_set_entrypoint_breakpoint(assembly_name: CharPtr, entr
_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;
Expand Down Expand Up @@ -345,7 +349,8 @@ export function mono_wasm_debugger_log(level: number, message_ptr: CharPtr): voi
}

if (BuildConfiguration === "Debug") {
console.debug(`MONO_WASM: Debugger.Debug: ${message}`);
// eslint-disable-next-line no-console
console.debug(`Debugger.Debug: ${message}`);
}
}

Expand Down
13 changes: 7 additions & 6 deletions src/mono/wasm/runtime/diagnostics/browser/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

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";
Expand All @@ -18,15 +19,15 @@ class ServerControllerImpl implements ServerController {
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"));
}

Expand All @@ -35,7 +36,7 @@ class ServerControllerImpl implements ServerController {
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;
}
}
Expand All @@ -52,15 +53,15 @@ export function getController(): ServerController {

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;
const pthreadId = getI32(pthreadIdPtr);
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
Expand Down
11 changes: 6 additions & 5 deletions src/mono/wasm/runtime/diagnostics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { is_nullish } from "../types/internal";
import type { VoidPtr } from "../types/emscripten";
import { getController, startDiagnosticServer } from "./browser/controller";
import * as memory from "../memory";
import { mono_log_warn } from "../logging";


// called from C on the main thread
Expand Down Expand Up @@ -37,7 +38,7 @@ export async function mono_wasm_init_diagnostics(): Promise<void> {
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();
Expand Down Expand Up @@ -96,12 +97,12 @@ function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | nu
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];
Expand All @@ -124,12 +125,12 @@ function diagnostic_options_from_ports_spec(val: string): DiagnosticOptions | nu
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 {
Expand Down
Loading

0 comments on commit 003b5ea

Please sign in to comment.