]> git.ipfire.org Git - thirdparty/binutils-gdb.git/commitdiff
[gdb/python] Handle !Py_IsInitialized () in gdbpy_initialize
authorTom de Vries <tdevries@suse.de>
Fri, 22 Nov 2024 18:34:24 +0000 (19:34 +0100)
committerTom de Vries <tdevries@suse.de>
Fri, 22 Nov 2024 18:34:24 +0000 (19:34 +0100)
I tried out making python initialization fail by passing an incorrect
PYTHONHOME, and got:
...
$ PYTHONHOME=foo gdb -q
Python path configuration:
  PYTHONHOME = 'foo'
  ...
Python Exception <class 'ModuleNotFoundError'>: No module named 'encodings'
Python not initialized
$
...

The relevant part of the code is:
...
static void
gdbpy_initialize (const struct extension_language_defn *extlang)
{
  if (!do_start_initialization () && PyErr_Occurred ())
    gdbpy_print_stack ();

   gdbpy_enter enter_py;
...

What happens is that:
- do_start_initialization returns false because Py_InitializeFromConfig fails,
  leaving us in the !Py_IsInitialized () state
- PyErr_Occurred () returns true
- gdbpy_print_stack is called, which prints
  "Python Exception <class 'ModuleNotFoundError'>: No module named 'encodings"

The problem is that in the Py_IsInitialized () == false state, very few
functions can be called, and PyErr_Occurred is not one of them [1], and
likewise functions in gdbpy_print_stack.

Fix this by:
- guarding the PyErr_Occurred / gdbpy_print_stack part with Py_IsInitialized ().
- handling the !Py_IsInitialized () case by printing the failure PyStatus
  in do_start_initialization

This gets us instead:
...
$ PYTHONHOME=foo ./gdb.sh -q
Python path configuration:
  PYTHONHOME = 'foo'
  ...
Python initialization failed: failed to get the Python codec of the filesystem encoding
Python not initialized
$
...

Tested on aarch64-linux.

Approved-By: Tom Tromey <tom@tromey.com>
[1] https://docs.python.org/3/c-api/init.html#before-python-initialization

gdb/python/python.c

index 7489b530e70b64a805354b1719dc8849e8c6d49e..820fb585475e326c1f12834a8adc08ed7c8642dd 100644 (file)
@@ -2375,7 +2375,14 @@ do_start_initialization ()
 init_done:
   PyConfig_Clear (&config);
   if (PyStatus_Exception (status))
-    return false;
+    {
+      if (PyStatus_IsError (status))
+       gdb_printf (_("Python initialization failed: %s\n"), status.err_msg);
+      else
+       gdb_printf (_("Python initialization failed with exit status: %d\n"),
+                   status.exitcode);
+      return false;
+    }
 #endif
 #else
   Py_Initialize ();
@@ -2720,7 +2727,7 @@ do_initialize (const struct extension_language_defn *extlang)
 static void
 gdbpy_initialize (const struct extension_language_defn *extlang)
 {
-  if (!do_start_initialization () && PyErr_Occurred ())
+  if (!do_start_initialization () && Py_IsInitialized () && PyErr_Occurred ())
     gdbpy_print_stack ();
 
   gdbpy_enter enter_py;