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 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
89 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
90 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
94 // Initializes the code generator variables for interactive use (repl)
96 static public void InitDynamic (string name)
98 current_domain = AppDomain.CurrentDomain;
99 AssemblyName an = Assembly.GetAssemblyName (name, name);
101 Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
102 Module.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
106 // Initializes the code generator variables
108 static public bool Init (string name, string output, bool want_debugging_support)
111 AssemblyName an = Assembly.GetAssemblyName (name, output);
115 if (an.KeyPair != null) {
116 // If we are going to strong name our assembly make
117 // sure all its refs are strong named
118 foreach (Assembly a in RootNamespace.Global.Assemblies) {
119 AssemblyName ref_name = a.GetName ();
120 byte [] b = ref_name.GetPublicKeyToken ();
121 if (b == null || b.Length == 0) {
122 Report.Error (1577, "Assembly generation failed " +
123 "-- Referenced assembly '" +
125 "' does not have a strong name.");
126 //Environment.Exit (1);
131 current_domain = AppDomain.CurrentDomain;
134 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135 AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
137 catch (ArgumentException) {
138 // specified key may not be exportable outside it's container
139 if (RootContext.StrongNameKeyContainer != null) {
140 Report.Error (1548, "Could not access the key inside the container `" +
141 RootContext.StrongNameKeyContainer + "'.");
142 Environment.Exit (1);
146 catch (CryptographicException) {
147 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149 Environment.Exit (1);
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.
169 Module.Builder = Assembly.Builder.DefineDynamicModule (
170 Basename (name), Basename (output), want_debugging_support);
173 // TODO: We should use SymbolWriter from DefineDynamicModule
174 if (want_debugging_support && !SymbolWriter.Initialize (Module.Builder, output)) {
175 Report.Error (40, "Unexpected debug information initialization error `{0}'",
176 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
180 } catch (ExecutionEngineException e) {
181 Report.Error (40, "Unexpected debug information initialization error `{0}'",
189 static public void Save (string name, bool saveDebugInfo)
192 Assembly.Builder.Save (Basename (name));
194 catch (COMException) {
195 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
198 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
199 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
200 RootContext.StrongNameKeyFile +
201 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
203 catch (System.IO.IOException io) {
204 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
207 catch (System.UnauthorizedAccessException ua) {
208 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
213 // Write debuger symbol file
216 SymbolWriter.WriteSymbolFile ();
222 /// An interface to hold all the information needed in the resolving phase.
224 public interface IResolveContext
226 DeclSpace DeclContainer { get; }
227 bool IsInObsoleteScope { get; }
228 bool IsInUnsafeScope { get; }
230 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
232 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
233 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
234 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
235 // handle generic method overrides differently
236 DeclSpace GenericDeclContainer { get; }
240 /// An Emit Context is created for each body of code (from methods,
241 /// properties bodies, indexer bodies or constructor bodies)
243 public class EmitContext : IResolveContext {
246 // Holds a varible used during collection or object initialization.
248 public Expression CurrentInitializerVariable;
250 DeclSpace decl_space;
252 public DeclSpace TypeContainer;
253 public ILGenerator ig;
256 public enum Flags : int {
258 /// This flag tracks the `checked' state of the compilation,
259 /// it controls whether we should generate code that does overflow
260 /// checking, or if we generate code that ignores overflows.
262 /// The default setting comes from the command line option to generate
263 /// checked or unchecked code plus any source code changes using the
264 /// checked/unchecked statements or expressions. Contrast this with
265 /// the ConstantCheckState flag.
270 /// The constant check state is always set to `true' and cant be changed
271 /// from the command line. The source code can change this setting with
272 /// the `checked' and `unchecked' statements and expressions.
274 ConstantCheckState = 1 << 1,
276 AllCheckStateFlags = CheckState | ConstantCheckState,
279 /// Whether we are inside an unsafe block
287 /// Whether control flow analysis is enabled
289 DoFlowAnalysis = 1 << 5,
292 /// Whether control flow analysis is disabled on structs
293 /// (only meaningful when DoFlowAnalysis is set)
295 OmitStructFlowAnalysis = 1 << 6,
298 /// Indicates the current context is in probing mode, no errors are reported.
300 ProbingMode = 1 << 7,
303 // Inside field intializer expression
305 InFieldInitializer = 1 << 8,
307 InferReturnType = 1 << 9,
309 InCompoundAssignment = 1 << 10,
311 OmitDebuggingInfo = 1 << 11
317 /// Whether we are emitting code inside a static or instance method
319 public bool IsStatic;
322 /// Whether the actual created method is static or instance method.
323 /// Althoug the method might be declared as `static', if an anonymous
324 /// method is involved, we might turn this into an instance method.
326 /// So this reflects the low-level staticness of the method, while
327 /// IsStatic represents the semantic, high-level staticness.
329 //public bool MethodIsStatic;
332 /// The value that is allowed to be returned or NULL if there is no
338 /// Points to the Type (extracted from the TypeContainer) that
339 /// declares this body of code
341 public readonly Type ContainerType;
344 /// Whether this is generating code for a constructor
346 public bool IsConstructor;
349 /// Keeps track of the Type to LocalBuilder temporary storage created
350 /// to store structures (used to compute the address of the structure
351 /// value on structure method invocations)
353 public Hashtable temporary_storage;
355 public Block CurrentBlock;
357 public int CurrentFile;
360 /// The location where we store the return value.
362 LocalBuilder return_value;
365 /// The location where return has to jump to return the
368 public Label ReturnLabel;
371 /// If we already defined the ReturnLabel
373 public bool HasReturnLabel;
376 /// Whether we are in a `fixed' initialization
378 public bool InFixedInitializer;
381 /// Whether we are inside an anonymous method.
383 public AnonymousExpression CurrentAnonymousMethod;
386 /// Location for this EmitContext
391 /// Inside an enum definition, we do not resolve enumeration values
392 /// to their enumerations, but rather to the underlying type/value
393 /// This is so EnumVal + EnumValB can be evaluated.
395 /// There is no "E operator + (E x, E y)", so during an enum evaluation
396 /// we relax the rules
398 public bool InEnumContext;
400 public readonly IResolveContext ResolveContext;
403 /// The current iterator
405 public Iterator CurrentIterator {
406 get { return CurrentAnonymousMethod as Iterator; }
410 /// Whether we are in the resolving stage or not
418 bool isAnonymousMethodAllowed = true;
421 FlowBranching current_flow_branching;
423 static int next_id = 0;
426 public override string ToString ()
428 return String.Format ("EmitContext ({0}:{1})", id,
429 CurrentAnonymousMethod, loc);
432 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
433 Type return_type, int code_flags, bool is_constructor)
435 this.ResolveContext = rc;
438 TypeContainer = parent;
439 this.decl_space = ds;
440 if (RootContext.Checked)
441 flags |= Flags.CheckState;
442 flags |= Flags.ConstantCheckState;
444 if (return_type == null)
445 throw new ArgumentNullException ("return_type");
447 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
448 throw new InternalErrorException ();
451 IsStatic = (code_flags & Modifiers.STATIC) != 0;
452 ReturnType = return_type;
453 IsConstructor = is_constructor;
456 current_phase = Phase.Created;
459 // Can only be null for the ResolveType contexts.
460 ContainerType = parent.TypeBuilder;
461 if (rc.IsInUnsafeScope)
462 flags |= Flags.InUnsafe;
467 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
468 Type return_type, int code_flags, bool is_constructor)
469 : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
473 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
474 Type return_type, int code_flags)
475 : this (rc, ds, ds, l, ig, return_type, code_flags, false)
479 // IResolveContext.DeclContainer
480 public DeclSpace DeclContainer {
481 get { return decl_space; }
482 set { decl_space = value; }
485 // IResolveContext.GenericDeclContainer
486 public DeclSpace GenericDeclContainer {
487 get { return DeclContainer; }
490 public bool CheckState {
491 get { return (flags & Flags.CheckState) != 0; }
494 public bool ConstantCheckState {
495 get { return (flags & Flags.ConstantCheckState) != 0; }
498 public bool InUnsafe {
499 get { return (flags & Flags.InUnsafe) != 0; }
502 public bool InCatch {
503 get { return (flags & Flags.InCatch) != 0; }
506 public bool InFinally {
507 get { return (flags & Flags.InFinally) != 0; }
510 public bool DoFlowAnalysis {
511 get { return (flags & Flags.DoFlowAnalysis) != 0; }
514 public bool OmitStructFlowAnalysis {
515 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
518 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
519 // it's public so that we can use a struct at the callsite
520 public struct FlagsHandle : IDisposable
523 readonly Flags invmask, oldval;
525 public FlagsHandle (EmitContext ec, Flags flagsToSet)
526 : this (ec, flagsToSet, flagsToSet)
530 internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
534 oldval = ec.flags & mask;
535 ec.flags = (ec.flags & invmask) | (val & mask);
537 if ((mask & Flags.ProbingMode) != 0)
538 Report.DisableReporting ();
541 public void Dispose ()
543 if ((invmask & Flags.ProbingMode) == 0)
544 Report.EnableReporting ();
546 ec.flags = (ec.flags & invmask) | oldval;
550 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
551 public FlagsHandle Set (Flags flagsToSet)
553 return new FlagsHandle (this, flagsToSet);
556 public FlagsHandle With (Flags bits, bool enable)
558 return new FlagsHandle (this, bits, enable ? bits : 0);
561 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
564 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
565 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
566 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
570 /// If this is true, then Return and ContextualReturn statements
571 /// will set the ReturnType value based on the expression types
572 /// of each return statement instead of the method return type
573 /// (which is initially null).
575 public bool InferReturnType {
576 get { return (flags & Flags.InferReturnType) != 0; }
579 // IResolveContext.IsInObsoleteScope
580 public bool IsInObsoleteScope {
582 // Disables obsolete checks when probing is on
583 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
587 public bool IsInProbingMode {
588 get { return (flags & Flags.ProbingMode) != 0; }
591 // IResolveContext.IsInUnsafeScope
592 public bool IsInUnsafeScope {
593 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
596 public bool IsAnonymousMethodAllowed {
597 get { return isAnonymousMethodAllowed; }
598 set { isAnonymousMethodAllowed = value; }
601 public bool IsInFieldInitializer {
602 get { return (flags & Flags.InFieldInitializer) != 0; }
605 public bool IsInCompoundAssignment {
606 get { return (flags & Flags.InCompoundAssignment) != 0; }
609 public bool IsVariableCapturingRequired {
611 return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
615 public FlowBranching CurrentBranching {
616 get { return current_flow_branching; }
619 public bool OmitDebuggingInfo {
620 get { return (flags & Flags.OmitDebuggingInfo) != 0; }
623 flags |= Flags.OmitDebuggingInfo;
625 flags &= ~Flags.OmitDebuggingInfo;
630 // Starts a new code branching. This inherits the state of all local
631 // variables and parameters from the current branching.
633 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
635 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
636 return current_flow_branching;
640 // Starts a new code branching for block `block'.
642 public FlowBranching StartFlowBranching (Block block)
644 flags |= Flags.DoFlowAnalysis;
646 current_flow_branching = FlowBranching.CreateBranching (
647 CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
648 return current_flow_branching;
651 public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
653 FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
654 current_flow_branching = branching;
658 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
660 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
661 current_flow_branching = branching;
665 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
667 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
668 current_flow_branching = branching;
672 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
674 FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
675 current_flow_branching = branching;
679 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
681 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
682 current_flow_branching = branching;
687 // Ends a code branching. Merges the state of locals and parameters
688 // from all the children of the ending branching.
690 public bool EndFlowBranching ()
692 FlowBranching old = current_flow_branching;
693 current_flow_branching = current_flow_branching.Parent;
695 FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
696 return vector.IsUnreachable;
700 // Kills the current code branching. This throws away any changed state
701 // information and should only be used in case of an error.
703 // FIXME: this is evil
704 public void KillFlowBranching ()
706 current_flow_branching = current_flow_branching.Parent;
709 public bool MustCaptureVariable (LocalInfo local)
711 if (CurrentAnonymousMethod == null)
714 // FIXME: IsIterator is too aggressive, we should capture only if child
715 // block contains yield
716 if (CurrentAnonymousMethod.IsIterator)
719 return local.Block.Toplevel != CurrentBlock.Toplevel;
722 public void EmitMeta (ToplevelBlock b)
727 ReturnLabel = ig.DefineLabel ();
731 // Here until we can fix the problem with Mono.CSharp.Switch, which
732 // currently can not cope with ig == null during resolve (which must
733 // be fixed for switch statements to work on anonymous methods).
735 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
742 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
743 if (Report.Errors > 0)
748 current_phase = Phase.Emitting;
752 EmitResolvedTopBlock (block, unreachable);
754 } catch (Exception e){
755 Console.WriteLine ("Exception caught by the compiler while emitting:");
756 Console.WriteLine (" Block that caused the problem begin at: " + block.loc);
758 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
768 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
769 Parameters ip, IMethodData md, out bool unreachable)
772 unreachable = this.unreachable;
776 current_phase = Phase.Resolving;
780 CurrentFile = loc.File;
785 if (!block.ResolveMeta (this, ip))
788 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
789 FlowBranchingToplevel top_level;
790 if (anonymous_method_host != null)
791 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
793 top_level = block.TopLevelBranching;
795 current_flow_branching = top_level;
796 bool ok = block.Resolve (this);
797 current_flow_branching = null;
802 bool flow_unreachable = top_level.End ();
803 if (flow_unreachable)
804 this.unreachable = unreachable = true;
807 } catch (Exception e) {
808 Console.WriteLine ("Exception caught by the compiler while compiling:");
809 Console.WriteLine (" Block that caused the problem begin at: " + loc);
811 if (CurrentBlock != null){
812 Console.WriteLine (" Block being compiled: [{0},{1}]",
813 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
815 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
820 if (return_type != TypeManager.void_type && !unreachable) {
821 if (CurrentAnonymousMethod == null) {
822 Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
824 } else if (!CurrentAnonymousMethod.IsIterator) {
825 Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
826 CurrentAnonymousMethod.GetSignatureForError ());
835 public Type ReturnType {
844 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
850 ig.MarkLabel (ReturnLabel);
852 if (return_value != null){
853 ig.Emit (OpCodes.Ldloc, return_value);
854 ig.Emit (OpCodes.Ret);
857 // If `HasReturnLabel' is set, then we already emitted a
858 // jump to the end of the method, so we must emit a `ret'
861 // Unfortunately, System.Reflection.Emit automatically emits
862 // a leave to the end of a finally block. This is a problem
863 // if no code is following the try/finally block since we may
864 // jump to a point after the end of the method.
865 // As a workaround, we're always creating a return label in
869 if ((block != null) && block.IsDestructor) {
870 // Nothing to do; S.R.E automatically emits a leave.
871 } else if (HasReturnLabel || !unreachable) {
872 if (return_type != TypeManager.void_type)
873 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
874 ig.Emit (OpCodes.Ret);
880 /// This is called immediately before emitting an IL opcode to tell the symbol
881 /// writer to which source line this opcode belongs.
883 public void Mark (Location loc)
885 if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
888 SymbolWriter.MarkSequencePoint (ig, loc);
891 public void DefineLocalVariable (string name, LocalBuilder builder)
893 SymbolWriter.DefineLocalVariable (name, builder);
896 public void BeginScope ()
899 SymbolWriter.OpenScope(ig);
902 public void EndScope ()
905 SymbolWriter.CloseScope(ig);
909 /// Returns a temporary storage for a variable of type t as
910 /// a local variable in the current body.
912 public LocalBuilder GetTemporaryLocal (Type t)
914 if (temporary_storage != null) {
915 object o = temporary_storage [t];
919 o = s.Count == 0 ? null : s.Pop ();
921 temporary_storage.Remove (t);
925 return (LocalBuilder) o;
927 return ig.DeclareLocal (t);
930 public void FreeTemporaryLocal (LocalBuilder b, Type t)
932 if (temporary_storage == null) {
933 temporary_storage = new Hashtable ();
934 temporary_storage [t] = b;
937 object o = temporary_storage [t];
939 temporary_storage [t] = b;
942 Stack s = o as Stack;
946 temporary_storage [t] = s;
952 /// Current loop begin and end labels.
954 public Label LoopBegin, LoopEnd;
957 /// Default target in a switch statement. Only valid if
960 public Label DefaultTarget;
963 /// If this is non-null, points to the current switch statement
965 public Switch Switch;
968 /// ReturnValue creates on demand the LocalBuilder for the
969 /// return value from the function. By default this is not
970 /// used. This is only required when returns are found inside
971 /// Try or Catch statements.
973 /// This method is typically invoked from the Emit phase, so
974 /// we allow the creation of a return label if it was not
975 /// requested during the resolution phase. Could be cleaned
976 /// up, but it would replicate a lot of logic in the Emit phase
977 /// of the code that uses it.
979 public LocalBuilder TemporaryReturn ()
981 if (return_value == null){
982 return_value = ig.DeclareLocal (return_type);
983 if (!HasReturnLabel){
984 ReturnLabel = ig.DefineLabel ();
985 HasReturnLabel = true;
993 /// This method is used during the Resolution phase to flag the
994 /// need to define the ReturnLabel
996 public void NeedReturnLabel ()
998 if (current_phase != Phase.Resolving){
1000 // The reason is that the `ReturnLabel' is declared between
1001 // resolution and emission
1003 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
1006 if (!HasReturnLabel)
1007 HasReturnLabel = true;
1011 public Expression GetThis (Location loc)
1014 if (CurrentBlock != null)
1015 my_this = new This (CurrentBlock, loc);
1017 my_this = new This (loc);
1019 if (!my_this.ResolveBase (this))
1027 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1029 protected CommonAssemblyModulClass ():
1034 public void AddAttributes (ArrayList attrs)
1036 foreach (Attribute a in attrs)
1039 if (attributes == null) {
1040 attributes = new Attributes (attrs);
1043 attributes.AddAttributes (attrs);
1046 public virtual void Emit (TypeContainer tc)
1048 if (OptAttributes == null)
1051 OptAttributes.Emit ();
1054 protected Attribute ResolveAttribute (Type a_type)
1056 Attribute a = OptAttributes.Search (a_type);
1063 public override IResolveContext ResolveContext {
1064 get { return this; }
1067 #region IResolveContext Members
1069 public DeclSpace DeclContainer {
1070 get { return RootContext.ToplevelTypes; }
1073 public DeclSpace GenericDeclContainer {
1074 get { return DeclContainer; }
1077 public bool IsInObsoleteScope {
1078 get { return false; }
1081 public bool IsInUnsafeScope {
1082 get { return false; }
1088 public class AssemblyClass : CommonAssemblyModulClass {
1089 // TODO: make it private and move all builder based methods here
1090 public AssemblyBuilder Builder;
1091 bool is_cls_compliant;
1092 bool wrap_non_exception_throws;
1093 Type runtime_compatibility_attr_type;
1095 public Attribute ClsCompliantAttribute;
1097 ListDictionary declarative_security;
1099 bool has_extension_method;
1100 public AssemblyName Name;
1101 MethodInfo add_type_forwarder;
1102 ListDictionary emitted_forwarders;
1105 // Module is here just because of error messages
1106 static string[] attribute_targets = new string [] { "assembly", "module" };
1108 public AssemblyClass (): base ()
1111 wrap_non_exception_throws = true;
1115 public bool HasExtensionMethods {
1118 has_extension_method = value;
1123 public bool IsClsCompliant {
1125 return is_cls_compliant;
1129 public bool WrapNonExceptionThrows {
1131 return wrap_non_exception_throws;
1135 public override AttributeTargets AttributeTargets {
1137 return AttributeTargets.Assembly;
1141 public override bool IsClsComplianceRequired ()
1143 return is_cls_compliant;
1146 public void Resolve ()
1148 runtime_compatibility_attr_type = TypeManager.CoreLookupType (
1149 "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", Kind.Class, false);
1151 if (OptAttributes == null)
1154 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1155 if (!OptAttributes.CheckTargets())
1158 if (TypeManager.cls_compliant_attribute_type != null)
1159 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1161 if (ClsCompliantAttribute != null) {
1162 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1165 if (runtime_compatibility_attr_type != null) {
1166 Attribute a = ResolveAttribute (runtime_compatibility_attr_type);
1168 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1170 wrap_non_exception_throws = (bool) val;
1176 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1179 // check for possible ECMA key
1180 if (strongNameBlob.Length == 16) {
1181 // will be rejected if not "the" ECMA key
1182 an.SetPublicKey (strongNameBlob);
1185 // take it, with or without, a private key
1186 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1187 // and make sure we only feed the public part to Sys.Ref
1188 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1190 // AssemblyName.SetPublicKey requires an additional header
1191 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1193 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1194 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1195 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1196 an.SetPublicKey (encodedPublicKey);
1200 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1201 Environment.Exit (1);
1205 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1206 public AssemblyName GetAssemblyName (string name, string output)
1208 if (OptAttributes != null) {
1209 foreach (Attribute a in OptAttributes.Attrs) {
1210 // cannot rely on any resolve-based members before you call Resolve
1211 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1214 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1215 // However, this is invoked by CodeGen.Init, when none of the namespaces
1217 // TODO: Does not handle quoted attributes properly
1219 case "AssemblyKeyFile":
1220 case "AssemblyKeyFileAttribute":
1221 case "System.Reflection.AssemblyKeyFileAttribute":
1222 if (RootContext.StrongNameKeyFile != 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 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1227 string value = a.GetString ();
1228 if (value.Length != 0)
1229 RootContext.StrongNameKeyFile = value;
1232 case "AssemblyKeyName":
1233 case "AssemblyKeyNameAttribute":
1234 case "System.Reflection.AssemblyKeyNameAttribute":
1235 if (RootContext.StrongNameKeyContainer != null) {
1236 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1237 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1238 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1240 string value = a.GetString ();
1241 if (value.Length != 0)
1242 RootContext.StrongNameKeyContainer = value;
1245 case "AssemblyDelaySign":
1246 case "AssemblyDelaySignAttribute":
1247 case "System.Reflection.AssemblyDelaySignAttribute":
1248 RootContext.StrongNameDelaySign = a.GetBoolean ();
1254 AssemblyName an = new AssemblyName ();
1255 an.Name = Path.GetFileNameWithoutExtension (name);
1257 // note: delay doesn't apply when using a key container
1258 if (RootContext.StrongNameKeyContainer != null) {
1259 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1263 // strongname is optional
1264 if (RootContext.StrongNameKeyFile == null)
1267 string AssemblyDir = Path.GetDirectoryName (output);
1269 // the StrongName key file may be relative to (a) the compiled
1270 // file or (b) to the output assembly. See bugzilla #55320
1271 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1273 // (a) relative to the compiled file
1274 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1275 bool exist = File.Exists (filename);
1276 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1277 // (b) relative to the outputed assembly
1278 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1279 exist = File.Exists (filename);
1283 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1284 byte[] snkeypair = new byte [fs.Length];
1285 fs.Read (snkeypair, 0, snkeypair.Length);
1287 if (RootContext.StrongNameDelaySign) {
1288 // delayed signing - DO NOT include private key
1289 SetPublicKey (an, snkeypair);
1292 // no delay so we make sure we have the private key
1294 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1295 an.KeyPair = new StrongNameKeyPair (snkeypair);
1297 catch (CryptographicException) {
1298 if (snkeypair.Length == 16) {
1299 // error # is different for ECMA key
1300 Report.Error (1606, "Could not sign the assembly. " +
1301 "ECMA key can only be used to delay-sign assemblies");
1304 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1312 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1318 void Error_AssemblySigning (string text)
1320 Report.Error (1548, "Error during assembly signing. " + text);
1324 bool CheckInternalsVisibleAttribute (Attribute a)
1326 string assembly_name = a.GetString ();
1327 if (assembly_name.Length == 0)
1330 AssemblyName aname = null;
1332 aname = new AssemblyName (assembly_name);
1333 } catch (FileLoadException) {
1334 } catch (ArgumentException) {
1337 // Bad assembly name format
1339 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1340 // Report error if we have defined Version or Culture
1341 else if (aname.Version != null || aname.CultureInfo != null)
1342 throw new Exception ("Friend assembly `" + a.GetString () +
1343 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1344 else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1345 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1346 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1354 static bool IsValidAssemblyVersion (string version)
1358 v = new Version (version);
1361 int major = int.Parse (version, CultureInfo.InvariantCulture);
1362 v = new Version (major, 0);
1368 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1369 if (candidate > ushort.MaxValue)
1376 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1378 if (a.IsValidSecurityAttribute ()) {
1379 if (declarative_security == null)
1380 declarative_security = new ListDictionary ();
1382 a.ExtractSecurityPermissionSet (declarative_security);
1386 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1387 string value = a.GetString ();
1388 if (value == null || value.Length == 0)
1391 if (RootContext.Target == Target.Exe) {
1392 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1397 if (a.Type == TypeManager.assembly_version_attribute_type) {
1398 string value = a.GetString ();
1399 if (value == null || value.Length == 0)
1402 value = value.Replace ('*', '0');
1404 if (!IsValidAssemblyVersion (value)) {
1405 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1411 if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1414 if (a.Type == TypeManager.type_forwarder_attr_type) {
1415 Type t = a.GetArgumentType ();
1416 if (t == null || TypeManager.HasElementType (t)) {
1417 Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1421 if (emitted_forwarders == null) {
1422 emitted_forwarders = new ListDictionary();
1423 } else if (emitted_forwarders.Contains(t)) {
1424 Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1425 Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1426 TypeManager.CSharpName(t));
1430 emitted_forwarders.Add(t, a);
1432 if (TypeManager.LookupDeclSpace (t) != null) {
1433 Report.SymbolRelatedToPreviousError (t);
1434 Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1435 TypeManager.CSharpName (t));
1440 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1441 TypeManager.CSharpName (t));
1445 if (t.IsGenericType) {
1446 Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1450 if (add_type_forwarder == null) {
1451 add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1452 BindingFlags.NonPublic | BindingFlags.Instance);
1454 if (add_type_forwarder == null) {
1455 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1460 add_type_forwarder.Invoke (Builder, new object[] { t });
1464 if (a.Type == TypeManager.extension_attribute_type) {
1465 a.Error_MisusedExtensionAttribute ();
1469 Builder.SetCustomAttribute (customBuilder);
1472 public override void Emit (TypeContainer tc)
1477 if (has_extension_method)
1478 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1481 if (runtime_compatibility_attr_type != null) {
1482 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1483 if (OptAttributes == null || !OptAttributes.Contains (runtime_compatibility_attr_type)) {
1484 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
1485 runtime_compatibility_attr_type, Location.Null, Type.EmptyTypes);
1486 PropertyInfo [] pis = new PropertyInfo [1];
1487 pis [0] = TypeManager.GetPredefinedProperty (runtime_compatibility_attr_type,
1488 "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
1489 object [] pargs = new object [1];
1491 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1495 if (declarative_security != null) {
1497 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1498 object builder_instance = Builder;
1501 // Microsoft runtime hacking
1502 if (add_permission == null) {
1503 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1504 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1506 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1507 builder_instance = fi.GetValue (Builder);
1510 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1511 declarative_security [SecurityAction.RequestOptional],
1512 declarative_security [SecurityAction.RequestRefuse] };
1513 add_permission.Invoke (builder_instance, args);
1516 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1521 public override string[] ValidAttributeTargets {
1523 return attribute_targets;
1527 // Wrapper for AssemblyBuilder.AddModule
1528 static MethodInfo adder_method;
1529 static public MethodInfo AddModule_Method {
1531 if (adder_method == null)
1532 adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1533 return adder_method;
1536 public Module AddModule (string module)
1538 MethodInfo m = AddModule_Method;
1540 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1541 Environment.Exit (1);
1545 return (Module) m.Invoke (Builder, new object [] { module });
1546 } catch (TargetInvocationException ex) {
1547 throw ex.InnerException;
1552 public class ModuleClass : CommonAssemblyModulClass {
1553 // TODO: make it private and move all builder based methods here
1554 public ModuleBuilder Builder;
1555 bool m_module_is_unsafe;
1557 bool has_default_charset;
1560 public CharSet DefaultCharSet = CharSet.Ansi;
1561 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1563 static string[] attribute_targets = new string [] { "module" };
1565 public ModuleClass (bool is_unsafe)
1567 m_module_is_unsafe = is_unsafe;
1570 public override AttributeTargets AttributeTargets {
1572 return AttributeTargets.Module;
1576 public override bool IsClsComplianceRequired ()
1578 return CodeGen.Assembly.IsClsCompliant;
1581 public override void Emit (TypeContainer tc)
1585 if (m_module_is_unsafe) {
1586 Type t = TypeManager.CoreLookupType ("System.Security", "UnverifiableCodeAttribute", Kind.Class, true);
1588 ConstructorInfo unverifiable_code_ctor = TypeManager.GetPredefinedConstructor (t, Location.Null, Type.EmptyTypes);
1589 if (unverifiable_code_ctor != null)
1590 Builder.SetCustomAttribute (new CustomAttributeBuilder (unverifiable_code_ctor, new object [0]));
1595 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1597 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1598 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1599 Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1601 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1602 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1603 Report.Warning (3017, 1, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1608 Builder.SetCustomAttribute (customBuilder);
1611 public bool HasDefaultCharSet {
1614 return has_default_charset;
1622 /// It is called very early therefore can resolve only predefined attributes
1624 public void Resolve ()
1627 if (OptAttributes == null)
1630 if (!OptAttributes.CheckTargets())
1633 if (TypeManager.default_charset_type == null)
1636 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1638 has_default_charset = true;
1639 DefaultCharSet = a.GetCharSetValue ();
1640 switch (DefaultCharSet) {
1645 DefaultCharSetType = TypeAttributes.AutoClass;
1647 case CharSet.Unicode:
1648 DefaultCharSetType = TypeAttributes.UnicodeClass;
1651 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1658 public override string[] ValidAttributeTargets {
1660 return attribute_targets;