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