Home | History | Annotate | Line # | Download | only in python
python.c revision 1.11
      1   1.1  christos /* General python/gdb code
      2   1.1  christos 
      3  1.11  christos    Copyright (C) 2008-2024 Free Software Foundation, Inc.
      4   1.1  christos 
      5   1.1  christos    This file is part of GDB.
      6   1.1  christos 
      7   1.1  christos    This program is free software; you can redistribute it and/or modify
      8   1.1  christos    it under the terms of the GNU General Public License as published by
      9   1.1  christos    the Free Software Foundation; either version 3 of the License, or
     10   1.1  christos    (at your option) any later version.
     11   1.1  christos 
     12   1.1  christos    This program is distributed in the hope that it will be useful,
     13   1.1  christos    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14   1.1  christos    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15   1.1  christos    GNU General Public License for more details.
     16   1.1  christos 
     17   1.1  christos    You should have received a copy of the GNU General Public License
     18   1.1  christos    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19   1.1  christos 
     20   1.1  christos #include "arch-utils.h"
     21   1.1  christos #include "command.h"
     22   1.1  christos #include "ui-out.h"
     23   1.1  christos #include "cli/cli-script.h"
     24  1.11  christos #include "cli/cli-cmds.h"
     25   1.1  christos #include "progspace.h"
     26   1.1  christos #include "objfiles.h"
     27   1.1  christos #include "value.h"
     28   1.1  christos #include "language.h"
     29   1.9  christos #include "gdbsupport/event-loop.h"
     30   1.1  christos #include "readline/tilde.h"
     31   1.1  christos #include "python.h"
     32   1.3  christos #include "extension-priv.h"
     33   1.1  christos #include "cli/cli-utils.h"
     34   1.1  christos #include <ctype.h>
     35   1.6  christos #include "location.h"
     36   1.9  christos #include "run-on-main-thread.h"
     37  1.11  christos #include "observable.h"
     38  1.11  christos 
     39  1.11  christos #if GDB_SELF_TEST
     40  1.10  christos #include "gdbsupport/selftest.h"
     41  1.11  christos #endif
     42   1.1  christos 
     43   1.1  christos /* Declared constants and enum for python stack printing.  */
     44   1.1  christos static const char python_excp_none[] = "none";
     45   1.1  christos static const char python_excp_full[] = "full";
     46   1.1  christos static const char python_excp_message[] = "message";
     47   1.1  christos 
     48   1.1  christos /* "set python print-stack" choices.  */
     49   1.1  christos static const char *const python_excp_enums[] =
     50   1.1  christos   {
     51   1.1  christos     python_excp_none,
     52   1.1  christos     python_excp_full,
     53   1.1  christos     python_excp_message,
     54   1.1  christos     NULL
     55   1.1  christos   };
     56   1.1  christos 
     57   1.1  christos /* The exception printing variable.  'full' if we want to print the
     58   1.1  christos    error message and stack, 'none' if we want to print nothing, and
     59   1.1  christos    'message' if we only want to print the error message.  'message' is
     60   1.1  christos    the default.  */
     61   1.1  christos static const char *gdbpy_should_print_stack = python_excp_message;
     62   1.1  christos 
     63   1.3  christos 
     64   1.3  christos #ifdef HAVE_PYTHON
     66   1.1  christos 
     67   1.1  christos #include "cli/cli-decode.h"
     68   1.1  christos #include "charset.h"
     69  1.11  christos #include "top.h"
     70   1.1  christos #include "ui.h"
     71   1.1  christos #include "python-internal.h"
     72   1.1  christos #include "linespec.h"
     73   1.9  christos #include "source.h"
     74   1.1  christos #include "gdbsupport/version.h"
     75   1.1  christos #include "target.h"
     76   1.1  christos #include "gdbthread.h"
     77   1.1  christos #include "interps.h"
     78   1.7  christos #include "event-top.h"
     79   1.1  christos #include "py-event.h"
     80   1.1  christos 
     81   1.1  christos /* True if Python has been successfully initialized, false
     82   1.1  christos    otherwise.  */
     83   1.1  christos 
     84   1.1  christos int gdb_python_initialized;
     85   1.5  christos 
     86   1.1  christos extern PyMethodDef python_GdbMethods[];
     87   1.1  christos 
     88   1.1  christos PyObject *gdb_module;
     89   1.1  christos PyObject *gdb_python_module;
     90   1.1  christos 
     91   1.1  christos /* Some string constants we may wish to use.  */
     92   1.1  christos PyObject *gdbpy_to_string_cst;
     93   1.1  christos PyObject *gdbpy_children_cst;
     94   1.1  christos PyObject *gdbpy_display_hint_cst;
     95   1.1  christos PyObject *gdbpy_doc_cst;
     96   1.1  christos PyObject *gdbpy_enabled_cst;
     97   1.1  christos PyObject *gdbpy_value_cst;
     98   1.1  christos 
     99   1.1  christos /* The GdbError exception.  */
    100   1.1  christos PyObject *gdbpy_gdberror_exc;
    101   1.1  christos 
    102   1.1  christos /* The `gdb.error' base class.  */
    103   1.1  christos PyObject *gdbpy_gdb_error;
    104   1.1  christos 
    105   1.1  christos /* The `gdb.MemoryError' exception.  */
    106   1.1  christos PyObject *gdbpy_gdb_memory_error;
    107   1.3  christos 
    108   1.3  christos static script_sourcer_func gdbpy_source_script;
    109   1.5  christos static objfile_script_sourcer_func gdbpy_source_objfile_script;
    110  1.10  christos static objfile_script_executor_func gdbpy_execute_objfile_script;
    111   1.3  christos static void gdbpy_initialize (const struct extension_language_defn *);
    112  1.11  christos static int gdbpy_initialized (const struct extension_language_defn *);
    113   1.3  christos static void finalize_python (const struct extension_language_defn *);
    114   1.3  christos static void gdbpy_eval_from_control_command
    115   1.3  christos   (const struct extension_language_defn *, struct command_line *cmd);
    116   1.3  christos static void gdbpy_start_type_printers (const struct extension_language_defn *,
    117   1.3  christos 				       struct ext_lang_type_printers *);
    118   1.3  christos static enum ext_lang_rc gdbpy_apply_type_printers
    119  1.11  christos   (const struct extension_language_defn *,
    120  1.11  christos    const struct ext_lang_type_printers *, struct type *,
    121   1.3  christos    gdb::unique_xmalloc_ptr<char> *);
    122   1.3  christos static void gdbpy_free_type_printers (const struct extension_language_defn *,
    123   1.3  christos 				      struct ext_lang_type_printers *);
    124  1.11  christos static void gdbpy_set_quit_flag (const struct extension_language_defn *);
    125   1.3  christos static bool gdbpy_check_quit_flag (const struct extension_language_defn *);
    126   1.3  christos static enum ext_lang_rc gdbpy_before_prompt_hook
    127  1.11  christos   (const struct extension_language_defn *, const char *current_gdb_prompt);
    128   1.9  christos static std::optional<std::string> gdbpy_colorize
    129  1.11  christos   (const std::string &filename, const std::string &contents);
    130  1.11  christos static std::optional<std::string> gdbpy_colorize_disasm
    131  1.11  christos (const std::string &content, gdbarch *gdbarch);
    132  1.11  christos static ext_lang_missing_debuginfo_result gdbpy_handle_missing_debuginfo
    133   1.3  christos   (const struct extension_language_defn *extlang, struct objfile *objfile);
    134   1.3  christos 
    135   1.3  christos /* The interface between gdb proper and loading of python scripts.  */
    136  1.10  christos 
    137   1.3  christos static const struct extension_language_script_ops python_extension_script_ops =
    138   1.3  christos {
    139   1.3  christos   gdbpy_source_script,
    140   1.5  christos   gdbpy_source_objfile_script,
    141   1.3  christos   gdbpy_execute_objfile_script,
    142   1.3  christos   gdbpy_auto_load_enabled
    143   1.3  christos };
    144   1.3  christos 
    145   1.3  christos /* The interface between gdb proper and python extensions.  */
    146  1.10  christos 
    147   1.3  christos static const struct extension_language_ops python_extension_ops =
    148  1.10  christos {
    149   1.3  christos   gdbpy_initialize,
    150  1.11  christos   gdbpy_initialized,
    151   1.3  christos   finalize_python,
    152   1.3  christos 
    153   1.3  christos   gdbpy_eval_from_control_command,
    154   1.3  christos 
    155   1.3  christos   gdbpy_start_type_printers,
    156   1.3  christos   gdbpy_apply_type_printers,
    157   1.3  christos   gdbpy_free_type_printers,
    158   1.3  christos 
    159   1.3  christos   gdbpy_apply_val_pretty_printer,
    160   1.3  christos 
    161   1.3  christos   gdbpy_apply_frame_filter,
    162   1.3  christos 
    163   1.3  christos   gdbpy_preserve_values,
    164   1.3  christos 
    165   1.3  christos   gdbpy_breakpoint_has_cond,
    166   1.3  christos   gdbpy_breakpoint_cond_says_stop,
    167   1.3  christos 
    168   1.3  christos   gdbpy_set_quit_flag,
    169   1.3  christos   gdbpy_check_quit_flag,
    170   1.3  christos 
    171   1.3  christos   gdbpy_before_prompt_hook,
    172   1.3  christos 
    173   1.9  christos   gdbpy_get_matching_xmethod_workers,
    174   1.9  christos 
    175  1.10  christos   gdbpy_colorize,
    176  1.10  christos 
    177  1.10  christos   gdbpy_colorize_disasm,
    178  1.10  christos 
    179  1.11  christos   gdbpy_print_insn,
    180  1.11  christos 
    181   1.3  christos   gdbpy_handle_missing_debuginfo
    182   1.3  christos };
    183  1.10  christos 
    184  1.10  christos #endif /* HAVE_PYTHON */
    185  1.10  christos 
    186  1.10  christos /* The main struct describing GDB's interface to the Python
    187  1.10  christos    extension language.  */
    188  1.10  christos const struct extension_language_defn extension_language_python =
    189  1.10  christos {
    190  1.10  christos   EXT_LANG_PYTHON,
    191  1.10  christos   "python",
    192  1.10  christos   "Python",
    193  1.10  christos 
    194  1.10  christos   ".py",
    195  1.10  christos   "-gdb.py",
    196  1.10  christos 
    197  1.10  christos   python_control,
    198  1.10  christos 
    199  1.10  christos #ifdef HAVE_PYTHON
    200  1.10  christos   &python_extension_script_ops,
    201  1.10  christos   &python_extension_ops
    202  1.10  christos #else
    203  1.10  christos   NULL,
    204  1.10  christos   NULL
    205  1.10  christos #endif
    206  1.10  christos };
    207  1.10  christos 
    208  1.10  christos #ifdef HAVE_PYTHON
    209   1.1  christos 
    210   1.1  christos /* Architecture and language to be used in callbacks from
    211  1.10  christos    the Python interpreter.  */
    212   1.1  christos struct gdbarch *gdbpy_enter::python_gdbarch;
    213   1.7  christos 
    214   1.7  christos gdbpy_enter::gdbpy_enter  (struct gdbarch *gdbarch,
    215   1.7  christos 			   const struct language_defn *language)
    216  1.10  christos : m_gdbarch (python_gdbarch),
    217   1.7  christos   m_language (language == nullptr ? nullptr : current_language)
    218   1.7  christos {
    219   1.7  christos   /* We should not ever enter Python unless initialized.  */
    220   1.7  christos   if (!gdb_python_initialized)
    221   1.7  christos     error (_("Python not initialized"));
    222   1.7  christos 
    223   1.7  christos   m_previous_active = set_active_ext_lang (&extension_language_python);
    224   1.7  christos 
    225   1.7  christos   m_state = PyGILState_Ensure ();
    226   1.7  christos 
    227  1.10  christos   python_gdbarch = gdbarch;
    228  1.10  christos   if (language != nullptr)
    229   1.1  christos     set_language (language->la_language);
    230   1.7  christos 
    231   1.8  christos   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
    232   1.7  christos   m_error.emplace ();
    233   1.1  christos }
    234   1.7  christos 
    235   1.1  christos gdbpy_enter::~gdbpy_enter ()
    236   1.1  christos {
    237   1.1  christos   /* Leftover Python error is forbidden by Python Exception Handling.  */
    238   1.1  christos   if (PyErr_Occurred ())
    239   1.1  christos     {
    240   1.1  christos       /* This order is similar to the one calling error afterwards. */
    241   1.1  christos       gdbpy_print_stack ();
    242   1.1  christos       warning (_("internal error: Unhandled Python exception"));
    243   1.1  christos     }
    244   1.8  christos 
    245   1.3  christos   m_error->restore ();
    246   1.7  christos 
    247  1.10  christos   python_gdbarch = m_gdbarch;
    248  1.10  christos   if (m_language != nullptr)
    249   1.3  christos     set_language (m_language->la_language);
    250   1.7  christos 
    251   1.9  christos   restore_active_ext_lang (m_previous_active);
    252   1.1  christos   PyGILState_Release (m_state);
    253   1.1  christos }
    254  1.10  christos 
    255  1.10  christos struct gdbarch *
    256  1.10  christos gdbpy_enter::get_gdbarch ()
    257  1.10  christos {
    258  1.10  christos   if (python_gdbarch != nullptr)
    259  1.10  christos     return python_gdbarch;
    260  1.10  christos   return get_current_arch ();
    261  1.10  christos }
    262  1.10  christos 
    263  1.10  christos void
    264  1.10  christos gdbpy_enter::finalize ()
    265  1.11  christos {
    266  1.10  christos   python_gdbarch = current_inferior ()->arch ();
    267  1.10  christos }
    268   1.1  christos 
    269   1.1  christos /* Set the quit flag.  */
    270   1.3  christos 
    271   1.3  christos static void
    272   1.1  christos gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
    273   1.1  christos {
    274   1.1  christos   PyErr_SetInterrupt ();
    275   1.1  christos }
    276   1.1  christos 
    277   1.1  christos /* Return true if the quit flag has been set, false otherwise.  */
    278  1.11  christos 
    279   1.3  christos static bool
    280   1.1  christos gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
    281   1.9  christos {
    282  1.11  christos   if (!gdb_python_initialized)
    283   1.9  christos     return false;
    284   1.9  christos 
    285   1.1  christos   gdbpy_gil gil;
    286   1.1  christos   return PyOS_InterruptOccurred ();
    287   1.1  christos }
    288  1.11  christos 
    289  1.11  christos /* Evaluate a Python command like PyRun_SimpleString, but takes a
    290  1.11  christos    Python start symbol, and does not automatically print the stack on
    291  1.11  christos    errors.  FILENAME is used to set the file name in error messages;
    292  1.11  christos    NULL means that this is evaluating a string, not the contents of a
    293   1.1  christos    file.  */
    294   1.1  christos 
    295  1.11  christos static int
    296  1.11  christos eval_python_command (const char *command, int start_symbol,
    297   1.1  christos 		     const char *filename = nullptr)
    298   1.7  christos {
    299   1.1  christos   PyObject *m, *d;
    300   1.1  christos 
    301   1.1  christos   m = PyImport_AddModule ("__main__");
    302   1.1  christos   if (m == NULL)
    303   1.1  christos     return -1;
    304   1.1  christos 
    305   1.1  christos   d = PyModule_GetDict (m);
    306   1.1  christos   if (d == NULL)
    307   1.1  christos     return -1;
    308  1.11  christos 
    309  1.11  christos   bool file_set = false;
    310  1.11  christos   if (filename != nullptr)
    311  1.11  christos     {
    312  1.11  christos       gdbpy_ref<> file = host_string_to_python_string ("__file__");
    313  1.11  christos       if (file == nullptr)
    314  1.11  christos 	return -1;
    315  1.11  christos 
    316  1.11  christos       /* PyDict_GetItemWithError returns a borrowed reference.  */
    317  1.11  christos       PyObject *found = PyDict_GetItemWithError (d, file.get ());
    318  1.11  christos       if (found == nullptr)
    319  1.11  christos 	{
    320  1.11  christos 	  if (PyErr_Occurred ())
    321  1.11  christos 	    return -1;
    322  1.11  christos 
    323  1.11  christos 	  gdbpy_ref<> filename_obj = host_string_to_python_string (filename);
    324  1.11  christos 	  if (filename_obj == nullptr)
    325  1.11  christos 	    return -1;
    326  1.11  christos 
    327  1.11  christos 	  if (PyDict_SetItem (d, file.get (), filename_obj.get ()) < 0)
    328  1.11  christos 	    return -1;
    329  1.11  christos 	  if (PyDict_SetItemString (d, "__cached__", Py_None) < 0)
    330  1.11  christos 	    return -1;
    331  1.11  christos 
    332  1.11  christos 	  file_set = true;
    333  1.11  christos 	}
    334  1.11  christos     }
    335  1.11  christos 
    336  1.11  christos   /* Use this API because it is in Python 3.2.  */
    337  1.11  christos   gdbpy_ref<> code (Py_CompileStringExFlags (command,
    338  1.11  christos 					     filename == nullptr
    339  1.11  christos 					     ? "<string>"
    340  1.11  christos 					     : filename,
    341  1.11  christos 					     start_symbol,
    342  1.11  christos 					     nullptr, -1));
    343  1.11  christos 
    344  1.11  christos   int result = -1;
    345  1.11  christos   if (code != nullptr)
    346  1.11  christos     {
    347  1.11  christos       gdbpy_ref<> eval_result (PyEval_EvalCode (code.get (), d, d));
    348  1.11  christos       if (eval_result != nullptr)
    349  1.11  christos 	result = 0;
    350  1.11  christos     }
    351  1.11  christos 
    352  1.11  christos   if (file_set)
    353  1.11  christos     {
    354  1.11  christos       /* If there's already an exception occurring, preserve it and
    355  1.11  christos 	 restore it before returning from this function.  */
    356  1.11  christos       std::optional<gdbpy_err_fetch> save_error;
    357  1.11  christos       if (result < 0)
    358  1.11  christos 	save_error.emplace ();
    359  1.11  christos 
    360  1.11  christos       /* CPython also just ignores errors here.  These should be
    361  1.11  christos 	 expected to be exceedingly rare anyway.  */
    362  1.11  christos       if (PyDict_DelItemString (d, "__file__") < 0)
    363  1.11  christos 	PyErr_Clear ();
    364  1.11  christos       if (PyDict_DelItemString (d, "__cached__") < 0)
    365  1.11  christos 	PyErr_Clear ();
    366  1.11  christos 
    367  1.11  christos       if (save_error.has_value ())
    368  1.11  christos 	save_error->restore ();
    369  1.11  christos     }
    370  1.11  christos 
    371   1.1  christos   return result;
    372   1.1  christos }
    373   1.1  christos 
    374   1.1  christos /* Implementation of the gdb "python-interactive" command.  */
    375   1.1  christos 
    376   1.8  christos static void
    377   1.1  christos python_interactive_command (const char *arg, int from_tty)
    378   1.6  christos {
    379   1.1  christos   struct ui *ui = current_ui;
    380   1.1  christos   int err;
    381   1.7  christos 
    382   1.1  christos   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    383   1.1  christos 
    384   1.1  christos   arg = skip_spaces (arg);
    385  1.10  christos 
    386   1.1  christos   gdbpy_enter enter_py;
    387   1.1  christos 
    388   1.1  christos   if (arg && *arg)
    389   1.8  christos     {
    390  1.11  christos       std::string script = std::string (arg) + "\n";
    391  1.11  christos       /* Py_single_input causes the result to be displayed.  */
    392   1.1  christos       err = eval_python_command (script.c_str (), Py_single_input);
    393   1.1  christos     }
    394   1.1  christos   else
    395   1.6  christos     {
    396   1.1  christos       err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
    397   1.1  christos       dont_repeat ();
    398   1.1  christos     }
    399   1.1  christos 
    400  1.11  christos   if (err)
    401   1.1  christos     gdbpy_handle_exception ();
    402   1.1  christos }
    403  1.11  christos 
    404  1.11  christos /* Like PyRun_SimpleFile, but if there is an exception, it is not
    405  1.11  christos    automatically displayed.  FILE is the Python script to run named
    406   1.1  christos    FILENAME.
    407   1.1  christos 
    408   1.1  christos    On Windows hosts few users would build Python themselves (this is no
    409   1.1  christos    trivial task on this platform), and thus use binaries built by
    410   1.1  christos    someone else instead.  There may happen situation where the Python
    411   1.1  christos    library and GDB are using two different versions of the C runtime
    412   1.1  christos    library.  Python, being built with VC, would use one version of the
    413   1.1  christos    msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
    414  1.11  christos    A FILE * from one runtime does not necessarily operate correctly in
    415   1.1  christos    the other runtime.  */
    416  1.11  christos 
    417   1.1  christos static int
    418   1.1  christos python_run_simple_file (FILE *file, const char *filename)
    419  1.11  christos {
    420  1.11  christos   std::string contents = read_remainder_of_file (file);
    421   1.1  christos   return eval_python_command (contents.c_str (), Py_file_input, filename);
    422   1.1  christos }
    423   1.1  christos 
    424   1.8  christos /* Given a command_line, return a command string suitable for passing
    425   1.1  christos    to Python.  Lines in the string are separated by newlines.  */
    426   1.8  christos 
    427   1.1  christos static std::string
    428   1.1  christos compute_python_string (struct command_line *l)
    429   1.1  christos {
    430   1.8  christos   struct command_line *iter;
    431   1.1  christos   std::string script;
    432   1.1  christos 
    433   1.1  christos   for (iter = l; iter; iter = iter->next)
    434   1.8  christos     {
    435   1.8  christos       script += iter->line;
    436   1.1  christos       script += '\n';
    437   1.1  christos     }
    438   1.1  christos   return script;
    439   1.1  christos }
    440   1.1  christos 
    441   1.1  christos /* Take a command line structure representing a 'python' command, and
    442   1.1  christos    evaluate its body using the Python interpreter.  */
    443   1.3  christos 
    444   1.3  christos static void
    445   1.3  christos gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
    446   1.1  christos 				 struct command_line *cmd)
    447   1.8  christos {
    448   1.1  christos   if (cmd->body_list_1 != nullptr)
    449   1.1  christos     error (_("Invalid \"python\" block structure."));
    450  1.10  christos 
    451   1.1  christos   gdbpy_enter enter_py;
    452   1.8  christos 
    453  1.11  christos   std::string script = compute_python_string (cmd->body_list_0.get ());
    454  1.11  christos   int ret = eval_python_command (script.c_str (), Py_file_input);
    455  1.11  christos   if (ret != 0)
    456   1.1  christos     gdbpy_handle_exception ();
    457   1.1  christos }
    458   1.1  christos 
    459   1.1  christos /* Implementation of the gdb "python" command.  */
    460   1.1  christos 
    461   1.8  christos static void
    462   1.1  christos python_command (const char *arg, int from_tty)
    463  1.10  christos {
    464   1.1  christos   gdbpy_enter enter_py;
    465   1.7  christos 
    466   1.1  christos   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    467   1.1  christos 
    468   1.1  christos   arg = skip_spaces (arg);
    469   1.1  christos   if (arg && *arg)
    470  1.11  christos     {
    471  1.11  christos       int ret = eval_python_command (arg, Py_file_input);
    472  1.11  christos       if (ret != 0)
    473   1.1  christos 	gdbpy_handle_exception ();
    474   1.1  christos     }
    475   1.1  christos   else
    476   1.8  christos     {
    477   1.1  christos       counted_command_line l = get_command_line (python_control, "");
    478   1.7  christos 
    479   1.1  christos       execute_control_command_untraced (l.get ());
    480   1.1  christos     }
    481   1.1  christos }
    482   1.1  christos 
    483   1.1  christos 
    484   1.1  christos 
    486   1.1  christos /* Transform a gdb parameters's value into a Python value.  May return
    487   1.1  christos    NULL (and set a Python exception) on error.  Helper function for
    488  1.10  christos    get_parameter.  */
    489   1.1  christos PyObject *
    490  1.10  christos gdbpy_parameter_value (const setting &var)
    491   1.1  christos {
    492   1.1  christos   switch (var.type ())
    493   1.1  christos     {
    494   1.1  christos     case var_string:
    495   1.1  christos     case var_string_noescape:
    496   1.1  christos     case var_optional_filename:
    497   1.1  christos     case var_filename:
    498  1.10  christos     case var_enum:
    499  1.10  christos       {
    500  1.10  christos 	const char *str;
    501  1.10  christos 	if (var.type () == var_enum)
    502  1.10  christos 	  str = var.get<const char *> ();
    503   1.1  christos 	else
    504   1.8  christos 	  str = var.get<std::string> ().c_str ();
    505   1.1  christos 
    506   1.1  christos 	return host_string_to_python_string (str).release ();
    507   1.1  christos       }
    508   1.1  christos 
    509  1.10  christos     case var_boolean:
    510   1.1  christos       {
    511   1.1  christos 	if (var.get<bool> ())
    512   1.1  christos 	  Py_RETURN_TRUE;
    513   1.1  christos 	else
    514   1.1  christos 	  Py_RETURN_FALSE;
    515   1.1  christos       }
    516   1.1  christos 
    517  1.10  christos     case var_auto_boolean:
    518   1.1  christos       {
    519   1.1  christos 	enum auto_boolean ab = var.get<enum auto_boolean> ();
    520   1.1  christos 
    521   1.1  christos 	if (ab == AUTO_BOOLEAN_TRUE)
    522   1.1  christos 	  Py_RETURN_TRUE;
    523   1.1  christos 	else if (ab == AUTO_BOOLEAN_FALSE)
    524   1.1  christos 	  Py_RETURN_FALSE;
    525   1.1  christos 	else
    526   1.1  christos 	  Py_RETURN_NONE;
    527  1.11  christos       }
    528   1.1  christos 
    529  1.11  christos     case var_uinteger:
    530   1.1  christos     case var_integer:
    531  1.11  christos     case var_pinteger:
    532  1.11  christos       {
    533  1.11  christos 	LONGEST value
    534  1.11  christos 	  = (var.type () == var_uinteger
    535  1.11  christos 	     ? static_cast<LONGEST> (var.get<unsigned int> ())
    536  1.11  christos 	     : static_cast<LONGEST> (var.get<int> ()));
    537  1.11  christos 
    538  1.11  christos 	if (var.extra_literals () != nullptr)
    539  1.11  christos 	  for (const literal_def *l = var.extra_literals ();
    540  1.11  christos 	       l->literal != nullptr;
    541  1.11  christos 	       l++)
    542  1.11  christos 	    if (value == l->use)
    543  1.11  christos 	      {
    544  1.11  christos 		if (strcmp (l->literal, "unlimited") == 0)
    545  1.11  christos 		  {
    546  1.11  christos 		    /* Compatibility hack for API brokenness.  */
    547  1.11  christos 		    if (var.type () == var_pinteger
    548  1.11  christos 			&& l->val.has_value ()
    549  1.11  christos 			&& *l->val == -1)
    550  1.11  christos 		      value = -1;
    551  1.11  christos 		    else
    552  1.11  christos 		      Py_RETURN_NONE;
    553  1.11  christos 		  }
    554  1.11  christos 		else if (l->val.has_value ())
    555  1.11  christos 		  value = *l->val;
    556  1.11  christos 		else
    557  1.11  christos 		  return host_string_to_python_string (l->literal).release ();
    558  1.11  christos 	      }
    559  1.11  christos 
    560  1.11  christos 	if (var.type () == var_uinteger)
    561  1.11  christos 	  return
    562  1.11  christos 	    gdb_py_object_from_ulongest
    563  1.11  christos 	      (static_cast<unsigned int> (value)).release ();
    564  1.11  christos 	else
    565  1.11  christos 	  return
    566   1.8  christos 	    gdb_py_object_from_longest
    567   1.1  christos 	      (static_cast<int> (value)).release ();
    568   1.1  christos       }
    569   1.1  christos     }
    570   1.1  christos 
    571   1.1  christos   return PyErr_Format (PyExc_RuntimeError,
    572   1.1  christos 		       _("Programmer error: unhandled type."));
    573   1.1  christos }
    574   1.1  christos 
    575   1.1  christos /* A Python function which returns a gdb parameter's value as a Python
    576   1.6  christos    value.  */
    577   1.1  christos 
    578   1.1  christos static PyObject *
    579   1.1  christos gdbpy_parameter (PyObject *self, PyObject *args)
    580   1.1  christos {
    581   1.1  christos   struct cmd_list_element *alias, *prefix, *cmd;
    582   1.1  christos   const char *arg;
    583   1.1  christos   int found = -1;
    584   1.1  christos 
    585   1.1  christos   if (! PyArg_ParseTuple (args, "s", &arg))
    586   1.8  christos     return NULL;
    587   1.1  christos 
    588   1.9  christos   std::string newarg = std::string ("show ") + arg;
    589   1.1  christos 
    590   1.8  christos   try
    591   1.1  christos     {
    592   1.9  christos       found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
    593   1.5  christos     }
    594   1.8  christos   catch (const gdb_exception &ex)
    595   1.5  christos     {
    596   1.5  christos       GDB_PY_HANDLE_EXCEPTION (ex);
    597  1.11  christos     }
    598  1.11  christos 
    599  1.11  christos   if (cmd == CMD_LIST_AMBIGUOUS)
    600  1.11  christos     return PyErr_Format (PyExc_RuntimeError,
    601   1.1  christos 			 _("Parameter `%s' is ambiguous."), arg);
    602   1.1  christos   else if (!found)
    603   1.1  christos     return PyErr_Format (PyExc_RuntimeError,
    604  1.10  christos 			 _("Could not find parameter `%s'."), arg);
    605   1.1  christos 
    606   1.1  christos   if (!cmd->var.has_value ())
    607  1.10  christos     return PyErr_Format (PyExc_RuntimeError,
    608  1.10  christos 			 _("`%s' is not a parameter."), arg);
    609   1.1  christos 
    610   1.1  christos   return gdbpy_parameter_value (*cmd->var);
    611   1.1  christos }
    612   1.1  christos 
    613   1.1  christos /* Wrapper for target_charset.  */
    614   1.1  christos 
    615   1.1  christos static PyObject *
    616  1.10  christos gdbpy_target_charset (PyObject *self, PyObject *args)
    617   1.1  christos {
    618   1.1  christos   const char *cset = target_charset (gdbpy_enter::get_gdbarch ());
    619   1.1  christos 
    620   1.1  christos   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
    621   1.1  christos }
    622   1.1  christos 
    623   1.1  christos /* Wrapper for target_wide_charset.  */
    624   1.1  christos 
    625   1.1  christos static PyObject *
    626  1.10  christos gdbpy_target_wide_charset (PyObject *self, PyObject *args)
    627  1.10  christos {
    628  1.10  christos   const char *cset = target_wide_charset (gdbpy_enter::get_gdbarch ());
    629  1.10  christos 
    630  1.10  christos   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
    631  1.10  christos }
    632  1.10  christos 
    633  1.10  christos /* Implement gdb.host_charset().  */
    634  1.10  christos 
    635  1.10  christos static PyObject *
    636  1.10  christos gdbpy_host_charset (PyObject *self, PyObject *args)
    637   1.1  christos {
    638   1.1  christos   const char *cset = host_charset ();
    639   1.1  christos 
    640   1.1  christos   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
    641   1.1  christos }
    642   1.1  christos 
    643   1.1  christos /* A Python function which evaluates a string using the gdb CLI.  */
    644   1.1  christos 
    645   1.1  christos static PyObject *
    646   1.1  christos execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
    647  1.11  christos {
    648  1.11  christos   const char *arg;
    649  1.11  christos   PyObject *from_tty_obj = nullptr;
    650  1.11  christos   PyObject *to_string_obj = nullptr;
    651   1.1  christos   static const char *keywords[] = { "command", "from_tty", "to_string",
    652   1.7  christos 				    nullptr };
    653   1.7  christos 
    654   1.7  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
    655  1.11  christos 					&PyBool_Type, &from_tty_obj,
    656   1.1  christos 					&PyBool_Type, &to_string_obj))
    657  1.11  christos     return nullptr;
    658  1.11  christos 
    659   1.1  christos   bool from_tty = false;
    660   1.1  christos   if (from_tty_obj != nullptr)
    661   1.1  christos     {
    662  1.11  christos       int cmp = PyObject_IsTrue (from_tty_obj);
    663  1.11  christos       if (cmp < 0)
    664   1.1  christos 	return nullptr;
    665   1.1  christos       from_tty = (cmp != 0);
    666  1.11  christos     }
    667  1.11  christos 
    668   1.1  christos   bool to_string = false;
    669   1.1  christos   if (to_string_obj != nullptr)
    670   1.1  christos     {
    671  1.11  christos       int cmp = PyObject_IsTrue (to_string_obj);
    672  1.11  christos       if (cmp < 0)
    673   1.1  christos 	return nullptr;
    674   1.1  christos       to_string = (cmp != 0);
    675   1.7  christos     }
    676   1.7  christos 
    677   1.8  christos   std::string to_string_res;
    678   1.8  christos 
    679  1.11  christos   scoped_restore preventer = prevent_dont_repeat ();
    680  1.11  christos 
    681  1.11  christos   /* If the executed command raises an exception, we may have to
    682  1.11  christos      enable stdin and recover the GDB prompt.
    683  1.11  christos 
    684  1.11  christos      Stdin should not be re-enabled if it is already blocked because,
    685  1.11  christos      for example, we are running a command in the context of a
    686  1.11  christos      synchronous execution command ("run", "continue", etc.).  Like
    687  1.11  christos      this:
    688  1.11  christos 
    689  1.11  christos      User runs "continue"
    690  1.11  christos      --> command blocks the prompt
    691  1.11  christos      --> Python API is invoked, e.g.  via events
    692  1.11  christos      --> gdb.execute(C) invoked inside Python
    693  1.11  christos      --> command C raises an exception
    694  1.11  christos 
    695  1.11  christos      In this case case, GDB would go back to the top "continue" command
    696  1.11  christos      and move on with its normal course of execution.  That is, it
    697  1.11  christos      would enable stdin in the way it normally does.
    698  1.11  christos 
    699  1.11  christos      Similarly, if the command we are about to execute enables the
    700  1.11  christos      stdin while we are still in the context of a synchronous
    701  1.11  christos      execution command, we would be displaying the prompt too early,
    702  1.11  christos      before the surrounding command completes.
    703  1.11  christos 
    704  1.11  christos      For these reasons, we keep the prompt blocked, if it already is.  */
    705  1.11  christos   bool prompt_was_blocked = (current_ui->prompt_state == PROMPT_BLOCKED);
    706  1.11  christos   scoped_restore save_prompt_state
    707  1.11  christos     = make_scoped_restore (&current_ui->keep_prompt_blocked,
    708   1.9  christos 			   prompt_was_blocked);
    709   1.1  christos 
    710   1.8  christos   try
    711   1.8  christos     {
    712   1.6  christos       gdbpy_allow_threads allow_threads;
    713   1.6  christos 
    714   1.8  christos       struct interp *interp;
    715   1.8  christos 
    716   1.8  christos       std::string arg_copy = arg;
    717   1.8  christos       bool first = true;
    718  1.10  christos       char *save_ptr = nullptr;
    719   1.8  christos       auto reader
    720   1.8  christos 	= [&] (std::string &buffer)
    721   1.8  christos 	  {
    722   1.8  christos 	    const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
    723   1.8  christos 					   "\n", &save_ptr);
    724   1.8  christos 	    first = false;
    725   1.8  christos 	    return result;
    726   1.8  christos 	  };
    727   1.8  christos 
    728   1.8  christos       counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
    729   1.8  christos 
    730   1.8  christos       {
    731   1.8  christos 	scoped_restore save_async = make_scoped_restore (&current_ui->async,
    732   1.8  christos 							 0);
    733   1.6  christos 
    734   1.8  christos 	scoped_restore save_uiout = make_scoped_restore (&current_uiout);
    735   1.8  christos 
    736   1.8  christos 	/* Use the console interpreter uiout to have the same print format
    737   1.8  christos 	   for console or MI.  */
    738   1.8  christos 	interp = interp_lookup (current_ui, "console");
    739   1.8  christos 	current_uiout = interp->interp_ui_out ();
    740   1.8  christos 
    741   1.8  christos 	if (to_string)
    742   1.8  christos 	  to_string_res = execute_control_commands_to_string (lines.get (),
    743   1.8  christos 							      from_tty);
    744   1.8  christos 	else
    745   1.1  christos 	  execute_control_commands (lines.get (), from_tty);
    746   1.8  christos       }
    747   1.8  christos 
    748   1.1  christos       /* Do any commands attached to breakpoint we stopped at.  */
    749   1.9  christos       bpstat_do_actions ();
    750   1.5  christos     }
    751   1.9  christos   catch (const gdb_exception &except)
    752   1.9  christos     {
    753   1.9  christos       /* If an exception occurred then we won't hit normal_stop (), or have
    754   1.9  christos 	 an exception reach the top level of the event loop, which are the
    755   1.9  christos 	 two usual places in which stdin would be re-enabled. So, before we
    756   1.9  christos 	 convert the exception and continue back in Python, we should
    757   1.5  christos 	 re-enable stdin here.  */
    758   1.5  christos       async_enable_stdin ();
    759   1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
    760   1.7  christos     }
    761  1.10  christos 
    762   1.1  christos   if (to_string)
    763   1.1  christos     return PyUnicode_FromString (to_string_res.c_str ());
    764   1.1  christos   Py_RETURN_NONE;
    765   1.8  christos }
    766   1.8  christos 
    767   1.8  christos /* Implementation of Python rbreak command.  Take a REGEX and
    768   1.8  christos    optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
    769   1.8  christos    Python list that contains newly set breakpoints that match that
    770   1.8  christos    criteria.  REGEX refers to a GDB format standard regex pattern of
    771   1.8  christos    symbols names to search; MINSYMS is an optional boolean (default
    772   1.8  christos    False) that indicates if the function should search GDB's minimal
    773   1.8  christos    symbols; THROTTLE is an optional integer (default unlimited) that
    774   1.8  christos    indicates the maximum amount of breakpoints allowable before the
    775   1.8  christos    function exits (note, if the throttle bound is passed, no
    776   1.8  christos    breakpoints will be set and a runtime error returned); SYMTABS is
    777   1.1  christos    an optional Python iterable that contains a set of gdb.Symtabs to
    778   1.1  christos    constrain the search within.  */
    779   1.8  christos 
    780   1.1  christos static PyObject *
    781   1.8  christos gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
    782   1.8  christos {
    783   1.8  christos   char *regex = NULL;
    784   1.8  christos   std::vector<symbol_search> symbols;
    785   1.8  christos   unsigned long count = 0;
    786   1.8  christos   PyObject *symtab_list = NULL;
    787   1.8  christos   PyObject *minsyms_p_obj = NULL;
    788   1.8  christos   int minsyms_p = 0;
    789   1.8  christos   unsigned int throttle = 0;
    790   1.8  christos   static const char *keywords[] = {"regex","minsyms", "throttle",
    791   1.8  christos 				   "symtabs", NULL};
    792   1.8  christos 
    793   1.8  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
    794   1.8  christos 					&regex, &PyBool_Type,
    795   1.1  christos 					&minsyms_p_obj, &throttle,
    796   1.1  christos 					&symtab_list))
    797   1.8  christos     return NULL;
    798   1.8  christos 
    799   1.8  christos   /* Parse minsyms keyword.  */
    800   1.8  christos   if (minsyms_p_obj != NULL)
    801   1.8  christos     {
    802   1.8  christos       int cmp = PyObject_IsTrue (minsyms_p_obj);
    803   1.8  christos       if (cmp < 0)
    804   1.8  christos 	return NULL;
    805   1.8  christos       minsyms_p = cmp;
    806  1.11  christos     }
    807   1.9  christos 
    808   1.9  christos   global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regex);
    809   1.9  christos   SCOPE_EXIT {
    810   1.9  christos     for (const char *elem : spec.filenames)
    811   1.9  christos       xfree ((void *) elem);
    812   1.8  christos   };
    813   1.8  christos 
    814   1.8  christos   /* The "symtabs" keyword is any Python iterable object that returns
    815   1.8  christos      a gdb.Symtab on each iteration.  If specified, iterate through
    816   1.8  christos      the provided gdb.Symtabs and extract their full path.  As
    817   1.8  christos      python_string_to_target_string returns a
    818   1.8  christos      gdb::unique_xmalloc_ptr<char> and a vector containing these types
    819   1.8  christos      cannot be coerced to a const char **p[] via the vector.data call,
    820   1.8  christos      release the value from the unique_xmalloc_ptr and place it in a
    821   1.8  christos      simple type symtab_list_type (which holds the vector and a
    822   1.8  christos      destructor that frees the contents of the allocated strings.  */
    823   1.8  christos   if (symtab_list != NULL)
    824   1.8  christos     {
    825   1.8  christos       gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
    826   1.8  christos 
    827   1.8  christos       if (iter == NULL)
    828   1.8  christos 	return NULL;
    829   1.8  christos 
    830   1.8  christos       while (true)
    831   1.8  christos 	{
    832   1.8  christos 	  gdbpy_ref<> next (PyIter_Next (iter.get ()));
    833   1.8  christos 
    834   1.8  christos 	  if (next == NULL)
    835   1.8  christos 	    {
    836   1.8  christos 	      if (PyErr_Occurred ())
    837   1.8  christos 		return NULL;
    838   1.8  christos 	      break;
    839   1.8  christos 	    }
    840   1.8  christos 
    841   1.8  christos 	  gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
    842   1.8  christos 							"filename"));
    843   1.8  christos 
    844   1.8  christos 	  if (obj_name == NULL)
    845   1.8  christos 	    return NULL;
    846   1.8  christos 
    847   1.8  christos 	  /* Is the object file still valid?  */
    848   1.8  christos 	  if (obj_name == Py_None)
    849   1.8  christos 	    continue;
    850   1.8  christos 
    851   1.8  christos 	  gdb::unique_xmalloc_ptr<char> filename =
    852   1.8  christos 	    python_string_to_target_string (obj_name.get ());
    853   1.8  christos 
    854   1.8  christos 	  if (filename == NULL)
    855   1.8  christos 	    return NULL;
    856   1.8  christos 
    857   1.9  christos 	  /* Make sure there is a definite place to store the value of
    858   1.9  christos 	     filename before it is released.  */
    859   1.8  christos 	  spec.filenames.push_back (nullptr);
    860   1.8  christos 	  spec.filenames.back () = filename.release ();
    861   1.8  christos 	}
    862   1.9  christos     }
    863   1.9  christos 
    864   1.8  christos   /* The search spec.  */
    865   1.8  christos   symbols = spec.search ();
    866   1.8  christos 
    867   1.8  christos   /* Count the number of symbols (both symbols and optionally minimal
    868   1.8  christos      symbols) so we can correctly check the throttle limit.  */
    869   1.8  christos   for (const symbol_search &p : symbols)
    870   1.8  christos     {
    871   1.8  christos       /* Minimal symbols included?  */
    872   1.8  christos       if (minsyms_p)
    873   1.8  christos 	{
    874   1.8  christos 	  if (p.msymbol.minsym != NULL)
    875   1.8  christos 	    count++;
    876   1.8  christos 	}
    877   1.8  christos 
    878   1.8  christos       if (p.symbol != NULL)
    879   1.8  christos 	count++;
    880   1.8  christos     }
    881   1.8  christos 
    882   1.1  christos   /* Check throttle bounds and exit if in excess.  */
    883   1.8  christos   if (throttle != 0 && count > throttle)
    884   1.8  christos     {
    885   1.8  christos       PyErr_SetString (PyExc_RuntimeError,
    886   1.1  christos 		       _("Number of breakpoints exceeds throttled maximum."));
    887   1.1  christos       return NULL;
    888   1.8  christos     }
    889   1.8  christos 
    890   1.8  christos   gdbpy_ref<> return_list (PyList_New (0));
    891   1.8  christos 
    892   1.8  christos   if (return_list == NULL)
    893   1.8  christos     return NULL;
    894   1.8  christos 
    895   1.8  christos   /* Construct full path names for symbols and call the Python
    896   1.8  christos      breakpoint constructor on the resulting names.  Be tolerant of
    897   1.8  christos      individual breakpoint failures.  */
    898   1.8  christos   for (const symbol_search &p : symbols)
    899   1.8  christos     {
    900   1.8  christos       std::string symbol_name;
    901   1.8  christos 
    902   1.8  christos       /* Skipping minimal symbols?  */
    903   1.8  christos       if (minsyms_p == 0)
    904   1.8  christos 	if (p.msymbol.minsym != NULL)
    905   1.8  christos 	  continue;
    906   1.8  christos 
    907  1.10  christos       if (p.msymbol.minsym == NULL)
    908   1.8  christos 	{
    909   1.8  christos 	  struct symtab *symtab = p.symbol->symtab ();
    910   1.8  christos 	  const char *fullname = symtab_to_fullname (symtab);
    911   1.8  christos 
    912   1.9  christos 	  symbol_name = fullname;
    913   1.8  christos 	  symbol_name  += ":";
    914   1.8  christos 	  symbol_name  += p.symbol->linkage_name ();
    915   1.9  christos 	}
    916   1.8  christos       else
    917   1.8  christos 	symbol_name = p.msymbol.minsym->linkage_name ();
    918   1.8  christos 
    919   1.8  christos       gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
    920   1.8  christos       gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
    921   1.8  christos 					    &breakpoint_object_type,
    922   1.8  christos 					    argList.get ()));
    923   1.8  christos 
    924   1.8  christos       /* Tolerate individual breakpoint failures.  */
    925   1.8  christos       if (obj == NULL)
    926   1.8  christos 	gdbpy_print_stack ();
    927   1.8  christos       else
    928   1.8  christos 	{
    929   1.8  christos 	  if (PyList_Append (return_list.get (), obj.get ()) == -1)
    930   1.8  christos 	    return NULL;
    931   1.8  christos 	}
    932   1.1  christos     }
    933   1.1  christos   return return_list.release ();
    934   1.1  christos }
    935   1.1  christos 
    936   1.1  christos /* A Python function which is a wrapper for decode_line_1.  */
    937   1.1  christos 
    938   1.1  christos static PyObject *
    939   1.8  christos gdbpy_decode_line (PyObject *self, PyObject *args)
    940   1.7  christos {
    941   1.7  christos   const char *arg = NULL;
    942  1.10  christos   gdbpy_ref<> result;
    943   1.1  christos   gdbpy_ref<> unparsed;
    944   1.1  christos   location_spec_up locspec;
    945   1.1  christos 
    946   1.1  christos   if (! PyArg_ParseTuple (args, "|s", &arg))
    947   1.9  christos     return NULL;
    948   1.9  christos 
    949   1.9  christos   /* Treat a string consisting of just whitespace the same as
    950   1.9  christos      NULL.  */
    951   1.9  christos   if (arg != NULL)
    952   1.9  christos     {
    953   1.9  christos       arg = skip_spaces (arg);
    954   1.9  christos       if (*arg == '\0')
    955   1.9  christos 	arg = NULL;
    956   1.6  christos     }
    957  1.10  christos 
    958  1.10  christos   if (arg != NULL)
    959   1.6  christos     locspec = string_to_location_spec_basic (&arg, current_language,
    960   1.8  christos 					     symbol_name_match_type::WILD);
    961   1.8  christos 
    962   1.8  christos   std::vector<symtab_and_line> decoded_sals;
    963   1.9  christos   symtab_and_line def_sal;
    964   1.1  christos   gdb::array_view<symtab_and_line> sals;
    965  1.10  christos   try
    966   1.8  christos     {
    967  1.10  christos       if (locspec != NULL)
    968   1.8  christos 	{
    969   1.8  christos 	  decoded_sals = decode_line_1 (locspec.get (), 0, NULL, NULL, 0);
    970   1.1  christos 	  sals = decoded_sals;
    971   1.1  christos 	}
    972   1.1  christos       else
    973   1.8  christos 	{
    974   1.8  christos 	  set_default_source_symtab_and_line ();
    975   1.1  christos 	  def_sal = get_current_source_symtab_and_line ();
    976   1.1  christos 	  sals = def_sal;
    977   1.9  christos 	}
    978   1.5  christos     }
    979   1.1  christos   catch (const gdb_exception &ex)
    980   1.8  christos     {
    981   1.1  christos       /* We know this will always throw.  */
    982   1.1  christos       gdbpy_convert_exception (ex);
    983   1.1  christos       return NULL;
    984   1.8  christos     }
    985   1.1  christos 
    986   1.8  christos   if (!sals.empty ())
    987   1.7  christos     {
    988   1.8  christos       result.reset (PyTuple_New (sals.size ()));
    989   1.8  christos       if (result == NULL)
    990   1.7  christos 	return NULL;
    991   1.8  christos       for (size_t i = 0; i < sals.size (); ++i)
    992   1.8  christos 	{
    993   1.8  christos 	  PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
    994   1.1  christos 	  if (obj == NULL)
    995   1.7  christos 	    return NULL;
    996   1.1  christos 
    997   1.1  christos 	  PyTuple_SetItem (result.get (), i, obj);
    998   1.1  christos 	}
    999   1.8  christos     }
   1000   1.1  christos   else
   1001   1.7  christos     result = gdbpy_ref<>::new_reference (Py_None);
   1002   1.7  christos 
   1003   1.8  christos   gdbpy_ref<> return_result (PyTuple_New (2));
   1004   1.1  christos   if (return_result == NULL)
   1005   1.6  christos     return NULL;
   1006   1.1  christos 
   1007  1.10  christos   if (arg != NULL && strlen (arg) > 0)
   1008   1.1  christos     {
   1009   1.8  christos       unparsed.reset (PyUnicode_FromString (arg));
   1010   1.1  christos       if (unparsed == NULL)
   1011   1.1  christos 	return NULL;
   1012   1.8  christos     }
   1013   1.1  christos   else
   1014   1.7  christos     unparsed = gdbpy_ref<>::new_reference (Py_None);
   1015   1.7  christos 
   1016   1.1  christos   PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
   1017   1.7  christos   PyTuple_SetItem (return_result.get (), 1, result.release ());
   1018   1.1  christos 
   1019   1.1  christos   return return_result.release ();
   1020   1.1  christos }
   1021   1.1  christos 
   1022  1.11  christos /* Parse a string and evaluate it as an expression.  */
   1023   1.1  christos static PyObject *
   1024  1.11  christos gdbpy_parse_and_eval (PyObject *self, PyObject *args, PyObject *kw)
   1025  1.11  christos {
   1026   1.1  christos   static const char *keywords[] = { "expression", "global_context", nullptr };
   1027  1.11  christos 
   1028  1.11  christos   const char *expr_str;
   1029  1.11  christos   PyObject *global_context_obj = nullptr;
   1030  1.11  christos 
   1031  1.11  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!", keywords,
   1032  1.11  christos 					&expr_str,
   1033   1.1  christos 					&PyBool_Type, &global_context_obj))
   1034  1.11  christos     return nullptr;
   1035  1.11  christos 
   1036  1.11  christos   parser_flags flags = 0;
   1037  1.11  christos   if (global_context_obj != NULL)
   1038  1.11  christos     {
   1039  1.11  christos       int cmp = PyObject_IsTrue (global_context_obj);
   1040  1.11  christos       if (cmp < 0)
   1041  1.11  christos 	return nullptr;
   1042  1.11  christos       if (cmp)
   1043   1.1  christos 	flags |= PARSER_LEAVE_BLOCK_ALONE;
   1044  1.11  christos     }
   1045   1.9  christos 
   1046   1.1  christos   PyObject *result = nullptr;
   1047  1.11  christos   try
   1048  1.11  christos     {
   1049  1.11  christos       scoped_value_mark free_values;
   1050  1.11  christos       struct value *val;
   1051  1.11  christos       {
   1052  1.11  christos 	/* Allow other Python threads to run while we're evaluating
   1053  1.11  christos 	   the expression.  This is important because the expression
   1054  1.11  christos 	   could involve inferior calls or otherwise be a lengthy
   1055  1.11  christos 	   calculation.  We take care here to re-acquire the GIL here
   1056  1.11  christos 	   before continuing with Python work.  */
   1057  1.11  christos 	gdbpy_allow_threads allow_threads;
   1058  1.11  christos 	val = parse_and_eval (expr_str, flags);
   1059   1.1  christos       }
   1060   1.9  christos       result = value_to_value_object (val);
   1061   1.5  christos     }
   1062   1.5  christos   catch (const gdb_exception &except)
   1063   1.5  christos     {
   1064   1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
   1065  1.11  christos     }
   1066   1.1  christos 
   1067   1.1  christos   return result;
   1068   1.6  christos }
   1069   1.6  christos 
   1070   1.6  christos /* Implementation of gdb.invalidate_cached_frames.  */
   1071   1.6  christos 
   1072   1.6  christos static PyObject *
   1073   1.6  christos gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
   1074   1.6  christos {
   1075   1.6  christos   reinit_frame_cache ();
   1076   1.6  christos   Py_RETURN_NONE;
   1077   1.1  christos }
   1078   1.3  christos 
   1079   1.3  christos /* Read a file as Python code.
   1080   1.1  christos    This is the extension_language_script_ops.script_sourcer "method".
   1081   1.1  christos    FILE is the file to load.  FILENAME is name of the file FILE.
   1082   1.1  christos    This does not throw any errors.  If an exception occurs python will print
   1083   1.3  christos    the traceback and clear the error indicator.  */
   1084   1.3  christos 
   1085   1.3  christos static void
   1086   1.1  christos gdbpy_source_script (const struct extension_language_defn *extlang,
   1087  1.10  christos 		     FILE *file, const char *filename)
   1088  1.11  christos {
   1089  1.11  christos   gdbpy_enter enter_py;
   1090  1.11  christos   int result = python_run_simple_file (file, filename);
   1091   1.1  christos   if (result != 0)
   1092   1.1  christos     gdbpy_handle_exception ();
   1093   1.1  christos }
   1094   1.1  christos 
   1095   1.1  christos 
   1096   1.1  christos 
   1098   1.1  christos /* Posting and handling events.  */
   1099   1.1  christos 
   1100   1.9  christos /* A single event.  */
   1101   1.9  christos struct gdbpy_event
   1102   1.9  christos {
   1103   1.9  christos   gdbpy_event (gdbpy_ref<> &&func)
   1104   1.9  christos     : m_func (func.release ())
   1105   1.9  christos   {
   1106   1.9  christos   }
   1107   1.9  christos 
   1108   1.9  christos   gdbpy_event (gdbpy_event &&other) noexcept
   1109   1.9  christos     : m_func (other.m_func)
   1110   1.9  christos   {
   1111   1.9  christos     other.m_func = nullptr;
   1112   1.9  christos   }
   1113   1.9  christos 
   1114   1.9  christos   gdbpy_event (const gdbpy_event &other)
   1115   1.9  christos     : m_func (other.m_func)
   1116   1.9  christos   {
   1117   1.9  christos     gdbpy_gil gil;
   1118   1.9  christos     Py_XINCREF (m_func);
   1119   1.9  christos   }
   1120   1.9  christos 
   1121   1.9  christos   ~gdbpy_event ()
   1122   1.9  christos   {
   1123   1.1  christos     gdbpy_gil gil;
   1124   1.9  christos     Py_XDECREF (m_func);
   1125   1.1  christos   }
   1126   1.9  christos 
   1127   1.9  christos   gdbpy_event &operator= (const gdbpy_event &other) = delete;
   1128  1.10  christos 
   1129   1.1  christos   void operator() ()
   1130   1.9  christos   {
   1131   1.9  christos     gdbpy_enter enter_py;
   1132   1.9  christos 
   1133   1.9  christos     gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
   1134   1.1  christos     if (call_result == NULL)
   1135   1.9  christos       gdbpy_print_stack ();
   1136   1.1  christos   }
   1137   1.9  christos 
   1138   1.9  christos private:
   1139   1.9  christos 
   1140   1.9  christos   /* The Python event.  This is just a callable object.  Note that
   1141   1.9  christos      this is not a gdbpy_ref<>, because we have to take particular
   1142   1.1  christos      care to only destroy the reference when holding the GIL. */
   1143   1.1  christos   PyObject *m_func;
   1144   1.1  christos };
   1145   1.1  christos 
   1146   1.1  christos /* Submit an event to the gdb thread.  */
   1147   1.1  christos static PyObject *
   1148   1.1  christos gdbpy_post_event (PyObject *self, PyObject *args)
   1149   1.1  christos {
   1150   1.1  christos   PyObject *func;
   1151   1.1  christos 
   1152   1.1  christos   if (!PyArg_ParseTuple (args, "O", &func))
   1153   1.1  christos     return NULL;
   1154   1.1  christos 
   1155   1.1  christos   if (!PyCallable_Check (func))
   1156   1.1  christos     {
   1157   1.1  christos       PyErr_SetString (PyExc_RuntimeError,
   1158   1.1  christos 		       _("Posted event is not callable"));
   1159   1.9  christos       return NULL;
   1160   1.9  christos     }
   1161   1.9  christos 
   1162   1.1  christos   gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
   1163   1.1  christos   gdbpy_event event (std::move (func_ref));
   1164   1.1  christos   run_on_main_thread (event);
   1165   1.1  christos 
   1166  1.11  christos   Py_RETURN_NONE;
   1167  1.11  christos }
   1168  1.11  christos 
   1169  1.11  christos /* Interrupt the current operation on the main thread.  */
   1170  1.11  christos static PyObject *
   1171  1.11  christos gdbpy_interrupt (PyObject *self, PyObject *args)
   1172  1.11  christos {
   1173  1.11  christos   {
   1174  1.11  christos     /* Make sure the interrupt isn't delivered immediately somehow.
   1175  1.11  christos        This probably is not truly needed, but at the same time it
   1176  1.11  christos        seems more clear to be explicit about the intent.  */
   1177  1.11  christos     gdbpy_allow_threads temporarily_exit_python;
   1178  1.11  christos     scoped_disable_cooperative_sigint_handling no_python_sigint;
   1179  1.11  christos 
   1180  1.11  christos     set_quit_flag ();
   1181  1.11  christos   }
   1182  1.11  christos 
   1183   1.1  christos   Py_RETURN_NONE;
   1184   1.1  christos }
   1185   1.3  christos 
   1186   1.3  christos 
   1187   1.3  christos 
   1189   1.3  christos /* This is the extension_language_ops.before_prompt "method".  */
   1190   1.1  christos 
   1191   1.1  christos static enum ext_lang_rc
   1192   1.3  christos gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
   1193   1.1  christos 			  const char *current_gdb_prompt)
   1194  1.10  christos {
   1195   1.7  christos   if (!gdb_python_initialized)
   1196   1.7  christos     return EXT_LANG_RC_NOP;
   1197   1.7  christos 
   1198   1.7  christos   gdbpy_enter enter_py;
   1199   1.1  christos 
   1200   1.1  christos   if (!evregpy_no_listeners_p (gdb_py_events.before_prompt)
   1201   1.1  christos       && evpy_emit_event (NULL, gdb_py_events.before_prompt) < 0)
   1202   1.1  christos     return EXT_LANG_RC_ERROR;
   1203   1.7  christos 
   1204   1.7  christos   if (gdb_python_module
   1205   1.1  christos       && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
   1206   1.7  christos     {
   1207   1.7  christos       gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
   1208   1.7  christos 						"prompt_hook"));
   1209   1.7  christos       if (hook == NULL)
   1210   1.1  christos 	{
   1211   1.7  christos 	  gdbpy_print_stack ();
   1212   1.1  christos 	  return EXT_LANG_RC_ERROR;
   1213  1.10  christos 	}
   1214   1.1  christos 
   1215   1.7  christos       if (PyCallable_Check (hook.get ()))
   1216   1.7  christos 	{
   1217   1.7  christos 	  gdbpy_ref<> current_prompt (PyUnicode_FromString (current_gdb_prompt));
   1218   1.7  christos 	  if (current_prompt == NULL)
   1219   1.1  christos 	    {
   1220   1.7  christos 	      gdbpy_print_stack ();
   1221   1.7  christos 	      return EXT_LANG_RC_ERROR;
   1222   1.7  christos 	    }
   1223   1.1  christos 
   1224   1.7  christos 	  gdbpy_ref<> result
   1225   1.7  christos 	    (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
   1226   1.7  christos 					   NULL));
   1227   1.7  christos 	  if (result == NULL)
   1228   1.1  christos 	    {
   1229   1.1  christos 	      gdbpy_print_stack ();
   1230   1.1  christos 	      return EXT_LANG_RC_ERROR;
   1231   1.1  christos 	    }
   1232  1.10  christos 
   1233   1.1  christos 	  /* Return type should be None, or a String.  If it is None,
   1234   1.1  christos 	     fall through, we will not set a prompt.  If it is a
   1235   1.1  christos 	     string, set  PROMPT.  Anything else, set an exception.  */
   1236   1.1  christos 	  if (result != Py_None && !PyUnicode_Check (result.get ()))
   1237   1.7  christos 	    {
   1238   1.7  christos 	      PyErr_Format (PyExc_RuntimeError,
   1239   1.1  christos 			    _("Return from prompt_hook must " \
   1240   1.1  christos 			      "be either a Python string, or None"));
   1241   1.1  christos 	      gdbpy_print_stack ();
   1242   1.1  christos 	      return EXT_LANG_RC_ERROR;
   1243   1.7  christos 	    }
   1244   1.7  christos 
   1245   1.1  christos 	  if (result != Py_None)
   1246   1.1  christos 	    {
   1247   1.7  christos 	      gdb::unique_xmalloc_ptr<char>
   1248   1.7  christos 		prompt (python_string_to_host_string (result.get ()));
   1249   1.7  christos 
   1250   1.7  christos 	      if (prompt == NULL)
   1251   1.7  christos 		{
   1252   1.7  christos 		  gdbpy_print_stack ();
   1253   1.7  christos 		  return EXT_LANG_RC_ERROR;
   1254   1.1  christos 		}
   1255   1.1  christos 
   1256   1.1  christos 	      set_prompt (prompt.get ());
   1257   1.1  christos 	      return EXT_LANG_RC_OK;
   1258   1.7  christos 	    }
   1259   1.1  christos 	}
   1260   1.1  christos     }
   1261   1.9  christos 
   1262   1.9  christos   return EXT_LANG_RC_NOP;
   1263  1.11  christos }
   1264   1.9  christos 
   1265   1.9  christos /* This is the extension_language_ops.colorize "method".  */
   1266   1.9  christos 
   1267   1.9  christos static std::optional<std::string>
   1268   1.9  christos gdbpy_colorize (const std::string &filename, const std::string &contents)
   1269  1.10  christos {
   1270   1.9  christos   if (!gdb_python_initialized)
   1271  1.10  christos     return {};
   1272  1.10  christos 
   1273  1.10  christos   gdbpy_enter enter_py;
   1274  1.10  christos 
   1275  1.10  christos   gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
   1276  1.10  christos   if (module == nullptr)
   1277  1.10  christos     {
   1278  1.10  christos       gdbpy_print_stack ();
   1279   1.9  christos       return {};
   1280   1.9  christos     }
   1281  1.10  christos 
   1282   1.9  christos   if (!PyObject_HasAttrString (module.get (), "colorize"))
   1283   1.9  christos     return {};
   1284   1.9  christos 
   1285   1.9  christos   gdbpy_ref<> hook (PyObject_GetAttrString (module.get (), "colorize"));
   1286   1.9  christos   if (hook == nullptr)
   1287   1.9  christos     {
   1288   1.9  christos       gdbpy_print_stack ();
   1289   1.9  christos       return {};
   1290   1.9  christos     }
   1291  1.10  christos 
   1292   1.9  christos   if (!PyCallable_Check (hook.get ()))
   1293   1.9  christos     return {};
   1294   1.9  christos 
   1295   1.9  christos   gdbpy_ref<> fname_arg (PyUnicode_FromString (filename.c_str ()));
   1296   1.9  christos   if (fname_arg == nullptr)
   1297  1.10  christos     {
   1298  1.10  christos       gdbpy_print_stack ();
   1299  1.10  christos       return {};
   1300  1.10  christos     }
   1301  1.10  christos 
   1302  1.10  christos   /* The pygments library, which is what we currently use for applying
   1303  1.10  christos      styling, is happy to take input as a bytes object, and to figure out
   1304  1.10  christos      the encoding for itself.  This removes the need for us to figure out
   1305   1.9  christos      (guess?) at how the content is encoded, which is probably a good
   1306   1.9  christos      thing.  */
   1307   1.9  christos   gdbpy_ref<> contents_arg (PyBytes_FromStringAndSize (contents.c_str (),
   1308   1.9  christos 						       contents.size ()));
   1309   1.9  christos   if (contents_arg == nullptr)
   1310   1.9  christos     {
   1311  1.10  christos       gdbpy_print_stack ();
   1312  1.10  christos       return {};
   1313  1.10  christos     }
   1314  1.10  christos 
   1315   1.9  christos   /* Calling gdb.colorize passing in the filename (a string), and the file
   1316   1.9  christos      contents (a bytes object).  This function should return either a bytes
   1317   1.9  christos      object, the same contents with styling applied, or None to indicate
   1318   1.9  christos      that no styling should be performed.  */
   1319   1.9  christos   gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
   1320   1.9  christos 						    fname_arg.get (),
   1321   1.9  christos 						    contents_arg.get (),
   1322   1.9  christos 						    nullptr));
   1323   1.9  christos   if (result == nullptr)
   1324   1.9  christos     {
   1325  1.10  christos       gdbpy_print_stack ();
   1326   1.9  christos       return {};
   1327  1.10  christos     }
   1328  1.10  christos 
   1329  1.10  christos   if (result == Py_None)
   1330  1.10  christos     return {};
   1331  1.10  christos   else if (!PyBytes_Check (result.get ()))
   1332  1.10  christos     {
   1333  1.10  christos       PyErr_SetString (PyExc_TypeError,
   1334  1.10  christos 		       _("Return value from gdb.colorize should be a bytes object or None."));
   1335  1.10  christos       gdbpy_print_stack ();
   1336  1.10  christos       return {};
   1337   1.9  christos     }
   1338  1.10  christos 
   1339  1.10  christos   return std::string (PyBytes_AsString (result.get ()));
   1340  1.11  christos }
   1341  1.10  christos 
   1342  1.10  christos /* This is the extension_language_ops.colorize_disasm "method".  */
   1343  1.10  christos 
   1344  1.10  christos static std::optional<std::string>
   1345  1.10  christos gdbpy_colorize_disasm (const std::string &content, gdbarch *gdbarch)
   1346  1.10  christos {
   1347  1.10  christos   if (!gdb_python_initialized)
   1348  1.10  christos     return {};
   1349  1.10  christos 
   1350   1.9  christos   gdbpy_enter enter_py;
   1351   1.9  christos 
   1352   1.9  christos   gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
   1353   1.9  christos   if (module == nullptr)
   1354  1.10  christos     {
   1355  1.10  christos       gdbpy_print_stack ();
   1356  1.10  christos       return {};
   1357  1.10  christos     }
   1358  1.10  christos 
   1359  1.10  christos   if (!PyObject_HasAttrString (module.get (), "colorize_disasm"))
   1360  1.10  christos     return {};
   1361  1.10  christos 
   1362  1.10  christos   gdbpy_ref<> hook (PyObject_GetAttrString (module.get (),
   1363  1.10  christos 					    "colorize_disasm"));
   1364  1.10  christos   if (hook == nullptr)
   1365  1.10  christos     {
   1366  1.10  christos       gdbpy_print_stack ();
   1367  1.10  christos       return {};
   1368  1.10  christos     }
   1369  1.10  christos 
   1370  1.10  christos   if (!PyCallable_Check (hook.get ()))
   1371  1.10  christos     return {};
   1372  1.10  christos 
   1373  1.10  christos   gdbpy_ref<> content_arg (PyBytes_FromString (content.c_str ()));
   1374  1.10  christos   if (content_arg == nullptr)
   1375  1.10  christos     {
   1376  1.10  christos       gdbpy_print_stack ();
   1377  1.10  christos       return {};
   1378  1.10  christos     }
   1379  1.10  christos 
   1380  1.10  christos   gdbpy_ref<> gdbarch_arg (gdbarch_to_arch_object (gdbarch));
   1381  1.10  christos   if (gdbarch_arg == nullptr)
   1382  1.10  christos     {
   1383  1.10  christos       gdbpy_print_stack ();
   1384  1.10  christos       return {};
   1385  1.10  christos     }
   1386  1.10  christos 
   1387  1.10  christos   gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
   1388  1.10  christos 						    content_arg.get (),
   1389  1.10  christos 						    gdbarch_arg.get (),
   1390  1.10  christos 						    nullptr));
   1391  1.10  christos   if (result == nullptr)
   1392  1.10  christos     {
   1393  1.10  christos       gdbpy_print_stack ();
   1394  1.10  christos       return {};
   1395  1.10  christos     }
   1396  1.10  christos 
   1397   1.9  christos   if (result == Py_None)
   1398  1.10  christos     return {};
   1399  1.10  christos 
   1400   1.9  christos   if (!PyBytes_Check (result.get ()))
   1401   1.9  christos     {
   1402   1.9  christos       PyErr_SetString (PyExc_TypeError,
   1403   1.9  christos 		       _("Return value from gdb.colorize_disasm should be a bytes object or None."));
   1404  1.10  christos       gdbpy_print_stack ();
   1405  1.10  christos       return {};
   1406  1.10  christos     }
   1407  1.10  christos 
   1408  1.10  christos   return std::string (PyBytes_AsString (result.get ()));
   1409  1.10  christos }
   1410  1.10  christos 
   1411  1.10  christos 
   1412  1.10  christos 
   1414  1.10  christos /* Implement gdb.format_address(ADDR,P_SPACE,ARCH).  Provide access to
   1415  1.10  christos    GDB's print_address function from Python.  The returned address will
   1416  1.10  christos    have the format '0x..... <symbol+offset>'.  */
   1417  1.10  christos 
   1418  1.10  christos static PyObject *
   1419  1.10  christos gdbpy_format_address (PyObject *self, PyObject *args, PyObject *kw)
   1420  1.10  christos {
   1421  1.10  christos   static const char *keywords[] =
   1422  1.10  christos     {
   1423  1.10  christos       "address", "progspace", "architecture", nullptr
   1424  1.10  christos     };
   1425  1.10  christos   PyObject *addr_obj = nullptr, *pspace_obj = nullptr, *arch_obj = nullptr;
   1426  1.10  christos   CORE_ADDR addr;
   1427  1.10  christos   struct gdbarch *gdbarch = nullptr;
   1428  1.10  christos   struct program_space *pspace = nullptr;
   1429  1.10  christos 
   1430  1.10  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O|OO", keywords,
   1431  1.10  christos 					&addr_obj, &pspace_obj, &arch_obj))
   1432  1.10  christos     return nullptr;
   1433  1.10  christos 
   1434  1.10  christos   if (get_addr_from_python (addr_obj, &addr) < 0)
   1435  1.10  christos     return nullptr;
   1436  1.10  christos 
   1437  1.10  christos   /* If the user passed None for progspace or architecture, then we
   1438  1.10  christos      consider this to mean "the default".  Here we replace references to
   1439  1.10  christos      None with nullptr, this means that in the following code we only have
   1440  1.10  christos      to handle the nullptr case.  These are only borrowed references, so
   1441  1.10  christos      no decref is required here.  */
   1442  1.10  christos   if (pspace_obj == Py_None)
   1443  1.10  christos     pspace_obj = nullptr;
   1444  1.10  christos   if (arch_obj == Py_None)
   1445  1.10  christos     arch_obj = nullptr;
   1446  1.10  christos 
   1447  1.11  christos   if (pspace_obj == nullptr && arch_obj == nullptr)
   1448  1.10  christos     {
   1449  1.10  christos       /* Grab both of these from the current inferior, and its associated
   1450  1.10  christos 	 default architecture.  */
   1451  1.10  christos       pspace = current_inferior ()->pspace;
   1452  1.10  christos       gdbarch = current_inferior ()->arch ();
   1453  1.10  christos     }
   1454  1.10  christos   else if (arch_obj == nullptr || pspace_obj == nullptr)
   1455  1.10  christos     {
   1456  1.10  christos       /* If the user has only given one of program space or architecture,
   1457  1.10  christos 	 then don't use the default for the other.  Sure we could use the
   1458  1.10  christos 	 default, but it feels like there's too much scope of mistakes in
   1459  1.10  christos 	 this case, so better to require the user to provide both
   1460  1.10  christos 	 arguments.  */
   1461  1.10  christos       PyErr_SetString (PyExc_ValueError,
   1462  1.10  christos 		       _("The architecture and progspace arguments must both be supplied"));
   1463  1.10  christos       return nullptr;
   1464  1.10  christos     }
   1465  1.10  christos   else
   1466  1.10  christos     {
   1467  1.10  christos       /* The user provided an address, program space, and architecture.
   1468  1.10  christos 	 Just check that these objects are valid.  */
   1469  1.10  christos       if (!gdbpy_is_progspace (pspace_obj))
   1470  1.10  christos 	{
   1471  1.10  christos 	  PyErr_SetString (PyExc_TypeError,
   1472  1.10  christos 			   _("The progspace argument is not a gdb.Progspace object"));
   1473  1.10  christos 	  return nullptr;
   1474  1.10  christos 	}
   1475  1.10  christos 
   1476  1.10  christos       pspace = progspace_object_to_program_space (pspace_obj);
   1477  1.10  christos       if (pspace == nullptr)
   1478  1.10  christos 	{
   1479  1.10  christos 	  PyErr_SetString (PyExc_ValueError,
   1480  1.10  christos 			   _("The progspace argument is not valid"));
   1481  1.10  christos 	  return nullptr;
   1482  1.10  christos 	}
   1483  1.10  christos 
   1484  1.10  christos       if (!gdbpy_is_architecture (arch_obj))
   1485  1.10  christos 	{
   1486  1.10  christos 	  PyErr_SetString (PyExc_TypeError,
   1487  1.10  christos 			   _("The architecture argument is not a gdb.Architecture object"));
   1488  1.10  christos 	  return nullptr;
   1489  1.10  christos 	}
   1490  1.10  christos 
   1491  1.10  christos       /* Architectures are never deleted once created, so gdbarch should
   1492  1.10  christos 	 never come back as nullptr.  */
   1493  1.10  christos       gdbarch = arch_object_to_gdbarch (arch_obj);
   1494  1.10  christos       gdb_assert (gdbarch != nullptr);
   1495  1.10  christos     }
   1496  1.10  christos 
   1497  1.10  christos   /* By this point we should know the program space and architecture we are
   1498  1.10  christos      going to use.  */
   1499  1.10  christos   gdb_assert (pspace != nullptr);
   1500  1.10  christos   gdb_assert (gdbarch != nullptr);
   1501  1.10  christos 
   1502  1.10  christos   /* Unfortunately print_address relies on the current program space for
   1503  1.10  christos      its symbol lookup.  Temporarily switch now.  */
   1504  1.10  christos   scoped_restore_current_program_space restore_progspace;
   1505  1.10  christos   set_current_program_space (pspace);
   1506   1.9  christos 
   1507   1.9  christos   /* Format the address, and return it as a string.  */
   1508   1.1  christos   string_file buf;
   1509   1.1  christos   print_address (gdbarch, addr, &buf);
   1510   1.1  christos   return PyUnicode_FromString (buf.c_str ());
   1511   1.1  christos }
   1512   1.1  christos 
   1513   1.1  christos 
   1514   1.1  christos 
   1516   1.1  christos /* Printing.  */
   1517   1.1  christos 
   1518   1.1  christos /* A python function to write a single string using gdb's filtered
   1519   1.1  christos    output stream .  The optional keyword STREAM can be used to write
   1520   1.7  christos    to a particular stream.  The default stream is to gdb_stdout.  */
   1521   1.1  christos 
   1522   1.1  christos static PyObject *
   1523   1.7  christos gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
   1524   1.7  christos {
   1525   1.1  christos   const char *arg;
   1526   1.1  christos   static const char *keywords[] = { "text", "stream", NULL };
   1527   1.9  christos   int stream_type = 0;
   1528   1.1  christos 
   1529   1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
   1530  1.10  christos 					&stream_type))
   1531  1.10  christos     return NULL;
   1532  1.10  christos 
   1533  1.10  christos   try
   1534   1.1  christos     {
   1535  1.10  christos       switch (stream_type)
   1536  1.10  christos 	{
   1537  1.10  christos 	case 1:
   1538  1.10  christos 	  {
   1539   1.1  christos 	    gdb_printf (gdb_stderr, "%s", arg);
   1540  1.10  christos 	    break;
   1541  1.10  christos 	  }
   1542  1.10  christos 	case 2:
   1543  1.10  christos 	  {
   1544   1.1  christos 	    gdb_printf (gdb_stdlog, "%s", arg);
   1545   1.9  christos 	    break;
   1546   1.5  christos 	  }
   1547   1.5  christos 	default:
   1548   1.5  christos 	  gdb_printf (gdb_stdout, "%s", arg);
   1549   1.1  christos 	}
   1550   1.1  christos     }
   1551   1.1  christos   catch (const gdb_exception &except)
   1552   1.1  christos     {
   1553   1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
   1554   1.1  christos     }
   1555   1.1  christos 
   1556   1.1  christos   Py_RETURN_NONE;
   1557   1.1  christos }
   1558   1.1  christos 
   1559   1.1  christos /* A python function to flush a gdb stream.  The optional keyword
   1560   1.7  christos    STREAM can be used to flush a particular stream.  The default stream
   1561   1.1  christos    is gdb_stdout.  */
   1562   1.1  christos 
   1563   1.7  christos static PyObject *
   1564   1.7  christos gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
   1565   1.1  christos {
   1566   1.1  christos   static const char *keywords[] = { "stream", NULL };
   1567   1.1  christos   int stream_type = 0;
   1568   1.1  christos 
   1569   1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
   1570   1.1  christos 					&stream_type))
   1571   1.1  christos     return NULL;
   1572   1.1  christos 
   1573   1.1  christos   switch (stream_type)
   1574   1.1  christos     {
   1575   1.1  christos     case 1:
   1576   1.1  christos       {
   1577   1.1  christos 	gdb_flush (gdb_stderr);
   1578   1.1  christos 	break;
   1579   1.1  christos       }
   1580   1.1  christos     case 2:
   1581   1.1  christos       {
   1582   1.1  christos 	gdb_flush (gdb_stdlog);
   1583   1.1  christos 	break;
   1584   1.1  christos       }
   1585   1.1  christos     default:
   1586   1.5  christos       gdb_flush (gdb_stdout);
   1587   1.5  christos     }
   1588   1.5  christos 
   1589   1.5  christos   Py_RETURN_NONE;
   1590   1.5  christos }
   1591   1.5  christos 
   1592   1.5  christos /* Return non-zero if print-stack is not "none".  */
   1593   1.5  christos 
   1594   1.1  christos int
   1595   1.1  christos gdbpy_print_python_errors_p (void)
   1596   1.1  christos {
   1597   1.1  christos   return gdbpy_should_print_stack != python_excp_none;
   1598   1.1  christos }
   1599   1.1  christos 
   1600   1.1  christos /* Print a python exception trace, print just a message, or print
   1601   1.1  christos    nothing and clear the python exception, depending on
   1602   1.1  christos    gdbpy_should_print_stack.  Only call this if a python exception is
   1603   1.1  christos    set.  */
   1604   1.1  christos void
   1605   1.1  christos gdbpy_print_stack (void)
   1606   1.1  christos {
   1607   1.1  christos 
   1608   1.1  christos   /* Print "none", just clear exception.  */
   1609   1.1  christos   if (gdbpy_should_print_stack == python_excp_none)
   1610   1.1  christos     {
   1611   1.1  christos       PyErr_Clear ();
   1612   1.1  christos     }
   1613  1.10  christos   /* Print "full" message and backtrace.  */
   1614   1.9  christos   else if (gdbpy_should_print_stack == python_excp_full)
   1615   1.1  christos     {
   1616   1.1  christos       PyErr_Print ();
   1617   1.1  christos       /* PyErr_Print doesn't necessarily end output with a newline.
   1618   1.9  christos 	 This works because Python's stdout/stderr is fed through
   1619   1.5  christos 	 gdb_printf.  */
   1620   1.5  christos       try
   1621   1.1  christos 	{
   1622   1.1  christos 	  begin_line ();
   1623   1.1  christos 	}
   1624   1.1  christos       catch (const gdb_exception &except)
   1625   1.8  christos 	{
   1626   1.1  christos 	}
   1627   1.8  christos     }
   1628   1.8  christos   /* Print "message", just error print message.  */
   1629   1.8  christos   else
   1630   1.8  christos     {
   1631   1.8  christos       gdbpy_err_fetch fetched_error;
   1632   1.8  christos 
   1633   1.1  christos       gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
   1634   1.9  christos       gdb::unique_xmalloc_ptr<char> type;
   1635   1.1  christos       /* Don't compute TYPE if MSG already indicates that there is an
   1636   1.8  christos 	 error.  */
   1637   1.1  christos       if (msg != NULL)
   1638   1.1  christos 	type = fetched_error.type_to_string ();
   1639   1.1  christos 
   1640  1.10  christos       try
   1641  1.11  christos 	{
   1642  1.10  christos 	  if (msg == NULL || type == NULL)
   1643   1.8  christos 	    {
   1644   1.1  christos 	      /* An error occurred computing the string representation of the
   1645   1.1  christos 		 error message.  */
   1646  1.10  christos 	      gdb_printf (gdb_stderr,
   1647  1.10  christos 			  _("Error occurred computing Python error "
   1648   1.1  christos 			    "message.\n"));
   1649   1.9  christos 	      PyErr_Clear ();
   1650   1.5  christos 	    }
   1651   1.5  christos 	  else
   1652   1.1  christos 	    gdb_printf (gdb_stderr, "Python Exception %s: %s\n",
   1653   1.1  christos 			type.get (), msg.get ());
   1654   1.1  christos 	}
   1655   1.8  christos       catch (const gdb_exception &except)
   1656   1.8  christos 	{
   1657   1.1  christos 	}
   1658   1.8  christos     }
   1659   1.8  christos }
   1660   1.1  christos 
   1661   1.8  christos /* Like gdbpy_print_stack, but if the exception is a
   1662   1.8  christos    KeyboardException, throw a gdb "quit" instead.  */
   1663   1.8  christos 
   1664   1.8  christos void
   1665   1.8  christos gdbpy_print_stack_or_quit ()
   1666   1.8  christos {
   1667   1.8  christos   if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
   1668   1.1  christos     {
   1669   1.8  christos       PyErr_Clear ();
   1670   1.1  christos       throw_quit ("Quit");
   1671   1.1  christos     }
   1672   1.1  christos   gdbpy_print_stack ();
   1673   1.1  christos }
   1674   1.1  christos 
   1675   1.1  christos 
   1676   1.7  christos 
   1678   1.1  christos /* Return a sequence holding all the Progspaces.  */
   1679   1.1  christos 
   1680   1.9  christos static PyObject *
   1681   1.9  christos gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
   1682   1.9  christos {
   1683   1.1  christos   gdbpy_ref<> list (PyList_New (0));
   1684   1.9  christos   if (list == NULL)
   1685   1.9  christos     return NULL;
   1686   1.9  christos 
   1687   1.1  christos   for (struct program_space *ps : program_spaces)
   1688   1.7  christos     {
   1689   1.1  christos       gdbpy_ref<> item = pspace_to_pspace_object (ps);
   1690   1.1  christos 
   1691  1.10  christos       if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
   1692  1.10  christos 	return NULL;
   1693  1.10  christos     }
   1694  1.10  christos 
   1695  1.10  christos   return list.release ();
   1696  1.10  christos }
   1697  1.10  christos 
   1698  1.10  christos /* Return the name of the current language.  */
   1699   1.1  christos 
   1700   1.1  christos static PyObject *
   1701  1.10  christos gdbpy_current_language (PyObject *unused1, PyObject *unused2)
   1702  1.10  christos {
   1703   1.1  christos   return host_string_to_python_string (current_language->name ()).release ();
   1704   1.1  christos }
   1705   1.1  christos 
   1706   1.3  christos 
   1707   1.3  christos 
   1709   1.1  christos /* See python.h.  */
   1710   1.3  christos struct objfile *gdbpy_current_objfile;
   1711   1.3  christos 
   1712   1.3  christos /* Set the current objfile to OBJFILE and then read FILE named FILENAME
   1713   1.3  christos    as Python code.  This does not throw any errors.  If an exception
   1714   1.1  christos    occurs python will print the traceback and clear the error indicator.
   1715   1.1  christos    This is the extension_language_script_ops.objfile_script_sourcer
   1716   1.1  christos    "method".  */
   1717   1.1  christos 
   1718  1.10  christos static void
   1719  1.10  christos gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
   1720  1.10  christos 			     struct objfile *objfile, FILE *file,
   1721   1.1  christos 			     const char *filename)
   1722  1.11  christos {
   1723  1.11  christos   if (!gdb_python_initialized)
   1724  1.11  christos     return;
   1725   1.1  christos 
   1726   1.1  christos   gdbpy_enter enter_py (objfile->arch ());
   1727   1.5  christos   scoped_restore restire_current_objfile
   1728   1.5  christos     = make_scoped_restore (&gdbpy_current_objfile, objfile);
   1729   1.5  christos 
   1730   1.5  christos   int result = python_run_simple_file (file, filename);
   1731   1.5  christos   if (result != 0)
   1732   1.5  christos     gdbpy_print_stack ();
   1733   1.5  christos }
   1734   1.5  christos 
   1735   1.5  christos /* Set the current objfile to OBJFILE and then execute SCRIPT
   1736   1.5  christos    as Python code.  This does not throw any errors.  If an exception
   1737   1.5  christos    occurs python will print the traceback and clear the error indicator.
   1738   1.5  christos    This is the extension_language_script_ops.objfile_script_executor
   1739   1.5  christos    "method".  */
   1740   1.5  christos 
   1741  1.10  christos static void
   1742  1.10  christos gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
   1743  1.10  christos 			      struct objfile *objfile, const char *name,
   1744   1.5  christos 			      const char *script)
   1745  1.11  christos {
   1746  1.11  christos   if (!gdb_python_initialized)
   1747  1.11  christos     return;
   1748   1.5  christos 
   1749   1.5  christos   gdbpy_enter enter_py (objfile->arch ());
   1750   1.1  christos   scoped_restore restire_current_objfile
   1751   1.1  christos     = make_scoped_restore (&gdbpy_current_objfile, objfile);
   1752   1.1  christos 
   1753   1.1  christos   int ret = eval_python_command (script, Py_file_input);
   1754   1.1  christos   if (ret != 0)
   1755   1.1  christos     gdbpy_print_stack ();
   1756   1.1  christos }
   1757   1.1  christos 
   1758   1.8  christos /* Return the current Objfile, or None if there isn't one.  */
   1759   1.1  christos 
   1760   1.1  christos static PyObject *
   1761  1.11  christos gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
   1762  1.11  christos {
   1763  1.11  christos   if (! gdbpy_current_objfile)
   1764  1.11  christos     Py_RETURN_NONE;
   1765  1.11  christos 
   1766  1.11  christos   return objfile_to_objfile_object (gdbpy_current_objfile).release ();
   1767  1.11  christos }
   1768  1.11  christos 
   1769  1.11  christos /* Implement the 'handle_missing_debuginfo' hook for Python.  GDB has
   1770  1.11  christos    failed to find any debug information for OBJFILE.  The extension has a
   1771  1.11  christos    chance to record this, or even install the required debug information.
   1772  1.11  christos    See the description of ext_lang_missing_debuginfo_result in
   1773  1.11  christos    extension-priv.h for details of the return value.  */
   1774  1.11  christos 
   1775  1.11  christos static ext_lang_missing_debuginfo_result
   1776  1.11  christos gdbpy_handle_missing_debuginfo (const struct extension_language_defn *extlang,
   1777  1.11  christos 				struct objfile *objfile)
   1778  1.11  christos {
   1779  1.11  christos   /* Early exit if Python is not initialised.  */
   1780  1.11  christos   if (!gdb_python_initialized || gdb_python_module == nullptr)
   1781  1.11  christos     return {};
   1782  1.11  christos 
   1783  1.11  christos   struct gdbarch *gdbarch = objfile->arch ();
   1784  1.11  christos 
   1785  1.11  christos   gdbpy_enter enter_py (gdbarch);
   1786  1.11  christos 
   1787  1.11  christos   /* Convert OBJFILE into the corresponding Python object.  */
   1788  1.11  christos   gdbpy_ref<> pyo_objfile = objfile_to_objfile_object (objfile);
   1789  1.11  christos   if (pyo_objfile == nullptr)
   1790  1.11  christos     {
   1791  1.11  christos       gdbpy_print_stack ();
   1792  1.11  christos       return {};
   1793  1.11  christos     }
   1794  1.11  christos 
   1795  1.11  christos   /* Lookup the helper function within the GDB module.  */
   1796  1.11  christos   gdbpy_ref<> pyo_handler
   1797  1.11  christos     (PyObject_GetAttrString (gdb_python_module, "_handle_missing_debuginfo"));
   1798  1.11  christos   if (pyo_handler == nullptr)
   1799  1.11  christos     {
   1800  1.11  christos       gdbpy_print_stack ();
   1801  1.11  christos       return {};
   1802  1.11  christos     }
   1803  1.11  christos 
   1804  1.11  christos   /* Call the function, passing in the Python objfile object.  */
   1805  1.11  christos   gdbpy_ref<> pyo_execute_ret
   1806  1.11  christos     (PyObject_CallFunctionObjArgs (pyo_handler.get (), pyo_objfile.get (),
   1807  1.11  christos 				   nullptr));
   1808  1.11  christos   if (pyo_execute_ret == nullptr)
   1809  1.11  christos     {
   1810  1.11  christos       /* If the handler is cancelled due to a Ctrl-C, then propagate
   1811  1.11  christos 	 the Ctrl-C as a GDB exception instead of swallowing it.  */
   1812  1.11  christos       gdbpy_print_stack_or_quit ();
   1813  1.11  christos       return {};
   1814  1.11  christos     }
   1815  1.11  christos 
   1816  1.11  christos   /* Parse the result, and convert it back to the C++ object.  */
   1817  1.11  christos   if (pyo_execute_ret == Py_None)
   1818  1.11  christos     return {};
   1819  1.11  christos 
   1820  1.11  christos   if (PyBool_Check (pyo_execute_ret.get ()))
   1821  1.11  christos     {
   1822  1.11  christos       bool try_again = PyObject_IsTrue (pyo_execute_ret.get ());
   1823  1.11  christos       return ext_lang_missing_debuginfo_result (try_again);
   1824  1.11  christos     }
   1825  1.11  christos 
   1826  1.11  christos   if (!gdbpy_is_string (pyo_execute_ret.get ()))
   1827  1.11  christos     {
   1828  1.11  christos       PyErr_SetString (PyExc_ValueError,
   1829  1.11  christos 		       "return value from _handle_missing_debuginfo should "
   1830  1.11  christos 		       "be None, a Bool, or a String");
   1831  1.11  christos       gdbpy_print_stack ();
   1832  1.11  christos       return {};
   1833  1.11  christos     }
   1834  1.11  christos 
   1835  1.11  christos   gdb::unique_xmalloc_ptr<char> filename
   1836  1.11  christos     = python_string_to_host_string (pyo_execute_ret.get ());
   1837  1.11  christos   if (filename == nullptr)
   1838   1.3  christos     {
   1839   1.3  christos       gdbpy_print_stack ();
   1840   1.3  christos       return {};
   1841   1.3  christos     }
   1842   1.1  christos 
   1843   1.3  christos   return ext_lang_missing_debuginfo_result (std::string (filename.get ()));
   1844   1.3  christos }
   1845   1.3  christos 
   1846   1.1  christos /* Compute the list of active python type printers and store them in
   1847   1.7  christos    EXT_PRINTERS->py_type_printers.  The product of this function is used by
   1848   1.1  christos    gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
   1849   1.1  christos    This is the extension_language_ops.start_type_printers "method".  */
   1850   1.3  christos 
   1851   1.1  christos static void
   1852  1.10  christos gdbpy_start_type_printers (const struct extension_language_defn *extlang,
   1853   1.1  christos 			   struct ext_lang_type_printers *ext_printers)
   1854   1.7  christos {
   1855   1.1  christos   PyObject *printers_obj = NULL;
   1856   1.1  christos 
   1857   1.1  christos   if (!gdb_python_initialized)
   1858   1.7  christos     return;
   1859   1.1  christos 
   1860   1.1  christos   gdbpy_enter enter_py;
   1861   1.7  christos 
   1862   1.7  christos   gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
   1863   1.1  christos   if (type_module == NULL)
   1864   1.1  christos     {
   1865   1.1  christos       gdbpy_print_stack ();
   1866   1.7  christos       return;
   1867   1.1  christos     }
   1868   1.1  christos 
   1869   1.7  christos   gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
   1870   1.3  christos 					    "get_type_recognizers"));
   1871   1.1  christos   if (func == NULL)
   1872   1.3  christos     {
   1873   1.3  christos       gdbpy_print_stack ();
   1874   1.1  christos       return;
   1875   1.1  christos     }
   1876   1.3  christos 
   1877   1.3  christos   printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
   1878  1.11  christos   if (printers_obj == NULL)
   1879   1.3  christos     gdbpy_print_stack ();
   1880   1.3  christos   else
   1881   1.3  christos     ext_printers->py_type_printers = printers_obj;
   1882   1.3  christos }
   1883   1.3  christos 
   1884   1.3  christos /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
   1885   1.3  christos    a newly allocated string holding the type's replacement name, and return
   1886  1.11  christos    EXT_LANG_RC_OK.
   1887  1.11  christos    If there's a Python error return EXT_LANG_RC_ERROR.
   1888   1.1  christos    Otherwise, return EXT_LANG_RC_NOP.
   1889   1.6  christos    This is the extension_language_ops.apply_type_printers "method".  */
   1890   1.7  christos 
   1891   1.1  christos static enum ext_lang_rc
   1892   1.1  christos gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
   1893   1.3  christos 			   const struct ext_lang_type_printers *ext_printers,
   1894   1.1  christos 			   struct type *type,
   1895   1.1  christos 			   gdb::unique_xmalloc_ptr<char> *prettied_type)
   1896   1.3  christos {
   1897   1.1  christos   PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
   1898  1.10  christos   gdb::unique_xmalloc_ptr<char> result;
   1899   1.1  christos 
   1900   1.7  christos   if (printers_obj == NULL)
   1901   1.1  christos     return EXT_LANG_RC_NOP;
   1902   1.1  christos 
   1903   1.1  christos   if (!gdb_python_initialized)
   1904   1.7  christos     return EXT_LANG_RC_NOP;
   1905   1.1  christos 
   1906   1.1  christos   gdbpy_enter enter_py;
   1907   1.7  christos 
   1908   1.1  christos   gdbpy_ref<> type_obj (type_to_type_object (type));
   1909   1.1  christos   if (type_obj == NULL)
   1910   1.1  christos     {
   1911   1.7  christos       gdbpy_print_stack ();
   1912   1.1  christos       return EXT_LANG_RC_ERROR;
   1913   1.1  christos     }
   1914   1.7  christos 
   1915   1.7  christos   gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
   1916   1.1  christos   if (type_module == NULL)
   1917   1.1  christos     {
   1918   1.1  christos       gdbpy_print_stack ();
   1919   1.7  christos       return EXT_LANG_RC_ERROR;
   1920   1.1  christos     }
   1921   1.1  christos 
   1922   1.7  christos   gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
   1923   1.7  christos 					    "apply_type_recognizers"));
   1924   1.7  christos   if (func == NULL)
   1925   1.7  christos     {
   1926   1.1  christos       gdbpy_print_stack ();
   1927   1.1  christos       return EXT_LANG_RC_ERROR;
   1928   1.1  christos     }
   1929   1.7  christos 
   1930   1.1  christos   gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
   1931   1.1  christos 							printers_obj,
   1932   1.7  christos 							type_obj.get (),
   1933   1.7  christos 							(char *) NULL));
   1934   1.7  christos   if (result_obj == NULL)
   1935   1.7  christos     {
   1936   1.7  christos       gdbpy_print_stack ();
   1937   1.1  christos       return EXT_LANG_RC_ERROR;
   1938   1.7  christos     }
   1939   1.7  christos 
   1940   1.1  christos   if (result_obj == Py_None)
   1941   1.1  christos     return EXT_LANG_RC_NOP;
   1942  1.11  christos 
   1943   1.7  christos   result = python_string_to_host_string (result_obj.get ());
   1944   1.1  christos   if (result == NULL)
   1945   1.1  christos     {
   1946   1.3  christos       gdbpy_print_stack ();
   1947   1.3  christos       return EXT_LANG_RC_ERROR;
   1948   1.1  christos     }
   1949   1.3  christos 
   1950   1.3  christos   *prettied_type = std::move (result);
   1951   1.3  christos   return EXT_LANG_RC_OK;
   1952   1.1  christos }
   1953   1.6  christos 
   1954   1.1  christos /* Free the result of start_type_printers.
   1955   1.1  christos    This is the extension_language_ops.free_type_printers "method".  */
   1956   1.1  christos 
   1957   1.1  christos static void
   1958   1.1  christos gdbpy_free_type_printers (const struct extension_language_defn *extlang,
   1959   1.1  christos 			  struct ext_lang_type_printers *ext_printers)
   1960   1.1  christos {
   1961  1.10  christos   PyObject *printers = (PyObject *) ext_printers->py_type_printers;
   1962   1.1  christos 
   1963   1.1  christos   if (printers == NULL)
   1964   1.1  christos     return;
   1965   1.1  christos 
   1966   1.1  christos   if (!gdb_python_initialized)
   1967   1.1  christos     return;
   1968   1.1  christos 
   1969   1.1  christos   gdbpy_enter enter_py;
   1970   1.1  christos   Py_DECREF (printers);
   1971   1.8  christos }
   1972   1.1  christos 
   1973   1.1  christos #else /* HAVE_PYTHON */
   1974   1.1  christos 
   1975   1.1  christos /* Dummy implementation of the gdb "python-interactive" and "python"
   1976   1.1  christos    command. */
   1977   1.1  christos 
   1978   1.8  christos static void
   1979   1.1  christos python_interactive_command (const char *arg, int from_tty)
   1980   1.7  christos {
   1981   1.1  christos   arg = skip_spaces (arg);
   1982   1.1  christos   if (arg && *arg)
   1983   1.1  christos     error (_("Python scripting is not supported in this copy of GDB."));
   1984   1.1  christos   else
   1985   1.8  christos     {
   1986   1.1  christos       counted_command_line l = get_command_line (python_control, "");
   1987   1.1  christos 
   1988   1.1  christos       execute_control_command_untraced (l.get ());
   1989   1.1  christos     }
   1990   1.1  christos }
   1991   1.1  christos 
   1992  1.10  christos static void
   1993  1.10  christos python_command (const char *arg, int from_tty)
   1994  1.10  christos {
   1995  1.10  christos   python_interactive_command (arg, from_tty);
   1996  1.10  christos }
   1997  1.10  christos 
   1998  1.10  christos #endif /* HAVE_PYTHON */
   1999  1.10  christos 
   2000  1.10  christos /* When this is turned on before Python is initialised then Python will
   2001  1.10  christos    ignore any environment variables related to Python.  This is equivalent
   2002  1.10  christos    to passing `-E' to the python program.  */
   2003  1.10  christos static bool python_ignore_environment = false;
   2004  1.10  christos 
   2005  1.10  christos /* Implement 'show python ignore-environment'.  */
   2006  1.10  christos 
   2007  1.10  christos static void
   2008  1.10  christos show_python_ignore_environment (struct ui_file *file, int from_tty,
   2009  1.10  christos 				struct cmd_list_element *c, const char *value)
   2010  1.10  christos {
   2011  1.10  christos   gdb_printf (file, _("Python's ignore-environment setting is %s.\n"),
   2012  1.10  christos 	      value);
   2013  1.10  christos }
   2014  1.10  christos 
   2015  1.10  christos /* Implement 'set python ignore-environment'.  This sets Python's internal
   2016  1.10  christos    flag no matter when the command is issued, however, if this is used
   2017  1.10  christos    after Py_Initialize has been called then most of the environment will
   2018  1.10  christos    already have been read.  */
   2019  1.10  christos 
   2020  1.10  christos static void
   2021  1.10  christos set_python_ignore_environment (const char *args, int from_tty,
   2022  1.10  christos 			       struct cmd_list_element *c)
   2023  1.10  christos {
   2024  1.10  christos #ifdef HAVE_PYTHON
   2025  1.10  christos   /* Py_IgnoreEnvironmentFlag is deprecated in Python 3.12.  Disable
   2026  1.10  christos      its usage in Python 3.10 and above since the PyConfig mechanism
   2027  1.10  christos      is now (also) used in 3.10 and higher.  See do_start_initialization()
   2028  1.10  christos      in this file.  */
   2029  1.10  christos #if PY_VERSION_HEX < 0x030a0000
   2030  1.10  christos   Py_IgnoreEnvironmentFlag = python_ignore_environment ? 1 : 0;
   2031  1.10  christos #endif
   2032  1.10  christos #endif
   2033  1.10  christos }
   2034  1.10  christos 
   2035  1.10  christos /* When this is turned on before Python is initialised then Python will
   2036  1.10  christos    not write `.pyc' files on import of a module.  */
   2037  1.10  christos static enum auto_boolean python_dont_write_bytecode = AUTO_BOOLEAN_AUTO;
   2038  1.10  christos 
   2039  1.10  christos /* Implement 'show python dont-write-bytecode'.  */
   2040  1.10  christos 
   2041  1.10  christos static void
   2042  1.10  christos show_python_dont_write_bytecode (struct ui_file *file, int from_tty,
   2043  1.10  christos 				 struct cmd_list_element *c, const char *value)
   2044  1.10  christos {
   2045  1.10  christos   if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
   2046  1.10  christos     {
   2047  1.10  christos       const char *auto_string
   2048  1.10  christos 	= (python_ignore_environment
   2049  1.10  christos 	   || getenv ("PYTHONDONTWRITEBYTECODE") == nullptr) ? "off" : "on";
   2050  1.10  christos 
   2051  1.10  christos       gdb_printf (file,
   2052  1.10  christos 		  _("Python's dont-write-bytecode setting is %s (currently %s).\n"),
   2053  1.10  christos 		  value, auto_string);
   2054  1.10  christos     }
   2055  1.10  christos   else
   2056  1.10  christos     gdb_printf (file, _("Python's dont-write-bytecode setting is %s.\n"),
   2057  1.10  christos 		value);
   2058  1.10  christos }
   2059  1.10  christos 
   2060  1.10  christos #ifdef HAVE_PYTHON
   2061  1.10  christos /* Return value to assign to PyConfig.write_bytecode or, when
   2062  1.10  christos    negated (via !), Py_DontWriteBytecodeFlag.  Py_DontWriteBytecodeFlag
   2063  1.10  christos    is deprecated in Python 3.12.  */
   2064  1.10  christos 
   2065  1.10  christos static int
   2066  1.10  christos python_write_bytecode ()
   2067  1.10  christos {
   2068  1.10  christos   int wbc = 0;
   2069  1.10  christos 
   2070  1.10  christos   if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
   2071  1.10  christos     {
   2072  1.10  christos       if (python_ignore_environment)
   2073  1.10  christos 	wbc = 1;
   2074  1.10  christos       else
   2075  1.10  christos 	{
   2076  1.10  christos 	  const char *pdwbc = getenv ("PYTHONDONTWRITEBYTECODE");
   2077  1.10  christos 	  wbc = (pdwbc == nullptr || pdwbc[0] == '\0') ? 1 : 0;
   2078  1.10  christos 	}
   2079  1.10  christos     }
   2080  1.10  christos   else
   2081  1.10  christos     wbc = python_dont_write_bytecode == AUTO_BOOLEAN_TRUE ? 0 : 1;
   2082  1.10  christos 
   2083  1.10  christos   return wbc;
   2084  1.10  christos }
   2085  1.10  christos #endif /* HAVE_PYTHON */
   2086  1.10  christos 
   2087  1.10  christos /* Implement 'set python dont-write-bytecode'.  This sets Python's internal
   2088  1.10  christos    flag no matter when the command is issued, however, if this is used
   2089  1.10  christos    after Py_Initialize has been called then many modules could already
   2090  1.10  christos    have been imported and their byte code written out.  */
   2091  1.10  christos 
   2092  1.10  christos static void
   2093  1.10  christos set_python_dont_write_bytecode (const char *args, int from_tty,
   2094  1.10  christos 				struct cmd_list_element *c)
   2095  1.10  christos {
   2096  1.10  christos #ifdef HAVE_PYTHON
   2097  1.10  christos   /* Py_DontWriteBytecodeFlag is deprecated in Python 3.12.  Disable
   2098  1.10  christos      its usage in Python 3.10 and above since the PyConfig mechanism
   2099   1.1  christos      is now (also) used in 3.10 and higher.  See do_start_initialization()
   2100   1.1  christos      in this file.  */
   2101   1.1  christos #if PY_VERSION_HEX < 0x030a0000
   2102   1.1  christos   Py_DontWriteBytecodeFlag = !python_write_bytecode ();
   2103   1.1  christos #endif
   2104   1.1  christos #endif /* HAVE_PYTHON */
   2105   1.1  christos }
   2106   1.1  christos 
   2107   1.1  christos 
   2108   1.1  christos 
   2110   1.1  christos /* Lists for 'set python' commands.  */
   2111   1.1  christos 
   2112   1.1  christos static struct cmd_list_element *user_set_python_list;
   2113   1.1  christos static struct cmd_list_element *user_show_python_list;
   2114  1.11  christos 
   2115   1.1  christos /* Initialize the Python code.  */
   2116   1.3  christos 
   2117   1.3  christos #ifdef HAVE_PYTHON
   2118   1.1  christos 
   2119   1.1  christos /* This is installed as a final cleanup and cleans up the
   2120   1.1  christos    interpreter.  This lets Python's 'atexit' work.  */
   2121   1.1  christos 
   2122   1.1  christos static void
   2123   1.3  christos finalize_python (const struct extension_language_defn *ignore)
   2124   1.3  christos {
   2125   1.3  christos   struct active_ext_lang_state *previous_active;
   2126   1.3  christos 
   2127   1.3  christos   /* We don't use ensure_python_env here because if we ever ran the
   2128   1.1  christos      cleanup, gdb would crash -- because the cleanup calls into the
   2129  1.10  christos      Python interpreter, which we are about to destroy.  It seems
   2130  1.10  christos      clearer to make the needed calls explicitly here than to create a
   2131  1.11  christos      cleanup and then mysteriously discard it.  */
   2132  1.11  christos 
   2133   1.1  christos   /* This is only called as a final cleanup so we can assume the active
   2134   1.1  christos      SIGINT handler is gdb's.  We still need to tell it to notify Python.  */
   2135   1.3  christos   previous_active = set_active_ext_lang (&extension_language_python);
   2136   1.9  christos 
   2137   1.3  christos   (void) PyGILState_Ensure ();
   2138   1.1  christos   gdbpy_enter::finalize ();
   2139   1.8  christos 
   2140  1.10  christos   /* Call the gdbpy_finalize_* functions from every *.c file.  */
   2141  1.10  christos   gdbpy_initialize_file::finalize_all ();
   2142  1.10  christos 
   2143  1.10  christos   Py_Finalize ();
   2144  1.10  christos 
   2145  1.10  christos   gdb_python_initialized = false;
   2146  1.10  christos   restore_active_ext_lang (previous_active);
   2147  1.10  christos }
   2148  1.10  christos 
   2149  1.10  christos static struct PyModuleDef python_GdbModuleDef =
   2150  1.10  christos {
   2151  1.10  christos   PyModuleDef_HEAD_INIT,
   2152  1.10  christos   "_gdb",
   2153   1.8  christos   NULL,
   2154   1.8  christos   -1,
   2155   1.8  christos   python_GdbMethods,
   2156   1.9  christos   NULL,
   2157   1.8  christos   NULL,
   2158   1.8  christos   NULL,
   2159   1.8  christos   NULL
   2160   1.8  christos };
   2161   1.8  christos 
   2162  1.10  christos /* This is called via the PyImport_AppendInittab mechanism called
   2163  1.10  christos    during initialization, to make the built-in _gdb module known to
   2164  1.10  christos    Python.  */
   2165  1.10  christos PyMODINIT_FUNC init__gdb_module (void);
   2166  1.10  christos PyMODINIT_FUNC
   2167  1.10  christos init__gdb_module (void)
   2168  1.10  christos {
   2169  1.10  christos   return PyModule_Create (&python_GdbModuleDef);
   2170  1.10  christos }
   2171  1.10  christos 
   2172  1.10  christos /* Emit a gdb.GdbExitingEvent, return a negative value if there are any
   2173  1.10  christos    errors, otherwise, return 0.  */
   2174  1.10  christos 
   2175  1.10  christos static int
   2176  1.10  christos emit_exiting_event (int exit_code)
   2177  1.10  christos {
   2178  1.10  christos   if (evregpy_no_listeners_p (gdb_py_events.gdb_exiting))
   2179  1.10  christos     return 0;
   2180  1.10  christos 
   2181  1.10  christos   gdbpy_ref<> event_obj = create_event_object (&gdb_exiting_event_object_type);
   2182  1.10  christos   if (event_obj == nullptr)
   2183  1.10  christos     return -1;
   2184  1.10  christos 
   2185  1.10  christos   gdbpy_ref<> code = gdb_py_object_from_longest (exit_code);
   2186  1.10  christos   if (evpy_add_attribute (event_obj.get (), "exit_code", code.get ()) < 0)
   2187  1.10  christos     return -1;
   2188  1.10  christos 
   2189  1.10  christos   return evpy_emit_event (event_obj.get (), gdb_py_events.gdb_exiting);
   2190  1.10  christos }
   2191  1.10  christos 
   2192  1.10  christos /* Callback for the gdb_exiting observable.  EXIT_CODE is the value GDB
   2193  1.10  christos    will exit with.  */
   2194  1.10  christos 
   2195  1.10  christos static void
   2196  1.10  christos gdbpy_gdb_exiting (int exit_code)
   2197   1.1  christos {
   2198   1.7  christos   if (!gdb_python_initialized)
   2199   1.7  christos     return;
   2200   1.1  christos 
   2201  1.10  christos   gdbpy_enter enter_py;
   2202  1.10  christos 
   2203  1.10  christos   if (emit_exiting_event (exit_code) < 0)
   2204  1.10  christos     gdbpy_print_stack ();
   2205  1.10  christos }
   2206  1.10  christos 
   2207  1.10  christos static bool
   2208  1.10  christos do_start_initialization ()
   2209  1.10  christos {
   2210  1.10  christos   /* Define all internal modules.  These are all imported (and thus
   2211  1.10  christos      created) during initialization.  */
   2212   1.1  christos   struct _inittab mods[] =
   2213   1.1  christos   {
   2214   1.1  christos     { "_gdb", init__gdb_module },
   2215   1.1  christos     { "_gdbevents", gdbpy_events_mod_func },
   2216   1.1  christos     { nullptr, nullptr }
   2217   1.1  christos   };
   2218   1.1  christos 
   2219   1.1  christos   if (PyImport_ExtendInittab (mods) < 0)
   2220   1.8  christos     return false;
   2221   1.9  christos 
   2222   1.8  christos #ifdef WITH_PYTHON_PATH
   2223  1.10  christos   /* Work around problem where python gets confused about where it is,
   2224  1.10  christos      and then can't find its libraries, etc.
   2225  1.10  christos      NOTE: Python assumes the following layout:
   2226  1.10  christos      /foo/bin/python
   2227  1.10  christos      /foo/lib/pythonX.Y/...
   2228  1.10  christos      This must be done before calling Py_Initialize.  */
   2229  1.10  christos   gdb::unique_xmalloc_ptr<char> progname
   2230  1.10  christos     (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
   2231  1.10  christos 	      SLASH_STRING, "python", (char *) NULL));
   2232   1.8  christos   /* Python documentation indicates that the memory given
   2233   1.1  christos      to Py_SetProgramName cannot be freed.  However, it seems that
   2234  1.10  christos      at least Python 3.7.4 Py_SetProgramName takes a copy of the
   2235   1.9  christos      given program_name.  Making progname_copy static and not release
   2236  1.10  christos      the memory avoids a leak report for Python versions that duplicate
   2237   1.1  christos      program_name, and respect the requirement of Py_SetProgramName
   2238   1.1  christos      for Python versions that do not duplicate program_name.  */
   2239   1.1  christos   static wchar_t *progname_copy;
   2240   1.7  christos 
   2241   1.1  christos   std::string oldloc = setlocale (LC_ALL, NULL);
   2242   1.8  christos   setlocale (LC_ALL, "");
   2243   1.1  christos   size_t progsize = strlen (progname.get ());
   2244  1.10  christos   progname_copy = XNEWVEC (wchar_t, progsize + 1);
   2245  1.10  christos   size_t count = mbstowcs (progname_copy, progname.get (), progsize + 1);
   2246  1.10  christos   if (count == (size_t) -1)
   2247   1.1  christos     {
   2248   1.1  christos       fprintf (stderr, "Could not convert python path to string\n");
   2249   1.1  christos       return false;
   2250   1.1  christos     }
   2251  1.10  christos   setlocale (LC_ALL, oldloc.c_str ());
   2252  1.10  christos 
   2253  1.10  christos   /* Py_SetProgramName was deprecated in Python 3.11.  Use PyConfig
   2254   1.8  christos      mechanisms for Python 3.10 and newer.  */
   2255  1.10  christos #if PY_VERSION_HEX < 0x030a0000
   2256  1.10  christos   /* Note that Py_SetProgramName expects the string it is passed to
   2257  1.11  christos      remain alive for the duration of the program's execution, so
   2258  1.10  christos      it is not freed after this call.  */
   2259  1.10  christos   Py_SetProgramName (progname_copy);
   2260  1.10  christos   Py_Initialize ();
   2261  1.10  christos #else
   2262  1.10  christos   PyConfig config;
   2263  1.10  christos 
   2264  1.10  christos   PyConfig_InitPythonConfig (&config);
   2265  1.10  christos   PyStatus status = PyConfig_SetString (&config, &config.program_name,
   2266  1.10  christos 					progname_copy);
   2267  1.10  christos   if (PyStatus_Exception (status))
   2268  1.10  christos     goto init_done;
   2269  1.10  christos 
   2270  1.10  christos   config.write_bytecode = python_write_bytecode ();
   2271  1.10  christos   config.use_environment = !python_ignore_environment;
   2272  1.10  christos 
   2273  1.10  christos   status = PyConfig_Read (&config);
   2274  1.10  christos   if (PyStatus_Exception (status))
   2275   1.1  christos     goto init_done;
   2276  1.10  christos 
   2277   1.1  christos   status = Py_InitializeFromConfig (&config);
   2278   1.1  christos 
   2279   1.9  christos init_done:
   2280   1.9  christos   PyConfig_Clear (&config);
   2281   1.9  christos   if (PyStatus_Exception (status))
   2282   1.9  christos     return false;
   2283   1.1  christos #endif
   2284   1.9  christos #else
   2285   1.1  christos   Py_Initialize ();
   2286   1.8  christos #endif
   2287   1.1  christos 
   2288   1.7  christos #if PY_VERSION_HEX < 0x03090000
   2289   1.1  christos   /* PyEval_InitThreads became deprecated in Python 3.9 and will
   2290   1.9  christos      be removed in Python 3.11.  Prior to Python 3.7, this call was
   2291   1.9  christos      required to initialize the GIL.  */
   2292   1.1  christos   PyEval_InitThreads ();
   2293   1.9  christos #endif
   2294   1.7  christos 
   2295   1.1  christos   gdb_module = PyImport_ImportModule ("_gdb");
   2296   1.1  christos   if (gdb_module == NULL)
   2297   1.1  christos     return false;
   2298   1.1  christos 
   2299   1.1  christos   if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
   2300   1.7  christos       || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
   2301   1.1  christos       || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
   2302   1.1  christos 				     target_name) < 0)
   2303   1.1  christos     return false;
   2304   1.1  christos 
   2305   1.7  christos   /* Add stream constants.  */
   2306   1.1  christos   if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
   2307   1.1  christos       || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
   2308   1.1  christos       || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
   2309   1.1  christos     return false;
   2310   1.1  christos 
   2311   1.1  christos   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
   2312   1.7  christos   if (gdbpy_gdb_error == NULL
   2313   1.1  christos       || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
   2314   1.1  christos     return false;
   2315   1.1  christos 
   2316   1.1  christos   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
   2317   1.1  christos 					       gdbpy_gdb_error, NULL);
   2318   1.7  christos   if (gdbpy_gdb_memory_error == NULL
   2319   1.1  christos       || gdb_pymodule_addobject (gdb_module, "MemoryError",
   2320  1.11  christos 				 gdbpy_gdb_memory_error) < 0)
   2321  1.11  christos     return false;
   2322   1.7  christos 
   2323   1.1  christos   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
   2324   1.8  christos   if (gdbpy_gdberror_exc == NULL
   2325   1.8  christos       || gdb_pymodule_addobject (gdb_module, "GdbError",
   2326   1.8  christos 				 gdbpy_gdberror_exc) < 0)
   2327   1.8  christos     return false;
   2328   1.8  christos 
   2329   1.8  christos   /* Call the gdbpy_initialize_* functions from every *.c file.  */
   2330  1.10  christos   if (!gdbpy_initialize_file::initialize_all ())
   2331   1.1  christos     return false;
   2332   1.7  christos 
   2333  1.10  christos #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base)	\
   2334   1.1  christos   if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
   2335   1.7  christos     return false;
   2336  1.10  christos #include "py-event-types.def"
   2337   1.1  christos #undef GDB_PY_DEFINE_EVENT_TYPE
   2338   1.7  christos 
   2339  1.10  christos   gdbpy_to_string_cst = PyUnicode_FromString ("to_string");
   2340   1.1  christos   if (gdbpy_to_string_cst == NULL)
   2341   1.7  christos     return false;
   2342  1.10  christos   gdbpy_children_cst = PyUnicode_FromString ("children");
   2343   1.1  christos   if (gdbpy_children_cst == NULL)
   2344   1.7  christos     return false;
   2345  1.10  christos   gdbpy_display_hint_cst = PyUnicode_FromString ("display_hint");
   2346   1.1  christos   if (gdbpy_display_hint_cst == NULL)
   2347   1.7  christos     return false;
   2348   1.1  christos   gdbpy_doc_cst = PyUnicode_FromString ("__doc__");
   2349  1.10  christos   if (gdbpy_doc_cst == NULL)
   2350  1.10  christos     return false;
   2351   1.1  christos   gdbpy_enabled_cst = PyUnicode_FromString ("enabled");
   2352   1.9  christos   if (gdbpy_enabled_cst == NULL)
   2353   1.1  christos     return false;
   2354   1.7  christos   gdbpy_value_cst = PyUnicode_FromString ("value");
   2355   1.1  christos   if (gdbpy_value_cst == NULL)
   2356   1.7  christos     return false;
   2357   1.7  christos 
   2358   1.7  christos   gdb::observers::gdb_exiting.attach (gdbpy_gdb_exiting, "python");
   2359  1.10  christos 
   2360  1.10  christos   /* Release the GIL while gdb runs.  */
   2361  1.10  christos   PyEval_SaveThread ();
   2362  1.10  christos 
   2363  1.10  christos   /* Only set this when initialization has succeeded.  */
   2364  1.10  christos   gdb_python_initialized = 1;
   2365  1.10  christos   return true;
   2366  1.10  christos }
   2367  1.10  christos 
   2368  1.10  christos #if GDB_SELF_TEST
   2369  1.10  christos namespace selftests {
   2370  1.10  christos 
   2371  1.10  christos /* Entry point for python unit tests.  */
   2372  1.10  christos 
   2373  1.10  christos static void
   2374  1.10  christos test_python ()
   2375  1.10  christos {
   2376  1.10  christos #define CMD(S) execute_command_to_string (S, "python print(5)", 0, true)
   2377  1.10  christos 
   2378  1.10  christos   std::string output;
   2379  1.10  christos 
   2380  1.10  christos   CMD (output);
   2381  1.10  christos   SELF_CHECK (output == "5\n");
   2382  1.10  christos   output.clear ();
   2383  1.10  christos 
   2384  1.10  christos   bool saw_exception = false;
   2385  1.10  christos   {
   2386  1.10  christos     scoped_restore reset_gdb_python_initialized
   2387  1.10  christos       = make_scoped_restore (&gdb_python_initialized, 0);
   2388  1.10  christos     try
   2389  1.10  christos       {
   2390  1.10  christos 	CMD (output);
   2391  1.10  christos       }
   2392  1.10  christos     catch (const gdb_exception &e)
   2393  1.10  christos       {
   2394  1.10  christos 	saw_exception = true;
   2395  1.10  christos 	SELF_CHECK (e.reason == RETURN_ERROR);
   2396  1.10  christos 	SELF_CHECK (e.error == GENERIC_ERROR);
   2397  1.10  christos 	SELF_CHECK (*e.message == "Python not initialized");
   2398  1.10  christos       }
   2399  1.10  christos     SELF_CHECK (saw_exception);
   2400  1.10  christos     SELF_CHECK (output.empty ());
   2401  1.10  christos   }
   2402  1.10  christos 
   2403  1.11  christos   saw_exception = false;
   2404  1.10  christos   {
   2405  1.10  christos     scoped_restore save_hook
   2406  1.11  christos       = make_scoped_restore (&hook_set_active_ext_lang,
   2407  1.11  christos 			     []() { raise (SIGINT); });
   2408  1.11  christos     try
   2409  1.10  christos       {
   2410  1.10  christos 	CMD (output);
   2411  1.11  christos       }
   2412  1.10  christos     catch (const gdb_exception_quit &e)
   2413  1.10  christos       {
   2414  1.10  christos 	saw_exception = true;
   2415  1.10  christos 	SELF_CHECK (e.reason == RETURN_QUIT);
   2416  1.10  christos 	SELF_CHECK (e.error == GDB_NO_ERROR);
   2417  1.10  christos 	SELF_CHECK (*e.message == "Quit");
   2418  1.10  christos       }
   2419  1.10  christos     SELF_CHECK (saw_exception);
   2420  1.10  christos     SELF_CHECK (output.empty ());
   2421  1.10  christos   }
   2422   1.7  christos 
   2423   1.7  christos #undef CMD
   2424   1.8  christos }
   2425   1.8  christos 
   2426   1.8  christos #undef CHECK_OUTPUT
   2427   1.9  christos 
   2428   1.7  christos } // namespace selftests
   2429   1.9  christos #endif /* GDB_SELF_TEST */
   2430   1.7  christos 
   2431  1.10  christos #endif /* HAVE_PYTHON */
   2432  1.10  christos 
   2433  1.10  christos /* See python.h.  */
   2434   1.7  christos cmd_list_element *python_cmd_element = nullptr;
   2435   1.7  christos 
   2436   1.7  christos void _initialize_python ();
   2437   1.7  christos void
   2438   1.7  christos _initialize_python ()
   2439   1.7  christos {
   2440   1.7  christos   cmd_list_element *python_interactive_cmd
   2441   1.7  christos     =	add_com ("python-interactive", class_obscure,
   2442   1.7  christos 		 python_interactive_command,
   2443   1.7  christos #ifdef HAVE_PYTHON
   2444   1.7  christos 	   _("\
   2445   1.7  christos Start an interactive Python prompt.\n\
   2446   1.9  christos \n\
   2447   1.7  christos To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
   2448   1.7  christos prompt).\n\
   2449   1.7  christos \n\
   2450   1.7  christos Alternatively, a single-line Python command can be given as an\n\
   2451   1.7  christos argument, and if the command is an expression, the result will be\n\
   2452   1.7  christos printed.  For example:\n\
   2453   1.7  christos \n\
   2454   1.7  christos     (gdb) python-interactive 2 + 3\n\
   2455  1.10  christos     5")
   2456   1.7  christos #else /* HAVE_PYTHON */
   2457   1.8  christos 	   _("\
   2458   1.7  christos Start a Python interactive prompt.\n\
   2459   1.7  christos \n\
   2460   1.7  christos Python scripting is not supported in this copy of GDB.\n\
   2461   1.7  christos This command is only a placeholder.")
   2462   1.7  christos #endif /* HAVE_PYTHON */
   2463   1.7  christos 	   );
   2464   1.8  christos   add_com_alias ("pi", python_interactive_cmd, class_obscure, 1);
   2465   1.7  christos 
   2466   1.7  christos   python_cmd_element = add_com ("python", class_obscure, python_command,
   2467   1.7  christos #ifdef HAVE_PYTHON
   2468   1.7  christos 	   _("\
   2469   1.7  christos Evaluate a Python command.\n\
   2470   1.7  christos \n\
   2471   1.7  christos The command can be given as an argument, for instance:\n\
   2472   1.7  christos \n\
   2473   1.7  christos     python print (23)\n\
   2474   1.7  christos \n\
   2475   1.7  christos If no argument is given, the following lines are read and used\n\
   2476   1.7  christos as the Python commands.  Type a line containing \"end\" to indicate\n\
   2477  1.10  christos the end of the command.")
   2478   1.1  christos #else /* HAVE_PYTHON */
   2479   1.7  christos 	   _("\
   2480  1.10  christos Evaluate a Python command.\n\
   2481  1.10  christos \n\
   2482  1.10  christos Python scripting is not supported in this copy of GDB.\n\
   2483  1.10  christos This command is only a placeholder.")
   2484  1.10  christos #endif /* HAVE_PYTHON */
   2485   1.7  christos 	   );
   2486   1.7  christos   add_com_alias ("py", python_cmd_element, class_obscure, 1);
   2487   1.7  christos 
   2488   1.7  christos   /* Add set/show python print-stack.  */
   2489   1.7  christos   add_setshow_prefix_cmd ("python", no_class,
   2490   1.7  christos 			  _("Prefix command for python preference settings."),
   2491   1.7  christos 			  _("Prefix command for python preference settings."),
   2492   1.7  christos 			  &user_set_python_list, &user_show_python_list,
   2493   1.7  christos 			  &setlist, &showlist);
   2494   1.7  christos 
   2495   1.7  christos   add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
   2496   1.1  christos 			&gdbpy_should_print_stack, _("\
   2497  1.10  christos Set mode for Python stack dump on error."), _("\
   2498  1.10  christos Show the mode of Python stack printing on error."), _("\
   2499  1.11  christos none  == no stack or message will be printed.\n\
   2500  1.11  christos full == a message and a stack will be printed.\n\
   2501  1.11  christos message == an error message without a stack will be printed."),
   2502  1.11  christos 			NULL, NULL,
   2503  1.10  christos 			&user_set_python_list,
   2504  1.10  christos 			&user_show_python_list);
   2505  1.10  christos 
   2506  1.10  christos   add_setshow_boolean_cmd ("ignore-environment", no_class,
   2507  1.10  christos 			   &python_ignore_environment, _("\
   2508  1.10  christos Set whether the Python interpreter should ignore environment variables."), _("\
   2509  1.10  christos Show whether the Python interpreter showlist ignore environment variables."), _("\
   2510  1.10  christos When enabled GDB's Python interpreter will ignore any Python related\n\
   2511  1.10  christos flags in the environment.  This is equivalent to passing `-E' to a\n\
   2512  1.10  christos python executable."),
   2513  1.10  christos 			   set_python_ignore_environment,
   2514  1.10  christos 			   show_python_ignore_environment,
   2515  1.10  christos 			   &user_set_python_list,
   2516  1.10  christos 			   &user_show_python_list);
   2517  1.10  christos 
   2518  1.10  christos   add_setshow_auto_boolean_cmd ("dont-write-bytecode", no_class,
   2519  1.10  christos 				&python_dont_write_bytecode, _("\
   2520  1.10  christos Set whether the Python interpreter should avoid byte-compiling python modules."), _("\
   2521  1.10  christos Show whether the Python interpreter should avoid byte-compiling python modules."), _("\
   2522  1.10  christos When enabled, GDB's embedded Python interpreter won't byte-compile python\n\
   2523  1.10  christos modules.  In order to take effect, this setting must be enabled in an early\n\
   2524  1.10  christos initialization file, i.e. those run via the --early-init-eval-command or\n\
   2525  1.10  christos -eix command line options.  A 'set python dont-write-bytecode on' command\n\
   2526  1.10  christos can also be issued directly from the GDB command line via the\n\
   2527  1.10  christos --early-init-eval-command or -eiex command line options.\n\
   2528  1.10  christos \n\
   2529  1.10  christos This setting defaults to 'auto'.  In this mode, provided the 'python\n\
   2530  1.10  christos ignore-environment' setting is 'off', the environment variable\n\
   2531  1.10  christos PYTHONDONTWRITEBYTECODE is examined to determine whether or not to\n\
   2532   1.7  christos byte-compile python modules.  PYTHONDONTWRITEBYTECODE is considered to be\n\
   2533  1.10  christos off/disabled either when set to the empty string or when the\n\
   2534  1.10  christos environment variable doesn't exist.  All other settings, including those\n\
   2535  1.10  christos which don't seem to make sense, indicate that it's on/enabled."),
   2536   1.1  christos 				set_python_dont_write_bytecode,
   2537   1.1  christos 				show_python_dont_write_bytecode,
   2538   1.1  christos 				&user_set_python_list,
   2539   1.1  christos 				&user_show_python_list);
   2540   1.1  christos 
   2541  1.10  christos #ifdef HAVE_PYTHON
   2542  1.10  christos #if GDB_SELF_TEST
   2543  1.10  christos   selftests::register_test ("python", selftests::test_python);
   2544   1.1  christos #endif /* GDB_SELF_TEST */
   2545   1.7  christos #endif /* HAVE_PYTHON */
   2546  1.10  christos }
   2547   1.1  christos 
   2548   1.1  christos #ifdef HAVE_PYTHON
   2549   1.1  christos 
   2550   1.1  christos /* Helper function for gdbpy_initialize.  This does the work and then
   2551   1.1  christos    returns false if an error has occurred and must be displayed, or true on
   2552   1.1  christos    success.  */
   2553   1.7  christos 
   2554   1.7  christos static bool
   2555   1.1  christos do_initialize (const struct extension_language_defn *extlang)
   2556   1.1  christos {
   2557   1.1  christos   PyObject *m;
   2558  1.10  christos   PyObject *sys_path;
   2559  1.10  christos 
   2560  1.10  christos   /* Add the initial data-directory to sys.path.  */
   2561  1.10  christos 
   2562  1.10  christos   std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
   2563  1.10  christos 			       + "python");
   2564  1.10  christos 
   2565  1.10  christos   sys_path = PySys_GetObject ("path");
   2566  1.10  christos 
   2567  1.10  christos   /* PySys_SetPath was deprecated in Python 3.11.  Disable this
   2568   1.1  christos      deprecated code for Python 3.10 and newer.  Also note that this
   2569   1.1  christos      ifdef eliminates potential initialization of sys.path via
   2570   1.1  christos      PySys_SetPath.  My (kevinb's) understanding of PEP 587 suggests
   2571   1.1  christos      that it's not necessary due to module_search_paths being
   2572   1.1  christos      initialized to an empty list following any of the PyConfig
   2573   1.1  christos      initialization functions.  If it does turn out that some kind of
   2574  1.10  christos      initialization is still needed, it should be added to the
   2575   1.1  christos      PyConfig-based initialization in do_start_initialize().  */
   2576   1.1  christos #if PY_VERSION_HEX < 0x030a0000
   2577  1.10  christos   /* If sys.path is not defined yet, define it first.  */
   2578   1.7  christos   if (!(sys_path && PyList_Check (sys_path)))
   2579   1.7  christos     {
   2580   1.1  christos       PySys_SetPath (L"");
   2581   1.1  christos       sys_path = PySys_GetObject ("path");
   2582   1.7  christos     }
   2583   1.1  christos #endif
   2584   1.1  christos   if (sys_path && PyList_Check (sys_path))
   2585   1.1  christos     {
   2586   1.1  christos       gdbpy_ref<> pythondir (PyUnicode_FromString (gdb_pythondir.c_str ()));
   2587   1.1  christos       if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
   2588   1.7  christos 	return false;
   2589   1.1  christos     }
   2590   1.7  christos   else
   2591   1.7  christos     return false;
   2592   1.1  christos 
   2593   1.1  christos   /* Import the gdb module to finish the initialization, and
   2594   1.1  christos      add it to __main__ for convenience.  */
   2595   1.1  christos   m = PyImport_AddModule ("__main__");
   2596   1.1  christos   if (m == NULL)
   2597   1.1  christos     return false;
   2598   1.1  christos 
   2599   1.1  christos   /* Keep the reference to gdb_python_module since it is in a global
   2600   1.1  christos      variable.  */
   2601   1.9  christos   gdb_python_module = PyImport_ImportModule ("gdb");
   2602   1.7  christos   if (gdb_python_module == NULL)
   2603   1.7  christos     {
   2604   1.7  christos       gdbpy_print_stack ();
   2605   1.7  christos       /* This is passed in one call to warning so that blank lines aren't
   2606   1.1  christos 	 inserted between each line of text.  */
   2607   1.1  christos       warning (_("\n"
   2608   1.7  christos 		 "Could not load the Python gdb module from `%s'.\n"
   2609   1.7  christos 		 "Limited Python support is available from the _gdb module.\n"
   2610   1.1  christos 		 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
   2611  1.10  christos 	       gdb_pythondir.c_str ());
   2612  1.10  christos       /* We return "success" here as we've already emitted the
   2613  1.10  christos 	 warning.  */
   2614   1.1  christos       return true;
   2615   1.7  christos     }
   2616  1.10  christos 
   2617   1.7  christos   return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
   2618  1.10  christos }
   2619  1.10  christos 
   2620  1.10  christos /* Perform Python initialization.  This will be called after GDB has
   2621  1.10  christos    performed all of its own initialization.  This is the
   2622   1.1  christos    extension_language_ops.initialize "method".  */
   2623  1.10  christos 
   2624   1.7  christos static void
   2625   1.7  christos gdbpy_initialize (const struct extension_language_defn *extlang)
   2626   1.7  christos {
   2627   1.7  christos   if (!do_start_initialization () && PyErr_Occurred ())
   2628   1.1  christos     gdbpy_print_stack ();
   2629   1.1  christos 
   2630   1.3  christos   gdbpy_enter enter_py;
   2631   1.3  christos 
   2632   1.3  christos   if (!do_initialize (extlang))
   2633   1.3  christos     {
   2634   1.3  christos       gdbpy_print_stack ();
   2635   1.3  christos       warning (_("internal error: Unhandled Python exception"));
   2636   1.3  christos     }
   2637   1.3  christos }
   2638   1.3  christos 
   2639   1.5  christos /* Return non-zero if Python has successfully initialized.
   2640   1.1  christos    This is the extension_languages_ops.initialized "method".  */
   2641   1.1  christos 
   2642   1.1  christos static int
   2643  1.10  christos gdbpy_initialized (const struct extension_language_defn *extlang)
   2644  1.10  christos {
   2645  1.10  christos   return gdb_python_initialized;
   2646  1.10  christos }
   2647   1.1  christos 
   2648   1.1  christos PyMethodDef python_GdbMethods[] =
   2649   1.1  christos {
   2650   1.1  christos   { "history", gdbpy_history, METH_VARARGS,
   2651   1.1  christos     "Get a value from history" },
   2652  1.11  christos   { "add_history", gdbpy_add_history, METH_VARARGS,
   2653  1.11  christos     "Add a value to the value history list" },
   2654  1.11  christos   { "history_count", gdbpy_history_count, METH_NOARGS,
   2655  1.11  christos     "Return an integer, the number of values in GDB's value history" },
   2656  1.11  christos   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
   2657   1.1  christos     "execute (command [, from_tty] [, to_string]) -> [String]\n\
   2658   1.1  christos Evaluate command, a string, as a gdb CLI command.  Optionally returns\n\
   2659   1.1  christos a Python String containing the output of the command if to_string is\n\
   2660   1.1  christos set to True." },
   2661   1.1  christos   { "execute_mi", (PyCFunction) gdbpy_execute_mi_command,
   2662   1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2663   1.1  christos     "execute_mi (command, arg...) -> dictionary\n\
   2664   1.1  christos Evaluate command, a string, as a gdb MI command.\n\
   2665   1.1  christos Arguments (also strings) are passed to the command." },
   2666   1.1  christos   { "parameter", gdbpy_parameter, METH_VARARGS,
   2667   1.1  christos     "Return a gdb parameter's value" },
   2668   1.1  christos 
   2669   1.1  christos   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
   2670   1.1  christos     "Return a tuple of all breakpoint objects" },
   2671   1.1  christos 
   2672   1.1  christos   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
   2673   1.1  christos     "Find the default visualizer for a Value." },
   2674   1.1  christos 
   2675   1.1  christos   { "progspaces", gdbpy_progspaces, METH_NOARGS,
   2676   1.1  christos     "Return a sequence of all progspaces." },
   2677   1.1  christos 
   2678   1.1  christos   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
   2679   1.1  christos     "Return the current Objfile being loaded, or None." },
   2680   1.1  christos 
   2681   1.1  christos   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
   2682   1.7  christos     "newest_frame () -> gdb.Frame.\n\
   2683   1.7  christos Return the newest frame object." },
   2684   1.7  christos   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
   2685   1.7  christos     "selected_frame () -> gdb.Frame.\n\
   2686   1.7  christos Return the selected frame object." },
   2687   1.7  christos   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
   2688   1.7  christos     "stop_reason_string (Integer) -> String.\n\
   2689   1.7  christos Return a string explaining unwind stop reason." },
   2690   1.7  christos 
   2691   1.7  christos   { "start_recording", gdbpy_start_recording, METH_VARARGS,
   2692   1.7  christos     "start_recording ([method] [, format]) -> gdb.Record.\n\
   2693   1.7  christos Start recording with the given method.  If no method is given, will fall back\n\
   2694   1.1  christos to the system default method.  If no format is given, will fall back to the\n\
   2695   1.1  christos default format for the given method."},
   2696   1.1  christos   { "current_recording", gdbpy_current_recording, METH_NOARGS,
   2697   1.1  christos     "current_recording () -> gdb.Record.\n\
   2698   1.1  christos Return current recording object." },
   2699   1.1  christos   { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
   2700   1.1  christos     "stop_recording () -> None.\n\
   2701   1.1  christos Stop current recording." },
   2702   1.1  christos 
   2703   1.1  christos   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
   2704   1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2705   1.1  christos     "lookup_type (name [, block]) -> type\n\
   2706   1.1  christos Return a Type corresponding to the given name." },
   2707   1.1  christos   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
   2708   1.9  christos     METH_VARARGS | METH_KEYWORDS,
   2709   1.9  christos     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
   2710   1.9  christos Return a tuple with the symbol corresponding to the given name (or None) and\n\
   2711   1.9  christos a boolean indicating if name is a field of the current implied argument\n\
   2712   1.9  christos `this' (when the current language is object-oriented)." },
   2713   1.9  christos   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
   2714   1.9  christos     METH_VARARGS | METH_KEYWORDS,
   2715   1.9  christos     "lookup_global_symbol (name [, domain]) -> symbol\n\
   2716   1.3  christos Return the symbol corresponding to the given name (or None)." },
   2717   1.3  christos   { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
   2718   1.3  christos     METH_VARARGS | METH_KEYWORDS,
   2719   1.3  christos     "lookup_static_symbol (name [, domain]) -> symbol\n\
   2720   1.3  christos Return the static-linkage symbol corresponding to the given name (or None)." },
   2721   1.3  christos   { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
   2722   1.3  christos     METH_VARARGS | METH_KEYWORDS,
   2723   1.3  christos     "lookup_static_symbols (name [, domain]) -> symbol\n\
   2724   1.1  christos Return a list of all static-linkage symbols corresponding to the given name." },
   2725   1.1  christos 
   2726   1.1  christos   { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
   2727   1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2728   1.1  christos     "lookup_objfile (name, [by_build_id]) -> objfile\n\
   2729   1.1  christos Look up the specified objfile.\n\
   2730   1.1  christos If by_build_id is True, the objfile is looked up by using name\n\
   2731  1.11  christos as its build id." },
   2732  1.11  christos 
   2733  1.11  christos   { "decode_line", gdbpy_decode_line, METH_VARARGS,
   2734   1.1  christos     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
   2735   1.1  christos that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
   2736   1.1  christos The first element contains any unparsed portion of the String parameter\n\
   2737   1.1  christos (or None if the string was fully parsed).  The second element contains\n\
   2738   1.1  christos a tuple that contains all the locations that match, represented as\n\
   2739  1.11  christos gdb.Symtab_and_line objects (or None)."},
   2740  1.11  christos   { "parse_and_eval", (PyCFunction) gdbpy_parse_and_eval,
   2741   1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2742   1.1  christos     "parse_and_eval (String, [Boolean]) -> Value.\n\
   2743   1.1  christos Parse String as an expression, evaluate it, and return the result as a Value."
   2744   1.1  christos   },
   2745   1.1  christos 
   2746   1.1  christos   { "post_event", gdbpy_post_event, METH_VARARGS,
   2747   1.1  christos     "Post an event into gdb's event loop." },
   2748  1.10  christos   { "interrupt", gdbpy_interrupt, METH_NOARGS,
   2749  1.10  christos     "Interrupt gdb's current operation." },
   2750  1.10  christos 
   2751   1.8  christos   { "target_charset", gdbpy_target_charset, METH_NOARGS,
   2752   1.8  christos     "target_charset () -> string.\n\
   2753   1.8  christos Return the name of the current target charset." },
   2754   1.1  christos   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
   2755   1.1  christos     "target_wide_charset () -> string.\n\
   2756   1.1  christos Return the name of the current target wide charset." },
   2757   1.1  christos   { "host_charset", gdbpy_host_charset, METH_NOARGS,
   2758   1.1  christos     "host_charset () -> string.\n\
   2759   1.1  christos Return the name of the current host charset." },
   2760   1.1  christos   { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
   2761   1.1  christos     "rbreak (Regex) -> List.\n\
   2762   1.1  christos Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
   2763   1.1  christos   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
   2764   1.1  christos     "string_to_argv (String) -> Array.\n\
   2765   1.1  christos Parse String and return an argv-like array.\n\
   2766   1.1  christos Arguments are separate by spaces and may be quoted."
   2767   1.1  christos   },
   2768   1.1  christos   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
   2769   1.1  christos     "Write a string using gdb's filtered stream." },
   2770   1.1  christos   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
   2771   1.1  christos     "Flush gdb's filtered stdout stream." },
   2772   1.6  christos   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
   2773   1.6  christos     "selected_thread () -> gdb.InferiorThread.\n\
   2774   1.6  christos Return the selected thread object." },
   2775   1.6  christos   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
   2776   1.6  christos     "selected_inferior () -> gdb.Inferior.\n\
   2777   1.6  christos Return the selected inferior object." },
   2778   1.8  christos   { "inferiors", gdbpy_inferiors, METH_NOARGS,
   2779   1.8  christos     "inferiors () -> (gdb.Inferior, ...).\n\
   2780   1.8  christos Return a tuple containing all inferiors." },
   2781   1.8  christos 
   2782   1.8  christos   { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
   2783   1.8  christos     "invalidate_cached_frames () -> None.\n\
   2784   1.8  christos Invalidate any cached frame objects in gdb.\n\
   2785   1.8  christos Intended for internal use only." },
   2786   1.9  christos 
   2787   1.9  christos   { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
   2788   1.9  christos     "convenience_variable (NAME) -> value.\n\
   2789  1.11  christos Return the value of the convenience variable $NAME,\n\
   2790   1.9  christos or None if not set." },
   2791   1.9  christos   { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
   2792   1.9  christos     "convenience_variable (NAME, VALUE) -> None.\n\
   2793  1.10  christos Set the value of the convenience variable $NAME." },
   2794  1.10  christos 
   2795  1.10  christos #ifdef TUI
   2796  1.10  christos   { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
   2797  1.10  christos     METH_VARARGS | METH_KEYWORDS,
   2798  1.10  christos     "register_window_type (NAME, CONSTRUCTOR) -> None\n\
   2799  1.10  christos Register a TUI window constructor." },
   2800  1.10  christos #endif	/* TUI */
   2801  1.10  christos 
   2802  1.10  christos   { "architecture_names", gdbpy_all_architecture_names, METH_NOARGS,
   2803  1.10  christos     "architecture_names () -> List.\n\
   2804  1.10  christos Return a list of all the architecture names GDB understands." },
   2805  1.10  christos 
   2806  1.10  christos   { "connections", gdbpy_connections, METH_NOARGS,
   2807  1.10  christos     "connections () -> List.\n\
   2808  1.10  christos Return a list of gdb.TargetConnection objects." },
   2809  1.10  christos 
   2810  1.10  christos   { "format_address", (PyCFunction) gdbpy_format_address,
   2811  1.10  christos     METH_VARARGS | METH_KEYWORDS,
   2812  1.10  christos     "format_address (ADDRESS, PROG_SPACE, ARCH) -> String.\n\
   2813  1.10  christos Format ADDRESS, an address within PROG_SPACE, a gdb.Progspace, using\n\
   2814  1.10  christos ARCH, a gdb.Architecture to determine the address size.  The format of\n\
   2815  1.10  christos the returned string is 'ADDRESS <SYMBOL+OFFSET>' without the quotes." },
   2816  1.11  christos 
   2817  1.11  christos   { "current_language", gdbpy_current_language, METH_NOARGS,
   2818  1.11  christos     "current_language () -> string\n\
   2819  1.11  christos Return the name of the currently selected language." },
   2820   1.1  christos 
   2821   1.1  christos   { "print_options", gdbpy_print_options, METH_NOARGS,
   2822   1.1  christos     "print_options () -> dict\n\
   2823   1.8  christos Return the current print options." },
   2824   1.8  christos 
   2825   1.8  christos   { "notify_mi", (PyCFunction) gdbpy_notify_mi,
   2826  1.10  christos     METH_VARARGS | METH_KEYWORDS,
   2827   1.8  christos     "notify_mi (name, data) -> None\n\
   2828   1.8  christos Output async record to MI channels if any." },
   2829   1.8  christos   {NULL, NULL, 0, NULL}
   2830   1.8  christos };
   2831   1.8  christos 
   2832   1.8  christos /* Define all the event objects.  */
   2833   1.8  christos #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
   2834   1.8  christos   PyTypeObject name##_event_object_type		    \
   2835   1.8  christos 	CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
   2836   1.8  christos     = { \
   2837   1.8  christos       PyVarObject_HEAD_INIT (NULL, 0)				\
   2838   1.8  christos       "gdb." py_name,                             /* tp_name */ \
   2839   1.8  christos       sizeof (event_object),                      /* tp_basicsize */ \
   2840   1.8  christos       0,                                          /* tp_itemsize */ \
   2841   1.8  christos       evpy_dealloc,                               /* tp_dealloc */ \
   2842   1.8  christos       0,                                          /* tp_print */ \
   2843   1.8  christos       0,                                          /* tp_getattr */ \
   2844   1.8  christos       0,                                          /* tp_setattr */ \
   2845   1.8  christos       0,                                          /* tp_compare */ \
   2846   1.8  christos       0,                                          /* tp_repr */ \
   2847   1.8  christos       0,                                          /* tp_as_number */ \
   2848   1.8  christos       0,                                          /* tp_as_sequence */ \
   2849   1.8  christos       0,                                          /* tp_as_mapping */ \
   2850   1.8  christos       0,                                          /* tp_hash  */ \
   2851   1.8  christos       0,                                          /* tp_call */ \
   2852   1.8  christos       0,                                          /* tp_str */ \
   2853   1.8  christos       0,                                          /* tp_getattro */ \
   2854   1.8  christos       0,                                          /* tp_setattro */ \
   2855   1.8  christos       0,                                          /* tp_as_buffer */ \
   2856   1.8  christos       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */ \
   2857   1.8  christos       doc,                                        /* tp_doc */ \
   2858   1.8  christos       0,                                          /* tp_traverse */ \
   2859   1.8  christos       0,                                          /* tp_clear */ \
   2860   1.8  christos       0,                                          /* tp_richcompare */ \
   2861   1.8  christos       0,                                          /* tp_weaklistoffset */ \
   2862   1.8  christos       0,                                          /* tp_iter */ \
   2863   1.8  christos       0,                                          /* tp_iternext */ \
   2864   1.8  christos       0,                                          /* tp_methods */ \
   2865   1.8  christos       0,                                          /* tp_members */ \
   2866   1.8  christos       0,                                          /* tp_getset */ \
   2867   1.8  christos       &base,                                      /* tp_base */ \
   2868   1.8  christos       0,                                          /* tp_dict */ \
   2869   1.1  christos       0,                                          /* tp_descr_get */ \
   2870                       0,                                          /* tp_descr_set */ \
   2871                       0,                                          /* tp_dictoffset */ \
   2872                       0,                                          /* tp_init */ \
   2873                       0                                           /* tp_alloc */ \
   2874                     };
   2875                 #include "py-event-types.def"
   2876                 #undef GDB_PY_DEFINE_EVENT_TYPE
   2877                 
   2878                 #endif /* HAVE_PYTHON */
   2879