1 /* General python/gdb code
3 Copyright (C) 2008, 2009, 2010 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/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
30 #include "exceptions.h"
34 /* True if we should print the stack when catching a Python error,
36 static int gdbpy_should_print_stack
= 1;
38 /* This is true if we should auto-load python code when an objfile is
39 opened, false otherwise. */
40 static int gdbpy_auto_load
= 1;
45 #include "libiberty.h"
46 #include "cli/cli-decode.h"
49 #include "python-internal.h"
52 #include "gdbthread.h"
54 static PyMethodDef GdbMethods
[];
58 /* Some string constants we may wish to use. */
59 PyObject
*gdbpy_to_string_cst
;
60 PyObject
*gdbpy_children_cst
;
61 PyObject
*gdbpy_display_hint_cst
;
62 PyObject
*gdbpy_doc_cst
;
65 /* Architecture and language to be used in callbacks from
66 the Python interpreter. */
67 struct gdbarch
*python_gdbarch
;
68 const struct language_defn
*python_language
;
70 /* Restore global language and architecture and Python GIL state
71 when leaving the Python interpreter. */
75 PyGILState_STATE state
;
76 struct gdbarch
*gdbarch
;
77 const struct language_defn
*language
;
81 restore_python_env (void *p
)
83 struct python_env
*env
= (struct python_env
*)p
;
84 PyGILState_Release (env
->state
);
85 python_gdbarch
= env
->gdbarch
;
86 python_language
= env
->language
;
90 /* Called before entering the Python interpreter to install the
91 current language and architecture to be used for Python values. */
94 ensure_python_env (struct gdbarch
*gdbarch
,
95 const struct language_defn
*language
)
97 struct python_env
*env
= xmalloc (sizeof *env
);
99 env
->state
= PyGILState_Ensure ();
100 env
->gdbarch
= python_gdbarch
;
101 env
->language
= python_language
;
103 python_gdbarch
= gdbarch
;
104 python_language
= language
;
106 return make_cleanup (restore_python_env
, env
);
110 /* Given a command_line, return a command string suitable for passing
111 to Python. Lines in the string are separated by newlines. The
112 return value is allocated using xmalloc and the caller is
113 responsible for freeing it. */
116 compute_python_string (struct command_line
*l
)
118 struct command_line
*iter
;
123 for (iter
= l
; iter
; iter
= iter
->next
)
124 size
+= strlen (iter
->line
) + 1;
126 script
= xmalloc (size
+ 1);
128 for (iter
= l
; iter
; iter
= iter
->next
)
130 int len
= strlen (iter
->line
);
131 strcpy (&script
[here
], iter
->line
);
133 script
[here
++] = '\n';
139 /* Take a command line structure representing a 'python' command, and
140 evaluate its body using the Python interpreter. */
143 eval_python_from_control_command (struct command_line
*cmd
)
147 struct cleanup
*cleanup
;
149 if (cmd
->body_count
!= 1)
150 error (_("Invalid \"python\" block structure."));
152 cleanup
= ensure_python_env (get_current_arch (), current_language
);
154 script
= compute_python_string (cmd
->body_list
[0]);
155 ret
= PyRun_SimpleString (script
);
159 gdbpy_print_stack ();
160 error (_("Error while executing Python code."));
163 do_cleanups (cleanup
);
166 /* Implementation of the gdb "python" command. */
169 python_command (char *arg
, int from_tty
)
171 struct cleanup
*cleanup
;
172 cleanup
= ensure_python_env (get_current_arch (), current_language
);
174 while (arg
&& *arg
&& isspace (*arg
))
178 if (PyRun_SimpleString (arg
))
180 gdbpy_print_stack ();
181 error (_("Error while executing Python code."));
186 struct command_line
*l
= get_command_line (python_control
, "");
187 make_cleanup_free_command_lines (&l
);
188 execute_control_command_untraced (l
);
191 do_cleanups (cleanup
);
196 /* Transform a gdb parameters's value into a Python value. May return
197 NULL (and set a Python exception) on error. Helper function for
201 parameter_to_python (struct cmd_list_element
*cmd
)
203 switch (cmd
->var_type
)
206 case var_string_noescape
:
207 case var_optional_filename
:
211 char *str
= * (char **) cmd
->var
;
214 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
219 if (* (int *) cmd
->var
)
225 case var_auto_boolean
:
227 enum auto_boolean ab
= * (enum auto_boolean
*) cmd
->var
;
228 if (ab
== AUTO_BOOLEAN_TRUE
)
230 else if (ab
== AUTO_BOOLEAN_FALSE
)
237 if ((* (int *) cmd
->var
) == INT_MAX
)
241 return PyLong_FromLong (* (int *) cmd
->var
);
245 unsigned int val
= * (unsigned int *) cmd
->var
;
248 return PyLong_FromUnsignedLong (val
);
252 return PyErr_Format (PyExc_RuntimeError
, "programmer error: unhandled type");
255 /* A Python function which returns a gdb parameter's value as a Python
259 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
261 struct cmd_list_element
*alias
, *prefix
, *cmd
;
264 volatile struct gdb_exception except
;
266 if (! PyArg_ParseTuple (args
, "s", &arg
))
269 newarg
= concat ("show ", arg
, (char *) NULL
);
271 TRY_CATCH (except
, RETURN_MASK_ALL
)
273 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
276 GDB_PY_HANDLE_EXCEPTION (except
);
278 return PyErr_Format (PyExc_RuntimeError
,
279 "could not find parameter `%s'", arg
);
282 return PyErr_Format (PyExc_RuntimeError
, "`%s' is not a parameter", arg
);
283 return parameter_to_python (cmd
);
286 /* Wrapper for target_charset. */
289 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
291 const char *cset
= target_charset (python_gdbarch
);
292 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
295 /* Wrapper for target_wide_charset. */
298 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
300 const char *cset
= target_wide_charset (python_gdbarch
);
301 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
304 /* A Python function which evaluates a string using the gdb CLI. */
307 execute_gdb_command (PyObject
*self
, PyObject
*args
)
309 struct cmd_list_element
*alias
, *prefix
, *cmd
;
311 PyObject
*from_tty_obj
= NULL
;
314 volatile struct gdb_exception except
;
316 if (! PyArg_ParseTuple (args
, "s|O!", &arg
, &PyBool_Type
, &from_tty_obj
))
322 cmp
= PyObject_IsTrue (from_tty_obj
);
328 TRY_CATCH (except
, RETURN_MASK_ALL
)
330 /* Copy the argument text in case the command modifies it. */
331 char *copy
= xstrdup (arg
);
332 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
333 execute_command (copy
, from_tty
);
334 do_cleanups (cleanup
);
336 GDB_PY_HANDLE_EXCEPTION (except
);
338 /* Do any commands attached to breakpoint we stopped at. */
339 bpstat_do_actions ();
344 /* Parse a string and evaluate it as an expression. */
346 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
349 struct value
*result
= NULL
;
350 volatile struct gdb_exception except
;
352 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
355 TRY_CATCH (except
, RETURN_MASK_ALL
)
357 result
= parse_and_eval (expr_str
);
359 GDB_PY_HANDLE_EXCEPTION (except
);
361 return value_to_value_object (result
);
364 /* Read a file as Python code. STREAM is the input file; FILE is the
368 source_python_script (FILE *stream
, char *file
)
370 PyGILState_STATE state
;
372 state
= PyGILState_Ensure ();
374 PyRun_SimpleFile (stream
, file
);
377 PyGILState_Release (state
);
384 /* A python function to write a single string using gdb's filtered
387 gdbpy_write (PyObject
*self
, PyObject
*args
)
390 if (! PyArg_ParseTuple (args
, "s", &arg
))
392 printf_filtered ("%s", arg
);
396 /* A python function to flush gdb's filtered output stream. */
398 gdbpy_flush (PyObject
*self
, PyObject
*args
)
400 gdb_flush (gdb_stdout
);
404 /* Print a python exception trace, or print nothing and clear the
405 python exception, depending on gdbpy_should_print_stack. Only call
406 this if a python exception is set. */
408 gdbpy_print_stack (void)
410 if (gdbpy_should_print_stack
)
418 /* The "current" objfile. This is set when gdb detects that a new
419 objfile has been loaded. It is only set for the duration of a call
420 to gdbpy_new_objfile; it is NULL at other times. */
421 static struct objfile
*gdbpy_current_objfile
;
423 /* The file name we attempt to read. */
424 #define GDBPY_AUTO_FILENAME "-gdb.py"
426 /* This is a new_objfile observer callback which loads python code
427 based on the path to the objfile. */
429 gdbpy_new_objfile (struct objfile
*objfile
)
432 char *filename
, *debugfile
;
435 struct cleanup
*cleanups
;
437 if (!gdbpy_auto_load
|| !objfile
|| !objfile
->name
)
440 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
442 gdbpy_current_objfile
= objfile
;
444 realname
= gdb_realpath (objfile
->name
);
445 len
= strlen (realname
);
446 filename
= xmalloc (len
+ sizeof (GDBPY_AUTO_FILENAME
));
447 memcpy (filename
, realname
, len
);
448 strcpy (filename
+ len
, GDBPY_AUTO_FILENAME
);
450 input
= fopen (filename
, "r");
451 debugfile
= filename
;
453 make_cleanup (xfree
, filename
);
454 make_cleanup (xfree
, realname
);
456 if (!input
&& debug_file_directory
)
458 /* Also try the same file in the separate debug info directory. */
459 debugfile
= xmalloc (strlen (filename
)
460 + strlen (debug_file_directory
) + 1);
461 strcpy (debugfile
, debug_file_directory
);
462 /* FILENAME is absolute, so we don't need a "/" here. */
463 strcat (debugfile
, filename
);
465 make_cleanup (xfree
, debugfile
);
466 input
= fopen (debugfile
, "r");
469 if (!input
&& gdb_datadir
)
471 /* Also try the same file in a subdirectory of gdb's data
473 debugfile
= xmalloc (strlen (gdb_datadir
) + strlen (filename
)
474 + strlen ("/auto-load") + 1);
475 strcpy (debugfile
, gdb_datadir
);
476 strcat (debugfile
, "/auto-load");
477 /* FILENAME is absolute, so we don't need a "/" here. */
478 strcat (debugfile
, filename
);
480 make_cleanup (xfree
, debugfile
);
481 input
= fopen (debugfile
, "r");
486 /* We don't want to throw an exception here -- but the user
487 would like to know that something went wrong. */
488 if (PyRun_SimpleFile (input
, debugfile
))
489 gdbpy_print_stack ();
493 do_cleanups (cleanups
);
494 gdbpy_current_objfile
= NULL
;
497 /* Return the current Objfile, or None if there isn't one. */
499 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
503 if (! gdbpy_current_objfile
)
506 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
512 /* Return a sequence holding all the Objfiles. */
514 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
516 struct objfile
*objf
;
519 list
= PyList_New (0);
525 PyObject
*item
= objfile_to_objfile_object (objf
);
526 if (!item
|| PyList_Append (list
, item
) == -1)
536 #else /* HAVE_PYTHON */
538 /* Dummy implementation of the gdb "python" command. */
541 python_command (char *arg
, int from_tty
)
543 while (arg
&& *arg
&& isspace (*arg
))
546 error (_("Python scripting is not supported in this copy of GDB."));
549 struct command_line
*l
= get_command_line (python_control
, "");
550 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
551 execute_control_command_untraced (l
);
552 do_cleanups (cleanups
);
557 eval_python_from_control_command (struct command_line
*cmd
)
559 error (_("Python scripting is not supported in this copy of GDB."));
563 source_python_script (FILE *stream
, char *file
)
566 throw_error (UNSUPPORTED_ERROR
,
567 _("Python scripting is not supported in this copy of GDB."));
570 #endif /* HAVE_PYTHON */
574 /* Lists for 'maint set python' commands. */
576 static struct cmd_list_element
*set_python_list
;
577 static struct cmd_list_element
*show_python_list
;
579 /* Function for use by 'maint set python' prefix command. */
582 set_python (char *args
, int from_tty
)
584 help_list (set_python_list
, "maintenance set python ", -1, gdb_stdout
);
587 /* Function for use by 'maint show python' prefix command. */
590 show_python (char *args
, int from_tty
)
592 cmd_show_list (show_python_list
, from_tty
, "");
595 /* Initialize the Python code. */
597 /* Provide a prototype to silence -Wmissing-prototypes. */
598 extern initialize_file_ftype _initialize_python
;
601 _initialize_python (void)
603 add_com ("python", class_obscure
, python_command
,
606 Evaluate a Python command.\n\
608 The command can be given as an argument, for instance:\n\
612 If no argument is given, the following lines are read and used\n\
613 as the Python commands. Type a line containing \"end\" to indicate\n\
614 the end of the command.")
615 #else /* HAVE_PYTHON */
617 Evaluate a Python command.\n\
619 Python scripting is not supported in this copy of GDB.\n\
620 This command is only a placeholder.")
621 #endif /* HAVE_PYTHON */
624 add_prefix_cmd ("python", no_class
, show_python
,
625 _("Prefix command for python maintenance settings."),
626 &show_python_list
, "maintenance show python ", 0,
627 &maintenance_show_cmdlist
);
628 add_prefix_cmd ("python", no_class
, set_python
,
629 _("Prefix command for python maintenance settings."),
630 &set_python_list
, "maintenance set python ", 0,
631 &maintenance_set_cmdlist
);
633 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
634 &gdbpy_should_print_stack
, _("\
635 Enable or disable printing of Python stack dump on error."), _("\
636 Show whether Python stack will be printed on error."), _("\
637 Enables or disables printing of Python stack traces."),
642 add_setshow_boolean_cmd ("auto-load", class_maintenance
,
643 &gdbpy_auto_load
, _("\
644 Enable or disable auto-loading of Python code when an object is opened."), _("\
645 Show whether Python code will be auto-loaded when an object is opened."), _("\
646 Enables or disables auto-loading of Python code when an object is opened."),
653 PyEval_InitThreads ();
655 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
657 /* The casts to (char*) are for python 2.4. */
658 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
659 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
660 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG", (char*) target_name
);
662 gdbpy_initialize_values ();
663 gdbpy_initialize_frames ();
664 gdbpy_initialize_commands ();
665 gdbpy_initialize_symbols ();
666 gdbpy_initialize_symtabs ();
667 gdbpy_initialize_blocks ();
668 gdbpy_initialize_functions ();
669 gdbpy_initialize_types ();
670 gdbpy_initialize_objfile ();
671 gdbpy_initialize_lazy_string ();
673 PyRun_SimpleString ("import gdb");
674 PyRun_SimpleString ("gdb.pretty_printers = []");
676 observer_attach_new_objfile (gdbpy_new_objfile
);
678 gdbpy_to_string_cst
= PyString_FromString ("to_string");
679 gdbpy_children_cst
= PyString_FromString ("children");
680 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
681 gdbpy_doc_cst
= PyString_FromString ("__doc__");
683 /* Create a couple objects which are used for Python's stdout and
685 PyRun_SimpleString ("\
687 class GdbOutputFile:\n\
695 def write(self, s):\n\
698 def writelines(self, iterable):\n\
699 for line in iterable:\n\
705 sys.stderr = GdbOutputFile()\n\
706 sys.stdout = GdbOutputFile()\n\
709 /* Release the GIL while gdb runs. */
710 PyThreadState_Swap (NULL
);
711 PyEval_ReleaseLock ();
713 #endif /* HAVE_PYTHON */
720 static PyMethodDef GdbMethods
[] =
722 { "history", gdbpy_history
, METH_VARARGS
,
723 "Get a value from history" },
724 { "execute", execute_gdb_command
, METH_VARARGS
,
725 "Execute a gdb command" },
726 { "parameter", gdbpy_parameter
, METH_VARARGS
,
727 "Return a gdb parameter's value" },
729 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
730 "Find the default visualizer for a Value." },
732 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
733 "Return the current Objfile being loaded, or None." },
734 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
735 "Return a sequence of all loaded objfiles." },
737 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
738 "selected_frame () -> gdb.Frame.\n\
739 Return the selected frame object." },
740 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
741 "stop_reason_string (Integer) -> String.\n\
742 Return a string explaining unwind stop reason." },
744 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
745 METH_VARARGS
| METH_KEYWORDS
,
746 "lookup_type (name [, block]) -> type\n\
747 Return a Type corresponding to the given name." },
748 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
749 METH_VARARGS
| METH_KEYWORDS
,
750 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
751 Return a tuple with the symbol corresponding to the given name (or None) and\n\
752 a boolean indicating if name is a field of the current implied argument\n\
753 `this' (when the current language is object-oriented)." },
754 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
755 "Return the block containing the given pc value, or None." },
756 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
757 "parse_and_eval (String) -> Value.\n\
758 Parse String as an expression, evaluate it, and return the result as a Value."
761 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
762 "target_charset () -> string.\n\
763 Return the name of the current target charset." },
764 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
765 "target_wide_charset () -> string.\n\
766 Return the name of the current target wide charset." },
768 { "write", gdbpy_write
, METH_VARARGS
,
769 "Write a string using gdb's filtered stream." },
770 { "flush", gdbpy_flush
, METH_NOARGS
,
771 "Flush gdb's filtered stdout stream." },
773 {NULL
, NULL
, 0, NULL
}
776 #endif /* HAVE_PYTHON */