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

[mono][wasm] Fix function signature mismatch in m2n invoke #101106

Merged
merged 20 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
36 changes: 29 additions & 7 deletions src/mono/browser/runtime/runtime.c
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,32 @@ init_icall_table (void)
#endif
}

static void fixupSymbol(char *key, char *fixedName) {
mkhamoyan marked this conversation as resolved.
Show resolved Hide resolved
int sb_index = 0;
int len = strlen (key);

for (int i = 0; i < len; ++i) {
unsigned char b = key[i];
if ((b >= '0' && b <= '9') ||
(b >= 'a' && b <= 'z') ||
(b >= 'A' && b <= 'Z') ||
(b == '_')) {
fixedName[sb_index++] = b;
}
else if (b == '.' || b == '-' || b == '+' || b == '<' || b == '>') {
fixedName[sb_index++] = '_';
}
else {
// Append the hexadecimal representation of b between underscores
sprintf(&fixedName[sb_index], "_%X_", b);
sb_index += 4; // Move the index after the appended hexadecimal characters
}
}

// Null-terminate the fixedName string
fixedName[sb_index] = '\0';
}

/*
* get_native_to_interp:
*
Expand All @@ -209,17 +235,13 @@ get_native_to_interp (MonoMethod *method, void *extra_arg)
const char *class_name = mono_class_get_name (klass);
const char *method_name = mono_method_get_name (method);
char key [128];
char fixedName[256];
mkhamoyan marked this conversation as resolved.
Show resolved Hide resolved
int len;

assert (strlen (name) < 100);
snprintf (key, sizeof(key), "%s_%s_%s", name, class_name, method_name);
len = strlen (key);
for (int i = 0; i < len; ++i) {
if (key [i] == '.')
key [i] = '_';
}

addr = wasm_dl_get_native_to_interp (key, extra_arg);
fixupSymbol(key, fixedName);
addr = wasm_dl_get_native_to_interp (fixedName, extra_arg);
MONO_EXIT_GC_UNSAFE;
return addr;
}
Expand Down
75 changes: 75 additions & 0 deletions src/mono/wasm/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -884,5 +884,80 @@ public void EnsureWasmAbiRulesAreFollowedInAOT(BuildArgs buildArgs, RunHost host
[BuildAndRun(host: RunHost.Chrome, aot: false)]
public void EnsureWasmAbiRulesAreFollowedInInterpreter(BuildArgs buildArgs, RunHost host, string id) =>
EnsureWasmAbiRulesAreFollowed(buildArgs, host, id);

[Theory]
[BuildAndRun(host: RunHost.Chrome, aot: true)]
ilonatommy marked this conversation as resolved.
Show resolved Hide resolved
public void UCOWithSpecialCharacters(BuildArgs buildArgs, RunHost host, string id)
{
string code =
mkhamoyan marked this conversation as resolved.
Show resolved Hide resolved
"""
using System;
using System.Runtime.InteropServices;
public unsafe partial class Test
{

public unsafe static int Main(string[] args)
{
((IntPtr)(delegate* unmanaged<int,int>)&Interop.ManagedFunc).ToString();

Console.WriteLine($"main: {args.Length}");
Interop.UnmanagedFunc();
return 0;
}
}

file partial class Interop
{
[UnmanagedCallersOnly(EntryPoint = "ManagedFunc")]
public static int ManagedFunc(int number)
{
// called from MyImport aka UnmanagedFunc
Console.WriteLine($"MyExport({number}) -> 42");
return 42;
}

[DllImport("local", EntryPoint = "UnmanagedFunc")]
public static extern void UnmanagedFunc(); // calls ManagedFunc aka MyExport
}
""";
string cCode =
mkhamoyan marked this conversation as resolved.
Show resolved Hide resolved
"""
#include <stdio.h>

int ManagedFunc(int number);

void UnmanagedFunc()
{
int ret = 0;
printf("UnmanagedFunc calling ManagedFunc\n");
ret = ManagedFunc(123);
printf("ManagedFunc returned %d\n", ret);
}
""";

var extraProperties = "<AllowUnsafeBlocks>true</AllowUnsafeBlocks>";
var extraItems = @"<NativeFileReference Include=""local.c"" />";

buildArgs = ExpandBuildArgs(buildArgs,
extraItems: extraItems,
extraProperties: extraProperties);

(string libraryDir, string output) = BuildProject(buildArgs,
id: id,
new BuildProjectOptions(
InitProject: () =>
{
File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), code);
File.WriteAllText(Path.Combine(_projectDir!, "local.c"), cCode);
},
Publish: buildArgs.AOT,
// Verbosity: "diagnostic",
DotnetWasmFromRuntimePack: false));

string objDir = Path.Combine(_projectDir!, "obj", buildArgs.Config!, "net9.0", "browser-wasm", "wasm", buildArgs.AOT ? "for-publish" : "for-build");

var runOutput = RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 42, host: host, id: id);
Assert.Contains("ManagedFunc returned 42", runOutput);
}
}
}
2 changes: 1 addition & 1 deletion src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ private string DelegateKey(PInvokeCallback export)
// it needs to match the key generated in get_native_to_interp
var method = export.Method;
string module_symbol = method.DeclaringType!.Module!.Assembly!.GetName()!.Name!;
return $"\"{module_symbol}_{method.DeclaringType.Name}_{method.Name}\"".Replace('.', '_');
return $"\"{_fixupSymbolName($"{module_symbol}_{method.DeclaringType.Name}_{method.Name}")}\"";
}

#pragma warning disable SYSLIB1045 // framework doesn't support GeneratedRegexAttribute
Expand Down
Loading