Skip to content

Commit c930a99

Browse files
committed
wip
1 parent d7acf9c commit c930a99

28 files changed

+264
-217
lines changed

src/mono/browser/runtime/assets.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
import type { AssetEntryInternal } from "./types/internal";
5+
46
import cwraps from "./cwraps";
57
import { mono_wasm_load_icu_data } from "./icu";
68
import { Module, loaderHelpers, mono_assert, runtimeHelpers } from "./globals";
79
import { mono_log_info, mono_log_debug, parseSymbolMapFile } from "./logging";
810
import { mono_wasm_load_bytes_into_heap } from "./memory";
911
import { endMeasure, MeasuredBlock, startMeasure } from "./profiler";
10-
import { AssetEntryInternal } from "./types/internal";
1112
import { AssetEntry } from "./types";
1213
import { VoidPtr } from "./types/emscripten";
1314
import { setSegmentationRulesFromJson } from "./hybrid-globalization/grapheme-segmenter";

src/mono/browser/runtime/cwraps.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,12 @@ import WasmEnableThreads from "consts:wasmEnableThreads";
66
import type {
77
MonoAssembly, MonoClass,
88
MonoMethod, MonoObject,
9-
MonoType, MonoObjectRef, MonoStringRef, JSMarshalerArguments
9+
MonoType, MonoObjectRef, MonoStringRef, JSMarshalerArguments, PThreadPtr
1010
} from "./types/internal";
1111
import type { VoidPtr, CharPtrPtr, Int32Ptr, CharPtr, ManagedPointer } from "./types/emscripten";
1212
import { Module, runtimeHelpers } from "./globals";
1313
import { mono_log_error } from "./logging";
1414
import { mono_assert } from "./globals";
15-
import { PThreadPtr } from "./pthreads/shared/types";
1615

1716
type SigLine = [lazyOrSkip: boolean | (() => boolean), name: string, returnType: string | null, argTypes?: string[], opts?: any];
1817

src/mono/browser/runtime/debug.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
import BuildConfiguration from "consts:configuration";
5+
56
import { INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals";
67
import { toBase64StringImpl } from "./base64";
78
import cwraps from "./cwraps";

src/mono/browser/runtime/diagnostics/browser/controller.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ import { threads_c_functions as cwraps } from "../../cwraps";
77
import { INTERNAL, mono_assert } from "../../globals";
88
import { mono_log_info, mono_log_debug, mono_log_warn } from "../../logging";
99
import { withStackAlloc, getI32 } from "../../memory";
10-
import { Thread, waitForThread } from "../../pthreads/browser";
10+
import { waitForThread } from "../../pthreads/browser";
1111
import { isDiagnosticMessage, makeDiagnosticServerControlCommand } from "../shared/controller-commands";
1212
import monoDiagnosticsMock from "consts:monoDiagnosticsMock";
13-
import { PThreadPtr } from "../../pthreads/shared/types";
13+
import { PThreadPtr, Thread } from "../../types/internal";
1414

1515
/// An object that can be used to control the diagnostic server.
1616
export interface ServerController {

src/mono/browser/runtime/diagnostics/index.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,9 @@ let diagnosticsServerEnabled = false;
3737
let diagnosticsInitialized = false;
3838

3939
export async function mono_wasm_init_diagnostics(): Promise<void> {
40-
if (diagnosticsInitialized)
41-
return;
42-
if (!WasmEnableThreads) {
43-
mono_log_warn("ignoring diagnostics options because this runtime does not support diagnostics");
44-
return;
45-
}
40+
if (!WasmEnableThreads) return;
41+
if (diagnosticsInitialized) return;
42+
4643
const options = diagnostic_options_from_environment();
4744
if (!options)
4845
return;

src/mono/browser/runtime/diagnostics/shared/controller-commands.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
import type { MonoThreadMessage } from "../../pthreads/shared";
54
import { isMonoThreadMessage } from "../../pthreads/shared";
5+
import type { MonoThreadMessage } from "../../types/internal";
66

77
// Messages from the main thread to the diagnostic server thread
88
export interface DiagnosticMessage extends MonoThreadMessage {

src/mono/browser/runtime/dotnet.d.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,10 @@ type MonoConfig = {
190190
* initial number of workers to add to the emscripten pthread pool
191191
*/
192192
pthreadPoolSize?: number;
193+
/**
194+
* initial number of unused workers keep in the emscripten pthread pool after startup
195+
*/
196+
pthreadPoolReady?: number;
193197
/**
194198
* If true, a list of the methods optimized by the interpreter will be saved and used for faster startup
195199
* on future runs of the application

src/mono/browser/runtime/exports-internal.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
import WasmEnableThreads from "consts:wasmEnableThreads";
5+
6+
import { MonoObjectNull, type MonoObject } from "./types/internal";
47
import cwraps, { profiler_c_functions } from "./cwraps";
58
import { mono_wasm_send_dbg_command_with_parms, mono_wasm_send_dbg_command, mono_wasm_get_dbg_command_info, mono_wasm_get_details, mono_wasm_release_object, mono_wasm_call_function_on, mono_wasm_debugger_resume, mono_wasm_detach_debugger, mono_wasm_raise_debug_event, mono_wasm_change_debugger_log_level, mono_wasm_debugger_attached } from "./debug";
69
import { http_wasm_supports_streaming_request, http_wasm_supports_streaming_response, http_wasm_create_controller, http_wasm_abort_request, http_wasm_abort_response, http_wasm_transform_stream_write, http_wasm_transform_stream_close, http_wasm_fetch, http_wasm_fetch_stream, http_wasm_fetch_bytes, http_wasm_get_response_header_names, http_wasm_get_response_header_values, http_wasm_get_response_bytes, http_wasm_get_response_length, http_wasm_get_streamed_response_bytes, http_wasm_get_response_type, http_wasm_get_response_status } from "./http";
@@ -17,16 +20,17 @@ import { loadLazyAssembly } from "./lazyLoading";
1720
import { loadSatelliteAssemblies } from "./satelliteAssemblies";
1821
import { forceDisposeProxies } from "./gc-handles";
1922
import { mono_wasm_get_func_id_to_name_mappings } from "./logging";
20-
import { MonoObject, MonoObjectNull } from "./types/internal";
2123
import { monoStringToStringUnsafe } from "./strings";
22-
import { thread_available } from "./pthreads/browser";
2324
import { mono_wasm_bind_cs_function } from "./invoke-cs";
2425

26+
import { dumpThreads, thread_available } from "./pthreads/browser";
27+
2528
export function export_internal(): any {
2629
return {
2730
// tests
2831
mono_wasm_exit: (exit_code: number) => { Module.err("early exit " + exit_code); },
2932
forceDisposeProxies,
33+
dumpThreads: WasmEnableThreads ? dumpThreads : undefined,
3034

3135
// with mono_wasm_debugger_log and mono_wasm_trace_logger
3236
logging: undefined,
@@ -57,7 +61,7 @@ export function export_internal(): any {
5761
get_global_this,
5862
get_dotnet_instance: () => exportedRuntimeAPI,
5963
dynamic_import,
60-
thread_available,
64+
thread_available: WasmEnableThreads ? thread_available : undefined,
6165
mono_wasm_bind_cs_function,
6266

6367
// BrowserWebSocket

src/mono/browser/runtime/exports.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ function initializeExports(globalObjects: GlobalObjects): RuntimeAPI {
7070
runtimeList = globalThisAny.getDotnetRuntime.__list;
7171
}
7272

73+
if (BuildConfiguration === "Debug") {
74+
globalThisAny.INTERNAL = globals.internal;
75+
}
76+
7377
return exportedRuntimeAPI;
7478
}
7579

src/mono/browser/runtime/interp-pgo.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ export async function getCacheKey(prefix: string): Promise<string | null> {
198198
delete inputs.dumpThreadsOnNonZeroExit;
199199
delete inputs.logExitCode;
200200
delete inputs.pthreadPoolSize;
201+
delete inputs.pthreadPoolReady;
201202
delete inputs.asyncFlushOnExit;
202203
delete inputs.remoteSources;
203204
delete inputs.ignorePdbLoadErrors;

src/mono/browser/runtime/loader/assets.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import WasmEnableThreads from "consts:wasmEnableThreads";
55

6-
import type { AssetEntryInternal, PromiseAndController } from "../types/internal";
6+
import { PThreadPtrNull, type AssetEntryInternal, type PThreadWorker, type PromiseAndController } from "../types/internal";
77
import type { AssetBehaviors, AssetEntry, LoadingResource, ResourceList, SingleAssetBehaviors as SingleAssetBehaviors, WebAssemblyBootResourceType } from "../types";
88
import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, ENVIRONMENT_IS_WEB, loaderHelpers, mono_assert, runtimeHelpers } from "./globals";
99
import { createPromiseController } from "./promise-controller";
@@ -733,4 +733,24 @@ export async function streamingCompileWasm() {
733733
catch (err) {
734734
loaderHelpers.wasmCompilePromise.promise_control.reject(err);
735735
}
736+
}
737+
738+
export function preloadWorkers() {
739+
if (!WasmEnableThreads) return;
740+
const jsModuleWorker = resolve_single_asset_path("js-module-threads");
741+
for (let i = 0; i < loaderHelpers.config.pthreadPoolSize!; i++) {
742+
const workerNumber = loaderHelpers.workerNextNumber++;
743+
const worker: Partial<PThreadWorker> = new Worker(jsModuleWorker.resolvedUrl!, {
744+
name: "dotnet-worker-" + workerNumber.toString().padStart(3, "0"),
745+
});
746+
worker.info = {
747+
workerNumber,
748+
pthreadId: PThreadPtrNull,
749+
reuseCount: 0,
750+
updateCount: 0,
751+
threadPrefix: " - ",
752+
threadName: "emscripten-pool",
753+
} as any;
754+
loaderHelpers.loadingWorkers.push(worker as any);
755+
}
736756
}

src/mono/browser/runtime/loader/config.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,10 +187,13 @@ export function normalizeConfig() {
187187
config.cachedResourcesPurgeDelay = 10000;
188188
}
189189

190+
// ActiveIssue https://github.com/dotnet/runtime/issues/75602
190191
if (WasmEnableThreads && !Number.isInteger(config.pthreadPoolSize)) {
191-
// ActiveIssue https://github.com/dotnet/runtime/issues/75602
192192
config.pthreadPoolSize = 7;
193193
}
194+
if (WasmEnableThreads && !Number.isInteger(config.pthreadPoolReady)) {
195+
config.pthreadPoolReady = 3;
196+
}
194197

195198
// this is how long the Mono GC will try to wait for all threads to be suspended before it gives up and aborts the process
196199
if (WasmEnableThreads && config.environmentVariables["MONO_SLEEP_ABORT_LIMIT"] === undefined) {

src/mono/browser/runtime/loader/globals.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ export function setLoaderGlobals(
9292
loadedFiles: [],
9393
loadedAssemblies: [],
9494
libraryInitializers: [],
95+
loadingWorkers: [],
96+
workerNextNumber: 1,
9597
actual_downloaded_assets_count: 0,
9698
actual_instantiated_assets_count: 0,
9799
expected_downloaded_assets_count: 0,

src/mono/browser/runtime/loader/run.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { ENVIRONMENT_IS_WEB, ENVIRONMENT_IS_WORKER, emscriptenModule, exportedRu
1010
import { deep_merge_config, deep_merge_module, mono_wasm_load_config } from "./config";
1111
import { installUnhandledErrorHandler, mono_exit, registerEmscriptenExitHandlers } from "./exit";
1212
import { setup_proxy_console, mono_log_info, mono_log_debug } from "./logging";
13-
import { mono_download_assets, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm } from "./assets";
13+
import { mono_download_assets, preloadWorkers, prepareAssets, prepareAssetsWorker, resolve_single_asset_path, streamingCompileWasm } from "./assets";
1414
import { detect_features_and_polyfill } from "./polyfills";
1515
import { runtimeHelpers, loaderHelpers } from "./globals";
1616
import { init_globalization } from "./icu";
@@ -487,6 +487,7 @@ async function createEmscriptenMain(): Promise<RuntimeAPI> {
487487
setTimeout(async () => {
488488
try {
489489
init_globalization();
490+
preloadWorkers();
490491
await mono_download_assets();
491492
}
492493
catch (err) {

src/mono/browser/runtime/loader/worker.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
import { MonoConfigInternal, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal";
4+
import { MonoConfigInternal, PThreadInfo, WorkerToMainMessageType, monoMessageSymbol } from "../types/internal";
55
import { MonoConfig } from "../types";
66
import { deep_merge_config, normalizeConfig } from "./config";
7-
import { ENVIRONMENT_IS_WEB, loaderHelpers } from "./globals";
7+
import { ENVIRONMENT_IS_WEB, loaderHelpers, runtimeHelpers } from "./globals";
88
import { mono_log_debug } from "./logging";
99

1010
export function setupPreloadChannelToMainThread() {
@@ -13,7 +13,8 @@ export function setupPreloadChannelToMainThread() {
1313
const mainPort = channel.port2;
1414
workerPort.addEventListener("message", (event) => {
1515
const config = JSON.parse(event.data.config) as MonoConfig;
16-
onMonoConfigReceived(config);
16+
const monoThreadInfo = JSON.parse(event.data.monoThreadInfo) as PThreadInfo;
17+
onMonoConfigReceived(config, monoThreadInfo);
1718
workerPort.close();
1819
mainPort.close();
1920
}, { once: true });
@@ -30,13 +31,13 @@ export function setupPreloadChannelToMainThread() {
3031
let workerMonoConfigReceived = false;
3132

3233
// called when the main thread sends us the mono config
33-
function onMonoConfigReceived(config: MonoConfigInternal): void {
34+
function onMonoConfigReceived(config: MonoConfigInternal, monoThreadInfo: PThreadInfo): void {
3435
if (workerMonoConfigReceived) {
3536
mono_log_debug("mono config already received");
3637
return;
3738
}
38-
3939
deep_merge_config(loaderHelpers.config, config);
40+
runtimeHelpers.monoThreadInfo = monoThreadInfo;
4041
normalizeConfig();
4142
mono_log_debug("mono config received");
4243
workerMonoConfigReceived = true;

src/mono/browser/runtime/polyfills.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import WasmEnableThreads from "consts:wasmEnableThreads";
55
import type { EmscriptenReplacements } from "./types/internal";
66
import type { TypedArray } from "./types/emscripten";
77
import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_WORKER, INTERNAL, Module, loaderHelpers, runtimeHelpers } from "./globals";
8-
import { replaceEmscriptenPThreadLibrary } from "./pthreads/shared/emscripten-replacements";
8+
import { replaceEmscriptenPThreadUI } from "./pthreads/browser/replacements";
9+
import { replaceEmscriptenPThreadWorker } from "./pthreads/worker/replacements";
910

1011
const dummyPerformance = {
1112
now: function () {
@@ -34,7 +35,11 @@ export function initializeReplacements(replacements: EmscriptenReplacements): vo
3435

3536
// threads
3637
if (WasmEnableThreads && replacements.modulePThread) {
37-
replaceEmscriptenPThreadLibrary(replacements.modulePThread);
38+
if (ENVIRONMENT_IS_WORKER) {
39+
replaceEmscriptenPThreadWorker(replacements.modulePThread);
40+
} else {
41+
replaceEmscriptenPThreadUI(replacements.modulePThread);
42+
}
3843
}
3944
}
4045

0 commit comments

Comments
 (0)