1 /* General python/gdb code
3 Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
26 #include "progspace.h"
30 #include "exceptions.h"
34 /* True if we should print the stack when catching a Python error,
36 static int gdbpy_should_print_stack = 1;
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
45 #include "python-internal.h"
48 #include "gdbthread.h"
50 static PyMethodDef GdbMethods[];
54 /* Some string constants we may wish to use. */
55 PyObject *gdbpy_to_string_cst;
56 PyObject *gdbpy_children_cst;
57 PyObject *gdbpy_display_hint_cst;
58 PyObject *gdbpy_doc_cst;
61 /* Architecture and language to be used in callbacks from
62 the Python interpreter. */
63 struct gdbarch *python_gdbarch;
64 const struct language_defn *python_language;
66 /* Restore global language and architecture and Python GIL state
67 when leaving the Python interpreter. */
71 PyGILState_STATE state;
72 struct gdbarch *gdbarch;
73 const struct language_defn *language;
77 restore_python_env (void *p)
79 struct python_env *env = (struct python_env *)p;
81 PyGILState_Release (env->state);
82 python_gdbarch = env->gdbarch;
83 python_language = env->language;
87 /* Called before entering the Python interpreter to install the
88 current language and architecture to be used for Python values. */
91 ensure_python_env (struct gdbarch *gdbarch,
92 const struct language_defn *language)
94 struct python_env *env = xmalloc (sizeof *env);
96 env->state = PyGILState_Ensure ();
97 env->gdbarch = python_gdbarch;
98 env->language = python_language;
100 python_gdbarch = gdbarch;
101 python_language = language;
103 return make_cleanup (restore_python_env, env);
107 /* Given a command_line, return a command string suitable for passing
108 to Python. Lines in the string are separated by newlines. The
109 return value is allocated using xmalloc and the caller is
110 responsible for freeing it. */
113 compute_python_string (struct command_line *l)
115 struct command_line *iter;
120 for (iter = l; iter; iter = iter->next)
121 size += strlen (iter->line) + 1;
123 script = xmalloc (size + 1);
125 for (iter = l; iter; iter = iter->next)
127 int len = strlen (iter->line);
129 strcpy (&script[here], iter->line);
131 script[here++] = '\n';
137 /* Take a command line structure representing a 'python' command, and
138 evaluate its body using the Python interpreter. */
141 eval_python_from_control_command (struct command_line *cmd)
145 struct cleanup *cleanup;
147 if (cmd->body_count != 1)
148 error (_("Invalid \"python\" block structure."));
150 cleanup = ensure_python_env (get_current_arch (), current_language);
152 script = compute_python_string (cmd->body_list[0]);
153 ret = PyRun_SimpleString (script);
157 gdbpy_print_stack ();
158 error (_("Error while executing Python code."));
161 do_cleanups (cleanup);
164 /* Implementation of the gdb "python" command. */
167 python_command (char *arg, int from_tty)
169 struct cleanup *cleanup;
171 cleanup = ensure_python_env (get_current_arch (), current_language);
172 while (arg && *arg && isspace (*arg))
176 if (PyRun_SimpleString (arg))
178 gdbpy_print_stack ();
179 error (_("Error while executing Python code."));
184 struct command_line *l = get_command_line (python_control, "");
186 make_cleanup_free_command_lines (&l);
187 execute_control_command_untraced (l);
190 do_cleanups (cleanup);
195 /* Transform a gdb parameters's value into a Python value. May return
196 NULL (and set a Python exception) on error. Helper function for
199 gdbpy_parameter_value (enum var_types type, void *var)
204 case var_string_noescape:
205 case var_optional_filename:
209 char *str = * (char **) var;
213 return PyString_Decode (str, strlen (str), host_charset (), NULL);
224 case var_auto_boolean:
226 enum auto_boolean ab = * (enum auto_boolean *) var;
228 if (ab == AUTO_BOOLEAN_TRUE)
230 else if (ab == AUTO_BOOLEAN_FALSE)
237 if ((* (int *) var) == INT_MAX)
241 return PyLong_FromLong (* (int *) var);
245 unsigned int val = * (unsigned int *) var;
249 return PyLong_FromUnsignedLong (val);
253 return PyErr_Format (PyExc_RuntimeError,
254 _("Programmer error: unhandled type."));
257 /* A Python function which returns a gdb parameter's value as a Python
261 gdbpy_parameter (PyObject *self, PyObject *args)
263 struct cmd_list_element *alias, *prefix, *cmd;
266 volatile struct gdb_exception except;
268 if (! PyArg_ParseTuple (args, "s", &arg))
271 newarg = concat ("show ", arg, (char *) NULL);
273 TRY_CATCH (except, RETURN_MASK_ALL)
275 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
278 GDB_PY_HANDLE_EXCEPTION (except);
280 return PyErr_Format (PyExc_RuntimeError,
281 _("Could not find parameter `%s'."), arg);
284 return PyErr_Format (PyExc_RuntimeError,
285 _("`%s' is not a parameter."), arg);
286 return gdbpy_parameter_value (cmd->var_type, cmd->var);
289 /* Wrapper for target_charset. */
292 gdbpy_target_charset (PyObject *self, PyObject *args)
294 const char *cset = target_charset (python_gdbarch);
296 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
299 /* Wrapper for target_wide_charset. */
302 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
304 const char *cset = target_wide_charset (python_gdbarch);
306 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
309 /* A Python function which evaluates a string using the gdb CLI. */
312 execute_gdb_command (PyObject *self, PyObject *args)
315 PyObject *from_tty_obj = NULL;
318 volatile struct gdb_exception except;
320 if (! PyArg_ParseTuple (args, "s|O!", &arg, &PyBool_Type, &from_tty_obj))
326 cmp = PyObject_IsTrue (from_tty_obj);
332 TRY_CATCH (except, RETURN_MASK_ALL)
334 /* Copy the argument text in case the command modifies it. */
335 char *copy = xstrdup (arg);
336 struct cleanup *cleanup = make_cleanup (xfree, copy);
338 execute_command (copy, from_tty);
339 do_cleanups (cleanup);
341 GDB_PY_HANDLE_EXCEPTION (except);
343 /* Do any commands attached to breakpoint we stopped at. */
344 bpstat_do_actions ();
349 /* Parse a string and evaluate it as an expression. */
351 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
354 struct value *result = NULL;
355 volatile struct gdb_exception except;
357 if (!PyArg_ParseTuple (args, "s", &expr_str))
360 TRY_CATCH (except, RETURN_MASK_ALL)
362 result = parse_and_eval (expr_str);
364 GDB_PY_HANDLE_EXCEPTION (except);
366 return value_to_value_object (result);
369 /* Read a file as Python code. STREAM is the input file; FILE is the
371 STREAM is not closed, that is the caller's responsibility. */
374 source_python_script (FILE *stream, const char *file)
376 struct cleanup *cleanup;
378 cleanup = ensure_python_env (get_current_arch (), current_language);
380 /* Note: If an exception occurs python will print the traceback and
381 clear the error indicator. */
382 PyRun_SimpleFile (stream, file);
384 do_cleanups (cleanup);
391 /* A python function to write a single string using gdb's filtered
394 gdbpy_write (PyObject *self, PyObject *args)
398 if (! PyArg_ParseTuple (args, "s", &arg))
400 printf_filtered ("%s", arg);
404 /* A python function to flush gdb's filtered output stream. */
406 gdbpy_flush (PyObject *self, PyObject *args)
408 gdb_flush (gdb_stdout);
412 /* Print a python exception trace, or print nothing and clear the
413 python exception, depending on gdbpy_should_print_stack. Only call
414 this if a python exception is set. */
416 gdbpy_print_stack (void)
418 if (gdbpy_should_print_stack)
421 /* PyErr_Print doesn't necessarily end output with a newline.
422 This works because Python's stdout/stderr is fed through
432 /* Return the current Progspace.
433 There always is one. */
436 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
440 result = pspace_to_pspace_object (current_program_space);
446 /* Return a sequence holding all the Progspaces. */
449 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
451 struct program_space *ps;
454 list = PyList_New (0);
460 PyObject *item = pspace_to_pspace_object (ps);
462 if (!item || PyList_Append (list, item) == -1)
474 /* The "current" objfile. This is set when gdb detects that a new
475 objfile has been loaded. It is only set for the duration of a call to
476 source_python_script_for_objfile; it is NULL at other times. */
477 static struct objfile *gdbpy_current_objfile;
479 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
483 source_python_script_for_objfile (struct objfile *objfile,
484 FILE *stream, const char *file)
486 struct cleanup *cleanups;
488 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
489 gdbpy_current_objfile = objfile;
491 /* Note: If an exception occurs python will print the traceback and
492 clear the error indicator. */
493 PyRun_SimpleFile (stream, file);
495 do_cleanups (cleanups);
496 gdbpy_current_objfile = NULL;
499 /* Return the current Objfile, or None if there isn't one. */
502 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
506 if (! gdbpy_current_objfile)
509 result = objfile_to_objfile_object (gdbpy_current_objfile);
515 /* Return a sequence holding all the Objfiles. */
518 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
520 struct objfile *objf;
523 list = PyList_New (0);
529 PyObject *item = objfile_to_objfile_object (objf);
531 if (!item || PyList_Append (list, item) == -1)
541 #else /* HAVE_PYTHON */
543 /* Dummy implementation of the gdb "python" command. */
546 python_command (char *arg, int from_tty)
548 while (arg && *arg && isspace (*arg))
551 error (_("Python scripting is not supported in this copy of GDB."));
554 struct command_line *l = get_command_line (python_control, "");
555 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
557 execute_control_command_untraced (l);
558 do_cleanups (cleanups);
563 eval_python_from_control_command (struct command_line *cmd)
565 error (_("Python scripting is not supported in this copy of GDB."));
569 source_python_script (FILE *stream, const char *file)
571 throw_error (UNSUPPORTED_ERROR,
572 _("Python scripting is not supported in this copy of GDB."));
575 #endif /* HAVE_PYTHON */
579 /* Lists for 'maint set python' commands. */
581 struct cmd_list_element *set_python_list;
582 struct cmd_list_element *show_python_list;
584 /* Function for use by 'maint set python' prefix command. */
587 set_python (char *args, int from_tty)
589 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
592 /* Function for use by 'maint show python' prefix command. */
595 show_python (char *args, int from_tty)
597 cmd_show_list (show_python_list, from_tty, "");
600 /* Initialize the Python code. */
602 /* Provide a prototype to silence -Wmissing-prototypes. */
603 extern initialize_file_ftype _initialize_python;
606 _initialize_python (void)
608 add_com ("python", class_obscure, python_command,
611 Evaluate a Python command.\n\
613 The command can be given as an argument, for instance:\n\
617 If no argument is given, the following lines are read and used\n\
618 as the Python commands. Type a line containing \"end\" to indicate\n\
619 the end of the command.")
620 #else /* HAVE_PYTHON */
622 Evaluate a Python command.\n\
624 Python scripting is not supported in this copy of GDB.\n\
625 This command is only a placeholder.")
626 #endif /* HAVE_PYTHON */
629 add_prefix_cmd ("python", no_class, show_python,
630 _("Prefix command for python maintenance settings."),
631 &show_python_list, "maintenance show python ", 0,
632 &maintenance_show_cmdlist);
633 add_prefix_cmd ("python", no_class, set_python,
634 _("Prefix command for python maintenance settings."),
635 &set_python_list, "maintenance set python ", 0,
636 &maintenance_set_cmdlist);
638 add_setshow_boolean_cmd ("print-stack", class_maintenance,
639 &gdbpy_should_print_stack, _("\
640 Enable or disable printing of Python stack dump on error."), _("\
641 Show whether Python stack will be printed on error."), _("\
642 Enables or disables printing of Python stack traces."),
649 PyEval_InitThreads ();
651 gdb_module = Py_InitModule ("gdb", GdbMethods);
653 /* The casts to (char*) are for python 2.4. */
654 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
655 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
656 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
658 gdbpy_initialize_auto_load ();
659 gdbpy_initialize_values ();
660 gdbpy_initialize_frames ();
661 gdbpy_initialize_commands ();
662 gdbpy_initialize_symbols ();
663 gdbpy_initialize_symtabs ();
664 gdbpy_initialize_blocks ();
665 gdbpy_initialize_functions ();
666 gdbpy_initialize_parameters ();
667 gdbpy_initialize_types ();
668 gdbpy_initialize_pspace ();
669 gdbpy_initialize_objfile ();
670 gdbpy_initialize_breakpoints ();
671 gdbpy_initialize_lazy_string ();
673 PyRun_SimpleString ("import gdb");
674 PyRun_SimpleString ("gdb.pretty_printers = []");
676 gdbpy_to_string_cst = PyString_FromString ("to_string");
677 gdbpy_children_cst = PyString_FromString ("children");
678 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
679 gdbpy_doc_cst = PyString_FromString ("__doc__");
681 /* Create a couple objects which are used for Python's stdout and
683 PyRun_SimpleString ("\
685 class GdbOutputFile:\n\
693 def write(self, s):\n\
696 def writelines(self, iterable):\n\
697 for line in iterable:\n\
703 sys.stderr = GdbOutputFile()\n\
704 sys.stdout = GdbOutputFile()\n\
707 /* Release the GIL while gdb runs. */
708 PyThreadState_Swap (NULL);
709 PyEval_ReleaseLock ();
711 #endif /* HAVE_PYTHON */
718 static PyMethodDef GdbMethods[] =
720 { "history", gdbpy_history, METH_VARARGS,
721 "Get a value from history" },
722 { "execute", execute_gdb_command, METH_VARARGS,
723 "Execute a gdb command" },
724 { "parameter", gdbpy_parameter, METH_VARARGS,
725 "Return a gdb parameter's value" },
727 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
728 "Return a tuple of all breakpoint objects" },
730 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
731 "Find the default visualizer for a Value." },
733 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
734 "Return the current Progspace." },
735 { "progspaces", gdbpy_progspaces, METH_NOARGS,
736 "Return a sequence of all progspaces." },
738 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
739 "Return the current Objfile being loaded, or None." },
740 { "objfiles", gdbpy_objfiles, METH_NOARGS,
741 "Return a sequence of all loaded objfiles." },
743 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
744 "selected_frame () -> gdb.Frame.\n\
745 Return the selected frame object." },
746 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
747 "stop_reason_string (Integer) -> String.\n\
748 Return a string explaining unwind stop reason." },
750 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
751 METH_VARARGS | METH_KEYWORDS,
752 "lookup_type (name [, block]) -> type\n\
753 Return a Type corresponding to the given name." },
754 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
755 METH_VARARGS | METH_KEYWORDS,
756 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
757 Return a tuple with the symbol corresponding to the given name (or None) and\n\
758 a boolean indicating if name is a field of the current implied argument\n\
759 `this' (when the current language is object-oriented)." },
760 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
761 "Return the block containing the given pc value, or None." },
762 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
763 "parse_and_eval (String) -> Value.\n\
764 Parse String as an expression, evaluate it, and return the result as a Value."
767 { "target_charset", gdbpy_target_charset, METH_NOARGS,
768 "target_charset () -> string.\n\
769 Return the name of the current target charset." },
770 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
771 "target_wide_charset () -> string.\n\
772 Return the name of the current target wide charset." },
774 { "write", gdbpy_write, METH_VARARGS,
775 "Write a string using gdb's filtered stream." },
776 { "flush", gdbpy_flush, METH_NOARGS,
777 "Flush gdb's filtered stdout stream." },
779 {NULL, NULL, 0, NULL}
782 #endif /* HAVE_PYTHON */