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 *const 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[];
77 PyObject *gdb_python_module;
79 /* Some string constants we may wish to use. */
80 PyObject *gdbpy_to_string_cst;
81 PyObject *gdbpy_children_cst;
82 PyObject *gdbpy_display_hint_cst;
83 PyObject *gdbpy_doc_cst;
84 PyObject *gdbpy_enabled_cst;
85 PyObject *gdbpy_value_cst;
87 /* The GdbError exception. */
88 PyObject *gdbpy_gdberror_exc;
90 /* The `gdb.error' base class. */
91 PyObject *gdbpy_gdb_error;
93 /* The `gdb.MemoryError' exception. */
94 PyObject *gdbpy_gdb_memory_error;
96 /* Architecture and language to be used in callbacks from
97 the Python interpreter. */
98 struct gdbarch *python_gdbarch;
99 const struct language_defn *python_language;
101 /* Restore global language and architecture and Python GIL state
102 when leaving the Python interpreter. */
106 PyGILState_STATE state;
107 struct gdbarch *gdbarch;
108 const struct language_defn *language;
109 PyObject *error_type, *error_value, *error_traceback;
113 restore_python_env (void *p)
115 struct python_env *env = (struct python_env *)p;
117 /* Leftover Python error is forbidden by Python Exception Handling. */
118 if (PyErr_Occurred ())
120 /* This order is similar to the one calling error afterwards. */
121 gdbpy_print_stack ();
122 warning (_("internal error: Unhandled Python exception"));
125 PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
127 PyGILState_Release (env->state);
128 python_gdbarch = env->gdbarch;
129 python_language = env->language;
133 /* Called before entering the Python interpreter to install the
134 current language and architecture to be used for Python values. */
137 ensure_python_env (struct gdbarch *gdbarch,
138 const struct language_defn *language)
140 struct python_env *env = xmalloc (sizeof *env);
142 env->state = PyGILState_Ensure ();
143 env->gdbarch = python_gdbarch;
144 env->language = python_language;
146 python_gdbarch = gdbarch;
147 python_language = language;
149 /* Save it and ensure ! PyErr_Occurred () afterwards. */
150 PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
152 return make_cleanup (restore_python_env, env);
155 /* Clear the quit flag. */
158 clear_quit_flag (void)
160 /* This clears the flag as a side effect. */
161 PyOS_InterruptOccurred ();
164 /* Set the quit flag. */
169 PyErr_SetInterrupt ();
172 /* Return true if the quit flag has been set, false otherwise. */
175 check_quit_flag (void)
177 return PyOS_InterruptOccurred ();
180 /* Evaluate a Python command like PyRun_SimpleString, but uses
181 Py_single_input which prints the result of expressions, and does
182 not automatically print the stack on errors. */
185 eval_python_command (const char *command)
189 m = PyImport_AddModule ("__main__");
193 d = PyModule_GetDict (m);
196 v = PyRun_StringFlags (command, Py_single_input, d, d, NULL);
207 /* Implementation of the gdb "python-interactive" command. */
210 python_interactive_command (char *arg, int from_tty)
212 struct cleanup *cleanup;
215 cleanup = make_cleanup_restore_integer (&interpreter_async);
216 interpreter_async = 0;
218 while (arg && *arg && isspace (*arg))
221 ensure_python_env (get_current_arch (), current_language);
225 int len = strlen (arg);
226 char *script = xmalloc (len + 2);
228 strcpy (script, arg);
230 script[len + 1] = '\0';
231 err = eval_python_command (script);
236 err = PyRun_InteractiveLoop (instream, "<stdin>");
242 gdbpy_print_stack ();
243 error (_("Error while executing Python code."));
246 do_cleanups (cleanup);
249 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
252 On Windows hosts few users would build Python themselves (this is no
253 trivial task on this platform), and thus use binaries built by
254 someone else instead. There may happen situation where the Python
255 library and GDB are using two different versions of the C runtime
256 library. Python, being built with VC, would use one version of the
257 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
258 A FILE * from one runtime does not necessarily operate correctly in
261 To work around this potential issue, we create on Windows hosts the
262 FILE object using Python routines, thus making sure that it is
263 compatible with the Python library. */
266 python_run_simple_file (FILE *file, const char *filename)
270 PyRun_SimpleFile (file, filename);
275 PyObject *python_file;
276 struct cleanup *cleanup;
278 /* Because we have a string for a filename, and are using Python to
279 open the file, we need to expand any tilde in the path first. */
280 full_path = tilde_expand (filename);
281 cleanup = make_cleanup (xfree, full_path);
282 python_file = PyFile_FromString (full_path, "r");
285 do_cleanups (cleanup);
286 gdbpy_print_stack ();
287 error (_("Error while opening file: %s"), full_path);
290 make_cleanup_py_decref (python_file);
291 PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
292 do_cleanups (cleanup);
297 /* Given a command_line, return a command string suitable for passing
298 to Python. Lines in the string are separated by newlines. The
299 return value is allocated using xmalloc and the caller is
300 responsible for freeing it. */
303 compute_python_string (struct command_line *l)
305 struct command_line *iter;
310 for (iter = l; iter; iter = iter->next)
311 size += strlen (iter->line) + 1;
313 script = xmalloc (size + 1);
315 for (iter = l; iter; iter = iter->next)
317 int len = strlen (iter->line);
319 strcpy (&script[here], iter->line);
321 script[here++] = '\n';
327 /* Take a command line structure representing a 'python' command, and
328 evaluate its body using the Python interpreter. */
331 eval_python_from_control_command (struct command_line *cmd)
335 struct cleanup *cleanup;
337 if (cmd->body_count != 1)
338 error (_("Invalid \"python\" block structure."));
340 cleanup = ensure_python_env (get_current_arch (), current_language);
342 script = compute_python_string (cmd->body_list[0]);
343 ret = PyRun_SimpleString (script);
346 error (_("Error while executing Python code."));
348 do_cleanups (cleanup);
351 /* Implementation of the gdb "python" command. */
354 python_command (char *arg, int from_tty)
356 struct cleanup *cleanup;
358 cleanup = ensure_python_env (get_current_arch (), current_language);
360 make_cleanup_restore_integer (&interpreter_async);
361 interpreter_async = 0;
363 while (arg && *arg && isspace (*arg))
367 if (PyRun_SimpleString (arg))
368 error (_("Error while executing Python code."));
372 struct command_line *l = get_command_line (python_control, "");
374 make_cleanup_free_command_lines (&l);
375 execute_control_command_untraced (l);
378 do_cleanups (cleanup);
383 /* Transform a gdb parameters's value into a Python value. May return
384 NULL (and set a Python exception) on error. Helper function for
387 gdbpy_parameter_value (enum var_types type, void *var)
392 case var_string_noescape:
393 case var_optional_filename:
397 char *str = * (char **) var;
401 return PyString_Decode (str, strlen (str), host_charset (), NULL);
412 case var_auto_boolean:
414 enum auto_boolean ab = * (enum auto_boolean *) var;
416 if (ab == AUTO_BOOLEAN_TRUE)
418 else if (ab == AUTO_BOOLEAN_FALSE)
425 if ((* (int *) var) == INT_MAX)
429 return PyLong_FromLong (* (int *) var);
433 unsigned int val = * (unsigned int *) var;
437 return PyLong_FromUnsignedLong (val);
441 return PyErr_Format (PyExc_RuntimeError,
442 _("Programmer error: unhandled type."));
445 /* A Python function which returns a gdb parameter's value as a Python
449 gdbpy_parameter (PyObject *self, PyObject *args)
451 struct cmd_list_element *alias, *prefix, *cmd;
455 volatile struct gdb_exception except;
457 if (! PyArg_ParseTuple (args, "s", &arg))
460 newarg = concat ("show ", arg, (char *) NULL);
462 TRY_CATCH (except, RETURN_MASK_ALL)
464 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
467 GDB_PY_HANDLE_EXCEPTION (except);
469 return PyErr_Format (PyExc_RuntimeError,
470 _("Could not find parameter `%s'."), arg);
473 return PyErr_Format (PyExc_RuntimeError,
474 _("`%s' is not a parameter."), arg);
475 return gdbpy_parameter_value (cmd->var_type, cmd->var);
478 /* Wrapper for target_charset. */
481 gdbpy_target_charset (PyObject *self, PyObject *args)
483 const char *cset = target_charset (python_gdbarch);
485 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
488 /* Wrapper for target_wide_charset. */
491 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
493 const char *cset = target_wide_charset (python_gdbarch);
495 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
498 /* A Python function which evaluates a string using the gdb CLI. */
501 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
504 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
505 int from_tty, to_string;
506 volatile struct gdb_exception except;
507 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
510 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
511 &PyBool_Type, &from_tty_obj,
512 &PyBool_Type, &to_string_obj))
518 int cmp = PyObject_IsTrue (from_tty_obj);
527 int cmp = PyObject_IsTrue (to_string_obj);
533 TRY_CATCH (except, RETURN_MASK_ALL)
535 /* Copy the argument text in case the command modifies it. */
536 char *copy = xstrdup (arg);
537 struct cleanup *cleanup = make_cleanup (xfree, copy);
539 make_cleanup_restore_integer (&interpreter_async);
540 interpreter_async = 0;
542 prevent_dont_repeat ();
544 result = execute_command_to_string (copy, from_tty);
548 execute_command (copy, from_tty);
551 do_cleanups (cleanup);
553 GDB_PY_HANDLE_EXCEPTION (except);
555 /* Do any commands attached to breakpoint we stopped at. */
556 bpstat_do_actions ();
560 PyObject *r = PyString_FromString (result);
567 /* Implementation of gdb.solib_name (Long) -> String.
568 Returns the name of the shared library holding a given address, or None. */
571 gdbpy_solib_name (PyObject *self, PyObject *args)
577 if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
580 soname = solib_name_from_address (current_program_space, pc);
582 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
592 /* A Python function which is a wrapper for decode_line_1. */
595 gdbpy_decode_line (PyObject *self, PyObject *args)
597 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
599 struct symtab_and_line sal;
600 const char *arg = NULL;
601 char *copy_to_free = NULL, *copy = NULL;
602 struct cleanup *cleanups;
603 PyObject *result = NULL;
604 PyObject *return_result = NULL;
605 PyObject *unparsed = NULL;
606 volatile struct gdb_exception except;
608 if (! PyArg_ParseTuple (args, "|s", &arg))
611 cleanups = make_cleanup (null_cleanup, NULL);
614 TRY_CATCH (except, RETURN_MASK_ALL)
618 copy = xstrdup (arg);
620 sals = decode_line_1 (©, 0, 0, 0);
624 set_default_source_symtab_and_line ();
625 sal = get_current_source_symtab_and_line ();
631 if (sals.sals != NULL && sals.sals != &sal)
633 make_cleanup (xfree, copy_to_free);
634 make_cleanup (xfree, sals.sals);
637 if (except.reason < 0)
639 do_cleanups (cleanups);
640 /* We know this will always throw. */
641 GDB_PY_HANDLE_EXCEPTION (except);
648 result = PyTuple_New (sals.nelts);
651 for (i = 0; i < sals.nelts; ++i)
655 obj = symtab_and_line_to_sal_object (sals.sals[i]);
662 PyTuple_SetItem (result, i, obj);
671 return_result = PyTuple_New (2);
678 if (copy && strlen (copy) > 0)
680 unparsed = PyString_FromString (copy);
681 if (unparsed == NULL)
684 Py_DECREF (return_result);
685 return_result = NULL;
695 PyTuple_SetItem (return_result, 0, unparsed);
696 PyTuple_SetItem (return_result, 1, result);
699 do_cleanups (cleanups);
701 return return_result;
704 /* Parse a string and evaluate it as an expression. */
706 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
708 const char *expr_str;
709 struct value *result = NULL;
710 volatile struct gdb_exception except;
712 if (!PyArg_ParseTuple (args, "s", &expr_str))
715 TRY_CATCH (except, RETURN_MASK_ALL)
717 char *copy = xstrdup (expr_str);
718 struct cleanup *cleanup = make_cleanup (xfree, copy);
720 result = parse_and_eval (copy);
721 do_cleanups (cleanup);
723 GDB_PY_HANDLE_EXCEPTION (except);
725 return value_to_value_object (result);
728 /* Implementation of gdb.find_pc_line function.
729 Returns the gdb.Symtab_and_line object corresponding to a PC value. */
732 gdbpy_find_pc_line (PyObject *self, PyObject *args)
734 struct symtab_and_line sal;
736 gdb_py_ulongest pc_llu;
738 if (!PyArg_ParseTuple (args, GDB_PY_LLU_ARG, &pc_llu))
741 pc = (CORE_ADDR) pc_llu;
742 sal = find_pc_line (pc, 0);
743 return symtab_and_line_to_sal_object (sal);
746 /* Read a file as Python code.
747 FILE is the file to run. FILENAME is name of the file FILE.
748 This does not throw any errors. If an exception occurs python will print
749 the traceback and clear the error indicator. */
752 source_python_script (FILE *file, const char *filename)
754 struct cleanup *cleanup;
756 cleanup = ensure_python_env (get_current_arch (), current_language);
757 python_run_simple_file (file, filename);
758 do_cleanups (cleanup);
763 /* Posting and handling events. */
765 /* A single event. */
768 /* The Python event. This is just a callable object. */
770 /* The next event. */
771 struct gdbpy_event *next;
774 /* All pending events. */
775 static struct gdbpy_event *gdbpy_event_list;
776 /* The final link of the event list. */
777 static struct gdbpy_event **gdbpy_event_list_end;
779 /* We use a file handler, and not an async handler, so that we can
780 wake up the main thread even when it is blocked in poll(). */
781 static struct serial *gdbpy_event_fds[2];
783 /* The file handler callback. This reads from the internal pipe, and
784 then processes the Python event queue. This will always be run in
785 the main gdb thread. */
788 gdbpy_run_events (struct serial *scb, void *context)
790 struct cleanup *cleanup;
792 cleanup = ensure_python_env (get_current_arch (), current_language);
794 /* Flush the fd. Do this before flushing the events list, so that
795 any new event post afterwards is sure to re-awake the event
797 while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
800 while (gdbpy_event_list)
802 /* Dispatching the event might push a new element onto the event
803 loop, so we update here "atomically enough". */
804 struct gdbpy_event *item = gdbpy_event_list;
805 gdbpy_event_list = gdbpy_event_list->next;
806 if (gdbpy_event_list == NULL)
807 gdbpy_event_list_end = &gdbpy_event_list;
810 if (PyObject_CallObject (item->event, NULL) == NULL)
813 Py_DECREF (item->event);
817 do_cleanups (cleanup);
820 /* Submit an event to the gdb thread. */
822 gdbpy_post_event (PyObject *self, PyObject *args)
824 struct gdbpy_event *event;
828 if (!PyArg_ParseTuple (args, "O", &func))
831 if (!PyCallable_Check (func))
833 PyErr_SetString (PyExc_RuntimeError,
834 _("Posted event is not callable"));
840 /* From here until the end of the function, we have the GIL, so we
841 can operate on our global data structures without worrying. */
842 wakeup = gdbpy_event_list == NULL;
844 event = XNEW (struct gdbpy_event);
847 *gdbpy_event_list_end = event;
848 gdbpy_event_list_end = &event->next;
850 /* Wake up gdb when needed. */
853 char c = 'q'; /* Anything. */
855 if (serial_write (gdbpy_event_fds[1], &c, 1))
856 return PyErr_SetFromErrno (PyExc_IOError);
862 /* Initialize the Python event handler. */
864 gdbpy_initialize_events (void)
866 if (serial_pipe (gdbpy_event_fds) == 0)
868 gdbpy_event_list_end = &gdbpy_event_list;
869 serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
876 before_prompt_hook (const char *current_gdb_prompt)
878 struct cleanup *cleanup;
881 cleanup = ensure_python_env (get_current_arch (), current_language);
883 if (gdb_python_module
884 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
888 hook = PyObject_GetAttrString (gdb_python_module, "prompt_hook");
892 if (PyCallable_Check (hook))
895 PyObject *current_prompt;
897 current_prompt = PyString_FromString (current_gdb_prompt);
898 if (current_prompt == NULL)
901 result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
903 Py_DECREF (current_prompt);
908 make_cleanup_py_decref (result);
910 /* Return type should be None, or a String. If it is None,
911 fall through, we will not set a prompt. If it is a
912 string, set PROMPT. Anything else, set an exception. */
913 if (result != Py_None && ! PyString_Check (result))
915 PyErr_Format (PyExc_RuntimeError,
916 _("Return from prompt_hook must " \
917 "be either a Python string, or None"));
921 if (result != Py_None)
923 prompt = python_string_to_host_string (result);
928 make_cleanup (xfree, prompt);
933 /* If a prompt has been set, PROMPT will not be NULL. If it is
934 NULL, do not set the prompt. */
938 do_cleanups (cleanup);
942 gdbpy_print_stack ();
943 do_cleanups (cleanup);
951 /* A python function to write a single string using gdb's filtered
952 output stream . The optional keyword STREAM can be used to write
953 to a particular stream. The default stream is to gdb_stdout. */
956 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
959 static char *keywords[] = {"text", "stream", NULL };
961 volatile struct gdb_exception except;
963 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
967 TRY_CATCH (except, RETURN_MASK_ALL)
973 fprintf_filtered (gdb_stderr, "%s", arg);
978 fprintf_filtered (gdb_stdlog, "%s", arg);
982 fprintf_filtered (gdb_stdout, "%s", arg);
985 GDB_PY_HANDLE_EXCEPTION (except);
990 /* A python function to flush a gdb stream. The optional keyword
991 STREAM can be used to flush a particular stream. The default stream
995 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
997 static char *keywords[] = {"stream", NULL };
1000 if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1004 switch (stream_type)
1008 gdb_flush (gdb_stderr);
1013 gdb_flush (gdb_stdlog);
1017 gdb_flush (gdb_stdout);
1023 /* Print a python exception trace, print just a message, or print
1024 nothing and clear the python exception, depending on
1025 gdbpy_should_print_stack. Only call this if a python exception is
1028 gdbpy_print_stack (void)
1030 /* Print "none", just clear exception. */
1031 if (gdbpy_should_print_stack == python_excp_none)
1035 /* Print "full" message and backtrace. */
1036 else if (gdbpy_should_print_stack == python_excp_full)
1039 /* PyErr_Print doesn't necessarily end output with a newline.
1040 This works because Python's stdout/stderr is fed through
1044 /* Print "message", just error print message. */
1047 PyObject *ptype, *pvalue, *ptraceback;
1048 char *msg = NULL, *type = NULL;
1050 PyErr_Fetch (&ptype, &pvalue, &ptraceback);
1052 /* Fetch the error message contained within ptype, pvalue. */
1053 msg = gdbpy_exception_to_string (ptype, pvalue);
1054 type = gdbpy_obj_to_string (ptype);
1057 /* An error occurred computing the string representation of the
1059 fprintf_filtered (gdb_stderr,
1060 _("Error occurred computing Python error" \
1064 fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
1068 Py_XDECREF (pvalue);
1069 Py_XDECREF (ptraceback);
1076 /* Return the current Progspace.
1077 There always is one. */
1080 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
1084 result = pspace_to_pspace_object (current_program_space);
1090 /* Return a sequence holding all the Progspaces. */
1093 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1095 struct program_space *ps;
1098 list = PyList_New (0);
1104 PyObject *item = pspace_to_pspace_object (ps);
1106 if (!item || PyList_Append (list, item) == -1)
1118 /* The "current" objfile. This is set when gdb detects that a new
1119 objfile has been loaded. It is only set for the duration of a call to
1120 source_python_script_for_objfile; it is NULL at other times. */
1121 static struct objfile *gdbpy_current_objfile;
1123 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1124 as Python code. This does not throw any errors. If an exception
1125 occurs python will print the traceback and clear the error indicator. */
1128 source_python_script_for_objfile (struct objfile *objfile, FILE *file,
1129 const char *filename)
1131 struct cleanup *cleanups;
1133 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
1134 gdbpy_current_objfile = objfile;
1136 python_run_simple_file (file, filename);
1138 do_cleanups (cleanups);
1139 gdbpy_current_objfile = NULL;
1142 /* Return the current Objfile, or None if there isn't one. */
1145 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1149 if (! gdbpy_current_objfile)
1152 result = objfile_to_objfile_object (gdbpy_current_objfile);
1158 /* Return a sequence holding all the Objfiles. */
1161 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
1163 struct objfile *objf;
1166 list = PyList_New (0);
1172 PyObject *item = objfile_to_objfile_object (objf);
1174 if (!item || PyList_Append (list, item) == -1)
1184 #else /* HAVE_PYTHON */
1186 /* Dummy implementation of the gdb "python-interactive" and "python"
1190 python_interactive_command (char *arg, int from_tty)
1192 while (arg && *arg && isspace (*arg))
1195 error (_("Python scripting is not supported in this copy of GDB."));
1198 struct command_line *l = get_command_line (python_control, "");
1199 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
1201 execute_control_command_untraced (l);
1202 do_cleanups (cleanups);
1207 python_command (char *arg, int from_tty)
1209 python_interactive_command (arg, from_tty);
1213 eval_python_from_control_command (struct command_line *cmd)
1215 error (_("Python scripting is not supported in this copy of GDB."));
1219 source_python_script (FILE *file, const char *filename)
1221 throw_error (UNSUPPORTED_ERROR,
1222 _("Python scripting is not supported in this copy of GDB."));
1226 gdbpy_should_stop (struct breakpoint_object *bp_obj)
1228 internal_error (__FILE__, __LINE__,
1229 _("gdbpy_should_stop called when Python scripting is " \
1234 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
1236 internal_error (__FILE__, __LINE__,
1237 _("gdbpy_breakpoint_has_py_cond called when Python " \
1238 "scripting is not supported."));
1241 #endif /* HAVE_PYTHON */
1245 /* Lists for 'set python' commands. */
1247 static struct cmd_list_element *user_set_python_list;
1248 static struct cmd_list_element *user_show_python_list;
1250 /* Function for use by 'set python' prefix command. */
1253 user_set_python (char *args, int from_tty)
1255 help_list (user_set_python_list, "set python ", all_commands,
1259 /* Function for use by 'show python' prefix command. */
1262 user_show_python (char *args, int from_tty)
1264 cmd_show_list (user_show_python_list, from_tty, "");
1267 /* Initialize the Python code. */
1269 /* Provide a prototype to silence -Wmissing-prototypes. */
1270 extern initialize_file_ftype _initialize_python;
1273 _initialize_python (void)
1276 struct cmd_list_element *cmd;
1278 add_com ("python-interactive", class_obscure,
1279 python_interactive_command,
1282 Start an interactive Python prompt.\n\
1284 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1287 Alternatively, a single-line Python command can be given as an\n\
1288 argument, and if the command is an expression, the result will be\n\
1289 printed. For example:\n\
1291 (gdb) python-interactive 2 + 3\n\
1294 #else /* HAVE_PYTHON */
1296 Start a Python interactive prompt.\n\
1298 Python scripting is not supported in this copy of GDB.\n\
1299 This command is only a placeholder.")
1300 #endif /* HAVE_PYTHON */
1302 add_com_alias ("pi", "python-interactive", class_obscure, 1);
1304 add_com ("python", class_obscure, python_command,
1307 Evaluate a Python command.\n\
1309 The command can be given as an argument, for instance:\n\
1313 If no argument is given, the following lines are read and used\n\
1314 as the Python commands. Type a line containing \"end\" to indicate\n\
1315 the end of the command.")
1316 #else /* HAVE_PYTHON */
1318 Evaluate a Python command.\n\
1320 Python scripting is not supported in this copy of GDB.\n\
1321 This command is only a placeholder.")
1322 #endif /* HAVE_PYTHON */
1324 add_com_alias ("py", "python", class_obscure, 1);
1326 /* Add set/show python print-stack. */
1327 add_prefix_cmd ("python", no_class, user_show_python,
1328 _("Prefix command for python preference settings."),
1329 &user_show_python_list, "show python ", 0,
1332 add_prefix_cmd ("python", no_class, user_set_python,
1333 _("Prefix command for python preference settings."),
1334 &user_set_python_list, "set python ", 0,
1337 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1338 &gdbpy_should_print_stack, _("\
1339 Set mode for Python stack dump on error."), _("\
1340 Show the mode of Python stack printing on error."), _("\
1341 none == no stack or message will be printed.\n\
1342 full == a message and a stack will be printed.\n\
1343 message == an error message without a stack will be printed."),
1345 &user_set_python_list,
1346 &user_show_python_list);
1349 #ifdef WITH_PYTHON_PATH
1350 /* Work around problem where python gets confused about where it is,
1351 and then can't find its libraries, etc.
1352 NOTE: Python assumes the following layout:
1354 /foo/lib/pythonX.Y/...
1355 This must be done before calling Py_Initialize. */
1356 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
1357 SLASH_STRING, "python", NULL));
1361 PyEval_InitThreads ();
1363 gdb_module = Py_InitModule ("_gdb", GdbMethods);
1365 /* The casts to (char*) are for python 2.4. */
1366 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
1367 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
1368 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1369 (char*) target_name);
1371 /* Add stream constants. */
1372 PyModule_AddIntConstant (gdb_module, "STDOUT", 0);
1373 PyModule_AddIntConstant (gdb_module, "STDERR", 1);
1374 PyModule_AddIntConstant (gdb_module, "STDLOG", 2);
1376 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1377 PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error);
1379 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1380 gdbpy_gdb_error, NULL);
1381 PyModule_AddObject (gdb_module, "MemoryError", gdbpy_gdb_memory_error);
1383 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1384 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
1386 gdbpy_initialize_gdb_readline ();
1387 gdbpy_initialize_auto_load ();
1388 gdbpy_initialize_values ();
1389 gdbpy_initialize_frames ();
1390 gdbpy_initialize_commands ();
1391 gdbpy_initialize_symbols ();
1392 gdbpy_initialize_symtabs ();
1393 gdbpy_initialize_blocks ();
1394 gdbpy_initialize_functions ();
1395 gdbpy_initialize_parameters ();
1396 gdbpy_initialize_types ();
1397 gdbpy_initialize_pspace ();
1398 gdbpy_initialize_objfile ();
1399 gdbpy_initialize_breakpoints ();
1400 gdbpy_initialize_finishbreakpoints ();
1401 gdbpy_initialize_lazy_string ();
1402 gdbpy_initialize_thread ();
1403 gdbpy_initialize_inferior ();
1404 gdbpy_initialize_events ();
1406 gdbpy_initialize_eventregistry ();
1407 gdbpy_initialize_py_events ();
1408 gdbpy_initialize_event ();
1409 gdbpy_initialize_stop_event ();
1410 gdbpy_initialize_signal_event ();
1411 gdbpy_initialize_breakpoint_event ();
1412 gdbpy_initialize_continue_event ();
1413 gdbpy_initialize_exited_event ();
1414 gdbpy_initialize_thread_event ();
1415 gdbpy_initialize_new_objfile_event () ;
1417 observer_attach_before_prompt (before_prompt_hook);
1419 gdbpy_to_string_cst = PyString_FromString ("to_string");
1420 gdbpy_children_cst = PyString_FromString ("children");
1421 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1422 gdbpy_doc_cst = PyString_FromString ("__doc__");
1423 gdbpy_enabled_cst = PyString_FromString ("enabled");
1424 gdbpy_value_cst = PyString_FromString ("value");
1426 /* Release the GIL while gdb runs. */
1427 PyThreadState_Swap (NULL);
1428 PyEval_ReleaseLock ();
1430 #endif /* HAVE_PYTHON */
1435 /* Perform the remaining python initializations.
1436 These must be done after GDB is at least mostly initialized.
1437 E.g., The "info pretty-printer" command needs the "info" prefix
1438 command installed. */
1441 finish_python_initialization (void)
1444 char *gdb_pythondir;
1446 struct cleanup *cleanup;
1448 cleanup = ensure_python_env (get_current_arch (), current_language);
1450 /* Add the initial data-directory to sys.path. */
1452 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1453 make_cleanup (xfree, gdb_pythondir);
1455 sys_path = PySys_GetObject ("path");
1457 if (sys_path && PyList_Check (sys_path))
1459 PyObject *pythondir;
1462 pythondir = PyString_FromString (gdb_pythondir);
1463 if (pythondir == NULL)
1466 err = PyList_Insert (sys_path, 0, pythondir);
1470 Py_DECREF (pythondir);
1473 PySys_SetPath (gdb_pythondir);
1475 /* Import the gdb module to finish the initialization, and
1476 add it to __main__ for convenience. */
1477 m = PyImport_AddModule ("__main__");
1481 gdb_python_module = PyImport_ImportModule ("gdb");
1482 if (gdb_python_module == NULL)
1484 gdbpy_print_stack ();
1485 warning (_("Could not load the Python gdb module from `%s'."),
1487 warning (_("Limited Python support is available from the _gdb module."));
1488 do_cleanups (cleanup);
1492 if (PyModule_AddObject (m, "gdb", gdb_python_module))
1495 /* Keep the reference to gdb_python_module since it is in a global
1498 do_cleanups (cleanup);
1502 gdbpy_print_stack ();
1503 warning (_("internal error: Unhandled Python exception"));
1504 do_cleanups (cleanup);
1507 #endif /* HAVE_PYTHON */
1513 static PyMethodDef GdbMethods[] =
1515 { "history", gdbpy_history, METH_VARARGS,
1516 "Get a value from history" },
1517 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1518 "Execute a gdb command" },
1519 { "parameter", gdbpy_parameter, METH_VARARGS,
1520 "Return a gdb parameter's value" },
1522 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1523 "Return a tuple of all breakpoint objects" },
1525 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1526 "Find the default visualizer for a Value." },
1528 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1529 "Return the current Progspace." },
1530 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1531 "Return a sequence of all progspaces." },
1533 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1534 "Return the current Objfile being loaded, or None." },
1535 { "objfiles", gdbpy_objfiles, METH_NOARGS,
1536 "Return a sequence of all loaded objfiles." },
1538 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1539 "newest_frame () -> gdb.Frame.\n\
1540 Return the newest frame object." },
1541 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1542 "selected_frame () -> gdb.Frame.\n\
1543 Return the selected frame object." },
1544 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1545 "stop_reason_string (Integer) -> String.\n\
1546 Return a string explaining unwind stop reason." },
1548 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1549 METH_VARARGS | METH_KEYWORDS,
1550 "lookup_type (name [, block]) -> type\n\
1551 Return a Type corresponding to the given name." },
1552 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1553 METH_VARARGS | METH_KEYWORDS,
1554 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1555 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1556 a boolean indicating if name is a field of the current implied argument\n\
1557 `this' (when the current language is object-oriented)." },
1558 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1559 METH_VARARGS | METH_KEYWORDS,
1560 "lookup_global_symbol (name [, domain]) -> symbol\n\
1561 Return the symbol corresponding to the given name (or None)." },
1562 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1563 "Return the block containing the given pc value, or None." },
1564 { "solib_name", gdbpy_solib_name, METH_VARARGS,
1565 "solib_name (Long) -> String.\n\
1566 Return the name of the shared library holding a given address, or None." },
1567 { "decode_line", gdbpy_decode_line, METH_VARARGS,
1568 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1569 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1570 The first element contains any unparsed portion of the String parameter\n\
1571 (or None if the string was fully parsed). The second element contains\n\
1572 a tuple that contains all the locations that match, represented as\n\
1573 gdb.Symtab_and_line objects (or None)."},
1574 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1575 "parse_and_eval (String) -> Value.\n\
1576 Parse String as an expression, evaluate it, and return the result as a Value."
1578 { "find_pc_line", gdbpy_find_pc_line, METH_VARARGS,
1579 "find_pc_line (pc) -> Symtab_and_line.\n\
1580 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1582 { "post_event", gdbpy_post_event, METH_VARARGS,
1583 "Post an event into gdb's event loop." },
1585 { "target_charset", gdbpy_target_charset, METH_NOARGS,
1586 "target_charset () -> string.\n\
1587 Return the name of the current target charset." },
1588 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1589 "target_wide_charset () -> string.\n\
1590 Return the name of the current target wide charset." },
1592 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1593 "string_to_argv (String) -> Array.\n\
1594 Parse String and return an argv-like array.\n\
1595 Arguments are separate by spaces and may be quoted."
1597 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1598 "Write a string using gdb's filtered stream." },
1599 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1600 "Flush gdb's filtered stdout stream." },
1601 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1602 "selected_thread () -> gdb.InferiorThread.\n\
1603 Return the selected thread object." },
1604 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
1605 "selected_inferior () -> gdb.Inferior.\n\
1606 Return the selected inferior object." },
1607 { "inferiors", gdbpy_inferiors, METH_NOARGS,
1608 "inferiors () -> (gdb.Inferior, ...).\n\
1609 Return a tuple containing all inferiors." },
1610 {NULL, NULL, 0, NULL}
1613 #endif /* HAVE_PYTHON */