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;
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 if (!SymbolWriter.Initialize (Module.Builder, filename)) {
93 -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.");
99 // Initializes the code generator variables
101 static public bool Init (string name, string output, bool want_debugging_support)
104 AssemblyName an = Assembly.GetAssemblyName (name, output);
108 if (an.KeyPair != null) {
109 // If we are going to strong name our assembly make
110 // sure all its refs are strong named
111 foreach (Assembly a in RootNamespace.Global.Assemblies) {
112 AssemblyName ref_name = a.GetName ();
113 byte [] b = ref_name.GetPublicKeyToken ();
114 if (b == null || b.Length == 0) {
115 Report.Error (1577, "Assembly generation failed " +
116 "-- Referenced assembly '" +
118 "' does not have a strong name.");
119 //Environment.Exit (1);
124 current_domain = AppDomain.CurrentDomain;
128 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
130 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
131 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
134 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135 AssemblyBuilderAccess.Save | 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);
155 // Get the complete AssemblyName from the builder
156 // (We need to get the public key and token)
157 Assembly.Name = Assembly.Builder.GetName ();
161 // Pass a path-less name to DefineDynamicModule. Wonder how
162 // this copes with output in different directories then.
163 // FIXME: figure out how this copes with --output /tmp/blah
165 // If the third argument is true, the ModuleBuilder will dynamically
166 // load the default symbol writer.
168 Module.Builder = Assembly.Builder.DefineDynamicModule (
169 Basename (name), Basename (output), false);
171 if (want_debugging_support)
172 InitializeSymbolWriter (output);
177 static public void Save (string name, bool saveDebugInfo)
180 Assembly.Builder.Save (Basename (name));
182 catch (COMException) {
183 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
186 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
187 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
188 RootContext.StrongNameKeyFile +
189 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
191 catch (System.IO.IOException io) {
192 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);
201 // Write debuger symbol file
204 SymbolWriter.WriteSymbolFile ();
210 /// An interface to hold all the information needed in the resolving phase.
212 public interface IResolveContext
214 DeclSpace DeclContainer { get; }
215 bool IsInObsoleteScope { get; }
216 bool IsInUnsafeScope { get; }
218 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
220 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
221 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
222 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
223 // handle generic method overrides differently
224 DeclSpace GenericDeclContainer { get; }
228 /// An Emit Context is created for each body of code (from methods,
229 /// properties bodies, indexer bodies or constructor bodies)
231 public class EmitContext : IResolveContext {
234 // Holds a varible used during collection or object initialization.
236 public Expression CurrentInitializerVariable;
238 DeclSpace decl_space;
240 public DeclSpace TypeContainer;
241 public ILGenerator ig;
244 public enum Flags : int {
246 /// This flag tracks the `checked' state of the compilation,
247 /// it controls whether we should generate code that does overflow
248 /// checking, or if we generate code that ignores overflows.
250 /// The default setting comes from the command line option to generate
251 /// checked or unchecked code plus any source code changes using the
252 /// checked/unchecked statements or expressions. Contrast this with
253 /// the ConstantCheckState flag.
258 /// The constant check state is always set to `true' and cant be changed
259 /// from the command line. The source code can change this setting with
260 /// the `checked' and `unchecked' statements and expressions.
262 ConstantCheckState = 1 << 1,
264 AllCheckStateFlags = CheckState | ConstantCheckState,
267 /// Whether we are inside an unsafe block
275 /// Whether control flow analysis is enabled
277 DoFlowAnalysis = 1 << 5,
280 /// Whether control flow analysis is disabled on structs
281 /// (only meaningful when DoFlowAnalysis is set)
283 OmitStructFlowAnalysis = 1 << 6,
286 /// Indicates the current context is in probing mode, no errors are reported.
288 ProbingMode = 1 << 7,
291 // Inside field intializer expression
293 InFieldInitializer = 1 << 8,
295 InferReturnType = 1 << 9,
297 InCompoundAssignment = 1 << 10,
299 OmitDebuggingInfo = 1 << 11
305 /// Whether we are emitting code inside a static or instance method
307 public bool IsStatic;
310 /// Whether the actual created method is static or instance method.
311 /// Althoug the method might be declared as `static', if an anonymous
312 /// method is involved, we might turn this into an instance method.
314 /// So this reflects the low-level staticness of the method, while
315 /// IsStatic represents the semantic, high-level staticness.
317 //public bool MethodIsStatic;
320 /// The value that is allowed to be returned or NULL if there is no
326 /// Points to the Type (extracted from the TypeContainer) that
327 /// declares this body of code
329 public readonly Type ContainerType;
332 /// Whether this is generating code for a constructor
334 public bool IsConstructor;
337 /// Keeps track of the Type to LocalBuilder temporary storage created
338 /// to store structures (used to compute the address of the structure
339 /// value on structure method invocations)
341 public Hashtable temporary_storage;
343 public Block CurrentBlock;
345 public int CurrentFile;
348 /// The location where we store the return value.
350 LocalBuilder return_value;
353 /// The location where return has to jump to return the
356 public Label ReturnLabel;
359 /// If we already defined the ReturnLabel
361 public bool HasReturnLabel;
364 /// Whether we are in a `fixed' initialization
366 public bool InFixedInitializer;
369 /// Whether we are inside an anonymous method.
371 public AnonymousExpression CurrentAnonymousMethod;
374 /// Location for this EmitContext
379 /// Inside an enum definition, we do not resolve enumeration values
380 /// to their enumerations, but rather to the underlying type/value
381 /// This is so EnumVal + EnumValB can be evaluated.
383 /// There is no "E operator + (E x, E y)", so during an enum evaluation
384 /// we relax the rules
386 public bool InEnumContext;
388 public readonly IResolveContext ResolveContext;
391 /// The current iterator
393 public Iterator CurrentIterator {
394 get { return CurrentAnonymousMethod as Iterator; }
398 /// Whether we are in the resolving stage or not
406 bool isAnonymousMethodAllowed = true;
409 FlowBranching current_flow_branching;
411 static int next_id = 0;
414 public override string ToString ()
416 return String.Format ("EmitContext ({0}:{1})", id,
417 CurrentAnonymousMethod, loc);
420 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
421 Type return_type, int code_flags, bool is_constructor)
423 this.ResolveContext = rc;
426 TypeContainer = parent;
427 this.decl_space = ds;
428 if (RootContext.Checked)
429 flags |= Flags.CheckState;
430 flags |= Flags.ConstantCheckState;
432 if (return_type == null)
433 throw new ArgumentNullException ("return_type");
435 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
436 throw new InternalErrorException ();
439 IsStatic = (code_flags & Modifiers.STATIC) != 0;
440 ReturnType = return_type;
441 IsConstructor = is_constructor;
444 current_phase = Phase.Created;
447 // Can only be null for the ResolveType contexts.
448 ContainerType = parent.TypeBuilder;
449 if (rc.IsInUnsafeScope)
450 flags |= Flags.InUnsafe;
455 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
456 Type return_type, int code_flags, bool is_constructor)
457 : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
461 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
462 Type return_type, int code_flags)
463 : this (rc, ds, ds, l, ig, return_type, code_flags, false)
467 // IResolveContext.DeclContainer
468 public DeclSpace DeclContainer {
469 get { return decl_space; }
470 set { decl_space = value; }
473 // IResolveContext.GenericDeclContainer
474 public DeclSpace GenericDeclContainer {
475 get { return DeclContainer; }
478 public bool CheckState {
479 get { return (flags & Flags.CheckState) != 0; }
482 public bool ConstantCheckState {
483 get { return (flags & Flags.ConstantCheckState) != 0; }
486 public bool InUnsafe {
487 get { return (flags & Flags.InUnsafe) != 0; }
490 public bool InCatch {
491 get { return (flags & Flags.InCatch) != 0; }
494 public bool InFinally {
495 get { return (flags & Flags.InFinally) != 0; }
498 public bool DoFlowAnalysis {
499 get { return (flags & Flags.DoFlowAnalysis) != 0; }
502 public bool OmitStructFlowAnalysis {
503 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
506 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
507 // it's public so that we can use a struct at the callsite
508 public struct FlagsHandle : IDisposable
511 readonly Flags invmask, oldval;
513 public FlagsHandle (EmitContext ec, Flags flagsToSet)
514 : this (ec, flagsToSet, flagsToSet)
518 internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
522 oldval = ec.flags & mask;
523 ec.flags = (ec.flags & invmask) | (val & mask);
525 if ((mask & Flags.ProbingMode) != 0)
526 Report.DisableReporting ();
529 public void Dispose ()
531 if ((invmask & Flags.ProbingMode) == 0)
532 Report.EnableReporting ();
534 ec.flags = (ec.flags & invmask) | oldval;
538 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
539 public FlagsHandle Set (Flags flagsToSet)
541 return new FlagsHandle (this, flagsToSet);
544 public FlagsHandle With (Flags bits, bool enable)
546 return new FlagsHandle (this, bits, enable ? bits : 0);
549 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
552 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
553 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
554 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
558 /// If this is true, then Return and ContextualReturn statements
559 /// will set the ReturnType value based on the expression types
560 /// of each return statement instead of the method return type
561 /// (which is initially null).
563 public bool InferReturnType {
564 get { return (flags & Flags.InferReturnType) != 0; }
567 // IResolveContext.IsInObsoleteScope
568 public bool IsInObsoleteScope {
570 // Disables obsolete checks when probing is on
571 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
575 public bool IsInProbingMode {
576 get { return (flags & Flags.ProbingMode) != 0; }
579 // IResolveContext.IsInUnsafeScope
580 public bool IsInUnsafeScope {
581 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
584 public bool IsAnonymousMethodAllowed {
585 get { return isAnonymousMethodAllowed; }
586 set { isAnonymousMethodAllowed = value; }
589 public bool IsInFieldInitializer {
590 get { return (flags & Flags.InFieldInitializer) != 0; }
593 public bool IsInCompoundAssignment {
594 get { return (flags & Flags.InCompoundAssignment) != 0; }
597 public bool IsVariableCapturingRequired {
599 return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
603 public FlowBranching CurrentBranching {
604 get { return current_flow_branching; }
607 public bool OmitDebuggingInfo {
608 get { return (flags & Flags.OmitDebuggingInfo) != 0; }
611 flags |= Flags.OmitDebuggingInfo;
613 flags &= ~Flags.OmitDebuggingInfo;
618 // Starts a new code branching. This inherits the state of all local
619 // variables and parameters from the current branching.
621 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
623 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
624 return current_flow_branching;
628 // Starts a new code branching for block `block'.
630 public FlowBranching StartFlowBranching (Block block)
632 flags |= Flags.DoFlowAnalysis;
634 current_flow_branching = FlowBranching.CreateBranching (
635 CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
636 return current_flow_branching;
639 public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
641 FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
642 current_flow_branching = branching;
646 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
648 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
649 current_flow_branching = branching;
653 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
655 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
656 current_flow_branching = branching;
660 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
662 FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
663 current_flow_branching = branching;
667 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
669 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
670 current_flow_branching = branching;
675 // Ends a code branching. Merges the state of locals and parameters
676 // from all the children of the ending branching.
678 public bool EndFlowBranching ()
680 FlowBranching old = current_flow_branching;
681 current_flow_branching = current_flow_branching.Parent;
683 FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
684 return vector.IsUnreachable;
688 // Kills the current code branching. This throws away any changed state
689 // information and should only be used in case of an error.
691 // FIXME: this is evil
692 public void KillFlowBranching ()
694 current_flow_branching = current_flow_branching.Parent;
697 public bool MustCaptureVariable (LocalInfo local)
699 if (CurrentAnonymousMethod == null)
702 // FIXME: IsIterator is too aggressive, we should capture only if child
703 // block contains yield
704 if (CurrentAnonymousMethod.IsIterator)
707 return local.Block.Toplevel != CurrentBlock.Toplevel;
710 public void EmitMeta (ToplevelBlock b)
715 ReturnLabel = ig.DefineLabel ();
719 // Here until we can fix the problem with Mono.CSharp.Switch, which
720 // currently can not cope with ig == null during resolve (which must
721 // be fixed for switch statements to work on anonymous methods).
723 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
730 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
731 if (Report.Errors > 0)
736 current_phase = Phase.Emitting;
740 EmitResolvedTopBlock (block, unreachable);
742 } catch (Exception e){
743 Console.WriteLine ("Exception caught by the compiler while emitting:");
744 Console.WriteLine (" Block that caused the problem begin at: " + block.loc);
746 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
755 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
756 Parameters ip, IMethodData md, out bool unreachable)
758 current_phase = Phase.Resolving;
766 CurrentFile = loc.File;
771 if (!block.ResolveMeta (this, ip))
774 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
775 FlowBranchingToplevel top_level;
776 if (anonymous_method_host != null)
777 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
779 top_level = block.TopLevelBranching;
781 current_flow_branching = top_level;
782 bool ok = block.Resolve (this);
783 current_flow_branching = null;
788 bool flow_unreachable = top_level.End ();
789 if (flow_unreachable)
793 } catch (Exception e) {
794 Console.WriteLine ("Exception caught by the compiler while compiling:");
795 Console.WriteLine (" Block that caused the problem begin at: " + loc);
797 if (CurrentBlock != null){
798 Console.WriteLine (" Block being compiled: [{0},{1}]",
799 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
801 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
806 if (return_type != TypeManager.void_type && !unreachable) {
807 if (CurrentAnonymousMethod == null) {
808 Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
810 } else if (!CurrentAnonymousMethod.IsIterator) {
811 Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
812 CurrentAnonymousMethod.GetSignatureForError ());
821 public Type ReturnType {
830 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
836 ig.MarkLabel (ReturnLabel);
838 if (return_value != null){
839 ig.Emit (OpCodes.Ldloc, return_value);
840 ig.Emit (OpCodes.Ret);
843 // If `HasReturnLabel' is set, then we already emitted a
844 // jump to the end of the method, so we must emit a `ret'
847 // Unfortunately, System.Reflection.Emit automatically emits
848 // a leave to the end of a finally block. This is a problem
849 // if no code is following the try/finally block since we may
850 // jump to a point after the end of the method.
851 // As a workaround, we're always creating a return label in
855 if ((block != null) && block.IsDestructor) {
856 // Nothing to do; S.R.E automatically emits a leave.
857 } else if (HasReturnLabel || !unreachable) {
858 if (return_type != TypeManager.void_type)
859 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
860 ig.Emit (OpCodes.Ret);
866 /// This is called immediately before emitting an IL opcode to tell the symbol
867 /// writer to which source line this opcode belongs.
869 public void Mark (Location loc)
871 if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
874 SymbolWriter.MarkSequencePoint (ig, loc);
877 public void DefineLocalVariable (string name, LocalBuilder builder)
879 SymbolWriter.DefineLocalVariable (name, builder);
882 public void BeginScope ()
885 SymbolWriter.OpenScope(ig);
888 public void EndScope ()
891 SymbolWriter.CloseScope(ig);
895 /// Returns a temporary storage for a variable of type t as
896 /// a local variable in the current body.
898 public LocalBuilder GetTemporaryLocal (Type t)
900 if (temporary_storage != null) {
901 object o = temporary_storage [t];
905 o = s.Count == 0 ? null : s.Pop ();
907 temporary_storage.Remove (t);
911 return (LocalBuilder) o;
913 return ig.DeclareLocal (t);
916 public void FreeTemporaryLocal (LocalBuilder b, Type t)
918 if (temporary_storage == null) {
919 temporary_storage = new Hashtable ();
920 temporary_storage [t] = b;
923 object o = temporary_storage [t];
925 temporary_storage [t] = b;
928 Stack s = o as Stack;
932 temporary_storage [t] = s;
938 /// Current loop begin and end labels.
940 public Label LoopBegin, LoopEnd;
943 /// Default target in a switch statement. Only valid if
946 public Label DefaultTarget;
949 /// If this is non-null, points to the current switch statement
951 public Switch Switch;
954 /// ReturnValue creates on demand the LocalBuilder for the
955 /// return value from the function. By default this is not
956 /// used. This is only required when returns are found inside
957 /// Try or Catch statements.
959 /// This method is typically invoked from the Emit phase, so
960 /// we allow the creation of a return label if it was not
961 /// requested during the resolution phase. Could be cleaned
962 /// up, but it would replicate a lot of logic in the Emit phase
963 /// of the code that uses it.
965 public LocalBuilder TemporaryReturn ()
967 if (return_value == null){
968 return_value = ig.DeclareLocal (return_type);
969 if (!HasReturnLabel){
970 ReturnLabel = ig.DefineLabel ();
971 HasReturnLabel = true;
979 /// This method is used during the Resolution phase to flag the
980 /// need to define the ReturnLabel
982 public void NeedReturnLabel ()
984 if (current_phase != Phase.Resolving){
986 // The reason is that the `ReturnLabel' is declared between
987 // resolution and emission
989 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
993 HasReturnLabel = true;
997 public Expression GetThis (Location loc)
1000 if (CurrentBlock != null)
1001 my_this = new This (CurrentBlock, loc);
1003 my_this = new This (loc);
1005 if (!my_this.ResolveBase (this))
1013 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1015 protected CommonAssemblyModulClass ():
1020 public void AddAttributes (ArrayList attrs)
1022 foreach (Attribute a in attrs)
1025 if (attributes == null) {
1026 attributes = new Attributes (attrs);
1029 attributes.AddAttributes (attrs);
1032 public virtual void Emit (TypeContainer tc)
1034 if (OptAttributes == null)
1037 OptAttributes.Emit ();
1040 protected Attribute ResolveAttribute (Type a_type)
1042 Attribute a = OptAttributes.Search (a_type);
1049 public override IResolveContext ResolveContext {
1050 get { return this; }
1053 #region IResolveContext Members
1055 public DeclSpace DeclContainer {
1056 get { return RootContext.ToplevelTypes; }
1059 public DeclSpace GenericDeclContainer {
1060 get { return DeclContainer; }
1063 public bool IsInObsoleteScope {
1064 get { return false; }
1067 public bool IsInUnsafeScope {
1068 get { return false; }
1074 public class AssemblyClass : CommonAssemblyModulClass {
1075 // TODO: make it private and move all builder based methods here
1076 public AssemblyBuilder Builder;
1077 bool is_cls_compliant;
1078 bool wrap_non_exception_throws;
1079 Type runtime_compatibility_attr_type;
1081 public Attribute ClsCompliantAttribute;
1083 ListDictionary declarative_security;
1085 bool has_extension_method;
1086 public AssemblyName Name;
1087 MethodInfo add_type_forwarder;
1088 ListDictionary emitted_forwarders;
1091 // Module is here just because of error messages
1092 static string[] attribute_targets = new string [] { "assembly", "module" };
1094 public AssemblyClass (): base ()
1097 wrap_non_exception_throws = true;
1101 public bool HasExtensionMethods {
1104 has_extension_method = value;
1109 public bool IsClsCompliant {
1111 return is_cls_compliant;
1115 public bool WrapNonExceptionThrows {
1117 return wrap_non_exception_throws;
1121 public override AttributeTargets AttributeTargets {
1123 return AttributeTargets.Assembly;
1127 public override bool IsClsComplianceRequired ()
1129 return is_cls_compliant;
1132 public void Resolve ()
1134 runtime_compatibility_attr_type = TypeManager.CoreLookupType (
1135 "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", Kind.Class, false);
1137 if (OptAttributes == null)
1140 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1141 if (!OptAttributes.CheckTargets())
1144 if (TypeManager.cls_compliant_attribute_type != null)
1145 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1147 if (ClsCompliantAttribute != null) {
1148 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1151 if (runtime_compatibility_attr_type != null) {
1152 Attribute a = ResolveAttribute (runtime_compatibility_attr_type);
1154 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1156 wrap_non_exception_throws = (bool) val;
1162 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1165 // check for possible ECMA key
1166 if (strongNameBlob.Length == 16) {
1167 // will be rejected if not "the" ECMA key
1168 an.SetPublicKey (strongNameBlob);
1171 // take it, with or without, a private key
1172 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1173 // and make sure we only feed the public part to Sys.Ref
1174 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1176 // AssemblyName.SetPublicKey requires an additional header
1177 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1179 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1180 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1181 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1182 an.SetPublicKey (encodedPublicKey);
1186 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1187 Environment.Exit (1);
1191 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1192 public AssemblyName GetAssemblyName (string name, string output)
1194 if (OptAttributes != null) {
1195 foreach (Attribute a in OptAttributes.Attrs) {
1196 // cannot rely on any resolve-based members before you call Resolve
1197 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1200 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1201 // However, this is invoked by CodeGen.Init, when none of the namespaces
1203 // TODO: Does not handle quoted attributes properly
1205 case "AssemblyKeyFile":
1206 case "AssemblyKeyFileAttribute":
1207 case "System.Reflection.AssemblyKeyFileAttribute":
1208 if (RootContext.StrongNameKeyFile != null) {
1209 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1210 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1211 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1214 string value = a.GetString ();
1215 if (value.Length != 0)
1216 RootContext.StrongNameKeyFile = value;
1219 case "AssemblyKeyName":
1220 case "AssemblyKeyNameAttribute":
1221 case "System.Reflection.AssemblyKeyNameAttribute":
1222 if (RootContext.StrongNameKeyContainer != null) {
1223 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1224 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1225 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1228 string value = a.GetString ();
1229 if (value.Length != 0)
1230 RootContext.StrongNameKeyContainer = value;
1233 case "AssemblyDelaySign":
1234 case "AssemblyDelaySignAttribute":
1235 case "System.Reflection.AssemblyDelaySignAttribute":
1236 RootContext.StrongNameDelaySign = a.GetBoolean ();
1242 AssemblyName an = new AssemblyName ();
1243 an.Name = Path.GetFileNameWithoutExtension (name);
1245 // note: delay doesn't apply when using a key container
1246 if (RootContext.StrongNameKeyContainer != null) {
1247 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1251 // strongname is optional
1252 if (RootContext.StrongNameKeyFile == null)
1255 string AssemblyDir = Path.GetDirectoryName (output);
1257 // the StrongName key file may be relative to (a) the compiled
1258 // file or (b) to the output assembly. See bugzilla #55320
1259 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1261 // (a) relative to the compiled file
1262 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1263 bool exist = File.Exists (filename);
1264 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1265 // (b) relative to the outputed assembly
1266 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1267 exist = File.Exists (filename);
1271 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1272 byte[] snkeypair = new byte [fs.Length];
1273 fs.Read (snkeypair, 0, snkeypair.Length);
1275 if (RootContext.StrongNameDelaySign) {
1276 // delayed signing - DO NOT include private key
1277 SetPublicKey (an, snkeypair);
1280 // no delay so we make sure we have the private key
1282 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1283 an.KeyPair = new StrongNameKeyPair (snkeypair);
1285 catch (CryptographicException) {
1286 if (snkeypair.Length == 16) {
1287 // error # is different for ECMA key
1288 Report.Error (1606, "Could not sign the assembly. " +
1289 "ECMA key can only be used to delay-sign assemblies");
1292 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1300 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1306 void Error_AssemblySigning (string text)
1308 Report.Error (1548, "Error during assembly signing. " + text);
1312 bool CheckInternalsVisibleAttribute (Attribute a)
1314 string assembly_name = a.GetString ();
1315 if (assembly_name.Length == 0)
1318 AssemblyName aname = null;
1320 aname = new AssemblyName (assembly_name);
1321 } catch (FileLoadException) {
1322 } catch (ArgumentException) {
1325 // Bad assembly name format
1327 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1328 // Report error if we have defined Version or Culture
1329 else if (aname.Version != null || aname.CultureInfo != null)
1330 throw new Exception ("Friend assembly `" + a.GetString () +
1331 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1332 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1333 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1334 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1342 static bool IsValidAssemblyVersion (string version)
1346 v = new Version (version);
1349 int major = int.Parse (version, CultureInfo.InvariantCulture);
1350 v = new Version (major, 0);
1356 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1357 if (candidate > ushort.MaxValue)
1364 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1366 if (a.IsValidSecurityAttribute ()) {
1367 if (declarative_security == null)
1368 declarative_security = new ListDictionary ();
1370 a.ExtractSecurityPermissionSet (declarative_security);
1374 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1375 string value = a.GetString ();
1376 if (value == null || value.Length == 0)
1379 if (RootContext.Target == Target.Exe) {
1380 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1385 if (a.Type == TypeManager.assembly_version_attribute_type) {
1386 string value = a.GetString ();
1387 if (value == null || value.Length == 0)
1390 value = value.Replace ('*', '0');
1392 if (!IsValidAssemblyVersion (value)) {
1393 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1399 if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1402 if (a.Type == TypeManager.type_forwarder_attr_type) {
1403 Type t = a.GetArgumentType ();
1404 if (t == null || TypeManager.HasElementType (t)) {
1405 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1409 if (emitted_forwarders == null) {
1410 emitted_forwarders = new ListDictionary();
1411 } else if (emitted_forwarders.Contains(t)) {
1412 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1413 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1414 TypeManager.CSharpName(t));
1418 emitted_forwarders.Add(t, a);
1420 if (TypeManager.LookupDeclSpace (t) != null) {
1421 Report.SymbolRelatedToPreviousError (t);
1422 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1423 TypeManager.CSharpName (t));
1428 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1429 TypeManager.CSharpName (t));
1433 if (t.IsGenericType) {
1434 Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1438 if (add_type_forwarder == null) {
1439 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1440 BindingFlags.NonPublic | BindingFlags.Instance);
1442 if (add_type_forwarder == null) {
1443 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1448 add_type_forwarder.Invoke (Builder, new object[] { t });
1452 if (a.Type == TypeManager.extension_attribute_type) {
1453 a.Error_MisusedExtensionAttribute ();
1457 Builder.SetCustomAttribute (customBuilder);
1460 public override void Emit (TypeContainer tc)
1465 if (has_extension_method)
1466 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1469 if (runtime_compatibility_attr_type != null) {
1470 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1471 if (OptAttributes == null || !OptAttributes.Contains (runtime_compatibility_attr_type)) {
1472 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
1473 runtime_compatibility_attr_type, Location.Null, Type.EmptyTypes);
1474 PropertyInfo [] pis = new PropertyInfo [1];
1475 pis [0] = TypeManager.GetPredefinedProperty (runtime_compatibility_attr_type,
1476 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
1477 object [] pargs = new object [1];
1479 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1483 if (declarative_security != null) {
1485 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1486 object builder_instance = Builder;
1489 // Microsoft runtime hacking
1490 if (add_permission == null) {
1491 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1492 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1494 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1495 builder_instance = fi.GetValue (Builder);
1498 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1499 declarative_security [SecurityAction.RequestOptional],
1500 declarative_security [SecurityAction.RequestRefuse] };
1501 add_permission.Invoke (builder_instance, args);
1504 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1509 public override string[] ValidAttributeTargets {
1511 return attribute_targets;
1515 // Wrapper for AssemblyBuilder.AddModule
1516 static MethodInfo adder_method;
1517 static public MethodInfo AddModule_Method {
1519 if (adder_method == null)
1520 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1521 return adder_method;
1524 public Module AddModule (string module)
1526 MethodInfo m = AddModule_Method;
1528 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1529 Environment.Exit (1);
1533 return (Module) m.Invoke (Builder, new object [] { module });
1534 } catch (TargetInvocationException ex) {
1535 throw ex.InnerException;
1540 public class ModuleClass : CommonAssemblyModulClass {
1541 // TODO: make it private and move all builder based methods here
1542 public ModuleBuilder Builder;
1543 bool m_module_is_unsafe;
1544 bool has_default_charset;
1546 public CharSet DefaultCharSet = CharSet.Ansi;
1547 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1549 static string[] attribute_targets = new string [] { "module" };
1551 public ModuleClass (bool is_unsafe)
1553 m_module_is_unsafe = is_unsafe;
1556 public override AttributeTargets AttributeTargets {
1558 return AttributeTargets.Module;
1562 public override bool IsClsComplianceRequired ()
1564 return CodeGen.Assembly.IsClsCompliant;
1567 public override void Emit (TypeContainer tc)
1571 if (m_module_is_unsafe) {
1572 Type t = TypeManager.CoreLookupType ("System.Security", "UnverifiableCodeAttribute", Kind.Class, true);
1574 ConstructorInfo unverifiable_code_ctor = TypeManager.GetPredefinedConstructor (t, Location.Null, Type.EmptyTypes);
1575 if (unverifiable_code_ctor != null)
1576 Builder.SetCustomAttribute (new CustomAttributeBuilder (unverifiable_code_ctor, new object [0]));
1581 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1583 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1584 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1585 Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1587 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1588 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1589 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1594 Builder.SetCustomAttribute (customBuilder);
1597 public bool HasDefaultCharSet {
1599 return has_default_charset;
1604 /// It is called very early therefore can resolve only predefined attributes
1606 public void Resolve ()
1609 if (OptAttributes == null)
1612 if (!OptAttributes.CheckTargets())
1615 if (TypeManager.default_charset_type == null)
1618 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1620 has_default_charset = true;
1621 DefaultCharSet = a.GetCharSetValue ();
1622 switch (DefaultCharSet) {
1627 DefaultCharSetType = TypeAttributes.AutoClass;
1629 case CharSet.Unicode:
1630 DefaultCharSetType = TypeAttributes.UnicodeClass;
1633 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1640 public override string[] ValidAttributeTargets {
1642 return attribute_targets;