Skip to content

Commit 184444b

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 db24e22 commit 184444b

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
@@ -93,24 +93,28 @@ struct InitializePythonRAII {
9393
InitializePythonRAII() {
9494
InitializePythonHome();
9595

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

112-
// Register _lldb as a built-in module.
113-
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
115+
// Register _lldb as a built-in module.
116+
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
117+
}
114118

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

0 commit comments

Comments
 (0)