public void CompileMethod(MethodContext context) { MethodInfo methodInfo = context.MethodInfo; PerfManager.Instance.WriteLine("> JIT CodeInjector is called on method [{0}]", methodInfo.Name); if (methodInfo.Name == "NetAsmAdd") { // Output the native code with the C code (see TestStaticCodeInjection class) context.SetOutputNativeCode(new byte[] { 0x8b, 0x44, 0x24, 0x04, 0x03, 0xc2, 0xc2, 0x04, 0x00 }); } else if (methodInfo.Name == "NetAsmAddFromDll") { CodeRef referenceToDllFunction = CodeRef.BindToDllFunction("NetAsmDemoCLib.dll", "NetAsmAddInC"); // Set the native code to use the DLL function context.SetOutputNativeCode(referenceToDllFunction); } else if (methodInfo.Name == "NetAsmIndirectCaller") { // Demonstrate how to call a clr method from a native method. MethodInfo info = typeof(TestDynamicCodeInjection).GetMethod("ManagedMethodCalledByNetAsm"); // Get the pointer to the method ManagedMethodCalledByNetAsm IntPtr pointerToFunction = info.MethodHandle.GetFunctionPointer(); // Generate an execution block with the template code nativeIndirectCall CodeRef codeRef = context.AllocExecutionBlock(nativeIndirectCall); // Calculate relative JMP address IntPtr jmpRelativeAddress = new IntPtr(pointerToFunction.ToInt64() - (codeRef.Pointer.ToInt64() + nativeIndirectCall.Length)); // Write the relative JMP address just after the JMP opcode (0xE9) Marshal.WriteIntPtr(codeRef.Pointer, 1, jmpRelativeAddress); // Set output native code context.SetOutputNativeCode(codeRef); } }
public void CompileMethod(MethodContext context) { // Print information about the method being compiled using reflection classes. MethodInfo methodInfo = context.MethodInfo; PerfManager.Instance.WriteLine("> JIT NopCodeInjector is called on method [{0}] with a StackSize {1}", methodInfo.Name, context.StackSize); // Generate a native code with a Ret + StackSize of the method CodeRef nativeCodeRef; if (context.StackSize > 0) { // If there is a stack, then, generate the RET + Stacksize opcode nativeCodeRef = context.AllocExecutionBlock(ReturnWithStackSize); Marshal.WriteInt16(nativeCodeRef.Pointer, 1, (short)context.StackSize); } else { // If there is no stack used, then RET nativeCodeRef = context.AllocExecutionBlock(ReturnWithNoStack); } // Inform NetAsm the native code to use for the method context.SetOutputNativeCode(nativeCodeRef); }