This repository has been archived by the owner on Dec 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 126
/
MethodReturnValueInliner.cs
403 lines (347 loc) · 10.4 KB
/
MethodReturnValueInliner.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
Copyright (C) 2011-2015 [email protected]
This file is part of de4dot.
de4dot is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
de4dot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with de4dot. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using de4dot.blocks;
namespace de4dot.code {
// A simple class that statically detects the values of some local variables
public class VariableValues {
IList<Block> allBlocks;
IList<Local> locals;
Dictionary<Local, Variable> variableToValue = new Dictionary<Local, Variable>();
public class Variable {
int writes = 0;
object value;
bool unknownValue = false;
public bool IsValid() {
return !unknownValue && writes == 1;
}
public object Value {
get {
if (!IsValid())
throw new ApplicationException("Unknown variable value");
return value;
}
set { this.value = value; }
}
public void AddWrite() {
writes++;
}
public void SetUnknown() {
unknownValue = true;
}
}
public VariableValues(IList<Local> locals, IList<Block> allBlocks) {
this.locals = locals;
this.allBlocks = allBlocks;
Initialize();
}
void Initialize() {
foreach (var variable in locals)
variableToValue[variable] = new Variable();
foreach (var block in allBlocks) {
for (int i = 0; i < block.Instructions.Count; i++) {
var instr = block.Instructions[i];
switch (instr.OpCode.Code) {
case Code.Stloc:
case Code.Stloc_S:
case Code.Stloc_0:
case Code.Stloc_1:
case Code.Stloc_2:
case Code.Stloc_3:
var variable = Instr.GetLocalVar(locals, instr);
var val = variableToValue[variable];
val.AddWrite();
object obj;
if (!GetValue(block, i, out obj))
val.SetUnknown();
val.Value = obj;
break;
default:
break;
}
}
}
}
bool GetValue(Block block, int index, out object obj) {
while (true) {
if (index <= 0) {
obj = null;
return false;
}
var instr = block.Instructions[--index];
if (instr.OpCode == OpCodes.Nop)
continue;
switch (instr.OpCode.Code) {
case Code.Ldc_I4:
case Code.Ldc_I8:
case Code.Ldc_R4:
case Code.Ldc_R8:
case Code.Ldstr:
obj = instr.Operand;
return true;
case Code.Ldc_I4_S:
obj = (int)(sbyte)instr.Operand;
return true;
case Code.Ldc_I4_0: obj = 0; return true;
case Code.Ldc_I4_1: obj = 1; return true;
case Code.Ldc_I4_2: obj = 2; return true;
case Code.Ldc_I4_3: obj = 3; return true;
case Code.Ldc_I4_4: obj = 4; return true;
case Code.Ldc_I4_5: obj = 5; return true;
case Code.Ldc_I4_6: obj = 6; return true;
case Code.Ldc_I4_7: obj = 7; return true;
case Code.Ldc_I4_8: obj = 8; return true;
case Code.Ldc_I4_M1:obj = -1; return true;
case Code.Ldnull: obj = null; return true;
default:
obj = null;
return false;
}
}
}
public Variable GetValue(Local variable) {
return variableToValue[variable];
}
}
public abstract class MethodReturnValueInliner {
protected List<CallResult> callResults;
List<Block> allBlocks;
MethodDef theMethod;
VariableValues variableValues;
int errors = 0;
bool useUnknownArgs = false;
public bool UseUnknownArgs {
get { return useUnknownArgs; }
set { useUnknownArgs = value; }
}
protected class CallResult {
public Block block;
public int callStartIndex;
public int callEndIndex;
public object[] args;
public object returnValue;
public CallResult(Block block, int callEndIndex) {
this.block = block;
this.callEndIndex = callEndIndex;
}
public IMethod GetMethodRef() {
return (IMethod)block.Instructions[callEndIndex].Operand;
}
}
public bool InlinedAllCalls {
get { return errors == 0; }
}
public abstract bool HasHandlers { get; }
public MethodDef Method {
get { return theMethod; }
}
protected abstract void InlineAllCalls();
// Returns null if method is not a method we should inline
protected abstract CallResult CreateCallResult(IMethod method, MethodSpec gim, Block block, int callInstrIndex);
public int Decrypt(Blocks blocks) {
if (!HasHandlers)
return 0;
return Decrypt(blocks.Method, blocks.MethodBlocks.GetAllBlocks());
}
public int Decrypt(MethodDef method, List<Block> allBlocks) {
if (!HasHandlers)
return 0;
try {
theMethod = method;
callResults = new List<CallResult>();
this.allBlocks = allBlocks;
FindAllCallResults();
InlineAllCalls();
InlineReturnValues();
return callResults.Count;
}
catch {
errors++;
throw;
}
finally {
theMethod = null;
callResults = null;
this.allBlocks = null;
variableValues = null;
}
}
bool GetLocalVariableValue(Local variable, out object value) {
if (variableValues == null)
variableValues = new VariableValues(theMethod.Body.Variables, allBlocks);
var val = variableValues.GetValue(variable);
if (!val.IsValid()) {
value = null;
return false;
}
value = val.Value;
return true;
}
void FindAllCallResults() {
foreach (var block in allBlocks)
FindCallResults(block);
}
void FindCallResults(Block block) {
for (int i = 0; i < block.Instructions.Count; i++) {
var instr = block.Instructions[i];
if (instr.OpCode != OpCodes.Call)
continue;
var method = instr.Operand as IMethod;
if (method == null)
continue;
IMethod elementMethod = method;
var gim = method as MethodSpec;
if (gim != null)
elementMethod = gim.Method;
var callResult = CreateCallResult(elementMethod, gim, block, i);
if (callResult == null)
continue;
if (FindArgs(callResult))
callResults.Add(callResult);
}
}
bool FindArgs(CallResult callResult) {
var block = callResult.block;
var method = callResult.GetMethodRef();
var methodArgs = DotNetUtils.GetArgs(method);
int numArgs = methodArgs.Count;
var args = new object[numArgs];
int instrIndex = callResult.callEndIndex - 1;
for (int i = numArgs - 1; i >= 0; i--) {
object arg = null;
if (!GetArg(method, block, ref arg, ref instrIndex))
return false;
if (arg is int)
arg = FixIntArg(methodArgs[i], (int)arg);
else if (arg is long)
arg = FixIntArg(methodArgs[i], (long)arg);
args[i] = arg;
}
callResult.args = args;
callResult.callStartIndex = instrIndex + 1;
return true;
}
object FixIntArg(TypeSig type, long value) {
switch (type.ElementType) {
case ElementType.Boolean: return value != 0;
case ElementType.Char: return (char)value;
case ElementType.I1: return (sbyte)value;
case ElementType.U1: return (byte)value;
case ElementType.I2: return (short)value;
case ElementType.U2: return (ushort)value;
case ElementType.I4: return (int)value;
case ElementType.U4: return (uint)value;
case ElementType.I8: return (long)value;
case ElementType.U8: return (ulong)value;
}
throw new ApplicationException(string.Format("Wrong type {0}", type));
}
bool GetArg(IMethod method, Block block, ref object arg, ref int instrIndex) {
while (true) {
if (instrIndex < 0) {
// We're here if there were no cflow deobfuscation, or if there are two or
// more blocks branching to the decrypter method, or the two blocks can't be
// merged because one is outside the exception handler (eg. buggy obfuscator).
Logger.w("Could not find all arguments to method {0} ({1:X8})",
Utils.RemoveNewlines(method),
method.MDToken.ToInt32());
errors++;
return false;
}
var instr = block.Instructions[instrIndex--];
switch (instr.OpCode.Code) {
case Code.Ldc_I4:
case Code.Ldc_I8:
case Code.Ldc_R4:
case Code.Ldc_R8:
case Code.Ldstr:
arg = instr.Operand;
break;
case Code.Ldc_I4_S:
arg = (int)(sbyte)instr.Operand;
break;
case Code.Ldc_I4_0: arg = 0; break;
case Code.Ldc_I4_1: arg = 1; break;
case Code.Ldc_I4_2: arg = 2; break;
case Code.Ldc_I4_3: arg = 3; break;
case Code.Ldc_I4_4: arg = 4; break;
case Code.Ldc_I4_5: arg = 5; break;
case Code.Ldc_I4_6: arg = 6; break;
case Code.Ldc_I4_7: arg = 7; break;
case Code.Ldc_I4_8: arg = 8; break;
case Code.Ldc_I4_M1:arg = -1; break;
case Code.Ldnull: arg = null; break;
case Code.Nop:
continue;
case Code.Ldloc:
case Code.Ldloc_S:
case Code.Ldloc_0:
case Code.Ldloc_1:
case Code.Ldloc_2:
case Code.Ldloc_3:
GetLocalVariableValue(instr.Instruction.GetLocal(theMethod.Body.Variables), out arg);
break;
case Code.Ldfld:
case Code.Ldsfld:
arg = instr.Operand;
break;
default:
int pushes, pops;
instr.Instruction.CalculateStackUsage(false, out pushes, out pops);
if (!useUnknownArgs || pushes != 1) {
Logger.w("Could not find all arguments to method {0} ({1:X8}), instr: {2}",
Utils.RemoveNewlines(method),
method.MDToken.ToInt32(),
instr);
errors++;
return false;
}
for (int i = 0; i < pops; i++) {
if (!GetArg(method, block, ref arg, ref instrIndex))
return false;
}
arg = null;
break;
}
break;
}
return true;
}
void InlineReturnValues() {
callResults = RemoveNulls(callResults);
callResults.Sort((a, b) => {
int i1 = allBlocks.FindIndex((x) => a.block == x);
int i2 = allBlocks.FindIndex((x) => b.block == x);
if (i1 != i2)
return i1.CompareTo(i2);
return a.callStartIndex.CompareTo(b.callStartIndex);
});
callResults.Reverse();
InlineReturnValues(callResults);
}
static List<CallResult> RemoveNulls(List<CallResult> inList) {
var outList = new List<CallResult>(inList.Count);
foreach (var callResult in inList) {
if (callResult.returnValue != null)
outList.Add(callResult);
}
return outList;
}
protected abstract void InlineReturnValues(IList<CallResult> callResults);
}
}