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"
46 #include "python-internal.h"
51 #include "gdbthread.h"
53 static PyMethodDef GdbMethods[];
57 /* Some string constants we may wish to use. */
58 PyObject *gdbpy_to_string_cst;
59 PyObject *gdbpy_children_cst;
60 PyObject *gdbpy_display_hint_cst;
61 PyObject *gdbpy_doc_cst;
62 PyObject *gdbpy_enabled_cst;
64 /* The GdbError exception. */
65 PyObject *gdbpy_gdberror_exc;
67 /* Architecture and language to be used in callbacks from
68 the Python interpreter. */
69 struct gdbarch *python_gdbarch;
70 const struct language_defn *python_language;
72 /* Restore global language and architecture and Python GIL state
73 when leaving the Python interpreter. */
77 PyGILState_STATE state;
78 struct gdbarch *gdbarch;
79 const struct language_defn *language;
83 restore_python_env (void *p)
85 struct python_env *env = (struct python_env *)p;
87 PyGILState_Release (env->state);
88 python_gdbarch = env->gdbarch;
89 python_language = env->language;
93 /* Called before entering the Python interpreter to install the
94 current language and architecture to be used for Python values. */
97 ensure_python_env (struct gdbarch *gdbarch,
98 const struct language_defn *language)
100 struct python_env *env = xmalloc (sizeof *env);
102 env->state = PyGILState_Ensure ();
103 env->gdbarch = python_gdbarch;
104 env->language = python_language;
106 python_gdbarch = gdbarch;
107 python_language = language;
109 return make_cleanup (restore_python_env, env);
113 /* Given a command_line, return a command string suitable for passing
114 to Python. Lines in the string are separated by newlines. The
115 return value is allocated using xmalloc and the caller is
116 responsible for freeing it. */
119 compute_python_string (struct command_line *l)
121 struct command_line *iter;
126 for (iter = l; iter; iter = iter->next)
127 size += strlen (iter->line) + 1;
129 script = xmalloc (size + 1);
131 for (iter = l; iter; iter = iter->next)
133 int len = strlen (iter->line);
135 strcpy (&script[here], iter->line);
137 script[here++] = '\n';
143 /* Take a command line structure representing a 'python' command, and
144 evaluate its body using the Python interpreter. */
147 eval_python_from_control_command (struct command_line *cmd)
151 struct cleanup *cleanup;
153 if (cmd->body_count != 1)
154 error (_("Invalid \"python\" block structure."));
156 cleanup = ensure_python_env (get_current_arch (), current_language);
158 script = compute_python_string (cmd->body_list[0]);
159 ret = PyRun_SimpleString (script);
163 gdbpy_print_stack ();
164 error (_("Error while executing Python code."));
167 do_cleanups (cleanup);
170 /* Implementation of the gdb "python" command. */
173 python_command (char *arg, int from_tty)
175 struct cleanup *cleanup;
177 cleanup = ensure_python_env (get_current_arch (), current_language);
178 while (arg && *arg && isspace (*arg))
182 if (PyRun_SimpleString (arg))
184 gdbpy_print_stack ();
185 error (_("Error while executing Python code."));
190 struct command_line *l = get_command_line (python_control, "");
192 make_cleanup_free_command_lines (&l);
193 execute_control_command_untraced (l);
196 do_cleanups (cleanup);
201 /* Transform a gdb parameters's value into a Python value. May return
202 NULL (and set a Python exception) on error. Helper function for
205 gdbpy_parameter_value (enum var_types type, void *var)
210 case var_string_noescape:
211 case var_optional_filename:
215 char *str = * (char **) var;
219 return PyString_Decode (str, strlen (str), host_charset (), NULL);
230 case var_auto_boolean:
232 enum auto_boolean ab = * (enum auto_boolean *) var;
234 if (ab == AUTO_BOOLEAN_TRUE)
236 else if (ab == AUTO_BOOLEAN_FALSE)
243 if ((* (int *) var) == INT_MAX)
247 return PyLong_FromLong (* (int *) var);
251 unsigned int val = * (unsigned int *) var;
255 return PyLong_FromUnsignedLong (val);
259 return PyErr_Format (PyExc_RuntimeError,
260 _("Programmer error: unhandled type."));
263 /* A Python function which returns a gdb parameter's value as a Python
267 gdbpy_parameter (PyObject *self, PyObject *args)
269 struct cmd_list_element *alias, *prefix, *cmd;
272 volatile struct gdb_exception except;
274 if (! PyArg_ParseTuple (args, "s", &arg))
277 newarg = concat ("show ", arg, (char *) NULL);
279 TRY_CATCH (except, RETURN_MASK_ALL)
281 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
284 GDB_PY_HANDLE_EXCEPTION (except);
286 return PyErr_Format (PyExc_RuntimeError,
287 _("Could not find parameter `%s'."), arg);
290 return PyErr_Format (PyExc_RuntimeError,
291 _("`%s' is not a parameter."), arg);
292 return gdbpy_parameter_value (cmd->var_type, cmd->var);
295 /* Wrapper for target_charset. */
298 gdbpy_target_charset (PyObject *self, PyObject *args)
300 const char *cset = target_charset (python_gdbarch);
302 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
305 /* Wrapper for target_wide_charset. */
308 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
310 const char *cset = target_wide_charset (python_gdbarch);
312 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
315 /* A Python function which evaluates a string using the gdb CLI. */
318 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
321 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
322 int from_tty, to_string;
323 volatile struct gdb_exception except;
324 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
327 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
328 &PyBool_Type, &from_tty_obj,
329 &PyBool_Type, &to_string_obj))
335 int cmp = PyObject_IsTrue (from_tty_obj);
344 int cmp = PyObject_IsTrue (to_string_obj);
350 TRY_CATCH (except, RETURN_MASK_ALL)
352 /* Copy the argument text in case the command modifies it. */
353 char *copy = xstrdup (arg);
354 struct cleanup *cleanup = make_cleanup (xfree, copy);
357 result = execute_command_to_string (copy, from_tty);
361 execute_command (copy, from_tty);
364 do_cleanups (cleanup);
366 GDB_PY_HANDLE_EXCEPTION (except);
368 /* Do any commands attached to breakpoint we stopped at. */
369 bpstat_do_actions ();
373 PyObject *r = PyString_FromString (result);
380 /* Implementation of gdb.solib_name (Long) -> String.
381 Returns the name of the shared library holding a given address, or None. */
384 gdbpy_solib_name (PyObject *self, PyObject *args)
389 unsigned PY_LONG_LONG pc;
390 const char *format = "K";
393 const char *format = "k";
396 if (!PyArg_ParseTuple (args, format, &pc))
399 soname = solib_name_from_address (current_program_space, pc);
401 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
411 /* A Python function which is a wrapper for decode_line_1. */
414 gdbpy_decode_line (PyObject *self, PyObject *args)
416 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to appease gcc. */
417 struct symtab_and_line sal;
420 struct cleanup *cleanups;
421 PyObject *result = NULL;
422 PyObject *return_result = NULL;
423 PyObject *unparsed = NULL;
424 volatile struct gdb_exception except;
426 if (! PyArg_ParseTuple (args, "|s", &arg))
429 cleanups = ensure_python_env (get_current_arch (), current_language);
431 TRY_CATCH (except, RETURN_MASK_ALL)
436 make_cleanup (xfree, arg);
438 sals = decode_line_1 (©, 0, 0, 0, 0, 0);
439 make_cleanup (xfree, sals.sals);
443 set_default_source_symtab_and_line ();
444 sal = get_current_source_symtab_and_line ();
449 if (except.reason < 0)
451 do_cleanups (cleanups);
452 /* We know this will always throw. */
453 GDB_PY_HANDLE_EXCEPTION (except);
460 result = PyTuple_New (sals.nelts);
463 for (i = 0; i < sals.nelts; ++i)
468 obj = symtab_and_line_to_sal_object (sals.sals[i]);
475 PyTuple_SetItem (result, i, obj);
484 return_result = PyTuple_New (2);
491 if (copy && strlen (copy) > 0)
492 unparsed = PyString_FromString (copy);
499 PyTuple_SetItem (return_result, 0, unparsed);
500 PyTuple_SetItem (return_result, 1, result);
502 do_cleanups (cleanups);
504 return return_result;
507 do_cleanups (cleanups);
511 /* Parse a string and evaluate it as an expression. */
513 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
516 struct value *result = NULL;
517 volatile struct gdb_exception except;
519 if (!PyArg_ParseTuple (args, "s", &expr_str))
522 TRY_CATCH (except, RETURN_MASK_ALL)
524 result = parse_and_eval (expr_str);
526 GDB_PY_HANDLE_EXCEPTION (except);
528 return value_to_value_object (result);
531 /* Read a file as Python code. STREAM is the input file; FILE is the
533 STREAM is not closed, that is the caller's responsibility. */
536 source_python_script (FILE *stream, const char *file)
538 struct cleanup *cleanup;
540 cleanup = ensure_python_env (get_current_arch (), current_language);
542 /* Note: If an exception occurs python will print the traceback and
543 clear the error indicator. */
544 PyRun_SimpleFile (stream, file);
546 do_cleanups (cleanup);
553 /* A python function to write a single string using gdb's filtered
556 gdbpy_write (PyObject *self, PyObject *args)
560 if (! PyArg_ParseTuple (args, "s", &arg))
562 printf_filtered ("%s", arg);
566 /* A python function to flush gdb's filtered output stream. */
568 gdbpy_flush (PyObject *self, PyObject *args)
570 gdb_flush (gdb_stdout);
574 /* Print a python exception trace, or print nothing and clear the
575 python exception, depending on gdbpy_should_print_stack. Only call
576 this if a python exception is set. */
578 gdbpy_print_stack (void)
580 if (gdbpy_should_print_stack)
583 /* PyErr_Print doesn't necessarily end output with a newline.
584 This works because Python's stdout/stderr is fed through
594 /* Return the current Progspace.
595 There always is one. */
598 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
602 result = pspace_to_pspace_object (current_program_space);
608 /* Return a sequence holding all the Progspaces. */
611 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
613 struct program_space *ps;
616 list = PyList_New (0);
622 PyObject *item = pspace_to_pspace_object (ps);
624 if (!item || PyList_Append (list, item) == -1)
636 /* The "current" objfile. This is set when gdb detects that a new
637 objfile has been loaded. It is only set for the duration of a call to
638 source_python_script_for_objfile; it is NULL at other times. */
639 static struct objfile *gdbpy_current_objfile;
641 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
645 source_python_script_for_objfile (struct objfile *objfile,
646 FILE *stream, const char *file)
648 struct cleanup *cleanups;
650 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
651 gdbpy_current_objfile = objfile;
653 /* Note: If an exception occurs python will print the traceback and
654 clear the error indicator. */
655 PyRun_SimpleFile (stream, file);
657 do_cleanups (cleanups);
658 gdbpy_current_objfile = NULL;
661 /* Return the current Objfile, or None if there isn't one. */
664 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
668 if (! gdbpy_current_objfile)
671 result = objfile_to_objfile_object (gdbpy_current_objfile);
677 /* Return a sequence holding all the Objfiles. */
680 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
682 struct objfile *objf;
685 list = PyList_New (0);
691 PyObject *item = objfile_to_objfile_object (objf);
693 if (!item || PyList_Append (list, item) == -1)
703 #else /* HAVE_PYTHON */
705 /* Dummy implementation of the gdb "python" command. */
708 python_command (char *arg, int from_tty)
710 while (arg && *arg && isspace (*arg))
713 error (_("Python scripting is not supported in this copy of GDB."));
716 struct command_line *l = get_command_line (python_control, "");
717 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
719 execute_control_command_untraced (l);
720 do_cleanups (cleanups);
725 eval_python_from_control_command (struct command_line *cmd)
727 error (_("Python scripting is not supported in this copy of GDB."));
731 source_python_script (FILE *stream, const char *file)
733 throw_error (UNSUPPORTED_ERROR,
734 _("Python scripting is not supported in this copy of GDB."));
737 #endif /* HAVE_PYTHON */
741 /* Lists for 'maint set python' commands. */
743 struct cmd_list_element *set_python_list;
744 struct cmd_list_element *show_python_list;
746 /* Function for use by 'maint set python' prefix command. */
749 set_python (char *args, int from_tty)
751 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
754 /* Function for use by 'maint show python' prefix command. */
757 show_python (char *args, int from_tty)
759 cmd_show_list (show_python_list, from_tty, "");
762 /* Initialize the Python code. */
764 /* Provide a prototype to silence -Wmissing-prototypes. */
765 extern initialize_file_ftype _initialize_python;
768 _initialize_python (void)
770 add_com ("python", class_obscure, python_command,
773 Evaluate a Python command.\n\
775 The command can be given as an argument, for instance:\n\
779 If no argument is given, the following lines are read and used\n\
780 as the Python commands. Type a line containing \"end\" to indicate\n\
781 the end of the command.")
782 #else /* HAVE_PYTHON */
784 Evaluate a Python command.\n\
786 Python scripting is not supported in this copy of GDB.\n\
787 This command is only a placeholder.")
788 #endif /* HAVE_PYTHON */
791 add_prefix_cmd ("python", no_class, show_python,
792 _("Prefix command for python maintenance settings."),
793 &show_python_list, "maintenance show python ", 0,
794 &maintenance_show_cmdlist);
795 add_prefix_cmd ("python", no_class, set_python,
796 _("Prefix command for python maintenance settings."),
797 &set_python_list, "maintenance set python ", 0,
798 &maintenance_set_cmdlist);
800 add_setshow_boolean_cmd ("print-stack", class_maintenance,
801 &gdbpy_should_print_stack, _("\
802 Enable or disable printing of Python stack dump on error."), _("\
803 Show whether Python stack will be printed on error."), _("\
804 Enables or disables printing of Python stack traces."),
810 #ifdef WITH_PYTHON_PATH
811 /* Work around problem where python gets confused about where it is,
812 and then can't find its libraries, etc.
813 NOTE: Python assumes the following layout:
815 /foo/lib/pythonX.Y/...
816 This must be done before calling Py_Initialize. */
817 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
818 SLASH_STRING, "python", NULL));
822 PyEval_InitThreads ();
824 gdb_module = Py_InitModule ("gdb", GdbMethods);
826 /* The casts to (char*) are for python 2.4. */
827 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
828 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
829 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
833 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
834 PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
835 xfree (gdb_pythondir);
838 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
839 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
841 gdbpy_initialize_auto_load ();
842 gdbpy_initialize_values ();
843 gdbpy_initialize_frames ();
844 gdbpy_initialize_commands ();
845 gdbpy_initialize_symbols ();
846 gdbpy_initialize_symtabs ();
847 gdbpy_initialize_blocks ();
848 gdbpy_initialize_functions ();
849 gdbpy_initialize_parameters ();
850 gdbpy_initialize_types ();
851 gdbpy_initialize_pspace ();
852 gdbpy_initialize_objfile ();
853 gdbpy_initialize_breakpoints ();
854 gdbpy_initialize_lazy_string ();
855 gdbpy_initialize_thread ();
856 gdbpy_initialize_inferior ();
858 PyRun_SimpleString ("import gdb");
859 PyRun_SimpleString ("gdb.pretty_printers = []");
861 gdbpy_to_string_cst = PyString_FromString ("to_string");
862 gdbpy_children_cst = PyString_FromString ("children");
863 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
864 gdbpy_doc_cst = PyString_FromString ("__doc__");
865 gdbpy_enabled_cst = PyString_FromString ("enabled");
867 /* Create a couple objects which are used for Python's stdout and
869 PyRun_SimpleString ("\
871 class GdbOutputFile:\n\
879 def write(self, s):\n\
882 def writelines(self, iterable):\n\
883 for line in iterable:\n\
889 sys.stderr = GdbOutputFile()\n\
890 sys.stdout = GdbOutputFile()\n\
892 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
893 # that directory name at the start of sys.path to allow the Python\n\
894 # interpreter to find them.\n\
895 sys.path.insert(0, gdb.PYTHONDIR)\n\
897 # The gdb module is implemented in C rather than in Python. As a result,\n\
898 # the associated __init.py__ script is not not executed by default when\n\
899 # the gdb module gets imported. Execute that script manually if it exists.\n\
900 gdb.__path__ = [gdb.PYTHONDIR + '/gdb']\n\
901 from os.path import exists\n\
902 ipy = gdb.PYTHONDIR + '/gdb/__init__.py'\n\
907 /* Release the GIL while gdb runs. */
908 PyThreadState_Swap (NULL);
909 PyEval_ReleaseLock ();
911 #endif /* HAVE_PYTHON */
918 static PyMethodDef GdbMethods[] =
920 { "history", gdbpy_history, METH_VARARGS,
921 "Get a value from history" },
922 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
923 "Execute a gdb command" },
924 { "parameter", gdbpy_parameter, METH_VARARGS,
925 "Return a gdb parameter's value" },
927 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
928 "Return a tuple of all breakpoint objects" },
930 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
931 "Find the default visualizer for a Value." },
933 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
934 "Return the current Progspace." },
935 { "progspaces", gdbpy_progspaces, METH_NOARGS,
936 "Return a sequence of all progspaces." },
938 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
939 "Return the current Objfile being loaded, or None." },
940 { "objfiles", gdbpy_objfiles, METH_NOARGS,
941 "Return a sequence of all loaded objfiles." },
943 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
944 "selected_frame () -> gdb.Frame.\n\
945 Return the selected frame object." },
946 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
947 "stop_reason_string (Integer) -> String.\n\
948 Return a string explaining unwind stop reason." },
950 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
951 METH_VARARGS | METH_KEYWORDS,
952 "lookup_type (name [, block]) -> type\n\
953 Return a Type corresponding to the given name." },
954 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
955 METH_VARARGS | METH_KEYWORDS,
956 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
957 Return a tuple with the symbol corresponding to the given name (or None) and\n\
958 a boolean indicating if name is a field of the current implied argument\n\
959 `this' (when the current language is object-oriented)." },
960 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
961 "Return the block containing the given pc value, or None." },
962 { "solib_name", gdbpy_solib_name, METH_VARARGS,
963 "solib_name (Long) -> String.\n\
964 Return the name of the shared library holding a given address, or None." },
965 { "decode_line", gdbpy_decode_line, METH_VARARGS,
966 "decode_line (String) -> Tuple. Decode a string argument the way\n\
967 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
968 The first element contains any unparsed portion of the String parameter\n\
969 (or None if the string was fully parsed). The second element contains\n\
970 a tuple that contains all the locations that match, represented as\n\
971 gdb.Symtab_and_line objects (or None)."},
972 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
973 "parse_and_eval (String) -> Value.\n\
974 Parse String as an expression, evaluate it, and return the result as a Value."
977 { "target_charset", gdbpy_target_charset, METH_NOARGS,
978 "target_charset () -> string.\n\
979 Return the name of the current target charset." },
980 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
981 "target_wide_charset () -> string.\n\
982 Return the name of the current target wide charset." },
984 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
985 "string_to_argv (String) -> Array.\n\
986 Parse String and return an argv-like array.\n\
987 Arguments are separate by spaces and may be quoted."
990 { "write", gdbpy_write, METH_VARARGS,
991 "Write a string using gdb's filtered stream." },
992 { "flush", gdbpy_flush, METH_NOARGS,
993 "Flush gdb's filtered stdout stream." },
994 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
995 "selected_thread () -> gdb.InferiorThread.\n\
996 Return the selected thread object." },
997 { "inferiors", gdbpy_inferiors, METH_NOARGS,
998 "inferiors () -> (gdb.Inferior, ...).\n\
999 Return a tuple containing all inferiors." },
1000 {NULL, NULL, 0, NULL}
1003 #endif /* HAVE_PYTHON */