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