Skip to content

Commit

Permalink
Use the Python frame safely in _pythonCallstack (pytorch#88993)
Browse files Browse the repository at this point in the history
Currently, the result of `PyEval_GetFrame()` is piped straight to `Py_INCREF`. However, `PyEval_GetFrame` [may return null](https://docs.python.org/3/c-api/reflection.html#c.PyEval_GetFrame), which seems to be the case sometimes, when calling `_pythonCallstack` from another thread. This is handled in the subsequent `while (nullptr != frame)` block, but `Py_INCREF`, called before it, [doesn't handle this case](https://docs.python.org/3/c-api/refcounting.html#c.Py_INCREF), so the program segfaults. The safe form of `Py_INCREF` is `Py_XINCREF`, so use that instead ([docs](https://docs.python.org/3/c-api/refcounting.html#c.Py_XINCREF)).
Pull Request resolved: pytorch#88993
Approved by: https://github.com/albanD
  • Loading branch information
charlie-wt authored and weiwangmeta committed Nov 30, 2022
1 parent 7c98e70 commit afd23b9
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion torch/csrc/jit/python/python_tracer.cpp
Expand Up @@ -27,7 +27,7 @@ namespace tracer {
std::vector<StackEntry> _pythonCallstack() {
pybind11::gil_scoped_acquire gil;
PyFrameObject* frame = PyEval_GetFrame();
Py_INCREF(frame);
Py_XINCREF(frame);
std::vector<StackEntry> entries;

while (nullptr != frame) {
Expand Down

0 comments on commit afd23b9

Please sign in to comment.