0x01 AOT技术亮点
最新的.NET 7 微软给我们带来了 Native AOT 发布模式。是的你没看错,通过该技术我们的 .NET 程序会直接编译为 Native 代码而不再是 IL ,程序运行的时候直接就是机器码,不再需要 JIT 编译。通过 AOT 技术,我们的程序启动会变的非常快并且使用更少的内存,并且运行的时候不需要在机器上安装任何运行时。这项技术有两个亮点,第一:生成的本机代码和传统的二进制文件一样不需要.NET运行时支持即可运行,以后用.net 7写的工具可以运行在很多老旧的windows系统版本上,第二:dnspy等反编译工具无法逆向这样的exe.
0x02 AOT实现
.NET 7 Native AOT技术编译一个控制台程序,关键需要在发布时配置csproj文件<PropertyGroup>标签内增加
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!--aot发布-->
<PublishAot>true</PublishAot>
</PropertyGroup>
</Project>
发布生成的ConsoleApp1.exe文件不能被dnspy反编译
0x03 AOT一些限制
.NET 7 AOT 发布的程序会有一些限制,我们编写的时候需要注意
No dynamic loading (for example, Assembly.LoadFile)
No runtime code generation (for example, System.Reflection.Emit)
No C++/CLI
No built-in COM (only applies to Windows)
Requires trimming, which has limitations
Implies compilation into a single file, which has known incompatibilities
Apps include required runtime libraries (just like self-contained apps, increasing their size, as compared to framework-dependent apps)