[mcs] Report second level references mismatch only for really used references. Fixes...
[mono.git] / mcs / mcs / assembly.cs
1 //
2 // assembly.cs: Assembly declaration and specifications
3 //
4 // Authors:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004-2011 Novell, Inc.
10 // Copyright 2011-2013 Xamarin Inc
11 //
12
13
14 using System;
15 using System.IO;
16 using System.Collections.Generic;
17 using System.Globalization;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
21 using Mono.Security.Cryptography;
22 using Mono.CompilerServices.SymbolWriter;
23 using System.Linq;
24
25 #if STATIC
26 using IKVM.Reflection;
27 using IKVM.Reflection.Emit;
28 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
29 #else
30 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
31 using System.Reflection;
32 using System.Reflection.Emit;
33 #endif
34
35 namespace Mono.CSharp
36 {
37         public interface IAssemblyDefinition
38         {
39                 string FullName { get; }
40                 bool IsCLSCompliant { get; }
41                 bool IsMissing { get; }
42                 string Name { get; }
43
44                 byte[] GetPublicKeyToken ();
45                 bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
46         }
47
48         public class AssemblyReferenceErrorInfo
49         {
50                 public AssemblyReferenceErrorInfo (AssemblyName dependencyName, string location, string message)
51                 {
52                         this.DependencyName = dependencyName;
53                         this.RequestingAssemblyLocation = location;
54                         this.Message = message;
55                 }
56
57                 public AssemblyName DependencyName { get; private set; }
58                 public string RequestingAssemblyLocation { get; private set; }
59                 public string Message { get; private set; }
60         }
61                 
62         public abstract class AssemblyDefinition : IAssemblyDefinition
63         {
64                 // TODO: make it private and move all builder based methods here
65                 public AssemblyBuilder Builder;
66                 protected AssemblyBuilderExtension builder_extra;
67                 MonoSymbolFile symbol_writer;
68
69                 bool is_cls_compliant;
70                 bool wrap_non_exception_throws;
71                 bool wrap_non_exception_throws_custom;
72                 bool has_user_debuggable;
73
74                 protected ModuleContainer module;
75                 readonly string name;
76                 protected readonly string file_name;
77
78                 byte[] public_key, public_key_token;
79                 bool delay_sign;
80
81                 // Holds private/public key pair when private key
82                 // was available
83                 StrongNameKeyPair private_key;  
84
85                 Attribute cls_attribute;
86                 Method entry_point;
87
88                 protected List<ImportedModuleDefinition> added_modules;
89                 SecurityType declarative_security;
90                 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
91                 AssemblyAttributesPlaceholder module_target_attrs;
92
93                 // Win32 version info values
94                 string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
95                 string pa_file_version, pa_assembly_version;
96
97                 protected AssemblyDefinition (ModuleContainer module, string name)
98                 {
99                         this.module = module;
100                         this.name = Path.GetFileNameWithoutExtension (name);
101
102                         wrap_non_exception_throws = true;
103
104                         delay_sign = Compiler.Settings.StrongNameDelaySign;
105
106                         //
107                         // Load strong name key early enough for assembly importer to be able to
108                         // use the keys for InternalsVisibleTo
109                         // This should go somewhere close to ReferencesLoading but don't have the place yet
110                         //
111                         if (Compiler.Settings.HasKeyFileOrContainer) {
112                                 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
113                         }
114                 }
115
116                 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
117                         : this (module, name)
118                 {
119                         this.file_name = fileName;
120                 }
121
122                 #region Properties
123
124                 public Attribute CLSCompliantAttribute {
125                         get {
126                                 return cls_attribute;
127                         }
128                 }
129
130                 public CompilerContext Compiler {
131                         get {
132                                 return module.Compiler;
133                         }
134                 }
135
136                 //
137                 // Assembly entry point, aka Main method
138                 //
139                 public Method EntryPoint {
140                         get {
141                                 return entry_point;
142                         }
143                         set {
144                                 entry_point = value;
145                         }
146                 }
147
148                 public string FullName {
149                         get {
150                                 return Builder.FullName;
151                         }
152                 }
153
154                 public bool HasCLSCompliantAttribute {
155                         get {
156                                 return cls_attribute != null;
157                         }
158                 }
159
160                 // TODO: This should not exist here but will require more changes
161                 public MetadataImporter Importer {
162                     get; set;
163                 }
164
165                 public bool IsCLSCompliant {
166                         get {
167                                 return is_cls_compliant;
168                         }
169                 }
170
171                 bool IAssemblyDefinition.IsMissing {
172                         get {
173                                 return false;
174                         }
175                 }
176
177                 public bool IsSatelliteAssembly { get; private set; }
178
179                 public string Name {
180                         get {
181                                 return name;
182                         }
183                 }
184
185                 public bool WrapNonExceptionThrows {
186                         get {
187                                 return wrap_non_exception_throws;
188                         }
189                 }
190
191                 protected Report Report {
192                         get {
193                                 return Compiler.Report;
194                         }
195                 }
196
197                 public MonoSymbolFile SymbolWriter {
198                         get {
199                                 return symbol_writer;
200                         }
201                 }
202
203                 #endregion
204
205                 public void AddModule (ImportedModuleDefinition module)
206                 {
207                         if (added_modules == null) {
208                                 added_modules = new List<ImportedModuleDefinition> ();
209                                 added_modules.Add (module);
210                         }
211                 }
212
213                 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
214                 {
215                         if (a.IsValidSecurityAttribute ()) {
216                                 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
217                                 return;
218                         }
219
220                         if (a.Type == pa.AssemblyCulture) {
221                                 string value = a.GetString ();
222                                 if (value == null || value.Length == 0)
223                                         return;
224
225                                 if (Compiler.Settings.Target == Target.Exe) {
226                                         Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
227                                         return;
228                                 }
229
230                                 if (value == "neutral")
231                                         value = "";
232
233                                 if (Compiler.Settings.Target == Target.Module) {
234                                         SetCustomAttribute (ctor, cdata);
235                                 } else {
236                                         builder_extra.SetCulture (value, a.Location);
237                                 }
238
239                                 IsSatelliteAssembly = true;
240                                 return;
241                         }
242
243                         if (a.Type == pa.AssemblyVersion) {
244                                 string value = a.GetString ();
245                                 if (value == null || value.Length == 0)
246                                         return;
247
248                                 var vinfo = IsValidAssemblyVersion (value, true);
249                                 if (vinfo == null) {
250                                         Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
251                                                 value);
252                                         return;
253                                 }
254
255                                 if (Compiler.Settings.Target == Target.Module) {
256                                         SetCustomAttribute (ctor, cdata);
257                                 } else {
258                                         builder_extra.SetVersion (vinfo, a.Location);
259                                         pa_assembly_version = vinfo.ToString ();
260                                 }
261
262                                 return;
263                         }
264
265                         if (a.Type == pa.AssemblyAlgorithmId) {
266                                 const int pos = 2; // skip CA header
267                                 uint alg = (uint) cdata [pos];
268                                 alg |= ((uint) cdata [pos + 1]) << 8;
269                                 alg |= ((uint) cdata [pos + 2]) << 16;
270                                 alg |= ((uint) cdata [pos + 3]) << 24;
271
272                                 if (Compiler.Settings.Target == Target.Module) {
273                                         SetCustomAttribute (ctor, cdata);
274                                 } else {
275                                         builder_extra.SetAlgorithmId (alg, a.Location);
276                                 }
277
278                                 return;
279                         }
280
281                         if (a.Type == pa.AssemblyFlags) {
282                                 const int pos = 2; // skip CA header
283                                 uint flags = (uint) cdata[pos];
284                                 flags |= ((uint) cdata [pos + 1]) << 8;
285                                 flags |= ((uint) cdata [pos + 2]) << 16;
286                                 flags |= ((uint) cdata [pos + 3]) << 24;
287
288                                 // Ignore set PublicKey flag if assembly is not strongnamed
289                                 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
290                                         flags &= ~(uint) AssemblyNameFlags.PublicKey;
291
292                                 if (Compiler.Settings.Target == Target.Module) {
293                                         SetCustomAttribute (ctor, cdata);
294                                 } else {
295                                         builder_extra.SetFlags (flags, a.Location);
296                                 }
297
298                                 return;
299                         }
300
301                         if (a.Type == pa.TypeForwarder) {
302                                 TypeSpec t = a.GetArgumentType ();
303                                 if (t == null || TypeManager.HasElementType (t)) {
304                                         Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
305                                         return;
306                                 }
307
308                                 if (emitted_forwarders == null) {
309                                         emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
310                                 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
311                                         Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
312                                         Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
313                                                 t.GetSignatureForError ());
314                                         return;
315                                 }
316
317                                 emitted_forwarders.Add (t.MemberDefinition, a);
318
319                                 if (t.MemberDefinition.DeclaringAssembly == this) {
320                                         Report.SymbolRelatedToPreviousError (t);
321                                         Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
322                                                 t.GetSignatureForError ());
323                                         return;
324                                 }
325
326                                 if (t.IsNested) {
327                                         Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
328                                                 t.GetSignatureForError ());
329                                         return;
330                                 }
331
332                                 AddTypeForwarders (t, a.Location);
333                                 return;
334                         }
335
336                         if (a.Type == pa.Extension) {
337                                 a.Error_MisusedExtensionAttribute ();
338                                 return;
339                         }
340
341                         if (a.Type == pa.InternalsVisibleTo) {
342                                 string assembly_name = a.GetString ();
343                                 if (assembly_name == null) {
344                                         Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
345                                         return;
346                                 }
347
348                                 if (assembly_name.Length == 0)
349                                         return;
350 #if STATIC
351                                 ParsedAssemblyName aname;
352                                 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
353                                 if (r != ParseAssemblyResult.OK) {
354                                         Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
355                                                 assembly_name);
356                                         return;
357                                 }
358
359                                 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
360                                         Report.Error (1725, a.Location,
361                                                 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
362                                                 assembly_name);
363
364                                         return;
365                                 }
366
367                                 if (public_key != null && !aname.HasPublicKey) {
368                                         Report.Error (1726, a.Location,
369                                                 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
370                                                 assembly_name);
371                                         return;
372                                 }
373 #endif
374                         } else if (a.Type == pa.RuntimeCompatibility) {
375                                 wrap_non_exception_throws_custom = true;
376                         } else if (a.Type == pa.AssemblyFileVersion) {
377                                 pa_file_version = a.GetString ();
378                                 if (string.IsNullOrEmpty (pa_file_version) || IsValidAssemblyVersion (pa_file_version, false) == null) {
379                                         Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
380                                                         pa_file_version, a.Name);
381                                         return;
382                                 }
383
384                                 // File version info decoding from blob is not supported
385                                 var cab = new CustomAttributeBuilder ((ConstructorInfo)ctor.GetMetaInfo (), new object [] { pa_file_version });
386                                 Builder.SetCustomAttribute (cab);
387                                 return;
388                         } else if (a.Type == pa.AssemblyProduct) {
389                                 vi_product = a.GetString ();
390                         } else if (a.Type == pa.AssemblyCompany) {
391                                 vi_company = a.GetString ();
392                         } else if (a.Type == pa.AssemblyCopyright) {
393                                 vi_copyright = a.GetString ();
394                         } else if (a.Type == pa.AssemblyTrademark) {
395                                 vi_trademark = a.GetString ();
396                         } else if (a.Type == pa.Debuggable) {
397                                 has_user_debuggable = true;
398                         } else if (a.Type == pa.AssemblyInformationalVersion) {
399                                 vi_product_version = a.GetString ();
400                         }
401
402                         //
403                         // Win32 version info attributes AssemblyDescription and AssemblyTitle cannot be
404                         // set using public API and because we have blob like attributes we need to use
405                         // special option DecodeVersionInfoAttributeBlobs to support values extraction
406                         //
407
408                         SetCustomAttribute (ctor, cdata);
409                 }
410
411                 void AddTypeForwarders (TypeSpec type, Location loc)
412                 {
413                         builder_extra.AddTypeForwarder (type.GetDefinition (), loc);
414
415                         var ntypes = MemberCache.GetDeclaredNestedTypes (type);
416                         if (ntypes == null)
417                                 return;
418                         
419                         foreach (var nested in ntypes) {
420                                 if (nested.IsPrivate)
421                                         continue;
422
423                                 AddTypeForwarders (nested, loc);
424                         }
425                 }
426
427                 //
428                 // When using assembly public key attributes InternalsVisibleTo key
429                 // was not checked, we have to do it later when we actually know what
430                 // our public key token is
431                 //
432                 void CheckReferencesPublicToken ()
433                 {
434                         var references = builder_extra.GetReferencedAssemblies ();
435                         foreach (var an in references) {
436                                 if (public_key != null && an.GetPublicKey ().Length == 0) {
437                                         Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
438                                                 an.FullName);
439                                 }
440
441                                 var ci = an.CultureInfo;
442                                 if (!ci.Equals (CultureInfo.InvariantCulture)) {
443                                         Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
444                                                 an.Name, ci.Name);
445                                 }
446
447                                 var ia = Importer.GetImportedAssemblyDefinition (an);
448                                 if (ia == null)
449                                         continue;
450
451                                 var an_references = GetNotUnifiedReferences (an);
452                                 if (an_references != null) {
453                                         foreach (var r in an_references) {
454                                                 //
455                                                 // Secondary check when assembly references is resolved but not used. For example
456                                                 // due to type-forwarding
457                                                 //
458                                                 if (references.Any (l => l.Name == r.DependencyName.Name)) {
459                                                         Report.SymbolRelatedToPreviousError (r.RequestingAssemblyLocation);
460                                                         Report.Error (1705, r.Message);
461                                                 }
462                                         }
463                                 }
464
465                                 if (!ia.IsFriendAssemblyTo (this))
466                                         continue;
467                                 
468                                 var attr = ia.GetAssemblyVisibleToName (this);
469                                 var atoken = attr.GetPublicKeyToken ();
470
471                                 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
472                                         continue;
473
474                                 Report.SymbolRelatedToPreviousError (ia.Location);
475                                 Report.Error (281,
476                                         "Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
477                                         attr.FullName, FullName);
478                         }
479                 }
480
481                 protected AssemblyName CreateAssemblyName ()
482                 {
483                         var an = new AssemblyName (name);
484
485                         if (public_key != null && Compiler.Settings.Target != Target.Module) {
486                                 if (delay_sign) {
487                                         an.SetPublicKey (public_key);
488                                 } else {
489                                         if (public_key.Length == 16) {
490                                                 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
491                                         } else if (private_key == null) {
492                                                 Error_AssemblySigning ("The specified key file does not have a private key");
493                                         } else {
494                                                 an.KeyPair = private_key;
495                                         }
496                                 }
497                         }
498
499                         return an;
500                 }
501
502                 public virtual ModuleBuilder CreateModuleBuilder ()
503                 {
504                         if (file_name == null)
505                                 throw new NotSupportedException ("transient module in static assembly");
506
507                         var module_name = Path.GetFileName (file_name);
508
509                         // Always initialize module without symbolInfo. We could be framework dependent
510                         // but returned ISymbolWriter does not have all what we need therefore some
511                         // adaptor will be needed for now we alwayas emit MDB format when generating
512                         // debug info
513                         return Builder.DefineDynamicModule (module_name, module_name, false);
514                 }
515
516                 public virtual void Emit ()
517                 {
518                         if (Compiler.Settings.Target == Target.Module) {
519                                 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
520                                 module_target_attrs.CreateContainer ();
521                                 module_target_attrs.DefineContainer ();
522                                 module_target_attrs.Define ();
523                                 module.AddCompilerGeneratedClass (module_target_attrs);
524                         } else if (added_modules != null) {
525                                 ReadModulesAssemblyAttributes ();
526                         }
527
528                         if (Compiler.Settings.GenerateDebugInfo) {
529                                 symbol_writer = new MonoSymbolFile ();
530                         }
531
532                         module.EmitContainer ();
533
534                         if (module.HasExtensionMethod) {
535                                 var pa = module.PredefinedAttributes.Extension;
536                                 if (pa.IsDefined) {
537                                         SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
538                                 }
539                         }
540
541                         if (!IsSatelliteAssembly) {
542                                 if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
543                                         var pa = module.PredefinedAttributes.Debuggable;
544                                         if (pa.IsDefined) {
545                                                 var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
546                                                 if (!Compiler.Settings.Optimize)
547                                                         modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
548
549                                                 pa.EmitAttribute (Builder, modes);
550                                         }
551                                 }
552
553                                 if (!wrap_non_exception_throws_custom) {
554                                         PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
555                                         if (pa.IsDefined && pa.ResolveBuilder ()) {
556                                                 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
557                                                 if (prop != null) {
558                                                         AttributeEncoder encoder = new AttributeEncoder ();
559                                                         encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
560                                                         SetCustomAttribute (pa.Constructor, encoder.ToArray ());
561                                                 }
562                                         }
563                                 }
564
565                                 if (declarative_security != null) {
566 #if STATIC
567                                         foreach (var entry in declarative_security) {
568                                                 Builder.__AddDeclarativeSecurity (entry);
569                                         }
570 #else
571                                         throw new NotSupportedException ("Assembly-level security");
572 #endif
573                                 }
574                         }
575
576                         CheckReferencesPublicToken ();
577
578                         SetEntryPoint ();
579                 }
580
581                 public byte[] GetPublicKeyToken ()
582                 {
583                         if (public_key == null || public_key_token != null)
584                                 return public_key_token;
585
586                         HashAlgorithm ha = SHA1.Create ();
587                         byte[] hash = ha.ComputeHash (public_key);
588                         // we need the last 8 bytes in reverse order
589                         public_key_token = new byte[8];
590                         Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
591                         Array.Reverse (public_key_token, 0, 8);
592                         return public_key_token;
593                 }
594
595                 protected virtual List<AssemblyReferenceErrorInfo> GetNotUnifiedReferences (AssemblyName assemblyName)
596                 {
597                         return null;
598                 }
599
600                 //
601                 // Either keyFile or keyContainer has to be non-null
602                 //
603                 void LoadPublicKey (string keyFile, string keyContainer)
604                 {
605                         if (keyContainer != null) {
606                                 try {
607                                         private_key = new StrongNameKeyPair (keyContainer);
608                                         public_key = private_key.PublicKey;
609                                 } catch {
610                                         Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
611                                 }
612
613                                 return;
614                         }
615
616                         bool key_file_exists = File.Exists (keyFile);
617
618                         //
619                         // For attribute based KeyFile do additional lookup
620                         // in output assembly path
621                         //
622                         if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
623                                 //
624                                 // The key file can be relative to output assembly
625                                 //
626                                 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
627                                 key_file_exists = File.Exists (test_path);
628                                 if (key_file_exists)
629                                         keyFile = test_path;
630                         }
631
632                         if (!key_file_exists) {
633                                 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
634                                 return;
635                         }
636
637                         using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
638                                 byte[] snkeypair = new byte[fs.Length];
639                                 fs.Read (snkeypair, 0, snkeypair.Length);
640
641                                 // check for ECMA key
642                                 if (snkeypair.Length == 16) {
643                                         public_key = snkeypair;
644                                         return;
645                                 }
646
647                                 try {
648                                         // take it, with or without, a private key
649                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
650                                         // and make sure we only feed the public part to Sys.Ref
651                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
652
653                                         // AssemblyName.SetPublicKey requires an additional header
654                                         byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
655
656                                         // Encode public key
657                                         public_key = new byte[12 + publickey.Length];
658                                         Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
659
660                                         // Length of Public Key (in bytes)
661                                         int lastPart = public_key.Length - 12;
662                                         public_key[8] = (byte) (lastPart & 0xFF);
663                                         public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
664                                         public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
665                                         public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
666
667                                         Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
668                                 } catch {
669                                         Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
670                                         return;
671                                 }
672
673                                 if (delay_sign)
674                                         return;
675
676                                 try {
677                                         // TODO: Is there better way to test for a private key presence ?
678                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
679                                         private_key = new StrongNameKeyPair (snkeypair);
680                                 } catch { }
681                         }
682                 }
683
684                 void ReadModulesAssemblyAttributes ()
685                 {
686                         foreach (var m in added_modules) {
687                                 var cattrs = m.ReadAssemblyAttributes ();
688                                 if (cattrs == null)
689                                         continue;
690
691                                 module.OptAttributes.AddAttributes (cattrs);
692                         }
693                 }
694
695                 public void Resolve ()
696                 {
697                         if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
698                                 //
699                                 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
700                                 // when -unsafe option was specified
701                                 //
702                                 Location loc = Location.Null;
703
704                                 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
705                                         new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
706
707                                 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
708
709                                 Arguments pos = new Arguments (1);
710                                 pos.Add (new Argument (req_min.GetConstant (null)));
711
712                                 Arguments named = new Arguments (1);
713                                 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
714
715                                 Attribute g = new Attribute ("assembly",
716                                         new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
717                                         new Arguments[] { pos, named }, loc, false);
718                                 g.AttachTo (module, module);
719
720                                 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
721                                 Compiler.Report.DisableReporting ();
722                                 try {
723                                         var ctor = g.Resolve ();
724                                         if (ctor != null) {
725                                                 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
726                                         }
727                                 } finally {
728                                         Compiler.Report.EnableReporting ();
729                                 }
730                         }
731
732                         if (module.OptAttributes == null)
733                                 return;
734
735                         // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
736                         if (!module.OptAttributes.CheckTargets())
737                                 return;
738
739                         cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
740
741                         if (cls_attribute != null) {
742                                 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
743                         }
744
745                         if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
746                                 foreach (var m in added_modules) {
747                                         if (!m.IsCLSCompliant) {
748                                                 Report.Error (3013,
749                                                         "Added modules must be marked with the CLSCompliant attribute to match the assembly",
750                                                         m.Name);
751                                         }
752                                 }
753                         }
754
755                         Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
756                         if (a != null) {
757                                 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
758                                 if (val != null)
759                                         wrap_non_exception_throws = val.Value;
760                         }
761                 }
762
763                 protected void ResolveAssemblySecurityAttributes ()
764                 {
765                         string key_file = null;
766                         string key_container = null;
767
768                         if (module.OptAttributes != null) {
769                                 foreach (Attribute a in module.OptAttributes.Attrs) {
770                                         // cannot rely on any resolve-based members before you call Resolve
771                                         if (a.ExplicitTarget != "assembly")
772                                                 continue;
773
774                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
775                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
776                                         //       are loaded yet.
777                                         // TODO: Does not handle quoted attributes properly
778                                         switch (a.Name) {
779                                         case "AssemblyKeyFile":
780                                         case "AssemblyKeyFileAttribute":
781                                         case "System.Reflection.AssemblyKeyFileAttribute":
782                                                 if (Compiler.Settings.StrongNameKeyFile != null) {
783                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
784                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
785                                                                         "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
786                                                 } else {
787                                                         string value = a.GetString ();
788                                                         if (!string.IsNullOrEmpty (value)) {
789                                                                 Error_ObsoleteSecurityAttribute (a, "keyfile");
790                                                                 key_file = value;
791                                                         }
792                                                 }
793                                                 break;
794                                         case "AssemblyKeyName":
795                                         case "AssemblyKeyNameAttribute":
796                                         case "System.Reflection.AssemblyKeyNameAttribute":
797                                                 if (Compiler.Settings.StrongNameKeyContainer != null) {
798                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
799                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
800                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
801                                                 } else {
802                                                         string value = a.GetString ();
803                                                         if (!string.IsNullOrEmpty (value)) {
804                                                                 Error_ObsoleteSecurityAttribute (a, "keycontainer");
805                                                                 key_container = value;
806                                                         }
807                                                 }
808                                                 break;
809                                         case "AssemblyDelaySign":
810                                         case "AssemblyDelaySignAttribute":
811                                         case "System.Reflection.AssemblyDelaySignAttribute":
812                                                 bool b = a.GetBoolean ();
813                                                 if (b) {
814                                                         Error_ObsoleteSecurityAttribute (a, "delaysign");
815                                                 }
816
817                                                 delay_sign = b;
818                                                 break;
819                                         }
820                                 }
821                         }
822
823                         // We came here only to report assembly attributes warnings
824                         if (public_key != null)
825                                 return;
826
827                         //
828                         // Load the strong key file found in attributes when no
829                         // command line key was given
830                         //
831                         if (key_file != null || key_container != null) {
832                                 LoadPublicKey (key_file, key_container);
833                         } else if (delay_sign) {
834                                 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
835                         }
836                 }
837
838                 public void EmbedResources ()
839                 {
840                         //
841                         // Add Win32 resources
842                         //
843                         if (Compiler.Settings.Win32ResourceFile != null) {
844                                 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
845                         } else {
846                                 Builder.DefineVersionInfoResource (vi_product, 
847                                                                    vi_product_version ?? pa_file_version ?? pa_assembly_version,
848                                                                    vi_company,
849                                                                    vi_copyright,
850                                                                    vi_trademark);
851                         }
852
853                         if (Compiler.Settings.Win32IconFile != null) {
854                                 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
855                         }
856
857                         if (Compiler.Settings.Resources != null) {
858                                 if (Compiler.Settings.Target == Target.Module) {
859                                         Report.Error (1507, "Cannot link resource file when building a module");
860                                 } else {
861                                         int counter = 0;
862                                         foreach (var res in Compiler.Settings.Resources) {
863                                                 if (!File.Exists (res.FileName)) {
864                                                         Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
865                                                         continue;
866                                                 }
867
868                                                 if (res.IsEmbeded) {
869                                                         Stream stream;
870                                                         if (counter++ < 10) {
871                                                                 stream = File.OpenRead (res.FileName);
872                                                         } else {
873                                                                 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
874                                                                 // we workaround it by reading everything into memory to compile projects with
875                                                                 // many embedded resource (over 3500) references
876                                                                 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
877                                                         }
878
879                                                         module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
880                                                 } else {
881                                                         Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
882                                                 }
883                                         }
884                                 }
885                         }
886                 }
887
888                 public void Save ()
889                 {
890                         PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
891                         ImageFileMachine machine;
892
893                         switch (Compiler.Settings.Platform) {
894                         case Platform.X86:
895                                 pekind |= PortableExecutableKinds.Required32Bit;
896                                 machine = ImageFileMachine.I386;
897                                 break;
898                         case Platform.X64:
899                                 pekind |= PortableExecutableKinds.PE32Plus;
900                                 machine = ImageFileMachine.AMD64;
901                                 break;
902                         case Platform.IA64:
903                                 machine = ImageFileMachine.IA64;
904                                 break;
905                         case Platform.AnyCPU32Preferred:
906 #if STATIC
907                                 pekind |= PortableExecutableKinds.Preferred32Bit;
908                                 machine = ImageFileMachine.I386;
909                                 break;
910 #else
911                                 throw new NotSupportedException ();
912 #endif
913                         case Platform.Arm:
914 #if STATIC
915                                 machine = ImageFileMachine.ARM;
916                                 break;
917 #else
918                                 throw new NotSupportedException ();
919 #endif
920                         case Platform.AnyCPU:
921                         default:
922                                 machine = ImageFileMachine.I386;
923                                 break;
924                         }
925
926                         Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
927                         try {
928                                 if (Compiler.Settings.Target == Target.Module) {
929                                         SaveModule (pekind, machine);
930                                 } else {
931                                         Builder.Save (module.Builder.ScopeName, pekind, machine);
932                                 }
933                         } catch (ArgumentOutOfRangeException) {
934                                 Report.Error (16, "Output file `{0}' exceeds the 4GB limit", name);
935                         } catch (Exception e) {
936                                 Report.Error (16, "Could not write to file `{0}'. {1}", name, e.Message);
937                         }
938                         Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
939
940                         // Save debug symbols file
941                         if (symbol_writer != null && Compiler.Report.Errors == 0) {
942                                 // TODO: it should run in parallel
943                                 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
944
945                                 var filename = file_name + ".mdb";
946                                 try {
947                                         // We mmap the file, so unlink the previous version since it may be in use
948                                         File.Delete (filename);
949                                 } catch {
950                                         // We can safely ignore
951                                 }
952
953                                 module.WriteDebugSymbol (symbol_writer);
954
955                                 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
956                                         symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
957                                 }
958
959                                 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
960                         }
961                 }
962
963                 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
964                 {
965                         Report.RuntimeMissingSupport (Location.Null, "-target:module");
966                 }
967
968                 void SetCustomAttribute (MethodSpec ctor, byte[] data)
969                 {
970                         if (module_target_attrs != null)
971                                 module_target_attrs.AddAssemblyAttribute (ctor, data);
972                         else
973                                 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
974                 }
975
976                 void SetEntryPoint ()
977                 {
978                         if (!Compiler.Settings.NeedsEntryPoint) {
979                                 if (Compiler.Settings.MainClass != null)
980                                         Report.Error (2017, "Cannot specify -main if building a module or library");
981
982                                 return;
983                         }
984
985                         PEFileKinds file_kind;
986
987                         switch (Compiler.Settings.Target) {
988                         case Target.Library:
989                         case Target.Module:
990                                 file_kind = PEFileKinds.Dll;
991                                 break;
992                         case Target.WinExe:
993                                 file_kind = PEFileKinds.WindowApplication;
994                                 break;
995                         default:
996                                 file_kind = PEFileKinds.ConsoleApplication;
997                                 break;
998                         }
999
1000                         if (entry_point == null) {
1001                                 string main_class = Compiler.Settings.MainClass;
1002                                 if (main_class != null) {
1003                                         // TODO: Handle dotted names
1004                                         var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
1005                                         if (texpr == null) {
1006                                                 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
1007                                                 return;
1008                                         }
1009
1010                                         var mtype = texpr.MemberDefinition as ClassOrStruct;
1011                                         if (mtype == null) {
1012                                                 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
1013                                                 return;
1014                                         }
1015
1016                                         Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
1017                                 } else {
1018                                         string pname = file_name == null ? name : Path.GetFileName (file_name);
1019                                         Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1020                                                 pname);
1021                                 }
1022
1023                                 return;
1024                         }
1025
1026                         Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
1027                 }
1028
1029                 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
1030                 {
1031                         Report.Warning (1699, 1, a.Location,
1032                                 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
1033                                 option, a.Name);
1034                 }
1035
1036                 void Error_AssemblySigning (string text)
1037                 {
1038                         Report.Error (1548, "Error during assembly signing. " + text);
1039                 }
1040
1041                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1042                 {
1043                         return false;
1044                 }
1045
1046                 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
1047                 {
1048                         string[] parts = version.Split ('.');
1049                         if (parts.Length < 1 || parts.Length > 4)
1050                                 return null;
1051
1052                         var values = new int[4];
1053                         for (int i = 0; i < parts.Length; ++i) {
1054                                 if (!int.TryParse (parts[i], out values[i])) {
1055                                         if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
1056                                                 if (i == 2) {
1057                                                         // Nothing can follow *
1058                                                         if (parts.Length > 3)
1059                                                                 return null;
1060
1061                                                         // Generate Build value based on days since 1/1/2000
1062                                                         TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
1063                                                         values[i] = System.Math.Max (days.Days, 0);
1064                                                         i = 3;
1065                                                 }
1066
1067                                                 if (i == 3) {
1068                                                         // Generate Revision value based on every other second today
1069                                                         var seconds = DateTime.Now - DateTime.Today;
1070                                                         values[i] = (int) seconds.TotalSeconds / 2;
1071                                                         continue;
1072                                                 }
1073                                         }
1074
1075                                         return null;
1076                                 }
1077
1078                                 if (values[i] > ushort.MaxValue)
1079                                         return null;
1080                         }
1081
1082                         return new Version (values[0], values[1], values[2], values[3]);
1083                 }
1084         }
1085
1086         public class AssemblyResource : IEquatable<AssemblyResource>
1087         {
1088                 public AssemblyResource (string fileName, string name)
1089                         : this (fileName, name, false)
1090                 {
1091                 }
1092
1093                 public AssemblyResource (string fileName, string name, bool isPrivate)
1094                 {
1095                         FileName = fileName;
1096                         Name = name;
1097                         Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1098                 }
1099
1100                 public ResourceAttributes Attributes { get; private set; }
1101                 public string Name { get; private set; }
1102                 public string FileName { get; private set; }
1103                 public bool IsEmbeded { get; set; }
1104
1105                 #region IEquatable<AssemblyResource> Members
1106
1107                 public bool Equals (AssemblyResource other)
1108                 {
1109                         return Name == other.Name;
1110                 }
1111
1112                 #endregion
1113         }
1114
1115         //
1116         // A placeholder class for assembly attributes when emitting module
1117         //
1118         class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1119         {
1120                 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1121                 public static readonly string AssemblyFieldName = "attributes";
1122
1123                 Field assembly;
1124
1125                 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1126                         : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1127                 {
1128                         assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1129                                 new MemberName (AssemblyFieldName), null);
1130
1131                         AddField (assembly);
1132                 }
1133
1134                 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1135                 {
1136                         assembly.SetCustomAttribute (ctor, data);
1137                 }
1138
1139                 public static string GetGeneratedName (string outputName)
1140                 {
1141                         return string.Format (TypeNamePrefix, outputName);
1142                 }
1143         }
1144
1145         //
1146         // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1147         // compiler. This is a default implementation for framework System.Reflection.Emit
1148         // which does not implement any of the methods
1149         //
1150         public class AssemblyBuilderExtension
1151         {
1152                 protected readonly CompilerContext ctx;
1153
1154                 public AssemblyBuilderExtension (CompilerContext ctx)
1155                 {
1156                         this.ctx = ctx;
1157                 }
1158
1159                 public virtual System.Reflection.Module AddModule (string module)
1160                 {
1161                         ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1162                         return null;
1163                 }
1164
1165                 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1166                 {
1167                         ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1168                 }
1169
1170                 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1171                 {
1172                         ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1173                 }
1174
1175                 public virtual void DefineWin32IconResource (string fileName)
1176                 {
1177                         ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1178                 }
1179
1180                 public virtual AssemblyName[] GetReferencedAssemblies ()
1181                 {
1182                         return null;
1183                 }
1184
1185                 public virtual void SetAlgorithmId (uint value, Location loc)
1186                 {
1187                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1188                 }
1189
1190                 public virtual void SetCulture (string culture, Location loc)
1191                 {
1192                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1193                 }
1194
1195                 public virtual void SetFlags (uint flags, Location loc)
1196                 {
1197                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1198                 }
1199
1200                 public virtual void SetVersion (Version version, Location loc)
1201                 {
1202                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1203                 }
1204         }
1205
1206         abstract class AssemblyReferencesLoader<T> where T : class
1207         {
1208                 protected readonly CompilerContext compiler;
1209
1210                 protected readonly List<string> paths;
1211
1212                 protected AssemblyReferencesLoader (CompilerContext compiler)
1213                 {
1214                         this.compiler = compiler;
1215
1216                         paths = new List<string> ();
1217                         paths.Add (Directory.GetCurrentDirectory ());
1218                         paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1219                 }
1220
1221                 public abstract T HasObjectType (T assembly);
1222                 protected abstract string[] GetDefaultReferences ();
1223                 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1224                 public abstract void LoadReferences (ModuleContainer module);
1225
1226                 protected void Error_FileNotFound (string fileName)
1227                 {
1228                         compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1229                 }
1230
1231                 protected void Error_FileCorrupted (string fileName)
1232                 {
1233                         compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1234                 }
1235
1236                 protected void Error_AssemblyIsModule (string fileName)
1237                 {
1238                         compiler.Report.Error (1509,
1239                                 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1240                                 fileName);
1241                 }
1242
1243                 protected void Error_ModuleIsAssembly (string fileName)
1244                 {
1245                         compiler.Report.Error (1542,
1246                                 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1247                                 fileName);
1248                 }
1249
1250                 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1251                 {
1252                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1253
1254                         loaded = new List<Tuple<RootNamespace, T>> ();
1255
1256                         //
1257                         // Load mscorlib.dll as the first
1258                         //
1259                         if (module.Compiler.Settings.StdLib) {
1260                                 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1261                         } else {
1262                                 corlib_assembly = default (T);
1263                         }
1264
1265                         T a;
1266                         foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1267                                 a = LoadAssemblyFile (r, false);
1268                                 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1269                                         continue;
1270
1271                                 var key = Tuple.Create (module.GlobalRootNamespace, a);
1272                                 if (loaded.Contains (key))
1273                                         continue;
1274
1275                                 loaded.Add (key);
1276                         }
1277
1278                         if (corlib_assembly == null) {
1279                                 //
1280                                 // Requires second pass because HasObjectType can trigger assembly load event
1281                                 //
1282                                 for (int i = 0; i < loaded.Count; ++i) {
1283                                         var assembly = loaded [i];
1284
1285                                         //
1286                                         // corlib assembly is the first referenced assembly which contains System.Object
1287                                         //
1288                                         corlib_assembly = HasObjectType (assembly.Item2);
1289                                         if (corlib_assembly != null) {
1290                                                 if (corlib_assembly != assembly.Item2) {
1291                                                         var ca = corlib_assembly;
1292                                                         i = loaded.FindIndex (l => l.Item2 == ca);
1293                                                 }
1294
1295                                                 loaded.RemoveAt (i);
1296                                                 break;
1297                                         }
1298                                 }
1299                         }
1300
1301                         foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1302                                 a = LoadAssemblyFile (entry.Item2, false);
1303                                 if (a == null)
1304                                         continue;
1305
1306                                 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1307                                 if (loaded.Contains (key))
1308                                         continue;
1309
1310                                 loaded.Add (key);
1311                         }
1312
1313                         if (compiler.Settings.LoadDefaultReferences) {
1314                                 foreach (string r in GetDefaultReferences ()) {
1315                                         a = LoadAssemblyFile (r, true);
1316                                         if (a == null)
1317                                                 continue;
1318
1319                                         var key = Tuple.Create (module.GlobalRootNamespace, a);
1320                                         if (loaded.Contains (key))
1321                                                 continue;
1322
1323                                         loaded.Add (key);
1324                                 }
1325                         }
1326
1327                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);
1328                 }
1329         }
1330 }