]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/python/python.c
gdb: make string-like set show commands use std::string variable
[thirdparty/binutils-gdb.git] / gdb / python / python.c
CommitLineData
d57a3c85
TJB
1/* General python/gdb code
2
3666a048 3 Copyright (C) 2008-2021 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"
cf9c1c75 38#include "gdbsupport/selftest.h"
d57a3c85 39
80b6e756
PM
40/* Declared constants and enum for python stack printing. */
41static const char python_excp_none[] = "none";
42static const char python_excp_full[] = "full";
43static const char python_excp_message[] = "message";
44
45/* "set python print-stack" choices. */
40478521 46static const char *const python_excp_enums[] =
80b6e756
PM
47 {
48 python_excp_none,
49 python_excp_full,
50 python_excp_message,
51 NULL
52 };
53
54/* The exception printing variable. 'full' if we want to print the
55 error message and stack, 'none' if we want to print nothing, and
56 'message' if we only want to print the error message. 'message' is
57 the default. */
58static const char *gdbpy_should_print_stack = python_excp_message;
d57a3c85 59
6dddc817
DE
60#ifdef HAVE_PYTHON
61/* Forward decls, these are defined later. */
e36122e9
TT
62extern const struct extension_language_script_ops python_extension_script_ops;
63extern const struct extension_language_ops python_extension_ops;
6dddc817
DE
64#endif
65
66/* The main struct describing GDB's interface to the Python
67 extension language. */
68const struct extension_language_defn extension_language_python =
69{
70 EXT_LANG_PYTHON,
71 "python",
72 "Python",
73
74 ".py",
75 "-gdb.py",
76
77 python_control,
78
79#ifdef HAVE_PYTHON
80 &python_extension_script_ops,
81 &python_extension_ops
82#else
83 NULL,
84 NULL
85#endif
86};
87\f
d57a3c85
TJB
88#ifdef HAVE_PYTHON
89
d57a3c85
TJB
90#include "cli/cli-decode.h"
91#include "charset.h"
92#include "top.h"
d57a3c85 93#include "python-internal.h"
cb2e07a6
PM
94#include "linespec.h"
95#include "source.h"
268a13a5 96#include "gdbsupport/version.h"
d57a3c85
TJB
97#include "target.h"
98#include "gdbthread.h"
b4a14fd0 99#include "interps.h"
9a27f2c6 100#include "event-top.h"
3f77c769 101#include "py-event.h"
d57a3c85 102
999633ed
TT
103/* True if Python has been successfully initialized, false
104 otherwise. */
105
106int gdb_python_initialized;
107
bcabf420 108extern PyMethodDef python_GdbMethods[];
d57a3c85
TJB
109
110PyObject *gdb_module;
b9516fa1 111PyObject *gdb_python_module;
d57a3c85 112
a6bac58e
TT
113/* Some string constants we may wish to use. */
114PyObject *gdbpy_to_string_cst;
115PyObject *gdbpy_children_cst;
116PyObject *gdbpy_display_hint_cst;
d8906c6f 117PyObject *gdbpy_doc_cst;
967cf477 118PyObject *gdbpy_enabled_cst;
fb6a3ed3 119PyObject *gdbpy_value_cst;
d8906c6f 120
07ca107c
DE
121/* The GdbError exception. */
122PyObject *gdbpy_gdberror_exc;
d452c4bc 123
621c8364
TT
124/* The `gdb.error' base class. */
125PyObject *gdbpy_gdb_error;
126
127/* The `gdb.MemoryError' exception. */
128PyObject *gdbpy_gdb_memory_error;
129
6dddc817
DE
130static script_sourcer_func gdbpy_source_script;
131static objfile_script_sourcer_func gdbpy_source_objfile_script;
9f050062 132static objfile_script_executor_func gdbpy_execute_objfile_script;
041ca48e 133static void gdbpy_initialize (const struct extension_language_defn *);
6dddc817
DE
134static int gdbpy_initialized (const struct extension_language_defn *);
135static void gdbpy_eval_from_control_command
136 (const struct extension_language_defn *, struct command_line *cmd);
137static void gdbpy_start_type_printers (const struct extension_language_defn *,
138 struct ext_lang_type_printers *);
139static enum ext_lang_rc gdbpy_apply_type_printers
140 (const struct extension_language_defn *,
141 const struct ext_lang_type_printers *, struct type *, char **);
142static void gdbpy_free_type_printers (const struct extension_language_defn *,
143 struct ext_lang_type_printers *);
6dddc817
DE
144static void gdbpy_set_quit_flag (const struct extension_language_defn *);
145static int gdbpy_check_quit_flag (const struct extension_language_defn *);
146static enum ext_lang_rc gdbpy_before_prompt_hook
147 (const struct extension_language_defn *, const char *current_gdb_prompt);
f6474de9
TT
148static gdb::optional<std::string> gdbpy_colorize
149 (const std::string &filename, const std::string &contents);
6dddc817
DE
150
151/* The interface between gdb proper and loading of python scripts. */
152
e36122e9 153const struct extension_language_script_ops python_extension_script_ops =
6dddc817
DE
154{
155 gdbpy_source_script,
156 gdbpy_source_objfile_script,
9f050062 157 gdbpy_execute_objfile_script,
6dddc817
DE
158 gdbpy_auto_load_enabled
159};
160
161/* The interface between gdb proper and python extensions. */
162
e36122e9 163const struct extension_language_ops python_extension_ops =
6dddc817 164{
041ca48e 165 gdbpy_initialize,
6dddc817
DE
166 gdbpy_initialized,
167
168 gdbpy_eval_from_control_command,
169
170 gdbpy_start_type_printers,
171 gdbpy_apply_type_printers,
172 gdbpy_free_type_printers,
173
174 gdbpy_apply_val_pretty_printer,
175
176 gdbpy_apply_frame_filter,
177
178 gdbpy_preserve_values,
179
180 gdbpy_breakpoint_has_cond,
181 gdbpy_breakpoint_cond_says_stop,
182
6dddc817
DE
183 gdbpy_set_quit_flag,
184 gdbpy_check_quit_flag,
185
883964a7
SC
186 gdbpy_before_prompt_hook,
187
883964a7 188 gdbpy_get_matching_xmethod_workers,
f6474de9
TT
189
190 gdbpy_colorize,
6dddc817
DE
191};
192
d452c4bc
UW
193/* Architecture and language to be used in callbacks from
194 the Python interpreter. */
195struct gdbarch *python_gdbarch;
196const struct language_defn *python_language;
197
4ecee2c4
TT
198gdbpy_enter::gdbpy_enter (struct gdbarch *gdbarch,
199 const struct language_defn *language)
200: m_gdbarch (python_gdbarch),
201 m_language (python_language)
d452c4bc 202{
4ecee2c4
TT
203 /* We should not ever enter Python unless initialized. */
204 if (!gdb_python_initialized)
205 error (_("Python not initialized"));
d452c4bc 206
4ecee2c4 207 m_previous_active = set_active_ext_lang (&extension_language_python);
d59b6f6c 208
4ecee2c4
TT
209 m_state = PyGILState_Ensure ();
210
211 python_gdbarch = gdbarch;
212 python_language = language;
213
214 /* Save it and ensure ! PyErr_Occurred () afterwards. */
5c329e6a 215 m_error.emplace ();
4ecee2c4
TT
216}
217
218gdbpy_enter::~gdbpy_enter ()
219{
8dc78533
JK
220 /* Leftover Python error is forbidden by Python Exception Handling. */
221 if (PyErr_Occurred ())
222 {
223 /* This order is similar to the one calling error afterwards. */
224 gdbpy_print_stack ();
225 warning (_("internal error: Unhandled Python exception"));
226 }
227
5c329e6a 228 m_error->restore ();
8dc78533 229
4ecee2c4
TT
230 python_gdbarch = m_gdbarch;
231 python_language = m_language;
6dddc817 232
4ecee2c4 233 restore_active_ext_lang (m_previous_active);
aa369509 234 PyGILState_Release (m_state);
4ecee2c4
TT
235}
236
c47bae85
KB
237/* A helper class to save and restore the GIL, but without touching
238 the other globals that are handled by gdbpy_enter. */
239
240class gdbpy_gil
241{
242public:
243
244 gdbpy_gil ()
245 : m_state (PyGILState_Ensure ())
246 {
247 }
248
249 ~gdbpy_gil ()
250 {
251 PyGILState_Release (m_state);
252 }
253
254 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
255
256private:
257
258 PyGILState_STATE m_state;
259};
260
522002f9
TT
261/* Set the quit flag. */
262
6dddc817
DE
263static void
264gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
522002f9
TT
265{
266 PyErr_SetInterrupt ();
267}
268
269/* Return true if the quit flag has been set, false otherwise. */
270
6dddc817
DE
271static int
272gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
522002f9 273{
c47bae85
KB
274 if (!gdb_python_initialized)
275 return 0;
276
277 gdbpy_gil gil;
522002f9
TT
278 return PyOS_InterruptOccurred ();
279}
280
8315665e
YPK
281/* Evaluate a Python command like PyRun_SimpleString, but uses
282 Py_single_input which prints the result of expressions, and does
283 not automatically print the stack on errors. */
284
285static int
286eval_python_command (const char *command)
287{
59876f8f 288 PyObject *m, *d;
8315665e
YPK
289
290 m = PyImport_AddModule ("__main__");
291 if (m == NULL)
292 return -1;
293
294 d = PyModule_GetDict (m);
295 if (d == NULL)
296 return -1;
7780f186 297 gdbpy_ref<> v (PyRun_StringFlags (command, Py_single_input, d, d, NULL));
8315665e
YPK
298 if (v == NULL)
299 return -1;
300
9a27f2c6 301#ifndef IS_PY3K
8315665e
YPK
302 if (Py_FlushLine ())
303 PyErr_Clear ();
9a27f2c6 304#endif
8315665e
YPK
305
306 return 0;
307}
308
309/* Implementation of the gdb "python-interactive" command. */
310
311static void
0b39b52e 312python_interactive_command (const char *arg, int from_tty)
8315665e 313{
f38d3ad1 314 struct ui *ui = current_ui;
8315665e
YPK
315 int err;
316
b7b633e9 317 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
8315665e 318
529480d0 319 arg = skip_spaces (arg);
8315665e 320
396a78b6 321 gdbpy_enter enter_py (get_current_arch (), current_language);
8315665e
YPK
322
323 if (arg && *arg)
324 {
075c55e0
TT
325 std::string script = std::string (arg) + "\n";
326 err = eval_python_command (script.c_str ());
8315665e
YPK
327 }
328 else
329 {
f38d3ad1 330 err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
8315665e
YPK
331 dont_repeat ();
332 }
333
334 if (err)
335 {
336 gdbpy_print_stack ();
337 error (_("Error while executing Python code."));
338 }
8315665e
YPK
339}
340
4c63965b
JK
341/* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
342 named FILENAME.
343
344 On Windows hosts few users would build Python themselves (this is no
345 trivial task on this platform), and thus use binaries built by
346 someone else instead. There may happen situation where the Python
347 library and GDB are using two different versions of the C runtime
348 library. Python, being built with VC, would use one version of the
349 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
350 A FILE * from one runtime does not necessarily operate correctly in
7ed7d719
JB
351 the other runtime.
352
27204489
CB
353 To work around this potential issue, we run code in Python to load
354 the script. */
7ed7d719
JB
355
356static void
4c63965b 357python_run_simple_file (FILE *file, const char *filename)
7ed7d719 358{
4c63965b
JK
359#ifndef _WIN32
360
361 PyRun_SimpleFile (file, filename);
362
363#else /* _WIN32 */
364
3ab1ec27
PM
365 /* Because we have a string for a filename, and are using Python to
366 open the file, we need to expand any tilde in the path first. */
9de10f6d 367 gdb::unique_xmalloc_ptr<char> full_path (tilde_expand (filename));
27204489
CB
368
369 if (gdb_python_module == nullptr
370 || ! PyObject_HasAttrString (gdb_python_module, "_execute_file"))
371 error (_("Installation error: gdb._execute_file function is missing"));
372
373 gdbpy_ref<> return_value
374 (PyObject_CallMethod (gdb_python_module, "_execute_file", "s",
375 full_path.get ()));
376 if (return_value == nullptr)
3ab1ec27 377 {
27204489 378 /* Use PyErr_PrintEx instead of gdbpy_print_stack to better match the
dda83cd7 379 behavior of the non-Windows codepath. */
27204489 380 PyErr_PrintEx(0);
3ab1ec27 381 }
256458bc 382
4c63965b 383#endif /* _WIN32 */
7ed7d719 384}
d452c4bc 385
d57a3c85 386/* Given a command_line, return a command string suitable for passing
7f968c89 387 to Python. Lines in the string are separated by newlines. */
d57a3c85 388
7f968c89 389static std::string
d57a3c85
TJB
390compute_python_string (struct command_line *l)
391{
392 struct command_line *iter;
7f968c89 393 std::string script;
d57a3c85 394
d57a3c85
TJB
395 for (iter = l; iter; iter = iter->next)
396 {
7f968c89
TT
397 script += iter->line;
398 script += '\n';
d57a3c85 399 }
d57a3c85
TJB
400 return script;
401}
402
403/* Take a command line structure representing a 'python' command, and
404 evaluate its body using the Python interpreter. */
405
6dddc817
DE
406static void
407gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
408 struct command_line *cmd)
d57a3c85 409{
12453b93 410 int ret;
d57a3c85 411
12973681 412 if (cmd->body_list_1 != nullptr)
d57a3c85
TJB
413 error (_("Invalid \"python\" block structure."));
414
60e600ec 415 gdbpy_enter enter_py (get_current_arch (), current_language);
ca30a762 416
12973681 417 std::string script = compute_python_string (cmd->body_list_0.get ());
7f968c89 418 ret = PyRun_SimpleString (script.c_str ());
12453b93 419 if (ret)
80b6e756 420 error (_("Error while executing Python code."));
d57a3c85
TJB
421}
422
423/* Implementation of the gdb "python" command. */
424
425static void
0b39b52e 426python_command (const char *arg, int from_tty)
d57a3c85 427{
a7785f8c 428 gdbpy_enter enter_py (get_current_arch (), current_language);
b4a14fd0 429
b7b633e9 430 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
b4a14fd0 431
529480d0 432 arg = skip_spaces (arg);
d57a3c85
TJB
433 if (arg && *arg)
434 {
12453b93 435 if (PyRun_SimpleString (arg))
80b6e756 436 error (_("Error while executing Python code."));
d57a3c85
TJB
437 }
438 else
439 {
12973681 440 counted_command_line l = get_command_line (python_control, "");
d59b6f6c 441
93921405 442 execute_control_command_untraced (l.get ());
d57a3c85
TJB
443 }
444}
445
446\f
447
448/* Transform a gdb parameters's value into a Python value. May return
449 NULL (and set a Python exception) on error. Helper function for
450 get_parameter. */
d7b32ed3 451PyObject *
1d7fe7f0 452gdbpy_parameter_value (const setting &var)
d57a3c85 453{
1d7fe7f0 454 switch (var.type ())
d57a3c85
TJB
455 {
456 case var_string:
457 case var_string_noescape:
458 case var_optional_filename:
459 case var_filename:
460 case var_enum:
461 {
1d7fe7f0 462 const char *str;
e0700ba4
SM
463 if (var.type () == var_enum)
464 str = var.get<const char *> ();
465 else
466 str = var.get<std::string> ().c_str ();
d59b6f6c 467
833d985d 468 return host_string_to_python_string (str).release ();
d57a3c85
TJB
469 }
470
471 case var_boolean:
472 {
1d7fe7f0 473 if (var.get<bool> ())
d57a3c85
TJB
474 Py_RETURN_TRUE;
475 else
476 Py_RETURN_FALSE;
477 }
478
479 case var_auto_boolean:
480 {
1d7fe7f0 481 enum auto_boolean ab = var.get<enum auto_boolean> ();
d59b6f6c 482
d57a3c85
TJB
483 if (ab == AUTO_BOOLEAN_TRUE)
484 Py_RETURN_TRUE;
485 else if (ab == AUTO_BOOLEAN_FALSE)
486 Py_RETURN_FALSE;
487 else
488 Py_RETURN_NONE;
489 }
490
491 case var_integer:
1d7fe7f0 492 if (var.get<int> () == INT_MAX)
d57a3c85
TJB
493 Py_RETURN_NONE;
494 /* Fall through. */
495 case var_zinteger:
0489430a 496 case var_zuinteger_unlimited:
1d7fe7f0 497 return gdb_py_object_from_longest (var.get<int> ()).release ();
d57a3c85
TJB
498
499 case var_uinteger:
500 {
1d7fe7f0 501 unsigned int val = var.get<unsigned int> ();
d59b6f6c 502
d57a3c85
TJB
503 if (val == UINT_MAX)
504 Py_RETURN_NONE;
512116ce 505 return gdb_py_object_from_ulongest (val).release ();
0489430a
TT
506 }
507
508 case var_zuinteger:
509 {
1d7fe7f0 510 unsigned int val = var.get<unsigned int> ();
512116ce 511 return gdb_py_object_from_ulongest (val).release ();
d57a3c85
TJB
512 }
513 }
514
256458bc 515 return PyErr_Format (PyExc_RuntimeError,
044c0f87 516 _("Programmer error: unhandled type."));
d57a3c85
TJB
517}
518
519/* A Python function which returns a gdb parameter's value as a Python
520 value. */
521
0c72ed4c 522static PyObject *
8f500870 523gdbpy_parameter (PyObject *self, PyObject *args)
d57a3c85
TJB
524{
525 struct cmd_list_element *alias, *prefix, *cmd;
ddd49eee 526 const char *arg;
cc924cad 527 int found = -1;
d57a3c85
TJB
528
529 if (! PyArg_ParseTuple (args, "s", &arg))
530 return NULL;
531
075c55e0 532 std::string newarg = std::string ("show ") + arg;
d57a3c85 533
a70b8144 534 try
d57a3c85 535 {
075c55e0 536 found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
d57a3c85 537 }
230d2906 538 catch (const gdb_exception &ex)
492d29ea 539 {
075c55e0 540 GDB_PY_HANDLE_EXCEPTION (ex);
492d29ea 541 }
492d29ea 542
cc924cad
TJB
543 if (!found)
544 return PyErr_Format (PyExc_RuntimeError,
044c0f87 545 _("Could not find parameter `%s'."), arg);
d57a3c85 546
1d7fe7f0 547 if (!cmd->var.has_value ())
256458bc 548 return PyErr_Format (PyExc_RuntimeError,
044c0f87 549 _("`%s' is not a parameter."), arg);
1d7fe7f0
LS
550
551 return gdbpy_parameter_value (*cmd->var);
d57a3c85
TJB
552}
553
f870a310
TT
554/* Wrapper for target_charset. */
555
556static PyObject *
557gdbpy_target_charset (PyObject *self, PyObject *args)
558{
559 const char *cset = target_charset (python_gdbarch);
d59b6f6c 560
f870a310
TT
561 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
562}
563
564/* Wrapper for target_wide_charset. */
565
566static PyObject *
567gdbpy_target_wide_charset (PyObject *self, PyObject *args)
568{
569 const char *cset = target_wide_charset (python_gdbarch);
d59b6f6c 570
f870a310
TT
571 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
572}
573
d57a3c85
TJB
574/* A Python function which evaluates a string using the gdb CLI. */
575
576static PyObject *
bc9f0842 577execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
d57a3c85 578{
ddd49eee 579 const char *arg;
bc9f0842
TT
580 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
581 int from_tty, to_string;
2adadf51 582 static const char *keywords[] = { "command", "from_tty", "to_string", NULL };
d57a3c85 583
2adadf51
PA
584 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
585 &PyBool_Type, &from_tty_obj,
586 &PyBool_Type, &to_string_obj))
d57a3c85
TJB
587 return NULL;
588
12453b93
TJB
589 from_tty = 0;
590 if (from_tty_obj)
591 {
bc9f0842 592 int cmp = PyObject_IsTrue (from_tty_obj);
12453b93 593 if (cmp < 0)
bc9f0842 594 return NULL;
12453b93
TJB
595 from_tty = cmp;
596 }
597
bc9f0842
TT
598 to_string = 0;
599 if (to_string_obj)
600 {
601 int cmp = PyObject_IsTrue (to_string_obj);
602 if (cmp < 0)
603 return NULL;
604 to_string = cmp;
605 }
606
db1ec11f
PA
607 std::string to_string_res;
608
1c97054b
BF
609 scoped_restore preventer = prevent_dont_repeat ();
610
a70b8144 611 try
d57a3c85 612 {
b5eba2d8
TT
613 gdbpy_allow_threads allow_threads;
614
e7ea3ec7 615 struct interp *interp;
bc9f0842 616
56bcdbea
TT
617 std::string arg_copy = arg;
618 bool first = true;
619 char *save_ptr = nullptr;
620 auto reader
621 = [&] ()
622 {
623 const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
624 "\n", &save_ptr);
625 first = false;
626 return result;
627 };
628
629 counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
630
a3a6aef4
TT
631 {
632 scoped_restore save_async = make_scoped_restore (&current_ui->async,
633 0);
b4a14fd0 634
a3a6aef4 635 scoped_restore save_uiout = make_scoped_restore (&current_uiout);
cd94f6d5 636
a3a6aef4
TT
637 /* Use the console interpreter uiout to have the same print format
638 for console or MI. */
639 interp = interp_lookup (current_ui, "console");
640 current_uiout = interp->interp_ui_out ();
e7ea3ec7 641
a3a6aef4
TT
642 if (to_string)
643 to_string_res = execute_control_commands_to_string (lines.get (),
644 from_tty);
645 else
646 execute_control_commands (lines.get (), from_tty);
647 }
648
649 /* Do any commands attached to breakpoint we stopped at. */
650 bpstat_do_actions ();
d57a3c85 651 }
230d2906 652 catch (const gdb_exception &except)
492d29ea 653 {
1ba1ac88
AB
654 /* If an exception occurred then we won't hit normal_stop (), or have
655 an exception reach the top level of the event loop, which are the
656 two usual places in which stdin would be re-enabled. So, before we
657 convert the exception and continue back in Python, we should
658 re-enable stdin here. */
659 async_enable_stdin ();
492d29ea
PA
660 GDB_PY_HANDLE_EXCEPTION (except);
661 }
d57a3c85 662
db1ec11f
PA
663 if (to_string)
664 return PyString_FromString (to_string_res.c_str ());
d57a3c85
TJB
665 Py_RETURN_NONE;
666}
667
d8ae99a7
PM
668/* Implementation of Python rbreak command. Take a REGEX and
669 optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
670 Python list that contains newly set breakpoints that match that
671 criteria. REGEX refers to a GDB format standard regex pattern of
672 symbols names to search; MINSYMS is an optional boolean (default
673 False) that indicates if the function should search GDB's minimal
674 symbols; THROTTLE is an optional integer (default unlimited) that
675 indicates the maximum amount of breakpoints allowable before the
676 function exits (note, if the throttle bound is passed, no
677 breakpoints will be set and a runtime error returned); SYMTABS is
678 an optional Python iterable that contains a set of gdb.Symtabs to
679 constrain the search within. */
680
681static PyObject *
682gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
683{
d8ae99a7
PM
684 char *regex = NULL;
685 std::vector<symbol_search> symbols;
686 unsigned long count = 0;
687 PyObject *symtab_list = NULL;
688 PyObject *minsyms_p_obj = NULL;
689 int minsyms_p = 0;
690 unsigned int throttle = 0;
691 static const char *keywords[] = {"regex","minsyms", "throttle",
692 "symtabs", NULL};
d8ae99a7
PM
693
694 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
695 &regex, &PyBool_Type,
696 &minsyms_p_obj, &throttle,
697 &symtab_list))
698 return NULL;
699
700 /* Parse minsyms keyword. */
701 if (minsyms_p_obj != NULL)
702 {
703 int cmp = PyObject_IsTrue (minsyms_p_obj);
704 if (cmp < 0)
705 return NULL;
706 minsyms_p = cmp;
707 }
708
470c0b1c
AB
709 global_symbol_searcher spec (FUNCTIONS_DOMAIN, regex);
710 SCOPE_EXIT {
711 for (const char *elem : spec.filenames)
712 xfree ((void *) elem);
713 };
714
d8ae99a7
PM
715 /* The "symtabs" keyword is any Python iterable object that returns
716 a gdb.Symtab on each iteration. If specified, iterate through
717 the provided gdb.Symtabs and extract their full path. As
718 python_string_to_target_string returns a
719 gdb::unique_xmalloc_ptr<char> and a vector containing these types
720 cannot be coerced to a const char **p[] via the vector.data call,
721 release the value from the unique_xmalloc_ptr and place it in a
722 simple type symtab_list_type (which holds the vector and a
723 destructor that frees the contents of the allocated strings. */
724 if (symtab_list != NULL)
725 {
726 gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
727
728 if (iter == NULL)
729 return NULL;
730
731 while (true)
732 {
733 gdbpy_ref<> next (PyIter_Next (iter.get ()));
734
735 if (next == NULL)
736 {
737 if (PyErr_Occurred ())
738 return NULL;
739 break;
740 }
741
742 gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
743 "filename"));
744
745 if (obj_name == NULL)
746 return NULL;
747
748 /* Is the object file still valid? */
749 if (obj_name == Py_None)
750 continue;
751
752 gdb::unique_xmalloc_ptr<char> filename =
753 python_string_to_target_string (obj_name.get ());
754
755 if (filename == NULL)
756 return NULL;
757
758 /* Make sure there is a definite place to store the value of
759 filename before it is released. */
470c0b1c
AB
760 spec.filenames.push_back (nullptr);
761 spec.filenames.back () = filename.release ();
d8ae99a7
PM
762 }
763 }
764
470c0b1c
AB
765 /* The search spec. */
766 symbols = spec.search ();
d8ae99a7
PM
767
768 /* Count the number of symbols (both symbols and optionally minimal
769 symbols) so we can correctly check the throttle limit. */
770 for (const symbol_search &p : symbols)
771 {
772 /* Minimal symbols included? */
773 if (minsyms_p)
774 {
775 if (p.msymbol.minsym != NULL)
776 count++;
777 }
778
779 if (p.symbol != NULL)
780 count++;
781 }
782
783 /* Check throttle bounds and exit if in excess. */
784 if (throttle != 0 && count > throttle)
785 {
786 PyErr_SetString (PyExc_RuntimeError,
787 _("Number of breakpoints exceeds throttled maximum."));
788 return NULL;
789 }
790
791 gdbpy_ref<> return_list (PyList_New (0));
792
793 if (return_list == NULL)
794 return NULL;
795
796 /* Construct full path names for symbols and call the Python
797 breakpoint constructor on the resulting names. Be tolerant of
798 individual breakpoint failures. */
799 for (const symbol_search &p : symbols)
800 {
801 std::string symbol_name;
802
803 /* Skipping minimal symbols? */
804 if (minsyms_p == 0)
805 if (p.msymbol.minsym != NULL)
806 continue;
807
808 if (p.msymbol.minsym == NULL)
809 {
810 struct symtab *symtab = symbol_symtab (p.symbol);
811 const char *fullname = symtab_to_fullname (symtab);
812
813 symbol_name = fullname;
814 symbol_name += ":";
987012b8 815 symbol_name += p.symbol->linkage_name ();
d8ae99a7
PM
816 }
817 else
c9d95fa3 818 symbol_name = p.msymbol.minsym->linkage_name ();
d8ae99a7
PM
819
820 gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
821 gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
822 &breakpoint_object_type,
823 argList.get ()));
824
825 /* Tolerate individual breakpoint failures. */
826 if (obj == NULL)
827 gdbpy_print_stack ();
828 else
829 {
830 if (PyList_Append (return_list.get (), obj.get ()) == -1)
831 return NULL;
832 }
833 }
834 return return_list.release ();
835}
836
cb2e07a6
PM
837/* A Python function which is a wrapper for decode_line_1. */
838
839static PyObject *
840gdbpy_decode_line (PyObject *self, PyObject *args)
841{
f2fc3015 842 const char *arg = NULL;
7780f186
TT
843 gdbpy_ref<> result;
844 gdbpy_ref<> unparsed;
ffc2605c 845 event_location_up location;
cb2e07a6
PM
846
847 if (! PyArg_ParseTuple (args, "|s", &arg))
848 return NULL;
849
ff47f4f0
TT
850 /* Treat a string consisting of just whitespace the same as
851 NULL. */
852 if (arg != NULL)
853 {
854 arg = skip_spaces (arg);
855 if (*arg == '\0')
856 arg = NULL;
857 }
858
f00aae0f 859 if (arg != NULL)
a20714ff
PA
860 location = string_to_event_location_basic (&arg, python_language,
861 symbol_name_match_type::WILD);
f00aae0f 862
6c5b2ebe
PA
863 std::vector<symtab_and_line> decoded_sals;
864 symtab_and_line def_sal;
865 gdb::array_view<symtab_and_line> sals;
a70b8144 866 try
cb2e07a6 867 {
59ecaff3 868 if (location != NULL)
6c5b2ebe
PA
869 {
870 decoded_sals = decode_line_1 (location.get (), 0, NULL, NULL, 0);
871 sals = decoded_sals;
872 }
cb2e07a6
PM
873 else
874 {
875 set_default_source_symtab_and_line ();
6c5b2ebe
PA
876 def_sal = get_current_source_symtab_and_line ();
877 sals = def_sal;
cb2e07a6
PM
878 }
879 }
230d2906 880 catch (const gdb_exception &ex)
cb2e07a6 881 {
cb2e07a6 882 /* We know this will always throw. */
6c5b2ebe 883 gdbpy_convert_exception (ex);
f3300387 884 return NULL;
cb2e07a6
PM
885 }
886
6c5b2ebe 887 if (!sals.empty ())
cb2e07a6 888 {
6c5b2ebe 889 result.reset (PyTuple_New (sals.size ()));
59876f8f 890 if (result == NULL)
0d50bde3 891 return NULL;
6c5b2ebe 892 for (size_t i = 0; i < sals.size (); ++i)
cb2e07a6 893 {
6c5b2ebe
PA
894 PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
895 if (obj == NULL)
0d50bde3 896 return NULL;
cb2e07a6 897
59876f8f 898 PyTuple_SetItem (result.get (), i, obj);
cb2e07a6
PM
899 }
900 }
901 else
7c66fffc 902 result = gdbpy_ref<>::new_reference (Py_None);
cb2e07a6 903
7780f186 904 gdbpy_ref<> return_result (PyTuple_New (2));
59876f8f 905 if (return_result == NULL)
0d50bde3 906 return NULL;
cb2e07a6 907
f00aae0f 908 if (arg != NULL && strlen (arg) > 0)
9bc3523d 909 {
59876f8f 910 unparsed.reset (PyString_FromString (arg));
9bc3523d 911 if (unparsed == NULL)
0d50bde3 912 return NULL;
9bc3523d 913 }
cb2e07a6 914 else
7c66fffc 915 unparsed = gdbpy_ref<>::new_reference (Py_None);
cb2e07a6 916
59876f8f
TT
917 PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
918 PyTuple_SetItem (return_result.get (), 1, result.release ());
cb2e07a6 919
59876f8f 920 return return_result.release ();
cb2e07a6
PM
921}
922
57a1d736
TT
923/* Parse a string and evaluate it as an expression. */
924static PyObject *
925gdbpy_parse_and_eval (PyObject *self, PyObject *args)
926{
ddd49eee 927 const char *expr_str;
57a1d736 928 struct value *result = NULL;
57a1d736
TT
929
930 if (!PyArg_ParseTuple (args, "s", &expr_str))
931 return NULL;
932
a70b8144 933 try
57a1d736 934 {
b5eba2d8 935 gdbpy_allow_threads allow_threads;
bbc13ae3 936 result = parse_and_eval (expr_str);
57a1d736 937 }
230d2906 938 catch (const gdb_exception &except)
492d29ea
PA
939 {
940 GDB_PY_HANDLE_EXCEPTION (except);
941 }
57a1d736
TT
942
943 return value_to_value_object (result);
944}
945
e0f3fd7c
TT
946/* Implementation of gdb.invalidate_cached_frames. */
947
948static PyObject *
949gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
950{
951 reinit_frame_cache ();
952 Py_RETURN_NONE;
953}
954
d234ef5c 955/* Read a file as Python code.
6dddc817
DE
956 This is the extension_language_script_ops.script_sourcer "method".
957 FILE is the file to load. FILENAME is name of the file FILE.
d234ef5c
DE
958 This does not throw any errors. If an exception occurs python will print
959 the traceback and clear the error indicator. */
973817a3 960
6dddc817
DE
961static void
962gdbpy_source_script (const struct extension_language_defn *extlang,
963 FILE *file, const char *filename)
973817a3 964{
60e600ec 965 gdbpy_enter enter_py (get_current_arch (), current_language);
4c63965b 966 python_run_simple_file (file, filename);
973817a3
JB
967}
968
d57a3c85
TJB
969\f
970
ca5c20b6
PM
971/* Posting and handling events. */
972
973/* A single event. */
974struct gdbpy_event
975{
971db5e2
TT
976 gdbpy_event (gdbpy_ref<> &&func)
977 : m_func (func.release ())
978 {
979 }
ca5c20b6 980
0fa7617d 981 gdbpy_event (gdbpy_event &&other) noexcept
971db5e2
TT
982 : m_func (other.m_func)
983 {
984 other.m_func = nullptr;
985 }
ca5c20b6 986
971db5e2
TT
987 gdbpy_event (const gdbpy_event &other)
988 : m_func (other.m_func)
989 {
990 gdbpy_gil gil;
991 Py_XINCREF (m_func);
992 }
993
994 ~gdbpy_event ()
995 {
996 gdbpy_gil gil;
997 Py_XDECREF (m_func);
998 }
ca5c20b6 999
971db5e2 1000 gdbpy_event &operator= (const gdbpy_event &other) = delete;
4a532131 1001
971db5e2
TT
1002 void operator() ()
1003 {
1004 gdbpy_enter enter_py (get_current_arch (), current_language);
ca5c20b6 1005
971db5e2
TT
1006 gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
1007 if (call_result == NULL)
1008 gdbpy_print_stack ();
1009 }
ca5c20b6 1010
971db5e2 1011private:
ca5c20b6 1012
971db5e2
TT
1013 /* The Python event. This is just a callable object. Note that
1014 this is not a gdbpy_ref<>, because we have to take particular
1015 care to only destroy the reference when holding the GIL. */
1016 PyObject *m_func;
1017};
ca5c20b6
PM
1018
1019/* Submit an event to the gdb thread. */
1020static PyObject *
1021gdbpy_post_event (PyObject *self, PyObject *args)
1022{
ca5c20b6 1023 PyObject *func;
ca5c20b6
PM
1024
1025 if (!PyArg_ParseTuple (args, "O", &func))
1026 return NULL;
1027
1028 if (!PyCallable_Check (func))
1029 {
256458bc 1030 PyErr_SetString (PyExc_RuntimeError,
ca5c20b6
PM
1031 _("Posted event is not callable"));
1032 return NULL;
1033 }
1034
971db5e2
TT
1035 gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
1036 gdbpy_event event (std::move (func_ref));
1037 run_on_main_thread (event);
ca5c20b6
PM
1038
1039 Py_RETURN_NONE;
1040}
1041
d17b6f81
PM
1042\f
1043
6dddc817
DE
1044/* This is the extension_language_ops.before_prompt "method". */
1045
1046static enum ext_lang_rc
1047gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
1048 const char *current_gdb_prompt)
d17b6f81 1049{
0646da15 1050 if (!gdb_python_initialized)
6dddc817 1051 return EXT_LANG_RC_NOP;
0646da15 1052
a88b13c7 1053 gdbpy_enter enter_py (get_current_arch (), current_language);
d17b6f81 1054
3f77c769
TT
1055 if (!evregpy_no_listeners_p (gdb_py_events.before_prompt)
1056 && evpy_emit_event (NULL, gdb_py_events.before_prompt) < 0)
1057 return EXT_LANG_RC_ERROR;
1058
b9516fa1
YPK
1059 if (gdb_python_module
1060 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
d17b6f81 1061 {
7780f186
TT
1062 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
1063 "prompt_hook"));
d17b6f81 1064 if (hook == NULL)
d17b6f81 1065 {
a88b13c7
TT
1066 gdbpy_print_stack ();
1067 return EXT_LANG_RC_ERROR;
1068 }
d17b6f81 1069
a88b13c7
TT
1070 if (PyCallable_Check (hook.get ()))
1071 {
7780f186 1072 gdbpy_ref<> current_prompt (PyString_FromString (current_gdb_prompt));
d17b6f81 1073 if (current_prompt == NULL)
a88b13c7
TT
1074 {
1075 gdbpy_print_stack ();
1076 return EXT_LANG_RC_ERROR;
1077 }
d17b6f81 1078
7780f186
TT
1079 gdbpy_ref<> result
1080 (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
1081 NULL));
d17b6f81 1082 if (result == NULL)
a88b13c7
TT
1083 {
1084 gdbpy_print_stack ();
1085 return EXT_LANG_RC_ERROR;
1086 }
d17b6f81
PM
1087
1088 /* Return type should be None, or a String. If it is None,
1089 fall through, we will not set a prompt. If it is a
1090 string, set PROMPT. Anything else, set an exception. */
a88b13c7 1091 if (result != Py_None && ! PyString_Check (result.get ()))
d17b6f81
PM
1092 {
1093 PyErr_Format (PyExc_RuntimeError,
1094 _("Return from prompt_hook must " \
1095 "be either a Python string, or None"));
a88b13c7
TT
1096 gdbpy_print_stack ();
1097 return EXT_LANG_RC_ERROR;
d17b6f81
PM
1098 }
1099
1100 if (result != Py_None)
1101 {
a88b13c7
TT
1102 gdb::unique_xmalloc_ptr<char>
1103 prompt (python_string_to_host_string (result.get ()));
d17b6f81
PM
1104
1105 if (prompt == NULL)
a88b13c7
TT
1106 {
1107 gdbpy_print_stack ();
1108 return EXT_LANG_RC_ERROR;
1109 }
1110
1111 set_prompt (prompt.get ());
1112 return EXT_LANG_RC_OK;
d17b6f81
PM
1113 }
1114 }
1115 }
1116
a88b13c7 1117 return EXT_LANG_RC_NOP;
d17b6f81
PM
1118}
1119
f6474de9
TT
1120/* This is the extension_language_ops.colorize "method". */
1121
1122static gdb::optional<std::string>
1123gdbpy_colorize (const std::string &filename, const std::string &contents)
1124{
1125 if (!gdb_python_initialized)
1126 return {};
1127
1128 gdbpy_enter enter_py (get_current_arch (), current_language);
1129
1130 if (gdb_python_module == nullptr
1131 || !PyObject_HasAttrString (gdb_python_module, "colorize"))
1132 return {};
1133
1134 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module, "colorize"));
1135 if (hook == nullptr)
1136 {
1137 gdbpy_print_stack ();
1138 return {};
1139 }
1140
1141 if (!PyCallable_Check (hook.get ()))
1142 return {};
1143
1144 gdbpy_ref<> fname_arg (PyString_FromString (filename.c_str ()));
1145 if (fname_arg == nullptr)
1146 {
1147 gdbpy_print_stack ();
1148 return {};
1149 }
1150 gdbpy_ref<> contents_arg (PyString_FromString (contents.c_str ()));
1151 if (contents_arg == nullptr)
1152 {
1153 gdbpy_print_stack ();
1154 return {};
1155 }
1156
1157 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1158 fname_arg.get (),
1159 contents_arg.get (),
1160 nullptr));
1161 if (result == nullptr)
1162 {
1163 gdbpy_print_stack ();
1164 return {};
1165 }
1166
1167 if (!gdbpy_is_string (result.get ()))
1168 return {};
1169
1170 gdbpy_ref<> unic = python_string_to_unicode (result.get ());
1171 if (unic == nullptr)
1172 {
1173 gdbpy_print_stack ();
1174 return {};
1175 }
1176 gdbpy_ref<> host_str (PyUnicode_AsEncodedString (unic.get (),
1177 host_charset (),
1178 nullptr));
1179 if (host_str == nullptr)
1180 {
1181 gdbpy_print_stack ();
1182 return {};
1183 }
1184
1185 return std::string (PyBytes_AsString (host_str.get ()));
1186}
1187
d17b6f81
PM
1188\f
1189
d57a3c85
TJB
1190/* Printing. */
1191
1192/* A python function to write a single string using gdb's filtered
99c3dc11
PM
1193 output stream . The optional keyword STREAM can be used to write
1194 to a particular stream. The default stream is to gdb_stdout. */
1195
d57a3c85 1196static PyObject *
99c3dc11 1197gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
d57a3c85 1198{
ddd49eee 1199 const char *arg;
2adadf51 1200 static const char *keywords[] = { "text", "stream", NULL };
99c3dc11 1201 int stream_type = 0;
256458bc 1202
2adadf51
PA
1203 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
1204 &stream_type))
d57a3c85 1205 return NULL;
99c3dc11 1206
a70b8144 1207 try
99c3dc11 1208 {
adb4fe3b 1209 switch (stream_type)
dda83cd7
SM
1210 {
1211 case 1:
1212 {
adb4fe3b
ME
1213 fprintf_filtered (gdb_stderr, "%s", arg);
1214 break;
dda83cd7
SM
1215 }
1216 case 2:
1217 {
adb4fe3b
ME
1218 fprintf_filtered (gdb_stdlog, "%s", arg);
1219 break;
dda83cd7
SM
1220 }
1221 default:
1222 fprintf_filtered (gdb_stdout, "%s", arg);
1223 }
99c3dc11 1224 }
230d2906 1225 catch (const gdb_exception &except)
492d29ea
PA
1226 {
1227 GDB_PY_HANDLE_EXCEPTION (except);
1228 }
256458bc 1229
d57a3c85
TJB
1230 Py_RETURN_NONE;
1231}
1232
99c3dc11
PM
1233/* A python function to flush a gdb stream. The optional keyword
1234 STREAM can be used to flush a particular stream. The default stream
1235 is gdb_stdout. */
1236
d57a3c85 1237static PyObject *
99c3dc11 1238gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
d57a3c85 1239{
2adadf51 1240 static const char *keywords[] = { "stream", NULL };
99c3dc11 1241 int stream_type = 0;
256458bc 1242
2adadf51
PA
1243 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1244 &stream_type))
99c3dc11
PM
1245 return NULL;
1246
1247 switch (stream_type)
1248 {
1249 case 1:
1250 {
1251 gdb_flush (gdb_stderr);
1252 break;
1253 }
1254 case 2:
1255 {
1256 gdb_flush (gdb_stdlog);
1257 break;
1258 }
1259 default:
1260 gdb_flush (gdb_stdout);
1261 }
256458bc 1262
d57a3c85
TJB
1263 Py_RETURN_NONE;
1264}
1265
69b4374a
DE
1266/* Return non-zero if print-stack is not "none". */
1267
1268int
1269gdbpy_print_python_errors_p (void)
1270{
1271 return gdbpy_should_print_stack != python_excp_none;
1272}
1273
80b6e756
PM
1274/* Print a python exception trace, print just a message, or print
1275 nothing and clear the python exception, depending on
1276 gdbpy_should_print_stack. Only call this if a python exception is
1277 set. */
d57a3c85
TJB
1278void
1279gdbpy_print_stack (void)
1280{
7f6a5dde 1281
80b6e756
PM
1282 /* Print "none", just clear exception. */
1283 if (gdbpy_should_print_stack == python_excp_none)
1284 {
1285 PyErr_Clear ();
1286 }
1287 /* Print "full" message and backtrace. */
1288 else if (gdbpy_should_print_stack == python_excp_full)
0bf0f8c4
DE
1289 {
1290 PyErr_Print ();
1291 /* PyErr_Print doesn't necessarily end output with a newline.
1292 This works because Python's stdout/stderr is fed through
1293 printf_filtered. */
a70b8144 1294 try
7f6a5dde
TT
1295 {
1296 begin_line ();
1297 }
230d2906 1298 catch (const gdb_exception &except)
492d29ea
PA
1299 {
1300 }
0bf0f8c4 1301 }
80b6e756 1302 /* Print "message", just error print message. */
d57a3c85 1303 else
80b6e756 1304 {
5c329e6a 1305 gdbpy_err_fetch fetched_error;
80b6e756 1306
5c329e6a
TT
1307 gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
1308 gdb::unique_xmalloc_ptr<char> type;
1309 /* Don't compute TYPE if MSG already indicates that there is an
1310 error. */
1311 if (msg != NULL)
1312 type = fetched_error.type_to_string ();
7f6a5dde 1313
a70b8144 1314 try
80b6e756 1315 {
5c329e6a 1316 if (msg == NULL || type == NULL)
7f6a5dde
TT
1317 {
1318 /* An error occurred computing the string representation of the
1319 error message. */
1320 fprintf_filtered (gdb_stderr,
1321 _("Error occurred computing Python error" \
1322 "message.\n"));
5c329e6a 1323 PyErr_Clear ();
7f6a5dde
TT
1324 }
1325 else
2708dbbd 1326 fprintf_filtered (gdb_stderr, "Python Exception %s: %s\n",
9b972014 1327 type.get (), msg.get ());
80b6e756 1328 }
230d2906 1329 catch (const gdb_exception &except)
492d29ea
PA
1330 {
1331 }
80b6e756 1332 }
d57a3c85
TJB
1333}
1334
6ef2312a
TT
1335/* Like gdbpy_print_stack, but if the exception is a
1336 KeyboardException, throw a gdb "quit" instead. */
1337
1338void
1339gdbpy_print_stack_or_quit ()
1340{
1341 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
1342 {
1343 PyErr_Clear ();
1344 throw_quit ("Quit");
1345 }
1346 gdbpy_print_stack ();
1347}
1348
89c73ade
TT
1349\f
1350
fa33c3cd
DE
1351/* Return a sequence holding all the Progspaces. */
1352
1353static PyObject *
1354gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1355{
7780f186 1356 gdbpy_ref<> list (PyList_New (0));
ff3724f5 1357 if (list == NULL)
fa33c3cd
DE
1358 return NULL;
1359
94c93c35
TT
1360 for (struct program_space *ps : program_spaces)
1361 {
1362 gdbpy_ref<> item = pspace_to_pspace_object (ps);
d59b6f6c 1363
94c93c35
TT
1364 if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
1365 return NULL;
1366 }
fa33c3cd 1367
ff3724f5 1368 return list.release ();
fa33c3cd
DE
1369}
1370
1371\f
1372
89c73ade 1373/* The "current" objfile. This is set when gdb detects that a new
8a1ea21f 1374 objfile has been loaded. It is only set for the duration of a call to
9f050062
DE
1375 gdbpy_source_objfile_script and gdbpy_execute_objfile_script; it is NULL
1376 at other times. */
89c73ade
TT
1377static struct objfile *gdbpy_current_objfile;
1378
4c63965b
JK
1379/* Set the current objfile to OBJFILE and then read FILE named FILENAME
1380 as Python code. This does not throw any errors. If an exception
6dddc817
DE
1381 occurs python will print the traceback and clear the error indicator.
1382 This is the extension_language_script_ops.objfile_script_sourcer
1383 "method". */
89c73ade 1384
6dddc817
DE
1385static void
1386gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
1387 struct objfile *objfile, FILE *file,
1388 const char *filename)
89c73ade 1389{
0646da15
TT
1390 if (!gdb_python_initialized)
1391 return;
1392
08feed99 1393 gdbpy_enter enter_py (objfile->arch (), current_language);
ba6a0ef3
AB
1394 scoped_restore restire_current_objfile
1395 = make_scoped_restore (&gdbpy_current_objfile, objfile);
89c73ade 1396
4c63965b 1397 python_run_simple_file (file, filename);
89c73ade
TT
1398}
1399
9f050062
DE
1400/* Set the current objfile to OBJFILE and then execute SCRIPT
1401 as Python code. This does not throw any errors. If an exception
1402 occurs python will print the traceback and clear the error indicator.
1403 This is the extension_language_script_ops.objfile_script_executor
1404 "method". */
1405
1406static void
1407gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
1408 struct objfile *objfile, const char *name,
1409 const char *script)
1410{
9f050062
DE
1411 if (!gdb_python_initialized)
1412 return;
1413
08feed99 1414 gdbpy_enter enter_py (objfile->arch (), current_language);
ba6a0ef3
AB
1415 scoped_restore restire_current_objfile
1416 = make_scoped_restore (&gdbpy_current_objfile, objfile);
9f050062
DE
1417
1418 PyRun_SimpleString (script);
9f050062
DE
1419}
1420
89c73ade 1421/* Return the current Objfile, or None if there isn't one. */
8a1ea21f 1422
89c73ade
TT
1423static PyObject *
1424gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1425{
89c73ade
TT
1426 if (! gdbpy_current_objfile)
1427 Py_RETURN_NONE;
1428
0a9db5ad 1429 return objfile_to_objfile_object (gdbpy_current_objfile).release ();
89c73ade
TT
1430}
1431
6dddc817
DE
1432/* Compute the list of active python type printers and store them in
1433 EXT_PRINTERS->py_type_printers. The product of this function is used by
1434 gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
1435 This is the extension_language_ops.start_type_printers "method". */
18a9fc12 1436
6dddc817
DE
1437static void
1438gdbpy_start_type_printers (const struct extension_language_defn *extlang,
1439 struct ext_lang_type_printers *ext_printers)
18a9fc12 1440{
59876f8f 1441 PyObject *printers_obj = NULL;
18a9fc12 1442
0646da15 1443 if (!gdb_python_initialized)
6dddc817 1444 return;
0646da15 1445
60e600ec 1446 gdbpy_enter enter_py (get_current_arch (), current_language);
18a9fc12 1447
7780f186 1448 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
18a9fc12
TT
1449 if (type_module == NULL)
1450 {
1451 gdbpy_print_stack ();
59876f8f 1452 return;
18a9fc12 1453 }
18a9fc12 1454
7780f186
TT
1455 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1456 "get_type_recognizers"));
18a9fc12
TT
1457 if (func == NULL)
1458 {
1459 gdbpy_print_stack ();
59876f8f 1460 return;
18a9fc12 1461 }
18a9fc12 1462
59876f8f 1463 printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
6dddc817 1464 if (printers_obj == NULL)
18a9fc12 1465 gdbpy_print_stack ();
6dddc817
DE
1466 else
1467 ext_printers->py_type_printers = printers_obj;
18a9fc12
TT
1468}
1469
6dddc817
DE
1470/* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
1471 a newly allocated string holding the type's replacement name, and return
1472 EXT_LANG_RC_OK. The caller is responsible for freeing the string.
1473 If there's a Python error return EXT_LANG_RC_ERROR.
1474 Otherwise, return EXT_LANG_RC_NOP.
1475 This is the extension_language_ops.apply_type_printers "method". */
1476
1477static enum ext_lang_rc
1478gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
1479 const struct ext_lang_type_printers *ext_printers,
1480 struct type *type, char **prettied_type)
18a9fc12 1481{
19ba03f4 1482 PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
9b972014 1483 gdb::unique_xmalloc_ptr<char> result;
18a9fc12
TT
1484
1485 if (printers_obj == NULL)
6dddc817 1486 return EXT_LANG_RC_NOP;
18a9fc12 1487
0646da15 1488 if (!gdb_python_initialized)
6dddc817 1489 return EXT_LANG_RC_NOP;
0646da15 1490
60e600ec 1491 gdbpy_enter enter_py (get_current_arch (), current_language);
18a9fc12 1492
7780f186 1493 gdbpy_ref<> type_obj (type_to_type_object (type));
18a9fc12
TT
1494 if (type_obj == NULL)
1495 {
1496 gdbpy_print_stack ();
59876f8f 1497 return EXT_LANG_RC_ERROR;
18a9fc12 1498 }
18a9fc12 1499
7780f186 1500 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
18a9fc12
TT
1501 if (type_module == NULL)
1502 {
1503 gdbpy_print_stack ();
59876f8f 1504 return EXT_LANG_RC_ERROR;
18a9fc12 1505 }
18a9fc12 1506
7780f186
TT
1507 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1508 "apply_type_recognizers"));
18a9fc12
TT
1509 if (func == NULL)
1510 {
1511 gdbpy_print_stack ();
59876f8f 1512 return EXT_LANG_RC_ERROR;
18a9fc12 1513 }
18a9fc12 1514
7780f186
TT
1515 gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
1516 printers_obj,
1517 type_obj.get (),
1518 (char *) NULL));
18a9fc12
TT
1519 if (result_obj == NULL)
1520 {
1521 gdbpy_print_stack ();
59876f8f 1522 return EXT_LANG_RC_ERROR;
18a9fc12 1523 }
18a9fc12 1524
59876f8f
TT
1525 if (result_obj == Py_None)
1526 return EXT_LANG_RC_NOP;
18a9fc12 1527
59876f8f
TT
1528 result = python_string_to_host_string (result_obj.get ());
1529 if (result == NULL)
9b972014 1530 {
59876f8f
TT
1531 gdbpy_print_stack ();
1532 return EXT_LANG_RC_ERROR;
9b972014 1533 }
59876f8f
TT
1534
1535 *prettied_type = result.release ();
1536 return EXT_LANG_RC_OK;
18a9fc12
TT
1537}
1538
6dddc817
DE
1539/* Free the result of start_type_printers.
1540 This is the extension_language_ops.free_type_printers "method". */
18a9fc12 1541
6dddc817
DE
1542static void
1543gdbpy_free_type_printers (const struct extension_language_defn *extlang,
1544 struct ext_lang_type_printers *ext_printers)
18a9fc12 1545{
19ba03f4 1546 PyObject *printers = (PyObject *) ext_printers->py_type_printers;
18a9fc12
TT
1547
1548 if (printers == NULL)
1549 return;
1550
0646da15
TT
1551 if (!gdb_python_initialized)
1552 return;
1553
60e600ec 1554 gdbpy_enter enter_py (get_current_arch (), current_language);
18a9fc12 1555 Py_DECREF (printers);
18a9fc12
TT
1556}
1557
d57a3c85
TJB
1558#else /* HAVE_PYTHON */
1559
8315665e
YPK
1560/* Dummy implementation of the gdb "python-interactive" and "python"
1561 command. */
d57a3c85
TJB
1562
1563static void
0b39b52e 1564python_interactive_command (const char *arg, int from_tty)
d57a3c85 1565{
529480d0 1566 arg = skip_spaces (arg);
d57a3c85
TJB
1567 if (arg && *arg)
1568 error (_("Python scripting is not supported in this copy of GDB."));
1569 else
1570 {
12973681 1571 counted_command_line l = get_command_line (python_control, "");
d59b6f6c 1572
93921405 1573 execute_control_command_untraced (l.get ());
d57a3c85
TJB
1574 }
1575}
1576
8315665e 1577static void
0b39b52e 1578python_command (const char *arg, int from_tty)
8315665e
YPK
1579{
1580 python_interactive_command (arg, from_tty);
1581}
1582
d57a3c85
TJB
1583#endif /* HAVE_PYTHON */
1584
edeaceda
AB
1585/* When this is turned on before Python is initialised then Python will
1586 ignore any environment variables related to Python. This is equivalent
1587 to passing `-E' to the python program. */
1588static bool python_ignore_environment = false;
1589
1590/* Implement 'show python ignore-environment'. */
1591
1592static void
1593show_python_ignore_environment (struct ui_file *file, int from_tty,
1594 struct cmd_list_element *c, const char *value)
1595{
1596 fprintf_filtered (file, _("Python's ignore-environment setting is %s.\n"),
1597 value);
1598}
1599
1600/* Implement 'set python ignore-environment'. This sets Python's internal
1601 flag no matter when the command is issued, however, if this is used
1602 after Py_Initialize has been called then most of the environment will
1603 already have been read. */
1604
1605static void
1606set_python_ignore_environment (const char *args, int from_tty,
1607 struct cmd_list_element *c)
1608{
1609#ifdef HAVE_PYTHON
1610 Py_IgnoreEnvironmentFlag = python_ignore_environment ? 1 : 0;
1611#endif
1612}
1613
1614/* When this is turned on before Python is initialised then Python will
1615 not write `.pyc' files on import of a module. */
1616static enum auto_boolean python_dont_write_bytecode = AUTO_BOOLEAN_AUTO;
1617
1618/* Implement 'show python dont-write-bytecode'. */
1619
1620static void
1621show_python_dont_write_bytecode (struct ui_file *file, int from_tty,
1622 struct cmd_list_element *c, const char *value)
1623{
1624 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
1625 {
1626 const char *auto_string
1627 = (python_ignore_environment
1628 || getenv ("PYTHONDONTWRITEBYTECODE") == nullptr) ? "off" : "on";
1629
1630 fprintf_filtered (file,
1631 _("Python's dont-write-bytecode setting is %s (currently %s).\n"),
1632 value, auto_string);
1633 }
1634 else
1635 fprintf_filtered (file, _("Python's dont-write-bytecode setting is %s.\n"),
1636 value);
1637}
1638
1639/* Implement 'set python dont-write-bytecode'. This sets Python's internal
1640 flag no matter when the command is issued, however, if this is used
1641 after Py_Initialize has been called then many modules could already
1642 have been imported and their byte code written out. */
1643
1644static void
1645set_python_dont_write_bytecode (const char *args, int from_tty,
1646 struct cmd_list_element *c)
1647{
1648#ifdef HAVE_PYTHON
1649 if (python_dont_write_bytecode == AUTO_BOOLEAN_AUTO)
1650 Py_DontWriteBytecodeFlag
1651 = (!python_ignore_environment
1652 && getenv ("PYTHONDONTWRITEBYTECODE") != nullptr) ? 1 : 0;
1653 else
1654 Py_DontWriteBytecodeFlag
1655 = python_dont_write_bytecode == AUTO_BOOLEAN_TRUE ? 1 : 0;
1656#endif /* HAVE_PYTHON */
1657}
1658
d57a3c85
TJB
1659\f
1660
713389e0
PM
1661/* Lists for 'set python' commands. */
1662
1663static struct cmd_list_element *user_set_python_list;
1664static struct cmd_list_element *user_show_python_list;
d57a3c85 1665
d57a3c85
TJB
1666/* Initialize the Python code. */
1667
810849a3
AS
1668#ifdef HAVE_PYTHON
1669
d7de8e3c
TT
1670/* This is installed as a final cleanup and cleans up the
1671 interpreter. This lets Python's 'atexit' work. */
1672
1673static void
1674finalize_python (void *ignore)
1675{
6dddc817
DE
1676 struct active_ext_lang_state *previous_active;
1677
d7de8e3c
TT
1678 /* We don't use ensure_python_env here because if we ever ran the
1679 cleanup, gdb would crash -- because the cleanup calls into the
1680 Python interpreter, which we are about to destroy. It seems
1681 clearer to make the needed calls explicitly here than to create a
1682 cleanup and then mysteriously discard it. */
6dddc817
DE
1683
1684 /* This is only called as a final cleanup so we can assume the active
1685 SIGINT handler is gdb's. We still need to tell it to notify Python. */
1686 previous_active = set_active_ext_lang (&extension_language_python);
1687
b1209b03 1688 (void) PyGILState_Ensure ();
f5656ead 1689 python_gdbarch = target_gdbarch ();
d7de8e3c
TT
1690 python_language = current_language;
1691
1692 Py_Finalize ();
6dddc817 1693
c47bae85 1694 gdb_python_initialized = false;
6dddc817 1695 restore_active_ext_lang (previous_active);
d7de8e3c 1696}
2bb8f231 1697
aeab5128 1698#ifdef IS_PY3K
5b3d3560
TT
1699static struct PyModuleDef python_GdbModuleDef =
1700{
1701 PyModuleDef_HEAD_INIT,
1702 "_gdb",
1703 NULL,
1704 -1,
1705 python_GdbMethods,
1706 NULL,
1707 NULL,
1708 NULL,
1709 NULL
1710};
1711
aeab5128
PK
1712/* This is called via the PyImport_AppendInittab mechanism called
1713 during initialization, to make the built-in _gdb module known to
1714 Python. */
6b366111 1715PyMODINIT_FUNC init__gdb_module (void);
aeab5128
PK
1716PyMODINIT_FUNC
1717init__gdb_module (void)
1718{
1719 return PyModule_Create (&python_GdbModuleDef);
1720}
1721#endif
1722
2bb8f231
TT
1723static bool
1724do_start_initialization ()
d57a3c85 1725{
0c4a4063
DE
1726#ifdef WITH_PYTHON_PATH
1727 /* Work around problem where python gets confused about where it is,
1728 and then can't find its libraries, etc.
1729 NOTE: Python assumes the following layout:
1730 /foo/bin/python
1731 /foo/lib/pythonX.Y/...
1732 This must be done before calling Py_Initialize. */
e8e7d10c 1733 gdb::unique_xmalloc_ptr<char> progname
f2aec7f6 1734 (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
e8e7d10c 1735 SLASH_STRING, "python", (char *) NULL));
9a27f2c6 1736#ifdef IS_PY3K
5b3d3560
TT
1737 /* Python documentation indicates that the memory given
1738 to Py_SetProgramName cannot be freed. However, it seems that
1739 at least Python 3.7.4 Py_SetProgramName takes a copy of the
1740 given program_name. Making progname_copy static and not release
1741 the memory avoids a leak report for Python versions that duplicate
1742 program_name, and respect the requirement of Py_SetProgramName
1743 for Python versions that do not duplicate program_name. */
1744 static wchar_t *progname_copy;
1745
7f968c89 1746 std::string oldloc = setlocale (LC_ALL, NULL);
9a27f2c6 1747 setlocale (LC_ALL, "");
5b3d3560 1748 size_t progsize = strlen (progname.get ());
d3c22fa8 1749 progname_copy = XNEWVEC (wchar_t, progsize + 1);
5b3d3560 1750 size_t count = mbstowcs (progname_copy, progname.get (), progsize + 1);
9a27f2c6
PK
1751 if (count == (size_t) -1)
1752 {
1753 fprintf (stderr, "Could not convert python path to string\n");
2bb8f231 1754 return false;
9a27f2c6 1755 }
7f968c89 1756 setlocale (LC_ALL, oldloc.c_str ());
9a27f2c6
PK
1757
1758 /* Note that Py_SetProgramName expects the string it is passed to
1759 remain alive for the duration of the program's execution, so
1760 it is not freed after this call. */
1761 Py_SetProgramName (progname_copy);
aeab5128
PK
1762
1763 /* Define _gdb as a built-in module. */
1764 PyImport_AppendInittab ("_gdb", init__gdb_module);
9a27f2c6 1765#else
e8e7d10c 1766 Py_SetProgramName (progname.release ());
9a27f2c6 1767#endif
0c4a4063
DE
1768#endif
1769
d57a3c85 1770 Py_Initialize ();
97ed802d
KB
1771#if PY_VERSION_HEX < 0x03090000
1772 /* PyEval_InitThreads became deprecated in Python 3.9 and will
1773 be removed in Python 3.11. Prior to Python 3.7, this call was
1774 required to initialize the GIL. */
ca30a762 1775 PyEval_InitThreads ();
97ed802d 1776#endif
d57a3c85 1777
9a27f2c6 1778#ifdef IS_PY3K
aeab5128 1779 gdb_module = PyImport_ImportModule ("_gdb");
9a27f2c6 1780#else
bcabf420 1781 gdb_module = Py_InitModule ("_gdb", python_GdbMethods);
9a27f2c6 1782#endif
999633ed 1783 if (gdb_module == NULL)
2bb8f231 1784 return false;
d57a3c85 1785
6c28e44a
TT
1786 if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
1787 || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
999633ed 1788 || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
6c28e44a 1789 target_name) < 0)
2bb8f231 1790 return false;
f17618ea 1791
99c3dc11 1792 /* Add stream constants. */
999633ed
TT
1793 if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
1794 || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
1795 || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
2bb8f231 1796 return false;
d57a3c85 1797
621c8364 1798 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
999633ed 1799 if (gdbpy_gdb_error == NULL
aa36459a 1800 || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
2bb8f231 1801 return false;
621c8364
TT
1802
1803 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1804 gdbpy_gdb_error, NULL);
999633ed 1805 if (gdbpy_gdb_memory_error == NULL
aa36459a
TT
1806 || gdb_pymodule_addobject (gdb_module, "MemoryError",
1807 gdbpy_gdb_memory_error) < 0)
2bb8f231 1808 return false;
621c8364 1809
07ca107c 1810 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
999633ed 1811 if (gdbpy_gdberror_exc == NULL
aa36459a
TT
1812 || gdb_pymodule_addobject (gdb_module, "GdbError",
1813 gdbpy_gdberror_exc) < 0)
2bb8f231 1814 return false;
07ca107c 1815
037bbc8e 1816 gdbpy_initialize_gdb_readline ();
999633ed
TT
1817
1818 if (gdbpy_initialize_auto_load () < 0
1819 || gdbpy_initialize_values () < 0
1820 || gdbpy_initialize_frames () < 0
1821 || gdbpy_initialize_commands () < 0
d050f7d7 1822 || gdbpy_initialize_instruction () < 0
4726b2d8 1823 || gdbpy_initialize_record () < 0
75c0bdf4 1824 || gdbpy_initialize_btrace () < 0
999633ed
TT
1825 || gdbpy_initialize_symbols () < 0
1826 || gdbpy_initialize_symtabs () < 0
1827 || gdbpy_initialize_blocks () < 0
1828 || gdbpy_initialize_functions () < 0
1829 || gdbpy_initialize_parameters () < 0
1830 || gdbpy_initialize_types () < 0
1831 || gdbpy_initialize_pspace () < 0
1832 || gdbpy_initialize_objfile () < 0
1833 || gdbpy_initialize_breakpoints () < 0
1834 || gdbpy_initialize_finishbreakpoints () < 0
1835 || gdbpy_initialize_lazy_string () < 0
bc79de95 1836 || gdbpy_initialize_linetable () < 0
999633ed
TT
1837 || gdbpy_initialize_thread () < 0
1838 || gdbpy_initialize_inferior () < 0
999633ed
TT
1839 || gdbpy_initialize_eventregistry () < 0
1840 || gdbpy_initialize_py_events () < 0
1841 || gdbpy_initialize_event () < 0
883964a7 1842 || gdbpy_initialize_arch () < 0
0f767f94 1843 || gdbpy_initialize_registers () < 0
d11916aa 1844 || gdbpy_initialize_xmethods () < 0
01b1af32
TT
1845 || gdbpy_initialize_unwind () < 0
1846 || gdbpy_initialize_tui () < 0)
2bb8f231 1847 return false;
505500db 1848
7d221d74
TT
1849#define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
1850 if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
1851 return false;
1852#include "py-event-types.def"
1853#undef GDB_PY_DEFINE_EVENT_TYPE
1854
a6bac58e 1855 gdbpy_to_string_cst = PyString_FromString ("to_string");
999633ed 1856 if (gdbpy_to_string_cst == NULL)
2bb8f231 1857 return false;
a6bac58e 1858 gdbpy_children_cst = PyString_FromString ("children");
999633ed 1859 if (gdbpy_children_cst == NULL)
2bb8f231 1860 return false;
a6bac58e 1861 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
999633ed 1862 if (gdbpy_display_hint_cst == NULL)
2bb8f231 1863 return false;
d8906c6f 1864 gdbpy_doc_cst = PyString_FromString ("__doc__");
999633ed 1865 if (gdbpy_doc_cst == NULL)
2bb8f231 1866 return false;
967cf477 1867 gdbpy_enabled_cst = PyString_FromString ("enabled");
999633ed 1868 if (gdbpy_enabled_cst == NULL)
2bb8f231 1869 return false;
fb6a3ed3 1870 gdbpy_value_cst = PyString_FromString ("value");
999633ed 1871 if (gdbpy_value_cst == NULL)
2bb8f231 1872 return false;
d8906c6f 1873
9dea9163 1874 /* Release the GIL while gdb runs. */
c47bae85 1875 PyEval_SaveThread ();
9dea9163 1876
d7de8e3c 1877 make_final_cleanup (finalize_python, NULL);
999633ed 1878
2bb8f231 1879 /* Only set this when initialization has succeeded. */
999633ed 1880 gdb_python_initialized = 1;
2bb8f231
TT
1881 return true;
1882}
999633ed 1883
cf9c1c75
TV
1884#if GDB_SELF_TEST
1885namespace selftests {
1886
1887/* Entry point for python unit tests. */
1888
1889static void
1890test_python ()
1891{
1892#define CMD execute_command_to_string ("python print(5)", 0, true);
1893
1894 std::string output;
1895
1896 output = CMD;
1897 SELF_CHECK (output == "5\n");
1898 output.clear ();
1899
1900 bool saw_exception = false;
1901 scoped_restore reset_gdb_python_initialized
1902 = make_scoped_restore (&gdb_python_initialized, 0);
1903 try
1904 {
1905 output = CMD;
1906 }
1907 catch (const gdb_exception &e)
1908 {
1909 saw_exception = true;
1910 SELF_CHECK (e.reason == RETURN_ERROR);
1911 SELF_CHECK (e.error == GENERIC_ERROR);
1912 SELF_CHECK (*e.message == "Python not initialized");
1913 }
1914 SELF_CHECK (saw_exception);
1915 SELF_CHECK (output.empty ());
1916
1917#undef CMD
1918}
1919
1920#undef CHECK_OUTPUT
1921
1922} // namespace selftests
1923#endif /* GDB_SELF_TEST */
1924
e68b7db1
TT
1925#endif /* HAVE_PYTHON */
1926
8588b356
SM
1927/* See python.h. */
1928cmd_list_element *python_cmd_element = nullptr;
1929
6c265988 1930void _initialize_python ();
2bb8f231 1931void
6c265988 1932_initialize_python ()
2bb8f231 1933{
3947f654
SM
1934 cmd_list_element *python_interactive_cmd
1935 = add_com ("python-interactive", class_obscure,
1936 python_interactive_command,
2bb8f231
TT
1937#ifdef HAVE_PYTHON
1938 _("\
1939Start an interactive Python prompt.\n\
1940\n\
1941To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1942prompt).\n\
1943\n\
1944Alternatively, a single-line Python command can be given as an\n\
1945argument, and if the command is an expression, the result will be\n\
1946printed. For example:\n\
1947\n\
1948 (gdb) python-interactive 2 + 3\n\
89549d7f 1949 5")
2bb8f231
TT
1950#else /* HAVE_PYTHON */
1951 _("\
1952Start a Python interactive prompt.\n\
1953\n\
1954Python scripting is not supported in this copy of GDB.\n\
1955This command is only a placeholder.")
1956#endif /* HAVE_PYTHON */
1957 );
3947f654 1958 add_com_alias ("pi", python_interactive_cmd, class_obscure, 1);
2bb8f231 1959
8588b356 1960 python_cmd_element = add_com ("python", class_obscure, python_command,
2bb8f231
TT
1961#ifdef HAVE_PYTHON
1962 _("\
1963Evaluate a Python command.\n\
1964\n\
1965The command can be given as an argument, for instance:\n\
1966\n\
a154931e 1967 python print (23)\n\
2bb8f231
TT
1968\n\
1969If no argument is given, the following lines are read and used\n\
1970as the Python commands. Type a line containing \"end\" to indicate\n\
1971the end of the command.")
1972#else /* HAVE_PYTHON */
1973 _("\
1974Evaluate a Python command.\n\
1975\n\
1976Python scripting is not supported in this copy of GDB.\n\
1977This command is only a placeholder.")
1978#endif /* HAVE_PYTHON */
1979 );
3947f654 1980 add_com_alias ("py", python_cmd_element, class_obscure, 1);
2bb8f231
TT
1981
1982 /* Add set/show python print-stack. */
0743fc83
TT
1983 add_basic_prefix_cmd ("python", no_class,
1984 _("Prefix command for python preference settings."),
2f822da5 1985 &user_show_python_list, 0, &showlist);
0743fc83
TT
1986
1987 add_show_prefix_cmd ("python", no_class,
1988 _("Prefix command for python preference settings."),
2f822da5 1989 &user_set_python_list, 0, &setlist);
2bb8f231
TT
1990
1991 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1992 &gdbpy_should_print_stack, _("\
1993Set mode for Python stack dump on error."), _("\
1994Show the mode of Python stack printing on error."), _("\
1995none == no stack or message will be printed.\n\
1996full == a message and a stack will be printed.\n\
1997message == an error message without a stack will be printed."),
1998 NULL, NULL,
1999 &user_set_python_list,
2000 &user_show_python_list);
edeaceda
AB
2001
2002 add_setshow_boolean_cmd ("ignore-environment", no_class,
2003 &python_ignore_environment, _("\
2004Set whether the Python interpreter should ignore environment variables."), _(" \
2005Show whether the Python interpreter showlist ignore environment variables."), _(" \
2006When enabled GDB's Python interpreter will ignore any Python related\n \
2007flags in the environment. This is equivalent to passing `-E' to a\n \
2008python executable."),
2009 set_python_ignore_environment,
2010 show_python_ignore_environment,
2011 &user_set_python_list,
2012 &user_show_python_list);
2013
2014 add_setshow_auto_boolean_cmd ("dont-write-bytecode", no_class,
2015 &python_dont_write_bytecode, _("\
2016Set whether the Python interpreter should ignore environment variables."), _(" \
2017Show whether the Python interpreter showlist ignore environment variables."), _(" \
2018When enabled GDB's Python interpreter will ignore any Python related\n \
2019flags in the environment. This is equivalent to passing `-E' to a\n \
2020python executable."),
2021 set_python_dont_write_bytecode,
2022 show_python_dont_write_bytecode,
2023 &user_set_python_list,
2024 &user_show_python_list);
cf9c1c75 2025
e68b7db1 2026#ifdef HAVE_PYTHON
cf9c1c75
TV
2027#if GDB_SELF_TEST
2028 selftests::register_test ("python", selftests::test_python);
2029#endif /* GDB_SELF_TEST */
e68b7db1 2030#endif /* HAVE_PYTHON */
9dea9163
DE
2031}
2032
2033#ifdef HAVE_PYTHON
2034
041ca48e
AB
2035/* Helper function for gdbpy_initialize. This does the work and then
2036 returns false if an error has occurred and must be displayed, or true on
2037 success. */
9dea9163 2038
a7785f8c 2039static bool
041ca48e 2040do_initialize (const struct extension_language_defn *extlang)
9dea9163 2041{
b9516fa1 2042 PyObject *m;
b9516fa1 2043 PyObject *sys_path;
f17618ea 2044
b9516fa1
YPK
2045 /* Add the initial data-directory to sys.path. */
2046
a7785f8c
TT
2047 std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
2048 + "python");
b9516fa1
YPK
2049
2050 sys_path = PySys_GetObject ("path");
ca30a762 2051
9a27f2c6
PK
2052 /* If sys.path is not defined yet, define it first. */
2053 if (!(sys_path && PyList_Check (sys_path)))
2054 {
2055#ifdef IS_PY3K
2056 PySys_SetPath (L"");
2057#else
2058 PySys_SetPath ("");
2059#endif
2060 sys_path = PySys_GetObject ("path");
2061 }
256458bc 2062 if (sys_path && PyList_Check (sys_path))
b9516fa1 2063 {
7780f186 2064 gdbpy_ref<> pythondir (PyString_FromString (gdb_pythondir.c_str ()));
a7785f8c
TT
2065 if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
2066 return false;
b9516fa1
YPK
2067 }
2068 else
a7785f8c 2069 return false;
b9516fa1
YPK
2070
2071 /* Import the gdb module to finish the initialization, and
2072 add it to __main__ for convenience. */
2073 m = PyImport_AddModule ("__main__");
2074 if (m == NULL)
a7785f8c 2075 return false;
b9516fa1 2076
a7785f8c
TT
2077 /* Keep the reference to gdb_python_module since it is in a global
2078 variable. */
b9516fa1
YPK
2079 gdb_python_module = PyImport_ImportModule ("gdb");
2080 if (gdb_python_module == NULL)
2081 {
2082 gdbpy_print_stack ();
41245087
DE
2083 /* This is passed in one call to warning so that blank lines aren't
2084 inserted between each line of text. */
2085 warning (_("\n"
2086 "Could not load the Python gdb module from `%s'.\n"
2087 "Limited Python support is available from the _gdb module.\n"
422186a9 2088 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
a7785f8c
TT
2089 gdb_pythondir.c_str ());
2090 /* We return "success" here as we've already emitted the
2091 warning. */
2092 return true;
b9516fa1
YPK
2093 }
2094
a7785f8c
TT
2095 return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
2096}
b9516fa1 2097
041ca48e
AB
2098/* Perform Python initialization. This will be called after GDB has
2099 performed all of its own initialization. This is the
2100 extension_language_ops.initialize "method". */
b9516fa1 2101
a7785f8c 2102static void
041ca48e 2103gdbpy_initialize (const struct extension_language_defn *extlang)
a7785f8c 2104{
8e3685bf
AB
2105 if (!do_start_initialization () && PyErr_Occurred ())
2106 gdbpy_print_stack ();
2107
a7785f8c 2108 gdbpy_enter enter_py (get_current_arch (), current_language);
b9516fa1 2109
041ca48e 2110 if (!do_initialize (extlang))
a7785f8c
TT
2111 {
2112 gdbpy_print_stack ();
2113 warning (_("internal error: Unhandled Python exception"));
2114 }
9dea9163 2115}
ca30a762 2116
6dddc817
DE
2117/* Return non-zero if Python has successfully initialized.
2118 This is the extension_languages_ops.initialized "method". */
2119
2120static int
2121gdbpy_initialized (const struct extension_language_defn *extlang)
2122{
2123 return gdb_python_initialized;
2124}
2125
bcabf420 2126PyMethodDef python_GdbMethods[] =
12453b93
TJB
2127{
2128 { "history", gdbpy_history, METH_VARARGS,
2129 "Get a value from history" },
540bf37b
AB
2130 { "add_history", gdbpy_add_history, METH_VARARGS,
2131 "Add a value to the value history list" },
bc9f0842 2132 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
751e7549
PM
2133 "execute (command [, from_tty] [, to_string]) -> [String]\n\
2134Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
2135a Python String containing the output of the command if to_string is\n\
2136set to True." },
8f500870 2137 { "parameter", gdbpy_parameter, METH_VARARGS,
12453b93
TJB
2138 "Return a gdb parameter's value" },
2139
adc36818
PM
2140 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
2141 "Return a tuple of all breakpoint objects" },
2142
b6313243
TT
2143 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
2144 "Find the default visualizer for a Value." },
2145
fa33c3cd
DE
2146 { "progspaces", gdbpy_progspaces, METH_NOARGS,
2147 "Return a sequence of all progspaces." },
2148
89c73ade
TT
2149 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
2150 "Return the current Objfile being loaded, or None." },
89c73ade 2151
d8e22779
TT
2152 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
2153 "newest_frame () -> gdb.Frame.\n\
2154Return the newest frame object." },
f8f6f20b
TJB
2155 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
2156 "selected_frame () -> gdb.Frame.\n\
2157Return the selected frame object." },
2158 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
2159 "stop_reason_string (Integer) -> String.\n\
2160Return a string explaining unwind stop reason." },
2161
4726b2d8
TW
2162 { "start_recording", gdbpy_start_recording, METH_VARARGS,
2163 "start_recording ([method] [, format]) -> gdb.Record.\n\
2164Start recording with the given method. If no method is given, will fall back\n\
2165to the system default method. If no format is given, will fall back to the\n\
2166default format for the given method."},
2167 { "current_recording", gdbpy_current_recording, METH_NOARGS,
2168 "current_recording () -> gdb.Record.\n\
2169Return current recording object." },
2170 { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
2171 "stop_recording () -> None.\n\
2172Stop current recording." },
2173
2c74e833
TT
2174 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
2175 METH_VARARGS | METH_KEYWORDS,
2176 "lookup_type (name [, block]) -> type\n\
2177Return a Type corresponding to the given name." },
f3e9a817
PM
2178 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
2179 METH_VARARGS | METH_KEYWORDS,
2180 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
2181Return a tuple with the symbol corresponding to the given name (or None) and\n\
2182a boolean indicating if name is a field of the current implied argument\n\
2183`this' (when the current language is object-oriented)." },
6e6fbe60
DE
2184 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
2185 METH_VARARGS | METH_KEYWORDS,
2186 "lookup_global_symbol (name [, domain]) -> symbol\n\
2187Return the symbol corresponding to the given name (or None)." },
2906593f
CB
2188 { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
2189 METH_VARARGS | METH_KEYWORDS,
2190 "lookup_static_symbol (name [, domain]) -> symbol\n\
2191Return the static-linkage symbol corresponding to the given name (or None)." },
086baaf1
AB
2192 { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
2193 METH_VARARGS | METH_KEYWORDS,
2194 "lookup_static_symbols (name [, domain]) -> symbol\n\
2195Return a list of all static-linkage symbols corresponding to the given name." },
6dddd6a5
DE
2196
2197 { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
2198 METH_VARARGS | METH_KEYWORDS,
2199 "lookup_objfile (name, [by_build_id]) -> objfile\n\
2200Look up the specified objfile.\n\
2201If by_build_id is True, the objfile is looked up by using name\n\
2202as its build id." },
2203
cb2e07a6
PM
2204 { "decode_line", gdbpy_decode_line, METH_VARARGS,
2205 "decode_line (String) -> Tuple. Decode a string argument the way\n\
2206that 'break' or 'edit' does. Return a tuple containing two elements.\n\
2207The first element contains any unparsed portion of the String parameter\n\
2208(or None if the string was fully parsed). The second element contains\n\
2209a tuple that contains all the locations that match, represented as\n\
2210gdb.Symtab_and_line objects (or None)."},
57a1d736
TT
2211 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
2212 "parse_and_eval (String) -> Value.\n\
2213Parse String as an expression, evaluate it, and return the result as a Value."
2214 },
2215
ca5c20b6
PM
2216 { "post_event", gdbpy_post_event, METH_VARARGS,
2217 "Post an event into gdb's event loop." },
2218
f870a310
TT
2219 { "target_charset", gdbpy_target_charset, METH_NOARGS,
2220 "target_charset () -> string.\n\
2221Return the name of the current target charset." },
2222 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
2223 "target_wide_charset () -> string.\n\
2224Return the name of the current target wide charset." },
d8ae99a7
PM
2225 { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
2226 "rbreak (Regex) -> List.\n\
2227Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
07ca107c
DE
2228 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
2229 "string_to_argv (String) -> Array.\n\
2230Parse String and return an argv-like array.\n\
2231Arguments are separate by spaces and may be quoted."
2232 },
99c3dc11 2233 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
12453b93 2234 "Write a string using gdb's filtered stream." },
99c3dc11 2235 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
12453b93 2236 "Flush gdb's filtered stdout stream." },
595939de
PM
2237 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
2238 "selected_thread () -> gdb.InferiorThread.\n\
2239Return the selected thread object." },
2aa48337
KP
2240 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
2241 "selected_inferior () -> gdb.Inferior.\n\
2242Return the selected inferior object." },
595939de
PM
2243 { "inferiors", gdbpy_inferiors, METH_NOARGS,
2244 "inferiors () -> (gdb.Inferior, ...).\n\
2245Return a tuple containing all inferiors." },
e0f3fd7c
TT
2246
2247 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
2248 "invalidate_cached_frames () -> None.\n\
2249Invalidate any cached frame objects in gdb.\n\
2250Intended for internal use only." },
2251
7729052b
TT
2252 { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
2253 "convenience_variable (NAME) -> value.\n\
2254Return the value of the convenience variable $NAME,\n\
2255or None if not set." },
2256 { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
2257 "convenience_variable (NAME, VALUE) -> None.\n\
2258Set the value of the convenience variable $NAME." },
2259
01b1af32
TT
2260#ifdef TUI
2261 { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
2262 METH_VARARGS | METH_KEYWORDS,
2263 "register_window_type (NAME, CONSTRUCSTOR) -> None\n\
2264Register a TUI window constructor." },
2265#endif /* TUI */
2266
12453b93
TJB
2267 {NULL, NULL, 0, NULL}
2268};
2269
7d221d74
TT
2270/* Define all the event objects. */
2271#define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2272 PyTypeObject name##_event_object_type \
dda83cd7 2273 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
7d221d74
TT
2274 = { \
2275 PyVarObject_HEAD_INIT (NULL, 0) \
2276 "gdb." py_name, /* tp_name */ \
2277 sizeof (event_object), /* tp_basicsize */ \
2278 0, /* tp_itemsize */ \
2279 evpy_dealloc, /* tp_dealloc */ \
2280 0, /* tp_print */ \
2281 0, /* tp_getattr */ \
2282 0, /* tp_setattr */ \
2283 0, /* tp_compare */ \
2284 0, /* tp_repr */ \
2285 0, /* tp_as_number */ \
2286 0, /* tp_as_sequence */ \
2287 0, /* tp_as_mapping */ \
2288 0, /* tp_hash */ \
2289 0, /* tp_call */ \
2290 0, /* tp_str */ \
2291 0, /* tp_getattro */ \
2292 0, /* tp_setattro */ \
2293 0, /* tp_as_buffer */ \
2294 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
2295 doc, /* tp_doc */ \
2296 0, /* tp_traverse */ \
2297 0, /* tp_clear */ \
2298 0, /* tp_richcompare */ \
2299 0, /* tp_weaklistoffset */ \
2300 0, /* tp_iter */ \
2301 0, /* tp_iternext */ \
2302 0, /* tp_methods */ \
2303 0, /* tp_members */ \
2304 0, /* tp_getset */ \
2305 &base, /* tp_base */ \
2306 0, /* tp_dict */ \
2307 0, /* tp_descr_get */ \
2308 0, /* tp_descr_set */ \
2309 0, /* tp_dictoffset */ \
2310 0, /* tp_init */ \
2311 0 /* tp_alloc */ \
2312 };
2313#include "py-event-types.def"
2314#undef GDB_PY_DEFINE_EVENT_TYPE
2315
12453b93 2316#endif /* HAVE_PYTHON */