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