Guest User

Untitled

a guest
Dec 11th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1.     private void BindNative(IntPtr functionPtr, String name, String prototype)
  2.     {
  3.         /*
  4.             * Manual implementation of a __cdecl function calling a __fastcall function.
  5.             * 1. Allocate Executable memory.
  6.             * 2. Write the function.
  7.             * 3. Call the function.
  8.             * 4. Release allocated memory.
  9.             * TODO: Improve this to a more static function.
  10.  
  11.             * push, prototype string pointer
  12.             * mov edx, name string pointer
  13.             * mov ecx, function pointer
  14.             * call, BindNative pointer; Remember to calculate the relative offset
  15.             * retn
  16.             */
  17.         var code = new Byte[21];
  18.  
  19.         using (var writer = new AssemblyWriter(new MemoryStream(code)))
  20.         {
  21.             var codePtr = Kernel32.VirtualAlloc(IntPtr.Zero, code.Length, AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
  22.  
  23.             writer.Write(Assembly.PushLV, prototype);
  24.             writer.Write(Assembly.MoveEDX, name);
  25.             writer.Write(Assembly.MoveECX, functionPtr);
  26.             writer.Write(Assembly.Call, (UInt32)bindNativePtr - (UInt32)codePtr - (UInt32)writer.BaseStream.Position - 5u); // -5u is to get back to the start of the call instruction, 5 is the size of the instruction.
  27.             writer.Write(Assembly.Return);
  28.  
  29.             Marshal.Copy(code, 0, codePtr, code.Length);
  30.             var bindNative = (BindNativePrototype)Marshal.GetDelegateForFunctionPointer(codePtr, typeof(BindNativePrototype));
  31.             bindNative();
  32.             Kernel32.VirtualFree(codePtr, code.Length, MemoryFreeType.Release);
  33.         }
  34.     }
Advertisement
Add Comment
Please, Sign In to add comment