1 /* General python/gdb code
3 Copyright (C) 2008, 2009, 2010, 2011 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"
37 /* True if we should print the stack when catching a Python error,
39 static int gdbpy_should_print_stack = 0;
43 #include "libiberty.h"
44 #include "cli/cli-decode.h"
48 #include "python-internal.h"
53 #include "gdbthread.h"
56 static PyMethodDef GdbMethods[];
60 /* Some string constants we may wish to use. */
61 PyObject *gdbpy_to_string_cst;
62 PyObject *gdbpy_children_cst;
63 PyObject *gdbpy_display_hint_cst;
64 PyObject *gdbpy_doc_cst;
65 PyObject *gdbpy_enabled_cst;
66 PyObject *gdbpy_value_cst;
68 /* The GdbError exception. */
69 PyObject *gdbpy_gdberror_exc;
71 /* The `gdb.error' base class. */
72 PyObject *gdbpy_gdb_error;
74 /* The `gdb.MemoryError' exception. */
75 PyObject *gdbpy_gdb_memory_error;
77 /* Architecture and language to be used in callbacks from
78 the Python interpreter. */
79 struct gdbarch *python_gdbarch;
80 const struct language_defn *python_language;
82 /* Restore global language and architecture and Python GIL state
83 when leaving the Python interpreter. */
87 PyGILState_STATE state;
88 struct gdbarch *gdbarch;
89 const struct language_defn *language;
90 PyObject *error_type, *error_value, *error_traceback;
94 restore_python_env (void *p)
96 struct python_env *env = (struct python_env *)p;
98 /* Leftover Python error is forbidden by Python Exception Handling. */
99 if (PyErr_Occurred ())
101 /* This order is similar to the one calling error afterwards. */
102 gdbpy_print_stack ();
103 warning (_("internal error: Unhandled Python exception"));
106 PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
108 PyGILState_Release (env->state);
109 python_gdbarch = env->gdbarch;
110 python_language = env->language;
114 /* Called before entering the Python interpreter to install the
115 current language and architecture to be used for Python values. */
118 ensure_python_env (struct gdbarch *gdbarch,
119 const struct language_defn *language)
121 struct python_env *env = xmalloc (sizeof *env);
123 env->state = PyGILState_Ensure ();
124 env->gdbarch = python_gdbarch;
125 env->language = python_language;
127 python_gdbarch = gdbarch;
128 python_language = language;
130 /* Save it and ensure ! PyErr_Occurred () afterwards. */
131 PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
133 return make_cleanup (restore_python_env, env);
137 /* Given a command_line, return a command string suitable for passing
138 to Python. Lines in the string are separated by newlines. The
139 return value is allocated using xmalloc and the caller is
140 responsible for freeing it. */
143 compute_python_string (struct command_line *l)
145 struct command_line *iter;
150 for (iter = l; iter; iter = iter->next)
151 size += strlen (iter->line) + 1;
153 script = xmalloc (size + 1);
155 for (iter = l; iter; iter = iter->next)
157 int len = strlen (iter->line);
159 strcpy (&script[here], iter->line);
161 script[here++] = '\n';
167 /* Take a command line structure representing a 'python' command, and
168 evaluate its body using the Python interpreter. */
171 eval_python_from_control_command (struct command_line *cmd)
175 struct cleanup *cleanup;
177 if (cmd->body_count != 1)
178 error (_("Invalid \"python\" block structure."));
180 cleanup = ensure_python_env (get_current_arch (), current_language);
182 script = compute_python_string (cmd->body_list[0]);
183 ret = PyRun_SimpleString (script);
187 gdbpy_print_stack ();
188 error (_("Error while executing Python code."));
191 do_cleanups (cleanup);
194 /* Implementation of the gdb "python" command. */
197 python_command (char *arg, int from_tty)
199 struct cleanup *cleanup;
201 cleanup = ensure_python_env (get_current_arch (), current_language);
202 while (arg && *arg && isspace (*arg))
206 if (PyRun_SimpleString (arg))
208 gdbpy_print_stack ();
209 error (_("Error while executing Python code."));
214 struct command_line *l = get_command_line (python_control, "");
216 make_cleanup_free_command_lines (&l);
217 execute_control_command_untraced (l);
220 do_cleanups (cleanup);
225 /* Transform a gdb parameters's value into a Python value. May return
226 NULL (and set a Python exception) on error. Helper function for
229 gdbpy_parameter_value (enum var_types type, void *var)
234 case var_string_noescape:
235 case var_optional_filename:
239 char *str = * (char **) var;
243 return PyString_Decode (str, strlen (str), host_charset (), NULL);
254 case var_auto_boolean:
256 enum auto_boolean ab = * (enum auto_boolean *) var;
258 if (ab == AUTO_BOOLEAN_TRUE)
260 else if (ab == AUTO_BOOLEAN_FALSE)
267 if ((* (int *) var) == INT_MAX)
271 return PyLong_FromLong (* (int *) var);
275 unsigned int val = * (unsigned int *) var;
279 return PyLong_FromUnsignedLong (val);
283 return PyErr_Format (PyExc_RuntimeError,
284 _("Programmer error: unhandled type."));
287 /* A Python function which returns a gdb parameter's value as a Python
291 gdbpy_parameter (PyObject *self, PyObject *args)
293 struct cmd_list_element *alias, *prefix, *cmd;
297 volatile struct gdb_exception except;
299 if (! PyArg_ParseTuple (args, "s", &arg))
302 newarg = concat ("show ", arg, (char *) NULL);
304 TRY_CATCH (except, RETURN_MASK_ALL)
306 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
309 GDB_PY_HANDLE_EXCEPTION (except);
311 return PyErr_Format (PyExc_RuntimeError,
312 _("Could not find parameter `%s'."), arg);
315 return PyErr_Format (PyExc_RuntimeError,
316 _("`%s' is not a parameter."), arg);
317 return gdbpy_parameter_value (cmd->var_type, cmd->var);
320 /* Wrapper for target_charset. */
323 gdbpy_target_charset (PyObject *self, PyObject *args)
325 const char *cset = target_charset (python_gdbarch);
327 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
330 /* Wrapper for target_wide_charset. */
333 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
335 const char *cset = target_wide_charset (python_gdbarch);
337 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
340 /* A Python function which evaluates a string using the gdb CLI. */
343 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
346 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
347 int from_tty, to_string;
348 volatile struct gdb_exception except;
349 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
352 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
353 &PyBool_Type, &from_tty_obj,
354 &PyBool_Type, &to_string_obj))
360 int cmp = PyObject_IsTrue (from_tty_obj);
369 int cmp = PyObject_IsTrue (to_string_obj);
375 TRY_CATCH (except, RETURN_MASK_ALL)
377 /* Copy the argument text in case the command modifies it. */
378 char *copy = xstrdup (arg);
379 struct cleanup *cleanup = make_cleanup (xfree, copy);
381 prevent_dont_repeat ();
383 result = execute_command_to_string (copy, from_tty);
387 execute_command (copy, from_tty);
390 do_cleanups (cleanup);
392 GDB_PY_HANDLE_EXCEPTION (except);
394 /* Do any commands attached to breakpoint we stopped at. */
395 bpstat_do_actions ();
399 PyObject *r = PyString_FromString (result);
406 /* Implementation of gdb.solib_name (Long) -> String.
407 Returns the name of the shared library holding a given address, or None. */
410 gdbpy_solib_name (PyObject *self, PyObject *args)
416 if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
419 soname = solib_name_from_address (current_program_space, pc);
421 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
431 /* A Python function which is a wrapper for decode_line_1. */
434 gdbpy_decode_line (PyObject *self, PyObject *args)
436 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
438 struct symtab_and_line sal;
439 const char *arg = NULL;
441 struct cleanup *cleanups;
442 PyObject *result = NULL;
443 PyObject *return_result = NULL;
444 PyObject *unparsed = NULL;
445 volatile struct gdb_exception except;
447 if (! PyArg_ParseTuple (args, "|s", &arg))
450 cleanups = ensure_python_env (get_current_arch (), current_language);
452 TRY_CATCH (except, RETURN_MASK_ALL)
456 copy = xstrdup (arg);
457 make_cleanup (xfree, copy);
458 sals = decode_line_1 (©, 0, 0, 0, 0);
459 make_cleanup (xfree, sals.sals);
463 set_default_source_symtab_and_line ();
464 sal = get_current_source_symtab_and_line ();
469 if (except.reason < 0)
471 do_cleanups (cleanups);
472 /* We know this will always throw. */
473 GDB_PY_HANDLE_EXCEPTION (except);
480 result = PyTuple_New (sals.nelts);
483 for (i = 0; i < sals.nelts; ++i)
488 obj = symtab_and_line_to_sal_object (sals.sals[i]);
495 PyTuple_SetItem (result, i, obj);
504 return_result = PyTuple_New (2);
511 if (copy && strlen (copy) > 0)
512 unparsed = PyString_FromString (copy);
519 PyTuple_SetItem (return_result, 0, unparsed);
520 PyTuple_SetItem (return_result, 1, result);
522 do_cleanups (cleanups);
524 return return_result;
527 do_cleanups (cleanups);
531 /* Parse a string and evaluate it as an expression. */
533 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
535 const char *expr_str;
536 struct value *result = NULL;
537 volatile struct gdb_exception except;
539 if (!PyArg_ParseTuple (args, "s", &expr_str))
542 TRY_CATCH (except, RETURN_MASK_ALL)
544 char *copy = xstrdup (expr_str);
545 struct cleanup *cleanup = make_cleanup (xfree, copy);
547 result = parse_and_eval (copy);
548 do_cleanups (cleanup);
550 GDB_PY_HANDLE_EXCEPTION (except);
552 return value_to_value_object (result);
555 /* Read a file as Python code. STREAM is the input file; FILE is the
557 STREAM is not closed, that is the caller's responsibility. */
560 source_python_script (FILE *stream, const char *file)
562 struct cleanup *cleanup;
564 cleanup = ensure_python_env (get_current_arch (), current_language);
566 /* Note: If an exception occurs python will print the traceback and
567 clear the error indicator. */
568 PyRun_SimpleFile (stream, file);
570 do_cleanups (cleanup);
575 /* Posting and handling events. */
577 /* A single event. */
580 /* The Python event. This is just a callable object. */
582 /* The next event. */
583 struct gdbpy_event *next;
586 /* All pending events. */
587 static struct gdbpy_event *gdbpy_event_list;
588 /* The final link of the event list. */
589 static struct gdbpy_event **gdbpy_event_list_end;
591 /* We use a file handler, and not an async handler, so that we can
592 wake up the main thread even when it is blocked in poll(). */
593 static struct serial *gdbpy_event_fds[2];
595 /* The file handler callback. This reads from the internal pipe, and
596 then processes the Python event queue. This will always be run in
597 the main gdb thread. */
600 gdbpy_run_events (struct serial *scb, void *context)
602 struct cleanup *cleanup;
605 cleanup = ensure_python_env (get_current_arch (), current_language);
607 /* Flush the fd. Do this before flushing the events list, so that
608 any new event post afterwards is sure to re-awake the event
610 while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
613 while (gdbpy_event_list)
615 /* Dispatching the event might push a new element onto the event
616 loop, so we update here "atomically enough". */
617 struct gdbpy_event *item = gdbpy_event_list;
618 gdbpy_event_list = gdbpy_event_list->next;
619 if (gdbpy_event_list == NULL)
620 gdbpy_event_list_end = &gdbpy_event_list;
623 if (PyObject_CallObject (item->event, NULL) == NULL)
626 Py_DECREF (item->event);
630 do_cleanups (cleanup);
633 /* Submit an event to the gdb thread. */
635 gdbpy_post_event (PyObject *self, PyObject *args)
637 struct gdbpy_event *event;
641 if (!PyArg_ParseTuple (args, "O", &func))
644 if (!PyCallable_Check (func))
646 PyErr_SetString (PyExc_RuntimeError,
647 _("Posted event is not callable"));
653 /* From here until the end of the function, we have the GIL, so we
654 can operate on our global data structures without worrying. */
655 wakeup = gdbpy_event_list == NULL;
657 event = XNEW (struct gdbpy_event);
660 *gdbpy_event_list_end = event;
661 gdbpy_event_list_end = &event->next;
663 /* Wake up gdb when needed. */
666 char c = 'q'; /* Anything. */
668 if (serial_write (gdbpy_event_fds[1], &c, 1))
669 return PyErr_SetFromErrno (PyExc_IOError);
675 /* Initialize the Python event handler. */
677 gdbpy_initialize_events (void)
679 if (serial_pipe (gdbpy_event_fds) == 0)
681 gdbpy_event_list_end = &gdbpy_event_list;
682 serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
689 before_prompt_hook (const char *current_gdb_prompt)
691 struct cleanup *cleanup;
694 cleanup = ensure_python_env (get_current_arch (), current_language);
696 if (PyObject_HasAttrString (gdb_module, "prompt_hook"))
700 hook = PyObject_GetAttrString (gdb_module, "prompt_hook");
704 if (PyCallable_Check (hook))
707 PyObject *current_prompt;
709 current_prompt = PyString_FromString (current_gdb_prompt);
710 if (current_prompt == NULL)
713 result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
715 Py_DECREF (current_prompt);
720 make_cleanup_py_decref (result);
722 /* Return type should be None, or a String. If it is None,
723 fall through, we will not set a prompt. If it is a
724 string, set PROMPT. Anything else, set an exception. */
725 if (result != Py_None && ! PyString_Check (result))
727 PyErr_Format (PyExc_RuntimeError,
728 _("Return from prompt_hook must " \
729 "be either a Python string, or None"));
733 if (result != Py_None)
735 prompt = python_string_to_host_string (result);
740 make_cleanup (xfree, prompt);
745 /* If a prompt has been set, PROMPT will not be NULL. If it is
746 NULL, do not set the prompt. */
750 do_cleanups (cleanup);
754 gdbpy_print_stack ();
755 do_cleanups (cleanup);
763 /* A python function to write a single string using gdb's filtered
764 output stream . The optional keyword STREAM can be used to write
765 to a particular stream. The default stream is to gdb_stdout. */
768 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
771 static char *keywords[] = {"text", "stream", NULL };
774 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
782 fprintf_filtered (gdb_stderr, "%s", arg);
787 fprintf_filtered (gdb_stdlog, "%s", arg);
791 fprintf_filtered (gdb_stdout, "%s", arg);
797 /* A python function to flush a gdb stream. The optional keyword
798 STREAM can be used to flush a particular stream. The default stream
802 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
804 static char *keywords[] = {"stream", NULL };
807 if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
815 gdb_flush (gdb_stderr);
820 gdb_flush (gdb_stdlog);
824 gdb_flush (gdb_stdout);
830 /* Print a python exception trace, or print nothing and clear the
831 python exception, depending on gdbpy_should_print_stack. Only call
832 this if a python exception is set. */
834 gdbpy_print_stack (void)
836 if (gdbpy_should_print_stack)
839 /* PyErr_Print doesn't necessarily end output with a newline.
840 This works because Python's stdout/stderr is fed through
850 /* Return the current Progspace.
851 There always is one. */
854 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
858 result = pspace_to_pspace_object (current_program_space);
864 /* Return a sequence holding all the Progspaces. */
867 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
869 struct program_space *ps;
872 list = PyList_New (0);
878 PyObject *item = pspace_to_pspace_object (ps);
880 if (!item || PyList_Append (list, item) == -1)
892 /* The "current" objfile. This is set when gdb detects that a new
893 objfile has been loaded. It is only set for the duration of a call to
894 source_python_script_for_objfile; it is NULL at other times. */
895 static struct objfile *gdbpy_current_objfile;
897 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
901 source_python_script_for_objfile (struct objfile *objfile,
902 FILE *stream, const char *file)
904 struct cleanup *cleanups;
906 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
907 gdbpy_current_objfile = objfile;
909 /* Note: If an exception occurs python will print the traceback and
910 clear the error indicator. */
911 PyRun_SimpleFile (stream, file);
913 do_cleanups (cleanups);
914 gdbpy_current_objfile = NULL;
917 /* Return the current Objfile, or None if there isn't one. */
920 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
924 if (! gdbpy_current_objfile)
927 result = objfile_to_objfile_object (gdbpy_current_objfile);
933 /* Return a sequence holding all the Objfiles. */
936 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
938 struct objfile *objf;
941 list = PyList_New (0);
947 PyObject *item = objfile_to_objfile_object (objf);
949 if (!item || PyList_Append (list, item) == -1)
959 #else /* HAVE_PYTHON */
961 /* Dummy implementation of the gdb "python" command. */
964 python_command (char *arg, int from_tty)
966 while (arg && *arg && isspace (*arg))
969 error (_("Python scripting is not supported in this copy of GDB."));
972 struct command_line *l = get_command_line (python_control, "");
973 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
975 execute_control_command_untraced (l);
976 do_cleanups (cleanups);
981 eval_python_from_control_command (struct command_line *cmd)
983 error (_("Python scripting is not supported in this copy of GDB."));
987 source_python_script (FILE *stream, const char *file)
989 throw_error (UNSUPPORTED_ERROR,
990 _("Python scripting is not supported in this copy of GDB."));
994 gdbpy_should_stop (struct breakpoint_object *bp_obj)
996 internal_error (__FILE__, __LINE__,
997 _("gdbpy_should_stop called when Python scripting is " \
1002 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
1004 internal_error (__FILE__, __LINE__,
1005 _("gdbpy_breakpoint_has_py_cond called when Python " \
1006 "scripting is not supported."));
1009 #endif /* HAVE_PYTHON */
1013 /* Lists for 'maint set python' commands. */
1015 static struct cmd_list_element *maint_set_python_list;
1016 static struct cmd_list_element *maint_show_python_list;
1018 /* Lists for 'set python' commands. */
1020 static struct cmd_list_element *user_set_python_list;
1021 static struct cmd_list_element *user_show_python_list;
1023 /* Function for use by 'maint set python' prefix command. */
1026 maint_set_python (char *args, int from_tty)
1028 help_list (maint_set_python_list, "maintenance set python ",
1029 class_deprecated, gdb_stdout);
1032 /* Function for use by 'maint show python' prefix command. */
1035 maint_show_python (char *args, int from_tty)
1037 cmd_show_list (maint_show_python_list, from_tty, "");
1040 /* Function for use by 'set python' prefix command. */
1043 user_set_python (char *args, int from_tty)
1045 help_list (user_set_python_list, "set python ", all_commands,
1049 /* Function for use by 'show python' prefix command. */
1052 user_show_python (char *args, int from_tty)
1054 cmd_show_list (user_show_python_list, from_tty, "");
1057 /* Initialize the Python code. */
1059 /* Provide a prototype to silence -Wmissing-prototypes. */
1060 extern initialize_file_ftype _initialize_python;
1063 _initialize_python (void)
1066 struct cmd_list_element *cmd;
1068 add_com ("python", class_obscure, python_command,
1071 Evaluate a Python command.\n\
1073 The command can be given as an argument, for instance:\n\
1077 If no argument is given, the following lines are read and used\n\
1078 as the Python commands. Type a line containing \"end\" to indicate\n\
1079 the end of the command.")
1080 #else /* HAVE_PYTHON */
1082 Evaluate a Python command.\n\
1084 Python scripting is not supported in this copy of GDB.\n\
1085 This command is only a placeholder.")
1086 #endif /* HAVE_PYTHON */
1089 add_prefix_cmd ("python", no_class, maint_show_python,
1090 _("Prefix command for python maintenance settings."),
1091 &maint_show_python_list, "maintenance show python ", 0,
1092 &maintenance_show_cmdlist);
1093 add_prefix_cmd ("python", no_class, maint_set_python,
1094 _("Prefix command for python maintenance settings."),
1095 &maint_set_python_list, "maintenance set python ", 0,
1096 &maintenance_set_cmdlist);
1098 add_setshow_boolean_cmd ("print-stack", class_maintenance,
1099 &gdbpy_should_print_stack, _("\
1100 Enable or disable printing of Python stack dump on error."), _("\
1101 Show whether Python stack will be printed on error."), _("\
1102 Enables or disables printing of Python stack traces."),
1104 &maint_set_python_list,
1105 &maint_show_python_list);
1107 /* Deprecate maint set/show python print-stack in favour of
1108 non-maintenance alternatives. */
1109 cmd_name = "print-stack";
1110 cmd = lookup_cmd (&cmd_name, maint_set_python_list, "", -1, 0);
1111 deprecate_cmd (cmd, "set python print-stack");
1112 cmd_name = "print-stack"; /* Reset name. */
1113 cmd = lookup_cmd (&cmd_name, maint_show_python_list, "", -1, 0);
1114 deprecate_cmd (cmd, "show python print-stack");
1116 /* Add set/show python print-stack. */
1117 add_prefix_cmd ("python", no_class, user_show_python,
1118 _("Prefix command for python preference settings."),
1119 &user_show_python_list, "show python ", 0,
1122 add_prefix_cmd ("python", no_class, user_set_python,
1123 _("Prefix command for python preference settings."),
1124 &user_set_python_list, "set python ", 0,
1127 add_setshow_boolean_cmd ("print-stack", no_class,
1128 &gdbpy_should_print_stack, _("\
1129 Enable or disable printing of Python stack dump on error."), _("\
1130 Show whether Python stack will be printed on error."), _("\
1131 Enables or disables printing of Python stack traces."),
1133 &user_set_python_list,
1134 &user_show_python_list);
1137 #ifdef WITH_PYTHON_PATH
1138 /* Work around problem where python gets confused about where it is,
1139 and then can't find its libraries, etc.
1140 NOTE: Python assumes the following layout:
1142 /foo/lib/pythonX.Y/...
1143 This must be done before calling Py_Initialize. */
1144 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
1145 SLASH_STRING, "python", NULL));
1149 PyEval_InitThreads ();
1151 gdb_module = Py_InitModule ("gdb", GdbMethods);
1153 /* The casts to (char*) are for python 2.4. */
1154 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
1155 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
1156 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1157 (char*) target_name);
1159 /* Add stream constants. */
1160 PyModule_AddIntConstant (gdb_module, "STDOUT", 0);
1161 PyModule_AddIntConstant (gdb_module, "STDERR", 1);
1162 PyModule_AddIntConstant (gdb_module, "STDLOG", 2);
1164 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1165 script below is run (depending on order of _initialize_* functions).
1166 Define the initial value of gdb.PYTHONDIR here. */
1168 char *gdb_pythondir;
1170 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1171 PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
1172 xfree (gdb_pythondir);
1175 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1176 PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error);
1178 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1179 gdbpy_gdb_error, NULL);
1180 PyModule_AddObject (gdb_module, "MemoryError", gdbpy_gdb_memory_error);
1182 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1183 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
1185 gdbpy_initialize_auto_load ();
1186 gdbpy_initialize_values ();
1187 gdbpy_initialize_frames ();
1188 gdbpy_initialize_commands ();
1189 gdbpy_initialize_symbols ();
1190 gdbpy_initialize_symtabs ();
1191 gdbpy_initialize_blocks ();
1192 gdbpy_initialize_functions ();
1193 gdbpy_initialize_parameters ();
1194 gdbpy_initialize_types ();
1195 gdbpy_initialize_pspace ();
1196 gdbpy_initialize_objfile ();
1197 gdbpy_initialize_breakpoints ();
1198 gdbpy_initialize_lazy_string ();
1199 gdbpy_initialize_thread ();
1200 gdbpy_initialize_inferior ();
1201 gdbpy_initialize_events ();
1203 gdbpy_initialize_eventregistry ();
1204 gdbpy_initialize_py_events ();
1205 gdbpy_initialize_event ();
1206 gdbpy_initialize_stop_event ();
1207 gdbpy_initialize_signal_event ();
1208 gdbpy_initialize_breakpoint_event ();
1209 gdbpy_initialize_continue_event ();
1210 gdbpy_initialize_exited_event ();
1211 gdbpy_initialize_thread_event ();
1213 observer_attach_before_prompt (before_prompt_hook);
1215 PyRun_SimpleString ("import gdb");
1216 PyRun_SimpleString ("gdb.pretty_printers = []");
1218 gdbpy_to_string_cst = PyString_FromString ("to_string");
1219 gdbpy_children_cst = PyString_FromString ("children");
1220 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1221 gdbpy_doc_cst = PyString_FromString ("__doc__");
1222 gdbpy_enabled_cst = PyString_FromString ("enabled");
1223 gdbpy_value_cst = PyString_FromString ("value");
1225 /* Release the GIL while gdb runs. */
1226 PyThreadState_Swap (NULL);
1227 PyEval_ReleaseLock ();
1229 #endif /* HAVE_PYTHON */
1234 /* Perform the remaining python initializations.
1235 These must be done after GDB is at least mostly initialized.
1236 E.g., The "info pretty-printer" command needs the "info" prefix
1237 command installed. */
1240 finish_python_initialization (void)
1242 struct cleanup *cleanup;
1244 cleanup = ensure_python_env (get_current_arch (), current_language);
1246 PyRun_SimpleString ("\
1250 class GdbOutputFile:\n\
1255 def isatty(self):\n\
1258 def write(self, s):\n\
1259 gdb.write(s, stream=gdb.STDOUT)\n \
1261 def writelines(self, iterable):\n\
1262 for line in iterable:\n\
1268 sys.stdout = GdbOutputFile()\n\
1270 class GdbOutputErrorFile:\n\
1275 def isatty(self):\n\
1278 def write(self, s):\n\
1279 gdb.write(s, stream=gdb.STDERR)\n \
1281 def writelines(self, iterable):\n\
1282 for line in iterable:\n\
1283 self.write(line)\n \
1288 sys.stderr = GdbOutputErrorFile()\n\
1290 # Ideally this would live in the gdb module, but it's intentionally written\n\
1291 # in python, and we need this to bootstrap the gdb module.\n\
1293 def GdbSetPythonDirectory (dir):\n\
1294 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1295 old_dir = gdb.PYTHONDIR\n\
1296 gdb.PYTHONDIR = dir\n\
1297 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1298 # that directory name at the start of sys.path to allow the Python\n\
1299 # interpreter to find them.\n\
1300 if old_dir in sys.path:\n\
1301 sys.path.remove (old_dir)\n\
1302 sys.path.insert (0, gdb.PYTHONDIR)\n\
1304 # Tell python where to find submodules of gdb.\n\
1305 gdb.__path__ = [gdb.PYTHONDIR + '/gdb']\n\
1307 # The gdb module is implemented in C rather than in Python. As a result,\n\
1308 # the associated __init.py__ script is not not executed by default when\n\
1309 # the gdb module gets imported. Execute that script manually if it\n\
1311 ipy = gdb.PYTHONDIR + '/gdb/__init__.py'\n\
1312 if os.path.exists (ipy):\n\
1315 # Install the default gdb.PYTHONDIR.\n\
1316 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1317 # Default prompt hook does nothing.\n\
1318 prompt_hook = None\n\
1321 do_cleanups (cleanup);
1324 #endif /* HAVE_PYTHON */
1330 static PyMethodDef GdbMethods[] =
1332 { "history", gdbpy_history, METH_VARARGS,
1333 "Get a value from history" },
1334 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1335 "Execute a gdb command" },
1336 { "parameter", gdbpy_parameter, METH_VARARGS,
1337 "Return a gdb parameter's value" },
1339 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1340 "Return a tuple of all breakpoint objects" },
1342 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1343 "Find the default visualizer for a Value." },
1345 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1346 "Return the current Progspace." },
1347 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1348 "Return a sequence of all progspaces." },
1350 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1351 "Return the current Objfile being loaded, or None." },
1352 { "objfiles", gdbpy_objfiles, METH_NOARGS,
1353 "Return a sequence of all loaded objfiles." },
1355 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1356 "newest_frame () -> gdb.Frame.\n\
1357 Return the newest frame object." },
1358 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1359 "selected_frame () -> gdb.Frame.\n\
1360 Return the selected frame object." },
1361 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1362 "stop_reason_string (Integer) -> String.\n\
1363 Return a string explaining unwind stop reason." },
1365 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1366 METH_VARARGS | METH_KEYWORDS,
1367 "lookup_type (name [, block]) -> type\n\
1368 Return a Type corresponding to the given name." },
1369 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1370 METH_VARARGS | METH_KEYWORDS,
1371 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1372 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1373 a boolean indicating if name is a field of the current implied argument\n\
1374 `this' (when the current language is object-oriented)." },
1375 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1376 METH_VARARGS | METH_KEYWORDS,
1377 "lookup_global_symbol (name [, domain]) -> symbol\n\
1378 Return the symbol corresponding to the given name (or None)." },
1379 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1380 "Return the block containing the given pc value, or None." },
1381 { "solib_name", gdbpy_solib_name, METH_VARARGS,
1382 "solib_name (Long) -> String.\n\
1383 Return the name of the shared library holding a given address, or None." },
1384 { "decode_line", gdbpy_decode_line, METH_VARARGS,
1385 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1386 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1387 The first element contains any unparsed portion of the String parameter\n\
1388 (or None if the string was fully parsed). The second element contains\n\
1389 a tuple that contains all the locations that match, represented as\n\
1390 gdb.Symtab_and_line objects (or None)."},
1391 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1392 "parse_and_eval (String) -> Value.\n\
1393 Parse String as an expression, evaluate it, and return the result as a Value."
1396 { "post_event", gdbpy_post_event, METH_VARARGS,
1397 "Post an event into gdb's event loop." },
1399 { "target_charset", gdbpy_target_charset, METH_NOARGS,
1400 "target_charset () -> string.\n\
1401 Return the name of the current target charset." },
1402 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1403 "target_wide_charset () -> string.\n\
1404 Return the name of the current target wide charset." },
1406 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1407 "string_to_argv (String) -> Array.\n\
1408 Parse String and return an argv-like array.\n\
1409 Arguments are separate by spaces and may be quoted."
1411 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1412 "Write a string using gdb's filtered stream." },
1413 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1414 "Flush gdb's filtered stdout stream." },
1415 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1416 "selected_thread () -> gdb.InferiorThread.\n\
1417 Return the selected thread object." },
1418 { "inferiors", gdbpy_inferiors, METH_NOARGS,
1419 "inferiors () -> (gdb.Inferior, ...).\n\
1420 Return a tuple containing all inferiors." },
1421 {NULL, NULL, 0, NULL}
1424 #endif /* HAVE_PYTHON */