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.
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;
26 using Mono.Security.Cryptography;
28 namespace Mono.CSharp {
31 /// Code generator class.
33 public class CodeGen {
34 static AppDomain current_domain;
35 static public SymbolWriter SymbolWriter;
37 public static AssemblyClass Assembly;
38 public static ModuleClass Module;
45 public static void Reset ()
47 Assembly = new AssemblyClass ();
48 Module = new ModuleClass (RootContext.Unsafe);
51 public static string Basename (string name)
53 int pos = name.LastIndexOf ('/');
56 return name.Substring (pos + 1);
58 pos = name.LastIndexOf ('\\');
60 return name.Substring (pos + 1);
65 public static string Dirname (string name)
67 int pos = name.LastIndexOf ('/');
70 return name.Substring (0, pos);
72 pos = name.LastIndexOf ('\\');
74 return name.Substring (0, pos);
79 static public string FileName;
82 // Initializes the symbol writer
84 static void InitializeSymbolWriter (string filename)
86 SymbolWriter = SymbolWriter.GetSymbolWriter (Module.Builder, filename);
89 // If we got an ISymbolWriter instance, initialize it.
91 if (SymbolWriter == null) {
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.");
99 // Initializes the code generator variables
101 static public bool Init (string name, string output, bool want_debugging_support)
104 AssemblyName an = Assembly.GetAssemblyName (name, output);
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 '" +
118 "' does not have a strong name.");
119 //Environment.Exit (1);
124 current_domain = AppDomain.CurrentDomain;
127 Assembly.Builder = current_domain.DefineDynamicAssembly (an,
128 AssemblyBuilderAccess.Save, Dirname (name));
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);
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);
148 // Pass a path-less name to DefineDynamicModule. Wonder how
149 // this copes with output in different directories then.
150 // FIXME: figure out how this copes with --output /tmp/blah
152 // If the third argument is true, the ModuleBuilder will dynamically
153 // load the default symbol writer.
155 Module.Builder = Assembly.Builder.DefineDynamicModule (
156 Basename (name), Basename (output), false);
158 if (want_debugging_support)
159 InitializeSymbolWriter (output);
164 static public void Save (string name)
167 Assembly.Builder.Save (Basename (name));
169 catch (COMException) {
170 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
173 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
174 Report.Error (1548, "Couldn't delay-sign the assembly with the '" +
175 RootContext.StrongNameKeyFile +
176 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
178 catch (System.IO.IOException io) {
179 Report.Error (16, "Could not write to file `"+name+"', cause: " + io.Message);
181 catch (System.UnauthorizedAccessException ua) {
182 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
185 if (SymbolWriter != null)
186 SymbolWriter.WriteSymbolFile ();
191 public interface IResolveContext
193 DeclSpace DeclContainer { get; }
194 bool IsInObsoleteScope { get; }
195 bool IsInUnsafeScope { get; }
199 /// An Emit Context is created for each body of code (from methods,
200 /// properties bodies, indexer bodies or constructor bodies)
202 public class EmitContext : IResolveContext {
205 public DeclSpace TypeContainer;
206 public ILGenerator ig;
209 /// This variable tracks the `checked' state of the compilation,
210 /// it controls whether we should generate code that does overflow
211 /// checking, or if we generate code that ignores overflows.
213 /// The default setting comes from the command line option to generate
214 /// checked or unchecked code plus any source code changes using the
215 /// checked/unchecked statements or expressions. Contrast this with
216 /// the ConstantCheckState flag.
219 public bool CheckState;
222 /// The constant check state is always set to `true' and cant be changed
223 /// from the command line. The source code can change this setting with
224 /// the `checked' and `unchecked' statements and expressions.
226 public bool ConstantCheckState;
229 /// Whether we are emitting code inside a static or instance method
231 public bool IsStatic;
234 /// Whether the actual created method is static or instance method.
235 /// Althoug the method might be declared as `static', if an anonymous
236 /// method is involved, we might turn this into an instance method.
238 /// So this reflects the low-level staticness of the method, while
239 /// IsStatic represents the semantic, high-level staticness.
241 public bool MethodIsStatic;
244 /// Whether we are emitting a field initializer
246 public bool IsFieldInitializer;
249 /// The value that is allowed to be returned or NULL if there is no
252 public Type ReturnType;
255 /// Points to the Type (extracted from the TypeContainer) that
256 /// declares this body of code
258 public Type ContainerType;
261 /// Whether this is generating code for a constructor
263 public bool IsConstructor;
266 /// Whether we're control flow analysis enabled
268 public bool DoFlowAnalysis;
271 /// Whether we're control flow analysis disabled on struct
273 public bool OmitStructFlowAnalysis;
276 /// Keeps track of the Type to LocalBuilder temporary storage created
277 /// to store structures (used to compute the address of the structure
278 /// value on structure method invocations)
280 public Hashtable temporary_storage;
282 public Block CurrentBlock;
284 public int CurrentFile;
287 /// The location where we store the return value.
289 LocalBuilder return_value;
292 /// The location where return has to jump to return the
295 public Label ReturnLabel;
298 /// If we already defined the ReturnLabel
300 public bool HasReturnLabel;
303 /// Whether we are inside an iterator block.
305 public bool InIterator;
307 public bool IsLastStatement;
310 /// Whether we are inside an unsafe block
312 public bool InUnsafe;
315 /// Whether we are in a `fixed' initialization
317 public bool InFixedInitializer;
319 public bool InRefOutArgumentResolving;
322 public bool InFinally;
325 /// Whether we are inside an anonymous method.
327 public AnonymousContainer CurrentAnonymousMethod;
330 /// Location for this EmitContext
335 /// Inside an enum definition, we do not resolve enumeration values
336 /// to their enumerations, but rather to the underlying type/value
337 /// This is so EnumVal + EnumValB can be evaluated.
339 /// There is no "E operator + (E x, E y)", so during an enum evaluation
340 /// we relax the rules
342 public bool InEnumContext;
345 /// Anonymous methods can capture local variables and fields,
346 /// this object tracks it. It is copied from the TopLevelBlock
349 public CaptureContext capture_context;
351 public readonly IResolveContext ResolveContext;
354 /// The current iterator
356 public Iterator CurrentIterator;
359 /// Whether we are in the resolving stage or not
368 FlowBranching current_flow_branching;
370 static int next_id = 0;
373 public override string ToString ()
375 return String.Format ("EmitContext ({0}:{1}:{2})", id,
376 CurrentIterator, capture_context, loc);
379 public EmitContext (IResolveContext rc, DeclSpace parent, DeclSpace ds, Location l, ILGenerator ig,
380 Type return_type, int code_flags, bool is_constructor)
382 this.ResolveContext = rc;
385 TypeContainer = parent;
387 CheckState = RootContext.Checked;
388 ConstantCheckState = true;
390 IsStatic = (code_flags & Modifiers.STATIC) != 0;
391 MethodIsStatic = IsStatic;
392 InIterator = (code_flags & Modifiers.METHOD_YIELDS) != 0;
393 ReturnType = return_type;
394 IsConstructor = is_constructor;
397 current_phase = Phase.Created;
400 // Can only be null for the ResolveType contexts.
401 ContainerType = parent.TypeBuilder;
402 InUnsafe = rc.IsInUnsafeScope;
406 if (ReturnType == TypeManager.void_type)
410 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
411 Type return_type, int code_flags, bool is_constructor)
412 : this (rc, ds, ds, l, ig, return_type, code_flags, is_constructor)
416 public EmitContext (IResolveContext rc, DeclSpace ds, Location l, ILGenerator ig,
417 Type return_type, int code_flags)
418 : this (rc, ds, ds, l, ig, return_type, code_flags, false)
422 public DeclSpace DeclContainer {
423 get { return declSpace; }
424 set { declSpace = value; }
427 public bool IsInObsoleteScope {
428 get { return ResolveContext.IsInObsoleteScope; }
431 public bool IsInUnsafeScope {
432 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
436 public FlowBranching CurrentBranching {
437 get { return current_flow_branching; }
440 public bool HaveCaptureInfo {
441 get { return capture_context != null; }
444 public void EmitScopeInitFromBlock (Block b)
446 if (capture_context != null)
447 capture_context.EmitScopeInitFromBlock (this, b);
451 // Starts a new code branching. This inherits the state of all local
452 // variables and parameters from the current branching.
454 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
456 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
457 return current_flow_branching;
461 // Starts a new code branching for block `block'.
463 public FlowBranching StartFlowBranching (Block block)
465 FlowBranching.BranchingType type;
467 if ((CurrentBranching != null) &&
468 (CurrentBranching.Type == FlowBranching.BranchingType.Switch))
469 type = FlowBranching.BranchingType.SwitchSection;
471 type = FlowBranching.BranchingType.Block;
473 DoFlowAnalysis = true;
475 current_flow_branching = FlowBranching.CreateBranching (
476 CurrentBranching, type, block, block.StartLocation);
477 return current_flow_branching;
480 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
482 FlowBranchingException branching = new FlowBranchingException (
483 CurrentBranching, stmt);
484 current_flow_branching = branching;
489 // Ends a code branching. Merges the state of locals and parameters
490 // from all the children of the ending branching.
492 public FlowBranching.UsageVector DoEndFlowBranching ()
494 FlowBranching old = current_flow_branching;
495 current_flow_branching = current_flow_branching.Parent;
497 return current_flow_branching.MergeChild (old);
501 // Ends a code branching. Merges the state of locals and parameters
502 // from all the children of the ending branching.
504 public FlowBranching.Reachability EndFlowBranching ()
506 FlowBranching.UsageVector vector = DoEndFlowBranching ();
508 return vector.Reachability;
512 // Kills the current code branching. This throws away any changed state
513 // information and should only be used in case of an error.
515 public void KillFlowBranching ()
517 current_flow_branching = current_flow_branching.Parent;
520 public void CaptureVariable (LocalInfo li)
522 capture_context.AddLocal (CurrentAnonymousMethod, li);
523 li.IsCaptured = true;
526 public void CaptureParameter (string name, Type t, int idx)
528 capture_context.AddParameter (this, CurrentAnonymousMethod, name, t, idx);
531 public void CaptureThis ()
533 capture_context.CaptureThis (CurrentAnonymousMethod);
538 // Use to register a field as captured
540 public void CaptureField (FieldExpr fe)
542 capture_context.AddField (this, CurrentAnonymousMethod, fe);
546 // Whether anonymous methods have captured variables
548 public bool HaveCapturedVariables ()
550 if (capture_context != null)
551 return capture_context.HaveCapturedVariables;
556 // Whether anonymous methods have captured fields or this.
558 public bool HaveCapturedFields ()
560 if (capture_context != null)
561 return capture_context.HaveCapturedFields;
566 // Emits the instance pointer for the host method
568 public void EmitMethodHostInstance (EmitContext target, AnonymousMethod am)
570 if (capture_context != null)
571 capture_context.EmitMethodHostInstance (target, am);
573 target.ig.Emit (OpCodes.Ldnull);
575 target.ig.Emit (OpCodes.Ldarg_0);
579 // Returns whether the `local' variable has been captured by an anonymous
582 public bool IsCaptured (LocalInfo local)
584 return capture_context.IsCaptured (local);
587 public bool IsParameterCaptured (string name)
589 if (capture_context != null)
590 return capture_context.IsParameterCaptured (name);
594 public void EmitMeta (ToplevelBlock b)
596 if (capture_context != null)
597 capture_context.EmitAnonymousHelperClasses (this);
601 ReturnLabel = ig.DefineLabel ();
605 // Here until we can fix the problem with Mono.CSharp.Switch, which
606 // currently can not cope with ig == null during resolve (which must
607 // be fixed for switch statements to work on anonymous methods).
609 public void EmitTopBlock (IMethodData md, ToplevelBlock block)
616 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
619 current_phase = Phase.Emitting;
620 EmitResolvedTopBlock (block, unreachable);
626 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
627 Parameters ip, IMethodData md, out bool unreachable)
629 current_phase = Phase.Resolving;
636 capture_context = block.CaptureContext;
639 CurrentFile = loc.File;
644 if (!block.ResolveMeta (this, ip))
647 bool old_do_flow_analysis = DoFlowAnalysis;
648 DoFlowAnalysis = true;
650 if (anonymous_method_host != null)
651 current_flow_branching = FlowBranching.CreateBranching (
652 anonymous_method_host.CurrentBranching,
653 FlowBranching.BranchingType.Block, block, loc);
655 current_flow_branching = block.TopLevelBranching;
657 if (!block.Resolve (this)) {
658 current_flow_branching = null;
659 DoFlowAnalysis = old_do_flow_analysis;
663 FlowBranching.Reachability reachability = current_flow_branching.MergeTopBlock ();
664 current_flow_branching = null;
666 DoFlowAnalysis = old_do_flow_analysis;
668 if (reachability.AlwaysReturns ||
669 reachability.AlwaysThrows ||
670 reachability.IsUnreachable)
673 } catch (Exception e) {
674 Console.WriteLine ("Exception caught by the compiler while compiling:");
675 Console.WriteLine (" Block that caused the problem begin at: " + loc);
677 if (CurrentBlock != null){
678 Console.WriteLine (" Block being compiled: [{0},{1}]",
679 CurrentBlock.StartLocation, CurrentBlock.EndLocation);
681 Console.WriteLine (e.GetType ().FullName + ": " + e.Message);
686 if (ReturnType != null && !unreachable) {
687 if (CurrentAnonymousMethod == null) {
688 Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
690 } else if (!CurrentAnonymousMethod.IsIterator) {
691 Report.Error (1643, CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
692 CurrentAnonymousMethod.GetSignatureForError ());
697 block.CompleteContexts ();
702 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
708 ig.MarkLabel (ReturnLabel);
710 if (return_value != null){
711 ig.Emit (OpCodes.Ldloc, return_value);
712 ig.Emit (OpCodes.Ret);
715 // If `HasReturnLabel' is set, then we already emitted a
716 // jump to the end of the method, so we must emit a `ret'
719 // Unfortunately, System.Reflection.Emit automatically emits
720 // a leave to the end of a finally block. This is a problem
721 // if no code is following the try/finally block since we may
722 // jump to a point after the end of the method.
723 // As a workaround, we're always creating a return label in
727 bool in_iterator = (CurrentAnonymousMethod != null) &&
728 CurrentAnonymousMethod.IsIterator && InIterator;
730 if ((block != null) && block.IsDestructor) {
731 // Nothing to do; S.R.E automatically emits a leave.
732 } else if (HasReturnLabel || (!unreachable && !in_iterator)) {
733 if (ReturnType != null)
734 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
735 ig.Emit (OpCodes.Ret);
740 // Close pending helper classes if we are the toplevel
742 if (capture_context != null && capture_context.ParentToplevel == null)
743 capture_context.CloseAnonymousHelperClasses ();
747 /// This is called immediately before emitting an IL opcode to tell the symbol
748 /// writer to which source line this opcode belongs.
750 public void Mark (Location loc, bool check_file)
752 if ((CodeGen.SymbolWriter == null) || loc.IsNull)
755 if (check_file && (CurrentFile != loc.File))
758 CodeGen.SymbolWriter.MarkSequencePoint (ig, loc.Row, loc.Column);
761 public void DefineLocalVariable (string name, LocalBuilder builder)
763 if (CodeGen.SymbolWriter == null)
766 CodeGen.SymbolWriter.DefineLocalVariable (name, builder);
769 public void BeginScope ()
773 if (CodeGen.SymbolWriter != null)
774 CodeGen.SymbolWriter.OpenScope(ig);
777 public void EndScope ()
781 if (CodeGen.SymbolWriter != null)
782 CodeGen.SymbolWriter.CloseScope(ig);
786 /// Returns a temporary storage for a variable of type t as
787 /// a local variable in the current body.
789 public LocalBuilder GetTemporaryLocal (Type t)
791 LocalBuilder location = null;
793 if (temporary_storage != null){
794 object o = temporary_storage [t];
797 ArrayList al = (ArrayList) o;
799 for (int i = 0; i < al.Count; i++){
801 location = (LocalBuilder) al [i];
807 location = (LocalBuilder) o;
808 if (location != null)
813 return ig.DeclareLocal (t);
816 public void FreeTemporaryLocal (LocalBuilder b, Type t)
818 if (temporary_storage == null){
819 temporary_storage = new Hashtable ();
820 temporary_storage [t] = b;
823 object o = temporary_storage [t];
825 temporary_storage [t] = b;
829 ArrayList al = (ArrayList) o;
830 for (int i = 0; i < al.Count; i++){
839 ArrayList replacement = new ArrayList ();
841 temporary_storage.Remove (t);
842 temporary_storage [t] = replacement;
846 /// Current loop begin and end labels.
848 public Label LoopBegin, LoopEnd;
851 /// Default target in a switch statement. Only valid if
854 public Label DefaultTarget;
857 /// If this is non-null, points to the current switch statement
859 public Switch Switch;
862 /// ReturnValue creates on demand the LocalBuilder for the
863 /// return value from the function. By default this is not
864 /// used. This is only required when returns are found inside
865 /// Try or Catch statements.
867 /// This method is typically invoked from the Emit phase, so
868 /// we allow the creation of a return label if it was not
869 /// requested during the resolution phase. Could be cleaned
870 /// up, but it would replicate a lot of logic in the Emit phase
871 /// of the code that uses it.
873 public LocalBuilder TemporaryReturn ()
875 if (return_value == null){
876 return_value = ig.DeclareLocal (ReturnType);
877 if (!HasReturnLabel){
878 ReturnLabel = ig.DefineLabel ();
879 HasReturnLabel = true;
887 /// This method is used during the Resolution phase to flag the
888 /// need to define the ReturnLabel
890 public void NeedReturnLabel ()
892 if (current_phase != Phase.Resolving){
894 // The reason is that the `ReturnLabel' is declared between
895 // resolution and emission
897 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
900 if (!InIterator && !HasReturnLabel)
901 HasReturnLabel = true;
905 // Emits the proper object to address fields on a remapped
906 // variable/parameter to field in anonymous-method/iterator proxy classes.
908 public void EmitThis (bool need_address)
910 ig.Emit (OpCodes.Ldarg_0);
911 if (capture_context != null && CurrentAnonymousMethod != null){
912 ScopeInfo si = CurrentAnonymousMethod.Scope;
914 if (si.ParentLink != null)
915 ig.Emit (OpCodes.Ldfld, si.ParentLink);
916 if (si.THIS != null){
917 if (need_address && TypeManager.IsValueType (si.THIS.FieldType))
918 ig.Emit (OpCodes.Ldflda, si.THIS);
920 ig.Emit (OpCodes.Ldfld, si.THIS);
929 // Emits the code necessary to load the instance required
930 // to access the captured LocalInfo
932 public void EmitCapturedVariableInstance (LocalInfo li)
934 if (capture_context == null)
935 throw new Exception ("Calling EmitCapturedContext when there is no capture_context");
937 capture_context.EmitCapturedVariableInstance (this, li, CurrentAnonymousMethod);
940 public void EmitParameter (string name, bool leave_copy, bool prepared, ref LocalTemporary temp)
942 capture_context.EmitParameter (this, name, leave_copy, prepared, ref temp);
945 public void EmitAssignParameter (string name, Expression source, bool leave_copy, bool prepare_for_load, ref LocalTemporary temp)
947 capture_context.EmitAssignParameter (this, name, source, leave_copy, prepare_for_load, ref temp);
950 public void EmitAddressOfParameter (string name)
952 capture_context.EmitAddressOfParameter (this, name);
955 public Expression GetThis (Location loc)
958 if (CurrentBlock != null)
959 my_this = new This (CurrentBlock, loc);
961 my_this = new This (loc);
963 if (!my_this.ResolveBase (this))
971 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
973 protected CommonAssemblyModulClass ():
978 public void AddAttributes (ArrayList attrs)
980 foreach (Attribute a in attrs)
983 if (attributes == null) {
984 attributes = new Attributes (attrs);
987 attributes.AddAttributes (attrs);
990 public virtual void Emit (TypeContainer tc)
992 if (OptAttributes == null)
995 OptAttributes.Emit ();
998 protected Attribute ResolveAttribute (Type a_type)
1000 if (OptAttributes == null)
1003 // Ensure that we only have GlobalAttributes, since the Search below isn't safe with other types.
1004 if (!OptAttributes.CheckTargets ())
1007 Attribute a = OptAttributes.Search (a_type);
1014 public override IResolveContext ResolveContext {
1020 #region IResolveContext Members
1022 public DeclSpace DeclContainer {
1024 return RootContext.Tree.Types;
1028 public bool IsInObsoleteScope {
1034 public bool IsInUnsafeScope {
1043 public class AssemblyClass : CommonAssemblyModulClass {
1044 // TODO: make it private and move all builder based methods here
1045 public AssemblyBuilder Builder;
1046 bool is_cls_compliant;
1047 bool wrap_non_exception_throws;
1049 public Attribute ClsCompliantAttribute;
1051 ListDictionary declarative_security;
1053 // Module is here just because of error messages
1054 static string[] attribute_targets = new string [] { "assembly", "module" };
1056 public AssemblyClass (): base ()
1058 wrap_non_exception_throws = true;
1061 public bool IsClsCompliant {
1063 return is_cls_compliant;
1067 public bool WrapNonExceptionThrows {
1069 return wrap_non_exception_throws;
1073 public override AttributeTargets AttributeTargets {
1075 return AttributeTargets.Assembly;
1079 public override bool IsClsComplianceRequired ()
1081 return is_cls_compliant;
1084 public void Resolve ()
1086 ClsCompliantAttribute = ResolveAttribute (TypeManager.cls_compliant_attribute_type);
1087 if (ClsCompliantAttribute != null) {
1088 is_cls_compliant = ClsCompliantAttribute.GetClsCompliantAttributeValue ();
1092 Attribute a = ResolveAttribute (TypeManager.runtime_compatibility_attr_type);
1094 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1096 wrap_non_exception_throws = (bool)val;
1102 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1105 // check for possible ECMA key
1106 if (strongNameBlob.Length == 16) {
1107 // will be rejected if not "the" ECMA key
1108 an.SetPublicKey (strongNameBlob);
1111 // take it, with or without, a private key
1112 RSA rsa = CryptoConvert.FromCapiKeyBlob (strongNameBlob);
1113 // and make sure we only feed the public part to Sys.Ref
1114 byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
1116 // AssemblyName.SetPublicKey requires an additional header
1117 byte[] publicKeyHeader = new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 };
1119 byte[] encodedPublicKey = new byte [12 + publickey.Length];
1120 Buffer.BlockCopy (publicKeyHeader, 0, encodedPublicKey, 0, 12);
1121 Buffer.BlockCopy (publickey, 0, encodedPublicKey, 12, publickey.Length);
1122 an.SetPublicKey (encodedPublicKey);
1126 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' is incorrectly encoded");
1127 Environment.Exit (1);
1131 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1132 public AssemblyName GetAssemblyName (string name, string output)
1134 if (OptAttributes != null) {
1135 foreach (Attribute a in OptAttributes.Attrs) {
1136 // cannot rely on any resolve-based members before you call Resolve
1137 if (a.ExplicitTarget == null || a.ExplicitTarget != "assembly")
1140 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1141 // However, this is invoked by CodeGen.Init, when none of the namespaces
1143 // TODO: Does not handle quoted attributes properly
1145 case "AssemblyKeyFile":
1146 case "AssemblyKeyFileAttribute":
1147 case "System.Reflection.AssemblyKeyFileAttribute":
1148 if (RootContext.StrongNameKeyFile != null) {
1149 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1150 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1151 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1154 string value = a.GetString ();
1155 if (value.Length != 0)
1156 RootContext.StrongNameKeyFile = value;
1159 case "AssemblyKeyName":
1160 case "AssemblyKeyNameAttribute":
1161 case "System.Reflection.AssemblyKeyNameAttribute":
1162 if (RootContext.StrongNameKeyContainer != null) {
1163 Report.SymbolRelatedToPreviousError (a.Location, a.Name);
1164 Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1165 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1168 string value = a.GetString ();
1169 if (value.Length != 0)
1170 RootContext.StrongNameKeyContainer = value;
1173 case "AssemblyDelaySign":
1174 case "AssemblyDelaySignAttribute":
1175 case "System.Reflection.AssemblyDelaySignAttribute":
1176 RootContext.StrongNameDelaySign = a.GetBoolean ();
1182 AssemblyName an = new AssemblyName ();
1183 an.Name = Path.GetFileNameWithoutExtension (name);
1185 // note: delay doesn't apply when using a key container
1186 if (RootContext.StrongNameKeyContainer != null) {
1187 an.KeyPair = new StrongNameKeyPair (RootContext.StrongNameKeyContainer);
1191 // strongname is optional
1192 if (RootContext.StrongNameKeyFile == null)
1195 string AssemblyDir = Path.GetDirectoryName (output);
1197 // the StrongName key file may be relative to (a) the compiled
1198 // file or (b) to the output assembly. See bugzilla #55320
1199 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1201 // (a) relative to the compiled file
1202 string filename = Path.GetFullPath (RootContext.StrongNameKeyFile);
1203 bool exist = File.Exists (filename);
1204 if ((!exist) && (AssemblyDir != null) && (AssemblyDir != String.Empty)) {
1205 // (b) relative to the outputed assembly
1206 filename = Path.GetFullPath (Path.Combine (AssemblyDir, RootContext.StrongNameKeyFile));
1207 exist = File.Exists (filename);
1211 using (FileStream fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) {
1212 byte[] snkeypair = new byte [fs.Length];
1213 fs.Read (snkeypair, 0, snkeypair.Length);
1215 if (RootContext.StrongNameDelaySign) {
1216 // delayed signing - DO NOT include private key
1217 SetPublicKey (an, snkeypair);
1220 // no delay so we make sure we have the private key
1222 CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
1223 an.KeyPair = new StrongNameKeyPair (snkeypair);
1225 catch (CryptographicException) {
1226 if (snkeypair.Length == 16) {
1227 // error # is different for ECMA key
1228 Report.Error (1606, "Could not sign the assembly. " +
1229 "ECMA key can only be used to delay-sign assemblies");
1232 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1240 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1246 void Error_AssemblySigning (string text)
1248 Report.Error (1548, "Error during assembly signing. " + text);
1251 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1253 if (a.Type.IsSubclassOf (TypeManager.security_attr_type) && a.CheckSecurityActionValidity (true)) {
1254 if (declarative_security == null)
1255 declarative_security = new ListDictionary ();
1257 a.ExtractSecurityPermissionSet (declarative_security);
1261 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1262 string value = a.GetString ();
1263 if (value == null || value.Length == 0)
1266 if (RootContext.Target == Target.Exe) {
1267 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1272 Builder.SetCustomAttribute (customBuilder);
1275 public override void Emit (TypeContainer tc)
1279 if (declarative_security != null) {
1281 MethodInfo add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1282 object builder_instance = Builder;
1285 // Microsoft runtime hacking
1286 if (add_permission == null) {
1287 Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1288 add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
1290 FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
1291 builder_instance = fi.GetValue (Builder);
1294 object[] args = new object [] { declarative_security [SecurityAction.RequestMinimum],
1295 declarative_security [SecurityAction.RequestOptional],
1296 declarative_security [SecurityAction.RequestRefuse] };
1297 add_permission.Invoke (builder_instance, args);
1300 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1305 public override string[] ValidAttributeTargets {
1307 return attribute_targets;
1312 public class ModuleClass : CommonAssemblyModulClass {
1313 // TODO: make it private and move all builder based methods here
1314 public ModuleBuilder Builder;
1315 bool m_module_is_unsafe;
1317 public CharSet DefaultCharSet = CharSet.Ansi;
1318 public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
1320 static string[] attribute_targets = new string [] { "module" };
1322 public ModuleClass (bool is_unsafe)
1324 m_module_is_unsafe = is_unsafe;
1327 public override AttributeTargets AttributeTargets {
1329 return AttributeTargets.Module;
1333 public override bool IsClsComplianceRequired ()
1335 return CodeGen.Assembly.IsClsCompliant;
1338 public override void Emit (TypeContainer tc)
1342 if (!m_module_is_unsafe)
1345 if (TypeManager.unverifiable_code_ctor == null) {
1346 Console.WriteLine ("Internal error ! Cannot set unverifiable code attribute.");
1350 Builder.SetCustomAttribute (new CustomAttributeBuilder (TypeManager.unverifiable_code_ctor, new object [0]));
1353 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder customBuilder)
1355 if (a.Type == TypeManager.cls_compliant_attribute_type) {
1356 if (CodeGen.Assembly.ClsCompliantAttribute == null) {
1357 Report.Warning (3012, 1, a.Location, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1359 else if (CodeGen.Assembly.IsClsCompliant != a.GetBoolean ()) {
1360 Report.SymbolRelatedToPreviousError (CodeGen.Assembly.ClsCompliantAttribute.Location, CodeGen.Assembly.ClsCompliantAttribute.GetSignatureForError ());
1361 Report.Error (3017, a.Location, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1366 Builder.SetCustomAttribute (customBuilder);
1370 /// It is called very early therefore can resolve only predefined attributes
1372 public void ResolveAttributes ()
1375 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1377 DefaultCharSet = a.GetCharSetValue ();
1378 switch (DefaultCharSet) {
1383 DefaultCharSetType = TypeAttributes.AutoClass;
1385 case CharSet.Unicode:
1386 DefaultCharSetType = TypeAttributes.UnicodeClass;
1389 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1396 public override string[] ValidAttributeTargets {
1398 return attribute_targets;