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 PyObject
*gdbpy_doc_cst
;
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. */
63 compute_python_string (struct command_line
*l
)
65 struct command_line
*iter
;
70 for (iter
= l
; iter
; iter
= iter
->next
)
71 size
+= strlen (iter
->line
) + 1;
73 script
= xmalloc (size
+ 1);
75 for (iter
= l
; iter
; iter
= iter
->next
)
77 int len
= strlen (iter
->line
);
78 strcpy (&script
[here
], iter
->line
);
80 script
[here
++] = '\n';
86 /* Take a command line structure representing a 'python' command, and
87 evaluate its body using the Python interpreter. */
90 eval_python_from_control_command (struct command_line
*cmd
)
94 struct cleanup
*cleanup
;
95 PyGILState_STATE state
;
97 if (cmd
->body_count
!= 1)
98 error (_("Invalid \"python\" block structure."));
100 state
= PyGILState_Ensure ();
101 cleanup
= make_cleanup_py_restore_gil (&state
);
103 script
= compute_python_string (cmd
->body_list
[0]);
104 ret
= PyRun_SimpleString (script
);
108 gdbpy_print_stack ();
109 error (_("Error while executing Python code."));
112 do_cleanups (cleanup
);
115 /* Implementation of the gdb "python" command. */
118 python_command (char *arg
, int from_tty
)
120 struct cleanup
*cleanup
;
121 PyGILState_STATE state
;
123 state
= PyGILState_Ensure ();
124 cleanup
= make_cleanup_py_restore_gil (&state
);
126 while (arg
&& *arg
&& isspace (*arg
))
130 if (PyRun_SimpleString (arg
))
132 gdbpy_print_stack ();
133 error (_("Error while executing Python code."));
138 struct command_line
*l
= get_command_line (python_control
, "");
139 make_cleanup_free_command_lines (&l
);
140 execute_control_command_untraced (l
);
143 do_cleanups (cleanup
);
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
153 parameter_to_python (struct cmd_list_element
*cmd
)
155 switch (cmd
->var_type
)
158 case var_string_noescape
:
159 case var_optional_filename
:
163 char *str
= * (char **) cmd
->var
;
166 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
171 if (* (int *) cmd
->var
)
177 case var_auto_boolean
:
179 enum auto_boolean ab
= * (enum auto_boolean
*) cmd
->var
;
180 if (ab
== AUTO_BOOLEAN_TRUE
)
182 else if (ab
== AUTO_BOOLEAN_FALSE
)
189 if ((* (int *) cmd
->var
) == INT_MAX
)
193 return PyLong_FromLong (* (int *) cmd
->var
);
197 unsigned int val
= * (unsigned int *) cmd
->var
;
200 return PyLong_FromUnsignedLong (val
);
204 return PyErr_Format (PyExc_RuntimeError
, "programmer error: unhandled type");
207 /* A Python function which returns a gdb parameter's value as a Python
211 get_parameter (PyObject
*self
, PyObject
*args
)
213 struct cmd_list_element
*alias
, *prefix
, *cmd
;
216 volatile struct gdb_exception except
;
218 if (! PyArg_ParseTuple (args
, "s", &arg
))
221 newarg
= concat ("show ", arg
, (char *) NULL
);
223 TRY_CATCH (except
, RETURN_MASK_ALL
)
225 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
228 GDB_PY_HANDLE_EXCEPTION (except
);
230 return PyErr_Format (PyExc_RuntimeError
,
231 "could not find parameter `%s'", arg
);
234 return PyErr_Format (PyExc_RuntimeError
, "`%s' is not a variable", arg
);
235 return parameter_to_python (cmd
);
238 /* A Python function which evaluates a string using the gdb CLI. */
241 execute_gdb_command (PyObject
*self
, PyObject
*args
)
243 struct cmd_list_element
*alias
, *prefix
, *cmd
;
245 PyObject
*from_tty_obj
= NULL
;
248 volatile struct gdb_exception except
;
250 if (! PyArg_ParseTuple (args
, "s|O!", &arg
, &PyBool_Type
, &from_tty_obj
))
256 cmp
= PyObject_IsTrue (from_tty_obj
);
262 TRY_CATCH (except
, RETURN_MASK_ALL
)
264 execute_command (arg
, from_tty
);
266 GDB_PY_HANDLE_EXCEPTION (except
);
268 /* Do any commands attached to breakpoint we stopped at. */
269 bpstat_do_actions ();
278 /* A python function to write a single string using gdb's filtered
281 gdbpy_write (PyObject
*self
, PyObject
*args
)
284 if (! PyArg_ParseTuple (args
, "s", &arg
))
286 printf_filtered ("%s", arg
);
290 /* A python function to flush gdb's filtered output stream. */
292 gdbpy_flush (PyObject
*self
, PyObject
*args
)
294 gdb_flush (gdb_stdout
);
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. */
302 gdbpy_print_stack (void)
304 if (gdbpy_should_print_stack
)
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
;
317 /* The file name we attempt to read. */
318 #define GDBPY_AUTO_FILENAME "-gdb.py"
320 /* This is a new_objfile observer callback which loads python code
321 based on the path to the objfile. */
323 gdbpy_new_objfile (struct objfile
*objfile
)
326 char *filename
, *debugfile
;
329 PyGILState_STATE state
;
330 struct cleanup
*cleanups
;
332 if (!gdbpy_auto_load
|| !objfile
|| !objfile
->name
)
335 state
= PyGILState_Ensure ();
337 gdbpy_current_objfile
= objfile
;
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
);
345 input
= fopen (filename
, "r");
346 debugfile
= filename
;
348 cleanups
= make_cleanup (xfree
, filename
);
349 make_cleanup (xfree
, realname
);
351 if (!input
&& debug_file_directory
)
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
);
360 make_cleanup (xfree
, debugfile
);
361 input
= fopen (debugfile
, "r");
364 if (!input
&& gdb_datadir
)
366 /* Also try the same file in a subdirectory of gdb's data
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
);
375 make_cleanup (xfree
, debugfile
);
376 input
= fopen (debugfile
, "r");
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 ();
388 do_cleanups (cleanups
);
389 gdbpy_current_objfile
= NULL
;
391 PyGILState_Release (state
);
394 /* Return the current Objfile, or None if there isn't one. */
396 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
400 if (! gdbpy_current_objfile
)
403 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
409 /* Return a sequence holding all the Objfiles. */
411 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
413 struct objfile
*objf
;
416 list
= PyList_New (0);
422 PyObject
*item
= objfile_to_objfile_object (objf
);
423 if (!item
|| PyList_Append (list
, item
) == -1)
433 #else /* HAVE_PYTHON */
435 /* Dummy implementation of the gdb "python" command. */
438 python_command (char *arg
, int from_tty
)
440 while (arg
&& *arg
&& isspace (*arg
))
443 error (_("Python scripting is not supported in this copy of GDB."));
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
);
454 eval_python_from_control_command (struct command_line
*cmd
)
456 error (_("Python scripting is not supported in this copy of GDB."));
459 #endif /* HAVE_PYTHON */
463 /* Lists for 'maint set python' commands. */
465 static struct cmd_list_element
*set_python_list
;
466 static struct cmd_list_element
*show_python_list
;
468 /* Function for use by 'maint set python' prefix command. */
471 set_python (char *args
, int from_tty
)
473 help_list (set_python_list
, "maintenance set python ", -1, gdb_stdout
);
476 /* Function for use by 'maint show python' prefix command. */
479 show_python (char *args
, int from_tty
)
481 cmd_show_list (show_python_list
, from_tty
, "");
484 /* Initialize the Python code. */
486 /* Provide a prototype to silence -Wmissing-prototypes. */
487 extern initialize_file_ftype _initialize_python
;
490 _initialize_python (void)
492 add_com ("python", class_obscure
, python_command
,
495 Evaluate a Python command.\n\
497 The command can be given as an argument, for instance:\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 */
506 Evaluate a Python command.\n\
508 Python scripting is not supported in this copy of GDB.\n\
509 This command is only a placeholder.")
510 #endif /* HAVE_PYTHON */
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
);
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."),
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."),
542 PyEval_InitThreads ();
544 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
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
);
551 gdbpy_initialize_values ();
552 gdbpy_initialize_frames ();
553 gdbpy_initialize_commands ();
554 gdbpy_initialize_functions ();
555 gdbpy_initialize_types ();
556 gdbpy_initialize_objfile ();
558 PyRun_SimpleString ("import gdb");
560 observer_attach_new_objfile (gdbpy_new_objfile
);
562 gdbpy_doc_cst
= PyString_FromString ("__doc__");
564 /* Create a couple objects which are used for Python's stdout and
566 PyRun_SimpleString ("\
568 class GdbOutputFile:\n\
576 def write(self, s):\n\
579 def writelines(self, iterable):\n\
580 for line in iterable:\n\
586 sys.stderr = GdbOutputFile()\n\
587 sys.stdout = GdbOutputFile()\n\
590 /* Release the GIL while gdb runs. */
591 PyThreadState_Swap (NULL
);
592 PyEval_ReleaseLock ();
594 #endif /* HAVE_PYTHON */
601 static PyMethodDef GdbMethods
[] =
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" },
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." },
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." },
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." },
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." },
632 {NULL
, NULL
, 0, NULL
}
635 #endif /* HAVE_PYTHON */