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