/
Example_ClrMD.cs
236 lines (199 loc) · 7.59 KB
/
Example_ClrMD.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// CilTools.BytecodeAnalysis example: Reading methods' bytecode from managed process using ClrMD
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.Diagnostics.Runtime;
using CilTools.BytecodeAnalysis;
// Required NuGet package: Microsoft.Diagnostics.Runtime
namespace Example_ClrMD
{
class Program
{
public static Dictionary<int, string> GetTokenTable(string module,ClrRuntime runtime)
{
//get metadata tokens for specified module in ClrMD debugging session
Dictionary<int, string> table = new Dictionary<int, string>();
foreach (var t in runtime.Heap.EnumerateTypes())
{
string name = t.Module.FileName;
if (name == null) name = "";
if (!Path.GetFileName(name).Equals(module, StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
foreach (var m in t.Methods)
{
if (!(m.Type.Name == t.Name)) continue; //skip inherited methods
table[(int)m.MetadataToken] = t.Name + "." + m.Name;
}
}
return table;
}
public static void DumpMethods(int pid)
{
//prints bytecode of methods in specified managed process
string module = "";
var process = System.Diagnostics.Process.GetProcessById(pid);
using (process)
{
module = Path.GetFileName(process.MainModule.FileName);
}
Console.WriteLine("Process ID: {0}; Process name: {1}", pid, module);
Console.WriteLine();
//Start ClrMD session
DataTarget dt = DataTarget.AttachToProcess(pid, 5000, AttachFlag.Passive);
using (dt)
{
ClrInfo runtimeInfo = dt.ClrVersions[0];
ClrRuntime runtime = runtimeInfo.CreateRuntime();
Dictionary<int, string> tokens = GetTokenTable(module, runtime);
//dump regular methods
foreach (var t in runtime.Heap.EnumerateTypes())
{
string name = t.Module.FileName;
if (name == null) name = "";
if (!(Path.GetFileName(name).Equals(module, StringComparison.InvariantCultureIgnoreCase)))
{
continue;
}
Console.WriteLine(t.Name);
foreach (var m in t.Methods)
{
if (!(m.Type.Name == t.Name)) continue;
Console.WriteLine(" Method: " + m.Name);
byte[] il;
int bytesread;
var ildata = m.IL;
if (ildata == null)
{
Console.WriteLine("Cannot load IL!");
Console.WriteLine();
continue;
}
else
{
il = new byte[ildata.Length];
dt.ReadProcessMemory(ildata.Address, il, ildata.Length, out bytesread);
}
foreach (CilInstruction instr in CilReader.GetInstructions(il))
{
if (instr.OpCode.FlowControl == FlowControl.Call)
{
int n = (int)instr.Operand;
if (tokens.ContainsKey(n))
{
Console.WriteLine(instr.OpCode.ToString().PadRight(10, ' ') + " " + tokens[n]);
}
else
{
Console.WriteLine(instr.OpCode.ToString().PadRight(10, ' ') + " 0x" + n.ToString("X"));
}
}
else Console.WriteLine(instr.ToString());
}
Console.WriteLine();
}
Console.WriteLine();
}
//dump dynamic methods
foreach (ClrObject o in runtime.Heap.EnumerateObjects())
{
if (o.Type == null) continue;
if (!o.Type.Name.Contains("ILGenerator")) continue;
try
{
string mname;
try
{
ClrObject builder = o.GetObjectField("m_methodBuilder");
mname = builder.GetStringField("m_strName");
}
catch (ArgumentException)
{
mname = "???";
}
int size = o.GetField<int>("m_length");
ClrObject stream = o.GetObjectField("m_ILStream");
ClrType type = stream.Type;
ulong obj = stream.Address;
int len = type.GetArrayLength(obj);
byte[] il = new byte[size];
for (int i = 0; i < size; i++) il[i] = (byte)type.GetArrayElementValue(obj, i);
Console.WriteLine("Dynamic method: " + mname);
foreach (CilInstruction instr in CilReader.GetInstructions(il))
{
if (instr.OpCode.FlowControl == FlowControl.Call)
{
int n = (int)instr.Operand;
if (tokens.ContainsKey(n))
{
Console.WriteLine(instr.OpCode.ToString().PadRight(10, ' ') + " " + tokens[n]);
}
else
{
Console.WriteLine(instr.OpCode.ToString().PadRight(10, ' ') + " 0x" + n.ToString("X"));
}
}
else Console.WriteLine(instr.ToString());
}
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().ToString() + ": " + ex.Message);
}
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter process ID>");
int id;
if (!Int32.TryParse(Console.ReadLine(), out id))
{
Console.WriteLine("Incorrect process ID entered");
}
else
{
DumpMethods(id);
}
Console.ReadKey();
}
}
}
/* Example output:
Enter process ID>
9092
Process ID: 9092; Process name: ConsoleApp1.exe
ConsoleApp1.Program
Method: .ctor
ldarg.0
call 0xA00001D
nop
ret
Method: GenerateCalcSum
[...]
Method: Main
nop
call ConsoleApp1.Program.GenerateCalcSum
stloc.0
ldloc.0
ldc.i4.1
ldc.i4.2
callvirt 0xA000019
stloc.1
ldloca.s V_1
call 0xA00001A
call 0xA00001B
nop
call 0xA00001C
pop
ret
Dynamic method: ???
ldarg.0
ldarg.1
add
ret
*/