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