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