Home | History | Annotate | Line # | Download | only in python
python.c revision 1.9
      1  1.1  christos /* General python/gdb code
      2  1.1  christos 
      3  1.9  christos    Copyright (C) 2008-2020 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 "defs.h"
     21  1.1  christos #include "arch-utils.h"
     22  1.1  christos #include "command.h"
     23  1.1  christos #include "ui-out.h"
     24  1.1  christos #include "cli/cli-script.h"
     25  1.1  christos #include "gdbcmd.h"
     26  1.1  christos #include "progspace.h"
     27  1.1  christos #include "objfiles.h"
     28  1.1  christos #include "value.h"
     29  1.1  christos #include "language.h"
     30  1.9  christos #include "gdbsupport/event-loop.h"
     31  1.1  christos #include "readline/tilde.h"
     32  1.1  christos #include "python.h"
     33  1.3  christos #include "extension-priv.h"
     34  1.1  christos #include "cli/cli-utils.h"
     35  1.1  christos #include <ctype.h>
     36  1.6  christos #include "location.h"
     37  1.9  christos #include "run-on-main-thread.h"
     38  1.1  christos 
     39  1.1  christos /* Declared constants and enum for python stack printing.  */
     40  1.1  christos static const char python_excp_none[] = "none";
     41  1.1  christos static const char python_excp_full[] = "full";
     42  1.1  christos static const char python_excp_message[] = "message";
     43  1.1  christos 
     44  1.1  christos /* "set python print-stack" choices.  */
     45  1.1  christos static const char *const python_excp_enums[] =
     46  1.1  christos   {
     47  1.1  christos     python_excp_none,
     48  1.1  christos     python_excp_full,
     49  1.1  christos     python_excp_message,
     50  1.1  christos     NULL
     51  1.1  christos   };
     52  1.1  christos 
     53  1.1  christos /* The exception printing variable.  'full' if we want to print the
     54  1.1  christos    error message and stack, 'none' if we want to print nothing, and
     55  1.1  christos    'message' if we only want to print the error message.  'message' is
     56  1.1  christos    the default.  */
     57  1.1  christos static const char *gdbpy_should_print_stack = python_excp_message;
     58  1.1  christos 
     59  1.1  christos #ifdef HAVE_PYTHON
     60  1.3  christos /* Forward decls, these are defined later.  */
     61  1.5  christos extern const struct extension_language_script_ops python_extension_script_ops;
     62  1.5  christos extern const struct extension_language_ops python_extension_ops;
     63  1.3  christos #endif
     64  1.3  christos 
     65  1.3  christos /* The main struct describing GDB's interface to the Python
     66  1.3  christos    extension language.  */
     67  1.3  christos const struct extension_language_defn extension_language_python =
     68  1.3  christos {
     69  1.3  christos   EXT_LANG_PYTHON,
     70  1.3  christos   "python",
     71  1.3  christos   "Python",
     72  1.3  christos 
     73  1.3  christos   ".py",
     74  1.3  christos   "-gdb.py",
     75  1.3  christos 
     76  1.3  christos   python_control,
     77  1.3  christos 
     78  1.3  christos #ifdef HAVE_PYTHON
     79  1.3  christos   &python_extension_script_ops,
     80  1.3  christos   &python_extension_ops
     81  1.3  christos #else
     82  1.3  christos   NULL,
     83  1.3  christos   NULL
     84  1.3  christos #endif
     85  1.3  christos };
     86  1.3  christos 
     87  1.3  christos #ifdef HAVE_PYTHON
     89  1.1  christos 
     90  1.1  christos #include "cli/cli-decode.h"
     91  1.1  christos #include "charset.h"
     92  1.1  christos #include "top.h"
     93  1.1  christos #include "python-internal.h"
     94  1.1  christos #include "linespec.h"
     95  1.9  christos #include "source.h"
     96  1.1  christos #include "gdbsupport/version.h"
     97  1.1  christos #include "target.h"
     98  1.1  christos #include "gdbthread.h"
     99  1.1  christos #include "interps.h"
    100  1.7  christos #include "event-top.h"
    101  1.1  christos #include "py-event.h"
    102  1.1  christos 
    103  1.1  christos /* True if Python has been successfully initialized, false
    104  1.1  christos    otherwise.  */
    105  1.1  christos 
    106  1.1  christos int gdb_python_initialized;
    107  1.5  christos 
    108  1.1  christos extern PyMethodDef python_GdbMethods[];
    109  1.1  christos 
    110  1.5  christos #ifdef IS_PY3K
    111  1.1  christos extern struct PyModuleDef python_GdbModuleDef;
    112  1.1  christos #endif
    113  1.1  christos 
    114  1.1  christos PyObject *gdb_module;
    115  1.1  christos PyObject *gdb_python_module;
    116  1.1  christos 
    117  1.1  christos /* Some string constants we may wish to use.  */
    118  1.1  christos PyObject *gdbpy_to_string_cst;
    119  1.1  christos PyObject *gdbpy_children_cst;
    120  1.1  christos PyObject *gdbpy_display_hint_cst;
    121  1.1  christos PyObject *gdbpy_doc_cst;
    122  1.1  christos PyObject *gdbpy_enabled_cst;
    123  1.1  christos PyObject *gdbpy_value_cst;
    124  1.1  christos 
    125  1.1  christos /* The GdbError exception.  */
    126  1.1  christos PyObject *gdbpy_gdberror_exc;
    127  1.1  christos 
    128  1.1  christos /* The `gdb.error' base class.  */
    129  1.1  christos PyObject *gdbpy_gdb_error;
    130  1.1  christos 
    131  1.1  christos /* The `gdb.MemoryError' exception.  */
    132  1.1  christos PyObject *gdbpy_gdb_memory_error;
    133  1.3  christos 
    134  1.3  christos static script_sourcer_func gdbpy_source_script;
    135  1.5  christos static objfile_script_sourcer_func gdbpy_source_objfile_script;
    136  1.3  christos static objfile_script_executor_func gdbpy_execute_objfile_script;
    137  1.3  christos static void gdbpy_finish_initialization
    138  1.3  christos   (const struct extension_language_defn *);
    139  1.3  christos static int gdbpy_initialized (const struct extension_language_defn *);
    140  1.3  christos static void gdbpy_eval_from_control_command
    141  1.3  christos   (const struct extension_language_defn *, struct command_line *cmd);
    142  1.3  christos static void gdbpy_start_type_printers (const struct extension_language_defn *,
    143  1.3  christos 				       struct ext_lang_type_printers *);
    144  1.3  christos static enum ext_lang_rc gdbpy_apply_type_printers
    145  1.3  christos   (const struct extension_language_defn *,
    146  1.3  christos    const struct ext_lang_type_printers *, struct type *, char **);
    147  1.3  christos static void gdbpy_free_type_printers (const struct extension_language_defn *,
    148  1.3  christos 				      struct ext_lang_type_printers *);
    149  1.3  christos static void gdbpy_set_quit_flag (const struct extension_language_defn *);
    150  1.3  christos static int gdbpy_check_quit_flag (const struct extension_language_defn *);
    151  1.3  christos static enum ext_lang_rc gdbpy_before_prompt_hook
    152  1.9  christos   (const struct extension_language_defn *, const char *current_gdb_prompt);
    153  1.9  christos static gdb::optional<std::string> gdbpy_colorize
    154  1.3  christos   (const std::string &filename, const std::string &contents);
    155  1.3  christos 
    156  1.3  christos /* The interface between gdb proper and loading of python scripts.  */
    157  1.5  christos 
    158  1.3  christos const struct extension_language_script_ops python_extension_script_ops =
    159  1.3  christos {
    160  1.3  christos   gdbpy_source_script,
    161  1.5  christos   gdbpy_source_objfile_script,
    162  1.3  christos   gdbpy_execute_objfile_script,
    163  1.3  christos   gdbpy_auto_load_enabled
    164  1.3  christos };
    165  1.3  christos 
    166  1.3  christos /* The interface between gdb proper and python extensions.  */
    167  1.5  christos 
    168  1.3  christos const struct extension_language_ops python_extension_ops =
    169  1.3  christos {
    170  1.3  christos   gdbpy_finish_initialization,
    171  1.3  christos   gdbpy_initialized,
    172  1.3  christos 
    173  1.3  christos   gdbpy_eval_from_control_command,
    174  1.3  christos 
    175  1.3  christos   gdbpy_start_type_printers,
    176  1.3  christos   gdbpy_apply_type_printers,
    177  1.3  christos   gdbpy_free_type_printers,
    178  1.3  christos 
    179  1.3  christos   gdbpy_apply_val_pretty_printer,
    180  1.3  christos 
    181  1.3  christos   gdbpy_apply_frame_filter,
    182  1.3  christos 
    183  1.3  christos   gdbpy_preserve_values,
    184  1.3  christos 
    185  1.3  christos   gdbpy_breakpoint_has_cond,
    186  1.3  christos   gdbpy_breakpoint_cond_says_stop,
    187  1.3  christos 
    188  1.3  christos   gdbpy_set_quit_flag,
    189  1.3  christos   gdbpy_check_quit_flag,
    190  1.3  christos 
    191  1.3  christos   gdbpy_before_prompt_hook,
    192  1.3  christos 
    193  1.9  christos   gdbpy_get_matching_xmethod_workers,
    194  1.9  christos 
    195  1.3  christos   gdbpy_colorize,
    196  1.3  christos };
    197  1.1  christos 
    198  1.1  christos /* Architecture and language to be used in callbacks from
    199  1.1  christos    the Python interpreter.  */
    200  1.1  christos struct gdbarch *python_gdbarch;
    201  1.1  christos const struct language_defn *python_language;
    202  1.7  christos 
    203  1.7  christos gdbpy_enter::gdbpy_enter  (struct gdbarch *gdbarch,
    204  1.7  christos 			   const struct language_defn *language)
    205  1.7  christos : m_gdbarch (python_gdbarch),
    206  1.7  christos   m_language (python_language)
    207  1.7  christos {
    208  1.7  christos   /* We should not ever enter Python unless initialized.  */
    209  1.7  christos   if (!gdb_python_initialized)
    210  1.7  christos     error (_("Python not initialized"));
    211  1.7  christos 
    212  1.7  christos   m_previous_active = set_active_ext_lang (&extension_language_python);
    213  1.7  christos 
    214  1.7  christos   m_state = PyGILState_Ensure ();
    215  1.7  christos 
    216  1.7  christos   python_gdbarch = gdbarch;
    217  1.1  christos   python_language = language;
    218  1.7  christos 
    219  1.8  christos   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
    220  1.7  christos   m_error.emplace ();
    221  1.1  christos }
    222  1.7  christos 
    223  1.1  christos gdbpy_enter::~gdbpy_enter ()
    224  1.1  christos {
    225  1.1  christos   /* Leftover Python error is forbidden by Python Exception Handling.  */
    226  1.1  christos   if (PyErr_Occurred ())
    227  1.1  christos     {
    228  1.1  christos       /* This order is similar to the one calling error afterwards. */
    229  1.1  christos       gdbpy_print_stack ();
    230  1.1  christos       warning (_("internal error: Unhandled Python exception"));
    231  1.1  christos     }
    232  1.8  christos 
    233  1.3  christos   m_error->restore ();
    234  1.7  christos 
    235  1.7  christos   python_gdbarch = m_gdbarch;
    236  1.3  christos   python_language = m_language;
    237  1.7  christos 
    238  1.9  christos   restore_active_ext_lang (m_previous_active);
    239  1.1  christos   PyGILState_Release (m_state);
    240  1.1  christos }
    241  1.9  christos 
    242  1.9  christos /* A helper class to save and restore the GIL, but without touching
    243  1.9  christos    the other globals that are handled by gdbpy_enter.  */
    244  1.9  christos 
    245  1.9  christos class gdbpy_gil
    246  1.9  christos {
    247  1.9  christos public:
    248  1.9  christos 
    249  1.9  christos   gdbpy_gil ()
    250  1.9  christos     : m_state (PyGILState_Ensure ())
    251  1.9  christos   {
    252  1.9  christos   }
    253  1.9  christos 
    254  1.9  christos   ~gdbpy_gil ()
    255  1.9  christos   {
    256  1.9  christos     PyGILState_Release (m_state);
    257  1.9  christos   }
    258  1.9  christos 
    259  1.9  christos   DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
    260  1.9  christos 
    261  1.9  christos private:
    262  1.9  christos 
    263  1.9  christos   PyGILState_STATE m_state;
    264  1.9  christos };
    265  1.1  christos 
    266  1.1  christos /* Set the quit flag.  */
    267  1.3  christos 
    268  1.3  christos static void
    269  1.1  christos gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
    270  1.1  christos {
    271  1.1  christos   PyErr_SetInterrupt ();
    272  1.1  christos }
    273  1.1  christos 
    274  1.1  christos /* Return true if the quit flag has been set, false otherwise.  */
    275  1.3  christos 
    276  1.3  christos static int
    277  1.1  christos gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
    278  1.9  christos {
    279  1.9  christos   if (!gdb_python_initialized)
    280  1.9  christos     return 0;
    281  1.9  christos 
    282  1.1  christos   gdbpy_gil gil;
    283  1.1  christos   return PyOS_InterruptOccurred ();
    284  1.1  christos }
    285  1.1  christos 
    286  1.1  christos /* Evaluate a Python command like PyRun_SimpleString, but uses
    287  1.1  christos    Py_single_input which prints the result of expressions, and does
    288  1.1  christos    not automatically print the stack on errors.  */
    289  1.1  christos 
    290  1.1  christos static int
    291  1.1  christos eval_python_command (const char *command)
    292  1.7  christos {
    293  1.1  christos   PyObject *m, *d;
    294  1.1  christos 
    295  1.1  christos   m = PyImport_AddModule ("__main__");
    296  1.1  christos   if (m == NULL)
    297  1.1  christos     return -1;
    298  1.1  christos 
    299  1.1  christos   d = PyModule_GetDict (m);
    300  1.1  christos   if (d == NULL)
    301  1.7  christos     return -1;
    302  1.1  christos   gdbpy_ref<> v (PyRun_StringFlags (command, Py_single_input, d, d, NULL));
    303  1.1  christos   if (v == NULL)
    304  1.1  christos     return -1;
    305  1.1  christos 
    306  1.1  christos #ifndef IS_PY3K
    307  1.1  christos   if (Py_FlushLine ())
    308  1.1  christos     PyErr_Clear ();
    309  1.1  christos #endif
    310  1.1  christos 
    311  1.1  christos   return 0;
    312  1.1  christos }
    313  1.1  christos 
    314  1.1  christos /* Implementation of the gdb "python-interactive" command.  */
    315  1.1  christos 
    316  1.8  christos static void
    317  1.1  christos python_interactive_command (const char *arg, int from_tty)
    318  1.6  christos {
    319  1.1  christos   struct ui *ui = current_ui;
    320  1.1  christos   int err;
    321  1.7  christos 
    322  1.1  christos   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    323  1.1  christos 
    324  1.1  christos   arg = skip_spaces (arg);
    325  1.7  christos 
    326  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
    327  1.1  christos 
    328  1.1  christos   if (arg && *arg)
    329  1.8  christos     {
    330  1.8  christos       std::string script = std::string (arg) + "\n";
    331  1.1  christos       err = eval_python_command (script.c_str ());
    332  1.1  christos     }
    333  1.1  christos   else
    334  1.6  christos     {
    335  1.1  christos       err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
    336  1.1  christos       dont_repeat ();
    337  1.1  christos     }
    338  1.1  christos 
    339  1.1  christos   if (err)
    340  1.1  christos     {
    341  1.1  christos       gdbpy_print_stack ();
    342  1.1  christos       error (_("Error while executing Python code."));
    343  1.1  christos     }
    344  1.1  christos }
    345  1.1  christos 
    346  1.1  christos /* A wrapper around PyRun_SimpleFile.  FILE is the Python script to run
    347  1.1  christos    named FILENAME.
    348  1.1  christos 
    349  1.1  christos    On Windows hosts few users would build Python themselves (this is no
    350  1.1  christos    trivial task on this platform), and thus use binaries built by
    351  1.1  christos    someone else instead.  There may happen situation where the Python
    352  1.1  christos    library and GDB are using two different versions of the C runtime
    353  1.1  christos    library.  Python, being built with VC, would use one version of the
    354  1.1  christos    msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
    355  1.1  christos    A FILE * from one runtime does not necessarily operate correctly in
    356  1.1  christos    the other runtime.
    357  1.9  christos 
    358  1.9  christos    To work around this potential issue, we run code in Python to load
    359  1.1  christos    the script.  */
    360  1.1  christos 
    361  1.1  christos static void
    362  1.1  christos python_run_simple_file (FILE *file, const char *filename)
    363  1.1  christos {
    364  1.1  christos #ifndef _WIN32
    365  1.1  christos 
    366  1.1  christos   PyRun_SimpleFile (file, filename);
    367  1.1  christos 
    368  1.1  christos #else /* _WIN32 */
    369  1.1  christos 
    370  1.1  christos   /* Because we have a string for a filename, and are using Python to
    371  1.7  christos      open the file, we need to expand any tilde in the path first.  */
    372  1.9  christos   gdb::unique_xmalloc_ptr<char> full_path (tilde_expand (filename));
    373  1.9  christos 
    374  1.9  christos   if (gdb_python_module == nullptr
    375  1.9  christos       || ! PyObject_HasAttrString (gdb_python_module, "_execute_file"))
    376  1.9  christos     error (_("Installation error: gdb._execute_file function is missing"));
    377  1.9  christos 
    378  1.9  christos   gdbpy_ref<> return_value
    379  1.9  christos     (PyObject_CallMethod (gdb_python_module, "_execute_file", "s",
    380  1.9  christos 			  full_path.get ()));
    381  1.9  christos   if (return_value == nullptr)
    382  1.9  christos     {
    383  1.9  christos       /* Use PyErr_PrintEx instead of gdbpy_print_stack to better match the
    384  1.9  christos          behavior of the non-Windows codepath.  */
    385  1.1  christos       PyErr_PrintEx(0);
    386  1.1  christos     }
    387  1.1  christos 
    388  1.1  christos #endif /* _WIN32 */
    389  1.1  christos }
    390  1.1  christos 
    391  1.8  christos /* Given a command_line, return a command string suitable for passing
    392  1.1  christos    to Python.  Lines in the string are separated by newlines.  */
    393  1.8  christos 
    394  1.1  christos static std::string
    395  1.1  christos compute_python_string (struct command_line *l)
    396  1.1  christos {
    397  1.8  christos   struct command_line *iter;
    398  1.1  christos   std::string script;
    399  1.1  christos 
    400  1.1  christos   for (iter = l; iter; iter = iter->next)
    401  1.8  christos     {
    402  1.8  christos       script += iter->line;
    403  1.1  christos       script += '\n';
    404  1.1  christos     }
    405  1.1  christos   return script;
    406  1.1  christos }
    407  1.1  christos 
    408  1.1  christos /* Take a command line structure representing a 'python' command, and
    409  1.1  christos    evaluate its body using the Python interpreter.  */
    410  1.3  christos 
    411  1.3  christos static void
    412  1.3  christos gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
    413  1.1  christos 				 struct command_line *cmd)
    414  1.1  christos {
    415  1.1  christos   int ret;
    416  1.8  christos 
    417  1.1  christos   if (cmd->body_list_1 != nullptr)
    418  1.1  christos     error (_("Invalid \"python\" block structure."));
    419  1.7  christos 
    420  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
    421  1.8  christos 
    422  1.8  christos   std::string script = compute_python_string (cmd->body_list_0.get ());
    423  1.1  christos   ret = PyRun_SimpleString (script.c_str ());
    424  1.1  christos   if (ret)
    425  1.1  christos     error (_("Error while executing Python code."));
    426  1.1  christos }
    427  1.1  christos 
    428  1.1  christos /* Implementation of the gdb "python" command.  */
    429  1.1  christos 
    430  1.8  christos static void
    431  1.1  christos python_command (const char *arg, int from_tty)
    432  1.7  christos {
    433  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
    434  1.7  christos 
    435  1.1  christos   scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
    436  1.1  christos 
    437  1.1  christos   arg = skip_spaces (arg);
    438  1.1  christos   if (arg && *arg)
    439  1.1  christos     {
    440  1.1  christos       if (PyRun_SimpleString (arg))
    441  1.1  christos 	error (_("Error while executing Python code."));
    442  1.1  christos     }
    443  1.1  christos   else
    444  1.8  christos     {
    445  1.1  christos       counted_command_line l = get_command_line (python_control, "");
    446  1.7  christos 
    447  1.1  christos       execute_control_command_untraced (l.get ());
    448  1.1  christos     }
    449  1.1  christos }
    450  1.1  christos 
    451  1.1  christos 
    452  1.1  christos 
    454  1.1  christos /* Transform a gdb parameters's value into a Python value.  May return
    455  1.1  christos    NULL (and set a Python exception) on error.  Helper function for
    456  1.1  christos    get_parameter.  */
    457  1.1  christos PyObject *
    458  1.1  christos gdbpy_parameter_value (enum var_types type, void *var)
    459  1.1  christos {
    460  1.1  christos   switch (type)
    461  1.1  christos     {
    462  1.1  christos     case var_string:
    463  1.1  christos     case var_string_noescape:
    464  1.1  christos     case var_optional_filename:
    465  1.1  christos     case var_filename:
    466  1.7  christos     case var_enum:
    467  1.1  christos       {
    468  1.1  christos 	const char *str = *(char **) var;
    469  1.1  christos 
    470  1.8  christos 	if (! str)
    471  1.1  christos 	  str = "";
    472  1.1  christos 	return host_string_to_python_string (str).release ();
    473  1.1  christos       }
    474  1.1  christos 
    475  1.9  christos     case var_boolean:
    476  1.1  christos       {
    477  1.1  christos 	if (* (bool *) var)
    478  1.1  christos 	  Py_RETURN_TRUE;
    479  1.1  christos 	else
    480  1.1  christos 	  Py_RETURN_FALSE;
    481  1.1  christos       }
    482  1.1  christos 
    483  1.1  christos     case var_auto_boolean:
    484  1.1  christos       {
    485  1.1  christos 	enum auto_boolean ab = * (enum auto_boolean *) var;
    486  1.1  christos 
    487  1.1  christos 	if (ab == AUTO_BOOLEAN_TRUE)
    488  1.1  christos 	  Py_RETURN_TRUE;
    489  1.1  christos 	else if (ab == AUTO_BOOLEAN_FALSE)
    490  1.1  christos 	  Py_RETURN_FALSE;
    491  1.1  christos 	else
    492  1.1  christos 	  Py_RETURN_NONE;
    493  1.1  christos       }
    494  1.1  christos 
    495  1.1  christos     case var_integer:
    496  1.1  christos       if ((* (int *) var) == INT_MAX)
    497  1.1  christos 	Py_RETURN_NONE;
    498  1.8  christos       /* Fall through.  */
    499  1.1  christos     case var_zinteger:
    500  1.1  christos     case var_zuinteger_unlimited:
    501  1.1  christos       return PyLong_FromLong (* (int *) var);
    502  1.1  christos 
    503  1.1  christos     case var_uinteger:
    504  1.1  christos       {
    505  1.1  christos 	unsigned int val = * (unsigned int *) var;
    506  1.1  christos 
    507  1.1  christos 	if (val == UINT_MAX)
    508  1.1  christos 	  Py_RETURN_NONE;
    509  1.8  christos 	return PyLong_FromUnsignedLong (val);
    510  1.8  christos       }
    511  1.8  christos 
    512  1.8  christos     case var_zuinteger:
    513  1.8  christos       {
    514  1.8  christos 	unsigned int val = * (unsigned int *) var;
    515  1.1  christos 	return PyLong_FromUnsignedLong (val);
    516  1.1  christos       }
    517  1.1  christos     }
    518  1.1  christos 
    519  1.1  christos   return PyErr_Format (PyExc_RuntimeError,
    520  1.1  christos 		       _("Programmer error: unhandled type."));
    521  1.1  christos }
    522  1.1  christos 
    523  1.1  christos /* A Python function which returns a gdb parameter's value as a Python
    524  1.6  christos    value.  */
    525  1.1  christos 
    526  1.1  christos static PyObject *
    527  1.1  christos gdbpy_parameter (PyObject *self, PyObject *args)
    528  1.1  christos {
    529  1.1  christos   struct cmd_list_element *alias, *prefix, *cmd;
    530  1.1  christos   const char *arg;
    531  1.1  christos   int found = -1;
    532  1.1  christos 
    533  1.1  christos   if (! PyArg_ParseTuple (args, "s", &arg))
    534  1.8  christos     return NULL;
    535  1.1  christos 
    536  1.9  christos   std::string newarg = std::string ("show ") + arg;
    537  1.1  christos 
    538  1.8  christos   try
    539  1.1  christos     {
    540  1.9  christos       found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
    541  1.5  christos     }
    542  1.8  christos   catch (const gdb_exception &ex)
    543  1.5  christos     {
    544  1.5  christos       GDB_PY_HANDLE_EXCEPTION (ex);
    545  1.1  christos     }
    546  1.1  christos 
    547  1.1  christos   if (!found)
    548  1.1  christos     return PyErr_Format (PyExc_RuntimeError,
    549  1.1  christos 			 _("Could not find parameter `%s'."), arg);
    550  1.1  christos 
    551  1.1  christos   if (! cmd->var)
    552  1.1  christos     return PyErr_Format (PyExc_RuntimeError,
    553  1.1  christos 			 _("`%s' is not a parameter."), arg);
    554  1.1  christos   return gdbpy_parameter_value (cmd->var_type, cmd->var);
    555  1.1  christos }
    556  1.1  christos 
    557  1.1  christos /* Wrapper for target_charset.  */
    558  1.1  christos 
    559  1.1  christos static PyObject *
    560  1.1  christos gdbpy_target_charset (PyObject *self, PyObject *args)
    561  1.1  christos {
    562  1.1  christos   const char *cset = target_charset (python_gdbarch);
    563  1.1  christos 
    564  1.1  christos   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
    565  1.1  christos }
    566  1.1  christos 
    567  1.1  christos /* Wrapper for target_wide_charset.  */
    568  1.1  christos 
    569  1.1  christos static PyObject *
    570  1.1  christos gdbpy_target_wide_charset (PyObject *self, PyObject *args)
    571  1.1  christos {
    572  1.1  christos   const char *cset = target_wide_charset (python_gdbarch);
    573  1.1  christos 
    574  1.1  christos   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
    575  1.1  christos }
    576  1.1  christos 
    577  1.1  christos /* A Python function which evaluates a string using the gdb CLI.  */
    578  1.1  christos 
    579  1.1  christos static PyObject *
    580  1.1  christos execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
    581  1.1  christos {
    582  1.1  christos   const char *arg;
    583  1.7  christos   PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
    584  1.1  christos   int from_tty, to_string;
    585  1.7  christos   static const char *keywords[] = { "command", "from_tty", "to_string", NULL };
    586  1.7  christos 
    587  1.7  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
    588  1.1  christos 					&PyBool_Type, &from_tty_obj,
    589  1.1  christos 					&PyBool_Type, &to_string_obj))
    590  1.1  christos     return NULL;
    591  1.1  christos 
    592  1.1  christos   from_tty = 0;
    593  1.1  christos   if (from_tty_obj)
    594  1.1  christos     {
    595  1.1  christos       int cmp = PyObject_IsTrue (from_tty_obj);
    596  1.1  christos       if (cmp < 0)
    597  1.1  christos 	return NULL;
    598  1.1  christos       from_tty = cmp;
    599  1.1  christos     }
    600  1.1  christos 
    601  1.1  christos   to_string = 0;
    602  1.1  christos   if (to_string_obj)
    603  1.1  christos     {
    604  1.1  christos       int cmp = PyObject_IsTrue (to_string_obj);
    605  1.1  christos       if (cmp < 0)
    606  1.1  christos 	return NULL;
    607  1.1  christos       to_string = cmp;
    608  1.7  christos     }
    609  1.7  christos 
    610  1.8  christos   std::string to_string_res;
    611  1.8  christos 
    612  1.9  christos   scoped_restore preventer = prevent_dont_repeat ();
    613  1.1  christos 
    614  1.8  christos   try
    615  1.8  christos     {
    616  1.6  christos       gdbpy_allow_threads allow_threads;
    617  1.6  christos 
    618  1.8  christos       struct interp *interp;
    619  1.8  christos 
    620  1.8  christos       std::string arg_copy = arg;
    621  1.8  christos       bool first = true;
    622  1.8  christos       char *save_ptr = nullptr;
    623  1.8  christos       auto reader
    624  1.8  christos 	= [&] ()
    625  1.8  christos 	  {
    626  1.8  christos 	    const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
    627  1.8  christos 					   "\n", &save_ptr);
    628  1.8  christos 	    first = false;
    629  1.8  christos 	    return result;
    630  1.8  christos 	  };
    631  1.8  christos 
    632  1.8  christos       counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
    633  1.8  christos 
    634  1.8  christos       {
    635  1.8  christos 	scoped_restore save_async = make_scoped_restore (&current_ui->async,
    636  1.8  christos 							 0);
    637  1.6  christos 
    638  1.8  christos 	scoped_restore save_uiout = make_scoped_restore (&current_uiout);
    639  1.8  christos 
    640  1.8  christos 	/* Use the console interpreter uiout to have the same print format
    641  1.8  christos 	   for console or MI.  */
    642  1.8  christos 	interp = interp_lookup (current_ui, "console");
    643  1.8  christos 	current_uiout = interp->interp_ui_out ();
    644  1.8  christos 
    645  1.8  christos 	if (to_string)
    646  1.8  christos 	  to_string_res = execute_control_commands_to_string (lines.get (),
    647  1.8  christos 							      from_tty);
    648  1.8  christos 	else
    649  1.1  christos 	  execute_control_commands (lines.get (), from_tty);
    650  1.8  christos       }
    651  1.8  christos 
    652  1.1  christos       /* Do any commands attached to breakpoint we stopped at.  */
    653  1.9  christos       bpstat_do_actions ();
    654  1.5  christos     }
    655  1.9  christos   catch (const gdb_exception &except)
    656  1.9  christos     {
    657  1.9  christos       /* If an exception occurred then we won't hit normal_stop (), or have
    658  1.9  christos 	 an exception reach the top level of the event loop, which are the
    659  1.9  christos 	 two usual places in which stdin would be re-enabled. So, before we
    660  1.9  christos 	 convert the exception and continue back in Python, we should
    661  1.5  christos 	 re-enable stdin here.  */
    662  1.5  christos       async_enable_stdin ();
    663  1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
    664  1.7  christos     }
    665  1.7  christos 
    666  1.1  christos   if (to_string)
    667  1.1  christos     return PyString_FromString (to_string_res.c_str ());
    668  1.1  christos   Py_RETURN_NONE;
    669  1.8  christos }
    670  1.8  christos 
    671  1.8  christos /* Implementation of Python rbreak command.  Take a REGEX and
    672  1.8  christos    optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
    673  1.8  christos    Python list that contains newly set breakpoints that match that
    674  1.8  christos    criteria.  REGEX refers to a GDB format standard regex pattern of
    675  1.8  christos    symbols names to search; MINSYMS is an optional boolean (default
    676  1.8  christos    False) that indicates if the function should search GDB's minimal
    677  1.8  christos    symbols; THROTTLE is an optional integer (default unlimited) that
    678  1.8  christos    indicates the maximum amount of breakpoints allowable before the
    679  1.8  christos    function exits (note, if the throttle bound is passed, no
    680  1.8  christos    breakpoints will be set and a runtime error returned); SYMTABS is
    681  1.1  christos    an optional Python iterable that contains a set of gdb.Symtabs to
    682  1.1  christos    constrain the search within.  */
    683  1.8  christos 
    684  1.1  christos static PyObject *
    685  1.8  christos gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
    686  1.8  christos {
    687  1.8  christos   char *regex = NULL;
    688  1.8  christos   std::vector<symbol_search> symbols;
    689  1.8  christos   unsigned long count = 0;
    690  1.8  christos   PyObject *symtab_list = NULL;
    691  1.8  christos   PyObject *minsyms_p_obj = NULL;
    692  1.8  christos   int minsyms_p = 0;
    693  1.8  christos   unsigned int throttle = 0;
    694  1.8  christos   static const char *keywords[] = {"regex","minsyms", "throttle",
    695  1.8  christos 				   "symtabs", NULL};
    696  1.8  christos 
    697  1.8  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
    698  1.8  christos 					&regex, &PyBool_Type,
    699  1.1  christos 					&minsyms_p_obj, &throttle,
    700  1.1  christos 					&symtab_list))
    701  1.8  christos     return NULL;
    702  1.8  christos 
    703  1.8  christos   /* Parse minsyms keyword.  */
    704  1.8  christos   if (minsyms_p_obj != NULL)
    705  1.8  christos     {
    706  1.8  christos       int cmp = PyObject_IsTrue (minsyms_p_obj);
    707  1.8  christos       if (cmp < 0)
    708  1.8  christos 	return NULL;
    709  1.8  christos       minsyms_p = cmp;
    710  1.9  christos     }
    711  1.9  christos 
    712  1.9  christos   global_symbol_searcher spec (FUNCTIONS_DOMAIN, regex);
    713  1.9  christos   SCOPE_EXIT {
    714  1.9  christos     for (const char *elem : spec.filenames)
    715  1.9  christos       xfree ((void *) elem);
    716  1.8  christos   };
    717  1.8  christos 
    718  1.8  christos   /* The "symtabs" keyword is any Python iterable object that returns
    719  1.8  christos      a gdb.Symtab on each iteration.  If specified, iterate through
    720  1.8  christos      the provided gdb.Symtabs and extract their full path.  As
    721  1.8  christos      python_string_to_target_string returns a
    722  1.8  christos      gdb::unique_xmalloc_ptr<char> and a vector containing these types
    723  1.8  christos      cannot be coerced to a const char **p[] via the vector.data call,
    724  1.8  christos      release the value from the unique_xmalloc_ptr and place it in a
    725  1.8  christos      simple type symtab_list_type (which holds the vector and a
    726  1.8  christos      destructor that frees the contents of the allocated strings.  */
    727  1.8  christos   if (symtab_list != NULL)
    728  1.8  christos     {
    729  1.8  christos       gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
    730  1.8  christos 
    731  1.8  christos       if (iter == NULL)
    732  1.8  christos 	return NULL;
    733  1.8  christos 
    734  1.8  christos       while (true)
    735  1.8  christos 	{
    736  1.8  christos 	  gdbpy_ref<> next (PyIter_Next (iter.get ()));
    737  1.8  christos 
    738  1.8  christos 	  if (next == NULL)
    739  1.8  christos 	    {
    740  1.8  christos 	      if (PyErr_Occurred ())
    741  1.8  christos 		return NULL;
    742  1.8  christos 	      break;
    743  1.8  christos 	    }
    744  1.8  christos 
    745  1.8  christos 	  gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
    746  1.8  christos 							"filename"));
    747  1.8  christos 
    748  1.8  christos 	  if (obj_name == NULL)
    749  1.8  christos 	    return NULL;
    750  1.8  christos 
    751  1.8  christos 	  /* Is the object file still valid?  */
    752  1.8  christos 	  if (obj_name == Py_None)
    753  1.8  christos 	    continue;
    754  1.8  christos 
    755  1.8  christos 	  gdb::unique_xmalloc_ptr<char> filename =
    756  1.8  christos 	    python_string_to_target_string (obj_name.get ());
    757  1.8  christos 
    758  1.8  christos 	  if (filename == NULL)
    759  1.8  christos 	    return NULL;
    760  1.8  christos 
    761  1.9  christos 	  /* Make sure there is a definite place to store the value of
    762  1.9  christos 	     filename before it is released.  */
    763  1.8  christos 	  spec.filenames.push_back (nullptr);
    764  1.8  christos 	  spec.filenames.back () = filename.release ();
    765  1.8  christos 	}
    766  1.9  christos     }
    767  1.9  christos 
    768  1.8  christos   /* The search spec.  */
    769  1.8  christos   symbols = spec.search ();
    770  1.8  christos 
    771  1.8  christos   /* Count the number of symbols (both symbols and optionally minimal
    772  1.8  christos      symbols) so we can correctly check the throttle limit.  */
    773  1.8  christos   for (const symbol_search &p : symbols)
    774  1.8  christos     {
    775  1.8  christos       /* Minimal symbols included?  */
    776  1.8  christos       if (minsyms_p)
    777  1.8  christos 	{
    778  1.8  christos 	  if (p.msymbol.minsym != NULL)
    779  1.8  christos 	    count++;
    780  1.8  christos 	}
    781  1.8  christos 
    782  1.8  christos       if (p.symbol != NULL)
    783  1.8  christos 	count++;
    784  1.8  christos     }
    785  1.8  christos 
    786  1.1  christos   /* Check throttle bounds and exit if in excess.  */
    787  1.8  christos   if (throttle != 0 && count > throttle)
    788  1.8  christos     {
    789  1.8  christos       PyErr_SetString (PyExc_RuntimeError,
    790  1.1  christos 		       _("Number of breakpoints exceeds throttled maximum."));
    791  1.1  christos       return NULL;
    792  1.8  christos     }
    793  1.8  christos 
    794  1.8  christos   gdbpy_ref<> return_list (PyList_New (0));
    795  1.8  christos 
    796  1.8  christos   if (return_list == NULL)
    797  1.8  christos     return NULL;
    798  1.8  christos 
    799  1.8  christos   /* Construct full path names for symbols and call the Python
    800  1.8  christos      breakpoint constructor on the resulting names.  Be tolerant of
    801  1.8  christos      individual breakpoint failures.  */
    802  1.8  christos   for (const symbol_search &p : symbols)
    803  1.8  christos     {
    804  1.8  christos       std::string symbol_name;
    805  1.8  christos 
    806  1.8  christos       /* Skipping minimal symbols?  */
    807  1.8  christos       if (minsyms_p == 0)
    808  1.8  christos 	if (p.msymbol.minsym != NULL)
    809  1.8  christos 	  continue;
    810  1.8  christos 
    811  1.8  christos       if (p.msymbol.minsym == NULL)
    812  1.8  christos 	{
    813  1.8  christos 	  struct symtab *symtab = symbol_symtab (p.symbol);
    814  1.8  christos 	  const char *fullname = symtab_to_fullname (symtab);
    815  1.8  christos 
    816  1.9  christos 	  symbol_name = fullname;
    817  1.8  christos 	  symbol_name  += ":";
    818  1.8  christos 	  symbol_name  += p.symbol->linkage_name ();
    819  1.9  christos 	}
    820  1.8  christos       else
    821  1.8  christos 	symbol_name = p.msymbol.minsym->linkage_name ();
    822  1.8  christos 
    823  1.8  christos       gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
    824  1.8  christos       gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
    825  1.8  christos 					    &breakpoint_object_type,
    826  1.8  christos 					    argList.get ()));
    827  1.8  christos 
    828  1.8  christos       /* Tolerate individual breakpoint failures.  */
    829  1.8  christos       if (obj == NULL)
    830  1.8  christos 	gdbpy_print_stack ();
    831  1.8  christos       else
    832  1.8  christos 	{
    833  1.8  christos 	  if (PyList_Append (return_list.get (), obj.get ()) == -1)
    834  1.8  christos 	    return NULL;
    835  1.8  christos 	}
    836  1.1  christos     }
    837  1.1  christos   return return_list.release ();
    838  1.1  christos }
    839  1.1  christos 
    840  1.1  christos /* A Python function which is a wrapper for decode_line_1.  */
    841  1.1  christos 
    842  1.1  christos static PyObject *
    843  1.8  christos gdbpy_decode_line (PyObject *self, PyObject *args)
    844  1.7  christos {
    845  1.7  christos   const char *arg = NULL;
    846  1.7  christos   gdbpy_ref<> result;
    847  1.1  christos   gdbpy_ref<> unparsed;
    848  1.1  christos   event_location_up location;
    849  1.1  christos 
    850  1.1  christos   if (! PyArg_ParseTuple (args, "|s", &arg))
    851  1.9  christos     return NULL;
    852  1.9  christos 
    853  1.9  christos   /* Treat a string consisting of just whitespace the same as
    854  1.9  christos      NULL.  */
    855  1.9  christos   if (arg != NULL)
    856  1.9  christos     {
    857  1.9  christos       arg = skip_spaces (arg);
    858  1.9  christos       if (*arg == '\0')
    859  1.9  christos 	arg = NULL;
    860  1.6  christos     }
    861  1.8  christos 
    862  1.8  christos   if (arg != NULL)
    863  1.6  christos     location = string_to_event_location_basic (&arg, python_language,
    864  1.8  christos 					       symbol_name_match_type::WILD);
    865  1.8  christos 
    866  1.8  christos   std::vector<symtab_and_line> decoded_sals;
    867  1.9  christos   symtab_and_line def_sal;
    868  1.1  christos   gdb::array_view<symtab_and_line> sals;
    869  1.6  christos   try
    870  1.8  christos     {
    871  1.8  christos       if (location != NULL)
    872  1.8  christos 	{
    873  1.8  christos 	  decoded_sals = decode_line_1 (location.get (), 0, NULL, NULL, 0);
    874  1.1  christos 	  sals = decoded_sals;
    875  1.1  christos 	}
    876  1.1  christos       else
    877  1.8  christos 	{
    878  1.8  christos 	  set_default_source_symtab_and_line ();
    879  1.1  christos 	  def_sal = get_current_source_symtab_and_line ();
    880  1.1  christos 	  sals = def_sal;
    881  1.9  christos 	}
    882  1.5  christos     }
    883  1.1  christos   catch (const gdb_exception &ex)
    884  1.8  christos     {
    885  1.1  christos       /* We know this will always throw.  */
    886  1.1  christos       gdbpy_convert_exception (ex);
    887  1.1  christos       return NULL;
    888  1.8  christos     }
    889  1.1  christos 
    890  1.8  christos   if (!sals.empty ())
    891  1.7  christos     {
    892  1.8  christos       result.reset (PyTuple_New (sals.size ()));
    893  1.8  christos       if (result == NULL)
    894  1.7  christos 	return NULL;
    895  1.8  christos       for (size_t i = 0; i < sals.size (); ++i)
    896  1.8  christos 	{
    897  1.8  christos 	  PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
    898  1.1  christos 	  if (obj == NULL)
    899  1.7  christos 	    return NULL;
    900  1.1  christos 
    901  1.1  christos 	  PyTuple_SetItem (result.get (), i, obj);
    902  1.1  christos 	}
    903  1.8  christos     }
    904  1.1  christos   else
    905  1.7  christos     result = gdbpy_ref<>::new_reference (Py_None);
    906  1.7  christos 
    907  1.8  christos   gdbpy_ref<> return_result (PyTuple_New (2));
    908  1.1  christos   if (return_result == NULL)
    909  1.6  christos     return NULL;
    910  1.1  christos 
    911  1.7  christos   if (arg != NULL && strlen (arg) > 0)
    912  1.1  christos     {
    913  1.8  christos       unparsed.reset (PyString_FromString (arg));
    914  1.1  christos       if (unparsed == NULL)
    915  1.1  christos 	return NULL;
    916  1.8  christos     }
    917  1.1  christos   else
    918  1.7  christos     unparsed = gdbpy_ref<>::new_reference (Py_None);
    919  1.7  christos 
    920  1.1  christos   PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
    921  1.7  christos   PyTuple_SetItem (return_result.get (), 1, result.release ());
    922  1.1  christos 
    923  1.1  christos   return return_result.release ();
    924  1.1  christos }
    925  1.1  christos 
    926  1.1  christos /* Parse a string and evaluate it as an expression.  */
    927  1.1  christos static PyObject *
    928  1.1  christos gdbpy_parse_and_eval (PyObject *self, PyObject *args)
    929  1.1  christos {
    930  1.1  christos   const char *expr_str;
    931  1.1  christos   struct value *result = NULL;
    932  1.1  christos 
    933  1.1  christos   if (!PyArg_ParseTuple (args, "s", &expr_str))
    934  1.9  christos     return NULL;
    935  1.1  christos 
    936  1.8  christos   try
    937  1.1  christos     {
    938  1.1  christos       gdbpy_allow_threads allow_threads;
    939  1.9  christos       result = parse_and_eval (expr_str);
    940  1.5  christos     }
    941  1.5  christos   catch (const gdb_exception &except)
    942  1.5  christos     {
    943  1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
    944  1.1  christos     }
    945  1.1  christos 
    946  1.1  christos   return value_to_value_object (result);
    947  1.6  christos }
    948  1.6  christos 
    949  1.6  christos /* Implementation of gdb.invalidate_cached_frames.  */
    950  1.6  christos 
    951  1.6  christos static PyObject *
    952  1.6  christos gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
    953  1.6  christos {
    954  1.6  christos   reinit_frame_cache ();
    955  1.6  christos   Py_RETURN_NONE;
    956  1.1  christos }
    957  1.3  christos 
    958  1.3  christos /* Read a file as Python code.
    959  1.1  christos    This is the extension_language_script_ops.script_sourcer "method".
    960  1.1  christos    FILE is the file to load.  FILENAME is name of the file FILE.
    961  1.1  christos    This does not throw any errors.  If an exception occurs python will print
    962  1.3  christos    the traceback and clear the error indicator.  */
    963  1.3  christos 
    964  1.3  christos static void
    965  1.1  christos gdbpy_source_script (const struct extension_language_defn *extlang,
    966  1.7  christos 		     FILE *file, const char *filename)
    967  1.1  christos {
    968  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
    969  1.1  christos   python_run_simple_file (file, filename);
    970  1.1  christos }
    971  1.1  christos 
    972  1.1  christos 
    973  1.1  christos 
    975  1.1  christos /* Posting and handling events.  */
    976  1.1  christos 
    977  1.9  christos /* A single event.  */
    978  1.9  christos struct gdbpy_event
    979  1.9  christos {
    980  1.9  christos   gdbpy_event (gdbpy_ref<> &&func)
    981  1.9  christos     : m_func (func.release ())
    982  1.9  christos   {
    983  1.9  christos   }
    984  1.9  christos 
    985  1.9  christos   gdbpy_event (gdbpy_event &&other) noexcept
    986  1.9  christos     : m_func (other.m_func)
    987  1.9  christos   {
    988  1.9  christos     other.m_func = nullptr;
    989  1.9  christos   }
    990  1.9  christos 
    991  1.9  christos   gdbpy_event (const gdbpy_event &other)
    992  1.9  christos     : m_func (other.m_func)
    993  1.9  christos   {
    994  1.9  christos     gdbpy_gil gil;
    995  1.9  christos     Py_XINCREF (m_func);
    996  1.9  christos   }
    997  1.9  christos 
    998  1.9  christos   ~gdbpy_event ()
    999  1.9  christos   {
   1000  1.1  christos     gdbpy_gil gil;
   1001  1.9  christos     Py_XDECREF (m_func);
   1002  1.1  christos   }
   1003  1.9  christos 
   1004  1.9  christos   gdbpy_event &operator= (const gdbpy_event &other) = delete;
   1005  1.9  christos 
   1006  1.1  christos   void operator() ()
   1007  1.9  christos   {
   1008  1.9  christos     gdbpy_enter enter_py (get_current_arch (), current_language);
   1009  1.9  christos 
   1010  1.9  christos     gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
   1011  1.1  christos     if (call_result == NULL)
   1012  1.9  christos       gdbpy_print_stack ();
   1013  1.1  christos   }
   1014  1.9  christos 
   1015  1.9  christos private:
   1016  1.9  christos 
   1017  1.9  christos   /* The Python event.  This is just a callable object.  Note that
   1018  1.9  christos      this is not a gdbpy_ref<>, because we have to take particular
   1019  1.1  christos      care to only destroy the reference when holding the GIL. */
   1020  1.1  christos   PyObject *m_func;
   1021  1.1  christos };
   1022  1.1  christos 
   1023  1.1  christos /* Submit an event to the gdb thread.  */
   1024  1.1  christos static PyObject *
   1025  1.1  christos gdbpy_post_event (PyObject *self, PyObject *args)
   1026  1.1  christos {
   1027  1.1  christos   PyObject *func;
   1028  1.1  christos 
   1029  1.1  christos   if (!PyArg_ParseTuple (args, "O", &func))
   1030  1.1  christos     return NULL;
   1031  1.1  christos 
   1032  1.1  christos   if (!PyCallable_Check (func))
   1033  1.1  christos     {
   1034  1.1  christos       PyErr_SetString (PyExc_RuntimeError,
   1035  1.1  christos 		       _("Posted event is not callable"));
   1036  1.9  christos       return NULL;
   1037  1.9  christos     }
   1038  1.9  christos 
   1039  1.1  christos   gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
   1040  1.1  christos   gdbpy_event event (std::move (func_ref));
   1041  1.1  christos   run_on_main_thread (event);
   1042  1.1  christos 
   1043  1.1  christos   Py_RETURN_NONE;
   1044  1.1  christos }
   1045  1.3  christos 
   1046  1.3  christos 
   1047  1.3  christos 
   1049  1.3  christos /* This is the extension_language_ops.before_prompt "method".  */
   1050  1.1  christos 
   1051  1.1  christos static enum ext_lang_rc
   1052  1.3  christos gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
   1053  1.1  christos 			  const char *current_gdb_prompt)
   1054  1.7  christos {
   1055  1.7  christos   if (!gdb_python_initialized)
   1056  1.7  christos     return EXT_LANG_RC_NOP;
   1057  1.7  christos 
   1058  1.7  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1059  1.1  christos 
   1060  1.1  christos   if (!evregpy_no_listeners_p (gdb_py_events.before_prompt)
   1061  1.1  christos       && evpy_emit_event (NULL, gdb_py_events.before_prompt) < 0)
   1062  1.1  christos     return EXT_LANG_RC_ERROR;
   1063  1.7  christos 
   1064  1.7  christos   if (gdb_python_module
   1065  1.1  christos       && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
   1066  1.7  christos     {
   1067  1.7  christos       gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
   1068  1.7  christos 						"prompt_hook"));
   1069  1.7  christos       if (hook == NULL)
   1070  1.1  christos 	{
   1071  1.7  christos 	  gdbpy_print_stack ();
   1072  1.1  christos 	  return EXT_LANG_RC_ERROR;
   1073  1.7  christos 	}
   1074  1.1  christos 
   1075  1.7  christos       if (PyCallable_Check (hook.get ()))
   1076  1.7  christos 	{
   1077  1.7  christos 	  gdbpy_ref<> current_prompt (PyString_FromString (current_gdb_prompt));
   1078  1.7  christos 	  if (current_prompt == NULL)
   1079  1.1  christos 	    {
   1080  1.7  christos 	      gdbpy_print_stack ();
   1081  1.7  christos 	      return EXT_LANG_RC_ERROR;
   1082  1.7  christos 	    }
   1083  1.1  christos 
   1084  1.7  christos 	  gdbpy_ref<> result
   1085  1.7  christos 	    (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
   1086  1.7  christos 					   NULL));
   1087  1.7  christos 	  if (result == NULL)
   1088  1.1  christos 	    {
   1089  1.1  christos 	      gdbpy_print_stack ();
   1090  1.1  christos 	      return EXT_LANG_RC_ERROR;
   1091  1.1  christos 	    }
   1092  1.7  christos 
   1093  1.1  christos 	  /* Return type should be None, or a String.  If it is None,
   1094  1.1  christos 	     fall through, we will not set a prompt.  If it is a
   1095  1.1  christos 	     string, set  PROMPT.  Anything else, set an exception.  */
   1096  1.1  christos 	  if (result != Py_None && ! PyString_Check (result.get ()))
   1097  1.7  christos 	    {
   1098  1.7  christos 	      PyErr_Format (PyExc_RuntimeError,
   1099  1.1  christos 			    _("Return from prompt_hook must " \
   1100  1.1  christos 			      "be either a Python string, or None"));
   1101  1.1  christos 	      gdbpy_print_stack ();
   1102  1.1  christos 	      return EXT_LANG_RC_ERROR;
   1103  1.7  christos 	    }
   1104  1.7  christos 
   1105  1.1  christos 	  if (result != Py_None)
   1106  1.1  christos 	    {
   1107  1.7  christos 	      gdb::unique_xmalloc_ptr<char>
   1108  1.7  christos 		prompt (python_string_to_host_string (result.get ()));
   1109  1.7  christos 
   1110  1.7  christos 	      if (prompt == NULL)
   1111  1.7  christos 		{
   1112  1.7  christos 		  gdbpy_print_stack ();
   1113  1.7  christos 		  return EXT_LANG_RC_ERROR;
   1114  1.1  christos 		}
   1115  1.1  christos 
   1116  1.1  christos 	      set_prompt (prompt.get ());
   1117  1.1  christos 	      return EXT_LANG_RC_OK;
   1118  1.7  christos 	    }
   1119  1.1  christos 	}
   1120  1.1  christos     }
   1121  1.9  christos 
   1122  1.9  christos   return EXT_LANG_RC_NOP;
   1123  1.9  christos }
   1124  1.9  christos 
   1125  1.9  christos /* This is the extension_language_ops.colorize "method".  */
   1126  1.9  christos 
   1127  1.9  christos static gdb::optional<std::string>
   1128  1.9  christos gdbpy_colorize (const std::string &filename, const std::string &contents)
   1129  1.9  christos {
   1130  1.9  christos   if (!gdb_python_initialized)
   1131  1.9  christos     return {};
   1132  1.9  christos 
   1133  1.9  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1134  1.9  christos 
   1135  1.9  christos   if (gdb_python_module == nullptr
   1136  1.9  christos       || !PyObject_HasAttrString (gdb_python_module, "colorize"))
   1137  1.9  christos     return {};
   1138  1.9  christos 
   1139  1.9  christos   gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module, "colorize"));
   1140  1.9  christos   if (hook == nullptr)
   1141  1.9  christos     {
   1142  1.9  christos       gdbpy_print_stack ();
   1143  1.9  christos       return {};
   1144  1.9  christos     }
   1145  1.9  christos 
   1146  1.9  christos   if (!PyCallable_Check (hook.get ()))
   1147  1.9  christos     return {};
   1148  1.9  christos 
   1149  1.9  christos   gdbpy_ref<> fname_arg (PyString_FromString (filename.c_str ()));
   1150  1.9  christos   if (fname_arg == nullptr)
   1151  1.9  christos     {
   1152  1.9  christos       gdbpy_print_stack ();
   1153  1.9  christos       return {};
   1154  1.9  christos     }
   1155  1.9  christos   gdbpy_ref<> contents_arg (PyString_FromString (contents.c_str ()));
   1156  1.9  christos   if (contents_arg == nullptr)
   1157  1.9  christos     {
   1158  1.9  christos       gdbpy_print_stack ();
   1159  1.9  christos       return {};
   1160  1.9  christos     }
   1161  1.9  christos 
   1162  1.9  christos   gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
   1163  1.9  christos 						    fname_arg.get (),
   1164  1.9  christos 						    contents_arg.get (),
   1165  1.9  christos 						    nullptr));
   1166  1.9  christos   if (result == nullptr)
   1167  1.9  christos     {
   1168  1.9  christos       gdbpy_print_stack ();
   1169  1.9  christos       return {};
   1170  1.9  christos     }
   1171  1.9  christos 
   1172  1.9  christos   if (!gdbpy_is_string (result.get ()))
   1173  1.9  christos     return {};
   1174  1.9  christos 
   1175  1.9  christos   gdbpy_ref<> unic = python_string_to_unicode (result.get ());
   1176  1.9  christos   if (unic == nullptr)
   1177  1.9  christos     {
   1178  1.9  christos       gdbpy_print_stack ();
   1179  1.9  christos       return {};
   1180  1.9  christos     }
   1181  1.9  christos   gdbpy_ref<> host_str (PyUnicode_AsEncodedString (unic.get (),
   1182  1.9  christos 						   host_charset (),
   1183  1.9  christos 						   nullptr));
   1184  1.9  christos   if (host_str == nullptr)
   1185  1.9  christos     {
   1186  1.9  christos       gdbpy_print_stack ();
   1187  1.9  christos       return {};
   1188  1.9  christos     }
   1189  1.1  christos 
   1190  1.1  christos   return std::string (PyBytes_AsString (host_str.get ()));
   1191  1.1  christos }
   1192  1.1  christos 
   1193  1.1  christos 
   1194  1.1  christos 
   1196  1.1  christos /* Printing.  */
   1197  1.1  christos 
   1198  1.1  christos /* A python function to write a single string using gdb's filtered
   1199  1.1  christos    output stream .  The optional keyword STREAM can be used to write
   1200  1.1  christos    to a particular stream.  The default stream is to gdb_stdout.  */
   1201  1.7  christos 
   1202  1.1  christos static PyObject *
   1203  1.1  christos gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
   1204  1.7  christos {
   1205  1.7  christos   const char *arg;
   1206  1.1  christos   static const char *keywords[] = { "text", "stream", NULL };
   1207  1.1  christos   int stream_type = 0;
   1208  1.9  christos 
   1209  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
   1210  1.1  christos 					&stream_type))
   1211  1.1  christos     return NULL;
   1212  1.1  christos 
   1213  1.1  christos   try
   1214  1.1  christos     {
   1215  1.1  christos       switch (stream_type)
   1216  1.1  christos         {
   1217  1.1  christos         case 1:
   1218  1.1  christos           {
   1219  1.1  christos 	    fprintf_filtered (gdb_stderr, "%s", arg);
   1220  1.1  christos 	    break;
   1221  1.1  christos           }
   1222  1.1  christos         case 2:
   1223  1.1  christos           {
   1224  1.1  christos 	    fprintf_filtered (gdb_stdlog, "%s", arg);
   1225  1.1  christos 	    break;
   1226  1.9  christos           }
   1227  1.5  christos         default:
   1228  1.5  christos           fprintf_filtered (gdb_stdout, "%s", arg);
   1229  1.5  christos         }
   1230  1.1  christos     }
   1231  1.1  christos   catch (const gdb_exception &except)
   1232  1.1  christos     {
   1233  1.1  christos       GDB_PY_HANDLE_EXCEPTION (except);
   1234  1.1  christos     }
   1235  1.1  christos 
   1236  1.1  christos   Py_RETURN_NONE;
   1237  1.1  christos }
   1238  1.1  christos 
   1239  1.1  christos /* A python function to flush a gdb stream.  The optional keyword
   1240  1.1  christos    STREAM can be used to flush a particular stream.  The default stream
   1241  1.7  christos    is gdb_stdout.  */
   1242  1.1  christos 
   1243  1.1  christos static PyObject *
   1244  1.7  christos gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
   1245  1.7  christos {
   1246  1.1  christos   static const char *keywords[] = { "stream", NULL };
   1247  1.1  christos   int stream_type = 0;
   1248  1.1  christos 
   1249  1.1  christos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
   1250  1.1  christos 					&stream_type))
   1251  1.1  christos     return NULL;
   1252  1.1  christos 
   1253  1.1  christos   switch (stream_type)
   1254  1.1  christos     {
   1255  1.1  christos     case 1:
   1256  1.1  christos       {
   1257  1.1  christos 	gdb_flush (gdb_stderr);
   1258  1.1  christos 	break;
   1259  1.1  christos       }
   1260  1.1  christos     case 2:
   1261  1.1  christos       {
   1262  1.1  christos 	gdb_flush (gdb_stdlog);
   1263  1.1  christos 	break;
   1264  1.1  christos       }
   1265  1.1  christos     default:
   1266  1.1  christos       gdb_flush (gdb_stdout);
   1267  1.5  christos     }
   1268  1.5  christos 
   1269  1.5  christos   Py_RETURN_NONE;
   1270  1.5  christos }
   1271  1.5  christos 
   1272  1.5  christos /* Return non-zero if print-stack is not "none".  */
   1273  1.5  christos 
   1274  1.5  christos int
   1275  1.1  christos gdbpy_print_python_errors_p (void)
   1276  1.1  christos {
   1277  1.1  christos   return gdbpy_should_print_stack != python_excp_none;
   1278  1.1  christos }
   1279  1.1  christos 
   1280  1.1  christos /* Print a python exception trace, print just a message, or print
   1281  1.1  christos    nothing and clear the python exception, depending on
   1282  1.1  christos    gdbpy_should_print_stack.  Only call this if a python exception is
   1283  1.1  christos    set.  */
   1284  1.1  christos void
   1285  1.1  christos gdbpy_print_stack (void)
   1286  1.1  christos {
   1287  1.1  christos 
   1288  1.1  christos   /* Print "none", just clear exception.  */
   1289  1.1  christos   if (gdbpy_should_print_stack == python_excp_none)
   1290  1.1  christos     {
   1291  1.1  christos       PyErr_Clear ();
   1292  1.1  christos     }
   1293  1.1  christos   /* Print "full" message and backtrace.  */
   1294  1.1  christos   else if (gdbpy_should_print_stack == python_excp_full)
   1295  1.9  christos     {
   1296  1.1  christos       PyErr_Print ();
   1297  1.1  christos       /* PyErr_Print doesn't necessarily end output with a newline.
   1298  1.1  christos 	 This works because Python's stdout/stderr is fed through
   1299  1.9  christos 	 printf_filtered.  */
   1300  1.5  christos       try
   1301  1.5  christos 	{
   1302  1.1  christos 	  begin_line ();
   1303  1.1  christos 	}
   1304  1.1  christos       catch (const gdb_exception &except)
   1305  1.1  christos 	{
   1306  1.8  christos 	}
   1307  1.1  christos     }
   1308  1.8  christos   /* Print "message", just error print message.  */
   1309  1.8  christos   else
   1310  1.8  christos     {
   1311  1.8  christos       gdbpy_err_fetch fetched_error;
   1312  1.8  christos 
   1313  1.8  christos       gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
   1314  1.1  christos       gdb::unique_xmalloc_ptr<char> type;
   1315  1.9  christos       /* Don't compute TYPE if MSG already indicates that there is an
   1316  1.1  christos 	 error.  */
   1317  1.8  christos       if (msg != NULL)
   1318  1.1  christos 	type = fetched_error.type_to_string ();
   1319  1.1  christos 
   1320  1.1  christos       try
   1321  1.1  christos 	{
   1322  1.1  christos 	  if (msg == NULL || type == NULL)
   1323  1.1  christos 	    {
   1324  1.8  christos 	      /* An error occurred computing the string representation of the
   1325  1.1  christos 		 error message.  */
   1326  1.1  christos 	      fprintf_filtered (gdb_stderr,
   1327  1.1  christos 				_("Error occurred computing Python error" \
   1328  1.7  christos 				  "message.\n"));
   1329  1.1  christos 	      PyErr_Clear ();
   1330  1.9  christos 	    }
   1331  1.5  christos 	  else
   1332  1.5  christos 	    fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
   1333  1.1  christos 			      type.get (), msg.get ());
   1334  1.1  christos 	}
   1335  1.1  christos       catch (const gdb_exception &except)
   1336  1.8  christos 	{
   1337  1.8  christos 	}
   1338  1.1  christos     }
   1339  1.8  christos }
   1340  1.8  christos 
   1341  1.1  christos /* Like gdbpy_print_stack, but if the exception is a
   1342  1.8  christos    KeyboardException, throw a gdb "quit" instead.  */
   1343  1.8  christos 
   1344  1.8  christos void
   1345  1.8  christos gdbpy_print_stack_or_quit ()
   1346  1.8  christos {
   1347  1.8  christos   if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
   1348  1.8  christos     {
   1349  1.1  christos       PyErr_Clear ();
   1350  1.8  christos       throw_quit ("Quit");
   1351  1.1  christos     }
   1352  1.1  christos   gdbpy_print_stack ();
   1353  1.1  christos }
   1354  1.1  christos 
   1355  1.1  christos 
   1356  1.1  christos 
   1358  1.7  christos /* Return a sequence holding all the Progspaces.  */
   1359  1.1  christos 
   1360  1.1  christos static PyObject *
   1361  1.9  christos gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
   1362  1.9  christos {
   1363  1.9  christos   gdbpy_ref<> list (PyList_New (0));
   1364  1.1  christos   if (list == NULL)
   1365  1.9  christos     return NULL;
   1366  1.9  christos 
   1367  1.9  christos   for (struct program_space *ps : program_spaces)
   1368  1.1  christos     {
   1369  1.7  christos       gdbpy_ref<> item = pspace_to_pspace_object (ps);
   1370  1.1  christos 
   1371  1.1  christos       if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
   1372  1.1  christos 	return NULL;
   1373  1.1  christos     }
   1374  1.1  christos 
   1375  1.1  christos   return list.release ();
   1376  1.5  christos }
   1377  1.5  christos 
   1378  1.1  christos 
   1379  1.1  christos 
   1381  1.1  christos /* The "current" objfile.  This is set when gdb detects that a new
   1382  1.3  christos    objfile has been loaded.  It is only set for the duration of a call to
   1383  1.3  christos    gdbpy_source_objfile_script and gdbpy_execute_objfile_script; it is NULL
   1384  1.3  christos    at other times.  */
   1385  1.1  christos static struct objfile *gdbpy_current_objfile;
   1386  1.3  christos 
   1387  1.3  christos /* Set the current objfile to OBJFILE and then read FILE named FILENAME
   1388  1.3  christos    as Python code.  This does not throw any errors.  If an exception
   1389  1.3  christos    occurs python will print the traceback and clear the error indicator.
   1390  1.1  christos    This is the extension_language_script_ops.objfile_script_sourcer
   1391  1.1  christos    "method".  */
   1392  1.1  christos 
   1393  1.1  christos static void
   1394  1.9  christos gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
   1395  1.1  christos 			     struct objfile *objfile, FILE *file,
   1396  1.1  christos 			     const char *filename)
   1397  1.1  christos {
   1398  1.1  christos   if (!gdb_python_initialized)
   1399  1.1  christos     return;
   1400  1.1  christos 
   1401  1.1  christos   gdbpy_enter enter_py (objfile->arch (), current_language);
   1402  1.5  christos   gdbpy_current_objfile = objfile;
   1403  1.5  christos 
   1404  1.5  christos   python_run_simple_file (file, filename);
   1405  1.5  christos 
   1406  1.5  christos   gdbpy_current_objfile = NULL;
   1407  1.5  christos }
   1408  1.5  christos 
   1409  1.5  christos /* Set the current objfile to OBJFILE and then execute SCRIPT
   1410  1.5  christos    as Python code.  This does not throw any errors.  If an exception
   1411  1.5  christos    occurs python will print the traceback and clear the error indicator.
   1412  1.5  christos    This is the extension_language_script_ops.objfile_script_executor
   1413  1.5  christos    "method".  */
   1414  1.5  christos 
   1415  1.5  christos static void
   1416  1.9  christos gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
   1417  1.5  christos 			      struct objfile *objfile, const char *name,
   1418  1.5  christos 			      const char *script)
   1419  1.5  christos {
   1420  1.5  christos   if (!gdb_python_initialized)
   1421  1.5  christos     return;
   1422  1.5  christos 
   1423  1.5  christos   gdbpy_enter enter_py (objfile->arch (), current_language);
   1424  1.1  christos   gdbpy_current_objfile = objfile;
   1425  1.1  christos 
   1426  1.1  christos   PyRun_SimpleString (script);
   1427  1.1  christos 
   1428  1.1  christos   gdbpy_current_objfile = NULL;
   1429  1.1  christos }
   1430  1.1  christos 
   1431  1.1  christos /* Return the current Objfile, or None if there isn't one.  */
   1432  1.8  christos 
   1433  1.1  christos static PyObject *
   1434  1.1  christos gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
   1435  1.3  christos {
   1436  1.3  christos   if (! gdbpy_current_objfile)
   1437  1.3  christos     Py_RETURN_NONE;
   1438  1.3  christos 
   1439  1.1  christos   return objfile_to_objfile_object (gdbpy_current_objfile).release ();
   1440  1.3  christos }
   1441  1.3  christos 
   1442  1.3  christos /* Compute the list of active python type printers and store them in
   1443  1.1  christos    EXT_PRINTERS->py_type_printers.  The product of this function is used by
   1444  1.7  christos    gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
   1445  1.1  christos    This is the extension_language_ops.start_type_printers "method".  */
   1446  1.1  christos 
   1447  1.3  christos static void
   1448  1.1  christos gdbpy_start_type_printers (const struct extension_language_defn *extlang,
   1449  1.7  christos 			   struct ext_lang_type_printers *ext_printers)
   1450  1.1  christos {
   1451  1.7  christos   PyObject *printers_obj = NULL;
   1452  1.1  christos 
   1453  1.1  christos   if (!gdb_python_initialized)
   1454  1.1  christos     return;
   1455  1.7  christos 
   1456  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1457  1.1  christos 
   1458  1.7  christos   gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
   1459  1.7  christos   if (type_module == NULL)
   1460  1.1  christos     {
   1461  1.1  christos       gdbpy_print_stack ();
   1462  1.1  christos       return;
   1463  1.7  christos     }
   1464  1.1  christos 
   1465  1.1  christos   gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
   1466  1.7  christos 					    "get_type_recognizers"));
   1467  1.3  christos   if (func == NULL)
   1468  1.1  christos     {
   1469  1.3  christos       gdbpy_print_stack ();
   1470  1.3  christos       return;
   1471  1.1  christos     }
   1472  1.1  christos 
   1473  1.3  christos   printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
   1474  1.3  christos   if (printers_obj == NULL)
   1475  1.3  christos     gdbpy_print_stack ();
   1476  1.3  christos   else
   1477  1.3  christos     ext_printers->py_type_printers = printers_obj;
   1478  1.3  christos }
   1479  1.3  christos 
   1480  1.3  christos /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
   1481  1.3  christos    a newly allocated string holding the type's replacement name, and return
   1482  1.3  christos    EXT_LANG_RC_OK.  The caller is responsible for freeing the string.
   1483  1.3  christos    If there's a Python error return EXT_LANG_RC_ERROR.
   1484  1.1  christos    Otherwise, return EXT_LANG_RC_NOP.
   1485  1.6  christos    This is the extension_language_ops.apply_type_printers "method".  */
   1486  1.7  christos 
   1487  1.1  christos static enum ext_lang_rc
   1488  1.1  christos gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
   1489  1.3  christos 			   const struct ext_lang_type_printers *ext_printers,
   1490  1.1  christos 			   struct type *type, char **prettied_type)
   1491  1.1  christos {
   1492  1.3  christos   PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
   1493  1.1  christos   gdb::unique_xmalloc_ptr<char> result;
   1494  1.7  christos 
   1495  1.1  christos   if (printers_obj == NULL)
   1496  1.7  christos     return EXT_LANG_RC_NOP;
   1497  1.1  christos 
   1498  1.1  christos   if (!gdb_python_initialized)
   1499  1.1  christos     return EXT_LANG_RC_NOP;
   1500  1.7  christos 
   1501  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1502  1.1  christos 
   1503  1.7  christos   gdbpy_ref<> type_obj (type_to_type_object (type));
   1504  1.1  christos   if (type_obj == NULL)
   1505  1.1  christos     {
   1506  1.1  christos       gdbpy_print_stack ();
   1507  1.7  christos       return EXT_LANG_RC_ERROR;
   1508  1.1  christos     }
   1509  1.1  christos 
   1510  1.7  christos   gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
   1511  1.7  christos   if (type_module == NULL)
   1512  1.1  christos     {
   1513  1.1  christos       gdbpy_print_stack ();
   1514  1.1  christos       return EXT_LANG_RC_ERROR;
   1515  1.7  christos     }
   1516  1.1  christos 
   1517  1.1  christos   gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
   1518  1.7  christos 					    "apply_type_recognizers"));
   1519  1.7  christos   if (func == NULL)
   1520  1.7  christos     {
   1521  1.7  christos       gdbpy_print_stack ();
   1522  1.1  christos       return EXT_LANG_RC_ERROR;
   1523  1.1  christos     }
   1524  1.1  christos 
   1525  1.7  christos   gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
   1526  1.1  christos 							printers_obj,
   1527  1.1  christos 							type_obj.get (),
   1528  1.7  christos 							(char *) NULL));
   1529  1.7  christos   if (result_obj == NULL)
   1530  1.7  christos     {
   1531  1.7  christos       gdbpy_print_stack ();
   1532  1.7  christos       return EXT_LANG_RC_ERROR;
   1533  1.1  christos     }
   1534  1.7  christos 
   1535  1.7  christos   if (result_obj == Py_None)
   1536  1.1  christos     return EXT_LANG_RC_NOP;
   1537  1.1  christos 
   1538  1.7  christos   result = python_string_to_host_string (result_obj.get ());
   1539  1.7  christos   if (result == NULL)
   1540  1.1  christos     {
   1541  1.1  christos       gdbpy_print_stack ();
   1542  1.3  christos       return EXT_LANG_RC_ERROR;
   1543  1.3  christos     }
   1544  1.1  christos 
   1545  1.3  christos   *prettied_type = result.release ();
   1546  1.3  christos   return EXT_LANG_RC_OK;
   1547  1.3  christos }
   1548  1.1  christos 
   1549  1.6  christos /* Free the result of start_type_printers.
   1550  1.1  christos    This is the extension_language_ops.free_type_printers "method".  */
   1551  1.1  christos 
   1552  1.1  christos static void
   1553  1.1  christos gdbpy_free_type_printers (const struct extension_language_defn *extlang,
   1554  1.1  christos 			  struct ext_lang_type_printers *ext_printers)
   1555  1.1  christos {
   1556  1.1  christos   PyObject *printers = (PyObject *) ext_printers->py_type_printers;
   1557  1.7  christos 
   1558  1.1  christos   if (printers == NULL)
   1559  1.1  christos     return;
   1560  1.1  christos 
   1561  1.1  christos   if (!gdb_python_initialized)
   1562  1.1  christos     return;
   1563  1.1  christos 
   1564  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1565  1.1  christos   Py_DECREF (printers);
   1566  1.1  christos }
   1567  1.8  christos 
   1568  1.1  christos #else /* HAVE_PYTHON */
   1569  1.1  christos 
   1570  1.1  christos /* Dummy implementation of the gdb "python-interactive" and "python"
   1571  1.1  christos    command. */
   1572  1.1  christos 
   1573  1.1  christos static void
   1574  1.8  christos python_interactive_command (const char *arg, int from_tty)
   1575  1.1  christos {
   1576  1.7  christos   arg = skip_spaces (arg);
   1577  1.1  christos   if (arg && *arg)
   1578  1.1  christos     error (_("Python scripting is not supported in this copy of GDB."));
   1579  1.1  christos   else
   1580  1.1  christos     {
   1581  1.8  christos       counted_command_line l = get_command_line (python_control, "");
   1582  1.1  christos 
   1583  1.1  christos       execute_control_command_untraced (l.get ());
   1584  1.1  christos     }
   1585  1.1  christos }
   1586  1.1  christos 
   1587  1.1  christos static void
   1588  1.1  christos python_command (const char *arg, int from_tty)
   1589  1.1  christos {
   1590  1.1  christos   python_interactive_command (arg, from_tty);
   1591  1.1  christos }
   1592  1.1  christos 
   1593  1.1  christos #endif /* HAVE_PYTHON */
   1594  1.1  christos 
   1595  1.1  christos 
   1596  1.1  christos 
   1598  1.1  christos /* Lists for 'set python' commands.  */
   1599  1.1  christos 
   1600  1.1  christos static struct cmd_list_element *user_set_python_list;
   1601  1.1  christos static struct cmd_list_element *user_show_python_list;
   1602  1.1  christos 
   1603  1.1  christos /* Initialize the Python code.  */
   1604  1.1  christos 
   1605  1.3  christos #ifdef HAVE_PYTHON
   1606  1.3  christos 
   1607  1.1  christos /* This is installed as a final cleanup and cleans up the
   1608  1.1  christos    interpreter.  This lets Python's 'atexit' work.  */
   1609  1.1  christos 
   1610  1.1  christos static void
   1611  1.1  christos finalize_python (void *ignore)
   1612  1.3  christos {
   1613  1.3  christos   struct active_ext_lang_state *previous_active;
   1614  1.3  christos 
   1615  1.3  christos   /* We don't use ensure_python_env here because if we ever ran the
   1616  1.3  christos      cleanup, gdb would crash -- because the cleanup calls into the
   1617  1.1  christos      Python interpreter, which we are about to destroy.  It seems
   1618  1.1  christos      clearer to make the needed calls explicitly here than to create a
   1619  1.1  christos      cleanup and then mysteriously discard it.  */
   1620  1.1  christos 
   1621  1.1  christos   /* This is only called as a final cleanup so we can assume the active
   1622  1.3  christos      SIGINT handler is gdb's.  We still need to tell it to notify Python.  */
   1623  1.9  christos   previous_active = set_active_ext_lang (&extension_language_python);
   1624  1.3  christos 
   1625  1.1  christos   (void) PyGILState_Ensure ();
   1626  1.8  christos   python_gdbarch = target_gdbarch ();
   1627  1.8  christos   python_language = current_language;
   1628  1.8  christos 
   1629  1.8  christos   Py_Finalize ();
   1630  1.8  christos 
   1631  1.9  christos   gdb_python_initialized = false;
   1632  1.8  christos   restore_active_ext_lang (previous_active);
   1633  1.8  christos }
   1634  1.8  christos 
   1635  1.8  christos #ifdef IS_PY3K
   1636  1.8  christos /* This is called via the PyImport_AppendInittab mechanism called
   1637  1.1  christos    during initialization, to make the built-in _gdb module known to
   1638  1.1  christos    Python.  */
   1639  1.7  christos PyMODINIT_FUNC init__gdb_module (void);
   1640  1.7  christos PyMODINIT_FUNC
   1641  1.1  christos init__gdb_module (void)
   1642  1.1  christos {
   1643  1.1  christos   return PyModule_Create (&python_GdbModuleDef);
   1644  1.9  christos }
   1645  1.9  christos #endif
   1646  1.9  christos 
   1647  1.9  christos static bool
   1648  1.9  christos do_start_initialization ()
   1649  1.9  christos {
   1650  1.9  christos #ifdef IS_PY3K
   1651  1.9  christos   size_t progsize, count;
   1652  1.1  christos   /* Python documentation indicates that the memory given
   1653  1.1  christos      to Py_SetProgramName cannot be freed.  However, it seems that
   1654  1.1  christos      at least Python 3.7.4 Py_SetProgramName takes a copy of the
   1655  1.1  christos      given program_name.  Making progname_copy static and not release
   1656  1.1  christos      the memory avoids a leak report for Python versions that duplicate
   1657  1.1  christos      program_name, and respect the requirement of Py_SetProgramName
   1658  1.1  christos      for Python versions that do not duplicate program_name.  */
   1659  1.1  christos   static wchar_t *progname_copy;
   1660  1.1  christos #endif
   1661  1.8  christos 
   1662  1.9  christos #ifdef WITH_PYTHON_PATH
   1663  1.8  christos   /* Work around problem where python gets confused about where it is,
   1664  1.1  christos      and then can't find its libraries, etc.
   1665  1.8  christos      NOTE: Python assumes the following layout:
   1666  1.1  christos      /foo/bin/python
   1667  1.8  christos      /foo/lib/pythonX.Y/...
   1668  1.9  christos      This must be done before calling Py_Initialize.  */
   1669  1.8  christos   gdb::unique_xmalloc_ptr<char> progname
   1670  1.1  christos     (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
   1671  1.1  christos 	      SLASH_STRING, "python", (char *) NULL));
   1672  1.1  christos #ifdef IS_PY3K
   1673  1.7  christos   std::string oldloc = setlocale (LC_ALL, NULL);
   1674  1.1  christos   setlocale (LC_ALL, "");
   1675  1.8  christos   progsize = strlen (progname.get ());
   1676  1.1  christos   progname_copy = XNEWVEC (wchar_t, progsize + 1);
   1677  1.1  christos   count = mbstowcs (progname_copy, progname.get (), progsize + 1);
   1678  1.1  christos   if (count == (size_t) -1)
   1679  1.1  christos     {
   1680  1.1  christos       fprintf (stderr, "Could not convert python path to string\n");
   1681  1.8  christos       return false;
   1682  1.8  christos     }
   1683  1.8  christos   setlocale (LC_ALL, oldloc.c_str ());
   1684  1.1  christos 
   1685  1.8  christos   /* Note that Py_SetProgramName expects the string it is passed to
   1686  1.1  christos      remain alive for the duration of the program's execution, so
   1687  1.1  christos      it is not freed after this call.  */
   1688  1.1  christos   Py_SetProgramName (progname_copy);
   1689  1.1  christos 
   1690  1.9  christos   /* Define _gdb as a built-in module.  */
   1691  1.9  christos   PyImport_AppendInittab ("_gdb", init__gdb_module);
   1692  1.9  christos #else
   1693  1.9  christos   Py_SetProgramName (progname.release ());
   1694  1.1  christos #endif
   1695  1.9  christos #endif
   1696  1.1  christos 
   1697  1.1  christos   Py_Initialize ();
   1698  1.8  christos #if PY_VERSION_HEX < 0x03090000
   1699  1.1  christos   /* PyEval_InitThreads became deprecated in Python 3.9 and will
   1700  1.5  christos      be removed in Python 3.11.  Prior to Python 3.7, this call was
   1701  1.1  christos      required to initialize the GIL.  */
   1702  1.1  christos   PyEval_InitThreads ();
   1703  1.7  christos #endif
   1704  1.1  christos 
   1705  1.9  christos #ifdef IS_PY3K
   1706  1.9  christos   gdb_module = PyImport_ImportModule ("_gdb");
   1707  1.1  christos #else
   1708  1.9  christos   gdb_module = Py_InitModule ("_gdb", python_GdbMethods);
   1709  1.7  christos #endif
   1710  1.1  christos   if (gdb_module == NULL)
   1711  1.1  christos     return false;
   1712  1.1  christos 
   1713  1.1  christos   if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
   1714  1.1  christos       || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
   1715  1.7  christos       || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
   1716  1.1  christos 				     target_name) < 0)
   1717  1.1  christos     return false;
   1718  1.1  christos 
   1719  1.1  christos   /* Add stream constants.  */
   1720  1.7  christos   if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
   1721  1.1  christos       || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
   1722  1.1  christos       || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
   1723  1.1  christos     return false;
   1724  1.1  christos 
   1725  1.1  christos   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
   1726  1.1  christos   if (gdbpy_gdb_error == NULL
   1727  1.7  christos       || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
   1728  1.1  christos     return false;
   1729  1.1  christos 
   1730  1.1  christos   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
   1731  1.1  christos 					       gdbpy_gdb_error, NULL);
   1732  1.1  christos   if (gdbpy_gdb_memory_error == NULL
   1733  1.7  christos       || gdb_pymodule_addobject (gdb_module, "MemoryError",
   1734  1.1  christos 				 gdbpy_gdb_memory_error) < 0)
   1735  1.1  christos     return false;
   1736  1.1  christos 
   1737  1.1  christos   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
   1738  1.1  christos   if (gdbpy_gdberror_exc == NULL
   1739  1.1  christos       || gdb_pymodule_addobject (gdb_module, "GdbError",
   1740  1.1  christos 				 gdbpy_gdberror_exc) < 0)
   1741  1.7  christos     return false;
   1742  1.7  christos 
   1743  1.7  christos   gdbpy_initialize_gdb_readline ();
   1744  1.1  christos 
   1745  1.1  christos   if (gdbpy_initialize_auto_load () < 0
   1746  1.1  christos       || gdbpy_initialize_values () < 0
   1747  1.1  christos       || gdbpy_initialize_frames () < 0
   1748  1.1  christos       || gdbpy_initialize_commands () < 0
   1749  1.1  christos       || gdbpy_initialize_instruction () < 0
   1750  1.1  christos       || gdbpy_initialize_record () < 0
   1751  1.1  christos       || gdbpy_initialize_btrace () < 0
   1752  1.1  christos       || gdbpy_initialize_symbols () < 0
   1753  1.1  christos       || gdbpy_initialize_symtabs () < 0
   1754  1.1  christos       || gdbpy_initialize_blocks () < 0
   1755  1.1  christos       || gdbpy_initialize_functions () < 0
   1756  1.1  christos       || gdbpy_initialize_parameters () < 0
   1757  1.1  christos       || gdbpy_initialize_types () < 0
   1758  1.1  christos       || gdbpy_initialize_pspace () < 0
   1759  1.1  christos       || gdbpy_initialize_objfile () < 0
   1760  1.1  christos       || gdbpy_initialize_breakpoints () < 0
   1761  1.3  christos       || gdbpy_initialize_finishbreakpoints () < 0
   1762  1.9  christos       || gdbpy_initialize_lazy_string () < 0
   1763  1.5  christos       || gdbpy_initialize_linetable () < 0
   1764  1.9  christos       || gdbpy_initialize_thread () < 0
   1765  1.9  christos       || gdbpy_initialize_inferior () < 0
   1766  1.7  christos       || gdbpy_initialize_eventregistry () < 0
   1767  1.1  christos       || gdbpy_initialize_py_events () < 0
   1768  1.8  christos       || gdbpy_initialize_event () < 0
   1769  1.8  christos       || gdbpy_initialize_arch () < 0
   1770  1.8  christos       || gdbpy_initialize_registers () < 0
   1771  1.8  christos       || gdbpy_initialize_xmethods () < 0
   1772  1.8  christos       || gdbpy_initialize_unwind () < 0
   1773  1.8  christos       || gdbpy_initialize_tui () < 0)
   1774  1.1  christos     return false;
   1775  1.1  christos 
   1776  1.7  christos #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base)	\
   1777  1.1  christos   if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
   1778  1.1  christos     return false;
   1779  1.7  christos #include "py-event-types.def"
   1780  1.1  christos #undef GDB_PY_DEFINE_EVENT_TYPE
   1781  1.1  christos 
   1782  1.7  christos   gdbpy_to_string_cst = PyString_FromString ("to_string");
   1783  1.1  christos   if (gdbpy_to_string_cst == NULL)
   1784  1.1  christos     return false;
   1785  1.7  christos   gdbpy_children_cst = PyString_FromString ("children");
   1786  1.1  christos   if (gdbpy_children_cst == NULL)
   1787  1.1  christos     return false;
   1788  1.7  christos   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
   1789  1.1  christos   if (gdbpy_display_hint_cst == NULL)
   1790  1.1  christos     return false;
   1791  1.7  christos   gdbpy_doc_cst = PyString_FromString ("__doc__");
   1792  1.1  christos   if (gdbpy_doc_cst == NULL)
   1793  1.1  christos     return false;
   1794  1.9  christos   gdbpy_enabled_cst = PyString_FromString ("enabled");
   1795  1.1  christos   if (gdbpy_enabled_cst == NULL)
   1796  1.1  christos     return false;
   1797  1.1  christos   gdbpy_value_cst = PyString_FromString ("value");
   1798  1.7  christos   if (gdbpy_value_cst == NULL)
   1799  1.1  christos     return false;
   1800  1.7  christos 
   1801  1.7  christos   /* Release the GIL while gdb runs.  */
   1802  1.7  christos   PyEval_SaveThread ();
   1803  1.7  christos 
   1804  1.7  christos   make_final_cleanup (finalize_python, NULL);
   1805  1.8  christos 
   1806  1.8  christos   /* Only set this when initialization has succeeded.  */
   1807  1.8  christos   gdb_python_initialized = 1;
   1808  1.9  christos   return true;
   1809  1.7  christos }
   1810  1.9  christos 
   1811  1.7  christos #endif /* HAVE_PYTHON */
   1812  1.7  christos 
   1813  1.7  christos /* See python.h.  */
   1814  1.7  christos cmd_list_element *python_cmd_element = nullptr;
   1815  1.7  christos 
   1816  1.7  christos void _initialize_python ();
   1817  1.7  christos void
   1818  1.7  christos _initialize_python ()
   1819  1.7  christos {
   1820  1.7  christos   add_com ("python-interactive", class_obscure,
   1821  1.7  christos 	   python_interactive_command,
   1822  1.7  christos #ifdef HAVE_PYTHON
   1823  1.7  christos 	   _("\
   1824  1.7  christos Start an interactive Python prompt.\n\
   1825  1.7  christos \n\
   1826  1.9  christos To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
   1827  1.7  christos prompt).\n\
   1828  1.7  christos \n\
   1829  1.7  christos Alternatively, a single-line Python command can be given as an\n\
   1830  1.7  christos argument, and if the command is an expression, the result will be\n\
   1831  1.7  christos printed.  For example:\n\
   1832  1.7  christos \n\
   1833  1.7  christos     (gdb) python-interactive 2 + 3\n\
   1834  1.7  christos     5")
   1835  1.7  christos #else /* HAVE_PYTHON */
   1836  1.7  christos 	   _("\
   1837  1.8  christos Start a Python interactive prompt.\n\
   1838  1.7  christos \n\
   1839  1.7  christos Python scripting is not supported in this copy of GDB.\n\
   1840  1.7  christos This command is only a placeholder.")
   1841  1.7  christos #endif /* HAVE_PYTHON */
   1842  1.7  christos 	   );
   1843  1.7  christos   add_com_alias ("pi", "python-interactive", class_obscure, 1);
   1844  1.8  christos 
   1845  1.7  christos   python_cmd_element = add_com ("python", class_obscure, python_command,
   1846  1.7  christos #ifdef HAVE_PYTHON
   1847  1.7  christos 	   _("\
   1848  1.7  christos Evaluate a Python command.\n\
   1849  1.7  christos \n\
   1850  1.7  christos The command can be given as an argument, for instance:\n\
   1851  1.7  christos \n\
   1852  1.7  christos     python print (23)\n\
   1853  1.7  christos \n\
   1854  1.7  christos If no argument is given, the following lines are read and used\n\
   1855  1.7  christos as the Python commands.  Type a line containing \"end\" to indicate\n\
   1856  1.7  christos the end of the command.")
   1857  1.7  christos #else /* HAVE_PYTHON */
   1858  1.1  christos 	   _("\
   1859  1.7  christos Evaluate a Python command.\n\
   1860  1.9  christos \n\
   1861  1.9  christos Python scripting is not supported in this copy of GDB.\n\
   1862  1.9  christos This command is only a placeholder.")
   1863  1.9  christos #endif /* HAVE_PYTHON */
   1864  1.9  christos 	   );
   1865  1.9  christos   add_com_alias ("py", "python", class_obscure, 1);
   1866  1.9  christos 
   1867  1.9  christos   /* Add set/show python print-stack.  */
   1868  1.9  christos   add_basic_prefix_cmd ("python", no_class,
   1869  1.7  christos 			_("Prefix command for python preference settings."),
   1870  1.7  christos 			&user_show_python_list, "show python ", 0,
   1871  1.7  christos 			&showlist);
   1872  1.7  christos 
   1873  1.7  christos   add_show_prefix_cmd ("python", no_class,
   1874  1.7  christos 		       _("Prefix command for python preference settings."),
   1875  1.7  christos 		       &user_set_python_list, "set python ", 0,
   1876  1.7  christos 		       &setlist);
   1877  1.7  christos 
   1878  1.7  christos   add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
   1879  1.7  christos 			&gdbpy_should_print_stack, _("\
   1880  1.1  christos Set mode for Python stack dump on error."), _("\
   1881  1.7  christos Show the mode of Python stack printing on error."), _("\
   1882  1.7  christos none  == no stack or message will be printed.\n\
   1883  1.7  christos full == a message and a stack will be printed.\n\
   1884  1.1  christos message == an error message without a stack will be printed."),
   1885  1.1  christos 			NULL, NULL,
   1886  1.1  christos 			&user_set_python_list,
   1887  1.1  christos 			&user_show_python_list);
   1888  1.1  christos 
   1889  1.7  christos #ifdef HAVE_PYTHON
   1890  1.7  christos   if (!do_start_initialization () && PyErr_Occurred ())
   1891  1.7  christos     gdbpy_print_stack ();
   1892  1.1  christos #endif /* HAVE_PYTHON */
   1893  1.7  christos }
   1894  1.7  christos 
   1895  1.1  christos #ifdef HAVE_PYTHON
   1896  1.1  christos 
   1897  1.1  christos /* Helper function for gdbpy_finish_initialization.  This does the
   1898  1.1  christos    work and then returns false if an error has occurred and must be
   1899  1.1  christos    displayed, or true on success.  */
   1900  1.1  christos 
   1901  1.7  christos static bool
   1902  1.7  christos do_finish_initialization (const struct extension_language_defn *extlang)
   1903  1.1  christos {
   1904  1.1  christos   PyObject *m;
   1905  1.1  christos   PyObject *sys_path;
   1906  1.1  christos 
   1907  1.1  christos   /* Add the initial data-directory to sys.path.  */
   1908  1.1  christos 
   1909  1.1  christos   std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
   1910  1.1  christos 			       + "python");
   1911  1.1  christos 
   1912  1.1  christos   sys_path = PySys_GetObject ("path");
   1913  1.1  christos 
   1914  1.1  christos   /* If sys.path is not defined yet, define it first.  */
   1915  1.1  christos   if (!(sys_path && PyList_Check (sys_path)))
   1916  1.1  christos     {
   1917  1.1  christos #ifdef IS_PY3K
   1918  1.7  christos       PySys_SetPath (L"");
   1919  1.7  christos #else
   1920  1.7  christos       PySys_SetPath ("");
   1921  1.1  christos #endif
   1922  1.1  christos       sys_path = PySys_GetObject ("path");
   1923  1.7  christos     }
   1924  1.1  christos   if (sys_path && PyList_Check (sys_path))
   1925  1.1  christos     {
   1926  1.1  christos       gdbpy_ref<> pythondir (PyString_FromString (gdb_pythondir.c_str ()));
   1927  1.1  christos       if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
   1928  1.1  christos 	return false;
   1929  1.7  christos     }
   1930  1.1  christos   else
   1931  1.7  christos     return false;
   1932  1.7  christos 
   1933  1.1  christos   /* Import the gdb module to finish the initialization, and
   1934  1.1  christos      add it to __main__ for convenience.  */
   1935  1.1  christos   m = PyImport_AddModule ("__main__");
   1936  1.1  christos   if (m == NULL)
   1937  1.1  christos     return false;
   1938  1.1  christos 
   1939  1.1  christos   /* Keep the reference to gdb_python_module since it is in a global
   1940  1.1  christos      variable.  */
   1941  1.1  christos   gdb_python_module = PyImport_ImportModule ("gdb");
   1942  1.9  christos   if (gdb_python_module == NULL)
   1943  1.7  christos     {
   1944  1.7  christos       gdbpy_print_stack ();
   1945  1.7  christos       /* This is passed in one call to warning so that blank lines aren't
   1946  1.7  christos 	 inserted between each line of text.  */
   1947  1.1  christos       warning (_("\n"
   1948  1.1  christos 		 "Could not load the Python gdb module from `%s'.\n"
   1949  1.7  christos 		 "Limited Python support is available from the _gdb module.\n"
   1950  1.7  christos 		 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
   1951  1.1  christos 	       gdb_pythondir.c_str ());
   1952  1.7  christos       /* We return "success" here as we've already emitted the
   1953  1.7  christos 	 warning.  */
   1954  1.7  christos       return true;
   1955  1.7  christos     }
   1956  1.7  christos 
   1957  1.1  christos   return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
   1958  1.7  christos }
   1959  1.7  christos 
   1960  1.7  christos /* Perform the remaining python initializations.
   1961  1.7  christos    These must be done after GDB is at least mostly initialized.
   1962  1.1  christos    E.g., The "info pretty-printer" command needs the "info" prefix
   1963  1.7  christos    command installed.
   1964  1.7  christos    This is the extension_language_ops.finish_initialization "method".  */
   1965  1.7  christos 
   1966  1.7  christos static void
   1967  1.7  christos gdbpy_finish_initialization (const struct extension_language_defn *extlang)
   1968  1.1  christos {
   1969  1.1  christos   gdbpy_enter enter_py (get_current_arch (), current_language);
   1970  1.3  christos 
   1971  1.3  christos   if (!do_finish_initialization (extlang))
   1972  1.3  christos     {
   1973  1.3  christos       gdbpy_print_stack ();
   1974  1.3  christos       warning (_("internal error: Unhandled Python exception"));
   1975  1.3  christos     }
   1976  1.3  christos }
   1977  1.3  christos 
   1978  1.3  christos /* Return non-zero if Python has successfully initialized.
   1979  1.1  christos    This is the extension_languages_ops.initialized "method".  */
   1980  1.1  christos 
   1981  1.1  christos static int
   1982  1.1  christos gdbpy_initialized (const struct extension_language_defn *extlang)
   1983  1.1  christos {
   1984  1.1  christos   return gdb_python_initialized;
   1985  1.5  christos }
   1986  1.1  christos 
   1987  1.1  christos #endif /* HAVE_PYTHON */
   1988  1.1  christos 
   1989  1.1  christos 
   1990  1.1  christos 
   1992  1.1  christos #ifdef HAVE_PYTHON
   1993  1.1  christos 
   1994  1.1  christos PyMethodDef python_GdbMethods[] =
   1995  1.1  christos {
   1996  1.1  christos   { "history", gdbpy_history, METH_VARARGS,
   1997  1.1  christos     "Get a value from history" },
   1998  1.1  christos   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
   1999  1.1  christos     "execute (command [, from_tty] [, to_string]) -> [String]\n\
   2000  1.1  christos Evaluate command, a string, as a gdb CLI command.  Optionally returns\n\
   2001  1.1  christos a Python String containing the output of the command if to_string is\n\
   2002  1.1  christos set to True." },
   2003  1.1  christos   { "parameter", gdbpy_parameter, METH_VARARGS,
   2004  1.1  christos     "Return a gdb parameter's value" },
   2005  1.1  christos 
   2006  1.1  christos   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
   2007  1.1  christos     "Return a tuple of all breakpoint objects" },
   2008  1.1  christos 
   2009  1.1  christos   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
   2010  1.1  christos     "Find the default visualizer for a Value." },
   2011  1.1  christos 
   2012  1.1  christos   { "progspaces", gdbpy_progspaces, METH_NOARGS,
   2013  1.1  christos     "Return a sequence of all progspaces." },
   2014  1.1  christos 
   2015  1.1  christos   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
   2016  1.1  christos     "Return the current Objfile being loaded, or None." },
   2017  1.1  christos 
   2018  1.1  christos   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
   2019  1.7  christos     "newest_frame () -> gdb.Frame.\n\
   2020  1.7  christos Return the newest frame object." },
   2021  1.7  christos   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
   2022  1.7  christos     "selected_frame () -> gdb.Frame.\n\
   2023  1.7  christos Return the selected frame object." },
   2024  1.7  christos   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
   2025  1.7  christos     "stop_reason_string (Integer) -> String.\n\
   2026  1.7  christos Return a string explaining unwind stop reason." },
   2027  1.7  christos 
   2028  1.7  christos   { "start_recording", gdbpy_start_recording, METH_VARARGS,
   2029  1.7  christos     "start_recording ([method] [, format]) -> gdb.Record.\n\
   2030  1.7  christos Start recording with the given method.  If no method is given, will fall back\n\
   2031  1.1  christos to the system default method.  If no format is given, will fall back to the\n\
   2032  1.1  christos default format for the given method."},
   2033  1.1  christos   { "current_recording", gdbpy_current_recording, METH_NOARGS,
   2034  1.1  christos     "current_recording () -> gdb.Record.\n\
   2035  1.1  christos Return current recording object." },
   2036  1.1  christos   { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
   2037  1.1  christos     "stop_recording () -> None.\n\
   2038  1.1  christos Stop current recording." },
   2039  1.1  christos 
   2040  1.1  christos   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
   2041  1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2042  1.1  christos     "lookup_type (name [, block]) -> type\n\
   2043  1.1  christos Return a Type corresponding to the given name." },
   2044  1.1  christos   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
   2045  1.9  christos     METH_VARARGS | METH_KEYWORDS,
   2046  1.9  christos     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
   2047  1.9  christos Return a tuple with the symbol corresponding to the given name (or None) and\n\
   2048  1.9  christos a boolean indicating if name is a field of the current implied argument\n\
   2049  1.9  christos `this' (when the current language is object-oriented)." },
   2050  1.9  christos   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
   2051  1.9  christos     METH_VARARGS | METH_KEYWORDS,
   2052  1.9  christos     "lookup_global_symbol (name [, domain]) -> symbol\n\
   2053  1.3  christos Return the symbol corresponding to the given name (or None)." },
   2054  1.3  christos   { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
   2055  1.3  christos     METH_VARARGS | METH_KEYWORDS,
   2056  1.3  christos     "lookup_static_symbol (name [, domain]) -> symbol\n\
   2057  1.3  christos Return the static-linkage symbol corresponding to the given name (or None)." },
   2058  1.3  christos   { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
   2059  1.3  christos     METH_VARARGS | METH_KEYWORDS,
   2060  1.3  christos     "lookup_static_symbols (name [, domain]) -> symbol\n\
   2061  1.1  christos Return a list of all static-linkage symbols corresponding to the given name." },
   2062  1.1  christos 
   2063  1.1  christos   { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
   2064  1.1  christos     METH_VARARGS | METH_KEYWORDS,
   2065  1.1  christos     "lookup_objfile (name, [by_build_id]) -> objfile\n\
   2066  1.1  christos Look up the specified objfile.\n\
   2067  1.1  christos If by_build_id is True, the objfile is looked up by using name\n\
   2068  1.1  christos as its build id." },
   2069  1.1  christos 
   2070  1.1  christos   { "decode_line", gdbpy_decode_line, METH_VARARGS,
   2071  1.1  christos     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
   2072  1.1  christos that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
   2073  1.1  christos The first element contains any unparsed portion of the String parameter\n\
   2074  1.1  christos (or None if the string was fully parsed).  The second element contains\n\
   2075  1.1  christos a tuple that contains all the locations that match, represented as\n\
   2076  1.1  christos gdb.Symtab_and_line objects (or None)."},
   2077  1.1  christos   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
   2078  1.1  christos     "parse_and_eval (String) -> Value.\n\
   2079  1.1  christos Parse String as an expression, evaluate it, and return the result as a Value."
   2080  1.1  christos   },
   2081  1.1  christos 
   2082  1.8  christos   { "post_event", gdbpy_post_event, METH_VARARGS,
   2083  1.8  christos     "Post an event into gdb's event loop." },
   2084  1.8  christos 
   2085  1.1  christos   { "target_charset", gdbpy_target_charset, METH_NOARGS,
   2086  1.1  christos     "target_charset () -> string.\n\
   2087  1.1  christos Return the name of the current target charset." },
   2088  1.1  christos   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
   2089  1.1  christos     "target_wide_charset () -> string.\n\
   2090  1.1  christos Return the name of the current target wide charset." },
   2091  1.1  christos   { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
   2092  1.1  christos     "rbreak (Regex) -> List.\n\
   2093  1.1  christos Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
   2094  1.1  christos   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
   2095  1.1  christos     "string_to_argv (String) -> Array.\n\
   2096  1.1  christos Parse String and return an argv-like array.\n\
   2097  1.1  christos Arguments are separate by spaces and may be quoted."
   2098  1.1  christos   },
   2099  1.1  christos   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
   2100  1.1  christos     "Write a string using gdb's filtered stream." },
   2101  1.1  christos   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
   2102  1.1  christos     "Flush gdb's filtered stdout stream." },
   2103  1.6  christos   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
   2104  1.6  christos     "selected_thread () -> gdb.InferiorThread.\n\
   2105  1.6  christos Return the selected thread object." },
   2106  1.6  christos   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
   2107  1.6  christos     "selected_inferior () -> gdb.Inferior.\n\
   2108  1.6  christos Return the selected inferior object." },
   2109  1.8  christos   { "inferiors", gdbpy_inferiors, METH_NOARGS,
   2110  1.8  christos     "inferiors () -> (gdb.Inferior, ...).\n\
   2111  1.8  christos Return a tuple containing all inferiors." },
   2112  1.8  christos 
   2113  1.8  christos   { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
   2114  1.8  christos     "invalidate_cached_frames () -> None.\n\
   2115  1.8  christos Invalidate any cached frame objects in gdb.\n\
   2116  1.8  christos Intended for internal use only." },
   2117  1.9  christos 
   2118  1.9  christos   { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
   2119  1.9  christos     "convenience_variable (NAME) -> value.\n\
   2120  1.9  christos Return the value of the convenience variable $NAME,\n\
   2121  1.9  christos or None if not set." },
   2122  1.9  christos   { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
   2123  1.9  christos     "convenience_variable (NAME, VALUE) -> None.\n\
   2124  1.1  christos Set the value of the convenience variable $NAME." },
   2125  1.1  christos 
   2126  1.1  christos #ifdef TUI
   2127  1.1  christos   { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
   2128  1.5  christos     METH_VARARGS | METH_KEYWORDS,
   2129  1.1  christos     "register_window_type (NAME, CONSTRUCSTOR) -> None\n\
   2130  1.1  christos Register a TUI window constructor." },
   2131  1.1  christos #endif	/* TUI */
   2132  1.1  christos 
   2133  1.1  christos   {NULL, NULL, 0, NULL}
   2134  1.5  christos };
   2135  1.1  christos 
   2136  1.1  christos #ifdef IS_PY3K
   2137  1.1  christos struct PyModuleDef python_GdbModuleDef =
   2138  1.1  christos {
   2139  1.1  christos   PyModuleDef_HEAD_INIT,
   2140  1.1  christos   "_gdb",
   2141  1.8  christos   NULL,
   2142  1.8  christos   -1,
   2143  1.8  christos   python_GdbMethods,
   2144  1.8  christos   NULL,
   2145  1.8  christos   NULL,
   2146  1.8  christos   NULL,
   2147  1.8  christos   NULL
   2148  1.8  christos };
   2149  1.8  christos #endif
   2150  1.8  christos 
   2151  1.8  christos /* Define all the event objects.  */
   2152  1.8  christos #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
   2153  1.8  christos   PyTypeObject name##_event_object_type		    \
   2154  1.8  christos         CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
   2155  1.8  christos     = { \
   2156  1.8  christos       PyVarObject_HEAD_INIT (NULL, 0)				\
   2157  1.8  christos       "gdb." py_name,                             /* tp_name */ \
   2158  1.8  christos       sizeof (event_object),                      /* tp_basicsize */ \
   2159  1.8  christos       0,                                          /* tp_itemsize */ \
   2160  1.8  christos       evpy_dealloc,                               /* tp_dealloc */ \
   2161  1.8  christos       0,                                          /* tp_print */ \
   2162  1.8  christos       0,                                          /* tp_getattr */ \
   2163  1.8  christos       0,                                          /* tp_setattr */ \
   2164  1.8  christos       0,                                          /* tp_compare */ \
   2165  1.8  christos       0,                                          /* tp_repr */ \
   2166  1.8  christos       0,                                          /* tp_as_number */ \
   2167  1.8  christos       0,                                          /* tp_as_sequence */ \
   2168  1.8  christos       0,                                          /* tp_as_mapping */ \
   2169  1.8  christos       0,                                          /* tp_hash  */ \
   2170  1.8  christos       0,                                          /* tp_call */ \
   2171  1.8  christos       0,                                          /* tp_str */ \
   2172  1.8  christos       0,                                          /* tp_getattro */ \
   2173  1.8  christos       0,                                          /* tp_setattro */ \
   2174  1.8  christos       0,                                          /* tp_as_buffer */ \
   2175  1.8  christos       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */ \
   2176  1.8  christos       doc,                                        /* tp_doc */ \
   2177  1.8  christos       0,                                          /* tp_traverse */ \
   2178  1.8  christos       0,                                          /* tp_clear */ \
   2179  1.8  christos       0,                                          /* tp_richcompare */ \
   2180  1.8  christos       0,                                          /* tp_weaklistoffset */ \
   2181  1.8  christos       0,                                          /* tp_iter */ \
   2182  1.8  christos       0,                                          /* tp_iternext */ \
   2183  1.8  christos       0,                                          /* tp_methods */ \
   2184  1.8  christos       0,                                          /* tp_members */ \
   2185  1.8  christos       0,                                          /* tp_getset */ \
   2186  1.8  christos       &base,                                      /* tp_base */ \
   2187  1.8  christos       0,                                          /* tp_dict */ \
   2188  1.1  christos       0,                                          /* tp_descr_get */ \
   2189                      0,                                          /* tp_descr_set */ \
   2190                      0,                                          /* tp_dictoffset */ \
   2191                      0,                                          /* tp_init */ \
   2192                      0                                           /* tp_alloc */ \
   2193                    };
   2194                #include "py-event-types.def"
   2195                #undef GDB_PY_DEFINE_EVENT_TYPE
   2196                
   2197                #endif /* HAVE_PYTHON */
   2198