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