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"
26 #include "progspace.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;
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
45 #include "python-internal.h"
48 #include "gdbthread.h"
50 static PyMethodDef GdbMethods
[];
54 /* Some string constants we may wish to use. */
55 PyObject
*gdbpy_to_string_cst
;
56 PyObject
*gdbpy_children_cst
;
57 PyObject
*gdbpy_display_hint_cst
;
58 PyObject
*gdbpy_doc_cst
;
60 /* The GdbError exception. */
61 PyObject
*gdbpy_gdberror_exc
;
63 /* Architecture and language to be used in callbacks from
64 the Python interpreter. */
65 struct gdbarch
*python_gdbarch
;
66 const struct language_defn
*python_language
;
68 /* Restore global language and architecture and Python GIL state
69 when leaving the Python interpreter. */
73 PyGILState_STATE state
;
74 struct gdbarch
*gdbarch
;
75 const struct language_defn
*language
;
79 restore_python_env (void *p
)
81 struct python_env
*env
= (struct python_env
*)p
;
83 PyGILState_Release (env
->state
);
84 python_gdbarch
= env
->gdbarch
;
85 python_language
= env
->language
;
89 /* Called before entering the Python interpreter to install the
90 current language and architecture to be used for Python values. */
93 ensure_python_env (struct gdbarch
*gdbarch
,
94 const struct language_defn
*language
)
96 struct python_env
*env
= xmalloc (sizeof *env
);
98 env
->state
= PyGILState_Ensure ();
99 env
->gdbarch
= python_gdbarch
;
100 env
->language
= python_language
;
102 python_gdbarch
= gdbarch
;
103 python_language
= language
;
105 return make_cleanup (restore_python_env
, env
);
109 /* Given a command_line, return a command string suitable for passing
110 to Python. Lines in the string are separated by newlines. The
111 return value is allocated using xmalloc and the caller is
112 responsible for freeing it. */
115 compute_python_string (struct command_line
*l
)
117 struct command_line
*iter
;
122 for (iter
= l
; iter
; iter
= iter
->next
)
123 size
+= strlen (iter
->line
) + 1;
125 script
= xmalloc (size
+ 1);
127 for (iter
= l
; iter
; iter
= iter
->next
)
129 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
;
173 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
, "");
188 make_cleanup_free_command_lines (&l
);
189 execute_control_command_untraced (l
);
192 do_cleanups (cleanup
);
197 /* Transform a gdb parameters's value into a Python value. May return
198 NULL (and set a Python exception) on error. Helper function for
201 gdbpy_parameter_value (enum var_types type
, void *var
)
206 case var_string_noescape
:
207 case var_optional_filename
:
211 char *str
= * (char **) var
;
215 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
226 case var_auto_boolean
:
228 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
230 if (ab
== AUTO_BOOLEAN_TRUE
)
232 else if (ab
== AUTO_BOOLEAN_FALSE
)
239 if ((* (int *) var
) == INT_MAX
)
243 return PyLong_FromLong (* (int *) var
);
247 unsigned int val
= * (unsigned int *) var
;
251 return PyLong_FromUnsignedLong (val
);
255 return PyErr_Format (PyExc_RuntimeError
,
256 _("Programmer error: unhandled type."));
259 /* A Python function which returns a gdb parameter's value as a Python
263 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
265 struct cmd_list_element
*alias
, *prefix
, *cmd
;
268 volatile struct gdb_exception except
;
270 if (! PyArg_ParseTuple (args
, "s", &arg
))
273 newarg
= concat ("show ", arg
, (char *) NULL
);
275 TRY_CATCH (except
, RETURN_MASK_ALL
)
277 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
280 GDB_PY_HANDLE_EXCEPTION (except
);
282 return PyErr_Format (PyExc_RuntimeError
,
283 _("Could not find parameter `%s'."), arg
);
286 return PyErr_Format (PyExc_RuntimeError
,
287 _("`%s' is not a parameter."), arg
);
288 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
291 /* Wrapper for target_charset. */
294 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
296 const char *cset
= target_charset (python_gdbarch
);
298 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
301 /* Wrapper for target_wide_charset. */
304 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
306 const char *cset
= target_wide_charset (python_gdbarch
);
308 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
311 /* A Python function which evaluates a string using the gdb CLI. */
314 execute_gdb_command (PyObject
*self
, PyObject
*args
)
317 PyObject
*from_tty_obj
= NULL
;
320 volatile struct gdb_exception except
;
322 if (! PyArg_ParseTuple (args
, "s|O!", &arg
, &PyBool_Type
, &from_tty_obj
))
328 cmp
= PyObject_IsTrue (from_tty_obj
);
334 TRY_CATCH (except
, RETURN_MASK_ALL
)
336 /* Copy the argument text in case the command modifies it. */
337 char *copy
= xstrdup (arg
);
338 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
340 execute_command (copy
, from_tty
);
341 do_cleanups (cleanup
);
343 GDB_PY_HANDLE_EXCEPTION (except
);
345 /* Do any commands attached to breakpoint we stopped at. */
346 bpstat_do_actions ();
351 /* Parse a string and evaluate it as an expression. */
353 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
356 struct value
*result
= NULL
;
357 volatile struct gdb_exception except
;
359 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
362 TRY_CATCH (except
, RETURN_MASK_ALL
)
364 result
= parse_and_eval (expr_str
);
366 GDB_PY_HANDLE_EXCEPTION (except
);
368 return value_to_value_object (result
);
371 /* Read a file as Python code. STREAM is the input file; FILE is the
373 STREAM is not closed, that is the caller's responsibility. */
376 source_python_script (FILE *stream
, const char *file
)
378 struct cleanup
*cleanup
;
380 cleanup
= ensure_python_env (get_current_arch (), current_language
);
382 /* Note: If an exception occurs python will print the traceback and
383 clear the error indicator. */
384 PyRun_SimpleFile (stream
, file
);
386 do_cleanups (cleanup
);
393 /* A python function to write a single string using gdb's filtered
396 gdbpy_write (PyObject
*self
, PyObject
*args
)
400 if (! PyArg_ParseTuple (args
, "s", &arg
))
402 printf_filtered ("%s", arg
);
406 /* A python function to flush gdb's filtered output stream. */
408 gdbpy_flush (PyObject
*self
, PyObject
*args
)
410 gdb_flush (gdb_stdout
);
414 /* Print a python exception trace, or print nothing and clear the
415 python exception, depending on gdbpy_should_print_stack. Only call
416 this if a python exception is set. */
418 gdbpy_print_stack (void)
420 if (gdbpy_should_print_stack
)
423 /* PyErr_Print doesn't necessarily end output with a newline.
424 This works because Python's stdout/stderr is fed through
434 /* Return the current Progspace.
435 There always is one. */
438 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
442 result
= pspace_to_pspace_object (current_program_space
);
448 /* Return a sequence holding all the Progspaces. */
451 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
453 struct program_space
*ps
;
456 list
= PyList_New (0);
462 PyObject
*item
= pspace_to_pspace_object (ps
);
464 if (!item
|| PyList_Append (list
, item
) == -1)
476 /* The "current" objfile. This is set when gdb detects that a new
477 objfile has been loaded. It is only set for the duration of a call to
478 source_python_script_for_objfile; it is NULL at other times. */
479 static struct objfile
*gdbpy_current_objfile
;
481 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
485 source_python_script_for_objfile (struct objfile
*objfile
,
486 FILE *stream
, const char *file
)
488 struct cleanup
*cleanups
;
490 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
491 gdbpy_current_objfile
= objfile
;
493 /* Note: If an exception occurs python will print the traceback and
494 clear the error indicator. */
495 PyRun_SimpleFile (stream
, file
);
497 do_cleanups (cleanups
);
498 gdbpy_current_objfile
= NULL
;
501 /* Return the current Objfile, or None if there isn't one. */
504 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
508 if (! gdbpy_current_objfile
)
511 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
517 /* Return a sequence holding all the Objfiles. */
520 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
522 struct objfile
*objf
;
525 list
= PyList_New (0);
531 PyObject
*item
= objfile_to_objfile_object (objf
);
533 if (!item
|| PyList_Append (list
, item
) == -1)
543 #else /* HAVE_PYTHON */
545 /* Dummy implementation of the gdb "python" command. */
548 python_command (char *arg
, int from_tty
)
550 while (arg
&& *arg
&& isspace (*arg
))
553 error (_("Python scripting is not supported in this copy of GDB."));
556 struct command_line
*l
= get_command_line (python_control
, "");
557 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
559 execute_control_command_untraced (l
);
560 do_cleanups (cleanups
);
565 eval_python_from_control_command (struct command_line
*cmd
)
567 error (_("Python scripting is not supported in this copy of GDB."));
571 source_python_script (FILE *stream
, const char *file
)
573 throw_error (UNSUPPORTED_ERROR
,
574 _("Python scripting is not supported in this copy of GDB."));
577 #endif /* HAVE_PYTHON */
581 /* Lists for 'maint set python' commands. */
583 struct cmd_list_element
*set_python_list
;
584 struct cmd_list_element
*show_python_list
;
586 /* Function for use by 'maint set python' prefix command. */
589 set_python (char *args
, int from_tty
)
591 help_list (set_python_list
, "maintenance set python ", -1, gdb_stdout
);
594 /* Function for use by 'maint show python' prefix command. */
597 show_python (char *args
, int from_tty
)
599 cmd_show_list (show_python_list
, from_tty
, "");
602 /* Initialize the Python code. */
604 /* Provide a prototype to silence -Wmissing-prototypes. */
605 extern initialize_file_ftype _initialize_python
;
608 _initialize_python (void)
610 add_com ("python", class_obscure
, python_command
,
613 Evaluate a Python command.\n\
615 The command can be given as an argument, for instance:\n\
619 If no argument is given, the following lines are read and used\n\
620 as the Python commands. Type a line containing \"end\" to indicate\n\
621 the end of the command.")
622 #else /* HAVE_PYTHON */
624 Evaluate a Python command.\n\
626 Python scripting is not supported in this copy of GDB.\n\
627 This command is only a placeholder.")
628 #endif /* HAVE_PYTHON */
631 add_prefix_cmd ("python", no_class
, show_python
,
632 _("Prefix command for python maintenance settings."),
633 &show_python_list
, "maintenance show python ", 0,
634 &maintenance_show_cmdlist
);
635 add_prefix_cmd ("python", no_class
, set_python
,
636 _("Prefix command for python maintenance settings."),
637 &set_python_list
, "maintenance set python ", 0,
638 &maintenance_set_cmdlist
);
640 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
641 &gdbpy_should_print_stack
, _("\
642 Enable or disable printing of Python stack dump on error."), _("\
643 Show whether Python stack will be printed on error."), _("\
644 Enables or disables printing of Python stack traces."),
650 #ifdef WITH_PYTHON_PATH
651 /* Work around problem where python gets confused about where it is,
652 and then can't find its libraries, etc.
653 NOTE: Python assumes the following layout:
655 /foo/lib/pythonX.Y/...
656 This must be done before calling Py_Initialize. */
657 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
658 SLASH_STRING
, "python", NULL
));
662 PyEval_InitThreads ();
664 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
666 /* The casts to (char*) are for python 2.4. */
667 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
668 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
669 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG", (char*) target_name
);
671 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
672 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
674 gdbpy_initialize_auto_load ();
675 gdbpy_initialize_values ();
676 gdbpy_initialize_frames ();
677 gdbpy_initialize_commands ();
678 gdbpy_initialize_symbols ();
679 gdbpy_initialize_symtabs ();
680 gdbpy_initialize_blocks ();
681 gdbpy_initialize_functions ();
682 gdbpy_initialize_parameters ();
683 gdbpy_initialize_types ();
684 gdbpy_initialize_pspace ();
685 gdbpy_initialize_objfile ();
686 gdbpy_initialize_breakpoints ();
687 gdbpy_initialize_lazy_string ();
689 PyRun_SimpleString ("import gdb");
690 PyRun_SimpleString ("gdb.pretty_printers = []");
692 gdbpy_to_string_cst
= PyString_FromString ("to_string");
693 gdbpy_children_cst
= PyString_FromString ("children");
694 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
695 gdbpy_doc_cst
= PyString_FromString ("__doc__");
697 /* Create a couple objects which are used for Python's stdout and
699 PyRun_SimpleString ("\
701 class GdbOutputFile:\n\
709 def write(self, s):\n\
712 def writelines(self, iterable):\n\
713 for line in iterable:\n\
719 sys.stderr = GdbOutputFile()\n\
720 sys.stdout = GdbOutputFile()\n\
723 /* Release the GIL while gdb runs. */
724 PyThreadState_Swap (NULL
);
725 PyEval_ReleaseLock ();
727 #endif /* HAVE_PYTHON */
734 static PyMethodDef GdbMethods
[] =
736 { "history", gdbpy_history
, METH_VARARGS
,
737 "Get a value from history" },
738 { "execute", execute_gdb_command
, METH_VARARGS
,
739 "Execute a gdb command" },
740 { "parameter", gdbpy_parameter
, METH_VARARGS
,
741 "Return a gdb parameter's value" },
743 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
744 "Return a tuple of all breakpoint objects" },
746 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
747 "Find the default visualizer for a Value." },
749 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
750 "Return the current Progspace." },
751 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
752 "Return a sequence of all progspaces." },
754 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
755 "Return the current Objfile being loaded, or None." },
756 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
757 "Return a sequence of all loaded objfiles." },
759 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
760 "selected_frame () -> gdb.Frame.\n\
761 Return the selected frame object." },
762 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
763 "stop_reason_string (Integer) -> String.\n\
764 Return a string explaining unwind stop reason." },
766 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
767 METH_VARARGS
| METH_KEYWORDS
,
768 "lookup_type (name [, block]) -> type\n\
769 Return a Type corresponding to the given name." },
770 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
771 METH_VARARGS
| METH_KEYWORDS
,
772 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
773 Return a tuple with the symbol corresponding to the given name (or None) and\n\
774 a boolean indicating if name is a field of the current implied argument\n\
775 `this' (when the current language is object-oriented)." },
776 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
777 "Return the block containing the given pc value, or None." },
778 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
779 "parse_and_eval (String) -> Value.\n\
780 Parse String as an expression, evaluate it, and return the result as a Value."
783 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
784 "target_charset () -> string.\n\
785 Return the name of the current target charset." },
786 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
787 "target_wide_charset () -> string.\n\
788 Return the name of the current target wide charset." },
790 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
791 "string_to_argv (String) -> Array.\n\
792 Parse String and return an argv-like array.\n\
793 Arguments are separate by spaces and may be quoted."
796 { "write", gdbpy_write
, METH_VARARGS
,
797 "Write a string using gdb's filtered stream." },
798 { "flush", gdbpy_flush
, METH_NOARGS
,
799 "Flush gdb's filtered stdout stream." },
801 {NULL
, NULL
, 0, NULL
}
804 #endif /* HAVE_PYTHON */