-
Notifications
You must be signed in to change notification settings - Fork 5.6k
[wasm][coreclr] Dispatch R2R-compiled UnmanagedCallersOnly callbacks to their native entrypoint #134355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pavelsavara
wants to merge
15
commits into
dotnet:main
Choose a base branch
from
pavelsavara:wasm_UCO_TO_R2R_dispatch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
[wasm][coreclr] Dispatch R2R-compiled UnmanagedCallersOnly callbacks to their native entrypoint #134355
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
54a5ce9
[wasm][coreclr] Dispatch R2R-compiled UnmanagedCallersOnly callbacks …
pavelsavara 29a46ff
Merge branch 'main' into wasm_UCO_TO_R2R_dispatch
pavelsavara c895bf4
Merge branch 'main' into wasm_UCO_TO_R2R_dispatch
pavelsavara 59cc113
Cache R2R entrypoint lookup in reverse thunks; tidy fallback whitespace
pavelsavara fa2adc5
Merge branch 'main' into wasm_UCO_TO_R2R_dispatch
pavelsavara 82c18a9
Guard R2R reverse-thunk dispatch: skip by-ref returns, volatile-publi…
pavelsavara ea945e2
Provide VolatileLoad/VolatileStore in wasm callhelpers compat shim
pavelsavara 03d1404
Test R2R native export callback dispatch on wasm
pavelsavara a3aceae
Harden wasm R2R reverse thunk dispatch
pavelsavara c0240ac
Expand wasm R2R native callback ABI coverage
pavelsavara 64a68e1
Reject unsupported wasm callback struct returns
pavelsavara bc31a52
Reject unsupported wasm vector callbacks
pavelsavara dfdc276
Emit atomic wasm R2R callback cache operations
pavelsavara f350cdf
Compile test native sources without generated-helper flags
pavelsavara 26268db
Skip wasm corerun for struct-returning callconv tests
pavelsavara File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,8 @@ | |
| using System.Linq; | ||
| using System.Text; | ||
|
|
||
| using ILCompiler.DependencyAnalysis.Wasm; | ||
| using Internal.JitInterface; | ||
| using Internal.TypeSystem; | ||
| using Internal.TypeSystem.Ecma; | ||
| using Internal.TypeSystem.Interop; | ||
|
|
@@ -246,6 +248,7 @@ public void EmitNativeToInterp(TextWriter w, List<PInvokeCallback> callbacks) | |
| // The current approach has limitations with overloaded methods. | ||
| extern "C" void LookupUnmanagedCallersOnlyMethodByName(const char* fullQualifiedTypeName, const char* methodName, MethodDesc** ppMD); | ||
| extern "C" void ExecuteInterpretedMethodFromUnmanaged(MethodDesc* pMD, int8_t* args, size_t argSize, int8_t* ret, PCODE callerIp); | ||
| extern "C" void* GetR2RNativeCodeForUnmanagedCallersOnly(MethodDesc* pMD); | ||
|
|
||
| """); | ||
|
|
||
|
|
@@ -254,6 +257,7 @@ public void EmitNativeToInterp(TextWriter w, List<PInvokeCallback> callbacks) | |
| callbacks.Sort(new PInvokeCallbackComparer()); | ||
| foreach (PInvokeCallback cb in callbacks) | ||
| { | ||
| RejectUnsupportedCallbackSignature(cb); | ||
| cb.EntrySymbol = FixedSymbolName(cb); | ||
|
|
||
| if (!callbackNames.Add(cb.EntrySymbol)) | ||
|
|
@@ -281,11 +285,36 @@ public void EmitNativeToInterp(TextWriter w, List<PInvokeCallback> callbacks) | |
| // those instead. Every other type this emits reaches the slot unchanged through a cast. | ||
| bool CarriesBits(int i) => parameterCTypes[i] is "float" or "double"; | ||
| string argsDeclaration = parameterCount > 0 | ||
| ? $"\n int64_t args[{parameterCount}] = {{ {string.Join(", ", Enumerable.Range(0, parameterCount).Select(i => CarriesBits(i) ? "0" : $"(int64_t)arg{i}"))} }};\n" | ||
| + string.Concat(Enumerable.Range(0, parameterCount).Where(CarriesBits).Select(i => $" memcpy(&args[{i}], &arg{i}, sizeof(arg{i}));\n")) | ||
| ? $"\n\n int64_t args[{parameterCount}] = {{ {string.Join(", ", Enumerable.Range(0, parameterCount).Select(i => CarriesBits(i) ? "0" : $"(int64_t)arg{i}"))} }};" | ||
| + string.Concat(Enumerable.Range(0, parameterCount).Where(CarriesBits).Select(i => $"\n memcpy(&args[{i}], &arg{i}, sizeof(arg{i}));")) | ||
| : string.Empty; | ||
| string parametersDeclaration = string.Join(", ", parameterCTypes.Select((p, i) => $"{p} arg{i}")); | ||
| string arguments = string.Join(", ", Enumerable.Range(0, parameterCount).Select(i => $"arg{i}")); | ||
| // A partial R2R image can compile an UnmanagedCallersOnly callback to native code. That R2R code | ||
| // is the directly-callable native entrypoint (same ABI as this wrapper's parameters), so dispatch | ||
| // to it and skip the interpreter/interp->R2R path entirely. | ||
| string r2rVar = $"R2RCode_{cb.EntrySymbol}"; | ||
| string paramTypesOnly = string.Join(", ", parameterCTypes); | ||
| string r2rDispatch = cb.IsVoid | ||
| ? $"((void(*)({paramTypesOnly}))r2r)({arguments});{w.NewLine} return;" | ||
| : $"return (({MapType(cb.ReturnType)}(*)({paramTypesOnly}))r2r)({arguments});"; | ||
| // Cache the resolved entrypoint in a per-callback static, published with acquire/release | ||
| // atomics: these are native entry points that can be entered concurrently, and the value is | ||
| // computed identically on every call, so the racing read/write is benign but must not tear. | ||
| string r2rStaticDecl = $"{w.NewLine}static void* {r2rVar} = (void*)(intptr_t)-1;"; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could the new r2r section stuff not be inline below where it is much more readable? |
||
| string r2rSection = | ||
| w.NewLine + " // Prefer the R2R native entrypoint when this callback was compiled (partial R2R)." | ||
| + w.NewLine + " // Resolve once and cache; a method's native-code availability is fixed after first prepare." | ||
| + w.NewLine + $" void* r2r = __atomic_load_n(&{r2rVar}, __ATOMIC_ACQUIRE);" | ||
| + w.NewLine + " if (r2r == (void*)(intptr_t)-1)" | ||
| + w.NewLine + " {" | ||
| + w.NewLine + $" r2r = GetR2RNativeCodeForUnmanagedCallersOnly(MD_{cb.EntrySymbol});" | ||
| + w.NewLine + $" __atomic_store_n(&{r2rVar}, r2r, __ATOMIC_RELEASE);" | ||
| + w.NewLine + " }" | ||
| + w.NewLine + " if (r2r != nullptr)" | ||
| + w.NewLine + " {" | ||
| + w.NewLine + $" {r2rDispatch}" | ||
| + w.NewLine + " }"; | ||
| string exportFunction = cb.IsExport ? | ||
| $$""" | ||
|
|
||
|
|
@@ -298,16 +327,16 @@ public void EmitNativeToInterp(TextWriter w, List<PInvokeCallback> callbacks) | |
| w.Write( | ||
| $$""" | ||
|
|
||
| static MethodDesc* MD_{{cb.EntrySymbol}} = nullptr; | ||
| static MethodDesc* MD_{{cb.EntrySymbol}} = nullptr;{{r2rStaticDecl}} | ||
|
pavelsavara marked this conversation as resolved.
|
||
| static {{ | ||
| MapType(cb.ReturnType)}} Call_{{cb.EntrySymbol}}({{parametersDeclaration}}) | ||
| {{{argsDeclaration}} | ||
| { | ||
| // Lazy lookup of MethodDesc for the function export scenario. | ||
| if (!MD_{{cb.EntrySymbol}}) | ||
| { | ||
| LookupUnmanagedCallersOnlyMethodByName("{{cb.TypeFullName}}, {{cb.AssemblyName}}", "{{cb.MethodName}}", &MD_{{cb.EntrySymbol}}); | ||
| }{{ | ||
| (!cb.IsVoid ? $"{w.NewLine}{w.NewLine} {MapType(cb.ReturnType)} result;" : "")}} | ||
| }{{r2rSection}}{{argsDeclaration}}{{ | ||
| (!cb.IsVoid ? $"{w.NewLine} {MapType(cb.ReturnType)} result;" : "")}} | ||
| ExecuteInterpretedMethodFromUnmanaged(MD_{{cb.EntrySymbol}}, {{argsArgs}}, {{(cb.IsVoid ? "nullptr" : "(int8_t*)&result")}}, (PCODE)&Call_{{cb.EntrySymbol}});{{ | ||
| (!cb.IsVoid ? $"{w.NewLine} return result;" : "")}} | ||
| }{{exportFunction}} | ||
|
|
@@ -350,6 +379,43 @@ static void RejectAmbiguousExport(PInvokeCallback cb) | |
| throw new LogAsErrorException( | ||
| $"Exported callback '{cb.EntryPoint}' cannot be resolved at run time: '{cb.TypeFullName}' declares more than one [UnmanagedCallersOnly] method named '{cb.MethodName}', and the runtime looks them up by name alone. Give them distinct names: {string.Join(", ", ambiguous)}"); | ||
| } | ||
|
|
||
| static void RejectUnsupportedCallbackSignature(PInvokeCallback cb) | ||
| { | ||
| List<string> loweredTokens = InteropSignature.ParseSignatureTokens( | ||
| InteropSignature.GetMethodSignature(cb.Method, WasmLowering.LoweringFlags.IsUnmanagedCallersOnly)); | ||
| string token = null; | ||
| for (int i = 1; i < loweredTokens.Count; i++) | ||
| { | ||
| if (IsUnsupportedToken(loweredTokens[i])) | ||
| { | ||
| token = loweredTokens[i]; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| if (token is null && !cb.IsVoid) | ||
| { | ||
| string returnToken = InteropSignature.GetAbiToken(cb.ReturnType); | ||
| if (IsUnsupportedToken(returnToken)) | ||
| token = returnToken; | ||
| } | ||
|
|
||
| if (token is not null) | ||
| { | ||
| throw new LogAsErrorException( | ||
| $"UnmanagedCallersOnly callback '{cb.Method}' has unsupported signature token '{token}', which the generated native wrapper does not support."); | ||
| } | ||
|
|
||
| if (!cb.IsVoid && IsPassedByReference(cb.ReturnType)) | ||
| { | ||
| throw new LogAsErrorException( | ||
| $"UnmanagedCallersOnly callback '{cb.Method}' has return type '{cb.ReturnType}' that uses a hidden return buffer, which the generated native wrapper does not support."); | ||
|
pavelsavara marked this conversation as resolved.
|
||
| } | ||
|
|
||
| static bool IsUnsupportedToken(string token) => | ||
| token is "V" || InteropSignature.IsMultiSlotToken(token); | ||
| } | ||
| } | ||
|
|
||
| private string CEntryPoint(PInvokeInfo pinvoke) | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.