56a2667c3e1312e94cc64f3ed34681fab76940fe
[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
11 //
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.   
15 //
16 // Only remove it if you need to debug locally on your tree.
17 //
18 #define PRODUCTION
19
20 using System;
21 using System.IO;
22 using System.Collections;
23 using System.Collections.Specialized;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Runtime.InteropServices;
27 using System.Security;
28 using System.Security.Cryptography;
29 using System.Security.Permissions;
30
31 using Mono.Security.Cryptography;
32
33 namespace Mono.CSharp {
34
35         /// <summary>
36         ///    Code generator class.
37         /// </summary>
38         public class CodeGen {
39                 static AppDomain current_domain;
40                 static public SymbolWriter SymbolWriter;
41
42                 public static AssemblyClass Assembly;
43                 public static ModuleClass Module;
44
45                 static CodeGen ()
46                 {
47                         Reset ();
48                 }
49
50                 public static void Reset ()
51                 {
52                         Assembly = new AssemblyClass ();
53                         Module = new ModuleClass (RootContext.Unsafe);
54                 }
55
56                 public static string Basename (string name)
57                 {
58                         int pos = name.LastIndexOf ('/');
59
60                         if (pos != -1)
61                                 return name.Substring (pos + 1);
62
63                         pos = name.LastIndexOf ('\\');
64                         if (pos != -1)
65                                 return name.Substring (pos + 1);
66
67                         return name;
68                 }
69
70                 public static string Dirname (string name)
71                 {
72                         int pos = name.LastIndexOf ('/');
73
74                         if (pos != -1)
75                                 return name.Substring (0, pos);
76
77                         pos = name.LastIndexOf ('\\');
78                         if (pos != -1)
79                                 return name.Substring (0, pos);
80
81                         return ".";
82                 }
83
84                 static public string FileName;
85
86                 //
87                 // Initializes the symbol writer
88                 //
89                 static void InitializeSymbolWriter (string filename)
90                 {
91                         SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
92
93                         //
94                         // If we got an ISymbolWriter instance, initialize it.
95                         //
96                         if (SymbolWriter == null) {
97                                 Report.Warning (
98                                         -18, 1, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
99                                 return;
100                         }
101                 }
102
103                 //
104                 // Initializes the code generator variables
105                 //
106                 static public bool Init (string name, string output, bool want_debugging_support)
107                 {
108                         FileName = output;
109                         AssemblyName an = Assembly.GetAssemblyName (name, output);
110                         if (an == null)
111                                 return false;
112
113                         if (an.KeyPair != null) {
114                                 // If we are going to strong name our assembly make
115                                 // sure all its refs are strong named
116                                 foreach (Assembly a in RootNamespace.Global.Assemblies) {
117                                         AssemblyName ref_name = a.GetName ();
118                                         byte [] b = ref_name.GetPublicKeyToken ();
119                                         if (b == null || b.Length == 0) {
120                                                 Report.Error (1577, "Assembly generation failed " +
121                                                                 "-- Referenced assembly '" +
122                                                                 ref_name.Name +
123                                                                 "' does not have a strong name.");
124                                                 //Environment.Exit (1);
125                                         }
126                                 }
127                         }
128                         
129                         current_domain = AppDomain.CurrentDomain;
130
131                         try {
132                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
133                                         AssemblyBuilderAccess.Save, Dirname (name));
134                         }
135                         catch (ArgumentException) {
136                                 // specified key may not be exportable outside it's container
137                                 if (RootContext.StrongNameKeyContainer != null) {
138                                         Report.Error (1548, "Could not access the key inside the container `" +
139                                                 RootContext.StrongNameKeyContainer + "'.");
140                                         Environment.Exit (1);
141                                 }
142                                 return false;
143                         }
144                         catch (CryptographicException) {
145                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
146                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
147                                         Environment.Exit (1);
148                                 }
149                                 return false;
150                         }
151
152 #if GMCS_SOURCE
153                         // Get the complete AssemblyName from the builder
154                         // (We need to get the public key and token)
155                         Assembly.Name = Assembly.Builder.GetName ();
156 #endif
157
158                         //
159                         // Pass a path-less name to DefineDynamicModule.  Wonder how
160                         // this copes with output in different directories then.
161                         // FIXME: figure out how this copes with --output /tmp/blah
162                         //
163                         // If the third argument is true, the ModuleBuilder will dynamically
164                         // load the default symbol writer.
165                         //
166                         Module.Builder = Assembly.Builder.DefineDynamicModule (
167                                 Basename (name), Basename (output), false);
168
169                         if (want_debugging_support)
170                                 InitializeSymbolWriter (output);
171
172                         return true;
173                 }
174
175                 static public void Save (string name)
176                 {
177                         try {
178                                 Assembly.Builder.Save (Basename (name));
179
180                                 if (SymbolWriter != null)
181                                         SymbolWriter.WriteSymbolFile ();
182                         }
183                         catch (COMException) {
184                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
185                                         throw;
186
187                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
188                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
189                                         RootContext.StrongNameKeyFile +
190                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
191                         }
192                         catch (System.IO.IOException io) {
193                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
194                         }
195                         catch (System.UnauthorizedAccessException ua) {
196                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
197                         }
198                 }
199         }
200
201
202         public interface IResolveContext
203         {
204                 DeclSpace DeclContainer { get; }
205                 bool IsInObsoleteScope { get; }
206                 bool IsInUnsafeScope { get; }
207
208                 // the declcontainer to lookup for type-parameters.  Should only use LookupGeneric on it.
209                 //
210                 // FIXME: This is somewhat of a hack.  We don't need a full DeclSpace for this.  We just need the
211                 //        current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
212                 //        Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to 
213                 //        handle generic method overrides differently
214                 DeclSpace GenericDeclContainer { get; }
215         }
216
217         /// <summary>
218         ///   An Emit Context is created for each body of code (from methods,
219         ///   properties bodies, indexer bodies or constructor bodies)
220         /// </summary>
221         public class EmitContext : IResolveContext {
222
223                 //
224                 // Holds a varible used during collection or object initialization.
225                 //
226                 public Expression CurrentInitializerVariable;
227
228                 DeclSpace decl_space;
229                 
230                 public DeclSpace TypeContainer;
231                 public ILGenerator ig;
232
233                 [Flags]
234                 public enum Flags : byte {
235                         /// <summary>
236                         ///   This flag tracks the `checked' state of the compilation,
237                         ///   it controls whether we should generate code that does overflow
238                         ///   checking, or if we generate code that ignores overflows.
239                         ///
240                         ///   The default setting comes from the command line option to generate
241                         ///   checked or unchecked code plus any source code changes using the
242                         ///   checked/unchecked statements or expressions.   Contrast this with
243                         ///   the ConstantCheckState flag.
244                         /// </summary>
245                         CheckState = 1 << 0,
246
247                         /// <summary>
248                         ///   The constant check state is always set to `true' and cant be changed
249                         ///   from the command line.  The source code can change this setting with
250                         ///   the `checked' and `unchecked' statements and expressions. 
251                         /// </summary>
252                         ConstantCheckState = 1 << 1,
253
254                         AllCheckStateFlags = CheckState | ConstantCheckState,
255
256                         /// <summary>
257                         ///  Whether we are inside an unsafe block
258                         /// </summary>
259                         InUnsafe = 1 << 2,
260
261                         InCatch = 1 << 3,
262                         InFinally = 1 << 4,
263
264                         /// <summary>
265                         ///   Whether control flow analysis is enabled
266                         /// </summary>
267                         DoFlowAnalysis = 1 << 5,
268
269                         /// <summary>
270                         ///   Whether control flow analysis is disabled on structs
271                         ///   (only meaningful when DoFlowAnalysis is set)
272                         /// </summary>
273                         OmitStructFlowAnalysis = 1 << 6,
274
275                         ///
276                         /// Indicates the current context is in probing mode, no errors are reported. 
277                         ///
278                         ProbingMode = 1 <<      7
279                 }
280
281                 Flags flags;
282
283                 /// <summary>
284                 ///   Whether we are emitting code inside a static or instance method
285                 /// </summary>
286                 public bool IsStatic;
287
288                 /// <summary>
289                 ///   Whether the actual created method is static or instance method.
290                 ///   Althoug the method might be declared as `static', if an anonymous
291                 ///   method is involved, we might turn this into an instance method.
292                 ///
293                 ///   So this reflects the low-level staticness of the method, while
294                 ///   IsStatic represents the semantic, high-level staticness.
295                 /// </summary>
296                 public bool MethodIsStatic;
297
298                 /// <summary>
299                 ///   Whether we are emitting a field initializer
300                 /// </summary>
301                 public bool IsFieldInitializer;
302
303                 /// <summary>
304                 ///   If this is true, then Return and ContextualReturn statements
305                 ///   will set the ReturnType value based on the expression types
306                 ///   of each return statement instead of the method return type
307                 ///   (which is initially null).
308                 /// </summary>
309                 public bool InferReturnType;
310
311                 /// <summary>
312                 ///   The value that is allowed to be returned or NULL if there is no
313                 ///   return type.
314                 /// </summary>
315                 Type return_type;
316
317                 /// <summary>
318                 ///   Points to the Type (extracted from the TypeContainer) that
319                 ///   declares this body of code
320                 /// </summary>
321                 public Type ContainerType;
322                 
323                 /// <summary>
324                 ///   Whether this is generating code for a constructor
325                 /// </summary>
326                 public bool IsConstructor;
327
328                 /// <summary>
329                 ///   Keeps track of the Type to LocalBuilder temporary storage created
330                 ///   to store structures (used to compute the address of the structure
331                 ///   value on structure method invocations)
332                 /// </summary>
333                 public Hashtable temporary_storage;
334
335                 public Block CurrentBlock;
336
337                 public int CurrentFile;
338
339                 /// <summary>
340                 ///   The location where we store the return value.
341                 /// </summary>
342                 LocalBuilder return_value;
343
344                 /// <summary>
345                 ///   The location where return has to jump to return the
346                 ///   value
347                 /// </summary>
348                 public Label ReturnLabel;
349
350                 /// <summary>
351                 ///   If we already defined the ReturnLabel
352                 /// </summary>
353                 public bool HasReturnLabel;
354
355                 /// <summary>
356                 ///   Whether we are inside an iterator block.
357                 /// </summary>
358                 public bool InIterator;
359
360                 /// <summary>
361                 ///  Whether we are in a `fixed' initialization
362                 /// </summary>
363                 public bool InFixedInitializer;
364
365                 /// <summary>
366                 ///  Whether we are inside an anonymous method.
367                 /// </summary>
368                 public AnonymousContainer CurrentAnonymousMethod;
369                 
370                 /// <summary>
371                 ///   Location for this EmitContext
372                 /// </summary>
373                 public Location loc;
374
375                 /// <summary>
376                 ///   Inside an enum definition, we do not resolve enumeration values
377                 ///   to their enumerations, but rather to the underlying type/value
378                 ///   This is so EnumVal + EnumValB can be evaluated.
379                 ///
380                 ///   There is no "E operator + (E x, E y)", so during an enum evaluation
381                 ///   we relax the rules
382                 /// </summary>
383                 public bool InEnumContext;
384
385                 public readonly IResolveContext ResolveContext;
386
387                 /// <summary>
388                 ///    The current iterator
389                 /// </summary>
390                 public Iterator CurrentIterator {
391                         get { return CurrentAnonymousMethod as Iterator; }
392                 }
393
394                 /// <summary>
395                 ///    Whether we are in the resolving stage or not
396                 /// </summary>
397                 enum Phase {
398                         Created,
399                         Resolving,
400                         Emitting
401                 }
402
403                 public static EmitContext TempEc;
404                 
405                 bool isAnonymousMethodAllowed = true;
406
407                 Phase current_phase;
408                 FlowBranching current_flow_branching;
409
410                 static int next_id = 0;
411                 int id = ++next_id;
412
413                 public override string ToString ()
414                 {
415                         return String.Format ("EmitContext ({0}:{1})", id,
416                                               CurrentAnonymousMethod, loc);
417                 }
418                 
419                 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
420                                     Type return_type, int code_flags, bool is_constructor)
421                 {
422                         this.ResolveContext = rc;
423                         this.ig = ig;
424
425                         TypeContainer = parent;
426                         this.decl_space = ds;
427                         if (RootContext.Checked)
428                                 flags |= Flags.CheckState;
429                         flags |= Flags.ConstantCheckState;
430
431                         if (return_type == null)
432                                 throw new ArgumentNullException ("return_type");
433 #if GMCS_SOURCE
434                         if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
435                                 throw new InternalErrorException ();
436 #endif
437
438                         IsStatic = (code_flags & Modifiers.STATIC) != 0;
439                         MethodIsStatic = IsStatic;
440                         InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
441                         ReturnType = return_type;
442                         IsConstructor = is_constructor;
443                         CurrentBlock = null;
444                         CurrentFile = 0;
445                         current_phase = Phase.Created;
446
447                         if (parent != null){
448                                 // Can only be null for the ResolveType contexts.
449                                 ContainerType = parent.TypeBuilder;
450                                 if (rc.IsInUnsafeScope)
451                                         flags |= Flags.InUnsafe;
452                         }
453                         loc = l;
454                 }
455
456                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
457                                     Type return_type, int code_flags, bool is_constructor)
458                         : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
459                 {
460                 }
461
462                 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
463                                     Type return_type, int code_flags)
464                         : this (rc, ds, ds, l, ig, return_type, code_flags, false)
465                 {
466                 }
467
468                 public DeclSpace DeclContainer { 
469                         get { return decl_space; }
470                         set { decl_space = value; }
471                 }
472
473                 public DeclSpace GenericDeclContainer {
474                         get { return DeclContainer; }
475                 }
476
477                 public bool CheckState {
478                         get { return (flags & Flags.CheckState) != 0; }
479                 }
480
481                 public bool ConstantCheckState {
482                         get { return (flags & Flags.ConstantCheckState) != 0; }
483                 }
484
485                 public bool InUnsafe {
486                         get { return (flags & Flags.InUnsafe) != 0; }
487                 }
488
489                 public bool InCatch {
490                         get { return (flags & Flags.InCatch) != 0; }
491                 }
492
493                 public bool InFinally {
494                         get { return (flags & Flags.InFinally) != 0; }
495                 }
496
497                 public bool DoFlowAnalysis {
498                         get { return (flags & Flags.DoFlowAnalysis) != 0; }
499                 }
500
501                 public bool OmitStructFlowAnalysis {
502                         get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
503                 }
504
505                 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
506                 // it's public so that we can use a struct at the callsite
507                 public struct FlagsHandle : IDisposable
508                 {
509                         EmitContext ec;
510                         readonly Flags invmask, oldval;
511
512                         public FlagsHandle (EmitContext ec, Flags flagsToSet)
513                                 : this (ec, flagsToSet, flagsToSet)
514                         {
515                         }
516
517                         internal FlagsHandle (EmitContext ec, Flags mask, Flags val)
518                         {
519                                 this.ec = ec;
520                                 invmask = ~mask;
521                                 oldval = ec.flags & mask;
522                                 ec.flags = (ec.flags & invmask) | (val & mask);
523
524                                 if ((mask & Flags.ProbingMode) != 0)
525                                         Report.DisableReporting ();
526                         }
527
528                         public void Dispose ()
529                         {
530                                 if ((invmask & Flags.ProbingMode) == 0)
531                                         Report.EnableReporting ();
532
533                                 ec.flags = (ec.flags & invmask) | oldval;
534                         }
535                 }
536
537                 // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
538                 public FlagsHandle Set (Flags flagsToSet)
539                 {
540                         return new FlagsHandle (this, flagsToSet);
541                 }
542
543                 public FlagsHandle With (Flags bits, bool enable)
544                 {
545                         return new FlagsHandle (this, bits, enable ? bits : 0);
546                 }
547
548                 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
549                 {
550                         Flags newflags = 
551                                 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
552                                 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
553                         return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
554                 }
555
556                 public bool IsInObsoleteScope {
557                         get {
558                                 // Disables obsolete checks when probing is on
559                                 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
560                         }
561                 }
562
563                 public bool IsInProbingMode {
564                         get { return (flags & Flags.ProbingMode) != 0; }
565                 }
566
567                 public bool IsInUnsafeScope {
568                         get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
569                 }
570
571                 public bool IsAnonymousMethodAllowed {
572                         get { return isAnonymousMethodAllowed; }
573                         set { isAnonymousMethodAllowed = value; }
574                 }
575
576                 public FlowBranching CurrentBranching {
577                         get { return current_flow_branching; }
578                 }
579
580                 // <summary>
581                 //   Starts a new code branching.  This inherits the state of all local
582                 //   variables and parameters from the current branching.
583                 // </summary>
584                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
585                 {
586                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
587                         return current_flow_branching;
588                 }
589
590                 // <summary>
591                 //   Starts a new code branching for block `block'.
592                 // </summary>
593                 public FlowBranching StartFlowBranching (Block block)
594                 {
595                         FlowBranching.BranchingType type;
596
597                         if ((CurrentBranching != null) &&
598                             (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
599                                 type = FlowBranching.BranchingType.SwitchSection;
600                         else
601                                 type = FlowBranching.BranchingType.Block;
602
603                         flags |= Flags.DoFlowAnalysis;
604
605                         current_flow_branching = FlowBranching.CreateBranching (
606                                 CurrentBranching, type, block, block.StartLocation);
607                         return current_flow_branching;
608                 }
609
610                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
611                 {
612                         FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
613                         current_flow_branching = branching;
614                         return branching;
615                 }
616
617                 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
618                 {
619                         FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
620                         current_flow_branching = branching;
621                         return branching;
622                 }
623
624                 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
625                 {
626                         FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
627                         current_flow_branching = branching;
628                         return branching;
629                 }
630
631                 // <summary>
632                 //   Ends a code branching.  Merges the state of locals and parameters
633                 //   from all the children of the ending branching.
634                 // </summary>
635                 public FlowBranching.UsageVector DoEndFlowBranching ()
636                 {
637                         FlowBranching old = current_flow_branching;
638                         current_flow_branching = current_flow_branching.Parent;
639
640                         return current_flow_branching.MergeChild (old);
641                 }
642
643                 // <summary>
644                 //   Ends a code branching.  Merges the state of locals and parameters
645                 //   from all the children of the ending branching.
646                 // </summary>
647                 public bool EndFlowBranching ()
648                 {
649                         FlowBranching.UsageVector vector = DoEndFlowBranching ();
650
651                         return vector.IsUnreachable;
652                 }
653
654                 // <summary>
655                 //   Kills the current code branching.  This throws away any changed state
656                 //   information and should only be used in case of an error.
657                 // </summary>
658                 public void KillFlowBranching ()
659                 {
660                         current_flow_branching = current_flow_branching.Parent;
661                 }
662
663                 public bool MustCaptureVariable (LocalInfo local)
664                 {
665                         if (CurrentAnonymousMethod == null)
666                                 return false;
667                         if (CurrentAnonymousMethod.IsIterator)
668                                 return true;
669                         return local.Block.Toplevel != CurrentBlock.Toplevel;
670                 }
671                 
672                 public void EmitMeta (ToplevelBlock b)
673                 {
674                         b.EmitMeta (this);
675
676                         if (HasReturnLabel)
677                                 ReturnLabel = ig.DefineLabel ();
678                 }
679
680                 //
681                 // Here until we can fix the problem with Mono.CSharp.Switch, which
682                 // currently can not cope with ig == null during resolve (which must
683                 // be fixed for switch statements to work on anonymous methods).
684                 //
685                 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
686                 {
687                         if (block == null)
688                                 return;
689                         
690                         bool unreachable;
691                         
692                         if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
693                                 if (Report.Errors > 0)
694                                         return;
695
696                                 EmitMeta (block);
697
698                                 current_phase = Phase.Emitting;
699                                 EmitResolvedTopBlock (block, unreachable);
700                         }
701                 }
702
703                 bool resolved;
704
705                 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
706                                              Parameters ip, IMethodData md, out bool unreachable)
707                 {
708                         current_phase = Phase.Resolving;
709                         
710                         unreachable = false;
711
712                         if (resolved)
713                                 return true;
714
715                         if (!loc.IsNull)
716                                 CurrentFile = loc.File;
717
718 #if PRODUCTION
719                         try {
720 #endif
721                                 if (!block.ResolveMeta (this, ip))
722                                         return false;
723
724                                 if ((md != null) && (md.Iterator != null)) {
725                                         if (!md.Iterator.Define (this))
726                                                 return false;
727                                 }
728
729                                 using (this.With (EmitContext.Flags.DoFlowAnalysis, true)) {
730                                         FlowBranchingToplevel top_level;
731                                         if (anonymous_method_host != null)
732                                                 top_level = new FlowBranchingToplevel (anonymous_method_host.CurrentBranching, block);
733                                         else 
734                                                 top_level = block.TopLevelBranching;
735
736                                         current_flow_branching = top_level;
737                                         bool ok = block.Resolve (this);
738                                         current_flow_branching = null;
739
740                                         if (!ok)
741                                                 return false;
742
743                                         bool flow_unreachable = top_level.End ();
744                                         if (flow_unreachable)
745                                                 unreachable = true;
746                                 }
747 #if PRODUCTION
748                         } catch (Exception e) {
749                                 Console.WriteLine ("Exception caught by the compiler while compiling:");
750                                 Console.WriteLine ("   Block that caused the problem begin at: " + loc);
751
752                                 if (CurrentBlock != null){
753                                         Console.WriteLine ("                     Block being compiled: [{0},{1}]",
754                                                            CurrentBlock.StartLocation, CurrentBlock.EndLocation);
755                                 }
756                                 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
757                                 throw;
758                         }
759 #endif
760
761                         if (return_type != TypeManager.void_type && !unreachable) {
762                                 if (CurrentAnonymousMethod == null) {
763                                         Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
764                                         return false;
765                                 } else if (!CurrentAnonymousMethod.IsIterator) {
766                                         Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
767                                                       CurrentAnonymousMethod.GetSignatureForError ());
768                                         return false;
769                                 }
770                         }
771
772                         if (!block.CompleteContexts (this))
773                                 return false;
774
775                         resolved = true;
776                         return true;
777                 }
778
779                 public Type ReturnType {
780                         set {
781                                 return_type = value;
782                         }
783                         get {
784                                 return return_type;
785                         }
786                 }
787
788                 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
789                 {
790                         if (block != null)
791                                 block.Emit (this);
792
793                         if (HasReturnLabel)
794                                 ig.MarkLabel (ReturnLabel);
795
796                         if (return_value != null){
797                                 ig.Emit (OpCodes.Ldloc, return_value);
798                                 ig.Emit (OpCodes.Ret);
799                         } else {
800                                 //
801                                 // If `HasReturnLabel' is set, then we already emitted a
802                                 // jump to the end of the method, so we must emit a `ret'
803                                 // there.
804                                 //
805                                 // Unfortunately, System.Reflection.Emit automatically emits
806                                 // a leave to the end of a finally block.  This is a problem
807                                 // if no code is following the try/finally block since we may
808                                 // jump to a point after the end of the method.
809                                 // As a workaround, we're always creating a return label in
810                                 // this case.
811                                 //
812
813                                 bool in_iterator = (CurrentAnonymousMethod != null) &&
814                                         CurrentAnonymousMethod.IsIterator && InIterator;
815
816                                 if ((block != null) && block.IsDestructor) {
817                                         // Nothing to do; S.R.E automatically emits a leave.
818                                 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
819                                         if (return_type != TypeManager.void_type)
820                                                 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
821                                         ig.Emit (OpCodes.Ret);
822                                 }
823                         }
824                 }
825
826                 /// <summary>
827                 ///   This is called immediately before emitting an IL opcode to tell the symbol
828                 ///   writer to which source line this opcode belongs.
829                 /// </summary>
830                 public void Mark (Location loc, bool check_file)
831                 {
832                         if ((CodeGen.SymbolWriter == null) || loc.IsNull)
833                                 return;
834
835                         if (check_file && (CurrentFile != loc.File))
836                                 return;
837
838                         CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
839                 }
840
841                 public void DefineLocalVariable (string name, LocalBuilder builder)
842                 {
843                         if (CodeGen.SymbolWriter == null)
844                                 return;
845
846                         CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
847                 }
848
849                 public void BeginScope ()
850                 {
851                         ig.BeginScope();
852
853                         if (CodeGen.SymbolWriter != null)
854                                 CodeGen.SymbolWriter.OpenScope(ig);
855                 }
856
857                 public void EndScope ()
858                 {
859                         ig.EndScope();
860
861                         if (CodeGen.SymbolWriter != null)
862                                 CodeGen.SymbolWriter.CloseScope(ig);
863                 }
864
865                 /// <summary>
866                 ///   Returns a temporary storage for a variable of type t as 
867                 ///   a local variable in the current body.
868                 /// </summary>
869                 public LocalBuilder GetTemporaryLocal (Type t)
870                 {
871                         if (temporary_storage != null) {
872                                 object o = temporary_storage [t];
873                                 if (o != null) {
874                                         if (o is Stack) {
875                                                 Stack s = (Stack) o;
876                                                 o = s.Count == 0 ? null : s.Pop ();
877                                         } else {
878                                                 temporary_storage.Remove (t);
879                                         }
880                                 }
881                                 if (o != null)
882                                         return (LocalBuilder) o;
883                         }
884                         return ig.DeclareLocal (t);
885                 }
886
887                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
888                 {
889                         Stack s;
890
891                         if (temporary_storage == null) {
892                                 temporary_storage = new Hashtable ();
893                                 temporary_storage [t] = b;
894                                 return;
895                         }
896                         object o = temporary_storage [t];
897                         if (o == null) {
898                                 temporary_storage [t] = b;
899                                 return;
900                         }
901                         if (o is Stack) {
902                                 s = (Stack) o;
903                         } else {
904                                 s = new Stack ();
905                                 s.Push (o);
906                                 temporary_storage [t] = s;
907                         }
908                         s.Push (b);
909                 }
910
911                 /// <summary>
912                 ///   Current loop begin and end labels.
913                 /// </summary>
914                 public Label LoopBegin, LoopEnd;
915
916                 /// <summary>
917                 ///   Default target in a switch statement.   Only valid if
918                 ///   InSwitch is true
919                 /// </summary>
920                 public Label DefaultTarget;
921
922                 /// <summary>
923                 ///   If this is non-null, points to the current switch statement
924                 /// </summary>
925                 public Switch Switch;
926
927                 /// <summary>
928                 ///   ReturnValue creates on demand the LocalBuilder for the
929                 ///   return value from the function.  By default this is not
930                 ///   used.  This is only required when returns are found inside
931                 ///   Try or Catch statements.
932                 ///
933                 ///   This method is typically invoked from the Emit phase, so
934                 ///   we allow the creation of a return label if it was not
935                 ///   requested during the resolution phase.   Could be cleaned
936                 ///   up, but it would replicate a lot of logic in the Emit phase
937                 ///   of the code that uses it.
938                 /// </summary>
939                 public LocalBuilder TemporaryReturn ()
940                 {
941                         if (return_value == null){
942                                 return_value = ig.DeclareLocal (return_type);
943                                 if (!HasReturnLabel){
944                                         ReturnLabel = ig.DefineLabel ();
945                                         HasReturnLabel = true;
946                                 }
947                         }
948
949                         return return_value;
950                 }
951
952                 /// <summary>
953                 ///   This method is used during the Resolution phase to flag the
954                 ///   need to define the ReturnLabel
955                 /// </summary>
956                 public void NeedReturnLabel ()
957                 {
958                         if (current_phase != Phase.Resolving){
959                                 //
960                                 // The reason is that the `ReturnLabel' is declared between
961                                 // resolution and emission
962                                 // 
963                                 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
964                         }
965                         
966                         if (!InIterator && !HasReturnLabel) 
967                                 HasReturnLabel = true;
968                 }
969
970
971                 public Expression GetThis (Location loc)
972                 {
973                         This my_this;
974                         if (CurrentBlock != null)
975                                 my_this = new This (CurrentBlock, loc);
976                         else
977                                 my_this = new This (loc);
978
979                         if (!my_this.ResolveBase (this))
980                                 my_this = null;
981
982                         return my_this;
983                 }
984         }
985
986
987         public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
988
989                 protected CommonAssemblyModulClass ():
990                         base (null)
991                 {
992                 }
993
994                 public void AddAttributes (ArrayList attrs)
995                 {
996                         foreach (Attribute a in attrs)
997                                 a.AttachTo (this);
998
999                         if (attributes == null) {
1000                                 attributes = new Attributes (attrs);
1001                                 return;
1002                         }
1003                         attributes.AddAttributes (attrs);
1004                 }
1005
1006                 public virtual void Emit (TypeContainer tc) 
1007                 {
1008                         if (OptAttributes == null)
1009                                 return;
1010
1011                         OptAttributes.Emit ();
1012                 }
1013
1014                 protected Attribute ResolveAttribute (Type a_type)
1015                 {
1016                         Attribute a = OptAttributes.Search (a_type);
1017                         if (a != null) {
1018                                 a.Resolve ();
1019                         }
1020                         return a;
1021                 }
1022
1023                 public override IResolveContext ResolveContext {
1024                         get { return this; }
1025                 }
1026
1027                 #region IResolveContext Members
1028
1029                 public DeclSpace DeclContainer {
1030                         get { return RootContext.ToplevelTypes; }
1031                 }
1032
1033                 public DeclSpace GenericDeclContainer {
1034                         get { return DeclContainer; }
1035                 }
1036
1037                 public bool IsInObsoleteScope {
1038                         get { return false; }
1039                 }
1040
1041                 public bool IsInUnsafeScope {
1042                         get { return false; }
1043                 }
1044
1045                 #endregion
1046         }
1047                 
1048         public class AssemblyClass : CommonAssemblyModulClass {
1049                 // TODO: make it private and move all builder based methods here
1050                 public AssemblyBuilder Builder;
1051                 bool is_cls_compliant;
1052                 bool wrap_non_exception_throws;
1053
1054                 public Attribute ClsCompliantAttribute;
1055
1056                 ListDictionary declarative_security;
1057 #if GMCS_SOURCE
1058                 bool has_extension_method;              
1059                 public AssemblyName Name;
1060                 MethodInfo add_type_forwarder;
1061                 ListDictionary emitted_forwarders;
1062 #endif
1063
1064                 // Module is here just because of error messages
1065                 static string[] attribute_targets = new string [] { "assembly", "module" };
1066
1067                 public AssemblyClass (): base ()
1068                 {
1069 #if GMCS_SOURCE
1070                         wrap_non_exception_throws = true;
1071 #endif
1072                 }
1073
1074                 public bool HasExtensionMethods {
1075                         set {
1076 #if GMCS_SOURCE                         
1077                                 has_extension_method = value;
1078 #endif
1079                         }
1080                 }
1081
1082                 public bool IsClsCompliant {
1083                         get {
1084                                 return is_cls_compliant;
1085                         }
1086                 }
1087
1088                 public bool WrapNonExceptionThrows {
1089                         get {
1090                                 return wrap_non_exception_throws;
1091                         }
1092                 }
1093
1094                 public override AttributeTargets AttributeTargets {
1095                         get {
1096                                 return AttributeTargets.Assembly;
1097                         }
1098                 }
1099
1100                 public override bool IsClsComplianceRequired ()
1101                 {
1102                         return is_cls_compliant;
1103                 }
1104
1105                 public void Resolve ()
1106                 {
1107                         if (OptAttributes == null)
1108                                 return;
1109
1110                         // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1111                         if (!OptAttributes.CheckTargets())
1112                                 return;
1113
1114                         ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1115                         if (ClsCompliantAttribute != null) {
1116                                 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1117                         }
1118
1119 #if GMCS_SOURCE
1120                         Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1121                         if (a != null) {
1122                                 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1123                                 if (val != null)
1124                                         wrap_non_exception_throws = (bool)val;
1125                         }
1126 #endif
1127                 }
1128
1129                 // fix bug #56621
1130                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1131                 {
1132                         try {
1133                                 // check for possible ECMA key
1134                                 if (strongNameBlob.Length == 16) {
1135                                         // will be rejected if not "the" ECMA key
1136                                         an.SetPublicKey (strongNameBlob);
1137                                 }
1138                                 else {
1139                                         // take it, with or without, a private key
1140                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1141                                         // and make sure we only feed the public part to Sys.Ref
1142                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1143                                         
1144                                         // AssemblyName.SetPublicKey requires an additional header
1145                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1146
1147                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1148                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1149                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1150                                         an.SetPublicKey (encodedPublicKey);
1151                                 }
1152                         }
1153                         catch (Exception) {
1154                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1155                                 Environment.Exit (1);
1156                         }
1157                 }
1158
1159                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1160                 public AssemblyName GetAssemblyName (string name, string output) 
1161                 {
1162                         if (OptAttributes != null) {
1163                                 foreach (Attribute a in OptAttributes.Attrs) {
1164                                         // cannot rely on any resolve-based members before you call Resolve
1165                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1166                                                 continue;
1167
1168                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1169                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1170                                         //       are loaded yet.
1171                                         // TODO: Does not handle quoted attributes properly
1172                                         switch (a.Name) {
1173                                                 case "AssemblyKeyFile":
1174                                                 case "AssemblyKeyFileAttribute":
1175                                                 case "System.Reflection.AssemblyKeyFileAttribute":
1176                                                         if (RootContext.StrongNameKeyFile != null) {
1177                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1178                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1179                                     "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1180                                                         }
1181                                                         else {
1182                                                                 string value = a.GetString ();
1183                                                                 if (value.Length != 0)
1184                                                                         RootContext.StrongNameKeyFile = value;
1185                                                         }
1186                                                         break;
1187                                                 case "AssemblyKeyName":
1188                                                 case "AssemblyKeyNameAttribute":
1189                                                 case "System.Reflection.AssemblyKeyNameAttribute":
1190                                                         if (RootContext.StrongNameKeyContainer != null) {
1191                                                                 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1192                                                                 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1193                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1194                                                         }
1195                                                         else {
1196                                                                 string value = a.GetString ();
1197                                                                 if (value.Length != 0)
1198                                                                         RootContext.StrongNameKeyContainer = value;
1199                                                         }
1200                                                         break;
1201                                                 case "AssemblyDelaySign":
1202                                                 case "AssemblyDelaySignAttribute":
1203                                                 case "System.Reflection.AssemblyDelaySignAttribute":
1204                                                         RootContext.StrongNameDelaySign = a.GetBoolean ();
1205                                                         break;
1206                                         }
1207                                 }
1208                         }
1209
1210                         AssemblyName an = new AssemblyName ();
1211                         an.Name = Path.GetFileNameWithoutExtension (name);
1212
1213                         // note: delay doesn't apply when using a key container
1214                         if (RootContext.StrongNameKeyContainer != null) {
1215                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1216                                 return an;
1217                         }
1218
1219                         // strongname is optional
1220                         if (RootContext.StrongNameKeyFile == null)
1221                                 return an;
1222
1223                         string AssemblyDir = Path.GetDirectoryName (output);
1224
1225                         // the StrongName key file may be relative to (a) the compiled
1226                         // file or (b) to the output assembly. See bugzilla #55320
1227                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1228
1229                         // (a) relative to the compiled file
1230                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1231                         bool exist = File.Exists (filename);
1232                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1233                                 // (b) relative to the outputed assembly
1234                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1235                                 exist = File.Exists (filename);
1236                         }
1237
1238                         if (exist) {
1239                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1240                                         byte[] snkeypair = new byte [fs.Length];
1241                                         fs.Read (snkeypair, 0, snkeypair.Length);
1242
1243                                         if (RootContext.StrongNameDelaySign) {
1244                                                 // delayed signing - DO NOT include private key
1245                                                 SetPublicKey (an, snkeypair);
1246                                         }
1247                                         else {
1248                                                 // no delay so we make sure we have the private key
1249                                                 try {
1250                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1251                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1252                                                 }
1253                                                 catch (CryptographicException) {
1254                                                         if (snkeypair.Length == 16) {
1255                                                                 // error # is different for ECMA key
1256                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1257                                                                         "ECMA key can only be used to delay-sign assemblies");
1258                                                         }
1259                                                         else {
1260                                                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1261                                                         }
1262                                                         return null;
1263                                                 }
1264                                         }
1265                                 }
1266                         }
1267                         else {
1268                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1269                                 return null;
1270                         }
1271                         return an;
1272                 }
1273
1274                 void Error_AssemblySigning (string text)
1275                 {
1276                         Report.Error (1548, "Error during assembly signing. " + text);
1277                 }
1278
1279 #if GMCS_SOURCE
1280                 bool CheckInternalsVisibleAttribute (Attribute a)
1281                 {
1282                         string assembly_name = a.GetString ();
1283                         if (assembly_name.Length == 0)
1284                                 return false;
1285                                 
1286                         AssemblyName aname = null;
1287                         try {
1288                                 aname = new AssemblyName (assembly_name);
1289                         } catch (FileLoadException) {
1290                         } catch (ArgumentException) {
1291                         }
1292                                 
1293                         // Bad assembly name format
1294                         if (aname == null)
1295                                 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1296                         // Report error if we have defined Version or Culture
1297                         else if (aname.Version != null || aname.CultureInfo != null)
1298                                 throw new Exception ("Friend assembly `" + a.GetString () + 
1299                                                 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1300                         else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null) {
1301                                 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1302                                                 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1303                                 return false;
1304                         }
1305
1306                         return true;
1307                 }
1308 #endif
1309
1310                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1311                 {
1312                         if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1313                                 if (declarative_security == null)
1314                                         declarative_security = new ListDictionary ();
1315
1316                                 a.ExtractSecurityPermissionSet (declarative_security);
1317                                 return;
1318                         }
1319
1320                         if (a.Type == TypeManager.assembly_culture_attribute_type) {
1321                                 string value = a.GetString ();
1322                                 if (value == null || value.Length == 0)
1323                                         return;
1324
1325                                 if (RootContext.Target == Target.Exe) {
1326                                         a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1327                                         return;
1328                                 }
1329                         }
1330
1331 #if GMCS_SOURCE
1332                         if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1333                                 return;
1334
1335                         if (a.Type == TypeManager.type_forwarder_attr_type) {
1336                                 Type t = a.GetArgumentType ();
1337                                 if (t == null || TypeManager.HasElementType (t)) {
1338                                         Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1339                                         return;
1340                                 }
1341
1342                                 if (emitted_forwarders == null) {
1343                                         emitted_forwarders = new ListDictionary();
1344                                 } else if (emitted_forwarders.Contains(t)) {
1345                                         Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1346                                         Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1347                                                 TypeManager.CSharpName(t));
1348                                         return;
1349                                 }
1350
1351                                 emitted_forwarders.Add(t, a);
1352
1353                                 if (TypeManager.LookupDeclSpace (t) != null) {
1354                                         Report.SymbolRelatedToPreviousError (t);
1355                                         Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1356                                                 TypeManager.CSharpName (t));
1357                                         return;
1358                                 }
1359
1360                                 if (t.IsNested) {
1361                                         Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1362                                                 TypeManager.CSharpName (t));
1363                                         return;
1364                                 }
1365
1366                                 if (t.IsGenericType) {
1367                                         Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1368                                         return;
1369                                 }
1370
1371                                 if (add_type_forwarder == null) {
1372                                         add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1373                                                 BindingFlags.NonPublic | BindingFlags.Instance);
1374
1375                                         if (add_type_forwarder == null) {
1376                                                 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1377                                                 return;
1378                                         }
1379                                 }
1380
1381                                 add_type_forwarder.Invoke (Builder, new object[] { t });
1382                                 return;
1383                         }
1384                         
1385                         if (a.Type == TypeManager.extension_attribute_type) {
1386                                 a.Error_MisusedExtensionAttribute ();
1387                                 return;
1388                         }
1389 #endif
1390                         Builder.SetCustomAttribute (customBuilder);
1391                 }
1392
1393                 public override void Emit (TypeContainer tc)
1394                 {
1395                         base.Emit (tc);
1396
1397 #if GMCS_SOURCE
1398                         if (has_extension_method)
1399                                 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1400
1401                         // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1402                         if (OptAttributes == null || !OptAttributes.Contains (TypeManager.runtime_compatibility_attr_type)) {
1403                                 ConstructorInfo ci = TypeManager.GetConstructor (
1404                                         TypeManager.runtime_compatibility_attr_type, Type.EmptyTypes);
1405                                 PropertyInfo [] pis = new PropertyInfo [1];
1406                                 pis [0] = TypeManager.GetProperty (
1407                                         TypeManager.runtime_compatibility_attr_type, "WrapNonExceptionThrows");
1408                                 object [] pargs = new object [1];
1409                                 pargs [0] = true;
1410                                 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1411                         }
1412 #endif
1413
1414                         if (declarative_security != null) {
1415
1416                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1417                                 object builder_instance = Builder;
1418
1419                                 try {
1420                                         // Microsoft runtime hacking
1421                                         if (add_permission == null) {
1422                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1423                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1424
1425                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1426                                                 builder_instance = fi.GetValue (Builder);
1427                                         }
1428
1429                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1430                                                                                                   declarative_security [SecurityAction.RequestOptional],
1431                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1432                                         add_permission.Invoke (builder_instance, args);
1433                                 }
1434                                 catch {
1435                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1436                                 }
1437                         }
1438                 }
1439
1440                 public override string[] ValidAttributeTargets {
1441                         get {
1442                                 return attribute_targets;
1443                         }
1444                 }
1445
1446                 // Wrapper for AssemblyBuilder.AddModule
1447                 static MethodInfo adder_method;
1448                 static public MethodInfo AddModule_Method {
1449                         get {
1450                                 if (adder_method == null)
1451                                         adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1452                                 return adder_method;
1453                         }
1454                 }
1455                 public Module AddModule (string module)
1456                 {
1457                         MethodInfo m = AddModule_Method;
1458                         if (m == null) {
1459                                 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1460                                 Environment.Exit (1);
1461                         }
1462
1463                         try {
1464                                 return (Module) m.Invoke (Builder, new object [] { module });
1465                         } catch (TargetInvocationException ex) {
1466                                 throw ex.InnerException;
1467                         }
1468                 }               
1469         }
1470
1471         public class ModuleClass : CommonAssemblyModulClass {
1472                 // TODO: make it private and move all builder based methods here
1473                 public ModuleBuilder Builder;
1474                 bool m_module_is_unsafe;
1475                 bool has_default_charset;
1476
1477                 public CharSet DefaultCharSet = CharSet.Ansi;
1478                 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1479
1480                 static string[] attribute_targets = new string [] { "module" };
1481
1482                 public ModuleClass (bool is_unsafe)
1483                 {
1484                         m_module_is_unsafe = is_unsafe;
1485                 }
1486
1487                 public override AttributeTargets AttributeTargets {
1488                         get {
1489                                 return AttributeTargets.Module;
1490                         }
1491                 }
1492
1493                 public override bool IsClsComplianceRequired ()
1494                 {
1495                         return CodeGen.Assembly.IsClsCompliant;
1496                 }
1497
1498                 public override void Emit (TypeContainer tc) 
1499                 {
1500                         base.Emit (tc);
1501
1502                         if (!m_module_is_unsafe)
1503                                 return;
1504
1505                         if (TypeManager.unverifiable_code_ctor == null) {
1506                                 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1507                                 return;
1508                         }
1509                                 
1510                         Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1511                 }
1512                 
1513                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1514                 {
1515                         if (a.Type == TypeManager.cls_compliant_attribute_type) {
1516                                 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1517                                         Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1518                                 }
1519                                 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1520                                         Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1521                                         Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1522                                         return;
1523                                 }
1524                         }
1525
1526                         Builder.SetCustomAttribute (customBuilder);
1527                 }
1528
1529                 public bool HasDefaultCharSet {
1530                         get {
1531                                 return has_default_charset;
1532                         }
1533                 }
1534
1535                 /// <summary>
1536                 /// It is called very early therefore can resolve only predefined attributes
1537                 /// </summary>
1538                 public void Resolve ()
1539                 {
1540 #if GMCS_SOURCE
1541                         if (OptAttributes == null)
1542                                 return;
1543
1544                         if (!OptAttributes.CheckTargets())
1545                                 return;
1546
1547                         Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1548                         if (a != null) {
1549                                 has_default_charset = true;
1550                                 DefaultCharSet = a.GetCharSetValue ();
1551                                 switch (DefaultCharSet) {
1552                                         case CharSet.Ansi:
1553                                         case CharSet.None:
1554                                                 break;
1555                                         case CharSet.Auto:
1556                                                 DefaultCharSetType = TypeAttributes.AutoClass;
1557                                                 break;
1558                                         case CharSet.Unicode:
1559                                                 DefaultCharSetType = TypeAttributes.UnicodeClass;
1560                                                 break;
1561                                         default:
1562                                                 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1563                                                 break;
1564                                 }
1565                         }
1566 #endif
1567                 }
1568
1569                 public override string[] ValidAttributeTargets {
1570                         get {
1571                                 return attribute_targets;
1572                         }
1573                 }
1574         }
1575 }