2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002, 2003 Ximian, Inc.
8 // (C) 2004 Novell, Inc.
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
19 using System.Security.Cryptography;
20 using System.Security.Permissions;
22 using Mono.Security.Cryptography;
24 namespace Mono.CSharp {
27 /// Code generator class.
29 public class CodeGen {
30 static AppDomain current_domain;
31 static public SymbolWriter SymbolWriter;
33 public static AssemblyClass Assembly;
34 public static ModuleClass Module;
41 public static void Reset ()
43 Assembly = new AssemblyClass ();
44 Module = new ModuleClass (RootContext.Unsafe);
47 public static string Basename (string name)
49 int pos = name.LastIndexOf ('/');
52 return name.Substring (pos + 1);
54 pos = name.LastIndexOf ('\\');
56 return name.Substring (pos + 1);
61 public static string Dirname (string name)
63 int pos = name.LastIndexOf ('/');
66 return name.Substring (0, pos);
68 pos = name.LastIndexOf ('\\');
70 return name.Substring (0, pos);
75 static public string FileName;
78 // Initializes the symbol writer
80 static void InitializeSymbolWriter (string filename)
82 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
85 // If we got an ISymbolWriter instance, initialize it.
87 if (SymbolWriter == null) {
89 -18, "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll). This is normally an installation problem. Please make sure to compile and install the mcs/class/Mono.CompilerServices.SymbolWriter directory.");
95 // Initializes the code generator variables
97 static public bool Init (string name, string output, bool want_debugging_support)
100 AssemblyName an = Assembly.GetAssemblyName (name, output);
104 if (an.KeyPair != null) {
105 // If we are going to strong name our assembly make
106 // sure all its refs are strong named
107 foreach (Assembly a in TypeManager.GetAssemblies ()) {
108 AssemblyName ref_name = a.GetName ();
109 byte [] b = ref_name.GetPublicKeyToken ();
110 if (b == null || b.Length == 0) {
111 Report.Warning (1577, "Assembly generation failed " +
112 "-- Referenced assembly '" +
114 "' does not have a strong name.");
115 //Environment.Exit (1);
120 current_domain = AppDomain.CurrentDomain;
123 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
124 AssemblyBuilderAccess.Save, Dirname (name));
126 catch (ArgumentException) {
127 // specified key may not be exportable outside it's container
128 if (RootContext.StrongNameKeyContainer != null) {
129 Report.Error (1548, "Could not access the key inside the container `" +
130 RootContext.StrongNameKeyContainer + "'.");
131 Environment.Exit (1);
135 catch (CryptographicException) {
136 if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null)) {
137 Report.Error (1548, "Could not use the specified key to strongname the assembly.");
138 Environment.Exit (1);
144 // Pass a path-less name to DefineDynamicModule. Wonder how
145 // this copes with output in different directories then.
146 // FIXME: figure out how this copes with --output /tmp/blah
148 // If the third argument is true, the ModuleBuilder will dynamically
149 // load the default symbol writer.
151 Module.Builder = Assembly.Builder.DefineDynamicModule (
152 Basename (name), Basename (output), false);
154 if (want_debugging_support)
155 InitializeSymbolWriter (output);
160 static public void Save (string name)
163 Assembly.Builder.Save (Basename (name));
165 catch (COMException) {
166 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
169 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
170 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
171 RootContext.StrongNameKeyFile +
172 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
174 catch (System.IO.IOException io) {
175 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
177 catch (System.UnauthorizedAccessException ua) {
178 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
181 if (SymbolWriter != null)
182 SymbolWriter.WriteSymbolFile ();
187 // Provides "local" store across code that can yield: locals
188 // or fields, notice that this should not be used by anonymous
189 // methods to create local storage, those only require
192 public class VariableStorage {
198 public VariableStorage (EmitContext ec, Type t)
202 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
204 local = ec.ig.DeclareLocal (t);
207 public void EmitThis (ILGenerator ig)
210 ig.Emit (OpCodes.Ldarg_0);
213 public void EmitStore (ILGenerator ig)
216 ig.Emit (OpCodes.Stloc, local);
218 ig.Emit (OpCodes.Stfld, fb);
221 public void EmitLoad (ILGenerator ig)
224 ig.Emit (OpCodes.Ldloc, local);
226 ig.Emit (OpCodes.Ldfld, fb);
229 public void EmitLoadAddress (ILGenerator ig)
232 ig.Emit (OpCodes.Ldloca, local);
234 ig.Emit (OpCodes.Ldflda, fb);
237 public void EmitCall (ILGenerator ig, MethodInfo mi)
239 // FIXME : we should handle a call like tostring
240 // here, where boxing is needed. However, we will
241 // never encounter that with the current usage.
243 bool value_type_call;
246 value_type_call = local.LocalType.IsValueType;
249 ig.Emit (OpCodes.Ldloca, local);
251 ig.Emit (OpCodes.Ldloc, local);
253 value_type_call = fb.FieldType.IsValueType;
256 ig.Emit (OpCodes.Ldflda, fb);
258 ig.Emit (OpCodes.Ldfld, fb);
261 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
266 /// An Emit Context is created for each body of code (from methods,
267 /// properties bodies, indexer bodies or constructor bodies)
269 public class EmitContext {
270 public DeclSpace DeclSpace;
271 public DeclSpace TypeContainer;
272 public ILGenerator ig;
275 /// This variable tracks the `checked' state of the compilation,
276 /// it controls whether we should generate code that does overflow
277 /// checking, or if we generate code that ignores overflows.
279 /// The default setting comes from the command line option to generate
280 /// checked or unchecked code plus any source code changes using the
281 /// checked/unchecked statements or expressions. Contrast this with
282 /// the ConstantCheckState flag.
285 public bool CheckState;
288 /// The constant check state is always set to `true' and cant be changed
289 /// from the command line. The source code can change this setting with
290 /// the `checked' and `unchecked' statements and expressions.
292 public bool ConstantCheckState;
295 /// Whether we are emitting code inside a static or instance method
297 public bool IsStatic;
300 /// Whether the actual created method is static or instance method.
301 /// Althoug the method might be declared as `static', if an anonymous
302 /// method is involved, we might turn this into an instance method.
304 /// So this reflects the low-level staticness of the method, while
305 /// IsStatic represents the semantic, high-level staticness.
307 public bool MethodIsStatic;
310 /// Whether we are emitting a field initializer
312 public bool IsFieldInitializer;
315 /// The value that is allowed to be returned or NULL if there is no
318 public Type ReturnType;
321 /// Points to the Type (extracted from the TypeContainer) that
322 /// declares this body of code
324 public Type ContainerType;
327 /// Whether this is generating code for a constructor
329 public bool IsConstructor;
332 /// Whether we're control flow analysis enabled
334 public bool DoFlowAnalysis;
337 /// Keeps track of the Type to LocalBuilder temporary storage created
338 /// to store structures (used to compute the address of the structure
339 /// value on structure method invocations)
341 public Hashtable temporary_storage;
343 public Block CurrentBlock;
345 public int CurrentFile;
348 /// The location where we store the return value.
350 LocalBuilder return_value;
353 /// The location where return has to jump to return the
356 public Label ReturnLabel;
359 /// If we already defined the ReturnLabel
361 public bool HasReturnLabel;
364 /// Whether we are inside an iterator block.
366 public bool InIterator;
368 public bool IsLastStatement;
371 /// Whether remapping of locals, parameters and fields is turned on.
372 /// Used by iterators and anonymous methods.
374 public bool RemapToProxy;
377 /// Whether we are inside an unsafe block
379 public bool InUnsafe;
382 /// Whether we are in a `fixed' initialization
384 public bool InFixedInitializer;
386 public bool InRefOutArgumentResolving;
389 public bool InFinally;
392 /// Whether we are inside an anonymous method.
394 public AnonymousMethod CurrentAnonymousMethod;
397 /// Location for this EmitContext
402 /// Inside an enum definition, we do not resolve enumeration values
403 /// to their enumerations, but rather to the underlying type/value
404 /// This is so EnumVal + EnumValB can be evaluated.
406 /// There is no "E operator + (E x, E y)", so during an enum evaluation
407 /// we relax the rules
409 public bool InEnumContext;
412 /// Anonymous methods can capture local variables and fields,
413 /// this object tracks it. It is copied from the TopLevelBlock
416 public CaptureContext capture_context;
419 /// Trace when method is called and is obsolete then this member suppress message
420 /// when call is inside next [Obsolete] method or type.
422 public bool TestObsoleteMethodUsage = true;
425 /// The current iterator
427 public Iterator CurrentIterator;
430 /// Whether we are in the resolving stage or not
439 FlowBranching current_flow_branching;
441 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
442 Type return_type, int code_flags, bool is_constructor)
446 TypeContainer = parent;
448 CheckState = RootContext.Checked;
449 ConstantCheckState = true;
451 IsStatic = (code_flags & Modifiers.STATIC) != 0;
452 MethodIsStatic = IsStatic;
453 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
454 RemapToProxy = InIterator;
455 ReturnType = return_type;
456 IsConstructor = is_constructor;
459 current_phase = Phase.Created;
462 // Can only be null for the ResolveType contexts.
463 ContainerType = parent.TypeBuilder;
464 if (parent.UnsafeContext)
467 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
471 if (ReturnType == TypeManager.void_type)
475 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
476 Type return_type, int code_flags, bool is_constructor)
477 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
481 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
482 Type return_type, int code_flags)
483 : this (tc, tc, l, ig, return_type, code_flags, false)
487 public FlowBranching CurrentBranching {
489 return current_flow_branching;
493 public bool HaveCaptureInfo {
495 return capture_context != null;
500 // Starts a new code branching. This inherits the state of all local
501 // variables and parameters from the current branching.
503 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
505 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
506 return current_flow_branching;
510 // Starts a new code branching for block `block'.
512 public FlowBranching StartFlowBranching (Block block)
514 FlowBranching.BranchingType type;
516 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
517 type = FlowBranching.BranchingType.SwitchSection;
519 type = FlowBranching.BranchingType.Block;
521 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
522 return current_flow_branching;
525 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
527 FlowBranchingException branching = new FlowBranchingException (
528 CurrentBranching, stmt);
529 current_flow_branching = branching;
534 // Ends a code branching. Merges the state of locals and parameters
535 // from all the children of the ending branching.
537 public FlowBranching.UsageVector DoEndFlowBranching ()
539 FlowBranching old = current_flow_branching;
540 current_flow_branching = current_flow_branching.Parent;
542 return current_flow_branching.MergeChild (old);
546 // Ends a code branching. Merges the state of locals and parameters
547 // from all the children of the ending branching.
549 public FlowBranching.Reachability EndFlowBranching ()
551 FlowBranching.UsageVector vector = DoEndFlowBranching ();
553 return vector.Reachability;
557 // Kills the current code branching. This throws away any changed state
558 // information and should only be used in case of an error.
560 public void KillFlowBranching ()
562 current_flow_branching = current_flow_branching.Parent;
565 public void CaptureVariable (LocalInfo li)
567 capture_context.AddLocal (CurrentAnonymousMethod, li);
568 li.IsCaptured = true;
571 public void CaptureParameter (string name, Type t, int idx)
573 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
576 public void CaptureThis ()
578 capture_context.CaptureThis ();
583 // Use to register a field as captured
585 public void CaptureField (FieldExpr fe)
587 capture_context.AddField (fe);
591 // Whether anonymous methods have captured variables
593 public bool HaveCapturedVariables ()
595 if (capture_context != null)
596 return capture_context.HaveCapturedVariables;
601 // Whether anonymous methods have captured fields or this.
603 public bool HaveCapturedFields ()
605 if (capture_context != null)
606 return capture_context.HaveCapturedFields;
611 // Emits the instance pointer for the host method
613 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
615 if (capture_context != null)
616 capture_context.EmitMethodHostInstance (target, am);
618 target.ig.Emit (OpCodes.Ldnull);
620 target.ig.Emit (OpCodes.Ldarg_0);
624 // Returns whether the `local' variable has been captured by an anonymous
627 public bool IsCaptured (LocalInfo local)
629 return capture_context.IsCaptured (local);
632 public bool IsParameterCaptured (string name)
634 if (capture_context != null)
635 return capture_context.IsParameterCaptured (name);
639 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
641 if (capture_context != null)
642 capture_context.EmitAnonymousHelperClasses (this);
646 ReturnLabel = ig.DefineLabel ();
650 // Here until we can fix the problem with Mono.CSharp.Switch, which
651 // currently can not cope with ig == null during resolve (which must
652 // be fixed for switch statements to work on anonymous methods).
654 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
661 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
662 EmitMeta (block, ip);
664 current_phase = Phase.Emitting;
665 EmitResolvedTopBlock (block, unreachable);
669 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
670 InternalParameters ip, Location loc, out bool unreachable)
672 current_phase = Phase.Resolving;
676 capture_context = block.CaptureContext;
678 if (!Location.IsNull (loc))
679 CurrentFile = loc.File;
684 int errors = Report.Errors;
686 block.ResolveMeta (block, this, ip);
687 if (Report.Errors != errors)
690 bool old_do_flow_analysis = DoFlowAnalysis;
691 DoFlowAnalysis = true;
693 if (anonymous_method_host != null)
694 current_flow_branching = FlowBranching.CreateBranching (
695 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
698 current_flow_branching = FlowBranching.CreateBranching (
699 null, FlowBranching.BranchingType.Block, block, loc);
701 if (!block.Resolve (this)) {
702 current_flow_branching = null;
703 DoFlowAnalysis = old_do_flow_analysis;
707 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
708 current_flow_branching = null;
710 DoFlowAnalysis = old_do_flow_analysis;
712 if (reachability.AlwaysReturns ||
713 reachability.AlwaysThrows ||
714 reachability.IsUnreachable)
717 } catch (Exception e) {
718 Console.WriteLine ("Exception caught by the compiler while compiling:");
719 Console.WriteLine (" Block that caused the problem begin at: " + loc);
721 if (CurrentBlock != null){
722 Console.WriteLine (" Block being compiled: [{0},{1}]",
723 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
725 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
730 if (ReturnType != null && !unreachable){
732 if (CurrentAnonymousMethod != null){
733 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
734 CurrentAnonymousMethod.Type);
736 Report.Error (161, loc, "Not all code paths return a value");
742 block.CompleteContexts ();
747 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
753 ig.MarkLabel (ReturnLabel);
755 if (return_value != null){
756 ig.Emit (OpCodes.Ldloc, return_value);
757 ig.Emit (OpCodes.Ret);
760 // If `HasReturnLabel' is set, then we already emitted a
761 // jump to the end of the method, so we must emit a `ret'
764 // Unfortunately, System.Reflection.Emit automatically emits
765 // a leave to the end of a finally block. This is a problem
766 // if no code is following the try/finally block since we may
767 // jump to a point after the end of the method.
768 // As a workaround, we're always creating a return label in
772 if ((block != null) && block.IsDestructor) {
773 // Nothing to do; S.R.E automatically emits a leave.
774 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
775 if (ReturnType != null)
776 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
777 ig.Emit (OpCodes.Ret);
782 // Close pending helper classes if we are the toplevel
784 if (capture_context != null && capture_context.ParentToplevel == null)
785 capture_context.CloseAnonymousHelperClasses ();
789 /// This is called immediately before emitting an IL opcode to tell the symbol
790 /// writer to which source line this opcode belongs.
792 public void Mark (Location loc, bool check_file)
794 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
797 if (check_file && (CurrentFile != loc.File))
800 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
803 public void DefineLocalVariable (string name, LocalBuilder builder)
805 if (CodeGen.SymbolWriter == null)
808 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
811 public void BeginScope ()
815 if (CodeGen.SymbolWriter != null)
816 CodeGen.SymbolWriter.OpenScope(ig);
819 public void EndScope ()
823 if (CodeGen.SymbolWriter != null)
824 CodeGen.SymbolWriter.CloseScope(ig);
828 /// Returns a temporary storage for a variable of type t as
829 /// a local variable in the current body.
831 public LocalBuilder GetTemporaryLocal (Type t)
833 LocalBuilder location = null;
835 if (temporary_storage != null){
836 object o = temporary_storage [t];
839 ArrayList al = (ArrayList) o;
841 for (int i = 0; i < al.Count; i++){
843 location = (LocalBuilder) al [i];
849 location = (LocalBuilder) o;
850 if (location != null)
855 return ig.DeclareLocal (t);
858 public void FreeTemporaryLocal (LocalBuilder b, Type t)
860 if (temporary_storage == null){
861 temporary_storage = new Hashtable ();
862 temporary_storage [t] = b;
865 object o = temporary_storage [t];
867 temporary_storage [t] = b;
871 ArrayList al = (ArrayList) o;
872 for (int i = 0; i < al.Count; i++){
881 ArrayList replacement = new ArrayList ();
883 temporary_storage.Remove (t);
884 temporary_storage [t] = replacement;
888 /// Current loop begin and end labels.
890 public Label LoopBegin, LoopEnd;
893 /// Default target in a switch statement. Only valid if
896 public Label DefaultTarget;
899 /// If this is non-null, points to the current switch statement
901 public Switch Switch;
904 /// ReturnValue creates on demand the LocalBuilder for the
905 /// return value from the function. By default this is not
906 /// used. This is only required when returns are found inside
907 /// Try or Catch statements.
909 /// This method is typically invoked from the Emit phase, so
910 /// we allow the creation of a return label if it was not
911 /// requested during the resolution phase. Could be cleaned
912 /// up, but it would replicate a lot of logic in the Emit phase
913 /// of the code that uses it.
915 public LocalBuilder TemporaryReturn ()
917 if (return_value == null){
918 return_value = ig.DeclareLocal (ReturnType);
919 if (!HasReturnLabel){
920 ReturnLabel = ig.DefineLabel ();
921 HasReturnLabel = true;
929 /// This method is used during the Resolution phase to flag the
930 /// need to define the ReturnLabel
932 public void NeedReturnLabel ()
934 if (current_phase != Phase.Resolving){
936 // The reason is that the `ReturnLabel' is declared between
937 // resolution and emission
939 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
942 if (!InIterator && !HasReturnLabel)
943 HasReturnLabel = true;
947 // Creates a field `name' with the type `t' on the proxy class
949 public FieldBuilder MapVariable (string name, Type t)
952 return CurrentIterator.MapVariable ("v_", name, t);
954 throw new Exception ("MapVariable for an unknown state");
957 public Expression RemapParameter (int idx)
959 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
960 fe.InstanceExpression = new ProxyInstance ();
961 return fe.DoResolve (this);
964 public Expression RemapParameterLValue (int idx, Expression right_side)
966 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
967 fe.InstanceExpression = new ProxyInstance ();
968 return fe.DoResolveLValue (this, right_side);
972 // Emits the proper object to address fields on a remapped
973 // variable/parameter to field in anonymous-method/iterator proxy classes.
975 public void EmitThis ()
977 ig.Emit (OpCodes.Ldarg_0);
980 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
981 if (TypeManager.IsValueType (this_field.FieldType))
982 ig.Emit (OpCodes.Ldflda, this_field);
984 ig.Emit (OpCodes.Ldfld, this_field);
986 } else if (capture_context != null && CurrentAnonymousMethod != null){
987 ScopeInfo si = CurrentAnonymousMethod.Scope;
989 if (si.ParentLink != null)
990 ig.Emit (OpCodes.Ldfld, si.ParentLink);
991 if (si.THIS != null){
992 ig.Emit (OpCodes.Ldfld, si.THIS);
1001 // Emits the code necessary to load the instance required
1002 // to access the captured LocalInfo
1004 public void EmitCapturedVariableInstance (LocalInfo li)
1007 ig.Emit (OpCodes.Ldarg_0);
1011 if (capture_context == null)
1012 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
1014 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
1017 public void EmitParameter (string name)
1019 capture_context.EmitParameter (this, name);
1022 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
1024 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
1027 public void EmitAddressOfParameter (string name)
1029 capture_context.EmitAddressOfParameter (this, name);
1032 public Expression GetThis (Location loc)
1035 if (CurrentBlock != null)
1036 my_this = new This (CurrentBlock, loc);
1038 my_this = new This (loc);
1040 if (!my_this.ResolveBase (this))
1048 public abstract class CommonAssemblyModulClass: Attributable {
1049 protected CommonAssemblyModulClass ():
1054 public void AddAttributes (ArrayList attrs)
1056 if (OptAttributes == null) {
1057 OptAttributes = new Attributes (attrs);
1060 OptAttributes.AddAttributes (attrs);
1063 public virtual void Emit (TypeContainer tc)
1065 if (OptAttributes == null)
1068 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1069 OptAttributes.Emit (ec, this);
1072 protected Attribute ResolveAttribute (Type a_type)
1074 if (OptAttributes == null)
1077 // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1078 if (!OptAttributes.CheckTargets (this))
1081 EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1082 Attribute a = OptAttributes.Search (a_type, temp_ec);
1084 a.Resolve (temp_ec);
1090 public class AssemblyClass: CommonAssemblyModulClass {
1091 // TODO: make it private and move all builder based methods here
1092 public AssemblyBuilder Builder;
1093 bool is_cls_compliant;
1094 public Attribute ClsCompliantAttribute;
1096 ListDictionary declarative_security;
1098 static string[] attribute_targets = new string [] { "assembly" };
1100 public AssemblyClass (): base ()
1102 is_cls_compliant = false;
1105 public bool IsClsCompliant {
1107 return is_cls_compliant;
1111 public override AttributeTargets AttributeTargets {
1113 return AttributeTargets.Assembly;
1117 public override bool IsClsCompliaceRequired(DeclSpace ds)
1119 return is_cls_compliant;
1122 public void ResolveClsCompliance ()
1124 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1125 if (ClsCompliantAttribute == null)
1128 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1132 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1135 // check for possible ECMA key
1136 if (strongNameBlob.Length == 16) {
1137 // will be rejected if not "the" ECMA key
1138 an.SetPublicKey (strongNameBlob);
1141 // take it, with or without, a private key
1142 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1143 // and make sure we only feed the public part to Sys.Ref
1144 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1146 // AssemblyName.SetPublicKey requires an additional header
1147 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1149 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1150 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1151 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1152 an.SetPublicKey (encodedPublicKey);
1156 Report.Error (1548, "Could not strongname the assembly. File `" +
1157 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1158 Environment.Exit (1);
1162 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1163 public AssemblyName GetAssemblyName (string name, string output)
1165 if (OptAttributes != null) {
1166 foreach (Attribute a in OptAttributes.Attrs) {
1167 // cannot rely on any resolve-based members before you call Resolve
1168 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1171 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1172 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1175 case "AssemblyKeyFile":
1176 case "AssemblyKeyFileAttribute":
1177 case "System.Reflection.AssemblyKeyFileAttribute":
1178 if (RootContext.StrongNameKeyFile != null) {
1179 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1180 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1183 string value = a.GetString ();
1184 if (value != String.Empty)
1185 RootContext.StrongNameKeyFile = value;
1188 case "AssemblyKeyName":
1189 case "AssemblyKeyNameAttribute":
1190 case "System.Reflection.AssemblyKeyNameAttribute":
1191 if (RootContext.StrongNameKeyContainer != null) {
1192 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1193 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1196 string value = a.GetString ();
1197 if (value != String.Empty)
1198 RootContext.StrongNameKeyContainer = value;
1201 case "AssemblyDelaySign":
1202 case "AssemblyDelaySignAttribute":
1203 case "System.Reflection.AssemblyDelaySignAttribute":
1204 RootContext.StrongNameDelaySign = a.GetBoolean ();
1210 AssemblyName an = new AssemblyName ();
1211 an.Name = Path.GetFileNameWithoutExtension (name);
1213 // note: delay doesn't apply when using a key container
1214 if (RootContext.StrongNameKeyContainer != null) {
1215 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1219 // strongname is optional
1220 if (RootContext.StrongNameKeyFile == null)
1223 string AssemblyDir = Path.GetDirectoryName (output);
1225 // the StrongName key file may be relative to (a) the compiled
1226 // file or (b) to the output assembly. See bugzilla #55320
1227 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1229 // (a) relative to the compiled file
1230 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1231 bool exist = File.Exists (filename);
1232 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1233 // (b) relative to the outputed assembly
1234 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1235 exist = File.Exists (filename);
1239 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1240 byte[] snkeypair = new byte [fs.Length];
1241 fs.Read (snkeypair, 0, snkeypair.Length);
1243 if (RootContext.StrongNameDelaySign) {
1244 // delayed signing - DO NOT include private key
1245 SetPublicKey (an, snkeypair);
1248 // no delay so we make sure we have the private key
1250 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1251 an.KeyPair = new StrongNameKeyPair (snkeypair);
1253 catch (CryptographicException) {
1254 if (snkeypair.Length == 16) {
1255 // error # is different for ECMA key
1256 Report.Error (1606, "Could not strongname the assembly. " +
1257 "ECMA key can only be used to delay-sign assemblies");
1260 Report.Error (1548, "Could not strongname the assembly. File `" +
1261 RootContext.StrongNameKeyFile +
1262 "' doesn't have a private key.");
1270 Report.Error (1548, "Could not strongname the assembly. File `" +
1271 RootContext.StrongNameKeyFile + "' not found.");
1277 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1279 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1280 if (declarative_security == null)
1281 declarative_security = new ListDictionary ();
1283 a.ExtractSecurityPermissionSet (declarative_security);
1287 Builder.SetCustomAttribute (customBuilder);
1290 public override void Emit (TypeContainer tc)
1294 if (declarative_security != null) {
1296 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1297 object builder_instance = Builder;
1300 // Microsoft runtime hacking
1301 if (add_permission == null) {
1302 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1303 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1305 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1306 builder_instance = fi.GetValue (Builder);
1309 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1310 declarative_security [SecurityAction.RequestOptional],
1311 declarative_security [SecurityAction.RequestRefuse] };
1312 add_permission.Invoke (builder_instance, args);
1315 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1320 public override string[] ValidAttributeTargets {
1322 return attribute_targets;
1327 public class ModuleClass: CommonAssemblyModulClass {
1328 // TODO: make it private and move all builder based methods here
1329 public ModuleBuilder Builder;
1330 bool m_module_is_unsafe;
1332 public CharSet DefaultCharSet = CharSet.Ansi;
1333 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1335 static string[] attribute_targets = new string [] { "module" };
1337 public ModuleClass (bool is_unsafe)
1339 m_module_is_unsafe = is_unsafe;
1342 public override AttributeTargets AttributeTargets {
1344 return AttributeTargets.Module;
1348 public override bool IsClsCompliaceRequired(DeclSpace ds)
1350 return CodeGen.Assembly.IsClsCompliant;
1353 public override void Emit (TypeContainer tc)
1357 if (!m_module_is_unsafe)
1360 if (TypeManager.unverifiable_code_ctor == null) {
1361 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1365 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1368 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1370 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1371 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1372 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1374 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1375 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1376 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1381 Builder.SetCustomAttribute (customBuilder);
1385 /// It is called very early therefore can resolve only predefined attributes
1387 public void ResolveAttributes ()
1390 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1392 DefaultCharSet = a.GetCharSetValue ();
1393 switch (DefaultCharSet) {
1398 DefaultCharSetType = TypeAttributes.AutoClass;
1400 case CharSet.Unicode:
1401 DefaultCharSetType = TypeAttributes.UnicodeClass;
1404 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1411 public override string[] ValidAttributeTargets {
1413 return attribute_targets;