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"
30 /* True if we should print the stack when catching a Python error,
32 static int gdbpy_should_print_stack = 1;
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;
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
45 #include "exceptions.h"
46 #include "python-internal.h"
49 #include "gdbthread.h"
51 static PyMethodDef GdbMethods[];
55 /* Some string constants we may wish to use. */
56 PyObject *gdbpy_to_string_cst;
57 PyObject *gdbpy_children_cst;
58 PyObject *gdbpy_display_hint_cst;
59 PyObject *gdbpy_doc_cst;
61 /* Given a command_line, return a command string suitable for passing
62 to Python. Lines in the string are separated by newlines. The
63 return value is allocated using xmalloc and the caller is
64 responsible for freeing it. */
67 compute_python_string (struct command_line *l)
69 struct command_line *iter;
74 for (iter = l; iter; iter = iter->next)
75 size += strlen (iter->line) + 1;
77 script = xmalloc (size + 1);
79 for (iter = l; iter; iter = iter->next)
81 int len = strlen (iter->line);
82 strcpy (&script[here], iter->line);
84 script[here++] = '\n';
90 /* Take a command line structure representing a 'python' command, and
91 evaluate its body using the Python interpreter. */
94 eval_python_from_control_command (struct command_line *cmd)
98 struct cleanup *cleanup;
99 PyGILState_STATE state;
101 if (cmd->body_count != 1)
102 error (_("Invalid \"python\" block structure."));
104 state = PyGILState_Ensure ();
105 cleanup = make_cleanup_py_restore_gil (&state);
107 script = compute_python_string (cmd->body_list[0]);
108 ret = PyRun_SimpleString (script);
112 gdbpy_print_stack ();
113 error (_("Error while executing Python code."));
116 do_cleanups (cleanup);
119 /* Implementation of the gdb "python" command. */
122 python_command (char *arg, int from_tty)
124 struct cleanup *cleanup;
125 PyGILState_STATE state;
127 state = PyGILState_Ensure ();
128 cleanup = make_cleanup_py_restore_gil (&state);
130 while (arg && *arg && isspace (*arg))
134 if (PyRun_SimpleString (arg))
136 gdbpy_print_stack ();
137 error (_("Error while executing Python code."));
142 struct command_line *l = get_command_line (python_control, "");
143 make_cleanup_free_command_lines (&l);
144 execute_control_command_untraced (l);
147 do_cleanups (cleanup);
152 /* Transform a gdb parameters's value into a Python value. May return
153 NULL (and set a Python exception) on error. Helper function for
157 parameter_to_python (struct cmd_list_element *cmd)
159 switch (cmd->var_type)
162 case var_string_noescape:
163 case var_optional_filename:
167 char *str = * (char **) cmd->var;
170 return PyString_Decode (str, strlen (str), host_charset (), NULL);
175 if (* (int *) cmd->var)
181 case var_auto_boolean:
183 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
184 if (ab == AUTO_BOOLEAN_TRUE)
186 else if (ab == AUTO_BOOLEAN_FALSE)
193 if ((* (int *) cmd->var) == INT_MAX)
197 return PyLong_FromLong (* (int *) cmd->var);
201 unsigned int val = * (unsigned int *) cmd->var;
204 return PyLong_FromUnsignedLong (val);
208 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
211 /* A Python function which returns a gdb parameter's value as a Python
215 gdbpy_parameter (PyObject *self, PyObject *args)
217 struct cmd_list_element *alias, *prefix, *cmd;
220 volatile struct gdb_exception except;
222 if (! PyArg_ParseTuple (args, "s", &arg))
225 newarg = concat ("show ", arg, (char *) NULL);
227 TRY_CATCH (except, RETURN_MASK_ALL)
229 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
232 GDB_PY_HANDLE_EXCEPTION (except);
234 return PyErr_Format (PyExc_RuntimeError,
235 "could not find parameter `%s'", arg);
238 return PyErr_Format (PyExc_RuntimeError, "`%s' is not a parameter", arg);
239 return parameter_to_python (cmd);
242 /* A Python function which evaluates a string using the gdb CLI. */
245 execute_gdb_command (PyObject *self, PyObject *args)
247 struct cmd_list_element *alias, *prefix, *cmd;
249 PyObject *from_tty_obj = NULL;
252 volatile struct gdb_exception except;
254 if (! PyArg_ParseTuple (args, "s|O!", &arg, &PyBool_Type, &from_tty_obj))
260 cmp = PyObject_IsTrue (from_tty_obj);
266 TRY_CATCH (except, RETURN_MASK_ALL)
268 execute_command (arg, from_tty);
270 GDB_PY_HANDLE_EXCEPTION (except);
272 /* Do any commands attached to breakpoint we stopped at. */
273 bpstat_do_actions ();
282 /* A python function to write a single string using gdb's filtered
285 gdbpy_write (PyObject *self, PyObject *args)
288 if (! PyArg_ParseTuple (args, "s", &arg))
290 printf_filtered ("%s", arg);
294 /* A python function to flush gdb's filtered output stream. */
296 gdbpy_flush (PyObject *self, PyObject *args)
298 gdb_flush (gdb_stdout);
302 /* Print a python exception trace, or print nothing and clear the
303 python exception, depending on gdbpy_should_print_stack. Only call
304 this if a python exception is set. */
306 gdbpy_print_stack (void)
308 if (gdbpy_should_print_stack)
316 /* The "current" objfile. This is set when gdb detects that a new
317 objfile has been loaded. It is only set for the duration of a call
318 to gdbpy_new_objfile; it is NULL at other times. */
319 static struct objfile *gdbpy_current_objfile;
321 /* The file name we attempt to read. */
322 #define GDBPY_AUTO_FILENAME "-gdb.py"
324 /* This is a new_objfile observer callback which loads python code
325 based on the path to the objfile. */
327 gdbpy_new_objfile (struct objfile *objfile)
330 char *filename, *debugfile;
333 PyGILState_STATE state;
334 struct cleanup *cleanups;
336 if (!gdbpy_auto_load || !objfile || !objfile->name)
339 state = PyGILState_Ensure ();
341 gdbpy_current_objfile = objfile;
343 realname = gdb_realpath (objfile->name);
344 len = strlen (realname);
345 filename = xmalloc (len + sizeof (GDBPY_AUTO_FILENAME));
346 memcpy (filename, realname, len);
347 strcpy (filename + len, GDBPY_AUTO_FILENAME);
349 input = fopen (filename, "r");
350 debugfile = filename;
352 cleanups = make_cleanup (xfree, filename);
353 make_cleanup (xfree, realname);
355 if (!input && debug_file_directory)
357 /* Also try the same file in the separate debug info directory. */
358 debugfile = xmalloc (strlen (filename)
359 + strlen (debug_file_directory) + 1);
360 strcpy (debugfile, debug_file_directory);
361 /* FILENAME is absolute, so we don't need a "/" here. */
362 strcat (debugfile, filename);
364 make_cleanup (xfree, debugfile);
365 input = fopen (debugfile, "r");
368 if (!input && gdb_datadir)
370 /* Also try the same file in a subdirectory of gdb's data
372 debugfile = xmalloc (strlen (gdb_datadir) + strlen (filename)
373 + strlen ("/auto-load") + 1);
374 strcpy (debugfile, gdb_datadir);
375 strcat (debugfile, "/auto-load");
376 /* FILENAME is absolute, so we don't need a "/" here. */
377 strcat (debugfile, filename);
379 make_cleanup (xfree, debugfile);
380 input = fopen (debugfile, "r");
385 /* We don't want to throw an exception here -- but the user
386 would like to know that something went wrong. */
387 if (PyRun_SimpleFile (input, debugfile))
388 gdbpy_print_stack ();
392 do_cleanups (cleanups);
393 gdbpy_current_objfile = NULL;
395 PyGILState_Release (state);
398 /* Return the current Objfile, or None if there isn't one. */
400 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
404 if (! gdbpy_current_objfile)
407 result = objfile_to_objfile_object (gdbpy_current_objfile);
413 /* Return a sequence holding all the Objfiles. */
415 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
417 struct objfile *objf;
420 list = PyList_New (0);
426 PyObject *item = objfile_to_objfile_object (objf);
427 if (!item || PyList_Append (list, item) == -1)
437 #else /* HAVE_PYTHON */
439 /* Dummy implementation of the gdb "python" command. */
442 python_command (char *arg, int from_tty)
444 while (arg && *arg && isspace (*arg))
447 error (_("Python scripting is not supported in this copy of GDB."));
450 struct command_line *l = get_command_line (python_control, "");
451 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
452 execute_control_command_untraced (l);
453 do_cleanups (cleanups);
458 eval_python_from_control_command (struct command_line *cmd)
460 error (_("Python scripting is not supported in this copy of GDB."));
463 #endif /* HAVE_PYTHON */
467 /* Lists for 'maint set python' commands. */
469 static struct cmd_list_element *set_python_list;
470 static struct cmd_list_element *show_python_list;
472 /* Function for use by 'maint set python' prefix command. */
475 set_python (char *args, int from_tty)
477 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
480 /* Function for use by 'maint show python' prefix command. */
483 show_python (char *args, int from_tty)
485 cmd_show_list (show_python_list, from_tty, "");
488 /* Initialize the Python code. */
490 /* Provide a prototype to silence -Wmissing-prototypes. */
491 extern initialize_file_ftype _initialize_python;
494 _initialize_python (void)
496 add_com ("python", class_obscure, python_command,
499 Evaluate a Python command.\n\
501 The command can be given as an argument, for instance:\n\
505 If no argument is given, the following lines are read and used\n\
506 as the Python commands. Type a line containing \"end\" to indicate\n\
507 the end of the command.")
508 #else /* HAVE_PYTHON */
510 Evaluate a Python command.\n\
512 Python scripting is not supported in this copy of GDB.\n\
513 This command is only a placeholder.")
514 #endif /* HAVE_PYTHON */
517 add_prefix_cmd ("python", no_class, show_python,
518 _("Prefix command for python maintenance settings."),
519 &show_python_list, "maintenance show python ", 0,
520 &maintenance_show_cmdlist);
521 add_prefix_cmd ("python", no_class, set_python,
522 _("Prefix command for python maintenance settings."),
523 &set_python_list, "maintenance set python ", 0,
524 &maintenance_set_cmdlist);
526 add_setshow_boolean_cmd ("print-stack", class_maintenance,
527 &gdbpy_should_print_stack, _("\
528 Enable or disable printing of Python stack dump on error."), _("\
529 Show whether Python stack will be printed on error."), _("\
530 Enables or disables printing of Python stack traces."),
535 add_setshow_boolean_cmd ("auto-load", class_maintenance,
536 &gdbpy_auto_load, _("\
537 Enable or disable auto-loading of Python code when an object is opened."), _("\
538 Show whether Python code will be auto-loaded when an object is opened."), _("\
539 Enables or disables auto-loading of Python code when an object is opened."),
546 PyEval_InitThreads ();
548 gdb_module = Py_InitModule ("gdb", GdbMethods);
550 /* The casts to (char*) are for python 2.4. */
551 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
552 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
553 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
555 gdbpy_initialize_values ();
556 gdbpy_initialize_frames ();
557 gdbpy_initialize_commands ();
558 gdbpy_initialize_functions ();
559 gdbpy_initialize_types ();
560 gdbpy_initialize_objfile ();
562 PyRun_SimpleString ("import gdb");
563 PyRun_SimpleString ("gdb.pretty_printers = []");
565 observer_attach_new_objfile (gdbpy_new_objfile);
567 gdbpy_to_string_cst = PyString_FromString ("to_string");
568 gdbpy_children_cst = PyString_FromString ("children");
569 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
570 gdbpy_doc_cst = PyString_FromString ("__doc__");
572 /* Create a couple objects which are used for Python's stdout and
574 PyRun_SimpleString ("\
576 class GdbOutputFile:\n\
584 def write(self, s):\n\
587 def writelines(self, iterable):\n\
588 for line in iterable:\n\
594 sys.stderr = GdbOutputFile()\n\
595 sys.stdout = GdbOutputFile()\n\
598 /* Release the GIL while gdb runs. */
599 PyThreadState_Swap (NULL);
600 PyEval_ReleaseLock ();
602 #endif /* HAVE_PYTHON */
609 static PyMethodDef GdbMethods[] =
611 { "history", gdbpy_history, METH_VARARGS,
612 "Get a value from history" },
613 { "execute", execute_gdb_command, METH_VARARGS,
614 "Execute a gdb command" },
615 { "parameter", gdbpy_parameter, METH_VARARGS,
616 "Return a gdb parameter's value" },
618 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
619 "Find the default visualizer for a Value." },
621 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
622 "Return the current Objfile being loaded, or None." },
623 { "objfiles", gdbpy_objfiles, METH_NOARGS,
624 "Return a sequence of all loaded objfiles." },
626 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
627 "selected_frame () -> gdb.Frame.\n\
628 Return the selected frame object." },
629 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
630 "stop_reason_string (Integer) -> String.\n\
631 Return a string explaining unwind stop reason." },
633 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
634 METH_VARARGS | METH_KEYWORDS,
635 "lookup_type (name [, block]) -> type\n\
636 Return a Type corresponding to the given name." },
638 { "write", gdbpy_write, METH_VARARGS,
639 "Write a string using gdb's filtered stream." },
640 { "flush", gdbpy_flush, METH_NOARGS,
641 "Flush gdb's filtered stdout stream." },
643 {NULL, NULL, 0, NULL}
646 #endif /* HAVE_PYTHON */