2015年9月20日 星期日

攔截 dynamic library 裡面的函數 - 1

這兩天從某位學弟大大學到了不少東西
主要是如何讓一個寫好的程執行檔呼叫你自己寫的 code
這好像也叫做 hook

先考慮最簡單的 hook
這個情況是 link stage 用 dynamic library 包進去的

Library test.c

#include <stdio>

void test() {
  puts("origin");
}

void test2() {
  puts("origin2");
}

Main file a.c

extern void test();
extern void test2();

int main() {
  test();
  test2();
  return 0;
}

Compile

這個程式可以這樣編譯
# build the dynamic library (so file)
$ gcc test.c -shared -fPIC -o libtest.o
# build the executable against the so file
$ gcc a.c libtest.o

執行結果如下
$ LD_LIBRARY_PATH=. ./a.out
origin
origin2

現在我們想插入自己的新函數,例如說我們寫了新的檔案 hook.c
希望原本的執行檔呼叫其中的 test()

Library hook/hook.c

#include <stdio>

void test() {
  puts("Haha");
}

我們一樣先把他編譯成一個 so file
接這只要設定好 LD_PRELOAD 這個環境變數
系統就會優先使用我們的 library 了

$ gcc hook/hook.c -shared -fPIC -o hook/libhook.so
$ LD_LIBRARY_PATH=. LD_PRELOAD=./hook/libhook.so ./a.out
Haha
origin2
如上面顯示
在不更改任何原本的執行檔的條件下
原本印出 origin1 的地方變成了 Haha

沒有留言:

張貼留言