2 // Mono.ILASM.MethodDef
5 // Jackson Harper (Jackson@LatitudeGeo.com)
7 // (C) 2003 Jackson Harper, All rights reserved
13 using System.Collections;
14 using System.Security;
16 namespace Mono.ILASM {
18 public class MethodDef : ICustomAttrTarget, IDeclSecurityTarget {
20 protected class GenericInfo {
23 public ArrayList ConstraintList;
26 private PEAPI.MethAttr meth_attr;
27 private PEAPI.CallConv call_conv;
28 private PEAPI.ImplAttr impl_attr;
30 private string signature;
31 private Hashtable vararg_sig_table;
32 private ITypeRef ret_type;
33 private ArrayList param_list;
34 private ArrayList inst_list;
35 private ArrayList customattr_list;
36 private DeclSecurity decl_sec;
37 private Hashtable label_table;
38 private Hashtable labelref_table;
39 private ArrayList label_list;
40 private PEAPI.MethodDef methoddef;
41 private bool entry_point;
42 private bool zero_init;
43 private bool is_resolved;
44 private bool is_defined;
45 private ArrayList local_list;
46 private Hashtable named_local_table;
47 private bool init_locals;
48 private int max_stack;
49 private bool pinvoke_info;
50 private ExternModule pinvoke_mod;
51 private string pinvoke_name;
52 private PEAPI.PInvokeAttr pinvoke_attr;
53 private SourceMethod source;
54 private PEAPI.NativeType ret_native_type;
55 private TypeDef type_def;
56 private GenericParameters gen_params;
58 public MethodDef (CodeGen codegen, PEAPI.MethAttr meth_attr,
59 PEAPI.CallConv call_conv, PEAPI.ImplAttr impl_attr,
60 string name, ITypeRef ret_type, ArrayList param_list,
61 Location start, GenericParameters gen_params, TypeDef type_def)
63 this.meth_attr = meth_attr;
64 this.call_conv = call_conv;
65 this.impl_attr = impl_attr;
67 this.ret_type = ret_type;
68 this.param_list = param_list;
69 this.type_def = type_def;
70 this.gen_params = gen_params;
72 inst_list = new ArrayList ();
73 label_table = new Hashtable ();
74 labelref_table = new Hashtable ();
75 label_list = new ArrayList ();
76 local_list = new ArrayList ();
77 named_local_table = new Hashtable ();
90 codegen.BeginMethodDef (this);
92 if (codegen.SymbolWriter != null)
93 source = codegen.SymbolWriter.BeginMethod (this, start);
100 public string Signature {
101 get { return signature; }
104 public ITypeRef RetType {
105 get { return ret_type; }
108 public PEAPI.CallConv CallConv {
109 get { return call_conv; }
112 public PEAPI.MethodDef PeapiMethodDef {
113 get { return methoddef; }
116 public PEAPI.MethAttr Attributes {
117 get { return meth_attr; }
118 set { meth_attr = value; }
121 public bool IsVararg {
122 get { return (call_conv & PEAPI.CallConv.Vararg) != 0; }
125 public bool IsStatic {
126 get { return (meth_attr & PEAPI.MethAttr.Static) != 0; }
129 public bool IsVirtual {
130 get { return (meth_attr & PEAPI.MethAttr.Virtual) != 0; }
133 public bool IsAbstract {
134 get { return (meth_attr & PEAPI.MethAttr.Abstract) != 0; }
137 public ITypeRef[] ParamTypeList () {
139 if (param_list == null)
140 return new ITypeRef[0];
142 ITypeRef[] type_list = new ITypeRef[param_list.Count];
143 foreach (ParamDef param in param_list) {
144 type_list[count++] = param.Type;
149 public void AddPInvokeInfo (PEAPI.PInvokeAttr pinvoke_attr, ExternModule pinvoke_mod,
152 this.pinvoke_attr = pinvoke_attr;
153 this.pinvoke_mod = pinvoke_mod;
154 this.pinvoke_name = pinvoke_name;
158 public int GenParamCount {
159 get { return (gen_params != null ? gen_params.Count : 0); }
162 public int GetGenericParamNum (string id)
164 if (gen_params == null)
165 throw new Exception ("Not a generic method");
167 return gen_params.GetGenericParamNum (id);
170 public void AddParamDefaultValue (int index, PEAPI.Constant defval)
172 if (param_list [index] != null) {
173 ((ParamDef)param_list [index]).AddDefaultValue (defval);
177 public void AddCustomAttribute (CustomAttr customattr)
179 if (customattr_list == null)
180 customattr_list = new ArrayList ();
182 customattr_list.Add (customattr);
185 public void AddPermissionSet (PEAPI.SecurityAction sec_action, PermissionSet ps)
187 if (decl_sec == null)
188 decl_sec = new DeclSecurity ();
190 decl_sec.AddPermissionSet (sec_action, ps);
193 public void AddPermission (PEAPI.SecurityAction sec_action, IPermission iper)
195 if (decl_sec == null)
196 decl_sec = new DeclSecurity ();
198 decl_sec.AddPermission (sec_action, iper);
201 public void AddRetTypeMarshalInfo (PEAPI.NativeType native_type)
203 this.ret_native_type = native_type;
206 public void AddLocals (ArrayList local_list)
208 int slot_pos = this.local_list.Count;
210 foreach (Local local in local_list) {
211 if (local.Slot == -1) {
212 local.Slot = slot_pos;
215 if (local.Name == null)
217 if(!named_local_table.Contains(local.Name))
218 named_local_table.Add (local.Name, local);
221 this.local_list.AddRange (local_list);
224 public Local GetNamedLocal (string name)
226 return (Local) named_local_table[name];
229 public int GetNamedLocalSlot (string name)
231 Local local = (Local) named_local_table[name];
236 public int GetNamedParamPos (string name)
241 foreach (ParamDef param in param_list) {
243 if (param.Name.CompareTo (name) == 0)
250 public ParamDef GetParam (int index)
252 if (param_list [index] != null)
253 return (ParamDef)param_list [index];
258 public void InitLocals ()
263 public void EntryPoint ()
266 throw new Exception ("Non-static method as entrypoint.");
270 public void ZeroInit ()
275 public void SetMaxStack (int max_stack)
277 this.max_stack = max_stack;
280 public void ResolveGenParam (PEAPI.GenParam gpar)
282 if (gpar.Index != -1)
285 if (gpar.Type == PEAPI.GenParamType.MVar)
286 gpar.Index = GetGenericParamNum (gpar.Name);
288 gpar.Index = type_def.GetGenericParamNum (gpar.Name);
291 /* TODO: Report error */
292 throw new Exception (String.Format ("Invalid {0}type parameter '{1}'",
293 (gpar.Type == PEAPI.GenParamType.MVar ? "method " : ""),
297 public void ResolveGenParams ()
299 GenericParameters type_params = (type_def != null) ? type_def.TypeParameters : null;
301 if (gen_params == null && type_params == null)
304 if (gen_params != null)
305 gen_params.ResolveConstraints (type_params, gen_params);
307 IGenericTypeRef gtr = ret_type as IGenericTypeRef;
309 gtr.Resolve (type_params, gen_params);
311 if (param_list == null)
314 foreach (ParamDef param in param_list) {
315 gtr = param.Type as IGenericTypeRef;
317 gtr.Resolve (type_params, gen_params);
321 public PEAPI.MethodDef Resolve (CodeGen code_gen)
323 return Resolve (code_gen, null);
326 public PEAPI.MethodDef Resolve (CodeGen code_gen, PEAPI.ClassDef classdef)
331 PEAPI.Param [] param_array = GenerateParams (code_gen);
333 ret_type.Resolve (code_gen);
335 if (classdef == null)
336 methoddef = code_gen.PEFile.AddMethod (meth_attr, impl_attr,
337 name, ret_type.PeapiType, param_array);
339 methoddef = classdef.AddMethod (meth_attr, impl_attr,
340 name, ret_type.PeapiType, param_array);
342 methoddef.AddCallConv (call_conv);
344 if (ret_native_type != null)
345 methoddef.AddRetTypeMarshallInfo (ret_native_type);
352 private PEAPI.Param [] GenerateParams (CodeGen code_gen)
354 PEAPI.Param[] param_array;
356 if (param_list != null && param_list.Count > 0) {
357 int param_count = param_list.Count;
359 // Remove the last param if its the sentinel, not sure what
360 // should happen with more then one sentinel
361 ParamDef last = (ParamDef) param_list [param_count-1];
362 if (last.IsSentinel ())
365 param_array = new PEAPI.Param [param_count];
366 for (int i = 0; i < param_count; i++) {
367 ParamDef paramdef = (ParamDef) param_list [i];
368 paramdef.Define (code_gen);
369 param_array [i] = paramdef.PeapiParam;
373 param_array = new PEAPI.Param [0];
379 public PEAPI.MethodRef GetVarargSig (PEAPI.Type[] opt)
382 throw new Exception ("Methods must be resolved before a vararg sig can be created.");
384 PEAPI.MethodRef methref = null;
385 StringBuilder sigbuilder = new StringBuilder ();
387 foreach (PEAPI.Type t in opt)
388 sigbuilder.Append (opt + ", ");
389 sig = sigbuilder.ToString ();
391 if (vararg_sig_table == null) {
392 vararg_sig_table = new Hashtable ();
394 methref = vararg_sig_table [sig] as PEAPI.MethodRef;
397 if (methref == null) {
398 methref = methoddef.MakeVarArgSignature (opt);
399 vararg_sig_table [sig] = methref;
406 /// Define a member method
408 public void Define (CodeGen code_gen)
413 if (type_def == null)
415 Resolve (code_gen, null);
417 Resolve (code_gen, (PEAPI.ClassDef) type_def.ClassDef);
419 WriteCode (code_gen, methoddef);
421 //code_gen.Report.Message (String.Format ("Assembled method {0}::{1}", typedef.FullName, name)); is_defined = true;
424 public void AddInstr (IInstr instr)
426 inst_list.Add (instr);
429 protected void WriteCode (CodeGen code_gen, PEAPI.MethodDef methoddef)
431 /// Add the custrom attributes to this method
432 if (customattr_list != null)
433 foreach (CustomAttr customattr in customattr_list) {
434 customattr.AddTo (code_gen, methoddef);
435 if (customattr.IsSuppressUnmanaged (code_gen))
436 methoddef.AddMethAttribute (PEAPI.MethAttr.HasSecurity);
439 /// Add declarative security to this method
440 if (decl_sec != null) {
441 decl_sec.AddTo (code_gen, methoddef);
442 methoddef.AddMethAttribute (PEAPI.MethAttr.HasSecurity);
448 // Generic type parameters
449 if (gen_params != null)
450 gen_params.Resolve (code_gen, methoddef);
453 methoddef.DeclareEntryPoint ();
455 if (local_list.Count > 0) {
456 int ec = code_gen.Report.ErrorCount;
457 PEAPI.Local[] local_array = new PEAPI.Local[local_list.Count];
460 foreach (Local local in local_list)
461 local_array[local.Slot] = local.GetPeapiLocal (code_gen);
463 if (code_gen.Report.ErrorCount > ec)
469 methoddef.AddLocals (local_array, init_locals);
472 /// Nothing seems to work if maxstack is not set,
473 /// i need to find out if this NEEDs to be set
474 /// and what its default value should be
477 methoddef.SetMaxStack (max_stack);
480 methoddef.AddPInvokeInfo (pinvoke_mod.ModuleRef,
481 (pinvoke_name != null ? pinvoke_name : name), pinvoke_attr);
484 if (inst_list.Count < 1)
487 PEAPI.CILInstructions cil = methoddef.CreateCodeBuffer ();
488 /// Create all the labels
489 /// TODO: Most labels don't actually need to be created so we could
490 /// probably only create the ones that need to be
491 LabelInfo[] label_info = new LabelInfo[label_table.Count + label_list.Count];
492 label_table.Values.CopyTo (label_info, 0);
493 label_list.CopyTo (label_info, label_table.Count);
494 int previous_pos = -1;
495 LabelInfo previous_label = null;
496 Array.Sort (label_info);
498 foreach (LabelInfo label in label_info) {
499 if (label.UseOffset) {
500 label.Define (new PEAPI.CILLabel (label.Offset));
503 if (label.Pos == previous_pos)
504 label.Label = previous_label.Label;
506 label.Define (cil.NewLabel ());
508 previous_label = label;
509 previous_pos = label.Pos;
512 // Set all the label refs
513 foreach (LabelInfo label in labelref_table.Values) {
514 LabelInfo def = (LabelInfo) label_table[label.Name];
516 code_gen.Report.Error ("Undefined Label: " + label);
519 label.Label = def.Label;
523 int next_label_pos = (label_info.Length > 0 ? label_info[0].Pos : -1);
525 for (int i=0; i<inst_list.Count; i++) {
526 IInstr instr = (IInstr) inst_list[i];
527 if (next_label_pos == i) {
528 cil.CodeLabel (label_info[label_pos].Label);
529 if (label_pos < label_info.Length) {
530 while (next_label_pos == i && ++label_pos < label_info.Length) {
531 if (label_info[label_pos].UseOffset)
532 cil.CodeLabel (label_info[label_pos].Label);
533 next_label_pos = label_info[label_pos].Pos;
536 if (label_pos >= label_info.Length)
540 source.MarkLocation (instr.Location.line, cil.Offset);
541 instr.Emit (code_gen, this, cil);
545 source.MarkLocation (source.EndLine, cil.Offset);
548 public LabelInfo AddLabel (string name)
550 LabelInfo label_info = (LabelInfo) label_table[name];
551 if (label_info != null)
553 label_info = new LabelInfo (name, inst_list.Count);
554 label_table.Add (name, label_info);
558 public LabelInfo AddLabelRef (string name)
560 LabelInfo label_info = (LabelInfo) label_table[name];
561 if (label_info != null)
563 label_info = (LabelInfo) labelref_table[name];
564 if (label_info != null)
566 label_info = new LabelInfo (name, -1);
567 labelref_table.Add (name, label_info);
571 public LabelInfo AddLabel (int offset)
573 // We go pos + 1 so this line is not counted
574 LabelInfo label_info = new LabelInfo (null, inst_list.Count+1, (uint) offset);
575 label_list.Add (label_info);
579 public LabelInfo AddLabel ()
581 int pos = inst_list.Count;
582 LabelInfo label_info = new LabelInfo (null, inst_list.Count);
583 label_list.Add (label_info);
587 public PEAPI.CILLabel GetLabelDef (string name)
589 LabelInfo label_info = (LabelInfo) label_table[name];
591 return label_info.Label;
594 public PEAPI.CILLabel GetLabelDef (int pos)
596 foreach (LabelInfo li in label_list) {
603 private void CreateSignature ()
606 signature = CreateVarargSignature (RetType, name, param_list);
608 signature = CreateSignature (RetType, name, param_list, GenParamCount);
611 public static string CreateSignature (ITypeRef RetType, string name, IList param_list, int gen_param_count)
613 StringBuilder builder = new StringBuilder ();
615 builder.Append (RetType.FullName);
616 builder.Append (" ");
617 builder.Append (name);
618 builder.AppendFormat ("`{0}", gen_param_count);
619 builder.Append ('(');
621 if (param_list != null) {
623 foreach (ParamDef paramdef in param_list) {
625 builder.Append (',');
626 builder.Append (paramdef.TypeName);
630 builder.Append (')');
632 return builder.ToString ();
635 public static string CreateVarargSignature (ITypeRef RetType, string name, IList param_list)
637 StringBuilder builder = new StringBuilder ();
638 ParamDef last = null;
640 builder.Append (RetType.FullName);
641 builder.Append (" ");
642 builder.Append (name);
643 builder.Append ('(');
646 if (param_list != null) {
647 foreach (ParamDef paramdef in param_list) {
649 builder.Append (',');
650 builder.Append (paramdef.TypeName);
653 last = (ParamDef) param_list[param_list.Count - 1];
657 if (last == null || !last.IsSentinel ()) {
659 builder.Append (',');
660 builder.Append ("...");
663 builder.Append (')');
665 return builder.ToString ();
668 public static string CreateVarargSignature (ITypeRef RetType, string name, ITypeRef [] param_list)
670 StringBuilder builder = new StringBuilder ();
671 ITypeRef last = null;
673 builder.Append (RetType.FullName);
674 builder.Append (" ");
675 builder.Append (name);
676 builder.Append ('(');
679 if (param_list != null && param_list.Length > 0) {
680 foreach (ITypeRef param in param_list) {
682 builder.Append (',');
683 builder.Append (param.FullName);
686 if (param is SentinelTypeRef)
692 if (last == null || !(last is SentinelTypeRef)) {
694 builder.Append (',');
695 builder.Append ("...");
698 builder.Append (')');
700 return builder.ToString ();
703 public static string CreateSignature (ITypeRef RetType, string name, ITypeRef[] param_list, int gen_param_count)
705 StringBuilder builder = new StringBuilder ();
707 builder.Append (RetType.FullName);
708 builder.Append (" ");
709 builder.Append (name);
710 builder.AppendFormat ("`{0}", gen_param_count);
711 builder.Append ('(');
713 if (param_list != null) {
715 foreach (ITypeRef param in param_list) {
717 builder.Append (',');
718 builder.Append (param.FullName);
720 if (param is SentinelTypeRef)
724 builder.Append (')');
726 return builder.ToString ();
729 private void FixAttributes ()
731 if (name == ".ctor" || name == ".cctor")
732 meth_attr |= PEAPI.MethAttr.SpecialName | PEAPI.MethAttr.RTSpecialName;
733 // If methods aren't flagged as static they are instance
734 if ((PEAPI.MethAttr.Static & meth_attr) == 0)
735 call_conv |= PEAPI.CallConv.Instance;