Debian Codegraph @

external/ikvm/reflect/Emit/MethodBuilder.cs

raw
1 /*
2 Copyright (C) 2008-2012 Jeroen Frijters
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11
12 1. The origin of this software must not be misrepresented; you must not
13 claim that you wrote the original software. If you use this software
14 in a product, an acknowledgment in the product documentation would be
15 appreciated but is not required.
16 2. Altered source versions must be plainly marked as such, and must not be
17 misrepresented as being the original software.
18 3. This notice may not be removed or altered from any source distribution.
19
20 Jeroen Frijters
21 [email protected]
22
23 */
24 using System;
25 using System.IO;
26 using System.Diagnostics;
27 using System.Collections.Generic;
28 using System.Runtime.InteropServices;
29 using System.Runtime.CompilerServices;
30 #if !NO_SYMBOL_WRITER
31 using System.Diagnostics.SymbolStore;
32 #endif
33 using IKVM.Reflection.Metadata;
34 using IKVM.Reflection.Writer;
35
36 namespace IKVM.Reflection.Emit
37 {
38 public sealed class MethodBuilder : MethodInfo
39 {
40 private readonly TypeBuilder typeBuilder;
41 private readonly string name;
42 private readonly int pseudoToken;
43 private int nameIndex;
44 private int signature;
45 private Type returnType;
46 private Type[] parameterTypes;
47 private PackedCustomModifiers customModifiers;
48 private MethodAttributes attributes;
49 private MethodImplAttributes implFlags;
50 private ILGenerator ilgen;
51 private int rva = -1;
52 private CallingConventions callingConvention;
53 private List<ParameterBuilder> parameters;
54 private GenericTypeParameterBuilder[] gtpb;
55 private List<CustomAttributeBuilder> declarativeSecurity;
56 private MethodSignature methodSignature;
57 private bool initLocals = true;
58
59 internal MethodBuilder(TypeBuilder typeBuilder, string name, MethodAttributes attributes, CallingConventions callingConvention)
60 {
61 this.typeBuilder = typeBuilder;
62 this.name = name;
63 this.pseudoToken = typeBuilder.ModuleBuilder.AllocPseudoToken();
64 this.attributes = attributes;
65 if ((attributes & MethodAttributes.Static) == 0)
66 {
67 callingConvention |= CallingConventions.HasThis;
68 }
69 this.callingConvention = callingConvention;
70 }
71
72 public ILGenerator GetILGenerator()
73 {
74 return GetILGenerator(16);
75 }
76
77 public ILGenerator GetILGenerator(int streamSize)
78 {
79 if (rva != -1)
80 {
81 throw new InvalidOperationException();
82 }
83 if (ilgen == null)
84 {
85 ilgen = new ILGenerator(typeBuilder.ModuleBuilder, streamSize);
86 }
87 return ilgen;
88 }
89
90 public void __ReleaseILGenerator()
91 {
92 if (ilgen != null)
93 {
94 #if !NO_SYMBOL_WRITER
95 if (this.ModuleBuilder.symbolWriter != null)
96 {
97 this.ModuleBuilder.symbolWriter.OpenMethod(new SymbolToken(-pseudoToken | 0x06000000), this);
98 }
99 #endif
100 rva = ilgen.WriteBody(initLocals);
101 #if !NO_SYMBOL_WRITER
102 if (this.ModuleBuilder.symbolWriter != null)
103 {
104 this.ModuleBuilder.symbolWriter.CloseMethod();
105 }
106 #endif
107 ilgen = null;
108 }
109 }
110
111 public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
112 {
113 SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute));
114 }
115
116 private void SetDllImportPseudoCustomAttribute(CustomAttributeBuilder customBuilder)
117 {
118 CallingConvention? callingConvention = customBuilder.GetFieldValue<CallingConvention>("CallingConvention");
119 CharSet? charSet = customBuilder.GetFieldValue<CharSet>("CharSet");
120 SetDllImportPseudoCustomAttribute((string)customBuilder.GetConstructorArgument(0),
121 (string)customBuilder.GetFieldValue("EntryPoint"),
122 callingConvention,
123 charSet,
124 (bool?)customBuilder.GetFieldValue("BestFitMapping"),
125 (bool?)customBuilder.GetFieldValue("ThrowOnUnmappableChar"),
126 (bool?)customBuilder.GetFieldValue("SetLastError"),
127 (bool?)customBuilder.GetFieldValue("PreserveSig"),
128 (bool?)customBuilder.GetFieldValue("ExactSpelling"));
129 }
130
131 internal void SetDllImportPseudoCustomAttribute(string dllName, string entryName, CallingConvention? nativeCallConv, CharSet? nativeCharSet,
132 bool? bestFitMapping, bool? throwOnUnmappableChar, bool? setLastError, bool? preserveSig, bool? exactSpelling)
133 {
134 const short NoMangle = 0x0001;
135 const short CharSetMask = 0x0006;
136 const short CharSetNotSpec = 0x0000;
137 const short CharSetAnsi = 0x0002;
138 const short CharSetUnicode = 0x0004;
139 const short CharSetAuto = 0x0006;
140 const short SupportsLastError = 0x0040;
141 const short CallConvMask = 0x0700;
142 const short CallConvWinapi = 0x0100;
143 const short CallConvCdecl = 0x0200;
144 const short CallConvStdcall = 0x0300;
145 const short CallConvThiscall = 0x0400;
146 const short CallConvFastcall = 0x0500;
147 // non-standard flags
148 const short BestFitOn = 0x0010;
149 const short BestFitOff = 0x0020;
150 const short CharMapErrorOn = 0x1000;
151 const short CharMapErrorOff = 0x2000;
152 short flags = CharSetNotSpec | CallConvWinapi;
153 if (bestFitMapping.HasValue)
154 {
155 flags |= bestFitMapping.Value ? BestFitOn : BestFitOff;
156 }
157 if (throwOnUnmappableChar.HasValue)
158 {
159 flags |= throwOnUnmappableChar.Value ? CharMapErrorOn : CharMapErrorOff;
160 }
161 if (nativeCallConv.HasValue)
162 {
163 flags &= ~CallConvMask;
164 switch (nativeCallConv.Value)
165 {
166 case System.Runtime.InteropServices.CallingConvention.Cdecl:
167 flags |= CallConvCdecl;
168 break;
169 case System.Runtime.InteropServices.CallingConvention.FastCall:
170 flags |= CallConvFastcall;
171 break;
172 case System.Runtime.InteropServices.CallingConvention.StdCall:
173 flags |= CallConvStdcall;
174 break;
175 case System.Runtime.InteropServices.CallingConvention.ThisCall:
176 flags |= CallConvThiscall;
177 break;
178 case System.Runtime.InteropServices.CallingConvention.Winapi:
179 flags |= CallConvWinapi;
180 break;
181 }
182 }
183 if (nativeCharSet.HasValue)
184 {
185 flags &= ~CharSetMask;
186 switch (nativeCharSet.Value)
187 {
188 case CharSet.Ansi:
189 case CharSet.None:
190 flags |= CharSetAnsi;
191 break;
192 case CharSet.Auto:
193 flags |= CharSetAuto;
194 break;
195 case CharSet.Unicode:
196 flags |= CharSetUnicode;
197 break;
198 }
199 }
200 if (exactSpelling.HasValue && exactSpelling.Value)
201 {
202 flags |= NoMangle;
203 }
204 if (!preserveSig.HasValue || preserveSig.Value)
205 {
206 implFlags |= MethodImplAttributes.PreserveSig;
207 }
208 if (setLastError.HasValue && setLastError.Value)
209 {
210 flags |= SupportsLastError;
211 }
212 ImplMapTable.Record rec = new ImplMapTable.Record();
213 rec.MappingFlags = flags;
214 rec.MemberForwarded = pseudoToken;
215 rec.ImportName = this.ModuleBuilder.Strings.Add(entryName ?? name);
216 rec.ImportScope = this.ModuleBuilder.ModuleRef.FindOrAddRecord(dllName == null ? 0 : this.ModuleBuilder.Strings.Add(dllName));
217 this.ModuleBuilder.ImplMap.AddRecord(rec);
218 }
219
220 private void SetMethodImplAttribute(CustomAttributeBuilder customBuilder)
221 {
222 MethodImplOptions opt;
223 switch (customBuilder.Constructor.ParameterCount)
224 {
225 case 0:
226 opt = 0;
227 break;
228 case 1:
229 {
230 object val = customBuilder.GetConstructorArgument(0);
231 if (val is short)
232 {
233 opt = (MethodImplOptions)(short)val;
234 }
235 else if (val is int)
236 {
237 opt = (MethodImplOptions)(int)val;
238 }
239 else
240 {
241 opt = (MethodImplOptions)val;
242 }
243 break;
244 }
245 default:
246 throw new NotSupportedException();
247 }
248 MethodCodeType? type = customBuilder.GetFieldValue<MethodCodeType>("MethodCodeType");
249 implFlags = (MethodImplAttributes)opt;
250 if (type.HasValue)
251 {
252 implFlags |= (MethodImplAttributes)type;
253 }
254 }
255
256 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
257 {
258 switch (customBuilder.KnownCA)
259 {
260 case KnownCA.DllImportAttribute:
261 SetDllImportPseudoCustomAttribute(customBuilder.DecodeBlob(this.Module.Assembly));
262 attributes |= MethodAttributes.PinvokeImpl;
263 break;
264 case KnownCA.MethodImplAttribute:
265 SetMethodImplAttribute(customBuilder.DecodeBlob(this.Module.Assembly));
266 break;
267 case KnownCA.PreserveSigAttribute:
268 implFlags |= MethodImplAttributes.PreserveSig;
269 break;
270 case KnownCA.SpecialNameAttribute:
271 attributes |= MethodAttributes.SpecialName;
272 break;
273 case KnownCA.SuppressUnmanagedCodeSecurityAttribute:
274 attributes |= MethodAttributes.HasSecurity;
275 goto default;
276 default:
277 this.ModuleBuilder.SetCustomAttribute(pseudoToken, customBuilder);
278 break;
279 }
280 }
281
282 public void __AddDeclarativeSecurity(CustomAttributeBuilder customBuilder)
283 {
284 attributes |= MethodAttributes.HasSecurity;
285 if (declarativeSecurity == null)
286 {
287 declarativeSecurity = new List<CustomAttributeBuilder>();
288 }
289 declarativeSecurity.Add(customBuilder);
290 }
291
292 #if !CORECLR
293 public void AddDeclarativeSecurity(System.Security.Permissions.SecurityAction securityAction, System.Security.PermissionSet permissionSet)
294 {
295 this.ModuleBuilder.AddDeclarativeSecurity(pseudoToken, securityAction, permissionSet);
296 this.attributes |= MethodAttributes.HasSecurity;
297 }
298 #endif
299
300 public void SetImplementationFlags(MethodImplAttributes attributes)
301 {
302 implFlags = attributes;
303 }
304
305 public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName)
306 {
307 if (parameters == null)
308 {
309 parameters = new List<ParameterBuilder>();
310 }
311 this.ModuleBuilder.Param.AddVirtualRecord();
312 ParameterBuilder pb = new ParameterBuilder(this.ModuleBuilder, position, attributes, strParamName);
313 if (parameters.Count == 0 || position >= parameters[parameters.Count - 1].Position)
314 {
315 parameters.Add(pb);
316 }
317 else
318 {
319 for (int i = 0; i < parameters.Count; i++)
320 {
321 if (parameters[i].Position > position)
322 {
323 parameters.Insert(i, pb);
324 break;
325 }
326 }
327 }
328 return pb;
329 }
330
331 private void CheckSig()
332 {
333 if (methodSignature != null)
334 {
335 throw new InvalidOperationException("The method signature can not be modified after it has been used.");
336 }
337 }
338
339 public void SetParameters(params Type[] parameterTypes)
340 {
341 CheckSig();
342 this.parameterTypes = Util.Copy(parameterTypes);
343 }
344
345 public void SetReturnType(Type returnType)
346 {
347 CheckSig();
348 this.returnType = returnType ?? this.Module.universe.System_Void;
349 }
350
351 public void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
352 {
353 SetSignature(returnType, parameterTypes, PackedCustomModifiers.CreateFromExternal(returnTypeOptionalCustomModifiers, returnTypeRequiredCustomModifiers,
354 parameterTypeOptionalCustomModifiers, parameterTypeRequiredCustomModifiers, Util.NullSafeLength(parameterTypes)));
355 }
356
357 public void __SetSignature(Type returnType, CustomModifiers returnTypeCustomModifiers, Type[] parameterTypes, CustomModifiers[] parameterTypeCustomModifiers)
358 {
359 SetSignature(returnType, parameterTypes, PackedCustomModifiers.CreateFromExternal(returnTypeCustomModifiers, parameterTypeCustomModifiers, Util.NullSafeLength(parameterTypes)));
360 }
361
362 private void SetSignature(Type returnType, Type[] parameterTypes, PackedCustomModifiers customModifiers)
363 {
364 CheckSig();
365 this.returnType = returnType ?? this.Module.universe.System_Void;
366 this.parameterTypes = Util.Copy(parameterTypes);
367 this.customModifiers = customModifiers;
368 }
369
370 public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
371 {
372 CheckSig();
373 if (gtpb != null)
374 {
375 throw new InvalidOperationException("Generic parameters already defined.");
376 }
377 gtpb = new GenericTypeParameterBuilder[names.Length];
378 for (int i = 0; i < names.Length; i++)
379 {
380 gtpb[i] = new GenericTypeParameterBuilder(names[i], this, i);
381 }
382 return (GenericTypeParameterBuilder[])gtpb.Clone();
383 }
384
385 public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
386 {
387 return new GenericMethodInstance(typeBuilder, this, typeArguments);
388 }
389
390 public override MethodInfo GetGenericMethodDefinition()
391 {
392 if (gtpb == null)
393 {
394 throw new InvalidOperationException();
395 }
396 return this;
397 }
398
399 public override Type[] GetGenericArguments()
400 {
401 return Util.Copy(gtpb);
402 }
403
404 internal override Type GetGenericMethodArgument(int index)
405 {
406 return gtpb[index];
407 }
408
409 internal override int GetGenericMethodArgumentCount()
410 {
411 return gtpb == null ? 0 : gtpb.Length;
412 }
413
414 public override Type ReturnType
415 {
416 get { return returnType; }
417 }
418
419 public override ParameterInfo ReturnParameter
420 {
421 get { return new ParameterInfoImpl(this, -1); }
422 }
423
424 public override MethodAttributes Attributes
425 {
426 get { return attributes; }
427 }
428
429 public void __SetAttributes(MethodAttributes attributes)
430 {
431 this.attributes = attributes;
432 }
433
434 public void __SetCallingConvention(CallingConventions callingConvention)
435 {
436 this.callingConvention = callingConvention;
437 this.methodSignature = null;
438 }
439
440 public override MethodImplAttributes GetMethodImplementationFlags()
441 {
442 return implFlags;
443 }
444
445 private sealed class ParameterInfoImpl : ParameterInfo
446 {
447 private readonly MethodBuilder method;
448 private readonly int parameter;
449
450 internal ParameterInfoImpl(MethodBuilder method, int parameter)
451 {
452 this.method = method;
453 this.parameter = parameter;
454 }
455
456 private ParameterBuilder ParameterBuilder
457 {
458 get
459 {
460 if (method.parameters != null)
461 {
462 foreach (ParameterBuilder pb in method.parameters)
463 {
464 // ParameterBuilder.Position is 1-based
465 if (pb.Position - 1 == parameter)
466 {
467 return pb;
468 }
469 }
470 }
471 return null;
472 }
473 }
474
475 public override string Name
476 {
477 get
478 {
479 ParameterBuilder pb = this.ParameterBuilder;
480 return pb != null ? pb.Name : null;
481 }
482 }
483
484 public override Type ParameterType
485 {
486 get { return parameter == -1 ? method.returnType : method.parameterTypes[parameter]; }
487 }
488
489 public override ParameterAttributes Attributes
490 {
491 get
492 {
493 ParameterBuilder pb = this.ParameterBuilder;
494 return pb != null ? (ParameterAttributes)pb.Attributes : ParameterAttributes.None;
495 }
496 }
497
498 public override int Position
499 {
500 get { return parameter; }
501 }
502
503 public override object RawDefaultValue
504 {
505 get
506 {
507 ParameterBuilder pb = this.ParameterBuilder;
508 if (pb != null && (pb.Attributes & (int)ParameterAttributes.HasDefault) != 0)
509 {
510 return method.ModuleBuilder.Constant.GetRawConstantValue(method.ModuleBuilder, pb.PseudoToken);
511 }
512 if (pb != null && (pb.Attributes & (int)ParameterAttributes.Optional) != 0)
513 {
514 return Missing.Value;
515 }
516 return null;
517 }
518 }
519
520 public override CustomModifiers __GetCustomModifiers()
521 {
522 return method.customModifiers.GetParameterCustomModifiers(parameter);
523 }
524
525 public override bool __TryGetFieldMarshal(out FieldMarshal fieldMarshal)
526 {
527 fieldMarshal = new FieldMarshal();
528 return false;
529 }
530
531 public override MemberInfo Member
532 {
533 get { return method; }
534 }
535
536 public override int MetadataToken
537 {
538 get
539 {
540 ParameterBuilder pb = this.ParameterBuilder;
541 return pb != null ? pb.PseudoToken : 0x08000000;
542 }
543 }
544
545 internal override Module Module
546 {
547 get { return method.Module; }
548 }
549 }
550
551 public override ParameterInfo[] GetParameters()
552 {
553 ParameterInfo[] parameters = new ParameterInfo[parameterTypes.Length];
554 for (int i = 0; i < parameters.Length; i++)
555 {
556 parameters[i] = new ParameterInfoImpl(this, i);
557 }
558 return parameters;
559 }
560
561 internal override int ParameterCount
562 {
563 get { return parameterTypes.Length; }
564 }
565
566 public override Type DeclaringType
567 {
568 get { return typeBuilder.IsModulePseudoType ? null : typeBuilder; }
569 }
570
571 public override string Name
572 {
573 get { return name; }
574 }
575
576 public override CallingConventions CallingConvention
577 {
578 get { return callingConvention; }
579 }
580
581 public override int MetadataToken
582 {
583 get { return pseudoToken; }
584 }
585
586 public override bool IsGenericMethod
587 {
588 get { return gtpb != null; }
589 }
590
591 public override bool IsGenericMethodDefinition
592 {
593 get { return gtpb != null; }
594 }
595
596 public override Module Module
597 {
598 get { return typeBuilder.Module; }
599 }
600
601 public Module GetModule()
602 {
603 return typeBuilder.Module;
604 }
605
606 public MethodToken GetToken()
607 {
608 return new MethodToken(pseudoToken);
609 }
610
611 public override MethodBody GetMethodBody()
612 {
613 throw new NotSupportedException();
614 }
615
616 public override int __MethodRVA
617 {
618 get { throw new NotImplementedException(); }
619 }
620
621 public bool InitLocals
622 {
623 get { return initLocals; }
624 set { initLocals = value; }
625 }
626
627 public void __AddUnmanagedExport(string name, int ordinal)
628 {
629 this.ModuleBuilder.AddUnmanagedExport(name, ordinal, this, new RelativeVirtualAddress(0xFFFFFFFF));
630 }
631
632 public void CreateMethodBody(byte[] il, int count)
633 {
634 if (il == null)
635 {
636 throw new NotSupportedException();
637 }
638 if (il.Length != count)
639 {
640 Array.Resize(ref il, count);
641 }
642 SetMethodBody(il, 16, null, null, null);
643 }
644
645 public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
646 {
647 ByteBuffer bb = this.ModuleBuilder.methodBodies;
648
649 if (localSignature == null && exceptionHandlers == null && maxStack <= 8 && il.Length < 64)
650 {
651 rva = bb.Position;
652 ILGenerator.WriteTinyHeader(bb, il.Length);
653 }
654 else
655 {
656 // fat headers require 4-byte alignment
657 bb.Align(4);
658 rva = bb.Position;
659 ILGenerator.WriteFatHeader(bb, initLocals, exceptionHandlers != null, (ushort)maxStack, il.Length,
660 localSignature == null ? 0 : this.ModuleBuilder.GetSignatureToken(localSignature, localSignature.Length).Token);
661 }
662
663 if (tokenFixups != null)
664 {
665 ILGenerator.AddTokenFixups(bb.Position, this.ModuleBuilder.tokenFixupOffsets, tokenFixups);
666 }
667 bb.Write(il);
668
669 if (exceptionHandlers != null)
670 {
671 List<ILGenerator.ExceptionBlock> exceptions = new List<ILGenerator.ExceptionBlock>();
672 foreach (ExceptionHandler block in exceptionHandlers)
673 {
674 exceptions.Add(new ILGenerator.ExceptionBlock(block));
675 }
676 ILGenerator.WriteExceptionHandlers(bb, exceptions);
677 }
678 }
679
680 internal void Bake()
681 {
682 this.nameIndex = this.ModuleBuilder.Strings.Add(name);
683 this.signature = this.ModuleBuilder.GetSignatureBlobIndex(this.MethodSignature);
684
685 __ReleaseILGenerator();
686
687 if (declarativeSecurity != null)
688 {
689 this.ModuleBuilder.AddDeclarativeSecurity(pseudoToken, declarativeSecurity);
690 }
691 }
692
693 internal ModuleBuilder ModuleBuilder
694 {
695 get { return typeBuilder.ModuleBuilder; }
696 }
697
698 internal void WriteMethodDefRecord(int baseRVA, MetadataWriter mw, ref int paramList)
699 {
700 if (rva != -1)
701 {
702 mw.Write(rva + baseRVA);
703 }
704 else
705 {
706 mw.Write(0);
707 }
708 mw.Write((short)implFlags);
709 mw.Write((short)attributes);
710 mw.WriteStringIndex(nameIndex);
711 mw.WriteBlobIndex(signature);
712 mw.WriteParam(paramList);
713 if (parameters != null)
714 {
715 paramList += parameters.Count;
716 }
717 }
718
719 internal void WriteParamRecords(MetadataWriter mw)
720 {
721 if (parameters != null)
722 {
723 foreach (ParameterBuilder pb in parameters)
724 {
725 pb.WriteParamRecord(mw);
726 }
727 }
728 }
729
730 internal void FixupToken(int token, ref int parameterToken)
731 {
732 typeBuilder.ModuleBuilder.RegisterTokenFixup(this.pseudoToken, token);
733 if (parameters != null)
734 {
735 foreach (ParameterBuilder pb in parameters)
736 {
737 pb.FixupToken(parameterToken++);
738 }
739 }
740 }
741
742 internal override MethodSignature MethodSignature
743 {
744 get
745 {
746 if (methodSignature == null)
747 {
748 methodSignature = MethodSignature.MakeFromBuilder(returnType ?? typeBuilder.Universe.System_Void, parameterTypes ?? Type.EmptyTypes,
749 customModifiers, callingConvention, gtpb == null ? 0 : gtpb.Length);
750 }
751 return methodSignature;
752 }
753 }
754
755 internal override int ImportTo(ModuleBuilder other)
756 {
757 return other.ImportMethodOrField(typeBuilder, name, this.MethodSignature);
758 }
759
760 internal void CheckBaked()
761 {
762 typeBuilder.CheckBaked();
763 }
764
765 internal override int GetCurrentToken()
766 {
767 if (typeBuilder.ModuleBuilder.IsSaved)
768 {
769 return typeBuilder.ModuleBuilder.ResolvePseudoToken(pseudoToken);
770 }
771 else
772 {
773 return pseudoToken;
774 }
775 }
776
777 internal override bool IsBaked
778 {
779 get { return typeBuilder.IsBaked; }
780 }
781 }
782 }