1 /* General python/gdb code
3 Copyright (C) 2008-2021 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"
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";
44 /* "set python print-stack" choices. */
45 static const char *const python_excp_enums[] =
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
57 static const char *gdbpy_should_print_stack = python_excp_message;
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;
65 /* The main struct describing GDB's interface to the Python
66 extension language. */
67 const struct extension_language_defn extension_language_python =
79 &python_extension_script_ops,
89 #include "cli/cli-decode.h"
92 #include "python-internal.h"
95 #include "gdbsupport/version.h"
97 #include "gdbthread.h"
99 #include "event-top.h"
100 #include "py-event.h"
102 /* True if Python has been successfully initialized, false
105 int gdb_python_initialized;
107 extern PyMethodDef python_GdbMethods[];
109 PyObject *gdb_module;
110 PyObject *gdb_python_module;
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;
120 /* The GdbError exception. */
121 PyObject *gdbpy_gdberror_exc;
123 /* The `gdb.error' base class. */
124 PyObject *gdbpy_gdb_error;
126 /* The `gdb.MemoryError' exception. */
127 PyObject *gdbpy_gdb_memory_error;
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);
150 /* The interface between gdb proper and loading of python scripts. */
152 const struct extension_language_script_ops python_extension_script_ops =
155 gdbpy_source_objfile_script,
156 gdbpy_execute_objfile_script,
157 gdbpy_auto_load_enabled
160 /* The interface between gdb proper and python extensions. */
162 const struct extension_language_ops python_extension_ops =
167 gdbpy_eval_from_control_command,
169 gdbpy_start_type_printers,
170 gdbpy_apply_type_printers,
171 gdbpy_free_type_printers,
173 gdbpy_apply_val_pretty_printer,
175 gdbpy_apply_frame_filter,
177 gdbpy_preserve_values,
179 gdbpy_breakpoint_has_cond,
180 gdbpy_breakpoint_cond_says_stop,
183 gdbpy_check_quit_flag,
185 gdbpy_before_prompt_hook,
187 gdbpy_get_matching_xmethod_workers,
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;
197 gdbpy_enter::gdbpy_enter (struct gdbarch *gdbarch,
198 const struct language_defn *language)
199 : m_gdbarch (python_gdbarch),
200 m_language (python_language)
202 /* We should not ever enter Python unless initialized. */
203 if (!gdb_python_initialized)
204 error (_("Python not initialized"));
206 m_previous_active = set_active_ext_lang (&extension_language_python);
208 m_state = PyGILState_Ensure ();
210 python_gdbarch = gdbarch;
211 python_language = language;
213 /* Save it and ensure ! PyErr_Occurred () afterwards. */
217 gdbpy_enter::~gdbpy_enter ()
219 /* Leftover Python error is forbidden by Python Exception Handling. */
220 if (PyErr_Occurred ())
222 /* This order is similar to the one calling error afterwards. */
223 gdbpy_print_stack ();
224 warning (_("internal error: Unhandled Python exception"));
229 python_gdbarch = m_gdbarch;
230 python_language = m_language;
232 restore_active_ext_lang (m_previous_active);
233 PyGILState_Release (m_state);
236 /* A helper class to save and restore the GIL, but without touching
237 the other globals that are handled by gdbpy_enter. */
244 : m_state (PyGILState_Ensure ())
250 PyGILState_Release (m_state);
253 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
257 PyGILState_STATE m_state;
260 /* Set the quit flag. */
263 gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
265 PyErr_SetInterrupt ();
268 /* Return true if the quit flag has been set, false otherwise. */
271 gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
273 if (!gdb_python_initialized)
277 return PyOS_InterruptOccurred ();
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. */
285 eval_python_command (const char *command)
289 m = PyImport_AddModule ("__main__");
293 d = PyModule_GetDict (m);
296 gdbpy_ref<> v (PyRun_StringFlags (command, Py_single_input, d, d, NULL));
308 /* Implementation of the gdb "python-interactive" command. */
311 python_interactive_command (const char *arg, int from_tty)
313 struct ui *ui = current_ui;
316 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
318 arg = skip_spaces (arg);
320 gdbpy_enter enter_py (get_current_arch (), current_language);
324 std::string script = std::string (arg) + "\n";
325 err = eval_python_command (script.c_str ());
329 err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
335 gdbpy_print_stack ();
336 error (_("Error while executing Python code."));
340 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
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
352 To work around this potential issue, we run code in Python to load
356 python_run_simple_file (FILE *file, const char *filename)
360 PyRun_SimpleFile (file, filename);
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));
368 if (gdb_python_module == nullptr
369 || ! PyObject_HasAttrString (gdb_python_module, "_execute_file"))
370 error (_("Installation error: gdb._execute_file function is missing"));
372 gdbpy_ref<> return_value
373 (PyObject_CallMethod (gdb_python_module, "_execute_file", "s",
375 if (return_value == nullptr)
377 /* Use PyErr_PrintEx instead of gdbpy_print_stack to better match the
378 behavior of the non-Windows codepath. */
385 /* Given a command_line, return a command string suitable for passing
386 to Python. Lines in the string are separated by newlines. */
389 compute_python_string (struct command_line *l)
391 struct command_line *iter;
394 for (iter = l; iter; iter = iter->next)
396 script += iter->line;
402 /* Take a command line structure representing a 'python' command, and
403 evaluate its body using the Python interpreter. */
406 gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
407 struct command_line *cmd)
411 if (cmd->body_list_1 != nullptr)
412 error (_("Invalid \"python\" block structure."));
414 gdbpy_enter enter_py (get_current_arch (), current_language);
416 std::string script = compute_python_string (cmd->body_list_0.get ());
417 ret = PyRun_SimpleString (script.c_str ());
419 error (_("Error while executing Python code."));
422 /* Implementation of the gdb "python" command. */
425 python_command (const char *arg, int from_tty)
427 gdbpy_enter enter_py (get_current_arch (), current_language);
429 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
431 arg = skip_spaces (arg);
434 if (PyRun_SimpleString (arg))
435 error (_("Error while executing Python code."));
439 counted_command_line l = get_command_line (python_control, "");
441 execute_control_command_untraced (l.get ());
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
451 gdbpy_parameter_value (enum var_types type, void *var)
456 case var_string_noescape:
457 case var_optional_filename:
461 const char *str = *(char **) var;
465 return host_string_to_python_string (str).release ();
476 case var_auto_boolean:
478 enum auto_boolean ab = * (enum auto_boolean *) var;
480 if (ab == AUTO_BOOLEAN_TRUE)
482 else if (ab == AUTO_BOOLEAN_FALSE)
489 if ((* (int *) var) == INT_MAX)
493 case var_zuinteger_unlimited:
494 return gdb_py_object_from_longest (* (int *) var).release ();
498 unsigned int val = * (unsigned int *) var;
502 return gdb_py_object_from_ulongest (val).release ();
507 unsigned int val = * (unsigned int *) var;
508 return gdb_py_object_from_ulongest (val).release ();
512 return PyErr_Format (PyExc_RuntimeError,
513 _("Programmer error: unhandled type."));
516 /* A Python function which returns a gdb parameter's value as a Python
520 gdbpy_parameter (PyObject *self, PyObject *args)
522 struct cmd_list_element *alias, *prefix, *cmd;
526 if (! PyArg_ParseTuple (args, "s", &arg))
529 std::string newarg = std::string ("show ") + arg;
533 found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
535 catch (const gdb_exception &ex)
537 GDB_PY_HANDLE_EXCEPTION (ex);
541 return PyErr_Format (PyExc_RuntimeError,
542 _("Could not find parameter `%s'."), arg);
545 return PyErr_Format (PyExc_RuntimeError,
546 _("`%s' is not a parameter."), arg);
547 return gdbpy_parameter_value (cmd->var_type, cmd->var);
550 /* Wrapper for target_charset. */
553 gdbpy_target_charset (PyObject *self, PyObject *args)
555 const char *cset = target_charset (python_gdbarch);
557 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
560 /* Wrapper for target_wide_charset. */
563 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
565 const char *cset = target_wide_charset (python_gdbarch);
567 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
570 /* A Python function which evaluates a string using the gdb CLI. */
573 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
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 };
580 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
581 &PyBool_Type, &from_tty_obj,
582 &PyBool_Type, &to_string_obj))
588 int cmp = PyObject_IsTrue (from_tty_obj);
597 int cmp = PyObject_IsTrue (to_string_obj);
603 std::string to_string_res;
605 scoped_restore preventer = prevent_dont_repeat ();
609 gdbpy_allow_threads allow_threads;
611 struct interp *interp;
613 std::string arg_copy = arg;
615 char *save_ptr = nullptr;
619 const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
625 counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
628 scoped_restore save_async = make_scoped_restore (¤t_ui->async,
631 scoped_restore save_uiout = make_scoped_restore (¤t_uiout);
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 ();
639 to_string_res = execute_control_commands_to_string (lines.get (),
642 execute_control_commands (lines.get (), from_tty);
645 /* Do any commands attached to breakpoint we stopped at. */
646 bpstat_do_actions ();
648 catch (const gdb_exception &except)
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);
660 return PyString_FromString (to_string_res.c_str ());
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. */
678 gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
681 std::vector<symbol_search> symbols;
682 unsigned long count = 0;
683 PyObject *symtab_list = NULL;
684 PyObject *minsyms_p_obj = NULL;
686 unsigned int throttle = 0;
687 static const char *keywords[] = {"regex","minsyms", "throttle",
690 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
691 ®ex, &PyBool_Type,
692 &minsyms_p_obj, &throttle,
696 /* Parse minsyms keyword. */
697 if (minsyms_p_obj != NULL)
699 int cmp = PyObject_IsTrue (minsyms_p_obj);
705 global_symbol_searcher spec (FUNCTIONS_DOMAIN, regex);
707 for (const char *elem : spec.filenames)
708 xfree ((void *) elem);
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)
722 gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
729 gdbpy_ref<> next (PyIter_Next (iter.get ()));
733 if (PyErr_Occurred ())
738 gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
741 if (obj_name == NULL)
744 /* Is the object file still valid? */
745 if (obj_name == Py_None)
748 gdb::unique_xmalloc_ptr<char> filename =
749 python_string_to_target_string (obj_name.get ());
751 if (filename == NULL)
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 ();
761 /* The search spec. */
762 symbols = spec.search ();
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)
768 /* Minimal symbols included? */
771 if (p.msymbol.minsym != NULL)
775 if (p.symbol != NULL)
779 /* Check throttle bounds and exit if in excess. */
780 if (throttle != 0 && count > throttle)
782 PyErr_SetString (PyExc_RuntimeError,
783 _("Number of breakpoints exceeds throttled maximum."));
787 gdbpy_ref<> return_list (PyList_New (0));
789 if (return_list == NULL)
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)
797 std::string symbol_name;
799 /* Skipping minimal symbols? */
801 if (p.msymbol.minsym != NULL)
804 if (p.msymbol.minsym == NULL)
806 struct symtab *symtab = symbol_symtab (p.symbol);
807 const char *fullname = symtab_to_fullname (symtab);
809 symbol_name = fullname;
811 symbol_name += p.symbol->linkage_name ();
814 symbol_name = p.msymbol.minsym->linkage_name ();
816 gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
817 gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
818 &breakpoint_object_type,
821 /* Tolerate individual breakpoint failures. */
823 gdbpy_print_stack ();
826 if (PyList_Append (return_list.get (), obj.get ()) == -1)
830 return return_list.release ();
833 /* A Python function which is a wrapper for decode_line_1. */
836 gdbpy_decode_line (PyObject *self, PyObject *args)
838 const char *arg = NULL;
840 gdbpy_ref<> unparsed;
841 event_location_up location;
843 if (! PyArg_ParseTuple (args, "|s", &arg))
846 /* Treat a string consisting of just whitespace the same as
850 arg = skip_spaces (arg);
856 location = string_to_event_location_basic (&arg, python_language,
857 symbol_name_match_type::WILD);
859 std::vector<symtab_and_line> decoded_sals;
860 symtab_and_line def_sal;
861 gdb::array_view<symtab_and_line> sals;
864 if (location != NULL)
866 decoded_sals = decode_line_1 (location.get (), 0, NULL, NULL, 0);
871 set_default_source_symtab_and_line ();
872 def_sal = get_current_source_symtab_and_line ();
876 catch (const gdb_exception &ex)
878 /* We know this will always throw. */
879 gdbpy_convert_exception (ex);
885 result.reset (PyTuple_New (sals.size ()));
888 for (size_t i = 0; i < sals.size (); ++i)
890 PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
894 PyTuple_SetItem (result.get (), i, obj);
898 result = gdbpy_ref<>::new_reference (Py_None);
900 gdbpy_ref<> return_result (PyTuple_New (2));
901 if (return_result == NULL)
904 if (arg != NULL && strlen (arg) > 0)
906 unparsed.reset (PyString_FromString (arg));
907 if (unparsed == NULL)
911 unparsed = gdbpy_ref<>::new_reference (Py_None);
913 PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
914 PyTuple_SetItem (return_result.get (), 1, result.release ());
916 return return_result.release ();
919 /* Parse a string and evaluate it as an expression. */
921 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
923 const char *expr_str;
924 struct value *result = NULL;
926 if (!PyArg_ParseTuple (args, "s", &expr_str))
931 gdbpy_allow_threads allow_threads;
932 result = parse_and_eval (expr_str);
934 catch (const gdb_exception &except)
936 GDB_PY_HANDLE_EXCEPTION (except);
939 return value_to_value_object (result);
942 /* Implementation of gdb.invalidate_cached_frames. */
945 gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
947 reinit_frame_cache ();
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. */
958 gdbpy_source_script (const struct extension_language_defn *extlang,
959 FILE *file, const char *filename)
961 gdbpy_enter enter_py (get_current_arch (), current_language);
962 python_run_simple_file (file, filename);
967 /* Posting and handling events. */
969 /* A single event. */
972 gdbpy_event (gdbpy_ref<> &&func)
973 : m_func (func.release ())
977 gdbpy_event (gdbpy_event &&other) noexcept
978 : m_func (other.m_func)
980 other.m_func = nullptr;
983 gdbpy_event (const gdbpy_event &other)
984 : m_func (other.m_func)
996 gdbpy_event &operator= (const gdbpy_event &other) = delete;
1000 gdbpy_enter enter_py (get_current_arch (), current_language);
1002 gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
1003 if (call_result == NULL)
1004 gdbpy_print_stack ();
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. */
1015 /* Submit an event to the gdb thread. */
1017 gdbpy_post_event (PyObject *self, PyObject *args)
1021 if (!PyArg_ParseTuple (args, "O", &func))
1024 if (!PyCallable_Check (func))
1026 PyErr_SetString (PyExc_RuntimeError,
1027 _("Posted event is not callable"));
1031 gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
1032 gdbpy_event event (std::move (func_ref));
1033 run_on_main_thread (event);
1040 /* This is the extension_language_ops.before_prompt "method". */
1042 static enum ext_lang_rc
1043 gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
1044 const char *current_gdb_prompt)
1046 if (!gdb_python_initialized)
1047 return EXT_LANG_RC_NOP;
1049 gdbpy_enter enter_py (get_current_arch (), current_language);
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;
1055 if (gdb_python_module
1056 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
1058 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
1062 gdbpy_print_stack ();
1063 return EXT_LANG_RC_ERROR;
1066 if (PyCallable_Check (hook.get ()))
1068 gdbpy_ref<> current_prompt (PyString_FromString (current_gdb_prompt));
1069 if (current_prompt == NULL)
1071 gdbpy_print_stack ();
1072 return EXT_LANG_RC_ERROR;
1076 (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
1080 gdbpy_print_stack ();
1081 return EXT_LANG_RC_ERROR;
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 ()))
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;
1096 if (result != Py_None)
1098 gdb::unique_xmalloc_ptr<char>
1099 prompt (python_string_to_host_string (result.get ()));
1103 gdbpy_print_stack ();
1104 return EXT_LANG_RC_ERROR;
1107 set_prompt (prompt.get ());
1108 return EXT_LANG_RC_OK;
1113 return EXT_LANG_RC_NOP;
1116 /* This is the extension_language_ops.colorize "method". */
1118 static gdb::optional<std::string>
1119 gdbpy_colorize (const std::string &filename, const std::string &contents)
1121 if (!gdb_python_initialized)
1124 gdbpy_enter enter_py (get_current_arch (), current_language);
1126 if (gdb_python_module == nullptr
1127 || !PyObject_HasAttrString (gdb_python_module, "colorize"))
1130 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module, "colorize"));
1131 if (hook == nullptr)
1133 gdbpy_print_stack ();
1137 if (!PyCallable_Check (hook.get ()))
1140 gdbpy_ref<> fname_arg (PyString_FromString (filename.c_str ()));
1141 if (fname_arg == nullptr)
1143 gdbpy_print_stack ();
1146 gdbpy_ref<> contents_arg (PyString_FromString (contents.c_str ()));
1147 if (contents_arg == nullptr)
1149 gdbpy_print_stack ();
1153 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1155 contents_arg.get (),
1157 if (result == nullptr)
1159 gdbpy_print_stack ();
1163 if (!gdbpy_is_string (result.get ()))
1166 gdbpy_ref<> unic = python_string_to_unicode (result.get ());
1167 if (unic == nullptr)
1169 gdbpy_print_stack ();
1172 gdbpy_ref<> host_str (PyUnicode_AsEncodedString (unic.get (),
1175 if (host_str == nullptr)
1177 gdbpy_print_stack ();
1181 return std::string (PyBytes_AsString (host_str.get ()));
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. */
1193 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
1196 static const char *keywords[] = { "text", "stream", NULL };
1197 int stream_type = 0;
1199 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
1205 switch (stream_type)
1209 fprintf_filtered (gdb_stderr, "%s", arg);
1214 fprintf_filtered (gdb_stdlog, "%s", arg);
1218 fprintf_filtered (gdb_stdout, "%s", arg);
1221 catch (const gdb_exception &except)
1223 GDB_PY_HANDLE_EXCEPTION (except);
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
1234 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
1236 static const char *keywords[] = { "stream", NULL };
1237 int stream_type = 0;
1239 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1243 switch (stream_type)
1247 gdb_flush (gdb_stderr);
1252 gdb_flush (gdb_stdlog);
1256 gdb_flush (gdb_stdout);
1262 /* Return non-zero if print-stack is not "none". */
1265 gdbpy_print_python_errors_p (void)
1267 return gdbpy_should_print_stack != python_excp_none;
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
1275 gdbpy_print_stack (void)
1278 /* Print "none", just clear exception. */
1279 if (gdbpy_should_print_stack == python_excp_none)
1283 /* Print "full" message and backtrace. */
1284 else if (gdbpy_should_print_stack == python_excp_full)
1287 /* PyErr_Print doesn't necessarily end output with a newline.
1288 This works because Python's stdout/stderr is fed through
1294 catch (const gdb_exception &except)
1298 /* Print "message", just error print message. */
1301 gdbpy_err_fetch fetched_error;
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
1308 type = fetched_error.type_to_string ();
1312 if (msg == NULL || type == NULL)
1314 /* An error occurred computing the string representation of the
1316 fprintf_filtered (gdb_stderr,
1317 _("Error occurred computing Python error" \
1322 fprintf_filtered (gdb_stderr, "Python Exception %s: %s\n",
1323 type.get (), msg.get ());
1325 catch (const gdb_exception &except)
1331 /* Like gdbpy_print_stack, but if the exception is a
1332 KeyboardException, throw a gdb "quit" instead. */
1335 gdbpy_print_stack_or_quit ()
1337 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
1340 throw_quit ("Quit");
1342 gdbpy_print_stack ();
1347 /* Return a sequence holding all the Progspaces. */
1350 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1352 gdbpy_ref<> list (PyList_New (0));
1356 for (struct program_space *ps : program_spaces)
1358 gdbpy_ref<> item = pspace_to_pspace_object (ps);
1360 if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
1364 return list.release ();
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
1373 static struct objfile *gdbpy_current_objfile;
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
1382 gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
1383 struct objfile *objfile, FILE *file,
1384 const char *filename)
1386 if (!gdb_python_initialized)
1389 gdbpy_enter enter_py (objfile->arch (), current_language);
1390 scoped_restore restire_current_objfile
1391 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1393 python_run_simple_file (file, filename);
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
1403 gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
1404 struct objfile *objfile, const char *name,
1407 if (!gdb_python_initialized)
1410 gdbpy_enter enter_py (objfile->arch (), current_language);
1411 scoped_restore restire_current_objfile
1412 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1414 PyRun_SimpleString (script);
1417 /* Return the current Objfile, or None if there isn't one. */
1420 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1422 if (! gdbpy_current_objfile)
1425 return objfile_to_objfile_object (gdbpy_current_objfile).release ();
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". */
1434 gdbpy_start_type_printers (const struct extension_language_defn *extlang,
1435 struct ext_lang_type_printers *ext_printers)
1437 PyObject *printers_obj = NULL;
1439 if (!gdb_python_initialized)
1442 gdbpy_enter enter_py (get_current_arch (), current_language);
1444 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1445 if (type_module == NULL)
1447 gdbpy_print_stack ();
1451 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1452 "get_type_recognizers"));
1455 gdbpy_print_stack ();
1459 printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
1460 if (printers_obj == NULL)
1461 gdbpy_print_stack ();
1463 ext_printers->py_type_printers = printers_obj;
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". */
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)
1478 PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
1479 gdb::unique_xmalloc_ptr<char> result;
1481 if (printers_obj == NULL)
1482 return EXT_LANG_RC_NOP;
1484 if (!gdb_python_initialized)
1485 return EXT_LANG_RC_NOP;
1487 gdbpy_enter enter_py (get_current_arch (), current_language);
1489 gdbpy_ref<> type_obj (type_to_type_object (type));
1490 if (type_obj == NULL)
1492 gdbpy_print_stack ();
1493 return EXT_LANG_RC_ERROR;
1496 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1497 if (type_module == NULL)
1499 gdbpy_print_stack ();
1500 return EXT_LANG_RC_ERROR;
1503 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1504 "apply_type_recognizers"));
1507 gdbpy_print_stack ();
1508 return EXT_LANG_RC_ERROR;
1511 gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
1515 if (result_obj == NULL)
1517 gdbpy_print_stack ();
1518 return EXT_LANG_RC_ERROR;
1521 if (result_obj == Py_None)
1522 return EXT_LANG_RC_NOP;
1524 result = python_string_to_host_string (result_obj.get ());
1527 gdbpy_print_stack ();
1528 return EXT_LANG_RC_ERROR;
1531 *prettied_type = result.release ();
1532 return EXT_LANG_RC_OK;
1535 /* Free the result of start_type_printers.
1536 This is the extension_language_ops.free_type_printers "method". */
1539 gdbpy_free_type_printers (const struct extension_language_defn *extlang,
1540 struct ext_lang_type_printers *ext_printers)
1542 PyObject *printers = (PyObject *) ext_printers->py_type_printers;
1544 if (printers == NULL)
1547 if (!gdb_python_initialized)
1550 gdbpy_enter enter_py (get_current_arch (), current_language);
1551 Py_DECREF (printers);
1554 #else /* HAVE_PYTHON */
1556 /* Dummy implementation of the gdb "python-interactive" and "python"
1560 python_interactive_command (const char *arg, int from_tty)
1562 arg = skip_spaces (arg);
1564 error (_("Python scripting is not supported in this copy of GDB."));
1567 counted_command_line l = get_command_line (python_control, "");
1569 execute_control_command_untraced (l.get ());
1574 python_command (const char *arg, int from_tty)
1576 python_interactive_command (arg, from_tty);
1579 #endif /* HAVE_PYTHON */
1583 /* Lists for 'set python' commands. */
1585 static struct cmd_list_element *user_set_python_list;
1586 static struct cmd_list_element *user_show_python_list;
1588 /* Initialize the Python code. */
1592 /* This is installed as a final cleanup and cleans up the
1593 interpreter. This lets Python's 'atexit' work. */
1596 finalize_python (void *ignore)
1598 struct active_ext_lang_state *previous_active;
1600 /* We don't use ensure_python_env here because if we ever ran the
1601 cleanup, gdb would crash -- because the cleanup calls into the
1602 Python interpreter, which we are about to destroy. It seems
1603 clearer to make the needed calls explicitly here than to create a
1604 cleanup and then mysteriously discard it. */
1606 /* This is only called as a final cleanup so we can assume the active
1607 SIGINT handler is gdb's. We still need to tell it to notify Python. */
1608 previous_active = set_active_ext_lang (&extension_language_python);
1610 (void) PyGILState_Ensure ();
1611 python_gdbarch = target_gdbarch ();
1612 python_language = current_language;
1616 gdb_python_initialized = false;
1617 restore_active_ext_lang (previous_active);
1621 static struct PyModuleDef python_GdbModuleDef =
1623 PyModuleDef_HEAD_INIT,
1634 /* This is called via the PyImport_AppendInittab mechanism called
1635 during initialization, to make the built-in _gdb module known to
1637 PyMODINIT_FUNC init__gdb_module (void);
1639 init__gdb_module (void)
1641 return PyModule_Create (&python_GdbModuleDef);
1646 do_start_initialization ()
1648 #ifdef WITH_PYTHON_PATH
1649 /* Work around problem where python gets confused about where it is,
1650 and then can't find its libraries, etc.
1651 NOTE: Python assumes the following layout:
1653 /foo/lib/pythonX.Y/...
1654 This must be done before calling Py_Initialize. */
1655 gdb::unique_xmalloc_ptr<char> progname
1656 (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
1657 SLASH_STRING, "python", (char *) NULL));
1659 /* Python documentation indicates that the memory given
1660 to Py_SetProgramName cannot be freed. However, it seems that
1661 at least Python 3.7.4 Py_SetProgramName takes a copy of the
1662 given program_name. Making progname_copy static and not release
1663 the memory avoids a leak report for Python versions that duplicate
1664 program_name, and respect the requirement of Py_SetProgramName
1665 for Python versions that do not duplicate program_name. */
1666 static wchar_t *progname_copy;
1668 std::string oldloc = setlocale (LC_ALL, NULL);
1669 setlocale (LC_ALL, "");
1670 size_t progsize = strlen (progname.get ());
1671 progname_copy = XNEWVEC (wchar_t, progsize + 1);
1672 size_t count = mbstowcs (progname_copy, progname.get (), progsize + 1);
1673 if (count == (size_t) -1)
1675 fprintf (stderr, "Could not convert python path to string\n");
1678 setlocale (LC_ALL, oldloc.c_str ());
1680 /* Note that Py_SetProgramName expects the string it is passed to
1681 remain alive for the duration of the program's execution, so
1682 it is not freed after this call. */
1683 Py_SetProgramName (progname_copy);
1685 /* Define _gdb as a built-in module. */
1686 PyImport_AppendInittab ("_gdb", init__gdb_module);
1688 Py_SetProgramName (progname.release ());
1693 #if PY_VERSION_HEX < 0x03090000
1694 /* PyEval_InitThreads became deprecated in Python 3.9 and will
1695 be removed in Python 3.11. Prior to Python 3.7, this call was
1696 required to initialize the GIL. */
1697 PyEval_InitThreads ();
1701 gdb_module = PyImport_ImportModule ("_gdb");
1703 gdb_module = Py_InitModule ("_gdb", python_GdbMethods);
1705 if (gdb_module == NULL)
1708 if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
1709 || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
1710 || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1714 /* Add stream constants. */
1715 if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
1716 || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
1717 || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
1720 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1721 if (gdbpy_gdb_error == NULL
1722 || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
1725 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1726 gdbpy_gdb_error, NULL);
1727 if (gdbpy_gdb_memory_error == NULL
1728 || gdb_pymodule_addobject (gdb_module, "MemoryError",
1729 gdbpy_gdb_memory_error) < 0)
1732 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1733 if (gdbpy_gdberror_exc == NULL
1734 || gdb_pymodule_addobject (gdb_module, "GdbError",
1735 gdbpy_gdberror_exc) < 0)
1738 gdbpy_initialize_gdb_readline ();
1740 if (gdbpy_initialize_auto_load () < 0
1741 || gdbpy_initialize_values () < 0
1742 || gdbpy_initialize_frames () < 0
1743 || gdbpy_initialize_commands () < 0
1744 || gdbpy_initialize_instruction () < 0
1745 || gdbpy_initialize_record () < 0
1746 || gdbpy_initialize_btrace () < 0
1747 || gdbpy_initialize_symbols () < 0
1748 || gdbpy_initialize_symtabs () < 0
1749 || gdbpy_initialize_blocks () < 0
1750 || gdbpy_initialize_functions () < 0
1751 || gdbpy_initialize_parameters () < 0
1752 || gdbpy_initialize_types () < 0
1753 || gdbpy_initialize_pspace () < 0
1754 || gdbpy_initialize_objfile () < 0
1755 || gdbpy_initialize_breakpoints () < 0
1756 || gdbpy_initialize_finishbreakpoints () < 0
1757 || gdbpy_initialize_lazy_string () < 0
1758 || gdbpy_initialize_linetable () < 0
1759 || gdbpy_initialize_thread () < 0
1760 || gdbpy_initialize_inferior () < 0
1761 || gdbpy_initialize_eventregistry () < 0
1762 || gdbpy_initialize_py_events () < 0
1763 || gdbpy_initialize_event () < 0
1764 || gdbpy_initialize_arch () < 0
1765 || gdbpy_initialize_registers () < 0
1766 || gdbpy_initialize_xmethods () < 0
1767 || gdbpy_initialize_unwind () < 0
1768 || gdbpy_initialize_tui () < 0)
1771 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
1772 if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
1774 #include "py-event-types.def"
1775 #undef GDB_PY_DEFINE_EVENT_TYPE
1777 gdbpy_to_string_cst = PyString_FromString ("to_string");
1778 if (gdbpy_to_string_cst == NULL)
1780 gdbpy_children_cst = PyString_FromString ("children");
1781 if (gdbpy_children_cst == NULL)
1783 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1784 if (gdbpy_display_hint_cst == NULL)
1786 gdbpy_doc_cst = PyString_FromString ("__doc__");
1787 if (gdbpy_doc_cst == NULL)
1789 gdbpy_enabled_cst = PyString_FromString ("enabled");
1790 if (gdbpy_enabled_cst == NULL)
1792 gdbpy_value_cst = PyString_FromString ("value");
1793 if (gdbpy_value_cst == NULL)
1796 /* Release the GIL while gdb runs. */
1797 PyEval_SaveThread ();
1799 make_final_cleanup (finalize_python, NULL);
1801 /* Only set this when initialization has succeeded. */
1802 gdb_python_initialized = 1;
1806 #endif /* HAVE_PYTHON */
1809 cmd_list_element *python_cmd_element = nullptr;
1811 void _initialize_python ();
1813 _initialize_python ()
1815 add_com ("python-interactive", class_obscure,
1816 python_interactive_command,
1819 Start an interactive Python prompt.\n\
1821 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1824 Alternatively, a single-line Python command can be given as an\n\
1825 argument, and if the command is an expression, the result will be\n\
1826 printed. For example:\n\
1828 (gdb) python-interactive 2 + 3\n\
1830 #else /* HAVE_PYTHON */
1832 Start a Python interactive prompt.\n\
1834 Python scripting is not supported in this copy of GDB.\n\
1835 This command is only a placeholder.")
1836 #endif /* HAVE_PYTHON */
1838 add_com_alias ("pi", "python-interactive", class_obscure, 1);
1840 python_cmd_element = add_com ("python", class_obscure, python_command,
1843 Evaluate a Python command.\n\
1845 The command can be given as an argument, for instance:\n\
1847 python print (23)\n\
1849 If no argument is given, the following lines are read and used\n\
1850 as the Python commands. Type a line containing \"end\" to indicate\n\
1851 the end of the command.")
1852 #else /* HAVE_PYTHON */
1854 Evaluate a Python command.\n\
1856 Python scripting is not supported in this copy of GDB.\n\
1857 This command is only a placeholder.")
1858 #endif /* HAVE_PYTHON */
1860 add_com_alias ("py", "python", class_obscure, 1);
1862 /* Add set/show python print-stack. */
1863 add_basic_prefix_cmd ("python", no_class,
1864 _("Prefix command for python preference settings."),
1865 &user_show_python_list, "show python ", 0,
1868 add_show_prefix_cmd ("python", no_class,
1869 _("Prefix command for python preference settings."),
1870 &user_set_python_list, "set python ", 0,
1873 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1874 &gdbpy_should_print_stack, _("\
1875 Set mode for Python stack dump on error."), _("\
1876 Show the mode of Python stack printing on error."), _("\
1877 none == no stack or message will be printed.\n\
1878 full == a message and a stack will be printed.\n\
1879 message == an error message without a stack will be printed."),
1881 &user_set_python_list,
1882 &user_show_python_list);
1887 /* Helper function for gdbpy_initialize. This does the work and then
1888 returns false if an error has occurred and must be displayed, or true on
1892 do_initialize (const struct extension_language_defn *extlang)
1897 /* Add the initial data-directory to sys.path. */
1899 std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
1902 sys_path = PySys_GetObject ("path");
1904 /* If sys.path is not defined yet, define it first. */
1905 if (!(sys_path && PyList_Check (sys_path)))
1908 PySys_SetPath (L"");
1912 sys_path = PySys_GetObject ("path");
1914 if (sys_path && PyList_Check (sys_path))
1916 gdbpy_ref<> pythondir (PyString_FromString (gdb_pythondir.c_str ()));
1917 if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
1923 /* Import the gdb module to finish the initialization, and
1924 add it to __main__ for convenience. */
1925 m = PyImport_AddModule ("__main__");
1929 /* Keep the reference to gdb_python_module since it is in a global
1931 gdb_python_module = PyImport_ImportModule ("gdb");
1932 if (gdb_python_module == NULL)
1934 gdbpy_print_stack ();
1935 /* This is passed in one call to warning so that blank lines aren't
1936 inserted between each line of text. */
1938 "Could not load the Python gdb module from `%s'.\n"
1939 "Limited Python support is available from the _gdb module.\n"
1940 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
1941 gdb_pythondir.c_str ());
1942 /* We return "success" here as we've already emitted the
1947 return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
1950 /* Perform Python initialization. This will be called after GDB has
1951 performed all of its own initialization. This is the
1952 extension_language_ops.initialize "method". */
1955 gdbpy_initialize (const struct extension_language_defn *extlang)
1957 if (!do_start_initialization () && PyErr_Occurred ())
1958 gdbpy_print_stack ();
1960 gdbpy_enter enter_py (get_current_arch (), current_language);
1962 if (!do_initialize (extlang))
1964 gdbpy_print_stack ();
1965 warning (_("internal error: Unhandled Python exception"));
1969 /* Return non-zero if Python has successfully initialized.
1970 This is the extension_languages_ops.initialized "method". */
1973 gdbpy_initialized (const struct extension_language_defn *extlang)
1975 return gdb_python_initialized;
1978 PyMethodDef python_GdbMethods[] =
1980 { "history", gdbpy_history, METH_VARARGS,
1981 "Get a value from history" },
1982 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1983 "execute (command [, from_tty] [, to_string]) -> [String]\n\
1984 Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
1985 a Python String containing the output of the command if to_string is\n\
1987 { "parameter", gdbpy_parameter, METH_VARARGS,
1988 "Return a gdb parameter's value" },
1990 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1991 "Return a tuple of all breakpoint objects" },
1993 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1994 "Find the default visualizer for a Value." },
1996 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1997 "Return a sequence of all progspaces." },
1999 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
2000 "Return the current Objfile being loaded, or None." },
2002 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
2003 "newest_frame () -> gdb.Frame.\n\
2004 Return the newest frame object." },
2005 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
2006 "selected_frame () -> gdb.Frame.\n\
2007 Return the selected frame object." },
2008 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
2009 "stop_reason_string (Integer) -> String.\n\
2010 Return a string explaining unwind stop reason." },
2012 { "start_recording", gdbpy_start_recording, METH_VARARGS,
2013 "start_recording ([method] [, format]) -> gdb.Record.\n\
2014 Start recording with the given method. If no method is given, will fall back\n\
2015 to the system default method. If no format is given, will fall back to the\n\
2016 default format for the given method."},
2017 { "current_recording", gdbpy_current_recording, METH_NOARGS,
2018 "current_recording () -> gdb.Record.\n\
2019 Return current recording object." },
2020 { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
2021 "stop_recording () -> None.\n\
2022 Stop current recording." },
2024 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
2025 METH_VARARGS | METH_KEYWORDS,
2026 "lookup_type (name [, block]) -> type\n\
2027 Return a Type corresponding to the given name." },
2028 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
2029 METH_VARARGS | METH_KEYWORDS,
2030 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
2031 Return a tuple with the symbol corresponding to the given name (or None) and\n\
2032 a boolean indicating if name is a field of the current implied argument\n\
2033 `this' (when the current language is object-oriented)." },
2034 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
2035 METH_VARARGS | METH_KEYWORDS,
2036 "lookup_global_symbol (name [, domain]) -> symbol\n\
2037 Return the symbol corresponding to the given name (or None)." },
2038 { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
2039 METH_VARARGS | METH_KEYWORDS,
2040 "lookup_static_symbol (name [, domain]) -> symbol\n\
2041 Return the static-linkage symbol corresponding to the given name (or None)." },
2042 { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
2043 METH_VARARGS | METH_KEYWORDS,
2044 "lookup_static_symbols (name [, domain]) -> symbol\n\
2045 Return a list of all static-linkage symbols corresponding to the given name." },
2047 { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
2048 METH_VARARGS | METH_KEYWORDS,
2049 "lookup_objfile (name, [by_build_id]) -> objfile\n\
2050 Look up the specified objfile.\n\
2051 If by_build_id is True, the objfile is looked up by using name\n\
2052 as its build id." },
2054 { "decode_line", gdbpy_decode_line, METH_VARARGS,
2055 "decode_line (String) -> Tuple. Decode a string argument the way\n\
2056 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
2057 The first element contains any unparsed portion of the String parameter\n\
2058 (or None if the string was fully parsed). The second element contains\n\
2059 a tuple that contains all the locations that match, represented as\n\
2060 gdb.Symtab_and_line objects (or None)."},
2061 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
2062 "parse_and_eval (String) -> Value.\n\
2063 Parse String as an expression, evaluate it, and return the result as a Value."
2066 { "post_event", gdbpy_post_event, METH_VARARGS,
2067 "Post an event into gdb's event loop." },
2069 { "target_charset", gdbpy_target_charset, METH_NOARGS,
2070 "target_charset () -> string.\n\
2071 Return the name of the current target charset." },
2072 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
2073 "target_wide_charset () -> string.\n\
2074 Return the name of the current target wide charset." },
2075 { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
2076 "rbreak (Regex) -> List.\n\
2077 Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
2078 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
2079 "string_to_argv (String) -> Array.\n\
2080 Parse String and return an argv-like array.\n\
2081 Arguments are separate by spaces and may be quoted."
2083 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
2084 "Write a string using gdb's filtered stream." },
2085 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
2086 "Flush gdb's filtered stdout stream." },
2087 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
2088 "selected_thread () -> gdb.InferiorThread.\n\
2089 Return the selected thread object." },
2090 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
2091 "selected_inferior () -> gdb.Inferior.\n\
2092 Return the selected inferior object." },
2093 { "inferiors", gdbpy_inferiors, METH_NOARGS,
2094 "inferiors () -> (gdb.Inferior, ...).\n\
2095 Return a tuple containing all inferiors." },
2097 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
2098 "invalidate_cached_frames () -> None.\n\
2099 Invalidate any cached frame objects in gdb.\n\
2100 Intended for internal use only." },
2102 { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
2103 "convenience_variable (NAME) -> value.\n\
2104 Return the value of the convenience variable $NAME,\n\
2105 or None if not set." },
2106 { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
2107 "convenience_variable (NAME, VALUE) -> None.\n\
2108 Set the value of the convenience variable $NAME." },
2111 { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
2112 METH_VARARGS | METH_KEYWORDS,
2113 "register_window_type (NAME, CONSTRUCSTOR) -> None\n\
2114 Register a TUI window constructor." },
2117 {NULL, NULL, 0, NULL}
2120 /* Define all the event objects. */
2121 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2122 PyTypeObject name##_event_object_type \
2123 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
2125 PyVarObject_HEAD_INIT (NULL, 0) \
2126 "gdb." py_name, /* tp_name */ \
2127 sizeof (event_object), /* tp_basicsize */ \
2128 0, /* tp_itemsize */ \
2129 evpy_dealloc, /* tp_dealloc */ \
2131 0, /* tp_getattr */ \
2132 0, /* tp_setattr */ \
2133 0, /* tp_compare */ \
2135 0, /* tp_as_number */ \
2136 0, /* tp_as_sequence */ \
2137 0, /* tp_as_mapping */ \
2141 0, /* tp_getattro */ \
2142 0, /* tp_setattro */ \
2143 0, /* tp_as_buffer */ \
2144 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
2146 0, /* tp_traverse */ \
2148 0, /* tp_richcompare */ \
2149 0, /* tp_weaklistoffset */ \
2151 0, /* tp_iternext */ \
2152 0, /* tp_methods */ \
2153 0, /* tp_members */ \
2154 0, /* tp_getset */ \
2155 &base, /* tp_base */ \
2157 0, /* tp_descr_get */ \
2158 0, /* tp_descr_set */ \
2159 0, /* tp_dictoffset */ \
2163 #include "py-event-types.def"
2164 #undef GDB_PY_DEFINE_EVENT_TYPE
2166 #endif /* HAVE_PYTHON */