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;
38 Assembly = new AssemblyClass ();
39 Module = new ModuleClass (RootContext.Unsafe);
42 public static string Basename (string name)
44 int pos = name.LastIndexOf ('/');
47 return name.Substring (pos + 1);
49 pos = name.LastIndexOf ('\\');
51 return name.Substring (pos + 1);
56 public static string Dirname (string name)
58 int pos = name.LastIndexOf ('/');
61 return name.Substring (0, pos);
63 pos = name.LastIndexOf ('\\');
65 return name.Substring (0, pos);
70 static string TrimExt (string name)
72 int pos = name.LastIndexOf ('.');
74 return name.Substring (0, pos);
77 static public string FileName;
80 // Initializes the symbol writer
82 static void InitializeSymbolWriter (string filename)
84 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
87 // If we got an ISymbolWriter instance, initialize it.
89 if (SymbolWriter == null) {
91 -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.");
97 // Initializes the code generator variables
99 static public void Init (string name, string output, bool want_debugging_support)
102 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);
158 static public void Save (string name)
161 Assembly.Builder.Save (Basename (name));
163 catch (COMException) {
164 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
167 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
168 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
169 RootContext.StrongNameKeyFile +
170 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
172 catch (System.IO.IOException io) {
173 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
176 if (SymbolWriter != null)
177 SymbolWriter.WriteSymbolFile ();
182 // Provides "local" store across code that can yield: locals
183 // or fields, notice that this should not be used by anonymous
184 // methods to create local storage, those only require
187 public class VariableStorage {
193 public VariableStorage (EmitContext ec, Type t)
197 fb = ec.CurrentIterator.MapVariable ("s_", count.ToString (), t);
199 local = ec.ig.DeclareLocal (t);
202 public void EmitThis (ILGenerator ig)
205 ig.Emit (OpCodes.Ldarg_0);
208 public void EmitStore (ILGenerator ig)
211 ig.Emit (OpCodes.Stloc, local);
213 ig.Emit (OpCodes.Stfld, fb);
216 public void EmitLoad (ILGenerator ig)
219 ig.Emit (OpCodes.Ldloc, local);
221 ig.Emit (OpCodes.Ldfld, fb);
224 public void EmitLoadAddress (ILGenerator ig)
227 ig.Emit (OpCodes.Ldloca, local);
229 ig.Emit (OpCodes.Ldflda, fb);
232 public void EmitCall (ILGenerator ig, MethodInfo mi)
234 // FIXME : we should handle a call like tostring
235 // here, where boxing is needed. However, we will
236 // never encounter that with the current usage.
238 bool value_type_call;
241 value_type_call = local.LocalType.IsValueType;
244 ig.Emit (OpCodes.Ldloca, local);
246 ig.Emit (OpCodes.Ldloc, local);
248 value_type_call = fb.FieldType.IsValueType;
251 ig.Emit (OpCodes.Ldflda, fb);
253 ig.Emit (OpCodes.Ldfld, fb);
256 ig.Emit (value_type_call ? OpCodes.Call : OpCodes.Callvirt, mi);
261 /// An Emit Context is created for each body of code (from methods,
262 /// properties bodies, indexer bodies or constructor bodies)
264 public class EmitContext {
265 public DeclSpace DeclSpace;
266 public DeclSpace TypeContainer;
267 public ILGenerator ig;
270 /// This variable tracks the `checked' state of the compilation,
271 /// it controls whether we should generate code that does overflow
272 /// checking, or if we generate code that ignores overflows.
274 /// The default setting comes from the command line option to generate
275 /// checked or unchecked code plus any source code changes using the
276 /// checked/unchecked statements or expressions. Contrast this with
277 /// the ConstantCheckState flag.
280 public bool CheckState;
283 /// The constant check state is always set to `true' and cant be changed
284 /// from the command line. The source code can change this setting with
285 /// the `checked' and `unchecked' statements and expressions.
287 public bool ConstantCheckState;
290 /// Whether we are emitting code inside a static or instance method
292 public bool IsStatic;
295 /// Whether we are emitting a field initializer
297 public bool IsFieldInitializer;
300 /// The value that is allowed to be returned or NULL if there is no
303 public Type ReturnType;
306 /// Points to the Type (extracted from the TypeContainer) that
307 /// declares this body of code
309 public Type ContainerType;
312 /// Whether this is generating code for a constructor
314 public bool IsConstructor;
317 /// Whether we're control flow analysis enabled
319 public bool DoFlowAnalysis;
322 /// Keeps track of the Type to LocalBuilder temporary storage created
323 /// to store structures (used to compute the address of the structure
324 /// value on structure method invocations)
326 public Hashtable temporary_storage;
328 public Block CurrentBlock;
330 public int CurrentFile;
333 /// The location where we store the return value.
335 LocalBuilder return_value;
338 /// The location where return has to jump to return the
341 public Label ReturnLabel;
344 /// If we already defined the ReturnLabel
346 public bool HasReturnLabel;
349 /// Whether we are inside an iterator block.
351 public bool InIterator;
353 public bool IsLastStatement;
356 /// Whether remapping of locals, parameters and fields is turned on.
357 /// Used by iterators and anonymous methods.
359 public bool RemapToProxy;
362 /// Whether we are inside an unsafe block
364 public bool InUnsafe;
367 /// Whether we are in a `fixed' initialization
369 public bool InFixedInitializer;
372 /// Whether we are inside an anonymous method.
374 public AnonymousMethod CurrentAnonymousMethod;
377 /// Location for this EmitContext
382 /// Used to flag that it is ok to define types recursively, as the
383 /// expressions are being evaluated as part of the type lookup
384 /// during the type resolution process
386 public bool ResolvingTypeTree;
389 /// Inside an enum definition, we do not resolve enumeration values
390 /// to their enumerations, but rather to the underlying type/value
391 /// This is so EnumVal + EnumValB can be evaluated.
393 /// There is no "E operator + (E x, E y)", so during an enum evaluation
394 /// we relax the rules
396 public bool InEnumContext;
399 /// Anonymous methods can capture local variables and fields,
400 /// this object tracks it. It is copied from the TopLevelBlock
403 public CaptureContext capture_context;
406 /// Trace when method is called and is obsolete then this member suppress message
407 /// when call is inside next [Obsolete] method or type.
409 public bool TestObsoleteMethodUsage = true;
412 /// The current iterator
414 public Iterator CurrentIterator;
417 /// Whether we are in the resolving stage or not
427 FlowBranching current_flow_branching;
429 public EmitContext (DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
430 Type return_type, int code_flags, bool is_constructor)
434 TypeContainer = parent;
436 CheckState = RootContext.Checked;
437 ConstantCheckState = true;
439 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
440 throw new Exception ("FUCK");
442 IsStatic = (code_flags & Modifiers.STATIC) != 0;
443 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
444 RemapToProxy = InIterator;
445 ReturnType = return_type;
446 IsConstructor = is_constructor;
449 current_phase = Phase.Created;
452 // Can only be null for the ResolveType contexts.
453 ContainerType = parent.TypeBuilder;
454 if (parent.UnsafeContext)
457 InUnsafe = (code_flags & Modifiers.UNSAFE) != 0;
461 if (ReturnType == TypeManager.void_type)
465 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
466 Type return_type, int code_flags, bool is_constructor)
467 : this (tc, tc, l, ig, return_type, code_flags, is_constructor)
471 public EmitContext (TypeContainer tc, Location l, ILGenerator ig,
472 Type return_type, int code_flags)
473 : this (tc, tc, l, ig, return_type, code_flags, false)
477 public FlowBranching CurrentBranching {
479 return current_flow_branching;
483 public bool HaveCaptureInfo {
485 return capture_context != null;
490 // Starts a new code branching. This inherits the state of all local
491 // variables and parameters from the current branching.
493 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
495 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
496 return current_flow_branching;
500 // Starts a new code branching for block `block'.
502 public FlowBranching StartFlowBranching (Block block)
504 FlowBranching.BranchingType type;
506 if (CurrentBranching.Type == FlowBranching.BranchingType.Switch)
507 type = FlowBranching.BranchingType.SwitchSection;
509 type = FlowBranching.BranchingType.Block;
511 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, block, block.StartLocation);
512 return current_flow_branching;
515 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
517 FlowBranchingException branching = new FlowBranchingException (
518 CurrentBranching, stmt);
519 current_flow_branching = branching;
524 // Ends a code branching. Merges the state of locals and parameters
525 // from all the children of the ending branching.
527 public FlowBranching.UsageVector DoEndFlowBranching ()
529 FlowBranching old = current_flow_branching;
530 current_flow_branching = current_flow_branching.Parent;
532 return current_flow_branching.MergeChild (old);
536 // Ends a code branching. Merges the state of locals and parameters
537 // from all the children of the ending branching.
539 public FlowBranching.Reachability EndFlowBranching ()
541 FlowBranching.UsageVector vector = DoEndFlowBranching ();
543 return vector.Reachability;
547 // Kills the current code branching. This throws away any changed state
548 // information and should only be used in case of an error.
550 public void KillFlowBranching ()
552 current_flow_branching = current_flow_branching.Parent;
555 public void CaptureVariable (LocalInfo li)
557 capture_context.AddLocal (CurrentAnonymousMethod, li);
558 li.IsCaptured = true;
561 public void CaptureParameter (string name, Type t, int idx)
563 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
566 public void CaptureThis ()
568 capture_context.CaptureThis ();
573 // Use to register a field as captured
575 public void CaptureField (FieldExpr fe)
577 capture_context.AddField (fe);
581 // Whether anonymous methods have captured variables
583 public bool HaveCapturedVariables ()
585 if (capture_context != null)
586 return capture_context.HaveCapturedVariables;
591 // Whether anonymous methods have captured fields or this.
593 public bool HaveCapturedFields ()
595 if (capture_context != null)
596 return capture_context.HaveCapturedFields;
601 // Emits the instance pointer for the host method
603 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
605 if (capture_context != null)
606 capture_context.EmitMethodHostInstance (target, am);
608 target.ig.Emit (OpCodes.Ldnull);
610 target.ig.Emit (OpCodes.Ldarg_0);
614 // Returns whether the `local' variable has been captured by an anonymous
617 public bool IsCaptured (LocalInfo local)
619 return capture_context.IsCaptured (local);
622 public bool IsParameterCaptured (string name)
624 if (capture_context != null)
625 return capture_context.IsParameterCaptured (name);
629 public void EmitMeta (ToplevelBlock b, InternalParameters ip)
631 if (capture_context != null)
632 capture_context.EmitAnonymousHelperClasses (this);
636 ReturnLabel = ig.DefineLabel ();
640 // Here until we can fix the problem with Mono.CSharp.Switch, which
641 // currently can not cope with ig == null during resolve (which must
642 // be fixed for switch statements to work on anonymous methods).
644 public void EmitTopBlock (ToplevelBlock block, InternalParameters ip, Location loc)
651 if (ResolveTopBlock (null, block, ip, loc, out unreachable)){
652 EmitMeta (block, ip);
654 current_phase = Phase.Emitting;
655 EmitResolvedTopBlock (block, unreachable);
659 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
660 InternalParameters ip, Location loc, out bool unreachable)
662 current_phase = Phase.Resolving;
666 capture_context = block.CaptureContext;
668 if (!Location.IsNull (loc))
669 CurrentFile = loc.File;
674 int errors = Report.Errors;
676 block.ResolveMeta (block, this, ip);
679 if (Report.Errors == errors){
680 bool old_do_flow_analysis = DoFlowAnalysis;
681 DoFlowAnalysis = true;
683 if (anonymous_method_host != null)
684 current_flow_branching = FlowBranching.CreateBranching (
685 anonymous_method_host.CurrentBranching, FlowBranching.BranchingType.Block,
688 current_flow_branching = FlowBranching.CreateBranching (
689 null, FlowBranching.BranchingType.Block, block, loc);
691 if (!block.Resolve (this)) {
692 current_flow_branching = null;
693 DoFlowAnalysis = old_do_flow_analysis;
697 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
698 current_flow_branching = null;
700 DoFlowAnalysis = old_do_flow_analysis;
702 if (reachability.AlwaysReturns ||
703 reachability.AlwaysThrows ||
704 reachability.IsUnreachable)
708 } catch (Exception e) {
709 Console.WriteLine ("Exception caught by the compiler while compiling:");
710 Console.WriteLine (" Block that caused the problem begin at: " + loc);
712 if (CurrentBlock != null){
713 Console.WriteLine (" Block being compiled: [{0},{1}]",
714 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
716 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
721 if (ReturnType != null && !unreachable){
723 if (CurrentAnonymousMethod != null){
724 Report.Error (1643, loc, "Not all code paths return a value in anonymous method of type `{0}'",
725 CurrentAnonymousMethod.Type);
727 Report.Error (161, loc, "Not all code paths return a value");
733 block.CompleteContexts ();
738 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
744 ig.MarkLabel (ReturnLabel);
746 if (return_value != null){
747 ig.Emit (OpCodes.Ldloc, return_value);
748 ig.Emit (OpCodes.Ret);
751 // If `HasReturnLabel' is set, then we already emitted a
752 // jump to the end of the method, so we must emit a `ret'
755 // Unfortunately, System.Reflection.Emit automatically emits
756 // a leave to the end of a finally block. This is a problem
757 // if no code is following the try/finally block since we may
758 // jump to a point after the end of the method.
759 // As a workaround, we're always creating a return label in
763 if ((block != null) && block.IsDestructor) {
764 // Nothing to do; S.R.E automatically emits a leave.
765 } else if (HasReturnLabel || (!unreachable && !InIterator)) {
766 if (ReturnType != null)
767 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
768 ig.Emit (OpCodes.Ret);
773 // Close pending helper classes if we are the toplevel
775 if (capture_context != null && capture_context.ParentToplevel == null)
776 capture_context.CloseAnonymousHelperClasses ();
780 /// This is called immediately before emitting an IL opcode to tell the symbol
781 /// writer to which source line this opcode belongs.
783 public void Mark (Location loc, bool check_file)
785 if ((CodeGen.SymbolWriter == null) || Location.IsNull (loc))
788 if (check_file && (CurrentFile != loc.File))
791 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, 0);
794 public void DefineLocalVariable (string name, LocalBuilder builder)
796 if (CodeGen.SymbolWriter == null)
799 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
803 /// Returns a temporary storage for a variable of type t as
804 /// a local variable in the current body.
806 public LocalBuilder GetTemporaryLocal (Type t)
808 LocalBuilder location = null;
810 if (temporary_storage != null){
811 object o = temporary_storage [t];
814 ArrayList al = (ArrayList) o;
816 for (int i = 0; i < al.Count; i++){
818 location = (LocalBuilder) al [i];
824 location = (LocalBuilder) o;
825 if (location != null)
830 return ig.DeclareLocal (t);
833 public void FreeTemporaryLocal (LocalBuilder b, Type t)
835 if (temporary_storage == null){
836 temporary_storage = new Hashtable ();
837 temporary_storage [t] = b;
840 object o = temporary_storage [t];
842 temporary_storage [t] = b;
846 ArrayList al = (ArrayList) o;
847 for (int i = 0; i < al.Count; i++){
856 ArrayList replacement = new ArrayList ();
858 temporary_storage.Remove (t);
859 temporary_storage [t] = replacement;
863 /// Current loop begin and end labels.
865 public Label LoopBegin, LoopEnd;
868 /// Default target in a switch statement. Only valid if
871 public Label DefaultTarget;
874 /// If this is non-null, points to the current switch statement
876 public Switch Switch;
879 /// ReturnValue creates on demand the LocalBuilder for the
880 /// return value from the function. By default this is not
881 /// used. This is only required when returns are found inside
882 /// Try or Catch statements.
884 /// This method is typically invoked from the Emit phase, so
885 /// we allow the creation of a return label if it was not
886 /// requested during the resolution phase. Could be cleaned
887 /// up, but it would replicate a lot of logic in the Emit phase
888 /// of the code that uses it.
890 public LocalBuilder TemporaryReturn ()
892 if (return_value == null){
893 return_value = ig.DeclareLocal (ReturnType);
894 if (!HasReturnLabel){
895 ReturnLabel = ig.DefineLabel ();
896 HasReturnLabel = true;
904 /// This method is used during the Resolution phase to flag the
905 /// need to define the ReturnLabel
907 public void NeedReturnLabel ()
909 if (current_phase != Phase.Resolving){
911 // The reason is that the `ReturnLabel' is declared between
912 // resolution and emission
914 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
917 if (!InIterator && !HasReturnLabel)
918 HasReturnLabel = true;
922 // Creates a field `name' with the type `t' on the proxy class
924 public FieldBuilder MapVariable (string name, Type t)
927 return CurrentIterator.MapVariable ("v_", name, t);
929 throw new Exception ("MapVariable for an unknown state");
932 public Expression RemapParameter (int idx)
934 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
935 fe.InstanceExpression = new ProxyInstance ();
936 return fe.DoResolve (this);
939 public Expression RemapParameterLValue (int idx, Expression right_side)
941 FieldExpr fe = new FieldExprNoAddress (CurrentIterator.parameter_fields [idx].FieldBuilder, loc);
942 fe.InstanceExpression = new ProxyInstance ();
943 return fe.DoResolveLValue (this, right_side);
947 // Emits the proper object to address fields on a remapped
948 // variable/parameter to field in anonymous-method/iterator proxy classes.
950 public void EmitThis ()
952 ig.Emit (OpCodes.Ldarg_0);
955 FieldBuilder this_field = CurrentIterator.this_field.FieldBuilder;
956 if (TypeManager.IsValueType (this_field.FieldType))
957 ig.Emit (OpCodes.Ldflda, this_field);
959 ig.Emit (OpCodes.Ldfld, this_field);
961 } else if (capture_context != null && CurrentAnonymousMethod != null){
962 ScopeInfo si = CurrentAnonymousMethod.Scope;
964 if (si.ParentLink != null)
965 ig.Emit (OpCodes.Ldfld, si.ParentLink);
966 if (si.THIS != null){
967 ig.Emit (OpCodes.Ldfld, si.THIS);
976 // Emits the code necessary to load the instance required
977 // to access the captured LocalInfo
979 public void EmitCapturedVariableInstance (LocalInfo li)
982 ig.Emit (OpCodes.Ldarg_0);
986 if (capture_context == null)
987 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
989 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
992 public void EmitParameter (string name)
994 capture_context.EmitParameter (this, name);
997 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load)
999 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load);
1002 public void EmitAddressOfParameter (string name)
1004 capture_context.EmitAddressOfParameter (this, name);
1007 public Expression GetThis (Location loc)
1010 if (CurrentBlock != null)
1011 my_this = new This (CurrentBlock, loc);
1013 my_this = new This (loc);
1015 if (!my_this.ResolveBase (this))
1023 public abstract class CommonAssemblyModulClass: Attributable {
1024 protected CommonAssemblyModulClass ():
1029 public void AddAttributes (ArrayList attrs)
1031 if (OptAttributes == null) {
1032 OptAttributes = new Attributes (attrs);
1035 OptAttributes.AddAttributes (attrs);
1038 public virtual void Emit (TypeContainer tc)
1040 if (OptAttributes == null)
1043 EmitContext ec = new EmitContext (tc, Mono.CSharp.Location.Null, null, null, 0, false);
1044 OptAttributes.Emit (ec, this);
1047 protected Attribute GetClsCompliantAttribute ()
1049 if (OptAttributes == null)
1052 // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1053 if (!OptAttributes.CheckTargets (this))
1056 EmitContext temp_ec = new EmitContext (RootContext.Tree.Types, Mono.CSharp.Location.Null, null, null, 0, false);
1057 Attribute a = OptAttributes.Search (TypeManager.cls_compliant_attribute_type, temp_ec);
1059 a.Resolve (temp_ec);
1065 public class AssemblyClass: CommonAssemblyModulClass {
1066 // TODO: make it private and move all builder based methods here
1067 public AssemblyBuilder Builder;
1069 bool is_cls_compliant;
1070 public Attribute ClsCompliantAttribute;
1072 ListDictionary declarative_security;
1074 static string[] attribute_targets = new string [] { "assembly" };
1076 public AssemblyClass (): base ()
1078 is_cls_compliant = false;
1081 public bool IsClsCompliant {
1083 return is_cls_compliant;
1087 public override AttributeTargets AttributeTargets {
1089 return AttributeTargets.Assembly;
1093 public override bool IsClsCompliaceRequired(DeclSpace ds)
1095 return is_cls_compliant;
1098 public void ResolveClsCompliance ()
1100 ClsCompliantAttribute = GetClsCompliantAttribute ();
1101 if (ClsCompliantAttribute == null)
1104 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue (null);
1108 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1111 // check for possible ECMA key
1112 if (strongNameBlob.Length == 16) {
1113 // will be rejected if not "the" ECMA key
1114 an.SetPublicKey (strongNameBlob);
1117 // take it, with or without, a private key
1118 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1119 // and make sure we only feed the public part to Sys.Ref
1120 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1122 // AssemblyName.SetPublicKey requires an additional header
1123 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1125 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1126 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1127 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1128 an.SetPublicKey (encodedPublicKey);
1132 Report.Error (1548, "Could not strongname the assembly. File `" +
1133 RootContext.StrongNameKeyFile + "' incorrectly encoded.");
1134 Environment.Exit (1);
1138 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1139 public AssemblyName GetAssemblyName (string name, string output)
1141 if (OptAttributes != null) {
1142 foreach (Attribute a in OptAttributes.Attrs) {
1143 // cannot rely on any resolve-based members before you call Resolve
1144 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1147 // TODO: This code is buggy: comparing Attribute name without resolving it is wrong.
1148 // However, this is invoked by CodeGen.Init, at which time none of the namespaces
1151 case "AssemblyKeyFile":
1152 case "AssemblyKeyFileAttribute":
1153 case "System.Reflection.AssemblyKeyFileAttribute":
1154 if (RootContext.StrongNameKeyFile != null) {
1155 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1156 Report.Warning (1616, "Compiler option '{0}' overrides '{1}' given in source", "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1159 string value = a.GetString ();
1160 if (value != String.Empty)
1161 RootContext.StrongNameKeyFile = value;
1164 case "AssemblyKeyName":
1165 case "AssemblyKeyNameAttribute":
1166 case "System.Reflection.AssemblyKeyNameAttribute":
1167 if (RootContext.StrongNameKeyContainer != null) {
1168 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1169 Report.Warning (1616, "keycontainer", "Compiler option '{0}' overrides '{1}' given in source", "System.Reflection.AssemblyKeyNameAttribute");
1172 string value = a.GetString ();
1173 if (value != String.Empty)
1174 RootContext.StrongNameKeyContainer = value;
1177 case "AssemblyDelaySign":
1178 case "AssemblyDelaySignAttribute":
1179 case "System.Reflection.AssemblyDelaySignAttribute":
1180 RootContext.StrongNameDelaySign = a.GetBoolean ();
1186 AssemblyName an = new AssemblyName ();
1187 an.Name = Path.GetFileNameWithoutExtension (name);
1189 // note: delay doesn't apply when using a key container
1190 if (RootContext.StrongNameKeyContainer != null) {
1191 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1195 // strongname is optional
1196 if (RootContext.StrongNameKeyFile == null)
1199 string AssemblyDir = Path.GetDirectoryName (output);
1201 // the StrongName key file may be relative to (a) the compiled
1202 // file or (b) to the output assembly. See bugzilla #55320
1203 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1205 // (a) relative to the compiled file
1206 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1207 bool exist = File.Exists (filename);
1208 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1209 // (b) relative to the outputed assembly
1210 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1211 exist = File.Exists (filename);
1215 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1216 byte[] snkeypair = new byte [fs.Length];
1217 fs.Read (snkeypair, 0, snkeypair.Length);
1219 if (RootContext.StrongNameDelaySign) {
1220 // delayed signing - DO NOT include private key
1221 SetPublicKey (an, snkeypair);
1224 // no delay so we make sure we have the private key
1226 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1227 an.KeyPair = new StrongNameKeyPair (snkeypair);
1229 catch (CryptographicException) {
1230 if (snkeypair.Length == 16) {
1231 // error # is different for ECMA key
1232 Report.Error (1606, "Could not strongname the assembly. " +
1233 "ECMA key can only be used to delay-sign assemblies");
1236 Report.Error (1548, "Could not strongname the assembly. File `" +
1237 RootContext.StrongNameKeyFile +
1238 "' doesn't have a private key.");
1240 Environment.Exit (1);
1246 Report.Error (1548, "Could not strongname the assembly. File `" +
1247 RootContext.StrongNameKeyFile + "' not found.");
1248 Environment.Exit (1);
1253 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1255 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1256 if (declarative_security == null)
1257 declarative_security = new ListDictionary ();
1259 a.ExtractSecurityPermissionSet (declarative_security);
1263 Builder.SetCustomAttribute (customBuilder);
1266 public override void Emit (TypeContainer tc)
1270 if (declarative_security != null) {
1272 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1273 object builder_instance = Builder;
1276 // Microsoft runtime hacking
1277 if (add_permission == null) {
1278 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1279 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1281 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1282 builder_instance = fi.GetValue (Builder);
1285 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1286 declarative_security [SecurityAction.RequestOptional],
1287 declarative_security [SecurityAction.RequestRefuse] };
1288 add_permission.Invoke (builder_instance, args);
1291 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1296 public override string[] ValidAttributeTargets {
1298 return attribute_targets;
1303 public class ModuleClass: CommonAssemblyModulClass {
1304 // TODO: make it private and move all builder based methods here
1305 public ModuleBuilder Builder;
1306 bool m_module_is_unsafe;
1308 static string[] attribute_targets = new string [] { "module" };
1310 public ModuleClass (bool is_unsafe)
1312 m_module_is_unsafe = is_unsafe;
1315 public override AttributeTargets AttributeTargets {
1317 return AttributeTargets.Module;
1321 public override bool IsClsCompliaceRequired(DeclSpace ds)
1323 return CodeGen.Assembly.IsClsCompliant;
1326 public override void Emit (TypeContainer tc)
1330 if (!m_module_is_unsafe)
1333 if (TypeManager.unverifiable_code_ctor == null) {
1334 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1338 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1341 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1343 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1344 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1345 Report.Warning (3012, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1347 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1348 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.Name);
1349 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1354 Builder.SetCustomAttribute (customBuilder);
1357 public override string[] ValidAttributeTargets {
1359 return attribute_targets;