PR 6878
[deliverable/binutils-gdb.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 { "execute", execute_gdb_command, METH_VARARGS,
56 "Execute a gdb command" },
57 { "get_parameter", get_parameter, METH_VARARGS,
58 "Return a gdb parameter's value" },
59
60 { "write", gdbpy_write, METH_VARARGS,
61 "Write a string using gdb's filtered stream." },
62 { "flush", gdbpy_flush, METH_NOARGS,
63 "Flush gdb's filtered stdout stream." },
64
65 {NULL, NULL, 0, NULL}
66 };
67
68 /* Given a command_line, return a command string suitable for passing
69 to Python. Lines in the string are separated by newlines. The
70 return value is allocated using xmalloc and the caller is
71 responsible for freeing it. */
72
73 static char *
74 compute_python_string (struct command_line *l)
75 {
76 struct command_line *iter;
77 char *script = NULL;
78 int size = 0;
79 int here;
80
81 for (iter = l; iter; iter = iter->next)
82 size += strlen (iter->line) + 1;
83
84 script = xmalloc (size + 1);
85 here = 0;
86 for (iter = l; iter; iter = iter->next)
87 {
88 int len = strlen (iter->line);
89 strcpy (&script[here], iter->line);
90 here += len;
91 script[here++] = '\n';
92 }
93 script[here] = '\0';
94 return script;
95 }
96
97 /* Take a command line structure representing a 'python' command, and
98 evaluate its body using the Python interpreter. */
99
100 void
101 eval_python_from_control_command (struct command_line *cmd)
102 {
103 char *script;
104
105 if (cmd->body_count != 1)
106 error (_("Invalid \"python\" block structure."));
107
108 script = compute_python_string (cmd->body_list[0]);
109 PyRun_SimpleString (script);
110 xfree (script);
111 if (PyErr_Occurred ())
112 {
113 gdbpy_print_stack ();
114 error (_("error while executing Python code"));
115 }
116 }
117
118 /* Implementation of the gdb "python" command. */
119
120 static void
121 python_command (char *arg, int from_tty)
122 {
123 while (arg && *arg && isspace (*arg))
124 ++arg;
125 if (arg && *arg)
126 {
127 PyRun_SimpleString (arg);
128 if (PyErr_Occurred ())
129 {
130 gdbpy_print_stack ();
131 error (_("error while executing Python code"));
132 }
133 }
134 else
135 {
136 struct command_line *l = get_command_line (python_control, "");
137 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
138 execute_control_command_untraced (l);
139 do_cleanups (cleanups);
140 }
141 }
142
143 \f
144
145 /* Transform a gdb parameters's value into a Python value. May return
146 NULL (and set a Python exception) on error. Helper function for
147 get_parameter. */
148
149 static PyObject *
150 parameter_to_python (struct cmd_list_element *cmd)
151 {
152 switch (cmd->var_type)
153 {
154 case var_string:
155 case var_string_noescape:
156 case var_optional_filename:
157 case var_filename:
158 case var_enum:
159 {
160 char *str = * (char **) cmd->var;
161 if (! str)
162 str = "";
163 return PyString_Decode (str, strlen (str), host_charset (), NULL);
164 }
165
166 case var_boolean:
167 {
168 if (* (int *) cmd->var)
169 Py_RETURN_TRUE;
170 else
171 Py_RETURN_FALSE;
172 }
173
174 case var_auto_boolean:
175 {
176 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
177 if (ab == AUTO_BOOLEAN_TRUE)
178 Py_RETURN_TRUE;
179 else if (ab == AUTO_BOOLEAN_FALSE)
180 Py_RETURN_FALSE;
181 else
182 Py_RETURN_NONE;
183 }
184
185 case var_integer:
186 if ((* (int *) cmd->var) == INT_MAX)
187 Py_RETURN_NONE;
188 /* Fall through. */
189 case var_zinteger:
190 return PyLong_FromLong (* (int *) cmd->var);
191
192 case var_uinteger:
193 {
194 unsigned int val = * (unsigned int *) cmd->var;
195 if (val == UINT_MAX)
196 Py_RETURN_NONE;
197 return PyLong_FromUnsignedLong (val);
198 }
199 }
200
201 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
202 }
203
204 /* A Python function which returns a gdb parameter's value as a Python
205 value. */
206
207 static PyObject *
208 get_parameter (PyObject *self, PyObject *args)
209 {
210 struct cmd_list_element *alias, *prefix, *cmd;
211 char *arg, *newarg;
212 volatile struct gdb_exception except;
213
214 if (! PyArg_ParseTuple (args, "s", &arg))
215 return NULL;
216
217 newarg = concat ("show ", arg, (char *) NULL);
218
219 TRY_CATCH (except, RETURN_MASK_ALL)
220 {
221 if (! lookup_cmd_composition (newarg, &alias, &prefix, &cmd))
222 {
223 xfree (newarg);
224 return PyErr_Format (PyExc_RuntimeError,
225 "could not find variable `%s'", arg);
226 }
227 }
228 xfree (newarg);
229 GDB_PY_HANDLE_EXCEPTION (except);
230
231 if (! cmd->var)
232 return PyErr_Format (PyExc_RuntimeError, "`%s' is not a variable", arg);
233 return parameter_to_python (cmd);
234 }
235
236 /* A Python function which evaluates a string using the gdb CLI. */
237
238 static PyObject *
239 execute_gdb_command (PyObject *self, PyObject *args)
240 {
241 struct cmd_list_element *alias, *prefix, *cmd;
242 char *arg, *newarg;
243 volatile struct gdb_exception except;
244
245 if (! PyArg_ParseTuple (args, "s", &arg))
246 return NULL;
247
248 TRY_CATCH (except, RETURN_MASK_ALL)
249 {
250 execute_command (arg, 0);
251 }
252 GDB_PY_HANDLE_EXCEPTION (except);
253
254 /* Do any commands attached to breakpoint we stopped at. */
255 bpstat_do_actions ();
256
257 Py_RETURN_NONE;
258 }
259
260 \f
261
262 /* Printing. */
263
264 /* A python function to write a single string using gdb's filtered
265 output stream. */
266 static PyObject *
267 gdbpy_write (PyObject *self, PyObject *args)
268 {
269 char *arg;
270 if (! PyArg_ParseTuple (args, "s", &arg))
271 return NULL;
272 printf_filtered ("%s", arg);
273 Py_RETURN_NONE;
274 }
275
276 /* A python function to flush gdb's filtered output stream. */
277 static PyObject *
278 gdbpy_flush (PyObject *self, PyObject *args)
279 {
280 gdb_flush (gdb_stdout);
281 Py_RETURN_NONE;
282 }
283
284 /* Print a python exception trace, or print nothing and clear the
285 python exception, depending on gdbpy_should_print_stack. Only call
286 this if a python exception is set. */
287 void
288 gdbpy_print_stack (void)
289 {
290 if (gdbpy_should_print_stack)
291 PyErr_Print ();
292 else
293 PyErr_Clear ();
294 }
295
296 #else /* HAVE_PYTHON */
297
298 /* Dummy implementation of the gdb "python" command. */
299
300 static void
301 python_command (char *arg, int from_tty)
302 {
303 while (arg && *arg && isspace (*arg))
304 ++arg;
305 if (arg && *arg)
306 error (_("Python scripting is not supported in this copy of GDB."));
307 else
308 {
309 struct command_line *l = get_command_line (python_control, "");
310 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
311 execute_control_command_untraced (l);
312 do_cleanups (cleanups);
313 }
314 }
315
316 void
317 eval_python_from_control_command (struct command_line *cmd)
318 {
319 error (_("Python scripting is not supported in this copy of GDB."));
320 }
321
322 #endif /* HAVE_PYTHON */
323
324 \f
325
326 /* Lists for 'maint set python' commands. */
327
328 static struct cmd_list_element *set_python_list;
329 static struct cmd_list_element *show_python_list;
330
331 /* Function for use by 'maint set python' prefix command. */
332
333 static void
334 set_python (char *args, int from_tty)
335 {
336 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
337 }
338
339 /* Function for use by 'maint show python' prefix command. */
340
341 static void
342 show_python (char *args, int from_tty)
343 {
344 cmd_show_list (show_python_list, from_tty, "");
345 }
346
347 /* Initialize the Python code. */
348
349 void
350 _initialize_python (void)
351 {
352 add_com ("python", class_obscure, python_command,
353 #ifdef HAVE_PYTHON
354 _("\
355 Evaluate a Python command.\n\
356 \n\
357 The command can be given as an argument, for instance:\n\
358 \n\
359 python print 23\n\
360 \n\
361 If no argument is given, the following lines are read and used\n\
362 as the Python commands. Type a line containing \"end\" to indicate\n\
363 the end of the command.")
364 #else /* HAVE_PYTHON */
365 _("\
366 Evaluate a Python command.\n\
367 \n\
368 Python scripting is not supported in this copy of GDB.\n\
369 This command is only a placeholder.")
370 #endif /* HAVE_PYTHON */
371 );
372
373 add_prefix_cmd ("python", no_class, show_python,
374 _("Prefix command for python maintenance settings."),
375 &show_python_list, "maintenance show python ", 0,
376 &maintenance_show_cmdlist);
377 add_prefix_cmd ("python", no_class, set_python,
378 _("Prefix command for python maintenance settings."),
379 &set_python_list, "maintenance set python ", 0,
380 &maintenance_set_cmdlist);
381
382 add_setshow_boolean_cmd ("print-stack", class_maintenance,
383 &gdbpy_should_print_stack, _("\
384 Enable or disable printing of Python stack dump on error."), _("\
385 Show whether Python stack will be printed on error."), _("\
386 Enables or disables printing of Python stack traces."),
387 NULL, NULL,
388 &set_python_list,
389 &show_python_list);
390
391 #ifdef HAVE_PYTHON
392 Py_Initialize ();
393
394 gdb_module = Py_InitModule ("gdb", GdbMethods);
395
396 /* The casts to (char*) are for python 2.4. */
397 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
398 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
399 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
400
401 PyRun_SimpleString ("import gdb");
402
403 /* Create a couple objects which are used for Python's stdout and
404 stderr. */
405 PyRun_SimpleString ("\
406 import sys\n\
407 class GdbOutputFile:\n\
408 def close(self):\n\
409 # Do nothing.\n\
410 return None\n\
411 \n\
412 def isatty(self):\n\
413 return False\n\
414 \n\
415 def write(self, s):\n\
416 gdb.write(s)\n\
417 \n\
418 def writelines(self, iterable):\n\
419 for line in iterable:\n\
420 self.write(line)\n\
421 \n\
422 def flush(self):\n\
423 gdb.flush()\n\
424 \n\
425 sys.stderr = GdbOutputFile()\n\
426 sys.stdout = GdbOutputFile()\n\
427 ");
428 #endif /* HAVE_PYTHON */
429 }
This page took 0.049361 seconds and 4 git commands to generate.