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