[asp.net] FormsAuthenticationTicket.FromByteArray stops early if it is passed a null...
[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 = RootContext.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 (RootContext.StrongNameKeyFile != null || RootContext.StrongNameKeyContainer != null) {
92                                 LoadPublicKey (RootContext.StrongNameKeyFile, RootContext.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 (RootContext.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 (RootContext.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 (RootContext.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 (RootContext.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 (RootContext.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.Error (281,
389                                         "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",
390                                         attr.FullName, FullName);
391                         }
392                 }
393
394                 protected AssemblyName CreateAssemblyName ()
395                 {
396                         var an = new AssemblyName (name);
397
398                         if (public_key != null && RootContext.Target != Target.Module) {
399                                 if (delay_sign) {
400                                         an.SetPublicKey (public_key);
401                                 } else {
402                                         if (public_key.Length == 16) {
403                                                 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
404                                         } else if (private_key == null) {
405                                                 Error_AssemblySigning ("The specified key file does not have a private key");
406                                         } else {
407                                                 an.KeyPair = private_key;
408                                         }
409                                 }
410                         }
411
412                         return an;
413                 }
414
415                 public virtual ModuleBuilder CreateModuleBuilder ()
416                 {
417                         if (file_name == null)
418                                 throw new NotSupportedException ("transient module in static assembly");
419
420                         var module_name = Path.GetFileName (file_name);
421
422                         // Always initialize module without symbolInfo. We could be framework dependent
423                         // but returned ISymbolWriter does not have all what we need therefore some
424                         // adaptor will be needed for now we alwayas emit MDB format when generating
425                         // debug info
426                         return Builder.DefineDynamicModule (module_name, module_name, false);
427                 }
428
429                 public virtual void Emit ()
430                 {
431                         if (RootContext.Target == Target.Module) {
432                                 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
433                                 module_target_attrs.CreateType ();
434                                 module_target_attrs.DefineType ();
435                                 module_target_attrs.Define ();
436                                 module.AddCompilerGeneratedClass (module_target_attrs);
437                         } else if (added_modules != null) {
438                                 ReadModulesAssemblyAttributes ();
439                         }
440
441                         if (RootContext.GenerateDebugInfo) {
442                                 symbol_writer = new MonoSymbolWriter (file_name);
443
444                                 // TODO: global variables
445                                 Location.DefineSymbolDocuments (symbol_writer);
446                                 SymbolWriter.symwriter = symbol_writer;
447                         }
448
449                         module.Emit ();
450
451                         if (module.HasExtensionMethod) {
452                                 var pa = module.PredefinedAttributes.Extension;
453                                 if (pa.IsDefined) {
454                                         SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
455                                 }
456                         }
457
458                         if (!wrap_non_exception_throws_custom) {
459                                 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
460                                 if (pa.IsDefined && pa.ResolveBuilder ()) {
461                                         var prop = pa.GetProperty ("WrapNonExceptionThrows", TypeManager.bool_type, Location.Null);
462                                         if (prop != null) {
463                                                 AttributeEncoder encoder = new AttributeEncoder ();
464                                                 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (true, Location.Null));
465                                                 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
466                                         }
467                                 }
468                         }
469
470                         if (declarative_security != null) {
471 #if STATIC
472                                 foreach (var entry in declarative_security) {
473                                         Builder.__AddDeclarativeSecurity (entry);
474                                 }
475 #else
476                                 var args = new PermissionSet[3];
477                                 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
478                                 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
479                                 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
480                                 builder_extra.AddPermissionRequests (args);
481 #endif
482                         }
483
484                         CheckReferencesPublicToken ();
485
486                         SetEntryPoint ();
487                 }
488
489                 public byte[] GetPublicKeyToken ()
490                 {
491                         if (public_key == null || public_key_token != null)
492                                 return public_key_token;
493
494                         HashAlgorithm ha = SHA1.Create ();
495                         byte[] hash = ha.ComputeHash (public_key);
496                         // we need the last 8 bytes in reverse order
497                         public_key_token = new byte[8];
498                         Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
499                         Array.Reverse (public_key_token, 0, 8);
500                         return public_key_token;
501                 }
502
503                 //
504                 // Either keyFile or keyContainer has to be non-null
505                 //
506                 void LoadPublicKey (string keyFile, string keyContainer)
507                 {
508                         if (keyContainer != null) {
509                                 try {
510                                         private_key = new StrongNameKeyPair (keyContainer);
511                                         public_key = private_key.PublicKey;
512                                 } catch {
513                                         Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
514                                 }
515
516                                 return;
517                         }
518
519                         bool key_file_exists = File.Exists (keyFile);
520
521                         //
522                         // For attribute based KeyFile do additional lookup
523                         // in output assembly path
524                         //
525                         if (!key_file_exists && RootContext.StrongNameKeyFile == null) {
526                                 //
527                                 // The key file can be relative to output assembly
528                                 //
529                                 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
530                                 key_file_exists = File.Exists (test_path);
531                                 if (key_file_exists)
532                                         keyFile = test_path;
533                         }
534
535                         if (!key_file_exists) {
536                                 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
537                                 return;
538                         }
539
540                         using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
541                                 byte[] snkeypair = new byte[fs.Length];
542                                 fs.Read (snkeypair, 0, snkeypair.Length);
543
544                                 // check for ECMA key
545                                 if (snkeypair.Length == 16) {
546                                         public_key = snkeypair;
547                                         return;
548                                 }
549
550                                 try {
551                                         // take it, with or without, a private key
552                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
553                                         // and make sure we only feed the public part to Sys.Ref
554                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
555
556                                         // AssemblyName.SetPublicKey requires an additional header
557                                         byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
558
559                                         // Encode public key
560                                         public_key = new byte[12 + publickey.Length];
561                                         Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
562
563                                         // Length of Public Key (in bytes)
564                                         int lastPart = public_key.Length - 12;
565                                         public_key[8] = (byte) (lastPart & 0xFF);
566                                         public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
567                                         public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
568                                         public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
569
570                                         Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
571                                 } catch {
572                                         Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
573                                         return;
574                                 }
575
576                                 if (delay_sign)
577                                         return;
578
579                                 try {
580                                         // TODO: Is there better way to test for a private key presence ?
581                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
582                                         private_key = new StrongNameKeyPair (snkeypair);
583                                 } catch { }
584                         }
585                 }
586
587                 void ReadModulesAssemblyAttributes ()
588                 {
589                         foreach (var m in added_modules) {
590                                 var cattrs = m.ReadAssemblyAttributes ();
591                                 if (cattrs == null)
592                                         continue;
593
594                                 module.OptAttributes.AddAttributes (cattrs);
595                         }
596                 }
597
598                 public void Resolve ()
599                 {
600                         if (RootContext.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
601                                 //
602                                 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
603                                 // when -unsafe option was specified
604                                 //
605                                 Location loc = Location.Null;
606
607                                 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
608                                         new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
609
610                                 var req_min = (ConstSpec) module.PredefinedTypes.SecurityAction.GetField ("RequestMinimum", module.PredefinedTypes.SecurityAction.TypeSpec, loc);
611
612                                 Arguments pos = new Arguments (1);
613                                 pos.Add (new Argument (req_min.GetConstant (null)));
614
615                                 Arguments named = new Arguments (1);
616                                 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (true, loc)));
617
618                                 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (module, null, null, null), "assembly",
619                                         new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
620                                         new Arguments[] { pos, named }, loc, false);
621                                 g.AttachTo (module, module);
622                                 var ctor = g.Resolve ();
623                                 if (ctor != null) {
624                                         g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
625                                 }
626                         }
627
628                         if (module.OptAttributes == null)
629                                 return;
630
631                         // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
632                         if (!module.OptAttributes.CheckTargets())
633                                 return;
634
635                         cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
636
637                         if (cls_attribute != null) {
638                                 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
639                         }
640
641                         if (added_modules != null && RootContext.VerifyClsCompliance && is_cls_compliant) {
642                                 foreach (var m in added_modules) {
643                                         if (!m.IsCLSCompliant) {
644                                                 Report.Error (3013,
645                                                         "Added modules must be marked with the CLSCompliant attribute to match the assembly",
646                                                         m.Name);
647                                         }
648                                 }
649                         }
650
651                         Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
652                         if (a != null) {
653                                 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
654                                 if (val != null)
655                                         wrap_non_exception_throws = val.Value;
656                         }
657                 }
658
659                 protected void ResolveAssemblySecurityAttributes ()
660                 {
661                         string key_file = null;
662                         string key_container = null;
663
664                         if (module.OptAttributes != null) {
665                                 foreach (Attribute a in module.OptAttributes.Attrs) {
666                                         // cannot rely on any resolve-based members before you call Resolve
667                                         if (a.ExplicitTarget != "assembly")
668                                                 continue;
669
670                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
671                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
672                                         //       are loaded yet.
673                                         // TODO: Does not handle quoted attributes properly
674                                         switch (a.Name) {
675                                         case "AssemblyKeyFile":
676                                         case "AssemblyKeyFileAttribute":
677                                         case "System.Reflection.AssemblyKeyFileAttribute":
678                                                 if (RootContext.StrongNameKeyFile != null) {
679                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
680                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
681                                                                         "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
682                                                 } else {
683                                                         string value = a.GetString ();
684                                                         if (!string.IsNullOrEmpty (value)) {
685                                                                 Error_ObsoleteSecurityAttribute (a, "keyfile");
686                                                                 key_file = value;
687                                                         }
688                                                 }
689                                                 break;
690                                         case "AssemblyKeyName":
691                                         case "AssemblyKeyNameAttribute":
692                                         case "System.Reflection.AssemblyKeyNameAttribute":
693                                                 if (RootContext.StrongNameKeyContainer != null) {
694                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
695                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
696                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
697                                                 } else {
698                                                         string value = a.GetString ();
699                                                         if (!string.IsNullOrEmpty (value)) {
700                                                                 Error_ObsoleteSecurityAttribute (a, "keycontainer");
701                                                                 key_container = value;
702                                                         }
703                                                 }
704                                                 break;
705                                         case "AssemblyDelaySign":
706                                         case "AssemblyDelaySignAttribute":
707                                         case "System.Reflection.AssemblyDelaySignAttribute":
708                                                 bool b = a.GetBoolean ();
709                                                 if (b) {
710                                                         Error_ObsoleteSecurityAttribute (a, "delaysign");
711                                                 }
712
713                                                 delay_sign = b;
714                                                 break;
715                                         }
716                                 }
717                         }
718
719                         // We came here only to report assembly attributes warnings
720                         if (public_key != null)
721                                 return;
722
723                         //
724                         // Load the strong key file found in attributes when no
725                         // command line key was given
726                         //
727                         if (key_file != null || key_container != null) {
728                                 LoadPublicKey (key_file, key_container);
729                         } else if (delay_sign) {
730                                 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
731                         }
732                 }
733
734                 public void EmbedResources ()
735                 {
736                         //
737                         // Add Win32 resources
738                         //
739                         if (RootContext.Win32ResourceFile != null) {
740                                 Builder.DefineUnmanagedResource (RootContext.Win32ResourceFile);
741                         } else {
742                                 Builder.DefineVersionInfoResource ();
743                         }
744
745                         if (RootContext.Win32IconFile != null) {
746                                 builder_extra.DefineWin32IconResource (RootContext.Win32IconFile);
747                         }
748
749                         if (RootContext.Resources != null) {
750                                 if (RootContext.Target == Target.Module) {
751                                         Report.Error (1507, "Cannot link resource file when building a module");
752                                 } else {
753                                         int counter = 0;
754                                         foreach (var res in RootContext.Resources) {
755                                                 if (!File.Exists (res.FileName)) {
756                                                         Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
757                                                         continue;
758                                                 }
759
760                                                 if (res.IsEmbeded) {
761                                                         Stream stream;
762                                                         if (counter++ < 10) {
763                                                                 stream = File.OpenRead (res.FileName);
764                                                         } else {
765                                                                 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
766                                                                 // we workaround it by reading everything into memory to compile projects with
767                                                                 // many embedded resource (over 3500) references
768                                                                 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
769                                                         }
770
771                                                         module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
772                                                 } else {
773                                                         Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
774                                                 }
775                                         }
776                                 }
777                         }
778                 }
779
780                 public void Save ()
781                 {
782                         PortableExecutableKinds pekind;
783                         ImageFileMachine machine;
784
785                         switch (RootContext.Platform) {
786                         case Platform.X86:
787                                 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
788                                 machine = ImageFileMachine.I386;
789                                 break;
790                         case Platform.X64:
791                                 pekind = PortableExecutableKinds.ILOnly;
792                                 machine = ImageFileMachine.AMD64;
793                                 break;
794                         case Platform.IA64:
795                                 pekind = PortableExecutableKinds.ILOnly;
796                                 machine = ImageFileMachine.IA64;
797                                 break;
798                         case Platform.AnyCPU:
799                         default:
800                                 pekind = PortableExecutableKinds.ILOnly;
801                                 machine = ImageFileMachine.I386;
802                                 break;
803                         }
804
805                         Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
806                         try {
807                                 if (RootContext.Target == Target.Module) {
808                                         SaveModule (pekind, machine);
809                                 } else {
810                                         Builder.Save (module.Builder.ScopeName, pekind, machine);
811                                 }
812                         } catch (Exception e) {
813                                 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
814                         }
815                         Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
816
817                         // Save debug symbols file
818                         if (symbol_writer != null) {
819                                 // TODO: it should run in parallel
820                                 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
821                                 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
822                                 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
823                         }
824                 }
825
826                 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
827                 {
828                         Report.RuntimeMissingSupport (Location.Null, "-target:module");
829                 }
830
831                 void SetCustomAttribute (MethodSpec ctor, byte[] data)
832                 {
833                         if (module_target_attrs != null)
834                                 module_target_attrs.AddAssemblyAttribute (ctor, data);
835                         else
836                                 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
837                 }
838
839                 void SetEntryPoint ()
840                 {
841                         if (!RootContext.NeedsEntryPoint) {
842                                 if (RootContext.MainClass != null)
843                                         Report.Error (2017, "Cannot specify -main if building a module or library");
844
845                                 return;
846                         }
847
848                         PEFileKinds file_kind;
849
850                         switch (RootContext.Target) {
851                         case Target.Library:
852                         case Target.Module:
853                                 file_kind = PEFileKinds.Dll;
854                                 break;
855                         case Target.WinExe:
856                                 file_kind = PEFileKinds.WindowApplication;
857                                 break;
858                         default:
859                                 file_kind = PEFileKinds.ConsoleApplication;
860                                 break;
861                         }
862
863                         if (entry_point == null) {
864                                 if (RootContext.MainClass != null) {
865                                         // TODO: Should use MemberCache
866                                         DeclSpace main_cont = module.GetDefinition (RootContext.MainClass) as DeclSpace;
867                                         if (main_cont == null) {
868                                                 Report.Error (1555, "Could not find `{0}' specified for Main method", RootContext.MainClass);
869                                                 return;
870                                         }
871
872                                         if (!(main_cont is ClassOrStruct)) {
873                                                 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", RootContext.MainClass);
874                                                 return;
875                                         }
876
877                                         Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
878                                         return;
879                                 }
880
881                                 if (Report.Errors == 0) {
882                                         string pname = file_name == null ? name : Path.GetFileName (file_name);
883
884                                         Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
885                                                 pname);
886                                 }
887
888                                 return;
889                         }
890
891                         Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
892                 }
893
894                 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
895                 {
896                         Report.Warning (1699, 1, a.Location,
897                                 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
898                                 option, a.Name);
899                 }
900
901                 void Error_AssemblySigning (string text)
902                 {
903                         Report.Error (1548, "Error during assembly signing. " + text);
904                 }
905
906                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
907                 {
908                         return false;
909                 }
910
911                 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
912                 {
913                         string[] parts = version.Split ('.');
914                         if (parts.Length < 1 || parts.Length > 4)
915                                 return null;
916
917                         var values = new int[4];
918                         for (int i = 0; i < parts.Length; ++i) {
919                                 if (!int.TryParse (parts[i], out values[i])) {
920                                         if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
921                                                 if (i == 2) {
922                                                         // Nothing can follow *
923                                                         if (parts.Length > 3)
924                                                                 return null;
925
926                                                         // Generate Build value based on days since 1/1/2000
927                                                         TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
928                                                         values[i] = System.Math.Max (days.Days, 0);
929                                                         i = 3;
930                                                 }
931
932                                                 if (i == 3) {
933                                                         // Generate Revision value based on every other second today
934                                                         var seconds = DateTime.Now - DateTime.Today;
935                                                         values[i] = (int) seconds.TotalSeconds / 2;
936                                                         continue;
937                                                 }
938                                         }
939
940                                         return null;
941                                 }
942
943                                 if (values[i] > ushort.MaxValue)
944                                         return null;
945                         }
946
947                         return new Version (values[0], values[1], values[2], values[3]);
948                 }
949         }
950
951         public class AssemblyResource : IEquatable<AssemblyResource>
952         {
953                 public AssemblyResource (string fileName, string name)
954                         : this (fileName, name, false)
955                 {
956                 }
957
958                 public AssemblyResource (string fileName, string name, bool isPrivate)
959                 {
960                         FileName = fileName;
961                         Name = name;
962                         Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
963                 }
964
965                 public ResourceAttributes Attributes { get; private set; }
966                 public string Name { get; private set; }
967                 public string FileName { get; private set; }
968                 public bool IsEmbeded { get; set; }
969
970                 #region IEquatable<AssemblyResource> Members
971
972                 public bool Equals (AssemblyResource other)
973                 {
974                         return Name == other.Name;
975                 }
976
977                 #endregion
978         }
979
980         //
981         // A placeholder class for assembly attributes when emitting module
982         //
983         class AssemblyAttributesPlaceholder : CompilerGeneratedClass
984         {
985                 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
986                 public static readonly string AssemblyFieldName = "attributes";
987
988                 Field assembly;
989
990                 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
991                         : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC)
992                 {
993                         assembly = new Field (this, new TypeExpression (TypeManager.object_type, Location), Modifiers.PUBLIC | Modifiers.STATIC,
994                                 new MemberName (AssemblyFieldName), null);
995
996                         AddField (assembly);
997                 }
998
999                 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1000                 {
1001                         assembly.SetCustomAttribute (ctor, data);
1002                 }
1003
1004                 public static string GetGeneratedName (string outputName)
1005                 {
1006                         return string.Format (TypeNamePrefix, outputName);
1007                 }
1008         }
1009
1010         //
1011         // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1012         // compiler. This is a default implementation for framework System.Reflection.Emit
1013         // which does not implement any of the methods
1014         //
1015         public class AssemblyBuilderExtension
1016         {
1017                 readonly CompilerContext ctx;
1018
1019                 public AssemblyBuilderExtension (CompilerContext ctx)
1020                 {
1021                         this.ctx = ctx;
1022                 }
1023
1024                 public virtual System.Reflection.Module AddModule (string module)
1025                 {
1026                         ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1027                         return null;
1028                 }
1029
1030                 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1031                 {
1032                         ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1033                 }
1034
1035                 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1036                 {
1037                         ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1038                 }
1039
1040                 public virtual void DefineWin32IconResource (string fileName)
1041                 {
1042                         ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1043                 }
1044
1045                 public virtual void SetAlgorithmId (uint value, Location loc)
1046                 {
1047                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1048                 }
1049
1050                 public virtual void SetCulture (string culture, Location loc)
1051                 {
1052                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1053                 }
1054
1055                 public virtual void SetFlags (uint flags, Location loc)
1056                 {
1057                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1058                 }
1059
1060                 public virtual void SetVersion (Version version, Location loc)
1061                 {
1062                         ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1063                 }
1064         }
1065
1066         abstract class AssemblyReferencesLoader<T>
1067         {
1068                 protected readonly CompilerContext compiler;
1069
1070                 protected readonly List<string> paths;
1071                 readonly string[] default_references;
1072
1073                 public AssemblyReferencesLoader (CompilerContext compiler)
1074                 {
1075                         this.compiler = compiler;
1076
1077                         if (RootContext.LoadDefaultReferences)
1078                                 default_references = GetDefaultReferences ();
1079                         else
1080                                 default_references = new string[0];
1081
1082                         paths = new List<string> ();
1083                         paths.AddRange (RootContext.ReferencesLookupPaths);
1084                         paths.Add (Directory.GetCurrentDirectory ());
1085                 }
1086
1087                 public abstract bool HasObjectType (T assembly);
1088                 protected abstract string[] GetDefaultReferences ();
1089                 public abstract T LoadAssemblyFile (string fileName);
1090                 public abstract T LoadAssemblyDefault (string assembly);
1091                 public abstract void LoadReferences (ModuleContainer module);
1092
1093                 protected void Error_FileNotFound (string fileName)
1094                 {
1095                         compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1096                 }
1097
1098                 protected void Error_FileCorrupted (string fileName)
1099                 {
1100                         compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1101                 }
1102
1103                 protected void Error_AssemblyIsModule (string fileName)
1104                 {
1105                         compiler.Report.Error (1509,
1106                                 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1107                                 fileName);
1108                 }
1109
1110                 protected void Error_ModuleIsAssembly (string fileName)
1111                 {
1112                         compiler.Report.Error (1542,
1113                                 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1114                                 fileName);
1115                 }
1116
1117                 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1118                 {
1119                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1120
1121                         loaded = new List<Tuple<RootNamespace, T>> ();
1122
1123                         //
1124                         // Load mscorlib.dll as the first
1125                         //
1126                         if (RootContext.StdLib) {
1127                                 corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
1128                         } else {
1129                                 corlib_assembly = default (T);
1130                         }
1131
1132                         T a;
1133                         foreach (string r in default_references) {
1134                                 a = LoadAssemblyDefault (r);
1135                                 if (a != null)
1136                                         loaded.Add (Tuple.Create (module.GlobalRootNamespace, a));
1137                         }
1138
1139                         foreach (string r in RootContext.AssemblyReferences) {
1140                                 a = LoadAssemblyFile (r);
1141                                 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1142                                         continue;
1143
1144                                 var key = Tuple.Create (module.GlobalRootNamespace, a);
1145                                 if (loaded.Contains (key))
1146                                         continue;
1147
1148                                 // A corlib assembly is the first assembly which contains System.Object
1149                                 if (corlib_assembly == null && HasObjectType (a)) {
1150                                         corlib_assembly = a;
1151                                         continue;
1152                                 }
1153
1154                                 loaded.Add (key);
1155                         }
1156
1157                         foreach (var entry in RootContext.AssemblyReferencesAliases) {
1158                                 a = LoadAssemblyFile (entry.Item2);
1159                                 if (a == null)
1160                                         continue;
1161
1162                                 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1163                                 if (loaded.Contains (key))
1164                                         continue;
1165
1166                                 loaded.Add (key);
1167                         }
1168
1169                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);
1170                 }
1171         }
1172 }