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