Repository navigation
Expand file tree
/
Copy pathAsyncMethodProcessor.cs
More file actions
515 lines (433 loc) · 21.8 KB
/
Copy pathAsyncMethodProcessor.cs
File metadata and controls
515 lines (433 loc) · 21.8 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
public partial class AsyncMethodProcessor
{
public ModuleWeaver ModuleWeaver;
public MethodDefinition Method;
MethodBody body;
FieldDefinition stateFieldDefinition;
TypeDefinition stateMachineTypeDefinition;
TypeReference stateMachineTypeReference;
MethodDefinition? stopStopwatchMethod;
ParameterFormattingProcessor parameterFormattingProcessor = new();
FieldDefinition startTimestampField;
FieldDefinition endTimestampField;
FieldDefinition durationTimestampField;
FieldDefinition durationTimespanField;
public void Process()
{
try
{
InnerProcess();
}
catch (Exception exception)
{
throw new($"An error occurred processing '{Method.FullName}'. Error: {exception.Message}", exception);
}
}
void InnerProcess()
{
var asyncAttribute = Method.GetAsyncStateMachineAttribute();
stateMachineTypeDefinition = asyncAttribute.ConstructorArguments
.Select(ctor => (TypeDefinition)ctor.Value)
.Single();
if (stateMachineTypeDefinition.HasGenericParameters)
{
var genericStateMachineType = new GenericInstanceType(stateMachineTypeDefinition);
foreach (var genericParameter in stateMachineTypeDefinition.GenericParameters)
{
genericStateMachineType.GenericArguments.Add(genericParameter);
}
stateMachineTypeReference = genericStateMachineType;
}
else
{
stateMachineTypeReference = stateMachineTypeDefinition;
}
var moveNextMethod = stateMachineTypeDefinition.Methods
.Single(_ => _.Name == "MoveNext");
body = moveNextMethod.Body;
body.SimplifyMacros();
// 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.EndsWith("__state") ||
fieldReference.Name.EndsWith("$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 ($State for VB.net)
// stloc.0
// ldloc.0
index = body.Instructions.IndexOf(firstStateUsage) - 1;
}
stateFieldDefinition = (from x in stateMachineTypeDefinition.Fields
where x.Name.EndsWith("__state") ||
x.Name.EndsWith("$State")
select x).First();
InjectStopwatchStart(index, body.Instructions[index]);
InjectStopwatchStopMethod();
InjectStopwatchStopCalls();
body.InitLocals = true;
body.OptimizeMacros();
}
Instruction FixReturns()
{
var instructions = body.Instructions;
// We inject both a nop and return. This allows us to inject between the nop
// and the return
var nop = Instruction.Create(OpCodes.Nop);
var lastRet = Instruction.Create(OpCodes.Ret);
foreach (var instruction in instructions)
{
if (instruction.OpCode == OpCodes.Ret)
{
instruction.OpCode = OpCodes.Leave;
instruction.Operand = nop;
}
}
instructions.Add(nop);
instructions.Add(lastRet);
return lastRet;
}
void InjectStopwatchStart(int index, Instruction nextInstruction)
{
// Field definitions
startTimestampField = InjectStartTimestamp(stateMachineTypeDefinition);
endTimestampField = InjectEndTimestamp(stateMachineTypeDefinition);
durationTimestampField = InjectDurationTimestamp(stateMachineTypeDefinition);
durationTimespanField = InjectDurationTimespan(stateMachineTypeDefinition);
body.Insert(index,
[
// This code looks like this:
// if (_startTimestamp == 0L)
// {
// _startTimestamp = Stopwatch.GetTimestamp();
// }
Instruction.Create(OpCodes.Ldarg_0),
Instruction.Create(OpCodes.Ldfld, startTimestampField),
Instruction.Create(OpCodes.Ldc_I4_0),
Instruction.Create(OpCodes.Conv_I8),
Instruction.Create(OpCodes.Ceq),
Instruction.Create(OpCodes.Brfalse_S, nextInstruction),
Instruction.Create(OpCodes.Ldarg_0),
Instruction.Create(OpCodes.Call, ModuleWeaver.Stopwatch_GetTimestampMethod),
Instruction.Create(OpCodes.Stfld, startTimestampField)
]);
}
void InjectStopwatchStopMethod()
{
if (stopStopwatchMethod != null)
{
return;
}
var method = new MethodDefinition("StopMethodTimerStopwatch",
MethodAttributes.Private,
ModuleWeaver.TypeSystem.VoidReference);
var methodBody = method.Body;
methodBody.SimplifyMacros();
foreach (var instruction in GetWriteTimeInstruction(methodBody))
{
methodBody.Instructions.Add(instruction);
}
methodBody.InitLocals = true;
methodBody.OptimizeMacros();
stateMachineTypeDefinition.Methods.Add(method);
stopStopwatchMethod = method;
}
void InjectStopwatchStopCalls()
{
// There are 2 locations where the stopwatch logic should be injected:
// 1: just before the ::SetException
// 2: end of the method (which is not executed after calling ::SetException) or just before SetResult
var stopStopwatchMethodReference = new MethodReference(stopStopwatchMethod.Name, stopStopwatchMethod.ReturnType, stateMachineTypeReference)
{
HasThis = stopStopwatchMethod.HasThis,
ExplicitThis = stopStopwatchMethod.ExplicitThis,
CallingConvention = stopStopwatchMethod.CallingConvention
};
var stopwatchInstructions = new List<Instruction>(new[]
{
Instruction.Create(OpCodes.Ldarg_0),
Instruction.Create(OpCodes.Call, stopStopwatchMethodReference)
});
var returnInstruction = FixReturns();
var endInstruction = returnInstruction;
// 1: SetException: We will search for the last known catch block, and implement a finally there with the stopwatch code
var exceptionHandler = (from handler in body.ExceptionHandlers
orderby handler.HandlerEnd.Offset descending
select handler).FirstOrDefault();
if (exceptionHandler != null)
{
var catchStartIndex = body.Instructions.IndexOf(exceptionHandler.HandlerStart);
var catchEndIndex = body.Instructions.IndexOf(exceptionHandler.HandlerEnd);
for (var i = catchEndIndex; i >= catchStartIndex; i--)
{
if (body.Instructions[i].Operand is MethodReference {Name: "SetException"})
{
// Insert before
for (var j = 0; j < stopwatchInstructions.Count; j++)
{
body.Instructions.Insert(i + j, stopwatchInstructions[j]);
}
break;
}
}
}
// 2: end of the method (either SetResult or end of the method)
for (var i = body.Instructions.Count - 1; i >= 0; i--)
{
if (body.Instructions[i].Operand is MethodReference {Name: "SetResult"})
{
// Insert directly before the SetResult call, so the log has happened by the time awaiters resume.
// The injected call is stack neutral, and the state is already -2 at this point.
endInstruction = body.Instructions[i];
break;
}
}
var startIndex = body.Instructions.IndexOf(endInstruction);
for (var i = 0; i < stopwatchInstructions.Count; i++)
{
body.Instructions.Insert(startIndex++, stopwatchInstructions[i]);
}
}
IEnumerable<Instruction> GetWriteTimeInstruction(MethodBody methodBody)
{
var stopwatchRunningCheck = Instruction.Create(OpCodes.Ldarg_0);
var startOfRealMethod = Instruction.Create(OpCodes.Ldarg_0);
// Check if state machine is completed (state == -2)
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, stateFieldDefinition);
yield return Instruction.Create(OpCodes.Ldc_I4, -2);
yield return Instruction.Create(OpCodes.Beq_S, stopwatchRunningCheck);
yield return Instruction.Create(OpCodes.Ret);
// Check if there is a start timestamp
yield return stopwatchRunningCheck; // Ldarg_0
yield return Instruction.Create(OpCodes.Ldfld, startTimestampField);
yield return Instruction.Create(OpCodes.Ldc_I4_0);
yield return Instruction.Create(OpCodes.Conv_I8);
yield return Instruction.Create(OpCodes.Ceq);
yield return Instruction.Create(OpCodes.Brfalse_S, startOfRealMethod);
yield return Instruction.Create(OpCodes.Ret);
yield return startOfRealMethod; // Ldarg_0
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.Stopwatch_GetTimestampMethod);
yield return Instruction.Create(OpCodes.Stfld, endTimestampField);
// durationTimestamp = endTimestampVar - endTimestampVar;
yield return Instruction.Create(OpCodes.Ldarg_0); // Yes, ldarg_0 twice
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, endTimestampField);
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, startTimestampField);
yield return Instruction.Create(OpCodes.Sub);
yield return Instruction.Create(OpCodes.Stfld, durationTimestampField);
// durationTimespanVar = new TimeSpan((long)(MethodTimerHelper.TimestampToTicks * (double)durationTimestamp));
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldsfld, ModuleWeaver.MethodTimerHelper_TimestampToTicks);
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, durationTimestampField);
yield return Instruction.Create(OpCodes.Conv_R8);
yield return Instruction.Create(OpCodes.Mul);
yield return Instruction.Create(OpCodes.Conv_I8);
yield return Instruction.Create(OpCodes.Newobj, ModuleWeaver.TimeSpan_ConstructorMethod);
yield return Instruction.Create(OpCodes.Stfld, durationTimespanField);
var logWithMessageMethodUsingLong = ModuleWeaver.LogWithMessageMethodUsingLong;
var logWithMessageMethodUsingTimeSpan = ModuleWeaver.LogWithMessageMethodUsingTimeSpan;
var logMethodUsingLong = ModuleWeaver.LogMethodUsingLong;
var logMethodUsingTimeSpan = ModuleWeaver.LogMethodUsingTimeSpan;
if (logWithMessageMethodUsingLong is null && logWithMessageMethodUsingTimeSpan is null)
{
if (logMethodUsingLong is null && logMethodUsingTimeSpan is null)
{
// var elapsedMillisecondsVariable = (long)durationTimespanVar.TotalMilliseconds;
// Trace.WriteLine(string.Concat(methodName, elapsedMillisecondsVariable.ToString(), "ms"))
var elapsedMillisecondsVariable = new VariableDefinition(ModuleWeaver.TypeSystem.Int64Reference);
methodBody.Variables.Add(elapsedMillisecondsVariable);
yield return Instruction.Create(OpCodes.Ldstr, Method.MethodName());
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldflda, durationTimespanField);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.TimeSpan_TotalMillisecondsMethod);
yield return Instruction.Create(OpCodes.Conv_I8);
yield return Instruction.Create(OpCodes.Stloc, elapsedMillisecondsVariable);
yield return Instruction.Create(OpCodes.Ldloca, elapsedMillisecondsVariable);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.Int64ToString);
yield return Instruction.Create(OpCodes.Ldstr, "ms");
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.ConcatMethod);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.TraceWriteLineMethod);
}
else
{
yield return Instruction.Create(OpCodes.Ldtoken, Method);
yield return Instruction.Create(OpCodes.Ldtoken, Method.DeclaringType);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.GetMethodFromHandle);
yield return Instruction.Create(OpCodes.Ldarg_0);
if (logMethodUsingTimeSpan is null)
{
// Use .TotalMilliseconds converted to long
yield return Instruction.Create(OpCodes.Ldflda, durationTimespanField);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.TimeSpan_TotalMillisecondsMethod);
yield return Instruction.Create(OpCodes.Conv_I8);
yield return Instruction.Create(OpCodes.Call, logMethodUsingLong);
}
else
{
// Use timespan directly
yield return Instruction.Create(OpCodes.Ldfld, durationTimespanField);
yield return Instruction.Create(OpCodes.Call, logMethodUsingTimeSpan);
}
}
}
else
{
// Important notes:
// 1. Because async works with state machines, use the state machine & fields instead of method & variables.
// 2. The ldarg_0 calls are required to load the state machine class and is required before every field call.
var formattedFieldDefinition = stateMachineTypeDefinition.Fields.FirstOrDefault(_ => _.Name.Equals("methodTimerMessage"));
if (formattedFieldDefinition is null)
{
formattedFieldDefinition = new("methodTimerMessage", FieldAttributes.Private | FieldAttributes.CompilerControlled, ModuleWeaver.TypeSystem.StringReference);
stateMachineTypeDefinition.Fields.Add(formattedFieldDefinition);
}
var formattedFieldReference = new FieldReference(formattedFieldDefinition.Name, formattedFieldDefinition.FieldType, stateMachineTypeReference);
foreach (var instruction in ProcessTimeAttribute(Method, formattedFieldReference))
{
yield return instruction;
}
// Handle call to log method
yield return Instruction.Create(OpCodes.Ldtoken, Method);
yield return Instruction.Create(OpCodes.Ldtoken, Method.DeclaringType);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.GetMethodFromHandle);
yield return Instruction.Create(OpCodes.Ldarg_0);
if (logWithMessageMethodUsingTimeSpan is null)
{
// Use .TotalMilliseconds converted to long
yield return Instruction.Create(OpCodes.Ldflda, durationTimespanField);
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.TimeSpan_TotalMillisecondsMethod);
yield return Instruction.Create(OpCodes.Conv_I8);
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, formattedFieldReference);
yield return Instruction.Create(OpCodes.Call, logWithMessageMethodUsingLong);
}
else
{
// Use timespan directly
yield return Instruction.Create(OpCodes.Ldfld, durationTimespanField);
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, formattedFieldReference);
yield return Instruction.Create(OpCodes.Call, logWithMessageMethodUsingTimeSpan);
}
}
yield return Instruction.Create(OpCodes.Ret);
}
IEnumerable<Instruction> ProcessTimeAttribute(MethodDefinition methodDefinition, FieldReference formattedFieldReference)
{
// Load everything for a string format
var timeAttribute = methodDefinition.GetTimeAttribute();
if (timeAttribute != null)
{
var value = timeAttribute.ConstructorArguments.FirstOrDefault().Value as string;
if (string.IsNullOrWhiteSpace(value))
{
// Load null a string
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldnull);
}
else
{
// Note: no need to validate, already done in AssemblyProcessor::ProcessMethod
var info = parameterFormattingProcessor.ParseParameterFormatting(value);
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldstr, info.Format);
yield return Instruction.Create(OpCodes.Ldc_I4, info.ParameterNames.Count);
yield return Instruction.Create(OpCodes.Newarr, ModuleWeaver.TypeSystem.ObjectReference);
for (var i = 0; i < info.ParameterNames.Count; i++)
{
var parameterName = info.ParameterNames[i];
if (string.Equals(parameterName, "this"))
{
// Field name is <>4__this
parameterName = "<>4__this";
// {this} could be optimized away, let's add it for the user
InjectThisIntoStateMachine(methodDefinition);
}
yield return Instruction.Create(OpCodes.Dup);
yield return Instruction.Create(OpCodes.Ldc_I4, i);
var field = stateMachineTypeDefinition.Fields.FirstOrDefault(_ => _.Name.Equals(parameterName));
if (field is null)
{
ModuleWeaver.WriteError($"Parameter '{parameterName}' is not available on the async state machine. Probably it has been optimized away by the compiler. Please update the format so it excludes this parameter.");
// To make sure the weaver still produces valid IL, pass in a null value
yield return Instruction.Create(OpCodes.Ldnull);
}
else
{
yield return Instruction.Create(OpCodes.Ldarg_0);
yield return Instruction.Create(OpCodes.Ldfld, field);
if (field.FieldType.IsBoxingRequired(ModuleWeaver.TypeSystem.ObjectReference))
{
yield return Instruction.Create(OpCodes.Box, ModuleWeaver.ModuleDefinition.ImportReference(field.FieldType));
}
}
yield return Instruction.Create(OpCodes.Stelem_Ref);
}
yield return Instruction.Create(OpCodes.Call, ModuleWeaver.StringFormatWithArray);
}
yield return Instruction.Create(OpCodes.Stfld, formattedFieldReference);
}
}
void InjectThisIntoStateMachine(MethodDefinition methodDefinition)
{
const string fieldName = "<>4__this";
if (stateMachineTypeDefinition.Fields.Any(_ => _.Name.Equals(fieldName)))
{
return;
}
// Step 1: inject the field
var thisField = new FieldDefinition(fieldName, FieldAttributes.Public, methodDefinition.DeclaringType);
stateMachineTypeDefinition.Fields.Add(thisField);
// Step 2: set the field value in the actual method, search for the first usage of the state machine class
var methodBody = methodDefinition.Body;
methodBody.SimplifyMacros();
var instructions = methodDefinition.Body.Instructions;
var startInstruction = instructions.FirstOrDefault(x =>
{
if (x.Operand is VariableDefinition variableDefinition)
{
if (variableDefinition.VariableType.FullName.Equals(stateMachineTypeDefinition.FullName))
{
return true;
}
}
return false;
});
if (startInstruction is null)
{
ModuleWeaver.WriteError("Failed to inject '{this}' into the async method, the compiler optimized it away and it could not be injected automatically, please create a support ticket.");
return;
}
// IL_0000: ldloca.s 'stateMachine [Range(Instruction(IL_0000 ldloca.s)-Instruction(IL_003c ldloca.s))]'
// IL_0002: ldarg.0 // this
// IL_0003: stfld class ClassWithAsyncMethod ClassWithAsyncMethod/'<MethodWithAwaitAndThisAsync>d__1'::'<>4__this'
var index = instructions.IndexOf(startInstruction);
instructions.Insert(index + 0, Instruction.Create(OpCodes.Ldloca_S, (VariableDefinition)startInstruction.Operand));
instructions.Insert(index + 1, Instruction.Create(OpCodes.Ldarg_0));
instructions.Insert(index + 2, Instruction.Create(OpCodes.Stfld, thisField));
methodBody.OptimizeMacros();
}
}