CubicLouve

Spring_MTの技術ブログ

gdbを使ってみる

gdbをはっきり説明せよと言われてもわからんが使ってみる。

デバッグシンボル付きでrubyをビルドしておく

rbenv + ruby-buildを使ってrubyを入れていれば、デフォルトでデバッグシンボル付きでビルドしてくれている。

rubyを読み込む

rbenvを使ってると、gdb rubyとすると

 % gdb ruby
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb  6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"..."/opt/boxen/rbenv/shims/ruby": not in executable format: File format not recognized

とこんな感じで怒られる(そりゃ当たり前だ)

rbenv which rubyrubyのバイナリのパスを見つけて、gdbを起動すると、

% gdb /opt/boxen/rbenv/versions/2.0.0-p247/bin/ruby 
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb  6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries ... done

こんな感じになる。

で、breakpointを設定する。
rubyのソースをみて、適当に関数を指定してみた。
今回は、string.cにあった、rb_str_new_cstrを指定した。
それで、backtraceを取ってみる。

(gdb) b rb_str_new_cstr
Breakpoint 1 at 0x1000f51a5
(gdb) r -e 'p "aaaa"'
Starting program: /opt/boxen/rbenv/versions/2.0.0-p247/bin/ruby -e 'p "aaaa"'
Reading symbols for shared libraries ++............................. done

Breakpoint 1, 0x00000001000f51a5 in rb_str_new_cstr ()
(gdb) bt
#0  0x00000001000f51a5 in rb_str_new_cstr ()
#1  0x000000010005abf7 in prep_io ()
#2  0x000000010005c327 in Init_IO ()
#3  0x0000000100056a21 in rb_call_inits ()
#4  0x000000010003773c in ruby_setup ()
#5  0x0000000100037779 in ruby_init ()
#6  0x0000000100000b4b in main ()

うまくいった。(と思う)
これからどうするかは考える。