1 /* General python/gdb code
3 Copyright (C) 2008-2012 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"
31 #include "event-loop.h"
33 #include "readline/tilde.h"
38 /* Declared constants and enum for python stack printing. */
39 static const char python_excp_none[] = "none";
40 static const char python_excp_full[] = "full";
41 static const char python_excp_message[] = "message";
43 /* "set python print-stack" choices. */
44 static const char *python_excp_enums[] =
52 /* The exception printing variable. 'full' if we want to print the
53 error message and stack, 'none' if we want to print nothing, and
54 'message' if we only want to print the error message. 'message' is
56 static const char *gdbpy_should_print_stack = python_excp_message;
60 #include "libiberty.h"
61 #include "cli/cli-decode.h"
65 #include "python-internal.h"
70 #include "gdbthread.h"
74 static PyMethodDef GdbMethods[];
78 /* Some string constants we may wish to use. */
79 PyObject *gdbpy_to_string_cst;
80 PyObject *gdbpy_children_cst;
81 PyObject *gdbpy_display_hint_cst;
82 PyObject *gdbpy_doc_cst;
83 PyObject *gdbpy_enabled_cst;
84 PyObject *gdbpy_value_cst;
86 /* The GdbError exception. */
87 PyObject *gdbpy_gdberror_exc;
89 /* The `gdb.error' base class. */
90 PyObject *gdbpy_gdb_error;
92 /* The `gdb.MemoryError' exception. */
93 PyObject *gdbpy_gdb_memory_error;
95 /* Architecture and language to be used in callbacks from
96 the Python interpreter. */
97 struct gdbarch *python_gdbarch;
98 const struct language_defn *python_language;
100 /* Restore global language and architecture and Python GIL state
101 when leaving the Python interpreter. */
105 PyGILState_STATE state;
106 struct gdbarch *gdbarch;
107 const struct language_defn *language;
108 PyObject *error_type, *error_value, *error_traceback;
112 restore_python_env (void *p)
114 struct python_env *env = (struct python_env *)p;
116 /* Leftover Python error is forbidden by Python Exception Handling. */
117 if (PyErr_Occurred ())
119 /* This order is similar to the one calling error afterwards. */
120 gdbpy_print_stack ();
121 warning (_("internal error: Unhandled Python exception"));
124 PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
126 PyGILState_Release (env->state);
127 python_gdbarch = env->gdbarch;
128 python_language = env->language;
132 /* Called before entering the Python interpreter to install the
133 current language and architecture to be used for Python values. */
136 ensure_python_env (struct gdbarch *gdbarch,
137 const struct language_defn *language)
139 struct python_env *env = xmalloc (sizeof *env);
141 env->state = PyGILState_Ensure ();
142 env->gdbarch = python_gdbarch;
143 env->language = python_language;
145 python_gdbarch = gdbarch;
146 python_language = language;
148 /* Save it and ensure ! PyErr_Occurred () afterwards. */
149 PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
151 return make_cleanup (restore_python_env, env);
154 /* A wrapper around PyRun_SimpleFile. FILENAME is the name of
155 the Python script to run.
157 One of the parameters of PyRun_SimpleFile is a FILE *.
158 The problem is that type FILE is extremely system and compiler
159 dependent. So, unless the Python library has been compiled using
160 the same build environment as GDB, we run the risk of getting
161 a crash due to inconsistencies between the definition used by GDB,
162 and the definition used by Python. A mismatch can very likely
165 There is also the situation where the Python library and GDB
166 are using two different versions of the C runtime library.
167 This is particularly visible on Windows, where few users would
168 build Python themselves (this is no trivial task on this platform),
169 and thus use binaries built by someone else instead. Python,
170 being built with VC, would use one version of the msvcr DLL
171 (Eg. msvcr100.dll), while MinGW uses msvcrt.dll. A FILE *
172 from one runtime does not necessarily operate correctly in
175 To work around this potential issue, we create the FILE object
176 using Python routines, thus making sure that it is compatible
177 with the Python library. */
180 python_run_simple_file (const char *filename)
183 PyObject *python_file;
184 struct cleanup *cleanup;
186 /* Because we have a string for a filename, and are using Python to
187 open the file, we need to expand any tilde in the path first. */
188 full_path = tilde_expand (filename);
189 cleanup = make_cleanup (xfree, full_path);
190 python_file = PyFile_FromString (full_path, "r");
193 do_cleanups (cleanup);
194 gdbpy_print_stack ();
195 error (_("Error while opening file: %s"), full_path);
198 make_cleanup_py_decref (python_file);
199 PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
200 do_cleanups (cleanup);
203 /* Given a command_line, return a command string suitable for passing
204 to Python. Lines in the string are separated by newlines. The
205 return value is allocated using xmalloc and the caller is
206 responsible for freeing it. */
209 compute_python_string (struct command_line *l)
211 struct command_line *iter;
216 for (iter = l; iter; iter = iter->next)
217 size += strlen (iter->line) + 1;
219 script = xmalloc (size + 1);
221 for (iter = l; iter; iter = iter->next)
223 int len = strlen (iter->line);
225 strcpy (&script[here], iter->line);
227 script[here++] = '\n';
233 /* Take a command line structure representing a 'python' command, and
234 evaluate its body using the Python interpreter. */
237 eval_python_from_control_command (struct command_line *cmd)
241 struct cleanup *cleanup;
243 if (cmd->body_count != 1)
244 error (_("Invalid \"python\" block structure."));
246 cleanup = ensure_python_env (get_current_arch (), current_language);
248 script = compute_python_string (cmd->body_list[0]);
249 ret = PyRun_SimpleString (script);
252 error (_("Error while executing Python code."));
254 do_cleanups (cleanup);
257 /* Implementation of the gdb "python" command. */
260 python_command (char *arg, int from_tty)
262 struct cleanup *cleanup;
264 cleanup = ensure_python_env (get_current_arch (), current_language);
266 make_cleanup_restore_integer (&interpreter_async);
267 interpreter_async = 0;
269 while (arg && *arg && isspace (*arg))
273 if (PyRun_SimpleString (arg))
274 error (_("Error while executing Python code."));
278 struct command_line *l = get_command_line (python_control, "");
280 make_cleanup_free_command_lines (&l);
281 execute_control_command_untraced (l);
284 do_cleanups (cleanup);
289 /* Transform a gdb parameters's value into a Python value. May return
290 NULL (and set a Python exception) on error. Helper function for
293 gdbpy_parameter_value (enum var_types type, void *var)
298 case var_string_noescape:
299 case var_optional_filename:
303 char *str = * (char **) var;
307 return PyString_Decode (str, strlen (str), host_charset (), NULL);
318 case var_auto_boolean:
320 enum auto_boolean ab = * (enum auto_boolean *) var;
322 if (ab == AUTO_BOOLEAN_TRUE)
324 else if (ab == AUTO_BOOLEAN_FALSE)
331 if ((* (int *) var) == INT_MAX)
335 return PyLong_FromLong (* (int *) var);
339 unsigned int val = * (unsigned int *) var;
343 return PyLong_FromUnsignedLong (val);
347 return PyErr_Format (PyExc_RuntimeError,
348 _("Programmer error: unhandled type."));
351 /* A Python function which returns a gdb parameter's value as a Python
355 gdbpy_parameter (PyObject *self, PyObject *args)
357 struct cmd_list_element *alias, *prefix, *cmd;
361 volatile struct gdb_exception except;
363 if (! PyArg_ParseTuple (args, "s", &arg))
366 newarg = concat ("show ", arg, (char *) NULL);
368 TRY_CATCH (except, RETURN_MASK_ALL)
370 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
373 GDB_PY_HANDLE_EXCEPTION (except);
375 return PyErr_Format (PyExc_RuntimeError,
376 _("Could not find parameter `%s'."), arg);
379 return PyErr_Format (PyExc_RuntimeError,
380 _("`%s' is not a parameter."), arg);
381 return gdbpy_parameter_value (cmd->var_type, cmd->var);
384 /* Wrapper for target_charset. */
387 gdbpy_target_charset (PyObject *self, PyObject *args)
389 const char *cset = target_charset (python_gdbarch);
391 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
394 /* Wrapper for target_wide_charset. */
397 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
399 const char *cset = target_wide_charset (python_gdbarch);
401 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
404 /* A Python function which evaluates a string using the gdb CLI. */
407 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
410 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
411 int from_tty, to_string;
412 volatile struct gdb_exception except;
413 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
416 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
417 &PyBool_Type, &from_tty_obj,
418 &PyBool_Type, &to_string_obj))
424 int cmp = PyObject_IsTrue (from_tty_obj);
433 int cmp = PyObject_IsTrue (to_string_obj);
439 TRY_CATCH (except, RETURN_MASK_ALL)
441 /* Copy the argument text in case the command modifies it. */
442 char *copy = xstrdup (arg);
443 struct cleanup *cleanup = make_cleanup (xfree, copy);
445 make_cleanup_restore_integer (&interpreter_async);
446 interpreter_async = 0;
448 prevent_dont_repeat ();
450 result = execute_command_to_string (copy, from_tty);
454 execute_command (copy, from_tty);
457 do_cleanups (cleanup);
459 GDB_PY_HANDLE_EXCEPTION (except);
461 /* Do any commands attached to breakpoint we stopped at. */
462 bpstat_do_actions ();
466 PyObject *r = PyString_FromString (result);
473 /* Implementation of gdb.solib_name (Long) -> String.
474 Returns the name of the shared library holding a given address, or None. */
477 gdbpy_solib_name (PyObject *self, PyObject *args)
483 if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
486 soname = solib_name_from_address (current_program_space, pc);
488 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
498 /* A Python function which is a wrapper for decode_line_1. */
501 gdbpy_decode_line (PyObject *self, PyObject *args)
503 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
505 struct symtab_and_line sal;
506 const char *arg = NULL;
508 struct cleanup *cleanups;
509 PyObject *result = NULL;
510 PyObject *return_result = NULL;
511 PyObject *unparsed = NULL;
512 volatile struct gdb_exception except;
514 if (! PyArg_ParseTuple (args, "|s", &arg))
517 cleanups = make_cleanup (null_cleanup, NULL);
519 TRY_CATCH (except, RETURN_MASK_ALL)
523 copy = xstrdup (arg);
524 make_cleanup (xfree, copy);
525 sals = decode_line_1 (©, 0, 0, 0);
526 make_cleanup (xfree, sals.sals);
530 set_default_source_symtab_and_line ();
531 sal = get_current_source_symtab_and_line ();
536 if (except.reason < 0)
538 do_cleanups (cleanups);
539 /* We know this will always throw. */
540 GDB_PY_HANDLE_EXCEPTION (except);
547 result = PyTuple_New (sals.nelts);
550 for (i = 0; i < sals.nelts; ++i)
555 obj = symtab_and_line_to_sal_object (sals.sals[i]);
562 PyTuple_SetItem (result, i, obj);
571 return_result = PyTuple_New (2);
578 if (copy && strlen (copy) > 0)
579 unparsed = PyString_FromString (copy);
586 PyTuple_SetItem (return_result, 0, unparsed);
587 PyTuple_SetItem (return_result, 1, result);
589 do_cleanups (cleanups);
591 return return_result;
594 do_cleanups (cleanups);
598 /* Parse a string and evaluate it as an expression. */
600 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
602 const char *expr_str;
603 struct value *result = NULL;
604 volatile struct gdb_exception except;
606 if (!PyArg_ParseTuple (args, "s", &expr_str))
609 TRY_CATCH (except, RETURN_MASK_ALL)
611 char *copy = xstrdup (expr_str);
612 struct cleanup *cleanup = make_cleanup (xfree, copy);
614 result = parse_and_eval (copy);
615 do_cleanups (cleanup);
617 GDB_PY_HANDLE_EXCEPTION (except);
619 return value_to_value_object (result);
622 /* Read a file as Python code.
623 FILE is the name of the file.
624 This does not throw any errors. If an exception occurs python will print
625 the traceback and clear the error indicator. */
628 source_python_script (const char *file)
630 struct cleanup *cleanup;
632 cleanup = ensure_python_env (get_current_arch (), current_language);
633 python_run_simple_file (file);
634 do_cleanups (cleanup);
639 /* Posting and handling events. */
641 /* A single event. */
644 /* The Python event. This is just a callable object. */
646 /* The next event. */
647 struct gdbpy_event *next;
650 /* All pending events. */
651 static struct gdbpy_event *gdbpy_event_list;
652 /* The final link of the event list. */
653 static struct gdbpy_event **gdbpy_event_list_end;
655 /* We use a file handler, and not an async handler, so that we can
656 wake up the main thread even when it is blocked in poll(). */
657 static struct serial *gdbpy_event_fds[2];
659 /* The file handler callback. This reads from the internal pipe, and
660 then processes the Python event queue. This will always be run in
661 the main gdb thread. */
664 gdbpy_run_events (struct serial *scb, void *context)
666 struct cleanup *cleanup;
669 cleanup = ensure_python_env (get_current_arch (), current_language);
671 /* Flush the fd. Do this before flushing the events list, so that
672 any new event post afterwards is sure to re-awake the event
674 while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
677 while (gdbpy_event_list)
679 /* Dispatching the event might push a new element onto the event
680 loop, so we update here "atomically enough". */
681 struct gdbpy_event *item = gdbpy_event_list;
682 gdbpy_event_list = gdbpy_event_list->next;
683 if (gdbpy_event_list == NULL)
684 gdbpy_event_list_end = &gdbpy_event_list;
687 if (PyObject_CallObject (item->event, NULL) == NULL)
690 Py_DECREF (item->event);
694 do_cleanups (cleanup);
697 /* Submit an event to the gdb thread. */
699 gdbpy_post_event (PyObject *self, PyObject *args)
701 struct gdbpy_event *event;
705 if (!PyArg_ParseTuple (args, "O", &func))
708 if (!PyCallable_Check (func))
710 PyErr_SetString (PyExc_RuntimeError,
711 _("Posted event is not callable"));
717 /* From here until the end of the function, we have the GIL, so we
718 can operate on our global data structures without worrying. */
719 wakeup = gdbpy_event_list == NULL;
721 event = XNEW (struct gdbpy_event);
724 *gdbpy_event_list_end = event;
725 gdbpy_event_list_end = &event->next;
727 /* Wake up gdb when needed. */
730 char c = 'q'; /* Anything. */
732 if (serial_write (gdbpy_event_fds[1], &c, 1))
733 return PyErr_SetFromErrno (PyExc_IOError);
739 /* Initialize the Python event handler. */
741 gdbpy_initialize_events (void)
743 if (serial_pipe (gdbpy_event_fds) == 0)
745 gdbpy_event_list_end = &gdbpy_event_list;
746 serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
753 before_prompt_hook (const char *current_gdb_prompt)
755 struct cleanup *cleanup;
758 cleanup = ensure_python_env (get_current_arch (), current_language);
760 if (PyObject_HasAttrString (gdb_module, "prompt_hook"))
764 hook = PyObject_GetAttrString (gdb_module, "prompt_hook");
768 if (PyCallable_Check (hook))
771 PyObject *current_prompt;
773 current_prompt = PyString_FromString (current_gdb_prompt);
774 if (current_prompt == NULL)
777 result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
779 Py_DECREF (current_prompt);
784 make_cleanup_py_decref (result);
786 /* Return type should be None, or a String. If it is None,
787 fall through, we will not set a prompt. If it is a
788 string, set PROMPT. Anything else, set an exception. */
789 if (result != Py_None && ! PyString_Check (result))
791 PyErr_Format (PyExc_RuntimeError,
792 _("Return from prompt_hook must " \
793 "be either a Python string, or None"));
797 if (result != Py_None)
799 prompt = python_string_to_host_string (result);
804 make_cleanup (xfree, prompt);
809 /* If a prompt has been set, PROMPT will not be NULL. If it is
810 NULL, do not set the prompt. */
814 do_cleanups (cleanup);
818 gdbpy_print_stack ();
819 do_cleanups (cleanup);
827 /* A python function to write a single string using gdb's filtered
828 output stream . The optional keyword STREAM can be used to write
829 to a particular stream. The default stream is to gdb_stdout. */
832 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
835 static char *keywords[] = {"text", "stream", NULL };
838 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
846 fprintf_filtered (gdb_stderr, "%s", arg);
851 fprintf_filtered (gdb_stdlog, "%s", arg);
855 fprintf_filtered (gdb_stdout, "%s", arg);
861 /* A python function to flush a gdb stream. The optional keyword
862 STREAM can be used to flush a particular stream. The default stream
866 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
868 static char *keywords[] = {"stream", NULL };
871 if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
879 gdb_flush (gdb_stderr);
884 gdb_flush (gdb_stdlog);
888 gdb_flush (gdb_stdout);
894 /* Print a python exception trace, print just a message, or print
895 nothing and clear the python exception, depending on
896 gdbpy_should_print_stack. Only call this if a python exception is
899 gdbpy_print_stack (void)
901 /* Print "none", just clear exception. */
902 if (gdbpy_should_print_stack == python_excp_none)
906 /* Print "full" message and backtrace. */
907 else if (gdbpy_should_print_stack == python_excp_full)
910 /* PyErr_Print doesn't necessarily end output with a newline.
911 This works because Python's stdout/stderr is fed through
915 /* Print "message", just error print message. */
918 PyObject *ptype, *pvalue, *ptraceback;
919 char *msg = NULL, *type = NULL;
921 PyErr_Fetch (&ptype, &pvalue, &ptraceback);
923 /* Fetch the error message contained within ptype, pvalue. */
924 msg = gdbpy_exception_to_string (ptype, pvalue);
925 type = gdbpy_obj_to_string (ptype);
928 /* An error occurred computing the string representation of the
930 fprintf_filtered (gdb_stderr,
931 _("Error occurred computing Python error" \
935 fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
940 Py_XDECREF (ptraceback);
947 /* Return the current Progspace.
948 There always is one. */
951 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
955 result = pspace_to_pspace_object (current_program_space);
961 /* Return a sequence holding all the Progspaces. */
964 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
966 struct program_space *ps;
969 list = PyList_New (0);
975 PyObject *item = pspace_to_pspace_object (ps);
977 if (!item || PyList_Append (list, item) == -1)
989 /* The "current" objfile. This is set when gdb detects that a new
990 objfile has been loaded. It is only set for the duration of a call to
991 source_python_script_for_objfile; it is NULL at other times. */
992 static struct objfile *gdbpy_current_objfile;
994 /* Set the current objfile to OBJFILE and then read FILE as Python code.
995 This does not throw any errors. If an exception occurs python will print
996 the traceback and clear the error indicator. */
999 source_python_script_for_objfile (struct objfile *objfile, const char *file)
1001 struct cleanup *cleanups;
1003 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
1004 gdbpy_current_objfile = objfile;
1006 python_run_simple_file (file);
1008 do_cleanups (cleanups);
1009 gdbpy_current_objfile = NULL;
1012 /* Return the current Objfile, or None if there isn't one. */
1015 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1019 if (! gdbpy_current_objfile)
1022 result = objfile_to_objfile_object (gdbpy_current_objfile);
1028 /* Return a sequence holding all the Objfiles. */
1031 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
1033 struct objfile *objf;
1036 list = PyList_New (0);
1042 PyObject *item = objfile_to_objfile_object (objf);
1044 if (!item || PyList_Append (list, item) == -1)
1054 #else /* HAVE_PYTHON */
1056 /* Dummy implementation of the gdb "python" command. */
1059 python_command (char *arg, int from_tty)
1061 while (arg && *arg && isspace (*arg))
1064 error (_("Python scripting is not supported in this copy of GDB."));
1067 struct command_line *l = get_command_line (python_control, "");
1068 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
1070 execute_control_command_untraced (l);
1071 do_cleanups (cleanups);
1076 eval_python_from_control_command (struct command_line *cmd)
1078 error (_("Python scripting is not supported in this copy of GDB."));
1082 source_python_script (const char *file)
1084 throw_error (UNSUPPORTED_ERROR,
1085 _("Python scripting is not supported in this copy of GDB."));
1089 gdbpy_should_stop (struct breakpoint_object *bp_obj)
1091 internal_error (__FILE__, __LINE__,
1092 _("gdbpy_should_stop called when Python scripting is " \
1097 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
1099 internal_error (__FILE__, __LINE__,
1100 _("gdbpy_breakpoint_has_py_cond called when Python " \
1101 "scripting is not supported."));
1104 #endif /* HAVE_PYTHON */
1107 /* Support for "mt set python print-stack on|off" is present in gdb 7.4
1108 to not break Eclipse.
1109 ref: https://bugs.eclipse.org/bugs/show_bug.cgi?id=367788. */
1111 /* Lists for 'maint set python' commands. */
1113 static struct cmd_list_element *maint_set_python_list;
1114 static struct cmd_list_element *maint_show_python_list;
1116 /* Function for use by 'maint set python' prefix command. */
1119 maint_set_python (char *args, int from_tty)
1121 help_list (maint_set_python_list, "maintenance set python ",
1122 class_deprecated, gdb_stdout);
1125 /* Function for use by 'maint show python' prefix command. */
1128 maint_show_python (char *args, int from_tty)
1130 cmd_show_list (maint_show_python_list, from_tty, "");
1133 /* True if we should print the stack when catching a Python error,
1135 static int gdbpy_should_print_stack_deprecated = 0;
1138 set_maint_python_print_stack (char *args, int from_tty,
1139 struct cmd_list_element *e)
1141 if (gdbpy_should_print_stack_deprecated)
1142 gdbpy_should_print_stack = python_excp_full;
1144 gdbpy_should_print_stack = python_excp_none;
1148 show_maint_python_print_stack (struct ui_file *file, int from_tty,
1149 struct cmd_list_element *c, const char *value)
1151 fprintf_filtered (file,
1152 _("The mode of Python stack printing on error is"
1154 gdbpy_should_print_stack == python_excp_full
1160 /* Lists for 'set python' commands. */
1162 static struct cmd_list_element *user_set_python_list;
1163 static struct cmd_list_element *user_show_python_list;
1165 /* Function for use by 'set python' prefix command. */
1168 user_set_python (char *args, int from_tty)
1170 help_list (user_set_python_list, "set python ", all_commands,
1174 /* Function for use by 'show python' prefix command. */
1177 user_show_python (char *args, int from_tty)
1179 cmd_show_list (user_show_python_list, from_tty, "");
1182 /* Initialize the Python code. */
1184 /* Provide a prototype to silence -Wmissing-prototypes. */
1185 extern initialize_file_ftype _initialize_python;
1188 _initialize_python (void)
1191 struct cmd_list_element *cmd;
1193 add_com ("python", class_obscure, python_command,
1196 Evaluate a Python command.\n\
1198 The command can be given as an argument, for instance:\n\
1202 If no argument is given, the following lines are read and used\n\
1203 as the Python commands. Type a line containing \"end\" to indicate\n\
1204 the end of the command.")
1205 #else /* HAVE_PYTHON */
1207 Evaluate a Python command.\n\
1209 Python scripting is not supported in this copy of GDB.\n\
1210 This command is only a placeholder.")
1211 #endif /* HAVE_PYTHON */
1214 add_prefix_cmd ("python", no_class, maint_show_python,
1215 _("Prefix command for python maintenance settings."),
1216 &maint_show_python_list, "maintenance show python ", 0,
1217 &maintenance_show_cmdlist);
1218 add_prefix_cmd ("python", no_class, maint_set_python,
1219 _("Prefix command for python maintenance settings."),
1220 &maint_set_python_list, "maintenance set python ", 0,
1221 &maintenance_set_cmdlist);
1223 add_setshow_boolean_cmd ("print-stack", class_maintenance,
1224 &gdbpy_should_print_stack_deprecated, _("\
1225 Enable or disable printing of Python stack dump on error."), _("\
1226 Show whether Python stack will be printed on error."), _("\
1227 Enables or disables printing of Python stack traces."),
1228 set_maint_python_print_stack,
1229 show_maint_python_print_stack,
1230 &maint_set_python_list,
1231 &maint_show_python_list);
1233 /* Deprecate maint set/show python print-stack in favour of
1234 non-maintenance alternatives. */
1235 cmd_name = "print-stack";
1236 cmd = lookup_cmd (&cmd_name, maint_set_python_list, "", -1, 0);
1237 deprecate_cmd (cmd, "set python print-stack");
1238 cmd_name = "print-stack"; /* Reset name. */
1239 cmd = lookup_cmd (&cmd_name, maint_show_python_list, "", -1, 0);
1240 deprecate_cmd (cmd, "show python print-stack");
1242 /* Add set/show python print-stack. */
1243 add_prefix_cmd ("python", no_class, user_show_python,
1244 _("Prefix command for python preference settings."),
1245 &user_show_python_list, "show python ", 0,
1248 add_prefix_cmd ("python", no_class, user_set_python,
1249 _("Prefix command for python preference settings."),
1250 &user_set_python_list, "set python ", 0,
1253 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1254 &gdbpy_should_print_stack, _("\
1255 Set mode for Python stack dump on error."), _("\
1256 Show the mode of Python stack printing on error."), _("\
1257 none == no stack or message will be printed.\n\
1258 full == a message and a stack will be printed.\n\
1259 message == an error message without a stack will be printed."),
1261 &user_set_python_list,
1262 &user_show_python_list);
1265 #ifdef WITH_PYTHON_PATH
1266 /* Work around problem where python gets confused about where it is,
1267 and then can't find its libraries, etc.
1268 NOTE: Python assumes the following layout:
1270 /foo/lib/pythonX.Y/...
1271 This must be done before calling Py_Initialize. */
1272 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
1273 SLASH_STRING, "python", NULL));
1277 PyEval_InitThreads ();
1279 gdb_module = Py_InitModule ("gdb", GdbMethods);
1281 /* The casts to (char*) are for python 2.4. */
1282 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
1283 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
1284 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1285 (char*) target_name);
1287 /* Add stream constants. */
1288 PyModule_AddIntConstant (gdb_module, "STDOUT", 0);
1289 PyModule_AddIntConstant (gdb_module, "STDERR", 1);
1290 PyModule_AddIntConstant (gdb_module, "STDLOG", 2);
1292 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1293 script below is run (depending on order of _initialize_* functions).
1294 Define the initial value of gdb.PYTHONDIR here. */
1296 char *gdb_pythondir;
1298 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1299 PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
1300 xfree (gdb_pythondir);
1303 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1304 PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error);
1306 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1307 gdbpy_gdb_error, NULL);
1308 PyModule_AddObject (gdb_module, "MemoryError", gdbpy_gdb_memory_error);
1310 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1311 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
1313 gdbpy_initialize_auto_load ();
1314 gdbpy_initialize_values ();
1315 gdbpy_initialize_frames ();
1316 gdbpy_initialize_commands ();
1317 gdbpy_initialize_symbols ();
1318 gdbpy_initialize_symtabs ();
1319 gdbpy_initialize_blocks ();
1320 gdbpy_initialize_functions ();
1321 gdbpy_initialize_parameters ();
1322 gdbpy_initialize_types ();
1323 gdbpy_initialize_pspace ();
1324 gdbpy_initialize_objfile ();
1325 gdbpy_initialize_breakpoints ();
1326 gdbpy_initialize_finishbreakpoints ();
1327 gdbpy_initialize_lazy_string ();
1328 gdbpy_initialize_thread ();
1329 gdbpy_initialize_inferior ();
1330 gdbpy_initialize_events ();
1332 gdbpy_initialize_eventregistry ();
1333 gdbpy_initialize_py_events ();
1334 gdbpy_initialize_event ();
1335 gdbpy_initialize_stop_event ();
1336 gdbpy_initialize_signal_event ();
1337 gdbpy_initialize_breakpoint_event ();
1338 gdbpy_initialize_continue_event ();
1339 gdbpy_initialize_exited_event ();
1340 gdbpy_initialize_thread_event ();
1341 gdbpy_initialize_new_objfile_event () ;
1343 observer_attach_before_prompt (before_prompt_hook);
1345 PyRun_SimpleString ("import gdb");
1346 PyRun_SimpleString ("gdb.pretty_printers = []");
1348 gdbpy_to_string_cst = PyString_FromString ("to_string");
1349 gdbpy_children_cst = PyString_FromString ("children");
1350 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1351 gdbpy_doc_cst = PyString_FromString ("__doc__");
1352 gdbpy_enabled_cst = PyString_FromString ("enabled");
1353 gdbpy_value_cst = PyString_FromString ("value");
1355 /* Release the GIL while gdb runs. */
1356 PyThreadState_Swap (NULL);
1357 PyEval_ReleaseLock ();
1359 #endif /* HAVE_PYTHON */
1364 /* Perform the remaining python initializations.
1365 These must be done after GDB is at least mostly initialized.
1366 E.g., The "info pretty-printer" command needs the "info" prefix
1367 command installed. */
1370 finish_python_initialization (void)
1372 struct cleanup *cleanup;
1374 cleanup = ensure_python_env (get_current_arch (), current_language);
1376 PyRun_SimpleString ("\
1380 class GdbOutputFile:\n\
1385 def isatty(self):\n\
1388 def write(self, s):\n\
1389 gdb.write(s, stream=gdb.STDOUT)\n \
1391 def writelines(self, iterable):\n\
1392 for line in iterable:\n\
1398 sys.stdout = GdbOutputFile()\n\
1400 class GdbOutputErrorFile:\n\
1405 def isatty(self):\n\
1408 def write(self, s):\n\
1409 gdb.write(s, stream=gdb.STDERR)\n \
1411 def writelines(self, iterable):\n\
1412 for line in iterable:\n\
1413 self.write(line)\n \
1418 sys.stderr = GdbOutputErrorFile()\n\
1420 # Ideally this would live in the gdb module, but it's intentionally written\n\
1421 # in python, and we need this to bootstrap the gdb module.\n\
1423 def GdbSetPythonDirectory (dir):\n\
1424 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1425 old_dir = gdb.PYTHONDIR\n\
1426 gdb.PYTHONDIR = dir\n\
1427 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1428 # that directory name at the start of sys.path to allow the Python\n\
1429 # interpreter to find them.\n\
1430 if old_dir in sys.path:\n\
1431 sys.path.remove (old_dir)\n\
1432 sys.path.insert (0, gdb.PYTHONDIR)\n\
1434 # Tell python where to find submodules of gdb.\n\
1435 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1437 # The gdb module is implemented in C rather than in Python. As a result,\n\
1438 # the associated __init.py__ script is not not executed by default when\n\
1439 # the gdb module gets imported. Execute that script manually if it\n\
1441 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1442 if os.path.exists (ipy):\n\
1445 # Install the default gdb.PYTHONDIR.\n\
1446 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1447 # Default prompt hook does nothing.\n\
1448 prompt_hook = None\n\
1451 do_cleanups (cleanup);
1454 #endif /* HAVE_PYTHON */
1460 static PyMethodDef GdbMethods[] =
1462 { "history", gdbpy_history, METH_VARARGS,
1463 "Get a value from history" },
1464 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1465 "Execute a gdb command" },
1466 { "parameter", gdbpy_parameter, METH_VARARGS,
1467 "Return a gdb parameter's value" },
1469 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1470 "Return a tuple of all breakpoint objects" },
1472 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1473 "Find the default visualizer for a Value." },
1475 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1476 "Return the current Progspace." },
1477 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1478 "Return a sequence of all progspaces." },
1480 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1481 "Return the current Objfile being loaded, or None." },
1482 { "objfiles", gdbpy_objfiles, METH_NOARGS,
1483 "Return a sequence of all loaded objfiles." },
1485 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1486 "newest_frame () -> gdb.Frame.\n\
1487 Return the newest frame object." },
1488 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1489 "selected_frame () -> gdb.Frame.\n\
1490 Return the selected frame object." },
1491 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1492 "stop_reason_string (Integer) -> String.\n\
1493 Return a string explaining unwind stop reason." },
1495 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1496 METH_VARARGS | METH_KEYWORDS,
1497 "lookup_type (name [, block]) -> type\n\
1498 Return a Type corresponding to the given name." },
1499 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1500 METH_VARARGS | METH_KEYWORDS,
1501 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1502 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1503 a boolean indicating if name is a field of the current implied argument\n\
1504 `this' (when the current language is object-oriented)." },
1505 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1506 METH_VARARGS | METH_KEYWORDS,
1507 "lookup_global_symbol (name [, domain]) -> symbol\n\
1508 Return the symbol corresponding to the given name (or None)." },
1509 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1510 "Return the block containing the given pc value, or None." },
1511 { "solib_name", gdbpy_solib_name, METH_VARARGS,
1512 "solib_name (Long) -> String.\n\
1513 Return the name of the shared library holding a given address, or None." },
1514 { "decode_line", gdbpy_decode_line, METH_VARARGS,
1515 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1516 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1517 The first element contains any unparsed portion of the String parameter\n\
1518 (or None if the string was fully parsed). The second element contains\n\
1519 a tuple that contains all the locations that match, represented as\n\
1520 gdb.Symtab_and_line objects (or None)."},
1521 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1522 "parse_and_eval (String) -> Value.\n\
1523 Parse String as an expression, evaluate it, and return the result as a Value."
1526 { "post_event", gdbpy_post_event, METH_VARARGS,
1527 "Post an event into gdb's event loop." },
1529 { "target_charset", gdbpy_target_charset, METH_NOARGS,
1530 "target_charset () -> string.\n\
1531 Return the name of the current target charset." },
1532 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1533 "target_wide_charset () -> string.\n\
1534 Return the name of the current target wide charset." },
1536 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1537 "string_to_argv (String) -> Array.\n\
1538 Parse String and return an argv-like array.\n\
1539 Arguments are separate by spaces and may be quoted."
1541 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1542 "Write a string using gdb's filtered stream." },
1543 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1544 "Flush gdb's filtered stdout stream." },
1545 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1546 "selected_thread () -> gdb.InferiorThread.\n\
1547 Return the selected thread object." },
1548 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
1549 "selected_inferior () -> gdb.Inferior.\n\
1550 Return the selected inferior object." },
1551 { "inferiors", gdbpy_inferiors, METH_NOARGS,
1552 "inferiors () -> (gdb.Inferior, ...).\n\
1553 Return a tuple containing all inferiors." },
1554 {NULL, NULL, 0, NULL}
1557 #endif /* HAVE_PYTHON */