本文整理汇总了C#中Mono.Cecil.Cil.MethodBody.GetILProcessor方法的典型用法代码示例。如果您正苦于以下问题:C# MethodBody.GetILProcessor方法的具体用法?C# MethodBody.GetILProcessor怎么用?C# MethodBody.GetILProcessor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mono.Cecil.Cil.MethodBody
的用法示例。
在下文中一共展示了MethodBody.GetILProcessor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateExplicitStub
/// <summary>
/// Create a new method in the declaring type of the given implicit implementation with the given name.
/// This method will call the implicit implementation.
/// </summary>
internal static MethodDefinition CreateExplicitStub(MethodDefinition implicitImpl, string name, MethodDefinition iMethod, bool avoidGenericParam)
{
// Create method
var newMethod = new MethodDefinition(name, implicitImpl.Attributes, implicitImpl.ReturnType);
newMethod.IsVirtual = false;
newMethod.IsAbstract = false;
newMethod.IsFinal = true;
// Clone generic parameters
foreach (var gp in implicitImpl.GenericParameters)
{
newMethod.GenericParameters.Add(new GenericParameter(gp.Name, newMethod));
}
// Update according to new context
var cloner = new TypeCloner(avoidGenericParam, implicitImpl.Module.TypeSystem);
newMethod.ReturnType = cloner.Get(implicitImpl.ReturnType, newMethod);
// Clone parameters
foreach (var p in iMethod.Parameters)
{
newMethod.Parameters.Add(new ParameterDefinition(p.Name, p.Attributes, cloner.Get(p.ParameterType, newMethod)));
}
// Add the method
var targetType = implicitImpl.DeclaringType;
targetType.Methods.Add(newMethod);
// Add override
newMethod.Overrides.Add(iMethod);
// Create method body
var body = new MethodBody(newMethod);
newMethod.Body = body;
var worker = body.GetILProcessor();
// Push this
worker.Emit(OpCodes.Ldarg, body.ThisParameter);
for (var i = 0; i < implicitImpl.Parameters.Count; i++)
{
var p = iMethod.Parameters[i];
var newMethodParam = newMethod.Parameters[i];
worker.Emit(OpCodes.Ldarg, newMethodParam);
if (/*avoidGenericParam &&*/ p.ParameterType.ContainsGenericParameter)
{
worker.Emit(OpCodes.Box, implicitImpl.Parameters[i].ParameterType);
}
}
worker.Emit(implicitImpl.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, implicitImpl);
worker.Emit(OpCodes.Ret);
// Mark method reachable
if (implicitImpl.IsReachable)
{
newMethod.SetReachable(null);
}
return newMethod;
}
示例2: Clone
/// <summary>
/// Create a clone of the given method body
/// </summary>
public static MethodBody Clone(this MethodBody source, MethodDefinition target)
{
var result = new MethodBody(target) { InitLocals = source.InitLocals, MaxStackSize = source.MaxStackSize };
var worker = result.GetILProcessor();
foreach (var i in source.Instructions)
{
// Poor mans clone, but sufficient for our needs
var clone = Instruction.Create(OpCodes.Nop);
clone.OpCode = i.OpCode;
clone.Operand = i.Operand;
worker.Append(clone);
}
return result;
}
示例3: MethodBodyPatcher
public MethodBodyPatcher(string methodName, MethodDefinition method)
{
_methodName = methodName;
_methodBody = method.Body;
_processor = _methodBody.GetILProcessor();
_realBodyStart = _methodBody.Instructions.First();
_realBodyEnd = _methodBody.Instructions.Last();
_markStart1BeforeCreateArgumentsArray = _processor.Create(OpCodes.Nop);
_markStart2BeforeCreateMethodExecutionArgs = _processor.Create(OpCodes.Nop);
_markStart3BeforeOnEntryCall = _processor.Create(OpCodes.Nop);
_markStart4BeforeRealBodyStartExceptionHandler = _processor.Create(OpCodes.Nop);
_markEnd1NewRealBodyEnd = _processor.Create(OpCodes.Nop);
_markEnd2BeforeOnExitCall = _processor.Create(OpCodes.Nop);
_markRetNew = EndsWithThrow ? _processor.Create(OpCodes.Throw) : _processor.Create(OpCodes.Ret);
}
示例4: AddInstruction
public void AddInstruction()
{
var object_ref = new TypeReference ("System", "Object", null, null, false);
var method = new MethodDefinition ("foo", MethodAttributes.Static, object_ref);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
var first = il.Create (OpCodes.Nop);
var second = il.Create (OpCodes.Nop);
body.Instructions.Add (first);
body.Instructions.Add (second);
Assert.IsNull (first.Previous);
Assert.AreEqual (second, first.Next);
Assert.AreEqual (first, second.Previous);
Assert.IsNull (second.Next);
}
示例5: Inject
public static MethodDefinition Inject(ModuleDefinition mod, MethodDefinition mtd)
{
MethodDefinition ret = new MethodDefinition(mtd.Name, mtd.Attributes, mod.TypeSystem.Void);
ret.Attributes = mtd.Attributes;
ret.ImplAttributes = mtd.ImplAttributes;
if (mtd.IsPInvokeImpl)
{
ret.PInvokeInfo = mtd.PInvokeInfo;
bool has = false;
foreach (ModuleReference modRef in mod.ModuleReferences)
if (modRef.Name == ret.PInvokeInfo.Module.Name)
{
has = true;
ret.PInvokeInfo.Module = modRef;
break;
}
if (!has)
mod.ModuleReferences.Add(ret.PInvokeInfo.Module);
}
if (mtd.HasCustomAttributes)
{
foreach (CustomAttribute attr in mtd.CustomAttributes)
{
CustomAttribute nAttr = new CustomAttribute(ImportMethod(attr.Constructor, mod, ret, null), attr.GetBlob());
ret.CustomAttributes.Add(nAttr);
}
}
foreach (GenericParameter param in mtd.GenericParameters)
{
var p = new GenericParameter(param.Name, ret);
if (param.HasCustomAttributes)
{
foreach (CustomAttribute attr in param.CustomAttributes)
{
CustomAttribute nAttr = new CustomAttribute(ImportMethod(attr.Constructor, mod, ret, null), attr.GetBlob());
p.CustomAttributes.Add(nAttr);
}
}
ret.GenericParameters.Add(p);
}
ret.ReturnType = ImportType(mtd.ReturnType, mod, ret, null);
foreach (ParameterDefinition param in mtd.Parameters)
{
var p = new ParameterDefinition(param.Name, param.Attributes, ImportType(param.ParameterType, mod, ret, null));
if (param.HasCustomAttributes)
{
foreach (CustomAttribute attr in param.CustomAttributes)
{
CustomAttribute nAttr = new CustomAttribute(ImportMethod(attr.Constructor, mod, ret, null), attr.GetBlob());
p.CustomAttributes.Add(nAttr);
}
}
ret.Parameters.Add(p);
}
if (mtd.HasBody)
{
MethodBody old = mtd.Body;
MethodBody bdy = new MethodBody(ret);
bdy.MaxStackSize = old.MaxStackSize;
bdy.InitLocals = old.InitLocals;
ILProcessor psr = bdy.GetILProcessor();
foreach (VariableDefinition var in old.Variables)
bdy.Variables.Add(new VariableDefinition(var.Name, ImportType(var.VariableType, mod, ret, null)));
foreach (Instruction inst in old.Instructions)
{
switch (inst.OpCode.OperandType)
{
case OperandType.InlineArg:
case OperandType.ShortInlineArg:
if (inst.Operand == old.ThisParameter)
psr.Emit(inst.OpCode, bdy.ThisParameter);
else
{
int param = mtd.Parameters.IndexOf(inst.Operand as ParameterDefinition);
psr.Emit(inst.OpCode, ret.Parameters[param]);
}
break;
case OperandType.InlineVar:
case OperandType.ShortInlineVar:
int var = old.Variables.IndexOf(inst.Operand as VariableDefinition);
psr.Emit(inst.OpCode, bdy.Variables[var]);
break;
case OperandType.InlineField:
psr.Emit(inst.OpCode, ImportField(inst.Operand as FieldReference, mod, null));
break;
case OperandType.InlineMethod:
if (inst.Operand == mtd)
psr.Emit(inst.OpCode, ret);
else
psr.Emit(inst.OpCode, ImportMethod(inst.Operand as MethodReference, mod, ret, null));
break;
case OperandType.InlineType:
//.........这里部分代码省略.........
示例6: CloneMethodBody
private static MethodBody CloneMethodBody(MethodBody body, MethodDefinition source, MethodDefinition target)
{
var context = target.DeclaringType.Module;
var nb = new MethodBody(target)
{
MaxStackSize = body.MaxStackSize,
InitLocals = body.InitLocals,
CodeSize = body.CodeSize
};
var worker = nb.GetILProcessor();
foreach (var var in body.Variables)
nb.Variables.Add(new VariableDefinition(
var.Name, FixTypeImport(context, source, target, var.VariableType)));
foreach (var instr in body.Instructions)
{
var ni = new Instruction(instr.OpCode, OpCodes.Nop);
switch (instr.OpCode.OperandType)
{
case OperandType.InlineArg:
case OperandType.ShortInlineArg:
if (instr.Operand == body.ThisParameter)
ni.Operand = nb.ThisParameter;
else
{
var param = body.Method.Parameters.IndexOf((ParameterDefinition)instr.Operand);
ni.Operand = target.Parameters[param];
}
break;
case OperandType.InlineVar:
case OperandType.ShortInlineVar:
var var = body.Variables.IndexOf((VariableDefinition)instr.Operand);
ni.Operand = nb.Variables[var];
break;
case OperandType.InlineField:
ni.Operand = FixFieldImport(context, source, target, (FieldReference)instr.Operand);
break;
case OperandType.InlineMethod:
ni.Operand = FixMethodImport(context, source, target, (MethodReference)instr.Operand);
break;
case OperandType.InlineType:
ni.Operand = FixTypeImport(context, source, target, (TypeReference)instr.Operand);
break;
case OperandType.InlineTok:
if ((instr.Operand) is TypeReference)
ni.Operand = FixTypeImport(context, source, target, (TypeReference)instr.Operand);
else if ((instr.Operand) is FieldReference)
ni.Operand = FixFieldImport(context, source, target, (FieldReference)instr.Operand);
else if ((instr.Operand) is MethodReference)
ni.Operand = FixMethodImport(context, source, target, (MethodReference)instr.Operand);
break;
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
case OperandType.InlineSwitch:
break;
default:
ni.Operand = instr.Operand;
break;
}
worker.Append(ni);
}
for (var i = 0; i < body.Instructions.Count; i++)
{
var instr = nb.Instructions[i];
var oldi = body.Instructions[i];
switch (instr.OpCode.OperandType)
{
case OperandType.InlineSwitch:
{
var olds = (Instruction[])oldi.Operand;
var targets = new Instruction[olds.Length];
for (var j = 0; j < targets.Length; j++)
targets[j] = GetInstruction(body, nb, olds[j]);
instr.Operand = targets;
}
break;
case OperandType.InlineBrTarget:
case OperandType.ShortInlineBrTarget:
instr.Operand = GetInstruction(body, nb, (Instruction)oldi.Operand);
break;
}
}
foreach (var eh in body.ExceptionHandlers)
{
var neh = new ExceptionHandler(eh.HandlerType)
{
TryStart = GetInstruction(body, nb, eh.TryStart),
TryEnd = GetInstruction(body, nb, eh.TryEnd),
HandlerStart = GetInstruction(body, nb, eh.HandlerStart),
HandlerEnd = GetInstruction(body, nb, eh.HandlerEnd)
};
//.........这里部分代码省略.........
示例7: UnattachedMethodBody
public void UnattachedMethodBody()
{
var system_void = typeof (void).ToDefinition ();
var method = new MethodDefinition ("NewMethod", MethodAttributes.Assembly | MethodAttributes.Static, system_void);
var body = new MethodBody (method);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ret);
method.Body = body;
Assert.AreEqual (body, method.Body);
}
示例8: Execute
//.........这里部分代码省略.........
Log(2, " Resource: {0}... ", resource.Name);
string classname;
if (!resource.IsXaml(out classname))
{
LogLine(2, "skipped.");
continue;
}
TypeDefinition typeDef = module.GetType(classname);
if (typeDef == null)
{
LogLine(2, "no type found... skipped.");
continue;
}
var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
if (initComp == null)
{
LogLine(2, "no InitializeComponent found... skipped.");
continue;
}
if (typeDef.Methods.FirstOrDefault(md => md.Name == "InitCompRuntime") != null)
{
LogLine(2, "InitCompRuntime already exists... skipped");
continue;
}
LogLine(2, "");
Log(2, " Duplicating {0}.InitializeComponent () into {0}.InitCompRuntime ... ", typeDef.Name);
var initCompRuntime = new MethodDefinition("InitCompRuntime", initComp.Attributes, initComp.ReturnType);
initCompRuntime.Body = initComp.Body;
typeDef.Methods.Add(initCompRuntime);
LogLine(2, "done.");
// IL_0000: ldarg.0
// IL_0001: callvirt instance void class [Xamarin.Forms.Core]Xamarin.Forms.ContentPage::'.ctor'()
//
// IL_0006: nop
// IL_0007: ldarg.1
// IL_0008: brfalse IL_0018
//
// IL_000d: ldarg.0
// IL_000e: callvirt instance void class Xamarin.Forms.Xaml.XamlcTests.MyPage::InitializeComponent()
// IL_0013: br IL_001e
//
// IL_0018: ldarg.0
// IL_0019: callvirt instance void class Xamarin.Forms.Xaml.XamlcTests.MyPage::InitCompRuntime()
// IL_001e: ret
var altCtor =
typeDef.Methods.Where(
md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType == module.TypeSystem.Boolean)
.FirstOrDefault();
if (altCtor != null)
Log(2, " Replacing body of {0}.{0} (bool {1}) ... ", typeDef.Name, altCtor.Parameters[0].Name);
else
{
Log(2, " Adding {0}.{0} (bool useCompiledXaml) ... ", typeDef.Name);
altCtor = new MethodDefinition(".ctor",
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName, module.TypeSystem.Void);
altCtor.Parameters.Add(new ParameterDefinition("useCompiledXaml", ParameterAttributes.None,
module.TypeSystem.Boolean));
}
var body = new MethodBody(altCtor);
var il = body.GetILProcessor();
var br2 = Instruction.Create(OpCodes.Ldarg_0);
var ret = Instruction.Create(OpCodes.Ret);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt,
module.Import(typeDef.BaseType.Resolve().GetConstructors().First(c => c.HasParameters == false)));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Brfalse, br2);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, initComp);
il.Emit(OpCodes.Br, ret);
il.Append(br2);
il.Emit(OpCodes.Callvirt, initCompRuntime);
il.Append(ret);
altCtor.Body = body;
if (!typeDef.Methods.Contains(altCtor))
typeDef.Methods.Add(altCtor);
LogLine(2, "done.");
}
LogLine(2, "");
}
Log(1, "Writing the assembly... ");
assemblyDefinition.Write(Assembly, new WriterParameters
{
WriteSymbols = DebugSymbols
});
LogLine(1, "done.");
return true;
}
示例9: InsertInvalidIl
/// <summary>
/// Inserts the invalid il.
/// </summary>
/// <param name="methodBody">The method body.</param>
private static void InsertInvalidIl(MethodBody methodBody)
{
//Get the instructions and cil worker
var instructions = methodBody.Instructions;
if (instructions.Count <= 0)
return; //We can only do this if we have instructions to work with
ILProcessor il = methodBody.GetILProcessor();
//First create an invalid il instruction
OpCode fakeOpCode = CreateInvalidOpCode();
Instruction invalidIlInstr1 = il.Create(fakeOpCode);
Instruction invalidIlInstr2 = il.Create(fakeOpCode);
Instruction originalFirst = instructions[0];
//Insert invalid il at the start
il.InsertBefore(originalFirst, invalidIlInstr1);
il.InsertBefore(invalidIlInstr1, invalidIlInstr2);
//Create the branch statement
Instruction branchStatement = il.Create(OpCodes.Br_S, originalFirst);
//Add the branch to the start
il.InsertBefore(invalidIlInstr2, branchStatement);
//Readjust the offsets
il.AdjustOffsets(methodBody, 4);
}
示例10: FoldAndReplace
private static void FoldAndReplace(
ref Dictionary<KeyValuePair<int, int>, ExInstruction> markings,
ref MethodBody body)
{
var instrList = body.Instructions;
var foldedBody = new Collection<Instruction>();
foreach(var marking in markings)
{
for(var i = 0;i < instrList.Count;i++)
{
if(marking.Key.Key == i)
{
for (var x = 0; x < marking.Key.Value +1; x++)
instrList.RemoveAt(marking.Key.Key -2);
switch(marking.Value.OpCode.Code)
{
case Code.Ldc_I4:
instrList.Insert(marking.Key.Key -3,
body.GetILProcessor().Create(OpCodes.Ldc_I4, (int)marking.Value.Value));
break;
case Code.Ldc_I8:
instrList.Insert(marking.Key.Key -3,
body.GetILProcessor().Create(OpCodes.Ldc_I8, (long)marking.Value.Value));
break;
}
break;
}
}
}
body.Instructions.Clear();
//body.SimplifyMacros();
var ilProc = body.GetILProcessor();
foreach (var instr in instrList)
ilProc.Append(instr);
//body.OptimizeMacros();//it can't resolve the tokens from rocks
}
示例11: ProcessInstructions
/// <summary>
/// Processes the instructions replacing all strings being loaded with an encrypted version.
/// </summary>
/// <param name="assemblyDef">The assembly definition.</param>
/// <param name="body">The body.</param>
/// <param name="decryptMethod">The decrypt method.</param>
private void ProcessInstructions(AssemblyDefinition assemblyDef, MethodBody body, MethodReference decryptMethod)
{
var instructions = body.Instructions;
var il = body.GetILProcessor();
List<Instruction> instructionsToExpand = new List<Instruction>();
List<int> offsets = new List<int>();
foreach (Instruction instruction in instructions)
{
//Find the call statement
switch (instruction.OpCode.Name)
{
case "ldstr":
//We've found a string load message - we need to replace this instruction
if (instruction.Operand is string) //Only do the direct strings for now
instructionsToExpand.Add(instruction);
break;
}
}
//Fix each ldstr instruction found
foreach (Instruction instruction in instructionsToExpand)
{
//What we do is replace the ldstr "bla" with:
//ldstr bytearray encrypted_array
//ldc.i4 random_integer
//call string class Decrypt(string, int32)
//First get the original value
string originalValue = instruction.Operand.ToString();
offsets.Add(instruction.Offset);
//Secondly generate a random integer as a salt
int salt = random.Next(5000, 10000);
//Now we need to work out what the encrypted value is and set the operand
OutputHelper.WriteLine("Encrypting string \"{0}\"", originalValue);
string byteArray = EncryptString(originalValue, salt);
Instruction loadString = il.Create(OpCodes.Ldstr, byteArray);
il.Replace(instruction, loadString);
//Now load the salt
Instruction loadSalt = il.Create(OpCodes.Ldc_I4, salt);
il.InsertAfter(loadString, loadSalt);
//Process the decryption
Instruction call = il.Create(OpCodes.Call, decryptMethod);
il.InsertAfter(loadSalt, call);
}
//Unfortunately one thing Mono.Cecil doesn't do is adjust instruction offsets for branch statements
//and exception handling start points. We need to fix these manually
if (offsets.Count == 0)
return;
//Do the adjustments
il.AdjustOffsets(body, offsets, 6 + assemblyDef.GetAddressSize());
}
示例12: GenerateDelegateMethod
private MethodBody GenerateDelegateMethod(MethodDefinition method, Class declaringClass)
{
// Delegate type
var delegateType = corlib.MainModule.GetType(typeof(Delegate).FullName);
// Delegate fields
var targetField = delegateType.Fields.First(x => x.Name == "_target");
var methodPtrField = delegateType.Fields.First(x => x.Name == "_methodPtr");
var methodPtrAuxField = delegateType.Fields.First(x => x.Name == "_methodPtrAux");
var body = new MethodBody(method);
var il = body.GetILProcessor();
if (method.Name == ".ctor")
{
// Mark
//GenerateMulticastInvokeThunk(declaringClass);
// Two main cases:
// - Instance method:
// this._methodPtr = fnptr;
// this._target = target;
// Result: this._methodPtr(this._target, arg1, ..) will directly work
// - Static method:
// this._target = this;
// this._methodPtrAux = fnptr;
// this._methodPtr = (delegate, arg1, ...) => { delegate->_methodPtrAux(arg1, ...); }
// Result: this._methodPtr(this._target, arg1, ...) will call thunk,
// which will call fnptr (from this._target._methodPtr) without the first argument
var target = Instruction.Create(OpCodes.Ldarg_0);
// if (target == null)
// {
il.Append(Instruction.Create(OpCodes.Ldarg, method.Parameters[0]));
il.Append(Instruction.Create(OpCodes.Brtrue, target));
// Generate thunk (for now, done using direct LLVM, not sure weither LLVM or IL is better)
// this._methodPtr = (delegate, arg1, ...) => { delegate->_methodPtrAux(arg1, ...); }
var invokeMethodHelper = GenerateStaticInvokeThunk(declaringClass);
// Fake Nop to push this thunk on stack (TODO: Better way to do this? i.e. store it in some static field?)
il.Append(Instruction.Create(OpCodes.Ldarg_0));
var loadFunctionPointerInstruction = Instruction.Create(OpCodes.Nop);
InstructionActions.Add(loadFunctionPointerInstruction, (stack) =>
{
// Push the generated method pointer on the stack
stack.Add(new StackValue(StackValueType.NativeInt, intPtr,
LLVM.BuildPointerCast(builder, invokeMethodHelper, intPtrLLVM, string.Empty)));
});
il.Append(loadFunctionPointerInstruction);
il.Append(Instruction.Create(OpCodes.Stfld, methodPtrField));
// this._methodPtrAux = method;
il.Append(Instruction.Create(OpCodes.Ldarg_0));
il.Append(Instruction.Create(OpCodes.Ldarg, method.Parameters[1]));
il.Append(Instruction.Create(OpCodes.Stfld, methodPtrAuxField));
// this._target = this;
il.Append(Instruction.Create(OpCodes.Ldarg_0));
il.Append(Instruction.Create(OpCodes.Ldarg_0));
il.Append(Instruction.Create(OpCodes.Stfld, targetField));
// return;
// }
il.Append(Instruction.Create(OpCodes.Ret));
// this._target = target;
il.Append(target);
il.Append(Instruction.Create(OpCodes.Ldarg, method.Parameters[0]));
il.Append(Instruction.Create(OpCodes.Stfld, targetField));
// this._methodPtr = method;
il.Append(Instruction.Create(OpCodes.Ldarg_0));
il.Append(Instruction.Create(OpCodes.Ldarg, method.Parameters[1]));
il.Append(Instruction.Create(OpCodes.Stfld, methodPtrField));
// return;
il.Append(Instruction.Create(OpCodes.Ret));
}
else if (method.Name == "GetMulticastDispatchMethod")
{
var invokeMethodHelper = GenerateMulticastInvokeThunk(declaringClass);
var loadFunctionPointerInstruction = Instruction.Create(OpCodes.Nop);
InstructionActions.Add(loadFunctionPointerInstruction, (stack) =>
{
// Push the generated method pointer on the stack
stack.Add(new StackValue(StackValueType.NativeInt, intPtr,
LLVM.BuildPointerCast(builder, invokeMethodHelper, intPtrLLVM, string.Empty)));
});
il.Append(loadFunctionPointerInstruction);
il.Append(Instruction.Create(OpCodes.Ret));
}
else if (method.Name == "Invoke")
{
// For now, generate IL
// Note that we could probably optimize at callsite too,
// but probably not necessary if LLVM and sealed class are optimized/inlined well enough
//.........这里部分代码省略.........
示例13: ProcessType
public override void ProcessType(TypeDefinition type)
{
#if XAMARIN_NO_TLS
return;
#else
if (!type.Is (Namespaces.ObjCRuntime, "Runtime"))
return;
MethodDefinition callbackMethod = null;
foreach (var m in type.Methods) {
if (!m.IsStatic || m.HasParameters)
continue;
if (m.Name.Equals ("TlsProviderFactoryCallback", StringComparison.Ordinal)) {
callbackMethod = m;
break;
}
}
if (callbackMethod == null)
throw new Exception ("Could not set the default TlsProvider");
var providerCtor = FindProviderConstructor (type.Module);
if (providerCtor == null)
return;
// re-write TlsProviderFactoryCallback()
var body = new MethodBody (callbackMethod);
var il = body.GetILProcessor ();
if (providerCtor != null)
il.Emit (OpCodes.Newobj, providerCtor);
else
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Ret);
callbackMethod.Body = body;
#endif
}
示例14: ProcessType
public override void ProcessType(TypeDefinition type)
{
if (!type.Is ("System.Net.Http", "HttpClient"))
return;
MethodDefinition default_ctor = null;
MethodDefinition full_ctor = null;
foreach (var m in type.Methods) {
if (m.IsStatic || !m.IsConstructor)
continue;
if (!m.HasParameters) {
default_ctor = m;
} else if (m.Parameters.Count == 2) {
full_ctor = m;
}
}
if (default_ctor == null || full_ctor == null)
throw new Exception ("Could not set the default HttpMessageHandler");
var handler = RuntimeOptions.GetHttpMessageHandler (Options.RuntimeOptions, type.Module);
MethodDefinition handler_ctor = null;
foreach (var m in handler.Methods) {
if (m.IsStatic || !m.IsConstructor || m.HasParameters)
continue;
handler_ctor = m;
break;
}
// re-write default ctor
var body = new MethodBody (default_ctor);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Newobj, handler_ctor);
il.Emit (OpCodes.Ldc_I4_1);
il.Emit (OpCodes.Call, full_ctor);
il.Emit (OpCodes.Ret);
default_ctor.Body = body;
}
示例15: VisitMethodBody
public override void VisitMethodBody(MethodBody body)
{
_body = body;
_il = body.GetILProcessor();
}