Code Monkey home page Code Monkey logo

zerosharp's Introduction

C# for systems programming

These samples show how to compile C# to native code using the .NET Native AOT technology (NativeAOT, also known as CoreRT previously).

The samples are for people who would like to use C#, but don't want to be bound by the choices of the base class libraries that normally come with C# (in the form that it's bundled in .NET). If you just want to native compile your .NET apps, go to the NativeAOT repo/branch instead. Nothing to see for you in this repo.

no-runtime is a rather pointless sample that demonstrates how to write code in C# that is directly runnable without a runtime. C# has value types and you can p/invoke into an unmanaged memory allocator, so you can do things with this, but you're so severily limited it's rather pointless. But Hello world ends up being about 8 kB native EXE with no dependencies, so that's rather cool.

with-runtime is something that can be actually useful. This includes the full managed and unmanaged runtime - GC, exception handling, and interface dispatch all work. Test.CoreLib used as the class library here is the same Test.CoreLib that you can find in the NativeAOT repo. Don't look for things like Object.ToString() because being compatible with .NET is not the point. This sample comes down to about 400 kB, most of which is the C runtime library.

efi-no-runtime is an EFI boot application that lets you run C# on bare metal, without an OS. Similar restrictions to the no-runtime sample apply. Making a version of this sample with a runtime would require some porting work on the runtime side.

Building the samples

.NET 7 SDK is a prerequisite for building these on all platforms.

In addition to the .NET 7 SDK, these are needed:

  • On Windows: Visual Studio 2022 with C++ development support and a Windows SDK
  • On Linux: clang
  • On macOS (untested): XCode

One you made sure you have the prerequisites, enter the appropriate sample directory and type:

$ dotnet publish -c Release

Some samples also come with a shell script (*.cmd) that pieces together all the tools and avoid MSBuild or dotnet. You need to make sure you have environment set up before running the script. Look at the script for details. The script is redundant with the *.csproj project files.

zerosharp's People

Contributors

333fred avatar kant2002 avatar michalstrehovsky avatar whiteblackgoose avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zerosharp's Issues

WebAssembly Support

Is there Support for WebAssembly planned? It would be a huge benefit to be able to compile C# programs without the runtime and GC overhead into wasm-files invocable by other applications or in the browser.

[question] cannot compile with-runtime

E:\GitHub\zerosharp\with-runtime>build.cmd

E:\GitHub\zerosharp\with-runtime>csc /debug /noconfig /nostdlib /runtimemetadata
version:v4.0.30319 zerosharp.cs /out:zerosharp.ilexe /langversion:latest /unsafe
 /r:Test.CoreLib.dll
Microsoft(R) Visual C# 编译器 版本 3.5.0-beta4-20153-05 (20b9af91)
版权所有(C) Microsoft Corporation。保留所有权利。

zerosharp.cs(46,13): warning CS0162: 检测到无法访问的代码

E:\GitHub\zerosharp\with-runtime>"C:\Users\Administrator\.nuget\packages\runtime
.win-x64.microsoft.dotnet.ilcompiler\1.0.0-alpha-27824-01\tools\ilc" zerosharp.i
lexe -r:Test.CoreLib.dll -o zerosharp.obj --systemmodule Test.CoreLib --map zero
sharp.map -O --noscan -g

E:\GitHub\zerosharp\with-runtime>link zerosharp.obj "C:\Users\Administrator\.nug
et\packages\runtime.win-x64.microsoft.dotnet.ilcompiler\1.0.0-alpha-27824-01\sdk
\bootstrapper.lib" "C:\Users\Administrator\.nuget\packages\runtime.win-x64.micro
soft.dotnet.ilcompiler\1.0.0-alpha-27824-01\sdk\Runtime.lib" kernel32.lib ole32.
lib advapi32.lib /incremental:no /debug /opt:ref
Microsoft (R) Incremental Linker Version 14.25.28612.0
Copyright (C) Microsoft Corporation.  All rights reserved.

libcpmt.lib(nothrow.obj) : fatal error LNK1112: 模块计算机类型“x86”与目标计算
机类型“x64”冲突

E:\GitHub\zerosharp\with-runtime>

(efinoruntime) Unresolved external symbol String___ctor

Hello, I'm trying to build the efinoruntime sample and I have this error:

.\build.cmd

C:\Users\valentin.charbonnier\Documents\Clone\NativeAOT\efi-no-runtime>csc /nologo /debug:embedded /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 zerosharp.cs /out:zerosharp.ilexe /langversion:latest /unsafe

C:\Users\valentin.charbonnier\Documents\Clone\NativeAOT\efi-no-runtime>"C:\Users\valentin.charbonnier\.nuget\packages\runtime.win-x64.microsoft.dotnet.ilcompiler\6.0.0-preview.7.21327.1"\tools\ilc zerosharp.ilexe -o                                                                                                                                                                                                                   zerosharp.obj --systemmodule zerosharp --map zerosharp.map -O

C:\Users\valentin.charbonnier\Documents\Clone\NativeAOT\efi-no-runtime>link /nologo /subsystem:EFI_APPLICATION zerosharp.obj /entry:EfiMain /incremental:no /out:BOOTX64.EFI
zerosharp.obj : error LNK2001: unresolved external symbol String___ctor
BOOTX64.EFI : fatal error LNK1120: 1 unresolved externals

Compiling a C# kernel to bare metal and booting in QEMU

Hello @MichalStrehovsky,

Ideally, I would have opened a discussion for this, as good etiquette...

Anyway, just to say I've managed to take the no-runtime example from this repo, successfully use it to compile a very basic C# kernel to x86 machine code, and then boot it in QEMU. It's a 13kb and really quite remarkable, particularly since I've only ever known .Net as a managed runtime.

The repo for my kernel is here: PatienceOS (nb. ignore the 'OS' moniker, high ambitions I guess) and an accompanying blog post with more details here: Compiling a C# kernel to bare metal and booting in QEMU.

Thank you for your amazing work with zerosharp and bflat.

Regards,
Frank

Issues with Linking NativeAOT (ILC) Compiled Object File for EFI Application on macOS (.NET8 RC1)

Hello,

I am encountering issues while trying to build and link a NativeAOT compiled object file for an EFI application on macOS. Below are the details of the problem and the steps I have taken so far:

Problem Description:
I am working on a project where I need to compile C# code using ILC and link the resulting object file to create an EFI application. The development environment is macOS M1, and I am targeting the x86_64 architecture on .NET8 RC1.

Steps Taken:
Compilation with ILC:
I used the following command to compile the C# code using .NET Native:

csc /nologo /debug:embedded /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 <source_files> /out:EFINet8Test /langversion:latest /unsafe
ilc EFINet8Test -o EFINet8Test.obj --systemmodule EFINet8Test--map EFINet8Test.map -O

Project-Level Compilation with dotnet build:
I also tried defining the csc arguments at the project level in the .csproj file properties and then built the project using dotnet build to ensure that the correct C# version and .NET 8 SDK were being used. However, this did not resolve the issue.

Linking with Clang:
I attempted to link the compiled object file using clang with the following command:
clang -o BOOTX64.EFI -target x86_64-unknown-windows -ffreestanding -nostdlib -e EfiMain EFINet8Test.obj -fuse-ld=/usr/local/opt/llvm/bin/lld-link

However, this resulted in an "unknown file type" error, indicating that lld-link does not recognise the format of the .obj file produced by ILC.

Exploration of Alternatives:

  • I explored using different linkers such as lld-link and ld from MinGW-w64, but none recognised the ILC-produced .obj file format.
  • I considered converting the object file format using objcopy, but this approach has its complexities.
  • I also attempted to pass custom clang arguments through the .csproj file using the IlcArg property, but the issue persisted.

Questions:

  • Is there a known solution or workaround for linking ILC-compiled object files for EFI applications on macOS?
  • Are there alternative linkers or tools that can recognise and link the .obj file produced by NativeAOT on macOS?
  • Is it possible to provide custom clang arguments or specify a custom linker through MSBuild or .csproj settings to address this issue?

Any guidance, suggestions, or insights into this problem would be greatly appreciated. Thank you in advance for your help!

no-runtime is not working

When dotnet publish -c Release -r win-x64 following exception happens.

EXEC : error : One or more errors occurred. (Code generation failed for method '[noruntime]Program.printf(uint8*)') [D:\d\kant\GitHub\zerosharp\no-runtime\noruntime.csproj]
  System.AggregateException: One or more errors occurred. (Code generation failed for method '[noruntime]Program.printf(uint8*)')
   ---> ILCompiler.CodeGenerationFailedException: Code generation failed for method '[noruntime]Program.printf(uint8*)'
   ---> System.InvalidOperationException: Expected type 'Internal.Runtime.CompilerHelpers.InteropHelpers' not found in module 'noruntime'
     at Internal.IL.HelperExtensions.GetKnownType(ModuleDesc module, String namespace, String name)
     at Internal.IL.Stubs.PInvokeILEmitter.EmitPInvokeCall(PInvokeILCodeStreams ilCodeStreams)
     at Internal.IL.Stubs.PInvokeILEmitter.EmitIL()
     at Internal.IL.Stubs.PInvokeILEmitter.EmitIL(MethodDesc method, PInvokeILEmitterConfiguration pinvokeILEmitterConfiguration, InteropStateManager interopStateManager)
     at ILCompiler.Compilation.CombinedILProvider.GetMethodIL(MethodDesc method)
     at ILCompiler.Compilation.ILCache.CreateValueFromKey(MethodDesc key)
     at Internal.TypeSystem.LockFreeReaderHashtable`2.CreateValueAndEnsureValueIsInTable(TKey key)
     at ILCompiler.Compilation.GetMethodIL(MethodDesc method)
     at Internal.IL.ILImporter..ctor(ILScanner compilation, MethodDesc method, MethodIL methodIL)
     at ILCompiler.ILScanner.CompileSingleMethod(ScannedMethodNode methodCodeNodeNeedingCode)
     --- End of inner exception stack trace ---
     at ILCompiler.ILScanner.CompileSingleMethod(ScannedMethodNode methodCodeNodeNeedingCode)
     at System.Threading.Tasks.Parallel.<>c__DisplayClass33_0`2.<ForEachWorker>b__0(Int32 i)
     at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`1.<ForWorker>b__1(RangeWorker& currentWorker, Int32 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
  --- End of stack trace from previous location ---
     at System.Threading.Tasks.Parallel.<>c__DisplayClass19_0`1.<ForWorker>b__1(RangeWorker& currentWorker, Int32 timeout, Boolean& replicationDelegateYieldedBeforeCompletion)
     at System.Threading.Tasks.TaskReplicator.Replica.Execute()
     --- End of inner exception stack trace ---
     at System.Threading.Tasks.TaskReplicator.Run[TState](ReplicatableUserAction`1 action, ParallelOptions options, Boolean stopOnFirstFailure)
     at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
  --- End of stack trace from previous location ---
     at System.Threading.Tasks.Parallel.ThrowSingleCancellationExceptionOrOtherException(ICollection exceptions, CancellationToken cancelToken, Exception otherException)
     at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
     at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IList`1 list, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
     at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
     at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body)
     at ILCompiler.ILScanner.CompileMultiThreaded(List`1 methodsToCompile)
     at ILCompiler.ILScanner.ComputeDependencyNodeDependencies(List`1 obj)
     at ILCompiler.DependencyAnalysisFramework.DependencyAnalyzer`2.ComputeMarkedNodes()
     at ILCompiler.ILScanner.ILCompiler.IILScanner.Scan()
     at ILCompiler.Program.Run(String[] args)
     at ILCompiler.Program.Main(String[] args)
...nuget\packages\microsoft.dotnet.ilcompiler\7.0.0-alpha.1.22058.1\

Adding a reference to Microsoft.DotNet.ILCompiler 8.0 preview to no-runtime project results in no console output

I want to use the preview version of NativeAot in order to make use of the new UnmanagedEntryPointsAssembly MSBuild property, but this results in no console output when invoking WriteConsoleW.


Reproduction steps:

  • Add the following to the no-runtime project file:
<ItemGroup>
	<PackageReference Include="Microsoft.DotNet.ILCompiler; runtime.win-x64.microsoft.dotnet.ilcompiler" Version="8.0.0-preview.4.23207.2" />
</ItemGroup>
  • Run dotnet publish -r win-x64 -c Debug in a command prompt.
  • Run the resulting no-runtime.exe file from the publish directory.

Expected result:
Console should display Hello world!.


Observed result:
Console displays no text and no errors.

None of the samples work

I have no idea why!

  • runtime.win-x64.microsoft.dotnet.ilcompiler\6.0.0-preview.2.21107.2
  • Latest Visual Studio 2019 with latest SDK and C++
    Am I missing something obvious?
zerosharp.mp4

Exporting and importing libraries with /SUBSYSTEM:EFI_APPLICATION is not supported

Runtime.WorkstationGC.lib(thread.cpp.obj) : error LNK2005: RhpReversePInvoke is already defined in efinoruntime.obj [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
Runtime.WorkstationGC.lib(thread.cpp.obj) : error LNK2005: RhpReversePInvokeReturn is already defined in efinoruntime.obj [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
Runtime.WorkstationGC.lib(PInvoke.asm.obj) : error LNK2005: RhpPInvoke is already defined in efinoruntime.obj [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
Runtime.WorkstationGC.lib(PInvoke.asm.obj) : error LNK2005: RhpPInvokeReturn is already defined in efinoruntime.obj [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
Runtime.WorkstationGC.lib(EHHelpers.cpp.obj) : error LNK2005: RhpFallbackFailFast is already defined in efinoruntime.obj [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
LINK : fatal error LNK1294: Exporting and importing libraries with /SUBSYSTEM:EFI_APPLICATION is not supported [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]
C:\Users\nifan\.nuget\packages\microsoft.dotnet.ilcompiler\7.0.0-alpha.1.22068.1\build\Microsoft.NETCore.Native.targets(376,5): error MSB3073: Command "link @ "obj\Debug\net6.0\win-x64\native\link.rsp"" exited with code 1294. [C:\Users\nifan\Documents\GitHub\zerosharp\efi-no-runtime\efinoruntime.csproj]

Cannot find ILC

Thank you so much for this! So, I've followed the instructions and building isn't working (I'm trying efi-no-runtime). A few notes:

  1. The readme says that VS2019 is required, but the project doesn't build at all in 2019 (stating that the 6.0 SDK isn't supported). So, I installed the 2022 preview.

  2. A build in VS2022 works and successfully generates a binary. However, a dumpbin on the binary shows the subsystem as Windows CUI, so the extra "stuff" (i.e. in the CSPROJ) doesn't appear to be hooked up.

  3. Invoking "dotnet publish -r windows-x64 -c Release" also does not working, yielding: C:\Program Files\dotnet\sdk\6.0.100-rc.1.21463.6\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Sdk.FrameworkReferenceResolution.targets(90,5): error NETSDK1083: The specified RuntimeIdentifier 'windows-x64' is not recognized. [C:\Users\m\Downloads\zerosharp-master\zerosharp-master\efi-no-runtime\efinoruntime.csproj]

  4. The readme also claims that build.cmd is redundant w/ the CSPROJ file, but the file names are totally different (i.e. build.cmd refers to 'zerosharp' while the output name in the CSPROJ is 'efinoruntime')

  5. ILC isn't in the nuget package. Mine was cached at C:\Users[username].nuget\packages\microsoft.dotnet.ilcompiler\7.0.0-alpha.1.21504.4\ but the tools directory (nor any directory in there) has an ILC.exe that the build.cmd is looking for.

Given that I can successfully compile the code to a managed binary, I'm perfectly fine using a batch file rather than the CSPROJ file to link to native, so I think the issue really is finding where ILC.exe is located? Help is greatly appreciated!

Diagnosing EFI attempted imports

Getting exports and import libraries are not supported with /SUBSYSTEM:EFI_APPLICATION when attempting to invoke a method/prop on an interface. As with, say, allocation (new object()), it's almost certainly that there's some missing code (eg an export for RhpNewFast) I need to add, and the compiler is trying to pull it in from the runtime because it's not present, but unlike w/ allocation, I can't for the life of me figure out what I need to add.

Partly the question is what I might be missing, but equally, is there any good way of telling what the compiler is actually trying to pull in? Changing the verbosity on the dotnet publish doesn't seem to yield any useful information.

For context:

interface IFoo
{
  void Bar();
}

class Foo1 : IFoo
{
  public void Bar() { }
}

class Foo2: IFoo
{
  public void Bar() { }
}

static class Indirection
{
  private ulong _counter;

  public static IFoo GetFoo() => _counter++ % 2 is 0 ? new Foo1() : new Foo2()
}

I can compile:

IFoo foo = new Foo1();
foo.Bar();
IFoo baz = new Foo2();
baz.Bar();

Presumably as the interface is just being optimized away.

But

var foos = new IFoo[] { new Foo1(), new Foo2() };
for (var i = 0; i < foos.Length; ++i)
{
  foos[i].Foo();
}

or

var foo = Indirection.GetFoo();
foo.Foo();

Results in the compilation error.

I also get

Runtime.WorkstationGC.lib(thread.cpp.obj) : error LNK2005: RhpReversePInvoke already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
Runtime.WorkstationGC.lib(thread.cpp.obj) : error LNK2005: RhpReversePInvokeReturn already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
Runtime.WorkstationGC.lib(EHHelpers.cpp.obj) : error LNK2005: RhpFallbackFailFast already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
Runtime.WorkstationGC.lib(WriteBarriers.asm.obj) : error LNK2005: RhpCheckedAssignRef already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
Runtime.WorkstationGC.lib(WriteBarriers.asm.obj) : error LNK2005: RhpAssignRef already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
Runtime.WorkstationGC.lib(WriteBarriers.asm.obj) : error LNK2005: RhpByRefAssignRef already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]
LIBCMT.lib(gs_cookie.obj) : error LNK2005: __security_cookie already defined in Project.obj [F:\projects\Project\src\Project\Project.csproj]

Because those are all explicitly defined, but I'm working under the assumption those will go away if I add whatever it is it's trying to import.

Pretty sure it's down to the method invocation, as I can, for example, create an array of IFoos, Unsafe.As<IFoo, IntPtr>, and print out the pointers.

Cheers!

no-runtime fails to build/publish

I don't know what has changed in the .NET 7 SDK between now and the last commit here, but I had to make some modifications to the no-runtime example.

Now the example builds, publishes and runs, although there is still an error in the output when publishing.

$ dotnet publish -c Release
MSBuild version 17.4.3+7e646be43 for .NET
  Determining projects to restore...
  All projects are up-to-date for restore.
  noruntime -> /home/stijn/projects/zerosharp/no-runtime/bin/Release/net7.0/linux-x64/noruntime.dll
  Generating native code
  <unknown>:0: error: Cannot represent a difference across sections
  noruntime -> /home/stijn/projects/zerosharp/no-runtime/bin/Release/net7.0/linux-x64/publish/

$ bin/Release/net7.0/linux-x64/publish/noruntime 
Hello world!

Does the patch below make sense, are they expected changes?

@@ -1,5 +1,6 @@
 using System;
 using System.Runtime;
+using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
 #region A couple very basic things
@@ -63,6 +64,8 @@ namespace System
 
     namespace Runtime.CompilerServices
     {
+        public class CallConvCdecl { }
+
         public class RuntimeHelpers
         {
             public static unsafe int OffsetToStringData => sizeof(IntPtr) + sizeof(int);
@@ -75,6 +78,13 @@ namespace System.Runtime.InteropServices
     {
         public DllImportAttribute(string dllName) { }
     }
+
+    public sealed class UnmanagedCallersOnlyAttribute : Attribute
+    {
+        public UnmanagedCallersOnlyAttribute() { }
+        public Type[] CallConvs;
+        public string EntryPoint;
+    }
 }
 #endregion
 
@@ -83,6 +93,35 @@ namespace System
 {
     namespace Runtime
     {
+        internal static class __Finalizer
+        {
+            [UnmanagedCallersOnly(EntryPoint = "ProcessFinalizers", CallConvs = new Type[] { typeof(CallConvCdecl) })]
+            public static void ProcessFinalizers() { }
+        }
+
+        internal static unsafe class CachedInterfaceDispatch
+        {
+            [RuntimeExport("RhpCidResolve")]
+            private static unsafe void RhpCidResolve(IntPtr callerTransitionBlockParam, IntPtr pCell) { }
+        }
+
+        internal static unsafe class EH
+        {
+            public ref struct ExInfo { }
+
+            [RuntimeExport("RhThrowHwEx")]
+            public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo) { }
+            [RuntimeExport("RhThrowEx")]
+            public static void RhThrowEx(object exceptionObj, ref ExInfo exInfo) { }
+            [RuntimeExport("RhRethrow")]
+            public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo) { }
+
+            [UnmanagedCallersOnly(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallConvs = new Type[] { typeof(CallConvCdecl) })]
+            public static void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { }
+            [RuntimeExport("RhpFailFastForPInvokeExceptionCoop")]
+            public static void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord) { }
+        }
+
         internal sealed class RuntimeExportAttribute : Attribute
         {
             public RuntimeExportAttribute(string entry) { }
@@ -90,6 +129,8 @@ namespace System
     }
 
     class Array<T> : Array { }
+
+    public class Type { }
 }
 
 namespace Internal.Runtime.CompilerHelpers
@@ -102,17 +143,10 @@ namespace Internal.Runtime.CompilerHelpers
         // A couple symbols the generated code will need we park them in this class
         // for no particular reason. These aid in transitioning to/from managed code.
         // Since we don't have a GC, the transition is a no-op.
-        [RuntimeExport("RhpReversePInvoke")]
-        static void RhpReversePInvoke(IntPtr frame) { }
-        [RuntimeExport("RhpReversePInvokeReturn")]
-        static void RhpReversePInvokeReturn(IntPtr frame) { }
         [RuntimeExport("RhpPInvoke")]
         static void RhpPInvoke(IntPtr frame) { }
         [RuntimeExport("RhpPInvokeReturn")]
         static void RhpPInvokeReturn(IntPtr frame) { }
-
-        [RuntimeExport("RhpFallbackFailFast")]
-        static void RhpFallbackFailFast() { while (true) ; }
     }
 }
 #endregion

Dynamically linking against C library

In the readme, it is mentioned that most of the size of the with-runtime example comes from the C library. Is it possible to instruct NativeAOT to dynamically link against msvcrt on Windows instead of statically linking it?

Consider adding a uefi library example.

Consider adding a baremetal UEFI library example.

image

shadowblitz16@Node202-Debian:~/Documents/source/C#/NtSharp/Kernel$ dotnet publish
MSBuild version 17.4.0+18d5aef85 for .NET
  Determining projects to restore...
  Restored /home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj (in 52 ms).
  Restored /home/shadowblitz16/Documents/source/C#/NtSharp/Kernel/Kernel.csproj (in 64 ms).
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/.NETCoreApp,Version=v7.0.AssemblyAttributes.cs(4,46): error CS0616: 'TargetFrameworkAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(13,30): error CS0616: 'AssemblyCompanyAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(14,30): error CS0616: 'AssemblyConfigurationAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(15,30): error CS0616: 'AssemblyFileVersionAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(16,30): error CS0616: 'AssemblyInformationalVersionAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(17,30): error CS0616: 'AssemblyProductAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(18,30): error CS0616: 'AssemblyTitleAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/obj/Debug/net7.0/LibCore.AssemblyInfo.cs(19,30): error CS0616: 'AssemblyVersionAttribute' is not an attribute class [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs(7,10): warning CS0436: The type 'IntPtr' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'nint' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(14,32): warning CS0436: The type 'IntPtr' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'nint' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(16,38): warning CS0436: The type 'IntPtr' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'nint' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(18,25): warning CS0436: The type 'IntPtr' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'nint' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(20,31): warning CS0436: The type 'IntPtr' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'nint' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs(78,30): warning CS0436: The type 'ValueType' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'ValueType' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs(127,47): warning CS0436: The type 'Attribute' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'Attribute' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs(100,43): warning CS0436: The type 'Delegate' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'Delegate' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs(129,33): warning CS0436: The type 'AttributeTargets' in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs' conflicts with the imported type 'AttributeTargets' in 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Using the type defined in '/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Core.cs'. [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(13,3): error CS0246: The type or namespace name 'RuntimeExportAttribute' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(13,3): error CS0246: The type or namespace name 'RuntimeExport' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(15,3): error CS0246: The type or namespace name 'RuntimeExportAttribute' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(15,3): error CS0246: The type or namespace name 'RuntimeExport' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(17,3): error CS0246: The type or namespace name 'RuntimeExportAttribute' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(17,3): error CS0246: The type or namespace name 'RuntimeExport' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(19,3): error CS0246: The type or namespace name 'RuntimeExportAttribute' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(19,3): error CS0246: The type or namespace name 'RuntimeExport' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(22,3): error CS0246: The type or namespace name 'RuntimeExportAttribute' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]
/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs(22,3): error CS0246: The type or namespace name 'RuntimeExport' could not be found (are you missing a using directive or an assembly reference?) [/home/shadowblitz16/Documents/source/C#/NtSharp/LibCore/LibCore.csproj]

with-runtime no longer work

I try to play with that repository. EFI example most fun 😄 . Other examples is interesting as well.

I experience issue with with-runtime project which does not work. I believe to make it work it is required to update binaries, but better it is handled not by me.

CSC not on the PATH

Hello !
when i try to run build.cmd it displays CSC not on the PATH. Refer to README.md.
here's the cmd file

@set DROPPATH=C:\Users\nifan\.nuget\packages\runtime.win-x64.microsoft.dotnet.ilcompiler\6.0.0-preview.5.21222.2
@set ILCPATH=%DROPPATH%\tools
@if not exist %ILCPATH%\ilc.exe (
  echo The DROPPATH environment variable not set. Refer to README.md.
  exit /B
)
@where csc >nul 2>&1
@if ERRORLEVEL 1 (
  echo CSC not on the PATH. Refer to README.md.
  exit /B
)

@del zerosharp.ilexe >nul 2>&1
@del zerosharp.obj >nul 2>&1
@del zerosharp.exe >nul 2>&1
@del zerosharp.map >nul 2>&1
@del zerosharp.pdb >nul 2>&1

@if "%1" == "clean" exit /B

csc /debug:embedded /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 zerosharp.cs /out:zerosharp.ilexe /langversion:latest /unsafe
%ILCPATH%\ilc zerosharp.ilexe -o zerosharp.obj --systemmodule zerosharp --map zerosharp.map -O --directpinvoke:kernel32
link /subsystem:console zerosharp.obj /entry:__managed__Main kernel32.lib /incremental:no

crossgen2

I was pleasantly surprised to see zerosharp by chance.
I am an embedded microcontroller developer. Now there are many ARM MCU chips that contain large SDRAM, and some chips have MMU controller, which contain 64MB of SDRAM, which can run LINUX or VXWORKS (RTOS),
The significance of C# running on MCU:

  1. Real-time. Running CLR on RTOS is much better in real-time than under linux.
    1.1 In some IoT edge computing scenarios, hard real-time is not required, and a delay of 10-100ms is acceptable. such as smart gateways.
    1.2 There are often not many other insignificant tasks in RTOS. Once the program is programmed into the chip, the chip will only run the program. Instead of running a C# program like a desktop operating system, users may be watching movies and playing games (using CPU time).
    2.Crossgen2:
    Compile the MSIL code into PIC (position independent code) code as much as possible and burn it into the MCU. For the Load, Reflection, Dynamic Emit features, for most low-level applications, these features are rarely used. In this way, the program running efficiency is expected to reach 90% of the C language development.
  2. At present, the instruction set of most MCUs is ARMv7 Thumb2.CoreCLR supports this instruction set.
  3. I think CoreClr for MCU only needs to include: Thread and IPC (for example: semaphore queue mutex), Debug, GC, JIT, DLLImport, and others are all cut out. It is expected that the generated BIN file will be within 16MB ( User code+CoreCLR+System.Array, List..., INT8~INT64.. (only a little core library)). This is totally acceptable.

my question:

  1. The work of cutting CORECLR is not difficult, the code of CORECLR is not modular enough, and I don't know JIT, VM, GC, so I don't know how to cut. can you crop? How much time and how much does it take? Do you want to do this? If you want, I can fund you, that's great, and I'll help you with programming that isn't too hard (except writing the CORECLR virtual machine...). I really want to use C# to develop MCU (Corssgen2+JIT way, no interpreter).
  2. I know that there is a .Net Compact Framework. The code is well written and the modular program is very good. Can Microsoft open source this? Because CORECLR coupling is too serious.
  3. Is the machine code generated by Crossgen2 currently PIC (position independent code)?
    These are Google translated.

偶然间看到zerosharp我感到非常惊喜.
我是一位嵌入式微控制器开发者,现在有很多ARM MCU芯片内部包含很大的SDRAM,也有一些芯片带MMU控制器,内部包含64MB的SDRAM,可以跑LINUX,也可以跑VXWORKS(RTOS),
C#在MCU运行的意义:
1.实时性。在RTOS上跑CLR要比linux下实时性好很多。
1.1 在一些IOT边缘计算的场景下,不需要硬实时,10-100ms的延迟是可以接受的。比如智能网关。
1.2 在RTOS中往往没有太多其他无关紧要的任务,一旦程序烧录到芯片中,那么这个芯片只会跑这个程序。而不是像桌面操作系统那样,正在运行C#程序的同时,用户有可能在看电影,玩游戏(占用CPU时间)。
2.Crossgen2:
尽可能把MSIL代码编译成PIC(位置无关的代码)的代码,烧录到MCU中。对于Load、反射、动态Emit特性,对于大部分底层应用程序来说,这些特性很少用到。这样程序运行效率我预计可以达到C语言开发的90%
3.目前大部分MCU的指令集是ARMv7 Thumb2.CoreCLR支持这个指令集。
4.我觉得CoreClr for MCU只需要包括:Thread and IPC(比如:信号量 队列 互斥锁)、Debug、GC、JIT、DLLImport,其他的都裁减掉,预计生成的BIN文件会在16MB之内(用户代码+CoreCLR+System.Array、List...、INT8~INT64..(仅此一点点核心库))。 这是完全可以接受的。

我的问题:
1.裁剪CORECLR的工作难度大不大,CORECLR的代码不够模块化,并且我也不懂JIT、VM、GC,所以我不知道如何裁剪。你可以裁剪吗?需要多少时间和多少钱?你想不想做这件事?如果你想,我可以资助你,那非常好,我帮你做些不是很难的编程工作(除了写CORECLR虚拟机...)。我非常想使用C#开发MCU(Corssgen2+JIT的方式,不用解释器)。
2.我知道有个.Net Compact Framework,这个代码写的很规范,模块化程序很好,这个微软可以开源吗?因为CORECLR耦合太严重了。
3.目前Crossgen2生成的机器码是PIC(位置无关的代码)吗?
这些是Google翻译的。

Confused on how this works.

How exactly does this work?
Are these just magic definitions the C# compiler looks for?...

    // The layout of primitive types is special cased because it would be recursive.
    // These really don't need any fields to work.
    public struct Boolean { }
    public struct Char { }
    public struct SByte { }
    public struct Byte { }
    public struct Int16 { }
    public struct UInt16 { }
    public struct Int32 { }
    public struct UInt32 { }
    public struct Int64 { }
    public struct UInt64 { }
    public struct IntPtr { }
    public struct UIntPtr { }
    public struct Single { }
    public struct Double { }

If so you should probably document them,
If not is there a way to rename the basic types?

String marshalling with noruntime

As I was delving myself with building a simple driver with the combination of samples of noruntime and noruntime-efi, I was a bit stranded with having to marshal C# string to for case of to a c string (LPCSTR).
Would it even be possible to marshal without a runtime? If it is, any suggestion or an idea of how to approach this issue?

Linking my project here for a more visual reference: https://github.com/ZeroLP/ZeroKernel (Hopefully I'm not violating any OSP license since I can't really find it in the official repo if there is one)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.