]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/python/python.c
This commit was manufactured by cvs2svn to create branch
[thirdparty/binutils-gdb.git] / gdb / python / python.c
CommitLineData
d57a3c85
TJB
1/* General python/gdb code
2
3 Copyright (C) 2008 Free Software Foundation, Inc.
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"
21#include "command.h"
22#include "ui-out.h"
23#include "cli/cli-script.h"
24#include "gdbcmd.h"
25
26#include <ctype.h>
27
28/* True if we should print the stack when catching a Python error,
29 false otherwise. */
30static int gdbpy_should_print_stack = 1;
31
32#ifdef HAVE_PYTHON
33
34#include "python.h"
35#include "libiberty.h"
36#include "cli/cli-decode.h"
37#include "charset.h"
38#include "top.h"
39#include "exceptions.h"
40#include "python-internal.h"
41#include "version.h"
42#include "target.h"
43#include "gdbthread.h"
44
45
46PyObject *gdb_module;
47
48static PyObject *get_parameter (PyObject *, PyObject *);
49static PyObject *execute_gdb_command (PyObject *, PyObject *);
50static PyObject *gdbpy_write (PyObject *, PyObject *);
51static PyObject *gdbpy_flush (PyObject *, PyObject *);
52
53static PyMethodDef GdbMethods[] =
54{
b4812cfe 55 { "get_value_from_history", gdbpy_get_value_from_history, METH_VARARGS,
56 "Get a value from history" },
d57a3c85
TJB
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" },
61
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." },
66
67 {NULL, NULL, 0, NULL}
68};
69
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. */
74
75static char *
76compute_python_string (struct command_line *l)
77{
78 struct command_line *iter;
79 char *script = NULL;
80 int size = 0;
81 int here;
82
83 for (iter = l; iter; iter = iter->next)
84 size += strlen (iter->line) + 1;
85
86 script = xmalloc (size + 1);
87 here = 0;
88 for (iter = l; iter; iter = iter->next)
89 {
90 int len = strlen (iter->line);
91 strcpy (&script[here], iter->line);
92 here += len;
93 script[here++] = '\n';
94 }
95 script[here] = '\0';
96 return script;
97}
98
99/* Take a command line structure representing a 'python' command, and
100 evaluate its body using the Python interpreter. */
101
102void
103eval_python_from_control_command (struct command_line *cmd)
104{
105 char *script;
6f581415 106 struct cleanup *cleanup;
107 PyGILState_STATE state;
d57a3c85
TJB
108
109 if (cmd->body_count != 1)
110 error (_("Invalid \"python\" block structure."));
111
6f581415 112 state = PyGILState_Ensure ();
113 cleanup = make_cleanup_py_restore_gil (&state);
114
d57a3c85
TJB
115 script = compute_python_string (cmd->body_list[0]);
116 PyRun_SimpleString (script);
117 xfree (script);
118 if (PyErr_Occurred ())
119 {
120 gdbpy_print_stack ();
121 error (_("error while executing Python code"));
122 }
6f581415 123
124 do_cleanups (cleanup);
d57a3c85
TJB
125}
126
127/* Implementation of the gdb "python" command. */
128
129static void
130python_command (char *arg, int from_tty)
131{
6f581415 132 struct cleanup *cleanup;
133 PyGILState_STATE state;
134
135 state = PyGILState_Ensure ();
136 cleanup = make_cleanup_py_restore_gil (&state);
137
d57a3c85
TJB
138 while (arg && *arg && isspace (*arg))
139 ++arg;
140 if (arg && *arg)
141 {
142 PyRun_SimpleString (arg);
143 if (PyErr_Occurred ())
144 {
145 gdbpy_print_stack ();
146 error (_("error while executing Python code"));
147 }
148 }
149 else
150 {
151 struct command_line *l = get_command_line (python_control, "");
6f581415 152 make_cleanup_free_command_lines (&l);
d57a3c85 153 execute_control_command_untraced (l);
d57a3c85 154 }
6f581415 155
156 do_cleanups (cleanup);
d57a3c85
TJB
157}
158
159\f
160
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
163 get_parameter. */
164
165static PyObject *
166parameter_to_python (struct cmd_list_element *cmd)
167{
168 switch (cmd->var_type)
169 {
170 case var_string:
171 case var_string_noescape:
172 case var_optional_filename:
173 case var_filename:
174 case var_enum:
175 {
176 char *str = * (char **) cmd->var;
177 if (! str)
178 str = "";
179 return PyString_Decode (str, strlen (str), host_charset (), NULL);
180 }
181
182 case var_boolean:
183 {
184 if (* (int *) cmd->var)
185 Py_RETURN_TRUE;
186 else
187 Py_RETURN_FALSE;
188 }
189
190 case var_auto_boolean:
191 {
192 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
193 if (ab == AUTO_BOOLEAN_TRUE)
194 Py_RETURN_TRUE;
195 else if (ab == AUTO_BOOLEAN_FALSE)
196 Py_RETURN_FALSE;
197 else
198 Py_RETURN_NONE;
199 }
200
201 case var_integer:
202 if ((* (int *) cmd->var) == INT_MAX)
203 Py_RETURN_NONE;
204 /* Fall through. */
205 case var_zinteger:
206 return PyLong_FromLong (* (int *) cmd->var);
207
208 case var_uinteger:
209 {
210 unsigned int val = * (unsigned int *) cmd->var;
211 if (val == UINT_MAX)
212 Py_RETURN_NONE;
213 return PyLong_FromUnsignedLong (val);
214 }
215 }
216
217 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
218}
219
220/* A Python function which returns a gdb parameter's value as a Python
221 value. */
222
223static PyObject *
224get_parameter (PyObject *self, PyObject *args)
225{
226 struct cmd_list_element *alias, *prefix, *cmd;
227 char *arg, *newarg;
228 volatile struct gdb_exception except;
229
230 if (! PyArg_ParseTuple (args, "s", &arg))
231 return NULL;
232
233 newarg = concat ("show ", arg, (char *) NULL);
234
235 TRY_CATCH (except, RETURN_MASK_ALL)
236 {
237 if (! lookup_cmd_composition (newarg, &alias, &prefix, &cmd))
238 {
239 xfree (newarg);
240 return PyErr_Format (PyExc_RuntimeError,
241 "could not find variable `%s'", arg);
242 }
243 }
244 xfree (newarg);
245 GDB_PY_HANDLE_EXCEPTION (except);
246
247 if (! cmd->var)
248 return PyErr_Format (PyExc_RuntimeError, "`%s' is not a variable", arg);
249 return parameter_to_python (cmd);
250}
251
252/* A Python function which evaluates a string using the gdb CLI. */
253
254static PyObject *
255execute_gdb_command (PyObject *self, PyObject *args)
256{
257 struct cmd_list_element *alias, *prefix, *cmd;
258 char *arg, *newarg;
259 volatile struct gdb_exception except;
d57a3c85
TJB
260
261 if (! PyArg_ParseTuple (args, "s", &arg))
262 return NULL;
263
d57a3c85
TJB
264 TRY_CATCH (except, RETURN_MASK_ALL)
265 {
266 execute_command (arg, 0);
267 }
268 GDB_PY_HANDLE_EXCEPTION (except);
269
347bddb7
PA
270 /* Do any commands attached to breakpoint we stopped at. */
271 bpstat_do_actions ();
d57a3c85
TJB
272
273 Py_RETURN_NONE;
274}
275
276\f
277
278/* Printing. */
279
280/* A python function to write a single string using gdb's filtered
281 output stream. */
282static PyObject *
283gdbpy_write (PyObject *self, PyObject *args)
284{
285 char *arg;
286 if (! PyArg_ParseTuple (args, "s", &arg))
287 return NULL;
288 printf_filtered ("%s", arg);
289 Py_RETURN_NONE;
290}
291
292/* A python function to flush gdb's filtered output stream. */
293static PyObject *
294gdbpy_flush (PyObject *self, PyObject *args)
295{
296 gdb_flush (gdb_stdout);
297 Py_RETURN_NONE;
298}
299
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. */
303void
304gdbpy_print_stack (void)
305{
306 if (gdbpy_should_print_stack)
307 PyErr_Print ();
308 else
309 PyErr_Clear ();
310}
311
312#else /* HAVE_PYTHON */
313
314/* Dummy implementation of the gdb "python" command. */
315
316static void
317python_command (char *arg, int from_tty)
318{
319 while (arg && *arg && isspace (*arg))
320 ++arg;
321 if (arg && *arg)
322 error (_("Python scripting is not supported in this copy of GDB."));
323 else
324 {
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);
329 }
330}
331
332void
333eval_python_from_control_command (struct command_line *cmd)
334{
335 error (_("Python scripting is not supported in this copy of GDB."));
336}
337
338#endif /* HAVE_PYTHON */
339
340\f
341
342/* Lists for 'maint set python' commands. */
343
344static struct cmd_list_element *set_python_list;
345static struct cmd_list_element *show_python_list;
346
347/* Function for use by 'maint set python' prefix command. */
348
349static void
350set_python (char *args, int from_tty)
351{
352 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
353}
354
355/* Function for use by 'maint show python' prefix command. */
356
357static void
358show_python (char *args, int from_tty)
359{
360 cmd_show_list (show_python_list, from_tty, "");
361}
362
363/* Initialize the Python code. */
364
365void
366_initialize_python (void)
367{
368 add_com ("python", class_obscure, python_command,
369#ifdef HAVE_PYTHON
370 _("\
371Evaluate a Python command.\n\
372\n\
373The command can be given as an argument, for instance:\n\
374\n\
375 python print 23\n\
376\n\
377If no argument is given, the following lines are read and used\n\
378as the Python commands. Type a line containing \"end\" to indicate\n\
379the end of the command.")
380#else /* HAVE_PYTHON */
381 _("\
382Evaluate a Python command.\n\
383\n\
384Python scripting is not supported in this copy of GDB.\n\
385This command is only a placeholder.")
386#endif /* HAVE_PYTHON */
387 );
388
389 add_prefix_cmd ("python", no_class, show_python,
390 _("Prefix command for python maintenance settings."),
509238d6 391 &show_python_list, "maintenance show python ", 0,
d57a3c85
TJB
392 &maintenance_show_cmdlist);
393 add_prefix_cmd ("python", no_class, set_python,
394 _("Prefix command for python maintenance settings."),
509238d6 395 &set_python_list, "maintenance set python ", 0,
d57a3c85
TJB
396 &maintenance_set_cmdlist);
397
398 add_setshow_boolean_cmd ("print-stack", class_maintenance,
399 &gdbpy_should_print_stack, _("\
400Enable or disable printing of Python stack dump on error."), _("\
401Show whether Python stack will be printed on error."), _("\
402Enables or disables printing of Python stack traces."),
403 NULL, NULL,
404 &set_python_list,
405 &show_python_list);
406
407#ifdef HAVE_PYTHON
408 Py_Initialize ();
6f581415 409 PyEval_InitThreads ();
d57a3c85
TJB
410
411 gdb_module = Py_InitModule ("gdb", GdbMethods);
412
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);
417
b4812cfe 418 gdbpy_initialize_values ();
419
d57a3c85
TJB
420 PyRun_SimpleString ("import gdb");
421
422 /* Create a couple objects which are used for Python's stdout and
423 stderr. */
424 PyRun_SimpleString ("\
425import sys\n\
426class GdbOutputFile:\n\
427 def close(self):\n\
428 # Do nothing.\n\
429 return None\n\
430\n\
431 def isatty(self):\n\
432 return False\n\
433\n\
434 def write(self, s):\n\
435 gdb.write(s)\n\
436\n\
437 def writelines(self, iterable):\n\
438 for line in iterable:\n\
439 self.write(line)\n\
440\n\
441 def flush(self):\n\
442 gdb.flush()\n\
443\n\
444sys.stderr = GdbOutputFile()\n\
445sys.stdout = GdbOutputFile()\n\
446");
6f581415 447
448 /* Release the GIL while gdb runs. */
449 PyThreadState_Swap (NULL);
450 PyEval_ReleaseLock ();
451
d57a3c85
TJB
452#endif /* HAVE_PYTHON */
453}