2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.
16 // Only remove it if you need to debug locally on your tree.
22 using System.Collections;
23 using System.Collections.Specialized;
24 using System.Globalization;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Runtime.InteropServices;
28 using System.Security;
29 using System.Security.Cryptography;
30 using System.Security.Permissions;
32 using Mono.Security.Cryptography;
34 namespace Mono.CSharp {
37 /// Code generator class.
39 public class CodeGen {
40 static AppDomain current_domain;
42 public static AssemblyClass Assembly;
49 public static void Reset ()
51 Assembly = new AssemblyClass ();
54 public static string Basename (string name)
56 int pos = name.LastIndexOf ('/');
59 return name.Substring (pos + 1);
61 pos = name.LastIndexOf ('\\');
63 return name.Substring (pos + 1);
68 public static string Dirname (string name)
70 int pos = name.LastIndexOf ('/');
73 return name.Substring (0, pos);
75 pos = name.LastIndexOf ('\\');
77 return name.Substring (0, pos);
82 static public string FileName;
85 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
87 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
92 // Initializes the code generator variables for interactive use (repl)
94 static public void InitDynamic (string name)
96 current_domain = AppDomain.CurrentDomain;
97 AssemblyName an = Assembly.GetAssemblyName (name, name);
99 Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
100 RootContext.ToplevelTypes = new ModuleContainer (true);
101 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
102 Assembly.Name = Assembly.Builder.GetName ();
106 // Initializes the code generator variables
108 static public bool Init (string name, string output, bool want_debugging_support)
111 AssemblyName an = Assembly.GetAssemblyName (name, output);
115 if (an.KeyPair != null) {
116 // If we are going to strong name our assembly make
117 // sure all its refs are strong named
118 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
119 AssemblyName ref_name = a.GetName ();
120 byte [] b = ref_name.GetPublicKeyToken ();
121 if (b == null || b.Length == 0) {
122 Report.Error (1577, "Assembly generation failed " +
123 "-- Referenced assembly '" +
125 "' does not have a strong name.");
126 //Environment.Exit (1);
131 current_domain = AppDomain.CurrentDomain;
134 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135 AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
137 catch (ArgumentException) {
138 // specified key may not be exportable outside it's container
139 if (RootContext.StrongNameKeyContainer != null) {
140 Report.Error (1548, "Could not access the key inside the container `" +
141 RootContext.StrongNameKeyContainer + "'.");
142 Environment.Exit (1);
146 catch (CryptographicException) {
147 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149 Environment.Exit (1);
154 // Get the complete AssemblyName from the builder
155 // (We need to get the public key and token)
156 Assembly.Name = Assembly.Builder.GetName ();
159 // Pass a path-less name to DefineDynamicModule. Wonder how
160 // this copes with output in different directories then.
161 // FIXME: figure out how this copes with --output /tmp/blah
163 // If the third argument is true, the ModuleBuilder will dynamically
164 // load the default symbol writer.
167 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
168 Basename (name), Basename (output), want_debugging_support);
171 // TODO: We should use SymbolWriter from DefineDynamicModule
172 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
173 Report.Error (40, "Unexpected debug information initialization error `{0}'",
174 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
178 } catch (ExecutionEngineException e) {
179 Report.Error (40, "Unexpected debug information initialization error `{0}'",
187 static public void Save (string name, bool saveDebugInfo)
190 PortableExecutableKinds pekind;
191 ImageFileMachine machine;
193 switch (RootContext.Platform) {
195 pekind = PortableExecutableKinds.Required32Bit;
196 machine = ImageFileMachine.I386;
199 pekind = PortableExecutableKinds.PE32Plus;
200 machine = ImageFileMachine.AMD64;
203 pekind = PortableExecutableKinds.PE32Plus;
204 machine = ImageFileMachine.IA64;
206 case Platform.AnyCPU:
208 pekind = PortableExecutableKinds.ILOnly;
209 machine = ImageFileMachine.I386;
215 Assembly.Builder.Save (Basename (name), pekind, machine);
217 Assembly.Builder.Save (Basename (name));
220 catch (COMException) {
221 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
224 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
225 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
226 RootContext.StrongNameKeyFile +
227 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
229 catch (System.IO.IOException io) {
230 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
233 catch (System.UnauthorizedAccessException ua) {
234 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
237 catch (System.NotImplementedException nie) {
238 Report.RuntimeMissingSupport (Location.Null, nie.Message);
243 // Write debuger symbol file
246 SymbolWriter.WriteSymbolFile ();
252 /// An interface to hold all the information needed in the resolving phase.
254 public interface IResolveContext
257 // A scope type context, it can be inflated for generic types
259 Type CurrentType { get; }
262 // A scope type parameters either VAR or MVAR
264 TypeParameter[] CurrentTypeParameters { get; }
267 // A type definition of the type context. For partial types definition use
268 // CurrentTypeDefinition.PartialContainer otherwise the context is local
270 // TODO: CurrentType.Definition
272 TypeContainer CurrentTypeDefinition { get; }
274 bool IsInObsoleteScope { get; }
275 bool IsInUnsafeScope { get; }
276 bool IsStatic { get; }
278 ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
279 FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
280 FullNamedExpression LookupNamespaceAlias (string name);
284 // Block or statement resolving context
286 public class BlockContext : ResolveContext
288 FlowBranching current_flow_branching;
290 public BlockContext (IResolveContext mc, ExplicitBlock block, Type returnType)
293 if (returnType == null)
294 throw new ArgumentNullException ("returnType");
296 this.return_type = returnType;
298 // TODO: check for null value
299 CurrentBlock = block;
302 public override FlowBranching CurrentBranching {
303 get { return current_flow_branching; }
307 // Starts a new code branching. This inherits the state of all local
308 // variables and parameters from the current branching.
310 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
312 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
313 return current_flow_branching;
317 // Starts a new code branching for block `block'.
319 public FlowBranching StartFlowBranching (Block block)
321 Set (Options.DoFlowAnalysis);
323 current_flow_branching = FlowBranching.CreateBranching (
324 CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
325 return current_flow_branching;
328 public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
330 FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
331 current_flow_branching = branching;
335 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
337 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
338 current_flow_branching = branching;
342 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
344 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
345 current_flow_branching = branching;
349 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
351 FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
352 current_flow_branching = branching;
356 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt, FlowBranching parent)
358 FlowBranchingToplevel branching = new FlowBranchingToplevel (parent, stmt);
359 current_flow_branching = branching;
364 // Ends a code branching. Merges the state of locals and parameters
365 // from all the children of the ending branching.
367 public bool EndFlowBranching ()
369 FlowBranching old = current_flow_branching;
370 current_flow_branching = current_flow_branching.Parent;
372 FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
373 return vector.IsUnreachable;
377 // Kills the current code branching. This throws away any changed state
378 // information and should only be used in case of an error.
380 // FIXME: this is evil
381 public void KillFlowBranching ()
383 current_flow_branching = current_flow_branching.Parent;
387 // This method is used during the Resolution phase to flag the
388 // need to define the ReturnLabel
390 public void NeedReturnLabel ()
393 HasReturnLabel = true;
398 /// An Emit Context is created for each body of code (from methods,
399 /// properties bodies, indexer bodies or constructor bodies)
401 public class EmitContext : IResolveContext {
407 /// This flag tracks the `checked' state of the compilation,
408 /// it controls whether we should generate code that does overflow
409 /// checking, or if we generate code that ignores overflows.
411 /// The default setting comes from the command line option to generate
412 /// checked or unchecked code plus any source code changes using the
413 /// checked/unchecked statements or expressions. Contrast this with
414 /// the ConstantCheckState flag.
416 CheckedScope = 1 << 0,
419 /// The constant check state is always set to `true' and cant be changed
420 /// from the command line. The source code can change this setting with
421 /// the `checked' and `unchecked' statements and expressions.
423 ConstantCheckState = 1 << 1,
425 AllCheckStateFlags = CheckedScope | ConstantCheckState,
428 // unsafe { ... } scope
430 UnsafeScope = 1 << 2,
432 FinallyScope = 1 << 4,
433 FieldInitializerScope = 1 << 5,
434 CompoundAssignmentScope = 1 << 6,
435 FixedInitializerScope = 1 << 7,
436 BaseInitializer = 1 << 8,
439 // Inside an enum definition, we do not resolve enumeration values
440 // to their enumerations, but rather to the underlying type/value
441 // This is so EnumVal + EnumValB can be evaluated.
443 // There is no "E operator + (E x, E y)", so during an enum evaluation
444 // we relax the rules
448 ConstantScope = 1 << 10,
450 ConstructorScope = 1 << 11,
453 /// Whether control flow analysis is enabled
455 DoFlowAnalysis = 1 << 20,
458 /// Whether control flow analysis is disabled on structs
459 /// (only meaningful when DoFlowAnalysis is set)
461 OmitStructFlowAnalysis = 1 << 21,
464 /// Indicates the current context is in probing mode, no errors are reported.
466 ProbingMode = 1 << 22,
469 // Return and ContextualReturn statements will set the ReturnType
470 // value based on the expression types of each return statement
471 // instead of the method return type which is initially null.
473 InferReturnType = 1 << 23,
475 OmitDebuggingInfo = 1 << 24
478 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
479 // it's public so that we can use a struct at the callsite
480 public struct FlagsHandle : IDisposable
483 readonly Options invmask, oldval;
485 public FlagsHandle (EmitContext ec, Options flagsToSet)
486 : this (ec, flagsToSet, flagsToSet)
490 internal FlagsHandle (EmitContext ec, Options mask, Options val)
494 oldval = ec.flags & mask;
495 ec.flags = (ec.flags & invmask) | (val & mask);
497 if ((mask & Options.ProbingMode) != 0)
498 Report.DisableReporting ();
501 public void Dispose ()
503 if ((invmask & Options.ProbingMode) == 0)
504 Report.EnableReporting ();
506 ec.flags = (ec.flags & invmask) | oldval;
513 // Holds a varible used during collection or object initialization.
515 public Expression CurrentInitializerVariable;
517 public ILGenerator ig;
520 /// The value that is allowed to be returned or NULL if there is no
523 protected Type return_type;
526 /// Keeps track of the Type to LocalBuilder temporary storage created
527 /// to store structures (used to compute the address of the structure
528 /// value on structure method invocations)
530 public Hashtable temporary_storage;
532 public Block CurrentBlock;
535 /// The location where we store the return value.
537 public LocalBuilder return_value;
540 /// The location where return has to jump to return the
543 public Label ReturnLabel;
546 /// If we already defined the ReturnLabel
548 public bool HasReturnLabel;
551 /// Whether we are inside an anonymous method.
553 public AnonymousExpression CurrentAnonymousMethod;
555 public IResolveContext ResolveContext;
558 /// The current iterator
560 public Iterator CurrentIterator {
561 get { return CurrentAnonymousMethod as Iterator; }
564 public TypeInferenceContext ReturnTypeInference;
566 public EmitContext (IResolveContext rc, ILGenerator ig, Type return_type)
568 this.ResolveContext = rc;
572 // The default setting comes from the command line option
574 if (RootContext.Checked)
575 flags |= Options.CheckedScope;
578 // The constant check state is always set to true
580 flags |= Options.ConstantCheckState;
582 this.return_type = return_type;
585 public virtual FlowBranching CurrentBranching {
589 public Type CurrentType {
590 get { return ResolveContext.CurrentType; }
593 public TypeParameter[] CurrentTypeParameters {
594 get { return ResolveContext.CurrentTypeParameters; }
597 public TypeContainer CurrentTypeDefinition {
598 get { return ResolveContext.CurrentTypeDefinition; }
601 public bool ConstantCheckState {
602 get { return (flags & Options.ConstantCheckState) != 0; }
605 public bool InUnsafe {
606 get { return HasSet (Options.UnsafeScope) || ResolveContext.IsInUnsafeScope; }
609 public bool DoFlowAnalysis {
610 get { return (flags & Options.DoFlowAnalysis) != 0; }
613 public bool OmitStructFlowAnalysis {
614 get { return (flags & Options.OmitStructFlowAnalysis) != 0; }
617 public bool HasSet (Options options)
619 return (this.flags & options) == options;
622 public bool HasAny (Options options)
624 return (this.flags & options) != 0;
627 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
628 public FlagsHandle Set (Options options)
630 return new FlagsHandle (this, options);
633 public FlagsHandle With (Options options, bool enable)
635 return new FlagsHandle (this, options, enable ? options : 0);
638 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
641 (do_flow_analysis ? Options.DoFlowAnalysis : 0) |
642 (omit_struct_analysis ? Options.OmitStructFlowAnalysis : 0);
643 return new FlagsHandle (this, Options.DoFlowAnalysis | Options.OmitStructFlowAnalysis, newflags);
646 // IResolveContext.IsInObsoleteScope
647 public bool IsInObsoleteScope {
649 // Disables obsolete checks when probing is on
650 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
654 public bool IsInProbingMode {
655 get { return (flags & Options.ProbingMode) != 0; }
658 bool IResolveContext.IsInUnsafeScope {
659 get { return InUnsafe; }
662 public bool IsStatic {
663 get { return ResolveContext.IsStatic; }
666 public bool IsVariableCapturingRequired {
668 return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
672 public bool OmitDebuggingInfo {
673 get { return (flags & Options.OmitDebuggingInfo) != 0; }
676 flags |= Options.OmitDebuggingInfo;
678 flags &= ~Options.OmitDebuggingInfo;
682 public bool MustCaptureVariable (LocalInfo local)
684 if (CurrentAnonymousMethod == null)
687 // FIXME: IsIterator is too aggressive, we should capture only if child
688 // block contains yield
689 if (CurrentAnonymousMethod.IsIterator)
692 return local.Block.Toplevel != CurrentBlock.Toplevel;
695 public Type ReturnType {
702 /// This is called immediately before emitting an IL opcode to tell the symbol
703 /// writer to which source line this opcode belongs.
705 public void Mark (Location loc)
707 if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
710 SymbolWriter.MarkSequencePoint (ig, loc);
713 public void DefineLocalVariable (string name, LocalBuilder builder)
715 SymbolWriter.DefineLocalVariable (name, builder);
718 public void BeginScope ()
721 SymbolWriter.OpenScope(ig);
724 public void EndScope ()
727 SymbolWriter.CloseScope(ig);
731 /// Returns a temporary storage for a variable of type t as
732 /// a local variable in the current body.
734 public LocalBuilder GetTemporaryLocal (Type t)
736 if (temporary_storage != null) {
737 object o = temporary_storage [t];
741 o = s.Count == 0 ? null : s.Pop ();
743 temporary_storage.Remove (t);
747 return (LocalBuilder) o;
749 return ig.DeclareLocal (t);
752 public void FreeTemporaryLocal (LocalBuilder b, Type t)
754 if (temporary_storage == null) {
755 temporary_storage = new Hashtable ();
756 temporary_storage [t] = b;
759 object o = temporary_storage [t];
761 temporary_storage [t] = b;
764 Stack s = o as Stack;
768 temporary_storage [t] = s;
774 /// Current loop begin and end labels.
776 public Label LoopBegin, LoopEnd;
779 /// Default target in a switch statement. Only valid if
782 public Label DefaultTarget;
785 /// If this is non-null, points to the current switch statement
787 public Switch Switch;
790 /// ReturnValue creates on demand the LocalBuilder for the
791 /// return value from the function. By default this is not
792 /// used. This is only required when returns are found inside
793 /// Try or Catch statements.
795 /// This method is typically invoked from the Emit phase, so
796 /// we allow the creation of a return label if it was not
797 /// requested during the resolution phase. Could be cleaned
798 /// up, but it would replicate a lot of logic in the Emit phase
799 /// of the code that uses it.
801 public LocalBuilder TemporaryReturn ()
803 if (return_value == null){
804 return_value = ig.DeclareLocal (return_type);
805 if (!HasReturnLabel){
806 ReturnLabel = ig.DefineLabel ();
807 HasReturnLabel = true;
814 public Expression GetThis (Location loc)
817 if (CurrentBlock != null)
818 my_this = new This (CurrentBlock, loc);
820 my_this = new This (loc);
822 if (!my_this.ResolveBase (this))
828 #region IResolveContext Members
830 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
832 return ResolveContext.LookupExtensionMethod (extensionType, name, loc);
835 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
837 return ResolveContext.LookupNamespaceOrType (name, loc, ignore_cs0104);
840 public FullNamedExpression LookupNamespaceAlias (string name)
842 return ResolveContext.LookupNamespaceAlias (name);
848 public class ResolveContext : EmitContext
850 public ResolveContext (IResolveContext mc)
851 : base (mc, null, null)
855 public ResolveContext (IResolveContext mc, Options options)
863 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext
865 public void AddAttributes (ArrayList attrs, IResolveContext context)
867 foreach (Attribute a in attrs)
868 a.AttachTo (this, context);
870 if (attributes == null) {
871 attributes = new Attributes (attrs);
874 attributes.AddAttributes (attrs);
877 public virtual void Emit (TypeContainer tc)
879 if (OptAttributes == null)
882 OptAttributes.Emit ();
885 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
887 Attribute a = OptAttributes.Search (a_type);
894 #region IResolveContext Members
896 public Type CurrentType {
900 public TypeParameter[] CurrentTypeParameters {
904 public TypeContainer CurrentTypeDefinition {
905 get { return RootContext.ToplevelTypes; }
908 public DeclSpace DeclContainer {
909 get { return RootContext.ToplevelTypes; }
912 public bool IsInObsoleteScope {
913 get { return false; }
916 public bool IsInUnsafeScope {
917 get { return false; }
920 public bool IsStatic {
921 get { return false; }
924 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
926 throw new NotImplementedException ();
929 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
931 return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
934 public FullNamedExpression LookupNamespaceAlias (string name)
942 public class AssemblyClass : CommonAssemblyModulClass {
943 // TODO: make it private and move all builder based methods here
944 public AssemblyBuilder Builder;
945 bool is_cls_compliant;
946 bool wrap_non_exception_throws;
948 public Attribute ClsCompliantAttribute;
950 ListDictionary declarative_security;
951 bool has_extension_method;
952 public AssemblyName Name;
953 MethodInfo add_type_forwarder;
954 ListDictionary emitted_forwarders;
956 // Module is here just because of error messages
957 static string[] attribute_targets = new string [] { "assembly", "module" };
959 public AssemblyClass (): base ()
961 wrap_non_exception_throws = true;
964 public bool HasExtensionMethods {
966 has_extension_method = value;
970 public bool IsClsCompliant {
972 return is_cls_compliant;
976 public bool WrapNonExceptionThrows {
978 return wrap_non_exception_throws;
982 public override AttributeTargets AttributeTargets {
984 return AttributeTargets.Assembly;
988 public override bool IsClsComplianceRequired ()
990 return is_cls_compliant;
993 public void Resolve ()
995 if (RootContext.Unsafe) {
997 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
998 // when -unsafe option was specified
1001 Location loc = Location.Null;
1003 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
1004 new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
1006 Arguments pos = new Arguments (1);
1007 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
1009 Arguments named = new Arguments (1);
1010 named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
1012 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
1013 new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
1014 new Arguments[] { pos, named }, loc, false);
1015 g.AttachTo (this, this);
1017 if (g.Resolve () != null) {
1018 declarative_security = new ListDictionary ();
1019 g.ExtractSecurityPermissionSet (declarative_security);
1023 if (OptAttributes == null)
1026 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1027 if (!OptAttributes.CheckTargets())
1030 ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
1032 if (ClsCompliantAttribute != null) {
1033 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1036 Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
1038 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1040 wrap_non_exception_throws = (bool) val;
1045 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1048 // check for possible ECMA key
1049 if (strongNameBlob.Length == 16) {
1050 // will be rejected if not "the" ECMA key
1051 an.SetPublicKey (strongNameBlob);
1054 // take it, with or without, a private key
1055 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1056 // and make sure we only feed the public part to Sys.Ref
1057 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1059 // AssemblyName.SetPublicKey requires an additional header
1060 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1062 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1063 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1064 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1065 an.SetPublicKey (encodedPublicKey);
1069 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1070 Environment.Exit (1);
1074 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1075 public AssemblyName GetAssemblyName (string name, string output)
1077 if (OptAttributes != null) {
1078 foreach (Attribute a in OptAttributes.Attrs) {
1079 // cannot rely on any resolve-based members before you call Resolve
1080 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1083 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1084 // However, this is invoked by CodeGen.Init, when none of the namespaces
1086 // TODO: Does not handle quoted attributes properly
1088 case "AssemblyKeyFile":
1089 case "AssemblyKeyFileAttribute":
1090 case "System.Reflection.AssemblyKeyFileAttribute":
1091 if (RootContext.StrongNameKeyFile != null) {
1092 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1093 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1094 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1096 string value = a.GetString ();
1097 if (value != null && value.Length != 0)
1098 RootContext.StrongNameKeyFile = value;
1101 case "AssemblyKeyName":
1102 case "AssemblyKeyNameAttribute":
1103 case "System.Reflection.AssemblyKeyNameAttribute":
1104 if (RootContext.StrongNameKeyContainer != null) {
1105 Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1106 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1107 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1109 string value = a.GetString ();
1110 if (value != null && value.Length != 0)
1111 RootContext.StrongNameKeyContainer = value;
1114 case "AssemblyDelaySign":
1115 case "AssemblyDelaySignAttribute":
1116 case "System.Reflection.AssemblyDelaySignAttribute":
1117 RootContext.StrongNameDelaySign = a.GetBoolean ();
1123 AssemblyName an = new AssemblyName ();
1124 an.Name = Path.GetFileNameWithoutExtension (name);
1126 // note: delay doesn't apply when using a key container
1127 if (RootContext.StrongNameKeyContainer != null) {
1128 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1132 // strongname is optional
1133 if (RootContext.StrongNameKeyFile == null)
1136 string AssemblyDir = Path.GetDirectoryName (output);
1138 // the StrongName key file may be relative to (a) the compiled
1139 // file or (b) to the output assembly. See bugzilla #55320
1140 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1142 // (a) relative to the compiled file
1143 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1144 bool exist = File.Exists (filename);
1145 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1146 // (b) relative to the outputed assembly
1147 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1148 exist = File.Exists (filename);
1152 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1153 byte[] snkeypair = new byte [fs.Length];
1154 fs.Read (snkeypair, 0, snkeypair.Length);
1156 if (RootContext.StrongNameDelaySign) {
1157 // delayed signing - DO NOT include private key
1158 SetPublicKey (an, snkeypair);
1161 // no delay so we make sure we have the private key
1163 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1164 an.KeyPair = new StrongNameKeyPair (snkeypair);
1166 catch (CryptographicException) {
1167 if (snkeypair.Length == 16) {
1168 // error # is different for ECMA key
1169 Report.Error (1606, "Could not sign the assembly. " +
1170 "ECMA key can only be used to delay-sign assemblies");
1173 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1181 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1187 void Error_AssemblySigning (string text)
1189 Report.Error (1548, "Error during assembly signing. " + text);
1192 bool CheckInternalsVisibleAttribute (Attribute a)
1194 string assembly_name = a.GetString ();
1195 if (assembly_name.Length == 0)
1198 AssemblyName aname = null;
1201 aname = new AssemblyName (assembly_name);
1203 throw new NotSupportedException ();
1205 } catch (FileLoadException) {
1206 } catch (ArgumentException) {
1209 // Bad assembly name format
1211 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1212 // Report error if we have defined Version or Culture
1213 else if (aname.Version != null || aname.CultureInfo != null)
1214 throw new Exception ("Friend assembly `" + a.GetString () +
1215 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1216 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1217 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1218 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1225 static bool IsValidAssemblyVersion (string version)
1229 v = new Version (version);
1232 int major = int.Parse (version, CultureInfo.InvariantCulture);
1233 v = new Version (major, 0);
1239 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1240 if (candidate > ushort.MaxValue)
1247 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
1249 if (a.IsValidSecurityAttribute ()) {
1250 if (declarative_security == null)
1251 declarative_security = new ListDictionary ();
1253 a.ExtractSecurityPermissionSet (declarative_security);
1257 if (a.Type == pa.AssemblyCulture) {
1258 string value = a.GetString ();
1259 if (value == null || value.Length == 0)
1262 if (RootContext.Target == Target.Exe) {
1263 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1268 if (a.Type == pa.AssemblyVersion) {
1269 string value = a.GetString ();
1270 if (value == null || value.Length == 0)
1273 value = value.Replace ('*', '0');
1275 if (!IsValidAssemblyVersion (value)) {
1276 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1281 if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
1284 if (a.Type == pa.TypeForwarder) {
1285 Type t = a.GetArgumentType ();
1286 if (t == null || TypeManager.HasElementType (t)) {
1287 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1291 t = TypeManager.DropGenericTypeArguments (t);
1292 if (emitted_forwarders == null) {
1293 emitted_forwarders = new ListDictionary();
1294 } else if (emitted_forwarders.Contains(t)) {
1295 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1296 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1297 TypeManager.CSharpName(t));
1301 emitted_forwarders.Add(t, a);
1303 if (TypeManager.LookupDeclSpace (t) != null) {
1304 Report.SymbolRelatedToPreviousError (t);
1305 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1306 TypeManager.CSharpName (t));
1310 if (t.DeclaringType != null) {
1311 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1312 TypeManager.CSharpName (t));
1316 if (add_type_forwarder == null) {
1317 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1318 BindingFlags.NonPublic | BindingFlags.Instance);
1320 if (add_type_forwarder == null) {
1321 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1326 add_type_forwarder.Invoke (Builder, new object[] { t });
1330 if (a.Type == pa.Extension) {
1331 a.Error_MisusedExtensionAttribute ();
1335 Builder.SetCustomAttribute (cb);
1338 public override void Emit (TypeContainer tc)
1342 if (has_extension_method)
1343 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
1345 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1346 PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
1347 if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
1348 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
1349 pa.Type, Location.Null, Type.EmptyTypes);
1350 PropertyInfo [] pis = new PropertyInfo [1];
1351 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
1352 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
1353 object [] pargs = new object [1];
1355 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1358 if (declarative_security != null) {
1360 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1361 object builder_instance = Builder;
1364 // Microsoft runtime hacking
1365 if (add_permission == null) {
1366 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1367 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1369 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1370 builder_instance = fi.GetValue (Builder);
1373 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1374 declarative_security [SecurityAction.RequestOptional],
1375 declarative_security [SecurityAction.RequestRefuse] };
1376 add_permission.Invoke (builder_instance, args);
1379 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1384 public override string[] ValidAttributeTargets {
1386 return attribute_targets;
1390 // Wrapper for AssemblyBuilder.AddModule
1391 static MethodInfo adder_method;
1392 static public MethodInfo AddModule_Method {
1394 if (adder_method == null)
1395 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1396 return adder_method;
1399 public Module AddModule (string module)
1401 MethodInfo m = AddModule_Method;
1403 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1404 Environment.Exit (1);
1408 return (Module) m.Invoke (Builder, new object [] { module });
1409 } catch (TargetInvocationException ex) {
1410 throw ex.InnerException;