**** Merged from MCS ****
[mono-project.git] / mcs / mcs / codegen.cs
blob4ccda28f545f14b45058533c68df818fa5e26cca
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.CSharp.Debugger.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CSharp.Debugger 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 ();
182 // Provides "local" store across code that can yield: locals
183 // or fields, notice that this should not be used by anonymous
184 // methods to create local storage, those only require
185 // variable mapping.
187 public class VariableStorage {
188 FieldBuilder fb;
189 LocalBuilder local;
191 static int count;
193 public VariableStorage (EmitContext ec, Type t)
195 count++;
196 if (ec.InIterator)
197 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
198 else
199 local = ec.ig.DeclareLocal (t);
202 public void EmitThis (ILGenerator ig)
204 if (fb != null)
205 ig.Emit (OpCodes.Ldarg_0);
208 public void EmitStore (ILGenerator ig)
210 if (fb == null)
211 ig.Emit (OpCodes.Stloc, local);
212 else
213 ig.Emit (OpCodes.Stfld, fb);
216 public void EmitLoad (ILGenerator ig)
218 if (fb == null)
219 ig.Emit (OpCodes.Ldloc, local);
220 else
221 ig.Emit (OpCodes.Ldfld, fb);
224 public void EmitLoadAddress (ILGenerator ig)
226 if (fb == null)
227 ig.Emit (OpCodes.Ldloca, local);
228 else
229 ig.Emit (OpCodes.Ldflda, fb);
232 public void EmitCall (ILGenerator ig, MethodInfo mi)
234 // FIXME : we should handle a call like tostring
235 // here, where boxing is needed. However, we will
236 // never encounter that with the current usage.
238 bool value_type_call;
239 EmitThis (ig);
240 if (fb == null) {
241 value_type_call = local.LocalType.IsValueType;
243 if (value_type_call)
244 ig.Emit (OpCodes.Ldloca, local);
245 else
246 ig.Emit (OpCodes.Ldloc, local);
247 } else {
248 value_type_call = fb.FieldType.IsValueType;
250 if (value_type_call)
251 ig.Emit (OpCodes.Ldflda, fb);
252 else
253 ig.Emit (OpCodes.Ldfld, fb);
256 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
260 /// <summary>
261 /// An Emit Context is created for each body of code (from methods,
262 /// properties bodies, indexer bodies or constructor bodies)
263 /// </summary>
264 public class EmitContext {
265 public DeclSpace DeclSpace;
266 public DeclSpace TypeContainer;
267 public ILGenerator ig;
269 /// <summary>
270 /// This variable tracks the `checked' state of the compilation,
271 /// it controls whether we should generate code that does overflow
272 /// checking, or if we generate code that ignores overflows.
274 /// The default setting comes from the command line option to generate
275 /// checked or unchecked code plus any source code changes using the
276 /// checked/unchecked statements or expressions. Contrast this with
277 /// the ConstantCheckState flag.
278 /// </summary>
280 public bool CheckState;
282 /// <summary>
283 /// The constant check state is always set to `true' and cant be changed
284 /// from the command line. The source code can change this setting with
285 /// the `checked' and `unchecked' statements and expressions.
286 /// </summary>
287 public bool ConstantCheckState;
289 /// <summary>
290 /// Whether we are emitting code inside a static or instance method
291 /// </summary>
292 public bool IsStatic;
294 /// <summary>
295 /// Whether we are emitting a field initializer
296 /// </summary>
297 public bool IsFieldInitializer;
299 /// <summary>
300 /// The value that is allowed to be returned or NULL if there is no
301 /// return type.
302 /// </summary>
303 public Type ReturnType;
305 /// <summary>
306 /// Points to the Type (extracted from the TypeContainer) that
307 /// declares this body of code
308 /// </summary>
309 public Type ContainerType;
311 /// <summary>
312 /// Whether this is generating code for a constructor
313 /// </summary>
314 public bool IsConstructor;
316 /// <summary>
317 /// Whether we're control flow analysis enabled
318 /// </summary>
319 public bool DoFlowAnalysis;
321 /// <summary>
322 /// Keeps track of the Type to LocalBuilder temporary storage created
323 /// to store structures (used to compute the address of the structure
324 /// value on structure method invocations)
325 /// </summary>
326 public Hashtable temporary_storage;
328 public Block CurrentBlock;
330 public int CurrentFile;
332 /// <summary>
333 /// The location where we store the return value.
334 /// </summary>
335 LocalBuilder return_value;
337 /// <summary>
338 /// The location where return has to jump to return the
339 /// value
340 /// </summary>
341 public Label ReturnLabel;
343 /// <summary>
344 /// If we already defined the ReturnLabel
345 /// </summary>
346 public bool HasReturnLabel;
348 /// <summary>
349 /// Whether we are inside an iterator block.
350 /// </summary>
351 public bool InIterator;
353 public bool IsLastStatement;
355 /// <summary>
356 /// Whether remapping of locals, parameters and fields is turned on.
357 /// Used by iterators and anonymous methods.
358 /// </summary>
359 public bool RemapToProxy;
361 /// <summary>
362 /// Whether we are inside an unsafe block
363 /// </summary>
364 public bool InUnsafe;
366 /// <summary>
367 /// Whether we are in a `fixed' initialization
368 /// </summary>
369 public bool InFixedInitializer;
371 /// <summary>
372 /// Whether we are inside an anonymous method.
373 /// </summary>
374 public AnonymousMethod CurrentAnonymousMethod;
376 /// <summary>
377 /// Location for this EmitContext
378 /// </summary>
379 public Location loc;
381 /// <summary>
382 /// Used to flag that it is ok to define types recursively, as the
383 /// expressions are being evaluated as part of the type lookup
384 /// during the type resolution process
385 /// </summary>
386 public bool ResolvingTypeTree;
388 /// <summary>
389 /// Inside an enum definition, we do not resolve enumeration values
390 /// to their enumerations, but rather to the underlying type/value
391 /// This is so EnumVal + EnumValB can be evaluated.
393 /// There is no "E operator + (E x, E y)", so during an enum evaluation
394 /// we relax the rules
395 /// </summary>
396 public bool InEnumContext;
398 /// <summary>
399 /// Anonymous methods can capture local variables and fields,
400 /// this object tracks it. It is copied from the TopLevelBlock
401 /// field.
402 /// </summary>
403 public CaptureContext capture_context;
405 /// <summary>
406 /// Trace when method is called and is obsolete then this member suppress message
407 /// when call is inside next [Obsolete] method or type.
408 /// </summary>
409 public bool TestObsoleteMethodUsage = true;
411 /// <summary>
412 /// The current iterator
413 /// </summary>
414 public Iterator CurrentIterator;
416 /// <summary>
417 /// Whether we are in the resolving stage or not
418 /// </summary>
419 enum Phase {
420 Created,
421 Resolving,
422 Emitting
425 Phase current_phase;
427 FlowBranching current_flow_branching;
429 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
430 Type return_type, int code_flags, bool is_constructor)
432 this.ig = ig;
434 TypeContainer = parent;
435 DeclSpace = ds;
436 CheckState = RootContext.Checked;
437 ConstantCheckState = true;
439 IsStatic = (code_flags & Modifiers.STATIC) != 0;
440 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
441 RemapToProxy = InIterator;
442 ReturnType = return_type;
443 IsConstructor = is_constructor;
444 CurrentBlock = null;
445 CurrentFile = 0;
446 current_phase = Phase.Created;
448 if (parent != null){
449 // Can only be null for the ResolveType contexts.
450 ContainerType = parent.TypeBuilder;
451 if (parent.UnsafeContext)
452 InUnsafe = true;
453 else
454 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
456 loc = l;
458 if (ReturnType == TypeManager.void_type)
459 ReturnType = null;
462 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
463 Type return_type, int code_flags, bool is_constructor)
464 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
468 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
469 Type return_type, int code_flags)
470 : this (tc, tc, l, ig, return_type, code_flags, false)
474 public FlowBranching CurrentBranching {
475 get {
476 return current_flow_branching;
480 public bool HaveCaptureInfo {
481 get {
482 return capture_context != null;
486 // <summary>
487 // Starts a new code branching. This inherits the state of all local
488 // variables and parameters from the current branching.
489 // </summary>
490 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
492 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
493 return current_flow_branching;
496 // <summary>
497 // Starts a new code branching for block `block'.
498 // </summary>
499 public FlowBranching StartFlowBranching (Block block)
501 FlowBranching.BranchingType type;
503 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
504 type = FlowBranching.BranchingType.SwitchSection;
505 else
506 type = FlowBranching.BranchingType.Block;
508 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
509 return current_flow_branching;
512 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
514 FlowBranchingException branching = new FlowBranchingException (
515 CurrentBranching, stmt);
516 current_flow_branching = branching;
517 return branching;
520 // <summary>
521 // Ends a code branching. Merges the state of locals and parameters
522 // from all the children of the ending branching.
523 // </summary>
524 public FlowBranching.UsageVector DoEndFlowBranching ()
526 FlowBranching old = current_flow_branching;
527 current_flow_branching = current_flow_branching.Parent;
529 return current_flow_branching.MergeChild (old);
532 // <summary>
533 // Ends a code branching. Merges the state of locals and parameters
534 // from all the children of the ending branching.
535 // </summary>
536 public FlowBranching.Reachability EndFlowBranching ()
538 FlowBranching.UsageVector vector = DoEndFlowBranching ();
540 return vector.Reachability;
543 // <summary>
544 // Kills the current code branching. This throws away any changed state
545 // information and should only be used in case of an error.
546 // </summary>
547 public void KillFlowBranching ()
549 current_flow_branching = current_flow_branching.Parent;
552 public void CaptureVariable (LocalInfo li)
554 capture_context.AddLocal (CurrentAnonymousMethod, li);
555 li.IsCaptured = true;
558 public void CaptureParameter (string name, Type t, int idx)
561 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
565 // Use to register a field as captured
567 public void CaptureField (FieldExpr fe)
569 capture_context.AddField (fe);
573 // Whether anonymous methods have captured variables
575 public bool HaveCapturedVariables ()
577 if (capture_context != null)
578 return capture_context.HaveCapturedVariables;
579 return false;
583 // Whether anonymous methods have captured fields or this.
585 public bool HaveCapturedFields ()
587 if (capture_context != null)
588 return capture_context.HaveCapturedFields;
589 return false;
593 // Emits the instance pointer for the host method
595 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
597 if (capture_context != null)
598 capture_context.EmitMethodHostInstance (target, am);
599 else if (IsStatic)
600 target.ig.Emit (OpCodes.Ldnull);
601 else
602 target.ig.Emit (OpCodes.Ldarg_0);
606 // Returns whether the `local' variable has been captured by an anonymous
607 // method
609 public bool IsCaptured (LocalInfo local)
611 return capture_context.IsCaptured (local);
614 public bool IsParameterCaptured (string name)
616 if (capture_context != null)
617 return capture_context.IsParameterCaptured (name);
618 return false;
621 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
623 if (capture_context != null)
624 capture_context.EmitHelperClasses (this);
625 b.EmitMeta (this);
627 if (HasReturnLabel)
628 ReturnLabel = ig.DefineLabel ();
632 // Here until we can fix the problem with Mono.CSharp.Switch, which
633 // currently can not cope with ig == null during resolve (which must
634 // be fixed for switch statements to work on anonymous methods).
636 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
638 if (block == null)
639 return;
641 bool unreachable;
643 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
644 EmitMeta (block, ip);
646 current_phase = Phase.Emitting;
647 EmitResolvedTopBlock (block, unreachable);
651 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
652 InternalParameters ip, Location loc, out bool unreachable)
654 current_phase = Phase.Resolving;
656 unreachable = false;
658 capture_context = block.CaptureContext;
660 if (!Location.IsNull (loc))
661 CurrentFile = loc.File;
663 #if PRODUCTION
664 try {
665 #endif
666 int errors = Report.Errors;
668 block.ResolveMeta (block, this, ip);
671 if (Report.Errors == errors){
672 bool old_do_flow_analysis = DoFlowAnalysis;
673 DoFlowAnalysis = true;
675 if (anonymous_method_host != null)
676 current_flow_branching = FlowBranching.CreateBranching (
677 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
678 block, loc);
679 else
680 current_flow_branching = FlowBranching.CreateBranching (
681 null, FlowBranching.BranchingType.Block, block, loc);
683 if (!block.Resolve (this)) {
684 current_flow_branching = null;
685 DoFlowAnalysis = old_do_flow_analysis;
686 return false;
689 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
690 current_flow_branching = null;
692 DoFlowAnalysis = old_do_flow_analysis;
694 if (reachability.AlwaysReturns ||
695 reachability.AlwaysThrows ||
696 reachability.IsUnreachable)
697 unreachable = true;
699 #if PRODUCTION
700 } catch (Exception e) {
701 Console.WriteLine ("Exception caught by the compiler while compiling:");
702 Console.WriteLine (" Block that caused the problem begin at: " + loc);
704 if (CurrentBlock != null){
705 Console.WriteLine (" Block being compiled: [{0},{1}]",
706 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
708 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
709 throw;
711 #endif
713 if (ReturnType != null && !unreachable){
714 if (!InIterator){
715 if (CurrentAnonymousMethod != null){
716 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
717 CurrentAnonymousMethod.Type);
718 } else {
719 Report.Error (161, loc, "Not all code paths return a value");
722 return false;
725 block.CompleteContexts ();
727 return true;
730 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
732 if (block != null)
733 block.Emit (this);
735 if (HasReturnLabel)
736 ig.MarkLabel (ReturnLabel);
738 if (return_value != null){
739 ig.Emit (OpCodes.Ldloc, return_value);
740 ig.Emit (OpCodes.Ret);
741 } else {
743 // If `HasReturnLabel' is set, then we already emitted a
744 // jump to the end of the method, so we must emit a `ret'
745 // there.
747 // Unfortunately, System.Reflection.Emit automatically emits
748 // a leave to the end of a finally block. This is a problem
749 // if no code is following the try/finally block since we may
750 // jump to a point after the end of the method.
751 // As a workaround, we're always creating a return label in
752 // this case.
755 if ((block != null) && block.IsDestructor) {
756 // Nothing to do; S.R.E automatically emits a leave.
757 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
758 if (ReturnType != null)
759 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
760 ig.Emit (OpCodes.Ret);
765 // Close pending helper classes if we are the toplevel
767 if (capture_context != null && capture_context.ParentToplevel == null)
768 capture_context.CloseHelperClasses ();
771 /// <summary>
772 /// This is called immediately before emitting an IL opcode to tell the symbol
773 /// writer to which source line this opcode belongs.
774 /// </summary>
775 public void Mark (Location loc, bool check_file)
777 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
778 return;
780 if (check_file && (CurrentFile != loc.File))
781 return;
783 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
786 public void DefineLocalVariable (string name, LocalBuilder builder)
788 if (CodeGen.SymbolWriter == null)
789 return;
791 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
794 /// <summary>
795 /// Returns a temporary storage for a variable of type t as
796 /// a local variable in the current body.
797 /// </summary>
798 public LocalBuilder GetTemporaryLocal (Type t)
800 LocalBuilder location = null;
802 if (temporary_storage != null){
803 object o = temporary_storage [t];
804 if (o != null){
805 if (o is ArrayList){
806 ArrayList al = (ArrayList) o;
808 for (int i = 0; i < al.Count; i++){
809 if (al [i] != null){
810 location = (LocalBuilder) al [i];
811 al [i] = null;
812 break;
815 } else
816 location = (LocalBuilder) o;
817 if (location != null)
818 return location;
822 return ig.DeclareLocal (t);
825 public void FreeTemporaryLocal (LocalBuilder b, Type t)
827 if (temporary_storage == null){
828 temporary_storage = new Hashtable ();
829 temporary_storage [t] = b;
830 return;
832 object o = temporary_storage [t];
833 if (o == null){
834 temporary_storage [t] = b;
835 return;
837 if (o is ArrayList){
838 ArrayList al = (ArrayList) o;
839 for (int i = 0; i < al.Count; i++){
840 if (al [i] == null){
841 al [i] = b;
842 return;
845 al.Add (b);
846 return;
848 ArrayList replacement = new ArrayList ();
849 replacement.Add (o);
850 temporary_storage.Remove (t);
851 temporary_storage [t] = replacement;
854 /// <summary>
855 /// Current loop begin and end labels.
856 /// </summary>
857 public Label LoopBegin, LoopEnd;
859 /// <summary>
860 /// Default target in a switch statement. Only valid if
861 /// InSwitch is true
862 /// </summary>
863 public Label DefaultTarget;
865 /// <summary>
866 /// If this is non-null, points to the current switch statement
867 /// </summary>
868 public Switch Switch;
870 /// <summary>
871 /// ReturnValue creates on demand the LocalBuilder for the
872 /// return value from the function. By default this is not
873 /// used. This is only required when returns are found inside
874 /// Try or Catch statements.
876 /// This method is typically invoked from the Emit phase, so
877 /// we allow the creation of a return label if it was not
878 /// requested during the resolution phase. Could be cleaned
879 /// up, but it would replicate a lot of logic in the Emit phase
880 /// of the code that uses it.
881 /// </summary>
882 public LocalBuilder TemporaryReturn ()
884 if (return_value == null){
885 return_value = ig.DeclareLocal (ReturnType);
886 if (!HasReturnLabel){
887 ReturnLabel = ig.DefineLabel ();
888 HasReturnLabel = true;
892 return return_value;
895 /// <summary>
896 /// This method is used during the Resolution phase to flag the
897 /// need to define the ReturnLabel
898 /// </summary>
899 public void NeedReturnLabel ()
901 if (current_phase != Phase.Resolving){
903 // The reason is that the `ReturnLabel' is declared between
904 // resolution and emission
906 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
909 if (!InIterator && !HasReturnLabel)
910 HasReturnLabel = true;
914 // Creates a field `name' with the type `t' on the proxy class
916 public FieldBuilder MapVariable (string name, Type t)
918 if (InIterator)
919 return CurrentIterator.MapVariable ("v_", name, t);
921 throw new Exception ("MapVariable for an unknown state");
924 public Expression RemapParameter (int idx)
926 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
927 fe.InstanceExpression = new ProxyInstance ();
928 return fe.DoResolve (this);
931 public Expression RemapParameterLValue (int idx, Expression right_side)
933 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
934 fe.InstanceExpression = new ProxyInstance ();
935 return fe.DoResolveLValue (this, right_side);
939 // Emits the proper object to address fields on a remapped
940 // variable/parameter to field in anonymous-method/iterator proxy classes.
942 public void EmitThis ()
944 ig.Emit (OpCodes.Ldarg_0);
945 if (InIterator){
946 if (!IsStatic){
947 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
948 if (TypeManager.IsValueType (this_field.FieldType))
949 ig.Emit (OpCodes.Ldflda, this_field);
950 else
951 ig.Emit (OpCodes.Ldfld, this_field);
953 } else if (capture_context != null && CurrentAnonymousMethod != null){
954 ScopeInfo si = CurrentAnonymousMethod.Scope;
955 while (si != null){
956 if (si.ParentLink != null)
957 ig.Emit (OpCodes.Ldfld, si.ParentLink);
958 if (si.THIS != null){
959 ig.Emit (OpCodes.Ldfld, si.THIS);
960 break;
962 si = si.ParentScope;
968 // Emits the code necessary to load the instance required
969 // to access the captured LocalInfo
971 public void EmitCapturedVariableInstance (LocalInfo li)
973 if (RemapToProxy){
974 ig.Emit (OpCodes.Ldarg_0);
975 return;
978 if (capture_context == null)
979 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
981 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
984 public void EmitParameter (string name)
986 capture_context.EmitParameter (this, name);
989 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
991 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
994 public void EmitAddressOfParameter (string name)
996 capture_context.EmitAddressOfParameter (this, name);
999 public Expression GetThis (Location loc)
1001 This my_this;
1002 if (CurrentBlock != null)
1003 my_this = new This (CurrentBlock, loc);
1004 else
1005 my_this = new This (loc);
1007 if (!my_this.ResolveBase (this))
1008 my_this = null;
1010 return my_this;
1015 public abstract class CommonAssemblyModulClass: Attributable {
1016 protected CommonAssemblyModulClass ():
1017 base (null)
1021 public void AddAttributes (ArrayList attrs)
1023 if (OptAttributes == null) {
1024 OptAttributes = new Attributes (attrs);
1025 return;
1027 OptAttributes.AddAttributes (attrs);
1028 OptAttributes.CheckTargets (this);
1031 public virtual void Emit (TypeContainer tc)
1033 if (OptAttributes == null)
1034 return;
1036 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1037 OptAttributes.Emit (ec, this);
1040 protected Attribute GetClsCompliantAttribute ()
1042 if (OptAttributes == null)
1043 return null;
1045 EmitContext temp_ec = new EmitContext (new RootTypes (), Mono.CSharp.Location.Null, null, null, 0, false);
1046 Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1047 if (a != null) {
1048 a.Resolve (temp_ec);
1050 return a;
1054 public class AssemblyClass: CommonAssemblyModulClass {
1055 // TODO: make it private and move all builder based methods here
1056 public AssemblyBuilder Builder;
1057 bool is_cls_compliant;
1059 ListDictionary declarative_security;
1061 static string[] attribute_targets = new string [] { "assembly" };
1063 public AssemblyClass (): base ()
1065 is_cls_compliant = false;
1068 public bool IsClsCompliant {
1069 get {
1070 return is_cls_compliant;
1074 public override AttributeTargets AttributeTargets {
1075 get {
1076 return AttributeTargets.Assembly;
1080 public override bool IsClsCompliaceRequired(DeclSpace ds)
1082 return is_cls_compliant;
1085 public void ResolveClsCompliance ()
1087 Attribute a = GetClsCompliantAttribute ();
1088 if (a == null)
1089 return;
1091 is_cls_compliant = a.GetClsCompliantAttributeValue (null);
1094 // fix bug #56621
1095 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1097 try {
1098 // check for possible ECMA key
1099 if (strongNameBlob.Length == 16) {
1100 // will be rejected if not "the" ECMA key
1101 an.SetPublicKey (strongNameBlob);
1103 else {
1104 // take it, with or without, a private key
1105 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1106 // and make sure we only feed the public part to Sys.Ref
1107 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1109 // AssemblyName.SetPublicKey requires an additional header
1110 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1112 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1113 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1114 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1115 an.SetPublicKey (encodedPublicKey);
1118 catch (Exception) {
1119 Report.Error (1548, "Could not strongname the assembly. File `" +
1120 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1121 Environment.Exit (1);
1125 public AssemblyName GetAssemblyName (string name, string output)
1127 if (OptAttributes != null) {
1128 foreach (Attribute a in OptAttributes.Attrs) {
1129 if (a.Target != AttributeTargets.Assembly)
1130 continue;
1131 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1132 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1133 // are loaded yet.
1134 switch (a.Name) {
1135 case "AssemblyKeyFile":
1136 case "AssemblyKeyFileAttribute":
1137 case "System.Reflection.AssemblyKeyFileAttribute":
1138 if (RootContext.StrongNameKeyFile != null) {
1139 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1140 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1142 else {
1143 string value = a.GetString ();
1144 if (value != String.Empty)
1145 RootContext.StrongNameKeyFile = value;
1147 break;
1148 case "AssemblyKeyName":
1149 case "AssemblyKeyNameAttribute":
1150 case "System.Reflection.AssemblyKeyNameAttribute":
1151 if (RootContext.StrongNameKeyContainer != null) {
1152 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1153 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1155 else {
1156 string value = a.GetString ();
1157 if (value != String.Empty)
1158 RootContext.StrongNameKeyContainer = value;
1160 break;
1161 case "AssemblyDelaySign":
1162 case "AssemblyDelaySignAttribute":
1163 case "System.Reflection.AssemblyDelaySignAttribute":
1164 RootContext.StrongNameDelaySign = a.GetBoolean ();
1165 break;
1170 AssemblyName an = new AssemblyName ();
1171 an.Name = Path.GetFileNameWithoutExtension (name);
1173 // note: delay doesn't apply when using a key container
1174 if (RootContext.StrongNameKeyContainer != null) {
1175 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1176 return an;
1179 // strongname is optional
1180 if (RootContext.StrongNameKeyFile == null)
1181 return an;
1183 string AssemblyDir = Path.GetDirectoryName (output);
1185 // the StrongName key file may be relative to (a) the compiled
1186 // file or (b) to the output assembly. See bugzilla #55320
1187 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1189 // (a) relative to the compiled file
1190 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1191 bool exist = File.Exists (filename);
1192 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1193 // (b) relative to the outputed assembly
1194 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1195 exist = File.Exists (filename);
1198 if (exist) {
1199 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1200 byte[] snkeypair = new byte [fs.Length];
1201 fs.Read (snkeypair, 0, snkeypair.Length);
1203 if (RootContext.StrongNameDelaySign) {
1204 // delayed signing - DO NOT include private key
1205 SetPublicKey (an, snkeypair);
1207 else {
1208 // no delay so we make sure we have the private key
1209 try {
1210 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1211 an.KeyPair = new StrongNameKeyPair (snkeypair);
1213 catch (CryptographicException) {
1214 if (snkeypair.Length == 16) {
1215 // error # is different for ECMA key
1216 Report.Error (1606, "Could not strongname the assembly. " +
1217 "ECMA key can only be used to delay-sign assemblies");
1219 else {
1220 Report.Error (1548, "Could not strongname the assembly. File `" +
1221 RootContext.StrongNameKeyFile +
1222 "' doesn't have a private key.");
1224 Environment.Exit (1);
1229 else {
1230 Report.Error (1548, "Could not strongname the assembly. File `" +
1231 RootContext.StrongNameKeyFile + "' not found.");
1232 Environment.Exit (1);
1234 return an;
1237 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1239 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1240 if (declarative_security == null)
1241 declarative_security = new ListDictionary ();
1243 a.ExtractSecurityPermissionSet (declarative_security);
1244 return;
1247 Builder.SetCustomAttribute (customBuilder);
1250 public override void Emit (TypeContainer tc)
1252 base.Emit (tc);
1254 if (declarative_security != null) {
1256 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1257 object builder_instance = Builder;
1259 try {
1260 // Microsoft runtime hacking
1261 if (add_permission == null) {
1262 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1263 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1265 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1266 builder_instance = fi.GetValue (Builder);
1269 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1270 declarative_security [SecurityAction.RequestOptional],
1271 declarative_security [SecurityAction.RequestRefuse] };
1272 add_permission.Invoke (builder_instance, args);
1274 catch {
1275 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1280 public override string[] ValidAttributeTargets {
1281 get {
1282 return attribute_targets;
1287 public class ModuleClass: CommonAssemblyModulClass {
1288 // TODO: make it private and move all builder based methods here
1289 public ModuleBuilder Builder;
1290 bool m_module_is_unsafe;
1292 static string[] attribute_targets = new string [] { "module" };
1294 public ModuleClass (bool is_unsafe)
1296 m_module_is_unsafe = is_unsafe;
1299 public override AttributeTargets AttributeTargets {
1300 get {
1301 return AttributeTargets.Module;
1305 public override bool IsClsCompliaceRequired(DeclSpace ds)
1307 return CodeGen.Assembly.IsClsCompliant;
1310 public override void Emit (TypeContainer tc)
1312 base.Emit (tc);
1314 if (!m_module_is_unsafe)
1315 return;
1317 if (TypeManager.unverifiable_code_ctor == null) {
1318 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1319 return;
1322 ApplyAttributeBuilder (null, new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1325 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1327 if (a != null && a.Type == TypeManager.cls_compliant_attribute_type) {
1328 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1331 Builder.SetCustomAttribute (customBuilder);
1334 public override string[] ValidAttributeTargets {
1335 get {
1336 return attribute_targets;