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