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