Skip to content

[NativeAOT] support calling UnmanagedCallersOnly functions before managed main() #77957

@AustinWise

Description

@AustinWise

Problem statement

Some existing applications use the CoreCLR hosting APIs to call managed functions before calling the main method of an assembly. A specific example is xamarin-macios. It uses coreclr_create_delegate and reverse P/Invoke to call some functions before using coreclr_execute_assembly to execute an assembly's main function.

While trying to replicate the CoreCLR hosting API does not make sense for NativeAOT, the ability to call managed functions before main() would be useful.

Implementation Ideas

Currently ILC will generate one of two entry points: __managed__Main for executables and __managed__Startup for libraries. If both were generated, a hosting application could call functions in the following order:

  1. Initialize the NativeAOT runtime using __managed__Startup
  2. Call UnmanagedCallersOnly functions
  3. Manuplicate argc and argv if desired.
  4. Call __managed__Main to run the application.

When generating both entry points, __managed__Main should not run library or module initializers.

Ass a proof of concept, see this example adding support to ILC in this commit and then using those entry points with a custom bootstrapper to emulate enough of the CoreCLR hosting API to make xamarin-macios work.

Alternatives Considered

Conceivably hosts like xamarin-macios could use module constructors to run code before the main method, as NativeAOT eagerly runs these at startup. The only missing feature when using this approach is the ability to manipulate command line arguments before the main method starts.

Open Questions

  • Should this capability only work when statically-linking the NativeAOT runtime? Should it also work when compiling the runtime and user EXE as shared library?
  • What should the command line arguments for ILC look like
  • How should the bootstrapper change to support these entry points.
  • How should this feature be exposed in MSBuild to users

Related issues

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions