Adding exception handlers with Mono.Cecil is not difficult, it just requires you to know how exception handlers are laid out in the metadata.

Let say you have the C# method:

static void Throw ()
{
throw new Exception ("oups");
}

If you decompile it, it should look somewhat similar to this:

.method private static hidebysig default void Throw ()  cil managed
{
IL_0000: ldstr "oups"
IL_0005: newobj instance void class [mscorlib]System.Exception::.ctor(string)
IL_000a: throw
}

Now let say that you want to inject code in this method such as it's similar to the C# code:

static void Throw ()
{
try {
throw new Exception ("oups");
} catch (Exception e) {
Console.WriteLine (e);
}
}

That is, you simply want to wrap the existing code in a try catch handler. You can do it easily with Cecil this way:

    var method = ...;
var il = method.Body.GetILProcessor (); var write = il.Create (
OpCodes.Call,
module.Import (typeof (Console).GetMethod ("WriteLine", new [] { typeof (object)})));
var ret = il.Create (OpCodes.Ret);
var leave = il.Create (OpCodes.Leave, ret); il.InsertAfter (
method.Body.Instructions.Last (),
write); il.InsertAfter (write, leave);
il.InsertAfter (leave, ret); var handler = new ExceptionHandler (ExceptionHandlerType.Catch) {
TryStart = method.Body.Instructions.First (),
TryEnd = write,
HandlerStart = write,
HandlerEnd = ret,
CatchType = module.Import (typeof (Exception)),
}; method.Body.ExceptionHandlers.Add (handler);

This code is manipulating the previous method to look like this:

.method private static hidebysig default void Throw ()  cil managed
{
.maxstack 1
.try { // 0
IL_0000: ldstr "oups"
IL_0005: newobj instance void class [mscorlib]System.Exception::'.ctor'(string)
IL_000a: throw
} // end .try 0
catch class [mscorlib]System.Exception { // 0
IL_000b: call void class [mscorlib]System.Console::WriteLine(object)
IL_0010: leave IL_0015
} // end handler 0
IL_0015: ret
}

We're adding three new instructions: a call to Console.WriteLine, a leave to gracefully exit the catch handler, and finally (pun intended), a ret. Then we're simply creating a ExceptionHandler instance to represent a try catch handler whose try encompasses the existing body, and whose catch is the WriteLine statement.

One important thing to note is that the end instruction of a range is not contained inside the range. It's basically a [TryStart:TryEnd[ range.

Add a try-catch with Mono Cecil的更多相关文章

  1. 运用Mono.Cecil 反射读取.NET程序集元数据

    CLR自带的反射机智和API可以很轻松的读取.NET程序集信息,但是不能对程序集进行修改.CLR提供的是只读的API,但是开源项目Mono.Cecil不仅仅可以读取.NET程序集的元数据,还可以进行修 ...

  2. 基于Mono.Cecil的静态注入

    Aop注入有2种方式:动态注入和静态注入,其中动态注入有很多实现了 动态注入有几种方式: 利用Remoting的ContextBoundObject或MarshalByRefObject. 动态代理( ...

  3. 使用Mono Cecil 动态获取运行时数据 (Atribute形式 进行注入 用于写Log) [此文报考 xxx is declared in another module and needs to be imported的解决方法]-摘自网络

    目录 一:普通写法 二:注入定义 三:Weave函数 四:参数构造 五:业务编写 六:注入调用 7.  怎么调用别的程序集的方法示例 8. [is declared in another module ...

  4. 巧用Mono.Cecil反射加载类型和方法信息

    最近在做服务的细粒度治理,统一管理所有服务的方法.参数.返回值信息.方便后续的各个模块之间的对接和协作. 目前系统中所有的服务,管理到接口契约粒度,即服务接口声明和服务接口实现.要做服务的细粒度治理: ...

  5. Mono.Cecil - 0.6

    原文:Mono.Cecil - 0.6 项目地址:Mono.Cecil 项目描述:In simple English, with Cecil, you can load existing manage ...

  6. c# Mono.Cecil IL方式 读MethodBody

    using Kufen.Common.Definitions; using Mono.Cecil; using System; using System.Collections.Generic; us ...

  7. Mono.Cecil 初探(一):实现AOP

    序言 本篇文章介绍基于Mono.Cecil实现静态AOP的两种方式:无交互AOP和交互式AOP. 概念介绍 Mono.Cecil:一个可加载并浏览现有程序集并进行动态修改并保存的.NET框架. AOP ...

  8. C# Asp.net中的AOP框架 Microsoft.CCI, Mono.Cecil, Typemock Open-AOP API, PostSharp -摘自网络 (可以利用反射 Attribute 进行面向切面编程 可以用在记录整个方法的Log方面)

    Both Microsoft.CCI and Mono.Cecil are low-level, and don't validate produced assemblies. It takes lo ...

  9. 利用Mono.Cecil动态修改程序集来破解商业组件(仅用于研究学习)

    原文 利用Mono.Cecil动态修改程序集来破解商业组件(仅用于研究学习) Mono.Cecil是一个强大的MSIL的注入工具,利用它可以实现动态创建程序集,也可以实现拦截器横向切入动态方法,甚至还 ...

随机推荐

  1. C# cs文件表头模版

    设置位置:C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplatesCache\CSharp\Web\2 ...

  2. DIV+CSS 命名规范

    常用的CSS命名规则: 头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar栏目:column 页面外围控制整体布局宽度:wrapper 左 ...

  3. mac安装IDEA

    Mac上安装Java7 首先我们需要去oracle下载最新的jdk,笔者拿到的最新的版本是1.7.0_45-b18,这里没有什么好说的,直接下载安装即可,安装完毕后需要在.bash_profile或者 ...

  4. Ubuntu创建新用户并增加管理员权限 删除某个用户

    sudo adduser xxx 这样的命令会在home目录下添加一个帐号sudo useradd xxx 仅仅是添加用户, 不会在home目录添加帐号 删除:终端方法:以下用newuser代替想要删 ...

  5. Spring 4 官方文档学习(十一)Web MVC 框架之Flash Attributes

    接上一篇中的重定向. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-fl ...

  6. 让Android 变身回一台真正的Linux系统吧!!!

    在Android上开发也有两年的时间了,虽然一直都知道Android是构建在Linux Kernel上的手机操作系统,但在此之前一直没有实感. 直到第一次买了Android的手机,并请人帮我Root后 ...

  7. Perl Spreadsheet::WriteExcel 模块自动生成excel 文件

    Spreadsheet::WriteExcel 是一个跨平台的生成excel文件的模块, 可以方便的设置单元格内容, 样式, sheet 的名称: 但是默认情况下中文会乱码, 需要用Encode模块进 ...

  8. python PIL 库处理文件

    通过PIL库提供的API接口可以很方便的处理图像,功能十分强大: 最近有一个替换png背景色的需求,替换背景色的同时又不能够覆盖原来的文字,之前利用perl 的CD 模块一直没能够正确处理,最终用PI ...

  9. unity3d游戏开发学习分享之表面着色器讲解

    一.三种着色器的书写格式: 1.surface shaders, 指的是表面着色器 2.vertex and fragment shaders and 指的是顶点和片段着色器 3.fixed func ...

  10. help()

    help() 用于查看函数或模块的帮助信息 In [1]: help(id) # 查看id()这个函数的帮助信息,注意不要写成help(id()) id(...) id(object) -> i ...