dotnet / runtimelab

This repo is for experimentation and exploring new ideas that may or may not make it into the main dotnet/runtime repo.
MIT License
1.4k stars 196 forks source link

[NativeAOT LLVM] Call wasm export #2430

Closed maraf closed 9 months ago

maraf commented 9 months ago

I'm having troubles calling wasm export

[UnmanagedCallersOnly(EntryPoint = "BrowserConsoleApp/MyClass!GetAnswer2")]
internal static int GetAnswer2() => 42;

At first, the wasm export isn't generated until csproj contains

<ItemGroup>
  <CustomLinkerArg Include="-Wl,--export,BrowserConsoleApp/MyClass!GetAnswer2" />
</ItemGroup>

Is it expected? According to https://github.com/dotnet/runtimelab/pull/2232 it should happen automatically, am I right?

But more importantly, if I try to run the export Module["_BrowserConsoleApp/MyClass!GetAnswer2"](); it fails with

slist.inl:245  Uncaught RuntimeError: memory access out of bounds
    at SList<Thread, DefaultSListTraits<Thread, DoNothingFailFastPolicy>>::Iterator::Insert(Thread*) (slist.inl:245)
    at SList<Thread, DefaultSListTraits<Thread, DoNothingFailFastPolicy>>::PushHead(Thread*) (slist.inl:85)
    at ThreadStore::AttachCurrentThread(bool) (threadstore.cpp:144)
    at ThreadStore::AttachCurrentThread() (threadstore.cpp:150)
    at Thread::ReversePInvokeAttachOrTrapThread(ReversePInvokeFrame*) (thread.cpp:1185)
    at ::RhpReversePInvokeAttachOrTrapThread2(ReversePInvokeFrame *) (thread.cpp:1318)
    at ::RhpReversePInvoke(ReversePInvokeFrame *) (thread.cpp:1332)
    at BrowserConsoleApp_MyClass__GetAnswer2 (Program.cs:33)
    at Object._BrowserConsoleApp/MyClass!GetAnswer2 (dotnet.native.js:924:22)
    at main.js:24:64

Am I doing something wrong? Am I missing someting?

maraf commented 9 months ago

Hmm, I can't repro it on a separate project. Closing for now

maraf commented 9 months ago

It happends if called before main, which makes sense. My bad

yowl commented 9 months ago

Does sound a little odd, for a NativeLib is should initialize the runtime on the first call. Do you have /p:NativeLib=Shared in the dotnet publish ?

maraf commented 9 months ago

@yowl Thank you! I missed that one. Anyway that implies producing a library. Is there a way to produce exe but be able to call exports before calling main?

EDIT: Should <IlcArg Include="--splitinit" /> be enough? No https://github.com/dotnet/runtimelab/blob/feature/NativeAOT-LLVM/src/coreclr/nativeaot/Bootstrap/main.cpp#L234 EDIT2: I think I would like the behavior as for CustomNativeMain=true, but without writing custom native main