diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index 752b63657095d8..dd33733a1d24db 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -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)] diff --git a/src/coreclr/hosts/corerun/wasm/libCorerun.js b/src/coreclr/hosts/corerun/wasm/libCorerun.js index 59218d8b64dc38..897b2a91e37a2e 100644 --- a/src/coreclr/hosts/corerun/wasm/libCorerun.js +++ b/src/coreclr/hosts/corerun/wasm/libCorerun.js @@ -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 }); diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index 076bb83bc89807..e19710f79afa7f 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -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); diff --git a/src/coreclr/jit/lowerwasm.cpp b/src/coreclr/jit/lowerwasm.cpp index 7dc46aadbf8951..0a6ce2660fffb3 100644 --- a/src/coreclr/jit/lowerwasm.cpp +++ b/src/coreclr/jit/lowerwasm.cpp @@ -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(); } //--------------------------------------------------------------------------------------------- diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs index 5f7debb1024cb3..23819d9c078c50 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs @@ -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(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 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(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); } } @@ -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 pattern = stackalloc byte[12]; int length = 0; pattern[length++] = 0x41; // i32.const diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmImportLinkagePInvoke.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmImportLinkagePInvoke.cs new file mode 100644 index 00000000000000..71d628715eae12 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/Webcil/WasmImportLinkagePInvoke.cs @@ -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); +} diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/WasmR2RAssert.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/WasmR2RAssert.cs index 8fb276fca9755e..29b1010c1e5554 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/WasmR2RAssert.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/WasmR2RAssert.cs @@ -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); @@ -603,8 +602,8 @@ private static void CheckFunctionExports( } /// - /// Verifies the name 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 name 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. /// private static void CheckFunctionNames( WebcilImageReader reader, @@ -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; } @@ -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; } @@ -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 GetWasmFunctionImportNames(WebcilImageReader reader, string module) + { + List 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 image = reader.GetEntireImage().AsSpan(); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunSymbolNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunSymbolNodeFactory.cs index 536a08f352d074..f3e9de567fa83d 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunSymbolNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunSymbolNodeFactory.cs @@ -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; @@ -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))); + }); + + /// + /// A native function a Wasm image imports and calls directly through WasmImportLinkage. + /// + public ExternFunctionSymbolNode GetWasmImportLinkagePInvokeTargetNode(string importModule, string importName, MethodSignature signature) + { + return _wasmImportLinkagePInvokeTargets.GetOrAdd((importModule, importName, signature)); + } + internal Import ResumptionStubEntryPoint(MethodWithGCInfo resumptionStub) { return _resumptionStubEntryPointFixups.GetOrAdd(resumptionStub); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 86a53d2f556482..357942ccb332b4 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -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); diff --git a/src/native/libs/Common/JavaScript/host/assets.ts b/src/native/libs/Common/JavaScript/host/assets.ts index d3e12d1756aa08..20e4331b357f37 100644 --- a/src/native/libs/Common/JavaScript/host/assets.ts +++ b/src/native/libs/Common/JavaScript/host/assets.ts @@ -10,6 +10,7 @@ const hasInstantiateStreaming = typeof WebAssembly !== "undefined" && typeof Web const loadedAssemblies: Map = 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(); @@ -61,7 +62,12 @@ export async function instantiateWebcilModule(webcilPromise: Promise, 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"; @@ -238,6 +244,7 @@ export function installVfsFile(bytes: Uint8Array, asset: VfsAsset) { export async function instantiateWasm(wasmPromise: Promise, 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) {