OSDN Git Service

77d8774ed6f94a63620da17e9893019a82247cd6
[pf3gnuchains/pf3gnuchains3x.git] / gdb / python / python.c
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.  */
30 static 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
46 PyObject *gdb_module;
47
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 *);
52
53 static PyMethodDef GdbMethods[] =
54 {
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" },
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
75 static char *
76 compute_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
102 void
103 eval_python_from_control_command (struct command_line *cmd)
104 {
105   char *script;
106
107   if (cmd->body_count != 1)
108     error (_("Invalid \"python\" block structure."));
109
110   script = compute_python_string (cmd->body_list[0]);
111   PyRun_SimpleString (script);
112   xfree (script);
113   if (PyErr_Occurred ())
114     {
115       gdbpy_print_stack ();
116       error (_("error while executing Python code"));
117     }
118 }
119
120 /* Implementation of the gdb "python" command.  */
121
122 static void
123 python_command (char *arg, int from_tty)
124 {
125   while (arg && *arg && isspace (*arg))
126     ++arg;
127   if (arg && *arg)
128     {
129       PyRun_SimpleString (arg);
130       if (PyErr_Occurred ())
131         {
132           gdbpy_print_stack ();
133           error (_("error while executing Python code"));
134         }
135     }
136   else
137     {
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);
142     }
143 }
144
145 \f
146
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
149    get_parameter.  */
150
151 static PyObject *
152 parameter_to_python (struct cmd_list_element *cmd)
153 {
154   switch (cmd->var_type)
155     {
156     case var_string:
157     case var_string_noescape:
158     case var_optional_filename:
159     case var_filename:
160     case var_enum:
161       {
162         char *str = * (char **) cmd->var;
163         if (! str)
164           str = "";
165         return PyString_Decode (str, strlen (str), host_charset (), NULL);
166       }
167
168     case var_boolean:
169       {
170         if (* (int *) cmd->var)
171           Py_RETURN_TRUE;
172         else
173           Py_RETURN_FALSE;
174       }
175
176     case var_auto_boolean:
177       {
178         enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
179         if (ab == AUTO_BOOLEAN_TRUE)
180           Py_RETURN_TRUE;
181         else if (ab == AUTO_BOOLEAN_FALSE)
182           Py_RETURN_FALSE;
183         else
184           Py_RETURN_NONE;
185       }
186
187     case var_integer:
188       if ((* (int *) cmd->var) == INT_MAX)
189         Py_RETURN_NONE;
190       /* Fall through.  */
191     case var_zinteger:
192       return PyLong_FromLong (* (int *) cmd->var);
193
194     case var_uinteger:
195       {
196         unsigned int val = * (unsigned int *) cmd->var;
197         if (val == UINT_MAX)
198           Py_RETURN_NONE;
199         return PyLong_FromUnsignedLong (val);
200       }
201     }
202
203   return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
204 }
205
206 /* A Python function which returns a gdb parameter's value as a Python
207    value.  */
208
209 static PyObject *
210 get_parameter (PyObject *self, PyObject *args)
211 {
212   struct cmd_list_element *alias, *prefix, *cmd;
213   char *arg, *newarg;
214   volatile struct gdb_exception except;
215
216   if (! PyArg_ParseTuple (args, "s", &arg))
217     return NULL;
218
219   newarg = concat ("show ", arg, (char *) NULL);
220
221   TRY_CATCH (except, RETURN_MASK_ALL)
222     {
223       if (! lookup_cmd_composition (newarg, &alias, &prefix, &cmd))
224         {
225           xfree (newarg);
226           return PyErr_Format (PyExc_RuntimeError,
227                                "could not find variable `%s'", arg);
228         }
229     }
230   xfree (newarg);
231   GDB_PY_HANDLE_EXCEPTION (except);
232
233   if (! cmd->var)
234     return PyErr_Format (PyExc_RuntimeError, "`%s' is not a variable", arg);
235   return parameter_to_python (cmd);
236 }
237
238 /* A Python function which evaluates a string using the gdb CLI.  */
239
240 static PyObject *
241 execute_gdb_command (PyObject *self, PyObject *args)
242 {
243   struct cmd_list_element *alias, *prefix, *cmd;
244   char *arg, *newarg;
245   volatile struct gdb_exception except;
246
247   if (! PyArg_ParseTuple (args, "s", &arg))
248     return NULL;
249
250   TRY_CATCH (except, RETURN_MASK_ALL)
251     {
252       execute_command (arg, 0);
253     }
254   GDB_PY_HANDLE_EXCEPTION (except);
255
256   /* Do any commands attached to breakpoint we stopped at.  */
257   bpstat_do_actions ();
258
259   Py_RETURN_NONE;
260 }
261
262 \f
263
264 /* Printing.  */
265
266 /* A python function to write a single string using gdb's filtered
267    output stream.  */
268 static PyObject *
269 gdbpy_write (PyObject *self, PyObject *args)
270 {
271   char *arg;
272   if (! PyArg_ParseTuple (args, "s", &arg))
273     return NULL;
274   printf_filtered ("%s", arg);
275   Py_RETURN_NONE;
276 }
277
278 /* A python function to flush gdb's filtered output stream.  */
279 static PyObject *
280 gdbpy_flush (PyObject *self, PyObject *args)
281 {
282   gdb_flush (gdb_stdout);
283   Py_RETURN_NONE;
284 }
285
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.  */
289 void
290 gdbpy_print_stack (void)
291 {
292   if (gdbpy_should_print_stack)
293     PyErr_Print ();
294   else
295     PyErr_Clear ();
296 }
297
298 #else /* HAVE_PYTHON */
299
300 /* Dummy implementation of the gdb "python" command.  */
301
302 static void
303 python_command (char *arg, int from_tty)
304 {
305   while (arg && *arg && isspace (*arg))
306     ++arg;
307   if (arg && *arg)
308     error (_("Python scripting is not supported in this copy of GDB."));
309   else
310     {
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);
315     }
316 }
317
318 void
319 eval_python_from_control_command (struct command_line *cmd)
320 {
321   error (_("Python scripting is not supported in this copy of GDB."));
322 }
323
324 #endif /* HAVE_PYTHON */
325
326 \f
327
328 /* Lists for 'maint set python' commands.  */
329
330 static struct cmd_list_element *set_python_list;
331 static struct cmd_list_element *show_python_list;
332
333 /* Function for use by 'maint set python' prefix command.  */
334
335 static void
336 set_python (char *args, int from_tty)
337 {
338   help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
339 }
340
341 /* Function for use by 'maint show python' prefix command.  */
342
343 static void
344 show_python (char *args, int from_tty)
345 {
346   cmd_show_list (show_python_list, from_tty, "");
347 }
348
349 /* Initialize the Python code.  */
350
351 void
352 _initialize_python (void)
353 {
354   add_com ("python", class_obscure, python_command,
355 #ifdef HAVE_PYTHON
356            _("\
357 Evaluate a Python command.\n\
358 \n\
359 The command can be given as an argument, for instance:\n\
360 \n\
361     python print 23\n\
362 \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 */
367            _("\
368 Evaluate a Python command.\n\
369 \n\
370 Python scripting is not supported in this copy of GDB.\n\
371 This command is only a placeholder.")
372 #endif /* HAVE_PYTHON */
373            );
374
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);
383
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."),
389                            NULL, NULL,
390                            &set_python_list,
391                            &show_python_list);
392
393 #ifdef HAVE_PYTHON
394   Py_Initialize ();
395
396   gdb_module = Py_InitModule ("gdb", GdbMethods);
397
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);
402
403   gdbpy_initialize_values ();
404
405   PyRun_SimpleString ("import gdb");
406
407   /* Create a couple objects which are used for Python's stdout and
408      stderr.  */
409   PyRun_SimpleString ("\
410 import sys\n\
411 class GdbOutputFile:\n\
412   def close(self):\n\
413     # Do nothing.\n\
414     return None\n\
415 \n\
416   def isatty(self):\n\
417     return False\n\
418 \n\
419   def write(self, s):\n\
420     gdb.write(s)\n\
421 \n\
422   def writelines(self, iterable):\n\
423     for line in iterable:\n\
424       self.write(line)\n\
425 \n\
426   def flush(self):\n\
427     gdb.flush()\n\
428 \n\
429 sys.stderr = GdbOutputFile()\n\
430 sys.stdout = GdbOutputFile()\n\
431 ");
432 #endif /* HAVE_PYTHON */
433 }