Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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) {
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];
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
85 changes: 85 additions & 0 deletions src/mono/wasm/Wasm.Build.Tests/Templates/WasmTemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -627,5 +627,90 @@ void AssertFile(string suffix)
Assert.True(copyOutputSymbolsToPublishDirectory == File.Exists(Path.Combine(publishFrameworkPath, fileName)), $"The {fileName} file {(copyOutputSymbolsToPublishDirectory ? "should" : "shouldn't")} exist in publish folder");
}
}

[Theory]
[InlineData("Debug")]
[InlineData("Release")]
public async Task UCOWithSpecialCharacters(string config)
{
string code =
"""
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 =
"""
#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);
}
""";
string id = $"browser_{config}_{GetRandomId()}";
string projectFile = CreateWasmTemplateProject(id, "wasmbrowser");
string projectName = Path.GetFileNameWithoutExtension(projectFile);
File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), code);
File.WriteAllText(Path.Combine(_projectDir!, "local.c"), cCode);

UpdateBrowserMainJs(DefaultTargetFramework);

var buildArgs = new BuildArgs(projectName, config, false, id, null);
string extraProperties = @"<AllowUnsafeBlocks>true</AllowUnsafeBlocks>";

buildArgs = ExpandBuildArgs(buildArgs, extraProperties: extraProperties,
extraItems: @$"<NativeFileReference Include=""local.c"" />");

bool expectRelinking = config == "Release";
BuildTemplateProject(buildArgs,
id: id,
new BuildProjectOptions(
DotnetWasmFromRuntimePack: !expectRelinking,
CreateProject: false,
HasV8Script: false,
MainJS: "main.js",
Publish: true,
TargetFramework: BuildTestBase.DefaultTargetFramework,
UseCache: false));

using var runCommand = new RunCommand(s_buildEnv, _testOutput)
.WithWorkingDirectory(_projectDir!);

await using var runner = new BrowserRunner(_testOutput);
var page = await runner.RunAsync(runCommand, $"run --no-silent -c {config} --no-build -r browser-wasm --forward-console");
await runner.WaitForExitMessageAsync(TimeSpan.FromMinutes(2));
Assert.Contains("ManagedFunc returned 42", string.Join(Environment.NewLine, runner.OutputLines));
}
}
}
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