1 /* General python/gdb code
3 Copyright (C) 2008, 2009 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
)
106 struct cleanup
*cleanup
;
107 PyGILState_STATE state
;
109 if (cmd
->body_count
!= 1)
110 error (_("Invalid \"python\" block structure."));
112 state
= PyGILState_Ensure ();
113 cleanup
= make_cleanup_py_restore_gil (&state
);
115 script
= compute_python_string (cmd
->body_list
[0]);
116 PyRun_SimpleString (script
);
118 if (PyErr_Occurred ())
120 gdbpy_print_stack ();
121 error (_("error while executing Python code"));
124 do_cleanups (cleanup
);
127 /* Implementation of the gdb "python" command. */
130 python_command (char *arg
, int from_tty
)
132 struct cleanup
*cleanup
;
133 PyGILState_STATE state
;
135 state
= PyGILState_Ensure ();
136 cleanup
= make_cleanup_py_restore_gil (&state
);
138 while (arg
&& *arg
&& isspace (*arg
))
142 PyRun_SimpleString (arg
);
143 if (PyErr_Occurred ())
145 gdbpy_print_stack ();
146 error (_("error while executing Python code"));
151 struct command_line
*l
= get_command_line (python_control
, "");
152 make_cleanup_free_command_lines (&l
);
153 execute_control_command_untraced (l
);
156 do_cleanups (cleanup
);
161 /* Transform a gdb parameters's value into a Python value. May return
162 NULL (and set a Python exception) on error. Helper function for
166 parameter_to_python (struct cmd_list_element
*cmd
)
168 switch (cmd
->var_type
)
171 case var_string_noescape
:
172 case var_optional_filename
:
176 char *str
= * (char **) cmd
->var
;
179 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
184 if (* (int *) cmd
->var
)
190 case var_auto_boolean
:
192 enum auto_boolean ab
= * (enum auto_boolean
*) cmd
->var
;
193 if (ab
== AUTO_BOOLEAN_TRUE
)
195 else if (ab
== AUTO_BOOLEAN_FALSE
)
202 if ((* (int *) cmd
->var
) == INT_MAX
)
206 return PyLong_FromLong (* (int *) cmd
->var
);
210 unsigned int val
= * (unsigned int *) cmd
->var
;
213 return PyLong_FromUnsignedLong (val
);
217 return PyErr_Format (PyExc_RuntimeError
, "programmer error: unhandled type");
220 /* A Python function which returns a gdb parameter's value as a Python
224 get_parameter (PyObject
*self
, PyObject
*args
)
226 struct cmd_list_element
*alias
, *prefix
, *cmd
;
228 volatile struct gdb_exception except
;
230 if (! PyArg_ParseTuple (args
, "s", &arg
))
233 newarg
= concat ("show ", arg
, (char *) NULL
);
235 TRY_CATCH (except
, RETURN_MASK_ALL
)
237 if (! lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
))
240 return PyErr_Format (PyExc_RuntimeError
,
241 "could not find variable `%s'", arg
);
245 GDB_PY_HANDLE_EXCEPTION (except
);
248 return PyErr_Format (PyExc_RuntimeError
, "`%s' is not a variable", arg
);
249 return parameter_to_python (cmd
);
252 /* A Python function which evaluates a string using the gdb CLI. */
255 execute_gdb_command (PyObject
*self
, PyObject
*args
)
257 struct cmd_list_element
*alias
, *prefix
, *cmd
;
259 volatile struct gdb_exception except
;
261 if (! PyArg_ParseTuple (args
, "s", &arg
))
264 TRY_CATCH (except
, RETURN_MASK_ALL
)
266 execute_command (arg
, 0);
268 GDB_PY_HANDLE_EXCEPTION (except
);
270 /* Do any commands attached to breakpoint we stopped at. */
271 bpstat_do_actions ();
280 /* A python function to write a single string using gdb's filtered
283 gdbpy_write (PyObject
*self
, PyObject
*args
)
286 if (! PyArg_ParseTuple (args
, "s", &arg
))
288 printf_filtered ("%s", arg
);
292 /* A python function to flush gdb's filtered output stream. */
294 gdbpy_flush (PyObject
*self
, PyObject
*args
)
296 gdb_flush (gdb_stdout
);
300 /* Print a python exception trace, or print nothing and clear the
301 python exception, depending on gdbpy_should_print_stack. Only call
302 this if a python exception is set. */
304 gdbpy_print_stack (void)
306 if (gdbpy_should_print_stack
)
312 #else /* HAVE_PYTHON */
314 /* Dummy implementation of the gdb "python" command. */
317 python_command (char *arg
, int from_tty
)
319 while (arg
&& *arg
&& isspace (*arg
))
322 error (_("Python scripting is not supported in this copy of GDB."));
325 struct command_line
*l
= get_command_line (python_control
, "");
326 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
327 execute_control_command_untraced (l
);
328 do_cleanups (cleanups
);
333 eval_python_from_control_command (struct command_line
*cmd
)
335 error (_("Python scripting is not supported in this copy of GDB."));
338 #endif /* HAVE_PYTHON */
342 /* Lists for 'maint set python' commands. */
344 static struct cmd_list_element
*set_python_list
;
345 static struct cmd_list_element
*show_python_list
;
347 /* Function for use by 'maint set python' prefix command. */
350 set_python (char *args
, int from_tty
)
352 help_list (set_python_list
, "maintenance set python ", -1, gdb_stdout
);
355 /* Function for use by 'maint show python' prefix command. */
358 show_python (char *args
, int from_tty
)
360 cmd_show_list (show_python_list
, from_tty
, "");
363 /* Initialize the Python code. */
366 _initialize_python (void)
368 add_com ("python", class_obscure
, python_command
,
371 Evaluate a Python command.\n\
373 The command can be given as an argument, for instance:\n\
377 If no argument is given, the following lines are read and used\n\
378 as the Python commands. Type a line containing \"end\" to indicate\n\
379 the end of the command.")
380 #else /* HAVE_PYTHON */
382 Evaluate a Python command.\n\
384 Python scripting is not supported in this copy of GDB.\n\
385 This command is only a placeholder.")
386 #endif /* HAVE_PYTHON */
389 add_prefix_cmd ("python", no_class
, show_python
,
390 _("Prefix command for python maintenance settings."),
391 &show_python_list
, "maintenance show python ", 0,
392 &maintenance_show_cmdlist
);
393 add_prefix_cmd ("python", no_class
, set_python
,
394 _("Prefix command for python maintenance settings."),
395 &set_python_list
, "maintenance set python ", 0,
396 &maintenance_set_cmdlist
);
398 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
399 &gdbpy_should_print_stack
, _("\
400 Enable or disable printing of Python stack dump on error."), _("\
401 Show whether Python stack will be printed on error."), _("\
402 Enables or disables printing of Python stack traces."),
409 PyEval_InitThreads ();
411 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
413 /* The casts to (char*) are for python 2.4. */
414 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
415 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
416 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG", (char*) target_name
);
418 gdbpy_initialize_values ();
420 PyRun_SimpleString ("import gdb");
422 /* Create a couple objects which are used for Python's stdout and
424 PyRun_SimpleString ("\
426 class GdbOutputFile:\n\
434 def write(self, s):\n\
437 def writelines(self, iterable):\n\
438 for line in iterable:\n\
444 sys.stderr = GdbOutputFile()\n\
445 sys.stdout = GdbOutputFile()\n\
448 /* Release the GIL while gdb runs. */
449 PyThreadState_Swap (NULL
);
450 PyEval_ReleaseLock ();
452 #endif /* HAVE_PYTHON */