隨想錄(systemtap中的基本原理),隨想錄systemtap

來源:互聯網
上載者:User

隨想錄(systemtap中的基本原理),隨想錄systemtap


【 聲明:著作權,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】


    systemtap中的probe功能非常令人著迷。這種類似hook的方法對於我們調試效能和分析問題非常有用,更重要的是它還不需要重新編譯,僅僅依靠幾個指令碼就可以完成你想要的功能,這不得不說是非常神奇。


    後來,我自己想了一下,這個功能應該不是很複雜。關鍵就是要做好probe函數的保護與復原工作就可以了。想到這,我就在vc 6.0上模擬實現了這麼一段代碼來說明問題。注意,如果在vs2010上運行,恢複地址那一行代碼修改為*(&data +3)=test即可。


#include <stdio.h>#include <windows.h>#define LEN 8unsigned char save[LEN];void test();void stub();// replace functionvoid stub(){unsigned int data;unsigned char* p;unsigned int index;p = test;// above is data, ebp and return address// restore return address*(&data + 2) = test;// restore datafor(index = 0; index < LEN; index ++) {p[index] = save[index];}printf("stub ");}//original functionvoid test(){printf(" china");}// content add is as follows//__asm {//lea eax, stub//call eax//}void set_stub(unsigned char* p, unsigned int data){*(unsigned short*)p = 0x058d;*(unsigned int*)(p+2) = data;*(unsigned short*)(p+6) = 0xd0ff;}int main(){unsigned char* p = (unsigned char*) test;DWORD old;DWORD tmp;unsigned index;// modify attribute of code segmentif(!VirtualProtect(p, LEN, 0x40, &old)){exit(1);}for(index = 0; index < LEN; index ++){save[index] = p[index];}// modify address set_stub(p, stub);// run test functiontest();// restore attribute of code segmentif(!VirtualProtect(p, LEN, old, &tmp)){exit(1);}return 1;}


    這段代碼的內容不複雜,關鍵就是說強迫運行test函數之前一定要運行一下stub函數。首先,我們需要將test函數開始的代碼設定成可讀可寫的屬性;其次就是儲存這一段原始代碼內容,因為之後還是需要恢複的;接著利用set_stub函數將test一開始的代碼設定成一段跳轉內容,這樣可以直接到stub執行;後面stub執行的時候,恢複ret地址和test開始處的data,這樣在stub返回的時候可以繼續到test函數執行;當然最後所有工作都完成的時候就可以恢複test資料區段的屬性了。就是這麼簡單。






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.