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