* TabControl.cs: Fix typo, emilinates an unneeded expose event.
[mono.git] / mcs / mcs / codegen.cs
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;
21
22 using Mono.Security.Cryptography;
23
24 namespace Mono.CSharp {
25
26         /// <summary>
27         ///    Code generator class.
28         /// </summary>
29         public class CodeGen {
30                 static AppDomain current_domain;
31                 static public SymbolWriter SymbolWriter;
32
33                 public static AssemblyClass Assembly;
34                 public static ModuleClass Module;
35
36                 static CodeGen ()
37                 {
38                         Reset ();
39                 }
40
41                 public static void Reset ()
42                 {
43                         Assembly = new AssemblyClass ();
44                         Module = new ModuleClass (RootContext.Unsafe);
45                 }
46
47                 public static string Basename (string name)
48                 {
49                         int pos = name.LastIndexOf ('/');
50
51                         if (pos != -1)
52                                 return name.Substring (pos + 1);
53
54                         pos = name.LastIndexOf ('\\');
55                         if (pos != -1)
56                                 return name.Substring (pos + 1);
57
58                         return name;
59                 }
60
61                 public static string Dirname (string name)
62                 {
63                         int pos = name.LastIndexOf ('/');
64
65                         if (pos != -1)
66                                 return name.Substring (0, pos);
67
68                         pos = name.LastIndexOf ('\\');
69                         if (pos != -1)
70                                 return name.Substring (0, pos);
71
72                         return ".";
73                 }
74
75                 static string TrimExt (string name)
76                 {
77                         int pos = name.LastIndexOf ('.');
78
79                         return name.Substring (0, pos);
80                 }
81
82                 static public string FileName;
83
84                 //
85                 // Initializes the symbol writer
86                 //
87                 static void InitializeSymbolWriter (string filename)
88                 {
89                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
90
91                         //
92                         // If we got an ISymbolWriter instance, initialize it.
93                         //
94                         if (SymbolWriter == null) {
95                                 Report.Warning (
96                                         -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.");
97                                 return;
98                         }
99                 }
100
101                 //
102                 // Initializes the code generator variables
103                 //
104                 static public bool Init (string name, string output, bool want_debugging_support)
105                 {
106                         FileName = output;
107                         AssemblyName an = Assembly.GetAssemblyName (name, output);
108                         if (an == null)
109                                 return false;
110
111                         if (an.KeyPair != null) {
112                                 // If we are going to strong name our assembly make
113                                 // sure all its refs are strong named
114                                 foreach (Assembly a in TypeManager.GetAssemblies ()) {
115                                         AssemblyName ref_name = a.GetName ();
116                                         byte [] b = ref_name.GetPublicKeyToken ();
117                                         if (b == null || b.Length == 0) {
118                                                 Report.Warning (1577, "Assembly generation failed " +
119                                                                 "-- Referenced assembly '" +
120                                                                 ref_name.Name +
121                                                                 "' does not have a strong name.");
122                                                 //Environment.Exit (1);
123                                         }
124                                 }
125                         }
126                         
127                         current_domain = AppDomain.CurrentDomain;
128
129                         try {
130                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
131                                         AssemblyBuilderAccess.Save, Dirname (name));
132                         }
133                         catch (ArgumentException) {
134                                 // specified key may not be exportable outside it's container
135                                 if (RootContext.StrongNameKeyContainer != null) {
136                                         Report.Error (1548, "Could not access the key inside the container `" +
137                                                 RootContext.StrongNameKeyContainer + "'.");
138                                         Environment.Exit (1);
139                                 }
140                                 return false;
141                         }
142                         catch (CryptographicException) {
143                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
144                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
145                                         Environment.Exit (1);
146                                 }
147                                 return false;
148                         }
149
150                         //
151                         // Pass a path-less name to DefineDynamicModule.  Wonder how
152                         // this copes with output in different directories then.
153                         // FIXME: figure out how this copes with --output /tmp/blah
154                         //
155                         // If the third argument is true, the ModuleBuilder will dynamically
156                         // load the default symbol writer.
157                         //
158                         Module.Builder = Assembly.Builder.DefineDynamicModule (
159                                 Basename (name), Basename (output), false);
160
161                         if (want_debugging_support)
162                                 InitializeSymbolWriter (output);
163
164                         return true;
165                 }
166
167                 static public void Save (string name)
168                 {
169                         try {
170                                 Assembly.Builder.Save (Basename (name));
171                         }
172                         catch (COMException) {
173                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
174                                         throw;
175
176                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
177                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
178                                         RootContext.StrongNameKeyFile +
179                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
180                         }
181                         catch (System.IO.IOException io) {
182                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
183                         }
184                         catch (System.UnauthorizedAccessException ua) {
185                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
186                         }
187
188                         if (SymbolWriter != null)
189                                 SymbolWriter.WriteSymbolFile ();
190                 }
191         }
192
193         //
194         // Provides "local" store across code that can yield: locals
195         // or fields, notice that this should not be used by anonymous
196         // methods to create local storage, those only require
197         // variable mapping.
198         //
199         public class VariableStorage {
200                 FieldBuilder fb;
201                 LocalBuilder local;
202                 
203                 static int count;
204                 
205                 public VariableStorage (EmitContext ec, Type t)
206                 {
207                         count++;
208                         if (ec.InIterator)
209                                 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
210                         else
211                                 local = ec.ig.DeclareLocal (t);
212                 }
213
214                 public void EmitThis (ILGenerator ig)
215                 {
216                         if (fb != null)
217                                 ig.Emit (OpCodes.Ldarg_0);
218                 }
219
220                 public void EmitStore (ILGenerator ig)
221                 {
222                         if (fb == null)
223                                 ig.Emit (OpCodes.Stloc, local);
224                         else
225                                 ig.Emit (OpCodes.Stfld, fb);
226                 }
227
228                 public void EmitLoad (ILGenerator ig)
229                 {
230                         if (fb == null)
231                                 ig.Emit (OpCodes.Ldloc, local);
232                         else 
233                                 ig.Emit (OpCodes.Ldfld, fb);
234                 }
235
236                 public void EmitLoadAddress (ILGenerator ig)
237                 {
238                         if (fb == null)
239                                 ig.Emit (OpCodes.Ldloca, local);
240                         else 
241                                 ig.Emit (OpCodes.Ldflda, fb);
242                 }
243                 
244                 public void EmitCall (ILGenerator ig, MethodInfo mi)
245                 {
246                         // FIXME : we should handle a call like tostring
247                         // here, where boxing is needed. However, we will
248                         // never encounter that with the current usage.
249                         
250                         bool value_type_call;
251                         EmitThis (ig);
252                         if (fb == null) {
253                                 value_type_call = local.LocalType.IsValueType;
254                                 
255                                 if (value_type_call)
256                                         ig.Emit (OpCodes.Ldloca, local);
257                                 else
258                                         ig.Emit (OpCodes.Ldloc, local);
259                         } else {
260                                 value_type_call = fb.FieldType.IsValueType;
261                                 
262                                 if (value_type_call)
263                                         ig.Emit (OpCodes.Ldflda, fb);
264                                 else
265                                         ig.Emit (OpCodes.Ldfld, fb);
266                         }
267                         
268                         ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
269                 }
270         }
271
272         /// <summary>
273         ///   An Emit Context is created for each body of code (from methods,
274         ///   properties bodies, indexer bodies or constructor bodies)
275         /// </summary>
276         public class EmitContext {
277                 public DeclSpace DeclSpace;
278                 public DeclSpace TypeContainer;
279                 public ILGenerator   ig;
280
281                 /// <summary>
282                 ///   This variable tracks the `checked' state of the compilation,
283                 ///   it controls whether we should generate code that does overflow
284                 ///   checking, or if we generate code that ignores overflows.
285                 ///
286                 ///   The default setting comes from the command line option to generate
287                 ///   checked or unchecked code plus any source code changes using the
288                 ///   checked/unchecked statements or expressions.   Contrast this with
289                 ///   the ConstantCheckState flag.
290                 /// </summary>
291                 
292                 public bool CheckState;
293
294                 /// <summary>
295                 ///   The constant check state is always set to `true' and cant be changed
296                 ///   from the command line.  The source code can change this setting with
297                 ///   the `checked' and `unchecked' statements and expressions. 
298                 /// </summary>
299                 public bool ConstantCheckState;
300
301                 /// <summary>
302                 ///   Whether we are emitting code inside a static or instance method
303                 /// </summary>
304                 public bool IsStatic;
305
306                 /// <summary>
307                 ///   Whether the actual created method is static or instance method.
308                 ///   Althoug the method might be declared as `static', if an anonymous
309                 ///   method is involved, we might turn this into an instance method.
310                 ///
311                 ///   So this reflects the low-level staticness of the method, while
312                 ///   IsStatic represents the semantic, high-level staticness.
313                 /// </summary>
314                 public bool MethodIsStatic;
315
316                 /// <summary>
317                 ///   Whether we are emitting a field initializer
318                 /// </summary>
319                 public bool IsFieldInitializer;
320
321                 /// <summary>
322                 ///   The value that is allowed to be returned or NULL if there is no
323                 ///   return type.
324                 /// </summary>
325                 public Type ReturnType;
326
327                 /// <summary>
328                 ///   Points to the Type (extracted from the TypeContainer) that
329                 ///   declares this body of code
330                 /// </summary>
331                 public Type ContainerType;
332                 
333                 /// <summary>
334                 ///   Whether this is generating code for a constructor
335                 /// </summary>
336                 public bool IsConstructor;
337
338                 /// <summary>
339                 ///   Whether we're control flow analysis enabled
340                 /// </summary>
341                 public bool DoFlowAnalysis;
342                 
343                 /// <summary>
344                 ///   Keeps track of the Type to LocalBuilder temporary storage created
345                 ///   to store structures (used to compute the address of the structure
346                 ///   value on structure method invocations)
347                 /// </summary>
348                 public Hashtable temporary_storage;
349
350                 public Block CurrentBlock;
351
352                 public int CurrentFile;
353
354                 /// <summary>
355                 ///   The location where we store the return value.
356                 /// </summary>
357                 LocalBuilder return_value;
358
359                 /// <summary>
360                 ///   The location where return has to jump to return the
361                 ///   value
362                 /// </summary>
363                 public Label ReturnLabel;
364
365                 /// <summary>
366                 ///   If we already defined the ReturnLabel
367                 /// </summary>
368                 public bool HasReturnLabel;
369
370                 /// <summary>
371                 ///   Whether we are inside an iterator block.
372                 /// </summary>
373                 public bool InIterator;
374
375                 public bool IsLastStatement;
376
377                 /// <summary>
378                 ///   Whether remapping of locals, parameters and fields is turned on.
379                 ///   Used by iterators and anonymous methods.
380                 /// </summary>
381                 public bool RemapToProxy;
382
383                 /// <summary>
384                 ///  Whether we are inside an unsafe block
385                 /// </summary>
386                 public bool InUnsafe;
387
388                 /// <summary>
389                 ///  Whether we are in a `fixed' initialization
390                 /// </summary>
391                 public bool InFixedInitializer;
392
393                 /// <summary>
394                 ///  Whether we are inside an anonymous method.
395                 /// </summary>
396                 public AnonymousMethod CurrentAnonymousMethod;
397                 
398                 /// <summary>
399                 ///   Location for this EmitContext
400                 /// </summary>
401                 public Location loc;
402
403                 /// <summary>
404                 ///   Inside an enum definition, we do not resolve enumeration values
405                 ///   to their enumerations, but rather to the underlying type/value
406                 ///   This is so EnumVal + EnumValB can be evaluated.
407                 ///
408                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
409                 ///   we relax the rules
410                 /// </summary>
411                 public bool InEnumContext;
412
413                 /// <summary>
414                 ///   Anonymous methods can capture local variables and fields,
415                 ///   this object tracks it.  It is copied from the TopLevelBlock
416                 ///   field.
417                 /// </summary>
418                 public CaptureContext capture_context;
419
420                 /// <summary>
421                 /// Trace when method is called and is obsolete then this member suppress message
422                 /// when call is inside next [Obsolete] method or type.
423                 /// </summary>
424                 public bool TestObsoleteMethodUsage = true;
425
426                 /// <summary>
427                 ///    The current iterator
428                 /// </summary>
429                 public Iterator CurrentIterator;
430
431                 /// <summary>
432                 ///    Whether we are in the resolving stage or not
433                 /// </summary>
434                 enum Phase {
435                         Created,
436                         Resolving,
437                         Emitting
438                 }
439                 
440                 Phase current_phase;
441                 FlowBranching current_flow_branching;
442                 
443                 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
444                                     Type return_type, int code_flags, bool is_constructor)
445                 {
446                         this.ig = ig;
447
448                         TypeContainer = parent;
449                         DeclSpace = ds;
450                         CheckState = RootContext.Checked;
451                         ConstantCheckState = true;
452
453                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
454                         MethodIsStatic = IsStatic;
455                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
456                         RemapToProxy = InIterator;
457                         ReturnType = return_type;
458                         IsConstructor = is_constructor;
459                         CurrentBlock = null;
460                         CurrentFile = 0;
461                         current_phase = Phase.Created;
462                         
463                         if (parent != null){
464                                 // Can only be null for the ResolveType contexts.
465                                 ContainerType = parent.TypeBuilder;
466                                 if (parent.UnsafeContext)
467                                         InUnsafe = true;
468                                 else
469                                         InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
470                         }
471                         loc = l;
472
473                         if (ReturnType == TypeManager.void_type)
474                                 ReturnType = null;
475                 }
476
477                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
478                                     Type return_type, int code_flags, bool is_constructor)
479                         : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
480                 {
481                 }
482
483                 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
484                                     Type return_type, int code_flags)
485                         : this (tc, tc, l, ig, return_type, code_flags, false)
486                 {
487                 }
488
489                 public FlowBranching CurrentBranching {
490                         get {
491                                 return current_flow_branching;
492                         }
493                 }
494
495                 public bool HaveCaptureInfo {
496                         get {
497                                 return capture_context != null;
498                         }
499                 }
500
501                 // <summary>
502                 //   Starts a new code branching.  This inherits the state of all local
503                 //   variables and parameters from the current branching.
504                 // </summary>
505                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
506                 {
507                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
508                         return current_flow_branching;
509                 }
510
511                 // <summary>
512                 //   Starts a new code branching for block `block'.
513                 // </summary>
514                 public FlowBranching StartFlowBranching (Block block)
515                 {
516                         FlowBranching.BranchingType type;
517
518                         if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
519                                 type = FlowBranching.BranchingType.SwitchSection;
520                         else
521                                 type = FlowBranching.BranchingType.Block;
522
523                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
524                         return current_flow_branching;
525                 }
526
527                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
528                 {
529                         FlowBranchingException branching = new FlowBranchingException (
530                                 CurrentBranching, stmt);
531                         current_flow_branching = branching;
532                         return branching;
533                 }
534
535                 // <summary>
536                 //   Ends a code branching.  Merges the state of locals and parameters
537                 //   from all the children of the ending branching.
538                 // </summary>
539                 public FlowBranching.UsageVector DoEndFlowBranching ()
540                 {
541                         FlowBranching old = current_flow_branching;
542                         current_flow_branching = current_flow_branching.Parent;
543
544                         return current_flow_branching.MergeChild (old);
545                 }
546
547                 // <summary>
548                 //   Ends a code branching.  Merges the state of locals and parameters
549                 //   from all the children of the ending branching.
550                 // </summary>
551                 public FlowBranching.Reachability EndFlowBranching ()
552                 {
553                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
554
555                         return vector.Reachability;
556                 }
557
558                 // <summary>
559                 //   Kills the current code branching.  This throws away any changed state
560                 //   information and should only be used in case of an error.
561                 // </summary>
562                 public void KillFlowBranching ()
563                 {
564                         current_flow_branching = current_flow_branching.Parent;
565                 }
566
567                 public void CaptureVariable (LocalInfo li)
568                 {
569                         capture_context.AddLocal (CurrentAnonymousMethod, li);
570                         li.IsCaptured = true;
571                 }
572
573                 public void CaptureParameter (string name, Type t, int idx)
574                 {
575                         capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
576                 }
577
578                 public void CaptureThis ()
579                 {
580                         capture_context.CaptureThis ();
581                 }
582                 
583                 
584                 //
585                 // Use to register a field as captured
586                 //
587                 public void CaptureField (FieldExpr fe)
588                 {
589                         capture_context.AddField (fe);
590                 }
591
592                 //
593                 // Whether anonymous methods have captured variables
594                 //
595                 public bool HaveCapturedVariables ()
596                 {
597                         if (capture_context != null)
598                                 return capture_context.HaveCapturedVariables;
599                         return false;
600                 }
601
602                 //
603                 // Whether anonymous methods have captured fields or this.
604                 //
605                 public bool HaveCapturedFields ()
606                 {
607                         if (capture_context != null)
608                                 return capture_context.HaveCapturedFields;
609                         return false;
610                 }
611
612                 //
613                 // Emits the instance pointer for the host method
614                 //
615                 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
616                 {
617                         if (capture_context != null)
618                                 capture_context.EmitMethodHostInstance (target, am);
619                         else if (IsStatic)
620                                 target.ig.Emit (OpCodes.Ldnull);
621                         else
622                                 target.ig.Emit (OpCodes.Ldarg_0);
623                 }
624
625                 //
626                 // Returns whether the `local' variable has been captured by an anonymous
627                 // method
628                 //
629                 public bool IsCaptured (LocalInfo local)
630                 {
631                         return capture_context.IsCaptured (local);
632                 }
633
634                 public bool IsParameterCaptured (string name)
635                 {
636                         if (capture_context != null)
637                                 return capture_context.IsParameterCaptured (name);
638                         return false;
639                 }
640                 
641                 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
642                 {
643                         if (capture_context != null)
644                                 capture_context.EmitAnonymousHelperClasses (this);
645                         b.EmitMeta (this);
646
647                         if (HasReturnLabel)
648                                 ReturnLabel = ig.DefineLabel ();
649                 }
650
651                 //
652                 // Here until we can fix the problem with Mono.CSharp.Switch, which
653                 // currently can not cope with ig == null during resolve (which must
654                 // be fixed for switch statements to work on anonymous methods).
655                 //
656                 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
657                 {
658                         if (block == null)
659                                 return;
660                         
661                         bool unreachable;
662                         
663                         if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
664                                 EmitMeta (block, ip);
665
666                                 current_phase = Phase.Emitting;
667                                 EmitResolvedTopBlock (block, unreachable);
668                         }
669                 }
670
671                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
672                                              InternalParameters ip, Location loc, out bool unreachable)
673                 {
674                         current_phase = Phase.Resolving;
675                         
676                         unreachable = false;
677
678                         capture_context = block.CaptureContext;
679                         
680                         if (!Location.IsNull (loc))
681                                 CurrentFile = loc.File;
682
683 #if PRODUCTION
684                         try {
685 #endif
686                                 int errors = Report.Errors;
687
688                                 block.ResolveMeta (block, this, ip);
689                                 if (Report.Errors != errors)
690                                         return false;
691
692                                         bool old_do_flow_analysis = DoFlowAnalysis;
693                                         DoFlowAnalysis = true;
694
695                                         if (anonymous_method_host != null)
696                                                 current_flow_branching = FlowBranching.CreateBranching (
697                                                 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
698                                                 block, loc);
699                                         else 
700                                                 current_flow_branching = FlowBranching.CreateBranching (
701                                                         null, FlowBranching.BranchingType.Block, block, loc);
702
703                                         if (!block.Resolve (this)) {
704                                                 current_flow_branching = null;
705                                                 DoFlowAnalysis = old_do_flow_analysis;
706                                                 return false;
707                                         }
708
709                                         FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
710                                         current_flow_branching = null;
711                                         
712                                         DoFlowAnalysis = old_do_flow_analysis;
713
714                                         if (reachability.AlwaysReturns ||
715                                             reachability.AlwaysThrows ||
716                                             reachability.IsUnreachable)
717                                                 unreachable = true;
718 #if PRODUCTION
719                         } catch (Exception e) {
720                                         Console.WriteLine ("Exception caught by the compiler while compiling:");
721                                         Console.WriteLine ("   Block that caused the problem begin at: " + loc);
722                                         
723                                         if (CurrentBlock != null){
724                                                 Console.WriteLine ("                     Block being compiled: [{0},{1}]",
725                                                                    CurrentBlock.StartLocation, CurrentBlock.EndLocation);
726                                         }
727                                         Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
728                                         throw;
729                         }
730 #endif
731
732                         if (ReturnType != null && !unreachable){
733                                 if (!InIterator){
734                                         if (CurrentAnonymousMethod != null){
735                                                 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
736                                                               CurrentAnonymousMethod.Type);
737                                         } else {
738                                                 Report.Error (161, loc, "Not all code paths return a value");
739                                         }
740                                         
741                                         return false;
742                                 }
743                         }
744                         block.CompleteContexts ();
745
746                         return true;
747                 }
748
749                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
750                 {
751                         if (block != null)
752                                 block.Emit (this);
753                         
754                         if (HasReturnLabel)
755                                 ig.MarkLabel (ReturnLabel);
756                         
757                         if (return_value != null){
758                                 ig.Emit (OpCodes.Ldloc, return_value);
759                                 ig.Emit (OpCodes.Ret);
760                         } else {
761                                 //
762                                 // If `HasReturnLabel' is set, then we already emitted a
763                                 // jump to the end of the method, so we must emit a `ret'
764                                 // there.
765                                 //
766                                 // Unfortunately, System.Reflection.Emit automatically emits
767                                 // a leave to the end of a finally block.  This is a problem
768                                 // if no code is following the try/finally block since we may
769                                 // jump to a point after the end of the method.
770                                 // As a workaround, we're always creating a return label in
771                                 // this case.
772                                 //
773
774                                 if ((block != null) && block.IsDestructor) {
775                                         // Nothing to do; S.R.E automatically emits a leave.
776                                 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
777                                         if (ReturnType != null)
778                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
779                                         ig.Emit (OpCodes.Ret);
780                                 }
781                         }
782
783                         //
784                         // Close pending helper classes if we are the toplevel
785                         //
786                         if (capture_context != null && capture_context.ParentToplevel == null)
787                                 capture_context.CloseAnonymousHelperClasses ();
788                 }
789
790                 /// <summary>
791                 ///   This is called immediately before emitting an IL opcode to tell the symbol
792                 ///   writer to which source line this opcode belongs.
793                 /// </summary>
794                 public void Mark (Location loc, bool check_file)
795                 {
796                         if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
797                                 return;
798
799                         if (check_file && (CurrentFile != loc.File))
800                                 return;
801
802                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
803                 }
804
805                 public void DefineLocalVariable (string name, LocalBuilder builder)
806                 {
807                         if (CodeGen.SymbolWriter == null)
808                                 return;
809
810                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
811                 }
812
813                 public void BeginScope ()
814                 {
815                         ig.BeginScope();
816
817                         if (CodeGen.SymbolWriter != null)
818                                 CodeGen.SymbolWriter.OpenScope(ig);
819                 }
820
821                 public void EndScope ()
822                 {
823                         ig.EndScope();
824
825                         if (CodeGen.SymbolWriter != null)
826                                 CodeGen.SymbolWriter.CloseScope(ig);
827                 }
828
829                 /// <summary>
830                 ///   Returns a temporary storage for a variable of type t as 
831                 ///   a local variable in the current body.
832                 /// </summary>
833                 public LocalBuilder GetTemporaryLocal (Type t)
834                 {
835                         LocalBuilder location = null;
836                         
837                         if (temporary_storage != null){
838                                 object o = temporary_storage [t];
839                                 if (o != null){
840                                         if (o is ArrayList){
841                                                 ArrayList al = (ArrayList) o;
842                                                 
843                                                 for (int i = 0; i < al.Count; i++){
844                                                         if (al [i] != null){
845                                                                 location = (LocalBuilder) al [i];
846                                                                 al [i] = null;
847                                                                 break;
848                                                         }
849                                                 }
850                                         } else
851                                                 location = (LocalBuilder) o;
852                                         if (location != null)
853                                                 return location;
854                                 }
855                         }
856                         
857                         return ig.DeclareLocal (t);
858                 }
859
860                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
861                 {
862                         if (temporary_storage == null){
863                                 temporary_storage = new Hashtable ();
864                                 temporary_storage [t] = b;
865                                 return;
866                         }
867                         object o = temporary_storage [t];
868                         if (o == null){
869                                 temporary_storage [t] = b;
870                                 return;
871                         }
872                         if (o is ArrayList){
873                                 ArrayList al = (ArrayList) o;
874                                 for (int i = 0; i < al.Count; i++){
875                                         if (al [i] == null){
876                                                 al [i] = b;
877                                                 return;
878                                         }
879                                 }
880                                 al.Add (b);
881                                 return;
882                         }
883                         ArrayList replacement = new ArrayList ();
884                         replacement.Add (o);
885                         temporary_storage.Remove (t);
886                         temporary_storage [t] = replacement;
887                 }
888
889                 /// <summary>
890                 ///   Current loop begin and end labels.
891                 /// </summary>
892                 public Label LoopBegin, LoopEnd;
893
894                 /// <summary>
895                 ///   Default target in a switch statement.   Only valid if
896                 ///   InSwitch is true
897                 /// </summary>
898                 public Label DefaultTarget;
899
900                 /// <summary>
901                 ///   If this is non-null, points to the current switch statement
902                 /// </summary>
903                 public Switch Switch;
904
905                 /// <summary>
906                 ///   ReturnValue creates on demand the LocalBuilder for the
907                 ///   return value from the function.  By default this is not
908                 ///   used.  This is only required when returns are found inside
909                 ///   Try or Catch statements.
910                 ///
911                 ///   This method is typically invoked from the Emit phase, so
912                 ///   we allow the creation of a return label if it was not
913                 ///   requested during the resolution phase.   Could be cleaned
914                 ///   up, but it would replicate a lot of logic in the Emit phase
915                 ///   of the code that uses it.
916                 /// </summary>
917                 public LocalBuilder TemporaryReturn ()
918                 {
919                         if (return_value == null){
920                                 return_value = ig.DeclareLocal (ReturnType);
921                                 if (!HasReturnLabel){
922                                         ReturnLabel = ig.DefineLabel ();
923                                         HasReturnLabel = true;
924                                 }
925                         }
926
927                         return return_value;
928                 }
929
930                 /// <summary>
931                 ///   This method is used during the Resolution phase to flag the
932                 ///   need to define the ReturnLabel
933                 /// </summary>
934                 public void NeedReturnLabel ()
935                 {
936                         if (current_phase != Phase.Resolving){
937                                 //
938                                 // The reason is that the `ReturnLabel' is declared between
939                                 // resolution and emission
940                                 // 
941                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
942                         }
943                         
944                         if (!InIterator && !HasReturnLabel) 
945                                 HasReturnLabel = true;
946                 }
947
948                 //
949                 // Creates a field `name' with the type `t' on the proxy class
950                 //
951                 public FieldBuilder MapVariable (string name, Type t)
952                 {
953                         if (InIterator)
954                                 return CurrentIterator.MapVariable ("v_", name, t);
955
956                         throw new Exception ("MapVariable for an unknown state");
957                 }
958
959                 public Expression RemapParameter (int idx)
960                 {
961                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
962                         fe.InstanceExpression = new ProxyInstance ();
963                         return fe.DoResolve (this);
964                 }
965
966                 public Expression RemapParameterLValue (int idx, Expression right_side)
967                 {
968                         FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
969                         fe.InstanceExpression = new ProxyInstance ();
970                         return fe.DoResolveLValue (this, right_side);
971                 }
972                 
973                 //
974                 // Emits the proper object to address fields on a remapped
975                 // variable/parameter to field in anonymous-method/iterator proxy classes.
976                 //
977                 public void EmitThis ()
978                 {
979                         ig.Emit (OpCodes.Ldarg_0);
980                         if (InIterator){
981                                 if (!IsStatic){
982                                         FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
983                                         if (TypeManager.IsValueType (this_field.FieldType))
984                                                 ig.Emit (OpCodes.Ldflda, this_field);
985                                         else
986                                                 ig.Emit (OpCodes.Ldfld, this_field);
987                                 } 
988                         } else if (capture_context != null && CurrentAnonymousMethod != null){
989                                 ScopeInfo si = CurrentAnonymousMethod.Scope;
990                                 while (si != null){
991                                         if (si.ParentLink != null)
992                                                 ig.Emit (OpCodes.Ldfld, si.ParentLink);
993                                         if (si.THIS != null){
994                                                 ig.Emit (OpCodes.Ldfld, si.THIS);
995                                                 break;
996                                         }
997                                         si = si.ParentScope;
998                                 }
999                         } 
1000                 }
1001
1002                 //
1003                 // Emits the code necessary to load the instance required
1004                 // to access the captured LocalInfo
1005                 //
1006                 public void EmitCapturedVariableInstance (LocalInfo li)
1007                 {
1008                         if (RemapToProxy){
1009                                 ig.Emit (OpCodes.Ldarg_0);
1010                                 return;
1011                         }
1012                         
1013                         if (capture_context == null)
1014                                 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
1015                         
1016                         capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
1017                 }
1018
1019                 public void EmitParameter (string name)
1020                 {
1021                         capture_context.EmitParameter (this, name);
1022                 }
1023
1024                 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
1025                 {
1026                         capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
1027                 }
1028
1029                 public void EmitAddressOfParameter (string name)
1030                 {
1031                         capture_context.EmitAddressOfParameter (this, name);
1032                 }
1033                 
1034                 public Expression GetThis (Location loc)
1035                 {
1036                         This my_this;
1037                         if (CurrentBlock != null)
1038                                 my_this = new This (CurrentBlock, loc);
1039                         else
1040                                 my_this = new This (loc);
1041
1042                         if (!my_this.ResolveBase (this))
1043                                 my_this = null;
1044
1045                         return my_this;
1046                 }
1047         }
1048
1049
1050         public abstract class CommonAssemblyModulClass: Attributable {
1051                 protected CommonAssemblyModulClass ():
1052                         base (null)
1053                 {
1054                 }
1055
1056                 public void AddAttributes (ArrayList attrs)
1057                 {
1058                         if (OptAttributes == null) {
1059                                 OptAttributes = new Attributes (attrs);
1060                                 return;
1061                         }
1062                         OptAttributes.AddAttributes (attrs);
1063                 }
1064
1065                 public virtual void Emit (TypeContainer tc) 
1066                 {
1067                         if (OptAttributes == null)
1068                                 return;
1069
1070                         EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1071                         OptAttributes.Emit (ec, this);
1072                 }
1073                 
1074                 protected Attribute GetClsCompliantAttribute ()
1075                 {
1076                         if (OptAttributes == null)
1077                                 return null;
1078
1079                         // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1080                         if (!OptAttributes.CheckTargets (this))
1081                                 return null;
1082
1083                         EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1084                         Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1085                         if (a != null) {
1086                                 a.Resolve (temp_ec);
1087                         }
1088                         return a;
1089                 }
1090         }
1091                 
1092         public class AssemblyClass: CommonAssemblyModulClass {
1093                 // TODO: make it private and move all builder based methods here
1094                 public AssemblyBuilder Builder;
1095                 bool is_cls_compliant;
1096                 public Attribute ClsCompliantAttribute;
1097
1098                 ListDictionary declarative_security;
1099
1100                 static string[] attribute_targets = new string [] { "assembly" };
1101
1102                 public AssemblyClass (): base ()
1103                 {
1104                         is_cls_compliant = false;
1105                 }
1106
1107                 public bool IsClsCompliant {
1108                         get {
1109                                 return is_cls_compliant;
1110                         }
1111                 }
1112
1113                 public override AttributeTargets AttributeTargets {
1114                         get {
1115                                 return AttributeTargets.Assembly;
1116                         }
1117                 }
1118
1119                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1120                 {
1121                         return is_cls_compliant;
1122                 }
1123
1124                 public void ResolveClsCompliance ()
1125                 {
1126                         ClsCompliantAttribute = GetClsCompliantAttribute ();
1127                         if (ClsCompliantAttribute == null)
1128                                 return;
1129
1130                         is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1131                 }
1132
1133                 // fix bug #56621
1134                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1135                 {
1136                         try {
1137                                 // check for possible ECMA key
1138                                 if (strongNameBlob.Length == 16) {
1139                                         // will be rejected if not "the" ECMA key
1140                                         an.SetPublicKey (strongNameBlob);
1141                                 }
1142                                 else {
1143                                         // take it, with or without, a private key
1144                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1145                                         // and make sure we only feed the public part to Sys.Ref
1146                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1147                                         
1148                                         // AssemblyName.SetPublicKey requires an additional header
1149                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1150
1151                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1152                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1153                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1154                                         an.SetPublicKey (encodedPublicKey);
1155                                 }
1156                         }
1157                         catch (Exception) {
1158                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1159                                         RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1160                                 Environment.Exit (1);
1161                         }
1162                 }
1163
1164                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1165                 public AssemblyName GetAssemblyName (string name, string output) 
1166                 {
1167                         if (OptAttributes != null) {
1168                                 foreach (Attribute a in OptAttributes.Attrs) {
1169                                         // cannot rely on any resolve-based members before you call Resolve
1170                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1171                                                 continue;
1172
1173                                         // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1174                                         //       However, this is invoked by CodeGen.Init, at which time none of the namespaces
1175                                         //       are loaded yet.
1176                                         switch (a.Name) {
1177                                                 case "AssemblyKeyFile":
1178                                                 case "AssemblyKeyFileAttribute":
1179                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1180                                                         if (RootContext.StrongNameKeyFile != null) {
1181                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1182                                                                 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1183                                                         }
1184                                                         else {
1185                                                                 string value = a.GetString ();
1186                                                                 if (value != String.Empty)
1187                                                                         RootContext.StrongNameKeyFile = value;
1188                                                         }
1189                                                         break;
1190                                                 case "AssemblyKeyName":
1191                                                 case "AssemblyKeyNameAttribute":
1192                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1193                                                         if (RootContext.StrongNameKeyContainer != null) {
1194                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1195                                                                 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1196                                                         }
1197                                                         else {
1198                                                                 string value = a.GetString ();
1199                                                                 if (value != String.Empty)
1200                                                                         RootContext.StrongNameKeyContainer = value;
1201                                                         }
1202                                                         break;
1203                                                 case "AssemblyDelaySign":
1204                                                 case "AssemblyDelaySignAttribute":
1205                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1206                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1207                                                         break;
1208                                         }
1209                                 }
1210                         }
1211
1212                         AssemblyName an = new AssemblyName ();
1213                         an.Name = Path.GetFileNameWithoutExtension (name);
1214
1215                         // note: delay doesn't apply when using a key container
1216                         if (RootContext.StrongNameKeyContainer != null) {
1217                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1218                                 return an;
1219                         }
1220
1221                         // strongname is optional
1222                         if (RootContext.StrongNameKeyFile == null)
1223                                 return an;
1224
1225                         string AssemblyDir = Path.GetDirectoryName (output);
1226
1227                         // the StrongName key file may be relative to (a) the compiled
1228                         // file or (b) to the output assembly. See bugzilla #55320
1229                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1230
1231                         // (a) relative to the compiled file
1232                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1233                         bool exist = File.Exists (filename);
1234                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1235                                 // (b) relative to the outputed assembly
1236                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1237                                 exist = File.Exists (filename);
1238                         }
1239
1240                         if (exist) {
1241                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1242                                         byte[] snkeypair = new byte [fs.Length];
1243                                         fs.Read (snkeypair, 0, snkeypair.Length);
1244
1245                                         if (RootContext.StrongNameDelaySign) {
1246                                                 // delayed signing - DO NOT include private key
1247                                                 SetPublicKey (an, snkeypair);
1248                                         }
1249                                         else {
1250                                                 // no delay so we make sure we have the private key
1251                                                 try {
1252                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1253                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1254                                                 }
1255                                                 catch (CryptographicException) {
1256                                                         if (snkeypair.Length == 16) {
1257                                                                 // error # is different for ECMA key
1258                                                                 Report.Error (1606, "Could not strongname the assembly. " + 
1259                                                                         "ECMA key can only be used to delay-sign assemblies");
1260                                                         }
1261                                                         else {
1262                                                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1263                                                                         RootContext.StrongNameKeyFile +
1264                                                                         "' doesn't have a private key.");
1265                                                         }
1266                                                         return null;
1267                                                 }
1268                                         }
1269                                 }
1270                         }
1271                         else {
1272                                 Report.Error (1548, "Could not strongname the assembly. File `" +
1273                                         RootContext.StrongNameKeyFile + "' not found.");
1274                                 return null;
1275                         }
1276                         return an;
1277                 }
1278
1279                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1280                 {
1281                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1282                                 if (declarative_security == null)
1283                                         declarative_security = new ListDictionary ();
1284
1285                                 a.ExtractSecurityPermissionSet (declarative_security);
1286                                 return;
1287                         }
1288
1289                         Builder.SetCustomAttribute (customBuilder);
1290                 }
1291
1292                 public override void Emit (TypeContainer tc)
1293                 {
1294                         base.Emit (tc);
1295
1296                         if (declarative_security != null) {
1297
1298                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1299                                 object builder_instance = Builder;
1300
1301                                 try {
1302                                         // Microsoft runtime hacking
1303                                         if (add_permission == null) {
1304                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1305                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1306
1307                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1308                                                 builder_instance = fi.GetValue (Builder);
1309                                         }
1310
1311                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1312                                                                                                   declarative_security [SecurityAction.RequestOptional],
1313                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1314                                         add_permission.Invoke (builder_instance, args);
1315                                 }
1316                                 catch {
1317                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1318                                 }
1319                         }
1320                 }
1321
1322                 public override string[] ValidAttributeTargets {
1323                         get {
1324                                 return attribute_targets;
1325                         }
1326                 }
1327         }
1328
1329         public class ModuleClass: CommonAssemblyModulClass {
1330                 // TODO: make it private and move all builder based methods here
1331                 public ModuleBuilder Builder;
1332                 bool m_module_is_unsafe;
1333
1334                 static string[] attribute_targets = new string [] { "module" };
1335
1336                 public ModuleClass (bool is_unsafe)
1337                 {
1338                         m_module_is_unsafe = is_unsafe;
1339                 }
1340
1341                 public override AttributeTargets AttributeTargets {
1342                         get {
1343                                 return AttributeTargets.Module;
1344                         }
1345                 }
1346
1347                 public override bool IsClsCompliaceRequired(DeclSpace ds)
1348                 {
1349                         return CodeGen.Assembly.IsClsCompliant;
1350                 }
1351
1352                 public override void Emit (TypeContainer tc) 
1353                 {
1354                         base.Emit (tc);
1355
1356                         if (!m_module_is_unsafe)
1357                                 return;
1358
1359                         if (TypeManager.unverifiable_code_ctor == null) {
1360                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1361                                 return;
1362                         }
1363                                 
1364                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1365                 }
1366                 
1367                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1368                 {
1369                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1370                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1371                                         Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1372                                 }
1373                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1374                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1375                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1376                                         return;
1377                                 }
1378                         }
1379
1380                         Builder.SetCustomAttribute (customBuilder);
1381                 }
1382
1383                 public override string[] ValidAttributeTargets {
1384                         get {
1385                                 return attribute_targets;
1386                         }
1387                 }
1388         }
1389 }