This repository has been archived by the owner on Mar 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 165
/
ILMerge.cs
2494 lines (2445 loc) · 108 KB
/
ILMerge.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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 System;
using System.IO;
using System.Compiler;
using System.Collections;
using System.Text.RegularExpressions;
using AssemblyResolving;
namespace ILMerging {
/// <summary>
/// ILMerge is a class containing members and methods for
/// merging multiple .NET assemblies into a single assembly.
/// </summary>
public class ILMerge {
#region Private Variables
private Class hiddenClass = null;
private AssemblyNode targetAssembly = null;
private Duplicator d = null;
private string[] directories = null;
private ArrayList searchDirs = new ArrayList();
private bool log = false;
private string logFile = null;
private Kind targetKind = Kind.SameAsPrimaryAssembly;
private string outputFileName = null;
private ArrayList assemblyNames = null;
private bool keyfileSpecified = false;
private string keyfile = null;
private bool keyContainerSpecified = false;
private string keyContainer = null;
private bool strongNameLost = false;
private bool closed = false;
private bool debugInfo = true;
private bool shortB = false;
private bool internalize = false;
private string excludeFile = "";
private ArrayList exemptionList = null;
private System.Version version = null;
private string attributeFileName = null;
private AssemblyNode attributeAssembly = null;
private bool copyattrs = false;
private bool allowMultipleAssemblyLevelAttributes = false;
private bool keepFirstOfMultipleAssemblyLevelAttributes = false;
private bool copyXmlDocumentation = false;
#if CROSSPLATFORM
/// <summary>
/// clrVersion is the string that is needed by SetTargetPlatform
/// to indicate which version of the CLR the output should run under.
/// </summary>
protected string clrVersion = null;
/// <summary>
/// clrDir is the string containing the path to the directory
/// the Framework assemblies can be found in for the version
/// indicated by clrVersion. It is also passed to SetTargetPlatform.
/// </summary>
protected string clrDir = null;
/// <summary>
/// Records whether the /targetplatform option was given by the user on
/// the command line. It isn't currently settable via the object model
/// since in that case a user just calls SetTargetPlatform directly.
/// </summary>
protected bool targetPlatformSpecified = false;
#endif
private bool usePublicKeyTokensForAssemblyReferences = true;
private bool allowZeroPeKind = false;
private bool allowWildCards = false;
private bool delaySign = false;
/// <summary>
/// Used to represent the set of names of types to allow duplicates of.
/// This was first implemented to allow assemblies obfuscated by Dotfuscator
/// to be merged because that tool adds the definition of an attribute to
/// each output assembly. The definitions are all identical and are not referenced
/// from anywhere, so renaming this particular public type doesn't matter.
/// </summary>
private Hashtable/*string -> bool*/ typesToAllowDuplicatesOf = new Hashtable();
/// <summary>
/// If this is true, then all public types are allowed to have duplicates; the duplicates
/// are just renamed.
/// </summary>
private bool allowAllDuplicates = false;
private bool unionMerge = false;
private Hashtable typeList = new Hashtable();
private ArrayList memberList;
private ArrayList resourceList = new ArrayList();
private int fileAlignment = 512; // default in Writer
#region External Visitor (Internal builds only)
#if INTERNAL
private StandardVisitor externalVisitor = null;
#endif
#endregion
/// <summary>
/// The string shown to the user when there is an error detected in the command line.
/// </summary>
protected virtual string UsageString {
get {
return
#if CROSSPLATFORM
"Usage: ilmerge [/lib:directory]* [/log[:filename]] [/keyfile:filename | /keycontainer:containername [/delaysign]] [/internalize[:filename]] [/t[arget]:(library|exe|winexe)] [/closed] [/ndebug] [/ver:version] [/copyattrs [/allowMultiple] [/keepFirst]] [/xmldocs] [/attr:filename] [/targetplatform:<version>[,<platformdir>] | /v1 | /v1.1 | /v2 | /v4] [/useFullPublicKeyForReferences] [/wildcards] [/zeroPeKind] [/allowDup:type]* [/union] [/align:n] /out:filename <primary assembly> [<other assemblies>...]";
#else
"Usage: ilmerge [/lib:directory]* [/log[:filename]] [/keyfile:filename | /keycontainer:containername [/delaysign]] [/internalize[:filename]] [/t[arget]:(library|exe|winexe)] [/closed] [/ndebug] [/ver:version] [/copyattrs [/allowMultiple] [/keepFirst]] [/xmldocs] [/attr:filename] [/useFullPublicKeyForReferences] [/wildcards] [/zeroPeKind] [/allowDup:type]* [/union] [/align:n] /out:filename <primary assembly> [<other assemblies>...]";
#endif
}
}
#endregion
#region Private Methods
private class CloseAssemblies {
Hashtable visitedAssemblies = new Hashtable();
internal Hashtable assembliesToBeAdded = new Hashtable();
private Hashtable currentlyActiveAssemblies = new Hashtable();
AssemblyNodeList initialAssemblies = null;
internal CloseAssemblies(AssemblyNodeList assems) {
initialAssemblies = assems;
for (int i = 0, n = assems.Count; i < n; i++) {
visitedAssemblies[assems[i].UniqueKey] = assems[i];
}
}
internal void Visit(AssemblyNode a) {
if (visitedAssemblies[a.UniqueKey] != null)
return; // all of a's references (transitively closed) have been visited and a has been considered
this.currentlyActiveAssemblies.Add(a.UniqueKey, a);
if (a.AssemblyReferences == null)
goto End;
for (int i = 0, n = a.AssemblyReferences.Count; i < n; i++) {
AssemblyNode refAssembly = a.AssemblyReferences[i].Assembly;
if (this.currentlyActiveAssemblies[refAssembly.UniqueKey] != null)
// don't chase back edges!! infinite recursion from
// cyclic references!!
continue;
else
Visit(refAssembly);
}
// if any of a's direct references have been added to the list
// then add a too.
for (int i = 0, n = a.AssemblyReferences.Count; i < n; i++) {
if (assembliesToBeAdded[a.AssemblyReferences[i].Assembly.UniqueKey] != null) {
assembliesToBeAdded[a.UniqueKey] = a;
goto End;
}
}
// if any of a's direct references are in the initial set of assemblies,
// then add a too.
for (int i = 0, n = a.AssemblyReferences.Count; i < n; i++) {
for (int j = 0, m = initialAssemblies.Count; j < m; j++) {
if (a.AssemblyReferences[i].Assembly.StrongName.CompareTo(initialAssemblies[j].StrongName) == 0) {
assembliesToBeAdded[a.UniqueKey] = a;
goto End; // no need to look any further
}
}
}
End:
visitedAssemblies[a.UniqueKey] = a; // record that a has been visited
this.currentlyActiveAssemblies.Remove(a.UniqueKey); // but is no longer in the current stack trace
return;
}
}
private AssemblyNode CreateTargetAssembly(string outputAssemblyName, ModuleKindFlags kind) {
AssemblyNode assem = new AssemblyNode();
assem.Name = outputAssemblyName;
assem.Kind = kind;
if (assem != null) assem.Version = new Version(0, 0, 0, 0);
assem.ModuleReferences = new ModuleReferenceList();
var doc = new System.Xml.XmlDocument();
doc.XmlResolver = null;
assem.Documentation = doc;
assem.AssemblyReferences = new AssemblyReferenceList();
TypeNodeList types = assem.Types = new TypeNodeList();
hiddenClass = new Class(
assem,
null,
null,
TypeFlags.Public,
Identifier.Empty,
Identifier.For("<Module>"),
null,
new InterfaceList(),
new MemberList(0));
types.Add(hiddenClass);
return assem;
}
private bool ExemptType(TypeNode t) {
if (exemptionList == null)
return false;
foreach (Regex r in exemptionList) {
Match m = r.Match(t.FullName);
if (m.Success)
return true;
m = r.Match("[" + t.DeclaringModule.Name + "]" + t.FullName);
if (m.Success)
return true;
}
return false;
}
/// <summary>
/// Call this method once for each namespace (top-level) type in an assembly!
/// Do not call it on nested types!
///
/// There is a very special case where in one assembly a type C declares a method m
/// that is FamilyOrAssembly and in another assembly, a type D extends C and overrides
/// the method as just Family and now both C and D are going to be in the merged assembly.
/// Since C.m was exported as just Family, it worked when D was in a different assembly,
/// but when they live in the same assembly, it means that D.m is less accessible than
/// the method it is overriding and the type fails to load.
/// </summary>
/// <param name="t">
/// Namespace type to recursively visit.
/// </param>
/// <param name="assemblyComVisibleAttribute">
/// When this is non-null then the type t comes from an assembly whose assembly-level
/// specification for the ComVisible attribute is not the same as the assembly-level
/// attribute that will be put onto the target assembly. In that case, if it is public,
/// then the type needs to be marked with the attribute so it doesn't inherit the
/// target assembly's assembly-level specification.
/// But do this only if the type is not explicitly marked with the attribute.
/// If it does then it doesn't inherit the assembly-level specification anyway.
/// This needs to be done only at the namespace type level: this method will make
/// sure that all of them are marked so then any nested types inherit those markings.
/// </param>
private void AdjustAccessibilityAndPossiblyMarkWithComVisibleAttribute(TypeNode t, AttributeNode assemblyComVisibleAttribute) {
if (assemblyComVisibleAttribute != null && t.IsPublic && t.GetAttribute(SystemTypes.ComVisibleAttribute) == null) {
t.Attributes.Add(assemblyComVisibleAttribute);
}
for (int i = 0, n = t.Members.Count; i < n; i++) {
TypeNode nestedType = t.Members[i] as TypeNode;
if (nestedType != null) {
// never need to mark nested types: they will inherit marking from namespace type
AdjustAccessibilityAndPossiblyMarkWithComVisibleAttribute(nestedType, null);
continue; // below code is for members that are not types
}
Method m = t.Members[i] as Method;
if (m == null) continue;
bool newSlot = (m.Flags & MethodFlags.NewSlot) != 0;
if (!(m.IsVirtual && m.IsFamily && !newSlot))
continue;
// now need to go find the method it is overriding
// need to look all the way up the inheritance chain because it may not be the
// closest supertype's declaration that causes this method to have its accessibility
// adjusted.
TypeNode baseType = t.BaseType;
while (baseType != null) {
Method overridenMethod = baseType.GetImplementingMethod(m, false); // don't look up the chain, doing that explicitly
if (overridenMethod != null && overridenMethod.IsFamilyOrAssembly
&& overridenMethod.DeclaringType.DeclaringModule == m.DeclaringType.DeclaringModule) {
m.Flags |= MethodFlags.FamORAssem;
break; // once its accessibility has been changed, it would never get changed back, so quit searching
}
baseType = baseType.BaseType;
}
}
}
private bool MergeInAssembly(AssemblyNode a, bool makeNonPublic, bool targetAssemblyIsComVisible) {
#region Check for name conflicts
// first, make sure there are no name conflicts. It suffices to
// just check the top-level names since all nested types are
// qualified by their declaring types.
// start at Type[1] because Type[0] is the special <Module>
// class which is treated specially below.
// If a top-level type is a duplicate, but is not public, then
// it is safe to just give it a new name since it
// cannot be referred to from outside of the target assembly anyway.
// At the user's discretion, they can decide whether there are any public types they don't mind
// having duplicates of. Primarily useful for obfuscators that define the same attribute name
// in each obfuscated assembly, but the attribute is used only as an assembly-level attribute
// (which probably gets lost during merging anyway unless it is on the primary assembly).
for (int i = 1, n = a.Types.Count; i < n; i++) {
TypeNode t = a.Types[i];
TypeNode duplicate = targetAssembly.GetType(t.Namespace, t.Name);
if (duplicate != null) {
if (!t.IsPublic || this.allowAllDuplicates || this.typesToAllowDuplicatesOf.ContainsKey(t.Name.Name)) {
string oldName = t.Name.Name;
string newName;
if (IsCompilerGenerated(t))
newName = a.Name + "." + oldName;
else
newName = a.Name + a.UniqueKey.ToString() + "." + oldName;
WriteToLog("Duplicate type name: modifying name of the type '{0}' (from assembly '{1}') to '{2}'",
t.FullName, t.DeclaringModule.Name, newName);
Identifier newId = Identifier.For(newName);
TypeNode dup = (TypeNode)d.DuplicateFor[t.UniqueKey];
if (dup == null)
t.Name = newId; // t hasn't been duplicated yet
else
dup.Name = newId; // t has been duplicated already
#region If a type is renamed, rename any associated resource
for (int j = 0, m = a.Resources.Count; j < m; j++) {
Resource r = a.Resources[j];
if (r.Name.Equals(oldName + ".resources")) {
WriteToLog("Duplicate resource name: modifying name of the resource '{0}' (from assembly '{1}') to '{2}.resources'",
r.Name, t.DeclaringModule.Name, newName);
r.Name = newName + ".resources";
a.Resources[j] = r;
//WriteToLog("\tResource: " + r.Name);
break; // at most one resource can have the same name?
}
}
#endregion If a type is renamed, rename any associated resource
} else {
string msg = String.Format("ERROR!!: Duplicate type '{0}' found in assembly '{1}'. Do you want to use the /allowDup option?",
t.FullName, t.DeclaringModule.Name);
WriteToLog(msg);
throw new InvalidOperationException("ILMerge.Merge: " + msg);
}
}
}
#endregion
#region Process the first type, <Module>, specially
// according to Herman Venter:
// The first type of each and every assembly is always the class
// <Module>. Take its members and add them to the <Module> class
// in the target assembly; that class was created when the target
// assembly was created.
if (a.Types[0].Members != null && a.Types[0].Members.Count > 0) {
TypeNode tempTypeNode = d.TargetType;
d.TargetType = hiddenClass;
for (int i = 0, n = a.Types[0].Members.Count; i < n; i++) {
Member newMember = (Member)d.Visit(a.Types[0].Members[i]);
hiddenClass.Members.Add(newMember);
}
d.TargetType = tempTypeNode;
}
#endregion
#region Deal with [ComVisible] and security attributes
var thisAssemblyIsComVisible = GetComVisibleSettingForAssembly(a);
AttributeNode assemblyComVisibleAttribute = null;
if (thisAssemblyIsComVisible != targetAssemblyIsComVisible) {
InstanceInitializer ctor = SystemTypes.ComVisibleAttribute.GetConstructor(SystemTypes.Boolean);
assemblyComVisibleAttribute = new AttributeNode(new MemberBinding(null, ctor), new ExpressionList(new Literal(thisAssemblyIsComVisible, SystemTypes.Boolean)));
}
for (int i = 0, n = a.Attributes == null ? 0 : a.Attributes.Count; i < n; i++) {
AttributeNode aNode = a.Attributes[i];
if (aNode == null) continue;
if (aNode.Type == SystemTypes.ComVisibleAttribute) {
a.Attributes[i] = null;
continue;
}
if (aNode.Type == SystemTypes.SecurityCriticalAttribute
|| aNode.Type == SystemTypes.SecurityTransparentAttribute
|| aNode.Type == SystemTypes.AllowPartiallyTrustedCallersAttribute
|| aNode.Type.FullName.Equals("System.Security.SecurityRules")
) {
WriteToLog("Assembly level attribute '{0}' from assembly '{1}' being deleted from target assembly",
aNode.Type.FullName, a.Name);
a.Attributes[i] = null;
continue;
}
}
#endregion
#region Process all other types in the assembly
// for all of the other types move the entire type into the target assembly,
// possibly changing its visibility.
for (int i = 1, n = a.Types.Count; i < n; i++) {
TypeNode oldType = a.Types[i];
Node newType = d.Visit(oldType); // If something went wrong then it doesn't return a TypeNode
TypeNode tn = newType as TypeNode;
if (tn != null) {
if (makeNonPublic) {
if (
tn.DeclaringType == null // only change the visibility of assembly-level types
&& !ExemptType(oldType)
) {
if ((tn.Flags & TypeFlags.VisibilityMask) == TypeFlags.Public)
tn.Flags &= ~TypeFlags.Public;
}
}
this.AdjustAccessibilityAndPossiblyMarkWithComVisibleAttribute(tn, assemblyComVisibleAttribute); // recursively walks down into all nested types
targetAssembly.Types.Add(tn);
}
}
#endregion
#region Merge in any assembly-level attributes, overriding matching attributes
// But only if option is explicitly set and if an attribute assembly is not being used.
if (copyattrs && attributeAssembly == null) {
#region Regular Attributes
AttributeList attrs = d.VisitAttributeList(a.Attributes);
MergeAttributeLists(this.targetAssembly.Attributes, attrs, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
#endregion
#region Security Attributes
// For security attributes, need to merge in the permission attributes within each
// "bundle" keyed by the Action
SecurityAttributeList secAttrs = d.VisitSecurityAttributeList(a.SecurityAttributes);
for (int i = 0, n = secAttrs.Count; i < n; i++) {
SecurityAttribute secAttr = secAttrs[i];
System.Security.Permissions.SecurityAction action = secAttr.Action;
// first, see if the targetAssembly already has a security attribute with the same action
int j = 0;
int m = targetAssembly.SecurityAttributes.Count;
while (j < m) {
if (targetAssembly.SecurityAttributes[j].Action == action) {
break;
}
j++;
}
if (j == m) { // not found: this is a new action, so just add it
targetAssembly.SecurityAttributes.Add(secAttr);
} else { // need to walk the permission attributes inside of this security attribute
AttributeList existingList = targetAssembly.SecurityAttributes[j].PermissionAttributes;
AttributeList currentAssemblyList = secAttr.PermissionAttributes;
MergeAttributeLists(existingList, currentAssemblyList, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
}
}
#endregion
#region Module Attributes
attrs = d.VisitAttributeList(a.ModuleAttributes);
MergeAttributeLists(this.targetAssembly.ModuleAttributes, attrs, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
#endregion
}
#endregion
#region Copy the resources over into the target assembly
for (int i = 0, n = a.Resources.Count; i < n; i++) {
Resource r = a.Resources[i];
//WriteToLog("\tResource: " + r.Name);
//if (r.Name.EndsWith(".licenses")){
// char[] foo = new char[r.Data.Length];
// for (int j = 0, m = r.Data.Length; j < m; j++) {
// foo[j] = (char)r.Data[j];
// }
// WriteToLog("\t\t" + foo.ToString());
//}
targetAssembly.Resources.Add(r);
}
#endregion
return true;
}
private bool IsCompilerGenerated(TypeNode t) {
return GetAttributeByName(t, "System.Runtime.CompilerServices.CompilerGeneratedAttribute") != null;
}
private static AttributeNode/*?*/ GetAttributeByName(TypeNode typeNode, string name) {
for (int i = 0, n = typeNode.Attributes == null ? 0 : typeNode.Attributes.Count; i < n; i++) {
AttributeNode aNode = typeNode.Attributes[i];
if (aNode == null) continue;
if (aNode.Type.FullName.Equals(name)) {
return aNode;
}
}
return null;
}
private static bool GetComVisibleSettingForAssembly(AssemblyNode a) {
bool isComVisible = true; // default value of ctor for [ComVisible]
for (int i = 0, n = a.Attributes == null ? 0 : a.Attributes.Count; i < n; i++) {
AttributeNode aNode = a.Attributes[i];
if (aNode == null) continue;
if (aNode.Type == SystemTypes.ComVisibleAttribute) {
if (aNode.Expressions != null && 0 < aNode.Expressions.Count) {
Literal l = aNode.Expressions[0] as Literal;
if (l != null && l.Type == SystemTypes.Boolean) {
isComVisible = (bool)l.Value;
}
}
}
}
return isComVisible;
}
private bool FuzzyEqual(TypeNode t1, TypeNode t2)
{
return t1 == t2 ||
(t1 != null &&
t2 != null &&
t1.Namespace != null &&
t2.Namespace != null &&
t1.Name != null &&
t2.Name != null &&
t1.Namespace.Name == t2.Namespace.Name &&
t1.Name.Name == t2.Name.Name);
}
private bool FuzzyEqual (ParameterList xs, ParameterList ys) {
if (xs.Count != ys.Count) return false;
for (int i = 0, n = xs.Count; i < n; i++) {
if (!FuzzyEqual(xs[i].Type, ys[i].Type)) return false;
}
return true;
}
private Member FuzzilyGetMatchingMember (TypeNode t, Member m) {
MemberList ml = t.GetMembersNamed(m.Name);
for (int i = 0, n = ml.Count; i < n; i++) {
Member mem = ml[i];
// type case statement would be *so* nice right now
if (mem.NodeType != m.NodeType) continue;
Method x = mem as Method; // handles regular Methods and InstanceInitializers
if (x != null){
if (FuzzyEqual(((Method)m).Parameters, x.Parameters)) return mem; else continue;
}
if (m.NodeType == NodeType.Field) {
if (FuzzyEqual(((Field)m).Type, ((Field)mem).Type)) return mem; else continue;
}
if (m.NodeType == NodeType.Event) {
if (FuzzyEqual(((Event)m).HandlerType, ((Event)mem).HandlerType)) return mem; else continue;
}
if (m.NodeType == NodeType.Property) {
if (FuzzyEqual(((Property)m).Type, ((Property)mem).Type)) return mem; else continue;
}
TypeNode otherT = mem as TypeNode; // handles Class, Interface, etc.
if (otherT != null) {
if (FuzzyEqual((TypeNode)m, otherT)) return mem; else continue;
}
System.Diagnostics.Debug.Assert(false, "Pseudo-typecase failed to find a match");
}
return null;
}
private bool MergeInAssembly_Union(AssemblyNode a, bool targetAssemblyIsComVisible) {
#region Process the first type, <Module>, specially
// according to Herman Venter:
// The first type of each and every assembly is always the class
// <Module>. Take its members and add them to the <Module> class
// in the target assembly; that class was created when the target
// assembly was created.
if (a.Types[0].Members != null && a.Types[0].Members.Count > 0) {
TypeNode tempTypeNode = d.TargetType;
d.TargetType = hiddenClass;
for (int i = 0, n = a.Types[0].Members.Count; i < n; i++) {
Member newMember = (Member)d.Visit(a.Types[0].Members[i]);
if (!hiddenClass.Members.Contains(newMember)) {
hiddenClass.Members.Add(newMember);
}
}
d.TargetType = tempTypeNode;
}
#endregion
#region Deal with [ComVisible]
var thisAssemblyIsComVisible = GetComVisibleSettingForAssembly(a);
AttributeNode assemblyComVisibleAttribute = null;
if (thisAssemblyIsComVisible != targetAssemblyIsComVisible) {
InstanceInitializer ctor = SystemTypes.ComVisibleAttribute.GetConstructor(SystemTypes.Boolean);
assemblyComVisibleAttribute = new AttributeNode(new MemberBinding(null, ctor), new ExpressionList(new Literal(thisAssemblyIsComVisible, SystemTypes.Boolean)));
}
for (int i = 0, n = a.Attributes == null ? 0 : a.Attributes.Count; i < n; i++) {
AttributeNode aNode = a.Attributes[i];
if (aNode == null) continue;
if (aNode.Type == SystemTypes.ComVisibleAttribute) {
a.Attributes[i] = null;
continue;
}
if (aNode.Type == SystemTypes.SecurityCriticalAttribute
|| aNode.Type == SystemTypes.SecurityTransparentAttribute
|| aNode.Type == SystemTypes.AllowPartiallyTrustedCallersAttribute
|| aNode.Type.FullName.Equals("System.Security.SecurityRules")
) {
WriteToLog("Assembly level attribute '{0}' from assembly '{1}' being deleted from target assembly",
aNode.Type.FullName, a.Name);
a.Attributes[i] = null;
continue;
}
}
#endregion
#region Process all other types in the assembly
// for all of the other types move the entire type into the target assembly,
// possibly changing its visibility.
FuzzilyForwardReferencesFromSource2Target(this.targetAssembly, a);
for (int i = 1, n = a.Types.Count; i < n; i++) {
TypeNode currentType = a.Types[i];
TypeNode targetType = targetAssembly.GetType(currentType.Namespace, currentType.Name);
if (targetType != null) {
memberList = (ArrayList)typeList[currentType.DocumentationId.ToString()];
TypeNode savedTargetType = d.TargetType;
d.TargetType = targetType;
for (int j = 0, o = currentType.Members.Count; j < o; j++) {
Member currentMember = currentType.Members[j];
if (!memberList.Contains(currentMember.DocumentationId.ToString())) {
Member newMember = d.Visit(currentMember) as Member;
if (newMember != null) {
targetType.Members.Add(newMember);
memberList.Add(currentMember.DocumentationId.ToString());
}
}
}
d.TargetType = savedTargetType;
} else {
if (d.TypesToBeDuplicated[currentType.UniqueKey] == null) {
d.FindTypesToBeDuplicated(new TypeNodeList(currentType));
}
Node newType = d.Visit(currentType); // If something went wrong then it doesn't return a TypeNode
TypeNode newTypeNode = newType as TypeNode;
if (newTypeNode != null) {
this.AdjustAccessibilityAndPossiblyMarkWithComVisibleAttribute(newTypeNode, assemblyComVisibleAttribute); // recursively walks down into all nested types
targetAssembly.Types.Add(newTypeNode);
memberList = new ArrayList();
for (int j = 0; j < currentType.Members.Count; j++) {
memberList.Add(newTypeNode.Members[j].DocumentationId.ToString());
}
typeList.Add(newTypeNode.DocumentationId.ToString(), memberList);
}
}
}
#endregion
#region Merge in any assembly-level attributes, overriding matching attributes
// But only if option is explicitly set and if an attribute assembly is not being used.
if (copyattrs && attributeAssembly == null) {
#region Regular Attributes
AttributeList attrs = d.VisitAttributeList(a.Attributes);
MergeAttributeLists(this.targetAssembly.Attributes, attrs, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
#endregion
#region Security Attributes
// For security attributes, need to merge in the permission attributes within each
// "bundle" keyed by the Action
SecurityAttributeList secAttrs = d.VisitSecurityAttributeList(a.SecurityAttributes);
for (int i = 0, n = secAttrs.Count; i < n; i++) {
SecurityAttribute secAttr = secAttrs[i];
System.Security.Permissions.SecurityAction action = secAttr.Action;
// first, see if the targetAssembly already has a security attribute with the same action
int j = 0;
int m = targetAssembly.SecurityAttributes.Count;
while (j < m) {
if (targetAssembly.SecurityAttributes[j].Action == action) {
break;
}
j++;
}
if (j == m) { // not found: this is a new action, so just add it
targetAssembly.SecurityAttributes.Add(secAttr);
}
else { // need to walk the permission attributes inside of this security attribute
AttributeList existingList = targetAssembly.SecurityAttributes[j].PermissionAttributes;
AttributeList currentAssemblyList = secAttr.PermissionAttributes;
MergeAttributeLists(existingList, currentAssemblyList, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
}
}
#endregion
#region Module Attributes
attrs = d.VisitAttributeList(a.ModuleAttributes);
MergeAttributeLists(this.targetAssembly.ModuleAttributes, attrs, this.allowMultipleAssemblyLevelAttributes, this.keepFirstOfMultipleAssemblyLevelAttributes);
#endregion
}
#endregion
#region Copy the resources over into the target assembly
for (int i = 0, n = a.Resources.Count; i < n; i++) {
Resource r = a.Resources[i];
if (!resourceList.Contains(r.Name)) {
targetAssembly.Resources.Add(r);
resourceList.Add(r.Name);
}
}
#endregion
return true;
}
private void FuzzilyForwardReferencesFromSource2Target (AssemblyNode targetAssembly, AssemblyNode sourceAssembly) {
for (int i = 1, n = sourceAssembly.Types.Count; i < n; i++) {
TypeNode currentType = sourceAssembly.Types[i];
TypeNode targetType = targetAssembly.GetType(currentType.Namespace, currentType.Name);
if (targetType == null) {
if (d.TypesToBeDuplicated[currentType.UniqueKey] == null) {
d.FindTypesToBeDuplicated(new TypeNodeList(currentType));
}
} else {
d.DuplicateFor[currentType.UniqueKey] = targetType;
for (int j = 0, o = currentType.Members.Count; j < o; j++) {
Member currentMember = currentType.Members[j];
Member existingMember = FuzzilyGetMatchingMember(targetType, currentMember);
if (existingMember != null)
d.DuplicateFor[currentMember.UniqueKey] = existingMember;
}
}
}
//for (int i = 0, n = sourceAssembly.AssemblyReferences == null ? 0 : sourceAssembly.AssemblyReferences.Count; i < n; i++) {
// AssemblyNode sourceExternalReference = sourceAssembly.AssemblyReferences[i].Assembly;
// if (sourceExternalReference == null) continue;
// for (int j = 0, m = targetAssembly.AssemblyReferences == null ? 0 : targetAssembly.AssemblyReferences.Count; j < m; j++) {
// AssemblyNode targetExternalReference = targetAssembly.AssemblyReferences[j].Assembly;
// if (targetExternalReference == null) continue;
// if (sourceExternalReference.Name == targetExternalReference.Name) {
// // This depends on there *NOT* being circular references!
// FuzzilyForwardReferencesFromSource2Target(targetExternalReference, sourceExternalReference);
// break;
// }
// }
//}
}
private void MergeAttributeLists(AttributeList targetList, AttributeList sourceList, bool allowMultiples, bool keepFirst)
{
var targetIsExe = this.targetAssembly.Kind == ModuleKindFlags.ConsoleApplication || this.targetAssembly.Kind == ModuleKindFlags.WindowsApplication;
if (sourceList != null) {
foreach (AttributeNode possiblyDuplicateAttr in sourceList) {
if (possiblyDuplicateAttr != null) {
// Certain types of attributes should not be merged onto the target assembly
// when it is an executable.
if (targetIsExe) {
switch (possiblyDuplicateAttr.Type.FullName) {
case "System.Security.AllowPartiallyTrustedCallersAttribute":
case "System.Security.SecurityCriticalAttribute":
case "System.Security.SecurityTransparentAttribute":
continue;
default:
break;
}
} else {
// Assume it is a library (dll).
}
if (this.UnionMerge) {
if (!AttributeExistsInTarget(possiblyDuplicateAttr, targetList)) {
targetList.Add(possiblyDuplicateAttr);
}
}
else if (allowMultiples && possiblyDuplicateAttr.AllowMultiple) {
targetList.Add(possiblyDuplicateAttr);
}
else { // overwrite if found, add if not found
int j = 0;
int m = targetList.Count;
while (j < m) {
if (possiblyDuplicateAttr.Type == targetList[j].Type) {
if (!keepFirst) {
targetList[j] = possiblyDuplicateAttr; // overwrite
}
break;
}
j++;
}
if (j == m) {
// then not found, can't overwrite, just add to end
targetList.Add(possiblyDuplicateAttr);
}
}
}
}
}
}
private bool AttributeExistsInTarget(AttributeNode possiblyDuplicateAttr, AttributeList targetList){
bool addAttribute = false;
int counter = 0;
while (counter < targetList.Count) {
if (possiblyDuplicateAttr.Type == targetList[counter].Type) {
ArrayList exprList1 = new ArrayList();
ArrayList exprList2 = new ArrayList();
if (possiblyDuplicateAttr.Expressions != null) {
foreach (Expression expression in possiblyDuplicateAttr.Expressions) {
exprList1.Add(expression.ToString());
}
}
if (targetList[counter].Expressions != null) {
foreach (Expression expression in targetList[counter].Expressions) {
exprList2.Add(expression.ToString());
}
}
if (exprList1.Count == exprList2.Count) {
bool completeMatch = true;
foreach (string exprValue in exprList1) {
if (!exprList2.Contains(exprValue)) {
completeMatch = false;
break;
}
}
if (completeMatch) {
foreach (string exprValue in exprList2) {
if (!exprList1.Contains(exprValue)) {
completeMatch = false;
break;
}
}
}
if (completeMatch) {
break;
}
}
}
counter++;
}
if (counter == targetList.Count) {
addAttribute = true;
}
return addAttribute;
}
private static bool IsPortablePdb(string pdb) {
using (var stream = File.OpenRead(pdb)) {
const uint ppdb_signature = 0x424a5342;
var position = stream.Position;
try {
var reader = new BinaryReader(stream);
return reader.ReadUInt32() == ppdb_signature;
} finally {
stream.Position = position;
}
}
}
#endregion
#region Protected Methods
/// <summary>
/// Provides a way for subtypes to create their own Duplicator to use for
/// the merging. When not overridden, the duplicator is the standard one.
/// </summary>
/// <param name="module">Top level module for this duplicator to copy types into.</param>
/// <returns>The duplicator to use for visiting the source modules.</returns>
protected virtual Duplicator CreateDuplicator(Module module) {
return new Duplicator(module, null);
}
/// <summary>
/// Provides a way for subtypes to create their own Duplicator to use for
/// the merging. When not overridden, the duplicator is the standard one.
/// </summary>
/// <param name="module">Top level module for this duplicator to copy types into.</param>
/// <param name="typeNode"></param>
/// <returns>The duplicator to use for visiting the source modules.</returns>
protected virtual Duplicator CreateDuplicator(Module module, TypeNode typeNode) {
return new Duplicator(module, typeNode);
}
/// <summary>
/// Returns true iff there is a violation of the command line arguments.
/// Currently, it doesn't check for much.
/// </summary>
/// <param name="args">Exactly the same array as passed to Main.</param>
/// <returns>true iff command line args are incorrect (in some simple cases)</returns>
protected virtual bool CheckUsage(string[] args) {
if (args.Length < 1) {
return true;
}
if (args.Length == 1 &&
(String.Compare(args[0], "-?", true) == 0 ||
String.Compare(args[0], "/?", true) == 0 ||
String.Compare(args[0], "-h", true) == 0)
) {
return true;
}
return false;
}
/// <summary>
/// Checks certain arguments and their combinations to detect proper usage.
/// Writes to Console for each violation.
/// </summary>
/// <returns>True iff no error is detected.</returns>
protected virtual bool ValidateOptions() {
bool errorInOptions = false;
if (!(this.assemblyNames.Count > 0)) {
Console.WriteLine("Must specify at least one input file!");
errorInOptions = true;
}
if (this.outputFileName == null) {
Console.WriteLine("Must specify an output file!");
errorInOptions = true;
}
if (this.keyfileSpecified) {
if (this.keyfile == null) {
errorInOptions = true;
Console.WriteLine("/keyfile option given, but no file name.");
}
}
if (this.keyContainerSpecified) {
if (this.keyContainer == null) {
errorInOptions = true;
Console.WriteLine("/keycontainer option given, but no container name.");
}
}
if (this.delaySign && !keyfileSpecified && !keyContainerSpecified) {
errorInOptions = true;
Console.WriteLine("/delaysign option given, but not the /keyfile or /keycontainer options.");
}
#if CROSSPLATFORM
if (this.targetPlatformSpecified) {
if (this.clrVersion == null) {
errorInOptions = true;
Console.WriteLine("/targetplatform option given, but couldn't set it");
}
}
#endif
return !errorInOptions;
}
/// <summary>
/// Sets internal state to reflect arguments specified by user on command line.
/// </summary>
/// <param name="args"></param>
protected virtual bool ProcessCommandLineOptions(string[] args) {
bool ok = true;
this.assemblyNames = new ArrayList(args.Length); // can't be more arguments than that
for (int i = 0, n = args.Length; i < n && ok; i++) // stop processing if not okay
{
string arg = args[i];
if (!(arg[0] == '-' || arg[0] == '/')) {
this.assemblyNames.Add(arg); // then take it as an input assembly
}
else {
string option = arg.Substring(1);
int setTo = option.IndexOf("=");
if (setTo < 0)
setTo = option.IndexOf(":");
string key = null;
string val = null;
if (setTo < 0) {
key = option.Substring(0, option.Length);
val = "";
}
else {
key = option.Substring(0, setTo);
val = option.Substring(setTo + 1);
}
if (String.Compare(key, "lib", true) == 0) {
if (val != "")
this.searchDirs.Add(val);
}
else if (String.Compare(key, "internalize", true) == 0) {
this.internalize = true;
if (val != "")
this.excludeFile = val;
}
else if (String.Compare(key, "log", true) == 0) {
this.log = true;
if (val != "")
this.logFile = val;
}
else if (String.Compare(key, "t", true) == 0
|| String.Compare(key, "target", true) == 0
) {
if (val != "") {
switch (val) {
case "library": this.targetKind = Kind.Dll; break;
case "exe": this.targetKind = Kind.Exe; break;
case "winexe": this.targetKind = Kind.WinExe; break;
}
}
else {
ok = false;
Console.WriteLine("/target given without an accompanying kind.");
}
}
else if (String.Compare(key, "ndebug", true) == 0) {
this.debugInfo = false;
}
else if (String.Compare(key, "closed", true) == 0) {
this.closed = true;
}
else if (String.Compare(key, "short", true) == 0) {
this.shortB = true;
}
else if (String.Compare(key, "copyattrs", true) == 0) {
this.copyattrs = true;
}
else if (String.Compare(key, "allowMultiple", true) == 0) {
if (!this.copyattrs) {
Console.WriteLine("/allowMultiple specified without specifying /copyattrs");
ok = false;
}
else {
this.allowMultipleAssemblyLevelAttributes = true;
}
} else if (String.Compare(key, "keepFirst", true) == 0) {
if (!this.copyattrs) {
Console.WriteLine("/keepFirst specified without specifying /copyattrs");
ok = false;
} else {
this.keepFirstOfMultipleAssemblyLevelAttributes = true;
}
} else if (String.Compare(key, "xmldocs", true) == 0) {
this.copyXmlDocumentation = true;
}
else if (String.Compare(key, "out", true) == 0) {
if (val != "")
this.outputFileName = val;
}
else if (String.Compare(key, "attr", true) == 0) {
if (val != "") {
this.attributeFileName = val;
}
else {
Console.WriteLine("/attr given without an accompanying assembly name.");
ok = false;
}
}
else if (String.Compare(key, "reference", true) == 0 || String.Compare(key, "r", true) == 0) {
if (val != "") {
this.assemblyNames.Add(val);
}
else {
Console.WriteLine("/reference given without an accompanying assembly name.");
ok = false;
}
}
else if (String.Compare(key, "targetplatform", true) == 0) {
#if CROSSPLATFORM
if (this.targetPlatformSpecified) {
Console.WriteLine("Target platform already specified earlier on command line.");
ok = false;