使用gdb调试Python进程

http://www.cnblogs.com/dkblog/category/287362.html

https://wiki.python.org/moin/DebuggingWithGdb

There are types of bugs that are difficult to debug from within Python:

segfaults (not uncaught Python exceptions)

hung processes (in cases where you can‘t get a Python traceback or debug with pdb)

out of control daemon processes

In these cases, you can try gdb.
prerequisites

You need to have gdb on your system and Python debugging extensions. Extensions package includes debugging symbols and adds Python-specific commands into gdb. On a modern Linux system, you can easily install these with:

Fedora:

sudo yum install gdb python-debuginfo

Ubuntu:

sudo apt-get install gdb python2.7-dbg

For gdb support on legacy systems, look at the end of this page.

RUNNING WITH GDB

There are two possible ways:

run python under gdb from the start. Note: the python executable needs to have debug symbols in it which may be another exe python2.7-dbg depending on your system

attach to already running python process
To run python under gdb there are also two ways.

Interactive:

$ gdb python
...
(gdb) run <programname>.py <arguments>
Automatic:

$ gdb -ex r --args python <programname>.py <arguments>
This will run the program til it exits, segfaults or you manually stop execution (using Ctrl+C).

If the process is already running, you can attach to it provided you know the process ID.

$ gdb python <pid of running process>
Attaching to a running process like this will cause it to stop. You can tell it to continue running with c command.

Debugging process

If your program segfaulted, gdb will automatically pause the program, so you can switch into gdb console to inspect its state. You can also manually interrupt program execution by pressing Ctrl+C in the console.

See the page EasierPythonDebugging for the list of Python helper commands for gdb.

Getting a C Stack Trace

If you are debugging a segfault, this is probably the first thing you want to do.

At the (gdb) prompt, just run the following command:

(gdb) bt
#0  0x0000002a95b3b705 in raise () from /lib/libc.so.6
#1  0x0000002a95b3ce8e in abort () from /lib/libc.so.6
#2  0x00000000004c164f in posix_abort (self=0x0, noargs=0x0)
    at ../Modules/posixmodule.c:7158
#3  0x0000000000489fac in call_function (pp_stack=0x7fbffff110, oparg=0)
    at ../Python/ceval.c:3531
#4  0x0000000000485fc2 in PyEval_EvalFrame (f=0x66ccd8)
    at ../Python/ceval.c:2163

With luck, this will give some idea of where the problem is occurring and if it doesn‘t help you fix the problem, it can help someone else track down the problem.

The quality of the results will depend greatly on the amount of debug information available.

getting a python stack trace

If you have Python extensions installed, you can enter:

(gdb) py-bt
to get stack trace with familiar Python source code.

Working With Hung Processes

If a process appears hung, it will either be waiting on something (a lock, IO, etc), or be in a busy loop somewhere. In either case, attaching to the process and getting a back trace can help.

If the process is in a busy loop, you may want to continue execution for a bit (using the cont command), then break (Ctrl+C) again and bring up a stack trace.

If the hang occurs in some thread, the following commands may be handy:

(gdb) info threads
  Id   Target Id         Frame
  37   Thread 0xa29feb40 (LWP 17914) "NotificationThr" 0xb7fdd424 in __kernel_vsyscall ()
  36   Thread 0xa03fcb40 (LWP 17913) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
  35   Thread 0xa0bfdb40 (LWP 17911) "QProcessManager" 0xb7fdd424 in __kernel_vsyscall ()
  34   Thread 0xa13feb40 (LWP 17910) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
  33   Thread 0xa1bffb40 (LWP 17909) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
  31   Thread 0xa31ffb40 (LWP 17907) "QFileInfoGather" 0xb7fdd424 in __kernel_vsyscall ()
  30   Thread 0xa3fdfb40 (LWP 17906) "QInotifyFileSys" 0xb7fdd424 in __kernel_vsyscall ()
  29   Thread 0xa481cb40 (LWP 17905) "QFileInfoGather" 0xb7fdd424 in __kernel_vsyscall ()
  7    Thread 0xa508db40 (LWP 17883) "QThread" 0xb7fdd424 in __kernel_vsyscall ()
  6    Thread 0xa5cebb40 (LWP 17882) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
  5    Thread 0xa660cb40 (LWP 17881) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
  3    Thread 0xabdffb40 (LWP 17876) "gdbus" 0xb7fdd424 in __kernel_vsyscall ()
  2    Thread 0xac7b7b40 (LWP 17875) "dconf worker" 0xb7fdd424 in __kernel_vsyscall ()
* 1    Thread 0xb7d876c0 (LWP 17863) "python2.7" 0xb7fdd424 in __kernel_vsyscall ()
Current thread is marked with *. To see where it is in Python code, use py-list:

(gdb) py-list
2025        # Open external files with our Mac app
2026        if sys.platform == "darwin" and ‘Spyder.app‘ in __file__:
2027            main.connect(app, SIGNAL(‘open_external_file(QString)‘),
2028                         lambda fname: main.open_external_file(fname))
2029
>2030        app.exec_()
2031        return main
2032
2033
2034    def __remove_temp_session():
2035        if osp.isfile(TEMP_SESSION_PATH):
To see Python code positions for all threads, use:

(gdb) thread apply all py-list
...
 200
 201        def accept(self):
>202            sock, addr = self._sock.accept()
 203            return _socketobject(_sock=sock), addr
 204        accept.__doc__ = _realsocket.accept.__doc__
 205
 206        def dup(self):
 207            """dup() -> socket object

Thread 35 (Thread 0xa0bfdb40 (LWP 17911)):
Unable to locate python frame

Thread 34 (Thread 0xa13feb40 (LWP 17910)):
 197            for method in _delegate_methods:
 198                setattr(self, method, dummy)
 199        close.__doc__ = _realsocket.close.__doc__
 200
 201        def accept(self):
>202            sock, addr = self._sock.accept()
 203            return _socketobject(_sock=sock), addr
...

References

http://fedoraproject.org/wiki/Features/EasierPythonDebugging

https://code.google.com/p/spyderlib/wiki/HowToDebugDeadlock

GDB on Legacy systems

It may happen that you need to use gdb on a legacy system without advanced Python support. In this case you may find the following information useful.

GDB Macros

A set of GDB macros are distributed with Python that aid in debugging the Python process. You can install them by adding the contents of Misc/gdbinit in the Python sources to~/.gdbinit -- or copy it from Subversion. Be sure to use the correct version for your version of Python or some features will not work.

Note that the new GDB commands this file adds will only work correctly if debugging symbols are available.

Depending on how you‘ve compiled Python, some calls may have had their frame pointers (i.e. $fp in GDB) optimised away, which means GDB won‘t have access to local variables like co that can be inspected for Python callstack information. For example, if you compile using -g -O3 using GCC 4.1, then this occurs. Similarly, with gcc 4.5.2 on Ubuntu (at least) the macros fail for the same reason. The usual symptom is that you‘ll see the call_function routine appearing to be between PyEval_EvalFrameEx and PyEval_EvalCodeEx, and the macro failing with No symbol "co" in current context.. There are two work-arounds for the issue:

Recompiling python with make "CFLAGS=-g -fno-inline -fno-strict-aliasing" solves this problem.

Patching the conditionals for Python frames in the pystack and pystackv routines to ignore frames with where $fp is 0, like so:

    <<<<         if $pc > PyEval_EvalFrameEx && $pc < PyEval_EvalCodeEx
    >>>>         if $pc > PyEval_EvalFrameEx && $pc < PyEval_EvalCodeEx && $fp != 0
Also note that the stop condition for the while-loops in the pystack and pystackv routines were originally designed for the case where you‘re running the Python interpreter directly, and not running the interpreter withing another program (by loading the shared library and manually bootstrapping the interpreter). So you may need to tweak the while-loops depending on the program you‘re intending to debug. See, for example, this StackOverflow post for another (putative) stop condition.

Getting Python Stack Traces With GDB Macros

At the gdb prompt, you can get a Python stack trace:

(gdb) pystack
Alternatively, you can get a list of the Python locals along with each stack frame:

(gdb) pystackv

More useful macros not in python‘s gdbinit file

See http://web.archive.org/web/20070915134837/http://www.mashebali.com/?Python_GDB_macros:The_Macros for some more handy python gdb macros.
时间: 2024-10-05 23:27:36

使用gdb调试Python进程的相关文章

用GDB排查Python程序故障

某Team在用Python开发一些代码,涉及子进程以及设法消除僵尸进程的需求.实践中他们碰上Python程序非预期退出的现象.最初他们决定用GDB调试Python解释器,查看exit()的源头.我听了之后,觉得这个问题应该用别的调试思路.帮他们排查这次程序故障时,除去原始问题,还衍生了其他问题. 这次的问题相比西安研发中心曾经碰上的Python信号处理问题,有不少基础知识.先验知识是共用的,此处不做再普及,感兴趣的同学可以翻看我以前发过的文章. 下文是一次具体的调试.分析记录.为了简化现场.方便

GDB调试多进程程序

[gdb manaul]https://sourceware.org/gdb/current/onlinedocs/gdb/Forks.html#Forks [参考]http://www.cnblogs.com/zhenjing/archive/2011/06/01/gdb_fork.html [参考]http://blog.chinaunix.net/uid-23062171-id-4107159.html gdb没有对fork创建的进程调试做特别的支持.如果用gdb调试父进程,父进程创建子进

使用 GDB 调试多进程程序

GDB 是 linux 系统上常用的调试工具,本文介绍了使用 GDB 调试多进程程序的几种方法,并对各种方法进行比较. 3 评论 田 强 ([email protected]), 软件工程师, IBM中国软件开发中心 2007 年 7 月 30 日 内容 在 IBM Bluemix 云平台上开发并部署您的下一个应用. 开始您的试用 GDB 是 linux 系统上常用的 c/c++ 调试工具,功能十分强大.对于较为复杂的系统,比如多进程系统,如何使用 GDB 调试呢?考虑下面这个三进程系统: 进程

用GDB调试多进程程序

在子进程中sleep,然后attach上去. gdb --pid=123456 ps出子进程的id,gdb attach 进程号. http://www.ibm.com/developerworks/cn/linux/l-cn-gdbmp/index.html 实际上,GDB 没有对多进程程序调试提供直接支持.例如,使用GDB调试某个进程,如果该进程fork了子进程,GDB会继续调试该进程,子进程会不受干扰地运行下去.如果你事先在子进程代码里设定了断点,子进程会收到SIGTRAP信号并终止.那么

使用GDB调试多进程

如果一个进程fork了多个进程,这时使用GBD工具对程序进行调试会如何呢? 实际上,GDB 没有对多进程程序调试提供直接支持.例如,使用GDB调试某个进程,如果该进程fork了子进程,GDB会继续调试该进程,子进程会不受干扰地运行下去. 如果你事先在子进程代码里设定了断点,子进程会收到SIGTRAP信号,如果没有对此信号进行捕捉处理,就会按默认的处理方式处理--终止进程. 那么该如何调试子进程呢?有3种方法: 1.follow-fork-mode 在2.5.60版Linux内核及以后,GDB对使

使用 gdb 调试运行中的 Python 进程

本文和大家分享的是使用 gdb 调试运行中的 Python 进程相关内容,一起来看看吧,希望对大家学习python有所帮助. 准备工作 安装 gdb 和 python2.7-dbg: $ sudo apt-get install gdb python2.7-dbg 设置 /proc/sys/kernel/yama/ptrace_scope: $ sudo su# echo 0 > /proc/sys/kernel/yama/ptrace_scope 运行 test.py: $ python te

gdb调试正在运行的进程

[转自] http://hi.baidu.com/brady_home/blog/item/6b92aa8ffdfee2e6f01f369b.html gdb调试正在运行的进程 2009年04月18日 星期六 下午 08:21 有时会遇到一种很特殊的调试需求,对当前正在运行的其它进程进行调试(正是我今天遇到的情形).这种情况有可能发生在那些无法直接在调试器中运行的进程身上,例如有的进程 只能在系统启动时运行.另外如果需要对进程产生的子进程进行调试的话,也只能采用这种方式.GDB可以对正在执行的程

gdb 远程调试android进程 -转

什么是gdb 它是gnu组织开发的一个强大的unix程序调试工具,我们可以用它来调试Android上的C.C++代码. 它主要可以做4件事情: 随心所欲地启动你的程序. 设置断点,程序执行到断点处会停住.(断点可以是表达式) 程序被停住后,可以查看此时程序中发生的事. 动态改变程序的执行环境. GDB远程调试原理图 如图上所示,我们需要使用gdbserver依附到我们要调试的进程上,gdb通过adbd和手机上的gdbserver 进行socket通信. 远程调试实战 在手机上启动gdbserve

gdb 远程调试android进程

原文:http://blog.csdn.net/xinfuqizao/article/details/7955346?utm_source=tuicool 什么是gdb 它是gnu组织开发的一个强大的unix程序调试工具,我们可以用它来调试Android上的C.C++代码. 它主要可以做4件事情: 随心所欲地启动你的程序. 设置断点,程序执行到断点处会停住.(断点可以是表达式) 程序被停住后,可以查看此时程序中发生的事. 动态改变程序的执行环境. GDB远程调试原理图 如图上所示,我们需要使用g