2005-02-19 Ben Maurer <bmaurer@ximian.com>
[mono-project.git] / mcs / bmcs / codegen.cs
blob9073d2a00a2a791e8461aac964e8ae330cf4c8fa
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 //
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
9 //
10 //#define PRODUCTION
11 using System;
12 using System.IO;
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
22 using Mono.Security.Cryptography;
24 namespace Mono.CSharp {
26 /// <summary>
27 /// Code generator class.
28 /// </summary>
29 public class CodeGen {
30 static AppDomain current_domain;
31 static public SymbolWriter SymbolWriter;
33 public static AssemblyClass Assembly;
34 public static ModuleClass Module;
36 static CodeGen ()
38 Assembly = new AssemblyClass ();
39 Module = new ModuleClass (RootContext.Unsafe);
42 public static string Basename (string name)
44 int pos = name.LastIndexOf ('/');
46 if (pos != -1)
47 return name.Substring (pos + 1);
49 pos = name.LastIndexOf ('\\');
50 if (pos != -1)
51 return name.Substring (pos + 1);
53 return name;
56 public static string Dirname (string name)
58 int pos = name.LastIndexOf ('/');
60 if (pos != -1)
61 return name.Substring (0, pos);
63 pos = name.LastIndexOf ('\\');
64 if (pos != -1)
65 return name.Substring (0, pos);
67 return ".";
70 static string TrimExt (string name)
72 int pos = name.LastIndexOf ('.');
74 return name.Substring (0, pos);
77 static public string FileName;
80 // Initializes the symbol writer
82 static void InitializeSymbolWriter (string filename)
84 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
87 // If we got an ISymbolWriter instance, initialize it.
89 if (SymbolWriter == null) {
90 Report.Warning (
91 -18, "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.");
92 return;
97 // Initializes the code generator variables
99 static public void Init (string name, string output, bool want_debugging_support)
101 FileName = output;
102 AssemblyName an = Assembly.GetAssemblyName (name, output);
104 if (an.KeyPair != null) {
105 // If we are going to strong name our assembly make
106 // sure all its refs are strong named
107 foreach (Assembly a in TypeManager.GetAssemblies ()) {
108 AssemblyName ref_name = a.GetName ();
109 byte [] b = ref_name.GetPublicKeyToken ();
110 if (b == null || b.Length == 0) {
111 Report.Warning (1577, "Assembly generation failed " +
112 "-- Referenced assembly '" +
113 ref_name.Name +
114 "' does not have a strong name.");
115 //Environment.Exit (1);
120 current_domain = AppDomain.CurrentDomain;
122 try {
123 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
124 AssemblyBuilderAccess.Save, Dirname (name));
126 catch (ArgumentException) {
127 // specified key may not be exportable outside it's container
128 if (RootContext.StrongNameKeyContainer != null) {
129 Report.Error (1548, "Could not access the key inside the container `" +
130 RootContext.StrongNameKeyContainer + "'.");
131 Environment.Exit (1);
133 throw;
135 catch (CryptographicException) {
136 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
137 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
138 Environment.Exit (1);
140 throw;
144 // Pass a path-less name to DefineDynamicModule. Wonder how
145 // this copes with output in different directories then.
146 // FIXME: figure out how this copes with --output /tmp/blah
148 // If the third argument is true, the ModuleBuilder will dynamically
149 // load the default symbol writer.
151 Module.Builder = Assembly.Builder.DefineDynamicModule (
152 Basename (name), Basename (output), false);
154 if (want_debugging_support)
155 InitializeSymbolWriter (output);
158 static public void Save (string name)
160 try {
161 Assembly.Builder.Save (Basename (name));
163 catch (COMException) {
164 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
165 throw;
167 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
168 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
169 RootContext.StrongNameKeyFile +
170 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
172 catch (System.IO.IOException io) {
173 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
176 if (SymbolWriter != null)
177 SymbolWriter.WriteSymbolFile ();
180 public static void AddGlobalAttributes (ArrayList attrs)
182 foreach (Attribute attr in attrs) {
183 if (attr.IsAssemblyAttribute)
184 Assembly.AddAttribute (attr);
185 else if (attr.IsModuleAttribute)
186 Module.AddAttribute (attr);
192 // Provides "local" store across code that can yield: locals
193 // or fields, notice that this should not be used by anonymous
194 // methods to create local storage, those only require
195 // variable mapping.
197 public class VariableStorage {
198 FieldBuilder fb;
199 LocalBuilder local;
201 static int count;
203 public VariableStorage (EmitContext ec, Type t)
205 count++;
206 if (ec.InIterator)
207 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
208 else
209 local = ec.ig.DeclareLocal (t);
212 public void EmitThis (ILGenerator ig)
214 if (fb != null)
215 ig.Emit (OpCodes.Ldarg_0);
218 public void EmitStore (ILGenerator ig)
220 if (fb == null)
221 ig.Emit (OpCodes.Stloc, local);
222 else
223 ig.Emit (OpCodes.Stfld, fb);
226 public void EmitLoad (ILGenerator ig)
228 if (fb == null)
229 ig.Emit (OpCodes.Ldloc, local);
230 else
231 ig.Emit (OpCodes.Ldfld, fb);
234 public void EmitLoadAddress (ILGenerator ig)
236 if (fb == null)
237 ig.Emit (OpCodes.Ldloca, local);
238 else
239 ig.Emit (OpCodes.Ldflda, fb);
242 public void EmitCall (ILGenerator ig, MethodInfo mi)
244 // FIXME : we should handle a call like tostring
245 // here, where boxing is needed. However, we will
246 // never encounter that with the current usage.
248 bool value_type_call;
249 EmitThis (ig);
250 if (fb == null) {
251 value_type_call = local.LocalType.IsValueType;
253 if (value_type_call)
254 ig.Emit (OpCodes.Ldloca, local);
255 else
256 ig.Emit (OpCodes.Ldloc, local);
257 } else {
258 value_type_call = fb.FieldType.IsValueType;
260 if (value_type_call)
261 ig.Emit (OpCodes.Ldflda, fb);
262 else
263 ig.Emit (OpCodes.Ldfld, fb);
266 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
270 /// <summary>
271 /// An Emit Context is created for each body of code (from methods,
272 /// properties bodies, indexer bodies or constructor bodies)
273 /// </summary>
274 public class EmitContext {
275 public DeclSpace DeclSpace;
276 public DeclSpace TypeContainer;
277 public ILGenerator ig;
279 /// <summary>
280 /// This variable tracks the `checked' state of the compilation,
281 /// it controls whether we should generate code that does overflow
282 /// checking, or if we generate code that ignores overflows.
284 /// The default setting comes from the command line option to generate
285 /// checked or unchecked code plus any source code changes using the
286 /// checked/unchecked statements or expressions. Contrast this with
287 /// the ConstantCheckState flag.
288 /// </summary>
290 public bool CheckState;
292 /// <summary>
293 /// The constant check state is always set to `true' and cant be changed
294 /// from the command line. The source code can change this setting with
295 /// the `checked' and `unchecked' statements and expressions.
296 /// </summary>
297 public bool ConstantCheckState;
299 /// <summary>
300 /// Whether we are emitting code inside a static or instance method
301 /// </summary>
302 public bool IsStatic;
304 /// <summary>
305 /// Whether we are emitting a field initializer
306 /// </summary>
307 public bool IsFieldInitializer;
309 /// <summary>
310 /// The value that is allowed to be returned or NULL if there is no
311 /// return type.
312 /// </summary>
313 public Type ReturnType;
315 /// <summary>
316 /// Points to the Type (extracted from the TypeContainer) that
317 /// declares this body of code
318 /// </summary>
319 public Type ContainerType;
321 /// <summary>
322 /// Whether this is generating code for a constructor
323 /// </summary>
324 public bool IsConstructor;
326 /// <summary>
327 /// Whether we're control flow analysis enabled
328 /// </summary>
329 public bool DoFlowAnalysis;
331 /// <summary>
332 /// Keeps track of the Type to LocalBuilder temporary storage created
333 /// to store structures (used to compute the address of the structure
334 /// value on structure method invocations)
335 /// </summary>
336 public Hashtable temporary_storage;
338 public Block CurrentBlock;
340 public int CurrentFile;
342 /// <summary>
343 /// The location where we store the return value.
344 /// </summary>
345 LocalBuilder return_value;
347 /// <summary>
348 /// The location where return has to jump to return the
349 /// value
350 /// </summary>
351 public Label ReturnLabel;
353 /// <summary>
354 /// If we already defined the ReturnLabel
355 /// </summary>
356 public bool HasReturnLabel;
358 /// <summary>
359 /// Whether we are inside an iterator block.
360 /// </summary>
361 public bool InIterator;
363 public bool IsLastStatement;
365 /// <summary>
366 /// Whether remapping of locals, parameters and fields is turned on.
367 /// Used by iterators and anonymous methods.
368 /// </summary>
369 public bool RemapToProxy;
371 /// <summary>
372 /// Whether we are inside an unsafe block
373 /// </summary>
374 public bool InUnsafe;
376 /// <summary>
377 /// Whether we are in a `fixed' initialization
378 /// </summary>
379 public bool InFixedInitializer;
381 /// <summary>
382 /// Whether we are inside an anonymous method.
383 /// </summary>
384 public AnonymousMethod CurrentAnonymousMethod;
386 /// <summary>
387 /// Location for this EmitContext
388 /// </summary>
389 public Location loc;
391 /// <summary>
392 /// Used to flag that it is ok to define types recursively, as the
393 /// expressions are being evaluated as part of the type lookup
394 /// during the type resolution process
395 /// </summary>
396 public bool ResolvingTypeTree;
398 /// <summary>
399 /// Inside an enum definition, we do not resolve enumeration values
400 /// to their enumerations, but rather to the underlying type/value
401 /// This is so EnumVal + EnumValB can be evaluated.
403 /// There is no "E operator + (E x, E y)", so during an enum evaluation
404 /// we relax the rules
405 /// </summary>
406 public bool InEnumContext;
408 /// <summary>
409 /// Anonymous methods can capture local variables and fields,
410 /// this object tracks it. It is copied from the TopLevelBlock
411 /// field.
412 /// </summary>
413 public CaptureContext capture_context;
415 /// <summary>
416 /// Trace when method is called and is obsolete then this member suppress message
417 /// when call is inside next [Obsolete] method or type.
418 /// </summary>
419 public bool TestObsoleteMethodUsage = true;
421 /// <summary>
422 /// The current iterator
423 /// </summary>
424 public Iterator CurrentIterator;
426 /// <summary>
427 /// Whether we are in the resolving stage or not
428 /// </summary>
429 enum Phase {
430 Created,
431 Resolving,
432 Emitting
435 Phase current_phase;
437 FlowBranching current_flow_branching;
439 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
440 Type return_type, int code_flags, bool is_constructor)
442 this.ig = ig;
444 TypeContainer = parent;
445 DeclSpace = ds;
446 CheckState = RootContext.Checked;
447 ConstantCheckState = true;
449 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
450 throw new Exception ("FUCK");
452 IsStatic = (code_flags & Modifiers.STATIC) != 0;
453 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
454 RemapToProxy = InIterator;
455 ReturnType = return_type;
456 IsConstructor = is_constructor;
457 CurrentBlock = null;
458 CurrentFile = 0;
459 current_phase = Phase.Created;
461 if (parent != null){
462 // Can only be null for the ResolveType contexts.
463 ContainerType = parent.TypeBuilder;
464 if (parent.UnsafeContext)
465 InUnsafe = true;
466 else
467 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
469 loc = l;
471 if (ReturnType == TypeManager.void_type)
472 ReturnType = null;
475 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
476 Type return_type, int code_flags, bool is_constructor)
477 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
481 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
482 Type return_type, int code_flags)
483 : this (tc, tc, l, ig, return_type, code_flags, false)
487 public FlowBranching CurrentBranching {
488 get {
489 return current_flow_branching;
493 public bool HaveCaptureInfo {
494 get {
495 return capture_context != null;
499 // <summary>
500 // Starts a new code branching. This inherits the state of all local
501 // variables and parameters from the current branching.
502 // </summary>
503 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
505 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
506 return current_flow_branching;
509 // <summary>
510 // Starts a new code branching for block `block'.
511 // </summary>
512 public FlowBranching StartFlowBranching (Block block)
514 FlowBranching.BranchingType type;
516 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
517 type = FlowBranching.BranchingType.SwitchSection;
518 else
519 type = FlowBranching.BranchingType.Block;
521 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
522 return current_flow_branching;
525 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
527 FlowBranchingException branching = new FlowBranchingException (
528 CurrentBranching, stmt);
529 current_flow_branching = branching;
530 return branching;
533 // <summary>
534 // Ends a code branching. Merges the state of locals and parameters
535 // from all the children of the ending branching.
536 // </summary>
537 public FlowBranching.UsageVector DoEndFlowBranching ()
539 FlowBranching old = current_flow_branching;
540 current_flow_branching = current_flow_branching.Parent;
542 return current_flow_branching.MergeChild (old);
545 // <summary>
546 // Ends a code branching. Merges the state of locals and parameters
547 // from all the children of the ending branching.
548 // </summary>
549 public FlowBranching.Reachability EndFlowBranching ()
551 FlowBranching.UsageVector vector = DoEndFlowBranching ();
553 return vector.Reachability;
556 // <summary>
557 // Kills the current code branching. This throws away any changed state
558 // information and should only be used in case of an error.
559 // </summary>
560 public void KillFlowBranching ()
562 current_flow_branching = current_flow_branching.Parent;
565 public void CaptureVariable (LocalInfo li)
567 capture_context.AddLocal (CurrentAnonymousMethod, li);
568 li.IsCaptured = true;
571 public void CaptureParameter (string name, Type t, int idx)
574 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
578 // Use to register a field as captured
580 public void CaptureField (FieldExpr fe)
582 capture_context.AddField (fe);
586 // Whether anonymous methods have captured variables
588 public bool HaveCapturedVariables ()
590 if (capture_context != null)
591 return capture_context.HaveCapturedVariables;
592 return false;
596 // Whether anonymous methods have captured fields or this.
598 public bool HaveCapturedFields ()
600 if (capture_context != null)
601 return capture_context.HaveCapturedFields;
602 return false;
606 // Emits the instance pointer for the host method
608 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
610 if (capture_context != null)
611 capture_context.EmitMethodHostInstance (target, am);
612 else if (IsStatic)
613 target.ig.Emit (OpCodes.Ldnull);
614 else
615 target.ig.Emit (OpCodes.Ldarg_0);
619 // Returns whether the `local' variable has been captured by an anonymous
620 // method
622 public bool IsCaptured (LocalInfo local)
624 return capture_context.IsCaptured (local);
627 public bool IsParameterCaptured (string name)
629 if (capture_context != null)
630 return capture_context.IsParameterCaptured (name);
631 return false;
634 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
636 if (capture_context != null)
637 capture_context.EmitHelperClasses (this);
638 b.EmitMeta (this);
640 if (HasReturnLabel)
641 ReturnLabel = ig.DefineLabel ();
645 // Here until we can fix the problem with Mono.CSharp.Switch, which
646 // currently can not cope with ig == null during resolve (which must
647 // be fixed for switch statements to work on anonymous methods).
649 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
651 if (block == null)
652 return;
654 bool unreachable;
656 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
657 EmitMeta (block, ip);
659 current_phase = Phase.Emitting;
660 EmitResolvedTopBlock (block, unreachable);
664 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
665 InternalParameters ip, Location loc, out bool unreachable)
667 current_phase = Phase.Resolving;
669 unreachable = false;
671 capture_context = block.CaptureContext;
673 if (!Location.IsNull (loc))
674 CurrentFile = loc.File;
676 #if PRODUCTION
677 try {
678 #endif
679 int errors = Report.Errors;
681 block.ResolveMeta (block, this, ip);
684 if (Report.Errors == errors){
685 bool old_do_flow_analysis = DoFlowAnalysis;
686 DoFlowAnalysis = true;
688 if (anonymous_method_host != null)
689 current_flow_branching = FlowBranching.CreateBranching (
690 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
691 block, loc);
692 else
693 current_flow_branching = FlowBranching.CreateBranching (
694 null, FlowBranching.BranchingType.Block, block, loc);
696 if (!block.Resolve (this)) {
697 current_flow_branching = null;
698 DoFlowAnalysis = old_do_flow_analysis;
699 return false;
702 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
703 current_flow_branching = null;
705 DoFlowAnalysis = old_do_flow_analysis;
707 if (reachability.AlwaysReturns ||
708 reachability.AlwaysThrows ||
709 reachability.IsUnreachable)
710 unreachable = true;
712 #if PRODUCTION
713 } catch (Exception e) {
714 Console.WriteLine ("Exception caught by the compiler while compiling:");
715 Console.WriteLine (" Block that caused the problem begin at: " + loc);
717 if (CurrentBlock != null){
718 Console.WriteLine (" Block being compiled: [{0},{1}]",
719 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
721 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
722 throw;
724 #endif
726 if (ReturnType != null && !unreachable){
727 if (!InIterator){
728 if (CurrentAnonymousMethod != null){
729 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
730 CurrentAnonymousMethod.Type);
731 } else {
732 Report.Error (161, loc, "Not all code paths return a value");
735 return false;
738 block.CompleteContexts ();
740 return true;
743 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
745 if (block != null)
746 block.Emit (this);
748 if (HasReturnLabel)
749 ig.MarkLabel (ReturnLabel);
751 if (return_value != null){
752 ig.Emit (OpCodes.Ldloc, return_value);
753 ig.Emit (OpCodes.Ret);
754 } else {
756 // If `HasReturnLabel' is set, then we already emitted a
757 // jump to the end of the method, so we must emit a `ret'
758 // there.
760 // Unfortunately, System.Reflection.Emit automatically emits
761 // a leave to the end of a finally block. This is a problem
762 // if no code is following the try/finally block since we may
763 // jump to a point after the end of the method.
764 // As a workaround, we're always creating a return label in
765 // this case.
768 if ((block != null) && block.IsDestructor) {
769 // Nothing to do; S.R.E automatically emits a leave.
770 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
771 if (ReturnType != null)
772 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
773 ig.Emit (OpCodes.Ret);
778 // Close pending helper classes if we are the toplevel
780 if (capture_context != null && capture_context.ParentToplevel == null)
781 capture_context.CloseHelperClasses ();
784 /// <summary>
785 /// This is called immediately before emitting an IL opcode to tell the symbol
786 /// writer to which source line this opcode belongs.
787 /// </summary>
788 public void Mark (Location loc, bool check_file)
790 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
791 return;
793 if (check_file && (CurrentFile != loc.File))
794 return;
796 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
799 public void DefineLocalVariable (string name, LocalBuilder builder)
801 if (CodeGen.SymbolWriter == null)
802 return;
804 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
807 /// <summary>
808 /// Returns a temporary storage for a variable of type t as
809 /// a local variable in the current body.
810 /// </summary>
811 public LocalBuilder GetTemporaryLocal (Type t)
813 LocalBuilder location = null;
815 if (temporary_storage != null){
816 object o = temporary_storage [t];
817 if (o != null){
818 if (o is ArrayList){
819 ArrayList al = (ArrayList) o;
821 for (int i = 0; i < al.Count; i++){
822 if (al [i] != null){
823 location = (LocalBuilder) al [i];
824 al [i] = null;
825 break;
828 } else
829 location = (LocalBuilder) o;
830 if (location != null)
831 return location;
835 return ig.DeclareLocal (t);
838 public void FreeTemporaryLocal (LocalBuilder b, Type t)
840 if (temporary_storage == null){
841 temporary_storage = new Hashtable ();
842 temporary_storage [t] = b;
843 return;
845 object o = temporary_storage [t];
846 if (o == null){
847 temporary_storage [t] = b;
848 return;
850 if (o is ArrayList){
851 ArrayList al = (ArrayList) o;
852 for (int i = 0; i < al.Count; i++){
853 if (al [i] == null){
854 al [i] = b;
855 return;
858 al.Add (b);
859 return;
861 ArrayList replacement = new ArrayList ();
862 replacement.Add (o);
863 temporary_storage.Remove (t);
864 temporary_storage [t] = replacement;
867 /// <summary>
868 /// Current loop begin and end labels.
869 /// </summary>
870 public Label LoopBegin, LoopEnd;
872 /// <summary>
873 /// Default target in a switch statement. Only valid if
874 /// InSwitch is true
875 /// </summary>
876 public Label DefaultTarget;
878 /// <summary>
879 /// If this is non-null, points to the current switch statement
880 /// </summary>
881 public Switch Switch;
883 /// <summary>
884 /// ReturnValue creates on demand the LocalBuilder for the
885 /// return value from the function. By default this is not
886 /// used. This is only required when returns are found inside
887 /// Try or Catch statements.
889 /// This method is typically invoked from the Emit phase, so
890 /// we allow the creation of a return label if it was not
891 /// requested during the resolution phase. Could be cleaned
892 /// up, but it would replicate a lot of logic in the Emit phase
893 /// of the code that uses it.
894 /// </summary>
895 public LocalBuilder TemporaryReturn ()
897 if (return_value == null){
898 return_value = ig.DeclareLocal (ReturnType);
899 if (!HasReturnLabel){
900 ReturnLabel = ig.DefineLabel ();
901 HasReturnLabel = true;
905 return return_value;
908 /// <summary>
909 /// This method is used during the Resolution phase to flag the
910 /// need to define the ReturnLabel
911 /// </summary>
912 public void NeedReturnLabel ()
914 if (current_phase != Phase.Resolving){
916 // The reason is that the `ReturnLabel' is declared between
917 // resolution and emission
919 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
922 if (!InIterator && !HasReturnLabel)
923 HasReturnLabel = true;
927 // Creates a field `name' with the type `t' on the proxy class
929 public FieldBuilder MapVariable (string name, Type t)
931 if (InIterator)
932 return CurrentIterator.MapVariable ("v_", name, t);
934 throw new Exception ("MapVariable for an unknown state");
937 public Expression RemapParameter (int idx)
939 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
940 fe.InstanceExpression = new ProxyInstance ();
941 return fe.DoResolve (this);
944 public Expression RemapParameterLValue (int idx, Expression right_side)
946 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
947 fe.InstanceExpression = new ProxyInstance ();
948 return fe.DoResolveLValue (this, right_side);
952 // Emits the proper object to address fields on a remapped
953 // variable/parameter to field in anonymous-method/iterator proxy classes.
955 public void EmitThis ()
957 ig.Emit (OpCodes.Ldarg_0);
958 if (InIterator){
959 if (!IsStatic){
960 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
961 if (TypeManager.IsValueType (this_field.FieldType))
962 ig.Emit (OpCodes.Ldflda, this_field);
963 else
964 ig.Emit (OpCodes.Ldfld, this_field);
966 } else if (capture_context != null && CurrentAnonymousMethod != null){
967 ScopeInfo si = CurrentAnonymousMethod.Scope;
968 while (si != null){
969 if (si.ParentLink != null)
970 ig.Emit (OpCodes.Ldfld, si.ParentLink);
971 if (si.THIS != null){
972 ig.Emit (OpCodes.Ldfld, si.THIS);
973 break;
975 si = si.ParentScope;
981 // Emits the code necessary to load the instance required
982 // to access the captured LocalInfo
984 public void EmitCapturedVariableInstance (LocalInfo li)
986 if (RemapToProxy){
987 ig.Emit (OpCodes.Ldarg_0);
988 return;
991 if (capture_context == null)
992 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
994 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
997 public void EmitParameter (string name)
999 capture_context.EmitParameter (this, name);
1002 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
1004 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
1007 public void EmitAddressOfParameter (string name)
1009 capture_context.EmitAddressOfParameter (this, name);
1012 public Expression GetThis (Location loc)
1014 This my_this;
1015 if (CurrentBlock != null)
1016 my_this = new This (CurrentBlock, loc);
1017 else
1018 my_this = new This (loc);
1020 if (!my_this.ResolveBase (this))
1021 my_this = null;
1023 return my_this;
1028 public abstract class CommonAssemblyModulClass: Attributable {
1029 protected CommonAssemblyModulClass ():
1030 base (null)
1034 public void AddAttribute (Attribute attr)
1036 if (OptAttributes == null) {
1037 OptAttributes = new Attributes (attr);
1038 return;
1040 OptAttributes.AddAttribute (attr);
1043 public void AddAttributes (ArrayList attrs)
1045 if (OptAttributes == null) {
1046 OptAttributes = new Attributes (attrs);
1047 return;
1049 OptAttributes.AddAttributes (attrs);
1052 public virtual void Emit (TypeContainer tc)
1054 if (OptAttributes == null)
1055 return;
1057 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1058 OptAttributes.Emit (ec, this);
1061 protected Attribute GetClsCompliantAttribute ()
1063 if (OptAttributes == null)
1064 return null;
1066 // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1067 if (!OptAttributes.CheckTargets (this))
1068 return null;
1070 EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1071 Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1072 if (a != null) {
1073 a.Resolve (temp_ec);
1075 return a;
1079 public class AssemblyClass: CommonAssemblyModulClass {
1080 // TODO: make it private and move all builder based methods here
1081 public AssemblyBuilder Builder;
1083 bool is_cls_compliant;
1084 public Attribute ClsCompliantAttribute;
1086 ListDictionary declarative_security;
1088 static string[] attribute_targets = new string [] { "assembly" };
1090 public AssemblyClass (): base ()
1092 is_cls_compliant = false;
1095 public bool IsClsCompliant {
1096 get {
1097 return is_cls_compliant;
1101 public override AttributeTargets AttributeTargets {
1102 get {
1103 return AttributeTargets.Assembly;
1107 public override bool IsClsCompliaceRequired(DeclSpace ds)
1109 return is_cls_compliant;
1112 public void ResolveClsCompliance ()
1114 ClsCompliantAttribute = GetClsCompliantAttribute ();
1115 if (ClsCompliantAttribute == null)
1116 return;
1118 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1121 // fix bug #56621
1122 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1124 try {
1125 // check for possible ECMA key
1126 if (strongNameBlob.Length == 16) {
1127 // will be rejected if not "the" ECMA key
1128 an.SetPublicKey (strongNameBlob);
1130 else {
1131 // take it, with or without, a private key
1132 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1133 // and make sure we only feed the public part to Sys.Ref
1134 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1136 // AssemblyName.SetPublicKey requires an additional header
1137 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1139 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1140 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1141 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1142 an.SetPublicKey (encodedPublicKey);
1145 catch (Exception) {
1146 Report.Error (1548, "Could not strongname the assembly. File `" +
1147 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1148 Environment.Exit (1);
1152 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1153 public AssemblyName GetAssemblyName (string name, string output)
1155 if (OptAttributes != null) {
1156 foreach (Attribute a in OptAttributes.Attrs) {
1157 // cannot rely on any resolve-based members before you call Resolve
1158 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1159 continue;
1161 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1162 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1163 // are loaded yet.
1164 switch (a.Name) {
1165 case "AssemblyKeyFile":
1166 case "AssemblyKeyFileAttribute":
1167 case "System.Reflection.AssemblyKeyFileAttribute":
1168 if (RootContext.StrongNameKeyFile != null) {
1169 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1170 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1172 else {
1173 string value = a.GetString ();
1174 if (value != String.Empty)
1175 RootContext.StrongNameKeyFile = value;
1177 break;
1178 case "AssemblyKeyName":
1179 case "AssemblyKeyNameAttribute":
1180 case "System.Reflection.AssemblyKeyNameAttribute":
1181 if (RootContext.StrongNameKeyContainer != null) {
1182 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1183 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1185 else {
1186 string value = a.GetString ();
1187 if (value != String.Empty)
1188 RootContext.StrongNameKeyContainer = value;
1190 break;
1191 case "AssemblyDelaySign":
1192 case "AssemblyDelaySignAttribute":
1193 case "System.Reflection.AssemblyDelaySignAttribute":
1194 RootContext.StrongNameDelaySign = a.GetBoolean ();
1195 break;
1200 AssemblyName an = new AssemblyName ();
1201 an.Name = Path.GetFileNameWithoutExtension (name);
1203 // note: delay doesn't apply when using a key container
1204 if (RootContext.StrongNameKeyContainer != null) {
1205 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1206 return an;
1209 // strongname is optional
1210 if (RootContext.StrongNameKeyFile == null)
1211 return an;
1213 string AssemblyDir = Path.GetDirectoryName (output);
1215 // the StrongName key file may be relative to (a) the compiled
1216 // file or (b) to the output assembly. See bugzilla #55320
1217 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1219 // (a) relative to the compiled file
1220 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1221 bool exist = File.Exists (filename);
1222 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1223 // (b) relative to the outputed assembly
1224 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1225 exist = File.Exists (filename);
1228 if (exist) {
1229 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1230 byte[] snkeypair = new byte [fs.Length];
1231 fs.Read (snkeypair, 0, snkeypair.Length);
1233 if (RootContext.StrongNameDelaySign) {
1234 // delayed signing - DO NOT include private key
1235 SetPublicKey (an, snkeypair);
1237 else {
1238 // no delay so we make sure we have the private key
1239 try {
1240 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1241 an.KeyPair = new StrongNameKeyPair (snkeypair);
1243 catch (CryptographicException) {
1244 if (snkeypair.Length == 16) {
1245 // error # is different for ECMA key
1246 Report.Error (1606, "Could not strongname the assembly. " +
1247 "ECMA key can only be used to delay-sign assemblies");
1249 else {
1250 Report.Error (1548, "Could not strongname the assembly. File `" +
1251 RootContext.StrongNameKeyFile +
1252 "' doesn't have a private key.");
1254 Environment.Exit (1);
1259 else {
1260 Report.Error (1548, "Could not strongname the assembly. File `" +
1261 RootContext.StrongNameKeyFile + "' not found.");
1262 Environment.Exit (1);
1264 return an;
1267 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1269 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1270 if (declarative_security == null)
1271 declarative_security = new ListDictionary ();
1273 a.ExtractSecurityPermissionSet (declarative_security);
1274 return;
1277 Builder.SetCustomAttribute (customBuilder);
1280 public override void Emit (TypeContainer tc)
1282 base.Emit (tc);
1284 if (declarative_security != null) {
1286 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1287 object builder_instance = Builder;
1289 try {
1290 // Microsoft runtime hacking
1291 if (add_permission == null) {
1292 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1293 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1295 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1296 builder_instance = fi.GetValue (Builder);
1299 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1300 declarative_security [SecurityAction.RequestOptional],
1301 declarative_security [SecurityAction.RequestRefuse] };
1302 add_permission.Invoke (builder_instance, args);
1304 catch {
1305 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1310 public override string[] ValidAttributeTargets {
1311 get {
1312 return attribute_targets;
1317 public class ModuleClass: CommonAssemblyModulClass {
1318 // TODO: make it private and move all builder based methods here
1319 public ModuleBuilder Builder;
1320 bool m_module_is_unsafe;
1322 static string[] attribute_targets = new string [] { "module" };
1324 public ModuleClass (bool is_unsafe)
1326 m_module_is_unsafe = is_unsafe;
1329 public override AttributeTargets AttributeTargets {
1330 get {
1331 return AttributeTargets.Module;
1335 public override bool IsClsCompliaceRequired(DeclSpace ds)
1337 return CodeGen.Assembly.IsClsCompliant;
1340 public override void Emit (TypeContainer tc)
1342 base.Emit (tc);
1344 if (!m_module_is_unsafe)
1345 return;
1347 if (TypeManager.unverifiable_code_ctor == null) {
1348 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1349 return;
1352 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1355 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1357 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1358 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1359 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1361 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1362 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1363 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1364 return;
1368 Builder.SetCustomAttribute (customBuilder);
1371 public override string[] ValidAttributeTargets {
1372 get {
1373 return attribute_targets;