1 /* General python/gdb code
3 Copyright (C) 2008 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/>. */
23 #include "cli/cli-script.h"
28 /* True if we should print the stack when catching a Python error,
30 static int gdbpy_should_print_stack = 1;
35 #include "libiberty.h"
36 #include "cli/cli-decode.h"
39 #include "exceptions.h"
40 #include "python-internal.h"
43 #include "gdbthread.h"
48 static PyObject *get_parameter (PyObject *, PyObject *);
49 static PyObject *execute_gdb_command (PyObject *, PyObject *);
50 static PyObject *gdbpy_write (PyObject *, PyObject *);
51 static PyObject *gdbpy_flush (PyObject *, PyObject *);
53 static PyMethodDef GdbMethods[] =
55 { "get_value_from_history", gdbpy_get_value_from_history, METH_VARARGS,
56 "Get a value from history" },
57 { "execute", execute_gdb_command, METH_VARARGS,
58 "Execute a gdb command" },
59 { "get_parameter", get_parameter, METH_VARARGS,
60 "Return a gdb parameter's value" },
62 { "write", gdbpy_write, METH_VARARGS,
63 "Write a string using gdb's filtered stream." },
64 { "flush", gdbpy_flush, METH_NOARGS,
65 "Flush gdb's filtered stdout stream." },
70 /* Given a command_line, return a command string suitable for passing
71 to Python. Lines in the string are separated by newlines. The
72 return value is allocated using xmalloc and the caller is
73 responsible for freeing it. */
76 compute_python_string (struct command_line *l)
78 struct command_line *iter;
83 for (iter = l; iter; iter = iter->next)
84 size += strlen (iter->line) + 1;
86 script = xmalloc (size + 1);
88 for (iter = l; iter; iter = iter->next)
90 int len = strlen (iter->line);
91 strcpy (&script[here], iter->line);
93 script[here++] = '\n';
99 /* Take a command line structure representing a 'python' command, and
100 evaluate its body using the Python interpreter. */
103 eval_python_from_control_command (struct command_line *cmd)
107 if (cmd->body_count != 1)
108 error (_("Invalid \"python\" block structure."));
110 script = compute_python_string (cmd->body_list[0]);
111 PyRun_SimpleString (script);
113 if (PyErr_Occurred ())
115 gdbpy_print_stack ();
116 error (_("error while executing Python code"));
120 /* Implementation of the gdb "python" command. */
123 python_command (char *arg, int from_tty)
125 while (arg && *arg && isspace (*arg))
129 PyRun_SimpleString (arg);
130 if (PyErr_Occurred ())
132 gdbpy_print_stack ();
133 error (_("error while executing Python code"));
138 struct command_line *l = get_command_line (python_control, "");
139 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
140 execute_control_command_untraced (l);
141 do_cleanups (cleanups);
147 /* Transform a gdb parameters's value into a Python value. May return
148 NULL (and set a Python exception) on error. Helper function for
152 parameter_to_python (struct cmd_list_element *cmd)
154 switch (cmd->var_type)
157 case var_string_noescape:
158 case var_optional_filename:
162 char *str = * (char **) cmd->var;
165 return PyString_Decode (str, strlen (str), host_charset (), NULL);
170 if (* (int *) cmd->var)
176 case var_auto_boolean:
178 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
179 if (ab == AUTO_BOOLEAN_TRUE)
181 else if (ab == AUTO_BOOLEAN_FALSE)
188 if ((* (int *) cmd->var) == INT_MAX)
192 return PyLong_FromLong (* (int *) cmd->var);
196 unsigned int val = * (unsigned int *) cmd->var;
199 return PyLong_FromUnsignedLong (val);
203 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
206 /* A Python function which returns a gdb parameter's value as a Python
210 get_parameter (PyObject *self, PyObject *args)
212 struct cmd_list_element *alias, *prefix, *cmd;
214 volatile struct gdb_exception except;
216 if (! PyArg_ParseTuple (args, "s", &arg))
219 newarg = concat ("show ", arg, (char *) NULL);
221 TRY_CATCH (except, RETURN_MASK_ALL)
223 if (! lookup_cmd_composition (newarg, &alias, &prefix, &cmd))
226 return PyErr_Format (PyExc_RuntimeError,
227 "could not find variable `%s'", arg);
231 GDB_PY_HANDLE_EXCEPTION (except);
234 return PyErr_Format (PyExc_RuntimeError, "`%s' is not a variable", arg);
235 return parameter_to_python (cmd);
238 /* A Python function which evaluates a string using the gdb CLI. */
241 execute_gdb_command (PyObject *self, PyObject *args)
243 struct cmd_list_element *alias, *prefix, *cmd;
245 volatile struct gdb_exception except;
247 if (! PyArg_ParseTuple (args, "s", &arg))
250 TRY_CATCH (except, RETURN_MASK_ALL)
252 execute_command (arg, 0);
254 GDB_PY_HANDLE_EXCEPTION (except);
256 /* Do any commands attached to breakpoint we stopped at. */
257 bpstat_do_actions ();
266 /* A python function to write a single string using gdb's filtered
269 gdbpy_write (PyObject *self, PyObject *args)
272 if (! PyArg_ParseTuple (args, "s", &arg))
274 printf_filtered ("%s", arg);
278 /* A python function to flush gdb's filtered output stream. */
280 gdbpy_flush (PyObject *self, PyObject *args)
282 gdb_flush (gdb_stdout);
286 /* Print a python exception trace, or print nothing and clear the
287 python exception, depending on gdbpy_should_print_stack. Only call
288 this if a python exception is set. */
290 gdbpy_print_stack (void)
292 if (gdbpy_should_print_stack)
298 #else /* HAVE_PYTHON */
300 /* Dummy implementation of the gdb "python" command. */
303 python_command (char *arg, int from_tty)
305 while (arg && *arg && isspace (*arg))
308 error (_("Python scripting is not supported in this copy of GDB."));
311 struct command_line *l = get_command_line (python_control, "");
312 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
313 execute_control_command_untraced (l);
314 do_cleanups (cleanups);
319 eval_python_from_control_command (struct command_line *cmd)
321 error (_("Python scripting is not supported in this copy of GDB."));
324 #endif /* HAVE_PYTHON */
328 /* Lists for 'maint set python' commands. */
330 static struct cmd_list_element *set_python_list;
331 static struct cmd_list_element *show_python_list;
333 /* Function for use by 'maint set python' prefix command. */
336 set_python (char *args, int from_tty)
338 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
341 /* Function for use by 'maint show python' prefix command. */
344 show_python (char *args, int from_tty)
346 cmd_show_list (show_python_list, from_tty, "");
349 /* Initialize the Python code. */
352 _initialize_python (void)
354 add_com ("python", class_obscure, python_command,
357 Evaluate a Python command.\n\
359 The command can be given as an argument, for instance:\n\
363 If no argument is given, the following lines are read and used\n\
364 as the Python commands. Type a line containing \"end\" to indicate\n\
365 the end of the command.")
366 #else /* HAVE_PYTHON */
368 Evaluate a Python command.\n\
370 Python scripting is not supported in this copy of GDB.\n\
371 This command is only a placeholder.")
372 #endif /* HAVE_PYTHON */
375 add_prefix_cmd ("python", no_class, show_python,
376 _("Prefix command for python maintenance settings."),
377 &show_python_list, "maintenance show python ", 0,
378 &maintenance_show_cmdlist);
379 add_prefix_cmd ("python", no_class, set_python,
380 _("Prefix command for python maintenance settings."),
381 &set_python_list, "maintenance set python ", 0,
382 &maintenance_set_cmdlist);
384 add_setshow_boolean_cmd ("print-stack", class_maintenance,
385 &gdbpy_should_print_stack, _("\
386 Enable or disable printing of Python stack dump on error."), _("\
387 Show whether Python stack will be printed on error."), _("\
388 Enables or disables printing of Python stack traces."),
396 gdb_module = Py_InitModule ("gdb", GdbMethods);
398 /* The casts to (char*) are for python 2.4. */
399 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
400 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
401 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
403 gdbpy_initialize_values ();
405 PyRun_SimpleString ("import gdb");
407 /* Create a couple objects which are used for Python's stdout and
409 PyRun_SimpleString ("\
411 class GdbOutputFile:\n\
419 def write(self, s):\n\
422 def writelines(self, iterable):\n\
423 for line in iterable:\n\
429 sys.stderr = GdbOutputFile()\n\
430 sys.stdout = GdbOutputFile()\n\
432 #endif /* HAVE_PYTHON */