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
);
137 /* A wrapper around PyRun_SimpleFile. FILENAME is the name of
138 the Python script to run.
140 One of the parameters of PyRun_SimpleFile is a FILE *.
141 The problem is that type FILE is extremely system and compiler
142 dependent. So, unless the Python library has been compiled using
143 the same build environment as GDB, we run the risk of getting
144 a crash due to inconsistencies between the definition used by GDB,
145 and the definition used by Python. A mismatch can very likely
148 There is also the situation where the Python library and GDB
149 are using two different versions of the C runtime library.
150 This is particularly visible on Windows, where few users would
151 build Python themselves (this is no trivial task on this platform),
152 and thus use binaries built by someone else instead. Python,
153 being built with VC, would use one version of the msvcr DLL
154 (Eg. msvcr100.dll), while MinGW uses msvcrt.dll. A FILE *
155 from one runtime does not necessarily operate correctly in
158 To work around this potential issue, we create the FILE object
159 using Python routines, thus making sure that it is compatible
160 with the Python library. */
163 python_run_simple_file (const char *filename
)
166 PyObject
*python_file
;
167 struct cleanup
*cleanup
;
169 filename_copy
= xstrdup (filename
);
170 cleanup
= make_cleanup (xfree
, filename_copy
);
171 python_file
= PyFile_FromString (filename_copy
, "r");
172 make_cleanup_py_decref (python_file
);
173 PyRun_SimpleFile (PyFile_AsFile (python_file
), filename
);
174 do_cleanups (cleanup
);
177 /* Given a command_line, return a command string suitable for passing
178 to Python. Lines in the string are separated by newlines. The
179 return value is allocated using xmalloc and the caller is
180 responsible for freeing it. */
183 compute_python_string (struct command_line
*l
)
185 struct command_line
*iter
;
190 for (iter
= l
; iter
; iter
= iter
->next
)
191 size
+= strlen (iter
->line
) + 1;
193 script
= xmalloc (size
+ 1);
195 for (iter
= l
; iter
; iter
= iter
->next
)
197 int len
= strlen (iter
->line
);
199 strcpy (&script
[here
], iter
->line
);
201 script
[here
++] = '\n';
207 /* Take a command line structure representing a 'python' command, and
208 evaluate its body using the Python interpreter. */
211 eval_python_from_control_command (struct command_line
*cmd
)
215 struct cleanup
*cleanup
;
217 if (cmd
->body_count
!= 1)
218 error (_("Invalid \"python\" block structure."));
220 cleanup
= ensure_python_env (get_current_arch (), current_language
);
222 script
= compute_python_string (cmd
->body_list
[0]);
223 ret
= PyRun_SimpleString (script
);
227 gdbpy_print_stack ();
228 error (_("Error while executing Python code."));
231 do_cleanups (cleanup
);
234 /* Implementation of the gdb "python" command. */
237 python_command (char *arg
, int from_tty
)
239 struct cleanup
*cleanup
;
241 cleanup
= ensure_python_env (get_current_arch (), current_language
);
243 make_cleanup_restore_integer (&interpreter_async
);
244 interpreter_async
= 0;
246 while (arg
&& *arg
&& isspace (*arg
))
250 if (PyRun_SimpleString (arg
))
252 gdbpy_print_stack ();
253 error (_("Error while executing Python code."));
258 struct command_line
*l
= get_command_line (python_control
, "");
260 make_cleanup_free_command_lines (&l
);
261 execute_control_command_untraced (l
);
264 do_cleanups (cleanup
);
269 /* Transform a gdb parameters's value into a Python value. May return
270 NULL (and set a Python exception) on error. Helper function for
273 gdbpy_parameter_value (enum var_types type
, void *var
)
278 case var_string_noescape
:
279 case var_optional_filename
:
283 char *str
= * (char **) var
;
287 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
298 case var_auto_boolean
:
300 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
302 if (ab
== AUTO_BOOLEAN_TRUE
)
304 else if (ab
== AUTO_BOOLEAN_FALSE
)
311 if ((* (int *) var
) == INT_MAX
)
315 return PyLong_FromLong (* (int *) var
);
319 unsigned int val
= * (unsigned int *) var
;
323 return PyLong_FromUnsignedLong (val
);
327 return PyErr_Format (PyExc_RuntimeError
,
328 _("Programmer error: unhandled type."));
331 /* A Python function which returns a gdb parameter's value as a Python
335 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
337 struct cmd_list_element
*alias
, *prefix
, *cmd
;
341 volatile struct gdb_exception except
;
343 if (! PyArg_ParseTuple (args
, "s", &arg
))
346 newarg
= concat ("show ", arg
, (char *) NULL
);
348 TRY_CATCH (except
, RETURN_MASK_ALL
)
350 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
353 GDB_PY_HANDLE_EXCEPTION (except
);
355 return PyErr_Format (PyExc_RuntimeError
,
356 _("Could not find parameter `%s'."), arg
);
359 return PyErr_Format (PyExc_RuntimeError
,
360 _("`%s' is not a parameter."), arg
);
361 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
364 /* Wrapper for target_charset. */
367 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
369 const char *cset
= target_charset (python_gdbarch
);
371 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
374 /* Wrapper for target_wide_charset. */
377 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
379 const char *cset
= target_wide_charset (python_gdbarch
);
381 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
384 /* A Python function which evaluates a string using the gdb CLI. */
387 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
390 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
391 int from_tty
, to_string
;
392 volatile struct gdb_exception except
;
393 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
396 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
397 &PyBool_Type
, &from_tty_obj
,
398 &PyBool_Type
, &to_string_obj
))
404 int cmp
= PyObject_IsTrue (from_tty_obj
);
413 int cmp
= PyObject_IsTrue (to_string_obj
);
419 TRY_CATCH (except
, RETURN_MASK_ALL
)
421 /* Copy the argument text in case the command modifies it. */
422 char *copy
= xstrdup (arg
);
423 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
425 make_cleanup_restore_integer (&interpreter_async
);
426 interpreter_async
= 0;
428 prevent_dont_repeat ();
430 result
= execute_command_to_string (copy
, from_tty
);
434 execute_command (copy
, from_tty
);
437 do_cleanups (cleanup
);
439 GDB_PY_HANDLE_EXCEPTION (except
);
441 /* Do any commands attached to breakpoint we stopped at. */
442 bpstat_do_actions ();
446 PyObject
*r
= PyString_FromString (result
);
453 /* Implementation of gdb.solib_name (Long) -> String.
454 Returns the name of the shared library holding a given address, or None. */
457 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
463 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
466 soname
= solib_name_from_address (current_program_space
, pc
);
468 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
478 /* A Python function which is a wrapper for decode_line_1. */
481 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
483 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
485 struct symtab_and_line sal
;
486 const char *arg
= NULL
;
488 struct cleanup
*cleanups
;
489 PyObject
*result
= NULL
;
490 PyObject
*return_result
= NULL
;
491 PyObject
*unparsed
= NULL
;
492 volatile struct gdb_exception except
;
494 if (! PyArg_ParseTuple (args
, "|s", &arg
))
497 cleanups
= ensure_python_env (get_current_arch (), current_language
);
499 TRY_CATCH (except
, RETURN_MASK_ALL
)
503 copy
= xstrdup (arg
);
504 make_cleanup (xfree
, copy
);
505 sals
= decode_line_1 (©
, 0, 0, 0, 0);
506 make_cleanup (xfree
, sals
.sals
);
510 set_default_source_symtab_and_line ();
511 sal
= get_current_source_symtab_and_line ();
516 if (except
.reason
< 0)
518 do_cleanups (cleanups
);
519 /* We know this will always throw. */
520 GDB_PY_HANDLE_EXCEPTION (except
);
527 result
= PyTuple_New (sals
.nelts
);
530 for (i
= 0; i
< sals
.nelts
; ++i
)
535 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
542 PyTuple_SetItem (result
, i
, obj
);
551 return_result
= PyTuple_New (2);
558 if (copy
&& strlen (copy
) > 0)
559 unparsed
= PyString_FromString (copy
);
566 PyTuple_SetItem (return_result
, 0, unparsed
);
567 PyTuple_SetItem (return_result
, 1, result
);
569 do_cleanups (cleanups
);
571 return return_result
;
574 do_cleanups (cleanups
);
578 /* Parse a string and evaluate it as an expression. */
580 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
582 const char *expr_str
;
583 struct value
*result
= NULL
;
584 volatile struct gdb_exception except
;
586 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
589 TRY_CATCH (except
, RETURN_MASK_ALL
)
591 char *copy
= xstrdup (expr_str
);
592 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
594 result
= parse_and_eval (copy
);
595 do_cleanups (cleanup
);
597 GDB_PY_HANDLE_EXCEPTION (except
);
599 return value_to_value_object (result
);
602 /* Read a file as Python code.
603 FILE is the name of the file.
604 This does not throw any errors. If an exception occurs python will print
605 the traceback and clear the error indicator. */
608 source_python_script (const char *file
)
610 struct cleanup
*cleanup
;
612 cleanup
= ensure_python_env (get_current_arch (), current_language
);
613 python_run_simple_file (file
);
614 do_cleanups (cleanup
);
619 /* Posting and handling events. */
621 /* A single event. */
624 /* The Python event. This is just a callable object. */
626 /* The next event. */
627 struct gdbpy_event
*next
;
630 /* All pending events. */
631 static struct gdbpy_event
*gdbpy_event_list
;
632 /* The final link of the event list. */
633 static struct gdbpy_event
**gdbpy_event_list_end
;
635 /* We use a file handler, and not an async handler, so that we can
636 wake up the main thread even when it is blocked in poll(). */
637 static struct serial
*gdbpy_event_fds
[2];
639 /* The file handler callback. This reads from the internal pipe, and
640 then processes the Python event queue. This will always be run in
641 the main gdb thread. */
644 gdbpy_run_events (struct serial
*scb
, void *context
)
646 struct cleanup
*cleanup
;
649 cleanup
= ensure_python_env (get_current_arch (), current_language
);
651 /* Flush the fd. Do this before flushing the events list, so that
652 any new event post afterwards is sure to re-awake the event
654 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
657 while (gdbpy_event_list
)
659 /* Dispatching the event might push a new element onto the event
660 loop, so we update here "atomically enough". */
661 struct gdbpy_event
*item
= gdbpy_event_list
;
662 gdbpy_event_list
= gdbpy_event_list
->next
;
663 if (gdbpy_event_list
== NULL
)
664 gdbpy_event_list_end
= &gdbpy_event_list
;
667 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
670 Py_DECREF (item
->event
);
674 do_cleanups (cleanup
);
677 /* Submit an event to the gdb thread. */
679 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
681 struct gdbpy_event
*event
;
685 if (!PyArg_ParseTuple (args
, "O", &func
))
688 if (!PyCallable_Check (func
))
690 PyErr_SetString (PyExc_RuntimeError
,
691 _("Posted event is not callable"));
697 /* From here until the end of the function, we have the GIL, so we
698 can operate on our global data structures without worrying. */
699 wakeup
= gdbpy_event_list
== NULL
;
701 event
= XNEW (struct gdbpy_event
);
704 *gdbpy_event_list_end
= event
;
705 gdbpy_event_list_end
= &event
->next
;
707 /* Wake up gdb when needed. */
710 char c
= 'q'; /* Anything. */
712 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
713 return PyErr_SetFromErrno (PyExc_IOError
);
719 /* Initialize the Python event handler. */
721 gdbpy_initialize_events (void)
723 if (serial_pipe (gdbpy_event_fds
) == 0)
725 gdbpy_event_list_end
= &gdbpy_event_list
;
726 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
733 before_prompt_hook (const char *current_gdb_prompt
)
735 struct cleanup
*cleanup
;
738 cleanup
= ensure_python_env (get_current_arch (), current_language
);
740 if (PyObject_HasAttrString (gdb_module
, "prompt_hook"))
744 hook
= PyObject_GetAttrString (gdb_module
, "prompt_hook");
748 if (PyCallable_Check (hook
))
751 PyObject
*current_prompt
;
753 current_prompt
= PyString_FromString (current_gdb_prompt
);
754 if (current_prompt
== NULL
)
757 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
759 Py_DECREF (current_prompt
);
764 make_cleanup_py_decref (result
);
766 /* Return type should be None, or a String. If it is None,
767 fall through, we will not set a prompt. If it is a
768 string, set PROMPT. Anything else, set an exception. */
769 if (result
!= Py_None
&& ! PyString_Check (result
))
771 PyErr_Format (PyExc_RuntimeError
,
772 _("Return from prompt_hook must " \
773 "be either a Python string, or None"));
777 if (result
!= Py_None
)
779 prompt
= python_string_to_host_string (result
);
784 make_cleanup (xfree
, prompt
);
789 /* If a prompt has been set, PROMPT will not be NULL. If it is
790 NULL, do not set the prompt. */
794 do_cleanups (cleanup
);
798 gdbpy_print_stack ();
799 do_cleanups (cleanup
);
807 /* A python function to write a single string using gdb's filtered
808 output stream . The optional keyword STREAM can be used to write
809 to a particular stream. The default stream is to gdb_stdout. */
812 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
815 static char *keywords
[] = {"text", "stream", NULL
};
818 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
826 fprintf_filtered (gdb_stderr
, "%s", arg
);
831 fprintf_filtered (gdb_stdlog
, "%s", arg
);
835 fprintf_filtered (gdb_stdout
, "%s", arg
);
841 /* A python function to flush a gdb stream. The optional keyword
842 STREAM can be used to flush a particular stream. The default stream
846 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
848 static char *keywords
[] = {"stream", NULL
};
851 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
859 gdb_flush (gdb_stderr
);
864 gdb_flush (gdb_stdlog
);
868 gdb_flush (gdb_stdout
);
874 /* Print a python exception trace, or print nothing and clear the
875 python exception, depending on gdbpy_should_print_stack. Only call
876 this if a python exception is set. */
878 gdbpy_print_stack (void)
880 if (gdbpy_should_print_stack
)
883 /* PyErr_Print doesn't necessarily end output with a newline.
884 This works because Python's stdout/stderr is fed through
894 /* Return the current Progspace.
895 There always is one. */
898 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
902 result
= pspace_to_pspace_object (current_program_space
);
908 /* Return a sequence holding all the Progspaces. */
911 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
913 struct program_space
*ps
;
916 list
= PyList_New (0);
922 PyObject
*item
= pspace_to_pspace_object (ps
);
924 if (!item
|| PyList_Append (list
, item
) == -1)
936 /* The "current" objfile. This is set when gdb detects that a new
937 objfile has been loaded. It is only set for the duration of a call to
938 source_python_script_for_objfile; it is NULL at other times. */
939 static struct objfile
*gdbpy_current_objfile
;
941 /* Set the current objfile to OBJFILE and then read FILE as Python code.
942 This does not throw any errors. If an exception occurs python will print
943 the traceback and clear the error indicator. */
946 source_python_script_for_objfile (struct objfile
*objfile
, const char *file
)
948 struct cleanup
*cleanups
;
950 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
951 gdbpy_current_objfile
= objfile
;
953 python_run_simple_file (file
);
955 do_cleanups (cleanups
);
956 gdbpy_current_objfile
= NULL
;
959 /* Return the current Objfile, or None if there isn't one. */
962 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
966 if (! gdbpy_current_objfile
)
969 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
975 /* Return a sequence holding all the Objfiles. */
978 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
980 struct objfile
*objf
;
983 list
= PyList_New (0);
989 PyObject
*item
= objfile_to_objfile_object (objf
);
991 if (!item
|| PyList_Append (list
, item
) == -1)
1001 #else /* HAVE_PYTHON */
1003 /* Dummy implementation of the gdb "python" command. */
1006 python_command (char *arg
, int from_tty
)
1008 while (arg
&& *arg
&& isspace (*arg
))
1011 error (_("Python scripting is not supported in this copy of GDB."));
1014 struct command_line
*l
= get_command_line (python_control
, "");
1015 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1017 execute_control_command_untraced (l
);
1018 do_cleanups (cleanups
);
1023 eval_python_from_control_command (struct command_line
*cmd
)
1025 error (_("Python scripting is not supported in this copy of GDB."));
1029 source_python_script (const char *file
)
1031 throw_error (UNSUPPORTED_ERROR
,
1032 _("Python scripting is not supported in this copy of GDB."));
1036 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1038 internal_error (__FILE__
, __LINE__
,
1039 _("gdbpy_should_stop called when Python scripting is " \
1044 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1046 internal_error (__FILE__
, __LINE__
,
1047 _("gdbpy_breakpoint_has_py_cond called when Python " \
1048 "scripting is not supported."));
1051 #endif /* HAVE_PYTHON */
1055 /* Lists for 'maint set python' commands. */
1057 static struct cmd_list_element
*maint_set_python_list
;
1058 static struct cmd_list_element
*maint_show_python_list
;
1060 /* Lists for 'set python' commands. */
1062 static struct cmd_list_element
*user_set_python_list
;
1063 static struct cmd_list_element
*user_show_python_list
;
1065 /* Function for use by 'maint set python' prefix command. */
1068 maint_set_python (char *args
, int from_tty
)
1070 help_list (maint_set_python_list
, "maintenance set python ",
1071 class_deprecated
, gdb_stdout
);
1074 /* Function for use by 'maint show python' prefix command. */
1077 maint_show_python (char *args
, int from_tty
)
1079 cmd_show_list (maint_show_python_list
, from_tty
, "");
1082 /* Function for use by 'set python' prefix command. */
1085 user_set_python (char *args
, int from_tty
)
1087 help_list (user_set_python_list
, "set python ", all_commands
,
1091 /* Function for use by 'show python' prefix command. */
1094 user_show_python (char *args
, int from_tty
)
1096 cmd_show_list (user_show_python_list
, from_tty
, "");
1099 /* Initialize the Python code. */
1101 /* Provide a prototype to silence -Wmissing-prototypes. */
1102 extern initialize_file_ftype _initialize_python
;
1105 _initialize_python (void)
1108 struct cmd_list_element
*cmd
;
1110 add_com ("python", class_obscure
, python_command
,
1113 Evaluate a Python command.\n\
1115 The command can be given as an argument, for instance:\n\
1119 If no argument is given, the following lines are read and used\n\
1120 as the Python commands. Type a line containing \"end\" to indicate\n\
1121 the end of the command.")
1122 #else /* HAVE_PYTHON */
1124 Evaluate a Python command.\n\
1126 Python scripting is not supported in this copy of GDB.\n\
1127 This command is only a placeholder.")
1128 #endif /* HAVE_PYTHON */
1131 add_prefix_cmd ("python", no_class
, maint_show_python
,
1132 _("Prefix command for python maintenance settings."),
1133 &maint_show_python_list
, "maintenance show python ", 0,
1134 &maintenance_show_cmdlist
);
1135 add_prefix_cmd ("python", no_class
, maint_set_python
,
1136 _("Prefix command for python maintenance settings."),
1137 &maint_set_python_list
, "maintenance set python ", 0,
1138 &maintenance_set_cmdlist
);
1140 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
1141 &gdbpy_should_print_stack
, _("\
1142 Enable or disable printing of Python stack dump on error."), _("\
1143 Show whether Python stack will be printed on error."), _("\
1144 Enables or disables printing of Python stack traces."),
1146 &maint_set_python_list
,
1147 &maint_show_python_list
);
1149 /* Deprecate maint set/show python print-stack in favour of
1150 non-maintenance alternatives. */
1151 cmd_name
= "print-stack";
1152 cmd
= lookup_cmd (&cmd_name
, maint_set_python_list
, "", -1, 0);
1153 deprecate_cmd (cmd
, "set python print-stack");
1154 cmd_name
= "print-stack"; /* Reset name. */
1155 cmd
= lookup_cmd (&cmd_name
, maint_show_python_list
, "", -1, 0);
1156 deprecate_cmd (cmd
, "show python print-stack");
1158 /* Add set/show python print-stack. */
1159 add_prefix_cmd ("python", no_class
, user_show_python
,
1160 _("Prefix command for python preference settings."),
1161 &user_show_python_list
, "show python ", 0,
1164 add_prefix_cmd ("python", no_class
, user_set_python
,
1165 _("Prefix command for python preference settings."),
1166 &user_set_python_list
, "set python ", 0,
1169 add_setshow_boolean_cmd ("print-stack", no_class
,
1170 &gdbpy_should_print_stack
, _("\
1171 Enable or disable printing of Python stack dump on error."), _("\
1172 Show whether Python stack will be printed on error."), _("\
1173 Enables or disables printing of Python stack traces."),
1175 &user_set_python_list
,
1176 &user_show_python_list
);
1179 #ifdef WITH_PYTHON_PATH
1180 /* Work around problem where python gets confused about where it is,
1181 and then can't find its libraries, etc.
1182 NOTE: Python assumes the following layout:
1184 /foo/lib/pythonX.Y/...
1185 This must be done before calling Py_Initialize. */
1186 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1187 SLASH_STRING
, "python", NULL
));
1191 PyEval_InitThreads ();
1193 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
1195 /* The casts to (char*) are for python 2.4. */
1196 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1197 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1198 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1199 (char*) target_name
);
1201 /* Add stream constants. */
1202 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1203 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1204 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1206 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1207 script below is run (depending on order of _initialize_* functions).
1208 Define the initial value of gdb.PYTHONDIR here. */
1210 char *gdb_pythondir
;
1212 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1213 PyModule_AddStringConstant (gdb_module
, "PYTHONDIR", gdb_pythondir
);
1214 xfree (gdb_pythondir
);
1217 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1218 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1220 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1221 gdbpy_gdb_error
, NULL
);
1222 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1224 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1225 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1227 gdbpy_initialize_auto_load ();
1228 gdbpy_initialize_values ();
1229 gdbpy_initialize_frames ();
1230 gdbpy_initialize_commands ();
1231 gdbpy_initialize_symbols ();
1232 gdbpy_initialize_symtabs ();
1233 gdbpy_initialize_blocks ();
1234 gdbpy_initialize_functions ();
1235 gdbpy_initialize_parameters ();
1236 gdbpy_initialize_types ();
1237 gdbpy_initialize_pspace ();
1238 gdbpy_initialize_objfile ();
1239 gdbpy_initialize_breakpoints ();
1240 gdbpy_initialize_lazy_string ();
1241 gdbpy_initialize_thread ();
1242 gdbpy_initialize_inferior ();
1243 gdbpy_initialize_events ();
1245 gdbpy_initialize_eventregistry ();
1246 gdbpy_initialize_py_events ();
1247 gdbpy_initialize_event ();
1248 gdbpy_initialize_stop_event ();
1249 gdbpy_initialize_signal_event ();
1250 gdbpy_initialize_breakpoint_event ();
1251 gdbpy_initialize_continue_event ();
1252 gdbpy_initialize_exited_event ();
1253 gdbpy_initialize_thread_event ();
1254 gdbpy_initialize_new_objfile_event () ;
1256 observer_attach_before_prompt (before_prompt_hook
);
1258 PyRun_SimpleString ("import gdb");
1259 PyRun_SimpleString ("gdb.pretty_printers = []");
1261 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1262 gdbpy_children_cst
= PyString_FromString ("children");
1263 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1264 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1265 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1266 gdbpy_value_cst
= PyString_FromString ("value");
1268 /* Release the GIL while gdb runs. */
1269 PyThreadState_Swap (NULL
);
1270 PyEval_ReleaseLock ();
1272 #endif /* HAVE_PYTHON */
1277 /* Perform the remaining python initializations.
1278 These must be done after GDB is at least mostly initialized.
1279 E.g., The "info pretty-printer" command needs the "info" prefix
1280 command installed. */
1283 finish_python_initialization (void)
1285 struct cleanup
*cleanup
;
1287 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1289 PyRun_SimpleString ("\
1293 class GdbOutputFile:\n\
1298 def isatty(self):\n\
1301 def write(self, s):\n\
1302 gdb.write(s, stream=gdb.STDOUT)\n \
1304 def writelines(self, iterable):\n\
1305 for line in iterable:\n\
1311 sys.stdout = GdbOutputFile()\n\
1313 class GdbOutputErrorFile:\n\
1318 def isatty(self):\n\
1321 def write(self, s):\n\
1322 gdb.write(s, stream=gdb.STDERR)\n \
1324 def writelines(self, iterable):\n\
1325 for line in iterable:\n\
1326 self.write(line)\n \
1331 sys.stderr = GdbOutputErrorFile()\n\
1333 # Ideally this would live in the gdb module, but it's intentionally written\n\
1334 # in python, and we need this to bootstrap the gdb module.\n\
1336 def GdbSetPythonDirectory (dir):\n\
1337 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1338 old_dir = gdb.PYTHONDIR\n\
1339 gdb.PYTHONDIR = dir\n\
1340 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1341 # that directory name at the start of sys.path to allow the Python\n\
1342 # interpreter to find them.\n\
1343 if old_dir in sys.path:\n\
1344 sys.path.remove (old_dir)\n\
1345 sys.path.insert (0, gdb.PYTHONDIR)\n\
1347 # Tell python where to find submodules of gdb.\n\
1348 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1350 # The gdb module is implemented in C rather than in Python. As a result,\n\
1351 # the associated __init.py__ script is not not executed by default when\n\
1352 # the gdb module gets imported. Execute that script manually if it\n\
1354 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1355 if os.path.exists (ipy):\n\
1358 # Install the default gdb.PYTHONDIR.\n\
1359 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1360 # Default prompt hook does nothing.\n\
1361 prompt_hook = None\n\
1364 do_cleanups (cleanup
);
1367 #endif /* HAVE_PYTHON */
1373 static PyMethodDef GdbMethods
[] =
1375 { "history", gdbpy_history
, METH_VARARGS
,
1376 "Get a value from history" },
1377 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1378 "Execute a gdb command" },
1379 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1380 "Return a gdb parameter's value" },
1382 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1383 "Return a tuple of all breakpoint objects" },
1385 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1386 "Find the default visualizer for a Value." },
1388 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1389 "Return the current Progspace." },
1390 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1391 "Return a sequence of all progspaces." },
1393 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1394 "Return the current Objfile being loaded, or None." },
1395 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1396 "Return a sequence of all loaded objfiles." },
1398 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1399 "newest_frame () -> gdb.Frame.\n\
1400 Return the newest frame object." },
1401 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1402 "selected_frame () -> gdb.Frame.\n\
1403 Return the selected frame object." },
1404 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1405 "stop_reason_string (Integer) -> String.\n\
1406 Return a string explaining unwind stop reason." },
1408 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1409 METH_VARARGS
| METH_KEYWORDS
,
1410 "lookup_type (name [, block]) -> type\n\
1411 Return a Type corresponding to the given name." },
1412 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1413 METH_VARARGS
| METH_KEYWORDS
,
1414 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1415 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1416 a boolean indicating if name is a field of the current implied argument\n\
1417 `this' (when the current language is object-oriented)." },
1418 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1419 METH_VARARGS
| METH_KEYWORDS
,
1420 "lookup_global_symbol (name [, domain]) -> symbol\n\
1421 Return the symbol corresponding to the given name (or None)." },
1422 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1423 "Return the block containing the given pc value, or None." },
1424 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1425 "solib_name (Long) -> String.\n\
1426 Return the name of the shared library holding a given address, or None." },
1427 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1428 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1429 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1430 The first element contains any unparsed portion of the String parameter\n\
1431 (or None if the string was fully parsed). The second element contains\n\
1432 a tuple that contains all the locations that match, represented as\n\
1433 gdb.Symtab_and_line objects (or None)."},
1434 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1435 "parse_and_eval (String) -> Value.\n\
1436 Parse String as an expression, evaluate it, and return the result as a Value."
1439 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1440 "Post an event into gdb's event loop." },
1442 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1443 "target_charset () -> string.\n\
1444 Return the name of the current target charset." },
1445 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1446 "target_wide_charset () -> string.\n\
1447 Return the name of the current target wide charset." },
1449 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1450 "string_to_argv (String) -> Array.\n\
1451 Parse String and return an argv-like array.\n\
1452 Arguments are separate by spaces and may be quoted."
1454 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1455 "Write a string using gdb's filtered stream." },
1456 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1457 "Flush gdb's filtered stdout stream." },
1458 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1459 "selected_thread () -> gdb.InferiorThread.\n\
1460 Return the selected thread object." },
1461 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1462 "selected_inferior () -> gdb.Inferior.\n\
1463 Return the selected inferior object." },
1464 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1465 "inferiors () -> (gdb.Inferior, ...).\n\
1466 Return a tuple containing all inferiors." },
1467 {NULL
, NULL
, 0, NULL
}
1470 #endif /* HAVE_PYTHON */