Skip to content

Commit b937713

Browse files
committed
[lldb] Call Import_AppendInittab exactly once before Py_Initialize
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 #70453. [1] https://docs.python.org/3.12/c-api/import.html#c.PyImport_AppendInittab
1 parent 36e73e4 commit b937713

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
@@ -97,24 +97,28 @@ struct InitializePythonRAII {
9797
InitializePythonRAII() {
9898
InitializePythonHome();
9999

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

116-
// Register _lldb as a built-in module.
117-
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
119+
// Register _lldb as a built-in module.
120+
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
121+
}
118122

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

0 commit comments

Comments
 (0)