简体   繁体   English

使用 bad_alloc 调试 Python/C++ 程序

[英]Debug Python/C++ program with bad_alloc

I have a Python program that interfaces with a PyBind11 C++ library.我有一个与 PyBind11 C++ 库接口的 Python 程序。

Somewhere in the library, something is throwing an std::bad_alloc .在图书馆的某个地方,有些东西正在抛出std::bad_alloc Python catches this and handily raises an exception: Python 捕捉到这一点并轻松引发异常:

MemoryError: std::bad_alloc

Running it all in GDB:在 GDB 中运行它:

gdb --ex run --args python3 ./my_program

Doesn't result in a break at the point of bad allocation.在分配错误时不会导致中断。

If I could get Python to segfault on the bad allocation or tell GDB to catch the exception before Python does, I'd be able to debug this.如果我可以让 Python 对错误分配进行段错误或告诉 GDB 在 Python 之前捕获异常,我将能够调试它。 Unfortunately, I'm not sure how to do either.不幸的是,我也不知道该怎么做。

Debugging this requires a few steps.调试它需要几个步骤。 First, we're going to need debugging symbols.首先,我们需要调试符号。 PyBind11 strips these, so we have to get them back. PyBind11 剥离了这些,因此我们必须将它们取回。

My CMake file looked like this:我的 CMake 文件如下所示:

cmake_minimum_required(VERSION 3.10)

find_package(pybind11 REQUIRED)

pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)

to get symbols back I need it to look like this:要找回符号,我需要它看起来像这样:

cmake_minimum_required(VERSION 3.10)

find_package(pybind11 REQUIRED)

pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)

target_link_libraries(my_python_module PRIVATE pybind11::module)
add_library(restore_default_visibility INTERFACE)
target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
target_link_libraries(my_python_module PRIVATE restore_default_visibility)

I also need to get a Debug build:我还需要一个调试版本:

cmake -DCMAKE_BUILD_TYPE=Debug ..

Now, I can start my Python program:现在,我可以启动我的 Python 程序:

gdb --args python3 ./my_program

One GDB starts, I set a breakpoint for the std::bad_alloc :一个 GDB 启动,我为std::bad_alloc设置了一个断点:

catch throw std::bad_alloc

Now I can run my program by typing c .现在我可以通过输入c来运行我的程序。

Later, when it crashes, I can use the bt command to get a backtrace, up and down to navigate the stack, print show the contents of variables, and Ctrl+X+A to see the source code.后来,当它崩溃时,我可以使用bt命令获取回溯, updown导航堆栈, print显示变量的内容,以及Ctrl+X+A来查看源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM