-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncMethodProcessor.cs
200 lines (171 loc) · 6.77 KB
/
AsyncMethodProcessor.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
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;
namespace TuPack
{
internal class AsyncMethodProcessor
{
static Int32 Count;
MethodDefinition method;
TypeDefinition stateMachineType;
MethodBody body;
List<Instruction> returnPoints;
Int32 asyncIndex;
string name;
TracerFunctions tracerFunctions;
public AsyncMethodProcessor(MethodDefinition method, TracerFunctions funcs)
{
this.method = method;
asyncIndex = Count++;
name = method.FullName;
tracerFunctions = funcs;
}
public void Process()
{
try
{
InnerProcess();
}
catch (Exception e)
{
throw new Exception($"An error occurred processing '{method.FullName}'. Error: {e.Message}", e);
}
}
void InnerProcess()
{
var asyncAttribute = method.GetAsyncStateMachineAttribute();
stateMachineType = asyncAttribute.ConstructorArguments.Select(ctor => (TypeDefinition)ctor.Value).Single();
var moveNextMethod = stateMachineType.Methods.Single(m => m.Name == "MoveNext");
body = moveNextMethod.Body;
body.SimplifyMacros();
returnPoints = GetAsyncReturns(body.Instructions).ToList();
// First, fall back to old mechanism
int index;
// Check roslyn usage
var firstStateUsage = (
from instruction in body.Instructions
let fieldReference = instruction.Operand as FieldReference
where instruction.OpCode == OpCodes.Ldfld && fieldReference != null && fieldReference.Name.Contains("__state")
select instruction
).FirstOrDefault();
if (firstStateUsage is null)
{
// Probably compiled without roslyn, inject at first line
index = 0;
}
else
{
// Initial code looks like this (hence the -1):
//
// <== this is where we want to start the stopwatch
// ldarg.0
// ldfld __state
// stloc.0
// ldloc.0
index = body.Instructions.IndexOf(firstStateUsage) - 1;
}
InjectTracer(index);
foreach (var returnPoint in returnPoints)
{
FixReturn(returnPoint);
}
body.InitLocals = true;
body.OptimizeMacros();
}
void FixReturn(Instruction returnPoint)
{
var opCode = returnPoint.OpCode;
var operand = returnPoint.Operand as Instruction;
returnPoint.OpCode = OpCodes.Nop;
returnPoint.Operand = null;
var instructions = body.Instructions;
var indexOf = instructions.IndexOf(returnPoint);
instructions.Insert(++indexOf, Instruction.Create(OpCodes.Ldc_I4, asyncIndex));
instructions.Insert(++indexOf, Instruction.Create(OpCodes.Ldstr, name));
instructions.Insert(++indexOf, Instruction.Create(OpCodes.Call, tracerFunctions.EndAsync));
indexOf++;
if (opCode == OpCodes.Leave || opCode == OpCodes.Leave_S)
{
instructions.Insert(indexOf, Instruction.Create(opCode, operand));
}
else
{
instructions.Insert(indexOf, Instruction.Create(opCode));
}
}
void InjectTracer(int index)
{
body.Insert(index, new[]
{
Instruction.Create(OpCodes.Ldc_I4, asyncIndex),
Instruction.Create(OpCodes.Ldstr, name),
Instruction.Create(OpCodes.Call, tracerFunctions.BeginAsync)
});
}
static IEnumerable<Instruction> GetAsyncReturns(Collection<Instruction> instructions)
{
// There are 3 possible return points:
//
// 1) async code:
// awaiter.GetResult();
// awaiter = new TaskAwaiter();
//
// 2) exception handling
// L_00d5: ldloc.1
// L_00d6: call instance void [mscorlib]System.Runtime.CompilerServices.AsyncTaskMethodBuilder::SetException(class [mscorlib]System.Exception)
//
// 3) all other returns
//
// We can do this smart by searching for all leave and leave_S op codes and check if they point to the last
// instruction of the method. This equals a "return" call.
var returnStatements = new List<Instruction>();
var possibleReturnStatements = new List<Instruction>();
// Look for the last leave statement (that is the line all "return" statements go to)
for (var i = instructions.Count - 1; i >= 0; i--)
{
var instruction = instructions[i];
if (instruction.IsLeaveInstruction())
{
possibleReturnStatements.Add(instructions[i + 1]);
break;
}
}
for (var i = 0; i < instructions.Count; i++)
{
var instruction = instructions[i];
if (instruction.IsLeaveInstruction())
{
if (possibleReturnStatements.Any(x => ReferenceEquals(instruction.Operand, x)))
{
// This is a return statement, this covers scenarios 1 and 3
returnStatements.Add(instruction);
}
else
{
// Check if we set an exception in this block, this covers scenario 2
for (var j = i - 3; j < i; j++)
{
var previousInstruction = instructions[j];
if (previousInstruction.OpCode == OpCodes.Call)
{
if (previousInstruction.Operand is MethodReference methodReference)
{
if (methodReference.Name.Equals("SetException"))
{
returnStatements.Add(instruction);
break;
}
}
}
}
}
}
}
return returnStatements;
}
}
}