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