2009-08-21 Marek Safar <marek.safar@gmail.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 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 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.Globalization;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Runtime.InteropServices;
28 using System.Security;
29 using System.Security.Cryptography;
30 using System.Security.Permissions;
31
32 using Mono.Security.Cryptography;
33
34 namespace Mono.CSharp {
35
36         /// <summary>
37         ///    Code generator class.
38         /// </summary>
39         public class CodeGen {
40                 static AppDomain current_domain;
41
42                 public static AssemblyClass Assembly;
43
44                 static CodeGen ()
45                 {
46                         Reset ();
47                 }
48
49                 public static void Reset ()
50                 {
51                         Assembly = new AssemblyClass ();
52                 }
53
54                 public static string Basename (string name)
55                 {
56                         int pos = name.LastIndexOf ('/');
57
58                         if (pos != -1)
59                                 return name.Substring (pos + 1);
60
61                         pos = name.LastIndexOf ('\\');
62                         if (pos != -1)
63                                 return name.Substring (pos + 1);
64
65                         return name;
66                 }
67
68                 public static string Dirname (string name)
69                 {
70                         int pos = name.LastIndexOf ('/');
71
72                         if (pos != -1)
73                                 return name.Substring (0, pos);
74
75                         pos = name.LastIndexOf ('\\');
76                         if (pos != -1)
77                                 return name.Substring (0, pos);
78
79                         return ".";
80                 }
81
82                 static public string FileName;
83
84 #if MS_COMPATIBLE
85                 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
86 #else
87                 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
88                 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
89 #endif
90                                 
91                 //
92                 // Initializes the code generator variables for interactive use (repl)
93                 //
94                 static public void InitDynamic (string name)
95                 {
96                         current_domain = AppDomain.CurrentDomain;
97                         AssemblyName an = Assembly.GetAssemblyName (name, name);
98                         
99                         Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run | COMPILER_ACCESS);
100                         RootContext.ToplevelTypes = new ModuleContainer (true);
101                         RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
102                         Assembly.Name = Assembly.Builder.GetName ();
103                 }
104                 
105                 //
106                 // Initializes the code generator variables
107                 //
108                 static public bool Init (string name, string output, bool want_debugging_support)
109                 {
110                         FileName = output;
111                         AssemblyName an = Assembly.GetAssemblyName (name, output);
112                         if (an == null)
113                                 return false;
114
115                         if (an.KeyPair != null) {
116                                 // If we are going to strong name our assembly make
117                                 // sure all its refs are strong named
118                                 foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
119                                         AssemblyName ref_name = a.GetName ();
120                                         byte [] b = ref_name.GetPublicKeyToken ();
121                                         if (b == null || b.Length == 0) {
122                                                 Report.Error (1577, "Assembly generation failed " +
123                                                                 "-- Referenced assembly '" +
124                                                                 ref_name.Name +
125                                                                 "' does not have a strong name.");
126                                                 //Environment.Exit (1);
127                                         }
128                                 }
129                         }
130                         
131                         current_domain = AppDomain.CurrentDomain;
132
133                         try {
134                                 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
135                                         AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname (name));
136                         }
137                         catch (ArgumentException) {
138                                 // specified key may not be exportable outside it's container
139                                 if (RootContext.StrongNameKeyContainer != null) {
140                                         Report.Error (1548, "Could not access the key inside the container `" +
141                                                 RootContext.StrongNameKeyContainer + "'.");
142                                         Environment.Exit (1);
143                                 }
144                                 throw;
145                         }
146                         catch (CryptographicException) {
147                                 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
148                                         Report.Error (1548, "Could not use the specified key to strongname the assembly.");
149                                         Environment.Exit (1);
150                                 }
151                                 return false;
152                         }
153
154                         // Get the complete AssemblyName from the builder
155                         // (We need to get the public key and token)
156                         Assembly.Name = Assembly.Builder.GetName ();
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                         try {
167                                 RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (
168                                         Basename (name), Basename (output), want_debugging_support);
169
170 #if !MS_COMPATIBLE
171                                 // TODO: We should use SymbolWriter from DefineDynamicModule
172                                 if (want_debugging_support && !SymbolWriter.Initialize (RootContext.ToplevelTypes.Builder, output)) {
173                                         Report.Error (40, "Unexpected debug information initialization error `{0}'",
174                                                 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
175                                         return false;
176                                 }
177 #endif
178                         } catch (ExecutionEngineException e) {
179                                 Report.Error (40, "Unexpected debug information initialization error `{0}'",
180                                         e.Message);
181                                 return false;
182                         }
183
184                         return true;
185                 }
186
187                 static public void Save (string name, bool saveDebugInfo)
188                 {
189 #if GMCS_SOURCE
190                         PortableExecutableKinds pekind;
191                         ImageFileMachine machine;
192
193                         switch (RootContext.Platform) {
194                         case Platform.X86:
195                                 pekind = PortableExecutableKinds.Required32Bit;
196                                 machine = ImageFileMachine.I386;
197                                 break;
198                         case Platform.X64:
199                                 pekind = PortableExecutableKinds.PE32Plus;
200                                 machine = ImageFileMachine.AMD64;
201                                 break;
202                         case Platform.IA64:
203                                 pekind = PortableExecutableKinds.PE32Plus;
204                                 machine = ImageFileMachine.IA64;
205                                 break;
206                         case Platform.AnyCPU:
207                         default:
208                                 pekind = PortableExecutableKinds.ILOnly;
209                                 machine = ImageFileMachine.I386;
210                                 break;
211                         }
212 #endif
213                         try {
214 #if GMCS_SOURCE
215                                 Assembly.Builder.Save (Basename (name), pekind, machine);
216 #else
217                                 Assembly.Builder.Save (Basename (name));
218 #endif
219                         }
220                         catch (COMException) {
221                                 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
222                                         throw;
223
224                                 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies 
225                                 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
226                                         RootContext.StrongNameKeyFile +
227                                         "', Use MCS with the Mono runtime or CSC to compile this assembly.");
228                         }
229                         catch (System.IO.IOException io) {
230                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
231                                 return;
232                         }
233                         catch (System.UnauthorizedAccessException ua) {
234                                 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
235                                 return;
236                         }
237                         catch (System.NotImplementedException nie) {
238                                 Report.RuntimeMissingSupport (Location.Null, nie.Message);
239                                 return;
240                         }
241
242                         //
243                         // Write debuger symbol file
244                         //
245                         if (saveDebugInfo)
246                                 SymbolWriter.WriteSymbolFile ();
247                         }
248         }
249
250
251         /// <summary>
252         /// An interface to hold all the information needed in the resolving phase.
253         /// </summary>
254         public interface IResolveContext
255         {
256                 //
257                 // A scope type context, it can be inflated for generic types
258                 //
259                 Type CurrentType { get; }
260
261                 //
262                 // A scope type parameters either VAR or MVAR
263                 //
264                 TypeParameter[] CurrentTypeParameters { get; }
265
266                 //
267                 // A type definition of the type context. For partial types definition use
268                 // CurrentTypeDefinition.PartialContainer otherwise the context is local
269                 //
270                 // TODO: CurrentType.Definition
271                 //
272                 TypeContainer CurrentTypeDefinition { get; }
273
274                 bool IsInObsoleteScope { get; }
275                 bool IsInUnsafeScope { get; }
276                 bool IsStatic { get; }
277
278                 ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
279                 FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
280                 FullNamedExpression LookupNamespaceAlias (string name);
281         }
282
283         //
284         // Block or statement resolving context
285         //
286         public class BlockContext : ResolveContext
287         {
288                 FlowBranching current_flow_branching;
289
290                 public BlockContext (IResolveContext mc, ExplicitBlock block, Type returnType)
291                         : base (mc)
292                 {
293                         if (returnType == null)
294                                 throw new ArgumentNullException ("returnType");
295
296                         this.return_type = returnType;
297
298                         // TODO: check for null value
299                         CurrentBlock = block;
300                 }
301
302                 public override FlowBranching CurrentBranching {
303                         get { return current_flow_branching; }
304                 }
305
306                 // <summary>
307                 //   Starts a new code branching.  This inherits the state of all local
308                 //   variables and parameters from the current branching.
309                 // </summary>
310                 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
311                 {
312                         current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
313                         return current_flow_branching;
314                 }
315
316                 // <summary>
317                 //   Starts a new code branching for block `block'.
318                 // </summary>
319                 public FlowBranching StartFlowBranching (Block block)
320                 {
321                         Set (Options.DoFlowAnalysis);
322
323                         current_flow_branching = FlowBranching.CreateBranching (
324                                 CurrentBranching, FlowBranching.BranchingType.Block, block, block.StartLocation);
325                         return current_flow_branching;
326                 }
327
328                 public FlowBranchingTryCatch StartFlowBranching (TryCatch stmt)
329                 {
330                         FlowBranchingTryCatch branching = new FlowBranchingTryCatch (CurrentBranching, stmt);
331                         current_flow_branching = branching;
332                         return branching;
333                 }
334
335                 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
336                 {
337                         FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
338                         current_flow_branching = branching;
339                         return branching;
340                 }
341
342                 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
343                 {
344                         FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
345                         current_flow_branching = branching;
346                         return branching;
347                 }
348
349                 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
350                 {
351                         FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
352                         current_flow_branching = branching;
353                         return branching;
354                 }
355
356                 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt, FlowBranching parent)
357                 {
358                         FlowBranchingToplevel branching = new FlowBranchingToplevel (parent, stmt);
359                         current_flow_branching = branching;
360                         return branching;
361                 }
362
363                 // <summary>
364                 //   Ends a code branching.  Merges the state of locals and parameters
365                 //   from all the children of the ending branching.
366                 // </summary>
367                 public bool EndFlowBranching ()
368                 {
369                         FlowBranching old = current_flow_branching;
370                         current_flow_branching = current_flow_branching.Parent;
371
372                         FlowBranching.UsageVector vector = current_flow_branching.MergeChild (old);
373                         return vector.IsUnreachable;
374                 }
375
376                 // <summary>
377                 //   Kills the current code branching.  This throws away any changed state
378                 //   information and should only be used in case of an error.
379                 // </summary>
380                 // FIXME: this is evil
381                 public void KillFlowBranching ()
382                 {
383                         current_flow_branching = current_flow_branching.Parent;
384                 }
385
386                 //
387                 // This method is used during the Resolution phase to flag the
388                 // need to define the ReturnLabel
389                 //
390                 public void NeedReturnLabel ()
391                 {
392                         if (!HasReturnLabel)
393                                 HasReturnLabel = true;
394                 }
395         }
396
397         /// <summary>
398         ///   An Emit Context is created for each body of code (from methods,
399         ///   properties bodies, indexer bodies or constructor bodies)
400         /// </summary>
401         public class EmitContext : IResolveContext {
402
403                 [Flags]
404                 public enum Options
405                 {
406                         /// <summary>
407                         ///   This flag tracks the `checked' state of the compilation,
408                         ///   it controls whether we should generate code that does overflow
409                         ///   checking, or if we generate code that ignores overflows.
410                         ///
411                         ///   The default setting comes from the command line option to generate
412                         ///   checked or unchecked code plus any source code changes using the
413                         ///   checked/unchecked statements or expressions.   Contrast this with
414                         ///   the ConstantCheckState flag.
415                         /// </summary>
416                         CheckedScope = 1 << 0,
417
418                         /// <summary>
419                         ///   The constant check state is always set to `true' and cant be changed
420                         ///   from the command line.  The source code can change this setting with
421                         ///   the `checked' and `unchecked' statements and expressions. 
422                         /// </summary>
423                         ConstantCheckState = 1 << 1,
424
425                         AllCheckStateFlags = CheckedScope | ConstantCheckState,
426
427                         //
428                         // unsafe { ... } scope
429                         //
430                         UnsafeScope = 1 << 2,
431                         CatchScope = 1 << 3,
432                         FinallyScope = 1 << 4,
433                         FieldInitializerScope = 1 << 5,
434                         CompoundAssignmentScope = 1 << 6,
435                         FixedInitializerScope = 1 << 7,
436                         BaseInitializer = 1 << 8,
437
438                         //
439                         // Inside an enum definition, we do not resolve enumeration values
440                         // to their enumerations, but rather to the underlying type/value
441                         // This is so EnumVal + EnumValB can be evaluated.
442                         //
443                         // There is no "E operator + (E x, E y)", so during an enum evaluation
444                         // we relax the rules
445                         //
446                         EnumScope = 1 << 9,
447
448                         ConstantScope = 1 << 10,
449
450                         ConstructorScope = 1 << 11,
451
452                         /// <summary>
453                         ///   Whether control flow analysis is enabled
454                         /// </summary>
455                         DoFlowAnalysis = 1 << 20,
456
457                         /// <summary>
458                         ///   Whether control flow analysis is disabled on structs
459                         ///   (only meaningful when DoFlowAnalysis is set)
460                         /// </summary>
461                         OmitStructFlowAnalysis = 1 << 21,
462
463                         ///
464                         /// Indicates the current context is in probing mode, no errors are reported. 
465                         ///
466                         ProbingMode = 1 <<      22,
467
468                         //
469                         // Return and ContextualReturn statements will set the ReturnType
470                         // value based on the expression types of each return statement
471                         // instead of the method return type which is initially null.
472                         //
473                         InferReturnType = 1 << 23,
474
475                         OmitDebuggingInfo = 1 << 24
476                 }
477
478                 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
479                 // it's public so that we can use a struct at the callsite
480                 public struct FlagsHandle : IDisposable
481                 {
482                         EmitContext ec;
483                         readonly Options invmask, oldval;
484
485                         public FlagsHandle (EmitContext ec, Options flagsToSet)
486                                 : this (ec, flagsToSet, flagsToSet)
487                         {
488                         }
489
490                         internal FlagsHandle (EmitContext ec, Options mask, Options val)
491                         {
492                                 this.ec = ec;
493                                 invmask = ~mask;
494                                 oldval = ec.flags & mask;
495                                 ec.flags = (ec.flags & invmask) | (val & mask);
496
497                                 if ((mask & Options.ProbingMode) != 0)
498                                         Report.DisableReporting ();
499                         }
500
501                         public void Dispose ()
502                         {
503                                 if ((invmask & Options.ProbingMode) == 0)
504                                         Report.EnableReporting ();
505
506                                 ec.flags = (ec.flags & invmask) | oldval;
507                         }
508                 }
509
510                 Options flags;
511
512                 //
513                 // Holds a varible used during collection or object initialization.
514                 //
515                 public Expression CurrentInitializerVariable;
516
517                 public ILGenerator ig;
518
519                 /// <summary>
520                 ///   The value that is allowed to be returned or NULL if there is no
521                 ///   return type.
522                 /// </summary>
523                 protected Type return_type;
524
525                 /// <summary>
526                 ///   Keeps track of the Type to LocalBuilder temporary storage created
527                 ///   to store structures (used to compute the address of the structure
528                 ///   value on structure method invocations)
529                 /// </summary>
530                 public Hashtable temporary_storage;
531
532                 public Block CurrentBlock;
533
534                 /// <summary>
535                 ///   The location where we store the return value.
536                 /// </summary>
537                 public LocalBuilder return_value;
538
539                 /// <summary>
540                 ///   The location where return has to jump to return the
541                 ///   value
542                 /// </summary>
543                 public Label ReturnLabel;
544
545                 /// <summary>
546                 ///   If we already defined the ReturnLabel
547                 /// </summary>
548                 public bool HasReturnLabel;
549
550                 /// <summary>
551                 ///  Whether we are inside an anonymous method.
552                 /// </summary>
553                 public AnonymousExpression CurrentAnonymousMethod;
554                 
555                 public IResolveContext ResolveContext;
556
557                 /// <summary>
558                 ///    The current iterator
559                 /// </summary>
560                 public Iterator CurrentIterator {
561                         get { return CurrentAnonymousMethod as Iterator; }
562                 }
563
564                 public TypeInferenceContext ReturnTypeInference;
565
566                 public EmitContext (IResolveContext rc, ILGenerator ig, Type return_type)
567                 {
568                         this.ResolveContext = rc;
569                         this.ig = ig;
570
571                         //
572                         // The default setting comes from the command line option
573                         //
574                         if (RootContext.Checked)
575                                 flags |= Options.CheckedScope;
576
577                         //
578                         // The constant check state is always set to true
579                         //
580                         flags |= Options.ConstantCheckState;
581
582                         this.return_type = return_type;
583                 }
584
585                 public virtual FlowBranching CurrentBranching {
586                         get { return null; }
587                 }
588
589                 public Type CurrentType {
590                         get { return ResolveContext.CurrentType; }
591                 }
592
593                 public TypeParameter[] CurrentTypeParameters {
594                         get { return ResolveContext.CurrentTypeParameters; }
595                 }
596
597                 public TypeContainer CurrentTypeDefinition {
598                         get { return ResolveContext.CurrentTypeDefinition; }
599                 }
600
601                 public bool ConstantCheckState {
602                         get { return (flags & Options.ConstantCheckState) != 0; }
603                 }
604
605                 public bool InUnsafe {
606                         get { return HasSet (Options.UnsafeScope) || ResolveContext.IsInUnsafeScope; }
607                 }
608
609                 public bool DoFlowAnalysis {
610                         get { return (flags & Options.DoFlowAnalysis) != 0; }
611                 }
612
613                 public bool OmitStructFlowAnalysis {
614                         get { return (flags & Options.OmitStructFlowAnalysis) != 0; }
615                 }
616
617                 public bool HasSet (Options options)
618                 {
619                         return (this.flags & options) == options;
620                 }
621
622                 public bool HasAny (Options options)
623                 {
624                         return (this.flags & options) != 0;
625                 }
626
627                 // Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
628                 public FlagsHandle Set (Options options)
629                 {
630                         return new FlagsHandle (this, options);
631                 }
632
633                 public FlagsHandle With (Options options, bool enable)
634                 {
635                         return new FlagsHandle (this, options, enable ? options : 0);
636                 }
637
638                 public FlagsHandle WithFlowAnalysis (bool do_flow_analysis, bool omit_struct_analysis)
639                 {
640                         Options newflags = 
641                                 (do_flow_analysis ? Options.DoFlowAnalysis : 0) |
642                                 (omit_struct_analysis ? Options.OmitStructFlowAnalysis : 0);
643                         return new FlagsHandle (this, Options.DoFlowAnalysis | Options.OmitStructFlowAnalysis, newflags);
644                 }
645                 
646                 // IResolveContext.IsInObsoleteScope
647                 public bool IsInObsoleteScope {
648                         get {
649                                 // Disables obsolete checks when probing is on
650                                 return IsInProbingMode || ResolveContext.IsInObsoleteScope;
651                         }
652                 }
653
654                 public bool IsInProbingMode {
655                         get { return (flags & Options.ProbingMode) != 0; }
656                 }
657
658                 bool IResolveContext.IsInUnsafeScope {
659                         get { return InUnsafe; }
660                 }
661
662                 public bool IsStatic {
663                         get { return ResolveContext.IsStatic; }
664                 }
665
666                 public bool IsVariableCapturingRequired {
667                         get {
668                                 return !IsInProbingMode && (CurrentBranching == null || !CurrentBranching.CurrentUsageVector.IsUnreachable);
669                         }
670                 }
671
672                 public bool OmitDebuggingInfo {
673                         get { return (flags & Options.OmitDebuggingInfo) != 0; }
674                         set {
675                                 if (value)
676                                         flags |= Options.OmitDebuggingInfo;
677                                 else
678                                         flags &= ~Options.OmitDebuggingInfo;
679                         }
680                 }
681
682                 public bool MustCaptureVariable (LocalInfo local)
683                 {
684                         if (CurrentAnonymousMethod == null)
685                                 return false;
686
687                         // FIXME: IsIterator is too aggressive, we should capture only if child
688                         // block contains yield
689                         if (CurrentAnonymousMethod.IsIterator)
690                                 return true;
691
692                         return local.Block.Toplevel != CurrentBlock.Toplevel;
693                 }
694                 
695                 public Type ReturnType {
696                         get {
697                                 return return_type;
698                         }
699                 }
700
701                 /// <summary>
702                 ///   This is called immediately before emitting an IL opcode to tell the symbol
703                 ///   writer to which source line this opcode belongs.
704                 /// </summary>
705                 public void Mark (Location loc)
706                 {
707                         if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
708                                 return;
709
710                         SymbolWriter.MarkSequencePoint (ig, loc);
711                 }
712
713                 public void DefineLocalVariable (string name, LocalBuilder builder)
714                 {
715                         SymbolWriter.DefineLocalVariable (name, builder);
716                 }
717
718                 public void BeginScope ()
719                 {
720                         ig.BeginScope();
721                         SymbolWriter.OpenScope(ig);
722                 }
723
724                 public void EndScope ()
725                 {
726                         ig.EndScope();
727                         SymbolWriter.CloseScope(ig);
728                 }
729
730                 /// <summary>
731                 ///   Returns a temporary storage for a variable of type t as 
732                 ///   a local variable in the current body.
733                 /// </summary>
734                 public LocalBuilder GetTemporaryLocal (Type t)
735                 {
736                         if (temporary_storage != null) {
737                                 object o = temporary_storage [t];
738                                 if (o != null) {
739                                         if (o is Stack) {
740                                                 Stack s = (Stack) o;
741                                                 o = s.Count == 0 ? null : s.Pop ();
742                                         } else {
743                                                 temporary_storage.Remove (t);
744                                         }
745                                 }
746                                 if (o != null)
747                                         return (LocalBuilder) o;
748                         }
749                         return ig.DeclareLocal (t);
750                 }
751
752                 public void FreeTemporaryLocal (LocalBuilder b, Type t)
753                 {
754                         if (temporary_storage == null) {
755                                 temporary_storage = new Hashtable ();
756                                 temporary_storage [t] = b;
757                                 return;
758                         }
759                         object o = temporary_storage [t];
760                         if (o == null) {
761                                 temporary_storage [t] = b;
762                                 return;
763                         }
764                         Stack s = o as Stack;
765                         if (s == null) {
766                                 s = new Stack ();
767                                 s.Push (o);
768                                 temporary_storage [t] = s;
769                         }
770                         s.Push (b);
771                 }
772
773                 /// <summary>
774                 ///   Current loop begin and end labels.
775                 /// </summary>
776                 public Label LoopBegin, LoopEnd;
777
778                 /// <summary>
779                 ///   Default target in a switch statement.   Only valid if
780                 ///   InSwitch is true
781                 /// </summary>
782                 public Label DefaultTarget;
783
784                 /// <summary>
785                 ///   If this is non-null, points to the current switch statement
786                 /// </summary>
787                 public Switch Switch;
788
789                 /// <summary>
790                 ///   ReturnValue creates on demand the LocalBuilder for the
791                 ///   return value from the function.  By default this is not
792                 ///   used.  This is only required when returns are found inside
793                 ///   Try or Catch statements.
794                 ///
795                 ///   This method is typically invoked from the Emit phase, so
796                 ///   we allow the creation of a return label if it was not
797                 ///   requested during the resolution phase.   Could be cleaned
798                 ///   up, but it would replicate a lot of logic in the Emit phase
799                 ///   of the code that uses it.
800                 /// </summary>
801                 public LocalBuilder TemporaryReturn ()
802                 {
803                         if (return_value == null){
804                                 return_value = ig.DeclareLocal (return_type);
805                                 if (!HasReturnLabel){
806                                         ReturnLabel = ig.DefineLabel ();
807                                         HasReturnLabel = true;
808                                 }
809                         }
810
811                         return return_value;
812                 }
813
814                 public Expression GetThis (Location loc)
815                 {
816                         This my_this;
817                         if (CurrentBlock != null)
818                                 my_this = new This (CurrentBlock, loc);
819                         else
820                                 my_this = new This (loc);
821
822                         if (!my_this.ResolveBase (this))
823                                 my_this = null;
824
825                         return my_this;
826                 }
827
828                 #region IResolveContext Members
829
830                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
831                 {
832                         return ResolveContext.LookupExtensionMethod (extensionType, name, loc);
833                 }
834
835                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
836                 {
837                         return ResolveContext.LookupNamespaceOrType (name, loc, ignore_cs0104);
838                 }
839
840                 public FullNamedExpression LookupNamespaceAlias (string name)
841                 {
842                         return ResolveContext.LookupNamespaceAlias (name);
843                 }
844
845                 #endregion
846         }
847
848         public class ResolveContext : EmitContext
849         {
850                 public ResolveContext (IResolveContext mc)
851                         : base (mc, null, null)
852                 {
853                 }
854
855                 public ResolveContext (IResolveContext mc, Options options)
856                         : this (mc)
857                 {
858                         Set (options);
859                 }
860         }
861
862
863         public abstract class CommonAssemblyModulClass : Attributable, IResolveContext
864         {
865                 public void AddAttributes (ArrayList attrs, IResolveContext context)
866                 {
867                         foreach (Attribute a in attrs)
868                                 a.AttachTo (this, context);
869
870                         if (attributes == null) {
871                                 attributes = new Attributes (attrs);
872                                 return;
873                         }
874                         attributes.AddAttributes (attrs);
875                 }
876
877                 public virtual void Emit (TypeContainer tc) 
878                 {
879                         if (OptAttributes == null)
880                                 return;
881
882                         OptAttributes.Emit ();
883                 }
884
885                 protected Attribute ResolveAttribute (PredefinedAttribute a_type)
886                 {
887                         Attribute a = OptAttributes.Search (a_type);
888                         if (a != null) {
889                                 a.Resolve ();
890                         }
891                         return a;
892                 }
893
894                 #region IResolveContext Members
895
896                 public Type CurrentType {
897                         get { return null; }
898                 }
899
900                 public TypeParameter[] CurrentTypeParameters {
901                         get { return null; }
902                 }
903
904                 public TypeContainer CurrentTypeDefinition {
905                         get { return RootContext.ToplevelTypes; }
906                 }
907
908                 public DeclSpace DeclContainer {
909                         get { return RootContext.ToplevelTypes; }
910                 }
911
912                 public bool IsInObsoleteScope {
913                         get { return false; }
914                 }
915
916                 public bool IsInUnsafeScope {
917                         get { return false; }
918                 }
919
920                 public bool IsStatic {
921                         get { return false; }
922                 }
923
924                 public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
925                 {
926                         throw new NotImplementedException ();
927                 }
928
929                 public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
930                 {
931                         return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
932                 }
933
934                 public FullNamedExpression LookupNamespaceAlias (string name)
935                 {
936                         return null;
937                 }
938
939                 #endregion
940         }
941                 
942         public class AssemblyClass : CommonAssemblyModulClass {
943                 // TODO: make it private and move all builder based methods here
944                 public AssemblyBuilder Builder;
945                 bool is_cls_compliant;
946                 bool wrap_non_exception_throws;
947
948                 public Attribute ClsCompliantAttribute;
949
950                 ListDictionary declarative_security;
951                 bool has_extension_method;              
952                 public AssemblyName Name;
953                 MethodInfo add_type_forwarder;
954                 ListDictionary emitted_forwarders;
955
956                 // Module is here just because of error messages
957                 static string[] attribute_targets = new string [] { "assembly", "module" };
958
959                 public AssemblyClass (): base ()
960                 {
961                         wrap_non_exception_throws = true;
962                 }
963
964                 public bool HasExtensionMethods {
965                         set {
966                                 has_extension_method = value;
967                         }
968                 }
969
970                 public bool IsClsCompliant {
971                         get {
972                                 return is_cls_compliant;
973                         }
974                 }
975
976                 public bool WrapNonExceptionThrows {
977                         get {
978                                 return wrap_non_exception_throws;
979                         }
980                 }
981
982                 public override AttributeTargets AttributeTargets {
983                         get {
984                                 return AttributeTargets.Assembly;
985                         }
986                 }
987
988                 public override bool IsClsComplianceRequired ()
989                 {
990                         return is_cls_compliant;
991                 }
992
993                 public void Resolve ()
994                 {
995                         if (RootContext.Unsafe) {
996                                 //
997                                 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
998                                 // when -unsafe option was specified
999                                 //
1000                                 
1001                                 Location loc = Location.Null;
1002
1003                                 MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
1004                                         new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
1005
1006                                 Arguments pos = new Arguments (1);
1007                                 pos.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions, "SecurityAction", loc), "RequestMinimum")));
1008
1009                                 Arguments named = new Arguments (1);
1010                                 named.Add (new NamedArgument (new LocatedToken (loc, "SkipVerification"), (new BoolLiteral (true, loc))));
1011
1012                                 GlobalAttribute g = new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly",
1013                                         new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
1014                                         new Arguments[] { pos, named }, loc, false);
1015                                 g.AttachTo (this, this);
1016
1017                                 if (g.Resolve () != null) {
1018                                         declarative_security = new ListDictionary ();
1019                                         g.ExtractSecurityPermissionSet (declarative_security);
1020                                 }
1021                         }
1022
1023                         if (OptAttributes == null)
1024                                 return;
1025
1026                         // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1027                         if (!OptAttributes.CheckTargets())
1028                                 return;
1029
1030                         ClsCompliantAttribute = ResolveAttribute (PredefinedAttributes.Get.CLSCompliant);
1031
1032                         if (ClsCompliantAttribute != null) {
1033                                 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1034                         }
1035
1036                         Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
1037                         if (a != null) {
1038                                 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1039                                 if (val != null)
1040                                         wrap_non_exception_throws = (bool) val;
1041                         }
1042                 }
1043
1044                 // fix bug #56621
1045                 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob) 
1046                 {
1047                         try {
1048                                 // check for possible ECMA key
1049                                 if (strongNameBlob.Length == 16) {
1050                                         // will be rejected if not "the" ECMA key
1051                                         an.SetPublicKey (strongNameBlob);
1052                                 }
1053                                 else {
1054                                         // take it, with or without, a private key
1055                                         RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1056                                         // and make sure we only feed the public part to Sys.Ref
1057                                         byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1058                                         
1059                                         // AssemblyName.SetPublicKey requires an additional header
1060                                         byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1061
1062                                         byte[] encodedPublicKey = new byte [12 + publickey.Length];
1063                                         Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1064                                         Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1065                                         an.SetPublicKey (encodedPublicKey);
1066                                 }
1067                         }
1068                         catch (Exception) {
1069                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1070                                 Environment.Exit (1);
1071                         }
1072                 }
1073
1074                 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1075                 public AssemblyName GetAssemblyName (string name, string output) 
1076                 {
1077                         if (OptAttributes != null) {
1078                                 foreach (Attribute a in OptAttributes.Attrs) {
1079                                         // cannot rely on any resolve-based members before you call Resolve
1080                                         if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1081                                                 continue;
1082
1083                                         // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1084                                         //       However, this is invoked by CodeGen.Init, when none of the namespaces
1085                                         //       are loaded yet.
1086                                         // TODO: Does not handle quoted attributes properly
1087                                         switch (a.Name) {
1088                                         case "AssemblyKeyFile":
1089                                         case "AssemblyKeyFileAttribute":
1090                                         case "System.Reflection.AssemblyKeyFileAttribute":
1091                                                 if (RootContext.StrongNameKeyFile != null) {
1092                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1093                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1094                                                                         "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1095                                                 } else {
1096                                                         string value = a.GetString ();
1097                                                         if (value != null && value.Length != 0)
1098                                                                 RootContext.StrongNameKeyFile = value;
1099                                                 }
1100                                                 break;
1101                                         case "AssemblyKeyName":
1102                                         case "AssemblyKeyNameAttribute":
1103                                         case "System.Reflection.AssemblyKeyNameAttribute":
1104                                                 if (RootContext.StrongNameKeyContainer != null) {
1105                                                         Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
1106                                                         Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1107                                                                         "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1108                                                 } else {
1109                                                         string value = a.GetString ();
1110                                                         if (value != null && value.Length != 0)
1111                                                                 RootContext.StrongNameKeyContainer = value;
1112                                                 }
1113                                                 break;
1114                                         case "AssemblyDelaySign":
1115                                         case "AssemblyDelaySignAttribute":
1116                                         case "System.Reflection.AssemblyDelaySignAttribute":
1117                                                 RootContext.StrongNameDelaySign = a.GetBoolean ();
1118                                                 break;
1119                                         }
1120                                 }
1121                         }
1122                         
1123                         AssemblyName an = new AssemblyName ();
1124                         an.Name = Path.GetFileNameWithoutExtension (name);
1125
1126                         // note: delay doesn't apply when using a key container
1127                         if (RootContext.StrongNameKeyContainer != null) {
1128                                 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1129                                 return an;
1130                         }
1131
1132                         // strongname is optional
1133                         if (RootContext.StrongNameKeyFile == null)
1134                                 return an;
1135
1136                         string AssemblyDir = Path.GetDirectoryName (output);
1137
1138                         // the StrongName key file may be relative to (a) the compiled
1139                         // file or (b) to the output assembly. See bugzilla #55320
1140                         // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1141
1142                         // (a) relative to the compiled file
1143                         string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1144                         bool exist = File.Exists (filename);
1145                         if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1146                                 // (b) relative to the outputed assembly
1147                                 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1148                                 exist = File.Exists (filename);
1149                         }
1150
1151                         if (exist) {
1152                                 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1153                                         byte[] snkeypair = new byte [fs.Length];
1154                                         fs.Read (snkeypair, 0, snkeypair.Length);
1155
1156                                         if (RootContext.StrongNameDelaySign) {
1157                                                 // delayed signing - DO NOT include private key
1158                                                 SetPublicKey (an, snkeypair);
1159                                         }
1160                                         else {
1161                                                 // no delay so we make sure we have the private key
1162                                                 try {
1163                                                         CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1164                                                         an.KeyPair = new StrongNameKeyPair (snkeypair);
1165                                                 }
1166                                                 catch (CryptographicException) {
1167                                                         if (snkeypair.Length == 16) {
1168                                                                 // error # is different for ECMA key
1169                                                                 Report.Error (1606, "Could not sign the assembly. " + 
1170                                                                         "ECMA key can only be used to delay-sign assemblies");
1171                                                         }
1172                                                         else {
1173                                                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1174                                                         }
1175                                                         return null;
1176                                                 }
1177                                         }
1178                                 }
1179                         }
1180                         else {
1181                                 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1182                                 return null;
1183                         }
1184                         return an;
1185                 }
1186
1187                 void Error_AssemblySigning (string text)
1188                 {
1189                         Report.Error (1548, "Error during assembly signing. " + text);
1190                 }
1191
1192                 bool CheckInternalsVisibleAttribute (Attribute a)
1193                 {
1194                         string assembly_name = a.GetString ();
1195                         if (assembly_name.Length == 0)
1196                                 return false;
1197                                 
1198                         AssemblyName aname = null;
1199                         try {
1200 #if GMCS_SOURCE
1201                                 aname = new AssemblyName (assembly_name);
1202 #else
1203                                 throw new NotSupportedException ();
1204 #endif
1205                         } catch (FileLoadException) {
1206                         } catch (ArgumentException) {
1207                         }
1208                                 
1209                         // Bad assembly name format
1210                         if (aname == null)
1211                                 Report.Warning (1700, 3, a.Location, "Assembly reference `" + assembly_name + "' is invalid and cannot be resolved");
1212                         // Report error if we have defined Version or Culture
1213                         else if (aname.Version != null || aname.CultureInfo != null)
1214                                 throw new Exception ("Friend assembly `" + a.GetString () + 
1215                                                 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1216                         else if (aname.GetPublicKey () == null && Name.GetPublicKey () != null && Name.GetPublicKey ().Length != 0) {
1217                                 Report.Error (1726, a.Location, "Friend assembly reference `" + aname.FullName + "' is invalid." +
1218                                                 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1219                                 return false;
1220                         }
1221
1222                         return true;
1223                 }
1224
1225                 static bool IsValidAssemblyVersion (string version)
1226                 {
1227                         Version v;
1228                         try {
1229                                 v = new Version (version);
1230                         } catch {
1231                                 try {
1232                                         int major = int.Parse (version, CultureInfo.InvariantCulture);
1233                                         v = new Version (major, 0);
1234                                 } catch {
1235                                         return false;
1236                                 }
1237                         }
1238
1239                         foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1240                                 if (candidate > ushort.MaxValue)
1241                                         return false;
1242                         }
1243
1244                         return true;
1245                 }
1246
1247                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
1248                 {
1249                         if (a.IsValidSecurityAttribute ()) {
1250                                 if (declarative_security == null)
1251                                         declarative_security = new ListDictionary ();
1252
1253                                 a.ExtractSecurityPermissionSet (declarative_security);
1254                                 return;
1255                         }
1256
1257                         if (a.Type == pa.AssemblyCulture) {
1258                                 string value = a.GetString ();
1259                                 if (value == null || value.Length == 0)
1260                                         return;
1261
1262                                 if (RootContext.Target == Target.Exe) {
1263                                         a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1264                                         return;
1265                                 }
1266                         }
1267
1268                         if (a.Type == pa.AssemblyVersion) {
1269                                 string value = a.GetString ();
1270                                 if (value == null || value.Length == 0)
1271                                         return;
1272
1273                                 value = value.Replace ('*', '0');
1274
1275                                 if (!IsValidAssemblyVersion (value)) {
1276                                         a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1277                                         return;
1278                                 }
1279                         }
1280
1281                         if (a.Type == pa.InternalsVisibleTo && !CheckInternalsVisibleAttribute (a))
1282                                 return;
1283
1284                         if (a.Type == pa.TypeForwarder) {
1285                                 Type t = a.GetArgumentType ();
1286                                 if (t == null || TypeManager.HasElementType (t)) {
1287                                         Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
1288                                         return;
1289                                 }
1290
1291                                 t = TypeManager.DropGenericTypeArguments (t);
1292                                 if (emitted_forwarders == null) {
1293                                         emitted_forwarders = new ListDictionary();
1294                                 } else if (emitted_forwarders.Contains(t)) {
1295                                         Report.SymbolRelatedToPreviousError(((Attribute)emitted_forwarders[t]).Location, null);
1296                                         Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
1297                                                 TypeManager.CSharpName(t));
1298                                         return;
1299                                 }
1300
1301                                 emitted_forwarders.Add(t, a);
1302
1303                                 if (TypeManager.LookupDeclSpace (t) != null) {
1304                                         Report.SymbolRelatedToPreviousError (t);
1305                                         Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
1306                                                 TypeManager.CSharpName (t));
1307                                         return;
1308                                 }
1309
1310                                 if (t.DeclaringType != null) {
1311                                         Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1312                                                 TypeManager.CSharpName (t));
1313                                         return;
1314                                 }
1315
1316                                 if (add_type_forwarder == null) {
1317                                         add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder",
1318                                                 BindingFlags.NonPublic | BindingFlags.Instance);
1319
1320                                         if (add_type_forwarder == null) {
1321                                                 Report.RuntimeMissingSupport (a.Location, "TypeForwardedTo attribute");
1322                                                 return;
1323                                         }
1324                                 }
1325
1326                                 add_type_forwarder.Invoke (Builder, new object[] { t });
1327                                 return;
1328                         }
1329                         
1330                         if (a.Type == pa.Extension) {
1331                                 a.Error_MisusedExtensionAttribute ();
1332                                 return;
1333                         }
1334
1335                         Builder.SetCustomAttribute (cb);
1336                 }
1337
1338                 public override void Emit (TypeContainer tc)
1339                 {
1340                         base.Emit (tc);
1341
1342                         if (has_extension_method)
1343                                 PredefinedAttributes.Get.Extension.EmitAttribute (Builder);
1344
1345                         // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1346                         PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
1347                         if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
1348                                 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
1349                                         pa.Type, Location.Null, Type.EmptyTypes);
1350                                 PropertyInfo [] pis = new PropertyInfo [1];
1351                                 pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
1352                                         "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type);
1353                                 object [] pargs = new object [1];
1354                                 pargs [0] = true;
1355                                 Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
1356                         }
1357
1358                         if (declarative_security != null) {
1359
1360                                 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1361                                 object builder_instance = Builder;
1362
1363                                 try {
1364                                         // Microsoft runtime hacking
1365                                         if (add_permission == null) {
1366                                                 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1367                                                 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1368
1369                                                 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1370                                                 builder_instance = fi.GetValue (Builder);
1371                                         }
1372
1373                                         object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1374                                                                                                   declarative_security [SecurityAction.RequestOptional],
1375                                                                                                   declarative_security [SecurityAction.RequestRefuse] };
1376                                         add_permission.Invoke (builder_instance, args);
1377                                 }
1378                                 catch {
1379                                         Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1380                                 }
1381                         }
1382                 }
1383
1384                 public override string[] ValidAttributeTargets {
1385                         get {
1386                                 return attribute_targets;
1387                         }
1388                 }
1389
1390                 // Wrapper for AssemblyBuilder.AddModule
1391                 static MethodInfo adder_method;
1392                 static public MethodInfo AddModule_Method {
1393                         get {
1394                                 if (adder_method == null)
1395                                         adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance|BindingFlags.NonPublic);
1396                                 return adder_method;
1397                         }
1398                 }
1399                 public Module AddModule (string module)
1400                 {
1401                         MethodInfo m = AddModule_Method;
1402                         if (m == null) {
1403                                 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1404                                 Environment.Exit (1);
1405                         }
1406
1407                         try {
1408                                 return (Module) m.Invoke (Builder, new object [] { module });
1409                         } catch (TargetInvocationException ex) {
1410                                 throw ex.InnerException;
1411                         }
1412                 }               
1413         }
1414 }