本文整理汇总了C#中Mono.Cecil.Cil.ILProcessor.InsertBefore方法的典型用法代码示例。如果您正苦于以下问题:C# ILProcessor.InsertBefore方法的具体用法?C# ILProcessor.InsertBefore怎么用?C# ILProcessor.InsertBefore使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mono.Cecil.Cil.ILProcessor
的用法示例。
在下文中一共展示了ILProcessor.InsertBefore方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InjectWriteIl
static void InjectWriteIl(List<Instruction> writeTimeIl, ILProcessor ilProcessor, Instruction beforeThis)
{
foreach (var instruction in writeTimeIl)
{
ilProcessor.InsertBefore(beforeThis, instruction);
}
ilProcessor.InsertBefore(beforeThis, Instruction.Create(OpCodes.Endfinally));
}
示例2: InterceptMethod
private void InterceptMethod(ILProcessor processor, TypeReference typeReference, Instruction instruction, string name)
{
var typeDefinition = typeReference.Resolve();
var attributeConstructor = typeDefinition.Methods.First(x => x.Name == ".ctor");
var attributeMethod = typeDefinition.Methods.First(x => x.Name == name);
processor.InsertBefore(instruction, processor.Create(OpCodes.Newobj, attributeConstructor));
processor.InsertBefore(instruction, processor.Create(OpCodes.Call, _getCurrentMethod));
processor.InsertBefore(instruction, processor.Create(OpCodes.Call, attributeMethod));
}
示例3: ProcessPredicateCreationPattern
private void ProcessPredicateCreationPattern(ILProcessor il, Instruction queryInvocation)
{
MethodReference predicateMethod = GetMethodReferenceFromInlinePredicatePattern(queryInvocation);
Instruction ldftn = GetNthPrevious(queryInvocation, 2);
il.InsertBefore(ldftn, il.Create(OpCodes.Dup));
il.InsertBefore(queryInvocation, il.Create(OpCodes.Ldtoken, predicateMethod));
// At this point the stack is like this:
// runtime method handle, delegate reference, target object, ObjectContainer
il.Replace(queryInvocation,
il.Create(OpCodes.Call,
InstantiateGenericMethod(
_NativeQueryHandler_ExecuteInstrumentedDelegateQuery,
GetQueryCallExtent(queryInvocation))));
}
示例4: InjectNewWriter
void InjectNewWriter(MethodDefinition sendData, ILProcessor processor, out VariableDefinition mswriter, out OpCode binaryWriter)
{
var buffer = sendData.Body.Instructions.First(
x => x.OpCode == OpCodes.Ldsfld
&& (x.Operand as FieldReference).Name == "buffer"
);
while (!(buffer.Next.OpCode == OpCodes.Callvirt
&& (buffer.Next.Operand as MethodReference).Name == "set_Position"))
{
processor.Remove(buffer.Next);
}
processor.Remove(buffer.Next);
//processor.Remove(buffer);
//VariableDefinition mswriter;
sendData.Body.Variables.Add(mswriter = new VariableDefinition("mswriter",
this.SourceDefinition.MainModule.Import(typeof(MemoryStream))
));
var res = processor.InsertBefore(buffer.Previous.Previous,
new
{
OpCodes.Newobj,
Operand = this.SourceDefinition.MainModule.Import(typeof(MemoryStream)
.GetConstructors()
.Single(x => x.GetParameters().Count() == 0)
)
},
new { OpCodes.Stloc, Operand = mswriter },
new { OpCodes.Ldloc, Operand = mswriter }
);
buffer.Previous.Previous.ReplaceTransfer(res[0], sendData);
processor.Remove(buffer.Previous);
processor.Remove(buffer.Previous);
buffer.OpCode = OpCodes.Newobj;
buffer.Operand = this.SourceDefinition.MainModule.Import(typeof(BinaryWriter)
.GetConstructors()
.Single(x => x.GetParameters().Count() == 1)
);
if (buffer.Next.OpCode != OpCodes.Ldloc_1)
{
throw new NotSupportedException("Expected Ldloc_1");
}
/*var*/
binaryWriter = buffer.Next.OpCode;
processor.InsertAfter(buffer,
new { OpCodes.Stloc_1 }
);
}
示例5: ProcessCachedStaticFieldPattern
private void ProcessCachedStaticFieldPattern(ILProcessor il, Instruction queryInvocation)
{
MethodReference predicateMethod = GetMethodReferenceFromStaticFieldPattern(queryInvocation);
il.InsertBefore(queryInvocation, il.Create(OpCodes.Ldtoken, predicateMethod));
// At this point the stack is like this:
// runtime method handle, delegate reference, ObjectContainer
il.Replace(queryInvocation,
il.Create(OpCodes.Call,
InstantiateGenericMethod(
_NativeQueryHandler_ExecuteInstrumentedStaticDelegateQuery,
GetQueryCallExtent(queryInvocation))));
}
示例6: HandleOfProperty
void HandleOfProperty(Instruction instruction, ILProcessor ilProcessor, Func<PropertyDefinition, MethodDefinition> func)
{
var propertyNameInstruction = instruction.Previous;
var propertyName = GetLdString(propertyNameInstruction);
var typeNameInstruction = propertyNameInstruction.Previous;
var typeName = GetLdString(typeNameInstruction);
var assemblyNameInstruction = typeNameInstruction.Previous;
var assemblyName = GetLdString(assemblyNameInstruction);
var typeDefinition = GetTypeDefinition(assemblyName, typeName);
var property = typeDefinition.Properties.FirstOrDefault(x => x.Name == propertyName);
if (property == null)
{
throw new WeavingException($"Could not find property named '{propertyName}'.")
{
SequencePoint = instruction.SequencePoint
};
}
var methodDefinition = func(property);
if (methodDefinition == null)
{
throw new WeavingException($"Could not find property named '{propertyName}'.")
{
SequencePoint = instruction.SequencePoint
};
}
ilProcessor.Remove(typeNameInstruction);
ilProcessor.Remove(propertyNameInstruction);
assemblyNameInstruction.OpCode = OpCodes.Ldtoken;
assemblyNameInstruction.Operand = methodDefinition;
if (typeDefinition.HasGenericParameters)
{
var typeReference = ModuleDefinition.ImportReference(typeDefinition);
ilProcessor.InsertBefore(instruction, Instruction.Create(OpCodes.Ldtoken, typeReference));
instruction.Operand = getMethodFromHandleGeneric;
}
else
{
instruction.Operand = getMethodFromHandle;
}
ilProcessor.InsertAfter(instruction, Instruction.Create(OpCodes.Castclass, methodInfoType));
}
示例7: HandleOfField
void HandleOfField(Instruction instruction, ILProcessor ilProcessor)
{
//Info.OfField("AssemblyToProcess","MethodClass","Field");
var fieldNameInstruction = instruction.Previous;
var fieldName = GetLdString(fieldNameInstruction);
var typeNameInstruction = fieldNameInstruction.Previous;
var typeName = GetLdString(typeNameInstruction);
var assemblyNameInstruction = typeNameInstruction.Previous;
var assemblyName = GetLdString(assemblyNameInstruction);
var typeDefinition = GetTypeDefinition(assemblyName, typeName);
var fieldDefinition = typeDefinition.Fields.FirstOrDefault(x => x.Name == fieldName);
if (fieldDefinition == null)
{
throw new WeavingException($"Could not find field named '{fieldName}'.")
{
SequencePoint = instruction.SequencePoint
};
}
var fieldReference = ModuleDefinition.ImportReference(fieldDefinition);
ilProcessor.Remove(typeNameInstruction);
ilProcessor.Remove(fieldNameInstruction);
assemblyNameInstruction.OpCode = OpCodes.Ldtoken;
assemblyNameInstruction.Operand = fieldReference;
if (typeDefinition.HasGenericParameters)
{
var typeReference = ModuleDefinition.ImportReference(typeDefinition);
ilProcessor.InsertBefore(instruction, Instruction.Create(OpCodes.Ldtoken,typeReference));
instruction.Operand = getFieldFromHandleGeneric;
}
else
{
instruction.Operand = getFieldFromHandle;
}
}
示例8: OnInvocation
//.........这里部分代码省略.........
// if(Verbosity >= 6)
// Console.WriteLine("Resolved non-specific generic method: " + mr.FullName);
// if(Verbosity >= 8) Console.WriteLine("RESOLVED TYPE: " + genericTypeParameter);
// var typeModuleDefinition = ModuleDefinition.ReadModule(type.Module.Assembly.Location);
// var typeDefinition = typeModuleDefinition.Types.Where(td => td.FullName == genericParameter).FirstOrDefault();
// if(typeDefinition != null && Verbosity >= 5)
// {
// Console.WriteLine("Resolved typeDefinition: " + typeDefinition);
// }
// else
// {
// Console.WriteLine("Failed to resolve typeDefinition: " + type.FullName);
//// foreach(var td in ModuleDefinition.ReadModule(type.Module.Assembly.Location).Types)
//// {
//// Console.WriteLine(" ... " + td.FullName);
//// }
// continue;
// }
// method.Module.Import(type); // try removing this
// IMetadataScope scope = method.Module;
// var typeRef = new TypeReference(type.Namespace, type.Name, typeModuleDefinition, scope, type.IsValueType);
// Console.WriteLine("TypeRef: "+ typeRef);
// method.Module.Import(type);
var replacementMethodImported = method.Module.Import (replacementMethod);
// IL_0000: ldtoken Rewriter.TestClass
if (genericTypeParameter != null) {
processor.InsertBefore (i, processor.Create (OpCodes.Ldtoken, method.Module.Import (genericTypeParameter)));
} else {
processor.InsertBefore (i, processor.Create (OpCodes.Ldtoken, method.Module.Import (genericTypeParameterDefinition)));
}
// IL_0005: call class [mscorlib]System.Type class
// [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
var gtfh = typeof(Type).GetMethod ("GetTypeFromHandle");
MethodReference gtfhRef = method.Module.Import (gtfh, mr);
processor.InsertBefore (i, processor.Create (OpCodes.Call, gtfhRef));
// IL_000a: call void class Rewriter.TestClass::TestMethod(class [mscorlib]System.Type)
var callMethod = processor.Create (i.OpCode, replacementMethodImported);
processor.InsertAfter (i, callMethod);
#region Cast the result, if it exists
if (mr.ReturnType.FullName != "System.Void" && !noCast) {
string castAssembly;
string castType;
if (genericTypeParameter != null) {
castAssembly = genericTypeParameter.Assembly.GetName (false).Name;
castType = "[" + castAssembly + "]" + genericTypeParameter.FullName;
} else if (genericTypeParameterDefinition != null) {
castAssembly = "";
castType = genericTypeParameterDefinition.ToString ();
// var resolvedGTPD = genericTypeParameterDefinition.Resolve();
// resolvedGTPD.FullName
} else {
castType = "???";
示例9: MoveInstructions
private static void MoveInstructions(Instruction start, Instruction end, Instruction insertionPoint, ILProcessor il)
{
IList<Instruction> toBeMoved = new List<Instruction>();
Instruction boundary = end.Next;
while(start != boundary)
{
toBeMoved.Add(start);
Instruction next = start.Next;
il.Remove(start);
start = next;
}
foreach (Instruction instruction in toBeMoved)
{
il.InsertBefore(insertionPoint, instruction);
}
}
示例10: ReplaceFixedArrayStatement
private void ReplaceFixedArrayStatement(MethodDefinition method, ILProcessor ilProcessor, Instruction fixedtoPatch)
{
var paramT = ((GenericInstanceMethod)fixedtoPatch.Operand).GenericArguments[0];
// Preparing locals
// local(0) T*
method.Body.Variables.Add(new VariableDefinition("pin", new PinnedType(new ByReferenceType(paramT))));
int index = method.Body.Variables.Count - 1;
Instruction ldlocFixed;
Instruction stlocFixed;
switch (index)
{
case 0:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_0);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_0);
break;
case 1:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_1);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_1);
break;
case 2:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_2);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_2);
break;
case 3:
stlocFixed = ilProcessor.Create(OpCodes.Stloc_3);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc_3);
break;
default:
stlocFixed = ilProcessor.Create(OpCodes.Stloc, index);
ldlocFixed = ilProcessor.Create(OpCodes.Ldloc, index);
break;
}
var instructionLdci40 = ilProcessor.Create(OpCodes.Ldc_I4_0);
ilProcessor.InsertBefore(fixedtoPatch, instructionLdci40);
var instructionLdElema = ilProcessor.Create(OpCodes.Ldelema, paramT);
ilProcessor.InsertBefore(fixedtoPatch, instructionLdElema);
ilProcessor.InsertBefore(fixedtoPatch, stlocFixed);
ilProcessor.Replace(fixedtoPatch, ldlocFixed);
}
示例11: InjectInstructionsBefore
public static void InjectInstructionsBefore(ILProcessor p, Instruction before, IEnumerable<Instruction> commands)
{
var instructions = commands.ToList();
/*
* following stuff is from http://eatplayhate.wordpress.com/2010/07/18/mono-cecil-vs-obfuscation-fight/
* and should redirect jumps?!
*/
var method = p.Body.Method;
var oldTarget = before;
var newTarget = instructions[0];
var isNewCode = false;
for (int j = 0; j < method.Body.Instructions.Count; j++)
{
var inst = method.Body.Instructions[j];
if (inst == newTarget)
{
isNewCode = true;
}
if (inst == before)
{
isNewCode = false;
}
if (!isNewCode)
{
if ((inst.OpCode.FlowControl == FlowControl.Branch ||
inst.OpCode.FlowControl == FlowControl.Cond_Branch) &&
inst.Operand == oldTarget)
inst.Operand = newTarget;
}
}
foreach (ExceptionHandler v in method.Body.ExceptionHandlers)
{
if (v.FilterStart == oldTarget)
v.FilterStart = newTarget;
if (v.HandlerEnd == oldTarget)
v.HandlerEnd = newTarget;
if (v.HandlerStart == oldTarget)
v.HandlerStart = newTarget;
if (v.TryEnd == oldTarget)
v.TryEnd = newTarget;
if (v.TryStart == oldTarget)
v.TryStart = newTarget;
}
//update: We now insert after changing, so trgs in the currently inserted code are not changed
foreach (var instruction in instructions)
{
p.InsertBefore(before, instruction);
}
}
示例12: Instrument
private static void Instrument (
AssemblyDefinition assembly,
TypeDefinition type,
Instruction instruction,
MethodReference countReference,
MethodDefinition method,
ILProcessor worker,
string lastLine,
InstrumentConfig config,
TextWriter writer,
ref int instrumentIndex)
{
//if the previous instruction is a Prefix instruction then this instruction MUST go with it.
//we cannot put an instruction between the two.
if (instruction.Previous != null && instruction.Previous.OpCode.OpCodeType == OpCodeType.Prefix)
return;
if (config.HasOffset (method.FullName, instruction.Offset))
return;
if (lastLine != null && config.HasLine (method.FullName, lastLine)) {
return;
}
var lineNumStart = -1;
var lineNumEnd = -1;
if (instruction.SequencePoint != null) {
lineNumStart = instruction.SequencePoint.StartLine;
lineNumEnd = instruction.SequencePoint.EndLine;
}
var parentTypeRef = type;
while (parentTypeRef.DeclaringType != null)
parentTypeRef = parentTypeRef.DeclaringType;
var line = string.Join ("\t",
assembly.Name, //0
parentTypeRef.FullName,//1
method.FullName, //2
lineNumStart, //3
lineNumEnd, //4
instruction.Offset, //5
instruction.ToString ().Replace ("\n", " "), //6
instruction.SequencePoint?.Document.Url); //7
writer.WriteLine (line);
var pathParamLoadInstruction = worker.Create (OpCodes.Ldstr, config.HitsPathPrefix);
var lineParamLoadInstruction = worker.Create (OpCodes.Ldc_I4, instrumentIndex);
var registerInstruction = worker.Create (OpCodes.Call, countReference);
//inserting method before instruction because after will not happen after a method Ret instruction
worker.InsertBefore (instruction, pathParamLoadInstruction);
worker.InsertAfter (pathParamLoadInstruction, lineParamLoadInstruction);
worker.InsertAfter (lineParamLoadInstruction, registerInstruction);
++instrumentIndex;
//change try/finally etc to point to our first instruction if they referenced the one we inserted before
foreach (var handler in method.Body.ExceptionHandlers) {
if (handler.FilterStart == instruction)
handler.FilterStart = pathParamLoadInstruction;
if (handler.TryStart == instruction)
handler.TryStart = pathParamLoadInstruction;
if (handler.TryEnd == instruction)
handler.TryEnd = pathParamLoadInstruction;
if (handler.HandlerStart == instruction)
handler.HandlerStart = pathParamLoadInstruction;
if (handler.HandlerEnd == instruction)
handler.HandlerEnd = pathParamLoadInstruction;
}
//change instructions with a target instruction if they referenced the one we inserted before to be our first instruction
foreach (var iteratedInstruction in method.Body.Instructions) {
var operand = iteratedInstruction.Operand;
if (operand == instruction) {
iteratedInstruction.Operand = pathParamLoadInstruction;
continue;
}
if (!(operand is Instruction []))
continue;
var operands = (Instruction [])operand;
for (var i = 0; i < operands.Length; ++i) {
if (operands [i] == instruction)
operands [i] = pathParamLoadInstruction;
}
}
}
示例13: Append
static void Append (ILProcessor il, IEnumerable<Instruction> instructions)
{
var method_instructions = il.Body.Instructions;
var last = method_instructions [method_instructions.Count - 1];
foreach (var instruction in instructions)
il.InsertBefore (last, instruction);
}
示例14: MethodPrepend
public static void MethodPrepend(ILProcessor il, Instruction first, IEnumerable<Instruction> instructions)
{
foreach (var instr in instructions) il.InsertBefore(first, instr);
}
示例15: InsertBefore
/// <summary>
/// Inserts the given instructions before the current (this) instruction using the given processor
/// </summary>
public static void InsertBefore(this Instruction instruction, ILProcessor processor, IEnumerable<Instruction> instructions)
{
foreach (var newInstruction in instructions)
{
processor.InsertBefore(instruction, newInstruction);
}
}