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