1 /* General python/gdb code
3 Copyright (C) 2008-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
26 #include "progspace.h"
30 #include "gdbsupport/event-loop.h"
31 #include "readline/tilde.h"
33 #include "extension-priv.h"
34 #include "cli/cli-utils.h"
37 #include "run-on-main-thread.h"
38 #include "gdbsupport/selftest.h"
39 #include "observable.h"
41 /* Declared constants and enum for python stack printing. */
42 static const char python_excp_none[] = "none";
43 static const char python_excp_full[] = "full";
44 static const char python_excp_message[] = "message";
46 /* "set python print-stack" choices. */
47 static const char *const python_excp_enums[] =
55 /* The exception printing variable. 'full' if we want to print the
56 error message and stack, 'none' if we want to print nothing, and
57 'message' if we only want to print the error message. 'message' is
59 static const char *gdbpy_should_print_stack = python_excp_message;
64 #include "cli/cli-decode.h"
67 #include "python-internal.h"
70 #include "gdbsupport/version.h"
72 #include "gdbthread.h"
74 #include "event-top.h"
77 /* True if Python has been successfully initialized, false
80 int gdb_python_initialized;
82 extern PyMethodDef python_GdbMethods[];
85 PyObject *gdb_python_module;
87 /* Some string constants we may wish to use. */
88 PyObject *gdbpy_to_string_cst;
89 PyObject *gdbpy_children_cst;
90 PyObject *gdbpy_display_hint_cst;
91 PyObject *gdbpy_doc_cst;
92 PyObject *gdbpy_enabled_cst;
93 PyObject *gdbpy_value_cst;
95 /* The GdbError exception. */
96 PyObject *gdbpy_gdberror_exc;
98 /* The `gdb.error' base class. */
99 PyObject *gdbpy_gdb_error;
101 /* The `gdb.MemoryError' exception. */
102 PyObject *gdbpy_gdb_memory_error;
104 static script_sourcer_func gdbpy_source_script;
105 static objfile_script_sourcer_func gdbpy_source_objfile_script;
106 static objfile_script_executor_func gdbpy_execute_objfile_script;
107 static void gdbpy_initialize (const struct extension_language_defn *);
108 static int gdbpy_initialized (const struct extension_language_defn *);
109 static void gdbpy_eval_from_control_command
110 (const struct extension_language_defn *, struct command_line *cmd);
111 static void gdbpy_start_type_printers (const struct extension_language_defn *,
112 struct ext_lang_type_printers *);
113 static enum ext_lang_rc gdbpy_apply_type_printers
114 (const struct extension_language_defn *,
115 const struct ext_lang_type_printers *, struct type *, char **);
116 static void gdbpy_free_type_printers (const struct extension_language_defn *,
117 struct ext_lang_type_printers *);
118 static void gdbpy_set_quit_flag (const struct extension_language_defn *);
119 static int gdbpy_check_quit_flag (const struct extension_language_defn *);
120 static enum ext_lang_rc gdbpy_before_prompt_hook
121 (const struct extension_language_defn *, const char *current_gdb_prompt);
122 static gdb::optional<std::string> gdbpy_colorize
123 (const std::string &filename, const std::string &contents);
124 static gdb::optional<std::string> gdbpy_colorize_disasm
125 (const std::string &content, gdbarch *gdbarch);
127 /* The interface between gdb proper and loading of python scripts. */
129 static const struct extension_language_script_ops python_extension_script_ops =
132 gdbpy_source_objfile_script,
133 gdbpy_execute_objfile_script,
134 gdbpy_auto_load_enabled
137 /* The interface between gdb proper and python extensions. */
139 static const struct extension_language_ops python_extension_ops =
144 gdbpy_eval_from_control_command,
146 gdbpy_start_type_printers,
147 gdbpy_apply_type_printers,
148 gdbpy_free_type_printers,
150 gdbpy_apply_val_pretty_printer,
152 gdbpy_apply_frame_filter,
154 gdbpy_preserve_values,
156 gdbpy_breakpoint_has_cond,
157 gdbpy_breakpoint_cond_says_stop,
160 gdbpy_check_quit_flag,
162 gdbpy_before_prompt_hook,
164 gdbpy_get_matching_xmethod_workers,
168 gdbpy_colorize_disasm,
171 #endif /* HAVE_PYTHON */
173 /* The main struct describing GDB's interface to the Python
174 extension language. */
175 const struct extension_language_defn extension_language_python =
187 &python_extension_script_ops,
188 &python_extension_ops
197 /* Architecture and language to be used in callbacks from
198 the Python interpreter. */
199 struct gdbarch *gdbpy_enter::python_gdbarch;
201 gdbpy_enter::gdbpy_enter (struct gdbarch *gdbarch,
202 const struct language_defn *language)
203 : m_gdbarch (python_gdbarch),
204 m_language (language == nullptr ? nullptr : current_language)
206 /* We should not ever enter Python unless initialized. */
207 if (!gdb_python_initialized)
208 error (_("Python not initialized"));
210 m_previous_active = set_active_ext_lang (&extension_language_python);
212 m_state = PyGILState_Ensure ();
214 python_gdbarch = gdbarch;
215 if (language != nullptr)
216 set_language (language->la_language);
218 /* Save it and ensure ! PyErr_Occurred () afterwards. */
222 gdbpy_enter::~gdbpy_enter ()
224 /* Leftover Python error is forbidden by Python Exception Handling. */
225 if (PyErr_Occurred ())
227 /* This order is similar to the one calling error afterwards. */
228 gdbpy_print_stack ();
229 warning (_("internal error: Unhandled Python exception"));
234 python_gdbarch = m_gdbarch;
235 if (m_language != nullptr)
236 set_language (m_language->la_language);
238 restore_active_ext_lang (m_previous_active);
239 PyGILState_Release (m_state);
243 gdbpy_enter::get_gdbarch ()
245 if (python_gdbarch != nullptr)
246 return python_gdbarch;
247 return get_current_arch ();
251 gdbpy_enter::finalize ()
253 python_gdbarch = target_gdbarch ();
256 /* A helper class to save and restore the GIL, but without touching
257 the other globals that are handled by gdbpy_enter. */
264 : m_state (PyGILState_Ensure ())
270 PyGILState_Release (m_state);
273 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
277 PyGILState_STATE m_state;
280 /* Set the quit flag. */
283 gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
285 PyErr_SetInterrupt ();
288 /* Return true if the quit flag has been set, false otherwise. */
291 gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
293 if (!gdb_python_initialized)
297 return PyOS_InterruptOccurred ();
300 /* Evaluate a Python command like PyRun_SimpleString, but uses
301 Py_single_input which prints the result of expressions, and does
302 not automatically print the stack on errors. */
305 eval_python_command (const char *command)
309 m = PyImport_AddModule ("__main__");
313 d = PyModule_GetDict (m);
316 gdbpy_ref<> v (PyRun_StringFlags (command, Py_single_input, d, d, NULL));
323 /* Implementation of the gdb "python-interactive" command. */
326 python_interactive_command (const char *arg, int from_tty)
328 struct ui *ui = current_ui;
331 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
333 arg = skip_spaces (arg);
335 gdbpy_enter enter_py;
339 std::string script = std::string (arg) + "\n";
340 err = eval_python_command (script.c_str ());
344 err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
350 gdbpy_print_stack ();
351 error (_("Error while executing Python code."));
355 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
358 On Windows hosts few users would build Python themselves (this is no
359 trivial task on this platform), and thus use binaries built by
360 someone else instead. There may happen situation where the Python
361 library and GDB are using two different versions of the C runtime
362 library. Python, being built with VC, would use one version of the
363 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
364 A FILE * from one runtime does not necessarily operate correctly in
367 To work around this potential issue, we run code in Python to load
371 python_run_simple_file (FILE *file, const char *filename)
375 PyRun_SimpleFile (file, filename);
379 /* Because we have a string for a filename, and are using Python to
380 open the file, we need to expand any tilde in the path first. */
381 gdb::unique_xmalloc_ptr<char> full_path (tilde_expand (filename));
383 if (gdb_python_module == nullptr
384 || ! PyObject_HasAttrString (gdb_python_module, "_execute_file"))
385 error (_("Installation error: gdb._execute_file function is missing"));
387 gdbpy_ref<> return_value
388 (PyObject_CallMethod (gdb_python_module, "_execute_file", "s",
390 if (return_value == nullptr)
392 /* Use PyErr_PrintEx instead of gdbpy_print_stack to better match the
393 behavior of the non-Windows codepath. */
400 /* Given a command_line, return a command string suitable for passing
401 to Python. Lines in the string are separated by newlines. */
404 compute_python_string (struct command_line *l)
406 struct command_line *iter;
409 for (iter = l; iter; iter = iter->next)
411 script += iter->line;
417 /* Take a command line structure representing a 'python' command, and
418 evaluate its body using the Python interpreter. */
421 gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
422 struct command_line *cmd)
426 if (cmd->body_list_1 != nullptr)
427 error (_("Invalid \"python\" block structure."));
429 gdbpy_enter enter_py;
431 std::string script = compute_python_string (cmd->body_list_0.get ());
432 ret = PyRun_SimpleString (script.c_str ());
434 error (_("Error while executing Python code."));
437 /* Implementation of the gdb "python" command. */
440 python_command (const char *arg, int from_tty)
442 gdbpy_enter enter_py;
444 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
446 arg = skip_spaces (arg);
449 if (PyRun_SimpleString (arg))
450 error (_("Error while executing Python code."));
454 counted_command_line l = get_command_line (python_control, "");
456 execute_control_command_untraced (l.get ());
462 /* Transform a gdb parameters's value into a Python value. May return
463 NULL (and set a Python exception) on error. Helper function for
466 gdbpy_parameter_value (const setting &var)
471 case var_string_noescape:
472 case var_optional_filename:
477 if (var.type () == var_enum)
478 str = var.get<const char *> ();
480 str = var.get<std::string> ().c_str ();
482 return host_string_to_python_string (str).release ();
487 if (var.get<bool> ())
493 case var_auto_boolean:
495 enum auto_boolean ab = var.get<enum auto_boolean> ();
497 if (ab == AUTO_BOOLEAN_TRUE)
499 else if (ab == AUTO_BOOLEAN_FALSE)
506 if (var.get<int> () == INT_MAX)
510 case var_zuinteger_unlimited:
511 return gdb_py_object_from_longest (var.get<int> ()).release ();
515 unsigned int val = var.get<unsigned int> ();
519 return gdb_py_object_from_ulongest (val).release ();
524 unsigned int val = var.get<unsigned int> ();
525 return gdb_py_object_from_ulongest (val).release ();
529 return PyErr_Format (PyExc_RuntimeError,
530 _("Programmer error: unhandled type."));
533 /* A Python function which returns a gdb parameter's value as a Python
537 gdbpy_parameter (PyObject *self, PyObject *args)
539 struct cmd_list_element *alias, *prefix, *cmd;
543 if (! PyArg_ParseTuple (args, "s", &arg))
546 std::string newarg = std::string ("show ") + arg;
550 found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
552 catch (const gdb_exception &ex)
554 GDB_PY_HANDLE_EXCEPTION (ex);
558 return PyErr_Format (PyExc_RuntimeError,
559 _("Could not find parameter `%s'."), arg);
561 if (!cmd->var.has_value ())
562 return PyErr_Format (PyExc_RuntimeError,
563 _("`%s' is not a parameter."), arg);
565 return gdbpy_parameter_value (*cmd->var);
568 /* Wrapper for target_charset. */
571 gdbpy_target_charset (PyObject *self, PyObject *args)
573 const char *cset = target_charset (gdbpy_enter::get_gdbarch ());
575 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
578 /* Wrapper for target_wide_charset. */
581 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
583 const char *cset = target_wide_charset (gdbpy_enter::get_gdbarch ());
585 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
588 /* Implement gdb.host_charset(). */
591 gdbpy_host_charset (PyObject *self, PyObject *args)
593 const char *cset = host_charset ();
595 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
598 /* A Python function which evaluates a string using the gdb CLI. */
601 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
604 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
605 int from_tty, to_string;
606 static const char *keywords[] = { "command", "from_tty", "to_string", NULL };
608 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
609 &PyBool_Type, &from_tty_obj,
610 &PyBool_Type, &to_string_obj))
616 int cmp = PyObject_IsTrue (from_tty_obj);
625 int cmp = PyObject_IsTrue (to_string_obj);
631 std::string to_string_res;
633 scoped_restore preventer = prevent_dont_repeat ();
637 gdbpy_allow_threads allow_threads;
639 struct interp *interp;
641 std::string arg_copy = arg;
643 char *save_ptr = nullptr;
647 const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
653 counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
656 scoped_restore save_async = make_scoped_restore (¤t_ui->async,
659 scoped_restore save_uiout = make_scoped_restore (¤t_uiout);
661 /* Use the console interpreter uiout to have the same print format
662 for console or MI. */
663 interp = interp_lookup (current_ui, "console");
664 current_uiout = interp->interp_ui_out ();
667 to_string_res = execute_control_commands_to_string (lines.get (),
670 execute_control_commands (lines.get (), from_tty);
673 /* Do any commands attached to breakpoint we stopped at. */
674 bpstat_do_actions ();
676 catch (const gdb_exception &except)
678 /* If an exception occurred then we won't hit normal_stop (), or have
679 an exception reach the top level of the event loop, which are the
680 two usual places in which stdin would be re-enabled. So, before we
681 convert the exception and continue back in Python, we should
682 re-enable stdin here. */
683 async_enable_stdin ();
684 GDB_PY_HANDLE_EXCEPTION (except);
688 return PyUnicode_FromString (to_string_res.c_str ());
692 /* Implementation of Python rbreak command. Take a REGEX and
693 optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
694 Python list that contains newly set breakpoints that match that
695 criteria. REGEX refers to a GDB format standard regex pattern of
696 symbols names to search; MINSYMS is an optional boolean (default
697 False) that indicates if the function should search GDB's minimal
698 symbols; THROTTLE is an optional integer (default unlimited) that
699 indicates the maximum amount of breakpoints allowable before the
700 function exits (note, if the throttle bound is passed, no
701 breakpoints will be set and a runtime error returned); SYMTABS is
702 an optional Python iterable that contains a set of gdb.Symtabs to
703 constrain the search within. */
706 gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
709 std::vector<symbol_search> symbols;
710 unsigned long count = 0;
711 PyObject *symtab_list = NULL;
712 PyObject *minsyms_p_obj = NULL;
714 unsigned int throttle = 0;
715 static const char *keywords[] = {"regex","minsyms", "throttle",
718 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
719 ®ex, &PyBool_Type,
720 &minsyms_p_obj, &throttle,
724 /* Parse minsyms keyword. */
725 if (minsyms_p_obj != NULL)
727 int cmp = PyObject_IsTrue (minsyms_p_obj);
733 global_symbol_searcher spec (FUNCTIONS_DOMAIN, regex);
735 for (const char *elem : spec.filenames)
736 xfree ((void *) elem);
739 /* The "symtabs" keyword is any Python iterable object that returns
740 a gdb.Symtab on each iteration. If specified, iterate through
741 the provided gdb.Symtabs and extract their full path. As
742 python_string_to_target_string returns a
743 gdb::unique_xmalloc_ptr<char> and a vector containing these types
744 cannot be coerced to a const char **p[] via the vector.data call,
745 release the value from the unique_xmalloc_ptr and place it in a
746 simple type symtab_list_type (which holds the vector and a
747 destructor that frees the contents of the allocated strings. */
748 if (symtab_list != NULL)
750 gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
757 gdbpy_ref<> next (PyIter_Next (iter.get ()));
761 if (PyErr_Occurred ())
766 gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
769 if (obj_name == NULL)
772 /* Is the object file still valid? */
773 if (obj_name == Py_None)
776 gdb::unique_xmalloc_ptr<char> filename =
777 python_string_to_target_string (obj_name.get ());
779 if (filename == NULL)
782 /* Make sure there is a definite place to store the value of
783 filename before it is released. */
784 spec.filenames.push_back (nullptr);
785 spec.filenames.back () = filename.release ();
789 /* The search spec. */
790 symbols = spec.search ();
792 /* Count the number of symbols (both symbols and optionally minimal
793 symbols) so we can correctly check the throttle limit. */
794 for (const symbol_search &p : symbols)
796 /* Minimal symbols included? */
799 if (p.msymbol.minsym != NULL)
803 if (p.symbol != NULL)
807 /* Check throttle bounds and exit if in excess. */
808 if (throttle != 0 && count > throttle)
810 PyErr_SetString (PyExc_RuntimeError,
811 _("Number of breakpoints exceeds throttled maximum."));
815 gdbpy_ref<> return_list (PyList_New (0));
817 if (return_list == NULL)
820 /* Construct full path names for symbols and call the Python
821 breakpoint constructor on the resulting names. Be tolerant of
822 individual breakpoint failures. */
823 for (const symbol_search &p : symbols)
825 std::string symbol_name;
827 /* Skipping minimal symbols? */
829 if (p.msymbol.minsym != NULL)
832 if (p.msymbol.minsym == NULL)
834 struct symtab *symtab = symbol_symtab (p.symbol);
835 const char *fullname = symtab_to_fullname (symtab);
837 symbol_name = fullname;
839 symbol_name += p.symbol->linkage_name ();
842 symbol_name = p.msymbol.minsym->linkage_name ();
844 gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
845 gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
846 &breakpoint_object_type,
849 /* Tolerate individual breakpoint failures. */
851 gdbpy_print_stack ();
854 if (PyList_Append (return_list.get (), obj.get ()) == -1)
858 return return_list.release ();
861 /* A Python function which is a wrapper for decode_line_1. */
864 gdbpy_decode_line (PyObject *self, PyObject *args)
866 const char *arg = NULL;
868 gdbpy_ref<> unparsed;
869 event_location_up location;
871 if (! PyArg_ParseTuple (args, "|s", &arg))
874 /* Treat a string consisting of just whitespace the same as
878 arg = skip_spaces (arg);
884 location = string_to_event_location_basic (&arg, current_language,
885 symbol_name_match_type::WILD);
887 std::vector<symtab_and_line> decoded_sals;
888 symtab_and_line def_sal;
889 gdb::array_view<symtab_and_line> sals;
892 if (location != NULL)
894 decoded_sals = decode_line_1 (location.get (), 0, NULL, NULL, 0);
899 set_default_source_symtab_and_line ();
900 def_sal = get_current_source_symtab_and_line ();
904 catch (const gdb_exception &ex)
906 /* We know this will always throw. */
907 gdbpy_convert_exception (ex);
913 result.reset (PyTuple_New (sals.size ()));
916 for (size_t i = 0; i < sals.size (); ++i)
918 PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
922 PyTuple_SetItem (result.get (), i, obj);
926 result = gdbpy_ref<>::new_reference (Py_None);
928 gdbpy_ref<> return_result (PyTuple_New (2));
929 if (return_result == NULL)
932 if (arg != NULL && strlen (arg) > 0)
934 unparsed.reset (PyUnicode_FromString (arg));
935 if (unparsed == NULL)
939 unparsed = gdbpy_ref<>::new_reference (Py_None);
941 PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
942 PyTuple_SetItem (return_result.get (), 1, result.release ());
944 return return_result.release ();
947 /* Parse a string and evaluate it as an expression. */
949 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
951 const char *expr_str;
952 struct value *result = NULL;
954 if (!PyArg_ParseTuple (args, "s", &expr_str))
959 gdbpy_allow_threads allow_threads;
960 result = parse_and_eval (expr_str);
962 catch (const gdb_exception &except)
964 GDB_PY_HANDLE_EXCEPTION (except);
967 return value_to_value_object (result);
970 /* Implementation of gdb.invalidate_cached_frames. */
973 gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
975 reinit_frame_cache ();
979 /* Read a file as Python code.
980 This is the extension_language_script_ops.script_sourcer "method".
981 FILE is the file to load. FILENAME is name of the file FILE.
982 This does not throw any errors. If an exception occurs python will print
983 the traceback and clear the error indicator. */
986 gdbpy_source_script (const struct extension_language_defn *extlang,
987 FILE *file, const char *filename)
989 gdbpy_enter enter_py;
990 python_run_simple_file (file, filename);
995 /* Posting and handling events. */
997 /* A single event. */
1000 gdbpy_event (gdbpy_ref<> &&func)
1001 : m_func (func.release ())
1005 gdbpy_event (gdbpy_event &&other) noexcept
1006 : m_func (other.m_func)
1008 other.m_func = nullptr;
1011 gdbpy_event (const gdbpy_event &other)
1012 : m_func (other.m_func)
1015 Py_XINCREF (m_func);
1021 Py_XDECREF (m_func);
1024 gdbpy_event &operator= (const gdbpy_event &other) = delete;
1028 gdbpy_enter enter_py;
1030 gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
1031 if (call_result == NULL)
1032 gdbpy_print_stack ();
1037 /* The Python event. This is just a callable object. Note that
1038 this is not a gdbpy_ref<>, because we have to take particular
1039 care to only destroy the reference when holding the GIL. */
1043 /* Submit an event to the gdb thread. */
1045 gdbpy_post_event (PyObject *self, PyObject *args)
1049 if (!PyArg_ParseTuple (args, "O", &func))
1052 if (!PyCallable_Check (func))
1054 PyErr_SetString (PyExc_RuntimeError,
1055 _("Posted event is not callable"));
1059 gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
1060 gdbpy_event event (std::move (func_ref));
1061 run_on_main_thread (event);
1068 /* This is the extension_language_ops.before_prompt "method". */
1070 static enum ext_lang_rc
1071 gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
1072 const char *current_gdb_prompt)
1074 if (!gdb_python_initialized)
1075 return EXT_LANG_RC_NOP;
1077 gdbpy_enter enter_py;
1079 if (!evregpy_no_listeners_p (gdb_py_events.before_prompt)
1080 && evpy_emit_event (NULL, gdb_py_events.before_prompt) < 0)
1081 return EXT_LANG_RC_ERROR;
1083 if (gdb_python_module
1084 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
1086 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
1090 gdbpy_print_stack ();
1091 return EXT_LANG_RC_ERROR;
1094 if (PyCallable_Check (hook.get ()))
1096 gdbpy_ref<> current_prompt (PyUnicode_FromString (current_gdb_prompt));
1097 if (current_prompt == NULL)
1099 gdbpy_print_stack ();
1100 return EXT_LANG_RC_ERROR;
1104 (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
1108 gdbpy_print_stack ();
1109 return EXT_LANG_RC_ERROR;
1112 /* Return type should be None, or a String. If it is None,
1113 fall through, we will not set a prompt. If it is a
1114 string, set PROMPT. Anything else, set an exception. */
1115 if (result != Py_None && !PyUnicode_Check (result.get ()))
1117 PyErr_Format (PyExc_RuntimeError,
1118 _("Return from prompt_hook must " \
1119 "be either a Python string, or None"));
1120 gdbpy_print_stack ();
1121 return EXT_LANG_RC_ERROR;
1124 if (result != Py_None)
1126 gdb::unique_xmalloc_ptr<char>
1127 prompt (python_string_to_host_string (result.get ()));
1131 gdbpy_print_stack ();
1132 return EXT_LANG_RC_ERROR;
1135 set_prompt (prompt.get ());
1136 return EXT_LANG_RC_OK;
1141 return EXT_LANG_RC_NOP;
1144 /* This is the extension_language_ops.colorize "method". */
1146 static gdb::optional<std::string>
1147 gdbpy_colorize (const std::string &filename, const std::string &contents)
1149 if (!gdb_python_initialized)
1152 gdbpy_enter enter_py;
1154 gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
1155 if (module == nullptr)
1157 gdbpy_print_stack ();
1161 if (!PyObject_HasAttrString (module.get (), "colorize"))
1164 gdbpy_ref<> hook (PyObject_GetAttrString (module.get (), "colorize"));
1165 if (hook == nullptr)
1167 gdbpy_print_stack ();
1171 if (!PyCallable_Check (hook.get ()))
1174 gdbpy_ref<> fname_arg (PyUnicode_FromString (filename.c_str ()));
1175 if (fname_arg == nullptr)
1177 gdbpy_print_stack ();
1181 /* The pygments library, which is what we currently use for applying
1182 styling, is happy to take input as a bytes object, and to figure out
1183 the encoding for itself. This removes the need for us to figure out
1184 (guess?) at how the content is encoded, which is probably a good
1186 gdbpy_ref<> contents_arg (PyBytes_FromStringAndSize (contents.c_str (),
1188 if (contents_arg == nullptr)
1190 gdbpy_print_stack ();
1194 /* Calling gdb.colorize passing in the filename (a string), and the file
1195 contents (a bytes object). This function should return either a bytes
1196 object, the same contents with styling applied, or None to indicate
1197 that no styling should be performed. */
1198 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1200 contents_arg.get (),
1202 if (result == nullptr)
1204 gdbpy_print_stack ();
1208 if (result == Py_None)
1210 else if (!PyBytes_Check (result.get ()))
1212 PyErr_SetString (PyExc_TypeError,
1213 _("Return value from gdb.colorize should be a bytes object or None."));
1214 gdbpy_print_stack ();
1218 return std::string (PyBytes_AsString (result.get ()));
1221 /* This is the extension_language_ops.colorize_disasm "method". */
1223 static gdb::optional<std::string>
1224 gdbpy_colorize_disasm (const std::string &content, gdbarch *gdbarch)
1226 if (!gdb_python_initialized)
1229 gdbpy_enter enter_py;
1231 gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
1232 if (module == nullptr)
1234 gdbpy_print_stack ();
1238 if (!PyObject_HasAttrString (module.get (), "colorize_disasm"))
1241 gdbpy_ref<> hook (PyObject_GetAttrString (module.get (),
1242 "colorize_disasm"));
1243 if (hook == nullptr)
1245 gdbpy_print_stack ();
1249 if (!PyCallable_Check (hook.get ()))
1252 gdbpy_ref<> content_arg (PyBytes_FromString (content.c_str ()));
1253 if (content_arg == nullptr)
1255 gdbpy_print_stack ();
1259 gdbpy_ref<> gdbarch_arg (gdbarch_to_arch_object (gdbarch));
1260 if (gdbarch_arg == nullptr)
1262 gdbpy_print_stack ();
1266 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1270 if (result == nullptr)
1272 gdbpy_print_stack ();
1276 if (result == Py_None)
1279 if (!PyBytes_Check (result.get ()))
1281 PyErr_SetString (PyExc_TypeError,
1282 _("Return value from gdb.colorize_disasm should be a bytes object or None."));
1283 gdbpy_print_stack ();
1287 return std::string (PyBytes_AsString (result.get ()));
1292 /* Implement gdb.format_address(ADDR,P_SPACE,ARCH). Provide access to
1293 GDB's print_address function from Python. The returned address will
1294 have the format '0x..... <symbol+offset>'. */
1297 gdbpy_format_address (PyObject *self, PyObject *args, PyObject *kw)
1299 static const char *keywords[] =
1301 "address", "progspace", "architecture", nullptr
1303 PyObject *addr_obj = nullptr, *pspace_obj = nullptr, *arch_obj = nullptr;
1305 struct gdbarch *gdbarch = nullptr;
1306 struct program_space *pspace = nullptr;
1308 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O|OO", keywords,
1309 &addr_obj, &pspace_obj, &arch_obj))
1312 if (get_addr_from_python (addr_obj, &addr) < 0)
1315 /* If the user passed None for progspace or architecture, then we
1316 consider this to mean "the default". Here we replace references to
1317 None with nullptr, this means that in the following code we only have
1318 to handle the nullptr case. These are only borrowed references, so
1319 no decref is required here. */
1320 if (pspace_obj == Py_None)
1321 pspace_obj = nullptr;
1322 if (arch_obj == Py_None)
1325 if (pspace_obj == nullptr && arch_obj == nullptr)
1327 /* Grab both of these from the current inferior, and its associated
1328 default architecture. */
1329 pspace = current_inferior ()->pspace;
1330 gdbarch = current_inferior ()->gdbarch;
1332 else if (arch_obj == nullptr || pspace_obj == nullptr)
1334 /* If the user has only given one of program space or architecture,
1335 then don't use the default for the other. Sure we could use the
1336 default, but it feels like there's too much scope of mistakes in
1337 this case, so better to require the user to provide both
1339 PyErr_SetString (PyExc_ValueError,
1340 _("The architecture and progspace arguments must both be supplied"));
1345 /* The user provided an address, program space, and architecture.
1346 Just check that these objects are valid. */
1347 if (!gdbpy_is_progspace (pspace_obj))
1349 PyErr_SetString (PyExc_TypeError,
1350 _("The progspace argument is not a gdb.Progspace object"));
1354 pspace = progspace_object_to_program_space (pspace_obj);
1355 if (pspace == nullptr)
1357 PyErr_SetString (PyExc_ValueError,
1358 _("The progspace argument is not valid"));
1362 if (!gdbpy_is_architecture (arch_obj))
1364 PyErr_SetString (PyExc_TypeError,
1365 _("The architecture argument is not a gdb.Architecture object"));
1369 /* Architectures are never deleted once created, so gdbarch should
1370 never come back as nullptr. */
1371 gdbarch = arch_object_to_gdbarch (arch_obj);
1372 gdb_assert (gdbarch != nullptr);
1375 /* By this point we should know the program space and architecture we are
1377 gdb_assert (pspace != nullptr);
1378 gdb_assert (gdbarch != nullptr);
1380 /* Unfortunately print_address relies on the current program space for
1381 its symbol lookup. Temporarily switch now. */
1382 scoped_restore_current_program_space restore_progspace;
1383 set_current_program_space (pspace);
1385 /* Format the address, and return it as a string. */
1387 print_address (gdbarch, addr, &buf);
1388 return PyUnicode_FromString (buf.c_str ());
1395 /* A python function to write a single string using gdb's filtered
1396 output stream . The optional keyword STREAM can be used to write
1397 to a particular stream. The default stream is to gdb_stdout. */
1400 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
1403 static const char *keywords[] = { "text", "stream", NULL };
1404 int stream_type = 0;
1406 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
1412 switch (stream_type)
1416 fprintf_filtered (gdb_stderr, "%s", arg);
1421 fprintf_filtered (gdb_stdlog, "%s", arg);
1425 fprintf_filtered (gdb_stdout, "%s", arg);
1428 catch (const gdb_exception &except)
1430 GDB_PY_HANDLE_EXCEPTION (except);
1436 /* A python function to flush a gdb stream. The optional keyword
1437 STREAM can be used to flush a particular stream. The default stream
1441 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
1443 static const char *keywords[] = { "stream", NULL };
1444 int stream_type = 0;
1446 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1450 switch (stream_type)
1454 gdb_flush (gdb_stderr);
1459 gdb_flush (gdb_stdlog);
1463 gdb_flush (gdb_stdout);
1469 /* Return non-zero if print-stack is not "none". */
1472 gdbpy_print_python_errors_p (void)
1474 return gdbpy_should_print_stack != python_excp_none;
1477 /* Print a python exception trace, print just a message, or print
1478 nothing and clear the python exception, depending on
1479 gdbpy_should_print_stack. Only call this if a python exception is
1482 gdbpy_print_stack (void)
1485 /* Print "none", just clear exception. */
1486 if (gdbpy_should_print_stack == python_excp_none)
1490 /* Print "full" message and backtrace. */
1491 else if (gdbpy_should_print_stack == python_excp_full)
1494 /* PyErr_Print doesn't necessarily end output with a newline.
1495 This works because Python's stdout/stderr is fed through
1501 catch (const gdb_exception &except)
1505 /* Print "message", just error print message. */
1508 gdbpy_err_fetch fetched_error;
1510 gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
1511 gdb::unique_xmalloc_ptr<char> type;
1512 /* Don't compute TYPE if MSG already indicates that there is an
1515 type = fetched_error.type_to_string ();
1519 if (msg == NULL || type == NULL)
1521 /* An error occurred computing the string representation of the
1523 fprintf_filtered (gdb_stderr,
1524 _("Error occurred computing Python error" \
1529 fprintf_filtered (gdb_stderr, "Python Exception %s: %s\n",
1530 type.get (), msg.get ());
1532 catch (const gdb_exception &except)
1538 /* Like gdbpy_print_stack, but if the exception is a
1539 KeyboardException, throw a gdb "quit" instead. */
1542 gdbpy_print_stack_or_quit ()
1544 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
1547 throw_quit ("Quit");
1549 gdbpy_print_stack ();
1554 /* Return a sequence holding all the Progspaces. */
1557 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1559 gdbpy_ref<> list (PyList_New (0));
1563 for (struct program_space *ps : program_spaces)
1565 gdbpy_ref<> item = pspace_to_pspace_object (ps);
1567 if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
1571 return list.release ();
1576 /* The "current" objfile. This is set when gdb detects that a new
1577 objfile has been loaded. It is only set for the duration of a call to
1578 gdbpy_source_objfile_script and gdbpy_execute_objfile_script; it is NULL
1580 static struct objfile *gdbpy_current_objfile;
1582 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1583 as Python code. This does not throw any errors. If an exception
1584 occurs python will print the traceback and clear the error indicator.
1585 This is the extension_language_script_ops.objfile_script_sourcer
1589 gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
1590 struct objfile *objfile, FILE *file,
1591 const char *filename)
1593 if (!gdb_python_initialized)
1596 gdbpy_enter enter_py (objfile->arch ());
1597 scoped_restore restire_current_objfile
1598 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1600 python_run_simple_file (file, filename);
1603 /* Set the current objfile to OBJFILE and then execute SCRIPT
1604 as Python code. This does not throw any errors. If an exception
1605 occurs python will print the traceback and clear the error indicator.
1606 This is the extension_language_script_ops.objfile_script_executor
1610 gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
1611 struct objfile *objfile, const char *name,
1614 if (!gdb_python_initialized)
1617 gdbpy_enter enter_py (objfile->arch ());
1618 scoped_restore restire_current_objfile
1619 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1621 PyRun_SimpleString (script);
1624 /* Return the current Objfile, or None if there isn't one. */
1627 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1629 if (! gdbpy_current_objfile)
1632 return objfile_to_objfile_object (gdbpy_current_objfile).release ();
1635 /* Compute the list of active python type printers and store them in
1636 EXT_PRINTERS->py_type_printers. The product of this function is used by
1637 gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
1638 This is the extension_language_ops.start_type_printers "method". */
1641 gdbpy_start_type_printers (const struct extension_language_defn *extlang,
1642 struct ext_lang_type_printers *ext_printers)
1644 PyObject *printers_obj = NULL;
1646 if (!gdb_python_initialized)
1649 gdbpy_enter enter_py;
1651 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1652 if (type_module == NULL)
1654 gdbpy_print_stack ();
1658 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1659 "get_type_recognizers"));
1662 gdbpy_print_stack ();
1666 printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
1667 if (printers_obj == NULL)
1668 gdbpy_print_stack ();
1670 ext_printers->py_type_printers = printers_obj;
1673 /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
1674 a newly allocated string holding the type's replacement name, and return
1675 EXT_LANG_RC_OK. The caller is responsible for freeing the string.
1676 If there's a Python error return EXT_LANG_RC_ERROR.
1677 Otherwise, return EXT_LANG_RC_NOP.
1678 This is the extension_language_ops.apply_type_printers "method". */
1680 static enum ext_lang_rc
1681 gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
1682 const struct ext_lang_type_printers *ext_printers,
1683 struct type *type, char **prettied_type)
1685 PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
1686 gdb::unique_xmalloc_ptr<char> result;
1688 if (printers_obj == NULL)
1689 return EXT_LANG_RC_NOP;
1691 if (!gdb_python_initialized)
1692 return EXT_LANG_RC_NOP;
1694 gdbpy_enter enter_py;
1696 gdbpy_ref<> type_obj (type_to_type_object (type));
1697 if (type_obj == NULL)
1699 gdbpy_print_stack ();
1700 return EXT_LANG_RC_ERROR;
1703 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1704 if (type_module == NULL)
1706 gdbpy_print_stack ();
1707 return EXT_LANG_RC_ERROR;
1710 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1711 "apply_type_recognizers"));
1714 gdbpy_print_stack ();
1715 return EXT_LANG_RC_ERROR;
1718 gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
1722 if (result_obj == NULL)
1724 gdbpy_print_stack ();
1725 return EXT_LANG_RC_ERROR;
1728 if (result_obj == Py_None)
1729 return EXT_LANG_RC_NOP;
1731 result = python_string_to_host_string (result_obj.get ());
1734 gdbpy_print_stack ();
1735 return EXT_LANG_RC_ERROR;
1738 *prettied_type = result.release ();
1739 return EXT_LANG_RC_OK;
1742 /* Free the result of start_type_printers.
1743 This is the extension_language_ops.free_type_printers "method". */
1746 gdbpy_free_type_printers (const struct extension_language_defn *extlang,
1747 struct ext_lang_type_printers *ext_printers)
1749 PyObject *printers = (PyObject *) ext_printers->py_type_printers;
1751 if (printers == NULL)
1754 if (!gdb_python_initialized)
1757 gdbpy_enter enter_py;
1758 Py_DECREF (printers);
1761 #else /* HAVE_PYTHON */
1763 /* Dummy implementation of the gdb "python-interactive" and "python"
1767 python_interactive_command (const char *arg, int from_tty)
1769 arg = skip_spaces (arg);
1771 error (_("Python scripting is not supported in this copy of GDB."));
1774 counted_command_line l = get_command_line (python_control, "");
1776 execute_control_command_untraced (l.get ());
1781 python_command (const char *arg, int from_tty)
1783 python_interactive_command (arg, from_tty);
1786 #endif /* HAVE_PYTHON */
1788 /* When this is turned on before Python is initialised then Python will
1789 ignore any environment variables related to Python. This is equivalent
1790 to passing `-E' to the python program. */
1791 static bool python_ignore_environment = false;
1793 /* Implement 'show python ignore-environment'. */
1796 show_python_ignore_environment (struct ui_file *file, int from_tty,
1797 struct cmd_list_element *c, const char *value)
1799 fprintf_filtered (file, _("Python's ignore-environment setting is %s.\n"),
1803 /* Implement 'set python ignore-environment'. This sets Python's internal
1804 flag no matter when the command is issued, however, if this is used
1805 after Py_Initialize has been called then most of the environment will
1806 already have been read. */
1809 set_python_ignore_environment (const char *args, int from_tty,
1810 struct cmd_list_element *c)
1813 Py_IgnoreEnvironmentFlag = python_ignore_environment ? 1 : 0;
1817 /* When this is turned on before Python is initialised then Python will
1818 not write `.pyc' files on import of a module. */
1819 static enum auto_boolean python_dont_write_bytecode = AUTO_BOOLEAN_AUTO;
1821 /* Implement 'show python dont-write-bytecode'. */
1824 show_python_dont_write_bytecode (struct ui_file *file, int from_tty,
1825 struct cmd_list_element *c, const char *value)
1827 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
1829 const char *auto_string
1830 = (python_ignore_environment
1831 || getenv ("PYTHONDONTWRITEBYTECODE") == nullptr) ? "off" : "on";
1833 fprintf_filtered (file,
1834 _("Python's dont-write-bytecode setting is %s (currently %s).\n"),
1835 value, auto_string);
1838 fprintf_filtered (file, _("Python's dont-write-bytecode setting is %s.\n"),
1842 /* Implement 'set python dont-write-bytecode'. This sets Python's internal
1843 flag no matter when the command is issued, however, if this is used
1844 after Py_Initialize has been called then many modules could already
1845 have been imported and their byte code written out. */
1848 set_python_dont_write_bytecode (const char *args, int from_tty,
1849 struct cmd_list_element *c)
1852 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
1853 Py_DontWriteBytecodeFlag
1854 = (!python_ignore_environment
1855 && getenv ("PYTHONDONTWRITEBYTECODE") != nullptr) ? 1 : 0;
1857 Py_DontWriteBytecodeFlag
1858 = python_dont_write_bytecode == AUTO_BOOLEAN_TRUE ? 1 : 0;
1859 #endif /* HAVE_PYTHON */
1864 /* Lists for 'set python' commands. */
1866 static struct cmd_list_element *user_set_python_list;
1867 static struct cmd_list_element *user_show_python_list;
1869 /* Initialize the Python code. */
1873 /* This is installed as a final cleanup and cleans up the
1874 interpreter. This lets Python's 'atexit' work. */
1877 finalize_python (void *ignore)
1879 struct active_ext_lang_state *previous_active;
1881 /* We don't use ensure_python_env here because if we ever ran the
1882 cleanup, gdb would crash -- because the cleanup calls into the
1883 Python interpreter, which we are about to destroy. It seems
1884 clearer to make the needed calls explicitly here than to create a
1885 cleanup and then mysteriously discard it. */
1887 /* This is only called as a final cleanup so we can assume the active
1888 SIGINT handler is gdb's. We still need to tell it to notify Python. */
1889 previous_active = set_active_ext_lang (&extension_language_python);
1891 (void) PyGILState_Ensure ();
1892 gdbpy_enter::finalize ();
1894 gdbpy_finalize_micommands ();
1898 gdb_python_initialized = false;
1899 restore_active_ext_lang (previous_active);
1902 static struct PyModuleDef python_GdbModuleDef =
1904 PyModuleDef_HEAD_INIT,
1915 /* This is called via the PyImport_AppendInittab mechanism called
1916 during initialization, to make the built-in _gdb module known to
1918 PyMODINIT_FUNC init__gdb_module (void);
1920 init__gdb_module (void)
1922 return PyModule_Create (&python_GdbModuleDef);
1925 /* Emit a gdb.GdbExitingEvent, return a negative value if there are any
1926 errors, otherwise, return 0. */
1929 emit_exiting_event (int exit_code)
1931 gdbpy_ref<> event_obj = create_event_object (&gdb_exiting_event_object_type);
1932 if (event_obj == nullptr)
1935 gdbpy_ref<> code = gdb_py_object_from_longest (exit_code);
1936 if (evpy_add_attribute (event_obj.get (), "exit_code", code.get ()) < 0)
1939 return evpy_emit_event (event_obj.get (), gdb_py_events.gdb_exiting);
1942 /* Callback for the gdb_exiting observable. EXIT_CODE is the value GDB
1946 gdbpy_gdb_exiting (int exit_code)
1948 if (!gdb_python_initialized)
1951 gdbpy_enter enter_py;
1953 if (emit_exiting_event (exit_code) < 0)
1954 gdbpy_print_stack ();
1958 do_start_initialization ()
1960 #ifdef WITH_PYTHON_PATH
1961 /* Work around problem where python gets confused about where it is,
1962 and then can't find its libraries, etc.
1963 NOTE: Python assumes the following layout:
1965 /foo/lib/pythonX.Y/...
1966 This must be done before calling Py_Initialize. */
1967 gdb::unique_xmalloc_ptr<char> progname
1968 (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
1969 SLASH_STRING, "python", (char *) NULL));
1970 /* Python documentation indicates that the memory given
1971 to Py_SetProgramName cannot be freed. However, it seems that
1972 at least Python 3.7.4 Py_SetProgramName takes a copy of the
1973 given program_name. Making progname_copy static and not release
1974 the memory avoids a leak report for Python versions that duplicate
1975 program_name, and respect the requirement of Py_SetProgramName
1976 for Python versions that do not duplicate program_name. */
1977 static wchar_t *progname_copy;
1979 std::string oldloc = setlocale (LC_ALL, NULL);
1980 setlocale (LC_ALL, "");
1981 size_t progsize = strlen (progname.get ());
1982 progname_copy = XNEWVEC (wchar_t, progsize + 1);
1983 size_t count = mbstowcs (progname_copy, progname.get (), progsize + 1);
1984 if (count == (size_t) -1)
1986 fprintf (stderr, "Could not convert python path to string\n");
1989 setlocale (LC_ALL, oldloc.c_str ());
1991 /* Note that Py_SetProgramName expects the string it is passed to
1992 remain alive for the duration of the program's execution, so
1993 it is not freed after this call. */
1994 Py_SetProgramName (progname_copy);
1996 /* Define _gdb as a built-in module. */
1997 PyImport_AppendInittab ("_gdb", init__gdb_module);
2001 #if PY_VERSION_HEX < 0x03090000
2002 /* PyEval_InitThreads became deprecated in Python 3.9 and will
2003 be removed in Python 3.11. Prior to Python 3.7, this call was
2004 required to initialize the GIL. */
2005 PyEval_InitThreads ();
2008 gdb_module = PyImport_ImportModule ("_gdb");
2009 if (gdb_module == NULL)
2012 if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
2013 || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
2014 || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
2018 /* Add stream constants. */
2019 if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
2020 || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
2021 || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
2024 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
2025 if (gdbpy_gdb_error == NULL
2026 || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
2029 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
2030 gdbpy_gdb_error, NULL);
2031 if (gdbpy_gdb_memory_error == NULL
2032 || gdb_pymodule_addobject (gdb_module, "MemoryError",
2033 gdbpy_gdb_memory_error) < 0)
2036 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
2037 if (gdbpy_gdberror_exc == NULL
2038 || gdb_pymodule_addobject (gdb_module, "GdbError",
2039 gdbpy_gdberror_exc) < 0)
2042 gdbpy_initialize_gdb_readline ();
2044 if (gdbpy_initialize_auto_load () < 0
2045 || gdbpy_initialize_values () < 0
2046 || gdbpy_initialize_frames () < 0
2047 || gdbpy_initialize_commands () < 0
2048 || gdbpy_initialize_instruction () < 0
2049 || gdbpy_initialize_record () < 0
2050 || gdbpy_initialize_btrace () < 0
2051 || gdbpy_initialize_symbols () < 0
2052 || gdbpy_initialize_symtabs () < 0
2053 || gdbpy_initialize_blocks () < 0
2054 || gdbpy_initialize_functions () < 0
2055 || gdbpy_initialize_parameters () < 0
2056 || gdbpy_initialize_types () < 0
2057 || gdbpy_initialize_pspace () < 0
2058 || gdbpy_initialize_objfile () < 0
2059 || gdbpy_initialize_breakpoints () < 0
2060 || gdbpy_initialize_finishbreakpoints () < 0
2061 || gdbpy_initialize_lazy_string () < 0
2062 || gdbpy_initialize_linetable () < 0
2063 || gdbpy_initialize_thread () < 0
2064 || gdbpy_initialize_inferior () < 0
2065 || gdbpy_initialize_eventregistry () < 0
2066 || gdbpy_initialize_py_events () < 0
2067 || gdbpy_initialize_event () < 0
2068 || gdbpy_initialize_arch () < 0
2069 || gdbpy_initialize_registers () < 0
2070 || gdbpy_initialize_xmethods () < 0
2071 || gdbpy_initialize_unwind () < 0
2072 || gdbpy_initialize_membuf () < 0
2073 || gdbpy_initialize_connection () < 0
2074 || gdbpy_initialize_tui () < 0
2075 || gdbpy_initialize_micommands () < 0)
2078 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2079 if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
2081 #include "py-event-types.def"
2082 #undef GDB_PY_DEFINE_EVENT_TYPE
2084 gdbpy_to_string_cst = PyUnicode_FromString ("to_string");
2085 if (gdbpy_to_string_cst == NULL)
2087 gdbpy_children_cst = PyUnicode_FromString ("children");
2088 if (gdbpy_children_cst == NULL)
2090 gdbpy_display_hint_cst = PyUnicode_FromString ("display_hint");
2091 if (gdbpy_display_hint_cst == NULL)
2093 gdbpy_doc_cst = PyUnicode_FromString ("__doc__");
2094 if (gdbpy_doc_cst == NULL)
2096 gdbpy_enabled_cst = PyUnicode_FromString ("enabled");
2097 if (gdbpy_enabled_cst == NULL)
2099 gdbpy_value_cst = PyUnicode_FromString ("value");
2100 if (gdbpy_value_cst == NULL)
2103 gdb::observers::gdb_exiting.attach (gdbpy_gdb_exiting, "python");
2105 /* Release the GIL while gdb runs. */
2106 PyEval_SaveThread ();
2108 make_final_cleanup (finalize_python, NULL);
2110 /* Only set this when initialization has succeeded. */
2111 gdb_python_initialized = 1;
2116 namespace selftests {
2118 /* Entry point for python unit tests. */
2123 #define CMD(S) execute_command_to_string (S, "python print(5)", 0, true)
2128 SELF_CHECK (output == "5\n");
2131 bool saw_exception = false;
2133 scoped_restore reset_gdb_python_initialized
2134 = make_scoped_restore (&gdb_python_initialized, 0);
2139 catch (const gdb_exception &e)
2141 saw_exception = true;
2142 SELF_CHECK (e.reason == RETURN_ERROR);
2143 SELF_CHECK (e.error == GENERIC_ERROR);
2144 SELF_CHECK (*e.message == "Python not initialized");
2146 SELF_CHECK (saw_exception);
2147 SELF_CHECK (output.empty ());
2150 saw_exception = false;
2152 scoped_restore save_hook
2153 = make_scoped_restore (&hook_set_active_ext_lang,
2154 []() { raise (SIGINT); });
2159 catch (const gdb_exception &e)
2161 saw_exception = true;
2162 SELF_CHECK (e.reason == RETURN_ERROR);
2163 SELF_CHECK (e.error == GENERIC_ERROR);
2164 SELF_CHECK (*e.message == "Error while executing Python code.");
2166 SELF_CHECK (saw_exception);
2167 std::string ref_output("Traceback (most recent call last):\n"
2168 " File \"<string>\", line 1, in <module>\n"
2169 "KeyboardInterrupt\n");
2170 SELF_CHECK (output == ref_output);
2178 } // namespace selftests
2179 #endif /* GDB_SELF_TEST */
2181 #endif /* HAVE_PYTHON */
2184 cmd_list_element *python_cmd_element = nullptr;
2186 void _initialize_python ();
2188 _initialize_python ()
2190 cmd_list_element *python_interactive_cmd
2191 = add_com ("python-interactive", class_obscure,
2192 python_interactive_command,
2195 Start an interactive Python prompt.\n\
2197 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
2200 Alternatively, a single-line Python command can be given as an\n\
2201 argument, and if the command is an expression, the result will be\n\
2202 printed. For example:\n\
2204 (gdb) python-interactive 2 + 3\n\
2206 #else /* HAVE_PYTHON */
2208 Start a Python interactive prompt.\n\
2210 Python scripting is not supported in this copy of GDB.\n\
2211 This command is only a placeholder.")
2212 #endif /* HAVE_PYTHON */
2214 add_com_alias ("pi", python_interactive_cmd, class_obscure, 1);
2216 python_cmd_element = add_com ("python", class_obscure, python_command,
2219 Evaluate a Python command.\n\
2221 The command can be given as an argument, for instance:\n\
2223 python print (23)\n\
2225 If no argument is given, the following lines are read and used\n\
2226 as the Python commands. Type a line containing \"end\" to indicate\n\
2227 the end of the command.")
2228 #else /* HAVE_PYTHON */
2230 Evaluate a Python command.\n\
2232 Python scripting is not supported in this copy of GDB.\n\
2233 This command is only a placeholder.")
2234 #endif /* HAVE_PYTHON */
2236 add_com_alias ("py", python_cmd_element, class_obscure, 1);
2238 /* Add set/show python print-stack. */
2239 add_setshow_prefix_cmd ("python", no_class,
2240 _("Prefix command for python preference settings."),
2241 _("Prefix command for python preference settings."),
2242 &user_set_python_list, &user_show_python_list,
2243 &setlist, &showlist);
2245 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
2246 &gdbpy_should_print_stack, _("\
2247 Set mode for Python stack dump on error."), _("\
2248 Show the mode of Python stack printing on error."), _("\
2249 none == no stack or message will be printed.\n\
2250 full == a message and a stack will be printed.\n\
2251 message == an error message without a stack will be printed."),
2253 &user_set_python_list,
2254 &user_show_python_list);
2256 add_setshow_boolean_cmd ("ignore-environment", no_class,
2257 &python_ignore_environment, _("\
2258 Set whether the Python interpreter should ignore environment variables."), _(" \
2259 Show whether the Python interpreter showlist ignore environment variables."), _(" \
2260 When enabled GDB's Python interpreter will ignore any Python related\n \
2261 flags in the environment. This is equivalent to passing `-E' to a\n \
2262 python executable."),
2263 set_python_ignore_environment,
2264 show_python_ignore_environment,
2265 &user_set_python_list,
2266 &user_show_python_list);
2268 add_setshow_auto_boolean_cmd ("dont-write-bytecode", no_class,
2269 &python_dont_write_bytecode, _("\
2270 Set whether the Python interpreter should ignore environment variables."), _(" \
2271 Show whether the Python interpreter showlist ignore environment variables."), _(" \
2272 When enabled GDB's Python interpreter will ignore any Python related\n \
2273 flags in the environment. This is equivalent to passing `-E' to a\n \
2274 python executable."),
2275 set_python_dont_write_bytecode,
2276 show_python_dont_write_bytecode,
2277 &user_set_python_list,
2278 &user_show_python_list);
2282 selftests::register_test ("python", selftests::test_python);
2283 #endif /* GDB_SELF_TEST */
2284 #endif /* HAVE_PYTHON */
2289 /* Helper function for gdbpy_initialize. This does the work and then
2290 returns false if an error has occurred and must be displayed, or true on
2294 do_initialize (const struct extension_language_defn *extlang)
2299 /* Add the initial data-directory to sys.path. */
2301 std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
2304 sys_path = PySys_GetObject ("path");
2306 /* If sys.path is not defined yet, define it first. */
2307 if (!(sys_path && PyList_Check (sys_path)))
2309 PySys_SetPath (L"");
2310 sys_path = PySys_GetObject ("path");
2312 if (sys_path && PyList_Check (sys_path))
2314 gdbpy_ref<> pythondir (PyUnicode_FromString (gdb_pythondir.c_str ()));
2315 if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
2321 /* Import the gdb module to finish the initialization, and
2322 add it to __main__ for convenience. */
2323 m = PyImport_AddModule ("__main__");
2327 /* Keep the reference to gdb_python_module since it is in a global
2329 gdb_python_module = PyImport_ImportModule ("gdb");
2330 if (gdb_python_module == NULL)
2332 gdbpy_print_stack ();
2333 /* This is passed in one call to warning so that blank lines aren't
2334 inserted between each line of text. */
2336 "Could not load the Python gdb module from `%s'.\n"
2337 "Limited Python support is available from the _gdb module.\n"
2338 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
2339 gdb_pythondir.c_str ());
2340 /* We return "success" here as we've already emitted the
2345 return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
2348 /* Perform Python initialization. This will be called after GDB has
2349 performed all of its own initialization. This is the
2350 extension_language_ops.initialize "method". */
2353 gdbpy_initialize (const struct extension_language_defn *extlang)
2355 if (!do_start_initialization () && PyErr_Occurred ())
2356 gdbpy_print_stack ();
2358 gdbpy_enter enter_py;
2360 if (!do_initialize (extlang))
2362 gdbpy_print_stack ();
2363 warning (_("internal error: Unhandled Python exception"));
2367 /* Return non-zero if Python has successfully initialized.
2368 This is the extension_languages_ops.initialized "method". */
2371 gdbpy_initialized (const struct extension_language_defn *extlang)
2373 return gdb_python_initialized;
2376 PyMethodDef python_GdbMethods[] =
2378 { "history", gdbpy_history, METH_VARARGS,
2379 "Get a value from history" },
2380 { "add_history", gdbpy_add_history, METH_VARARGS,
2381 "Add a value to the value history list" },
2382 { "history_count", gdbpy_history_count, METH_NOARGS,
2383 "Return an integer, the number of values in GDB's value history" },
2384 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
2385 "execute (command [, from_tty] [, to_string]) -> [String]\n\
2386 Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
2387 a Python String containing the output of the command if to_string is\n\
2389 { "parameter", gdbpy_parameter, METH_VARARGS,
2390 "Return a gdb parameter's value" },
2392 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
2393 "Return a tuple of all breakpoint objects" },
2395 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
2396 "Find the default visualizer for a Value." },
2398 { "progspaces", gdbpy_progspaces, METH_NOARGS,
2399 "Return a sequence of all progspaces." },
2401 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
2402 "Return the current Objfile being loaded, or None." },
2404 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
2405 "newest_frame () -> gdb.Frame.\n\
2406 Return the newest frame object." },
2407 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
2408 "selected_frame () -> gdb.Frame.\n\
2409 Return the selected frame object." },
2410 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
2411 "stop_reason_string (Integer) -> String.\n\
2412 Return a string explaining unwind stop reason." },
2414 { "start_recording", gdbpy_start_recording, METH_VARARGS,
2415 "start_recording ([method] [, format]) -> gdb.Record.\n\
2416 Start recording with the given method. If no method is given, will fall back\n\
2417 to the system default method. If no format is given, will fall back to the\n\
2418 default format for the given method."},
2419 { "current_recording", gdbpy_current_recording, METH_NOARGS,
2420 "current_recording () -> gdb.Record.\n\
2421 Return current recording object." },
2422 { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
2423 "stop_recording () -> None.\n\
2424 Stop current recording." },
2426 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
2427 METH_VARARGS | METH_KEYWORDS,
2428 "lookup_type (name [, block]) -> type\n\
2429 Return a Type corresponding to the given name." },
2430 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
2431 METH_VARARGS | METH_KEYWORDS,
2432 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
2433 Return a tuple with the symbol corresponding to the given name (or None) and\n\
2434 a boolean indicating if name is a field of the current implied argument\n\
2435 `this' (when the current language is object-oriented)." },
2436 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
2437 METH_VARARGS | METH_KEYWORDS,
2438 "lookup_global_symbol (name [, domain]) -> symbol\n\
2439 Return the symbol corresponding to the given name (or None)." },
2440 { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
2441 METH_VARARGS | METH_KEYWORDS,
2442 "lookup_static_symbol (name [, domain]) -> symbol\n\
2443 Return the static-linkage symbol corresponding to the given name (or None)." },
2444 { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
2445 METH_VARARGS | METH_KEYWORDS,
2446 "lookup_static_symbols (name [, domain]) -> symbol\n\
2447 Return a list of all static-linkage symbols corresponding to the given name." },
2449 { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
2450 METH_VARARGS | METH_KEYWORDS,
2451 "lookup_objfile (name, [by_build_id]) -> objfile\n\
2452 Look up the specified objfile.\n\
2453 If by_build_id is True, the objfile is looked up by using name\n\
2454 as its build id." },
2456 { "decode_line", gdbpy_decode_line, METH_VARARGS,
2457 "decode_line (String) -> Tuple. Decode a string argument the way\n\
2458 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
2459 The first element contains any unparsed portion of the String parameter\n\
2460 (or None if the string was fully parsed). The second element contains\n\
2461 a tuple that contains all the locations that match, represented as\n\
2462 gdb.Symtab_and_line objects (or None)."},
2463 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
2464 "parse_and_eval (String) -> Value.\n\
2465 Parse String as an expression, evaluate it, and return the result as a Value."
2468 { "post_event", gdbpy_post_event, METH_VARARGS,
2469 "Post an event into gdb's event loop." },
2471 { "target_charset", gdbpy_target_charset, METH_NOARGS,
2472 "target_charset () -> string.\n\
2473 Return the name of the current target charset." },
2474 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
2475 "target_wide_charset () -> string.\n\
2476 Return the name of the current target wide charset." },
2477 { "host_charset", gdbpy_host_charset, METH_NOARGS,
2478 "host_charset () -> string.\n\
2479 Return the name of the current host charset." },
2480 { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
2481 "rbreak (Regex) -> List.\n\
2482 Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
2483 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
2484 "string_to_argv (String) -> Array.\n\
2485 Parse String and return an argv-like array.\n\
2486 Arguments are separate by spaces and may be quoted."
2488 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
2489 "Write a string using gdb's filtered stream." },
2490 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
2491 "Flush gdb's filtered stdout stream." },
2492 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
2493 "selected_thread () -> gdb.InferiorThread.\n\
2494 Return the selected thread object." },
2495 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
2496 "selected_inferior () -> gdb.Inferior.\n\
2497 Return the selected inferior object." },
2498 { "inferiors", gdbpy_inferiors, METH_NOARGS,
2499 "inferiors () -> (gdb.Inferior, ...).\n\
2500 Return a tuple containing all inferiors." },
2502 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
2503 "invalidate_cached_frames () -> None.\n\
2504 Invalidate any cached frame objects in gdb.\n\
2505 Intended for internal use only." },
2507 { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
2508 "convenience_variable (NAME) -> value.\n\
2509 Return the value of the convenience variable $NAME,\n\
2510 or None if not set." },
2511 { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
2512 "convenience_variable (NAME, VALUE) -> None.\n\
2513 Set the value of the convenience variable $NAME." },
2516 { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
2517 METH_VARARGS | METH_KEYWORDS,
2518 "register_window_type (NAME, CONSTRUCSTOR) -> None\n\
2519 Register a TUI window constructor." },
2522 { "architecture_names", gdbpy_all_architecture_names, METH_NOARGS,
2523 "architecture_names () -> List.\n\
2524 Return a list of all the architecture names GDB understands." },
2526 { "connections", gdbpy_connections, METH_NOARGS,
2527 "connections () -> List.\n\
2528 Return a list of gdb.TargetConnection objects." },
2530 { "format_address", (PyCFunction) gdbpy_format_address,
2531 METH_VARARGS | METH_KEYWORDS,
2532 "format_address (ADDRESS, PROG_SPACE, ARCH) -> String.\n\
2533 Format ADDRESS, an address within PROG_SPACE, a gdb.Progspace, using\n\
2534 ARCH, a gdb.Architecture to determine the address size. The format of\n\
2535 the returned string is 'ADDRESS <SYMBOL+OFFSET>' without the quotes." },
2537 {NULL, NULL, 0, NULL}
2540 /* Define all the event objects. */
2541 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2542 PyTypeObject name##_event_object_type \
2543 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
2545 PyVarObject_HEAD_INIT (NULL, 0) \
2546 "gdb." py_name, /* tp_name */ \
2547 sizeof (event_object), /* tp_basicsize */ \
2548 0, /* tp_itemsize */ \
2549 evpy_dealloc, /* tp_dealloc */ \
2551 0, /* tp_getattr */ \
2552 0, /* tp_setattr */ \
2553 0, /* tp_compare */ \
2555 0, /* tp_as_number */ \
2556 0, /* tp_as_sequence */ \
2557 0, /* tp_as_mapping */ \
2561 0, /* tp_getattro */ \
2562 0, /* tp_setattro */ \
2563 0, /* tp_as_buffer */ \
2564 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
2566 0, /* tp_traverse */ \
2568 0, /* tp_richcompare */ \
2569 0, /* tp_weaklistoffset */ \
2571 0, /* tp_iternext */ \
2572 0, /* tp_methods */ \
2573 0, /* tp_members */ \
2574 0, /* tp_getset */ \
2575 &base, /* tp_base */ \
2577 0, /* tp_descr_get */ \
2578 0, /* tp_descr_set */ \
2579 0, /* tp_dictoffset */ \
2583 #include "py-event-types.def"
2584 #undef GDB_PY_DEFINE_EVENT_TYPE
2586 #endif /* HAVE_PYTHON */