一:背景
1. 讲故事
前些天在看 aot的时候关注了下 源生成器
,挺有意思的一个东西,今天写一篇文章简单的分享下。
二:源生成器探究之旅
1. 源生成器是什么
简单来说,源生成器是roslyn编译器
给程序员开的一道口子,在这个口子里可以塞入一些自定义的cs代码,让roslyn编译器
在编译代码的时候顺带给一起处理了,简单的说就是 夹带私货 ,但古话又说 师不顺路, 医不叩门
,所以还是比较尴尬的,看一下官方给的图,图中的橙色区域就是夹带的私货。
有些朋友肯定好奇,这玩意有什么用?其实在aot领域中,jsonserializer 就使用了 sourcegeneration
来给序列化的类型(weatherforecast)生成元数据,参考代码如下:
[jsonsourcegenerationoptions(writeindented = true)] [jsonserializable(typeof(weatherforecast))] internal partial class sourcegenerationcontext : jsonserializercontext { }
2. 一个简单的例子
上面的例子不过多深入,先看看怎么实现0到1的问题,这里使用官方例子,用钩子来实现 分布方法
的方法体。
新建 sourcegenerator 类库项目
这里面的source就是钩子代码,不过目前只能是.net standard 2.0
项目,应该是要达到最大的兼容性,参考代码如下:
namespace sourcegenerator { [generator] public class hellosourcegenerator : isourcegenerator { public void execute(generatorexecutioncontext context) { // find the main method var mainmethod = context.compilation.getentrypoint(context.cancellationtoken); // build up the source code string source = $@" // <auto-generated/> using system; namespace {mainmethod.containingnamespace.todisplaystring()} {{ public static partial class {mainmethod.containingtype.name} {{ static partial void hellofrom(string name) => console.writeline($""generator says: hi from '{{name}}'""); }} }} "; var typename = mainmethod.containingtype.name; // add the source code to the compilation context.addsource($"{typename}.g.cs", source); } public void initialize(generatorinitializationcontext context) { // no initialization required for this one } } }
新建 example_21_15 项目
这是一个控制台程序,引用刚才的项目,并声明部分方法 hellofrom
,参考代码如下:
namespace example_21_15 { partial class program { static void main(string[] args) { hellofrom("generated code"); console.readline(); } static partial void hellofrom(string name); } }
要记住在 example_21_15.csproj 中 include 时要额外增加两个参数,参考如下:
<itemgroup> <projectreference include="..\sourcegenerator\sourcegenerator.csproj" outputitemtype="analyzer" referenceoutputassembly="false" /> </itemgroup>
配置好之后就可以把程序跑起来了,可以看到方法体确实是钩子中的代码。
三:roslyn如何夹带私货
1. windbg调试
究竟是如何夹带私货,本质上是 roslyn 内部的逻辑,现在的问题是如何给他挖出来了呢?这就需要使用强大的 windbg,采用exe启动劫持的方式洞察,流程步骤如下:
windbg 的exe劫持
资深的 windbg 玩家我相信都知道这个招数,我写了一个简单的 bat 脚本,对 dotnet.exe 进行启动拦截,要提醒的是有安全软件的话可以先卸载掉,以免出现无权限的问题。
set applicationname=dotnet.exe set windbgpath=c:\program files (x86)\windows kits\10\debuggers\x64\windbg.exe reg add "hkey_local_machine\software\microsoft\windows nt\currentversion\image file execution options\%applicationname%" /v debugger /t reg_sz /d "%windbgpath%" /f echo 已成功设置 pause
修改狗子代码
最简单粗暴的方式就是加 debugger.break
,好让他在 windbg 中自动中断。
public class hellosourcegenerator : isourcegenerator { public void execute(generatorexecutioncontext context) { debugger.break(); //... } }
使用 dotnet publish 发布程序
所有的埋伏做好之后,最后就是用 dotnet publish 来引诱 roslyn 出洞,参考命令如下 dotnet publish -r win-x64 -c debug -o d:\testdump
, 命令执行之后果然给拦截到了,截图如下:
由于调用栈难得,再弄一份文字版。
0:029> !clrstack os thread id: 0x443c (29) child sp ip call site 00000068e603dd18 00007ffe0135d962 [helpermethodframe: 00000068e603dd18] system.diagnostics.debugger.breakinternal() 00000068e603de20 00007ffd6dd357da system.diagnostics.debugger.break() [/_/src/coreclr/system.private.corelib/src/system/diagnostics/debugger.cs @ 18] 00000068e603de50 00007ffd13920522 sourcegenerator.hellosourcegenerator.execute(microsoft.codeanalysis.generatorexecutioncontext) 00000068e603df10 00007ffd6a4ad4ac microsoft.codeanalysis.sourcegeneratoradaptor.b__5_5(microsoft.codeanalysis.sourceproductioncontext, generatorcontextbuilder) [/_/src/compilers/core/portable/sourcegeneration/generatoradaptor.cs @ 55] 00000068e603e020 00007ffd6a5bfdd8 microsoft.codeanalysis.userfunctionextensions+c__displayclass3_0`2[[microsoft.codeanalysis.sourceproductioncontext, microsoft.codeanalysis],[system.__canon, system.private.corelib]].b__0(microsoft.codeanalysis.sourceproductioncontext, system.__canon, system.threading.cancellationtoken) [/_/src/compilers/core/portable/sourcegeneration/userfunction.cs @ 101] 00000068e603e070 00007ffd6a624e9c microsoft.codeanalysis.sourceoutputnode`1[[system.__canon, system.private.corelib]].updatestatetable(builder, microsoft.codeanalysis.nodestatetable`1,system.collections.generic.ienumerable`1>>, system.threading.cancellationtoken) [/_/src/compilers/core/portable/sourcegeneration/nodes/sourceoutputnode.cs @ 70] 00000068e603e2b0 00007ffd13fd1ed8 microsoft.codeanalysis.driverstatetable+builder.getlateststatetablefornode[[system.valuetuple`2[[system.__canon, system.private.corelib],[system.__canon, system.private.corelib]], system.private.corelib]](microsoft.codeanalysis.iincrementalgeneratornode`1>) [/_/src/compilers/core/portable/sourcegeneration/nodes/driverstatetable.cs @ 60] 00000068e603e320 00007ffd6a625349 microsoft.codeanalysis.sourceoutputnode`1[[system.__canon, system.private.corelib]].appendoutputs(microsoft.codeanalysis.incrementalexecutioncontext, system.threading.cancellationtoken) [/_/src/compilers/core/portable/sourcegeneration/nodes/sourceoutputnode.cs @ 102] 00000068e603e460 00007ffd6a4b0837 microsoft.codeanalysis.generatordriver.updateoutputs(system.collections.immutable.immutablearray`1, microsoft.codeanalysis.incrementalgeneratoroutputkind, builder, system.threading.cancellationtoken, builder) [/_/src/compilers/core/portable/sourcegeneration/generatordriver.cs @ 340] 00000068e603e520 00007ffd6a4afc9b microsoft.codeanalysis.generatordriver.rungeneratorscore(microsoft.codeanalysis.compilation, microsoft.codeanalysis.diagnosticbag, system.threading.cancellationtoken) [/_/src/compilers/core/portable/sourcegeneration/generatordriver.cs @ 303] 00000068e603ecb0 00007ffd6a4adfc1 microsoft.codeanalysis.generatordriver.rungeneratorsandupdatecompilation(microsoft.codeanalysis.compilation, microsoft.codeanalysis.compilation byref, system.collections.immutable.immutablearray`1 byref, system.threading.cancellationtoken) [/_/src/compilers/core/portable/sourcegeneration/generatordriver.cs @ 54] 00000068e603ee50 00007ffd6a468763 microsoft.codeanalysis.commoncompiler.rungenerators(microsoft.codeanalysis.compilation, system.string, microsoft.codeanalysis.parseoptions, system.collections.immutable.immutablearray`1, microsoft.codeanalysis.diagnostics.analyzerconfigoptionsprovider, system.collections.immutable.immutablearray`1, microsoft.codeanalysis.diagnosticbag) [/_/src/compilers/core/portable/commandline/commoncompiler.cs @ 838] 00000068e603ef20 00007ffd6a469520 microsoft.codeanalysis.commoncompiler.compileandemit(microsoft.codeanalysis.touchedfilelogger, microsoft.codeanalysis.compilation byref, system.collections.immutable.immutablearray`1, system.collections.immutable.immutablearray`1, system.collections.immutable.immutablearray`1, microsoft.codeanalysis.analyzerconfigset, system.collections.immutable.immutablearray`1, system.collections.immutable.immutablearray`1, microsoft.codeanalysis.diagnosticbag, microsoft.codeanalysis.errorlogger, system.threading.cancellationtoken, system.threading.cancellationtokensource byref, microsoft.codeanalysis.diagnostics.analyzerdriver byref, system.nullable`1 byref) [/_/src/compilers/core/portable/commandline/commoncompiler.cs @ 1145] 00000068e603f280 00007ffd6a468c52 microsoft.codeanalysis.commoncompiler.runcore(system.io.textwriter, microsoft.codeanalysis.errorlogger, system.threading.cancellationtoken) [/_/src/compilers/core/portable/commandline/commoncompiler.cs @ 956] 00000068e603f450 00007ffd6a4684b6 microsoft.codeanalysis.commoncompiler.run(system.io.textwriter, system.threading.cancellationtoken) [/_/src/compilers/core/portable/commandline/commoncompiler.cs @ 781] 00000068e603f4c0 00007ffd6aaf9def microsoft.codeanalysis.compilerserver.compilerserverhost.runcompilation(microsoft.codeanalysis.compilerserver.runrequest byref, system.threading.cancellationtoken) [/_/src/compilers/server/vbcscompiler/compilerrequesthandler.cs @ 152] 00000068e603f5e0 00007ffd6aaff745 microsoft.codeanalysis.compilerserver.clientconnectionhandler+c__displayclass8_0.b__1() [/_/src/compilers/server/vbcscompiler/clientconnectionhandler.cs @ 168] 00000068e603f640 00007ffd6de7b78f system.threading.tasks.task`1[[system.__canon, system.private.corelib]].innerinvoke() [/_/src/libraries/system.private.corelib/src/system/threading/tasks/future.cs @ 501] 00000068e603f680 00007ffd6dc364bd system.threading.executioncontext.runinternal(system.threading.executioncontext, system.threading.contextcallback, system.object) [/_/src/libraries/system.private.corelib/src/system/threading/executioncontext.cs @ 179] 00000068e603f6f0 00007ffd6dc50914 system.threading.tasks.task.executewiththreadlocal(system.threading.tasks.task byref, system.threading.thread) [/_/src/libraries/system.private.corelib/src/system/threading/tasks/task.cs @ 2345] 00000068e603f9c0 00007ffd72d1c663 [debuggeru2mcatchhandlerframe: 00000068e603f9c0]
最后一个问题就是如果找到这个调用栈上的源码,当然是在 github 上找啦: https://github.com/dotnet/roslyn ,拉下来后就可以根据调用栈上的方法来分析啦,参考如下:
四:总结
在研究底层方面,windbg可谓是一把趁手的兵器,这个例子也算是活生生的论证了一把,否则真的不知道从 roslyn 何处来论证官方给出的流程图,对吧。
到此这篇关于详解c#中有趣的 sourcegenerator生成器的文章就介绍到这了,更多相关c# sourcegenerator生成器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论