gdb
[deliverable/binutils-gdb.git] / gdb / python / python.c
1 /* General python/gdb code
2
3 Copyright (C) 2008, 2009 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 #include "objfiles.h"
26 #include "observer.h"
27
28 #include <ctype.h>
29
30 /* True if we should print the stack when catching a Python error,
31 false otherwise. */
32 static int gdbpy_should_print_stack = 1;
33
34 /* This is true if we should auto-load python code when an objfile is
35 opened, false otherwise. */
36 static int gdbpy_auto_load = 1;
37
38 #ifdef HAVE_PYTHON
39
40 #include "python.h"
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
43 #include "charset.h"
44 #include "top.h"
45 #include "exceptions.h"
46 #include "python-internal.h"
47 #include "version.h"
48 #include "target.h"
49 #include "gdbthread.h"
50
51 static PyMethodDef GdbMethods[];
52
53 PyObject *gdb_module;
54
55 PyObject *gdbpy_doc_cst;
56
57 /* Given a command_line, return a command string suitable for passing
58 to Python. Lines in the string are separated by newlines. The
59 return value is allocated using xmalloc and the caller is
60 responsible for freeing it. */
61
62 static char *
63 compute_python_string (struct command_line *l)
64 {
65 struct command_line *iter;
66 char *script = NULL;
67 int size = 0;
68 int here;
69
70 for (iter = l; iter; iter = iter->next)
71 size += strlen (iter->line) + 1;
72
73 script = xmalloc (size + 1);
74 here = 0;
75 for (iter = l; iter; iter = iter->next)
76 {
77 int len = strlen (iter->line);
78 strcpy (&script[here], iter->line);
79 here += len;
80 script[here++] = '\n';
81 }
82 script[here] = '\0';
83 return script;
84 }
85
86 /* Take a command line structure representing a 'python' command, and
87 evaluate its body using the Python interpreter. */
88
89 void
90 eval_python_from_control_command (struct command_line *cmd)
91 {
92 int ret;
93 char *script;
94 struct cleanup *cleanup;
95 PyGILState_STATE state;
96
97 if (cmd->body_count != 1)
98 error (_("Invalid \"python\" block structure."));
99
100 state = PyGILState_Ensure ();
101 cleanup = make_cleanup_py_restore_gil (&state);
102
103 script = compute_python_string (cmd->body_list[0]);
104 ret = PyRun_SimpleString (script);
105 xfree (script);
106 if (ret)
107 {
108 gdbpy_print_stack ();
109 error (_("Error while executing Python code."));
110 }
111
112 do_cleanups (cleanup);
113 }
114
115 /* Implementation of the gdb "python" command. */
116
117 static void
118 python_command (char *arg, int from_tty)
119 {
120 struct cleanup *cleanup;
121 PyGILState_STATE state;
122
123 state = PyGILState_Ensure ();
124 cleanup = make_cleanup_py_restore_gil (&state);
125
126 while (arg && *arg && isspace (*arg))
127 ++arg;
128 if (arg && *arg)
129 {
130 if (PyRun_SimpleString (arg))
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 make_cleanup_free_command_lines (&l);
140 execute_control_command_untraced (l);
141 }
142
143 do_cleanups (cleanup);
144 }
145
146 \f
147
148 /* Transform a gdb parameters's value into a Python value. May return
149 NULL (and set a Python exception) on error. Helper function for
150 get_parameter. */
151
152 static PyObject *
153 parameter_to_python (struct cmd_list_element *cmd)
154 {
155 switch (cmd->var_type)
156 {
157 case var_string:
158 case var_string_noescape:
159 case var_optional_filename:
160 case var_filename:
161 case var_enum:
162 {
163 char *str = * (char **) cmd->var;
164 if (! str)
165 str = "";
166 return PyString_Decode (str, strlen (str), host_charset (), NULL);
167 }
168
169 case var_boolean:
170 {
171 if (* (int *) cmd->var)
172 Py_RETURN_TRUE;
173 else
174 Py_RETURN_FALSE;
175 }
176
177 case var_auto_boolean:
178 {
179 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
180 if (ab == AUTO_BOOLEAN_TRUE)
181 Py_RETURN_TRUE;
182 else if (ab == AUTO_BOOLEAN_FALSE)
183 Py_RETURN_FALSE;
184 else
185 Py_RETURN_NONE;
186 }
187
188 case var_integer:
189 if ((* (int *) cmd->var) == INT_MAX)
190 Py_RETURN_NONE;
191 /* Fall through. */
192 case var_zinteger:
193 return PyLong_FromLong (* (int *) cmd->var);
194
195 case var_uinteger:
196 {
197 unsigned int val = * (unsigned int *) cmd->var;
198 if (val == UINT_MAX)
199 Py_RETURN_NONE;
200 return PyLong_FromUnsignedLong (val);
201 }
202 }
203
204 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
205 }
206
207 /* A Python function which returns a gdb parameter's value as a Python
208 value. */
209
210 static PyObject *
211 get_parameter (PyObject *self, PyObject *args)
212 {
213 struct cmd_list_element *alias, *prefix, *cmd;
214 char *arg, *newarg;
215 int found = -1;
216 volatile struct gdb_exception except;
217
218 if (! PyArg_ParseTuple (args, "s", &arg))
219 return NULL;
220
221 newarg = concat ("show ", arg, (char *) NULL);
222
223 TRY_CATCH (except, RETURN_MASK_ALL)
224 {
225 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
226 }
227 xfree (newarg);
228 GDB_PY_HANDLE_EXCEPTION (except);
229 if (!found)
230 return PyErr_Format (PyExc_RuntimeError,
231 "could not find parameter `%s'", arg);
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 PyObject *from_tty_obj = NULL;
246 int from_tty;
247 int cmp;
248 volatile struct gdb_exception except;
249
250 if (! PyArg_ParseTuple (args, "s|O!", &arg, &PyBool_Type, &from_tty_obj))
251 return NULL;
252
253 from_tty = 0;
254 if (from_tty_obj)
255 {
256 cmp = PyObject_IsTrue (from_tty_obj);
257 if (cmp < 0)
258 return NULL;
259 from_tty = cmp;
260 }
261
262 TRY_CATCH (except, RETURN_MASK_ALL)
263 {
264 execute_command (arg, from_tty);
265 }
266 GDB_PY_HANDLE_EXCEPTION (except);
267
268 /* Do any commands attached to breakpoint we stopped at. */
269 bpstat_do_actions ();
270
271 Py_RETURN_NONE;
272 }
273
274 \f
275
276 /* Printing. */
277
278 /* A python function to write a single string using gdb's filtered
279 output stream. */
280 static PyObject *
281 gdbpy_write (PyObject *self, PyObject *args)
282 {
283 char *arg;
284 if (! PyArg_ParseTuple (args, "s", &arg))
285 return NULL;
286 printf_filtered ("%s", arg);
287 Py_RETURN_NONE;
288 }
289
290 /* A python function to flush gdb's filtered output stream. */
291 static PyObject *
292 gdbpy_flush (PyObject *self, PyObject *args)
293 {
294 gdb_flush (gdb_stdout);
295 Py_RETURN_NONE;
296 }
297
298 /* Print a python exception trace, or print nothing and clear the
299 python exception, depending on gdbpy_should_print_stack. Only call
300 this if a python exception is set. */
301 void
302 gdbpy_print_stack (void)
303 {
304 if (gdbpy_should_print_stack)
305 PyErr_Print ();
306 else
307 PyErr_Clear ();
308 }
309
310 \f
311
312 /* The "current" objfile. This is set when gdb detects that a new
313 objfile has been loaded. It is only set for the duration of a call
314 to gdbpy_new_objfile; it is NULL at other times. */
315 static struct objfile *gdbpy_current_objfile;
316
317 /* The file name we attempt to read. */
318 #define GDBPY_AUTO_FILENAME "-gdb.py"
319
320 /* This is a new_objfile observer callback which loads python code
321 based on the path to the objfile. */
322 static void
323 gdbpy_new_objfile (struct objfile *objfile)
324 {
325 char *realname;
326 char *filename, *debugfile;
327 int len;
328 FILE *input;
329 PyGILState_STATE state;
330 struct cleanup *cleanups;
331
332 if (!gdbpy_auto_load || !objfile || !objfile->name)
333 return;
334
335 state = PyGILState_Ensure ();
336
337 gdbpy_current_objfile = objfile;
338
339 realname = gdb_realpath (objfile->name);
340 len = strlen (realname);
341 filename = xmalloc (len + sizeof (GDBPY_AUTO_FILENAME));
342 memcpy (filename, realname, len);
343 strcpy (filename + len, GDBPY_AUTO_FILENAME);
344
345 input = fopen (filename, "r");
346 debugfile = filename;
347
348 cleanups = make_cleanup (xfree, filename);
349 make_cleanup (xfree, realname);
350
351 if (!input && debug_file_directory)
352 {
353 /* Also try the same file in the separate debug info directory. */
354 debugfile = xmalloc (strlen (filename)
355 + strlen (debug_file_directory) + 1);
356 strcpy (debugfile, debug_file_directory);
357 /* FILENAME is absolute, so we don't need a "/" here. */
358 strcat (debugfile, filename);
359
360 make_cleanup (xfree, debugfile);
361 input = fopen (debugfile, "r");
362 }
363
364 if (!input && gdb_datadir)
365 {
366 /* Also try the same file in a subdirectory of gdb's data
367 directory. */
368 debugfile = xmalloc (strlen (gdb_datadir) + strlen (filename)
369 + strlen ("/auto-load") + 1);
370 strcpy (debugfile, gdb_datadir);
371 strcat (debugfile, "/auto-load");
372 /* FILENAME is absolute, so we don't need a "/" here. */
373 strcat (debugfile, filename);
374
375 make_cleanup (xfree, debugfile);
376 input = fopen (debugfile, "r");
377 }
378
379 if (input)
380 {
381 /* We don't want to throw an exception here -- but the user
382 would like to know that something went wrong. */
383 if (PyRun_SimpleFile (input, debugfile))
384 gdbpy_print_stack ();
385 fclose (input);
386 }
387
388 do_cleanups (cleanups);
389 gdbpy_current_objfile = NULL;
390
391 PyGILState_Release (state);
392 }
393
394 /* Return the current Objfile, or None if there isn't one. */
395 static PyObject *
396 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
397 {
398 PyObject *result;
399
400 if (! gdbpy_current_objfile)
401 Py_RETURN_NONE;
402
403 result = objfile_to_objfile_object (gdbpy_current_objfile);
404 if (result)
405 Py_INCREF (result);
406 return result;
407 }
408
409 /* Return a sequence holding all the Objfiles. */
410 static PyObject *
411 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
412 {
413 struct objfile *objf;
414 PyObject *list;
415
416 list = PyList_New (0);
417 if (!list)
418 return NULL;
419
420 ALL_OBJFILES (objf)
421 {
422 PyObject *item = objfile_to_objfile_object (objf);
423 if (!item || PyList_Append (list, item) == -1)
424 {
425 Py_DECREF (list);
426 return NULL;
427 }
428 }
429
430 return list;
431 }
432
433 #else /* HAVE_PYTHON */
434
435 /* Dummy implementation of the gdb "python" command. */
436
437 static void
438 python_command (char *arg, int from_tty)
439 {
440 while (arg && *arg && isspace (*arg))
441 ++arg;
442 if (arg && *arg)
443 error (_("Python scripting is not supported in this copy of GDB."));
444 else
445 {
446 struct command_line *l = get_command_line (python_control, "");
447 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
448 execute_control_command_untraced (l);
449 do_cleanups (cleanups);
450 }
451 }
452
453 void
454 eval_python_from_control_command (struct command_line *cmd)
455 {
456 error (_("Python scripting is not supported in this copy of GDB."));
457 }
458
459 #endif /* HAVE_PYTHON */
460
461 \f
462
463 /* Lists for 'maint set python' commands. */
464
465 static struct cmd_list_element *set_python_list;
466 static struct cmd_list_element *show_python_list;
467
468 /* Function for use by 'maint set python' prefix command. */
469
470 static void
471 set_python (char *args, int from_tty)
472 {
473 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
474 }
475
476 /* Function for use by 'maint show python' prefix command. */
477
478 static void
479 show_python (char *args, int from_tty)
480 {
481 cmd_show_list (show_python_list, from_tty, "");
482 }
483
484 /* Initialize the Python code. */
485
486 /* Provide a prototype to silence -Wmissing-prototypes. */
487 extern initialize_file_ftype _initialize_python;
488
489 void
490 _initialize_python (void)
491 {
492 add_com ("python", class_obscure, python_command,
493 #ifdef HAVE_PYTHON
494 _("\
495 Evaluate a Python command.\n\
496 \n\
497 The command can be given as an argument, for instance:\n\
498 \n\
499 python print 23\n\
500 \n\
501 If no argument is given, the following lines are read and used\n\
502 as the Python commands. Type a line containing \"end\" to indicate\n\
503 the end of the command.")
504 #else /* HAVE_PYTHON */
505 _("\
506 Evaluate a Python command.\n\
507 \n\
508 Python scripting is not supported in this copy of GDB.\n\
509 This command is only a placeholder.")
510 #endif /* HAVE_PYTHON */
511 );
512
513 add_prefix_cmd ("python", no_class, show_python,
514 _("Prefix command for python maintenance settings."),
515 &show_python_list, "maintenance show python ", 0,
516 &maintenance_show_cmdlist);
517 add_prefix_cmd ("python", no_class, set_python,
518 _("Prefix command for python maintenance settings."),
519 &set_python_list, "maintenance set python ", 0,
520 &maintenance_set_cmdlist);
521
522 add_setshow_boolean_cmd ("print-stack", class_maintenance,
523 &gdbpy_should_print_stack, _("\
524 Enable or disable printing of Python stack dump on error."), _("\
525 Show whether Python stack will be printed on error."), _("\
526 Enables or disables printing of Python stack traces."),
527 NULL, NULL,
528 &set_python_list,
529 &show_python_list);
530
531 add_setshow_boolean_cmd ("auto-load", class_maintenance,
532 &gdbpy_auto_load, _("\
533 Enable or disable auto-loading of Python code when an object is opened."), _("\
534 Show whether Python code will be auto-loaded when an object is opened."), _("\
535 Enables or disables auto-loading of Python code when an object is opened."),
536 NULL, NULL,
537 &set_python_list,
538 &show_python_list);
539
540 #ifdef HAVE_PYTHON
541 Py_Initialize ();
542 PyEval_InitThreads ();
543
544 gdb_module = Py_InitModule ("gdb", GdbMethods);
545
546 /* The casts to (char*) are for python 2.4. */
547 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
548 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
549 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
550
551 gdbpy_initialize_values ();
552 gdbpy_initialize_frames ();
553 gdbpy_initialize_commands ();
554 gdbpy_initialize_functions ();
555 gdbpy_initialize_types ();
556 gdbpy_initialize_objfile ();
557
558 PyRun_SimpleString ("import gdb");
559
560 observer_attach_new_objfile (gdbpy_new_objfile);
561
562 gdbpy_doc_cst = PyString_FromString ("__doc__");
563
564 /* Create a couple objects which are used for Python's stdout and
565 stderr. */
566 PyRun_SimpleString ("\
567 import sys\n\
568 class GdbOutputFile:\n\
569 def close(self):\n\
570 # Do nothing.\n\
571 return None\n\
572 \n\
573 def isatty(self):\n\
574 return False\n\
575 \n\
576 def write(self, s):\n\
577 gdb.write(s)\n\
578 \n\
579 def writelines(self, iterable):\n\
580 for line in iterable:\n\
581 self.write(line)\n\
582 \n\
583 def flush(self):\n\
584 gdb.flush()\n\
585 \n\
586 sys.stderr = GdbOutputFile()\n\
587 sys.stdout = GdbOutputFile()\n\
588 ");
589
590 /* Release the GIL while gdb runs. */
591 PyThreadState_Swap (NULL);
592 PyEval_ReleaseLock ();
593
594 #endif /* HAVE_PYTHON */
595 }
596
597 \f
598
599 #if HAVE_PYTHON
600
601 static PyMethodDef GdbMethods[] =
602 {
603 { "history", gdbpy_history, METH_VARARGS,
604 "Get a value from history" },
605 { "execute", execute_gdb_command, METH_VARARGS,
606 "Execute a gdb command" },
607 { "get_parameter", get_parameter, METH_VARARGS,
608 "Return a gdb parameter's value" },
609
610 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
611 "Return the current Objfile being loaded, or None." },
612 { "objfiles", gdbpy_objfiles, METH_NOARGS,
613 "Return a sequence of all loaded objfiles." },
614
615 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
616 "selected_frame () -> gdb.Frame.\n\
617 Return the selected frame object." },
618 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
619 "stop_reason_string (Integer) -> String.\n\
620 Return a string explaining unwind stop reason." },
621
622 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
623 METH_VARARGS | METH_KEYWORDS,
624 "lookup_type (name [, block]) -> type\n\
625 Return a Type corresponding to the given name." },
626
627 { "write", gdbpy_write, METH_VARARGS,
628 "Write a string using gdb's filtered stream." },
629 { "flush", gdbpy_flush, METH_NOARGS,
630 "Flush gdb's filtered stdout stream." },
631
632 {NULL, NULL, 0, NULL}
633 };
634
635 #endif /* HAVE_PYTHON */
This page took 0.042044 seconds and 4 git commands to generate.