2010-10-27 21 views
4

我想計算我的函數填充多少個字節,以便我可以使用CreateRemoteThread()將其注入到另一個進程中。一旦我知道了字節數,我可以使用函數的指針將它們寫入遠程進程。我發現了一個網上的文章(見http://www.codeproject.com/KB/threads/winspy.aspx#section_3,第三章),他們做的在C++中的以下內容:我的函數使用了多少個字節? (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) { 
} 

然後,他們計算的字節ThreadFunc數目罷了使用:

const int cbCodeSize = ((LPBYTE) AfterThreadFunc - (LPBYTE) ThreadFunc); 

使用它們分配cbCodeSize在遠程進程中爲內存注入ThreadFunc並將ThreadFunc的副本寫入分配的內存:

pCodeRemote = (PDWORD) VirtualAllocEx(hProcess, 0, cbCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);  
if (pCodeRemote == NULL) 
__leave; 
WriteProcessMemory(hProcess, pCodeRemote, &ThreadFunc, cbCodeSize, &dwNumBytesXferred); 

我想在C#中執行此操作。 :) 我曾嘗試創建的代表,得到他們的指針,並減去他們是這樣的:

// 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 ; 

它只是看起來不正確,因爲我得到一個靜態的數字,無論我做什麼用的代碼。
我的問題是,如果可能的話,如何計算一個函數的代碼填充C#中的字節數?

預先感謝您。

回答

7

我不認爲這是可能的,因爲在.NET中動態優化和代碼生成。您可以嘗試測量IL碼長度,但是當您嘗試在一般情況下測量機器相關代碼長度時,它將失敗。

通過'失敗'我的意思是你不能得到正確的大小,通過動態使用這種技術提供任何意義。

當然,你可以去找到如何NGEN,JIT編譯工作,pdb結構,並嘗試測量。例如,您可以通過探索VS中生成的機器碼來確定代碼的大小。

How to see the Assembly code generated by the JIT using Visual Studio


如果你真的需要確定尺寸,開始NET Internals and Code Injection/NET Internals and Native Compiling但我無法想象爲什麼你想它。

注意約JIT是怎麼工作的所有內部是如有更改所以要根據解決方案可以通過打破.NET任何未來的版本。


如果你想堅持IL:檢查Profiling Interfaces(CLR分析API),以及一個有點老的文章:Rewrite MSIL Code on the Fly with the .NET Framework Profiling APINo Code Can Hide from the Profiling API in the .NET Framework 2.0。在SO上還有一些關於CLR分析API的主題。探索組裝

但最簡單的方法是Reflection API,你要MethodBody那裏。所以你可以檢查LengthMethodBody.GetILAsByteArray,你會發現在IL-命令中的方法長度。

+1

+1。另外,CLR可以自由地獲取連續的C#函數,並將其轉換爲多個不同的本地代碼範圍。 – 2010-10-28 00:01:31

+0

非常感謝您的全面回答。 – prettyCode 2010-10-28 06:22:12

+0

@prettyCode,很高興幫助你:) – 2010-10-28 08:57:05

相關問題