在不需要的系统调用

时间:2017-02-26 19:05:50

标签: python debugging system-calls

我被告知要修复遗留应用程序中的错误。

我可以重现一个错误,但我不清楚错误执行的python源代码行。

我可以看到strace的相关失败:文件被打开,不应该打开。

我想让相关的open()linux-syscall在python解释器中引发一个Exception。我的目标:我希望看到堆栈跟踪能够修复错误。

通过这种方式,我可以避免花费大量时间在调试器上进行操作。

与其他词语相同:如果syscall被执行,导致open("/somefile", O_RDONLY) = 4的strace输出,python解释器应该以traceback退出。

有人有解决方案吗?

如果您不了解我在寻找什么,请发表评论。

2 个答案:

答案 0 :(得分:4)

我们可以在导入模块之前在open上做一个补丁,这是一个例子:

test.py中的

def func():
    with open('test', 'w') as f:
        pass
test2.py中的

try:
    import __builtin__ # for python2
except ImportError:
    import builtins as __builtin__ #for python3

import copy
import traceback

orig_open = copy.copy(__builtin__.open)

def myopen(*args):
    traceback.print_stack()
    return orig_open(*args)

__builtin__.open = myopen

from test import func # Note that we import the module after patching on open()

func()

并且在func()中调用test2.py时,将打印调用堆栈:

$ python test2.py 
  File "test2.py", line 19, in <module>
    func()
  File "/tmp/test.py", line 4, in func
    with open('test', 'w') as f:
  File "test2.py", line 12, in myopen
    traceback.print_stack()

答案 1 :(得分:4)

您可以在gdb下运行python,在open()系统调用(或者更确切地说,调用它的libc中的存根函数)上设置(条件)断点,并且,当命中断点时,发送向python进程发出SIGINT信号并让它继续运行,因此python脚本的执行应该被所需的堆栈跟踪中断。

下面的shell脚本会自动执行该过程。

用法:

stack_trace_on_open filename -- python script.py [ script args ]

<强> stack_trace_on_open

#!/usr/bin/env bash

myname="$(basename "$0")"

if [[ $# -lt 4 || "$2" != '--' ]]
then
    echo >&2 "Usage: $myname <filename> -- python <script.py> [script args ...]"
    exit 1
fi

fname=$1
python_exe="$3"
shift 3

gdb -q "$python_exe" <<END
set breakpoint pending on
break open
condition 1 strcmp(\$rdi,"$fname") == 0
run "$@"
signal 2
cont
quit
END

演示:

$ cat test.py 
import ctypes

clib = ctypes.CDLL(None)
fd = clib.open("/dev/urandom", 0)
clib.close(fd)

$ ./stack_trace_on_open /dev/urandom -- python test.py 
Reading symbols from python...(no debugging symbols found)...done.
(gdb) (gdb) Function "open" not defined.
Breakpoint 1 (open) pending.
(gdb) (gdb) Starting program: /usr/bin/python "test.py"
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, open64 () at ../sysdeps/unix/syscall-template.S:84
84  ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) Continuing with signal SIGINT.

Breakpoint 1, open64 () at ../sysdeps/unix/syscall-template.S:84
84  in ../sysdeps/unix/syscall-template.S
(gdb) Continuing.
Traceback (most recent call last):                #     <--------
  File "test.py", line 4, in <module>             #     <--------
    fd = clib.open("/dev/urandom", 0)             #     <--------
KeyboardInterrupt
[Inferior 1 (process 14248) exited with code 01]
(gdb)