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