]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/python/python.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / python / python.c
... / ...
CommitLineData
1/* General python/gdb code
2
3 Copyright (C) 2008-2025 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20#include "arch-utils.h"
21#include "command.h"
22#include "ui-out.h"
23#include "cli/cli-script.h"
24#include "cli/cli-cmds.h"
25#include "progspace.h"
26#include "objfiles.h"
27#include "value.h"
28#include "language.h"
29#include "gdbsupport/event-loop.h"
30#include "readline/tilde.h"
31#include "python.h"
32#include "extension-priv.h"
33#include "cli/cli-utils.h"
34#include <ctype.h>
35#include "location.h"
36#include "run-on-main-thread.h"
37#include "observable.h"
38#include "build-id.h"
39#include "cli/cli-style.h"
40
41#if GDB_SELF_TEST
42#include "gdbsupport/selftest.h"
43#endif
44
45/* Declared constants and enum for python stack printing. */
46static const char python_excp_none[] = "none";
47static const char python_excp_full[] = "full";
48static const char python_excp_message[] = "message";
49
50/* "set python print-stack" choices. */
51static const char *const python_excp_enums[] =
52 {
53 python_excp_none,
54 python_excp_full,
55 python_excp_message,
56 NULL
57 };
58
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
62 the default. */
63static const char *gdbpy_should_print_stack = python_excp_message;
64
65\f
66#ifdef HAVE_PYTHON
67
68#include "cli/cli-decode.h"
69#include "charset.h"
70#include "top.h"
71#include "ui.h"
72#include "python-internal.h"
73#include "linespec.h"
74#include "source.h"
75#include "gdbsupport/version.h"
76#include "target.h"
77#include "gdbthread.h"
78#include "interps.h"
79#include "event-top.h"
80#include "py-event.h"
81#include "py-color.h"
82
83/* True if Python has been successfully initialized, false
84 otherwise. */
85
86int gdb_python_initialized;
87
88extern PyMethodDef python_GdbMethods[];
89
90PyObject *gdb_module;
91PyObject *gdb_python_module;
92
93/* Some string constants we may wish to use. */
94PyObject *gdbpy_to_string_cst;
95PyObject *gdbpy_children_cst;
96PyObject *gdbpy_display_hint_cst;
97PyObject *gdbpy_doc_cst;
98PyObject *gdbpy_enabled_cst;
99PyObject *gdbpy_value_cst;
100
101/* The GdbError exception. */
102PyObject *gdbpy_gdberror_exc;
103
104/* The `gdb.error' base class. */
105PyObject *gdbpy_gdb_error;
106
107/* The `gdb.MemoryError' exception. */
108PyObject *gdbpy_gdb_memory_error;
109
110static script_sourcer_func gdbpy_source_script;
111static objfile_script_sourcer_func gdbpy_source_objfile_script;
112static objfile_script_executor_func gdbpy_execute_objfile_script;
113static void gdbpy_initialize (const struct extension_language_defn *);
114static int gdbpy_initialized (const struct extension_language_defn *);
115static void finalize_python (const struct extension_language_defn *);
116static void gdbpy_eval_from_control_command
117 (const struct extension_language_defn *, struct command_line *cmd);
118static void gdbpy_start_type_printers (const struct extension_language_defn *,
119 struct ext_lang_type_printers *);
120static 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> *);
124static void gdbpy_free_type_printers (const struct extension_language_defn *,
125 struct ext_lang_type_printers *);
126static void gdbpy_set_quit_flag (const struct extension_language_defn *);
127static bool gdbpy_check_quit_flag (const struct extension_language_defn *);
128static enum ext_lang_rc gdbpy_before_prompt_hook
129 (const struct extension_language_defn *, const char *current_gdb_prompt);
130static std::optional<std::string> gdbpy_colorize
131 (const std::string &filename, const std::string &contents,
132 enum language lang);
133static std::optional<std::string> gdbpy_colorize_disasm
134(const std::string &content, gdbarch *gdbarch);
135static ext_lang_missing_file_result gdbpy_handle_missing_debuginfo
136 (const struct extension_language_defn *extlang, struct objfile *objfile);
137static 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);
140
141/* The interface between gdb proper and loading of python scripts. */
142
143static const struct extension_language_script_ops python_extension_script_ops =
144{
145 gdbpy_source_script,
146 gdbpy_source_objfile_script,
147 gdbpy_execute_objfile_script,
148 gdbpy_auto_load_enabled
149};
150
151/* The interface between gdb proper and python extensions. */
152
153static const struct extension_language_ops python_extension_ops =
154{
155 gdbpy_initialize,
156 gdbpy_initialized,
157 finalize_python,
158
159 gdbpy_eval_from_control_command,
160
161 gdbpy_start_type_printers,
162 gdbpy_apply_type_printers,
163 gdbpy_free_type_printers,
164
165 gdbpy_apply_val_pretty_printer,
166
167 gdbpy_apply_frame_filter,
168
169 gdbpy_load_ptwrite_filter,
170
171 gdbpy_preserve_values,
172
173 gdbpy_breakpoint_has_cond,
174 gdbpy_breakpoint_cond_says_stop,
175
176 gdbpy_set_quit_flag,
177 gdbpy_check_quit_flag,
178
179 gdbpy_before_prompt_hook,
180
181 gdbpy_get_matching_xmethod_workers,
182
183 gdbpy_colorize,
184
185 gdbpy_colorize_disasm,
186
187 gdbpy_print_insn,
188
189 gdbpy_handle_missing_debuginfo,
190 gdbpy_find_objfile_from_buildid
191};
192
193#endif /* HAVE_PYTHON */
194
195/* The main struct describing GDB's interface to the Python
196 extension language. */
197const struct extension_language_defn extension_language_python =
198{
199 EXT_LANG_PYTHON,
200 "python",
201 "Python",
202
203 ".py",
204 "-gdb.py",
205
206 python_control,
207
208#ifdef HAVE_PYTHON
209 &python_extension_script_ops,
210 &python_extension_ops
211#else
212 NULL,
213 NULL
214#endif
215};
216
217#ifdef HAVE_PYTHON
218
219/* Architecture and language to be used in callbacks from
220 the Python interpreter. */
221struct gdbarch *gdbpy_enter::python_gdbarch;
222
223gdbpy_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)
227{
228 /* We should not ever enter Python unless initialized. */
229 if (!gdb_python_initialized)
230 error (_("Python not initialized"));
231
232 m_previous_active = set_active_ext_lang (&extension_language_python);
233
234 m_state = PyGILState_Ensure ();
235
236 python_gdbarch = gdbarch;
237 if (language != nullptr)
238 set_language (language->la_language);
239
240 /* Save it and ensure ! PyErr_Occurred () afterwards. */
241 m_error.emplace ();
242}
243
244gdbpy_enter::~gdbpy_enter ()
245{
246 /* Leftover Python error is forbidden by Python Exception Handling. */
247 if (PyErr_Occurred ())
248 {
249 /* This order is similar to the one calling error afterwards. */
250 gdbpy_print_stack ();
251 warning (_("internal error: Unhandled Python exception"));
252 }
253
254 m_error->restore ();
255
256 python_gdbarch = m_gdbarch;
257 if (m_language != nullptr)
258 set_language (m_language->la_language);
259
260 restore_active_ext_lang (m_previous_active);
261 PyGILState_Release (m_state);
262}
263
264struct gdbarch *
265gdbpy_enter::get_gdbarch ()
266{
267 if (python_gdbarch != nullptr)
268 return python_gdbarch;
269 return get_current_arch ();
270}
271
272void
273gdbpy_enter::finalize ()
274{
275 python_gdbarch = current_inferior ()->arch ();
276}
277
278/* Set the quit flag. */
279
280static void
281gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
282{
283 PyErr_SetInterrupt ();
284}
285
286/* Return true if the quit flag has been set, false otherwise. */
287
288static bool
289gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
290{
291 if (!gdb_python_initialized)
292 return false;
293
294 gdbpy_gil gil;
295 return PyOS_InterruptOccurred ();
296}
297
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
302 file. */
303
304static int
305eval_python_command (const char *command, int start_symbol,
306 const char *filename = nullptr)
307{
308 PyObject *m, *d;
309
310 m = PyImport_AddModule ("__main__");
311 if (m == NULL)
312 return -1;
313
314 d = PyModule_GetDict (m);
315 if (d == NULL)
316 return -1;
317
318 bool file_set = false;
319 if (filename != nullptr)
320 {
321 gdbpy_ref<> file = host_string_to_python_string ("__file__");
322 if (file == nullptr)
323 return -1;
324
325 /* PyDict_GetItemWithError returns a borrowed reference. */
326 PyObject *found = PyDict_GetItemWithError (d, file.get ());
327 if (found == nullptr)
328 {
329 if (PyErr_Occurred ())
330 return -1;
331
332 gdbpy_ref<> filename_obj = host_string_to_python_string (filename);
333 if (filename_obj == nullptr)
334 return -1;
335
336 if (PyDict_SetItem (d, file.get (), filename_obj.get ()) < 0)
337 return -1;
338 if (PyDict_SetItemString (d, "__cached__", Py_None) < 0)
339 return -1;
340
341 file_set = true;
342 }
343 }
344
345 /* Use this API because it is in Python 3.2. */
346 gdbpy_ref<> code (Py_CompileStringExFlags (command,
347 filename == nullptr
348 ? "<string>"
349 : filename,
350 start_symbol,
351 nullptr, -1));
352
353 int result = -1;
354 if (code != nullptr)
355 {
356 gdbpy_ref<> eval_result (PyEval_EvalCode (code.get (), d, d));
357 if (eval_result != nullptr)
358 result = 0;
359 }
360
361 if (file_set)
362 {
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;
366 if (result < 0)
367 save_error.emplace ();
368
369 /* CPython also just ignores errors here. These should be
370 expected to be exceedingly rare anyway. */
371 if (PyDict_DelItemString (d, "__file__") < 0)
372 PyErr_Clear ();
373 if (PyDict_DelItemString (d, "__cached__") < 0)
374 PyErr_Clear ();
375
376 if (save_error.has_value ())
377 save_error->restore ();
378 }
379
380 return result;
381}
382
383/* Implementation of the gdb "python-interactive" command. */
384
385static void
386python_interactive_command (const char *arg, int from_tty)
387{
388 struct ui *ui = current_ui;
389 int err;
390
391 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
392
393 arg = skip_spaces (arg);
394
395 gdbpy_enter enter_py;
396
397 if (arg && *arg)
398 {
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);
402 }
403 else
404 {
405 err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
406 dont_repeat ();
407 }
408
409 if (err)
410 gdbpy_handle_exception ();
411}
412
413/* Like PyRun_SimpleFile, but if there is an exception, it is not
414 automatically displayed. FILE is the Python script to run named
415 FILENAME.
416
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. */
425
426static int
427python_run_simple_file (FILE *file, const char *filename)
428{
429 std::string contents = read_remainder_of_file (file);
430 return eval_python_command (contents.c_str (), Py_file_input, filename);
431}
432
433/* Given a command_line, return a command string suitable for passing
434 to Python. Lines in the string are separated by newlines. */
435
436static std::string
437compute_python_string (struct command_line *l)
438{
439 struct command_line *iter;
440 std::string script;
441
442 for (iter = l; iter; iter = iter->next)
443 {
444 script += iter->line;
445 script += '\n';
446 }
447 return script;
448}
449
450/* Take a command line structure representing a 'python' command, and
451 evaluate its body using the Python interpreter. */
452
453static void
454gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
455 struct command_line *cmd)
456{
457 if (cmd->body_list_1 != nullptr)
458 error (_("Invalid \"python\" block structure."));
459
460 gdbpy_enter enter_py;
461
462 std::string script = compute_python_string (cmd->body_list_0.get ());
463 int ret = eval_python_command (script.c_str (), Py_file_input);
464 if (ret != 0)
465 gdbpy_handle_exception ();
466}
467
468/* Implementation of the gdb "python" command. */
469
470static void
471python_command (const char *arg, int from_tty)
472{
473 gdbpy_enter enter_py;
474
475 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
476
477 arg = skip_spaces (arg);
478 if (arg && *arg)
479 {
480 int ret = eval_python_command (arg, Py_file_input);
481 if (ret != 0)
482 gdbpy_handle_exception ();
483 }
484 else
485 {
486 counted_command_line l = get_command_line (python_control, "");
487
488 execute_control_command_untraced (l.get ());
489 }
490}
491
492\f
493
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
496 get_parameter. */
497PyObject *
498gdbpy_parameter_value (const setting &var)
499{
500 switch (var.type ())
501 {
502 case var_string:
503 case var_string_noescape:
504 case var_optional_filename:
505 case var_filename:
506 case var_enum:
507 {
508 const char *str;
509 if (var.type () == var_enum)
510 str = var.get<const char *> ();
511 else
512 str = var.get<std::string> ().c_str ();
513
514 return host_string_to_python_string (str).release ();
515 }
516
517 case var_color:
518 {
519 const ui_file_style::color &color = var.get<ui_file_style::color> ();
520 return create_color_object (color).release ();
521 }
522
523 case var_boolean:
524 {
525 if (var.get<bool> ())
526 Py_RETURN_TRUE;
527 else
528 Py_RETURN_FALSE;
529 }
530
531 case var_auto_boolean:
532 {
533 enum auto_boolean ab = var.get<enum auto_boolean> ();
534
535 if (ab == AUTO_BOOLEAN_TRUE)
536 Py_RETURN_TRUE;
537 else if (ab == AUTO_BOOLEAN_FALSE)
538 Py_RETURN_FALSE;
539 else
540 Py_RETURN_NONE;
541 }
542
543 case var_uinteger:
544 case var_integer:
545 case var_pinteger:
546 {
547 LONGEST value
548 = (var.type () == var_uinteger
549 ? static_cast<LONGEST> (var.get<unsigned int> ())
550 : static_cast<LONGEST> (var.get<int> ()));
551
552 if (var.extra_literals () != nullptr)
553 for (const literal_def *l = var.extra_literals ();
554 l->literal != nullptr;
555 l++)
556 if (value == l->use)
557 {
558 if (strcmp (l->literal, "unlimited") == 0)
559 {
560 /* Compatibility hack for API brokenness. */
561 if (var.type () == var_pinteger
562 && l->val.has_value ()
563 && *l->val == -1)
564 value = -1;
565 else
566 Py_RETURN_NONE;
567 }
568 else if (l->val.has_value ())
569 value = *l->val;
570 else
571 return host_string_to_python_string (l->literal).release ();
572 }
573
574 if (var.type () == var_uinteger)
575 return
576 gdb_py_object_from_ulongest
577 (static_cast<unsigned int> (value)).release ();
578 else
579 return
580 gdb_py_object_from_longest
581 (static_cast<int> (value)).release ();
582 }
583 }
584
585 return PyErr_Format (PyExc_RuntimeError,
586 _("Programmer error: unhandled type."));
587}
588
589/* A Python function which returns a gdb parameter's value as a Python
590 value. */
591
592static PyObject *
593gdbpy_parameter (PyObject *self, PyObject *args)
594{
595 struct cmd_list_element *alias, *prefix, *cmd;
596 const char *arg;
597 int found = -1;
598
599 if (! PyArg_ParseTuple (args, "s", &arg))
600 return NULL;
601
602 std::string newarg = std::string ("show ") + arg;
603
604 try
605 {
606 found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
607 }
608 catch (const gdb_exception &ex)
609 {
610 return gdbpy_handle_gdb_exception (nullptr, ex);
611 }
612
613 if (cmd == CMD_LIST_AMBIGUOUS)
614 return PyErr_Format (PyExc_RuntimeError,
615 _("Parameter `%s' is ambiguous."), arg);
616 else if (!found)
617 return PyErr_Format (PyExc_RuntimeError,
618 _("Could not find parameter `%s'."), arg);
619
620 if (!cmd->var.has_value ())
621 return PyErr_Format (PyExc_RuntimeError,
622 _("`%s' is not a parameter."), arg);
623
624 return gdbpy_parameter_value (*cmd->var);
625}
626
627/* Wrapper for target_charset. */
628
629static PyObject *
630gdbpy_target_charset (PyObject *self, PyObject *args)
631{
632 const char *cset = target_charset (gdbpy_enter::get_gdbarch ());
633
634 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
635}
636
637/* Wrapper for target_wide_charset. */
638
639static PyObject *
640gdbpy_target_wide_charset (PyObject *self, PyObject *args)
641{
642 const char *cset = target_wide_charset (gdbpy_enter::get_gdbarch ());
643
644 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
645}
646
647/* Implement gdb.host_charset(). */
648
649static PyObject *
650gdbpy_host_charset (PyObject *self, PyObject *args)
651{
652 const char *cset = host_charset ();
653
654 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
655}
656
657/* A Python function which evaluates a string using the gdb CLI. */
658
659static PyObject *
660execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
661{
662 const char *arg;
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 };
668
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))
673 return nullptr;
674
675 bool from_tty = false;
676 if (from_tty_obj != nullptr)
677 {
678 int cmp = PyObject_IsTrue (from_tty_obj);
679 if (cmp < 0)
680 return nullptr;
681 from_tty = (cmp != 0);
682 }
683
684 bool to_string = false;
685 if (to_string_obj != nullptr)
686 {
687 int cmp = PyObject_IsTrue (to_string_obj);
688 if (cmp < 0)
689 return nullptr;
690 to_string = (cmp != 0);
691 }
692
693 bool styling_p = !to_string;
694 if (styling != nullptr)
695 {
696 int cmp = PyObject_IsTrue (styling);
697 if (cmp < 0)
698 return nullptr;
699 styling_p = (cmp != 0);
700 }
701
702 std::string to_string_res;
703
704 scoped_restore preventer = prevent_dont_repeat ();
705
706 /* If the executed command raises an exception, we may have to
707 enable stdin and recover the GDB prompt.
708
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
712 this:
713
714 User runs "continue"
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
719
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.
723
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.
728
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 (&current_ui->keep_prompt_blocked,
733 prompt_was_blocked);
734
735 try
736 {
737 gdbpy_allow_threads allow_threads;
738
739 struct interp *interp;
740
741 std::string arg_copy = arg;
742 bool first = true;
743 char *save_ptr = nullptr;
744 auto reader
745 = [&] (std::string &buffer)
746 {
747 const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
748 "\n", &save_ptr);
749 first = false;
750 return result;
751 };
752
753 counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
754
755 {
756 scoped_restore save_async = make_scoped_restore (&current_ui->async,
757 0);
758
759 scoped_restore save_uiout = make_scoped_restore (&current_uiout);
760
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;
766 if (!styling_p)
767 disable_styling.emplace ();
768
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 ();
773
774 if (to_string)
775 {
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
779 styled. */
780 to_string_res
781 = execute_control_commands_to_string (lines.get (), from_tty,
782 true);
783 }
784 else
785 execute_control_commands (lines.get (), from_tty);
786 }
787
788 /* Do any commands attached to breakpoint we stopped at. */
789 bpstat_do_actions ();
790 }
791 catch (const gdb_exception &except)
792 {
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);
800 }
801
802 if (to_string)
803 return PyUnicode_Decode (to_string_res.c_str (), to_string_res.size (),
804 host_charset (), nullptr);
805 Py_RETURN_NONE;
806}
807
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. */
820
821static PyObject *
822gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
823{
824 char *regex = NULL;
825 std::vector<symbol_search> symbols;
826 unsigned long count = 0;
827 PyObject *symtab_list = NULL;
828 PyObject *minsyms_p_obj = NULL;
829 int minsyms_p = 0;
830 unsigned int throttle = 0;
831 static const char *keywords[] = {"regex","minsyms", "throttle",
832 "symtabs", NULL};
833
834 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
835 &regex, &PyBool_Type,
836 &minsyms_p_obj, &throttle,
837 &symtab_list))
838 return NULL;
839
840 /* Parse minsyms keyword. */
841 if (minsyms_p_obj != NULL)
842 {
843 int cmp = PyObject_IsTrue (minsyms_p_obj);
844 if (cmp < 0)
845 return NULL;
846 minsyms_p = cmp;
847 }
848
849 global_symbol_searcher spec (SEARCH_FUNCTION_DOMAIN, regex);
850
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)
861 {
862 gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
863
864 if (iter == NULL)
865 return NULL;
866
867 while (true)
868 {
869 gdbpy_ref<> next (PyIter_Next (iter.get ()));
870
871 if (next == NULL)
872 {
873 if (PyErr_Occurred ())
874 return NULL;
875 break;
876 }
877
878 gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
879 "filename"));
880
881 if (obj_name == NULL)
882 return NULL;
883
884 /* Is the object file still valid? */
885 if (obj_name == Py_None)
886 continue;
887
888 gdb::unique_xmalloc_ptr<char> filename =
889 python_string_to_target_string (obj_name.get ());
890
891 if (filename == NULL)
892 return NULL;
893
894 spec.add_filename (std::move (filename));
895 }
896 }
897
898 /* The search spec. */
899 symbols = spec.search ();
900
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)
904 {
905 /* Minimal symbols included? */
906 if (minsyms_p)
907 {
908 if (p.msymbol.minsym != NULL)
909 count++;
910 }
911
912 if (p.symbol != NULL)
913 count++;
914 }
915
916 /* Check throttle bounds and exit if in excess. */
917 if (throttle != 0 && count > throttle)
918 {
919 PyErr_SetString (PyExc_RuntimeError,
920 _("Number of breakpoints exceeds throttled maximum."));
921 return NULL;
922 }
923
924 gdbpy_ref<> return_list (PyList_New (0));
925
926 if (return_list == NULL)
927 return NULL;
928
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)
933 {
934 std::string symbol_name;
935
936 /* Skipping minimal symbols? */
937 if (minsyms_p == 0)
938 if (p.msymbol.minsym != NULL)
939 continue;
940
941 if (p.msymbol.minsym == NULL)
942 {
943 struct symtab *symtab = p.symbol->symtab ();
944 const char *fullname = symtab_to_fullname (symtab);
945
946 symbol_name = fullname;
947 symbol_name += ":";
948 symbol_name += p.symbol->linkage_name ();
949 }
950 else
951 symbol_name = p.msymbol.minsym->linkage_name ();
952
953 gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
954 gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
955 &breakpoint_object_type,
956 argList.get ()));
957
958 /* Tolerate individual breakpoint failures. */
959 if (obj == NULL)
960 gdbpy_print_stack ();
961 else
962 {
963 if (PyList_Append (return_list.get (), obj.get ()) == -1)
964 return NULL;
965 }
966 }
967 return return_list.release ();
968}
969
970/* A Python function which is a wrapper for decode_line_1. */
971
972static PyObject *
973gdbpy_decode_line (PyObject *self, PyObject *args)
974{
975 const char *arg = NULL;
976 gdbpy_ref<> result;
977 gdbpy_ref<> unparsed;
978 location_spec_up locspec;
979
980 if (! PyArg_ParseTuple (args, "|s", &arg))
981 return NULL;
982
983 /* Treat a string consisting of just whitespace the same as
984 NULL. */
985 if (arg != NULL)
986 {
987 arg = skip_spaces (arg);
988 if (*arg == '\0')
989 arg = NULL;
990 }
991
992 if (arg != NULL)
993 locspec = string_to_location_spec_basic (&arg, current_language,
994 symbol_name_match_type::WILD);
995
996 std::vector<symtab_and_line> decoded_sals;
997 symtab_and_line def_sal;
998 gdb::array_view<symtab_and_line> sals;
999 try
1000 {
1001 if (locspec != NULL)
1002 {
1003 decoded_sals = decode_line_1 (locspec.get (), 0, NULL, NULL, 0);
1004 sals = decoded_sals;
1005 }
1006 else
1007 {
1008 set_default_source_symtab_and_line ();
1009 def_sal = get_current_source_symtab_and_line (current_program_space);
1010 sals = def_sal;
1011 }
1012 }
1013 catch (const gdb_exception &ex)
1014 {
1015 /* We know this will always throw. */
1016 return gdbpy_handle_gdb_exception (nullptr, ex);
1017 }
1018
1019 if (!sals.empty ())
1020 {
1021 result.reset (PyTuple_New (sals.size ()));
1022 if (result == NULL)
1023 return NULL;
1024 for (size_t i = 0; i < sals.size (); ++i)
1025 {
1026 PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
1027 if (obj == NULL)
1028 return NULL;
1029
1030 PyTuple_SetItem (result.get (), i, obj);
1031 }
1032 }
1033 else
1034 result = gdbpy_ref<>::new_reference (Py_None);
1035
1036 gdbpy_ref<> return_result (PyTuple_New (2));
1037 if (return_result == NULL)
1038 return NULL;
1039
1040 if (arg != NULL && strlen (arg) > 0)
1041 {
1042 unparsed.reset (PyUnicode_FromString (arg));
1043 if (unparsed == NULL)
1044 return NULL;
1045 }
1046 else
1047 unparsed = gdbpy_ref<>::new_reference (Py_None);
1048
1049 PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
1050 PyTuple_SetItem (return_result.get (), 1, result.release ());
1051
1052 return return_result.release ();
1053}
1054
1055/* Parse a string and evaluate it as an expression. */
1056static PyObject *
1057gdbpy_parse_and_eval (PyObject *self, PyObject *args, PyObject *kw)
1058{
1059 static const char *keywords[] = { "expression", "global_context", nullptr };
1060
1061 const char *expr_str;
1062 PyObject *global_context_obj = nullptr;
1063
1064 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!", keywords,
1065 &expr_str,
1066 &PyBool_Type, &global_context_obj))
1067 return nullptr;
1068
1069 parser_flags flags = 0;
1070 if (global_context_obj != NULL)
1071 {
1072 int cmp = PyObject_IsTrue (global_context_obj);
1073 if (cmp < 0)
1074 return nullptr;
1075 if (cmp)
1076 flags |= PARSER_LEAVE_BLOCK_ALONE;
1077 }
1078
1079 PyObject *result = nullptr;
1080 try
1081 {
1082 scoped_value_mark free_values;
1083 struct value *val;
1084 {
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);
1092 }
1093 result = value_to_value_object (val);
1094 }
1095 catch (const gdb_exception &except)
1096 {
1097 return gdbpy_handle_gdb_exception (nullptr, except);
1098 }
1099
1100 return result;
1101}
1102
1103/* Implementation of gdb.invalidate_cached_frames. */
1104
1105static PyObject *
1106gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
1107{
1108 reinit_frame_cache ();
1109 Py_RETURN_NONE;
1110}
1111
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. */
1117
1118static void
1119gdbpy_source_script (const struct extension_language_defn *extlang,
1120 FILE *file, const char *filename)
1121{
1122 gdbpy_enter enter_py;
1123 int result = python_run_simple_file (file, filename);
1124 if (result != 0)
1125 gdbpy_handle_exception ();
1126}
1127
1128\f
1129
1130/* Posting and handling events. */
1131
1132/* A single event. */
1133struct gdbpy_event
1134{
1135 gdbpy_event (gdbpy_ref<> &&func)
1136 : m_func (func.release ())
1137 {
1138 }
1139
1140 gdbpy_event (gdbpy_event &&other) noexcept
1141 : m_func (other.m_func)
1142 {
1143 other.m_func = nullptr;
1144 }
1145
1146 gdbpy_event (const gdbpy_event &other)
1147 : m_func (other.m_func)
1148 {
1149 gdbpy_gil gil;
1150 Py_XINCREF (m_func);
1151 }
1152
1153 ~gdbpy_event ()
1154 {
1155 gdbpy_gil gil;
1156 Py_XDECREF (m_func);
1157 }
1158
1159 gdbpy_event &operator= (const gdbpy_event &other) = delete;
1160
1161 void operator() ()
1162 {
1163 gdbpy_enter enter_py;
1164
1165 gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
1166 if (call_result == NULL)
1167 gdbpy_print_stack ();
1168 }
1169
1170private:
1171
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. */
1175 PyObject *m_func;
1176};
1177
1178/* Submit an event to the gdb thread. */
1179static PyObject *
1180gdbpy_post_event (PyObject *self, PyObject *args)
1181{
1182 PyObject *func;
1183
1184 if (!PyArg_ParseTuple (args, "O", &func))
1185 return NULL;
1186
1187 if (!PyCallable_Check (func))
1188 {
1189 PyErr_SetString (PyExc_RuntimeError,
1190 _("Posted event is not callable"));
1191 return NULL;
1192 }
1193
1194 gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
1195 gdbpy_event event (std::move (func_ref));
1196 run_on_main_thread (event);
1197
1198 Py_RETURN_NONE;
1199}
1200
1201/* Interrupt the current operation on the main thread. */
1202static PyObject *
1203gdbpy_interrupt (PyObject *self, PyObject *args)
1204{
1205 {
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;
1211
1212 set_quit_flag ();
1213 }
1214
1215 Py_RETURN_NONE;
1216}
1217
1218\f
1219
1220/* This is the extension_language_ops.before_prompt "method". */
1221
1222static enum ext_lang_rc
1223gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
1224 const char *current_gdb_prompt)
1225{
1226 if (!gdb_python_initialized)
1227 return EXT_LANG_RC_NOP;
1228
1229 gdbpy_enter enter_py;
1230
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;
1234
1235 if (gdb_python_module
1236 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
1237 {
1238 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
1239 "prompt_hook"));
1240 if (hook == NULL)
1241 {
1242 gdbpy_print_stack ();
1243 return EXT_LANG_RC_ERROR;
1244 }
1245
1246 if (PyCallable_Check (hook.get ()))
1247 {
1248 gdbpy_ref<> current_prompt (PyUnicode_FromString (current_gdb_prompt));
1249 if (current_prompt == NULL)
1250 {
1251 gdbpy_print_stack ();
1252 return EXT_LANG_RC_ERROR;
1253 }
1254
1255 gdbpy_ref<> result
1256 (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
1257 NULL));
1258 if (result == NULL)
1259 {
1260 gdbpy_print_stack ();
1261 return EXT_LANG_RC_ERROR;
1262 }
1263
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 ()))
1268 {
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;
1274 }
1275
1276 if (result != Py_None)
1277 {
1278 gdb::unique_xmalloc_ptr<char>
1279 prompt (python_string_to_host_string (result.get ()));
1280
1281 if (prompt == NULL)
1282 {
1283 gdbpy_print_stack ();
1284 return EXT_LANG_RC_ERROR;
1285 }
1286
1287 set_prompt (prompt.get ());
1288 return EXT_LANG_RC_OK;
1289 }
1290 }
1291 }
1292
1293 return EXT_LANG_RC_NOP;
1294}
1295
1296/* This is the extension_language_ops.colorize "method". */
1297
1298static std::optional<std::string>
1299gdbpy_colorize (const std::string &filename, const std::string &contents,
1300 enum language lang)
1301{
1302 if (!gdb_python_initialized)
1303 return {};
1304
1305 gdbpy_enter enter_py;
1306
1307 gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
1308 if (module == nullptr)
1309 {
1310 gdbpy_print_stack ();
1311 return {};
1312 }
1313
1314 if (!PyObject_HasAttrString (module.get (), "colorize"))
1315 return {};
1316
1317 gdbpy_ref<> hook (PyObject_GetAttrString (module.get (), "colorize"));
1318 if (hook == nullptr)
1319 {
1320 gdbpy_print_stack ();
1321 return {};
1322 }
1323
1324 if (!PyCallable_Check (hook.get ()))
1325 return {};
1326
1327 gdbpy_ref<> fname_arg (PyUnicode_FromString (filename.c_str ()));
1328 if (fname_arg == nullptr)
1329 {
1330 gdbpy_print_stack ();
1331 return {};
1332 }
1333
1334 gdbpy_ref<> lang_arg (PyUnicode_FromString (language_str (lang)));
1335 if (lang_arg == nullptr)
1336 {
1337 gdbpy_print_stack ();
1338 return {};
1339 }
1340
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
1345 thing. */
1346 gdbpy_ref<> contents_arg (PyBytes_FromStringAndSize (contents.c_str (),
1347 contents.size ()));
1348 if (contents_arg == nullptr)
1349 {
1350 gdbpy_print_stack ();
1351 return {};
1352 }
1353
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 (),
1359 fname_arg.get (),
1360 contents_arg.get (),
1361 lang_arg.get (),
1362 nullptr));
1363 if (result == nullptr)
1364 {
1365 gdbpy_print_stack ();
1366 return {};
1367 }
1368
1369 if (result == Py_None)
1370 return {};
1371 else if (!PyBytes_Check (result.get ()))
1372 {
1373 PyErr_SetString (PyExc_TypeError,
1374 _("Return value from gdb.colorize should be a bytes object or None."));
1375 gdbpy_print_stack ();
1376 return {};
1377 }
1378
1379 return std::string (PyBytes_AsString (result.get ()));
1380}
1381
1382/* This is the extension_language_ops.colorize_disasm "method". */
1383
1384static std::optional<std::string>
1385gdbpy_colorize_disasm (const std::string &content, gdbarch *gdbarch)
1386{
1387 if (!gdb_python_initialized)
1388 return {};
1389
1390 gdbpy_enter enter_py;
1391
1392 gdbpy_ref<> module (PyImport_ImportModule ("gdb.styling"));
1393 if (module == nullptr)
1394 {
1395 gdbpy_print_stack ();
1396 return {};
1397 }
1398
1399 if (!PyObject_HasAttrString (module.get (), "colorize_disasm"))
1400 return {};
1401
1402 gdbpy_ref<> hook (PyObject_GetAttrString (module.get (),
1403 "colorize_disasm"));
1404 if (hook == nullptr)
1405 {
1406 gdbpy_print_stack ();
1407 return {};
1408 }
1409
1410 if (!PyCallable_Check (hook.get ()))
1411 return {};
1412
1413 gdbpy_ref<> content_arg (PyBytes_FromString (content.c_str ()));
1414 if (content_arg == nullptr)
1415 {
1416 gdbpy_print_stack ();
1417 return {};
1418 }
1419
1420 gdbpy_ref<> gdbarch_arg (gdbarch_to_arch_object (gdbarch));
1421 if (gdbarch_arg == nullptr)
1422 {
1423 gdbpy_print_stack ();
1424 return {};
1425 }
1426
1427 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1428 content_arg.get (),
1429 gdbarch_arg.get (),
1430 nullptr));
1431 if (result == nullptr)
1432 {
1433 gdbpy_print_stack ();
1434 return {};
1435 }
1436
1437 if (result == Py_None)
1438 return {};
1439
1440 if (!PyBytes_Check (result.get ()))
1441 {
1442 PyErr_SetString (PyExc_TypeError,
1443 _("Return value from gdb.colorize_disasm should be a bytes object or None."));
1444 gdbpy_print_stack ();
1445 return {};
1446 }
1447
1448 return std::string (PyBytes_AsString (result.get ()));
1449}
1450
1451\f
1452
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>'. */
1456
1457static PyObject *
1458gdbpy_format_address (PyObject *self, PyObject *args, PyObject *kw)
1459{
1460 static const char *keywords[] =
1461 {
1462 "address", "progspace", "architecture", nullptr
1463 };
1464 PyObject *addr_obj = nullptr, *pspace_obj = nullptr, *arch_obj = nullptr;
1465 CORE_ADDR addr;
1466 struct gdbarch *gdbarch = nullptr;
1467 struct program_space *pspace = nullptr;
1468
1469 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O|OO", keywords,
1470 &addr_obj, &pspace_obj, &arch_obj))
1471 return nullptr;
1472
1473 if (get_addr_from_python (addr_obj, &addr) < 0)
1474 return nullptr;
1475
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)
1484 arch_obj = nullptr;
1485
1486 if (pspace_obj == nullptr && arch_obj == nullptr)
1487 {
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 ();
1492 }
1493 else if (arch_obj == nullptr || pspace_obj == nullptr)
1494 {
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
1499 arguments. */
1500 PyErr_SetString (PyExc_ValueError,
1501 _("The architecture and progspace arguments must both be supplied"));
1502 return nullptr;
1503 }
1504 else
1505 {
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))
1509 {
1510 PyErr_SetString (PyExc_TypeError,
1511 _("The progspace argument is not a gdb.Progspace object"));
1512 return nullptr;
1513 }
1514
1515 pspace = progspace_object_to_program_space (pspace_obj);
1516 if (pspace == nullptr)
1517 {
1518 PyErr_SetString (PyExc_ValueError,
1519 _("The progspace argument is not valid"));
1520 return nullptr;
1521 }
1522
1523 if (!gdbpy_is_architecture (arch_obj))
1524 {
1525 PyErr_SetString (PyExc_TypeError,
1526 _("The architecture argument is not a gdb.Architecture object"));
1527 return nullptr;
1528 }
1529
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);
1534 }
1535
1536 /* By this point we should know the program space and architecture we are
1537 going to use. */
1538 gdb_assert (pspace != nullptr);
1539 gdb_assert (gdbarch != nullptr);
1540
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);
1545
1546 /* Format the address, and return it as a string. */
1547 string_file buf;
1548 print_address (gdbarch, addr, &buf);
1549 return PyUnicode_FromString (buf.c_str ());
1550}
1551
1552\f
1553
1554/* Printing. */
1555
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. */
1559
1560static PyObject *
1561gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
1562{
1563 const char *arg;
1564 static const char *keywords[] = { "text", "stream", NULL };
1565 int stream_type = 0;
1566
1567 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
1568 &stream_type))
1569 return NULL;
1570
1571 try
1572 {
1573 switch (stream_type)
1574 {
1575 case 1:
1576 {
1577 gdb_printf (gdb_stderr, "%s", arg);
1578 break;
1579 }
1580 case 2:
1581 {
1582 gdb_printf (gdb_stdlog, "%s", arg);
1583 break;
1584 }
1585 default:
1586 gdb_printf (gdb_stdout, "%s", arg);
1587 }
1588 }
1589 catch (const gdb_exception &except)
1590 {
1591 return gdbpy_handle_gdb_exception (nullptr, except);
1592 }
1593
1594 Py_RETURN_NONE;
1595}
1596
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
1599 is gdb_stdout. */
1600
1601static PyObject *
1602gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
1603{
1604 static const char *keywords[] = { "stream", NULL };
1605 int stream_type = 0;
1606
1607 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1608 &stream_type))
1609 return NULL;
1610
1611 switch (stream_type)
1612 {
1613 case 1:
1614 {
1615 if (gdb_stderr != nullptr)
1616 gdb_flush (gdb_stderr);
1617 break;
1618 }
1619 case 2:
1620 {
1621 if (gdb_stdlog != nullptr)
1622 gdb_flush (gdb_stdlog);
1623 break;
1624 }
1625 default:
1626 if (gdb_stdout != nullptr)
1627 gdb_flush (gdb_stdout);
1628 }
1629
1630 Py_RETURN_NONE;
1631}
1632
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
1635 be empty. */
1636
1637static PyObject *
1638gdbpy_warning (PyObject *self, PyObject *args, PyObject *kw)
1639{
1640 const char *text;
1641 static const char *keywords[] = { "text", nullptr };
1642
1643 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s", keywords, &text))
1644 return nullptr;
1645
1646 if (strlen (text) == 0)
1647 {
1648 PyErr_SetString (PyExc_ValueError,
1649 _("Empty text string passed to gdb.warning"));
1650 return nullptr;
1651 }
1652
1653 try
1654 {
1655 warning ("%s", text);
1656 }
1657 catch (const gdb_exception &ex)
1658 {
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);
1662 }
1663
1664 Py_RETURN_NONE;
1665}
1666
1667/* Return non-zero if print-stack is not "none". */
1668
1669int
1670gdbpy_print_python_errors_p (void)
1671{
1672 return gdbpy_should_print_stack != python_excp_none;
1673}
1674
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
1678 set. */
1679void
1680gdbpy_print_stack (void)
1681{
1682
1683 /* Print "none", just clear exception. */
1684 if (gdbpy_should_print_stack == python_excp_none)
1685 {
1686 PyErr_Clear ();
1687 }
1688 /* Print "full" message and backtrace. */
1689 else if (gdbpy_should_print_stack == python_excp_full)
1690 {
1691 PyErr_Print ();
1692 /* PyErr_Print doesn't necessarily end output with a newline.
1693 This works because Python's stdout/stderr is fed through
1694 gdb_printf. */
1695 try
1696 {
1697 begin_line ();
1698 }
1699 catch (const gdb_exception &except)
1700 {
1701 }
1702 }
1703 /* Print "message", just error print message. */
1704 else
1705 {
1706 gdbpy_err_fetch fetched_error;
1707
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
1711 error. */
1712 if (msg != NULL)
1713 type = fetched_error.type_to_string ();
1714
1715 try
1716 {
1717 if (msg == NULL || type == NULL)
1718 {
1719 /* An error occurred computing the string representation of the
1720 error message. */
1721 gdb_printf (gdb_stderr,
1722 _("Error occurred computing Python error "
1723 "message.\n"));
1724 PyErr_Clear ();
1725 }
1726 else
1727 gdb_printf (gdb_stderr, "Python Exception %s: %s\n",
1728 type.get (), msg.get ());
1729 }
1730 catch (const gdb_exception &except)
1731 {
1732 }
1733 }
1734}
1735
1736/* Like gdbpy_print_stack, but if the exception is a
1737 KeyboardException, throw a gdb "quit" instead. */
1738
1739void
1740gdbpy_print_stack_or_quit ()
1741{
1742 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
1743 {
1744 PyErr_Clear ();
1745 throw_quit ("Quit");
1746 }
1747 gdbpy_print_stack ();
1748}
1749
1750\f
1751
1752/* Return a sequence holding all the Progspaces. */
1753
1754static PyObject *
1755gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1756{
1757 gdbpy_ref<> list (PyList_New (0));
1758 if (list == NULL)
1759 return NULL;
1760
1761 for (struct program_space *ps : program_spaces)
1762 {
1763 gdbpy_ref<> item = pspace_to_pspace_object (ps);
1764
1765 if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
1766 return NULL;
1767 }
1768
1769 return list.release ();
1770}
1771
1772/* Return the name of the current language. */
1773
1774static PyObject *
1775gdbpy_current_language (PyObject *unused1, PyObject *unused2)
1776{
1777 return host_string_to_python_string (current_language->name ()).release ();
1778}
1779
1780\f
1781
1782/* See python.h. */
1783struct objfile *gdbpy_current_objfile;
1784
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
1789 "method". */
1790
1791static void
1792gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
1793 struct objfile *objfile, FILE *file,
1794 const char *filename)
1795{
1796 if (!gdb_python_initialized)
1797 return;
1798
1799 gdbpy_enter enter_py (objfile->arch ());
1800 scoped_restore restire_current_objfile
1801 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1802
1803 int result = python_run_simple_file (file, filename);
1804 if (result != 0)
1805 gdbpy_print_stack ();
1806}
1807
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
1812 "method". */
1813
1814static void
1815gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
1816 struct objfile *objfile, const char *name,
1817 const char *script)
1818{
1819 if (!gdb_python_initialized)
1820 return;
1821
1822 gdbpy_enter enter_py (objfile->arch ());
1823 scoped_restore restire_current_objfile
1824 = make_scoped_restore (&gdbpy_current_objfile, objfile);
1825
1826 int ret = eval_python_command (script, Py_file_input);
1827 if (ret != 0)
1828 gdbpy_print_stack ();
1829}
1830
1831/* Return the current Objfile, or None if there isn't one. */
1832
1833static PyObject *
1834gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1835{
1836 if (! gdbpy_current_objfile)
1837 Py_RETURN_NONE;
1838
1839 return objfile_to_objfile_object (gdbpy_current_objfile).release ();
1840}
1841
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. */
1847
1848static ext_lang_missing_file_result
1849gdbpy_handle_missing_debuginfo (const struct extension_language_defn *extlang,
1850 struct objfile *objfile)
1851{
1852 /* Early exit if Python is not initialised. */
1853 if (!gdb_python_initialized || gdb_python_module == nullptr)
1854 return {};
1855
1856 struct gdbarch *gdbarch = objfile->arch ();
1857
1858 gdbpy_enter enter_py (gdbarch);
1859
1860 /* Convert OBJFILE into the corresponding Python object. */
1861 gdbpy_ref<> pyo_objfile = objfile_to_objfile_object (objfile);
1862 if (pyo_objfile == nullptr)
1863 {
1864 gdbpy_print_stack ();
1865 return {};
1866 }
1867
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)
1872 {
1873 gdbpy_print_stack ();
1874 return {};
1875 }
1876
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 (),
1880 nullptr));
1881 if (pyo_execute_ret == nullptr)
1882 {
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 ();
1886 return {};
1887 }
1888
1889 /* Parse the result, and convert it back to the C++ object. */
1890 if (pyo_execute_ret == Py_None)
1891 return {};
1892
1893 if (PyBool_Check (pyo_execute_ret.get ()))
1894 {
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);
1899 }
1900
1901 if (!gdbpy_is_string (pyo_execute_ret.get ()))
1902 {
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 ();
1907 return {};
1908 }
1909
1910 gdb::unique_xmalloc_ptr<char> filename
1911 = python_string_to_host_string (pyo_execute_ret.get ());
1912 if (filename == nullptr)
1913 {
1914 gdbpy_print_stack ();
1915 return {};
1916 }
1917
1918 return ext_lang_missing_file_result (std::string (filename.get ()));
1919}
1920
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. */
1926
1927static ext_lang_missing_file_result
1928gdbpy_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)
1932{
1933 gdb_assert (pspace != nullptr);
1934 gdb_assert (build_id != nullptr);
1935 gdb_assert (missing_filename != nullptr);
1936
1937 /* Early exit if Python is not initialised. */
1938 if (!gdb_python_initialized || gdb_python_module == nullptr)
1939 return {};
1940
1941 gdbpy_enter enter_py;
1942
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)
1947 {
1948 gdbpy_print_stack ();
1949 return {};
1950 }
1951
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)
1955 {
1956 gdbpy_print_stack ();
1957 return {};
1958 }
1959
1960 /* Convert PSPACE to a Python object. */
1961 gdbpy_ref<> pyo_pspace = pspace_to_pspace_object (pspace);
1962 if (pyo_pspace == nullptr)
1963 {
1964 gdbpy_print_stack ();
1965 return {};
1966 }
1967
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)
1972 {
1973 gdbpy_print_stack ();
1974 return {};
1975 }
1976
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 (),
1981 nullptr));
1982 if (pyo_execute_ret == nullptr)
1983 {
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 ();
1987 return {};
1988 }
1989
1990 /* Parse the result, and convert it back to the C++ object. */
1991 if (pyo_execute_ret == Py_None)
1992 return {};
1993
1994 if (PyBool_Check (pyo_execute_ret.get ()))
1995 {
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);
2000 }
2001
2002 if (!gdbpy_is_string (pyo_execute_ret.get ()))
2003 {
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 ();
2008 return {};
2009 }
2010
2011 gdb::unique_xmalloc_ptr<char> filename
2012 = python_string_to_host_string (pyo_execute_ret.get ());
2013 if (filename == nullptr)
2014 {
2015 gdbpy_print_stack ();
2016 return {};
2017 }
2018
2019 return ext_lang_missing_file_result (std::string (filename.get ()));
2020}
2021
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". */
2026
2027static void
2028gdbpy_start_type_printers (const struct extension_language_defn *extlang,
2029 struct ext_lang_type_printers *ext_printers)
2030{
2031 PyObject *printers_obj = NULL;
2032
2033 if (!gdb_python_initialized)
2034 return;
2035
2036 gdbpy_enter enter_py;
2037
2038 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
2039 if (type_module == NULL)
2040 {
2041 gdbpy_print_stack ();
2042 return;
2043 }
2044
2045 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
2046 "get_type_recognizers"));
2047 if (func == NULL)
2048 {
2049 gdbpy_print_stack ();
2050 return;
2051 }
2052
2053 printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
2054 if (printers_obj == NULL)
2055 gdbpy_print_stack ();
2056 else
2057 ext_printers->py_type_printers = printers_obj;
2058}
2059
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
2062 EXT_LANG_RC_OK.
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". */
2066
2067static enum ext_lang_rc
2068gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
2069 const struct ext_lang_type_printers *ext_printers,
2070 struct type *type,
2071 gdb::unique_xmalloc_ptr<char> *prettied_type)
2072{
2073 PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
2074 gdb::unique_xmalloc_ptr<char> result;
2075
2076 if (printers_obj == NULL)
2077 return EXT_LANG_RC_NOP;
2078
2079 if (!gdb_python_initialized)
2080 return EXT_LANG_RC_NOP;
2081
2082 gdbpy_enter enter_py;
2083
2084 gdbpy_ref<> type_obj (type_to_type_object (type));
2085 if (type_obj == NULL)
2086 {
2087 gdbpy_print_stack ();
2088 return EXT_LANG_RC_ERROR;
2089 }
2090
2091 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
2092 if (type_module == NULL)
2093 {
2094 gdbpy_print_stack ();
2095 return EXT_LANG_RC_ERROR;
2096 }
2097
2098 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
2099 "apply_type_recognizers"));
2100 if (func == NULL)
2101 {
2102 gdbpy_print_stack ();
2103 return EXT_LANG_RC_ERROR;
2104 }
2105
2106 gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
2107 printers_obj,
2108 type_obj.get (),
2109 (char *) NULL));
2110 if (result_obj == NULL)
2111 {
2112 gdbpy_print_stack ();
2113 return EXT_LANG_RC_ERROR;
2114 }
2115
2116 if (result_obj == Py_None)
2117 return EXT_LANG_RC_NOP;
2118
2119 result = python_string_to_host_string (result_obj.get ());
2120 if (result == NULL)
2121 {
2122 gdbpy_print_stack ();
2123 return EXT_LANG_RC_ERROR;
2124 }
2125
2126 *prettied_type = std::move (result);
2127 return EXT_LANG_RC_OK;
2128}
2129
2130/* Free the result of start_type_printers.
2131 This is the extension_language_ops.free_type_printers "method". */
2132
2133static void
2134gdbpy_free_type_printers (const struct extension_language_defn *extlang,
2135 struct ext_lang_type_printers *ext_printers)
2136{
2137 PyObject *printers = (PyObject *) ext_printers->py_type_printers;
2138
2139 if (printers == NULL)
2140 return;
2141
2142 if (!gdb_python_initialized)
2143 return;
2144
2145 gdbpy_enter enter_py;
2146 Py_DECREF (printers);
2147}
2148
2149#else /* HAVE_PYTHON */
2150
2151/* Dummy implementation of the gdb "python-interactive" and "python"
2152 command. */
2153
2154static void
2155python_interactive_command (const char *arg, int from_tty)
2156{
2157 arg = skip_spaces (arg);
2158 if (arg && *arg)
2159 error (_("Python scripting is not supported in this copy of GDB."));
2160 else
2161 {
2162 counted_command_line l = get_command_line (python_control, "");
2163
2164 execute_control_command_untraced (l.get ());
2165 }
2166}
2167
2168static void
2169python_command (const char *arg, int from_tty)
2170{
2171 python_interactive_command (arg, from_tty);
2172}
2173
2174#endif /* HAVE_PYTHON */
2175
2176/* Stand-in for Py_IsInitialized (). To be used because after a python fatal
2177 error, no calls into Python are allowed. */
2178
2179static bool py_isinitialized = false;
2180
2181/* Variables to hold the effective values of "python ignore-environment" and
2182 "python dont-write-bytecode" at Python initialization. */
2183
2184static bool python_ignore_environment_at_python_initialization;
2185static bool python_dont_write_bytecode_at_python_initialization;
2186
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. */
2190static bool python_ignore_environment = false;
2191
2192/* Implement 'show python ignore-environment'. */
2193
2194static void
2195show_python_ignore_environment (struct ui_file *file, int from_tty,
2196 struct cmd_list_element *c, const char *value)
2197{
2198 gdb_printf (file, _("Python's ignore-environment setting is %s.\n"),
2199 value);
2200}
2201
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. */
2206
2207static void
2208set_python_ignore_environment (const char *args, int from_tty,
2209 struct cmd_list_element *c)
2210{
2211 if (py_isinitialized)
2212 {
2213 python_ignore_environment
2214 = python_ignore_environment_at_python_initialization;
2215
2216 warning (_("Setting python ignore-environment after Python"
2217 " initialization has no effect, try setting this during"
2218 " early initialization"));
2219 }
2220}
2221
2222/* When this is turned on before Python is initialised then Python will
2223 not write `.pyc' files on import of a module. */
2224static enum auto_boolean python_dont_write_bytecode = AUTO_BOOLEAN_AUTO;
2225
2226
2227/* Return true if environment variable PYTHONDONTWRITEBYTECODE is set to a
2228 non-empty string. */
2229
2230static bool
2231env_python_dont_write_bytecode ()
2232{
2233 const char *envvar = getenv ("PYTHONDONTWRITEBYTECODE");
2234 return envvar != nullptr && envvar[0] != '\0';
2235}
2236
2237/* Implement 'show python dont-write-bytecode'. */
2238
2239static void
2240show_python_dont_write_bytecode (struct ui_file *file, int from_tty,
2241 struct cmd_list_element *c, const char *value)
2242{
2243 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
2244 {
2245 const char *auto_string
2246 = ((python_ignore_environment
2247 || !env_python_dont_write_bytecode ())
2248 ? "off"
2249 : "on");
2250
2251 gdb_printf (file,
2252 _("Python's dont-write-bytecode setting is %s (currently %s).\n"),
2253 value, auto_string);
2254 }
2255 else
2256 gdb_printf (file, _("Python's dont-write-bytecode setting is %s.\n"),
2257 value);
2258}
2259
2260#ifdef HAVE_PYTHON
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. */
2264
2265static int
2266python_write_bytecode ()
2267{
2268 int wbc = 0;
2269
2270 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
2271 {
2272 if (python_ignore_environment)
2273 wbc = 1;
2274 else
2275 wbc = env_python_dont_write_bytecode () ? 0 : 1;
2276 }
2277 else
2278 wbc = python_dont_write_bytecode == AUTO_BOOLEAN_TRUE ? 0 : 1;
2279
2280 return wbc;
2281}
2282#endif /* HAVE_PYTHON */
2283
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. */
2288
2289static void
2290set_python_dont_write_bytecode (const char *args, int from_tty,
2291 struct cmd_list_element *c)
2292{
2293 if (py_isinitialized)
2294 {
2295 python_dont_write_bytecode
2296 = (python_dont_write_bytecode_at_python_initialization
2297 ? AUTO_BOOLEAN_TRUE
2298 : AUTO_BOOLEAN_FALSE);
2299
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"));
2304 }
2305}
2306
2307\f
2308
2309/* Lists for 'set python' commands. */
2310
2311static struct cmd_list_element *user_set_python_list;
2312static struct cmd_list_element *user_show_python_list;
2313
2314/* Initialize the Python code. */
2315
2316#ifdef HAVE_PYTHON
2317
2318/* This is installed as a final cleanup and cleans up the
2319 interpreter. This lets Python's 'atexit' work. */
2320
2321static void
2322finalize_python (const struct extension_language_defn *ignore)
2323{
2324 if (!gdb_python_initialized)
2325 return;
2326
2327 struct active_ext_lang_state *previous_active;
2328
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. */
2334
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);
2338
2339 (void) PyGILState_Ensure ();
2340 gdbpy_enter::finalize ();
2341
2342 /* Call the gdbpy_finalize_* functions from every *.c file. */
2343 gdbpy_initialize_file::finalize_all ();
2344
2345 Py_Finalize ();
2346
2347 gdb_python_initialized = false;
2348 restore_active_ext_lang (previous_active);
2349}
2350
2351static struct PyModuleDef python_GdbModuleDef =
2352{
2353 PyModuleDef_HEAD_INIT,
2354 "_gdb",
2355 NULL,
2356 -1,
2357 python_GdbMethods,
2358 NULL,
2359 NULL,
2360 NULL,
2361 NULL
2362};
2363
2364/* This is called via the PyImport_AppendInittab mechanism called
2365 during initialization, to make the built-in _gdb module known to
2366 Python. */
2367PyMODINIT_FUNC init__gdb_module (void);
2368PyMODINIT_FUNC
2369init__gdb_module (void)
2370{
2371 return PyModule_Create (&python_GdbModuleDef);
2372}
2373
2374/* Emit a gdb.GdbExitingEvent, return a negative value if there are any
2375 errors, otherwise, return 0. */
2376
2377static int
2378emit_exiting_event (int exit_code)
2379{
2380 if (evregpy_no_listeners_p (gdb_py_events.gdb_exiting))
2381 return 0;
2382
2383 gdbpy_ref<> event_obj = create_event_object (&gdb_exiting_event_object_type);
2384 if (event_obj == nullptr)
2385 return -1;
2386
2387 gdbpy_ref<> code = gdb_py_object_from_longest (exit_code);
2388 if (evpy_add_attribute (event_obj.get (), "exit_code", code.get ()) < 0)
2389 return -1;
2390
2391 return evpy_emit_event (event_obj.get (), gdb_py_events.gdb_exiting);
2392}
2393
2394/* Callback for the gdb_exiting observable. EXIT_CODE is the value GDB
2395 will exit with. */
2396
2397static void
2398gdbpy_gdb_exiting (int exit_code)
2399{
2400 if (!gdb_python_initialized)
2401 return;
2402
2403 gdbpy_enter enter_py;
2404
2405 if (emit_exiting_event (exit_code) < 0)
2406 gdbpy_print_stack ();
2407}
2408
2409#if PY_VERSION_HEX < 0x030a0000
2410/* Signal handler to convert a SIGABRT into an exception. */
2411
2412static void
2413catch_python_fatal (int signum)
2414{
2415 signal (SIGABRT, catch_python_fatal);
2416
2417 throw_exception_sjlj (gdb_exception {RETURN_ERROR, GENERIC_ERROR});
2418}
2419
2420/* Call Py_Initialize (), and return true if successful. */
2421
2422static bool
2423py_initialize_catch_abort ()
2424{
2425 auto prev_handler = signal (SIGABRT, catch_python_fatal);
2426 SCOPE_EXIT { signal (SIGABRT, prev_handler); };
2427
2428 TRY_SJLJ
2429 {
2430 Py_Initialize ();
2431 py_isinitialized = true;
2432 }
2433 CATCH_SJLJ (e, RETURN_MASK_ERROR)
2434 {
2435 }
2436 END_CATCH_SJLJ;
2437
2438 return py_isinitialized;
2439}
2440#endif
2441
2442/* Initialize python, either by calling Py_Initialize or
2443 Py_InitializeFromConfig, and return true if successful. */
2444
2445static bool
2446py_initialize ()
2447{
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;
2453
2454 /* Don't show "python dont-write-bytecode auto" after Python
2455 initialization. */
2456 python_dont_write_bytecode
2457 = (python_dont_write_bytecode_at_python_initialization
2458 ? AUTO_BOOLEAN_TRUE
2459 : AUTO_BOOLEAN_FALSE);
2460
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;
2470#else
2471 wchar_t *progname_copy = nullptr;
2472 SCOPE_EXIT { XDELETEVEC (progname_copy); };
2473#endif
2474
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:
2479 /foo/bin/python
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));
2485
2486 {
2487 std::string oldloc = setlocale (LC_ALL, NULL);
2488 SCOPE_EXIT { setlocale (LC_ALL, oldloc.c_str ()); };
2489
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)
2495 {
2496 fprintf (stderr, "Could not convert python path to string\n");
2497 return false;
2498 }
2499 }
2500#endif
2501
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 ();
2515#else
2516 PyConfig config;
2517
2518 PyConfig_InitPythonConfig (&config);
2519 PyStatus status;
2520 if (progname_copy != nullptr)
2521 {
2522 status = PyConfig_SetString (&config, &config.program_name,
2523 progname_copy);
2524 if (PyStatus_Exception (status))
2525 goto init_done;
2526 }
2527
2528 config.write_bytecode = !python_dont_write_bytecode_at_python_initialization;
2529 config.use_environment = !python_ignore_environment_at_python_initialization;
2530
2531 status = PyConfig_Read (&config);
2532 if (PyStatus_Exception (status))
2533 goto init_done;
2534
2535 status = Py_InitializeFromConfig (&config);
2536
2537init_done:
2538 PyConfig_Clear (&config);
2539 if (PyStatus_Exception (status))
2540 {
2541 if (PyStatus_IsError (status))
2542 gdb_printf (_("Python initialization failed: %s\n"), status.err_msg);
2543 else
2544 gdb_printf (_("Python initialization failed with exit status: %d\n"),
2545 status.exitcode);
2546 return false;
2547 }
2548
2549 py_isinitialized = true;
2550 return true;
2551#endif
2552}
2553
2554static bool
2555do_start_initialization ()
2556{
2557 /* Define all internal modules. These are all imported (and thus
2558 created) during initialization. */
2559 struct _inittab mods[] =
2560 {
2561 { "_gdb", init__gdb_module },
2562 { "_gdbevents", gdbpy_events_mod_func },
2563 { nullptr, nullptr }
2564 };
2565
2566 if (PyImport_ExtendInittab (mods) < 0)
2567 return false;
2568
2569 if (!py_initialize ())
2570 return false;
2571
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 ();
2577#endif
2578
2579 gdb_module = PyImport_ImportModule ("_gdb");
2580 if (gdb_module == NULL)
2581 return false;
2582
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",
2586 target_name) < 0)
2587 return false;
2588
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)
2593 return false;
2594
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)
2598 return false;
2599
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)
2605 return false;
2606
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)
2611 return false;
2612
2613 /* Call the gdbpy_initialize_* functions from every *.c file. */
2614 if (!gdbpy_initialize_file::initialize_all ())
2615 return false;
2616
2617#define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2618 if (gdbpy_type_ready (&name##_event_object_type) < 0) \
2619 return false;
2620#include "py-event-types.def"
2621#undef GDB_PY_DEFINE_EVENT_TYPE
2622
2623 gdbpy_to_string_cst = PyUnicode_FromString ("to_string");
2624 if (gdbpy_to_string_cst == NULL)
2625 return false;
2626 gdbpy_children_cst = PyUnicode_FromString ("children");
2627 if (gdbpy_children_cst == NULL)
2628 return false;
2629 gdbpy_display_hint_cst = PyUnicode_FromString ("display_hint");
2630 if (gdbpy_display_hint_cst == NULL)
2631 return false;
2632 gdbpy_doc_cst = PyUnicode_FromString ("__doc__");
2633 if (gdbpy_doc_cst == NULL)
2634 return false;
2635 gdbpy_enabled_cst = PyUnicode_FromString ("enabled");
2636 if (gdbpy_enabled_cst == NULL)
2637 return false;
2638 gdbpy_value_cst = PyUnicode_FromString ("value");
2639 if (gdbpy_value_cst == NULL)
2640 return false;
2641
2642 gdb::observers::gdb_exiting.attach (gdbpy_gdb_exiting, "python");
2643
2644 /* Release the GIL while gdb runs. */
2645 PyEval_SaveThread ();
2646
2647 /* Only set this when initialization has succeeded. */
2648 gdb_python_initialized = 1;
2649 return true;
2650}
2651
2652#if GDB_SELF_TEST
2653namespace selftests {
2654
2655/* Entry point for python unit tests. */
2656
2657static void
2658test_python ()
2659{
2660#define CMD(S) execute_command_to_string (S, "python print(5)", 0, true)
2661
2662 std::string output;
2663
2664 CMD (output);
2665 SELF_CHECK (output == "5\n");
2666 output.clear ();
2667
2668 bool saw_exception = false;
2669 {
2670 scoped_restore reset_gdb_python_initialized
2671 = make_scoped_restore (&gdb_python_initialized, 0);
2672 try
2673 {
2674 CMD (output);
2675 }
2676 catch (const gdb_exception &e)
2677 {
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");
2682 }
2683 SELF_CHECK (saw_exception);
2684 SELF_CHECK (output.empty ());
2685 }
2686
2687 saw_exception = false;
2688 {
2689 scoped_restore save_hook
2690 = make_scoped_restore (&hook_set_active_ext_lang,
2691 []() { raise (SIGINT); });
2692 try
2693 {
2694 CMD (output);
2695 }
2696 catch (const gdb_exception_quit &e)
2697 {
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");
2702 }
2703 SELF_CHECK (saw_exception);
2704 SELF_CHECK (output.empty ());
2705 }
2706
2707#undef CMD
2708}
2709
2710#undef CHECK_OUTPUT
2711
2712} /* namespace selftests */
2713#endif /* GDB_SELF_TEST */
2714
2715#endif /* HAVE_PYTHON */
2716
2717/* See python.h. */
2718cmd_list_element *python_cmd_element = nullptr;
2719
2720INIT_GDB_FILE (python)
2721{
2722 cmd_list_element *python_interactive_cmd
2723 = add_com ("python-interactive", class_obscure,
2724 python_interactive_command,
2725#ifdef HAVE_PYTHON
2726 _("\
2727Start an interactive Python prompt.\n\
2728\n\
2729To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
2730prompt).\n\
2731\n\
2732Alternatively, a single-line Python command can be given as an\n\
2733argument, and if the command is an expression, the result will be\n\
2734printed. For example:\n\
2735\n\
2736 (gdb) python-interactive 2 + 3\n\
2737 5")
2738#else /* HAVE_PYTHON */
2739 _("\
2740Start a Python interactive prompt.\n\
2741\n\
2742Python scripting is not supported in this copy of GDB.\n\
2743This command is only a placeholder.")
2744#endif /* HAVE_PYTHON */
2745 );
2746 add_com_alias ("pi", python_interactive_cmd, class_obscure, 1);
2747
2748 python_cmd_element = add_com ("python", class_obscure, python_command,
2749#ifdef HAVE_PYTHON
2750 _("\
2751Evaluate a Python command.\n\
2752\n\
2753The command can be given as an argument, for instance:\n\
2754\n\
2755 python print (23)\n\
2756\n\
2757If no argument is given, the following lines are read and used\n\
2758as the Python commands. Type a line containing \"end\" to indicate\n\
2759the end of the command.")
2760#else /* HAVE_PYTHON */
2761 _("\
2762Evaluate a Python command.\n\
2763\n\
2764Python scripting is not supported in this copy of GDB.\n\
2765This command is only a placeholder.")
2766#endif /* HAVE_PYTHON */
2767 );
2768 add_com_alias ("py", python_cmd_element, class_obscure, 1);
2769
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);
2776
2777 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
2778 &gdbpy_should_print_stack, _("\
2779Set mode for Python stack dump on error."), _("\
2780Show the mode of Python stack printing on error."), _("\
2781none == no stack or message will be printed.\n\
2782full == a message and a stack will be printed.\n\
2783message == an error message without a stack will be printed."),
2784 NULL, NULL,
2785 &user_set_python_list,
2786 &user_show_python_list);
2787
2788 add_setshow_boolean_cmd ("ignore-environment", no_class,
2789 &python_ignore_environment, _("\
2790Set whether the Python interpreter should ignore environment variables."), _("\
2791Show whether the Python interpreter showlist ignore environment variables."), _("\
2792When enabled GDB's Python interpreter will ignore any Python related\n\
2793flags in the environment. This is equivalent to passing `-E' to a\n\
2794python executable."),
2795 set_python_ignore_environment,
2796 show_python_ignore_environment,
2797 &user_set_python_list,
2798 &user_show_python_list);
2799
2800 add_setshow_auto_boolean_cmd ("dont-write-bytecode", no_class,
2801 &python_dont_write_bytecode, _("\
2802Set whether the Python interpreter should avoid byte-compiling python modules."), _("\
2803Show whether the Python interpreter should avoid byte-compiling python modules."), _("\
2804When enabled, GDB's embedded Python interpreter won't byte-compile python\n\
2805modules. In order to take effect, this setting must be enabled in an early\n\
2806initialization 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\
2808can also be issued directly from the GDB command line via the\n\
2809--early-init-eval-command or -eiex command line options.\n\
2810\n\
2811This setting defaults to 'auto'. In this mode, provided the 'python\n\
2812ignore-environment' setting is 'off', the environment variable\n\
2813PYTHONDONTWRITEBYTECODE is examined to determine whether or not to\n\
2814byte-compile python modules. PYTHONDONTWRITEBYTECODE is considered to be\n\
2815off/disabled either when set to the empty string or when the\n\
2816environment variable doesn't exist. All other settings, including those\n\
2817which 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);
2822
2823#ifdef HAVE_PYTHON
2824#if GDB_SELF_TEST
2825 selftests::register_test ("python", selftests::test_python);
2826#endif /* GDB_SELF_TEST */
2827#endif /* HAVE_PYTHON */
2828}
2829
2830#ifdef HAVE_PYTHON
2831
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
2834 success. */
2835
2836static bool
2837do_initialize (const struct extension_language_defn *extlang)
2838{
2839 PyObject *m;
2840 PyObject *sys_path;
2841
2842 /* Add the initial data-directory to sys.path. */
2843
2844 std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
2845 + "python");
2846
2847 sys_path = PySys_GetObject ("path");
2848
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)))
2861 {
2862 PySys_SetPath (L"");
2863 sys_path = PySys_GetObject ("path");
2864 }
2865#endif
2866 if (sys_path && PyList_Check (sys_path))
2867 {
2868 gdbpy_ref<> pythondir (PyUnicode_FromString (gdb_pythondir.c_str ()));
2869 if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
2870 return false;
2871 }
2872 else
2873 return false;
2874
2875 /* Import the gdb module to finish the initialization, and
2876 add it to __main__ for convenience. */
2877 m = PyImport_AddModule ("__main__");
2878 if (m == NULL)
2879 return false;
2880
2881 /* Keep the reference to gdb_python_module since it is in a global
2882 variable. */
2883 gdb_python_module = PyImport_ImportModule ("gdb");
2884 if (gdb_python_module == NULL)
2885 {
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. */
2889 warning (_("\n"
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
2895 warning. */
2896 return true;
2897 }
2898
2899 return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
2900}
2901
2902/* Emit warnings in case python initialization has failed. */
2903
2904static void
2905python_initialization_failed_warnings ()
2906{
2907 const char *pythonhome = nullptr;
2908 const char *pythonpath = nullptr;
2909
2910 if (!python_ignore_environment)
2911 {
2912 pythonhome = getenv ("PYTHONHOME");
2913 pythonpath = getenv ("PYTHONPATH");
2914 }
2915
2916 bool have_pythonhome
2917 = pythonhome != nullptr && pythonhome[0] != '\0';
2918 bool have_pythonpath
2919 = pythonpath != nullptr && pythonpath[0] != '\0';
2920
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."));
2927
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."));
2933}
2934
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". */
2938
2939static void
2940gdbpy_initialize (const struct extension_language_defn *extlang)
2941{
2942 if (!do_start_initialization ())
2943 {
2944 if (py_isinitialized)
2945 {
2946 if (PyErr_Occurred ())
2947 gdbpy_print_stack ();
2948
2949 /* We got no use for the Python interpreter anymore. Finalize it
2950 ASAP. */
2951 Py_Finalize ();
2952 }
2953 else
2954 python_initialization_failed_warnings ();
2955
2956 /* Continue with python disabled. */
2957 return;
2958 }
2959
2960 gdbpy_enter enter_py;
2961
2962 if (!do_initialize (extlang))
2963 {
2964 gdbpy_print_stack ();
2965 warning (_("internal error: Unhandled Python exception"));
2966 }
2967}
2968
2969/* Return non-zero if Python has successfully initialized.
2970 This is the extension_languages_ops.initialized "method". */
2971
2972static int
2973gdbpy_initialized (const struct extension_language_defn *extlang)
2974{
2975 return gdb_python_initialized;
2976}
2977
2978PyMethodDef python_GdbMethods[] =
2979{
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\
2988Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
2989a Python String containing the output of the command if to_string is\n\
2990set to True." },
2991 { "execute_mi", (PyCFunction) gdbpy_execute_mi_command,
2992 METH_VARARGS | METH_KEYWORDS,
2993 "execute_mi (command, arg...) -> dictionary\n\
2994Evaluate command, a string, as a gdb MI command.\n\
2995Arguments (also strings) are passed to the command." },
2996 { "parameter", gdbpy_parameter, METH_VARARGS,
2997 "Return a gdb parameter's value" },
2998
2999 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
3000 "Return a tuple of all breakpoint objects" },
3001
3002 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
3003 "Find the default visualizer for a Value." },
3004
3005 { "progspaces", gdbpy_progspaces, METH_NOARGS,
3006 "Return a sequence of all progspaces." },
3007
3008 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
3009 "Return the current Objfile being loaded, or None." },
3010
3011 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
3012 "newest_frame () -> gdb.Frame.\n\
3013Return the newest frame object." },
3014 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
3015 "selected_frame () -> gdb.Frame.\n\
3016Return the selected frame object." },
3017 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
3018 "stop_reason_string (Integer) -> String.\n\
3019Return a string explaining unwind stop reason." },
3020
3021 { "start_recording", gdbpy_start_recording, METH_VARARGS,
3022 "start_recording ([method] [, format]) -> gdb.Record.\n\
3023Start recording with the given method. If no method is given, will fall back\n\
3024to the system default method. If no format is given, will fall back to the\n\
3025default format for the given method."},
3026 { "current_recording", gdbpy_current_recording, METH_NOARGS,
3027 "current_recording () -> gdb.Record.\n\
3028Return current recording object." },
3029 { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
3030 "stop_recording () -> None.\n\
3031Stop current recording." },
3032
3033 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
3034 METH_VARARGS | METH_KEYWORDS,
3035 "lookup_type (name [, block]) -> type\n\
3036Return 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\
3040Return a tuple with the symbol corresponding to the given name (or None) and\n\
3041a 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\
3046Return 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\
3050Return 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\
3054Return a list of all static-linkage symbols corresponding to the given name." },
3055
3056 { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
3057 METH_VARARGS | METH_KEYWORDS,
3058 "lookup_objfile (name, [by_build_id]) -> objfile\n\
3059Look up the specified objfile.\n\
3060If by_build_id is True, the objfile is looked up by using name\n\
3061as its build id." },
3062
3063 { "decode_line", gdbpy_decode_line, METH_VARARGS,
3064 "decode_line (String) -> Tuple. Decode a string argument the way\n\
3065that 'break' or 'edit' does. Return a tuple containing two elements.\n\
3066The 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\
3068a tuple that contains all the locations that match, represented as\n\
3069gdb.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\
3073Parse String as an expression, evaluate it, and return the result as a Value."
3074 },
3075
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." },
3080
3081 { "target_charset", gdbpy_target_charset, METH_NOARGS,
3082 "target_charset () -> string.\n\
3083Return the name of the current target charset." },
3084 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
3085 "target_wide_charset () -> string.\n\
3086Return the name of the current target wide charset." },
3087 { "host_charset", gdbpy_host_charset, METH_NOARGS,
3088 "host_charset () -> string.\n\
3089Return the name of the current host charset." },
3090 { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
3091 "rbreak (Regex) -> List.\n\
3092Return 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\
3095Parse String and return an argv-like array.\n\
3096Arguments are separate by spaces and may be quoted."
3097 },
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\
3104Return the selected thread object." },
3105 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
3106 "selected_inferior () -> gdb.Inferior.\n\
3107Return the selected inferior object." },
3108 { "inferiors", gdbpy_inferiors, METH_NOARGS,
3109 "inferiors () -> (gdb.Inferior, ...).\n\
3110Return a tuple containing all inferiors." },
3111
3112 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
3113 "invalidate_cached_frames () -> None.\n\
3114Invalidate any cached frame objects in gdb.\n\
3115Intended for internal use only." },
3116
3117 { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
3118 "convenience_variable (NAME) -> value.\n\
3119Return the value of the convenience variable $NAME,\n\
3120or None if not set." },
3121 { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
3122 "convenience_variable (NAME, VALUE) -> None.\n\
3123Set the value of the convenience variable $NAME." },
3124
3125#ifdef TUI
3126 { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
3127 METH_VARARGS | METH_KEYWORDS,
3128 "register_window_type (NAME, CONSTRUCTOR) -> None\n\
3129Register a TUI window constructor." },
3130#endif /* TUI */
3131
3132 { "architecture_names", gdbpy_all_architecture_names, METH_NOARGS,
3133 "architecture_names () -> List.\n\
3134Return a list of all the architecture names GDB understands." },
3135
3136 { "connections", gdbpy_connections, METH_NOARGS,
3137 "connections () -> List.\n\
3138Return a list of gdb.TargetConnection objects." },
3139
3140 { "format_address", (PyCFunction) gdbpy_format_address,
3141 METH_VARARGS | METH_KEYWORDS,
3142 "format_address (ADDRESS, PROG_SPACE, ARCH) -> String.\n\
3143Format ADDRESS, an address within PROG_SPACE, a gdb.Progspace, using\n\
3144ARCH, a gdb.Architecture to determine the address size. The format of\n\
3145the returned string is 'ADDRESS <SYMBOL+OFFSET>' without the quotes." },
3146
3147 { "current_language", gdbpy_current_language, METH_NOARGS,
3148 "current_language () -> string\n\
3149Return the name of the currently selected language." },
3150
3151 { "print_options", gdbpy_print_options, METH_NOARGS,
3152 "print_options () -> dict\n\
3153Return the current print options." },
3154
3155 { "notify_mi", (PyCFunction) gdbpy_notify_mi,
3156 METH_VARARGS | METH_KEYWORDS,
3157 "notify_mi (name, data) -> None\n\
3158Output async record to MI channels if any." },
3159
3160 { "warning", (PyCFunction) gdbpy_warning,
3161 METH_VARARGS | METH_KEYWORDS,
3162 "warning (text) -> None\n\
3163Print a warning." },
3164
3165 {NULL, NULL, 0, NULL}
3166};
3167
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") \
3172 = { \
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 */ \
3178 0, /* tp_print */ \
3179 0, /* tp_getattr */ \
3180 0, /* tp_setattr */ \
3181 0, /* tp_compare */ \
3182 0, /* tp_repr */ \
3183 0, /* tp_as_number */ \
3184 0, /* tp_as_sequence */ \
3185 0, /* tp_as_mapping */ \
3186 0, /* tp_hash */ \
3187 0, /* tp_call */ \
3188 0, /* tp_str */ \
3189 0, /* tp_getattro */ \
3190 0, /* tp_setattro */ \
3191 0, /* tp_as_buffer */ \
3192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
3193 doc, /* tp_doc */ \
3194 0, /* tp_traverse */ \
3195 0, /* tp_clear */ \
3196 0, /* tp_richcompare */ \
3197 0, /* tp_weaklistoffset */ \
3198 0, /* tp_iter */ \
3199 0, /* tp_iternext */ \
3200 0, /* tp_methods */ \
3201 0, /* tp_members */ \
3202 0, /* tp_getset */ \
3203 &base, /* tp_base */ \
3204 0, /* tp_dict */ \
3205 0, /* tp_descr_get */ \
3206 0, /* tp_descr_set */ \
3207 0, /* tp_dictoffset */ \
3208 0, /* tp_init */ \
3209 0 /* tp_alloc */ \
3210 };
3211#include "py-event-types.def"
3212#undef GDB_PY_DEFINE_EVENT_TYPE
3213
3214#endif /* HAVE_PYTHON */