Skip to content

Commit f945fdd

Browse files
committed
[wasi] Phase 5 + Phase 6: corerun.wasm host + native wasm exceptions
Working CoreCLR-WASI corerun: builds, links as a WASI Component (wasm-component-ld), runs under nesm and wasmtime 45, prints USAGE in ~200 ms. ** Linker / EH model (Phase 6 folded into Phase 5) ** - eng/native/configureplatform.cmake: switch CLR_CMAKE_TARGET_WASI from -fexceptions (sjlj) to -fwasm-exceptions + -mllvm -wasm-use-legacy-eh=false. sjlj cannot handle the interpreter ResumeAfterCatch throw-from-catch pattern; the new try_table/throw_ref proposal is what wasmtime 45 supports natively. Pulls in wasi-sdk 33's eh-flavored libc++/libc++abi/libunwind automatically. - eng/native/configureplatform.cmake: add browser-style project-wide link options for WASI (-fwasm-exceptions, -Wno-unused-command-line-argument, -Wl,--error-limit=0). Clear CMAKE_C/CXX_IMPLICIT_LINK_LIBRARIES and CMAKE_C/CXX_STANDARD_LIBRARIES so CMake doesn't add a default -lstdc++ (wasi-sdk ships libc++ only). Link -lc -lc++ -lc++abi -lunwind -ldl plus the WASI emulated libc helpers (process-clocks, signal, mman, getpid). - src/coreclr/CMakeLists.txt: drop -mllvm -wasm-enable-sjlj for WASI (was the sjlj setup we tried first). Document the EH model decision inline. Disable FEATURE_EVENT_TRACE and FEATURE_PERFTRACING for the initial WASI bring-up so the diagnostic-server PAL (ds-ipc-pal-socket.c) doesn't get pulled in — revisit when WASI sockets are validated. ** Host (Phase 5 proper) ** - src/coreclr/hosts/corerun/CMakeLists.txt: use wasm-component-ld (target-local via target_link_options, pointed at the wasi-sdk binary by absolute path because clang's -fuse-ld doesn't accept custom linker names) so the output is a WASI Component, not a plain core wasm module. Add stack-size and initial-memory tuning matching the Mono-WASI runtime. configure.cmake is included unconditionally (its check_symbol_exists/check_struct_has_member helpers gracefully return FALSE on WASI without failing the build). Skip CMAKE_DL_LIBS / -rdynamic on WASM hosts. - src/coreclr/hosts/corerun/corerun.hpp: gate try_load_library's dlopen call behind #ifdef TARGET_WASM (returns false on WASM; callers treat it as 'library not available'). ** PAL stubs to satisfy the link (Phase 5 link-stage discovery) ** - src/coreclr/pal/src/arch/wasm/stubs.cpp: add WASI-block stubs for the symbols seh-unwind.cpp (excluded) and debug/debug.cpp (excluded) would normally provide: * RaiseException (SEH entry), DebugBreak, OutputDebugStringA/W * PAL_FreeExceptionRecords, AllocateExceptionRecords, PAL_VirtualUnwind * Signal-handling: SEHInitializeSignals / SEHCleanupSignals / UnmaskActivationSignal / PAL_EnableCrashReportBeforeSignalChaining (C++ linkage to match pal/src/include/pal/signal.hpp declarations) * GetThreadContext, FlushInstructionCache * SystemJS_GetLocaleInfo (browser-only entry; null on WASI) Most stubs assert at runtime — they exist purely so the linker resolves references in code paths that never run on the WASI interpreter. ** Install (eng/native/functions.cmake) ** - install_clr: distinguish CLR_CMAKE_TARGET_BROWSER (install .js+.wasm pair per emscripten) from CLR_CMAKE_TARGET_WASI (install the single wasm-component-ld binary as one file). Previous unified WASM branch expected the emscripten .js sidecar which doesn't exist on WASI. ** Eventpipe / cdac deferral ** - eng/native.wasm.targets: drop the FEATURE_PERFTRACING_PAL_TCP=1 plumbing added earlier (Phase 4) — eventpipe is now disabled entirely for WASI via FEATURE_PERFTRACING=0 in coreclr/CMakeLists.txt. Listen-port disables retained for symmetry with browser-CoreCLR and for when we re-enable PERFTRACING. - src/coreclr/debug/debug-pal/CMakeLists.txt: restore the WASI exclusion of DEBUG_PAL_REFEREENCE_DIAGNOSTICSERVER (Phase 4 enabled it; with PERFTRACING off the diag-server PAL isn't needed). cdac kept on by default; switch off if/when it complicates the wasm-component-ld link. Verified end-to-end: corerun.wasm (88 MB) parses as a Component (3 core modules, 18 wasi:* imports, canonical functions), instantiates under nesm with --sandbox, prints USAGE on stderr, exit code 0, elapsed ~200ms. Co-authored-by: Copilot <[email protected]>
1 parent f4f4041 commit f945fdd

8 files changed

Lines changed: 223 additions & 9 deletions

File tree

‎eng/native.wasm.targets‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,11 @@
4242
</ItemGroup>
4343
<ItemGroup Condition="'$(TargetsWasi)' == 'true' and '$(RuntimeFlavor)' == 'CoreCLR'">
4444
<NativeCMakeArg Include="-cmakeargs &quot;-DGEN_PINVOKE=1&quot;" />
45-
<NativeCMakeArg Include="-cmakeargs &quot;-DFEATURE_PERFTRACING_PAL_TCP=1&quot;" />
45+
<!-- Initial WASI bring-up disables EventPipe / diagnostic-server PAL
46+
via FEATURE_PERFTRACING=0 in src/coreclr/CMakeLists.txt; the
47+
PERFTRACING_DISABLE_* flags are unused while PERFTRACING is off
48+
but kept for symmetry with browser-CoreCLR and for when we
49+
re-enable PERFTRACING in a follow-up. -->
4650
<NativeCMakeArg Include="-cmakeargs &quot;-DFEATURE_PERFTRACING_DISABLE_PERFTRACING_LISTEN_PORTS=1&quot;" />
4751
<NativeCMakeArg Include="-cmakeargs &quot;-DFEATURE_PERFTRACING_DISABLE_DEFAULT_LISTEN_PORT=1&quot;" />
4852
</ItemGroup>

‎eng/native/configureplatform.cmake‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,43 @@ else()
519519
add_compile_options(-msimd128)
520520
endif()
521521
if(CLR_CMAKE_TARGET_WASI)
522-
add_compile_options(-fexceptions)
522+
# Follow the browser-CoreCLR linking pattern (project-wide
523+
# add_link_options + add_compile_options for the EH model).
524+
# Native wasm exceptions are required (sjlj cannot handle the
525+
# interpreter's ResumeAfterCatch throw-from-catch pattern). The
526+
# wasi-sdk 33 sysroot ships eh-flavored libc++/libc++abi/libunwind
527+
# which clang picks automatically when -fwasm-exceptions is set.
528+
# -wasm-use-legacy-eh=false selects the new try_table/throw_ref
529+
# proposal which wasmtime 45+ supports natively. Legacy try would
530+
# require wasmtime --legacy-exceptions.
531+
add_compile_options(-fwasm-exceptions)
532+
add_compile_options(-mllvm -wasm-use-legacy-eh=false)
533+
534+
# Suppress the default CMake C++ stdlib (-lstdc++); wasi-sdk has
535+
# libc++ only and we link the eh-flavored variant explicitly below.
536+
set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "" CACHE STRING "" FORCE)
537+
set(CMAKE_CXX_STANDARD_LIBRARIES "" CACHE STRING "" FORCE)
538+
set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "" CACHE STRING "" FORCE)
539+
set(CMAKE_C_STANDARD_LIBRARIES "" CACHE STRING "" FORCE)
540+
541+
add_link_options(-fwasm-exceptions)
542+
add_link_options(-mllvm -wasm-use-legacy-eh=false)
543+
add_link_options(-Wno-unused-command-line-argument)
544+
add_link_options(-Wl,--error-limit=0)
545+
546+
# Supply the wasi-sdk libc++ stack explicitly so the eh-flavored
547+
# variants are picked.
548+
add_link_options(-lc)
549+
add_link_options(-lc++)
550+
add_link_options(-lc++abi)
551+
add_link_options(-lunwind)
552+
add_link_options(-ldl)
553+
554+
# WASI emulated libc helpers the CoreCLR PAL pulls in.
555+
add_link_options(-lwasi-emulated-process-clocks)
556+
add_link_options(-lwasi-emulated-signal)
557+
add_link_options(-lwasi-emulated-mman)
558+
add_link_options(-lwasi-emulated-getpid)
523559
endif()
524560
endif()
525561
endif()

‎eng/native/functions.cmake‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,8 +559,8 @@ function(install_clr)
559559
560560
foreach(destination ${destinations})
561561
# CMake bug with executable WASM outputs - https://gitlab.kitware.com/cmake/cmake/-/issues/20745
562-
if (CLR_CMAKE_TARGET_ARCH_WASM AND "${targetType}" STREQUAL "EXECUTABLE")
563-
# Use install FILES since these are WASM assets that aren't executable.
562+
if (CLR_CMAKE_TARGET_BROWSER AND "${targetType}" STREQUAL "EXECUTABLE")
563+
# Emscripten produces a .js + .wasm pair; install both as data files.
564564
install(FILES
565565
"$<TARGET_FILE_DIR:${targetName}>/${targetName}.js"
566566
"$<TARGET_FILE_DIR:${targetName}>/${targetName}.wasm"
@@ -574,6 +574,13 @@ function(install_clr)
574574
endif()
575575
"
576576
COMPONENT ${INSTALL_CLR_COMPONENT} ${INSTALL_CLR_OPTIONAL})
577+
elseif (CLR_CMAKE_TARGET_WASI AND "${targetType}" STREQUAL "EXECUTABLE")
578+
# wasi-sdk produces a single .wasm binary (the executable itself, no
579+
# extension). Install it as a data file — making it PROGRAMS would
580+
# require execute permission on a wasm file which the host runtime
581+
# (wasmtime) doesn't need.
582+
install(FILES $<TARGET_FILE:${targetName}>
583+
DESTINATION ${destination} COMPONENT ${INSTALL_CLR_COMPONENT} ${INSTALL_CLR_OPTIONAL})
577584
else()
578585
# We don't need to install the export libraries for our DLLs
579586
# since they won't be directly linked against.

‎src/coreclr/CMakeLists.txt‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,17 @@ if(CLR_CMAKE_TARGET_WASI)
3939
add_compile_definitions(_WASI_EMULATED_PROCESS_CLOCKS)
4040
add_compile_definitions(_WASI_EMULATED_MMAN)
4141
add_compile_definitions(_WASI_EMULATED_GETPID)
42-
add_compile_options(-mllvm -wasm-enable-sjlj)
42+
# Exception model: -fwasm-exceptions (set via configureplatform.cmake's
43+
# -fwasm-exceptions compile/link options). sjlj is intentionally NOT used —
44+
# it cannot handle throw-from-catch which the interpreter's ResumeAfterCatch
45+
# requires. WASI SDK 33 ships an eh-flavored libc++abi/libunwind which
46+
# clang picks automatically when -fwasm-exceptions is set.
47+
# Disable EventPipe / diagnostic-server PAL for the initial WASI bring-up.
48+
# eventpipe pulls in ds-ipc-pal-socket.c which requires UNIX-domain or TCP
49+
# sockets we have not validated end-to-end yet. Revisit once corerun.wasm
50+
# actually runs; for now keep the surface area small.
51+
set(FEATURE_EVENT_TRACE 0)
52+
set(FEATURE_PERFTRACING 0)
4353
# WASI doesn't define these fcntl constants — provide them as no-ops
4454
add_compile_definitions(F_DUPFD_CLOEXEC=1030)
4555
add_compile_definitions(O_CLOEXEC=0)

‎src/coreclr/debug/debug-pal/CMakeLists.txt‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@ if(CLR_CMAKE_HOST_WIN32)
2424
endif(CLR_CMAKE_HOST_WIN32)
2525

2626
if(CLR_CMAKE_HOST_UNIX)
27-
set(DEBUG_PAL_REFEREENCE_DIAGNOSTICSERVER ON)
27+
if (NOT CLR_CMAKE_TARGET_WASI)
28+
# Diagnostic-server PAL pulls in ds-ipc-pal-socket.c (UNIX-domain /
29+
# TCP sockets). Initial WASI bring-up disables EventPipe entirely via
30+
# FEATURE_PERFTRACING=0; re-enable once PERFTRACING is wired.
31+
set(DEBUG_PAL_REFEREENCE_DIAGNOSTICSERVER ON)
32+
endif()
2833

2934
add_definitions(-DPAL_IMPLEMENTATION)
3035
add_definitions(-D_POSIX_C_SOURCE=200809L)

‎src/coreclr/hosts/corerun/CMakeLists.txt‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ set(CORERUN_IN_BROWSER 0)
77
if(CLR_CMAKE_HOST_WIN32)
88
add_definitions(-DFX_VER_INTERNALNAME_STR=corerun.exe)
99
else()
10+
# WASI: getauxval and (sometimes) dirent.d_type are absent. The
11+
# check_symbol_exists / check_struct_has_member helpers report FALSE
12+
# without failing the build, so this is safe to include unconditionally.
1013
include(configure.cmake)
1114
endif()
1215

@@ -36,9 +39,11 @@ if(CLR_CMAKE_HOST_WIN32)
3639
target_link_options(corerun PRIVATE "/CETCOMPAT")
3740
endif()
3841
else()
39-
target_link_libraries(corerun PRIVATE ${CMAKE_DL_LIBS})
40-
# Required to expose symbols for global symbol discovery
41-
target_link_libraries(corerun PRIVATE -rdynamic)
42+
if (NOT CLR_CMAKE_TARGET_ARCH_WASM)
43+
target_link_libraries(corerun PRIVATE ${CMAKE_DL_LIBS})
44+
# Required to expose symbols for global symbol discovery
45+
target_link_libraries(corerun PRIVATE -rdynamic)
46+
endif()
4247

4348
# Android implements pthread natively.
4449
# WASM, linking against pthreads indicates Node.js workers are
@@ -116,6 +121,20 @@ else()
116121
-sNODERAWFS=1
117122
-lnodefs.js)
118123
endif()
124+
elseif (CLR_CMAKE_TARGET_WASI)
125+
# Use wasm-component-ld to produce a WASI Component (wraps the
126+
# wasi:[email protected] imports into the component model). The default
127+
# -fuse-ld=lld set by init-compiler.sh produces a plain core
128+
# module which wasmtime/nesm/etc. can't instantiate against
129+
# a component-host. Pass the absolute path because clang only
130+
# accepts well-known linker names (lld/bfd/gold/etc.) otherwise.
131+
# Target-local so the cmake feature-detection test executables
132+
# keep using lld.
133+
get_filename_component(_wasi_sdk_bin "${CMAKE_C_COMPILER}" DIRECTORY)
134+
target_link_options(corerun PRIVATE
135+
"-fuse-ld=${_wasi_sdk_bin}/wasm-component-ld"
136+
-Wl,-z,stack-size=8388608
137+
-Wl,--initial-memory=52428800)
119138
endif()
120139

121140
if (CORERUN_IN_BROWSER)

‎src/coreclr/hosts/corerun/corerun.hpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -713,13 +713,20 @@ namespace pal
713713

714714
inline bool try_load_library(const pal::string_t& path, pal::mod_t& hMod)
715715
{
716+
#ifdef TARGET_WASM
717+
// WASM hosts statically link all symbols; there is no dlopen.
718+
// Callers handle the false return as "library not available".
719+
(void)path; hMod = nullptr;
720+
return false;
721+
#else
716722
hMod = (pal::mod_t)dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
717723
if (hMod == nullptr)
718724
{
719725
pal::fprintf(stderr, W("Failed to load: '%s'. Error: %s\n"), path.c_str(), dlerror());
720726
return false;
721727
}
722728
return true;
729+
#endif
723730
}
724731

725732

‎src/coreclr/pal/src/arch/wasm/stubs.cpp‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
#include <emscripten/emscripten.h>
1010
#elif defined(TARGET_WASI)
1111
#include <stdlib.h>
12+
#include <stdint.h>
1213
#include <errno.h>
14+
#include <stdio.h>
1315
#include "pal/wasi/pal_wasi_missing.h"
1416
#endif
1517

@@ -166,6 +168,130 @@ DWORD CONTEXTGetExceptionCodeForSignal(const siginfo_t *siginfo,
166168
return 0;
167169
}
168170

171+
// RaiseException is the WIN32-style SEH entry — normally provided by
172+
// seh-unwind.cpp, which we exclude on WASI. The managed exception path on the
173+
// WASI interpreter throws PAL_SEHException via C++ throw instead, so this
174+
// surface is never reached. Stub kept only to satisfy linker references in
175+
// SString / NamespaceUtil / CLRConfig.
176+
extern "C" VOID PALAPI
177+
RaiseException(
178+
IN DWORD dwExceptionCode,
179+
IN DWORD dwExceptionFlags,
180+
IN DWORD nNumberOfArguments,
181+
IN CONST ULONG_PTR *lpArguments)
182+
{
183+
(void)dwExceptionFlags; (void)nNumberOfArguments; (void)lpArguments;
184+
_ASSERT(!"RaiseException not implemented on wasi");
185+
abort();
186+
}
187+
188+
// WIN32 debug-output APIs. WASI build excludes pal/src/debug/debug.cpp; route
189+
// to the same internal channels stderr would on a real platform.
190+
extern "C" VOID PALAPI
191+
DebugBreak()
192+
{
193+
_ASSERT(!"DebugBreak not implemented on wasi");
194+
__builtin_debugtrap();
195+
abort();
196+
}
197+
198+
extern "C" VOID PALAPI
199+
OutputDebugStringA(IN LPCSTR lpOutputString)
200+
{
201+
if (lpOutputString) fputs(lpOutputString, stderr);
202+
}
203+
204+
extern "C" VOID PALAPI
205+
OutputDebugStringW(IN LPCWSTR lpOutputString)
206+
{
207+
(void)lpOutputString; // wchar_t* — not converted here; stub only
208+
}
209+
210+
// PAL exception-record allocation. Normally provided by seh-unwind.cpp, which
211+
// we exclude on WASI. The WASI interpreter doesn't dispatch through the
212+
// EXCEPTION_RECORD/CONTEXT machinery (it throws PAL_SEHException directly),
213+
// so these are only here to satisfy linker references in dispatch helpers
214+
// that never run.
215+
extern "C" PALIMPORT VOID PALAPI
216+
PAL_FreeExceptionRecords(IN EXCEPTION_RECORD *exceptionRecord, IN CONTEXT *contextRecord)
217+
{
218+
(void)exceptionRecord;
219+
free(contextRecord);
220+
}
221+
222+
extern "C" VOID
223+
AllocateExceptionRecords(EXCEPTION_RECORD** exceptionRecord, CONTEXT** contextRecord)
224+
{
225+
*exceptionRecord = (EXCEPTION_RECORD*)calloc(1, sizeof(EXCEPTION_RECORD));
226+
*contextRecord = (CONTEXT*)calloc(1, sizeof(CONTEXT));
227+
}
228+
229+
extern "C" PALIMPORT BOOL PALAPI
230+
PAL_VirtualUnwind(CONTEXT *context)
231+
{
232+
(void)context;
233+
_ASSERT(!"PAL_VirtualUnwind not implemented on wasi");
234+
return FALSE;
235+
}
236+
237+
// Signal-handling surface — pal/src/exception/signal.cpp is excluded on WASI.
238+
// Stubs return success/no-op so the PAL init/shutdown paths continue.
239+
// These are C++ symbols (declared without extern "C" in pal/src/include/pal/signal.hpp).
240+
BOOL SEHInitializeSignals(CorUnix::CPalThread* pthrCurrent, DWORD flags)
241+
{
242+
(void)pthrCurrent; (void)flags;
243+
return TRUE;
244+
}
245+
246+
void SEHCleanupSignals(bool isChildProcess)
247+
{
248+
(void)isChildProcess;
249+
}
250+
251+
void UnmaskActivationSignal()
252+
{
253+
}
254+
255+
extern "C" VOID PALAPI
256+
PAL_EnableCrashReportBeforeSignalChaining(void)
257+
{
258+
// No-op: WASI has no signal delivery.
259+
}
260+
261+
// Per-thread context retrieval. Normally implemented via ptrace on Unix.
262+
// WASI single-process has no other thread to inspect.
263+
extern "C" PALIMPORT BOOL PALAPI
264+
GetThreadContext(IN HANDLE hThread, IN OUT LPCONTEXT lpContext)
265+
{
266+
(void)hThread; (void)lpContext;
267+
_ASSERT(!"GetThreadContext not implemented on wasi");
268+
return FALSE;
269+
}
270+
271+
// FlushInstructionCache: no-op on WASI. wasm has no separate I-cache to flush.
272+
extern "C" PALIMPORT BOOL PALAPI
273+
FlushInstructionCache(IN HANDLE hProcess, IN LPCVOID lpBaseAddress, IN SIZE_T dwSize)
274+
{
275+
(void)hProcess; (void)lpBaseAddress; (void)dwSize;
276+
return TRUE;
277+
}
278+
279+
// SystemJS_GetLocaleInfo is the browser ICU shim entrypoint
280+
// (src/native/libs/System.Native.Browser/native/globalization-locale.ts).
281+
// On WASI we don't have a JS host; return null. The managed Globalization
282+
// layer must already gracefully handle this for the browser-not-loaded case.
283+
extern "C" uint16_t* SystemJS_GetLocaleInfo(
284+
const uint16_t* locale, int32_t localeLength,
285+
const uint16_t* culture, int32_t cultureLength,
286+
const uint16_t* result, int32_t resultMaxLength,
287+
int* resultLength)
288+
{
289+
(void)locale; (void)localeLength; (void)culture; (void)cultureLength;
290+
(void)result; (void)resultMaxLength;
291+
if (resultLength) *resultLength = 0;
292+
return nullptr;
293+
}
294+
169295
// PAL also indirectly references getpwuid_r through PAL_GetUserName-style
170296
// paths (init/pal.cpp transitively includes <pwd.h>). Provide a stub so
171297
// transitive references resolve.

0 commit comments

Comments
 (0)