I would like to calculate how many bytes my function fills so I can inject it into another process using CreateRemoteThread (). As soon as I know the number of bytes, I can write them to the remote process using a function pointer. I found an article on the Internet (see http://www.codeproject.com/KB/threads/winspy.aspx#section_3 , chapter III), where they do the following in C ++:
// ThreadFunc // Notice: - the code being injected; //Return value: password length static DWORD WINAPI ThreadFunc (INJDATA *pData) { //Code to be executed remotely } // This function marks the memory address after ThreadFunc. static void AfterThreadFunc (void) { }
Then they calculate the number of bytes of ThreadFunc using:
const int cbCodeSize = ((LPBYTE) AfterThreadFunc - (LPBYTE) ThreadFunc);
Using cbCodeSize , they allocate memory in the remote process for the ThreadFunc entered and write a copy of ThreadFunc to the allocated memory:
pCodeRemote = (PDWORD) VirtualAllocEx( hProcess, 0, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if (pCodeRemote == NULL) __leave; WriteProcessMemory( hProcess, pCodeRemote, &ThreadFunc, cbCodeSize, &dwNumBytesXferred );
I would like to do this in C #. :) I tried to create delegates, get their pointers and subtract them as follows:
// Thread proc, to be used with Create*Thread public delegate int ThreadProc(InjectionData param); //Function pointer ThreadFuncDeleg = new ThreadProc(ThreadFunc); ThreadFuncPtr = Marshal.GetFunctionPointerForDelegate(ThreadFuncDeleg); //FunctionPointer AfterThreadFuncDeleg = new ThreadProc(AfterThreadFunc); IntPtr AfterThreadFuncDelegPtr= Marshal.GetFunctionPointerForDelegate(AfterThreadFuncDeleg); //Number of bytes int cbCodeSize = (AfterThreadFuncDelegPtr.ToInt32() - ThreadFuncPtr.ToInt32())*4 ;
This just doesn't seem right, as I get a static number no matter what I do with the code.
My question is, if possible, how to calculate the number of bytes, the function code fills in C #?
Thanks in advance.