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.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;
41 static public SymbolWriter SymbolWriter;
43 public static AssemblyClass Assembly;
44 public static ModuleClass Module;
51 public static void Reset ()
53 Assembly = new AssemblyClass ();
54 Module = new ModuleClass (RootContext.Unsafe);
57 public static string Basename (string name)
59 int pos = name.LastIndexOf ('/');
62 return name.Substring (pos + 1);
64 pos = name.LastIndexOf ('\\');
66 return name.Substring (pos + 1);
71 public static string Dirname (string name)
73 int pos = name.LastIndexOf ('/');
76 return name.Substring (0, pos);
78 pos = name.LastIndexOf ('\\');
80 return name.Substring (0, pos);
85 static public string FileName;
88 // Initializes the symbol writer
90 static void InitializeSymbolWriter (string filename)
92 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
95 // If we got an ISymbolWriter instance, initialize it.
97 if (SymbolWriter == null) {
99 -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.");
105 // Initializes the code generator variables
107 static public bool Init (string name, string output, bool want_debugging_support)
110 AssemblyName an = Assembly.GetAssemblyName (name, output);
114 if (an.KeyPair != null) {
115 // If we are going to strong name our assembly make
116 // sure all its refs are strong named
117 foreach (Assembly a in RootNamespace.Global.Assemblies) {
118 AssemblyName ref_name = a.GetName ();
119 byte [] b = ref_name.GetPublicKeyToken ();
120 if (b == null || b.Length == 0) {
121 Report.Error (1577, "Assembly generation failed " +
122 "-- Referenced assembly '" +
124 "' does not have a strong name.");
125 //Environment.Exit (1);
130 current_domain = AppDomain.CurrentDomain;
134 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
136 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
137 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
140 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
141 AssemblyBuilderAccess.Save | COMPILER_ACCESS, Dirname (name));
143 catch (ArgumentException) {
144 // specified key may not be exportable outside it's container
145 if (RootContext.StrongNameKeyContainer != null) {
146 Report.Error (1548, "Could not access the key inside the container `" +
147 RootContext.StrongNameKeyContainer + "'.");
148 Environment.Exit (1);
152 catch (CryptographicException) {
153 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
154 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
155 Environment.Exit (1);
161 // Get the complete AssemblyName from the builder
162 // (We need to get the public key and token)
163 Assembly.Name = Assembly.Builder.GetName ();
167 // Pass a path-less name to DefineDynamicModule. Wonder how
168 // this copes with output in different directories then.
169 // FIXME: figure out how this copes with --output /tmp/blah
171 // If the third argument is true, the ModuleBuilder will dynamically
172 // load the default symbol writer.
174 Module.Builder = Assembly.Builder.DefineDynamicModule (
175 Basename (name), Basename (output), false);
177 if (want_debugging_support)
178 InitializeSymbolWriter (output);
183 static public void Save (string name)
186 Assembly.Builder.Save (Basename (name));
188 if (SymbolWriter != null)
189 SymbolWriter.WriteSymbolFile ();
191 catch (COMException) {
192 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
195 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
196 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
197 RootContext.StrongNameKeyFile +
198 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
200 catch (System.IO.IOException io) {
201 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
203 catch (System.UnauthorizedAccessException ua) {
204 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
210 public interface IResolveContext
212 DeclSpace DeclContainer { get; }
213 bool IsInObsoleteScope { get; }
214 bool IsInUnsafeScope { get; }
216 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
218 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
219 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
220 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
221 // handle generic method overrides differently
222 DeclSpace GenericDeclContainer { get; }
226 /// An Emit Context is created for each body of code (from methods,
227 /// properties bodies, indexer bodies or constructor bodies)
229 public class EmitContext : IResolveContext {
232 // Holds a varible used during collection or object initialization.
234 public Expression CurrentInitializerVariable;
236 DeclSpace decl_space;
238 public DeclSpace TypeContainer;
239 public ILGenerator ig;
242 public enum Flags : int {
244 /// This flag tracks the `checked' state of the compilation,
245 /// it controls whether we should generate code that does overflow
246 /// checking, or if we generate code that ignores overflows.
248 /// The default setting comes from the command line option to generate
249 /// checked or unchecked code plus any source code changes using the
250 /// checked/unchecked statements or expressions. Contrast this with
251 /// the ConstantCheckState flag.
256 /// The constant check state is always set to `true' and cant be changed
257 /// from the command line. The source code can change this setting with
258 /// the `checked' and `unchecked' statements and expressions.
260 ConstantCheckState = 1 << 1,
262 AllCheckStateFlags = CheckState | ConstantCheckState,
265 /// Whether we are inside an unsafe block
273 /// Whether control flow analysis is enabled
275 DoFlowAnalysis = 1 << 5,
278 /// Whether control flow analysis is disabled on structs
279 /// (only meaningful when DoFlowAnalysis is set)
281 OmitStructFlowAnalysis = 1 << 6,
284 /// Indicates the current context is in probing mode, no errors are reported.
286 ProbingMode = 1 << 7,
289 // Inside field intializer expression
291 InFieldInitializer = 1 << 8,
293 InferReturnType = 1 << 9,
295 InCompoundAssignment = 1 << 10
301 /// Whether we are emitting code inside a static or instance method
303 public bool IsStatic;
306 /// Whether the actual created method is static or instance method.
307 /// Althoug the method might be declared as `static', if an anonymous
308 /// method is involved, we might turn this into an instance method.
310 /// So this reflects the low-level staticness of the method, while
311 /// IsStatic represents the semantic, high-level staticness.
313 public bool MethodIsStatic;
316 /// The value that is allowed to be returned or NULL if there is no
322 /// Points to the Type (extracted from the TypeContainer) that
323 /// declares this body of code
325 public readonly Type ContainerType;
328 /// Whether this is generating code for a constructor
330 public bool IsConstructor;
333 /// Keeps track of the Type to LocalBuilder temporary storage created
334 /// to store structures (used to compute the address of the structure
335 /// value on structure method invocations)
337 public Hashtable temporary_storage;
339 public Block CurrentBlock;
341 public int CurrentFile;
344 /// The location where we store the return value.
346 LocalBuilder return_value;
349 /// The location where return has to jump to return the
352 public Label ReturnLabel;
355 /// If we already defined the ReturnLabel
357 public bool HasReturnLabel;
360 /// Whether we are inside an iterator block.
362 public bool InIterator;
365 /// Whether we are in a `fixed' initialization
367 public bool InFixedInitializer;
370 /// Whether we are inside an anonymous method.
372 public AnonymousContainer CurrentAnonymousMethod;
375 /// Location for this EmitContext
380 /// Inside an enum definition, we do not resolve enumeration values
381 /// to their enumerations, but rather to the underlying type/value
382 /// This is so EnumVal + EnumValB can be evaluated.
384 /// There is no "E operator + (E x, E y)", so during an enum evaluation
385 /// we relax the rules
387 public bool InEnumContext;
389 public readonly IResolveContext ResolveContext;
392 /// The current iterator
394 public Iterator CurrentIterator {
395 get { return CurrentAnonymousMethod as Iterator; }
399 /// Whether we are in the resolving stage or not
407 public static EmitContext TempEc;
409 bool isAnonymousMethodAllowed = true;
412 FlowBranching current_flow_branching;
414 static int next_id = 0;
417 public override string ToString ()
419 return String.Format ("EmitContext ({0}:{1})", id,
420 CurrentAnonymousMethod, loc);
423 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
424 Type return_type, int code_flags, bool is_constructor)
426 this.ResolveContext = rc;
429 TypeContainer = parent;
430 this.decl_space = ds;
431 if (RootContext.Checked)
432 flags |= Flags.CheckState;
433 flags |= Flags.ConstantCheckState;
435 if (return_type == null)
436 throw new ArgumentNullException ("return_type");
438 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
439 throw new InternalErrorException ();
442 IsStatic = (code_flags & Modifiers.STATIC) != 0;
443 MethodIsStatic = IsStatic;
444 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
445 ReturnType = return_type;
446 IsConstructor = is_constructor;
449 current_phase = Phase.Created;
452 // Can only be null for the ResolveType contexts.
453 ContainerType = parent.TypeBuilder;
454 if (rc.IsInUnsafeScope)
455 flags |= Flags.InUnsafe;
460 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
461 Type return_type, int code_flags, bool is_constructor)
462 : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
466 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
467 Type return_type, int code_flags)
468 : this (rc, ds, ds, l, ig, return_type, code_flags, false)
472 public DeclSpace DeclContainer {
473 get { return decl_space; }
474 set { decl_space = value; }
477 public DeclSpace GenericDeclContainer {
478 get { return DeclContainer; }
481 public bool CheckState {
482 get { return (flags & Flags.CheckState) != 0; }
485 public bool ConstantCheckState {
486 get { return (flags & Flags.ConstantCheckState) != 0; }
489 public bool InUnsafe {
490 get { return (flags & Flags.InUnsafe) != 0; }
493 public bool InCatch {
494 get { return (flags & Flags.InCatch) != 0; }
497 public bool InFinally {
498 get { return (flags & Flags.InFinally) != 0; }
501 public bool DoFlowAnalysis {
502 get { return (flags & Flags.DoFlowAnalysis) != 0; }
505 public bool OmitStructFlowAnalysis {
506 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
509 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
510 // it's public so that we can use a struct at the callsite
511 public struct FlagsHandle : IDisposable
514 readonly Flags invmask, oldval;
516 public FlagsHandle (EmitContext ec, Flags flagsToSet)
517 : this (ec, flagsToSet, flagsToSet)
521 internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
525 oldval = ec.flags & mask;
526 ec.flags = (ec.flags & invmask) | (val & mask);
528 if ((mask & Flags.ProbingMode) != 0)
529 Report.DisableReporting ();
532 public void Dispose ()
534 if ((invmask & Flags.ProbingMode) == 0)
535 Report.EnableReporting ();
537 ec.flags = (ec.flags & invmask) | oldval;
541 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
542 public FlagsHandle Set (Flags flagsToSet)
544 return new FlagsHandle (this, flagsToSet);
547 public FlagsHandle With (Flags bits, bool enable)
549 return new FlagsHandle (this, bits, enable ? bits : 0);
552 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
555 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
556 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
557 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
561 /// If this is true, then Return and ContextualReturn statements
562 /// will set the ReturnType value based on the expression types
563 /// of each return statement instead of the method return type
564 /// (which is initially null).
566 public bool InferReturnType {
567 get { return (flags & Flags.InferReturnType) != 0; }
570 public bool IsInObsoleteScope {
572 // Disables obsolete checks when probing is on
573 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
577 public bool IsInProbingMode {
578 get { return (flags & Flags.ProbingMode) != 0; }
581 public bool IsInUnsafeScope {
582 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
585 public bool IsAnonymousMethodAllowed {
586 get { return isAnonymousMethodAllowed; }
587 set { isAnonymousMethodAllowed = value; }
590 public bool IsInFieldInitializer {
591 get { return (flags & Flags.InFieldInitializer) != 0; }
594 public bool IsInCompoundAssignment {
595 get { return (flags & Flags.InCompoundAssignment) != 0; }
598 public FlowBranching CurrentBranching {
599 get { return current_flow_branching; }
603 // Starts a new code branching. This inherits the state of all local
604 // variables and parameters from the current branching.
606 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
608 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
609 return current_flow_branching;
613 // Starts a new code branching for block `block'.
615 public FlowBranching StartFlowBranching (Block block)
617 FlowBranching.BranchingType type;
619 if ((CurrentBranching != null) &&
620 (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
621 type = FlowBranching.BranchingType.SwitchSection;
623 type = FlowBranching.BranchingType.Block;
625 flags |= Flags.DoFlowAnalysis;
627 current_flow_branching = FlowBranching.CreateBranching (
628 CurrentBranching, type, block, block.StartLocation);
629 return current_flow_branching;
632 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
634 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
635 current_flow_branching = branching;
639 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
641 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
642 current_flow_branching = branching;
646 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
648 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
649 current_flow_branching = branching;
654 // Ends a code branching. Merges the state of locals and parameters
655 // from all the children of the ending branching.
657 public FlowBranching.UsageVector DoEndFlowBranching ()
659 FlowBranching old = current_flow_branching;
660 current_flow_branching = current_flow_branching.Parent;
662 return current_flow_branching.MergeChild (old);
666 // Ends a code branching. Merges the state of locals and parameters
667 // from all the children of the ending branching.
669 public bool EndFlowBranching ()
671 FlowBranching.UsageVector vector = DoEndFlowBranching ();
673 return vector.IsUnreachable;
677 // Kills the current code branching. This throws away any changed state
678 // information and should only be used in case of an error.
680 public void KillFlowBranching ()
682 current_flow_branching = current_flow_branching.Parent;
685 public bool MustCaptureVariable (LocalInfo local)
687 if (CurrentAnonymousMethod == null)
689 if (CurrentAnonymousMethod.IsIterator)
691 return local.Block.Toplevel != CurrentBlock.Toplevel;
694 public void EmitMeta (ToplevelBlock b)
699 ReturnLabel = ig.DefineLabel ();
703 // Here until we can fix the problem with Mono.CSharp.Switch, which
704 // currently can not cope with ig == null during resolve (which must
705 // be fixed for switch statements to work on anonymous methods).
707 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
714 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
715 if (Report.Errors > 0)
720 current_phase = Phase.Emitting;
721 EmitResolvedTopBlock (block, unreachable);
727 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
728 Parameters ip, IMethodData md, out bool unreachable)
730 current_phase = Phase.Resolving;
738 CurrentFile = loc.File;
743 if (!block.ResolveMeta (this, ip))
746 if ((md != null) && (md.Iterator != null)) {
747 if (!md.Iterator.Define (this))
751 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
752 FlowBranchingToplevel top_level;
753 if (anonymous_method_host != null)
754 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
756 top_level = block.TopLevelBranching;
758 current_flow_branching = top_level;
759 bool ok = block.Resolve (this);
760 current_flow_branching = null;
765 bool flow_unreachable = top_level.End ();
766 if (flow_unreachable)
770 } catch (Exception e) {
771 Console.WriteLine ("Exception caught by the compiler while compiling:");
772 Console.WriteLine (" Block that caused the problem begin at: " + loc);
774 if (CurrentBlock != null){
775 Console.WriteLine (" Block being compiled: [{0},{1}]",
776 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
778 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
783 if (return_type != TypeManager.void_type && !unreachable) {
784 if (CurrentAnonymousMethod == null) {
785 Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
787 } else if (!CurrentAnonymousMethod.IsIterator) {
788 Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
789 CurrentAnonymousMethod.GetSignatureForError ());
794 if (!block.CompleteContexts (this))
801 public Type ReturnType {
810 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
816 ig.MarkLabel (ReturnLabel);
818 if (return_value != null){
819 ig.Emit (OpCodes.Ldloc, return_value);
820 ig.Emit (OpCodes.Ret);
823 // If `HasReturnLabel' is set, then we already emitted a
824 // jump to the end of the method, so we must emit a `ret'
827 // Unfortunately, System.Reflection.Emit automatically emits
828 // a leave to the end of a finally block. This is a problem
829 // if no code is following the try/finally block since we may
830 // jump to a point after the end of the method.
831 // As a workaround, we're always creating a return label in
835 bool in_iterator = (CurrentAnonymousMethod != null) &&
836 CurrentAnonymousMethod.IsIterator && InIterator;
838 if ((block != null) && block.IsDestructor) {
839 // Nothing to do; S.R.E automatically emits a leave.
840 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
841 if (return_type != TypeManager.void_type)
842 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
843 ig.Emit (OpCodes.Ret);
849 /// This is called immediately before emitting an IL opcode to tell the symbol
850 /// writer to which source line this opcode belongs.
852 public void Mark (Location loc, bool check_file)
854 if ((CodeGen.SymbolWriter == null) || loc.IsNull)
857 if (check_file && (CurrentFile != loc.File))
860 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
863 public void DefineLocalVariable (string name, LocalBuilder builder)
865 if (CodeGen.SymbolWriter == null)
868 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
871 public void BeginScope ()
875 if (CodeGen.SymbolWriter != null)
876 CodeGen.SymbolWriter.OpenScope(ig);
879 public void EndScope ()
883 if (CodeGen.SymbolWriter != null)
884 CodeGen.SymbolWriter.CloseScope(ig);
888 /// Returns a temporary storage for a variable of type t as
889 /// a local variable in the current body.
891 public LocalBuilder GetTemporaryLocal (Type t)
893 if (temporary_storage != null) {
894 object o = temporary_storage [t];
898 o = s.Count == 0 ? null : s.Pop ();
900 temporary_storage.Remove (t);
904 return (LocalBuilder) o;
906 return ig.DeclareLocal (t);
909 public void FreeTemporaryLocal (LocalBuilder b, Type t)
913 if (temporary_storage == null) {
914 temporary_storage = new Hashtable ();
915 temporary_storage [t] = b;
918 object o = temporary_storage [t];
920 temporary_storage [t] = b;
928 temporary_storage [t] = s;
934 /// Current loop begin and end labels.
936 public Label LoopBegin, LoopEnd;
939 /// Default target in a switch statement. Only valid if
942 public Label DefaultTarget;
945 /// If this is non-null, points to the current switch statement
947 public Switch Switch;
950 /// ReturnValue creates on demand the LocalBuilder for the
951 /// return value from the function. By default this is not
952 /// used. This is only required when returns are found inside
953 /// Try or Catch statements.
955 /// This method is typically invoked from the Emit phase, so
956 /// we allow the creation of a return label if it was not
957 /// requested during the resolution phase. Could be cleaned
958 /// up, but it would replicate a lot of logic in the Emit phase
959 /// of the code that uses it.
961 public LocalBuilder TemporaryReturn ()
963 if (return_value == null){
964 return_value = ig.DeclareLocal (return_type);
965 if (!HasReturnLabel){
966 ReturnLabel = ig.DefineLabel ();
967 HasReturnLabel = true;
975 /// This method is used during the Resolution phase to flag the
976 /// need to define the ReturnLabel
978 public void NeedReturnLabel ()
980 if (current_phase != Phase.Resolving){
982 // The reason is that the `ReturnLabel' is declared between
983 // resolution and emission
985 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
988 if (!InIterator && !HasReturnLabel)
989 HasReturnLabel = true;
993 public Expression GetThis (Location loc)
996 if (CurrentBlock != null)
997 my_this = new This (CurrentBlock, loc);
999 my_this = new This (loc);
1001 if (!my_this.ResolveBase (this))
1009 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1011 protected CommonAssemblyModulClass ():
1016 public void AddAttributes (ArrayList attrs)
1018 foreach (Attribute a in attrs)
1021 if (attributes == null) {
1022 attributes = new Attributes (attrs);
1025 attributes.AddAttributes (attrs);
1028 public virtual void Emit (TypeContainer tc)
1030 if (OptAttributes == null)
1033 OptAttributes.Emit ();
1036 protected Attribute ResolveAttribute (Type a_type)
1038 Attribute a = OptAttributes.Search (a_type);
1045 public override IResolveContext ResolveContext {
1046 get { return this; }
1049 #region IResolveContext Members
1051 public DeclSpace DeclContainer {
1052 get { return RootContext.ToplevelTypes; }
1055 public DeclSpace GenericDeclContainer {
1056 get { return DeclContainer; }
1059 public bool IsInObsoleteScope {
1060 get { return false; }
1063 public bool IsInUnsafeScope {
1064 get { return false; }
1070 public class AssemblyClass : CommonAssemblyModulClass {
1071 // TODO: make it private and move all builder based methods here
1072 public AssemblyBuilder Builder;
1073 bool is_cls_compliant;
1074 bool wrap_non_exception_throws;
1076 public Attribute ClsCompliantAttribute;
1078 ListDictionary declarative_security;
1080 bool has_extension_method;
1081 public AssemblyName Name;
1082 MethodInfo add_type_forwarder;
1083 ListDictionary emitted_forwarders;
1086 // Module is here just because of error messages
1087 static string[] attribute_targets = new string [] { "assembly", "module" };
1089 public AssemblyClass (): base ()
1092 wrap_non_exception_throws = true;
1096 public bool HasExtensionMethods {
1099 has_extension_method = value;
1104 public bool IsClsCompliant {
1106 return is_cls_compliant;
1110 public bool WrapNonExceptionThrows {
1112 return wrap_non_exception_throws;
1116 public override AttributeTargets AttributeTargets {
1118 return AttributeTargets.Assembly;
1122 public override bool IsClsComplianceRequired ()
1124 return is_cls_compliant;
1127 public void Resolve ()
1129 if (OptAttributes == null)
1132 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1133 if (!OptAttributes.CheckTargets())
1136 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1137 if (ClsCompliantAttribute != null) {
1138 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1142 Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1144 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1146 wrap_non_exception_throws = (bool)val;
1152 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1155 // check for possible ECMA key
1156 if (strongNameBlob.Length == 16) {
1157 // will be rejected if not "the" ECMA key
1158 an.SetPublicKey (strongNameBlob);
1161 // take it, with or without, a private key
1162 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1163 // and make sure we only feed the public part to Sys.Ref
1164 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1166 // AssemblyName.SetPublicKey requires an additional header
1167 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1169 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1170 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1171 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1172 an.SetPublicKey (encodedPublicKey);
1176 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1177 Environment.Exit (1);
1181 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1182 public AssemblyName GetAssemblyName (string name, string output)
1184 if (OptAttributes != null) {
1185 foreach (Attribute a in OptAttributes.Attrs) {
1186 // cannot rely on any resolve-based members before you call Resolve
1187 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1190 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1191 // However, this is invoked by CodeGen.Init, when none of the namespaces
1193 // TODO: Does not handle quoted attributes properly
1195 case "AssemblyKeyFile":
1196 case "AssemblyKeyFileAttribute":
1197 case "System.Reflection.AssemblyKeyFileAttribute":
1198 if (RootContext.StrongNameKeyFile != null) {
1199 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1200 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1201 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1204 string value = a.GetString ();
1205 if (value.Length != 0)
1206 RootContext.StrongNameKeyFile = value;
1209 case "AssemblyKeyName":
1210 case "AssemblyKeyNameAttribute":
1211 case "System.Reflection.AssemblyKeyNameAttribute":
1212 if (RootContext.StrongNameKeyContainer != null) {
1213 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1214 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1215 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1218 string value = a.GetString ();
1219 if (value.Length != 0)
1220 RootContext.StrongNameKeyContainer = value;
1223 case "AssemblyDelaySign":
1224 case "AssemblyDelaySignAttribute":
1225 case "System.Reflection.AssemblyDelaySignAttribute":
1226 RootContext.StrongNameDelaySign = a.GetBoolean ();
1232 AssemblyName an = new AssemblyName ();
1233 an.Name = Path.GetFileNameWithoutExtension (name);
1235 // note: delay doesn't apply when using a key container
1236 if (RootContext.StrongNameKeyContainer != null) {
1237 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1241 // strongname is optional
1242 if (RootContext.StrongNameKeyFile == null)
1245 string AssemblyDir = Path.GetDirectoryName (output);
1247 // the StrongName key file may be relative to (a) the compiled
1248 // file or (b) to the output assembly. See bugzilla #55320
1249 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1251 // (a) relative to the compiled file
1252 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1253 bool exist = File.Exists (filename);
1254 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1255 // (b) relative to the outputed assembly
1256 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1257 exist = File.Exists (filename);
1261 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1262 byte[] snkeypair = new byte [fs.Length];
1263 fs.Read (snkeypair, 0, snkeypair.Length);
1265 if (RootContext.StrongNameDelaySign) {
1266 // delayed signing - DO NOT include private key
1267 SetPublicKey (an, snkeypair);
1270 // no delay so we make sure we have the private key
1272 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1273 an.KeyPair = new StrongNameKeyPair (snkeypair);
1275 catch (CryptographicException) {
1276 if (snkeypair.Length == 16) {
1277 // error # is different for ECMA key
1278 Report.Error (1606, "Could not sign the assembly. " +
1279 "ECMA key can only be used to delay-sign assemblies");
1282 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1290 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1296 void Error_AssemblySigning (string text)
1298 Report.Error (1548, "Error during assembly signing. " + text);
1302 bool CheckInternalsVisibleAttribute (Attribute a)
1304 string assembly_name = a.GetString ();
1305 if (assembly_name.Length == 0)
1308 AssemblyName aname = null;
1310 aname = new AssemblyName (assembly_name);
1311 } catch (FileLoadException) {
1312 } catch (ArgumentException) {
1315 // Bad assembly name format
1317 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1318 // Report error if we have defined Version or Culture
1319 else if (aname.Version != null || aname.CultureInfo != null)
1320 throw new Exception ("Friend assembly `" + a.GetString () +
1321 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1322 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1323 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1324 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1332 static bool IsValidAssemblyVersion (string version)
1336 v = new Version (version);
1339 int major = int.Parse (version, CultureInfo.InvariantCulture);
1340 v = new Version (major, 0);
1346 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1347 if (candidate > ushort.MaxValue)
1354 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1356 if (TypeManager.IsSubclassOf (a.Type, TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1357 if (declarative_security == null)
1358 declarative_security = new ListDictionary ();
1360 a.ExtractSecurityPermissionSet (declarative_security);
1364 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1365 string value = a.GetString ();
1366 if (value == null || value.Length == 0)
1369 if (RootContext.Target == Target.Exe) {
1370 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1375 if (a.Type == TypeManager.assembly_version_attribute_type) {
1376 string value = a.GetString ();
1377 if (value == null || value.Length == 0)
1380 value = value.Replace ('*', '0');
1382 if (!IsValidAssemblyVersion (value)) {
1383 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1389 if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1392 if (a.Type == TypeManager.type_forwarder_attr_type) {
1393 Type t = a.GetArgumentType ();
1394 if (t == null || TypeManager.HasElementType (t)) {
1395 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1399 if (emitted_forwarders == null) {
1400 emitted_forwarders = new ListDictionary();
1401 } else if (emitted_forwarders.Contains(t)) {
1402 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1403 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1404 TypeManager.CSharpName(t));
1408 emitted_forwarders.Add(t, a);
1410 if (TypeManager.LookupDeclSpace (t) != null) {
1411 Report.SymbolRelatedToPreviousError (t);
1412 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1413 TypeManager.CSharpName (t));
1418 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1419 TypeManager.CSharpName (t));
1423 if (t.IsGenericType) {
1424 Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1428 if (add_type_forwarder == null) {
1429 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1430 BindingFlags.NonPublic | BindingFlags.Instance);
1432 if (add_type_forwarder == null) {
1433 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1438 add_type_forwarder.Invoke (Builder, new object[] { t });
1442 if (a.Type == TypeManager.extension_attribute_type) {
1443 a.Error_MisusedExtensionAttribute ();
1447 Builder.SetCustomAttribute (customBuilder);
1450 public override void Emit (TypeContainer tc)
1455 if (has_extension_method)
1456 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1458 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1459 if (OptAttributes == null || !OptAttributes.Contains (TypeManager.runtime_compatibility_attr_type)) {
1460 ConstructorInfo ci = TypeManager.GetCoreConstructor (
1461 TypeManager.runtime_compatibility_attr_type, Type.EmptyTypes);
1462 PropertyInfo [] pis = new PropertyInfo [1];
1463 pis [0] = TypeManager.GetCoreProperty (
1464 TypeManager.runtime_compatibility_attr_type, "WrapNonExceptionThrows");
1465 object [] pargs = new object [1];
1467 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1471 if (declarative_security != null) {
1473 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1474 object builder_instance = Builder;
1477 // Microsoft runtime hacking
1478 if (add_permission == null) {
1479 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1480 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1482 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1483 builder_instance = fi.GetValue (Builder);
1486 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1487 declarative_security [SecurityAction.RequestOptional],
1488 declarative_security [SecurityAction.RequestRefuse] };
1489 add_permission.Invoke (builder_instance, args);
1492 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1497 public override string[] ValidAttributeTargets {
1499 return attribute_targets;
1503 // Wrapper for AssemblyBuilder.AddModule
1504 static MethodInfo adder_method;
1505 static public MethodInfo AddModule_Method {
1507 if (adder_method == null)
1508 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1509 return adder_method;
1512 public Module AddModule (string module)
1514 MethodInfo m = AddModule_Method;
1516 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1517 Environment.Exit (1);
1521 return (Module) m.Invoke (Builder, new object [] { module });
1522 } catch (TargetInvocationException ex) {
1523 throw ex.InnerException;
1528 public class ModuleClass : CommonAssemblyModulClass {
1529 // TODO: make it private and move all builder based methods here
1530 public ModuleBuilder Builder;
1531 bool m_module_is_unsafe;
1532 bool has_default_charset;
1534 public CharSet DefaultCharSet = CharSet.Ansi;
1535 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1537 static string[] attribute_targets = new string [] { "module" };
1539 public ModuleClass (bool is_unsafe)
1541 m_module_is_unsafe = is_unsafe;
1544 public override AttributeTargets AttributeTargets {
1546 return AttributeTargets.Module;
1550 public override bool IsClsComplianceRequired ()
1552 return CodeGen.Assembly.IsClsCompliant;
1555 public override void Emit (TypeContainer tc)
1559 if (!m_module_is_unsafe)
1562 if (TypeManager.unverifiable_code_ctor == null) {
1563 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1567 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1570 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1572 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1573 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1574 Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1576 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1577 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1578 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1583 Builder.SetCustomAttribute (customBuilder);
1586 public bool HasDefaultCharSet {
1588 return has_default_charset;
1593 /// It is called very early therefore can resolve only predefined attributes
1595 public void Resolve ()
1598 if (OptAttributes == null)
1601 if (!OptAttributes.CheckTargets())
1604 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1606 has_default_charset = true;
1607 DefaultCharSet = a.GetCharSetValue ();
1608 switch (DefaultCharSet) {
1613 DefaultCharSetType = TypeAttributes.AutoClass;
1615 case CharSet.Unicode:
1616 DefaultCharSetType = TypeAttributes.UnicodeClass;
1619 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1626 public override string[] ValidAttributeTargets {
1628 return attribute_targets;