Py_Finalize() 导致 Python 3.9 出现分段错误,但 Python 2.7 不会出现

Py_Finalize() resulting in Segmentation Fault for Python 3.9 but not for Python 2.7

我正在开发一个使用此 C++ matplotlib 包装器的项目 matplotlibcpp.h

使用这个原始头文件的最小示例是

    #include "matplotlibcpp.h"

    namespace plt = matplotlibcpp;

    int main() {
        plt::plot({1,3,2,4});
        plt::show();
    }

注意:分段错误似乎并不依赖于上面的示例,而是真正出现在任何调用 mathplotlibcpp.h 头文件中的函数的程序中。我选择这个绘图示例是因为实际的绘图会起作用,你会看到绘图但是一旦你关闭它并且程序完成,你就会得到分段错误。此外,它是项目 git 中心页面上的官方示例之一。

您也可以将主函数中的两行替换为例如plt::figure() 并且在执行的最后.

,您仍然会得到一个工作程序和一个分段错误

用 python2.7 编译它似乎工作正常

g++ minimal.cpp -std=c++11 -I/usr/include/python2.7 -I/home/<user>/.local/lib/python2.7/site-packages/numpy/core/include/ -lpython2.7

$ ldd a.out 
    linux-vdso.so.1 (0x00007ffe1f3f7000)
    libpython2.7.so.1.0 => /usr/lib/libpython2.7.so.1.0 (0x00007f8320f8f000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f8320db2000)
    libm.so.6 => /usr/lib/libm.so.6 (0x00007f8320c6d000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007f8320c53000)
    libc.so.6 => /usr/lib/libc.so.6 (0x00007f8320a86000)
    libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007f8320a65000)
    libdl.so.2 => /usr/lib/libdl.so.2 (0x00007f8320a5c000)
    libutil.so.1 => /usr/lib/libutil.so.1 (0x00007f8320a57000)
    /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f83211c2000)

用 python3.9 编译它似乎会导致分段错误

g++ minimal.cpp -std=c++11 -I/usr/include/python3.9 -I/home/pascal/.local/lib/python3.9/site-packages/numpy/core/include/ -lpython3.9

此处 ./a.out 导致 分段错误(核心已转储)

$ ldd a.out 
    linux-vdso.so.1 (0x00007fff8dbc5000)
    libpython3.9.so.1.0 => /usr/lib/libpython3.9.so.1.0 (0x00007f60176ec000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f601750f000)
    libm.so.6 => /usr/lib/libm.so.6 (0x00007f60173ca000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007f60173b0000)
    libc.so.6 => /usr/lib/libc.so.6 (0x00007f60171e3000)
    libpthread.so.0 => /usr/lib/libpthread.so.0 (0x00007f60171c2000)
    libdl.so.2 => /usr/lib/libdl.so.2 (0x00007f60171b9000)
    libutil.so.1 => /usr/lib/libutil.so.1 (0x00007f60171b4000)
    /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f6017adf000)

两者都是在使用 arch linux 和 g++ 版本 10.2.0 的系统上编译的。

这是在他们 git 中找到的 issue,但到目前为止,还没有人提出解决方案。

现在我将问题隔离为对 Py_Finalize() 的调用。对于 Python3 这调用 Py_FinalizeEx()。所以 Python2 和 Python3 是有区别的。

现在在 matplotlibcpp.h 文件中 Py_Finalize() 在析构函数中被调用:

~_interpreter() {
    Py_Finalize();
}

如果你把它注释掉,你就摆脱了分段错误。现在我真的对这个最终确定函数感到困惑,因为文档状态 (for python3)

Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (del() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.

现在头文件中还有一个 Kill() 函数,它调用解构函数的显式性,但从未使用过。

现在,似乎只有当我们超出范围时才会调用解构函数,即他们从不使用 free()delete。而且我认为它只是尝试释放已经释放的东西但是弄清楚它有点困难,因为我对 C Python API.

太不熟悉了

堆栈跟踪:(我希望我正确安装了 python 调试符号。不确定为什么 Qt5 小部件符号不显示。)

注意:我用 -std=c++17 -Wall -g

编译了下面的堆栈跟踪

另请注意,函数 matplotlibcpp::detail::_interpreter::interkeeper(bool) 显式调用解构函数,请参阅 kill()。我之所以提到,是因为在下面的堆栈跟踪中提到了这个函数——但我不确定为什么。该函数的源代码具有以下注释:

/* 
    For now, _interpreter is implemented as a singleton since its currently not possible to have
   multiple independent embedded python interpreters without patching the python source code
   or starting a separate process for each. [1]
   Furthermore, many python objects expect that they are destructed in the same thread as they
   were constructed. [2] So for advanced usage, a `kill()` function is provided so that library
   users can manually ensure that the interpreter is constructed and destroyed within the
   same thread.
     1: http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program
     2: https://github.com/lava/matplotlib-cpp/pull/202#issue-436220256
   */

堆栈跟踪:

Thread 1 "MAIN" received signal SIGSEGV, Segmentation fault.
0x00007fffde884225 in ?? () from /usr/lib/libQt5Widgets.so.5
(gdb) bt
#0  0x00007fffde884225 in ?? () from /usr/lib/libQt5Widgets.so.5
#1  0x00007fffdf14540a in ?? () from /usr/lib/python3.9/site-packages/PyQt5/QtWidgets.abi3.so
#2  0x00007fffe2bc67eb in ?? () from /usr/lib/python3.9/site-packages/PyQt5/QtCore.abi3.so
#3  0x00007ffff7d0ea5c in cfunction_vectorcall_NOARGS (func=0x7fffe2cccb80, args=<optimized out>, nargsf=<optimized out>, kwnames=<optimized out>) at Objects/methodobject.c:485
#4  0x00007ffff7e0ca69 in atexit_callfuncs (module=<optimized out>) at ./Modules/atexitmodule.c:93
#5  0x00007ffff7c744e7 in call_py_exitfuncs (tstate=0x555555597240) at Python/pylifecycle.c:2374
#6  0x00007ffff7dfc627 in Py_FinalizeEx () at Python/pylifecycle.c:1373
#7  0x000055555555926d in matplotlibcpp::detail::_interpreter::~_interpreter (this=0x55555555e620 <matplotlibcpp::detail::_interpreter::interkeeper(bool)::ctx>, 
    __in_chrg=<optimized out>) at /home/pascal/test/cpp/foo/matplotlibcpp.h:288
#8  0x00007ffff76d24a7 in __run_exit_handlers () from /usr/lib/libc.so.6
#9  0x00007ffff76d264e in exit () from /usr/lib/libc.so.6
#10 0x00007ffff76bab2c in __libc_start_main () from /usr/lib/libc.so.6
#11 0x000055555555646e in _start ()

我无法轻松访问 Linux 并在那里进行测试,但我想我现在明白发生了什么。

  1. matplotlibcpp 使用静态变量来保存 Python 解释器(参见 interkeeper(bool should_kill) 中的第 129 行)。与 C++ 静态函数变量一样,它在第一次调用函数时初始化,并在程序退出时销毁 (reference)。

  2. main 完成时,libc 为所有共享库和您的程序(即堆栈跟踪中的 __run_exit_handlers)运行清理例程。由于您的程序是 C++ 程序,因此其退出处理程序的一部分正在破坏所有使用过的静态变量。其中之一是 Python 解释器。它的析构函数调用 Py_Finalize(),这是 Python 的清理例程。到目前为止,一切都很好。

  3. Python 有一个类似的 atexit 机制,允许来自任何地方的 Python 代码注册在解释器关闭期间应该调用的函数。显然,这里选择使用的后端 matplotlib 是 PyQt5。它似乎注册了这样的 atexit 回调。

  4. PyQt5 的回调被调用,然后崩溃。请注意,这是现在的内部 PyQt5 代码。为什么会崩溃?我的“有根据的”猜测是,在调用程序的退出处理程序之前,Qt 的 library 退出处理程序在步骤 2 中 已经被调用 。这显然会导致库中出现一些奇怪的状态(也许某些对象被释放了?)和崩溃。

这留下了两个有趣的问题:

  1. 如何解决这个问题?解决方案应该是在您的程序退出之前销毁 ctx,因此 Python 解释器在任何共享库自行终止之前被销毁。 Static lifetimes are known for causing similar problems. If changing matplotlibcpp's interface to not use global static states is not a possible solution, I think you really have to manually call plt::detail::_interpreter::kill() at the end of your main function. You should be able to use atexit() 并注册一个在库拆卸之前终止解释器的回调——不过我还没有测试过它。

  2. 为什么这行得通?我的猜测是,也许 PyQt5 的回调中的某些内容已更改,现在导致此崩溃,或者您在 Python 2 中使用了不同的后端。如果在程序退出之前没有其他库破坏性终止,这很好。