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-2011 Novell, Inc.
10 // Copyright 2011-2013 Xamarin Inc
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;
25 using IKVM.Reflection;
26 using IKVM.Reflection.Emit;
27 using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
29 using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
30 using System.Reflection;
31 using System.Reflection.Emit;
36 public interface IAssemblyDefinition
38 string FullName { 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 MonoSymbolFile symbol_writer;
54 bool is_cls_compliant;
55 bool wrap_non_exception_throws;
56 bool wrap_non_exception_throws_custom;
57 bool has_user_debuggable;
59 protected ModuleContainer module;
61 protected readonly string file_name;
63 byte[] public_key, public_key_token;
66 // Holds private/public key pair when private key
68 StrongNameKeyPair private_key;
70 Attribute cls_attribute;
73 protected List<ImportedModuleDefinition> added_modules;
74 SecurityType declarative_security;
75 Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
76 AssemblyAttributesPlaceholder module_target_attrs;
78 // Win32 version info values
79 string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
80 string pa_file_version, pa_assembly_version;
82 protected AssemblyDefinition (ModuleContainer module, string name)
85 this.name = Path.GetFileNameWithoutExtension (name);
87 wrap_non_exception_throws = true;
89 delay_sign = Compiler.Settings.StrongNameDelaySign;
92 // Load strong name key early enough for assembly importer to be able to
93 // use the keys for InternalsVisibleTo
94 // This should go somewhere close to ReferencesLoading but don't have the place yet
96 if (Compiler.Settings.HasKeyFileOrContainer) {
97 LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
101 protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
102 : this (module, name)
104 this.file_name = fileName;
109 public Attribute CLSCompliantAttribute {
111 return cls_attribute;
115 public CompilerContext Compiler {
117 return module.Compiler;
122 // Assembly entry point, aka Main method
124 public Method EntryPoint {
133 public string FullName {
135 return Builder.FullName;
139 public bool HasCLSCompliantAttribute {
141 return cls_attribute != null;
145 // TODO: This should not exist here but will require more changes
146 public MetadataImporter Importer {
150 public bool IsCLSCompliant {
152 return is_cls_compliant;
156 bool IAssemblyDefinition.IsMissing {
162 public bool IsSatelliteAssembly { get; private set; }
170 public bool WrapNonExceptionThrows {
172 return wrap_non_exception_throws;
176 protected Report Report {
178 return Compiler.Report;
182 public MonoSymbolFile SymbolWriter {
184 return symbol_writer;
190 public void AddModule (ImportedModuleDefinition module)
192 if (added_modules == null) {
193 added_modules = new List<ImportedModuleDefinition> ();
194 added_modules.Add (module);
198 public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
200 if (a.IsValidSecurityAttribute ()) {
201 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
205 if (a.Type == pa.AssemblyCulture) {
206 string value = a.GetString ();
207 if (value == null || value.Length == 0)
210 if (Compiler.Settings.Target == Target.Exe) {
211 Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
215 if (value == "neutral")
218 if (Compiler.Settings.Target == Target.Module) {
219 SetCustomAttribute (ctor, cdata);
221 builder_extra.SetCulture (value, a.Location);
224 IsSatelliteAssembly = true;
228 if (a.Type == pa.AssemblyVersion) {
229 string value = a.GetString ();
230 if (value == null || value.Length == 0)
233 var vinfo = IsValidAssemblyVersion (value, true);
235 Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
240 if (Compiler.Settings.Target == Target.Module) {
241 SetCustomAttribute (ctor, cdata);
243 builder_extra.SetVersion (vinfo, a.Location);
244 pa_assembly_version = vinfo.ToString ();
250 if (a.Type == pa.AssemblyAlgorithmId) {
251 const int pos = 2; // skip CA header
252 uint alg = (uint) cdata [pos];
253 alg |= ((uint) cdata [pos + 1]) << 8;
254 alg |= ((uint) cdata [pos + 2]) << 16;
255 alg |= ((uint) cdata [pos + 3]) << 24;
257 if (Compiler.Settings.Target == Target.Module) {
258 SetCustomAttribute (ctor, cdata);
260 builder_extra.SetAlgorithmId (alg, a.Location);
266 if (a.Type == pa.AssemblyFlags) {
267 const int pos = 2; // skip CA header
268 uint flags = (uint) cdata[pos];
269 flags |= ((uint) cdata [pos + 1]) << 8;
270 flags |= ((uint) cdata [pos + 2]) << 16;
271 flags |= ((uint) cdata [pos + 3]) << 24;
273 // Ignore set PublicKey flag if assembly is not strongnamed
274 if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
275 flags &= ~(uint) AssemblyNameFlags.PublicKey;
277 if (Compiler.Settings.Target == Target.Module) {
278 SetCustomAttribute (ctor, cdata);
280 builder_extra.SetFlags (flags, a.Location);
286 if (a.Type == pa.TypeForwarder) {
287 TypeSpec t = a.GetArgumentType ();
288 if (t == null || TypeManager.HasElementType (t)) {
289 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
293 if (emitted_forwarders == null) {
294 emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
295 } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
296 Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
297 Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
298 t.GetSignatureForError ());
302 emitted_forwarders.Add (t.MemberDefinition, a);
304 if (t.MemberDefinition.DeclaringAssembly == this) {
305 Report.SymbolRelatedToPreviousError (t);
306 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
307 t.GetSignatureForError ());
312 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
313 t.GetSignatureForError ());
317 AddTypeForwarders (t, a.Location);
321 if (a.Type == pa.Extension) {
322 a.Error_MisusedExtensionAttribute ();
326 if (a.Type == pa.InternalsVisibleTo) {
327 string assembly_name = a.GetString ();
328 if (assembly_name == null) {
329 Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
333 if (assembly_name.Length == 0)
336 ParsedAssemblyName aname;
337 ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
338 if (r != ParseAssemblyResult.OK) {
339 Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
344 if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
345 Report.Error (1725, a.Location,
346 "Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
352 if (public_key != null && !aname.HasPublicKey) {
353 Report.Error (1726, a.Location,
354 "Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
359 } else if (a.Type == pa.RuntimeCompatibility) {
360 wrap_non_exception_throws_custom = true;
361 } else if (a.Type == pa.AssemblyFileVersion) {
362 pa_file_version = a.GetString ();
363 if (string.IsNullOrEmpty (pa_file_version) || IsValidAssemblyVersion (pa_file_version, false) == null) {
364 Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
365 pa_file_version, a.Name);
369 // File version info decoding from blob is not supported
370 var cab = new CustomAttributeBuilder ((ConstructorInfo)ctor.GetMetaInfo (), new object [] { pa_file_version });
371 Builder.SetCustomAttribute (cab);
373 } else if (a.Type == pa.AssemblyProduct) {
374 vi_product = a.GetString ();
375 } else if (a.Type == pa.AssemblyCompany) {
376 vi_company = a.GetString ();
377 } else if (a.Type == pa.AssemblyCopyright) {
378 vi_copyright = a.GetString ();
379 } else if (a.Type == pa.AssemblyTrademark) {
380 vi_trademark = a.GetString ();
381 } else if (a.Type == pa.Debuggable) {
382 has_user_debuggable = true;
383 } else if (a.Type == pa.AssemblyInformationalVersion) {
384 vi_product_version = a.GetString ();
388 // Win32 version info attributes AssemblyDescription and AssemblyTitle cannot be
389 // set using public API and because we have blob like attributes we need to use
390 // special option DecodeVersionInfoAttributeBlobs to support values extraction
393 SetCustomAttribute (ctor, cdata);
396 void AddTypeForwarders (TypeSpec type, Location loc)
398 builder_extra.AddTypeForwarder (type.GetDefinition (), loc);
400 var ntypes = MemberCache.GetDeclaredNestedTypes (type);
404 foreach (var nested in ntypes) {
405 if (nested.IsPrivate)
408 AddTypeForwarders (nested, loc);
413 // When using assembly public key attributes InternalsVisibleTo key
414 // was not checked, we have to do it later when we actually know what
415 // our public key token is
417 void CheckReferencesPublicToken ()
419 foreach (var an in builder_extra.GetReferencedAssemblies ()) {
420 if (public_key != null && an.GetPublicKey ().Length == 0) {
421 Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
425 var ci = an.CultureInfo;
426 if (!ci.Equals (CultureInfo.InvariantCulture)) {
427 Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
431 var ia = Importer.GetImportedAssemblyDefinition (an);
435 var references = GetNotUnifiedReferences (an);
436 if (references != null) {
437 foreach (var r in references) {
438 Report.SymbolRelatedToPreviousError ( r[0]);
439 Report.Error (1705, r [1]);
443 if (!ia.IsFriendAssemblyTo (this))
446 var attr = ia.GetAssemblyVisibleToName (this);
447 var atoken = attr.GetPublicKeyToken ();
449 if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
452 Report.SymbolRelatedToPreviousError (ia.Location);
454 "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",
455 attr.FullName, FullName);
459 protected AssemblyName CreateAssemblyName ()
461 var an = new AssemblyName (name);
463 if (public_key != null && Compiler.Settings.Target != Target.Module) {
465 an.SetPublicKey (public_key);
467 if (public_key.Length == 16) {
468 Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
469 } else if (private_key == null) {
470 Error_AssemblySigning ("The specified key file does not have a private key");
472 an.KeyPair = private_key;
480 public virtual ModuleBuilder CreateModuleBuilder ()
482 if (file_name == null)
483 throw new NotSupportedException ("transient module in static assembly");
485 var module_name = Path.GetFileName (file_name);
487 // Always initialize module without symbolInfo. We could be framework dependent
488 // but returned ISymbolWriter does not have all what we need therefore some
489 // adaptor will be needed for now we alwayas emit MDB format when generating
491 return Builder.DefineDynamicModule (module_name, module_name, false);
494 public virtual void Emit ()
496 if (Compiler.Settings.Target == Target.Module) {
497 module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
498 module_target_attrs.CreateContainer ();
499 module_target_attrs.DefineContainer ();
500 module_target_attrs.Define ();
501 module.AddCompilerGeneratedClass (module_target_attrs);
502 } else if (added_modules != null) {
503 ReadModulesAssemblyAttributes ();
506 if (Compiler.Settings.GenerateDebugInfo) {
507 symbol_writer = new MonoSymbolFile ();
510 module.EmitContainer ();
512 if (module.HasExtensionMethod) {
513 var pa = module.PredefinedAttributes.Extension;
515 SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
519 if (!IsSatelliteAssembly) {
520 if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
521 var pa = module.PredefinedAttributes.Debuggable;
523 var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
524 if (!Compiler.Settings.Optimize)
525 modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
527 pa.EmitAttribute (Builder, modes);
531 if (!wrap_non_exception_throws_custom) {
532 PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
533 if (pa.IsDefined && pa.ResolveBuilder ()) {
534 var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
536 AttributeEncoder encoder = new AttributeEncoder ();
537 encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
538 SetCustomAttribute (pa.Constructor, encoder.ToArray ());
543 if (declarative_security != null) {
545 foreach (var entry in declarative_security) {
546 Builder.__AddDeclarativeSecurity (entry);
549 throw new NotSupportedException ("Assembly-level security");
554 CheckReferencesPublicToken ();
559 public byte[] GetPublicKeyToken ()
561 if (public_key == null || public_key_token != null)
562 return public_key_token;
564 HashAlgorithm ha = SHA1.Create ();
565 byte[] hash = ha.ComputeHash (public_key);
566 // we need the last 8 bytes in reverse order
567 public_key_token = new byte[8];
568 Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
569 Array.Reverse (public_key_token, 0, 8);
570 return public_key_token;
573 protected virtual List<string[]> GetNotUnifiedReferences (AssemblyName assemblyName)
579 // Either keyFile or keyContainer has to be non-null
581 void LoadPublicKey (string keyFile, string keyContainer)
583 if (keyContainer != null) {
585 private_key = new StrongNameKeyPair (keyContainer);
586 public_key = private_key.PublicKey;
588 Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
594 bool key_file_exists = File.Exists (keyFile);
597 // For attribute based KeyFile do additional lookup
598 // in output assembly path
600 if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
602 // The key file can be relative to output assembly
604 string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
605 key_file_exists = File.Exists (test_path);
610 if (!key_file_exists) {
611 Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
615 using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
616 byte[] snkeypair = new byte[fs.Length];
617 fs.Read (snkeypair, 0, snkeypair.Length);
619 // check for ECMA key
620 if (snkeypair.Length == 16) {
621 public_key = snkeypair;
626 // take it, with or without, a private key
627 RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
628 // and make sure we only feed the public part to Sys.Ref
629 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
631 // AssemblyName.SetPublicKey requires an additional header
632 byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
635 public_key = new byte[12 + publickey.Length];
636 Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
638 // Length of Public Key (in bytes)
639 int lastPart = public_key.Length - 12;
640 public_key[8] = (byte) (lastPart & 0xFF);
641 public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
642 public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
643 public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
645 Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
647 Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
655 // TODO: Is there better way to test for a private key presence ?
656 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
657 private_key = new StrongNameKeyPair (snkeypair);
662 void ReadModulesAssemblyAttributes ()
664 foreach (var m in added_modules) {
665 var cattrs = m.ReadAssemblyAttributes ();
669 module.OptAttributes.AddAttributes (cattrs);
673 public void Resolve ()
675 if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
677 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
678 // when -unsafe option was specified
680 Location loc = Location.Null;
682 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
683 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
685 var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
687 Arguments pos = new Arguments (1);
688 pos.Add (new Argument (req_min.GetConstant (null)));
690 Arguments named = new Arguments (1);
691 named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
693 Attribute g = new Attribute ("assembly",
694 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
695 new Arguments[] { pos, named }, loc, false);
696 g.AttachTo (module, module);
698 // Disable no-location warnings (e.g. obsolete) for compiler generated attribute
699 Compiler.Report.DisableReporting ();
701 var ctor = g.Resolve ();
703 g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
706 Compiler.Report.EnableReporting ();
710 if (module.OptAttributes == null)
713 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
714 if (!module.OptAttributes.CheckTargets())
717 cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
719 if (cls_attribute != null) {
720 is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
723 if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
724 foreach (var m in added_modules) {
725 if (!m.IsCLSCompliant) {
727 "Added modules must be marked with the CLSCompliant attribute to match the assembly",
733 Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
735 var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
737 wrap_non_exception_throws = val.Value;
741 protected void ResolveAssemblySecurityAttributes ()
743 string key_file = null;
744 string key_container = null;
746 if (module.OptAttributes != null) {
747 foreach (Attribute a in module.OptAttributes.Attrs) {
748 // cannot rely on any resolve-based members before you call Resolve
749 if (a.ExplicitTarget != "assembly")
752 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
753 // However, this is invoked by CodeGen.Init, when none of the namespaces
755 // TODO: Does not handle quoted attributes properly
757 case "AssemblyKeyFile":
758 case "AssemblyKeyFileAttribute":
759 case "System.Reflection.AssemblyKeyFileAttribute":
760 if (Compiler.Settings.StrongNameKeyFile != null) {
761 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
762 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
763 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
765 string value = a.GetString ();
766 if (!string.IsNullOrEmpty (value)) {
767 Error_ObsoleteSecurityAttribute (a, "keyfile");
772 case "AssemblyKeyName":
773 case "AssemblyKeyNameAttribute":
774 case "System.Reflection.AssemblyKeyNameAttribute":
775 if (Compiler.Settings.StrongNameKeyContainer != null) {
776 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
777 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
778 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
780 string value = a.GetString ();
781 if (!string.IsNullOrEmpty (value)) {
782 Error_ObsoleteSecurityAttribute (a, "keycontainer");
783 key_container = value;
787 case "AssemblyDelaySign":
788 case "AssemblyDelaySignAttribute":
789 case "System.Reflection.AssemblyDelaySignAttribute":
790 bool b = a.GetBoolean ();
792 Error_ObsoleteSecurityAttribute (a, "delaysign");
801 // We came here only to report assembly attributes warnings
802 if (public_key != null)
806 // Load the strong key file found in attributes when no
807 // command line key was given
809 if (key_file != null || key_container != null) {
810 LoadPublicKey (key_file, key_container);
811 } else if (delay_sign) {
812 Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
816 public void EmbedResources ()
819 // Add Win32 resources
821 if (Compiler.Settings.Win32ResourceFile != null) {
822 Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
824 Builder.DefineVersionInfoResource (vi_product,
825 vi_product_version ?? pa_file_version ?? pa_assembly_version,
831 if (Compiler.Settings.Win32IconFile != null) {
832 builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
835 if (Compiler.Settings.Resources != null) {
836 if (Compiler.Settings.Target == Target.Module) {
837 Report.Error (1507, "Cannot link resource file when building a module");
840 foreach (var res in Compiler.Settings.Resources) {
841 if (!File.Exists (res.FileName)) {
842 Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
848 if (counter++ < 10) {
849 stream = File.OpenRead (res.FileName);
851 // TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
852 // we workaround it by reading everything into memory to compile projects with
853 // many embedded resource (over 3500) references
854 stream = new MemoryStream (File.ReadAllBytes (res.FileName));
857 module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
859 Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
868 PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
869 ImageFileMachine machine;
871 switch (Compiler.Settings.Platform) {
873 pekind |= PortableExecutableKinds.Required32Bit;
874 machine = ImageFileMachine.I386;
877 pekind |= PortableExecutableKinds.PE32Plus;
878 machine = ImageFileMachine.AMD64;
881 machine = ImageFileMachine.IA64;
883 case Platform.AnyCPU32Preferred:
885 pekind |= PortableExecutableKinds.Preferred32Bit;
886 machine = ImageFileMachine.I386;
889 throw new NotSupportedException ();
893 machine = ImageFileMachine.ARM;
896 throw new NotSupportedException ();
898 case Platform.AnyCPU:
900 machine = ImageFileMachine.I386;
904 Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
906 if (Compiler.Settings.Target == Target.Module) {
907 SaveModule (pekind, machine);
909 Builder.Save (module.Builder.ScopeName, pekind, machine);
911 } catch (ArgumentOutOfRangeException) {
912 Report.Error (16, "Output file `{0}' exceeds the 4GB limit");
913 } catch (Exception e) {
914 Report.Error (16, "Could not write to file `{0}'. {1}", name, e.Message);
916 Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
918 // Save debug symbols file
919 if (symbol_writer != null && Compiler.Report.Errors == 0) {
920 // TODO: it should run in parallel
921 Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
923 var filename = file_name + ".mdb";
925 // We mmap the file, so unlink the previous version since it may be in use
926 File.Delete (filename);
928 // We can safely ignore
931 module.WriteDebugSymbol (symbol_writer);
933 using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
934 symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
937 Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
941 protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
943 Report.RuntimeMissingSupport (Location.Null, "-target:module");
946 void SetCustomAttribute (MethodSpec ctor, byte[] data)
948 if (module_target_attrs != null)
949 module_target_attrs.AddAssemblyAttribute (ctor, data);
951 Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
954 void SetEntryPoint ()
956 if (!Compiler.Settings.NeedsEntryPoint) {
957 if (Compiler.Settings.MainClass != null)
958 Report.Error (2017, "Cannot specify -main if building a module or library");
963 PEFileKinds file_kind;
965 switch (Compiler.Settings.Target) {
968 file_kind = PEFileKinds.Dll;
971 file_kind = PEFileKinds.WindowApplication;
974 file_kind = PEFileKinds.ConsoleApplication;
978 if (entry_point == null) {
979 string main_class = Compiler.Settings.MainClass;
980 if (main_class != null) {
981 // TODO: Handle dotted names
982 var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
984 Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
988 var mtype = texpr.MemberDefinition as ClassOrStruct;
990 Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
994 Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
996 string pname = file_name == null ? name : Path.GetFileName (file_name);
997 Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
1004 Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
1007 void Error_ObsoleteSecurityAttribute (Attribute a, string option)
1009 Report.Warning (1699, 1, a.Location,
1010 "Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
1014 void Error_AssemblySigning (string text)
1016 Report.Error (1548, "Error during assembly signing. " + text);
1019 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1024 static Version IsValidAssemblyVersion (string version, bool allowGenerated)
1026 string[] parts = version.Split ('.');
1027 if (parts.Length < 1 || parts.Length > 4)
1030 var values = new int[4];
1031 for (int i = 0; i < parts.Length; ++i) {
1032 if (!int.TryParse (parts[i], out values[i])) {
1033 if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
1035 // Nothing can follow *
1036 if (parts.Length > 3)
1039 // Generate Build value based on days since 1/1/2000
1040 TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
1041 values[i] = System.Math.Max (days.Days, 0);
1046 // Generate Revision value based on every other second today
1047 var seconds = DateTime.Now - DateTime.Today;
1048 values[i] = (int) seconds.TotalSeconds / 2;
1056 if (values[i] > ushort.MaxValue)
1060 return new Version (values[0], values[1], values[2], values[3]);
1064 public class AssemblyResource : IEquatable<AssemblyResource>
1066 public AssemblyResource (string fileName, string name)
1067 : this (fileName, name, false)
1071 public AssemblyResource (string fileName, string name, bool isPrivate)
1073 FileName = fileName;
1075 Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
1078 public ResourceAttributes Attributes { get; private set; }
1079 public string Name { get; private set; }
1080 public string FileName { get; private set; }
1081 public bool IsEmbeded { get; set; }
1083 #region IEquatable<AssemblyResource> Members
1085 public bool Equals (AssemblyResource other)
1087 return Name == other.Name;
1094 // A placeholder class for assembly attributes when emitting module
1096 class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
1098 static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
1099 public static readonly string AssemblyFieldName = "attributes";
1103 public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
1104 : base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
1106 assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
1107 new MemberName (AssemblyFieldName), null);
1109 AddField (assembly);
1112 public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
1114 assembly.SetCustomAttribute (ctor, data);
1117 public static string GetGeneratedName (string outputName)
1119 return string.Format (TypeNamePrefix, outputName);
1124 // Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
1125 // compiler. This is a default implementation for framework System.Reflection.Emit
1126 // which does not implement any of the methods
1128 public class AssemblyBuilderExtension
1130 protected readonly CompilerContext ctx;
1132 public AssemblyBuilderExtension (CompilerContext ctx)
1137 public virtual System.Reflection.Module AddModule (string module)
1139 ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
1143 public virtual void AddPermissionRequests (PermissionSet[] permissions)
1145 ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
1148 public virtual void AddTypeForwarder (TypeSpec type, Location loc)
1150 ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
1153 public virtual void DefineWin32IconResource (string fileName)
1155 ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
1158 public virtual AssemblyName[] GetReferencedAssemblies ()
1163 public virtual void SetAlgorithmId (uint value, Location loc)
1165 ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
1168 public virtual void SetCulture (string culture, Location loc)
1170 ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
1173 public virtual void SetFlags (uint flags, Location loc)
1175 ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
1178 public virtual void SetVersion (Version version, Location loc)
1180 ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
1184 abstract class AssemblyReferencesLoader<T> where T : class
1186 protected readonly CompilerContext compiler;
1188 protected readonly List<string> paths;
1190 protected AssemblyReferencesLoader (CompilerContext compiler)
1192 this.compiler = compiler;
1194 paths = new List<string> ();
1195 paths.Add (Directory.GetCurrentDirectory ());
1196 paths.AddRange (compiler.Settings.ReferencesLookupPaths);
1199 public abstract bool HasObjectType (T assembly);
1200 protected abstract string[] GetDefaultReferences ();
1201 public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
1202 public abstract void LoadReferences (ModuleContainer module);
1204 protected void Error_FileNotFound (string fileName)
1206 compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
1209 protected void Error_FileCorrupted (string fileName)
1211 compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
1214 protected void Error_AssemblyIsModule (string fileName)
1216 compiler.Report.Error (1509,
1217 "Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
1221 protected void Error_ModuleIsAssembly (string fileName)
1223 compiler.Report.Error (1542,
1224 "Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
1228 protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
1230 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
1232 loaded = new List<Tuple<RootNamespace, T>> ();
1235 // Load mscorlib.dll as the first
1237 if (module.Compiler.Settings.StdLib) {
1238 corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
1240 corlib_assembly = default (T);
1244 foreach (string r in module.Compiler.Settings.AssemblyReferences) {
1245 a = LoadAssemblyFile (r, false);
1246 if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
1249 var key = Tuple.Create (module.GlobalRootNamespace, a);
1250 if (loaded.Contains (key))
1256 if (corlib_assembly == null) {
1258 // Requires second pass because HasObjectType can trigger assembly load event
1260 for (int i = 0; i < loaded.Count; ++i) {
1261 var assembly = loaded [i];
1264 // corlib assembly is the first referenced assembly which contains System.Object
1266 if (HasObjectType (assembly.Item2)) {
1267 corlib_assembly = assembly.Item2;
1268 loaded.RemoveAt (i);
1274 foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
1275 a = LoadAssemblyFile (entry.Item2, false);
1279 var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
1280 if (loaded.Contains (key))
1286 if (compiler.Settings.LoadDefaultReferences) {
1287 foreach (string r in GetDefaultReferences ()) {
1288 a = LoadAssemblyFile (r, true);
1292 var key = Tuple.Create (module.GlobalRootNamespace, a);
1293 if (loaded.Contains (key))
1300 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);