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