如何扫描 MSIL 代码以查找某些函数调用
我要构建一个 SOA gui 框架,并且我想自动检测服务以及来自客户端模块的服务依赖性。 到目前为止,我有这样的代码,它使用放置在类模块上的属性来工作:
[ServiceProvider(typeof(DemoService3))]
[ServiceConsumer(typeof(DemoService1))]
我想知道如何自动扫描这些代码,这样人们就不会忘记添加标记并可能在运行时获得空引用。 在代码中,服务是通过以下命令注册和获取的:
Services.RegisterService(new DemoService1());
Services.FetchService<DemoService3>();
我想找到这些调用,以及传入的类型(两者都采用类型参数,第一个参数是隐式的)...其余的代码用于执行我的依赖项和构建已经完成:)
I am to build a SOA gui framework, and I'd like to autodetect services, and service dependencies from client modules. I have code such as this so far, which works using attributes, placed on class modules:
[ServiceProvider(typeof(DemoService3))]
[ServiceConsumer(typeof(DemoService1))]
I am wondering how I can scan for these automagically, so that people wouldn't forget to add the marker and potentially get null references at runtime. In the code services are registered and fetched via the following commands:
Services.RegisterService(new DemoService1());
Services.FetchService<DemoService3>();
I want to find these calls, and also the types being passed in (both take a type param, implicit for the first one)... the rest of the code for doing my dependencies and construction is already done :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在 CLR 级别(而不是 C# 级别)分析 IL 才能解决这个问题。
您应该能够利用 Mono Cecil 来实现这一目标。
You will need to analyze the IL at the CLR level, not the C# level to figure this out.
You should be able to leverage Mono Cecil to pull this off.
您可以使用 Mono.Cecil 或 .NET 反射来完成此任务。
建议使用 Mono.Cecil,因为它具有更好的性能和灵活性。 以下是一些可以帮助您入门的示例(Cecil + 顶部的简单扩展):
You can either use Mono.Cecil or .NET reflection to accomplish that.
Mono.Cecil is recommended due to its better performance and flexibility. Here are some samples (Cecil + simple extensions on top) that could get you started:
如果您由于某种原因无法使用 Mono.Cecil,您可以考虑手动解析 IL:您实际上只需要找到
call
和callvirt
指令,可能进行足够的静态分析来理解 new DemoService1() 返回的类型。typeof(YourClass).GetMethod("YourMethod").GetMethodBody().GetILAsByteArray()
是你的朋友。If you're unable to use Mono.Cecil for some reason, you could consider parsing the IL by hand: you'd effectively just need to find
call
andcallvirt
instructions, possibly doing static analysis enough to understand the type returned bynew DemoService1()
.typeof(YourClass).GetMethod("YourMethod").GetMethodBody().GetILAsByteArray()
is your friend.