chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Tap.Shared;
 
[assembly: OpenTap.PluginAssembly(true)]
namespace OpenTap
{
    /// <summary>
    /// Marks an assembly as one containing OpenTAP plugins.
    /// </summary>
    [AttributeUsage(AttributeTargets.Assembly)]
    public class PluginAssemblyAttribute : Attribute
    {
        /// <summary>
        /// Ask the <see cref="PluginSearcher"/> to also look for plugins among the internal types in this assembly (default is to only search in public types).
        /// </summary>
        public bool SearchInternalTypes { get; }
        /// <summary>
        /// (Optional) Full name of Plugin Init method that gets run before any other code in the plugin. Will only run once. 
        /// Requirement: Must be parameterless public static method returning void inside public static class
        /// Important note: If init method fails (throws an <see cref="Exception"/>), then NONE of the <see cref="ITapPlugin"/> types will load
        /// </summary>
        public string PluginInitMethod { get; }
        /// <summary>
        /// Marks an assembly as one containing OpenTAP plugins.
        /// </summary>
        /// <param name="SearchInternalTypes">True to ask the <see cref="PluginSearcher"/> to also look for plugins among the internal types in this assembly (default is to only search in public types).</param>
        public PluginAssemblyAttribute(bool SearchInternalTypes)
        {
            this.SearchInternalTypes = SearchInternalTypes;
        }
        /// <summary>
        /// Marks an assembly as one containing OpenTAP plugins.
        /// </summary>
        /// <param name="SearchInternalTypes">True to ask the <see cref="PluginSearcher"/> to also look for plugins among the internal types in this assembly (default is to only search in public types).</param>
        /// <param name="PluginInitMethod">Full name of Plugin Init method (<see cref="PluginInitMethod"/>)</param>
        public PluginAssemblyAttribute(bool SearchInternalTypes, string PluginInitMethod)
        {
            this.SearchInternalTypes = SearchInternalTypes;
            this.PluginInitMethod = PluginInitMethod;
        }
    }
 
 
    /// <summary>
    /// Searches assemblies for classes implementing ITapPlugin.
    /// </summary>
    public class PluginSearcher
    {
        private Options Option { get; set; }
 
        /// <summary>
        /// Options for Plugin Searcher.
        /// </summary>
        [Flags]
        public enum Options
        {
            /// <summary> No options </summary>
            None = 0,
            /// <summary> Allow multiple assemblies with the same name </summary>
            IncludeSameAssemblies = 1
        }
 
        /// <summary>
        /// Searches assemblies for classes implementing ITapPlugin.
        /// </summary>
        public PluginSearcher() { }
 
        internal PluginSearcher(PluginSearcher copy)
        {
            AbsorbLoadedPlugins(copy);
            if (AllTypes.TryGetValue(PluginMarkerType.Name, out var marker)) PluginMarkerType = marker;
        }
 
        /// <summary>
        /// Searches assemblies for classes implementing ITapPlugin.
        /// </summary>
        /// <param name="opts">Option setting for Plugin Searcher.</param>
        public PluginSearcher(Options opts = Options.None)
        {
            Option = opts;
        }
 
        private class AssemblyRef
        {
            public string Name;
            public Version Version;
 
            public AssemblyRef(string name, Version version)
            {
                Name = name;
                Version = version;
            }
 
            public override int GetHashCode()
            {
                return Name.GetHashCode() * 17 + Version.GetHashCode();
            }
 
            public override bool Equals(object obj)
            {
                if (obj is AssemblyRef)
                {
                    var o = obj as AssemblyRef;
                    return (Name==o.Name) && (Version==o.Version);
                }
                return base.Equals(obj);
            }
        }
 
        private static readonly TraceSource log = Log.CreateSource("Searcher");
        class AssemblyDependencyGraph
        {
            private Options Option { get; set; }
 
            public AssemblyDependencyGraph(Options opt)
            {
                nameToAsmMap = new Dictionary<AssemblyRef, AssemblyData>();
 
                nameToAsmMap2 = new Dictionary<string, AssemblyRef>();
                asmNameToAsmData = new Dictionary<string, AssemblyData>();
                Assemblies = new List<AssemblyData>();
                UnfoundAssemblies = new HashSet<AssemblyRef>();
 
                Option = opt;
            }
 
            static string VersionFromFileVersion(FileVersionInfo v)
            {
                return $"{v.FileMajorPart}.{v.FileMinorPart}.{v.FileBuildPart}";
            }
 
            /// <summary>
            /// Returns a list of assemblies and their dependencies/references. 
            /// The list is sorted such that a dependency is before the assembly/assemblies that depend on it.
            /// </summary>
            public List<AssemblyData> Generate(IEnumerable<string> files)
            {
                if (nameToFileMap == null)
                    nameToFileMap = files.ToLookup(Path.GetFileNameWithoutExtension);
                else
                {
                    var existingFiles = nameToFileMap.SelectMany(g => g.Select(s => s));
                    nameToFileMap = existingFiles.Concat(files).Distinct().ToLookup(Path.GetFileNameWithoutExtension);
                }
 
                // print a warning if the same assembly is loaded more than once.
                foreach (var entry in nameToFileMap)
                {
                    var count = entry.Count();
                    if (count == 1) continue;
                    if (entry.Key.EndsWith(".resources") && entry.Key.StartsWith("Microsoft.CodeAnalysis"))
                        continue; // This improves the performance in debug builds, where lots of locale resource files are present.
                    
                    var versions = new HashSet<string>();
                    bool allInDependencies = true;
                    foreach (var file in entry)
                    {
                        try
                        {
                            if ((Path.GetDirectoryName(file)?.Contains("Dependencies") ?? false) == false)   
                                allInDependencies = false;
                            var fileVersion = FileVersionInfo.GetVersionInfo(file);
 
                            // According to docs fileVersion is never null. Could be set to 0.0.0 though, but this is fine.
                            versions.Add(VersionFromFileVersion(fileVersion));
                        }
                        catch
                        {
                            // Accept errors here, this code is only used to print warnings.       
                        }
                    }
 
                    if (allInDependencies) continue; // these were only inside the dependencies folder.
                    if (versions.Count == 1) continue;
 
                    log.Warning("Multiple assemblies of different versions named {0} exists ", entry.Key);
 
                    int i = 0;
                    foreach (var file in entry)
                    {
                        string ver = "unknown";
                        try
                        {
                            ver = VersionFromFileVersion(FileVersionInfo.GetVersionInfo(file));
                        }
                        catch (Exception)
                        {
                            log.Debug("Unable to get version of {0}.", file);
                        }
 
                        log.Debug("Assembly {2}: {0} version: {1}", file, ver, 1 + i++);
                    }    
                }
                foreach (string file in files)
                    AddAssemblyInfo(file);
 
                return Assemblies;
            }
            
            private List<AssemblyData> Assemblies;
            private Dictionary<AssemblyRef, AssemblyData> nameToAsmMap;
            private Dictionary<string, AssemblyRef> nameToAsmMap2;
            private readonly Dictionary<string, AssemblyData> asmNameToAsmData;
            private ILookup<string, string> nameToFileMap;
            HashSet<AssemblyRef> UnfoundAssemblies; // for assemblies that are not in the files.
 
            ImmutableDictionary<Assembly, AssemblyData> assemblyToAssemblyDataLookup = ImmutableDictionary<Assembly, AssemblyData>.Empty;
 
            /// <summary>
            /// Find the AssemblyData for a specific loaded Assembly. If not found, it will analyze it and cache it.
            /// </summary>
            internal AssemblyData FindAssemblyData(Assembly asm)
            {
                if (!assemblyToAssemblyDataLookup.TryGetValue(asm, out var asmData))
                {
                    var name = asm.FullName;
                    if (asmNameToAsmData.TryGetValue(name, out var asmData2))
                    {
                        asmData = asmData2;
                    }else if (nameToAsmMap2.TryGetValue(asm.Location?.ToUpper() ?? "", out var asmRef) && nameToAsmMap.TryGetValue(asmRef, out var asmData3))
                    {
                        asmData = asmData3;
                    }
 
                    if (asmData == null)
                    {
                        foreach (var assembly in Assemblies)
                        {
                            if (assembly.GetCached() == asm)
                            {
                                asmData = assembly;
                                break;
                            }
                        }
                    }
                    if (asmData == null)
                    {
                        asmData = AddAssemblyInfo(asm.Location, asm);
                    }
                    assemblyToAssemblyDataLookup = assemblyToAssemblyDataLookup.Add(asm, asmData);
                }
                
                return asmData;
            }
            
            /// <summary> Manually analyze and add an assembly file. </summary>
            internal AssemblyData AddAssemblyInfo(string file, Assembly loadedAssembly = null)
            {
                var normalizedFile = PathUtils.NormalizePath(file);
                if (nameToAsmMap2.TryGetValue(normalizedFile, out AssemblyRef asmRef2))
                {
                    return nameToAsmMap[asmRef2];
                }
                try
                {
                    // This can happen if the plugin was uninstalled.
                    // If the plugin was loaded, it was most likely also searched if we reached this point.
                    if (!File.Exists(file)) return null;
                    if (file.Contains(".resources.dll"))
                        return null;
                    var thisAssembly = new AssemblyData(file, loadedAssembly);
                    
                    List<AssemblyRef> refNames = new List<AssemblyRef>();
                    using (FileStream str = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        if(str.Length > int.MaxValue)
                            return null; // otherwise PEReader() will throw.
                        if(str.Length < 50) 
                            return null; // Don't consider super small assemblies.
                        using (PEReader header = new PEReader(str, PEStreamOptions.LeaveOpen))
                        {
                            if (!header.HasMetadata)
                                return null;
 
                            MetadataReader metadata = header.GetMetadataReader();
                            AssemblyDefinition def = metadata.GetAssemblyDefinition();
 
                            // if we were asked to only provide distinct assembly names and 
                            // this assembly name has already been encountered, just return that.
                            var fileIdentifier = Option.HasFlag(Options.IncludeSameAssemblies) ? file : def.GetAssemblyName().FullName;
                            if (asmNameToAsmData.TryGetValue(fileIdentifier, out AssemblyData data))
                                return data;
 
                            thisAssembly.Name = metadata.GetString(def.Name);
 
                            if (string.Compare(thisAssembly.Name, Path.GetFileNameWithoutExtension(file), true) != 0)
                                throw new Exception("Assembly name does not match the file name.");
                            var thisRef = new AssemblyRef(thisAssembly.Name, def.Version);
 
                            var prov = new CustomAttributeTypeProvider();
                            foreach (CustomAttributeHandle attrHandle in def.GetCustomAttributes())
                            {
                                CustomAttribute attr = metadata.GetCustomAttribute(attrHandle);
 
                                if (attr.Constructor.Kind == HandleKind.MemberReference)
                                {
                                    var ctor = metadata.GetMemberReference((MemberReferenceHandle)attr.Constructor);
                                    string attributeFullName = GetFullName(metadata, ctor.Parent);
                                    if (attributeFullName == typeof(AssemblyInformationalVersionAttribute).FullName)
                                    {
                                        var valueString = attr.DecodeValue(prov).FixedArguments[0].Value?.ToString();
                                        if (SemanticVersion.TryParse(valueString, out _))
                                            thisAssembly.RawVersion = valueString;
                                        break;
                                    }
                                }
                            }
 
                            // If the semantic version was not set, fall back to using the version
                            // from the AssemblyDefinition
                            if (string.IsNullOrWhiteSpace(thisAssembly.RawVersion))
                            {
                                thisAssembly.RawVersion = def.Version.ToString();
                            }
 
                            thisAssembly.Version = def.Version;
 
                            if (!nameToAsmMap.ContainsKey(thisRef))
                            {
                                nameToAsmMap.Add(thisRef, thisAssembly);
                                nameToAsmMap2[PathUtils.NormalizePath(thisAssembly.Location)] = thisRef;
                            }
 
                            asmNameToAsmData[fileIdentifier] = thisAssembly;
 
                            foreach (var asmRefHandle in metadata.AssemblyReferences)
                            {
                                var asmRef = metadata.GetAssemblyReference(asmRefHandle);
                                var name = metadata.GetString(asmRef.Name);
                                var newRef = new AssemblyRef(name, asmRef.Version);
                                if (UnfoundAssemblies.Contains(newRef))
                                {
                                    continue;
                                }
                                refNames.Add(new AssemblyRef(name, asmRef.Version));
                            }
                        }
 
                        List<AssemblyData> refList = null;
                        foreach (var refName in refNames)
                        {
                            if (nameToAsmMap.TryGetValue(refName, out AssemblyData asmData2))
                            {
                                if (refList == null) refList = new List<AssemblyData>();
                                refList.Add(asmData2);
                            }
                            else
                            {
                                if (nameToFileMap.Contains(refName.Name))
                                {
                                    AssemblyData asm = null;
                                    foreach (string file2 in nameToFileMap[refName.Name])
                                    {
                                        var data = AddAssemblyInfo(file2);
                                        if (data == null) continue;
                                        if (data.Version == refName.Version)
                                        {
                                            asm = data;
                                            break;
                                        }
                                        else if (Utils.Compatible(data.Version, refName.Version))
                                        {
                                            asm = data;
                                        }
                                    }
                                    if (asm != null)
                                    {
                                        if (refList == null) refList = new List<AssemblyData>();
                                        refList.Add(asm);
                                    }
                                    else
                                    {
                                        UnfoundAssemblies.Add(refName);
                                    }
                                }
                                else
                                {
                                    UnfoundAssemblies.Add(refName);
                                }
                            }
                        }
                        thisAssembly.References = (IEnumerable<AssemblyData>) refList ?? Array.Empty<AssemblyData>();
                        Assemblies.Add(thisAssembly);
                        return thisAssembly;
                    }
                }
                catch (Exception ex)
                {
                    // there was an error loading the file. Ignore that file.
                    log.Warning("Skipping assembly '{0}'. {1}", Path.GetFileName(file), ex.Message);
                    log.Debug(ex);
                    return null;
                }
            }
        }
        
        /// <summary>
        /// The assemblies found by Search. Ordered such that referenced assemblies come before assemblies that reference them.
        /// </summary>
        public IEnumerable<AssemblyData> Assemblies;
 
        AssemblyDependencyGraph graph = null;
 
        /// <summary>
        /// Searches assembly files and returns all the plugin types found in those.
        /// The search will also populate a complete list of types searched in the AllTypes property
        /// and all Assemblies found in the Assemblies property.
        /// Subsequent calls to this method will add to those properties.
        /// </summary>
        public IEnumerable<TypeData> Search(string dir)
        {
            var finder = new AssemblyFinder() { Quiet = true, IncludeDependencies = true, DirectoriesToSearch = new[] { dir } };
            IEnumerable<string> files = finder.AllAssemblies();
 
            return Search(files);
        }
 
 
        private readonly object AddAssemblyLock = new();
        /// <summary> Adds an assembly outside the 'search' context. </summary>
        internal AssemblyData AddAssembly(string path, Assembly loadedAssembly)
        {
            // This fixes a race condition when TypeData.FromType() is called in parallel.
            lock (AddAssemblyLock)
            {
                var asm = graph.AddAssemblyInfo(path, loadedAssembly);
                PluginsInAssemblyRecursive(asm);
                return asm;
            }
        }
 
        private TypeData PluginFromPluginRecursive(TypeData type)
        {
            if (AllTypes.TryGetValue(type.Name, out var plugin)) return plugin;
            plugin = type.Clone();
 
            AllTypes.Add(plugin.Name, plugin);
            foreach (var oldBaseType in type.BaseTypes ?? [])
            {
                var basetype = PluginFromPluginRecursive(oldBaseType);
                if (basetype != null)
                {
                    basetype.AddDerivedType(plugin);
                    plugin.AddBaseType(basetype);
                    plugin.AddPluginTypes(basetype.PluginTypes);
                }
            }
 
            foreach (var oldInterfaceType in type.PluginTypes ?? [])
            {
                var @interface = PluginFromPluginRecursive(oldInterfaceType);
                if (@interface != null)
                {
                    plugin.AddPluginType(@interface);
                }
            }
 
            plugin.FinalizeCreation();
 
            if (plugin.PluginTypes != null)
            {
                PluginTypes.Add(plugin);
            }
 
            return plugin;
        }
 
        private void AbsorbLoadedPlugins(PluginSearcher searcher)
        {
            // The searcher we are currently absorbing can be mutated by calls to e.g. TypeData.FromType()
            // We need to guard against access to searcher.AllTypes while we are absorbing it.
            lock (searcher.AddAssemblyLock)
            {
                // Create new instances of all the plugins which were already loaded. 
                // This solves problems related to scanning new plugin versions after a package upgrade.
                // The current process should keep displaying information about the loaded plugin instead of whatever is on disk.
                TypeData[] alreadyLoaded = [.. searcher.AllTypes.Values.Where(x => x.IsAssemblyLoaded())];
                foreach (var m in alreadyLoaded)
                {
                    PluginFromPluginRecursive(m);
                }
            }
        }
 
        /// <summary>
        /// Searches assembly files and returns all the plugin types found in those.
        /// The search will also populate a complete list of types searched in the AllTypes property
        /// and all Assemblies found in the Assemblies property.
        /// Subsequent calls to this method will add to those properties.
        /// </summary>
        public IEnumerable<TypeData> Search(IEnumerable<string> files)
        {
            Stopwatch timer = Stopwatch.StartNew();
            graph ??= new AssemblyDependencyGraph(Option);
            Assemblies = graph.Generate(files);
            log.Debug(timer, "Ordered {0} assemblies according to references.", Assemblies.Count());
 
            foreach (AssemblyData asm in Assemblies)
            {
                PluginsInAssemblyRecursive(asm);
            }
 
            return PluginTypes;
        }
 
        internal readonly TypeData PluginMarkerType = new TypeData(typeof(ITapPlugin).FullName);
 
        private void PluginsInAssemblyRecursive(AssemblyData asm)
        {
            // This is possible if the package containing the file was uninstalled
            if (!File.Exists(asm.Location))
                return;
            CurrentAsm = asm;
            ReadPrivateTypesInCurrentAsm = false;
            TypesInCurrentAsm = new Dictionary<TypeDefinitionHandle, TypeData>();
            using (FileStream file = new FileStream(asm.Location, FileMode.Open, FileAccess.Read))
            using (PEReader header = new PEReader(file, PEStreamOptions.LeaveOpen))
            {
                CurrentReader = header.GetMetadataReader();
                
                foreach (CustomAttributeHandle attrHandle in CurrentReader.CustomAttributes)
                {
                    CustomAttribute attr = CurrentReader.GetCustomAttribute(attrHandle);
                    
                    bool isPluginAssemblyAttribute = false;
                    if (attr.Constructor.Kind == HandleKind.MethodDefinition)
                    {
                        MethodDefinition ctor = CurrentReader.GetMethodDefinition((MethodDefinitionHandle)attr.Constructor);
                        isPluginAssemblyAttribute = MatchFullName(CurrentReader, ctor.GetDeclaringType(), "OpenTap", nameof(PluginAssemblyAttribute));
                    }
                    else if (attr.Constructor.Kind == HandleKind.MemberReference)
                    {
                        var ctor = CurrentReader.GetMemberReference((MemberReferenceHandle)attr.Constructor);
                        isPluginAssemblyAttribute = MatchFullName(CurrentReader, ctor.Parent, "OpenTap", nameof(PluginAssemblyAttribute));
                    }
                    if(isPluginAssemblyAttribute)
                    {
                        var valueString = attr.DecodeValue(new CustomAttributeTypeProvider());
                        ReadPrivateTypesInCurrentAsm = (bool)valueString.FixedArguments[0].Value;
                        if (valueString.FixedArguments.Count() > 1)
                        {
                            string initMethodName = valueString.FixedArguments.ElementAt(1).Value.ToString();
                            asm.PluginAssemblyAttribute = new PluginAssemblyAttribute(ReadPrivateTypesInCurrentAsm, initMethodName);
                        }
                        else
                            asm.PluginAssemblyAttribute = new PluginAssemblyAttribute(ReadPrivateTypesInCurrentAsm);
                        break;
                    }
                }
                
                foreach (var typeDefHandle in CurrentReader.TypeDefinitions)
                {
                    try
                    {
                        PluginFromTypeDefRecursive(typeDefHandle);
                    }
                    catch
                    {
                        // fixes an issue in the plugin searcher if it tries to scan an assembly with native types in it.
                    }
                }
            }
        }
 
        /// <summary>
        /// All types found by the search indexed by their SearchAssembly.FullName.
        /// Null if PluginSearcher.Search has not been called.
        /// </summary>
        internal readonly Dictionary<string, TypeData> AllTypes = [];
 
        /// <summary>
        /// Types found by the search that implement ITapPlugin.
        /// Null if PluginSearcher.Search has not been called.
        /// </summary>
        internal readonly HashSet<TypeData> PluginTypes = [];
 
        private AssemblyData CurrentAsm;
        private bool ReadPrivateTypesInCurrentAsm = false;
        private Dictionary<TypeDefinitionHandle, TypeData> TypesInCurrentAsm;
        private MetadataReader CurrentReader;
 
 
        private TypeData PluginFromEntityRecursive(EntityHandle handle)
        {
            switch (handle.Kind)
            {
                case HandleKind.TypeReference:
                    return PluginFromTypeRef((TypeReferenceHandle)handle);
                case HandleKind.TypeDefinition:
                    return PluginFromTypeDefRecursive((TypeDefinitionHandle)handle);
                case HandleKind.TypeSpecification:
                    var baseSpec = CurrentReader.GetTypeSpecification((TypeSpecificationHandle)handle);
                    try
                    {
                        return baseSpec.DecodeSignature(new SignatureTypeProvider(this), AllTypes);
                    }
                    catch
                    {
                        return null;
                    }
                default:
                    return null;
            }
        }
 
        private TypeData PluginFromTypeRef(TypeReferenceHandle handle)
        {
            string ifaceFullName = GetFullName(CurrentReader,handle);
            if (AllTypes.TryGetValue(ifaceFullName, out var tp))
                return tp;
            return null; // This is not a type that we care about (not defined in any of the files the searcher is given)
        }
 
        private static string valueTypeName = typeof(ValueType).FullName;
        private static readonly ConcurrentDictionary<string, bool> ValueTypeMap = new ConcurrentDictionary<string, bool>(); 
        private bool IsValueType(TypeDefinition typeDef, string typeName = null)
        {
            
            bool helper(string s)
            {
                try
                {
                    if (s == valueTypeName) return true;
 
                    var baseType = typeDef.BaseType;
                    switch (baseType.Kind)
                    {
                        case HandleKind.TypeReference:
                            var tr = (TypeReferenceHandle)baseType;
                            var r = CurrentReader.GetTypeReference(tr);
                            return CurrentReader.GetString(r.Name) == "ValueType";
                        case HandleKind.TypeDefinition:
                            var td = (TypeDefinitionHandle)baseType;
                            if (td.IsNil) return false;
                            var d = CurrentReader.GetTypeDefinition(td);
                            return IsValueType(d);
                        default:
                            return false;
                    }
                }
                catch
                {
                    // This should be rare, and if the reader can't resolve some base type we can't do anything about it.
                    // Just assume it isn't a valuetype and move on.
                    return false;
                }
            }
 
            typeName ??= GetTypeName(typeDef);
            return ValueTypeMap.GetOrAdd(typeName, helper);
        }
 
        private string GetTypeName(TypeDefinition td)
        {
            string typeName;
 
            TypeDefinitionHandle declaringTypeHandle = td.GetDeclaringType();
            if (declaringTypeHandle.IsNil)
            {
                typeName = string.Format("{0}.{1}", CurrentReader.GetString(td.Namespace),
                    CurrentReader.GetString(td.Name));
            }
            else
            {
                // This is a nested type
                TypeData declaringType = PluginFromTypeDefRecursive(declaringTypeHandle);
                if (declaringType == null)
                    return null;
                typeName = string.Format("{0}+{1}", declaringType.Name, CurrentReader.GetString(td.Name));
            }
 
            return typeName;
        }
 
        private static HashSet<string> warnOnceLookup = new HashSet<string>();
        private TypeData PluginFromTypeDefRecursive(TypeDefinitionHandle handle)
        {
            if (TypesInCurrentAsm.TryGetValue(handle, out var result))
                return result;
            TypeDefinition typeDef = CurrentReader.GetTypeDefinition(handle);
            var typeAttributes = typeDef.Attributes;
            if (ReadPrivateTypesInCurrentAsm)
            {
                if ((typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic &&
                    (typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public &&
                    (typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.NestedPrivate &&
                    (typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.NestedPublic)
                    return null;
            }
            else
            {
                if ((typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public &&
                    (typeAttributes & TypeAttributes.VisibilityMask) != TypeAttributes.NestedPublic)
                    return null;
            }
 
            var typeName = GetTypeName(typeDef);
            if (typeName == null) return null;
            if (AllTypes.TryGetValue(typeName, out var existingPlugin))
            {
                if (existingPlugin.Assembly.Name == CurrentAsm.Name)
                {
                    // we assume this is the same plugin, just in another copy of the dll
 
                    // This can happen if you are creating a package with file in a subfoler. 
                    // That file will get copied, and we end up with it twice in the installation dir
                    // in that case it is important for the logic in EnumeratePlugins that this assembly also has the plugin types listed.
                    if (existingPlugin.PluginTypes != null &&
                        (CurrentAsm.PluginTypes == null || !CurrentAsm.PluginTypes.Any(t => t.Name == existingPlugin.Name)))
                    {
                        CurrentAsm.AddPluginType(existingPlugin);
                    }
                }
                else
                {
                    // DescendsTo will try to load the plugin. Manually walk the basetypes instead.
                    var basetypes = new Queue<TypeData>();
                    basetypes.Enqueue(existingPlugin);
                    bool isPlugin = false;
                    while (basetypes.Any())
                    {
                        var t = basetypes.Dequeue();
                        if (PluginMarkerType.Equals(t))
                        {
                            isPlugin = true;
                            break;
                        }
                        if (t.BaseTypes != null)
                        {
                            foreach (var bt in t.BaseTypes)
                            {
                                basetypes.Enqueue(bt);
                            }
                        }
                    }
                    if (isPlugin && existingPlugin.IsBrowsable)
                    {
                        var key = $"{typeName}-{existingPlugin.Assembly.Name}-{CurrentAsm.Name}";
                        if (warnOnceLookup.Add(key)) 
                        {
                            log.Warning($"Plugin with duplicate type name {typeName} defined in '{existingPlugin.Assembly.Name}' and '{CurrentAsm.Name}'");
                        }
                    }
                }
                return existingPlugin;
            }
            TypeData plugin = new TypeData(typeName);
            if (plugin.Name == PluginMarkerType.Name)
            {
                PluginMarkerType.Assembly = CurrentAsm;
                PluginMarkerType.TypeAttributes = typeDef.Attributes;
                AllTypes.Add(PluginMarkerType.Name, PluginMarkerType);
                TypesInCurrentAsm.Add(handle, PluginMarkerType);
                CurrentAsm.AddPluginType(PluginMarkerType);
                return PluginMarkerType;
            }
            plugin.TypeAttributes = typeDef.Attributes;
            plugin.Assembly = CurrentAsm;
 
            List<string> supportedPlatforms = null;
            foreach (CustomAttributeHandle attrHandle in typeDef.GetCustomAttributes())
            {
                CustomAttribute attr = CurrentReader.GetCustomAttribute(attrHandle);
                string attributeFullName = "";
                if (attr.Constructor.Kind == HandleKind.MethodDefinition)
                {
                    MethodDefinition ctor =
                        CurrentReader.GetMethodDefinition((MethodDefinitionHandle) attr.Constructor);
                    attributeFullName = GetFullName(CurrentReader, ctor.GetDeclaringType());
 
                }
                else if (attr.Constructor.Kind == HandleKind.MemberReference)
                {
                    var ctor = CurrentReader.GetMemberReference((MemberReferenceHandle) attr.Constructor);
                    attributeFullName = GetFullName(CurrentReader, ctor.Parent);
                }
 
                switch (attributeFullName)
                {
                    case "System.Runtime.Versioning.SupportedOSPlatformAttribute":
                    {
                        var valueString = attr.DecodeValue(new CustomAttributeTypeProvider(AllTypes));
                        if (valueString.FixedArguments.Length == 1 &&  valueString.FixedArguments[0].Value is string platform) 
                        {
                            supportedPlatforms ??= [];
                            supportedPlatforms.Add(platform);
                        }
                    }
                        break;
                    case "OpenTap.DisplayAttribute":
                    {
                        var valueString = attr.DecodeValue(new CustomAttributeTypeProvider(AllTypes));
                        string displayName =
                            GetStringIfNotNull(valueString.FixedArguments[0]
                                .Value); // the first argument to the DisplayAttribute constructor is the display name
                        string displayDescription = GetStringIfNotNull(valueString.FixedArguments[1].Value);
                        string displayGroup = GetStringIfNotNull(valueString.FixedArguments[2].Value);
                        double displayOrder = (double)valueString.FixedArguments[3].Value;
                        bool displayCollapsed = bool.Parse(GetStringIfNotNull(valueString.FixedArguments[4].Value));
                        string[] displayGroups = GetStringArrayIfNotNull(valueString.FixedArguments[5].Value);
                        DisplayAttribute attrInstance = new DisplayAttribute(displayName, displayDescription,
                            displayGroup, displayOrder, displayCollapsed, displayGroups);
                        plugin.Display = attrInstance;
                    }
                        break;
                    case "OpenTap.HelpLinkAttribute":
                    {
                        var valueString = attr.DecodeValue(new CustomAttributeTypeProvider(AllTypes));
                        if (valueString.FixedArguments.Length == 1 && valueString.FixedArguments[0].Value is string helpLink)
                        {
                            plugin.HelpLink = new HelpLinkAttribute(helpLink);
                        }
                        else
                        {
                            plugin.HelpLink = new HelpLinkAttribute();
                        }
                    }
                        break;
                    case "System.ComponentModel.BrowsableAttribute":
                    {
                        var valueString = attr.DecodeValue(new CustomAttributeTypeProvider());
                        plugin.IsBrowsable = bool.Parse(valueString.FixedArguments.First().Value.ToString());
                    }
                        break;
                    default:
                        break;
                }
            }
 
            // If the plugin type is not compatible with this platform, don't add it.
            if (supportedPlatforms != null)
            {
                bool supported = supportedPlatforms.Any(platform =>
                {
                    var cmp = StringComparison.OrdinalIgnoreCase;
                    if (platform.StartsWith("windows", cmp)) return OperatingSystem.Current == OperatingSystem.Windows;
                    if (platform.StartsWith("linux", cmp)) return OperatingSystem.Current == OperatingSystem.Linux;
                    if (platform.StartsWith("macos", cmp)) return OperatingSystem.Current == OperatingSystem.MacOS;
                    if (platform.StartsWith("osx", cmp)) return OperatingSystem.Current == OperatingSystem.MacOS;
                    return false;
                });
                if (!supported) return null;
            }
 
            TypesInCurrentAsm.Add(handle, plugin);
            AllTypes.Add(plugin.Name, plugin);
            if (!typeDef.BaseType.IsNil)
            {
                TypeData baseType = PluginFromEntityRecursive(typeDef.BaseType);
                if (baseType != null)
                {
                    baseType.AddDerivedType(plugin);
                    plugin.AddBaseType(baseType);
                    plugin.AddPluginTypes(baseType.PluginTypes);
                }
            }
 
            foreach (InterfaceImplementationHandle ifaceHandle in typeDef.GetInterfaceImplementations())
            {
                EntityHandle ifaceEntity = CurrentReader.GetInterfaceImplementation(ifaceHandle).Interface;
                TypeData iface = PluginFromEntityRecursive(ifaceEntity);
                if (iface == null)
                    continue;
                iface.AddDerivedType(plugin);
                plugin.AddBaseType(iface);
                plugin.AddPluginTypes(iface.PluginTypes);
                if (iface.Name == PluginMarkerType.Name && plugin.PluginTypes == null)
                {
                    plugin.AddPluginType(plugin); // this inherits directly from ITapPlugin (otherwise it should have been picked up earlier)
                }
            }
            plugin.FinalizeCreation();
 
            // Check if the type is constructable by inspecting the available constructors
            if (plugin.createInstanceSet == false)
            {
                // Abstract types and interfaces cannot be instantiated
                if (typeAttributes.HasFlag(TypeAttributes.Interface) || typeAttributes.HasFlag(TypeAttributes.Abstract))
                {
                    plugin.CanCreateInstance = false;
                }
                // It is not possible to instantiate types if they have unresolved generic parameters.
                // Since we are currently reflecing an unloaded assembly, it is impossible for generic parameters
                // to be resolved. If there are generic parameters, this typedata must therefore be unconstroctable.
                // Once the type is actually loaded, whether an instance can be created for resolved instances
                // of this type will be computed differently in the TypeData implementation.
                else if (typeDef.GetGenericParameters().Count != 0)
                {
                    plugin.CanCreateInstance = false;
                }
                else if (IsValueType(typeDef, typeName))
                {
                    plugin.CanCreateInstance = true;
                }
                else
                {
                    // The type can only be instantiated if it has a parameter-less constructor which does not require type arguments
                    bool hasGenericParameters(MethodDefinition m)
                    {
                        return m.GetGenericParameters().Count > 0;
                    }
 
                    bool hasParameters(MethodDefinition m)
                    {
                        return m.GetParameters().Count > 0;
                    }
                    
                    foreach (var methodHandle in typeDef.GetMethods())
                    {
                        var m = CurrentReader.GetMethodDefinition(methodHandle);
 
                        // This method is applicable if it is public, non-static, and has the RTSpecialName attribute
                        // The RTSpecialName attribute means that the method has a special significance explained by its name.
                        // All constructors will have this attribute, but most user-defined methods will not.
                        var attributes = m.Attributes;
                        var applicable = attributes.HasFlag(MethodAttributes.Public) &&
                                         attributes.HasFlag(MethodAttributes.Static) == false &&
                                         attributes.HasFlag(MethodAttributes.RTSpecialName);
 
                        if (!applicable)
                            continue;
 
                        if (CurrentReader.GetString(m.Name) != ".ctor")
                            continue;
 
                        if (hasGenericParameters(m) || hasParameters(m))
                        {
                            plugin.CanCreateInstance = false;
                            continue;
                        }
                        
                        // We know that the type is constructable, so we can stop searching.
                        plugin.CanCreateInstance = true;
                        break;
                    }
                }
            }
 
            if (plugin.PluginTypes != null)
            {
                PluginTypes.Add(plugin);
                CurrentAsm.AddPluginType(plugin);
 
                if(plugin.Assembly.RawVersion == null)
                {
                    foreach (CustomAttributeHandle attrHandle in CurrentReader.GetAssemblyDefinition().GetCustomAttributes())
                    {
                        CustomAttribute attr = CurrentReader.GetCustomAttribute(attrHandle);
                        
                        if (attr.Constructor.Kind == HandleKind.MemberReference)
                        {
                            var ctor = CurrentReader.GetMemberReference((MemberReferenceHandle)attr.Constructor);
                            string attributeFullName = GetFullName(CurrentReader, ctor.Parent);
                            if(attributeFullName == typeof(AssemblyInformationalVersionAttribute).FullName)
                            {
                                var valueString = attr.DecodeValue(new CustomAttributeTypeProvider(AllTypes));
                                plugin.Assembly.RawVersion = GetStringIfNotNull(valueString.FixedArguments[0].Value);
                            }
                        }
                    }
                }
            }
            return plugin;
        }
 
        private static string GetStringIfNotNull(object obj)
        {
            return obj?.ToString();
        }
 
        private static string[] GetStringArrayIfNotNull(object obj)
        {
            if (obj == null)
                return null;
            return (obj as IEnumerable<CustomAttributeTypedArgument<TypeData>>).Select(o => o.Value.ToString()).ToArray();
        }
 
        /// <summary>
        /// Helper to get the full name (namespace + name) of the type referenced by a TypeDefinitionHandle or TypeReferenceHandle
        /// </summary>
        static string GetFullName(MetadataReader metadata, EntityHandle handle)
        {
            switch (handle.Kind)
            {
                case HandleKind.TypeDefinition:
                    var def = metadata.GetTypeDefinition((TypeDefinitionHandle)handle);
                    return String.Format("{0}.{1}", metadata.GetString(def.Namespace), metadata.GetString(def.Name));
                case HandleKind.TypeReference:
                    var r = metadata.GetTypeReference((TypeReferenceHandle)handle);
                    return String.Format("{0}.{1}", metadata.GetString(r.Namespace), metadata.GetString(r.Name));
                //case HandleKind.TypeSpecification:
                //    var s = metadata.GetTypeSpecification((TypeSpecificationHandle)handle);
                //    s.DecodeSignature(new CustomAttributeTypeProvider(), null);
                //    return new PluginType ();
                default:
                    return null;
            }
        }
 
        bool MatchFullName(MetadataReader metadata, EntityHandle handle, string matchNamespace, string matchName)
        {
            switch (handle.Kind)
            {
                case HandleKind.TypeDefinition:
                var def = metadata.GetTypeDefinition((TypeDefinitionHandle)handle);
                return metadata.GetString(def.Namespace) == matchNamespace && metadata.GetString(def.Name) == matchName;
                case HandleKind.TypeReference:
                var r = metadata.GetTypeReference((TypeReferenceHandle)handle);
                return metadata.GetString(r.Namespace) == matchNamespace && metadata.GetString(r.Name) == matchName;
                default:
                    return false;
            }
        }
        
        #region Providers needed by the Metadata API (not really important the way we use the API)
        struct CustomAttributeTypeProvider : ICustomAttributeTypeProvider<TypeData>
        {
            private Dictionary<string, TypeData> _types;
 
            public CustomAttributeTypeProvider(Dictionary<string, TypeData> types)
            {
                _types = types;
            }
 
            public TypeData GetPrimitiveType(PrimitiveTypeCode typeCode)
            {
                return null;
            }
 
            public TypeData GetSystemType()
            {
                return _types["System.Type"];
            }
 
            public TypeData GetSZArrayType(TypeData elementType)
            {
                return null;
            }
 
            public TypeData GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
            {
                string fullName = GetFullName(reader,handle);
                return _types[fullName];
            }
 
            public TypeData GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
            {
                string fullName = GetFullName(reader, handle);
                return _types[fullName];
            }
 
            public TypeData GetTypeFromSerializedName(string name)
            {
                if (name == null)
                    return null;
 
                return _types[name];
            }
 
            public PrimitiveTypeCode GetUnderlyingEnumType(TypeData type)
            {
                throw new NotImplementedException();
            }
 
            public bool IsSystemType(TypeData type)
            {
                return type.Name == "System.Type";
            }
        }
 
        class SignatureTypeProvider : ISignatureTypeProvider<TypeData, Dictionary<string, TypeData>>
        {
            private readonly PluginSearcher _Searcher;
            public SignatureTypeProvider(PluginSearcher searcher)
            {
                _Searcher = searcher;
            }
 
            public TypeData GetArrayType(TypeData elementType, ArrayShape shape)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetByReferenceType(TypeData elementType)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetFunctionPointerType(MethodSignature<TypeData> signature)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetGenericInstantiation(TypeData genericType, ImmutableArray<TypeData> typeArguments)
            {
                return genericType;
            }
 
            public TypeData GetGenericMethodParameter(Dictionary<string, TypeData> genericContext, int index)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetGenericTypeParameter(Dictionary<string, TypeData> genericContext, int index)
            {
                return null;
            }
 
            public TypeData GetModifiedType(TypeData modifier, TypeData unmodifiedType, bool isRequired)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetPinnedType(TypeData elementType)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetPointerType(TypeData elementType)
            {
                throw new NotImplementedException();
            }
 
            public TypeData GetPrimitiveType(PrimitiveTypeCode typeCode)
            {
                return new TypeData("System." + typeCode);
            }
 
            public TypeData GetSZArrayType(TypeData elementType)
            {
                return elementType != null ? new TypeData(elementType.Name) : null;
            }
 
            public TypeData GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
            {
                return _Searcher.PluginFromTypeDefRecursive(handle);
            }
 
            public TypeData GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
            {
                return _Searcher.PluginFromTypeRef(handle);
            }
 
            public TypeData GetTypeFromSpecification(MetadataReader reader, Dictionary<string, TypeData> genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
            {
                throw new NotImplementedException();
            }
        }
        #endregion
        internal AssemblyData GetAssemblyData(Assembly asm) => graph.FindAssemblyData(asm);
    
    }
}