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 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}'",
385 if (!a.IsFriendAssemblyTo (this))
388 var attr = a.GetAssemblyVisibleToName (this);
389 var atoken = attr.GetPublicKeyToken ();
391 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
394 Report.SymbolRelatedToPreviousError (a.Location);
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);
401 protected AssemblyName CreateAssemblyName ()
403 var an = new AssemblyName (name);
405 if (public_key != null && Compiler.Settings.Target != Target.Module) {
407 an.SetPublicKey (public_key);
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");
414 an.KeyPair = private_key;
422 public virtual ModuleBuilder CreateModuleBuilder ()
424 if (file_name == null)
425 throw new NotSupportedException ("transient module in static assembly");
427 var module_name = Path.GetFileName (file_name);
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
433 return Builder.DefineDynamicModule (module_name, module_name, false);
436 public virtual void Emit ()
438 if (Compiler.Settings.Target == Target.Module) {
439 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
440 module_target_attrs.CreateType ();
441 module_target_attrs.DefineType ();
442 module_target_attrs.Define ();
443 module.AddCompilerGeneratedClass (module_target_attrs);
444 } else if (added_modules != null) {
445 ReadModulesAssemblyAttributes ();
448 if (Compiler.Settings.GenerateDebugInfo) {
449 symbol_writer = new MonoSymbolWriter (file_name);
451 // Register all source files with symbol writer
452 foreach (var source in Compiler.SourceFiles) {
453 source.DefineSymbolInfo (symbol_writer);
456 // TODO: global variables
457 SymbolWriter.symwriter = symbol_writer;
462 if (module.HasExtensionMethod) {
463 var pa = module.PredefinedAttributes.Extension;
465 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
469 if (!wrap_non_exception_throws_custom) {
470 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
471 if (pa.IsDefined && pa.ResolveBuilder ()) {
472 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
474 AttributeEncoder encoder = new AttributeEncoder ();
475 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
476 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
481 if (declarative_security != null) {
483 foreach (var entry in declarative_security) {
484 Builder.__AddDeclarativeSecurity (entry);
487 var args = new PermissionSet[3];
488 declarative_security.TryGetValue (SecurityAction.RequestMinimum, out args[0]);
489 declarative_security.TryGetValue (SecurityAction.RequestOptional, out args[1]);
490 declarative_security.TryGetValue (SecurityAction.RequestRefuse, out args[2]);
491 builder_extra.AddPermissionRequests (args);
495 CheckReferencesPublicToken ();
500 public byte[] GetPublicKeyToken ()
502 if (public_key == null || public_key_token != null)
503 return public_key_token;
505 HashAlgorithm ha = SHA1.Create ();
506 byte[] hash = ha.ComputeHash (public_key);
507 // we need the last 8 bytes in reverse order
508 public_key_token = new byte[8];
509 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
510 Array.Reverse (public_key_token, 0, 8);
511 return public_key_token;
515 // Either keyFile or keyContainer has to be non-null
517 void LoadPublicKey (string keyFile, string keyContainer)
519 if (keyContainer != null) {
521 private_key = new StrongNameKeyPair (keyContainer);
522 public_key = private_key.PublicKey;
524 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
530 bool key_file_exists = File.Exists (keyFile);
533 // For attribute based KeyFile do additional lookup
534 // in output assembly path
536 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
538 // The key file can be relative to output assembly
540 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
541 key_file_exists = File.Exists (test_path);
546 if (!key_file_exists) {
547 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
551 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
552 byte[] snkeypair = new byte[fs.Length];
553 fs.Read (snkeypair, 0, snkeypair.Length);
555 // check for ECMA key
556 if (snkeypair.Length == 16) {
557 public_key = snkeypair;
562 // take it, with or without, a private key
563 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
564 // and make sure we only feed the public part to Sys.Ref
565 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
567 // AssemblyName.SetPublicKey requires an additional header
568 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
571 public_key = new byte[12 + publickey.Length];
572 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
574 // Length of Public Key (in bytes)
575 int lastPart = public_key.Length - 12;
576 public_key[8] = (byte) (lastPart & 0xFF);
577 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
578 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
579 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
581 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
583 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
591 // TODO: Is there better way to test for a private key presence ?
592 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
593 private_key = new StrongNameKeyPair (snkeypair);
598 void ReadModulesAssemblyAttributes ()
600 foreach (var m in added_modules) {
601 var cattrs = m.ReadAssemblyAttributes ();
605 module.OptAttributes.AddAttributes (cattrs);
609 public void Resolve ()
611 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
613 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
614 // when -unsafe option was specified
616 Location loc = Location.Null;
618 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
619 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
621 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
623 Arguments pos = new Arguments (1);
624 pos.Add (new Argument (req_min.GetConstant (null)));
626 Arguments named = new Arguments (1);
627 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
629 Attribute g = new Attribute ("assembly",
630 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
631 new Arguments[] { pos, named }, loc, false);
632 g.AttachTo (module, module);
633 var ctor = g.Resolve ();
635 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
639 if (module.OptAttributes == null)
642 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
643 if (!module.OptAttributes.CheckTargets())
646 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
648 if (cls_attribute != null) {
649 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
652 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
653 foreach (var m in added_modules) {
654 if (!m.IsCLSCompliant) {
656 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
662 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
664 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
666 wrap_non_exception_throws = val.Value;
670 protected void ResolveAssemblySecurityAttributes ()
672 string key_file = null;
673 string key_container = null;
675 if (module.OptAttributes != null) {
676 foreach (Attribute a in module.OptAttributes.Attrs) {
677 // cannot rely on any resolve-based members before you call Resolve
678 if (a.ExplicitTarget != "assembly")
681 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
682 // However, this is invoked by CodeGen.Init, when none of the namespaces
684 // TODO: Does not handle quoted attributes properly
686 case "AssemblyKeyFile":
687 case "AssemblyKeyFileAttribute":
688 case "System.Reflection.AssemblyKeyFileAttribute":
689 if (Compiler.Settings.StrongNameKeyFile != null) {
690 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
691 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
692 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
694 string value = a.GetString ();
695 if (!string.IsNullOrEmpty (value)) {
696 Error_ObsoleteSecurityAttribute (a, "keyfile");
701 case "AssemblyKeyName":
702 case "AssemblyKeyNameAttribute":
703 case "System.Reflection.AssemblyKeyNameAttribute":
704 if (Compiler.Settings.StrongNameKeyContainer != null) {
705 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
706 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
707 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
709 string value = a.GetString ();
710 if (!string.IsNullOrEmpty (value)) {
711 Error_ObsoleteSecurityAttribute (a, "keycontainer");
712 key_container = value;
716 case "AssemblyDelaySign":
717 case "AssemblyDelaySignAttribute":
718 case "System.Reflection.AssemblyDelaySignAttribute":
719 bool b = a.GetBoolean ();
721 Error_ObsoleteSecurityAttribute (a, "delaysign");
730 // We came here only to report assembly attributes warnings
731 if (public_key != null)
735 // Load the strong key file found in attributes when no
736 // command line key was given
738 if (key_file != null || key_container != null) {
739 LoadPublicKey (key_file, key_container);
740 } else if (delay_sign) {
741 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
745 public void EmbedResources ()
748 // Add Win32 resources
750 if (Compiler.Settings.Win32ResourceFile != null) {
751 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
753 Builder.DefineVersionInfoResource ();
756 if (Compiler.Settings.Win32IconFile != null) {
757 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
760 if (Compiler.Settings.Resources != null) {
761 if (Compiler.Settings.Target == Target.Module) {
762 Report.Error (1507, "Cannot link resource file when building a module");
765 foreach (var res in Compiler.Settings.Resources) {
766 if (!File.Exists (res.FileName)) {
767 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
773 if (counter++ < 10) {
774 stream = File.OpenRead (res.FileName);
776 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
777 // we workaround it by reading everything into memory to compile projects with
778 // many embedded resource (over 3500) references
779 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
782 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
784 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
793 PortableExecutableKinds pekind;
794 ImageFileMachine machine;
796 switch (Compiler.Settings.Platform) {
798 pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
799 machine = ImageFileMachine.I386;
802 pekind = PortableExecutableKinds.ILOnly;
803 machine = ImageFileMachine.AMD64;
806 pekind = PortableExecutableKinds.ILOnly;
807 machine = ImageFileMachine.IA64;
809 case Platform.AnyCPU:
811 pekind = PortableExecutableKinds.ILOnly;
812 machine = ImageFileMachine.I386;
816 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
818 if (Compiler.Settings.Target == Target.Module) {
819 SaveModule (pekind, machine);
821 Builder.Save (module.Builder.ScopeName, pekind, machine);
823 } catch (Exception e) {
824 Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
826 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
828 // Save debug symbols file
829 if (symbol_writer != null) {
830 // TODO: it should run in parallel
831 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
832 symbol_writer.WriteSymbolFile (SymbolWriter.GetGuid (module.Builder));
833 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
837 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
839 Report.RuntimeMissingSupport (Location.Null, "-target:module");
842 void SetCustomAttribute (MethodSpec ctor, byte[] data)
844 if (module_target_attrs != null)
845 module_target_attrs.AddAssemblyAttribute (ctor, data);
847 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
850 void SetEntryPoint ()
852 if (!Compiler.Settings.NeedsEntryPoint) {
853 if (Compiler.Settings.MainClass != null)
854 Report.Error (2017, "Cannot specify -main if building a module or library");
859 PEFileKinds file_kind;
861 switch (Compiler.Settings.Target) {
864 file_kind = PEFileKinds.Dll;
867 file_kind = PEFileKinds.WindowApplication;
870 file_kind = PEFileKinds.ConsoleApplication;
874 if (entry_point == null) {
875 string main_class = Compiler.Settings.MainClass;
876 if (main_class != null) {
877 // TODO: Handle dotted names
878 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
880 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
884 var mtype = texpr.Type.MemberDefinition as ClassOrStruct;
886 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
890 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
892 string pname = file_name == null ? name : Path.GetFileName (file_name);
893 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
900 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
903 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
905 Report.Warning (1699, 1, a.Location,
906 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
910 void Error_AssemblySigning (string text)
912 Report.Error (1548, "Error during assembly signing. " + text);
915 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
920 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
922 string[] parts = version.Split ('.');
923 if (parts.Length < 1 || parts.Length > 4)
926 var values = new int[4];
927 for (int i = 0; i < parts.Length; ++i) {
928 if (!int.TryParse (parts[i], out values[i])) {
929 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
931 // Nothing can follow *
932 if (parts.Length > 3)
935 // Generate Build value based on days since 1/1/2000
936 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
937 values[i] = System.Math.Max (days.Days, 0);
942 // Generate Revision value based on every other second today
943 var seconds = DateTime.Now - DateTime.Today;
944 values[i] = (int) seconds.TotalSeconds / 2;
952 if (values[i] > ushort.MaxValue)
956 return new Version (values[0], values[1], values[2], values[3]);
960 public class AssemblyResource : IEquatable<AssemblyResource>
962 public AssemblyResource (string fileName, string name)
963 : this (fileName, name, false)
967 public AssemblyResource (string fileName, string name, bool isPrivate)
971 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
974 public ResourceAttributes Attributes { get; private set; }
975 public string Name { get; private set; }
976 public string FileName { get; private set; }
977 public bool IsEmbeded { get; set; }
979 #region IEquatable<AssemblyResource> Members
981 public bool Equals (AssemblyResource other)
983 return Name == other.Name;
990 // A placeholder class for assembly attributes when emitting module
992 class AssemblyAttributesPlaceholder : CompilerGeneratedClass
994 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
995 public static readonly string AssemblyFieldName = "attributes";
999 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1000 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC)
1002 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1003 new MemberName (AssemblyFieldName), null);
1005 AddField (assembly);
1008 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1010 assembly.SetCustomAttribute (ctor, data);
1013 public static string GetGeneratedName (string outputName)
1015 return string.Format (TypeNamePrefix, outputName);
1020 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1021 // compiler. This is a default implementation for framework System.Reflection.Emit
1022 // which does not implement any of the methods
1024 public class AssemblyBuilderExtension
1026 readonly CompilerContext ctx;
1028 public AssemblyBuilderExtension (CompilerContext ctx)
1033 public virtual System.Reflection.Module AddModule (string module)
1035 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1039 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1041 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1044 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1046 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1049 public virtual void DefineWin32IconResource (string fileName)
1051 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1054 public virtual void SetAlgorithmId (uint value, Location loc)
1056 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1059 public virtual void SetCulture (string culture, Location loc)
1061 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1064 public virtual void SetFlags (uint flags, Location loc)
1066 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1069 public virtual void SetVersion (Version version, Location loc)
1071 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1075 abstract class AssemblyReferencesLoader<T>
1077 protected readonly CompilerContext compiler;
1079 protected readonly List<string> paths;
1081 public AssemblyReferencesLoader (CompilerContext compiler)
1083 this.compiler = compiler;
1085 paths = new List<string> ();
1086 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1087 paths.Add (Directory.GetCurrentDirectory ());
1090 public abstract bool HasObjectType (T assembly);
1091 protected abstract string[] GetDefaultReferences ();
1092 public abstract T LoadAssemblyFile (string fileName);
1093 public abstract T LoadAssemblyDefault (string assembly);
1094 public abstract void LoadReferences (ModuleContainer module);
1096 protected void Error_FileNotFound (string fileName)
1098 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1101 protected void Error_FileCorrupted (string fileName)
1103 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1106 protected void Error_AssemblyIsModule (string fileName)
1108 compiler.Report.Error (1509,
1109 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1113 protected void Error_ModuleIsAssembly (string fileName)
1115 compiler.Report.Error (1542,
1116 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1120 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1122 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1124 loaded = new List<Tuple<RootNamespace, T>> ();
1127 // Load mscorlib.dll as the first
1129 if (module.Compiler.Settings.StdLib) {
1130 corlib_assembly = LoadAssemblyDefault ("mscorlib.dll");
1132 corlib_assembly = default (T);
1136 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1137 a = LoadAssemblyFile (r);
1138 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1141 var key = Tuple.Create (module.GlobalRootNamespace, a);
1142 if (loaded.Contains (key))
1145 // A corlib assembly is the first assembly which contains System.Object
1146 if (corlib_assembly == null && HasObjectType (a)) {
1147 corlib_assembly = a;
1154 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1155 a = LoadAssemblyFile (entry.Item2);
1159 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1160 if (loaded.Contains (key))
1166 if (compiler.Settings.LoadDefaultReferences) {
1167 foreach (string r in GetDefaultReferences ()) {
1168 a = LoadAssemblyDefault (r);
1172 var key = Tuple.Create (module.GlobalRootNamespace, a);
1173 if (loaded.Contains (key))
1180 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);