Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/coreclr/hosts/corerun/corerun.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ static int run(const configuration& config)
// The NodeJS process is kept alive by pending async work via safeSetTimeout() -> runtimeKeepalivePush()
// The actual exit code would be set by SystemJS_ResolveMainPromise if the managed Main() is async.
// Or in Module.onExit handler when managed Main() is synchronous.
return 0;
return exit_code;
#else // TARGET_BROWSER
return corerun_shutdown(exit_code);
#endif // TARGET_BROWSER
Expand Down
22 changes: 3 additions & 19 deletions src/coreclr/hosts/corerun/wasm/libCorerun.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ function libCoreRunFactory() {
"$FS",
"$NODEFS",
"$NODERAWFS",
"corerun_shutdown"
"corerun_shutdown",
"BrowserHost_ShutdownDotnet",
];
const mergeCoreRun = {
$CORERUN: {
Expand All @@ -25,28 +26,11 @@ function libCoreRunFactory() {
}

ENV["DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"] = "true";
const originalExitJS = exitJS;
exitJS = (status, implicit) => {
if (!implicit) {
EXITSTATUS = status;
ABORT = true;
if (dotnetBrowserUtilsExports.abortBackgroundTimers) {
dotnetBrowserUtilsExports.abortBackgroundTimers();
}
}
if (!keepRuntimeAlive()) {
ABORT = true;
var latched = _corerun_shutdown(EXITSTATUS || 0);
if (EXITSTATUS === undefined) {
EXITSTATUS = latched;
}
}
return originalExitJS(EXITSTATUS, implicit);
};
},
},
$CORERUN__postset: "CORERUN.selfInitialize()",
$CORERUN__deps: commonDeps,
BrowserHost_ShutdownDotnet: (exitCode) => _corerun_shutdown(exitCode),
};
const patchNODERAWFS = {
cwd: () => {
Expand Down
10 changes: 10 additions & 0 deletions src/coreclr/vm/assembly.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,10 @@ struct Param
LPWSTR *wzArgs;
} param;

#if defined(TARGET_BROWSER)
extern "C" void SystemJS_ResolveMainPromise(int exitCode);
#endif // TARGET_BROWSER

static void RunMainInternal(Param* pParam)
{
MethodDescCallSite threadStart(pParam->pFD);
Expand Down Expand Up @@ -1223,6 +1227,9 @@ static void RunMainInternal(Param* pParam)
// Set the return value to 0 instead of returning random junk
*pParam->piRetVal = 0;
threadStart.Call(&stackVar);
#if defined(TARGET_BROWSER)
SystemJS_ResolveMainPromise(*pParam->piRetVal);
#endif // TARGET_BROWSER
}
// WASM-TODO: remove this
// https://github.com/dotnet/runtime/issues/121064
Expand Down Expand Up @@ -1257,6 +1264,9 @@ static void RunMainInternal(Param* pParam)
// Call the main method
*pParam->piRetVal = (INT32)threadStart.Call_RetArgSlot(&stackVar);
SetLatchedExitCode(*pParam->piRetVal);
#if defined(TARGET_BROWSER)
SystemJS_ResolveMainPromise(*pParam->piRetVal);
#endif // TARGET_BROWSER
}

GCPROTECT_END();
Expand Down
2 changes: 1 addition & 1 deletion src/mono/browser/runtime/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ function performDeferredSymbolMapParsing () {

//# chrome
//# at http://127.0.0.1:63817/dotnet.wasm:wasm-function[8963]:0x1e23f4
regexes.push(/(?<replaceSection>[a-z]+:\/\/[^ )]*:wasm-function\[(?<funcNum>\d+)\]:0x[a-fA-F\d]+)/);
regexes.push(/(?<replaceSection>[a-z]+:\/\/[a-zA-Z0-9.:/_]*:wasm-function\[(?<funcNum>\d+)\]:0x[a-fA-F\d]+)/);

//# <?>.wasm-function[8962]
regexes.push(/(?<replaceSection><[^ >]+>[.:]wasm-function\[(?<funcNum>[0-9]+)\])/);
Expand Down
28 changes: 15 additions & 13 deletions src/mono/sample/wasm/Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,28 @@
<NestedBuildProperty Include="WasmTestForwardConsole" />
</ItemGroup>

<Target Name="BuildSampleInTree"
Inputs="
Program.cs;
$(_WasmMainJSFileName);
$(_SampleProject);
$(MSBuildProjectFile)
$(TargetFileName)
"
Outputs="
bin/$(Configuration)/publish/wwwroot/_framework/dotnet.native.wasm;
bin/$(Configuration)/publish/wwwroot/_framework/dotnet.native.js;
bin/$(Configuration)/publish/wwwroot/$(_WasmMainJSFileName);
">
<Target Name="_ValidateRuntimeFlavorBuild" BeforeTargets="BuildSampleInTree">
<PropertyGroup>
<_MonoBuildDir>$(ArtifactsObjDir)mono\browser.wasm.$(Configuration)\out\lib\</_MonoBuildDir>
<_CoreCLRBuildDir>$(ArtifactsObjDir)coreclr\browser.wasm.$(Configuration)\libs-native\</_CoreCLRBuildDir>
</PropertyGroup>
<Error Condition="'$(RuntimeFlavor)' == 'Mono' and !Exists('$(_MonoBuildDir)')"
Text="Mono build not found at '$(_MonoBuildDir)'. Build Mono for browser-wasm first: ./build.sh mono+libs -os browser -c $(Configuration)" />
<Error Condition="'$(RuntimeFlavor)' == 'CoreCLR' and !Exists('$(_CoreCLRBuildDir)')"
Text="CoreCLR build not found at '$(_CoreCLRBuildDir)'. Build CoreCLR for browser-wasm first: ./build.sh clr+libs+host -os browser -c $(Configuration)" />
</Target>

<Target Name="BuildSampleInTree">
<PropertyGroup>
<_ScriptExt Condition="'$(OS)' == 'Windows_NT'">.cmd</_ScriptExt>
<_ScriptExt Condition="'$(OS)' != 'Windows_NT'">.sh</_ScriptExt>
<_Dotnet>$(RepoRoot)dotnet$(_ScriptExt)</_Dotnet>
<_SampleProject Condition="'$(_SampleProject)' == ''">$(MSBuildProjectFile)</_SampleProject>
<_SampleAssembly Condition="'$(_SampleAssembly)' == ''">$(TargetFileName)</_SampleAssembly>
</PropertyGroup>
<!-- Clean obj (in artifacts) and bin (local) folders to avoid stale artifacts from previous builds, when runtime binaries and scripts change normal clean is too fragile -->
<RemoveDir Directories="$(BaseIntermediateOutputPath)" Condition="Exists('$(BaseIntermediateOutputPath)')" />
<RemoveDir Directories="$(MSBuildProjectDirectory)\bin" Condition="Exists('$(MSBuildProjectDirectory)\bin')" />
<ItemGroup>
<NestedBuildPropertyValue Include="/p:Nested_%(NestedBuildProperty.Identity)=$(%(NestedBuildProperty.Identity))" Condition="'$(%(NestedBuildProperty.Identity))' != '%(NestedBuildProperty.DefaultValue)'" />
</ItemGroup>
Expand Down
5 changes: 3 additions & 2 deletions src/mono/sample/wasm/browser/wwwroot/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ try {

const exports = await getAssemblyExports("Wasm.Browser.Sample");
await exports.Sample.Test.PrintMeaning(delay(2000).then(() => 42));
console.log("Program has exited normally.");
await dotnet.runMainAndExit();
const exitCode = await dotnet.run();
console.log(`Program has exited with code ${exitCode}.`);
exit(exitCode);
}
catch (err) {
exit(2, err);
Expand Down
2 changes: 1 addition & 1 deletion src/mono/sample/wasm/console-node/wwwroot/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ import { dotnet } from './_framework/dotnet.js'
await dotnet
.withDiagnosticTracing(false)
.withApplicationArguments("dotnet", "is", "great!")
.run()
.runMainAndExit();
18 changes: 10 additions & 8 deletions src/native/corehost/browserhost/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,18 @@ set(SHARED_LIB_DESTINATION
set(SHARED_CLR_DESTINATION
${CLR_ARTIFACTS_BIN_DIR}/coreclr/browser.wasm.${CMAKE_BUILD_RUNTIME_CONFIGURATION}/sharedFramework)

# these dependencies assume that you built `libs.native+clr.runtime` subsets first
# CoreCLR runtime .a libraries
LIST(APPEND NATIVE_LIBS
${SHARED_CLR_DESTINATION}/libcoreclr_static.a
${SHARED_CLR_DESTINATION}/libnativeresourcestring.a
${SHARED_CLR_DESTINATION}/libgcinfo_unix_wasm.a
${SHARED_CLR_DESTINATION}/libcoreclrminipal.a
${SHARED_CLR_DESTINATION}/libcoreclrpal.a
${SHARED_CLR_DESTINATION}/libminipal.a
)

# Shared platform .a libraries
list(APPEND NATIVE_LIBS
${SHARED_LIB_DESTINATION}/libSystem.Native.Browser.a
${SHARED_LIB_DESTINATION}/libSystem.Runtime.InteropServices.JavaScript.Native.a
${SHARED_LIB_DESTINATION}/libSystem.Native.a
Expand Down Expand Up @@ -95,18 +99,13 @@ set_target_properties(browserhost PROPERTIES

if (UPPERCASE_CMAKE_BUILD_TYPE STREQUAL DEBUG)
target_link_options(browserhost PRIVATE
# -sVERBOSE
# -sASSERTIONS=1
--emit-symbol-map
# add -sVERBOSE=1 to debug linking issues
-sASSERTIONS=1
-sLLD_REPORT_UNDEFINED
-sERROR_ON_UNDEFINED_SYMBOLS=1
)
endif ()

# add -sVERBOSE=1 to debug linking issues
# WASM-TODO -emit-llvm
# WASM-TODO --source-map-base http://microsoft.com
# WASM-TODO -sSEPARATE_DWARF=1, -gseparate-dwarf
target_link_options(browserhost PRIVATE
-sINITIAL_MEMORY=134217728
-sMAXIMUM_MEMORY=2147483648
Expand All @@ -121,6 +120,7 @@ target_link_options(browserhost PRIVATE
-sEXPORTED_FUNCTIONS=${CMAKE_EMCC_EXPORTED_FUNCTIONS}
-sEXPORT_NAME=createDotnetRuntime
-sENVIRONMENT=web,webview,worker,node,shell
--emit-symbol-map
-Wl,-error-limit=0)

target_link_libraries(browserhost PRIVATE
Expand All @@ -135,6 +135,8 @@ install(TARGETS browserhost DESTINATION corehost COMPONENT runtime)
install(TARGETS browserhost DESTINATION sharedFramework COMPONENT runtime)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dotnet.native.wasm DESTINATION corehost COMPONENT runtime)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dotnet.native.wasm DESTINATION sharedFramework COMPONENT runtime)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dotnet.native.js.symbols DESTINATION corehost COMPONENT runtime)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dotnet.native.js.symbols DESTINATION sharedFramework COMPONENT runtime)

set_source_files_properties(${BROWSERHOST_SOURCES} PROPERTIES OBJECT_DEPENDS
"${JS_SYSTEM_NATIVE_BROWSER};${JS_SYSTEM_BROWSER_UTILS};${JS_SYSTEM_RUNTIME_INTEROPSERVICES_JAVASCRIPT_NATIVE};${JS_BROWSER_HOST};${JS_SYSTEM_NATIVE_BROWSER_EXPOST}")
29 changes: 25 additions & 4 deletions src/native/corehost/browserhost/browserhost.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ extern "C" void* BrowserHost_CreateHostContract(void)
return &host_contract;
}

extern "C" int BrowserHost_InitializeCoreCLR(int propertiesCount, const char** propertyKeys, const char** propertyValues)
extern "C" int BrowserHost_InitializeDotnet(int propertiesCount, const char** propertyKeys, const char** propertyValues)
{
coreclr_set_error_writer(log_error_info);

Expand All @@ -122,15 +122,36 @@ extern "C" int BrowserHost_InitializeCoreCLR(int propertiesCount, const char** p
return 0;
}

static bool executeAssemblyFailed = false;
extern "C" int BrowserHost_ExecuteAssembly(const char* assemblyPath, int argc, const char** argv)
{
int ignore_exit_code = 0;
int retval = coreclr_execute_assembly(CurrentClrInstance, CurrentAppDomainId, argc, argv, assemblyPath, (uint32_t*)&ignore_exit_code);
executeAssemblyFailed = false;
int exit_code = 0;
int retval = coreclr_execute_assembly(CurrentClrInstance, CurrentAppDomainId, argc, argv, assemblyPath, (uint32_t*)&exit_code);

if (retval < 0)
{
std::fprintf(stderr, "coreclr_execute_assembly failed - Error: 0x%08x\n", retval);
executeAssemblyFailed = true;
return -1;
}
return 0;
return exit_code;
}

extern "C" int BrowserHost_ShutdownDotnet(int exit_code)
{
if (executeAssemblyFailed)
{
return exit_code;
}

int latched_exit_code = exit_code;
int result = coreclr_shutdown_2(CurrentClrInstance, CurrentAppDomainId, &latched_exit_code);
if (result < 0)
{
std::fprintf(stderr, "coreclr_shutdown_2 failed - Error: 0x%08x\n", result);
return -1;
}

return latched_exit_code;
}
14 changes: 7 additions & 7 deletions src/native/corehost/browserhost/host/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function initializeCoreCLR(): number {
buffers.push(valuePtr as any);
}

const res = _ems_._BrowserHost_InitializeCoreCLR(propertyCount, appctx_keys, appctx_values);
const res = _ems_._BrowserHost_InitializeDotnet(propertyCount, appctx_keys, appctx_values);
for (const buf of buffers) {
_ems_._free(buf as any);
}
Expand Down Expand Up @@ -81,14 +81,14 @@ export async function runMain(mainAssemblyName?: string, args?: string[]): Promi
ptrs.push(ptr);
_ems_.HEAPU32[(argsvPtr >>> 2) + i] = ptr;
}
const res = _ems_._BrowserHost_ExecuteAssembly(mainAssemblyNamePtr, args.length, argsvPtr);
_ems_.EXITSTATUS = _ems_._BrowserHost_ExecuteAssembly(mainAssemblyNamePtr, args.length, argsvPtr);
for (const ptr of ptrs) {
_ems_._free(ptr);
}

if (res != 0) {
if (_ems_.EXITSTATUS == -1) {
const reason = new Error("Failed to execute assembly");
_ems_.dotnetApi.exit(res, reason);
_ems_.dotnetApi.exit(-1, reason);
throw reason;
}

Expand All @@ -107,9 +107,9 @@ export async function runMain(mainAssemblyName?: string, args?: string[]): Promi
}

export async function runMainAndExit(mainAssemblyName?: string, args?: string[]): Promise<number> {
const res = await runMain(mainAssemblyName, args);
const exitCode = await runMain(mainAssemblyName, args);
try {
_ems_.dotnetApi.exit(0, null);
_ems_.dotnetApi.exit(exitCode, null);
} catch (error: any) {
// do not propagate ExitStatus exception
if (!error || typeof error.status !== "number") {
Expand All @@ -118,6 +118,6 @@ export async function runMainAndExit(mainAssemblyName?: string, args?: string[])
}
return error.status;
}
return res;
return exitCode;
}

6 changes: 0 additions & 6 deletions src/native/corehost/browserhost/host/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,6 @@ function setupEmscripten() {
for (const key in loaderConfig.environmentVariables) {
_ems_.ENV[key] = loaderConfig.environmentVariables[key];
}

_ems_.Module.preInit = [() => {
_ems_.FS.createPath("/", loaderConfig.virtualWorkingDirectory!, true, true);
_ems_.FS.chdir(loaderConfig.virtualWorkingDirectory!);
}, ...(_ems_.Module.preInit || [])];

}

export { BrowserHost_ExternalAssemblyProbe } from "./assets";
5 changes: 3 additions & 2 deletions src/native/corehost/browserhost/libBrowserHost.footer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ function libBrowserHostFactory() {
let explicitDeps = [
"wasm_load_icu_data",
"BrowserHost_CreateHostContract",
"BrowserHost_InitializeCoreCLR",
"BrowserHost_ExecuteAssembly"
"BrowserHost_InitializeDotnet",
"BrowserHost_ExecuteAssembly",
"BrowserHost_ShutdownDotnet",
];
let commonDeps = [
"$DOTNET",
Expand Down
Loading
Loading