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