-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathpmi.cs
More file actions
1562 lines (1358 loc) · 49 KB
/
pmi.cs
File metadata and controls
1562 lines (1358 loc) · 49 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using pmi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Buffers;
using System.Threading;
class Util
{
public static string MapPathToFileName(string path)
{
// Return all file system path components with underscores.
return Regex.Replace(path, @"[:/\\]", "_");
}
}
// Helper type that provides a class that implements IAsyncStateMachine
//
// Note the class we want is is the nested class generated by the
// async compilation mechanism in Roslyn.
class AsyncHelper
{
static async ValueTask<long> V(long i, Task t) { await t; return i; }
}
// Helper type that provides a class implementing ICriticalNotifyCompletion
class RefAwaiter : ICriticalNotifyCompletion
{
public void OnCompleted(Action a) { }
public void UnsafeOnCompleted(Action a) { }
}
// Helper type that provides a struct implementing ICriticalNotifyCompletion
struct StructAwaiter : ICriticalNotifyCompletion
{
public void OnCompleted(Action a) { }
public void UnsafeOnCompleted(Action a) { }
}
// Specialized assembly resolution support
//
// We want to handle specifying a "load path" where assemblies can be found.
// The environment variable PMIPATH is a semicolon-separated list of paths. If the
// Assembly can't be found by the usual mechanisms, we'll probe on the PMIPATH list.
//
// This can be done via an assembly resolve event handler (from the default load
// context) or via a custom load context.
//
// Where possible we use a custom load context because it's more flexible --
// eg allowing two different versions of an assembly to be loaded (except for corelib).
//
// The Resolver class contains the common logic; the CustomLoadContext adapts it
// to the different runtimes.
//
public class Resolver
{
public static Assembly ResolveEventHandler(object sender, ResolveEventArgs args)
{
// What assembly we are searching for...?
int idx = args.Name.IndexOf(",");
if (idx == -1)
{
Console.WriteLine($"ResolveEventHandler called with unexpected args: {args}");
return null;
}
string assemblyName = args.Name.Substring(0, idx) + ".dll";
return Resolve(assemblyName, AssemblyLoadContext.Default);
}
public static Assembly Resolve(string assemblyName, AssemblyLoadContext context)
{
string pmiPath = null;
if (context is CustomLoadContext)
{
pmiPath = ((CustomLoadContext)context).PmiPath;
}
else
{
pmiPath = Environment.GetEnvironmentVariable("PMIPATH");
}
// Do we have a PMIPATH?
if (pmiPath == null)
{
return null;
}
string[] pmiPaths = pmiPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string path in pmiPaths)
{
string tmpPath = Path.GetFullPath(Path.Combine(path, assemblyName));
if (File.Exists(tmpPath))
{
// Found it!
try
{
Assembly result = context.LoadFromAssemblyPath(tmpPath);
return result;
}
catch (Exception)
{
}
}
}
return null;
}
}
#if NETFRAMEWORK || NETCOREAPP1_0 || NETCOREAPP1_1 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2
// Full Fx and older NETCOREAPP: via the assembly resolve event
public class CustomLoadContext : AssemblyLoadContext
{
readonly static string s_pmiPath;
public string PmiPath => s_pmiPath;
public CustomLoadContext(string ignored)
{
}
// Use .cctor to install the resolve handler and set PmiPath
static CustomLoadContext()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(Resolver.ResolveEventHandler);
s_pmiPath = Environment.GetEnvironmentVariable("PMIPATH");
}
public Assembly LoadAssembly(string assemblyPath)
{
return Assembly.LoadFrom(assemblyPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
return Resolver.Resolve(assemblyName.Name + ".dll", this);
}
}
#else
// NETCOREAPP3+: via a true custom load context
public class CustomLoadContext : AssemblyLoadContext
{
public string PmiPath { get; }
public CustomLoadContext(string assemblyPath)
{
string pmiPath = Environment.GetEnvironmentVariable("PMIPATH");
if (pmiPath != null)
{
pmiPath += ";";
}
else
{
pmiPath = "";
}
// Add in current assembly path and framework path
pmiPath += Path.GetDirectoryName(assemblyPath);
pmiPath += ";";
pmiPath += Path.GetDirectoryName(typeof(object).Assembly.Location);
PmiPath = pmiPath;
}
public Assembly LoadAssembly(string assemblyPath)
{
return LoadFromAssemblyPath(assemblyPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
return Resolver.Resolve(assemblyName.Name + ".dll", this);
}
}
#endif
// This set of classes provides a way to forcibly jit a large number of methods.
// It can be used as is or included as a component in jit measurement and testing
// tools.
//
// In .Net Core, PrepareMethod should give codegen that is very similar to
// the code one would see if the method were actually called (the same is not
// as true in .Net Framework -- in particular the jit may make very different
// inlining decisions).
//
// Assemblies defining generic types and generic methods require special handling.
// Methods in generic types and generic methods can inspire the jit to create
// numerous different method bodies depending on the type parameters used
// for instantation.
//
// The code below uses a very simple generic instantiation strategy. It currently
// only handles one- and two-parameter generic types with simple constraints.
// Base class for visiting types and methods in an assembly.
class Visitor
{
protected DateTime startTime;
protected string assemblyName;
protected string assemblyPath;
public virtual void Start()
{
}
public virtual void Finish()
{
}
public virtual void StartAssembly(Assembly assembly, string _assemblyPath)
{
startTime = DateTime.Now;
assemblyName = assembly.GetName().Name;
assemblyPath = _assemblyPath;
}
public virtual void FinishAssembly(Assembly assembly)
{
}
public virtual void UninstantiableType(Type type, string reason)
{
}
public virtual void StartType(Type type)
{
}
public virtual void FinishType(Type type)
{
}
public virtual void StartMethod(Type type, MethodBase method)
{
}
public virtual bool FinishMethod(Type type, MethodBase method)
{
return true;
}
public virtual void UninstantiableMethod(MethodBase method)
{
}
public virtual void UninstantiableMethods(MethodBase[] methods)
{
}
public TimeSpan ElapsedTime()
{
return DateTime.Now - startTime;
}
}
// Support for counting assemblies, types and methods.
class CounterBase : Visitor
{
protected int typeCount;
protected int uninstantiableTypeCount;
protected int methodCount;
protected int uninstantiableMethodCount;
public int TypeCount => typeCount;
public int UninstantiableTypeCount => uninstantiableTypeCount;
public int MethodCount => methodCount;
public int UninstantiableMethodCount => uninstantiableMethodCount;
public override void StartAssembly(Assembly assembly, string assemblyPath)
{
base.StartAssembly(assembly, assemblyPath);
typeCount = 0;
methodCount = 0;
uninstantiableTypeCount = 0;
uninstantiableMethodCount = 0;
}
public override void FinishType(Type type)
{
base.FinishType(type);
typeCount++;
}
public override void UninstantiableType(Type type, string reason)
{
base.UninstantiableType(type, reason);
uninstantiableTypeCount++;
}
public override bool FinishMethod(Type type, MethodBase method)
{
bool result = base.FinishMethod(type, method);
methodCount++;
return result;
}
public override void UninstantiableMethod(MethodBase method)
{
base.UninstantiableMethod(method);
uninstantiableMethodCount++;
}
public override void UninstantiableMethods(MethodBase[] methods)
{
base.UninstantiableMethods(methods);
uninstantiableMethodCount += methods.Length;
}
}
// Counts types and methods
class Counter : CounterBase
{
public override void StartAssembly(Assembly assembly, string assemblyPath)
{
base.StartAssembly(assembly, assemblyPath);
Console.WriteLine($"Computing Count for {assemblyName}");
}
public override void StartType(Type type)
{
base.StartType(type);
Console.WriteLine($"#types: {typeCount}, #methods: {methodCount}, before type {type.FullName}");
}
public override void FinishAssembly(Assembly assembly)
{
base.FinishAssembly(assembly);
TimeSpan elapsed = ElapsedTime();
Console.WriteLine(
$"Counts {assemblyName} - #types: {typeCount}, #methods: {methodCount}, " +
$"skipped types: {uninstantiableTypeCount}, skipped methods: {uninstantiableMethodCount}, " +
$"elapsed ms: {elapsed.TotalMilliseconds:F2}");
}
}
// Invoke the jit on some methods
abstract class PrepareBase : CounterBase
{
protected int firstMethod;
protected int methodsPrepared;
protected DateTime startType;
protected bool _verbose;
protected bool _time;
public PrepareBase(int f, bool verbose, bool time)
{
firstMethod = f;
_verbose = verbose;
_time = time;
}
public override void StartAssembly(Assembly assembly, string assemblyPath)
{
base.StartAssembly(assembly, assemblyPath);
methodsPrepared = 0;
}
public override void FinishAssembly(Assembly assembly)
{
base.FinishAssembly(assembly);
TimeSpan elapsed = ElapsedTime();
Console.Write(
$"Completed assembly {assemblyName} - #types: {typeCount}, #methods: {methodsPrepared}, " +
$"skipped types: {uninstantiableTypeCount}, skipped methods: {uninstantiableMethodCount}");
if (_time || _verbose)
{
Console.WriteLine($", time: {elapsed.TotalMilliseconds:F2}ms");
}
else
{
Console.WriteLine("");
}
}
public override void StartType(Type type)
{
base.StartType(type);
if (_verbose)
{
Console.WriteLine($"Start type {type.FullName}");
}
startType = DateTime.Now;
}
public override void FinishType(Type type)
{
if (_verbose)
{
TimeSpan elapsedType = DateTime.Now - startType;
Console.WriteLine($"Completed type {type.FullName}, elapsed ms: {elapsedType.TotalMilliseconds:F2}");
}
base.FinishType(type);
}
public override void UninstantiableType(Type type, string reason)
{
if (_verbose)
{
Console.WriteLine($"Unable to instantiate {type.FullName}: {reason}");
}
base.UninstantiableType(type, reason);
}
public override void StartMethod(Type type, MethodBase method)
{
base.StartMethod(type, method);
AttemptMethod(type, method);
}
public abstract void AttemptMethod(Type type, MethodBase method);
protected bool TryPrepareMethod(Type type, MethodBase method, out TimeSpan elapsedFunc)
{
bool success = false;
elapsedFunc = TimeSpan.MinValue;
try
{
DateTime startFunc = DateTime.Now;
GC.WaitForPendingFinalizers();
System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle);
elapsedFunc = DateTime.Now - startFunc;
success = true;
}
catch (System.EntryPointNotFoundException)
{
Console.WriteLine();
Console.WriteLine($"EntryPointNotFoundException {type.FullName}::{method.Name}");
}
catch (System.BadImageFormatException)
{
Console.WriteLine();
Console.WriteLine($"BadImageFormatException {type.FullName}::{method.Name}");
}
catch (System.MissingMethodException)
{
Console.WriteLine();
Console.WriteLine($"MissingMethodException {type.FullName}::{method.Name}");
}
catch (System.ArgumentException e)
{
Console.WriteLine();
string msg = e.Message.Split(new char[] { '\r', '\n' })[0];
Console.WriteLine($"ArgumentException {type.FullName}::{method.Name} {msg}");
}
catch (System.IO.FileNotFoundException eFileNotFound)
{
Console.WriteLine();
Console.WriteLine($"FileNotFoundException {type.FullName}::{method.Name}" +
$" - {eFileNotFound.FileName} ({eFileNotFound.Message})");
}
catch (System.DllNotFoundException eDllNotFound)
{
Console.WriteLine();
Console.WriteLine($"DllNotFoundException {type.FullName}::{method.Name} ({eDllNotFound.Message})");
}
catch (System.TypeInitializationException eTypeInitialization)
{
Console.WriteLine();
Console.WriteLine("TypeInitializationException {type.FullName}::{method.Name}" +
$"{eTypeInitialization.TypeName} ({eTypeInitialization.Message})");
}
catch (System.Runtime.InteropServices.MarshalDirectiveException)
{
Console.WriteLine();
Console.WriteLine($"MarshalDirectiveException {type.FullName}::{method.Name}");
}
catch (System.TypeLoadException)
{
Console.WriteLine();
Console.WriteLine($"TypeLoadException {type.FullName}::{method.Name}");
}
catch (System.OverflowException)
{
Console.WriteLine();
Console.WriteLine($"OverflowException {type.FullName}::{method.Name}");
}
catch (System.InvalidProgramException)
{
Console.WriteLine();
Console.WriteLine($"InvalidProgramException {type.FullName}::{method.Name}");
}
catch (System.InvalidOperationException)
{
Console.WriteLine();
Console.WriteLine($"InvalidOperationException {type.FullName}::{method.Name}");
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine($"Unknown exception {type.FullName}::{method.Name}");
Console.WriteLine(e);
}
return success;
}
protected string GetGenericArgumentsString(MethodBase method)
{
if (method.IsGenericMethod)
{
Type[] args = method.GetGenericArguments();
string argString = "<";
bool first = true;
foreach (Type t in args)
{
if (!first)
{
argString += ",";
}
argString += t.ToString();
first = false;
}
argString += ">";
return argString;
}
else
{
return "";
}
}
}
// Invoke the jit on all methods starting from an initial method.
// By default the initial method is the first one visisted.
class PrepareAll : PrepareBase
{
string pmiFullLogFileName;
string pmiPartialLogFileName;
string markerFileName;
public PrepareAll(int firstMethod, bool verbose, bool time) : base(firstMethod, verbose, time)
{
}
public override void StartAssembly(Assembly assembly, string assemblyPath)
{
base.StartAssembly(assembly, assemblyPath);
if (_verbose)
{
Console.WriteLine($"PrepAll for {assemblyName}");
}
string assemblyPathAsFile = Util.MapPathToFileName(assemblyPath);
pmiFullLogFileName = $"{assemblyPathAsFile}.pmi";
pmiPartialLogFileName = $"{assemblyPathAsFile}.pmiPartial";
markerFileName = $"NextMethodToPrep-{assemblyPathAsFile}.marker";
}
public override void AttemptMethod(Type type, MethodBase method)
{
// Many concurrent PMIs are invoked by jit-diff / jit-dasm-pmi.
// We need to make sure the file names we choose are unique
// as well as being predictable by DRIVEALL. We construct a
// filename based on the full pathname of the assembly being
// used.
WriteAndFlushNextMethodToPrepMarker();
if (methodCount >= firstMethod)
{
methodsPrepared++;
if (method.IsAbstract)
{
if (_verbose)
{
Console.WriteLine($"PREPALL type# {typeCount} method# {methodCount} {type.FullName}::{method.Name} - skipping (abstract)");
}
}
else if (method.ContainsGenericParameters)
{
if (_verbose)
{
Console.WriteLine($"PREPALL type# {typeCount} method# {methodCount} {type.FullName}::{method.Name} - skipping (generic parameters)");
}
UninstantiableMethod(method);
}
else
{
string genericArgString = "";
if (_verbose)
{
genericArgString = GetGenericArgumentsString(method);
Console.WriteLine($"PREPALL type# {typeCount} method# {methodCount} {type.FullName}::{method.Name}{genericArgString}");
}
var succeeded = TryPrepareMethod(type, method, out TimeSpan elapsedFunc);
if (_verbose || !succeeded)
{
Console.Write($"{(succeeded ? "Completed" : "Failed")} type# {typeCount} method# {methodCount} {type.FullName}::{method.Name}{genericArgString}");
if (elapsedFunc != TimeSpan.MinValue)
{
Console.WriteLine($", elapsed ms: {elapsedFunc.TotalMilliseconds:F2}");
}
else
{
Console.WriteLine();
}
}
}
}
}
public override void FinishAssembly(Assembly assembly)
{
base.FinishAssembly(assembly);
if (File.Exists(markerFileName))
{
File.Delete(markerFileName);
}
}
private void WriteAndFlushNextMethodToPrepMarker()
{
int nextMethodToPrep = (methodCount + 1);
const int Tries = 10;
for (int i = 0; i < Tries; i++)
{
try
{
using (var writer = new StreamWriter(File.Create(markerFileName)))
{
writer.Write($"{nextMethodToPrep}");
}
break;
}
catch (IOException) when (i < Tries - 1)
{
Thread.Sleep((i + 1) * 100);
}
}
}
}
// Invoke the jit on exactly one method.
class PrepareOne : PrepareBase
{
public PrepareOne(int firstMethod, bool verbose, bool time) : base(firstMethod, verbose, time)
{
}
public override void StartAssembly(Assembly assembly, string assemblyPath)
{
base.StartAssembly(assembly, assemblyPath);
if (_verbose)
{
Console.WriteLine($"PrepOne for {assemblyName} method {firstMethod} ");
}
}
public override void AttemptMethod(Type type, MethodBase method)
{
if (methodCount >= firstMethod)
{
methodsPrepared++;
if (method.IsAbstract)
{
if (_verbose)
{
Console.WriteLine($"PREPONE type# {typeCount} method# {methodCount} {type.FullName}::{method.Name} - skipping (abstract)");
}
}
else if (method.ContainsGenericParameters)
{
if (_verbose)
{
Console.WriteLine($"PREPONE type# {typeCount} method# {methodCount} {type.FullName}::{method.Name} - skipping (generic parameters)");
}
}
else
{
string genericArgString = GetGenericArgumentsString(method);
if (_verbose)
{
Console.WriteLine($"PREPONE type# {typeCount} method# {methodCount} {type.FullName}::{method.Name}{genericArgString}");
}
var succeeded = TryPrepareMethod(type, method, out TimeSpan elapsedFunc);
if (_verbose || !succeeded)
{
Console.Write($"{(succeeded ? "Completed" : "Failed")} type# {typeCount} method# {methodCount} {type.FullName}::{method.Name}{genericArgString}");
if (elapsedFunc != TimeSpan.MinValue)
{
Console.WriteLine($", elapsed ms: {elapsedFunc.TotalMilliseconds:F2}");
}
else
{
Console.WriteLine();
}
}
}
}
}
public override bool FinishMethod(Type type, MethodBase method)
{
bool baseResult = base.FinishMethod(type, method);
return baseResult && (methodCount <= firstMethod);
}
}
static class GlobalMethodHolder
{
public static MethodBase[] GlobalMethodInfoSet;
public static void PopulateGlobalMethodInfoSet(MethodBase[] globalMethods)
{
GlobalMethodInfoSet = globalMethods;
}
}
// The worker is responsible for driving the visitor through the
// types and methods of an assembly.
//
// It includes the generic instantiation strategy.
class Worker
{
Visitor visitor;
int goodAssemblyCount;
int badAssemblyCount;
int nonAssemblyCount;
bool compileAndInvokeCctorsFirst;
public Worker(Visitor v, bool cctorsFirst)
{
visitor = v;
goodAssemblyCount = 0;
badAssemblyCount = 0;
nonAssemblyCount = 0;
compileAndInvokeCctorsFirst = cctorsFirst;
}
private static BindingFlags BindingFlagsForCollectingAllMethodsOrCtors = (
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Static
);
private Assembly LoadAssembly(string assemblyPath)
{
Assembly result = null;
// The core library needs special handling as it often is in fragile ngen format
if (assemblyPath.EndsWith("System.Private.CoreLib.dll", StringComparison.OrdinalIgnoreCase) || assemblyPath.EndsWith("mscorlib.dll", StringComparison.OrdinalIgnoreCase))
{
result = typeof(object).Assembly;
}
else
{
CustomLoadContext context = new CustomLoadContext(assemblyPath);
try
{
result = context.LoadAssembly(assemblyPath);
goodAssemblyCount++;
}
catch (ArgumentException)
{
Console.WriteLine($"Assembly load failure ({assemblyPath}): ArgumentException");
badAssemblyCount++;
}
catch (BadImageFormatException e)
{
Console.WriteLine($"Assembly load failure ({assemblyPath}): BadImageFormatException (is it a managed assembly?)");
Console.WriteLine(e);
nonAssemblyCount++;
}
catch (FileLoadException f)
{
Console.WriteLine($"Assembly load failure ({assemblyPath}): FileLoadException");
Console.WriteLine(f);
badAssemblyCount++;
}
catch (FileNotFoundException)
{
Console.WriteLine($"Assembly load failure ({assemblyPath}): file not found");
badAssemblyCount++;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine($"Assembly load failure ({assemblyPath}): UnauthorizedAccessException");
badAssemblyCount++;
}
}
return result;
}
static MethodBase[] GetMethods(Type t)
{
if (Object.ReferenceEquals(t, typeof(GlobalMethodHolder)))
{
return GlobalMethodHolder.GlobalMethodInfoSet;
}
MethodInfo[] mi = t.GetMethods(BindingFlagsForCollectingAllMethodsOrCtors);
ConstructorInfo[] ci = t.GetConstructors(BindingFlagsForCollectingAllMethodsOrCtors);
MethodBase[] mMI = new MethodBase[mi.Length + ci.Length];
for (int i = 0; i < mi.Length; i++)
{
mMI[i] = mi[i];
}
for (int i = 0; i < ci.Length; i++)
{
mMI[i + mi.Length] = ci[i];
}
return mMI;
}
private static List<Type> LoadTypes(Assembly assembly)
{
List<Type> result = new List<Type>();
var globalMethods = assembly.ManifestModule.GetMethods(BindingFlagsForCollectingAllMethodsOrCtors);
if (globalMethods.Length > 0)
{
GlobalMethodHolder.PopulateGlobalMethodInfoSet(globalMethods);
result.Add(typeof(GlobalMethodHolder));
}
string assemblyName = assembly.GetName().Name;
try
{
result.AddRange(assembly.GetTypes());
return result;
}
catch (ReflectionTypeLoadException e)
{
Console.WriteLine($"ReflectionTypeLoadException {assemblyName}");
Exception[] ea = e.LoaderExceptions;
foreach (Exception e2 in ea)
{
Console.WriteLine($"ReflectionTypeLoadException {assemblyName} ex: {e2.Message}");
}
if (e.Types != null)
{
foreach (Type t in e.Types)
{
if (t != null)
{
Console.WriteLine($"ReflectionTypeLoadException {assemblyName} type: {t.Name}");
}
}
}
return null;
}
catch (FileLoadException)
{
Console.WriteLine($"FileLoadException {assemblyName}");
return null;
}
catch (FileNotFoundException e)
{
string temp = e.ToString();
string[] ts = temp.Split('\'');
temp = ts[1];
Console.WriteLine($"FileNotFoundException {assemblyName} : {temp}");
return null;
}
}
public int Work(IEnumerable<string> assemblyNames)
{
int maxResult = 0;
int goodTypeCount = 0;
int badTypeCount = 0;
int goodMethodCount = 0;
int badMethodCount = 0;
DateTime startTime = DateTime.Now;
visitor.Start();
foreach (string assemblyName in assemblyNames)
{
int thisResult = Work(assemblyName);
if ((thisResult == 0) && visitor is CounterBase)
{
CounterBase counterVisitor = visitor as CounterBase;
goodTypeCount += counterVisitor.TypeCount;
goodMethodCount += counterVisitor.MethodCount;
badTypeCount += counterVisitor.UninstantiableTypeCount;
badMethodCount += counterVisitor.UninstantiableMethodCount;
}
maxResult = Math.Max(thisResult, maxResult);
}
visitor.Finish();
// Produce summary if visitor's final output is not sufficient.
if ((badAssemblyCount > 0) || (nonAssemblyCount > 0) || (goodAssemblyCount > 1))
{
DateTime stopTime = DateTime.Now;
TimeSpan totalTime = stopTime - startTime;
Console.WriteLine();
Console.WriteLine($"Overall: {goodAssemblyCount} assemblies {goodTypeCount} types {goodMethodCount} methods in {totalTime.TotalMilliseconds:F2}ms");
Console.WriteLine($" {nonAssemblyCount} non-assemblies {badAssemblyCount} skipped assemblies {badTypeCount} skipped types {badMethodCount} skipped methods");
}
return maxResult;
}
public int Work(string assemblyName)
{
string assemblyPath = Path.GetFullPath(assemblyName);
Assembly assembly = LoadAssembly(assemblyPath);
if (assembly == null)
{
return 102;
}
List<Type> types = LoadTypes(assembly);
if (types == null)
{
return 103;
}
visitor.StartAssembly(assembly, assemblyPath);
bool keepGoing = true;
foreach (Type t in types)
{
// Skip types with no jittable methods
if (t.IsInterface)
{
continue;
}
// Likewise there are no methods of interest in delegates.
if (t.IsSubclassOf(typeof(System.Delegate)))
{
continue;
}
if (t.IsGenericType)
{
List<Type> instances = GetInstances(t);
foreach (Type ti in instances)
{
keepGoing = Work(ti);
if (!keepGoing)
{
break;
}
}
}
else
{
keepGoing = Work(t);
}
if (!keepGoing)
{
break;
}
}
visitor.FinishAssembly(assembly);