Skip to content

Commit db433de

Browse files
committed
[lldb] Call Import_AppendInittab before Py_Initialize (llvm#82095)
The Python documentation [1] says that `PyImport_AppendInittab` should be called before `Py_Initialize()`. Starting with Python 3.12, this is enforced with a fatal error: Fatal Python error: PyImport_AppendInittab: PyImport_AppendInittab() may not be called after Py_Initialize() This commit ensures we only modify the table of built-in modules if Python hasn't been initialized. For Python embedded in LLDB, that means this happen exactly once, before the first call to `Py_Initialize`, which becomes a NO-OP after. However, when lldb is imported in an existing Python interpreter, Python will have already been initialized, but by definition, the lldb module will already have been loaded, so it's safe to skip adding it (again). This fixes llvm#70453. [1] https://docs.python.org/3.12/c-api/import.html#c.PyImport_AppendInittab (cherry picked from commit fbce244)
1 parent 3f8a139 commit db433de

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -95,24 +95,28 @@ struct InitializePythonRAII {
9595
InitializePythonRAII() {
9696
InitializePythonHome();
9797

98+
// The table of built-in modules can only be extended before Python is
99+
// initialized.
100+
if (!Py_IsInitialized()) {
98101
#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
99-
// Python's readline is incompatible with libedit being linked into lldb.
100-
// Provide a patched version local to the embedded interpreter.
101-
bool ReadlinePatched = false;
102-
for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
103-
if (strcmp(p->name, "readline") == 0) {
104-
p->initfunc = initlldb_readline;
105-
break;
102+
// Python's readline is incompatible with libedit being linked into lldb.
103+
// Provide a patched version local to the embedded interpreter.
104+
bool ReadlinePatched = false;
105+
for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
106+
if (strcmp(p->name, "readline") == 0) {
107+
p->initfunc = initlldb_readline;
108+
break;
109+
}
110+
}
111+
if (!ReadlinePatched) {
112+
PyImport_AppendInittab("readline", initlldb_readline);
113+
ReadlinePatched = true;
106114
}
107-
}
108-
if (!ReadlinePatched) {
109-
PyImport_AppendInittab("readline", initlldb_readline);
110-
ReadlinePatched = true;
111-
}
112115
#endif
113116

114-
// Register _lldb as a built-in module.
115-
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
117+
// Register _lldb as a built-in module.
118+
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
119+
}
116120

117121
// Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
118122
// calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you

0 commit comments

Comments
 (0)