Skip to content

Commit

Permalink
Rework the parameter building
Browse files Browse the repository at this point in the history
  • Loading branch information
lewing committed Sep 2, 2024
1 parent 0bda870 commit 85ebd63
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,6 @@ public void UCOWithSpecialCharacters(BuildArgs buildArgs, RunHost host, string i
DotnetWasmFromRuntimePack: false));

var runOutput = RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 42, host: host, id: id);
Assert.Contains("Conflict.A.Managed8\u4F60Func(33) -> 33", runOutput);
Assert.DoesNotContain("Conflict.A.Managed8\u4F60Func(123) -> 123", runOutput);
Assert.Contains("ManagedFunc returned 42", runOutput);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ public unsafe partial class Test
public unsafe static int Main(string[] args)
{
((IntPtr)(delegate* unmanaged<int,int>)&Interop.Managed8\u4F60Func).ToString();
((IntPtr)(delegate* unmanaged<int,int>)&Conflict.A.Interop.Managed8\u4F60Func)(33);
Console.WriteLine($"main: {args.Length}");
Interop.UnmanagedFunc();

Expand All @@ -19,7 +18,6 @@ file class Interop {
[UnmanagedCallersOnly(EntryPoint = "ConflictManagedFunc")]
public static int Managed8\u4F60Func(int number)
{
// called from UnmanagedFunc
Console.WriteLine($"Conflict.A.Managed8\u4F60Func({number}) -> {number}");
return number;
}
Expand Down
2 changes: 2 additions & 0 deletions src/tasks/WasmAppBuilder/PInvokeCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,8 @@ public PInvokeCallback(MethodInfo method)
}
}


public ParameterInfo[] Parameters => Method.GetParameters();
public string? EntryPoint { get; }
public MethodInfo Method { get; }
public string? EntrySymbol { get; set; }
Expand Down
70 changes: 21 additions & 49 deletions src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,43 +304,19 @@ private static string EscapeLiteral(string input)
{
char c = input[i];

if (char.IsHighSurrogate(c) && i + 1 < input.Length && char.IsLowSurrogate(input[i + 1]))
sb.Append(c switch
{
int codepoint = char.ConvertToUtf32(c, input[i + 1]);
sb.AppendFormat("\\U{0:X8}", codepoint);
i++; // Skip the low surrogate
}
else
{
switch (c)
{
case '\\':
sb.Append("\\\\");
break;
case '\"':
sb.Append("\\\"");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
if (char.IsControl(c) || c > 127)
{
sb.AppendFormat("\\u{0:X4}", (int)c);
}
else
{
sb.Append(c);
}
break;
}
}
'\\' => "\\\\",
'\"' => "\\\"",
'\n' => "\\n",
'\r' => "\\r",
'\t' => "\\t",
_ when char.IsHighSurrogate(c) && i + 1 < input.Length && char.IsLowSurrogate(input[i + 1])
=> $"\\U{char.ConvertToUtf32(c, input[++i]):X8}",
_ when char.IsControl(c) || c > 127
=> $"\\u{(int)c:X4}",
_ => c.ToString()
});
}

return sb.ToString();
Expand All @@ -356,9 +332,7 @@ private void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> callbacks)
// of the delegate invoke in the [MonoPInvokeCallback]
// or [UnamanagedCallersOnly] attribute.
// Only blittable parameter/return types are supposed.
int cb_index = 0;

// Arguments to interp entry functions in the runtime
w.Write($$"""
InterpFtnDesc wasm_native_to_interp_ftndescs[{{callbacks.Count}}] = {};
Expand All @@ -367,6 +341,7 @@ private void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> callbacks)

var callbackNames = new HashSet<string>();
var keys = new HashSet<string>();
int cb_index = 0;
foreach (var cb in callbacks)
{
cb.EntrySymbol = CEntryPoint(cb);
Expand All @@ -375,38 +350,35 @@ private void EmitNativeToInterp(StreamWriter w, List<PInvokeCallback> callbacks)
Error($"Two callbacks with the same symbol '{cb.EntrySymbol}' are not supported.");
}
callbackNames.Add(cb.EntrySymbol);
var key = cb.Key;
if (keys.Contains(key))
if (keys.Contains(cb.Key))
{
Error($"Two callbacks with the same key '{key}' are not supported.");

Error($"Two callbacks with the same Name and number of arguments '{cb.Key}' are not supported.");
}
keys.Add(key);
keys.Add(cb.Key);

// The signature of the interp entry function
// This is a gsharedvt_in signature
var parameters = cb.Method.GetParameters();
var numParams = parameters.Length;
var unmanagedRange = Enumerable.Range(0, numParams);
var interpEntryArgs = new List<string>();
if (!cb.IsVoid)
{
interpEntryArgs.Add("(int*)&result");
}
interpEntryArgs.AddRange(unmanagedRange.Select(i => $"(int*)&arg{i}"));
interpEntryArgs.AddRange(cb.Parameters.Select((_, i) => $"(int*)&arg{i}"));
interpEntryArgs.Add($"wasm_native_to_interp_ftndescs [{cb_index}].arg");

w.Write(
$$"""
{{(cb.IsExport ? $"__attribute__((export_name(\"{EscapeLiteral(cb.EntryPoint!)}\")))" : "// no export name defined")}}
{{MapType(cb.ReturnType)}}
{{cb.EntrySymbol}} ({{string.Join(", ", unmanagedRange.Select(i => $"{MapType(parameters[i].ParameterType)} arg{i}"))}}) {
{{cb.EntrySymbol}} ({{string.Join(", ", cb.Parameters.Select((info, i) => $"{MapType(info.ParameterType)} arg{i}"))}}) {
typedef void (*InterpEntry_T{{cb_index}}) ({{string.Join(", ", interpEntryArgs.Select(_ => "int*"))}});
{{(!cb.IsVoid ? $"{MapType(cb.ReturnType)} result;" : "// void result")}}
if (!(InterpEntry_T{{cb_index}})wasm_native_to_interp_ftndescs [{{cb_index}}].func) {
{{(cb.IsExport ? "initialize_runtime(); " : "")}}// ensure the ftndescs and runtime are initialized when required
mono_wasm_marshal_get_managed_wrapper ("{{cb.AssemblyName}}", "{{cb.Namespace}}", "{{cb.TypeName}}", "{{cb.MethodName}}", {{numParams}});
{{(cb.IsExport && _isLibraryMode ? "initialize_runtime(); " : "")}}// ensure the ftndescs and runtime are initialized when required
mono_wasm_marshal_get_managed_wrapper ("{{cb.AssemblyName}}", "{{cb.Namespace}}", "{{cb.TypeName}}", "{{cb.MethodName}}", {{cb.Parameters.Length}});
}
((InterpEntry_T{{cb_index}})wasm_native_to_interp_ftndescs [{{cb_index}}].func) ({{string.Join(", ", interpEntryArgs)}});
Expand Down

0 comments on commit 85ebd63

Please sign in to comment.