我正在开发一个 IL 重写分析器,我的目标是能够向方法添加一个 try-finally 块。本质上:
// IL to set some state
try {
// original IL
} finally {
// IL to revert state
}
根据分析 API ( https://msdn.microsoft.com/en-us/library/ms232096.aspx ) 的有限文档和信息,似乎应该能够使用 SetILFunctionBody 添加新的异常处理子句。
我一直在关注来自http://clrprofiler.codeplex.com/SourceControl/list/changesets?branch=master的 Microsoft 示例 ILRewrite 分析器。我添加了代码以将“EHClause”添加到由“ILRewriter”类维护的 EHClause 列表中,并添加了适当的 leave.s 和 endfinally IL 指令。从分析器的角度来看,一切似乎都正常(SetILFunctionBody 成功),但是当调用修改后的方法时,我们得到了可怕的“公共语言运行时检测到无效程序”。没有更多信息的例外。
我尝试过的事情:
- 审查了仪器,代码没有在受保护区域内做非法的事情(例如返回或分支到外部)。
- 如果我删除 EHClause 和 leave.s/endfinally 指令,则检测方法运行良好。
- 我在 ILRewriting 代码中添加了大量日志记录,以便在最后转储修改后的 IL、EH 信息和字节。我已经使用所需的 try-finally 和状态跟踪代码制作了一个类似的方法,并且这两种方法的 IL(检测与编译)是相同的。然而,实际的“导出”字节有点不同。
这使我相信,分析 API 可能不支持将新的异常处理子句添加到没有任何开头的方法中。我很想听听您对如何解决这个问题的任何想法。
这是来自日志记录的一些信息 - * 是原始 IL。
EXPORTING IL:
Offset IL notes
0 0x28 call EnterScope
5 0x10e stloc (store isInScope bool)
9 0x00 nop BeginTry
10 0x00 *
11 0x14 *
12 0x0a *
13 0x02 *
14 0x28 *
19 0x0a *
20 0x06 *
21 0x0b *
22 0x2b *
24 0x07 *
25 0xde leave.s
27 0x10c ldloc scope bool
31 0x39 brfalse (if not in scope then go to nop-at-endfinally)
36 0x28 call LeaveScope
41 0x00 nop-at-endfinally
42 0xdc endfinally
43 0x2a *
EXPORT EHClause count:1
EXPORT EHClause 0: ClassToken[0x0], ExceptionFilter[0x0] (null?:1), ExceptionFlags:[0x2]; TryBegin:[0x0]@9, TryEnd:[0x10C]@27, HandlerBegin:[0x10C]@27, HandlerEnd:[0xDC]@42
EXPORT EHClause -- using classToken because (clause->ExceptionFlags & COR_ILEXCEPTION_CLAUSE_FILTER) == 0
Export EHClause -- has classToken [0x0] 0
ILWriter::Export. MaxStack:9, EHCount:1, InstructionCount:20, CodeSize:44, TotalSize:84,
Method Bytes (84): 0x1b 0x30 0x09 0x00 0x2c 0x00 0x00 0x00 0x10 0x00 0x00 0x11 0x28 0x46 0x00 0x00 0x0a 0xfe 0x0e 0x02 0x00 0x00 0x00 0x14 0x0a 0x02 0x28 0x11 0x00 0x00 0x0a 0x0a 0x06 0x0b 0x2b 0x00 0x07 0xde 0x10 0xfe 0x0c 0x02 0x00 0x39 0x05 0x00 0x00 0x00 0x28 0x46 0x00 0x00 0x0a 0x00 0xdc 0x2a 0x41 0x1c 0x00 0x00 0x02 0x00 0x00 0x00 0x09 0x00 0x00 0x00 0x12 0x00 0x00 0x00 0x1b 0x00 0x00 0x00 0x10 0x00 0x00 0x00 0x00 0x00 0x00 0x00
这是使用当前分析器添加 nop 的样子:
ILWriter::Import finished. MaxStack:6, EHCount:0, InstructionCount:11, CodeSize:16, MethodSize:28
EXPORTING IL:
0 0x00 nop
1 0x00
2 0x14
3 0x0a
4 0x02
5 0x28
10 0x0a
11 0x06
12 0x0b
13 0x2b
15 0x07
16 0x2a
ILWriter::Export. MaxStack:6, EHCount:0, InstructionCount:12, CodeSize:17, TotalSize:32,
Method Bytes (32): 0x13 0x30 0x06 0x00 0x11 0x00 0x00 0x00 0x01 0x00 0x00 0x11 0x00 0x00 0x14 0x0a 0x02 0x28 0x11 0x00 0x00 0x0a 0x0a 0x06 0x0b 0x2b 0x00 0x07 0x2a 0x00 0x00 0x00