1 /* General python/gdb code
3 Copyright (C) 2008-2025 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/>. */
20 #include "arch-utils.h"
23 #include "cli/cli-script.h"
24 #include "cli/cli-cmds.h"
25 #include "progspace.h"
29 #include "gdbsupport/event-loop.h"
30 #include "readline/tilde.h"
32 #include "extension-priv.h"
33 #include "cli/cli-utils.h"
36 #include "run-on-main-thread.h"
37 #include "observable.h"
39 #include "cli/cli-style.h"
42 #include "gdbsupport/selftest.h"
45 /* Declared constants and enum for python stack printing. */
46 static const char python_excp_none
[] = "none";
47 static const char python_excp_full
[] = "full";
48 static const char python_excp_message
[] = "message";
50 /* "set python print-stack" choices. */
51 static const char *const python_excp_enums
[] =
59 /* The exception printing variable. 'full' if we want to print the
60 error message and stack, 'none' if we want to print nothing, and
61 'message' if we only want to print the error message. 'message' is
63 static const char *gdbpy_should_print_stack
= python_excp_message
;
68 #include "cli/cli-decode.h"
72 #include "python-internal.h"
75 #include "gdbsupport/version.h"
77 #include "gdbthread.h"
79 #include "event-top.h"
83 /* True if Python has been successfully initialized, false
86 int gdb_python_initialized
;
88 extern PyMethodDef python_GdbMethods
[];
91 PyObject
*gdb_python_module
;
93 /* Some string constants we may wish to use. */
94 PyObject
*gdbpy_to_string_cst
;
95 PyObject
*gdbpy_children_cst
;
96 PyObject
*gdbpy_display_hint_cst
;
97 PyObject
*gdbpy_doc_cst
;
98 PyObject
*gdbpy_enabled_cst
;
99 PyObject
*gdbpy_value_cst
;
101 /* The GdbError exception. */
102 PyObject
*gdbpy_gdberror_exc
;
104 /* The `gdb.error' base class. */
105 PyObject
*gdbpy_gdb_error
;
107 /* The `gdb.MemoryError' exception. */
108 PyObject
*gdbpy_gdb_memory_error
;
110 static script_sourcer_func gdbpy_source_script
;
111 static objfile_script_sourcer_func gdbpy_source_objfile_script
;
112 static objfile_script_executor_func gdbpy_execute_objfile_script
;
113 static void gdbpy_initialize (const struct extension_language_defn
*);
114 static int gdbpy_initialized (const struct extension_language_defn
*);
115 static void finalize_python (const struct extension_language_defn
*);
116 static void gdbpy_eval_from_control_command
117 (const struct extension_language_defn
*, struct command_line
*cmd
);
118 static void gdbpy_start_type_printers (const struct extension_language_defn
*,
119 struct ext_lang_type_printers
*);
120 static enum ext_lang_rc gdbpy_apply_type_printers
121 (const struct extension_language_defn
*,
122 const struct ext_lang_type_printers
*, struct type
*,
123 gdb::unique_xmalloc_ptr
<char> *);
124 static void gdbpy_free_type_printers (const struct extension_language_defn
*,
125 struct ext_lang_type_printers
*);
126 static void gdbpy_set_quit_flag (const struct extension_language_defn
*);
127 static bool gdbpy_check_quit_flag (const struct extension_language_defn
*);
128 static enum ext_lang_rc gdbpy_before_prompt_hook
129 (const struct extension_language_defn
*, const char *current_gdb_prompt
);
130 static std::optional
<std::string
> gdbpy_colorize
131 (const std::string
&filename
, const std::string
&contents
,
133 static std::optional
<std::string
> gdbpy_colorize_disasm
134 (const std::string
&content
, gdbarch
*gdbarch
);
135 static ext_lang_missing_file_result gdbpy_handle_missing_debuginfo
136 (const struct extension_language_defn
*extlang
, struct objfile
*objfile
);
137 static ext_lang_missing_file_result gdbpy_find_objfile_from_buildid
138 (const struct extension_language_defn
*extlang
, program_space
*pspace
,
139 const struct bfd_build_id
*build_id
, const char *missing_filename
);
141 /* The interface between gdb proper and loading of python scripts. */
143 static const struct extension_language_script_ops python_extension_script_ops
=
146 gdbpy_source_objfile_script
,
147 gdbpy_execute_objfile_script
,
148 gdbpy_auto_load_enabled
151 /* The interface between gdb proper and python extensions. */
153 static const struct extension_language_ops python_extension_ops
=
159 gdbpy_eval_from_control_command
,
161 gdbpy_start_type_printers
,
162 gdbpy_apply_type_printers
,
163 gdbpy_free_type_printers
,
165 gdbpy_apply_val_pretty_printer
,
167 gdbpy_apply_frame_filter
,
169 gdbpy_load_ptwrite_filter
,
171 gdbpy_preserve_values
,
173 gdbpy_breakpoint_has_cond
,
174 gdbpy_breakpoint_cond_says_stop
,
177 gdbpy_check_quit_flag
,
179 gdbpy_before_prompt_hook
,
181 gdbpy_get_matching_xmethod_workers
,
185 gdbpy_colorize_disasm
,
189 gdbpy_handle_missing_debuginfo
,
190 gdbpy_find_objfile_from_buildid
193 #endif /* HAVE_PYTHON */
195 /* The main struct describing GDB's interface to the Python
196 extension language. */
197 const struct extension_language_defn extension_language_python
=
209 &python_extension_script_ops
,
210 &python_extension_ops
219 /* Architecture and language to be used in callbacks from
220 the Python interpreter. */
221 struct gdbarch
*gdbpy_enter::python_gdbarch
;
223 gdbpy_enter::gdbpy_enter (struct gdbarch
*gdbarch
,
224 const struct language_defn
*language
)
225 : m_gdbarch (python_gdbarch
),
226 m_language (language
== nullptr ? nullptr : current_language
)
228 /* We should not ever enter Python unless initialized. */
229 if (!gdb_python_initialized
)
230 error (_("Python not initialized"));
232 m_previous_active
= set_active_ext_lang (&extension_language_python
);
234 m_state
= PyGILState_Ensure ();
236 python_gdbarch
= gdbarch
;
237 if (language
!= nullptr)
238 set_language (language
->la_language
);
240 /* Save it and ensure ! PyErr_Occurred () afterwards. */
244 gdbpy_enter::~gdbpy_enter ()
246 /* Leftover Python error is forbidden by Python Exception Handling. */
247 if (PyErr_Occurred ())
249 /* This order is similar to the one calling error afterwards. */
250 gdbpy_print_stack ();
251 warning (_("internal error: Unhandled Python exception"));
256 python_gdbarch
= m_gdbarch
;
257 if (m_language
!= nullptr)
258 set_language (m_language
->la_language
);
260 restore_active_ext_lang (m_previous_active
);
261 PyGILState_Release (m_state
);
265 gdbpy_enter::get_gdbarch ()
267 if (python_gdbarch
!= nullptr)
268 return python_gdbarch
;
269 return get_current_arch ();
273 gdbpy_enter::finalize ()
275 python_gdbarch
= current_inferior ()->arch ();
278 /* Set the quit flag. */
281 gdbpy_set_quit_flag (const struct extension_language_defn
*extlang
)
283 PyErr_SetInterrupt ();
286 /* Return true if the quit flag has been set, false otherwise. */
289 gdbpy_check_quit_flag (const struct extension_language_defn
*extlang
)
291 if (!gdb_python_initialized
)
295 return PyOS_InterruptOccurred ();
298 /* Evaluate a Python command like PyRun_SimpleString, but takes a
299 Python start symbol, and does not automatically print the stack on
300 errors. FILENAME is used to set the file name in error messages;
301 NULL means that this is evaluating a string, not the contents of a
305 eval_python_command (const char *command
, int start_symbol
,
306 const char *filename
= nullptr)
310 m
= PyImport_AddModule ("__main__");
314 d
= PyModule_GetDict (m
);
318 bool file_set
= false;
319 if (filename
!= nullptr)
321 gdbpy_ref
<> file
= host_string_to_python_string ("__file__");
325 /* PyDict_GetItemWithError returns a borrowed reference. */
326 PyObject
*found
= PyDict_GetItemWithError (d
, file
.get ());
327 if (found
== nullptr)
329 if (PyErr_Occurred ())
332 gdbpy_ref
<> filename_obj
= host_string_to_python_string (filename
);
333 if (filename_obj
== nullptr)
336 if (PyDict_SetItem (d
, file
.get (), filename_obj
.get ()) < 0)
338 if (PyDict_SetItemString (d
, "__cached__", Py_None
) < 0)
345 /* Use this API because it is in Python 3.2. */
346 gdbpy_ref
<> code (Py_CompileStringExFlags (command
,
356 gdbpy_ref
<> eval_result (PyEval_EvalCode (code
.get (), d
, d
));
357 if (eval_result
!= nullptr)
363 /* If there's already an exception occurring, preserve it and
364 restore it before returning from this function. */
365 std::optional
<gdbpy_err_fetch
> save_error
;
367 save_error
.emplace ();
369 /* CPython also just ignores errors here. These should be
370 expected to be exceedingly rare anyway. */
371 if (PyDict_DelItemString (d
, "__file__") < 0)
373 if (PyDict_DelItemString (d
, "__cached__") < 0)
376 if (save_error
.has_value ())
377 save_error
->restore ();
383 /* Implementation of the gdb "python-interactive" command. */
386 python_interactive_command (const char *arg
, int from_tty
)
388 struct ui
*ui
= current_ui
;
391 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
, 0);
393 arg
= skip_spaces (arg
);
395 gdbpy_enter enter_py
;
399 std::string script
= std::string (arg
) + "\n";
400 /* Py_single_input causes the result to be displayed. */
401 err
= eval_python_command (script
.c_str (), Py_single_input
);
405 err
= PyRun_InteractiveLoop (ui
->instream
, "<stdin>");
410 gdbpy_handle_exception ();
413 /* Like PyRun_SimpleFile, but if there is an exception, it is not
414 automatically displayed. FILE is the Python script to run named
417 On Windows hosts few users would build Python themselves (this is no
418 trivial task on this platform), and thus use binaries built by
419 someone else instead. There may happen situation where the Python
420 library and GDB are using two different versions of the C runtime
421 library. Python, being built with VC, would use one version of the
422 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
423 A FILE * from one runtime does not necessarily operate correctly in
424 the other runtime. */
427 python_run_simple_file (FILE *file
, const char *filename
)
429 std::string contents
= read_remainder_of_file (file
);
430 return eval_python_command (contents
.c_str (), Py_file_input
, filename
);
433 /* Given a command_line, return a command string suitable for passing
434 to Python. Lines in the string are separated by newlines. */
437 compute_python_string (struct command_line
*l
)
439 struct command_line
*iter
;
442 for (iter
= l
; iter
; iter
= iter
->next
)
444 script
+= iter
->line
;
450 /* Take a command line structure representing a 'python' command, and
451 evaluate its body using the Python interpreter. */
454 gdbpy_eval_from_control_command (const struct extension_language_defn
*extlang
,
455 struct command_line
*cmd
)
457 if (cmd
->body_list_1
!= nullptr)
458 error (_("Invalid \"python\" block structure."));
460 gdbpy_enter enter_py
;
462 std::string script
= compute_python_string (cmd
->body_list_0
.get ());
463 int ret
= eval_python_command (script
.c_str (), Py_file_input
);
465 gdbpy_handle_exception ();
468 /* Implementation of the gdb "python" command. */
471 python_command (const char *arg
, int from_tty
)
473 gdbpy_enter enter_py
;
475 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
, 0);
477 arg
= skip_spaces (arg
);
480 int ret
= eval_python_command (arg
, Py_file_input
);
482 gdbpy_handle_exception ();
486 counted_command_line l
= get_command_line (python_control
, "");
488 execute_control_command_untraced (l
.get ());
494 /* Transform a gdb parameters's value into a Python value. May return
495 NULL (and set a Python exception) on error. Helper function for
498 gdbpy_parameter_value (const setting
&var
)
503 case var_string_noescape
:
504 case var_optional_filename
:
509 if (var
.type () == var_enum
)
510 str
= var
.get
<const char *> ();
512 str
= var
.get
<std::string
> ().c_str ();
514 return host_string_to_python_string (str
).release ();
519 const ui_file_style::color
&color
= var
.get
<ui_file_style::color
> ();
520 return create_color_object (color
).release ();
525 if (var
.get
<bool> ())
531 case var_auto_boolean
:
533 enum auto_boolean ab
= var
.get
<enum auto_boolean
> ();
535 if (ab
== AUTO_BOOLEAN_TRUE
)
537 else if (ab
== AUTO_BOOLEAN_FALSE
)
548 = (var
.type () == var_uinteger
549 ? static_cast<LONGEST
> (var
.get
<unsigned int> ())
550 : static_cast<LONGEST
> (var
.get
<int> ()));
552 if (var
.extra_literals () != nullptr)
553 for (const literal_def
*l
= var
.extra_literals ();
554 l
->literal
!= nullptr;
558 if (strcmp (l
->literal
, "unlimited") == 0)
560 /* Compatibility hack for API brokenness. */
561 if (var
.type () == var_pinteger
562 && l
->val
.has_value ()
568 else if (l
->val
.has_value ())
571 return host_string_to_python_string (l
->literal
).release ();
574 if (var
.type () == var_uinteger
)
576 gdb_py_object_from_ulongest
577 (static_cast<unsigned int> (value
)).release ();
580 gdb_py_object_from_longest
581 (static_cast<int> (value
)).release ();
585 return PyErr_Format (PyExc_RuntimeError
,
586 _("Programmer error: unhandled type."));
589 /* A Python function which returns a gdb parameter's value as a Python
593 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
595 struct cmd_list_element
*alias
, *prefix
, *cmd
;
599 if (! PyArg_ParseTuple (args
, "s", &arg
))
602 std::string newarg
= std::string ("show ") + arg
;
606 found
= lookup_cmd_composition (newarg
.c_str (), &alias
, &prefix
, &cmd
);
608 catch (const gdb_exception
&ex
)
610 return gdbpy_handle_gdb_exception (nullptr, ex
);
613 if (cmd
== CMD_LIST_AMBIGUOUS
)
614 return PyErr_Format (PyExc_RuntimeError
,
615 _("Parameter `%s' is ambiguous."), arg
);
617 return PyErr_Format (PyExc_RuntimeError
,
618 _("Could not find parameter `%s'."), arg
);
620 if (!cmd
->var
.has_value ())
621 return PyErr_Format (PyExc_RuntimeError
,
622 _("`%s' is not a parameter."), arg
);
624 return gdbpy_parameter_value (*cmd
->var
);
627 /* Wrapper for target_charset. */
630 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
632 const char *cset
= target_charset (gdbpy_enter::get_gdbarch ());
634 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
637 /* Wrapper for target_wide_charset. */
640 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
642 const char *cset
= target_wide_charset (gdbpy_enter::get_gdbarch ());
644 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
647 /* Implement gdb.host_charset(). */
650 gdbpy_host_charset (PyObject
*self
, PyObject
*args
)
652 const char *cset
= host_charset ();
654 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
657 /* A Python function which evaluates a string using the gdb CLI. */
660 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
663 PyObject
*from_tty_obj
= nullptr;
664 PyObject
*to_string_obj
= nullptr;
665 PyObject
*styling
= nullptr;
666 static const char *keywords
[]
667 = { "command", "from_tty", "to_string", "styling", nullptr };
669 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!O!", keywords
, &arg
,
670 &PyBool_Type
, &from_tty_obj
,
671 &PyBool_Type
, &to_string_obj
,
672 &PyBool_Type
, &styling
))
675 bool from_tty
= false;
676 if (from_tty_obj
!= nullptr)
678 int cmp
= PyObject_IsTrue (from_tty_obj
);
681 from_tty
= (cmp
!= 0);
684 bool to_string
= false;
685 if (to_string_obj
!= nullptr)
687 int cmp
= PyObject_IsTrue (to_string_obj
);
690 to_string
= (cmp
!= 0);
693 bool styling_p
= !to_string
;
694 if (styling
!= nullptr)
696 int cmp
= PyObject_IsTrue (styling
);
699 styling_p
= (cmp
!= 0);
702 std::string to_string_res
;
704 scoped_restore preventer
= prevent_dont_repeat ();
706 /* If the executed command raises an exception, we may have to
707 enable stdin and recover the GDB prompt.
709 Stdin should not be re-enabled if it is already blocked because,
710 for example, we are running a command in the context of a
711 synchronous execution command ("run", "continue", etc.). Like
715 --> command blocks the prompt
716 --> Python API is invoked, e.g. via events
717 --> gdb.execute(C) invoked inside Python
718 --> command C raises an exception
720 In this case case, GDB would go back to the top "continue" command
721 and move on with its normal course of execution. That is, it
722 would enable stdin in the way it normally does.
724 Similarly, if the command we are about to execute enables the
725 stdin while we are still in the context of a synchronous
726 execution command, we would be displaying the prompt too early,
727 before the surrounding command completes.
729 For these reasons, we keep the prompt blocked, if it already is. */
730 bool prompt_was_blocked
= (current_ui
->prompt_state
== PROMPT_BLOCKED
);
731 scoped_restore save_prompt_state
732 = make_scoped_restore (¤t_ui
->keep_prompt_blocked
,
737 gdbpy_allow_threads allow_threads
;
739 struct interp
*interp
;
741 std::string arg_copy
= arg
;
743 char *save_ptr
= nullptr;
745 = [&] (std::string
&buffer
)
747 const char *result
= strtok_r (first
? &arg_copy
[0] : nullptr,
753 counted_command_line lines
= read_command_lines_1 (reader
, 1, nullptr);
756 scoped_restore save_async
= make_scoped_restore (¤t_ui
->async
,
759 scoped_restore save_uiout
= make_scoped_restore (¤t_uiout
);
761 /* If the Python 'styling' argument was False then temporarily
762 disable styling. Otherwise, don't do anything, styling could
763 already be disabled for some other reason, we shouldn't override
764 that and force styling on. */
765 std::optional
<scoped_disable_styling
> disable_styling
;
767 disable_styling
.emplace ();
769 /* Use the console interpreter uiout to have the same print format
770 for console or MI. */
771 interp
= interp_lookup (current_ui
, "console");
772 current_uiout
= interp
->interp_ui_out ();
776 /* Pass 'true' here to always request styling, however, if
777 the scoped_disable_styling disabled styling, or the user
778 has globally disabled styling, then the output will not be
781 = execute_control_commands_to_string (lines
.get (), from_tty
,
785 execute_control_commands (lines
.get (), from_tty
);
788 /* Do any commands attached to breakpoint we stopped at. */
789 bpstat_do_actions ();
791 catch (const gdb_exception
&except
)
793 /* If an exception occurred then we won't hit normal_stop (), or have
794 an exception reach the top level of the event loop, which are the
795 two usual places in which stdin would be re-enabled. So, before we
796 convert the exception and continue back in Python, we should
797 re-enable stdin here. */
798 async_enable_stdin ();
799 return gdbpy_handle_gdb_exception (nullptr, except
);
803 return PyUnicode_Decode (to_string_res
.c_str (), to_string_res
.size (),
804 host_charset (), nullptr);
808 /* Implementation of Python rbreak command. Take a REGEX and
809 optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
810 Python list that contains newly set breakpoints that match that
811 criteria. REGEX refers to a GDB format standard regex pattern of
812 symbols names to search; MINSYMS is an optional boolean (default
813 False) that indicates if the function should search GDB's minimal
814 symbols; THROTTLE is an optional integer (default unlimited) that
815 indicates the maximum amount of breakpoints allowable before the
816 function exits (note, if the throttle bound is passed, no
817 breakpoints will be set and a runtime error returned); SYMTABS is
818 an optional Python iterable that contains a set of gdb.Symtabs to
819 constrain the search within. */
822 gdbpy_rbreak (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
825 std::vector
<symbol_search
> symbols
;
826 unsigned long count
= 0;
827 PyObject
*symtab_list
= NULL
;
828 PyObject
*minsyms_p_obj
= NULL
;
830 unsigned int throttle
= 0;
831 static const char *keywords
[] = {"regex","minsyms", "throttle",
834 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!IO", keywords
,
835 ®ex
, &PyBool_Type
,
836 &minsyms_p_obj
, &throttle
,
840 /* Parse minsyms keyword. */
841 if (minsyms_p_obj
!= NULL
)
843 int cmp
= PyObject_IsTrue (minsyms_p_obj
);
849 global_symbol_searcher
spec (SEARCH_FUNCTION_DOMAIN
, regex
);
851 /* The "symtabs" keyword is any Python iterable object that returns
852 a gdb.Symtab on each iteration. If specified, iterate through
853 the provided gdb.Symtabs and extract their full path. As
854 python_string_to_target_string returns a
855 gdb::unique_xmalloc_ptr<char> and a vector containing these types
856 cannot be coerced to a const char **p[] via the vector.data call,
857 release the value from the unique_xmalloc_ptr and place it in a
858 simple type symtab_list_type (which holds the vector and a
859 destructor that frees the contents of the allocated strings. */
860 if (symtab_list
!= NULL
)
862 gdbpy_ref
<> iter (PyObject_GetIter (symtab_list
));
869 gdbpy_ref
<> next (PyIter_Next (iter
.get ()));
873 if (PyErr_Occurred ())
878 gdbpy_ref
<> obj_name (PyObject_GetAttrString (next
.get (),
881 if (obj_name
== NULL
)
884 /* Is the object file still valid? */
885 if (obj_name
== Py_None
)
888 gdb::unique_xmalloc_ptr
<char> filename
=
889 python_string_to_target_string (obj_name
.get ());
891 if (filename
== NULL
)
894 spec
.add_filename (std::move (filename
));
898 /* The search spec. */
899 symbols
= spec
.search ();
901 /* Count the number of symbols (both symbols and optionally minimal
902 symbols) so we can correctly check the throttle limit. */
903 for (const symbol_search
&p
: symbols
)
905 /* Minimal symbols included? */
908 if (p
.msymbol
.minsym
!= NULL
)
912 if (p
.symbol
!= NULL
)
916 /* Check throttle bounds and exit if in excess. */
917 if (throttle
!= 0 && count
> throttle
)
919 PyErr_SetString (PyExc_RuntimeError
,
920 _("Number of breakpoints exceeds throttled maximum."));
924 gdbpy_ref
<> return_list (PyList_New (0));
926 if (return_list
== NULL
)
929 /* Construct full path names for symbols and call the Python
930 breakpoint constructor on the resulting names. Be tolerant of
931 individual breakpoint failures. */
932 for (const symbol_search
&p
: symbols
)
934 std::string symbol_name
;
936 /* Skipping minimal symbols? */
938 if (p
.msymbol
.minsym
!= NULL
)
941 if (p
.msymbol
.minsym
== NULL
)
943 struct symtab
*symtab
= p
.symbol
->symtab ();
944 const char *fullname
= symtab_to_fullname (symtab
);
946 symbol_name
= fullname
;
948 symbol_name
+= p
.symbol
->linkage_name ();
951 symbol_name
= p
.msymbol
.minsym
->linkage_name ();
953 gdbpy_ref
<> argList (Py_BuildValue("(s)", symbol_name
.c_str ()));
954 gdbpy_ref
<> obj (PyObject_CallObject ((PyObject
*)
955 &breakpoint_object_type
,
958 /* Tolerate individual breakpoint failures. */
960 gdbpy_print_stack ();
963 if (PyList_Append (return_list
.get (), obj
.get ()) == -1)
967 return return_list
.release ();
970 /* A Python function which is a wrapper for decode_line_1. */
973 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
975 const char *arg
= NULL
;
977 gdbpy_ref
<> unparsed
;
978 location_spec_up locspec
;
980 if (! PyArg_ParseTuple (args
, "|s", &arg
))
983 /* Treat a string consisting of just whitespace the same as
987 arg
= skip_spaces (arg
);
993 locspec
= string_to_location_spec_basic (&arg
, current_language
,
994 symbol_name_match_type::WILD
);
996 std::vector
<symtab_and_line
> decoded_sals
;
997 symtab_and_line def_sal
;
998 gdb::array_view
<symtab_and_line
> sals
;
1001 if (locspec
!= NULL
)
1003 decoded_sals
= decode_line_1 (locspec
.get (), 0, NULL
, NULL
, 0);
1004 sals
= decoded_sals
;
1008 set_default_source_symtab_and_line ();
1009 def_sal
= get_current_source_symtab_and_line (current_program_space
);
1013 catch (const gdb_exception
&ex
)
1015 /* We know this will always throw. */
1016 return gdbpy_handle_gdb_exception (nullptr, ex
);
1021 result
.reset (PyTuple_New (sals
.size ()));
1024 for (size_t i
= 0; i
< sals
.size (); ++i
)
1026 PyObject
*obj
= symtab_and_line_to_sal_object (sals
[i
]);
1030 PyTuple_SetItem (result
.get (), i
, obj
);
1034 result
= gdbpy_ref
<>::new_reference (Py_None
);
1036 gdbpy_ref
<> return_result (PyTuple_New (2));
1037 if (return_result
== NULL
)
1040 if (arg
!= NULL
&& strlen (arg
) > 0)
1042 unparsed
.reset (PyUnicode_FromString (arg
));
1043 if (unparsed
== NULL
)
1047 unparsed
= gdbpy_ref
<>::new_reference (Py_None
);
1049 PyTuple_SetItem (return_result
.get (), 0, unparsed
.release ());
1050 PyTuple_SetItem (return_result
.get (), 1, result
.release ());
1052 return return_result
.release ();
1055 /* Parse a string and evaluate it as an expression. */
1057 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1059 static const char *keywords
[] = { "expression", "global_context", nullptr };
1061 const char *expr_str
;
1062 PyObject
*global_context_obj
= nullptr;
1064 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!", keywords
,
1066 &PyBool_Type
, &global_context_obj
))
1069 parser_flags flags
= 0;
1070 if (global_context_obj
!= NULL
)
1072 int cmp
= PyObject_IsTrue (global_context_obj
);
1076 flags
|= PARSER_LEAVE_BLOCK_ALONE
;
1079 PyObject
*result
= nullptr;
1082 scoped_value_mark free_values
;
1085 /* Allow other Python threads to run while we're evaluating
1086 the expression. This is important because the expression
1087 could involve inferior calls or otherwise be a lengthy
1088 calculation. We take care here to re-acquire the GIL here
1089 before continuing with Python work. */
1090 gdbpy_allow_threads allow_threads
;
1091 val
= parse_and_eval (expr_str
, flags
);
1093 result
= value_to_value_object (val
);
1095 catch (const gdb_exception
&except
)
1097 return gdbpy_handle_gdb_exception (nullptr, except
);
1103 /* Implementation of gdb.invalidate_cached_frames. */
1106 gdbpy_invalidate_cached_frames (PyObject
*self
, PyObject
*args
)
1108 reinit_frame_cache ();
1112 /* Read a file as Python code.
1113 This is the extension_language_script_ops.script_sourcer "method".
1114 FILE is the file to load. FILENAME is name of the file FILE.
1115 This does not throw any errors. If an exception occurs python will print
1116 the traceback and clear the error indicator. */
1119 gdbpy_source_script (const struct extension_language_defn
*extlang
,
1120 FILE *file
, const char *filename
)
1122 gdbpy_enter enter_py
;
1123 int result
= python_run_simple_file (file
, filename
);
1125 gdbpy_handle_exception ();
1130 /* Posting and handling events. */
1132 /* A single event. */
1135 gdbpy_event (gdbpy_ref
<> &&func
)
1136 : m_func (func
.release ())
1140 gdbpy_event (gdbpy_event
&&other
) noexcept
1141 : m_func (other
.m_func
)
1143 other
.m_func
= nullptr;
1146 gdbpy_event (const gdbpy_event
&other
)
1147 : m_func (other
.m_func
)
1150 Py_XINCREF (m_func
);
1156 Py_XDECREF (m_func
);
1159 gdbpy_event
&operator= (const gdbpy_event
&other
) = delete;
1163 gdbpy_enter enter_py
;
1165 gdbpy_ref
<> call_result (PyObject_CallObject (m_func
, NULL
));
1166 if (call_result
== NULL
)
1167 gdbpy_print_stack ();
1172 /* The Python event. This is just a callable object. Note that
1173 this is not a gdbpy_ref<>, because we have to take particular
1174 care to only destroy the reference when holding the GIL. */
1178 /* Submit an event to the gdb thread. */
1180 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
1184 if (!PyArg_ParseTuple (args
, "O", &func
))
1187 if (!PyCallable_Check (func
))
1189 PyErr_SetString (PyExc_RuntimeError
,
1190 _("Posted event is not callable"));
1194 gdbpy_ref
<> func_ref
= gdbpy_ref
<>::new_reference (func
);
1195 gdbpy_event
event (std::move (func_ref
));
1196 run_on_main_thread (event
);
1201 /* Interrupt the current operation on the main thread. */
1203 gdbpy_interrupt (PyObject
*self
, PyObject
*args
)
1206 /* Make sure the interrupt isn't delivered immediately somehow.
1207 This probably is not truly needed, but at the same time it
1208 seems more clear to be explicit about the intent. */
1209 gdbpy_allow_threads temporarily_exit_python
;
1210 scoped_disable_cooperative_sigint_handling no_python_sigint
;
1220 /* This is the extension_language_ops.before_prompt "method". */
1222 static enum ext_lang_rc
1223 gdbpy_before_prompt_hook (const struct extension_language_defn
*extlang
,
1224 const char *current_gdb_prompt
)
1226 if (!gdb_python_initialized
)
1227 return EXT_LANG_RC_NOP
;
1229 gdbpy_enter enter_py
;
1231 if (!evregpy_no_listeners_p (gdb_py_events
.before_prompt
)
1232 && evpy_emit_event (NULL
, gdb_py_events
.before_prompt
) < 0)
1233 return EXT_LANG_RC_ERROR
;
1235 if (gdb_python_module
1236 && PyObject_HasAttrString (gdb_python_module
, "prompt_hook"))
1238 gdbpy_ref
<> hook (PyObject_GetAttrString (gdb_python_module
,
1242 gdbpy_print_stack ();
1243 return EXT_LANG_RC_ERROR
;
1246 if (PyCallable_Check (hook
.get ()))
1248 gdbpy_ref
<> current_prompt (PyUnicode_FromString (current_gdb_prompt
));
1249 if (current_prompt
== NULL
)
1251 gdbpy_print_stack ();
1252 return EXT_LANG_RC_ERROR
;
1256 (PyObject_CallFunctionObjArgs (hook
.get (), current_prompt
.get (),
1260 gdbpy_print_stack ();
1261 return EXT_LANG_RC_ERROR
;
1264 /* Return type should be None, or a String. If it is None,
1265 fall through, we will not set a prompt. If it is a
1266 string, set PROMPT. Anything else, set an exception. */
1267 if (result
!= Py_None
&& !PyUnicode_Check (result
.get ()))
1269 PyErr_Format (PyExc_RuntimeError
,
1270 _("Return from prompt_hook must " \
1271 "be either a Python string, or None"));
1272 gdbpy_print_stack ();
1273 return EXT_LANG_RC_ERROR
;
1276 if (result
!= Py_None
)
1278 gdb::unique_xmalloc_ptr
<char>
1279 prompt (python_string_to_host_string (result
.get ()));
1283 gdbpy_print_stack ();
1284 return EXT_LANG_RC_ERROR
;
1287 set_prompt (prompt
.get ());
1288 return EXT_LANG_RC_OK
;
1293 return EXT_LANG_RC_NOP
;
1296 /* This is the extension_language_ops.colorize "method". */
1298 static std::optional
<std::string
>
1299 gdbpy_colorize (const std::string
&filename
, const std::string
&contents
,
1302 if (!gdb_python_initialized
)
1305 gdbpy_enter enter_py
;
1307 gdbpy_ref
<> module (PyImport_ImportModule ("gdb.styling"));
1308 if (module
== nullptr)
1310 gdbpy_print_stack ();
1314 if (!PyObject_HasAttrString (module
.get (), "colorize"))
1317 gdbpy_ref
<> hook (PyObject_GetAttrString (module
.get (), "colorize"));
1318 if (hook
== nullptr)
1320 gdbpy_print_stack ();
1324 if (!PyCallable_Check (hook
.get ()))
1327 gdbpy_ref
<> fname_arg (PyUnicode_FromString (filename
.c_str ()));
1328 if (fname_arg
== nullptr)
1330 gdbpy_print_stack ();
1334 gdbpy_ref
<> lang_arg (PyUnicode_FromString (language_str (lang
)));
1335 if (lang_arg
== nullptr)
1337 gdbpy_print_stack ();
1341 /* The pygments library, which is what we currently use for applying
1342 styling, is happy to take input as a bytes object, and to figure out
1343 the encoding for itself. This removes the need for us to figure out
1344 (guess?) at how the content is encoded, which is probably a good
1346 gdbpy_ref
<> contents_arg (PyBytes_FromStringAndSize (contents
.c_str (),
1348 if (contents_arg
== nullptr)
1350 gdbpy_print_stack ();
1354 /* Calling gdb.colorize passing in the filename (a string), and the file
1355 contents (a bytes object). This function should return either a bytes
1356 object, the same contents with styling applied, or None to indicate
1357 that no styling should be performed. */
1358 gdbpy_ref
<> result (PyObject_CallFunctionObjArgs (hook
.get (),
1360 contents_arg
.get (),
1363 if (result
== nullptr)
1365 gdbpy_print_stack ();
1369 if (result
== Py_None
)
1371 else if (!PyBytes_Check (result
.get ()))
1373 PyErr_SetString (PyExc_TypeError
,
1374 _("Return value from gdb.colorize should be a bytes object or None."));
1375 gdbpy_print_stack ();
1379 return std::string (PyBytes_AsString (result
.get ()));
1382 /* This is the extension_language_ops.colorize_disasm "method". */
1384 static std::optional
<std::string
>
1385 gdbpy_colorize_disasm (const std::string
&content
, gdbarch
*gdbarch
)
1387 if (!gdb_python_initialized
)
1390 gdbpy_enter enter_py
;
1392 gdbpy_ref
<> module (PyImport_ImportModule ("gdb.styling"));
1393 if (module
== nullptr)
1395 gdbpy_print_stack ();
1399 if (!PyObject_HasAttrString (module
.get (), "colorize_disasm"))
1402 gdbpy_ref
<> hook (PyObject_GetAttrString (module
.get (),
1403 "colorize_disasm"));
1404 if (hook
== nullptr)
1406 gdbpy_print_stack ();
1410 if (!PyCallable_Check (hook
.get ()))
1413 gdbpy_ref
<> content_arg (PyBytes_FromString (content
.c_str ()));
1414 if (content_arg
== nullptr)
1416 gdbpy_print_stack ();
1420 gdbpy_ref
<> gdbarch_arg (gdbarch_to_arch_object (gdbarch
));
1421 if (gdbarch_arg
== nullptr)
1423 gdbpy_print_stack ();
1427 gdbpy_ref
<> result (PyObject_CallFunctionObjArgs (hook
.get (),
1431 if (result
== nullptr)
1433 gdbpy_print_stack ();
1437 if (result
== Py_None
)
1440 if (!PyBytes_Check (result
.get ()))
1442 PyErr_SetString (PyExc_TypeError
,
1443 _("Return value from gdb.colorize_disasm should be a bytes object or None."));
1444 gdbpy_print_stack ();
1448 return std::string (PyBytes_AsString (result
.get ()));
1453 /* Implement gdb.format_address(ADDR,P_SPACE,ARCH). Provide access to
1454 GDB's print_address function from Python. The returned address will
1455 have the format '0x..... <symbol+offset>'. */
1458 gdbpy_format_address (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1460 static const char *keywords
[] =
1462 "address", "progspace", "architecture", nullptr
1464 PyObject
*addr_obj
= nullptr, *pspace_obj
= nullptr, *arch_obj
= nullptr;
1466 struct gdbarch
*gdbarch
= nullptr;
1467 struct program_space
*pspace
= nullptr;
1469 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "O|OO", keywords
,
1470 &addr_obj
, &pspace_obj
, &arch_obj
))
1473 if (get_addr_from_python (addr_obj
, &addr
) < 0)
1476 /* If the user passed None for progspace or architecture, then we
1477 consider this to mean "the default". Here we replace references to
1478 None with nullptr, this means that in the following code we only have
1479 to handle the nullptr case. These are only borrowed references, so
1480 no decref is required here. */
1481 if (pspace_obj
== Py_None
)
1482 pspace_obj
= nullptr;
1483 if (arch_obj
== Py_None
)
1486 if (pspace_obj
== nullptr && arch_obj
== nullptr)
1488 /* Grab both of these from the current inferior, and its associated
1489 default architecture. */
1490 pspace
= current_inferior ()->pspace
;
1491 gdbarch
= current_inferior ()->arch ();
1493 else if (arch_obj
== nullptr || pspace_obj
== nullptr)
1495 /* If the user has only given one of program space or architecture,
1496 then don't use the default for the other. Sure we could use the
1497 default, but it feels like there's too much scope of mistakes in
1498 this case, so better to require the user to provide both
1500 PyErr_SetString (PyExc_ValueError
,
1501 _("The architecture and progspace arguments must both be supplied"));
1506 /* The user provided an address, program space, and architecture.
1507 Just check that these objects are valid. */
1508 if (!gdbpy_is_progspace (pspace_obj
))
1510 PyErr_SetString (PyExc_TypeError
,
1511 _("The progspace argument is not a gdb.Progspace object"));
1515 pspace
= progspace_object_to_program_space (pspace_obj
);
1516 if (pspace
== nullptr)
1518 PyErr_SetString (PyExc_ValueError
,
1519 _("The progspace argument is not valid"));
1523 if (!gdbpy_is_architecture (arch_obj
))
1525 PyErr_SetString (PyExc_TypeError
,
1526 _("The architecture argument is not a gdb.Architecture object"));
1530 /* Architectures are never deleted once created, so gdbarch should
1531 never come back as nullptr. */
1532 gdbarch
= arch_object_to_gdbarch (arch_obj
);
1533 gdb_assert (gdbarch
!= nullptr);
1536 /* By this point we should know the program space and architecture we are
1538 gdb_assert (pspace
!= nullptr);
1539 gdb_assert (gdbarch
!= nullptr);
1541 /* Unfortunately print_address relies on the current program space for
1542 its symbol lookup. Temporarily switch now. */
1543 scoped_restore_current_program_space restore_progspace
;
1544 set_current_program_space (pspace
);
1546 /* Format the address, and return it as a string. */
1548 print_address (gdbarch
, addr
, &buf
);
1549 return PyUnicode_FromString (buf
.c_str ());
1556 /* A python function to write a single string using gdb's filtered
1557 output stream . The optional keyword STREAM can be used to write
1558 to a particular stream. The default stream is to gdb_stdout. */
1561 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1564 static const char *keywords
[] = { "text", "stream", NULL
};
1565 int stream_type
= 0;
1567 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
1573 switch (stream_type
)
1577 gdb_printf (gdb_stderr
, "%s", arg
);
1582 gdb_printf (gdb_stdlog
, "%s", arg
);
1586 gdb_printf (gdb_stdout
, "%s", arg
);
1589 catch (const gdb_exception
&except
)
1591 return gdbpy_handle_gdb_exception (nullptr, except
);
1597 /* A python function to flush a gdb stream. The optional keyword
1598 STREAM can be used to flush a particular stream. The default stream
1602 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1604 static const char *keywords
[] = { "stream", NULL
};
1605 int stream_type
= 0;
1607 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
1611 switch (stream_type
)
1615 if (gdb_stderr
!= nullptr)
1616 gdb_flush (gdb_stderr
);
1621 if (gdb_stdlog
!= nullptr)
1622 gdb_flush (gdb_stdlog
);
1626 if (gdb_stdout
!= nullptr)
1627 gdb_flush (gdb_stdout
);
1633 /* Implement gdb.warning(). Takes a single text string argument and emit a
1634 warning using GDB's 'warning' function. The input text string must not
1638 gdbpy_warning (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1641 static const char *keywords
[] = { "text", nullptr };
1643 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s", keywords
, &text
))
1646 if (strlen (text
) == 0)
1648 PyErr_SetString (PyExc_ValueError
,
1649 _("Empty text string passed to gdb.warning"));
1655 warning ("%s", text
);
1657 catch (const gdb_exception
&ex
)
1659 /* The warning() call probably cannot throw an exception. But just
1660 in case it ever does. */
1661 return gdbpy_handle_gdb_exception (nullptr, ex
);
1667 /* Return non-zero if print-stack is not "none". */
1670 gdbpy_print_python_errors_p (void)
1672 return gdbpy_should_print_stack
!= python_excp_none
;
1675 /* Print a python exception trace, print just a message, or print
1676 nothing and clear the python exception, depending on
1677 gdbpy_should_print_stack. Only call this if a python exception is
1680 gdbpy_print_stack (void)
1683 /* Print "none", just clear exception. */
1684 if (gdbpy_should_print_stack
== python_excp_none
)
1688 /* Print "full" message and backtrace. */
1689 else if (gdbpy_should_print_stack
== python_excp_full
)
1692 /* PyErr_Print doesn't necessarily end output with a newline.
1693 This works because Python's stdout/stderr is fed through
1699 catch (const gdb_exception
&except
)
1703 /* Print "message", just error print message. */
1706 gdbpy_err_fetch fetched_error
;
1708 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
1709 gdb::unique_xmalloc_ptr
<char> type
;
1710 /* Don't compute TYPE if MSG already indicates that there is an
1713 type
= fetched_error
.type_to_string ();
1717 if (msg
== NULL
|| type
== NULL
)
1719 /* An error occurred computing the string representation of the
1721 gdb_printf (gdb_stderr
,
1722 _("Error occurred computing Python error "
1727 gdb_printf (gdb_stderr
, "Python Exception %s: %s\n",
1728 type
.get (), msg
.get ());
1730 catch (const gdb_exception
&except
)
1736 /* Like gdbpy_print_stack, but if the exception is a
1737 KeyboardException, throw a gdb "quit" instead. */
1740 gdbpy_print_stack_or_quit ()
1742 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt
))
1745 throw_quit ("Quit");
1747 gdbpy_print_stack ();
1752 /* Return a sequence holding all the Progspaces. */
1755 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
1757 gdbpy_ref
<> list (PyList_New (0));
1761 for (struct program_space
*ps
: program_spaces
)
1763 gdbpy_ref
<> item
= pspace_to_pspace_object (ps
);
1765 if (item
== NULL
|| PyList_Append (list
.get (), item
.get ()) == -1)
1769 return list
.release ();
1772 /* Return the name of the current language. */
1775 gdbpy_current_language (PyObject
*unused1
, PyObject
*unused2
)
1777 return host_string_to_python_string (current_language
->name ()).release ();
1783 struct objfile
*gdbpy_current_objfile
;
1785 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1786 as Python code. This does not throw any errors. If an exception
1787 occurs python will print the traceback and clear the error indicator.
1788 This is the extension_language_script_ops.objfile_script_sourcer
1792 gdbpy_source_objfile_script (const struct extension_language_defn
*extlang
,
1793 struct objfile
*objfile
, FILE *file
,
1794 const char *filename
)
1796 if (!gdb_python_initialized
)
1799 gdbpy_enter
enter_py (objfile
->arch ());
1800 scoped_restore restire_current_objfile
1801 = make_scoped_restore (&gdbpy_current_objfile
, objfile
);
1803 int result
= python_run_simple_file (file
, filename
);
1805 gdbpy_print_stack ();
1808 /* Set the current objfile to OBJFILE and then execute SCRIPT
1809 as Python code. This does not throw any errors. If an exception
1810 occurs python will print the traceback and clear the error indicator.
1811 This is the extension_language_script_ops.objfile_script_executor
1815 gdbpy_execute_objfile_script (const struct extension_language_defn
*extlang
,
1816 struct objfile
*objfile
, const char *name
,
1819 if (!gdb_python_initialized
)
1822 gdbpy_enter
enter_py (objfile
->arch ());
1823 scoped_restore restire_current_objfile
1824 = make_scoped_restore (&gdbpy_current_objfile
, objfile
);
1826 int ret
= eval_python_command (script
, Py_file_input
);
1828 gdbpy_print_stack ();
1831 /* Return the current Objfile, or None if there isn't one. */
1834 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
1836 if (! gdbpy_current_objfile
)
1839 return objfile_to_objfile_object (gdbpy_current_objfile
).release ();
1842 /* Implement the 'handle_missing_debuginfo' hook for Python. GDB has
1843 failed to find any debug information for OBJFILE. The extension has a
1844 chance to record this, or even install the required debug information.
1845 See the description of ext_lang_missing_file_result in extension-priv.h
1846 for details of the return value. */
1848 static ext_lang_missing_file_result
1849 gdbpy_handle_missing_debuginfo (const struct extension_language_defn
*extlang
,
1850 struct objfile
*objfile
)
1852 /* Early exit if Python is not initialised. */
1853 if (!gdb_python_initialized
|| gdb_python_module
== nullptr)
1856 struct gdbarch
*gdbarch
= objfile
->arch ();
1858 gdbpy_enter
enter_py (gdbarch
);
1860 /* Convert OBJFILE into the corresponding Python object. */
1861 gdbpy_ref
<> pyo_objfile
= objfile_to_objfile_object (objfile
);
1862 if (pyo_objfile
== nullptr)
1864 gdbpy_print_stack ();
1868 /* Lookup the helper function within the GDB module. */
1869 gdbpy_ref
<> pyo_handler
1870 (PyObject_GetAttrString (gdb_python_module
, "_handle_missing_debuginfo"));
1871 if (pyo_handler
== nullptr)
1873 gdbpy_print_stack ();
1877 /* Call the function, passing in the Python objfile object. */
1878 gdbpy_ref
<> pyo_execute_ret
1879 (PyObject_CallFunctionObjArgs (pyo_handler
.get (), pyo_objfile
.get (),
1881 if (pyo_execute_ret
== nullptr)
1883 /* If the handler is cancelled due to a Ctrl-C, then propagate
1884 the Ctrl-C as a GDB exception instead of swallowing it. */
1885 gdbpy_print_stack_or_quit ();
1889 /* Parse the result, and convert it back to the C++ object. */
1890 if (pyo_execute_ret
== Py_None
)
1893 if (PyBool_Check (pyo_execute_ret
.get ()))
1895 /* We know the value is a bool, so it must be either Py_True or
1896 Py_False. Anything else would not get past the above check. */
1897 bool try_again
= pyo_execute_ret
.get () == Py_True
;
1898 return ext_lang_missing_file_result (try_again
);
1901 if (!gdbpy_is_string (pyo_execute_ret
.get ()))
1903 PyErr_SetString (PyExc_ValueError
,
1904 "return value from _handle_missing_debuginfo should "
1905 "be None, a Bool, or a String");
1906 gdbpy_print_stack ();
1910 gdb::unique_xmalloc_ptr
<char> filename
1911 = python_string_to_host_string (pyo_execute_ret
.get ());
1912 if (filename
== nullptr)
1914 gdbpy_print_stack ();
1918 return ext_lang_missing_file_result (std::string (filename
.get ()));
1921 /* Implement the find_objfile_from_buildid hook for Python. PSPACE is the
1922 program space in which GDB is trying to find an objfile, BUILD_ID is the
1923 build-id for the missing objfile, and EXPECTED_FILENAME is a non-NULL
1924 string which can be used (if needed) in messages to the user, and
1925 represents the file GDB is looking for. */
1927 static ext_lang_missing_file_result
1928 gdbpy_find_objfile_from_buildid (const struct extension_language_defn
*extlang
,
1929 program_space
*pspace
,
1930 const struct bfd_build_id
*build_id
,
1931 const char *missing_filename
)
1933 gdb_assert (pspace
!= nullptr);
1934 gdb_assert (build_id
!= nullptr);
1935 gdb_assert (missing_filename
!= nullptr);
1937 /* Early exit if Python is not initialised. */
1938 if (!gdb_python_initialized
|| gdb_python_module
== nullptr)
1941 gdbpy_enter enter_py
;
1943 /* Convert BUILD_ID into a Python object. */
1944 std::string hex_form
= bin2hex (build_id
->data
, build_id
->size
);
1945 gdbpy_ref
<> pyo_buildid
= host_string_to_python_string (hex_form
.c_str ());
1946 if (pyo_buildid
== nullptr)
1948 gdbpy_print_stack ();
1952 /* Convert MISSING_FILENAME to a Python object. */
1953 gdbpy_ref
<> pyo_filename
= host_string_to_python_string (missing_filename
);
1954 if (pyo_filename
== nullptr)
1956 gdbpy_print_stack ();
1960 /* Convert PSPACE to a Python object. */
1961 gdbpy_ref
<> pyo_pspace
= pspace_to_pspace_object (pspace
);
1962 if (pyo_pspace
== nullptr)
1964 gdbpy_print_stack ();
1968 /* Lookup the helper function within the GDB module. */
1969 gdbpy_ref
<> pyo_handler
1970 (PyObject_GetAttrString (gdb_python_module
, "_handle_missing_objfile"));
1971 if (pyo_handler
== nullptr)
1973 gdbpy_print_stack ();
1977 /* Call the function, passing in the Python objfile object. */
1978 gdbpy_ref
<> pyo_execute_ret
1979 (PyObject_CallFunctionObjArgs (pyo_handler
.get (), pyo_pspace
.get (),
1980 pyo_buildid
.get (), pyo_filename
.get (),
1982 if (pyo_execute_ret
== nullptr)
1984 /* If the handler is cancelled due to a Ctrl-C, then propagate
1985 the Ctrl-C as a GDB exception instead of swallowing it. */
1986 gdbpy_print_stack_or_quit ();
1990 /* Parse the result, and convert it back to the C++ object. */
1991 if (pyo_execute_ret
== Py_None
)
1994 if (PyBool_Check (pyo_execute_ret
.get ()))
1996 /* We know the value is a bool, so it must be either Py_True or
1997 Py_False. Anything else would not get past the above check. */
1998 bool try_again
= pyo_execute_ret
.get () == Py_True
;
1999 return ext_lang_missing_file_result (try_again
);
2002 if (!gdbpy_is_string (pyo_execute_ret
.get ()))
2004 PyErr_SetString (PyExc_ValueError
,
2005 "return value from _find_objfile_by_buildid should "
2006 "be None, a bool, or a str");
2007 gdbpy_print_stack ();
2011 gdb::unique_xmalloc_ptr
<char> filename
2012 = python_string_to_host_string (pyo_execute_ret
.get ());
2013 if (filename
== nullptr)
2015 gdbpy_print_stack ();
2019 return ext_lang_missing_file_result (std::string (filename
.get ()));
2022 /* Compute the list of active python type printers and store them in
2023 EXT_PRINTERS->py_type_printers. The product of this function is used by
2024 gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
2025 This is the extension_language_ops.start_type_printers "method". */
2028 gdbpy_start_type_printers (const struct extension_language_defn
*extlang
,
2029 struct ext_lang_type_printers
*ext_printers
)
2031 PyObject
*printers_obj
= NULL
;
2033 if (!gdb_python_initialized
)
2036 gdbpy_enter enter_py
;
2038 gdbpy_ref
<> type_module (PyImport_ImportModule ("gdb.types"));
2039 if (type_module
== NULL
)
2041 gdbpy_print_stack ();
2045 gdbpy_ref
<> func (PyObject_GetAttrString (type_module
.get (),
2046 "get_type_recognizers"));
2049 gdbpy_print_stack ();
2053 printers_obj
= PyObject_CallFunctionObjArgs (func
.get (), (char *) NULL
);
2054 if (printers_obj
== NULL
)
2055 gdbpy_print_stack ();
2057 ext_printers
->py_type_printers
= printers_obj
;
2060 /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
2061 a newly allocated string holding the type's replacement name, and return
2063 If there's a Python error return EXT_LANG_RC_ERROR.
2064 Otherwise, return EXT_LANG_RC_NOP.
2065 This is the extension_language_ops.apply_type_printers "method". */
2067 static enum ext_lang_rc
2068 gdbpy_apply_type_printers (const struct extension_language_defn
*extlang
,
2069 const struct ext_lang_type_printers
*ext_printers
,
2071 gdb::unique_xmalloc_ptr
<char> *prettied_type
)
2073 PyObject
*printers_obj
= (PyObject
*) ext_printers
->py_type_printers
;
2074 gdb::unique_xmalloc_ptr
<char> result
;
2076 if (printers_obj
== NULL
)
2077 return EXT_LANG_RC_NOP
;
2079 if (!gdb_python_initialized
)
2080 return EXT_LANG_RC_NOP
;
2082 gdbpy_enter enter_py
;
2084 gdbpy_ref
<> type_obj (type_to_type_object (type
));
2085 if (type_obj
== NULL
)
2087 gdbpy_print_stack ();
2088 return EXT_LANG_RC_ERROR
;
2091 gdbpy_ref
<> type_module (PyImport_ImportModule ("gdb.types"));
2092 if (type_module
== NULL
)
2094 gdbpy_print_stack ();
2095 return EXT_LANG_RC_ERROR
;
2098 gdbpy_ref
<> func (PyObject_GetAttrString (type_module
.get (),
2099 "apply_type_recognizers"));
2102 gdbpy_print_stack ();
2103 return EXT_LANG_RC_ERROR
;
2106 gdbpy_ref
<> result_obj (PyObject_CallFunctionObjArgs (func
.get (),
2110 if (result_obj
== NULL
)
2112 gdbpy_print_stack ();
2113 return EXT_LANG_RC_ERROR
;
2116 if (result_obj
== Py_None
)
2117 return EXT_LANG_RC_NOP
;
2119 result
= python_string_to_host_string (result_obj
.get ());
2122 gdbpy_print_stack ();
2123 return EXT_LANG_RC_ERROR
;
2126 *prettied_type
= std::move (result
);
2127 return EXT_LANG_RC_OK
;
2130 /* Free the result of start_type_printers.
2131 This is the extension_language_ops.free_type_printers "method". */
2134 gdbpy_free_type_printers (const struct extension_language_defn
*extlang
,
2135 struct ext_lang_type_printers
*ext_printers
)
2137 PyObject
*printers
= (PyObject
*) ext_printers
->py_type_printers
;
2139 if (printers
== NULL
)
2142 if (!gdb_python_initialized
)
2145 gdbpy_enter enter_py
;
2146 Py_DECREF (printers
);
2149 #else /* HAVE_PYTHON */
2151 /* Dummy implementation of the gdb "python-interactive" and "python"
2155 python_interactive_command (const char *arg
, int from_tty
)
2157 arg
= skip_spaces (arg
);
2159 error (_("Python scripting is not supported in this copy of GDB."));
2162 counted_command_line l
= get_command_line (python_control
, "");
2164 execute_control_command_untraced (l
.get ());
2169 python_command (const char *arg
, int from_tty
)
2171 python_interactive_command (arg
, from_tty
);
2174 #endif /* HAVE_PYTHON */
2176 /* Stand-in for Py_IsInitialized (). To be used because after a python fatal
2177 error, no calls into Python are allowed. */
2179 static bool py_isinitialized
= false;
2181 /* Variables to hold the effective values of "python ignore-environment" and
2182 "python dont-write-bytecode" at Python initialization. */
2184 static bool python_ignore_environment_at_python_initialization
;
2185 static bool python_dont_write_bytecode_at_python_initialization
;
2187 /* When this is turned on before Python is initialised then Python will
2188 ignore any environment variables related to Python. This is equivalent
2189 to passing `-E' to the python program. */
2190 static bool python_ignore_environment
= false;
2192 /* Implement 'show python ignore-environment'. */
2195 show_python_ignore_environment (struct ui_file
*file
, int from_tty
,
2196 struct cmd_list_element
*c
, const char *value
)
2198 gdb_printf (file
, _("Python's ignore-environment setting is %s.\n"),
2202 /* Implement 'set python ignore-environment'. This sets Python's internal
2203 flag no matter when the command is issued, however, if this is used
2204 after Py_Initialize has been called then most of the environment will
2205 already have been read. */
2208 set_python_ignore_environment (const char *args
, int from_tty
,
2209 struct cmd_list_element
*c
)
2211 if (py_isinitialized
)
2213 python_ignore_environment
2214 = python_ignore_environment_at_python_initialization
;
2216 warning (_("Setting python ignore-environment after Python"
2217 " initialization has no effect, try setting this during"
2218 " early initialization"));
2222 /* When this is turned on before Python is initialised then Python will
2223 not write `.pyc' files on import of a module. */
2224 static enum auto_boolean python_dont_write_bytecode
= AUTO_BOOLEAN_AUTO
;
2227 /* Return true if environment variable PYTHONDONTWRITEBYTECODE is set to a
2228 non-empty string. */
2231 env_python_dont_write_bytecode ()
2233 const char *envvar
= getenv ("PYTHONDONTWRITEBYTECODE");
2234 return envvar
!= nullptr && envvar
[0] != '\0';
2237 /* Implement 'show python dont-write-bytecode'. */
2240 show_python_dont_write_bytecode (struct ui_file
*file
, int from_tty
,
2241 struct cmd_list_element
*c
, const char *value
)
2243 if (python_dont_write_bytecode
== AUTO_BOOLEAN_AUTO
)
2245 const char *auto_string
2246 = ((python_ignore_environment
2247 || !env_python_dont_write_bytecode ())
2252 _("Python's dont-write-bytecode setting is %s (currently %s).\n"),
2253 value
, auto_string
);
2256 gdb_printf (file
, _("Python's dont-write-bytecode setting is %s.\n"),
2261 /* Return value to assign to PyConfig.write_bytecode or, when
2262 negated (via !), Py_DontWriteBytecodeFlag. Py_DontWriteBytecodeFlag
2263 is deprecated in Python 3.12. */
2266 python_write_bytecode ()
2270 if (python_dont_write_bytecode
== AUTO_BOOLEAN_AUTO
)
2272 if (python_ignore_environment
)
2275 wbc
= env_python_dont_write_bytecode () ? 0 : 1;
2278 wbc
= python_dont_write_bytecode
== AUTO_BOOLEAN_TRUE
? 0 : 1;
2282 #endif /* HAVE_PYTHON */
2284 /* Implement 'set python dont-write-bytecode'. This sets Python's internal
2285 flag no matter when the command is issued, however, if this is used
2286 after Py_Initialize has been called then many modules could already
2287 have been imported and their byte code written out. */
2290 set_python_dont_write_bytecode (const char *args
, int from_tty
,
2291 struct cmd_list_element
*c
)
2293 if (py_isinitialized
)
2295 python_dont_write_bytecode
2296 = (python_dont_write_bytecode_at_python_initialization
2298 : AUTO_BOOLEAN_FALSE
);
2300 warning (_("Setting python dont-write-bytecode after Python"
2301 " initialization has no effect, try setting this during"
2302 " early initialization, or try setting"
2303 " sys.dont_write_bytecode"));
2309 /* Lists for 'set python' commands. */
2311 static struct cmd_list_element
*user_set_python_list
;
2312 static struct cmd_list_element
*user_show_python_list
;
2314 /* Initialize the Python code. */
2318 /* This is installed as a final cleanup and cleans up the
2319 interpreter. This lets Python's 'atexit' work. */
2322 finalize_python (const struct extension_language_defn
*ignore
)
2324 if (!gdb_python_initialized
)
2327 struct active_ext_lang_state
*previous_active
;
2329 /* We don't use ensure_python_env here because if we ever ran the
2330 cleanup, gdb would crash -- because the cleanup calls into the
2331 Python interpreter, which we are about to destroy. It seems
2332 clearer to make the needed calls explicitly here than to create a
2333 cleanup and then mysteriously discard it. */
2335 /* This is only called as a final cleanup so we can assume the active
2336 SIGINT handler is gdb's. We still need to tell it to notify Python. */
2337 previous_active
= set_active_ext_lang (&extension_language_python
);
2339 (void) PyGILState_Ensure ();
2340 gdbpy_enter::finalize ();
2342 /* Call the gdbpy_finalize_* functions from every *.c file. */
2343 gdbpy_initialize_file::finalize_all ();
2347 gdb_python_initialized
= false;
2348 restore_active_ext_lang (previous_active
);
2351 static struct PyModuleDef python_GdbModuleDef
=
2353 PyModuleDef_HEAD_INIT
,
2364 /* This is called via the PyImport_AppendInittab mechanism called
2365 during initialization, to make the built-in _gdb module known to
2367 PyMODINIT_FUNC
init__gdb_module (void);
2369 init__gdb_module (void)
2371 return PyModule_Create (&python_GdbModuleDef
);
2374 /* Emit a gdb.GdbExitingEvent, return a negative value if there are any
2375 errors, otherwise, return 0. */
2378 emit_exiting_event (int exit_code
)
2380 if (evregpy_no_listeners_p (gdb_py_events
.gdb_exiting
))
2383 gdbpy_ref
<> event_obj
= create_event_object (&gdb_exiting_event_object_type
);
2384 if (event_obj
== nullptr)
2387 gdbpy_ref
<> code
= gdb_py_object_from_longest (exit_code
);
2388 if (evpy_add_attribute (event_obj
.get (), "exit_code", code
.get ()) < 0)
2391 return evpy_emit_event (event_obj
.get (), gdb_py_events
.gdb_exiting
);
2394 /* Callback for the gdb_exiting observable. EXIT_CODE is the value GDB
2398 gdbpy_gdb_exiting (int exit_code
)
2400 if (!gdb_python_initialized
)
2403 gdbpy_enter enter_py
;
2405 if (emit_exiting_event (exit_code
) < 0)
2406 gdbpy_print_stack ();
2409 #if PY_VERSION_HEX < 0x030a0000
2410 /* Signal handler to convert a SIGABRT into an exception. */
2413 catch_python_fatal (int signum
)
2415 signal (SIGABRT
, catch_python_fatal
);
2417 throw_exception_sjlj (gdb_exception
{RETURN_ERROR
, GENERIC_ERROR
});
2420 /* Call Py_Initialize (), and return true if successful. */
2423 py_initialize_catch_abort ()
2425 auto prev_handler
= signal (SIGABRT
, catch_python_fatal
);
2426 SCOPE_EXIT
{ signal (SIGABRT
, prev_handler
); };
2431 py_isinitialized
= true;
2433 CATCH_SJLJ (e
, RETURN_MASK_ERROR
)
2438 return py_isinitialized
;
2442 /* Initialize python, either by calling Py_Initialize or
2443 Py_InitializeFromConfig, and return true if successful. */
2448 /* Sample values at Python initialization. */
2449 python_dont_write_bytecode_at_python_initialization
2450 = !python_write_bytecode ();
2451 python_ignore_environment_at_python_initialization
2452 = python_ignore_environment
;
2454 /* Don't show "python dont-write-bytecode auto" after Python
2456 python_dont_write_bytecode
2457 = (python_dont_write_bytecode_at_python_initialization
2459 : AUTO_BOOLEAN_FALSE
);
2461 #if PY_VERSION_HEX < 0x030a0000
2462 /* Python documentation indicates that the memory given
2463 to Py_SetProgramName cannot be freed. However, it seems that
2464 at least Python 3.7.4 Py_SetProgramName takes a copy of the
2465 given program_name. Making progname_copy static and not release
2466 the memory avoids a leak report for Python versions that duplicate
2467 program_name, and respect the requirement of Py_SetProgramName
2468 for Python versions that do not duplicate program_name. */
2469 static wchar_t *progname_copy
= nullptr;
2471 wchar_t *progname_copy
= nullptr;
2472 SCOPE_EXIT
{ XDELETEVEC (progname_copy
); };
2475 #ifdef WITH_PYTHON_PATH
2476 /* Work around problem where python gets confused about where it is,
2477 and then can't find its libraries, etc.
2478 NOTE: Python assumes the following layout:
2480 /foo/lib/pythonX.Y/...
2481 This must be done before calling Py_Initialize. */
2482 gdb::unique_xmalloc_ptr
<char> progname
2483 (concat (gdb_ldirname (python_libdir
.c_str ()).c_str (), SLASH_STRING
, "bin",
2484 SLASH_STRING
, "python", (char *) NULL
));
2487 std::string oldloc
= setlocale (LC_ALL
, NULL
);
2488 SCOPE_EXIT
{ setlocale (LC_ALL
, oldloc
.c_str ()); };
2490 setlocale (LC_ALL
, "");
2491 size_t progsize
= strlen (progname
.get ());
2492 progname_copy
= XNEWVEC (wchar_t, progsize
+ 1);
2493 size_t count
= mbstowcs (progname_copy
, progname
.get (), progsize
+ 1);
2494 if (count
== (size_t) -1)
2496 fprintf (stderr
, "Could not convert python path to string\n");
2502 /* Py_SetProgramName was deprecated in Python 3.11. Use PyConfig
2503 mechanisms for Python 3.10 and newer. */
2504 #if PY_VERSION_HEX < 0x030a0000
2505 /* Note that Py_SetProgramName expects the string it is passed to
2506 remain alive for the duration of the program's execution, so
2507 it is not freed after this call. */
2508 if (progname_copy
!= nullptr)
2509 Py_SetProgramName (progname_copy
);
2510 Py_DontWriteBytecodeFlag
2511 = python_dont_write_bytecode_at_python_initialization
;
2512 Py_IgnoreEnvironmentFlag
2513 = python_ignore_environment_at_python_initialization
? 1 : 0;
2514 return py_initialize_catch_abort ();
2518 PyConfig_InitPythonConfig (&config
);
2520 if (progname_copy
!= nullptr)
2522 status
= PyConfig_SetString (&config
, &config
.program_name
,
2524 if (PyStatus_Exception (status
))
2528 config
.write_bytecode
= !python_dont_write_bytecode_at_python_initialization
;
2529 config
.use_environment
= !python_ignore_environment_at_python_initialization
;
2531 status
= PyConfig_Read (&config
);
2532 if (PyStatus_Exception (status
))
2535 status
= Py_InitializeFromConfig (&config
);
2538 PyConfig_Clear (&config
);
2539 if (PyStatus_Exception (status
))
2541 if (PyStatus_IsError (status
))
2542 gdb_printf (_("Python initialization failed: %s\n"), status
.err_msg
);
2544 gdb_printf (_("Python initialization failed with exit status: %d\n"),
2549 py_isinitialized
= true;
2555 do_start_initialization ()
2557 /* Define all internal modules. These are all imported (and thus
2558 created) during initialization. */
2559 struct _inittab mods
[] =
2561 { "_gdb", init__gdb_module
},
2562 { "_gdbevents", gdbpy_events_mod_func
},
2563 { nullptr, nullptr }
2566 if (PyImport_ExtendInittab (mods
) < 0)
2569 if (!py_initialize ())
2572 #if PY_VERSION_HEX < 0x03090000
2573 /* PyEval_InitThreads became deprecated in Python 3.9 and will
2574 be removed in Python 3.11. Prior to Python 3.7, this call was
2575 required to initialize the GIL. */
2576 PyEval_InitThreads ();
2579 gdb_module
= PyImport_ImportModule ("_gdb");
2580 if (gdb_module
== NULL
)
2583 if (PyModule_AddStringConstant (gdb_module
, "VERSION", version
) < 0
2584 || PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", host_name
) < 0
2585 || PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
2589 /* Add stream constants. */
2590 if (PyModule_AddIntConstant (gdb_module
, "STDOUT", 0) < 0
2591 || PyModule_AddIntConstant (gdb_module
, "STDERR", 1) < 0
2592 || PyModule_AddIntConstant (gdb_module
, "STDLOG", 2) < 0)
2595 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
2596 if (gdbpy_gdb_error
== NULL
2597 || gdb_pymodule_addobject (gdb_module
, "error", gdbpy_gdb_error
) < 0)
2600 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
2601 gdbpy_gdb_error
, NULL
);
2602 if (gdbpy_gdb_memory_error
== NULL
2603 || gdb_pymodule_addobject (gdb_module
, "MemoryError",
2604 gdbpy_gdb_memory_error
) < 0)
2607 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
2608 if (gdbpy_gdberror_exc
== NULL
2609 || gdb_pymodule_addobject (gdb_module
, "GdbError",
2610 gdbpy_gdberror_exc
) < 0)
2613 /* Call the gdbpy_initialize_* functions from every *.c file. */
2614 if (!gdbpy_initialize_file::initialize_all ())
2617 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2618 if (gdbpy_type_ready (&name##_event_object_type) < 0) \
2620 #include "py-event-types.def"
2621 #undef GDB_PY_DEFINE_EVENT_TYPE
2623 gdbpy_to_string_cst
= PyUnicode_FromString ("to_string");
2624 if (gdbpy_to_string_cst
== NULL
)
2626 gdbpy_children_cst
= PyUnicode_FromString ("children");
2627 if (gdbpy_children_cst
== NULL
)
2629 gdbpy_display_hint_cst
= PyUnicode_FromString ("display_hint");
2630 if (gdbpy_display_hint_cst
== NULL
)
2632 gdbpy_doc_cst
= PyUnicode_FromString ("__doc__");
2633 if (gdbpy_doc_cst
== NULL
)
2635 gdbpy_enabled_cst
= PyUnicode_FromString ("enabled");
2636 if (gdbpy_enabled_cst
== NULL
)
2638 gdbpy_value_cst
= PyUnicode_FromString ("value");
2639 if (gdbpy_value_cst
== NULL
)
2642 gdb::observers::gdb_exiting
.attach (gdbpy_gdb_exiting
, "python");
2644 /* Release the GIL while gdb runs. */
2645 PyEval_SaveThread ();
2647 /* Only set this when initialization has succeeded. */
2648 gdb_python_initialized
= 1;
2653 namespace selftests
{
2655 /* Entry point for python unit tests. */
2660 #define CMD(S) execute_command_to_string (S, "python print(5)", 0, true)
2665 SELF_CHECK (output
== "5\n");
2668 bool saw_exception
= false;
2670 scoped_restore reset_gdb_python_initialized
2671 = make_scoped_restore (&gdb_python_initialized
, 0);
2676 catch (const gdb_exception
&e
)
2678 saw_exception
= true;
2679 SELF_CHECK (e
.reason
== RETURN_ERROR
);
2680 SELF_CHECK (e
.error
== GENERIC_ERROR
);
2681 SELF_CHECK (*e
.message
== "Python not initialized");
2683 SELF_CHECK (saw_exception
);
2684 SELF_CHECK (output
.empty ());
2687 saw_exception
= false;
2689 scoped_restore save_hook
2690 = make_scoped_restore (&hook_set_active_ext_lang
,
2691 []() { raise (SIGINT
); });
2696 catch (const gdb_exception_quit
&e
)
2698 saw_exception
= true;
2699 SELF_CHECK (e
.reason
== RETURN_QUIT
);
2700 SELF_CHECK (e
.error
== GDB_NO_ERROR
);
2701 SELF_CHECK (*e
.message
== "Quit");
2703 SELF_CHECK (saw_exception
);
2704 SELF_CHECK (output
.empty ());
2712 } /* namespace selftests */
2713 #endif /* GDB_SELF_TEST */
2715 #endif /* HAVE_PYTHON */
2718 cmd_list_element
*python_cmd_element
= nullptr;
2720 INIT_GDB_FILE (python
)
2722 cmd_list_element
*python_interactive_cmd
2723 = add_com ("python-interactive", class_obscure
,
2724 python_interactive_command
,
2727 Start an interactive Python prompt.\n\
2729 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
2732 Alternatively, a single-line Python command can be given as an\n\
2733 argument, and if the command is an expression, the result will be\n\
2734 printed. For example:\n\
2736 (gdb) python-interactive 2 + 3\n\
2738 #else /* HAVE_PYTHON */
2740 Start a Python interactive prompt.\n\
2742 Python scripting is not supported in this copy of GDB.\n\
2743 This command is only a placeholder.")
2744 #endif /* HAVE_PYTHON */
2746 add_com_alias ("pi", python_interactive_cmd
, class_obscure
, 1);
2748 python_cmd_element
= add_com ("python", class_obscure
, python_command
,
2751 Evaluate a Python command.\n\
2753 The command can be given as an argument, for instance:\n\
2755 python print (23)\n\
2757 If no argument is given, the following lines are read and used\n\
2758 as the Python commands. Type a line containing \"end\" to indicate\n\
2759 the end of the command.")
2760 #else /* HAVE_PYTHON */
2762 Evaluate a Python command.\n\
2764 Python scripting is not supported in this copy of GDB.\n\
2765 This command is only a placeholder.")
2766 #endif /* HAVE_PYTHON */
2768 add_com_alias ("py", python_cmd_element
, class_obscure
, 1);
2770 /* Add set/show python print-stack. */
2771 add_setshow_prefix_cmd ("python", no_class
,
2772 _("Prefix command for python preference settings."),
2773 _("Prefix command for python preference settings."),
2774 &user_set_python_list
, &user_show_python_list
,
2775 &setlist
, &showlist
);
2777 add_setshow_enum_cmd ("print-stack", no_class
, python_excp_enums
,
2778 &gdbpy_should_print_stack
, _("\
2779 Set mode for Python stack dump on error."), _("\
2780 Show the mode of Python stack printing on error."), _("\
2781 none == no stack or message will be printed.\n\
2782 full == a message and a stack will be printed.\n\
2783 message == an error message without a stack will be printed."),
2785 &user_set_python_list
,
2786 &user_show_python_list
);
2788 add_setshow_boolean_cmd ("ignore-environment", no_class
,
2789 &python_ignore_environment
, _("\
2790 Set whether the Python interpreter should ignore environment variables."), _("\
2791 Show whether the Python interpreter showlist ignore environment variables."), _("\
2792 When enabled GDB's Python interpreter will ignore any Python related\n\
2793 flags in the environment. This is equivalent to passing `-E' to a\n\
2794 python executable."),
2795 set_python_ignore_environment
,
2796 show_python_ignore_environment
,
2797 &user_set_python_list
,
2798 &user_show_python_list
);
2800 add_setshow_auto_boolean_cmd ("dont-write-bytecode", no_class
,
2801 &python_dont_write_bytecode
, _("\
2802 Set whether the Python interpreter should avoid byte-compiling python modules."), _("\
2803 Show whether the Python interpreter should avoid byte-compiling python modules."), _("\
2804 When enabled, GDB's embedded Python interpreter won't byte-compile python\n\
2805 modules. In order to take effect, this setting must be enabled in an early\n\
2806 initialization file, i.e. those run via the --early-init-eval-command or\n\
2807 -eix command line options. A 'set python dont-write-bytecode on' command\n\
2808 can also be issued directly from the GDB command line via the\n\
2809 --early-init-eval-command or -eiex command line options.\n\
2811 This setting defaults to 'auto'. In this mode, provided the 'python\n\
2812 ignore-environment' setting is 'off', the environment variable\n\
2813 PYTHONDONTWRITEBYTECODE is examined to determine whether or not to\n\
2814 byte-compile python modules. PYTHONDONTWRITEBYTECODE is considered to be\n\
2815 off/disabled either when set to the empty string or when the\n\
2816 environment variable doesn't exist. All other settings, including those\n\
2817 which don't seem to make sense, indicate that it's on/enabled."),
2818 set_python_dont_write_bytecode
,
2819 show_python_dont_write_bytecode
,
2820 &user_set_python_list
,
2821 &user_show_python_list
);
2825 selftests::register_test ("python", selftests::test_python
);
2826 #endif /* GDB_SELF_TEST */
2827 #endif /* HAVE_PYTHON */
2832 /* Helper function for gdbpy_initialize. This does the work and then
2833 returns false if an error has occurred and must be displayed, or true on
2837 do_initialize (const struct extension_language_defn
*extlang
)
2842 /* Add the initial data-directory to sys.path. */
2844 std::string gdb_pythondir
= (std::string (gdb_datadir
) + SLASH_STRING
2847 sys_path
= PySys_GetObject ("path");
2849 /* PySys_SetPath was deprecated in Python 3.11. Disable this
2850 deprecated code for Python 3.10 and newer. Also note that this
2851 ifdef eliminates potential initialization of sys.path via
2852 PySys_SetPath. My (kevinb's) understanding of PEP 587 suggests
2853 that it's not necessary due to module_search_paths being
2854 initialized to an empty list following any of the PyConfig
2855 initialization functions. If it does turn out that some kind of
2856 initialization is still needed, it should be added to the
2857 PyConfig-based initialization in do_start_initialize(). */
2858 #if PY_VERSION_HEX < 0x030a0000
2859 /* If sys.path is not defined yet, define it first. */
2860 if (!(sys_path
&& PyList_Check (sys_path
)))
2862 PySys_SetPath (L
"");
2863 sys_path
= PySys_GetObject ("path");
2866 if (sys_path
&& PyList_Check (sys_path
))
2868 gdbpy_ref
<> pythondir (PyUnicode_FromString (gdb_pythondir
.c_str ()));
2869 if (pythondir
== NULL
|| PyList_Insert (sys_path
, 0, pythondir
.get ()))
2875 /* Import the gdb module to finish the initialization, and
2876 add it to __main__ for convenience. */
2877 m
= PyImport_AddModule ("__main__");
2881 /* Keep the reference to gdb_python_module since it is in a global
2883 gdb_python_module
= PyImport_ImportModule ("gdb");
2884 if (gdb_python_module
== NULL
)
2886 gdbpy_print_stack ();
2887 /* This is passed in one call to warning so that blank lines aren't
2888 inserted between each line of text. */
2890 "Could not load the Python gdb module from `%s'.\n"
2891 "Limited Python support is available from the _gdb module.\n"
2892 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
2893 gdb_pythondir
.c_str ());
2894 /* We return "success" here as we've already emitted the
2899 return gdb_pymodule_addobject (m
, "gdb", gdb_python_module
) >= 0;
2902 /* Emit warnings in case python initialization has failed. */
2905 python_initialization_failed_warnings ()
2907 const char *pythonhome
= nullptr;
2908 const char *pythonpath
= nullptr;
2910 if (!python_ignore_environment
)
2912 pythonhome
= getenv ("PYTHONHOME");
2913 pythonpath
= getenv ("PYTHONPATH");
2916 bool have_pythonhome
2917 = pythonhome
!= nullptr && pythonhome
[0] != '\0';
2918 bool have_pythonpath
2919 = pythonpath
!= nullptr && pythonpath
[0] != '\0';
2921 if (have_pythonhome
)
2922 warning (_("Python failed to initialize with PYTHONHOME set. Maybe"
2923 " because it is set incorrectly? Maybe because it points to"
2924 " incompatible standard libraries? Consider changing or"
2925 " unsetting it, or ignoring it using \"set python"
2926 " ignore-environment on\" at early initialization."));
2928 if (have_pythonpath
)
2929 warning (_("Python failed to initialize with PYTHONPATH set. Maybe because"
2930 " it points to incompatible modules? Consider changing or"
2931 " unsetting it, or ignoring it using \"set python"
2932 " ignore-environment on\" at early initialization."));
2935 /* Perform Python initialization. This will be called after GDB has
2936 performed all of its own initialization. This is the
2937 extension_language_ops.initialize "method". */
2940 gdbpy_initialize (const struct extension_language_defn
*extlang
)
2942 if (!do_start_initialization ())
2944 if (py_isinitialized
)
2946 if (PyErr_Occurred ())
2947 gdbpy_print_stack ();
2949 /* We got no use for the Python interpreter anymore. Finalize it
2954 python_initialization_failed_warnings ();
2956 /* Continue with python disabled. */
2960 gdbpy_enter enter_py
;
2962 if (!do_initialize (extlang
))
2964 gdbpy_print_stack ();
2965 warning (_("internal error: Unhandled Python exception"));
2969 /* Return non-zero if Python has successfully initialized.
2970 This is the extension_languages_ops.initialized "method". */
2973 gdbpy_initialized (const struct extension_language_defn
*extlang
)
2975 return gdb_python_initialized
;
2978 PyMethodDef python_GdbMethods
[] =
2980 { "history", gdbpy_history
, METH_VARARGS
,
2981 "Get a value from history" },
2982 { "add_history", gdbpy_add_history
, METH_VARARGS
,
2983 "Add a value to the value history list" },
2984 { "history_count", gdbpy_history_count
, METH_NOARGS
,
2985 "Return an integer, the number of values in GDB's value history" },
2986 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
2987 "execute (command [, from_tty] [, to_string]) -> [String]\n\
2988 Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
2989 a Python String containing the output of the command if to_string is\n\
2991 { "execute_mi", (PyCFunction
) gdbpy_execute_mi_command
,
2992 METH_VARARGS
| METH_KEYWORDS
,
2993 "execute_mi (command, arg...) -> dictionary\n\
2994 Evaluate command, a string, as a gdb MI command.\n\
2995 Arguments (also strings) are passed to the command." },
2996 { "parameter", gdbpy_parameter
, METH_VARARGS
,
2997 "Return a gdb parameter's value" },
2999 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
3000 "Return a tuple of all breakpoint objects" },
3002 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
3003 "Find the default visualizer for a Value." },
3005 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
3006 "Return a sequence of all progspaces." },
3008 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
3009 "Return the current Objfile being loaded, or None." },
3011 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
3012 "newest_frame () -> gdb.Frame.\n\
3013 Return the newest frame object." },
3014 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
3015 "selected_frame () -> gdb.Frame.\n\
3016 Return the selected frame object." },
3017 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
3018 "stop_reason_string (Integer) -> String.\n\
3019 Return a string explaining unwind stop reason." },
3021 { "start_recording", gdbpy_start_recording
, METH_VARARGS
,
3022 "start_recording ([method] [, format]) -> gdb.Record.\n\
3023 Start recording with the given method. If no method is given, will fall back\n\
3024 to the system default method. If no format is given, will fall back to the\n\
3025 default format for the given method."},
3026 { "current_recording", gdbpy_current_recording
, METH_NOARGS
,
3027 "current_recording () -> gdb.Record.\n\
3028 Return current recording object." },
3029 { "stop_recording", gdbpy_stop_recording
, METH_NOARGS
,
3030 "stop_recording () -> None.\n\
3031 Stop current recording." },
3033 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
3034 METH_VARARGS
| METH_KEYWORDS
,
3035 "lookup_type (name [, block]) -> type\n\
3036 Return a Type corresponding to the given name." },
3037 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
3038 METH_VARARGS
| METH_KEYWORDS
,
3039 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
3040 Return a tuple with the symbol corresponding to the given name (or None) and\n\
3041 a boolean indicating if name is a field of the current implied argument\n\
3042 `this' (when the current language is object-oriented)." },
3043 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
3044 METH_VARARGS
| METH_KEYWORDS
,
3045 "lookup_global_symbol (name [, domain]) -> symbol\n\
3046 Return the symbol corresponding to the given name (or None)." },
3047 { "lookup_static_symbol", (PyCFunction
) gdbpy_lookup_static_symbol
,
3048 METH_VARARGS
| METH_KEYWORDS
,
3049 "lookup_static_symbol (name [, domain]) -> symbol\n\
3050 Return the static-linkage symbol corresponding to the given name (or None)." },
3051 { "lookup_static_symbols", (PyCFunction
) gdbpy_lookup_static_symbols
,
3052 METH_VARARGS
| METH_KEYWORDS
,
3053 "lookup_static_symbols (name [, domain]) -> symbol\n\
3054 Return a list of all static-linkage symbols corresponding to the given name." },
3056 { "lookup_objfile", (PyCFunction
) gdbpy_lookup_objfile
,
3057 METH_VARARGS
| METH_KEYWORDS
,
3058 "lookup_objfile (name, [by_build_id]) -> objfile\n\
3059 Look up the specified objfile.\n\
3060 If by_build_id is True, the objfile is looked up by using name\n\
3061 as its build id." },
3063 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
3064 "decode_line (String) -> Tuple. Decode a string argument the way\n\
3065 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
3066 The first element contains any unparsed portion of the String parameter\n\
3067 (or None if the string was fully parsed). The second element contains\n\
3068 a tuple that contains all the locations that match, represented as\n\
3069 gdb.Symtab_and_line objects (or None)."},
3070 { "parse_and_eval", (PyCFunction
) gdbpy_parse_and_eval
,
3071 METH_VARARGS
| METH_KEYWORDS
,
3072 "parse_and_eval (String, [Boolean]) -> Value.\n\
3073 Parse String as an expression, evaluate it, and return the result as a Value."
3076 { "post_event", gdbpy_post_event
, METH_VARARGS
,
3077 "Post an event into gdb's event loop." },
3078 { "interrupt", gdbpy_interrupt
, METH_NOARGS
,
3079 "Interrupt gdb's current operation." },
3081 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
3082 "target_charset () -> string.\n\
3083 Return the name of the current target charset." },
3084 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
3085 "target_wide_charset () -> string.\n\
3086 Return the name of the current target wide charset." },
3087 { "host_charset", gdbpy_host_charset
, METH_NOARGS
,
3088 "host_charset () -> string.\n\
3089 Return the name of the current host charset." },
3090 { "rbreak", (PyCFunction
) gdbpy_rbreak
, METH_VARARGS
| METH_KEYWORDS
,
3091 "rbreak (Regex) -> List.\n\
3092 Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
3093 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
3094 "string_to_argv (String) -> Array.\n\
3095 Parse String and return an argv-like array.\n\
3096 Arguments are separate by spaces and may be quoted."
3098 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
3099 "Write a string using gdb's filtered stream." },
3100 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
3101 "Flush gdb's filtered stdout stream." },
3102 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
3103 "selected_thread () -> gdb.InferiorThread.\n\
3104 Return the selected thread object." },
3105 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
3106 "selected_inferior () -> gdb.Inferior.\n\
3107 Return the selected inferior object." },
3108 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
3109 "inferiors () -> (gdb.Inferior, ...).\n\
3110 Return a tuple containing all inferiors." },
3112 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames
, METH_NOARGS
,
3113 "invalidate_cached_frames () -> None.\n\
3114 Invalidate any cached frame objects in gdb.\n\
3115 Intended for internal use only." },
3117 { "convenience_variable", gdbpy_convenience_variable
, METH_VARARGS
,
3118 "convenience_variable (NAME) -> value.\n\
3119 Return the value of the convenience variable $NAME,\n\
3120 or None if not set." },
3121 { "set_convenience_variable", gdbpy_set_convenience_variable
, METH_VARARGS
,
3122 "convenience_variable (NAME, VALUE) -> None.\n\
3123 Set the value of the convenience variable $NAME." },
3126 { "register_window_type", (PyCFunction
) gdbpy_register_tui_window
,
3127 METH_VARARGS
| METH_KEYWORDS
,
3128 "register_window_type (NAME, CONSTRUCTOR) -> None\n\
3129 Register a TUI window constructor." },
3132 { "architecture_names", gdbpy_all_architecture_names
, METH_NOARGS
,
3133 "architecture_names () -> List.\n\
3134 Return a list of all the architecture names GDB understands." },
3136 { "connections", gdbpy_connections
, METH_NOARGS
,
3137 "connections () -> List.\n\
3138 Return a list of gdb.TargetConnection objects." },
3140 { "format_address", (PyCFunction
) gdbpy_format_address
,
3141 METH_VARARGS
| METH_KEYWORDS
,
3142 "format_address (ADDRESS, PROG_SPACE, ARCH) -> String.\n\
3143 Format ADDRESS, an address within PROG_SPACE, a gdb.Progspace, using\n\
3144 ARCH, a gdb.Architecture to determine the address size. The format of\n\
3145 the returned string is 'ADDRESS <SYMBOL+OFFSET>' without the quotes." },
3147 { "current_language", gdbpy_current_language
, METH_NOARGS
,
3148 "current_language () -> string\n\
3149 Return the name of the currently selected language." },
3151 { "print_options", gdbpy_print_options
, METH_NOARGS
,
3152 "print_options () -> dict\n\
3153 Return the current print options." },
3155 { "notify_mi", (PyCFunction
) gdbpy_notify_mi
,
3156 METH_VARARGS
| METH_KEYWORDS
,
3157 "notify_mi (name, data) -> None\n\
3158 Output async record to MI channels if any." },
3160 { "warning", (PyCFunction
) gdbpy_warning
,
3161 METH_VARARGS
| METH_KEYWORDS
,
3162 "warning (text) -> None\n\
3163 Print a warning." },
3165 {NULL
, NULL
, 0, NULL
}
3168 /* Define all the event objects. */
3169 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
3170 PyTypeObject name##_event_object_type \
3171 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
3173 PyVarObject_HEAD_INIT (NULL, 0) \
3174 "gdb." py_name, /* tp_name */ \
3175 sizeof (event_object), /* tp_basicsize */ \
3176 0, /* tp_itemsize */ \
3177 evpy_dealloc, /* tp_dealloc */ \
3179 0, /* tp_getattr */ \
3180 0, /* tp_setattr */ \
3181 0, /* tp_compare */ \
3183 0, /* tp_as_number */ \
3184 0, /* tp_as_sequence */ \
3185 0, /* tp_as_mapping */ \
3189 0, /* tp_getattro */ \
3190 0, /* tp_setattro */ \
3191 0, /* tp_as_buffer */ \
3192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
3194 0, /* tp_traverse */ \
3196 0, /* tp_richcompare */ \
3197 0, /* tp_weaklistoffset */ \
3199 0, /* tp_iternext */ \
3200 0, /* tp_methods */ \
3201 0, /* tp_members */ \
3202 0, /* tp_getset */ \
3203 &base, /* tp_base */ \
3205 0, /* tp_descr_get */ \
3206 0, /* tp_descr_set */ \
3207 0, /* tp_dictoffset */ \
3211 #include "py-event-types.def"
3212 #undef GDB_PY_DEFINE_EVENT_TYPE
3214 #endif /* HAVE_PYTHON */