2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 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.Reflection;
25 using System.Reflection.Emit;
26 using System.Runtime.InteropServices;
27 using System.Security;
28 using System.Security.Cryptography;
29 using System.Security.Permissions;
31 using Mono.Security.Cryptography;
33 namespace Mono.CSharp {
36 /// Code generator class.
38 public class CodeGen {
39 static AppDomain current_domain;
40 static public SymbolWriter SymbolWriter;
42 public static AssemblyClass Assembly;
43 public static ModuleClass Module;
50 public static void Reset ()
52 Assembly = new AssemblyClass ();
53 Module = new ModuleClass (RootContext.Unsafe);
56 public static string Basename (string name)
58 int pos = name.LastIndexOf ('/');
61 return name.Substring (pos + 1);
63 pos = name.LastIndexOf ('\\');
65 return name.Substring (pos + 1);
70 public static string Dirname (string name)
72 int pos = name.LastIndexOf ('/');
75 return name.Substring (0, pos);
77 pos = name.LastIndexOf ('\\');
79 return name.Substring (0, pos);
84 static public string FileName;
87 // Initializes the symbol writer
89 static void InitializeSymbolWriter (string filename)
91 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
94 // If we got an ISymbolWriter instance, initialize it.
96 if (SymbolWriter == null) {
98 -18, 1, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
104 // Initializes the code generator variables
106 static public bool Init (string name, string output, bool want_debugging_support)
109 AssemblyName an = Assembly.GetAssemblyName (name, output);
113 if (an.KeyPair != null) {
114 // If we are going to strong name our assembly make
115 // sure all its refs are strong named
116 foreach (Assembly a in RootNamespace.Global.Assemblies) {
117 AssemblyName ref_name = a.GetName ();
118 byte [] b = ref_name.GetPublicKeyToken ();
119 if (b == null || b.Length == 0) {
120 Report.Error (1577, "Assembly generation failed " +
121 "-- Referenced assembly '" +
123 "' does not have a strong name.");
124 //Environment.Exit (1);
129 current_domain = AppDomain.CurrentDomain;
132 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
133 AssemblyBuilderAccess.Save, Dirname (name));
135 catch (ArgumentException) {
136 // specified key may not be exportable outside it's container
137 if (RootContext.StrongNameKeyContainer != null) {
138 Report.Error (1548, "Could not access the key inside the container `" +
139 RootContext.StrongNameKeyContainer + "'.");
140 Environment.Exit (1);
144 catch (CryptographicException) {
145 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
146 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
147 Environment.Exit (1);
153 // Get the complete AssemblyName from the builder
154 // (We need to get the public key and token)
155 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.
166 Module.Builder = Assembly.Builder.DefineDynamicModule (
167 Basename (name), Basename (output), false);
169 if (want_debugging_support)
170 InitializeSymbolWriter (output);
175 static public void Save (string name)
178 Assembly.Builder.Save (Basename (name));
180 if (SymbolWriter != null)
181 SymbolWriter.WriteSymbolFile ();
183 catch (COMException) {
184 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
187 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
188 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
189 RootContext.StrongNameKeyFile +
190 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
192 catch (System.IO.IOException io) {
193 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
195 catch (System.UnauthorizedAccessException ua) {
196 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
202 public interface IResolveContext
204 DeclSpace DeclContainer { get; }
205 bool IsInObsoleteScope { get; }
206 bool IsInUnsafeScope { get; }
208 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
210 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
211 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
212 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
213 // handle generic method overrides differently
214 DeclSpace GenericDeclContainer { get; }
218 /// An Emit Context is created for each body of code (from methods,
219 /// properties bodies, indexer bodies or constructor bodies)
221 public class EmitContext : IResolveContext {
224 // Holds a varible used during collection or object initialization.
226 public Expression CurrentInitializerVariable;
228 DeclSpace decl_space;
230 public DeclSpace TypeContainer;
231 public ILGenerator ig;
234 public enum Flags : byte {
236 /// This flag tracks the `checked' state of the compilation,
237 /// it controls whether we should generate code that does overflow
238 /// checking, or if we generate code that ignores overflows.
240 /// The default setting comes from the command line option to generate
241 /// checked or unchecked code plus any source code changes using the
242 /// checked/unchecked statements or expressions. Contrast this with
243 /// the ConstantCheckState flag.
248 /// The constant check state is always set to `true' and cant be changed
249 /// from the command line. The source code can change this setting with
250 /// the `checked' and `unchecked' statements and expressions.
252 ConstantCheckState = 1 << 1,
254 AllCheckStateFlags = CheckState | ConstantCheckState,
257 /// Whether we are inside an unsafe block
265 /// Whether control flow analysis is enabled
267 DoFlowAnalysis = 1 << 5,
270 /// Whether control flow analysis is disabled on structs
271 /// (only meaningful when DoFlowAnalysis is set)
273 OmitStructFlowAnalysis = 1 << 6,
276 /// Indicates the current context is in probing mode, no errors are reported.
284 /// Whether we are emitting code inside a static or instance method
286 public bool IsStatic;
289 /// Whether the actual created method is static or instance method.
290 /// Althoug the method might be declared as `static', if an anonymous
291 /// method is involved, we might turn this into an instance method.
293 /// So this reflects the low-level staticness of the method, while
294 /// IsStatic represents the semantic, high-level staticness.
296 public bool MethodIsStatic;
299 /// Whether we are emitting a field initializer
301 public bool IsFieldInitializer;
304 /// If this is true, then Return and ContextualReturn statements
305 /// will set the ReturnType value based on the expression types
306 /// of each return statement instead of the method return type
307 /// (which is initially null).
309 public bool InferReturnType;
312 /// The value that is allowed to be returned or NULL if there is no
318 /// Points to the Type (extracted from the TypeContainer) that
319 /// declares this body of code
321 public Type ContainerType;
324 /// Whether this is generating code for a constructor
326 public bool IsConstructor;
329 /// Keeps track of the Type to LocalBuilder temporary storage created
330 /// to store structures (used to compute the address of the structure
331 /// value on structure method invocations)
333 public Hashtable temporary_storage;
335 public Block CurrentBlock;
337 public int CurrentFile;
340 /// The location where we store the return value.
342 LocalBuilder return_value;
345 /// The location where return has to jump to return the
348 public Label ReturnLabel;
351 /// If we already defined the ReturnLabel
353 public bool HasReturnLabel;
356 /// Whether we are inside an iterator block.
358 public bool InIterator;
361 /// Whether we are in a `fixed' initialization
363 public bool InFixedInitializer;
366 /// Whether we are inside an anonymous method.
368 public AnonymousContainer CurrentAnonymousMethod;
371 /// Location for this EmitContext
376 /// Inside an enum definition, we do not resolve enumeration values
377 /// to their enumerations, but rather to the underlying type/value
378 /// This is so EnumVal + EnumValB can be evaluated.
380 /// There is no "E operator + (E x, E y)", so during an enum evaluation
381 /// we relax the rules
383 public bool InEnumContext;
385 public readonly IResolveContext ResolveContext;
388 /// The current iterator
390 public Iterator CurrentIterator {
391 get { return CurrentAnonymousMethod as Iterator; }
395 /// Whether we are in the resolving stage or not
403 public static EmitContext TempEc;
405 bool isAnonymousMethodAllowed = true;
408 FlowBranching current_flow_branching;
410 static int next_id = 0;
413 public override string ToString ()
415 return String.Format ("EmitContext ({0}:{1})", id,
416 CurrentAnonymousMethod, loc);
419 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
420 Type return_type, int code_flags, bool is_constructor)
422 this.ResolveContext = rc;
425 TypeContainer = parent;
426 this.decl_space = ds;
427 if (RootContext.Checked)
428 flags |= Flags.CheckState;
429 flags |= Flags.ConstantCheckState;
431 if (return_type == null)
432 throw new ArgumentNullException ("return_type");
434 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
435 throw new InternalErrorException ();
438 IsStatic = (code_flags & Modifiers.STATIC) != 0;
439 MethodIsStatic = IsStatic;
440 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
441 ReturnType = return_type;
442 IsConstructor = is_constructor;
445 current_phase = Phase.Created;
448 // Can only be null for the ResolveType contexts.
449 ContainerType = parent.TypeBuilder;
450 if (rc.IsInUnsafeScope)
451 flags |= Flags.InUnsafe;
456 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
457 Type return_type, int code_flags, bool is_constructor)
458 : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
462 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
463 Type return_type, int code_flags)
464 : this (rc, ds, ds, l, ig, return_type, code_flags, false)
468 public DeclSpace DeclContainer {
469 get { return decl_space; }
470 set { decl_space = value; }
473 public DeclSpace GenericDeclContainer {
474 get { return DeclContainer; }
477 public bool CheckState {
478 get { return (flags & Flags.CheckState) != 0; }
481 public bool ConstantCheckState {
482 get { return (flags & Flags.ConstantCheckState) != 0; }
485 public bool InUnsafe {
486 get { return (flags & Flags.InUnsafe) != 0; }
489 public bool InCatch {
490 get { return (flags & Flags.InCatch) != 0; }
493 public bool InFinally {
494 get { return (flags & Flags.InFinally) != 0; }
497 public bool DoFlowAnalysis {
498 get { return (flags & Flags.DoFlowAnalysis) != 0; }
501 public bool OmitStructFlowAnalysis {
502 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
505 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
506 // it's public so that we can use a struct at the callsite
507 public struct FlagsHandle : IDisposable
510 readonly Flags invmask, oldval;
512 public FlagsHandle (EmitContext ec, Flags flagsToSet)
513 : this (ec, flagsToSet, flagsToSet)
517 internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
521 oldval = ec.flags & mask;
522 ec.flags = (ec.flags & invmask) | (val & mask);
524 if ((mask & Flags.ProbingMode) != 0)
525 Report.DisableReporting ();
528 public void Dispose ()
530 if ((invmask & Flags.ProbingMode) == 0)
531 Report.EnableReporting ();
533 ec.flags = (ec.flags & invmask) | oldval;
537 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
538 public FlagsHandle Set (Flags flagsToSet)
540 return new FlagsHandle (this, flagsToSet);
543 public FlagsHandle With (Flags bits, bool enable)
545 return new FlagsHandle (this, bits, enable ? bits : 0);
548 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
551 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
552 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
553 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
556 public bool IsInObsoleteScope {
558 // Disables obsolete checks when probing is on
559 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
563 public bool IsInProbingMode {
564 get { return (flags & Flags.ProbingMode) != 0; }
567 public bool IsInUnsafeScope {
568 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
571 public bool IsAnonymousMethodAllowed {
572 get { return isAnonymousMethodAllowed; }
573 set { isAnonymousMethodAllowed = value; }
576 public FlowBranching CurrentBranching {
577 get { return current_flow_branching; }
581 // Starts a new code branching. This inherits the state of all local
582 // variables and parameters from the current branching.
584 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
586 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
587 return current_flow_branching;
591 // Starts a new code branching for block `block'.
593 public FlowBranching StartFlowBranching (Block block)
595 FlowBranching.BranchingType type;
597 if ((CurrentBranching != null) &&
598 (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
599 type = FlowBranching.BranchingType.SwitchSection;
601 type = FlowBranching.BranchingType.Block;
603 flags |= Flags.DoFlowAnalysis;
605 current_flow_branching = FlowBranching.CreateBranching (
606 CurrentBranching, type, block, block.StartLocation);
607 return current_flow_branching;
610 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
612 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
613 current_flow_branching = branching;
617 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
619 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
620 current_flow_branching = branching;
624 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
626 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
627 current_flow_branching = branching;
632 // Ends a code branching. Merges the state of locals and parameters
633 // from all the children of the ending branching.
635 public FlowBranching.UsageVector DoEndFlowBranching ()
637 FlowBranching old = current_flow_branching;
638 current_flow_branching = current_flow_branching.Parent;
640 return current_flow_branching.MergeChild (old);
644 // Ends a code branching. Merges the state of locals and parameters
645 // from all the children of the ending branching.
647 public bool EndFlowBranching ()
649 FlowBranching.UsageVector vector = DoEndFlowBranching ();
651 return vector.IsUnreachable;
655 // Kills the current code branching. This throws away any changed state
656 // information and should only be used in case of an error.
658 public void KillFlowBranching ()
660 current_flow_branching = current_flow_branching.Parent;
663 public bool MustCaptureVariable (LocalInfo local)
665 if (CurrentAnonymousMethod == null)
667 if (CurrentAnonymousMethod.IsIterator)
669 return local.Block.Toplevel != CurrentBlock.Toplevel;
672 public void EmitMeta (ToplevelBlock b)
677 ReturnLabel = ig.DefineLabel ();
681 // Here until we can fix the problem with Mono.CSharp.Switch, which
682 // currently can not cope with ig == null during resolve (which must
683 // be fixed for switch statements to work on anonymous methods).
685 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
692 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
693 if (Report.Errors > 0)
698 current_phase = Phase.Emitting;
699 EmitResolvedTopBlock (block, unreachable);
705 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
706 Parameters ip, IMethodData md, out bool unreachable)
708 current_phase = Phase.Resolving;
716 CurrentFile = loc.File;
721 if (!block.ResolveMeta (this, ip))
724 if ((md != null) && (md.Iterator != null)) {
725 if (!md.Iterator.Define (this))
729 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
730 FlowBranchingToplevel top_level;
731 if (anonymous_method_host != null)
732 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
734 top_level = block.TopLevelBranching;
736 current_flow_branching = top_level;
737 bool ok = block.Resolve (this);
738 current_flow_branching = null;
743 bool flow_unreachable = top_level.End ();
744 if (flow_unreachable)
748 } catch (Exception e) {
749 Console.WriteLine ("Exception caught by the compiler while compiling:");
750 Console.WriteLine (" Block that caused the problem begin at: " + loc);
752 if (CurrentBlock != null){
753 Console.WriteLine (" Block being compiled: [{0},{1}]",
754 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
756 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
761 if (return_type != TypeManager.void_type && !unreachable) {
762 if (CurrentAnonymousMethod == null) {
763 Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
765 } else if (!CurrentAnonymousMethod.IsIterator) {
766 Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
767 CurrentAnonymousMethod.GetSignatureForError ());
772 if (!block.CompleteContexts (this))
779 public Type ReturnType {
788 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
794 ig.MarkLabel (ReturnLabel);
796 if (return_value != null){
797 ig.Emit (OpCodes.Ldloc, return_value);
798 ig.Emit (OpCodes.Ret);
801 // If `HasReturnLabel' is set, then we already emitted a
802 // jump to the end of the method, so we must emit a `ret'
805 // Unfortunately, System.Reflection.Emit automatically emits
806 // a leave to the end of a finally block. This is a problem
807 // if no code is following the try/finally block since we may
808 // jump to a point after the end of the method.
809 // As a workaround, we're always creating a return label in
813 bool in_iterator = (CurrentAnonymousMethod != null) &&
814 CurrentAnonymousMethod.IsIterator && InIterator;
816 if ((block != null) && block.IsDestructor) {
817 // Nothing to do; S.R.E automatically emits a leave.
818 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
819 if (return_type != TypeManager.void_type)
820 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
821 ig.Emit (OpCodes.Ret);
827 /// This is called immediately before emitting an IL opcode to tell the symbol
828 /// writer to which source line this opcode belongs.
830 public void Mark (Location loc, bool check_file)
832 if ((CodeGen.SymbolWriter == null) || loc.IsNull)
835 if (check_file && (CurrentFile != loc.File))
838 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
841 public void DefineLocalVariable (string name, LocalBuilder builder)
843 if (CodeGen.SymbolWriter == null)
846 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
849 public void BeginScope ()
853 if (CodeGen.SymbolWriter != null)
854 CodeGen.SymbolWriter.OpenScope(ig);
857 public void EndScope ()
861 if (CodeGen.SymbolWriter != null)
862 CodeGen.SymbolWriter.CloseScope(ig);
866 /// Returns a temporary storage for a variable of type t as
867 /// a local variable in the current body.
869 public LocalBuilder GetTemporaryLocal (Type t)
871 if (temporary_storage != null) {
872 object o = temporary_storage [t];
876 o = s.Count == 0 ? null : s.Pop ();
878 temporary_storage.Remove (t);
882 return (LocalBuilder) o;
884 return ig.DeclareLocal (t);
887 public void FreeTemporaryLocal (LocalBuilder b, Type t)
891 if (temporary_storage == null) {
892 temporary_storage = new Hashtable ();
893 temporary_storage [t] = b;
896 object o = temporary_storage [t];
898 temporary_storage [t] = b;
906 temporary_storage [t] = s;
912 /// Current loop begin and end labels.
914 public Label LoopBegin, LoopEnd;
917 /// Default target in a switch statement. Only valid if
920 public Label DefaultTarget;
923 /// If this is non-null, points to the current switch statement
925 public Switch Switch;
928 /// ReturnValue creates on demand the LocalBuilder for the
929 /// return value from the function. By default this is not
930 /// used. This is only required when returns are found inside
931 /// Try or Catch statements.
933 /// This method is typically invoked from the Emit phase, so
934 /// we allow the creation of a return label if it was not
935 /// requested during the resolution phase. Could be cleaned
936 /// up, but it would replicate a lot of logic in the Emit phase
937 /// of the code that uses it.
939 public LocalBuilder TemporaryReturn ()
941 if (return_value == null){
942 return_value = ig.DeclareLocal (return_type);
943 if (!HasReturnLabel){
944 ReturnLabel = ig.DefineLabel ();
945 HasReturnLabel = true;
953 /// This method is used during the Resolution phase to flag the
954 /// need to define the ReturnLabel
956 public void NeedReturnLabel ()
958 if (current_phase != Phase.Resolving){
960 // The reason is that the `ReturnLabel' is declared between
961 // resolution and emission
963 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
966 if (!InIterator && !HasReturnLabel)
967 HasReturnLabel = true;
971 public Expression GetThis (Location loc)
974 if (CurrentBlock != null)
975 my_this = new This (CurrentBlock, loc);
977 my_this = new This (loc);
979 if (!my_this.ResolveBase (this))
987 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
989 protected CommonAssemblyModulClass ():
994 public void AddAttributes (ArrayList attrs)
996 foreach (Attribute a in attrs)
999 if (attributes == null) {
1000 attributes = new Attributes (attrs);
1003 attributes.AddAttributes (attrs);
1006 public virtual void Emit (TypeContainer tc)
1008 if (OptAttributes == null)
1011 OptAttributes.Emit ();
1014 protected Attribute ResolveAttribute (Type a_type)
1016 Attribute a = OptAttributes.Search (a_type);
1023 public override IResolveContext ResolveContext {
1024 get { return this; }
1027 #region IResolveContext Members
1029 public DeclSpace DeclContainer {
1030 get { return RootContext.ToplevelTypes; }
1033 public DeclSpace GenericDeclContainer {
1034 get { return DeclContainer; }
1037 public bool IsInObsoleteScope {
1038 get { return false; }
1041 public bool IsInUnsafeScope {
1042 get { return false; }
1048 public class AssemblyClass : CommonAssemblyModulClass {
1049 // TODO: make it private and move all builder based methods here
1050 public AssemblyBuilder Builder;
1051 bool is_cls_compliant;
1052 bool wrap_non_exception_throws;
1054 public Attribute ClsCompliantAttribute;
1056 ListDictionary declarative_security;
1058 bool has_extension_method;
1059 public AssemblyName Name;
1060 MethodInfo add_type_forwarder;
1061 ListDictionary emitted_forwarders;
1064 // Module is here just because of error messages
1065 static string[] attribute_targets = new string [] { "assembly", "module" };
1067 public AssemblyClass (): base ()
1070 wrap_non_exception_throws = true;
1074 public bool HasExtensionMethods {
1077 has_extension_method = value;
1082 public bool IsClsCompliant {
1084 return is_cls_compliant;
1088 public bool WrapNonExceptionThrows {
1090 return wrap_non_exception_throws;
1094 public override AttributeTargets AttributeTargets {
1096 return AttributeTargets.Assembly;
1100 public override bool IsClsComplianceRequired ()
1102 return is_cls_compliant;
1105 public void Resolve ()
1107 if (OptAttributes == null)
1110 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1111 if (!OptAttributes.CheckTargets())
1114 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1115 if (ClsCompliantAttribute != null) {
1116 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1120 Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1122 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1124 wrap_non_exception_throws = (bool)val;
1130 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1133 // check for possible ECMA key
1134 if (strongNameBlob.Length == 16) {
1135 // will be rejected if not "the" ECMA key
1136 an.SetPublicKey (strongNameBlob);
1139 // take it, with or without, a private key
1140 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1141 // and make sure we only feed the public part to Sys.Ref
1142 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1144 // AssemblyName.SetPublicKey requires an additional header
1145 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1147 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1148 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1149 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1150 an.SetPublicKey (encodedPublicKey);
1154 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1155 Environment.Exit (1);
1159 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1160 public AssemblyName GetAssemblyName (string name, string output)
1162 if (OptAttributes != null) {
1163 foreach (Attribute a in OptAttributes.Attrs) {
1164 // cannot rely on any resolve-based members before you call Resolve
1165 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1168 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1169 // However, this is invoked by CodeGen.Init, when none of the namespaces
1171 // TODO: Does not handle quoted attributes properly
1173 case "AssemblyKeyFile":
1174 case "AssemblyKeyFileAttribute":
1175 case "System.Reflection.AssemblyKeyFileAttribute":
1176 if (RootContext.StrongNameKeyFile != null) {
1177 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1178 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1179 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1182 string value = a.GetString ();
1183 if (value.Length != 0)
1184 RootContext.StrongNameKeyFile = value;
1187 case "AssemblyKeyName":
1188 case "AssemblyKeyNameAttribute":
1189 case "System.Reflection.AssemblyKeyNameAttribute":
1190 if (RootContext.StrongNameKeyContainer != null) {
1191 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1192 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1193 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1196 string value = a.GetString ();
1197 if (value.Length != 0)
1198 RootContext.StrongNameKeyContainer = value;
1201 case "AssemblyDelaySign":
1202 case "AssemblyDelaySignAttribute":
1203 case "System.Reflection.AssemblyDelaySignAttribute":
1204 RootContext.StrongNameDelaySign = a.GetBoolean ();
1210 AssemblyName an = new AssemblyName ();
1211 an.Name = Path.GetFileNameWithoutExtension (name);
1213 // note: delay doesn't apply when using a key container
1214 if (RootContext.StrongNameKeyContainer != null) {
1215 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1219 // strongname is optional
1220 if (RootContext.StrongNameKeyFile == null)
1223 string AssemblyDir = Path.GetDirectoryName (output);
1225 // the StrongName key file may be relative to (a) the compiled
1226 // file or (b) to the output assembly. See bugzilla #55320
1227 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1229 // (a) relative to the compiled file
1230 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1231 bool exist = File.Exists (filename);
1232 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1233 // (b) relative to the outputed assembly
1234 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1235 exist = File.Exists (filename);
1239 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1240 byte[] snkeypair = new byte [fs.Length];
1241 fs.Read (snkeypair, 0, snkeypair.Length);
1243 if (RootContext.StrongNameDelaySign) {
1244 // delayed signing - DO NOT include private key
1245 SetPublicKey (an, snkeypair);
1248 // no delay so we make sure we have the private key
1250 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1251 an.KeyPair = new StrongNameKeyPair (snkeypair);
1253 catch (CryptographicException) {
1254 if (snkeypair.Length == 16) {
1255 // error # is different for ECMA key
1256 Report.Error (1606, "Could not sign the assembly. " +
1257 "ECMA key can only be used to delay-sign assemblies");
1260 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1268 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1274 void Error_AssemblySigning (string text)
1276 Report.Error (1548, "Error during assembly signing. " + text);
1280 bool CheckInternalsVisibleAttribute (Attribute a)
1282 string assembly_name = a.GetString ();
1283 if (assembly_name.Length == 0)
1286 AssemblyName aname = null;
1288 aname = new AssemblyName (assembly_name);
1289 } catch (FileLoadException) {
1290 } catch (ArgumentException) {
1293 // Bad assembly name format
1295 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1296 // Report error if we have defined Version or Culture
1297 else if (aname.Version != null || aname.CultureInfo != null)
1298 throw new Exception ("Friend assembly `" + a.GetString () +
1299 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1300 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null) {
1301 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1302 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1310 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1312 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1313 if (declarative_security == null)
1314 declarative_security = new ListDictionary ();
1316 a.ExtractSecurityPermissionSet (declarative_security);
1320 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1321 string value = a.GetString ();
1322 if (value == null || value.Length == 0)
1325 if (RootContext.Target == Target.Exe) {
1326 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1332 if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1335 if (a.Type == TypeManager.type_forwarder_attr_type) {
1336 Type t = a.GetArgumentType ();
1337 if (t == null || TypeManager.HasElementType (t)) {
1338 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1342 if (emitted_forwarders == null) {
1343 emitted_forwarders = new ListDictionary();
1344 } else if (emitted_forwarders.Contains(t)) {
1345 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1346 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1347 TypeManager.CSharpName(t));
1351 emitted_forwarders.Add(t, a);
1353 if (TypeManager.LookupDeclSpace (t) != null) {
1354 Report.SymbolRelatedToPreviousError (t);
1355 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1356 TypeManager.CSharpName (t));
1361 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1362 TypeManager.CSharpName (t));
1366 if (t.IsGenericType) {
1367 Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1371 if (add_type_forwarder == null) {
1372 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1373 BindingFlags.NonPublic | BindingFlags.Instance);
1375 if (add_type_forwarder == null) {
1376 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1381 add_type_forwarder.Invoke (Builder, new object[] { t });
1385 if (a.Type == TypeManager.extension_attribute_type) {
1386 a.Error_MisusedExtensionAttribute ();
1390 Builder.SetCustomAttribute (customBuilder);
1393 public override void Emit (TypeContainer tc)
1398 if (has_extension_method)
1399 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1401 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1402 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.runtime_compatibility_attr_type)) {
1403 ConstructorInfo ci = TypeManager.GetConstructor (
1404 TypeManager.runtime_compatibility_attr_type, Type.EmptyTypes);
1405 PropertyInfo [] pis = new PropertyInfo [1];
1406 pis [0] = TypeManager.GetProperty (
1407 TypeManager.runtime_compatibility_attr_type, "WrapNonExceptionThrows");
1408 object [] pargs = new object [1];
1410 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1414 if (declarative_security != null) {
1416 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1417 object builder_instance = Builder;
1420 // Microsoft runtime hacking
1421 if (add_permission == null) {
1422 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1423 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1425 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1426 builder_instance = fi.GetValue (Builder);
1429 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1430 declarative_security [SecurityAction.RequestOptional],
1431 declarative_security [SecurityAction.RequestRefuse] };
1432 add_permission.Invoke (builder_instance, args);
1435 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1440 public override string[] ValidAttributeTargets {
1442 return attribute_targets;
1446 // Wrapper for AssemblyBuilder.AddModule
1447 static MethodInfo adder_method;
1448 static public MethodInfo AddModule_Method {
1450 if (adder_method == null)
1451 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1452 return adder_method;
1455 public Module AddModule (string module)
1457 MethodInfo m = AddModule_Method;
1459 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1460 Environment.Exit (1);
1464 return (Module) m.Invoke (Builder, new object [] { module });
1465 } catch (TargetInvocationException ex) {
1466 throw ex.InnerException;
1471 public class ModuleClass : CommonAssemblyModulClass {
1472 // TODO: make it private and move all builder based methods here
1473 public ModuleBuilder Builder;
1474 bool m_module_is_unsafe;
1475 bool has_default_charset;
1477 public CharSet DefaultCharSet = CharSet.Ansi;
1478 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1480 static string[] attribute_targets = new string [] { "module" };
1482 public ModuleClass (bool is_unsafe)
1484 m_module_is_unsafe = is_unsafe;
1487 public override AttributeTargets AttributeTargets {
1489 return AttributeTargets.Module;
1493 public override bool IsClsComplianceRequired ()
1495 return CodeGen.Assembly.IsClsCompliant;
1498 public override void Emit (TypeContainer tc)
1502 if (!m_module_is_unsafe)
1505 if (TypeManager.unverifiable_code_ctor == null) {
1506 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1510 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1513 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1515 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1516 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1517 Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1519 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1520 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1521 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1526 Builder.SetCustomAttribute (customBuilder);
1529 public bool HasDefaultCharSet {
1531 return has_default_charset;
1536 /// It is called very early therefore can resolve only predefined attributes
1538 public void Resolve ()
1541 if (OptAttributes == null)
1544 if (!OptAttributes.CheckTargets())
1547 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1549 has_default_charset = true;
1550 DefaultCharSet = a.GetCharSetValue ();
1551 switch (DefaultCharSet) {
1556 DefaultCharSetType = TypeAttributes.AutoClass;
1558 case CharSet.Unicode:
1559 DefaultCharSetType = TypeAttributes.UnicodeClass;
1562 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1569 public override string[] ValidAttributeTargets {
1571 return attribute_targets;