LoginSignup
8
4

More than 3 years have passed since last update.

Pythonでgdbを操作する。

Last updated at Posted at 2019-06-20

概要

ここでは、Pythonによるgdb操作の概要および、gdbによるPythonスクリプトのデバッグの概要について説明する。これは、Google Colabでも使える。

gdbをPythonで操作する

gdbをPythonスクリプトで操作することが出来る。以下に操作例を示す。ここでは、catコマンドを操作するcat.pyというPythonスクリプトファイルでgdbを操作する。

gdb -x cat.py

cat.pyというスクリプトを以下のように定義する。ここでは、Google Colabでも使えるように、%%writefileから記載しているが、通常利用の場合はここを消せばよい。なお、import gdbは、gdb内で動かすスクリプト限定なので、gdb内で動作しているかの確認に使える。エラーが出た場合、外部スクリプトとして使っているのでエラー終了となる。
また、gdb.executeの出力は、string指定が出来るのでこれを利用して、ファイルに出力できる。

%%writefile cat.py
import gdb

gdb.execute('file /bin/cat')
o = gdb.execute('disassemble exit', to_string=True)
print(o)
gdb.execute('quit')

breakpointを設定するなら、こんな感じになる。(Pythonスクリプトをデバッグする例)

import gdb

gdb.execute("file python3")
gdb.execute("set pagination off")
gdb.Breakpoint("xxxxxx.cpp:136")
gdb.execute("run test.py")
for i in range(1010):
    gdb.execute("bt")
    gdb.execute("continue")

なお、cuda-gdbもgdbの拡張版なので、同じスクリプトが、そのまま動く。ただし、cuda部分もデバッグできるので同じPythonスクリプトで分析してもその分遅くなる。ただし、cuda-gdbでは、Pythonスクリプトのデバッギング機能であるpy-xx系コマンドは動かなかった。

Pythonスクリプトをgdbでデバッグする

gdb python3と実行すると該当コマンドが利用できる。ただし、gdb7(2009年リリース)から使える機能であるが、それをベースにしているcuda-gdbでは動かなかった。

  • py-list (該当範囲のPythonコード出力)
  • py-bt (該当Pythonコードのバックトレース)
  • py-up (Pythonスタックの上へ)
  • py-down (Pythonスタックの下へ)
  • py-print (Pythonスタックの変数表示)
  • py-locals (Pythonスタックの変数リスト表示)

など

Google Colabについて

gdbのインストール

Colabでは、gdbがデフォルトではインストールされていない。このため以下のコマンド実行が必要である。

!apt install gdb python3-dbg

なお、一般的なDocker等のコンテナの場合、PTRACEがデフォルトでは不可なので、gdbをそのままでは利用できない。このため、設定を確認する必要がある。

cuda-gdbの問題

(2019/08/28更新本障害は修正された)cuda-gdb internal-error caused on google colab #5

Colabは、コンテナで動いているためgdb/cuda-gdbの場合、[tcsetpgrp failed in terminal_inferior: Inappropriate ioctl for device]とシステムコールが失敗するが、それなりに動く。
ただし、cuda-gdbは、ブレークポイントを設定して動かすと止まることがある。

cuda-gdb/7.12/gdb/block.c:456: internal-error: set_block_compunit_symtab: Assertion `gb->compunit_symtab == NULL' failed.
A problem internal to GDB has been detected,
further debugging may prove unreliable.
Quit this debugging session? (y or n) n

This is a bug, please report it.  For instructions, see:
<http://www.gnu.org/software/gdb/bugs/>.

cuda-gdb/7.12/gdb/block.c:456: internal-error: set_block_compunit_symtab: Assertion `gb->compunit_symtab == NULL' failed.
A problem internal to GDB has been detected,
further debugging may prove unreliable.
Create a core file of GDB? (y or n) n

参考資料

gdbのリファレンス

Pythonマニュアル

その他

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4