Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelsavara committed Jul 17, 2022
1 parent 3ea30ed commit 2050175
Show file tree
Hide file tree
Showing 22 changed files with 903 additions and 652 deletions.
4 changes: 2 additions & 2 deletions src/mono/sample/wasm/browser/main.js
Expand Up @@ -22,7 +22,7 @@ function sub(a, b) {

try {
const { MONO, RuntimeBuildInfo, IMPORTS } = await createDotnetRuntime(() => {
console.log('user code in createDotnetRuntime');
console.log('user code in createDotnetRuntime callback');
return {
configSrc: "./mono-config.json",
preInit: () => { console.log('user code Module.preInit'); },
Expand All @@ -31,7 +31,7 @@ try {
postRun: () => { console.log('user code Module.postRun'); },
}
});
console.log('after createDotnetRuntime');
console.log('user code after createDotnetRuntime()');
IMPORTS.Sample = {
Test: {
add,
Expand Down
29 changes: 14 additions & 15 deletions src/mono/wasm/runtime/crypto-worker.ts
Expand Up @@ -62,7 +62,7 @@ export function dotnet_browser_encrypt_decrypt(isEncrypting: boolean, key_buffer
}

if (result.length > output_len) {
console.error(`ENCRYPT DECRYPT: Encrypt/Decrypt length exceeds output length: ${result.length} > ${output_len}`);
console.error(`MONO_WASM_ENCRYPT_DECRYPT: Encrypt/Decrypt length exceeds output length: ${result.length} > ${output_len}`);
return ERR_ARGS;
}

Expand Down Expand Up @@ -91,7 +91,7 @@ function _send_simple_msg(msg: any, prefix: string, output_buffer: number, outpu
}

if (result.length > output_len) {
console.error(`${prefix}: Result length exceeds output length: ${result.length} > ${output_len}`);
console.error(`MONO_WASM_ENCRYPT_DECRYPT: ${prefix}: Result length exceeds output length: ${result.length} > ${output_len}`);
return ERR_ARGS;
}

Expand Down Expand Up @@ -132,7 +132,7 @@ function _send_msg_worker(msg: any): number | any {
const responseJson = JSON.parse(response);

if (responseJson.error !== undefined) {
console.error(`Worker failed with: ${responseJson.error}`);
console.error(`MONO_WASM_ENCRYPT_DECRYPT: Worker failed with: ${responseJson.error}`);
if (responseJson.error_type == "ArgumentsError")
return ERR_ARGS;
if (responseJson.error_type == "WorkerFailedError")
Expand All @@ -144,9 +144,9 @@ function _send_msg_worker(msg: any): number | any {
return responseJson.result;
} catch (err) {
if (err instanceof Error && err.stack !== undefined)
console.error(`${err.stack}`);
console.error(`MONO_WASM_ENCRYPT_DECRYPT: ${err.stack}`);
else
console.error(`_send_msg_worker failed: ${err}`);
console.error(`MONO_WASM_ENCRYPT_DECRYPT: _send_msg_worker failed: ${err}`);
return ERR_OP_FAILED;
}
}
Expand Down Expand Up @@ -202,10 +202,9 @@ class LibraryChannel {

public send_msg(msg: string): string {
try {
let state = Atomics.load(this.comm, this.STATE_IDX);
if (state !== this.STATE_IDLE)
console.log(`send_msg, waiting for idle now, ${state}`);
state = this.wait_for_state(pstate => pstate == this.STATE_IDLE, "waiting");
// const state = Atomics.load(this.comm, this.STATE_IDX);
// if (state !== this.STATE_IDLE) console.debug(`MONO_WASM_ENCRYPT_DECRYPT: send_msg, waiting for idle now, ${state}`);
this.wait_for_state(pstate => pstate == this.STATE_IDLE, "waiting");

this.send_request(msg);
return this.read_response();
Expand All @@ -214,14 +213,13 @@ class LibraryChannel {
throw err;
}
finally {
const state = Atomics.load(this.comm, this.STATE_IDX);
if (state !== this.STATE_IDLE)
console.log(`state at end of send_msg: ${state}`);
// const state = Atomics.load(this.comm, this.STATE_IDX);
// if (state !== this.STATE_IDLE) console.debug(`MONO_WASM_ENCRYPT_DECRYPT: state at end of send_msg: ${state}`);
}
}

public shutdown(): void {
console.debug("Shutting down crypto");
// console.debug("MONO_WASM_ENCRYPT_DECRYPT: Shutting down crypto");
const state = Atomics.load(this.comm, this.STATE_IDX);
if (state !== this.STATE_IDLE)
throw new Error(`OWNER: Invalid sync communication channel state: ${state}`);
Expand All @@ -232,14 +230,15 @@ class LibraryChannel {
Atomics.notify(this.comm, this.STATE_IDX);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
private reset(reason: string): void {
console.debug(`reset: ${reason}`);
// console.debug(`MONO_WASM_ENCRYPT_DECRYPT: reset: ${reason}`);
const state = Atomics.load(this.comm, this.STATE_IDX);
if (state === this.STATE_SHUTDOWN)
return;

if (state === this.STATE_RESET || state === this.STATE_IDLE) {
console.debug(`state is already RESET or idle: ${state}`);
// console.debug(`MONO_WASM_ENCRYPT_DECRYPT: state is already RESET or idle: ${state}`);
return;
}

Expand Down
33 changes: 16 additions & 17 deletions src/mono/wasm/runtime/debug.ts
Expand Up @@ -5,17 +5,17 @@ import { INTERNAL, Module, MONO, runtimeHelpers } from "./imports";
import { toBase64StringImpl } from "./base64";
import cwraps from "./cwraps";
import { VoidPtr, CharPtr } from "./types/emscripten";
const commands_received : any = new Map<number, CommandResponse>();
const commands_received: any = new Map<number, CommandResponse>();
const wasm_func_map = new Map<number, string>();
commands_received.remove = function (key: number) : CommandResponse { const value = this.get(key); this.delete(key); return value;};
commands_received.remove = function (key: number): CommandResponse { const value = this.get(key); this.delete(key); return value; };
let _call_function_res_cache: any = {};
let _next_call_function_res_id = 0;
let _debugger_buffer_len = -1;
let _debugger_buffer: VoidPtr;
let _assembly_name_str: string; //keep this variable, it's used by BrowserDebugProxy
let _entrypoint_method_token: number; //keep this variable, it's used by BrowserDebugProxy

const regexes:any[] = [];
const regexes: any[] = [];

// V8
// at <anonymous>:wasm-function[1900]:0x83f63
Expand Down Expand Up @@ -66,7 +66,7 @@ export function mono_wasm_add_dbg_command_received(res_ok: boolean, id: number,
}
};
if (commands_received.has(id))
console.warn("Addind an id that already exists in commands_received");
console.warn("MONO_WASM: Addind an id that already exists in commands_received");
commands_received.set(id, buffer_obj);
}

Expand Down Expand Up @@ -178,7 +178,7 @@ function _create_proxy_from_object_id(objectId: string, details: any) {
if (objectId.startsWith("dotnet:array:")) {
let ret: Array<any>;
if (details.items === undefined) {
ret = details.map ((p: any) => p.value);
ret = details.map((p: any) => p.value);
return ret;
}
if (details.dimensionsDetails === undefined || details.dimensionsDetails.length === 1) {
Expand Down Expand Up @@ -363,27 +363,27 @@ export function mono_wasm_debugger_log(level: number, message_ptr: CharPtr): voi
return;
}

console.debug(`Debugger.Debug: ${message}`);
console.debug(`MONO_WASM: Debugger.Debug: ${message}`);
}

function _readSymbolMapFile(filename: string): void {
try {
const res = Module.FS_readFile(filename, {flags: "r", encoding: "utf8"});
const res = Module.FS_readFile(filename, { flags: "r", encoding: "utf8" });
res.split(/[\r\n]/).forEach((line: string) => {
const parts:string[] = line.split(/:/);
const parts: string[] = line.split(/:/);
if (parts.length < 2)
return;

parts[1] = parts.splice(1).join(":");
wasm_func_map.set(Number(parts[0]), parts[1]);
});

console.debug(`Loaded ${wasm_func_map.size} symbols`);
} catch (error:any) {
console.debug(`MONO_WASM: Loaded ${wasm_func_map.size} symbols`);
} catch (error: any) {
if (error.errno == 44) // NOENT
console.debug(`Could not find symbols file ${filename}. Ignoring.`);
console.debug(`MONO_WASM: Could not find symbols file ${filename}. Ignoring.`);
else
console.log(`Error loading symbol file ${filename}: ${JSON.stringify(error)}`);
console.log(`MONO_WASM: Error loading symbol file ${filename}: ${JSON.stringify(error)}`);
return;
}
}
Expand All @@ -395,11 +395,10 @@ export function mono_wasm_symbolicate_string(message: string): string {

const origMessage = message;

for (let i = 0; i < regexes.length; i ++)
{
for (let i = 0; i < regexes.length; i++) {
const newRaw = message.replace(new RegExp(regexes[i], "g"), (substring, ...args) => {
const groups = args.find(arg => {
return typeof(arg) == "object" && arg.replaceSection !== undefined;
return typeof (arg) == "object" && arg.replaceSection !== undefined;
});

if (groups === undefined)
Expand All @@ -421,7 +420,7 @@ export function mono_wasm_symbolicate_string(message: string): string {

return origMessage;
} catch (error) {
console.debug(`failed to symbolicate: ${error}`);
console.debug(`MONO_WASM: failed to symbolicate: ${error}`);
return message;
}
}
Expand Down Expand Up @@ -506,7 +505,7 @@ export function setup_proxy_console(id: string, originalConsole: Console, origin
};
}

const originalConsoleObj : any = originalConsole;
const originalConsoleObj: any = originalConsole;
const methods = ["debug", "trace", "warn", "info", "error"];
for (const m of methods) {
if (typeof (originalConsoleObj[m]) !== "function") {
Expand Down
6 changes: 3 additions & 3 deletions src/mono/wasm/runtime/diagnostics.ts
Expand Up @@ -52,7 +52,7 @@ class EventPipeFileSession implements EventPipeSession {
this._state = State.Initialized;
this._sessionID = sessionID;
this._tracePath = tracePath;
console.debug(`EventPipe session ${this.sessionID} created`);
console.debug(`MONO_WASM: EventPipe session ${this.sessionID} created`);
}

start = () => {
Expand All @@ -61,7 +61,7 @@ class EventPipeFileSession implements EventPipeSession {
}
this._state = State.Started;
start_streaming(this._sessionID);
console.debug(`EventPipe session ${this.sessionID} started`);
console.debug(`MONO_WASM: EventPipe session ${this.sessionID} started`);
}

stop = () => {
Expand All @@ -70,7 +70,7 @@ class EventPipeFileSession implements EventPipeSession {
}
this._state = State.Done;
stop_streaming(this._sessionID);
console.debug(`EventPipe session ${this.sessionID} stopped`);
console.debug(`MONO_WASM: EventPipe session ${this.sessionID} stopped`);
}

getTraceBlob = () => {
Expand Down
81 changes: 40 additions & 41 deletions src/mono/wasm/runtime/dotnet.d.ts
Expand Up @@ -50,14 +50,14 @@ declare interface EmscriptenModule {
stackRestore(stack: VoidPtr): void;
stackAlloc(size: number): VoidPtr;
ready: Promise<unknown>;
instantiateWasm?: (imports: WebAssembly.Imports, successCallback: (instance: WebAssembly.Instance) => void) => any;
preInit?: (() => any)[];
preRun?: (() => any)[];
onRuntimeInitialized?: () => any;
postRun?: (() => any)[];
onAbort?: {
(error: any): void;
};
onRuntimeInitialized?: () => any;
instantiateWasm: (imports: any, successCallback: Function) => any;
}
declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;

Expand Down Expand Up @@ -141,12 +141,12 @@ interface MonoObjectRef extends ManagedPointer {
__brandMonoObjectRef: "MonoObjectRef";
}
declare type MonoConfig = {
isError: false;
assembly_root: string;
assets: AllAssetEntryTypes[];
isError?: false;
assembly_root?: string;
assets?: AssetEntry[];
debug_level?: number;
enable_debugging?: number;
globalization_mode: GlobalizationMode;
globalization_mode?: GlobalizationMode;
diagnostic_tracing?: boolean;
remote_sources?: string[];
environment_variables?: {
Expand All @@ -163,43 +163,28 @@ declare type MonoConfigError = {
message: string;
error: any;
};
declare type AllAssetEntryTypes = AssetEntry | AssemblyEntry | SatelliteAssemblyEntry | VfsEntry | IcuData;
declare type AssetEntry = {
interface ResourceRequest {
name: string;
behavior: AssetBehaviours;
resolvedUrl?: string;
hash?: string;
}
interface AssetEntry extends ResourceRequest {
name: string;
behavior: AssetBehaviours;
virtual_path?: string;
culture?: string;
resolvedUrl?: string;
hash?: string;
load_remote?: boolean;
is_optional?: boolean;
buffer?: ArrayBuffer;
};
interface AssemblyEntry extends AssetEntry {
name: "assembly";
}
interface SatelliteAssemblyEntry extends AssetEntry {
name: "resource";
culture: string;
}
interface VfsEntry extends AssetEntry {
name: "vfs";
virtual_path: string;
}
interface IcuData extends AssetEntry {
name: "icu";
load_remote: boolean;
}
declare const enum AssetBehaviours {
Resource = "resource",
Assembly = "assembly",
Heap = "heap",
ICU = "icu",
VFS = "vfs"
}
declare const enum GlobalizationMode {
ICU = "icu",
INVARIANT = "invariant",
AUTO = "auto"
pending?: LoadingResource;
}
declare type AssetBehaviours = "resource" | "assembly" | "pdb" | "heap" | "icu" | "vfs" | "dotnetwasm";
declare type GlobalizationMode = "icu" | // load ICU globalization data from any runtime assets with behavior "icu".
"invariant" | // operate in invariant globalization mode.
"auto";
declare type AOTProfilerOptions = {
write_at?: string;
send_to?: string;
Expand All @@ -214,12 +199,17 @@ interface EventPipeSessionOptions {
}
declare type DotnetModuleConfig = {
disableDotnet6Compatibility?: boolean;
config?: MonoConfig | MonoConfigError;
config?: MonoConfig;
configSrc?: string;
onConfigLoaded?: (config: MonoConfig) => Promise<void>;
onDotnetReady?: () => void;
onConfigLoaded?: (config: MonoConfig) => void | Promise<void>;
onDotnetReady?: () => void | Promise<void>;
preInitAsync?: (() => Promise<void>)[];
preRunAsync?: (() => Promise<void>)[];
postRunAsync?: (() => Promise<void>)[];
onRuntimeInitializedAsync?: (() => Promise<void>)[];
imports?: DotnetModuleConfigImports;
exports?: string[];
downloadResource?: (request: ResourceRequest) => LoadingResource;
} & Partial<EmscriptenModule>;
declare type DotnetModuleConfigImports = {
require?: (name: string) => any;
Expand All @@ -242,6 +232,11 @@ declare type DotnetModuleConfigImports = {
};
url?: any;
};
interface LoadingResource {
name: string;
url: string;
response: Promise<Response>;
}

declare type EventPipeSessionID = bigint;
interface EventPipeSession {
Expand Down Expand Up @@ -289,7 +284,7 @@ interface Diagnostics {
declare function mono_wasm_runtime_ready(): void;

declare function mono_wasm_setenv(name: string, value: string): void;
declare function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise<void>;
declare function mono_wasm_load_runtime(unused?: string, debug_level?: number): void;
declare function mono_wasm_load_data_archive(data: Uint8Array, prefix: string): boolean;
/**
* Loads the mono config file (typically called mono-config.json) asynchroniously
Expand All @@ -299,6 +294,10 @@ declare function mono_wasm_load_data_archive(data: Uint8Array, prefix: string):
* @throws Will throw an error if the config file loading fails
*/
declare function mono_wasm_load_config(configFilePath: string): Promise<void>;
/**
* @deprecated
*/
declare function mono_load_runtime_and_bcl_args(cfg?: MonoConfig | MonoConfigError | undefined): Promise<void>;

declare function mono_wasm_load_icu_data(offset: VoidPtr): boolean;

Expand Down Expand Up @@ -435,7 +434,7 @@ declare const MONO: {
mono_run_main_and_exit: typeof mono_run_main_and_exit;
mono_wasm_get_assembly_exports: typeof mono_wasm_get_assembly_exports;
mono_wasm_add_assembly: (name: string, data: VoidPtr, size: number) => number;
mono_wasm_load_runtime: (unused: string, debug_level: number) => void;
mono_wasm_load_runtime: typeof mono_wasm_load_runtime;
config: MonoConfig | MonoConfigError;
loaded_files: string[];
setB32: typeof setB32;
Expand Down Expand Up @@ -563,4 +562,4 @@ declare class ArraySegment implements IMemoryView, IDisposable {
get byteLength(): number;
}

export { ArraySegment, BINDINGType, CreateDotnetRuntimeType, DotnetModuleConfig, DotnetPublicAPI, EmscriptenModule, IMemoryView, MONOType, ManagedError, ManagedObject, MemoryViewType, MonoArray, MonoObject, MonoString, Span, VoidPtr, createDotnetRuntime as default };
export { ArraySegment, AssetBehaviours, AssetEntry, BINDINGType, CreateDotnetRuntimeType, DotnetModuleConfig, DotnetPublicAPI, EmscriptenModule, IMemoryView, LoadingResource, MONOType, ManagedError, ManagedObject, MemoryViewType, MonoArray, MonoConfig, MonoObject, MonoString, ResourceRequest, Span, VoidPtr, createDotnetRuntime as default };

0 comments on commit 2050175

Please sign in to comment.