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"
57 static PyMethodDef GdbMethods
[];
61 /* Some string constants we may wish to use. */
62 PyObject
*gdbpy_to_string_cst
;
63 PyObject
*gdbpy_children_cst
;
64 PyObject
*gdbpy_display_hint_cst
;
65 PyObject
*gdbpy_doc_cst
;
66 PyObject
*gdbpy_enabled_cst
;
67 PyObject
*gdbpy_value_cst
;
69 /* The GdbError exception. */
70 PyObject
*gdbpy_gdberror_exc
;
72 /* The `gdb.error' base class. */
73 PyObject
*gdbpy_gdb_error
;
75 /* The `gdb.MemoryError' exception. */
76 PyObject
*gdbpy_gdb_memory_error
;
78 /* Architecture and language to be used in callbacks from
79 the Python interpreter. */
80 struct gdbarch
*python_gdbarch
;
81 const struct language_defn
*python_language
;
83 /* Restore global language and architecture and Python GIL state
84 when leaving the Python interpreter. */
88 PyGILState_STATE state
;
89 struct gdbarch
*gdbarch
;
90 const struct language_defn
*language
;
91 PyObject
*error_type
, *error_value
, *error_traceback
;
95 restore_python_env (void *p
)
97 struct python_env
*env
= (struct python_env
*)p
;
99 /* Leftover Python error is forbidden by Python Exception Handling. */
100 if (PyErr_Occurred ())
102 /* This order is similar to the one calling error afterwards. */
103 gdbpy_print_stack ();
104 warning (_("internal error: Unhandled Python exception"));
107 PyErr_Restore (env
->error_type
, env
->error_value
, env
->error_traceback
);
109 PyGILState_Release (env
->state
);
110 python_gdbarch
= env
->gdbarch
;
111 python_language
= env
->language
;
115 /* Called before entering the Python interpreter to install the
116 current language and architecture to be used for Python values. */
119 ensure_python_env (struct gdbarch
*gdbarch
,
120 const struct language_defn
*language
)
122 struct python_env
*env
= xmalloc (sizeof *env
);
124 env
->state
= PyGILState_Ensure ();
125 env
->gdbarch
= python_gdbarch
;
126 env
->language
= python_language
;
128 python_gdbarch
= gdbarch
;
129 python_language
= language
;
131 /* Save it and ensure ! PyErr_Occurred () afterwards. */
132 PyErr_Fetch (&env
->error_type
, &env
->error_value
, &env
->error_traceback
);
134 return make_cleanup (restore_python_env
, env
);
138 /* Given a command_line, return a command string suitable for passing
139 to Python. Lines in the string are separated by newlines. The
140 return value is allocated using xmalloc and the caller is
141 responsible for freeing it. */
144 compute_python_string (struct command_line
*l
)
146 struct command_line
*iter
;
151 for (iter
= l
; iter
; iter
= iter
->next
)
152 size
+= strlen (iter
->line
) + 1;
154 script
= xmalloc (size
+ 1);
156 for (iter
= l
; iter
; iter
= iter
->next
)
158 int len
= strlen (iter
->line
);
160 strcpy (&script
[here
], iter
->line
);
162 script
[here
++] = '\n';
168 /* Take a command line structure representing a 'python' command, and
169 evaluate its body using the Python interpreter. */
172 eval_python_from_control_command (struct command_line
*cmd
)
176 struct cleanup
*cleanup
;
178 if (cmd
->body_count
!= 1)
179 error (_("Invalid \"python\" block structure."));
181 cleanup
= ensure_python_env (get_current_arch (), current_language
);
183 script
= compute_python_string (cmd
->body_list
[0]);
184 ret
= PyRun_SimpleString (script
);
188 gdbpy_print_stack ();
189 error (_("Error while executing Python code."));
192 do_cleanups (cleanup
);
195 /* Implementation of the gdb "python" command. */
198 python_command (char *arg
, int from_tty
)
200 struct cleanup
*cleanup
;
202 cleanup
= ensure_python_env (get_current_arch (), current_language
);
204 make_cleanup_restore_integer (&interpreter_async
);
205 interpreter_async
= 0;
207 while (arg
&& *arg
&& isspace (*arg
))
211 if (PyRun_SimpleString (arg
))
213 gdbpy_print_stack ();
214 error (_("Error while executing Python code."));
219 struct command_line
*l
= get_command_line (python_control
, "");
221 make_cleanup_free_command_lines (&l
);
222 execute_control_command_untraced (l
);
225 do_cleanups (cleanup
);
230 /* Transform a gdb parameters's value into a Python value. May return
231 NULL (and set a Python exception) on error. Helper function for
234 gdbpy_parameter_value (enum var_types type
, void *var
)
239 case var_string_noescape
:
240 case var_optional_filename
:
244 char *str
= * (char **) var
;
248 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
259 case var_auto_boolean
:
261 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
263 if (ab
== AUTO_BOOLEAN_TRUE
)
265 else if (ab
== AUTO_BOOLEAN_FALSE
)
272 if ((* (int *) var
) == INT_MAX
)
276 return PyLong_FromLong (* (int *) var
);
280 unsigned int val
= * (unsigned int *) var
;
284 return PyLong_FromUnsignedLong (val
);
288 return PyErr_Format (PyExc_RuntimeError
,
289 _("Programmer error: unhandled type."));
292 /* A Python function which returns a gdb parameter's value as a Python
296 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
298 struct cmd_list_element
*alias
, *prefix
, *cmd
;
302 volatile struct gdb_exception except
;
304 if (! PyArg_ParseTuple (args
, "s", &arg
))
307 newarg
= concat ("show ", arg
, (char *) NULL
);
309 TRY_CATCH (except
, RETURN_MASK_ALL
)
311 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
314 GDB_PY_HANDLE_EXCEPTION (except
);
316 return PyErr_Format (PyExc_RuntimeError
,
317 _("Could not find parameter `%s'."), arg
);
320 return PyErr_Format (PyExc_RuntimeError
,
321 _("`%s' is not a parameter."), arg
);
322 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
325 /* Wrapper for target_charset. */
328 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
330 const char *cset
= target_charset (python_gdbarch
);
332 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
335 /* Wrapper for target_wide_charset. */
338 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
340 const char *cset
= target_wide_charset (python_gdbarch
);
342 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
345 /* A Python function which evaluates a string using the gdb CLI. */
348 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
351 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
352 int from_tty
, to_string
;
353 volatile struct gdb_exception except
;
354 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
357 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
358 &PyBool_Type
, &from_tty_obj
,
359 &PyBool_Type
, &to_string_obj
))
365 int cmp
= PyObject_IsTrue (from_tty_obj
);
374 int cmp
= PyObject_IsTrue (to_string_obj
);
380 TRY_CATCH (except
, RETURN_MASK_ALL
)
382 /* Copy the argument text in case the command modifies it. */
383 char *copy
= xstrdup (arg
);
384 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
386 make_cleanup_restore_integer (&interpreter_async
);
387 interpreter_async
= 0;
389 prevent_dont_repeat ();
391 result
= execute_command_to_string (copy
, from_tty
);
395 execute_command (copy
, from_tty
);
398 do_cleanups (cleanup
);
400 GDB_PY_HANDLE_EXCEPTION (except
);
402 /* Do any commands attached to breakpoint we stopped at. */
403 bpstat_do_actions ();
407 PyObject
*r
= PyString_FromString (result
);
414 /* Implementation of gdb.solib_name (Long) -> String.
415 Returns the name of the shared library holding a given address, or None. */
418 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
424 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
427 soname
= solib_name_from_address (current_program_space
, pc
);
429 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
439 /* A Python function which is a wrapper for decode_line_1. */
442 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
444 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
446 struct symtab_and_line sal
;
447 const char *arg
= NULL
;
449 struct cleanup
*cleanups
;
450 PyObject
*result
= NULL
;
451 PyObject
*return_result
= NULL
;
452 PyObject
*unparsed
= NULL
;
453 volatile struct gdb_exception except
;
455 if (! PyArg_ParseTuple (args
, "|s", &arg
))
458 cleanups
= ensure_python_env (get_current_arch (), current_language
);
460 TRY_CATCH (except
, RETURN_MASK_ALL
)
464 copy
= xstrdup (arg
);
465 make_cleanup (xfree
, copy
);
466 sals
= decode_line_1 (©
, 0, 0, 0, 0);
467 make_cleanup (xfree
, sals
.sals
);
471 set_default_source_symtab_and_line ();
472 sal
= get_current_source_symtab_and_line ();
477 if (except
.reason
< 0)
479 do_cleanups (cleanups
);
480 /* We know this will always throw. */
481 GDB_PY_HANDLE_EXCEPTION (except
);
488 result
= PyTuple_New (sals
.nelts
);
491 for (i
= 0; i
< sals
.nelts
; ++i
)
496 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
503 PyTuple_SetItem (result
, i
, obj
);
512 return_result
= PyTuple_New (2);
519 if (copy
&& strlen (copy
) > 0)
520 unparsed
= PyString_FromString (copy
);
527 PyTuple_SetItem (return_result
, 0, unparsed
);
528 PyTuple_SetItem (return_result
, 1, result
);
530 do_cleanups (cleanups
);
532 return return_result
;
535 do_cleanups (cleanups
);
539 /* Parse a string and evaluate it as an expression. */
541 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
543 const char *expr_str
;
544 struct value
*result
= NULL
;
545 volatile struct gdb_exception except
;
547 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
550 TRY_CATCH (except
, RETURN_MASK_ALL
)
552 char *copy
= xstrdup (expr_str
);
553 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
555 result
= parse_and_eval (copy
);
556 do_cleanups (cleanup
);
558 GDB_PY_HANDLE_EXCEPTION (except
);
560 return value_to_value_object (result
);
563 /* Read a file as Python code. STREAM is the input file; FILE is the
565 STREAM is not closed, that is the caller's responsibility. */
568 source_python_script (FILE *stream
, const char *file
)
570 struct cleanup
*cleanup
;
572 cleanup
= ensure_python_env (get_current_arch (), current_language
);
574 /* Note: If an exception occurs python will print the traceback and
575 clear the error indicator. */
576 PyRun_SimpleFile (stream
, file
);
578 do_cleanups (cleanup
);
583 /* Posting and handling events. */
585 /* A single event. */
588 /* The Python event. This is just a callable object. */
590 /* The next event. */
591 struct gdbpy_event
*next
;
594 /* All pending events. */
595 static struct gdbpy_event
*gdbpy_event_list
;
596 /* The final link of the event list. */
597 static struct gdbpy_event
**gdbpy_event_list_end
;
599 /* We use a file handler, and not an async handler, so that we can
600 wake up the main thread even when it is blocked in poll(). */
601 static struct serial
*gdbpy_event_fds
[2];
603 /* The file handler callback. This reads from the internal pipe, and
604 then processes the Python event queue. This will always be run in
605 the main gdb thread. */
608 gdbpy_run_events (struct serial
*scb
, void *context
)
610 struct cleanup
*cleanup
;
613 cleanup
= ensure_python_env (get_current_arch (), current_language
);
615 /* Flush the fd. Do this before flushing the events list, so that
616 any new event post afterwards is sure to re-awake the event
618 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
621 while (gdbpy_event_list
)
623 /* Dispatching the event might push a new element onto the event
624 loop, so we update here "atomically enough". */
625 struct gdbpy_event
*item
= gdbpy_event_list
;
626 gdbpy_event_list
= gdbpy_event_list
->next
;
627 if (gdbpy_event_list
== NULL
)
628 gdbpy_event_list_end
= &gdbpy_event_list
;
631 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
634 Py_DECREF (item
->event
);
638 do_cleanups (cleanup
);
641 /* Submit an event to the gdb thread. */
643 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
645 struct gdbpy_event
*event
;
649 if (!PyArg_ParseTuple (args
, "O", &func
))
652 if (!PyCallable_Check (func
))
654 PyErr_SetString (PyExc_RuntimeError
,
655 _("Posted event is not callable"));
661 /* From here until the end of the function, we have the GIL, so we
662 can operate on our global data structures without worrying. */
663 wakeup
= gdbpy_event_list
== NULL
;
665 event
= XNEW (struct gdbpy_event
);
668 *gdbpy_event_list_end
= event
;
669 gdbpy_event_list_end
= &event
->next
;
671 /* Wake up gdb when needed. */
674 char c
= 'q'; /* Anything. */
676 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
677 return PyErr_SetFromErrno (PyExc_IOError
);
683 /* Initialize the Python event handler. */
685 gdbpy_initialize_events (void)
687 if (serial_pipe (gdbpy_event_fds
) == 0)
689 gdbpy_event_list_end
= &gdbpy_event_list
;
690 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
697 before_prompt_hook (const char *current_gdb_prompt
)
699 struct cleanup
*cleanup
;
702 cleanup
= ensure_python_env (get_current_arch (), current_language
);
704 if (PyObject_HasAttrString (gdb_module
, "prompt_hook"))
708 hook
= PyObject_GetAttrString (gdb_module
, "prompt_hook");
712 if (PyCallable_Check (hook
))
715 PyObject
*current_prompt
;
717 current_prompt
= PyString_FromString (current_gdb_prompt
);
718 if (current_prompt
== NULL
)
721 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
723 Py_DECREF (current_prompt
);
728 make_cleanup_py_decref (result
);
730 /* Return type should be None, or a String. If it is None,
731 fall through, we will not set a prompt. If it is a
732 string, set PROMPT. Anything else, set an exception. */
733 if (result
!= Py_None
&& ! PyString_Check (result
))
735 PyErr_Format (PyExc_RuntimeError
,
736 _("Return from prompt_hook must " \
737 "be either a Python string, or None"));
741 if (result
!= Py_None
)
743 prompt
= python_string_to_host_string (result
);
748 make_cleanup (xfree
, prompt
);
753 /* If a prompt has been set, PROMPT will not be NULL. If it is
754 NULL, do not set the prompt. */
756 set_prompt (prompt
, 0);
758 do_cleanups (cleanup
);
762 gdbpy_print_stack ();
763 do_cleanups (cleanup
);
771 /* A python function to write a single string using gdb's filtered
772 output stream . The optional keyword STREAM can be used to write
773 to a particular stream. The default stream is to gdb_stdout. */
776 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
779 static char *keywords
[] = {"text", "stream", NULL
};
782 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
790 fprintf_filtered (gdb_stderr
, "%s", arg
);
795 fprintf_filtered (gdb_stdlog
, "%s", arg
);
799 fprintf_filtered (gdb_stdout
, "%s", arg
);
805 /* A python function to flush a gdb stream. The optional keyword
806 STREAM can be used to flush a particular stream. The default stream
810 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
812 static char *keywords
[] = {"stream", NULL
};
815 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
823 gdb_flush (gdb_stderr
);
828 gdb_flush (gdb_stdlog
);
832 gdb_flush (gdb_stdout
);
838 /* Print a python exception trace, or print nothing and clear the
839 python exception, depending on gdbpy_should_print_stack. Only call
840 this if a python exception is set. */
842 gdbpy_print_stack (void)
844 if (gdbpy_should_print_stack
)
847 /* PyErr_Print doesn't necessarily end output with a newline.
848 This works because Python's stdout/stderr is fed through
858 /* Return the current Progspace.
859 There always is one. */
862 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
866 result
= pspace_to_pspace_object (current_program_space
);
872 /* Return a sequence holding all the Progspaces. */
875 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
877 struct program_space
*ps
;
880 list
= PyList_New (0);
886 PyObject
*item
= pspace_to_pspace_object (ps
);
888 if (!item
|| PyList_Append (list
, item
) == -1)
900 /* The "current" objfile. This is set when gdb detects that a new
901 objfile has been loaded. It is only set for the duration of a call to
902 source_python_script_for_objfile; it is NULL at other times. */
903 static struct objfile
*gdbpy_current_objfile
;
905 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
909 source_python_script_for_objfile (struct objfile
*objfile
,
910 FILE *stream
, const char *file
)
912 struct cleanup
*cleanups
;
914 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
915 gdbpy_current_objfile
= objfile
;
917 /* Note: If an exception occurs python will print the traceback and
918 clear the error indicator. */
919 PyRun_SimpleFile (stream
, file
);
921 do_cleanups (cleanups
);
922 gdbpy_current_objfile
= NULL
;
925 /* Return the current Objfile, or None if there isn't one. */
928 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
932 if (! gdbpy_current_objfile
)
935 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
941 /* Return a sequence holding all the Objfiles. */
944 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
946 struct objfile
*objf
;
949 list
= PyList_New (0);
955 PyObject
*item
= objfile_to_objfile_object (objf
);
957 if (!item
|| PyList_Append (list
, item
) == -1)
967 #else /* HAVE_PYTHON */
969 /* Dummy implementation of the gdb "python" command. */
972 python_command (char *arg
, int from_tty
)
974 while (arg
&& *arg
&& isspace (*arg
))
977 error (_("Python scripting is not supported in this copy of GDB."));
980 struct command_line
*l
= get_command_line (python_control
, "");
981 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
983 execute_control_command_untraced (l
);
984 do_cleanups (cleanups
);
989 eval_python_from_control_command (struct command_line
*cmd
)
991 error (_("Python scripting is not supported in this copy of GDB."));
995 source_python_script (FILE *stream
, const char *file
)
997 throw_error (UNSUPPORTED_ERROR
,
998 _("Python scripting is not supported in this copy of GDB."));
1002 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1004 internal_error (__FILE__
, __LINE__
,
1005 _("gdbpy_should_stop called when Python scripting is " \
1010 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1012 internal_error (__FILE__
, __LINE__
,
1013 _("gdbpy_breakpoint_has_py_cond called when Python " \
1014 "scripting is not supported."));
1017 #endif /* HAVE_PYTHON */
1021 /* Lists for 'maint set python' commands. */
1023 static struct cmd_list_element
*maint_set_python_list
;
1024 static struct cmd_list_element
*maint_show_python_list
;
1026 /* Lists for 'set python' commands. */
1028 static struct cmd_list_element
*user_set_python_list
;
1029 static struct cmd_list_element
*user_show_python_list
;
1031 /* Function for use by 'maint set python' prefix command. */
1034 maint_set_python (char *args
, int from_tty
)
1036 help_list (maint_set_python_list
, "maintenance set python ",
1037 class_deprecated
, gdb_stdout
);
1040 /* Function for use by 'maint show python' prefix command. */
1043 maint_show_python (char *args
, int from_tty
)
1045 cmd_show_list (maint_show_python_list
, from_tty
, "");
1048 /* Function for use by 'set python' prefix command. */
1051 user_set_python (char *args
, int from_tty
)
1053 help_list (user_set_python_list
, "set python ", all_commands
,
1057 /* Function for use by 'show python' prefix command. */
1060 user_show_python (char *args
, int from_tty
)
1062 cmd_show_list (user_show_python_list
, from_tty
, "");
1065 /* Initialize the Python code. */
1067 /* Provide a prototype to silence -Wmissing-prototypes. */
1068 extern initialize_file_ftype _initialize_python
;
1071 _initialize_python (void)
1074 struct cmd_list_element
*cmd
;
1076 add_com ("python", class_obscure
, python_command
,
1079 Evaluate a Python command.\n\
1081 The command can be given as an argument, for instance:\n\
1085 If no argument is given, the following lines are read and used\n\
1086 as the Python commands. Type a line containing \"end\" to indicate\n\
1087 the end of the command.")
1088 #else /* HAVE_PYTHON */
1090 Evaluate a Python command.\n\
1092 Python scripting is not supported in this copy of GDB.\n\
1093 This command is only a placeholder.")
1094 #endif /* HAVE_PYTHON */
1097 add_prefix_cmd ("python", no_class
, maint_show_python
,
1098 _("Prefix command for python maintenance settings."),
1099 &maint_show_python_list
, "maintenance show python ", 0,
1100 &maintenance_show_cmdlist
);
1101 add_prefix_cmd ("python", no_class
, maint_set_python
,
1102 _("Prefix command for python maintenance settings."),
1103 &maint_set_python_list
, "maintenance set python ", 0,
1104 &maintenance_set_cmdlist
);
1106 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
1107 &gdbpy_should_print_stack
, _("\
1108 Enable or disable printing of Python stack dump on error."), _("\
1109 Show whether Python stack will be printed on error."), _("\
1110 Enables or disables printing of Python stack traces."),
1112 &maint_set_python_list
,
1113 &maint_show_python_list
);
1115 /* Deprecate maint set/show python print-stack in favour of
1116 non-maintenance alternatives. */
1117 cmd_name
= "print-stack";
1118 cmd
= lookup_cmd (&cmd_name
, maint_set_python_list
, "", -1, 0);
1119 deprecate_cmd (cmd
, "set python print-stack");
1120 cmd_name
= "print-stack"; /* Reset name. */
1121 cmd
= lookup_cmd (&cmd_name
, maint_show_python_list
, "", -1, 0);
1122 deprecate_cmd (cmd
, "show python print-stack");
1124 /* Add set/show python print-stack. */
1125 add_prefix_cmd ("python", no_class
, user_show_python
,
1126 _("Prefix command for python preference settings."),
1127 &user_show_python_list
, "show python ", 0,
1130 add_prefix_cmd ("python", no_class
, user_set_python
,
1131 _("Prefix command for python preference settings."),
1132 &user_set_python_list
, "set python ", 0,
1135 add_setshow_boolean_cmd ("print-stack", no_class
,
1136 &gdbpy_should_print_stack
, _("\
1137 Enable or disable printing of Python stack dump on error."), _("\
1138 Show whether Python stack will be printed on error."), _("\
1139 Enables or disables printing of Python stack traces."),
1141 &user_set_python_list
,
1142 &user_show_python_list
);
1145 #ifdef WITH_PYTHON_PATH
1146 /* Work around problem where python gets confused about where it is,
1147 and then can't find its libraries, etc.
1148 NOTE: Python assumes the following layout:
1150 /foo/lib/pythonX.Y/...
1151 This must be done before calling Py_Initialize. */
1152 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1153 SLASH_STRING
, "python", NULL
));
1157 PyEval_InitThreads ();
1159 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
1161 /* The casts to (char*) are for python 2.4. */
1162 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1163 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1164 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1165 (char*) target_name
);
1167 /* Add stream constants. */
1168 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1169 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1170 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1172 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1173 script below is run (depending on order of _initialize_* functions).
1174 Define the initial value of gdb.PYTHONDIR here. */
1176 char *gdb_pythondir
;
1178 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1179 PyModule_AddStringConstant (gdb_module
, "PYTHONDIR", gdb_pythondir
);
1180 xfree (gdb_pythondir
);
1183 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1184 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1186 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1187 gdbpy_gdb_error
, NULL
);
1188 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1190 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1191 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1193 gdbpy_initialize_auto_load ();
1194 gdbpy_initialize_values ();
1195 gdbpy_initialize_frames ();
1196 gdbpy_initialize_commands ();
1197 gdbpy_initialize_symbols ();
1198 gdbpy_initialize_symtabs ();
1199 gdbpy_initialize_blocks ();
1200 gdbpy_initialize_functions ();
1201 gdbpy_initialize_parameters ();
1202 gdbpy_initialize_types ();
1203 gdbpy_initialize_pspace ();
1204 gdbpy_initialize_objfile ();
1205 gdbpy_initialize_breakpoints ();
1206 gdbpy_initialize_lazy_string ();
1207 gdbpy_initialize_thread ();
1208 gdbpy_initialize_inferior ();
1209 gdbpy_initialize_events ();
1211 gdbpy_initialize_eventregistry ();
1212 gdbpy_initialize_py_events ();
1213 gdbpy_initialize_event ();
1214 gdbpy_initialize_stop_event ();
1215 gdbpy_initialize_signal_event ();
1216 gdbpy_initialize_breakpoint_event ();
1217 gdbpy_initialize_continue_event ();
1218 gdbpy_initialize_exited_event ();
1219 gdbpy_initialize_thread_event ();
1221 observer_attach_before_prompt (before_prompt_hook
);
1223 PyRun_SimpleString ("import gdb");
1224 PyRun_SimpleString ("gdb.pretty_printers = []");
1226 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1227 gdbpy_children_cst
= PyString_FromString ("children");
1228 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1229 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1230 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1231 gdbpy_value_cst
= PyString_FromString ("value");
1233 /* Release the GIL while gdb runs. */
1234 PyThreadState_Swap (NULL
);
1235 PyEval_ReleaseLock ();
1237 #endif /* HAVE_PYTHON */
1242 /* Perform the remaining python initializations.
1243 These must be done after GDB is at least mostly initialized.
1244 E.g., The "info pretty-printer" command needs the "info" prefix
1245 command installed. */
1248 finish_python_initialization (void)
1250 struct cleanup
*cleanup
;
1252 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1254 PyRun_SimpleString ("\
1258 class GdbOutputFile:\n\
1263 def isatty(self):\n\
1266 def write(self, s):\n\
1267 gdb.write(s, stream=gdb.STDOUT)\n \
1269 def writelines(self, iterable):\n\
1270 for line in iterable:\n\
1276 sys.stdout = GdbOutputFile()\n\
1278 class GdbOutputErrorFile:\n\
1283 def isatty(self):\n\
1286 def write(self, s):\n\
1287 gdb.write(s, stream=gdb.STDERR)\n \
1289 def writelines(self, iterable):\n\
1290 for line in iterable:\n\
1291 self.write(line)\n \
1296 sys.stderr = GdbOutputErrorFile()\n\
1298 # Ideally this would live in the gdb module, but it's intentionally written\n\
1299 # in python, and we need this to bootstrap the gdb module.\n\
1301 def GdbSetPythonDirectory (dir):\n\
1302 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1303 old_dir = gdb.PYTHONDIR\n\
1304 gdb.PYTHONDIR = dir\n\
1305 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1306 # that directory name at the start of sys.path to allow the Python\n\
1307 # interpreter to find them.\n\
1308 if old_dir in sys.path:\n\
1309 sys.path.remove (old_dir)\n\
1310 sys.path.insert (0, gdb.PYTHONDIR)\n\
1312 # Tell python where to find submodules of gdb.\n\
1313 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1315 # The gdb module is implemented in C rather than in Python. As a result,\n\
1316 # the associated __init.py__ script is not not executed by default when\n\
1317 # the gdb module gets imported. Execute that script manually if it\n\
1319 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1320 if os.path.exists (ipy):\n\
1323 # Install the default gdb.PYTHONDIR.\n\
1324 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1325 # Default prompt hook does nothing.\n\
1326 prompt_hook = None\n\
1329 do_cleanups (cleanup
);
1332 #endif /* HAVE_PYTHON */
1338 static PyMethodDef GdbMethods
[] =
1340 { "history", gdbpy_history
, METH_VARARGS
,
1341 "Get a value from history" },
1342 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1343 "Execute a gdb command" },
1344 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1345 "Return a gdb parameter's value" },
1347 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1348 "Return a tuple of all breakpoint objects" },
1350 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1351 "Find the default visualizer for a Value." },
1353 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1354 "Return the current Progspace." },
1355 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1356 "Return a sequence of all progspaces." },
1358 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1359 "Return the current Objfile being loaded, or None." },
1360 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1361 "Return a sequence of all loaded objfiles." },
1363 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1364 "newest_frame () -> gdb.Frame.\n\
1365 Return the newest frame object." },
1366 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1367 "selected_frame () -> gdb.Frame.\n\
1368 Return the selected frame object." },
1369 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1370 "stop_reason_string (Integer) -> String.\n\
1371 Return a string explaining unwind stop reason." },
1373 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1374 METH_VARARGS
| METH_KEYWORDS
,
1375 "lookup_type (name [, block]) -> type\n\
1376 Return a Type corresponding to the given name." },
1377 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1378 METH_VARARGS
| METH_KEYWORDS
,
1379 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1380 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1381 a boolean indicating if name is a field of the current implied argument\n\
1382 `this' (when the current language is object-oriented)." },
1383 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1384 METH_VARARGS
| METH_KEYWORDS
,
1385 "lookup_global_symbol (name [, domain]) -> symbol\n\
1386 Return the symbol corresponding to the given name (or None)." },
1387 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1388 "Return the block containing the given pc value, or None." },
1389 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1390 "solib_name (Long) -> String.\n\
1391 Return the name of the shared library holding a given address, or None." },
1392 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1393 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1394 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1395 The first element contains any unparsed portion of the String parameter\n\
1396 (or None if the string was fully parsed). The second element contains\n\
1397 a tuple that contains all the locations that match, represented as\n\
1398 gdb.Symtab_and_line objects (or None)."},
1399 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1400 "parse_and_eval (String) -> Value.\n\
1401 Parse String as an expression, evaluate it, and return the result as a Value."
1404 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1405 "Post an event into gdb's event loop." },
1407 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1408 "target_charset () -> string.\n\
1409 Return the name of the current target charset." },
1410 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1411 "target_wide_charset () -> string.\n\
1412 Return the name of the current target wide charset." },
1414 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1415 "string_to_argv (String) -> Array.\n\
1416 Parse String and return an argv-like array.\n\
1417 Arguments are separate by spaces and may be quoted."
1419 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1420 "Write a string using gdb's filtered stream." },
1421 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1422 "Flush gdb's filtered stdout stream." },
1423 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1424 "selected_thread () -> gdb.InferiorThread.\n\
1425 Return the selected thread object." },
1426 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1427 "inferiors () -> (gdb.Inferior, ...).\n\
1428 Return a tuple containing all inferiors." },
1429 {NULL
, NULL
, 0, NULL
}
1432 #endif /* HAVE_PYTHON */