Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -602,12 +602,12 @@ internal IntPtr GetGCHandle(GCHandleType type)

[ErrorHandler(typeof(QCallExceptionStatusMarshaller), ErrorLocation.HiddenLastParameter)]
[LibraryImport(RuntimeHelpers.QCall, EntryPoint = "QCall_FreeGCHandleForTypeHandle")]
private static partial IntPtr FreeGCHandle(QCallTypeHandle typeHandle, IntPtr objHandle);
private static partial void FreeGCHandle(QCallTypeHandle typeHandle, IntPtr objHandle);

internal IntPtr FreeGCHandle(IntPtr objHandle)
internal void FreeGCHandle(IntPtr objHandle)
{
RuntimeTypeHandle nativeHandle = GetNativeHandle();
return FreeGCHandle(new QCallTypeHandle(ref nativeHandle), objHandle);
FreeGCHandle(new QCallTypeHandle(ref nativeHandle), objHandle);
}

[MethodImpl(MethodImplOptions.InternalCall)]
Expand Down
30 changes: 18 additions & 12 deletions src/coreclr/hosts/corerun/wasm/libCorerun.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,18 +268,24 @@ function libCoreRunFactory() {
throw new Error("__async_continuation was not preserved by the linker or optimizer");
}
payloadPtr = HEAPU32[ptrPtr >>> 2 >>> 0];
wasmInstance = new WebAssembly.Instance(wasmModule, {
webcil: {
memory: wasmMemory,
__stack_pointer: wasmExports.__stack_pointer,
__coreclr_wasm_rtlrestorecontext_tag: wasmExports.__coreclr_wasm_rtlrestorecontext_tag,
__indirect_function_table: wasmTable,
__table_base: new WebAssembly.Global({ value: "i32", mutable: false }, tableStartIndex),
__memory_base: new WebAssembly.Global({ value: "i32", mutable: false }, payloadPtr),
// Runtime-async continuation return value, shared with the runtime module.
__async_continuation: wasmExports.__async_continuation
}
});
const webcilImports = {
memory: wasmMemory,
__stack_pointer: wasmExports.__stack_pointer,
__coreclr_wasm_rtlrestorecontext_tag: wasmExports.__coreclr_wasm_rtlrestorecontext_tag,
__indirect_function_table: wasmTable,
__table_base: new WebAssembly.Global({ value: "i32", mutable: false }, tableStartIndex),
__memory_base: new WebAssembly.Global({ value: "i32", mutable: false }, payloadPtr),
// Runtime-async continuation return value, shared with the runtime module.
__async_continuation: wasmExports.__async_continuation
};
// R2R Webcil images can import [WasmImportLinkage] P/Invoke targets from their declared modules.
// Reuse Emscripten's host imports for "env" and "wasi_snapshot_preview1".
const imports = { webcil: webcilImports };
if (typeof (wasmImports) !== "undefined") {
imports.env = wasmImports;
imports.wasi_snapshot_preview1 = wasmImports;
}
wasmInstance = new WebAssembly.Instance(wasmModule, imports);
} catch (e) {
const errorMessage = e instanceof Error ? e.message : String(e);
console.error("Failed to construct WebAssembly instance for Webcil image:", { wasmPath, errorMessage });
Expand Down
8 changes: 0 additions & 8 deletions src/coreclr/jit/lower.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6399,14 +6399,6 @@ GenTree* Lowering::LowerDirectCall(GenTreeCall* call)
// For JIT helper based tailcall (only used on x86) the target
// address is passed as an arg to the helper so we want a node for
// it.
#ifdef TARGET_WASMARCH
if (m_compiler->IsReadyToRun())
{
// IAT_VALUE identifies a directly callable symbol rather than a portable entrypoint cell.
call->gtDirectCallAddress = addr;
break;
}
#endif
if (!IsCallTargetInRange(addr) || call->IsTailCallViaJitHelper())
{
result = AddrGen(addr);
Expand Down
5 changes: 3 additions & 2 deletions src/coreclr/jit/lowerwasm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ void Lowering::SetMultiplyUsed(GenTree* node DEBUGARG(const char* reason))
// IsCallTargetInRange: Can a call target address be encoded in-place?
//
// Return Value:
// False when PEP is enabled, true when it is not enabled.
// True when PEP is disabled or this is ReadyToRun, where direct call targets are function symbols that can
// be encoded directly even with PEP codegen.
//
bool Lowering::IsCallTargetInRange(void* addr)
{
return !m_compiler->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PORTABLE_ENTRY_POINTS);
return !m_compiler->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PORTABLE_ENTRY_POINTS) || m_compiler->IsReadyToRun();
}

//---------------------------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,60 @@ void Validate(ReadyToRunReader reader)
}
Assert.NotEmpty(globalizationTargets);
Assert.Equal(directModule, globalizationTargets.Contains(true));

// P/Invokes into configured direct modules keep the PInvokeTarget fixup instead of importing the native symbol.
WebcilImageReader webcilReader = Assert.IsType<WebcilImageReader>(reader.CompositeReader);
Assert.DoesNotContain(WasmR2RAssert.GetWasmFunctionImportNames(webcilReader, "webcil"),
name => name.StartsWith("GlobalizationNative_", StringComparison.Ordinal));
}
}

[ConditionalFact(typeof(TestPaths), nameof(TestPaths.IsWasmTarget))]
public void WasmImportLinkagePInvokesImportFromTheirModule()
{
CompiledAssembly input = new()
{
AssemblyName = nameof(WasmImportLinkagePInvokesImportFromTheirModule),
SourceResourceNames = ["Webcil/WasmImportLinkagePInvoke.cs"],
};
new R2RTestRunner(_output).Run(new R2RTestCase(
nameof(WasmImportLinkagePInvokesImportFromTheirModule),
[
new(nameof(WasmImportLinkagePInvokesImportFromTheirModule), [new CrossgenAssembly(input)])
{
Options = [Crossgen2Option.Optimize],
AdditionalArgs = ["--codegenopt", "JitNoInline=1"],
OutputFileExtension = ".wasm",
Validate = Validate,
},
]));

static void Validate(ReadyToRunReader reader)
{
SignatureFormattingOptions formattingOptions = new();
List<string> pinvokeTargets = new();
foreach (ReadyToRunImportSection section in reader.ImportSections)
{
foreach (ReadyToRunImportSection.ImportSectionEntry entry in section.Entries)
{
if (entry.Signature?.FixupKind == ReadyToRunFixupKind.PInvokeTarget)
{
pinvokeTargets.Add(entry.Signature.ToString(formattingOptions));
}
}
}

WebcilImageReader webcilReader = Assert.IsType<WebcilImageReader>(reader.CompositeReader);
Assert.Equal(["[method]resource.call"],
WasmR2RAssert.GetWasmFunctionImportNames(webcilReader, "test:module/interface@1.0.0"));
Assert.DoesNotContain(WasmR2RAssert.GetWasmFunctionImportNames(webcilReader, "webcil"),
name => name.Contains("resource.call", StringComparison.Ordinal));
Assert.DoesNotContain(WasmR2RAssert.GetWasmFunctionImportNames(webcilReader, "webcil"),
name => name.Contains("QCall_Test", StringComparison.Ordinal));
Assert.DoesNotContain(pinvokeTargets, target => target.Contains(".Imported(", StringComparison.Ordinal));
Assert.Contains(pinvokeTargets, target => target.Contains(".NotDirect(", StringComparison.Ordinal));
Assert.Contains(pinvokeTargets, target => target.Contains(".QCallTarget(", StringComparison.Ordinal));
Assert.True(WasmR2RAssert.WasmIndexSpacesHaveExpectedEntries(webcilReader, out string diagnostic), diagnostic);
}
}

Expand Down Expand Up @@ -184,6 +238,9 @@ void Validate(ReadyToRunReader reader)
uint tableIndex = checked(reader.WasmMinFunctionTableIndex + (uint)callee.EntryPointRuntimeFunctionId);
int functionIndex = webcilReader.GetFunctionIndexFromTableIndex(tableIndex);
Assert.True(functionIndex >= 0);
// GetFunctionIndexFromTableIndex returns a defined-function index; call operands index
// the whole function space, which starts with the imported functions.
functionIndex += WasmR2RAssert.GetWasmFunctionImportCount(webcilReader);
Span<byte> pattern = stackalloc byte[12];
int length = 0;
pattern[length++] = 0x41; // i32.const
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: DisableRuntimeMarshalling]

public static class WasmImportLinkagePInvoke
{
[WasmImportLinkage]
[DllImport("test:module/interface@1.0.0", EntryPoint = "[method]resource.call")]
private static extern int Imported(int value);

[DllImport("NotDirect", EntryPoint = "NotDirect_Call")]
private static extern int NotDirect(int value);

[DllImport("QCall", EntryPoint = "QCall_Test")]
private static extern int QCallTarget(int value);

public static int CallImported(int value) => Imported(value);

public static int CallNotDirect(int value) => NotDirect(value);

public static int CallQCallTarget(int value) => QCallTarget(value);
}
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,6 @@ public static bool WasmIndexSpacesHaveExpectedEntries(WebcilImageReader reader,
uint importedGlobalCount = CountWasmImports(imports, WasmImportKind.Global);
uint importedTagCount = CountWasmImports(imports, WasmImportKind.Tag);

CheckImportCount(WasmImportKind.Function, importedFunctionCount, 0, failures);
CheckImportCount(WasmImportKind.Table, importedTableCount, 1, failures);
CheckImportCount(WasmImportKind.Memory, importedMemoryCount, 1, failures);
CheckImportCount(WasmImportKind.Global, importedGlobalCount, 4, failures);
Expand Down Expand Up @@ -603,8 +602,8 @@ private static void CheckFunctionExports(
}

/// <summary>
/// Verifies the <c>name</c> custom section names every defined function, since it is the only
/// record of function names once they are no longer carried by the export table.
/// Verifies the <c>name</c> custom section names every function, imported and defined, since it is
/// the only record of function names once they are no longer carried by the export table.
/// </summary>
private static void CheckFunctionNames(
WebcilImageReader reader,
Expand All @@ -620,9 +619,11 @@ private static void CheckFunctionNames(
}

uint count = ReadWasmUleb32(image, ref offset, subsectionEnd);
if (count != definedFunctionCount)
if (count != importedFunctionCount + definedFunctionCount)
{
failures.Add($"Name section names {count} functions for {definedFunctionCount} function-section entries.");
failures.Add(
$"Name section names {count} functions for {importedFunctionCount} function imports and " +
$"{definedFunctionCount} function-section entries.");
return;
}

Expand All @@ -632,15 +633,14 @@ private static void CheckFunctionNames(
uint index = ReadWasmUleb32(image, ref offset, subsectionEnd);
string name = ReadWasmName(image, ref offset, subsectionEnd);

// Names must cover the defined-function range exactly. Checking only the ordering and
// the lower bound would accept a uniformly shifted map, which is precisely the
// off-by-one this section has to be trusted not to have.
uint expectedIndex = importedFunctionCount + i;
// Names must cover the whole function index space, imports included, exactly. Checking
// only the ordering and the lower bound would accept a uniformly shifted map, which is
// precisely the off-by-one this section has to be trusted not to have.
uint expectedIndex = i;
if (index != expectedIndex)
{
failures.Add(
$"Name section entry {i} names function index {index}; expected {expectedIndex} " +
$"after {importedFunctionCount} function imports.");
$"Name section entry {i} names function index {index}; expected {expectedIndex}.");
return;
}

Expand Down Expand Up @@ -716,6 +716,21 @@ private static bool TryGetWasmFunctionNameSubsection(
return false;
}

public static int GetWasmFunctionImportCount(WebcilImageReader reader)
=> ReadWasmImports(reader).Values.Count(import => import.Kind == WasmImportKind.Function);

public static List<string> GetWasmFunctionImportNames(WebcilImageReader reader, string module)
{
List<string> names = new();
foreach (((string importModule, string name), WasmImportIndex import) in ReadWasmImports(reader))
{
if (import.Kind == WasmImportKind.Function && importModule == module)
names.Add(name);
}

return names;
}

private static Dictionary<(string Module, string Name), WasmImportIndex> ReadWasmImports(WebcilImageReader reader)
{
ReadOnlySpan<byte> image = reader.GetEntireImage().AsSpan();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using ILCompiler.DependencyAnalysis.ReadyToRun;

using Internal.IL;
using Internal.JitInterface;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
Expand Down Expand Up @@ -823,6 +825,22 @@ public Import GetPInvokeTargetNode(MethodWithToken methodWithToken)
return _pInvokeTargetNodes.GetOrAdd(new PInvokeTargetKey(methodWithToken, isIndirect: false));
}

private NodeCache<(string ImportModule, string ImportName, MethodSignature Signature), ExternFunctionSymbolNode> _wasmImportLinkagePInvokeTargets =
new NodeCache<(string ImportModule, string ImportName, MethodSignature Signature), ExternFunctionSymbolNode>(key =>
{
Utf8String symbolName = new Utf8String($"{key.ImportModule}#{key.ImportName}");
return new ExternFunctionSymbolNode(symbolName, key.Signature, isUnmanagedCallersOnly: true, isAsyncCall: false, hasGenericContextArg: false,
new WasmLinkageMetadata(new Utf8String(key.ImportName), new Utf8String(key.ImportModule)));
});

/// <summary>
/// A native function a Wasm image imports and calls directly through WasmImportLinkage.
/// </summary>
public ExternFunctionSymbolNode GetWasmImportLinkagePInvokeTargetNode(string importModule, string importName, MethodSignature signature)
{
return _wasmImportLinkagePInvokeTargets.GetOrAdd((importModule, importName, signature));
}

internal Import ResumptionStubEntryPoint(MethodWithGCInfo resumptionStub)
{
return _resumptionStubEntryPointFixups.GetOrAdd(resumptionStub);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3659,10 +3659,27 @@ private unsafe HRESULT allocPgoInstrumentationBySchema(CORINFO_METHOD_STRUCT_* f
private void getAddressOfPInvokeTarget(CORINFO_METHOD_STRUCT_* method, ref CORINFO_CONST_LOOKUP pLookup)
{
MethodDesc methodDesc = HandleToObject(method);
MethodSignature nativeSignature = methodDesc.Signature;
if (methodDesc is IL.Stubs.PInvokeTargetNativeMethod rawPInvoke)
methodDesc = rawPInvoke.Target;
Debug.Assert(_compilation.CompilationModuleGroup.VersionsWithMethodBody(methodDesc));
EcmaMethod ecmaMethod = (EcmaMethod)methodDesc;

if (_compilation.NodeFactory.Target.IsWasm
&& _compilation.CompilationModuleGroup.IsDirectPInvoke(ecmaMethod)
&& ecmaMethod.HasCustomAttribute("System.Runtime.InteropServices", "WasmImportLinkageAttribute"))
{
// [WasmImportLinkage] P/Invokes are ordinary WebAssembly function imports. Other P/Invokes use
// the PInvokeTarget fixup and generated table below.
PInvokeMetadata metadata = ecmaMethod.GetPInvokeMethodMetadata();
string entryPoint = metadata.Name ?? ecmaMethod.GetName();
ExternFunctionSymbolNode target = _compilation.SymbolNodeFactory.GetWasmImportLinkagePInvokeTargetNode(
metadata.Module, entryPoint, nativeSignature);
pLookup.addr = (void*)ObjectToHandle(target);
pLookup.accessType = InfoAccessType.IAT_VALUE;
return;
}

ModuleToken moduleToken = new ModuleToken(ecmaMethod.Module, ecmaMethod.Handle);
MethodWithToken methodWithToken = new MethodWithToken(ecmaMethod, moduleToken, constrainedType: null, unboxing: false, genericContextObject: null);

Expand Down
9 changes: 8 additions & 1 deletion src/native/libs/Common/JavaScript/host/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const hasInstantiateStreaming = typeof WebAssembly !== "undefined" && typeof Web
const loadedAssemblies: Map<string, { ptr: number, length: number }> = new Map();
// Self-installing wrapper version; keep in sync with WebcilConstants.WASM_WRAPPER_VERSION_SELF_INSTALLING.
const webcilWrapperVersion = 2;
let hostImports: WebAssembly.Imports | undefined;

export function registerPdbBytes(bytes: Uint8Array, virtualPath: string, shortName: string) {
const sp = _ems_.stackSave();
Expand Down Expand Up @@ -61,7 +62,12 @@ export async function instantiateWebcilModule(webcilPromise: Promise<Response>,
let payloadPtr = 0;
try {
payloadPtr = allocWebcilPayload(payloadSize);
const imports: WebAssembly.Imports = { webcil: buildWebcilImports(memory, payloadPtr, tableEntries) };
const webcilImports = buildWebcilImports(memory, payloadPtr, tableEntries);
// R2R Webcil images have tableEntries > 0; IL-only Webcil images have no table. R2R images use the
// host-provided imports to resolve [WasmImportLinkage] P/Invokes from their declared modules.
const imports: WebAssembly.Imports = tableEntries > 0
? { ...hostImports, webcil: webcilImports }
: { webcil: webcilImports };
let instance: WebAssembly.Instance;
const contentType = res.headers && res.headers.get ? res.headers.get("Content-Type") : undefined;
const streamingOk = hasInstantiateStreaming && typeof globalThis.Response === "function" && res instanceof globalThis.Response && contentType === "application/wasm";
Expand Down Expand Up @@ -238,6 +244,7 @@ export function installVfsFile(bytes: Uint8Array, asset: VfsAsset) {
export async function instantiateWasm(wasmPromise: Promise<Response>, imports: WebAssembly.Imports): Promise<{ instance: WebAssembly.Instance; module: WebAssembly.Module; }> {
let instance: WebAssembly.Instance;
let module: WebAssembly.Module;
hostImports = imports;
try {
const res = await checkResponseOk(wasmPromise);
if (!hasInstantiateStreaming || !res.isStreamingOk) {
Expand Down
Loading