跳到主要內容

glibc的malloc hook機制試玩

glibc裡其實有實作了不少有趣的機制,我今天試著玩其中的一個小東西 - memory allocation hooks


我們都知道,在C語言中若需要在執行期要到一塊大小為size的記憶體需要透過malloc(size)去獲得,但是malloc之後必須在不用了以後正確釋放,否則就會有memory leak產生。用肉眼去觀察malloc/free的流程是非常辛苦的一件事,尤其當我們接手別人的程式時,要確認這件事更是困難重重。當然,有不少現成的分析工具可以使用,不過我愈來愈想知道那些工具的可能實作手法,或許必要時就可以自己做一個客制化的小工具。在這種想法下,我在這篇文章發現了memory allocation hooks(嗯...以前從來沒有仔細看過glibc manual,沒想到glibc的特異功能還真不少 :P),稍微想了一下,利用這個機制應該就可以完成一個簡易的memory leak detector,glibc對其相關介面的描述是:


__malloc_hook

The value of this variable is a pointer to the function that malloc uses whenever it is called. You should define this function to look like malloc; that is, like:
          void *function (size_t size, const void *caller)
The value of caller is the return address found on the stack when the malloc function was called. This value allows you to trace the memory consumption of the program.
__free_hook
The value of this variable is a pointer to function that free uses whenever it is called. You should define this function to look like free; that is, like:
          void function (void *ptr, const void *caller)
The value of caller is the return address found on the stack when the free function was called. This value allows you to trace the memory consumption of the program.
__malloc_initialize_hook
The value of this variable is a pointer to a function that is called once when the malloc implementation is initialized. This is a weak variable, so it can be overridden in the application with a definition like the following:
          void (*__malloc_initialize_hook) (void) = my_init_hook;
說明的很清楚,網頁還給出一個流程說明,我修改了一下讓其可以完整執行起來:
  1. #include <stdio.h>
  2. /* Prototypes for __malloc_hook, __free_hook */
  3. #include <malloc.h>
  4.  
  5. /* Prototypes for our hooks.  */
  6. static void my_init_hook (void);
  7. static void *my_malloc_hook (size_t, const void *);
  8. static void my_free_hook (void*, const void *);
  9. /* two function pointer to save old hooks */
  10. static void *(*old_malloc_hook)(size_t, const void *);
  11. static void (*old_free_hook)(void *, const void *);
  12.  
  13. /* Override initializing hook from the C library. */
  14. void (*__malloc_initialize_hook) (void) = my_init_hook;
  15.  
  16. static void
  17. my_init_hook (void)
  18. {
  19.                 old_malloc_hook = __malloc_hook;
  20.                 old_free_hook = __free_hook;
  21.                 __malloc_hook = my_malloc_hook;
  22.                 __free_hook = my_free_hook;
  23. }
  24.  
  25. static void *
  26. my_malloc_hook (size_t size, const void *caller)
  27. {
  28.                 void *result;
  29.  
  30.                 printf("caller %pn", caller);
  31.                 /* Restore all old hooks */
  32.                 __malloc_hook = old_malloc_hook;
  33.                 __free_hook = old_free_hook;
  34.                 /* Call recursively */
  35.                 result = malloc (size);
  36.                 /* Save underlying hooks */
  37.                 old_malloc_hook = __malloc_hook;
  38.                 old_free_hook = __free_hook;
  39.  
  40.                 /* printf might call malloc, so protect it too. */
  41.                 printf ("malloc (%u) returns %pn", (unsigned int) size, result);
  42.                 /* Restore our own hooks */
  43.                 __malloc_hook = my_malloc_hook;
  44.                 __free_hook = my_free_hook;
  45.                 return result;
  46. }
  47.  
  48. static void
  49. my_free_hook (void *ptr, const void *caller)
  50. {
  51.                 /* Restore all old hooks */
  52.                 __malloc_hook = old_malloc_hook;
  53.                 __free_hook = old_free_hook;
  54.                 /* Call recursively */
  55.                 free (ptr);
  56.                 /* Save underlying hooks */
  57.                 old_malloc_hook = __malloc_hook;
  58.                 old_free_hook = __free_hook;
  59.                 /* printf might call free, so protect it too. */
  60.                 printf ("freed pointer %pn", ptr);
  61.                 /* Restore our own hooks */
  62.                 __malloc_hook = my_malloc_hook;
  63.                 __free_hook = my_free_hook;
  64. }
  65.  
  66. static void foo(void)
  67. {
  68.         char *ptr = malloc(100);
  69.  
  70.         *ptr = 0x99;
  71.        
  72.         free(ptr);
  73. }
  74.  
  75. int main(void)
  76. {
  77.         foo();
  78.  
  79.         foo();
  80. }

不試還好,一試就發現執行結果跟我預期不符。我在my_malloc_hook將caller的address印出來看,結果發現兩次foo()去呼叫malloc(),卻出現不同結果:


[mars@dream malloc_free_hook]$ gcc -o test_simple test_simple.c 
[mars@dream malloc_free_hook]$ ./test_simple 
caller 0xb77bea13
malloc (100) returns 0x96c8008
freed pointer 0x96c8008
caller 0x804860a
malloc (100) returns 0x96c8008
freed pointer 0x96c8008

可以確認的是,第二次是對的,並且在第二次之後也都是對的(用objdunp -d即可確認foo中的malloc呼叫時,其PC是0x804860a),那第一次的錯誤是怎麼回事?

想一想...耶!知道了!因為gcc預設是用dynamic linking去link libc的關係啊!

之前我翻譯過Eli大俠的共享庫動態載入機制中有提到,程式對動態共享庫的引用,第一次引用的路徑是不同於第二次的!第一次長這樣:

會由PLT[0]中的resolver去"call" malloc(所以return address是落在libc.so,可透過/proc/process_id/maps觀察得知),然後在第二次呼叫時,才會直接跳到已被更新的GOT[n](此時是由call func@PLT過來的,所以return address落在我們的函式中)。第二次呼叫的流程長這樣:


有趣吧?:) 所以我們可以在main中malloc()/free()一次,當作第一次的malloc不會有memory leak問題,只看接下來的統計即可。換另個角度想,那麼只要用static link的方式就應該要能避掉這個問題嘍?我們來試一下:


[mars@dream malloc_free_hook]$ gcc -static -o test_simple test_simple.c 
[mars@dream malloc_free_hook]$ ./test_simple 
caller 0x804de54
malloc (20) returns 0x8bdbcd8
caller 0x8073803
malloc (2480) returns 0x8bdbcf0
caller 0x8048376
malloc (100) returns 0x8bdc6a8
freed pointer 0x8bdc6a8
caller 0x8048376
malloc (100) returns 0x8bdc6a8
freed pointer 0x8bdc6a8

看來我們在程式中呼叫的都一致了,但藍色的是哪裡多出來的?同樣地,我用objdump -d看一下,發現是在_dl_init_paths與__libc_malloc中:

08073790 <_dl_init_paths>:
 8073790:       55                      push   %ebp
 8073791:       b9 dc 5f 0c 08          mov    $0x80c5fdc,%ecx
 8073796:       89 e5                   mov    %esp,%ebp
...

 80737fe:       e8 8d a4 fd ff          call   804dc90 <__libc_malloc>
 8073803:       89 03                   mov    %eax,(%ebx)
 8073805:       a1 e4 5f 0c 08          mov    0x80c5fe4,%eax
 807380a:       8b 30                   mov    (%eax),%esi
 807380c:       85 f6                   test   %esi,%esi
...
0804dc90 <__libc_malloc>:
 804dc90:       55                      push   %ebp
 804dc91:       89 e5                   mov    %esp,%ebp
 804dc93:       83 ec 1c                sub    $0x1c,%esp
...
 804de52:       ff d0                   call   *%eax
 804de54:       89 c6                   mov    %eax,%esi
 804de56:       e9 c5 fe ff ff          jmp    804dd20 <__libc_malloc+0x90>
 804de5b:       90                      nop
 804de5c:       8d 74 26 00             lea    0x0(%esi,%eiz,1),%esi

真是Orz...原來這個hook機制用在static link的情況時,似乎會有其他的初始動作,使得我們的hook會在還沒在main()之前就被用到。看來明天要來翻glibc的代碼來看看...

果然還是要動手試作一下才知道一堆眉眉角角...-_-

留言

這個網誌中的熱門文章

淺讀Linux root file system初始化流程

在Unix的世界中,file system佔據一個極重要的抽象化地位。其中,/ 所代表的rootfs更是所有後續新增file system所必須依賴前提條件。以Linux為例,黑客 Jserv 就曾經詳細說明過 initramfs的背後設計考量 。本篇文章不再重複背景知識,主要將追蹤rootfs初始化的流程作點整理,免得自己日後忘記。 :-) file system與特定CPU架構無關,所以我觀察的起點從init/main.c的start_kernel()開始,這是Linux作完基本CPU初始化後首先跳進的C function(我閱讀的版本為 3.12 )。跟root file system有關的流程羅列如下: start_kernel()         -> vfs_caches_init_early()         -> vfs_caches_init()                 -> mnt_init()                         -> init_rootfs()                         -> init_mount_tree()         -> rest_init()                 -> kernel_thread(kernel_init,...) 其中比較重要的是mnt_int()中的init_rootfs()與init_mout_tree()。init_rootfs()實作如下: int __init init_rootfs(void) {         int err = register_filesystem(&rootfs_fs_type);         if (err)                 return err;         if (IS_ENABLED(CONFIG_TMPFS) && !saved_root_name[0] &&                 (!root_fs_names || strstr(root_fs_names, "tmpfs"))) {          

誰在呼叫我?不同的backtrace實作說明好文章

今天下班前一個同事問到:如何在Linux kernel的function中主動印出backtrace以方便除錯? 寫過kernel module的人都知道,基本上就是用dump_stack()之類的function就可以作到了。但是dump_stack()的功能是如何作到的呢?概念上其實並不難,慣用手法就是先觀察stack在function call時的變化(一般OS或計組教科書都有很好的說明,如果不想翻書,可以參考 這篇 ),然後將對應的return address一層一層找出來後,再將對應的function名稱印出即可(透過執行檔中的section去讀取函式名稱即可,所以要將KALLSYM選項打開)。在userspace的實作可參考Jserv介紹過的 whocallme 或對岸好手實作過的 backtrace() ,都是針對x86架構的很好說明文章。 不過從前面兩篇文章可以知道,只要知道編譯器的calling convention,就可以實作出backtrace,所以是否GCC有提供現成的機制呢?Yes, that is what __builtin_return_address() for!! 可以參考這篇 文章 。該篇文章還提到了其他可以拿來實作功能更齊全的backtrace的 程式庫 ,在了解了運作原理後,用那些東西還蠻方便的。 OK,那Linux kernel是怎麼做的呢?就是用頭兩篇文章的方式啦~ 每個不同的CPU架構各自手工實作一份dump_stack()。 為啥不用GCC的機制?畢竟...嗯,我猜想,除了backtrace以外,開發者還會想看其他register的值,還有一些有的沒的,所以光是GCC提供的介面是很難印出全部所要的資訊,與其用半套GCC的機制,不如全都自己來~ arm的實作 大致上長這樣,可以看到基本上就只是透過迭代fp, lr, pc來完成: 352 void unwind_backtrace (struct pt_regs * regs , struct task_struct *tsk) 353 { 354 struct stackframe frame ; 355 register unsigned long current_sp asm ( "

kernel panic之後怎麼辦?

今天同事在處理一個陌生的模組時遇到kernel panic,Linux印出了backtrace,同事大致上可以知道是在哪個function中,但該function的長度頗長,短時間無法定位在哪個位置,在這種情況下,要如何收斂除錯範圍呢?更糟的是,由於加入printk會改變模組行為,所以printk基本上無法拿來檢查參數的值是否正常。 一般這樣的問題會backtrace的資訊來著手。從這個資訊我們可以知道在function中的多少offset發生錯誤,以x86為例(從 LDD3 借來的例子): Unable to handle kernel NULL pointer dereference at virtual address 00000000 printing eip: d083a064 Oops: 0002 [#1] SMP CPU:    0 EIP:    0060:[<d083a064>]    Not tainted EFLAGS: 00010246   (2.6.6) EIP is at faulty_write+0x4/0x10 [faulty] eax: 00000000   ebx: 00000000   ecx: 00000000   edx: 00000000 esi: cf8b2460   edi: cf8b2480   ebp: 00000005   esp: c31c5f74 ds: 007b   es: 007b   ss: 0068 Process bash (pid: 2086, threadinfo=c31c4000 task=cfa0a6c0) Stack: c0150558 cf8b2460 080e9408 00000005 cf8b2480 00000000 cf8b2460 cf8b2460        fffffff7 080e9408 c31c4000 c0150682 cf8b2460 080e9408 00000005 cf8b2480        00000000 00000001 00000005 c0103f8f 00000001 080e9408 00000005 00000005 Call Trace:  [<c0150558>] vfs