2 // assembly.cs: Assembly declaration and specifications
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004 Novell, Inc.
15 using System.Collections.Generic;
16 using System.Globalization;
17 using System.Security;
18 using System.Security.Cryptography;
19 using System.Security.Permissions;
20 using Mono.Security.Cryptography;
21 using Mono.CompilerServices.SymbolWriter;
24 using IKVM.Reflection;
25 using IKVM.Reflection.Emit;
26 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
28 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
29 using System.Reflection;
30 using System.Reflection.Emit;
35 public interface IAssemblyDefinition
37 string FullName { get; }
38 bool HasExtensionMethod { get; }
39 bool IsCLSCompliant { get; }
40 bool IsMissing { get; }
43 byte[] GetPublicKeyToken ();
44 bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
47 public abstract class AssemblyDefinition : IAssemblyDefinition
49 // TODO: make it private and move all builder based methods here
50 public AssemblyBuilder Builder;
51 protected AssemblyBuilderExtension builder_extra;
52 MonoSymbolWriter symbol_writer;
54 bool is_cls_compliant;
55 bool wrap_non_exception_throws;
56 bool wrap_non_exception_throws_custom;
58 protected ModuleContainer module;
60 protected readonly string file_name;
62 byte[] public_key, public_key_token;
65 // Holds private/public key pair when private key
67 StrongNameKeyPair private_key;
69 Attribute cls_attribute;
72 protected List<ImportedModuleDefinition> added_modules;
73 SecurityType declarative_security;
74 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
75 AssemblyAttributesPlaceholder module_target_attrs;
77 protected AssemblyDefinition (ModuleContainer module, string name)
80 this.name = Path.GetFileNameWithoutExtension (name);
82 wrap_non_exception_throws = true;
84 delay_sign = Compiler.Settings.StrongNameDelaySign;
87 // Load strong name key early enough for assembly importer to be able to
88 // use the keys for InternalsVisibleTo
89 // This should go somewhere close to ReferencesLoading but don't have the place yet
91 if (Compiler.Settings.HasKeyFileOrContainer) {
92 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
96 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
99 this.file_name = fileName;
104 public Attribute CLSCompliantAttribute {
106 return cls_attribute;
110 public CompilerContext Compiler {
112 return module.Compiler;
117 // Assembly entry point, aka Main method
119 public Method EntryPoint {
128 public string FullName {
130 return Builder.FullName;
134 public bool HasExtensionMethod {
136 return module.HasExtensionMethod;
140 public bool HasCLSCompliantAttribute {
142 return cls_attribute != null;
146 // TODO: This should not exist here but will require more changes
147 public MetadataImporter Importer {
151 public bool IsCLSCompliant {
153 return is_cls_compliant;
157 bool IAssemblyDefinition.IsMissing {
169 public bool WrapNonExceptionThrows {
171 return wrap_non_exception_throws;
175 protected Report Report {
177 return Compiler.Report;
183 public void AddModule (ImportedModuleDefinition module)
185 if (added_modules == null) {
186 added_modules = new List<ImportedModuleDefinition> ();
187 added_modules.Add (module);
191 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
193 if (a.IsValidSecurityAttribute ()) {
194 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
198 if (a.Type == pa.AssemblyCulture) {
199 string value = a.GetString ();
200 if (value == null || value.Length == 0)
203 if (Compiler.Settings.Target == Target.Exe) {
204 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
208 if (value == "neutral")
211 if (Compiler.Settings.Target == Target.Module) {
212 SetCustomAttribute (ctor, cdata);
214 builder_extra.SetCulture (value, a.Location);
220 if (a.Type == pa.AssemblyVersion) {
221 string value = a.GetString ();
222 if (value == null || value.Length == 0)
225 var vinfo = IsValidAssemblyVersion (value, true);
227 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
231 if (Compiler.Settings.Target == Target.Module) {
232 SetCustomAttribute (ctor, cdata);
234 builder_extra.SetVersion (vinfo, a.Location);
240 if (a.Type == pa.AssemblyAlgorithmId) {
241 const int pos = 2; // skip CA header
242 uint alg = (uint) cdata [pos];
243 alg |= ((uint) cdata [pos + 1]) << 8;
244 alg |= ((uint) cdata [pos + 2]) << 16;
245 alg |= ((uint) cdata [pos + 3]) << 24;
247 if (Compiler.Settings.Target == Target.Module) {
248 SetCustomAttribute (ctor, cdata);
250 builder_extra.SetAlgorithmId (alg, a.Location);
256 if (a.Type == pa.AssemblyFlags) {
257 const int pos = 2; // skip CA header
258 uint flags = (uint) cdata[pos];
259 flags |= ((uint) cdata [pos + 1]) << 8;
260 flags |= ((uint) cdata [pos + 2]) << 16;
261 flags |= ((uint) cdata [pos + 3]) << 24;
263 // Ignore set PublicKey flag if assembly is not strongnamed
264 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
265 flags &= ~(uint) AssemblyNameFlags.PublicKey;
267 if (Compiler.Settings.Target == Target.Module) {
268 SetCustomAttribute (ctor, cdata);
270 builder_extra.SetFlags (flags, a.Location);
276 if (a.Type == pa.TypeForwarder) {
277 TypeSpec t = a.GetArgumentType ();
278 if (t == null || TypeManager.HasElementType (t)) {
279 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
283 if (emitted_forwarders == null) {
284 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
285 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
286 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
287 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
288 TypeManager.CSharpName (t));
292 emitted_forwarders.Add (t.MemberDefinition, a);
294 if (t.MemberDefinition.DeclaringAssembly == this) {
295 Report.SymbolRelatedToPreviousError (t);
296 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
297 TypeManager.CSharpName (t));
302 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
303 TypeManager.CSharpName (t));
307 builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
311 if (a.Type == pa.Extension) {
312 a.Error_MisusedExtensionAttribute ();
316 if (a.Type == pa.InternalsVisibleTo) {
317 string assembly_name = a.GetString ();
318 if (assembly_name.Length == 0)
321 AssemblyName aname = null;
323 aname = new AssemblyName (assembly_name);
324 } catch (Exception) {
325 Report.Warning (1700, 3, a.Location, "Assembly reference `{0}' is invalid and cannot be resolved",
330 if (aname.Version != null || aname.CultureInfo != 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",
338 // TODO: GetPublicKey () does not work on .NET when AssemblyName is constructed from a string
339 if (public_key != null && aname.GetPublicKey () == null) {
340 Report.Error (1726, a.Location,
341 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
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",
357 SetCustomAttribute (ctor, cdata);
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
365 void CheckReferencesPublicToken ()
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;
374 if (public_key != null && !a.HasStrongName) {
375 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
379 if (!a.IsFriendAssemblyTo (this))
382 var attr = a.GetAssemblyVisibleToName (this);
383 var atoken = attr.GetPublicKeyToken ();
385 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
388 Report.SymbolRelatedToPreviousError (a.Location);
390 "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",
391 attr.FullName, FullName);
395 protected AssemblyName CreateAssemblyName ()
397 var an = new AssemblyName (name);
399 if (public_key != null && Compiler.Settings.Target != Target.Module) {
401 an.SetPublicKey (public_key);
403 if (public_key.Length == 16) {
404 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
405 } else if (private_key == null) {
406 Error_AssemblySigning ("The specified key file does not have a private key");
408 an.KeyPair = private_key;
416 public virtual ModuleBuilder CreateModuleBuilder ()
418 if (file_name == null)
419 throw new NotSupportedException ("transient module in static assembly");
421 var module_name = Path.GetFileName (file_name);
423 // Always initialize module without symbolInfo. We could be framework dependent
424 // but returned ISymbolWriter does not have all what we need therefore some
425 // adaptor will be needed for now we alwayas emit MDB format when generating
427 return Builder.DefineDynamicModule (module_name, module_name, false);
430 public virtual void Emit ()
432 if (Compiler.Settings.Target == Target.Module) {
433 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
434 module_target_attrs.CreateType ();
435 module_target_attrs.DefineType ();
436 module_target_attrs.Define ();
437 module.AddCompilerGeneratedClass (module_target_attrs);
438 } else if (added_modules != null) {
439 ReadModulesAssemblyAttributes ();
442 if (Compiler.Settings.GenerateDebugInfo) {
443 symbol_writer = new MonoSymbolWriter (file_name);
445 // TODO: global variables
446 Location.DefineSymbolDocuments (symbol_writer);
447 SymbolWriter.symwriter = symbol_writer;
452 if (module.HasExtensionMethod) {
453 var pa = module.PredefinedAttributes.Extension;
455 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
459 if (!wrap_non_exception_throws_custom) {
460 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
461 if (pa.IsDefined && pa.ResolveBuilder ()) {
462 var prop = pa.GetProperty ("WrapNonExceptionThrows", Compiler.BuildinTypes.Bool, Location.Null);
464 AttributeEncoder encoder = new AttributeEncoder ();
465 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuildinTypes, true, Location.Null));
466 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
471 if (declarative_security != null) {
473 foreach (var entry in declarative_security) {
474 Builder.__AddDeclarativeSecurity (entry);
477 var args = new PermissionSet[3];
478 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
479 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
480 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
481 builder_extra.AddPermissionRequests (args);
485 CheckReferencesPublicToken ();
490 public byte[] GetPublicKeyToken ()
492 if (public_key == null || public_key_token != null)
493 return public_key_token;
495 HashAlgorithm ha = SHA1.Create ();
496 byte[] hash = ha.ComputeHash (public_key);
497 // we need the last 8 bytes in reverse order
498 public_key_token = new byte[8];
499 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
500 Array.Reverse (public_key_token, 0, 8);
501 return public_key_token;
505 // Either keyFile or keyContainer has to be non-null
507 void LoadPublicKey (string keyFile, string keyContainer)
509 if (keyContainer != null) {
511 private_key = new StrongNameKeyPair (keyContainer);
512 public_key = private_key.PublicKey;
514 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
520 bool key_file_exists = File.Exists (keyFile);
523 // For attribute based KeyFile do additional lookup
524 // in output assembly path
526 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
528 // The key file can be relative to output assembly
530 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
531 key_file_exists = File.Exists (test_path);
536 if (!key_file_exists) {
537 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
541 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
542 byte[] snkeypair = new byte[fs.Length];
543 fs.Read (snkeypair, 0, snkeypair.Length);
545 // check for ECMA key
546 if (snkeypair.Length == 16) {
547 public_key = snkeypair;
552 // take it, with or without, a private key
553 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
554 // and make sure we only feed the public part to Sys.Ref
555 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
557 // AssemblyName.SetPublicKey requires an additional header
558 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
561 public_key = new byte[12 + publickey.Length];
562 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
564 // Length of Public Key (in bytes)
565 int lastPart = public_key.Length - 12;
566 public_key[8] = (byte) (lastPart & 0xFF);
567 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
568 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
569 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
571 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
573 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
581 // TODO: Is there better way to test for a private key presence ?
582 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
583 private_key = new StrongNameKeyPair (snkeypair);
588 void ReadModulesAssemblyAttributes ()
590 foreach (var m in added_modules) {
591 var cattrs = m.ReadAssemblyAttributes ();
595 module.OptAttributes.AddAttributes (cattrs);
599 public void Resolve ()
601 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
603 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
604 // when -unsafe option was specified
606 Location loc = Location.Null;
608 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
609 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
611 var req_min = (ConstSpec) module.PredefinedTypes.SecurityAction.GetField ("RequestMinimum", module.PredefinedTypes.SecurityAction.TypeSpec, loc);
613 Arguments pos = new Arguments (1);
614 pos.Add (new Argument (req_min.GetConstant (null)));
616 Arguments named = new Arguments (1);
617 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuildinTypes, true, loc)));
619 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (module, null, null, null), "assembly",
620 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
621 new Arguments[] { pos, named }, loc, false);
622 g.AttachTo (module, module);
623 var ctor = g.Resolve ();
625 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
629 if (module.OptAttributes == null)
632 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
633 if (!module.OptAttributes.CheckTargets())
636 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
638 if (cls_attribute != null) {
639 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
642 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
643 foreach (var m in added_modules) {
644 if (!m.IsCLSCompliant) {
646 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
652 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
654 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
656 wrap_non_exception_throws = val.Value;
660 protected void ResolveAssemblySecurityAttributes ()
662 string key_file = null;
663 string key_container = null;
665 if (module.OptAttributes != null) {
666 foreach (Attribute a in module.OptAttributes.Attrs) {
667 // cannot rely on any resolve-based members before you call Resolve
668 if (a.ExplicitTarget != "assembly")
671 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
672 // However, this is invoked by CodeGen.Init, when none of the namespaces
674 // TODO: Does not handle quoted attributes properly
676 case "AssemblyKeyFile":
677 case "AssemblyKeyFileAttribute":
678 case "System.Reflection.AssemblyKeyFileAttribute":
679 if (Compiler.Settings.StrongNameKeyFile != null) {
680 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
681 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
682 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
684 string value = a.GetString ();
685 if (!string.IsNullOrEmpty (value)) {
686 Error_ObsoleteSecurityAttribute (a, "keyfile");
691 case "AssemblyKeyName":
692 case "AssemblyKeyNameAttribute":
693 case "System.Reflection.AssemblyKeyNameAttribute":
694 if (Compiler.Settings.StrongNameKeyContainer != null) {
695 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
696 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
697 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
699 string value = a.GetString ();
700 if (!string.IsNullOrEmpty (value)) {
701 Error_ObsoleteSecurityAttribute (a, "keycontainer");
702 key_container = value;
706 case "AssemblyDelaySign":
707 case "AssemblyDelaySignAttribute":
708 case "System.Reflection.AssemblyDelaySignAttribute":
709 bool b = a.GetBoolean ();
711 Error_ObsoleteSecurityAttribute (a, "delaysign");
720 // We came here only to report assembly attributes warnings
721 if (public_key != null)
725 // Load the strong key file found in attributes when no
726 // command line key was given
728 if (key_file != null || key_container != null) {
729 LoadPublicKey (key_file, key_container);
730 } else if (delay_sign) {
731 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
735 public void EmbedResources ()
738 // Add Win32 resources
740 if (Compiler.Settings.Win32ResourceFile != null) {
741 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
743 Builder.DefineVersionInfoResource ();
746 if (Compiler.Settings.Win32IconFile != null) {
747 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
750 if (Compiler.Settings.Resources != null) {
751 if (Compiler.Settings.Target == Target.Module) {
752 Report.Error (1507, "Cannot link resource file when building a module");
755 foreach (var res in Compiler.Settings.Resources) {
756 if (!File.Exists (res.FileName)) {
757 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
763 if (counter++ < 10) {
764 stream = File.OpenRead (res.FileName);
766 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
767 // we workaround it by reading everything into memory to compile projects with
768 // many embedded resource (over 3500) references
769 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
772 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
774 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
783 PortableExecutableKinds pekind;
784 ImageFileMachine machine;
786 switch (Compiler.Settings.Platform) {
788 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
789 machine = ImageFileMachine.I386;
792 pekind = PortableExecutableKinds.ILOnly;
793 machine = ImageFileMachine.AMD64;
796 pekind = PortableExecutableKinds.ILOnly;
797 machine = ImageFileMachine.IA64;
799 case Platform.AnyCPU:
801 pekind = PortableExecutableKinds.ILOnly;
802 machine = ImageFileMachine.I386;
806 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
808 if (Compiler.Settings.Target == Target.Module) {
809 SaveModule (pekind, machine);
811 Builder.Save (module.Builder.ScopeName, pekind, machine);
813 } catch (Exception e) {
814 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
816 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
818 // Save debug symbols file
819 if (symbol_writer != null) {
820 // TODO: it should run in parallel
821 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
822 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
823 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
827 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
829 Report.RuntimeMissingSupport (Location.Null, "-target:module");
832 void SetCustomAttribute (MethodSpec ctor, byte[] data)
834 if (module_target_attrs != null)
835 module_target_attrs.AddAssemblyAttribute (ctor, data);
837 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
840 void SetEntryPoint ()
842 if (!Compiler.Settings.NeedsEntryPoint) {
843 if (Compiler.Settings.MainClass != null)
844 Report.Error (2017, "Cannot specify -main if building a module or library");
849 PEFileKinds file_kind;
851 switch (Compiler.Settings.Target) {
854 file_kind = PEFileKinds.Dll;
857 file_kind = PEFileKinds.WindowApplication;
860 file_kind = PEFileKinds.ConsoleApplication;
864 if (entry_point == null) {
865 if (Compiler.Settings.MainClass != null) {
866 // TODO: Should use MemberCache
867 DeclSpace main_cont = module.GetDefinition (Compiler.Settings.MainClass) as DeclSpace;
868 if (main_cont == null) {
869 Report.Error (1555, "Could not find `{0}' specified for Main method", Compiler.Settings.MainClass);
873 if (!(main_cont is ClassOrStruct)) {
874 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", Compiler.Settings.MainClass);
878 Report.Error (1558, main_cont.Location, "`{0}' does not have a suitable static Main method", main_cont.GetSignatureForError ());
882 if (Report.Errors == 0) {
883 string pname = file_name == null ? name : Path.GetFileName (file_name);
885 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
892 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
895 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
897 Report.Warning (1699, 1, a.Location,
898 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
902 void Error_AssemblySigning (string text)
904 Report.Error (1548, "Error during assembly signing. " + text);
907 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
912 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
914 string[] parts = version.Split ('.');
915 if (parts.Length < 1 || parts.Length > 4)
918 var values = new int[4];
919 for (int i = 0; i < parts.Length; ++i) {
920 if (!int.TryParse (parts[i], out values[i])) {
921 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
923 // Nothing can follow *
924 if (parts.Length > 3)
927 // Generate Build value based on days since 1/1/2000
928 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
929 values[i] = System.Math.Max (days.Days, 0);
934 // Generate Revision value based on every other second today
935 var seconds = DateTime.Now - DateTime.Today;
936 values[i] = (int) seconds.TotalSeconds / 2;
944 if (values[i] > ushort.MaxValue)
948 return new Version (values[0], values[1], values[2], values[3]);
952 public class AssemblyResource : IEquatable<AssemblyResource>
954 public AssemblyResource (string fileName, string name)
955 : this (fileName, name, false)
959 public AssemblyResource (string fileName, string name, bool isPrivate)
963 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
966 public ResourceAttributes Attributes { get; private set; }
967 public string Name { get; private set; }
968 public string FileName { get; private set; }
969 public bool IsEmbeded { get; set; }
971 #region IEquatable<AssemblyResource> Members
973 public bool Equals (AssemblyResource other)
975 return Name == other.Name;
982 // A placeholder class for assembly attributes when emitting module
984 class AssemblyAttributesPlaceholder : CompilerGeneratedClass
986 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
987 public static readonly string AssemblyFieldName = "attributes";
991 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
992 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC)
994 assembly = new Field (this, new TypeExpression (parent.Compiler.BuildinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
995 new MemberName (AssemblyFieldName), null);
1000 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1002 assembly.SetCustomAttribute (ctor, data);
1005 public static string GetGeneratedName (string outputName)
1007 return string.Format (TypeNamePrefix, outputName);
1012 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1013 // compiler. This is a default implementation for framework System.Reflection.Emit
1014 // which does not implement any of the methods
1016 public class AssemblyBuilderExtension
1018 readonly CompilerContext ctx;
1020 public AssemblyBuilderExtension (CompilerContext ctx)
1025 public virtual System.Reflection.Module AddModule (string module)
1027 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1031 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1033 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1036 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1038 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1041 public virtual void DefineWin32IconResource (string fileName)
1043 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1046 public virtual void SetAlgorithmId (uint value, Location loc)
1048 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1051 public virtual void SetCulture (string culture, Location loc)
1053 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1056 public virtual void SetFlags (uint flags, Location loc)
1058 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1061 public virtual void SetVersion (Version version, Location loc)
1063 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1067 abstract class AssemblyReferencesLoader<T>
1069 protected readonly CompilerContext compiler;
1071 protected readonly List<string> paths;
1073 public AssemblyReferencesLoader (CompilerContext compiler)
1075 this.compiler = compiler;
1077 paths = new List<string> ();
1078 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1079 paths.Add (Directory.GetCurrentDirectory ());
1082 public abstract bool HasObjectType (T assembly);
1083 protected abstract string[] GetDefaultReferences ();
1084 public abstract T LoadAssemblyFile (string fileName);
1085 public abstract T LoadAssemblyDefault (string assembly);
1086 public abstract void LoadReferences (ModuleContainer module);
1088 protected void Error_FileNotFound (string fileName)
1090 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1093 protected void Error_FileCorrupted (string fileName)
1095 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1098 protected void Error_AssemblyIsModule (string fileName)
1100 compiler.Report.Error (1509,
1101 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1105 protected void Error_ModuleIsAssembly (string fileName)
1107 compiler.Report.Error (1542,
1108 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1112 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1114 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1116 loaded = new List<Tuple<RootNamespace, T>> ();
1119 // Load mscorlib.dll as the first
1121 if (module.Compiler.Settings.StdLib) {
1122 corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
1124 corlib_assembly = default (T);
1128 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1129 a = LoadAssemblyFile (r);
1130 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1133 var key = Tuple.Create (module.GlobalRootNamespace, a);
1134 if (loaded.Contains (key))
1137 // A corlib assembly is the first assembly which contains System.Object
1138 if (corlib_assembly == null && HasObjectType (a)) {
1139 corlib_assembly = a;
1146 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1147 a = LoadAssemblyFile (entry.Item2);
1151 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1152 if (loaded.Contains (key))
1158 if (compiler.Settings.LoadDefaultReferences) {
1159 foreach (string r in GetDefaultReferences ()) {
1160 a = LoadAssemblyDefault (r);
1164 var key = Tuple.Create (module.GlobalRootNamespace, a);
1165 if (loaded.Contains (key))
1172 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);