Skip to content
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

[wasm] Unmanaged structs are considered blittable if module has DisableRuntimeMarshallingAttribute #73310

Merged
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
78 changes: 58 additions & 20 deletions src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
internal sealed class PInvokeTableGenerator
{
private static readonly char[] s_charsToReplace = new[] { '.', '-', '+' };
private readonly Dictionary<Assembly, bool> _assemblyDisableRuntimeMarshallingAttributeCache = new();

private TaskLoggingHelper Log { get; set; }

Expand Down Expand Up @@ -45,7 +46,7 @@ public IEnumerable<string> Generate(string[] pinvokeModules, string[] assemblies
using (var w = File.CreateText(tmpFileName))
{
EmitPInvokeTable(w, modules, pinvokes);
EmitNativeToInterp(w, callbacks);
EmitNativeToInterp(w, ref callbacks);
}

if (Utils.CopyIfDifferent(tmpFileName, outputPath, useHash: false))
Expand All @@ -68,6 +69,8 @@ private void CollectPInvokes(List<PInvoke> pinvokes, List<PInvokeCallback> callb
try
{
CollectPInvokesForMethod(method);
if (DoesMethodHaveCallbacks(method))
callbacks.Add(new PInvokeCallback(method));
}
catch (Exception ex) when (ex is not LogAsErrorException)
{
Expand All @@ -94,21 +97,57 @@ void CollectPInvokesForMethod(MethodInfo method)
Log.LogMessage(MessageImportance.Low, $"Adding pinvoke signature {signature} for method '{type.FullName}.{method.Name}'");
signatures.Add(signature);
}
}

bool DoesMethodHaveCallbacks(MethodInfo method)
{
if (!MethodHasCallbackAttributes(method))
return false;

if (TryIsMethodGetParametersUnsupported(method, out string? reason))
{
Log.LogWarning(null, "WASM0001", "", "", 0, 0, 0, 0,
$"Skipping callback '{method.DeclaringType!.FullName}::{method.Name}' because '{reason}'.");
return false;
}

if (method.DeclaringType != null && HasAssemblyDisableRuntimeMarshallingAttribute(method.DeclaringType.Assembly))
return true;

// No DisableRuntimeMarshalling attribute, so check if the params/ret-type are
// blittable
bool isVoid = method.ReturnType.FullName == "System.Void";
if (!isVoid && !IsBlittable(method.ReturnType))
Error($"The return type '{method.ReturnType.FullName}' of pinvoke callback method '{method}' needs to be blittable.");

foreach (var p in method.GetParameters())
{
if (!IsBlittable(p.ParameterType))
Error("Parameter types of pinvoke callback method '" + method + "' needs to be blittable.");
}

return true;
}

static bool MethodHasCallbackAttributes(MethodInfo method)
{
foreach (CustomAttributeData cattr in CustomAttributeData.GetCustomAttributes(method))
{
try
{
if (cattr.AttributeType.FullName == "System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute" ||
cattr.AttributeType.Name == "MonoPInvokeCallbackAttribute")

callbacks.Add(new PInvokeCallback(method));
{
return true;
}
}
catch
{
// Assembly not found, ignore
}
}

return false;
}
}

Expand Down Expand Up @@ -302,8 +341,10 @@ private static bool TryIsMethodGetParametersUnsupported(MethodInfo method, [NotN

if (TryIsMethodGetParametersUnsupported(pinvoke.Method, out string? reason))
{
// Don't use method.ToString() or any of it's parameters, or return type
// because at least one of those are unsupported, and will throw
Log.LogWarning(null, "WASM0001", "", "", 0, 0, 0, 0,
$"Skipping pinvoke '{pinvoke.Method.DeclaringType!.FullName}::{pinvoke.Method}' because '{reason}'.");
$"Skipping pinvoke '{pinvoke.Method.DeclaringType!.FullName}::{pinvoke.Method.Name}' because '{reason}'.");

pinvoke.Skip = true;
return null;
Expand All @@ -324,7 +365,7 @@ private static bool TryIsMethodGetParametersUnsupported(MethodInfo method, [NotN
return sb.ToString();
}

private static void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> callbacks)
private static void EmitNativeToInterp(StreamWriter w, ref List<PInvokeCallback> callbacks)
{
// Generate native->interp entry functions
// These are called by native code, so they need to obtain
Expand All @@ -339,22 +380,7 @@ private static void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> cal
// Arguments to interp entry functions in the runtime
w.WriteLine("InterpFtnDesc wasm_native_to_interp_ftndescs[" + callbacks.Count + "];");

foreach (var cb in callbacks)
{
MethodInfo method = cb.Method;
bool isVoid = method.ReturnType.FullName == "System.Void";

if (!isVoid && !IsBlittable(method.ReturnType))
Error($"The return type '{method.ReturnType.FullName}' of pinvoke callback method '{method}' needs to be blittable.");
foreach (var p in method.GetParameters())
{
if (!IsBlittable(p.ParameterType))
Error("Parameter types of pinvoke callback method '" + method + "' needs to be blittable.");
}
}

var callbackNames = new HashSet<string>();

foreach (var cb in callbacks)
{
var sb = new StringBuilder();
Expand Down Expand Up @@ -460,6 +486,18 @@ private static void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> cal
w.WriteLine("};");
}

private bool HasAssemblyDisableRuntimeMarshallingAttribute(Assembly assembly)
{
if (!_assemblyDisableRuntimeMarshallingAttributeCache.TryGetValue(assembly, out var value))
{
_assemblyDisableRuntimeMarshallingAttributeCache[assembly] = value = assembly
.GetCustomAttributesData()
.Any(d => d.AttributeType.Name == "DisableRuntimeMarshallingAttribute");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can use nameof(DisableRuntimeMarshallingAttribute) with using System.Runtime.CompilerServices;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The assembly is also compiled for net47 and the attribute is not available there.

}

return value;
}

private static bool IsBlittable(Type type)
{
if (type.IsPrimitive || type.IsByRef || type.IsPointer || type.IsEnum)
Expand Down
4 changes: 3 additions & 1 deletion src/tests/BuildWasmApps/Wasm.Build.Tests/BuildTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,9 @@ protected static string RunWithXHarness(string testCommand, string testLogPath,
// App arguments
if (envVars != null)
{
var setenv = string.Join(' ', envVars.Select(kvp => $"\"--setenv={kvp.Key}={kvp.Value}\"").ToArray());
var setenv = string.Join(' ', envVars
.Where(ev => ev.Key != "PATH")
.Select(kvp => $"\"--setenv={kvp.Key}={kvp.Value}\"").ToArray());
args.Append($" {setenv}");
}

Expand Down
Loading