1 /* General python/gdb code
3 Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
26 #include "progspace.h"
30 #include "exceptions.h"
31 #include "event-loop.h"
33 #include "readline/tilde.h"
38 /* Declared constants and enum for python stack printing. */
39 static const char python_excp_none
[] = "none";
40 static const char python_excp_full
[] = "full";
41 static const char python_excp_message
[] = "message";
43 /* "set python print-stack" choices. */
44 static const char *const python_excp_enums
[] =
52 /* The exception printing variable. 'full' if we want to print the
53 error message and stack, 'none' if we want to print nothing, and
54 'message' if we only want to print the error message. 'message' is
56 static const char *gdbpy_should_print_stack
= python_excp_message
;
60 #include "libiberty.h"
61 #include "cli/cli-decode.h"
65 #include "python-internal.h"
70 #include "gdbthread.h"
73 #include "event-top.h"
75 static PyMethodDef GdbMethods
[];
78 static struct PyModuleDef GdbModuleDef
;
82 PyObject
*gdb_python_module
;
84 /* Some string constants we may wish to use. */
85 PyObject
*gdbpy_to_string_cst
;
86 PyObject
*gdbpy_children_cst
;
87 PyObject
*gdbpy_display_hint_cst
;
88 PyObject
*gdbpy_doc_cst
;
89 PyObject
*gdbpy_enabled_cst
;
90 PyObject
*gdbpy_value_cst
;
92 /* The GdbError exception. */
93 PyObject
*gdbpy_gdberror_exc
;
95 /* The `gdb.error' base class. */
96 PyObject
*gdbpy_gdb_error
;
98 /* The `gdb.MemoryError' exception. */
99 PyObject
*gdbpy_gdb_memory_error
;
101 /* Architecture and language to be used in callbacks from
102 the Python interpreter. */
103 struct gdbarch
*python_gdbarch
;
104 const struct language_defn
*python_language
;
106 /* Restore global language and architecture and Python GIL state
107 when leaving the Python interpreter. */
111 PyGILState_STATE state
;
112 struct gdbarch
*gdbarch
;
113 const struct language_defn
*language
;
114 PyObject
*error_type
, *error_value
, *error_traceback
;
118 restore_python_env (void *p
)
120 struct python_env
*env
= (struct python_env
*)p
;
122 /* Leftover Python error is forbidden by Python Exception Handling. */
123 if (PyErr_Occurred ())
125 /* This order is similar to the one calling error afterwards. */
126 gdbpy_print_stack ();
127 warning (_("internal error: Unhandled Python exception"));
130 PyErr_Restore (env
->error_type
, env
->error_value
, env
->error_traceback
);
132 PyGILState_Release (env
->state
);
133 python_gdbarch
= env
->gdbarch
;
134 python_language
= env
->language
;
138 /* Called before entering the Python interpreter to install the
139 current language and architecture to be used for Python values. */
142 ensure_python_env (struct gdbarch
*gdbarch
,
143 const struct language_defn
*language
)
145 struct python_env
*env
= xmalloc (sizeof *env
);
147 env
->state
= PyGILState_Ensure ();
148 env
->gdbarch
= python_gdbarch
;
149 env
->language
= python_language
;
151 python_gdbarch
= gdbarch
;
152 python_language
= language
;
154 /* Save it and ensure ! PyErr_Occurred () afterwards. */
155 PyErr_Fetch (&env
->error_type
, &env
->error_value
, &env
->error_traceback
);
157 return make_cleanup (restore_python_env
, env
);
160 /* Clear the quit flag. */
163 clear_quit_flag (void)
165 /* This clears the flag as a side effect. */
166 PyOS_InterruptOccurred ();
169 /* Set the quit flag. */
174 PyErr_SetInterrupt ();
177 /* Return true if the quit flag has been set, false otherwise. */
180 check_quit_flag (void)
182 return PyOS_InterruptOccurred ();
185 /* Evaluate a Python command like PyRun_SimpleString, but uses
186 Py_single_input which prints the result of expressions, and does
187 not automatically print the stack on errors. */
190 eval_python_command (const char *command
)
194 m
= PyImport_AddModule ("__main__");
198 d
= PyModule_GetDict (m
);
201 v
= PyRun_StringFlags (command
, Py_single_input
, d
, d
, NULL
);
214 /* Implementation of the gdb "python-interactive" command. */
217 python_interactive_command (char *arg
, int from_tty
)
219 struct cleanup
*cleanup
;
222 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
223 interpreter_async
= 0;
225 while (arg
&& *arg
&& isspace (*arg
))
228 ensure_python_env (get_current_arch (), current_language
);
232 int len
= strlen (arg
);
233 char *script
= xmalloc (len
+ 2);
235 strcpy (script
, arg
);
237 script
[len
+ 1] = '\0';
238 err
= eval_python_command (script
);
243 err
= PyRun_InteractiveLoop (instream
, "<stdin>");
249 gdbpy_print_stack ();
250 error (_("Error while executing Python code."));
253 do_cleanups (cleanup
);
256 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
259 On Windows hosts few users would build Python themselves (this is no
260 trivial task on this platform), and thus use binaries built by
261 someone else instead. There may happen situation where the Python
262 library and GDB are using two different versions of the C runtime
263 library. Python, being built with VC, would use one version of the
264 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
265 A FILE * from one runtime does not necessarily operate correctly in
268 To work around this potential issue, we create on Windows hosts the
269 FILE object using Python routines, thus making sure that it is
270 compatible with the Python library. */
273 python_run_simple_file (FILE *file
, const char *filename
)
277 PyRun_SimpleFile (file
, filename
);
282 PyObject
*python_file
;
283 struct cleanup
*cleanup
;
285 /* Because we have a string for a filename, and are using Python to
286 open the file, we need to expand any tilde in the path first. */
287 full_path
= tilde_expand (filename
);
288 cleanup
= make_cleanup (xfree
, full_path
);
289 python_file
= PyFile_FromString (full_path
, "r");
292 do_cleanups (cleanup
);
293 gdbpy_print_stack ();
294 error (_("Error while opening file: %s"), full_path
);
297 make_cleanup_py_decref (python_file
);
298 PyRun_SimpleFile (PyFile_AsFile (python_file
), filename
);
299 do_cleanups (cleanup
);
304 /* Given a command_line, return a command string suitable for passing
305 to Python. Lines in the string are separated by newlines. The
306 return value is allocated using xmalloc and the caller is
307 responsible for freeing it. */
310 compute_python_string (struct command_line
*l
)
312 struct command_line
*iter
;
317 for (iter
= l
; iter
; iter
= iter
->next
)
318 size
+= strlen (iter
->line
) + 1;
320 script
= xmalloc (size
+ 1);
322 for (iter
= l
; iter
; iter
= iter
->next
)
324 int len
= strlen (iter
->line
);
326 strcpy (&script
[here
], iter
->line
);
328 script
[here
++] = '\n';
334 /* Take a command line structure representing a 'python' command, and
335 evaluate its body using the Python interpreter. */
338 eval_python_from_control_command (struct command_line
*cmd
)
342 struct cleanup
*cleanup
;
344 if (cmd
->body_count
!= 1)
345 error (_("Invalid \"python\" block structure."));
347 cleanup
= ensure_python_env (get_current_arch (), current_language
);
349 script
= compute_python_string (cmd
->body_list
[0]);
350 ret
= PyRun_SimpleString (script
);
353 error (_("Error while executing Python code."));
355 do_cleanups (cleanup
);
358 /* Implementation of the gdb "python" command. */
361 python_command (char *arg
, int from_tty
)
363 struct cleanup
*cleanup
;
365 cleanup
= ensure_python_env (get_current_arch (), current_language
);
367 make_cleanup_restore_integer (&interpreter_async
);
368 interpreter_async
= 0;
370 while (arg
&& *arg
&& isspace (*arg
))
374 if (PyRun_SimpleString (arg
))
375 error (_("Error while executing Python code."));
379 struct command_line
*l
= get_command_line (python_control
, "");
381 make_cleanup_free_command_lines (&l
);
382 execute_control_command_untraced (l
);
385 do_cleanups (cleanup
);
390 /* Transform a gdb parameters's value into a Python value. May return
391 NULL (and set a Python exception) on error. Helper function for
394 gdbpy_parameter_value (enum var_types type
, void *var
)
399 case var_string_noescape
:
400 case var_optional_filename
:
404 char *str
= * (char **) var
;
408 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
419 case var_auto_boolean
:
421 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
423 if (ab
== AUTO_BOOLEAN_TRUE
)
425 else if (ab
== AUTO_BOOLEAN_FALSE
)
432 if ((* (int *) var
) == INT_MAX
)
436 return PyLong_FromLong (* (int *) var
);
440 unsigned int val
= * (unsigned int *) var
;
444 return PyLong_FromUnsignedLong (val
);
448 return PyErr_Format (PyExc_RuntimeError
,
449 _("Programmer error: unhandled type."));
452 /* A Python function which returns a gdb parameter's value as a Python
456 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
458 struct cmd_list_element
*alias
, *prefix
, *cmd
;
462 volatile struct gdb_exception except
;
464 if (! PyArg_ParseTuple (args
, "s", &arg
))
467 newarg
= concat ("show ", arg
, (char *) NULL
);
469 TRY_CATCH (except
, RETURN_MASK_ALL
)
471 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
474 GDB_PY_HANDLE_EXCEPTION (except
);
476 return PyErr_Format (PyExc_RuntimeError
,
477 _("Could not find parameter `%s'."), arg
);
480 return PyErr_Format (PyExc_RuntimeError
,
481 _("`%s' is not a parameter."), arg
);
482 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
485 /* Wrapper for target_charset. */
488 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
490 const char *cset
= target_charset (python_gdbarch
);
492 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
495 /* Wrapper for target_wide_charset. */
498 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
500 const char *cset
= target_wide_charset (python_gdbarch
);
502 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
505 /* A Python function which evaluates a string using the gdb CLI. */
508 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
511 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
512 int from_tty
, to_string
;
513 volatile struct gdb_exception except
;
514 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
517 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
518 &PyBool_Type
, &from_tty_obj
,
519 &PyBool_Type
, &to_string_obj
))
525 int cmp
= PyObject_IsTrue (from_tty_obj
);
534 int cmp
= PyObject_IsTrue (to_string_obj
);
540 TRY_CATCH (except
, RETURN_MASK_ALL
)
542 /* Copy the argument text in case the command modifies it. */
543 char *copy
= xstrdup (arg
);
544 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
546 make_cleanup_restore_integer (&interpreter_async
);
547 interpreter_async
= 0;
549 prevent_dont_repeat ();
551 result
= execute_command_to_string (copy
, from_tty
);
555 execute_command (copy
, from_tty
);
558 do_cleanups (cleanup
);
560 GDB_PY_HANDLE_EXCEPTION (except
);
562 /* Do any commands attached to breakpoint we stopped at. */
563 bpstat_do_actions ();
567 PyObject
*r
= PyString_FromString (result
);
574 /* Implementation of gdb.solib_name (Long) -> String.
575 Returns the name of the shared library holding a given address, or None. */
578 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
584 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
587 soname
= solib_name_from_address (current_program_space
, pc
);
589 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
599 /* A Python function which is a wrapper for decode_line_1. */
602 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
604 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
606 struct symtab_and_line sal
;
607 const char *arg
= NULL
;
608 char *copy_to_free
= NULL
, *copy
= NULL
;
609 struct cleanup
*cleanups
;
610 PyObject
*result
= NULL
;
611 PyObject
*return_result
= NULL
;
612 PyObject
*unparsed
= NULL
;
613 volatile struct gdb_exception except
;
615 if (! PyArg_ParseTuple (args
, "|s", &arg
))
618 cleanups
= make_cleanup (null_cleanup
, NULL
);
621 TRY_CATCH (except
, RETURN_MASK_ALL
)
625 copy
= xstrdup (arg
);
627 sals
= decode_line_1 (©
, 0, 0, 0);
631 set_default_source_symtab_and_line ();
632 sal
= get_current_source_symtab_and_line ();
638 if (sals
.sals
!= NULL
&& sals
.sals
!= &sal
)
640 make_cleanup (xfree
, copy_to_free
);
641 make_cleanup (xfree
, sals
.sals
);
644 if (except
.reason
< 0)
646 do_cleanups (cleanups
);
647 /* We know this will always throw. */
648 GDB_PY_HANDLE_EXCEPTION (except
);
655 result
= PyTuple_New (sals
.nelts
);
658 for (i
= 0; i
< sals
.nelts
; ++i
)
662 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
669 PyTuple_SetItem (result
, i
, obj
);
678 return_result
= PyTuple_New (2);
685 if (copy
&& strlen (copy
) > 0)
687 unparsed
= PyString_FromString (copy
);
688 if (unparsed
== NULL
)
691 Py_DECREF (return_result
);
692 return_result
= NULL
;
702 PyTuple_SetItem (return_result
, 0, unparsed
);
703 PyTuple_SetItem (return_result
, 1, result
);
706 do_cleanups (cleanups
);
708 return return_result
;
711 /* Parse a string and evaluate it as an expression. */
713 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
715 const char *expr_str
;
716 struct value
*result
= NULL
;
717 volatile struct gdb_exception except
;
719 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
722 TRY_CATCH (except
, RETURN_MASK_ALL
)
724 char *copy
= xstrdup (expr_str
);
725 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
727 result
= parse_and_eval (copy
);
728 do_cleanups (cleanup
);
730 GDB_PY_HANDLE_EXCEPTION (except
);
732 return value_to_value_object (result
);
735 /* Implementation of gdb.find_pc_line function.
736 Returns the gdb.Symtab_and_line object corresponding to a PC value. */
739 gdbpy_find_pc_line (PyObject
*self
, PyObject
*args
)
741 struct symtab_and_line sal
;
743 gdb_py_ulongest pc_llu
;
745 if (!PyArg_ParseTuple (args
, GDB_PY_LLU_ARG
, &pc_llu
))
748 pc
= (CORE_ADDR
) pc_llu
;
749 sal
= find_pc_line (pc
, 0);
750 return symtab_and_line_to_sal_object (sal
);
753 /* Read a file as Python code.
754 FILE is the file to run. FILENAME is name of the file FILE.
755 This does not throw any errors. If an exception occurs python will print
756 the traceback and clear the error indicator. */
759 source_python_script (FILE *file
, const char *filename
)
761 struct cleanup
*cleanup
;
763 cleanup
= ensure_python_env (get_current_arch (), current_language
);
764 python_run_simple_file (file
, filename
);
765 do_cleanups (cleanup
);
770 /* Posting and handling events. */
772 /* A single event. */
775 /* The Python event. This is just a callable object. */
777 /* The next event. */
778 struct gdbpy_event
*next
;
781 /* All pending events. */
782 static struct gdbpy_event
*gdbpy_event_list
;
783 /* The final link of the event list. */
784 static struct gdbpy_event
**gdbpy_event_list_end
;
786 /* We use a file handler, and not an async handler, so that we can
787 wake up the main thread even when it is blocked in poll(). */
788 static struct serial
*gdbpy_event_fds
[2];
790 /* The file handler callback. This reads from the internal pipe, and
791 then processes the Python event queue. This will always be run in
792 the main gdb thread. */
795 gdbpy_run_events (struct serial
*scb
, void *context
)
797 struct cleanup
*cleanup
;
799 cleanup
= ensure_python_env (get_current_arch (), current_language
);
801 /* Flush the fd. Do this before flushing the events list, so that
802 any new event post afterwards is sure to re-awake the event
804 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
807 while (gdbpy_event_list
)
809 /* Dispatching the event might push a new element onto the event
810 loop, so we update here "atomically enough". */
811 struct gdbpy_event
*item
= gdbpy_event_list
;
812 gdbpy_event_list
= gdbpy_event_list
->next
;
813 if (gdbpy_event_list
== NULL
)
814 gdbpy_event_list_end
= &gdbpy_event_list
;
817 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
820 Py_DECREF (item
->event
);
824 do_cleanups (cleanup
);
827 /* Submit an event to the gdb thread. */
829 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
831 struct gdbpy_event
*event
;
835 if (!PyArg_ParseTuple (args
, "O", &func
))
838 if (!PyCallable_Check (func
))
840 PyErr_SetString (PyExc_RuntimeError
,
841 _("Posted event is not callable"));
847 /* From here until the end of the function, we have the GIL, so we
848 can operate on our global data structures without worrying. */
849 wakeup
= gdbpy_event_list
== NULL
;
851 event
= XNEW (struct gdbpy_event
);
854 *gdbpy_event_list_end
= event
;
855 gdbpy_event_list_end
= &event
->next
;
857 /* Wake up gdb when needed. */
860 char c
= 'q'; /* Anything. */
862 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
863 return PyErr_SetFromErrno (PyExc_IOError
);
869 /* Initialize the Python event handler. */
871 gdbpy_initialize_events (void)
873 if (serial_pipe (gdbpy_event_fds
) == 0)
875 gdbpy_event_list_end
= &gdbpy_event_list
;
876 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
883 before_prompt_hook (const char *current_gdb_prompt
)
885 struct cleanup
*cleanup
;
888 cleanup
= ensure_python_env (get_current_arch (), current_language
);
890 if (gdb_python_module
891 && PyObject_HasAttrString (gdb_python_module
, "prompt_hook"))
895 hook
= PyObject_GetAttrString (gdb_python_module
, "prompt_hook");
899 if (PyCallable_Check (hook
))
902 PyObject
*current_prompt
;
904 current_prompt
= PyString_FromString (current_gdb_prompt
);
905 if (current_prompt
== NULL
)
908 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
910 Py_DECREF (current_prompt
);
915 make_cleanup_py_decref (result
);
917 /* Return type should be None, or a String. If it is None,
918 fall through, we will not set a prompt. If it is a
919 string, set PROMPT. Anything else, set an exception. */
920 if (result
!= Py_None
&& ! PyString_Check (result
))
922 PyErr_Format (PyExc_RuntimeError
,
923 _("Return from prompt_hook must " \
924 "be either a Python string, or None"));
928 if (result
!= Py_None
)
930 prompt
= python_string_to_host_string (result
);
935 make_cleanup (xfree
, prompt
);
940 /* If a prompt has been set, PROMPT will not be NULL. If it is
941 NULL, do not set the prompt. */
945 do_cleanups (cleanup
);
949 gdbpy_print_stack ();
950 do_cleanups (cleanup
);
958 /* A python function to write a single string using gdb's filtered
959 output stream . The optional keyword STREAM can be used to write
960 to a particular stream. The default stream is to gdb_stdout. */
963 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
966 static char *keywords
[] = {"text", "stream", NULL
};
968 volatile struct gdb_exception except
;
970 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
974 TRY_CATCH (except
, RETURN_MASK_ALL
)
980 fprintf_filtered (gdb_stderr
, "%s", arg
);
985 fprintf_filtered (gdb_stdlog
, "%s", arg
);
989 fprintf_filtered (gdb_stdout
, "%s", arg
);
992 GDB_PY_HANDLE_EXCEPTION (except
);
997 /* A python function to flush a gdb stream. The optional keyword
998 STREAM can be used to flush a particular stream. The default stream
1002 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1004 static char *keywords
[] = {"stream", NULL
};
1005 int stream_type
= 0;
1007 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
1011 switch (stream_type
)
1015 gdb_flush (gdb_stderr
);
1020 gdb_flush (gdb_stdlog
);
1024 gdb_flush (gdb_stdout
);
1030 /* Print a python exception trace, print just a message, or print
1031 nothing and clear the python exception, depending on
1032 gdbpy_should_print_stack. Only call this if a python exception is
1035 gdbpy_print_stack (void)
1037 /* Print "none", just clear exception. */
1038 if (gdbpy_should_print_stack
== python_excp_none
)
1042 /* Print "full" message and backtrace. */
1043 else if (gdbpy_should_print_stack
== python_excp_full
)
1046 /* PyErr_Print doesn't necessarily end output with a newline.
1047 This works because Python's stdout/stderr is fed through
1051 /* Print "message", just error print message. */
1054 PyObject
*ptype
, *pvalue
, *ptraceback
;
1055 char *msg
= NULL
, *type
= NULL
;
1057 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
1059 /* Fetch the error message contained within ptype, pvalue. */
1060 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
1061 type
= gdbpy_obj_to_string (ptype
);
1064 /* An error occurred computing the string representation of the
1066 fprintf_filtered (gdb_stderr
,
1067 _("Error occurred computing Python error" \
1071 fprintf_filtered (gdb_stderr
, "Python Exception %s %s: \n",
1075 Py_XDECREF (pvalue
);
1076 Py_XDECREF (ptraceback
);
1083 /* Return the current Progspace.
1084 There always is one. */
1087 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
1091 result
= pspace_to_pspace_object (current_program_space
);
1097 /* Return a sequence holding all the Progspaces. */
1100 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
1102 struct program_space
*ps
;
1105 list
= PyList_New (0);
1111 PyObject
*item
= pspace_to_pspace_object (ps
);
1113 if (!item
|| PyList_Append (list
, item
) == -1)
1125 /* The "current" objfile. This is set when gdb detects that a new
1126 objfile has been loaded. It is only set for the duration of a call to
1127 source_python_script_for_objfile; it is NULL at other times. */
1128 static struct objfile
*gdbpy_current_objfile
;
1130 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1131 as Python code. This does not throw any errors. If an exception
1132 occurs python will print the traceback and clear the error indicator. */
1135 source_python_script_for_objfile (struct objfile
*objfile
, FILE *file
,
1136 const char *filename
)
1138 struct cleanup
*cleanups
;
1140 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
1141 gdbpy_current_objfile
= objfile
;
1143 python_run_simple_file (file
, filename
);
1145 do_cleanups (cleanups
);
1146 gdbpy_current_objfile
= NULL
;
1149 /* Return the current Objfile, or None if there isn't one. */
1152 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
1156 if (! gdbpy_current_objfile
)
1159 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
1165 /* Return a sequence holding all the Objfiles. */
1168 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
1170 struct objfile
*objf
;
1173 list
= PyList_New (0);
1179 PyObject
*item
= objfile_to_objfile_object (objf
);
1181 if (!item
|| PyList_Append (list
, item
) == -1)
1191 /* Compute the list of active type printers and return it. The result
1192 of this function can be passed to apply_type_printers, and should
1193 be freed by free_type_printers. */
1196 start_type_printers (void)
1198 struct cleanup
*cleanups
;
1199 PyObject
*type_module
, *func
, *result_obj
= NULL
;
1201 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1203 type_module
= PyImport_ImportModule ("gdb.types");
1204 if (type_module
== NULL
)
1206 gdbpy_print_stack ();
1209 make_cleanup_py_decref (type_module
);
1211 func
= PyObject_GetAttrString (type_module
, "get_type_recognizers");
1214 gdbpy_print_stack ();
1217 make_cleanup_py_decref (func
);
1219 result_obj
= PyObject_CallFunctionObjArgs (func
, (char *) NULL
);
1220 if (result_obj
== NULL
)
1221 gdbpy_print_stack ();
1224 do_cleanups (cleanups
);
1228 /* If TYPE is recognized by some type printer, return a newly
1229 allocated string holding the type's replacement name. The caller
1230 is responsible for freeing the string. Otherwise, return NULL.
1232 This function has a bit of a funny name, since it actually applies
1233 recognizers, but this seemed clearer given the start_type_printers
1234 and free_type_printers functions. */
1237 apply_type_printers (void *printers
, struct type
*type
)
1239 struct cleanup
*cleanups
;
1240 PyObject
*type_obj
, *type_module
, *func
, *result_obj
;
1241 PyObject
*printers_obj
= printers
;
1242 char *result
= NULL
;
1244 if (printers_obj
== NULL
)
1247 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1249 type_obj
= type_to_type_object (type
);
1250 if (type_obj
== NULL
)
1252 gdbpy_print_stack ();
1255 make_cleanup_py_decref (type_obj
);
1257 type_module
= PyImport_ImportModule ("gdb.types");
1258 if (type_module
== NULL
)
1260 gdbpy_print_stack ();
1263 make_cleanup_py_decref (type_module
);
1265 func
= PyObject_GetAttrString (type_module
, "apply_type_recognizers");
1268 gdbpy_print_stack ();
1271 make_cleanup_py_decref (func
);
1273 result_obj
= PyObject_CallFunctionObjArgs (func
, printers_obj
,
1274 type_obj
, (char *) NULL
);
1275 if (result_obj
== NULL
)
1277 gdbpy_print_stack ();
1280 make_cleanup_py_decref (result_obj
);
1282 if (result_obj
!= Py_None
)
1284 result
= python_string_to_host_string (result_obj
);
1286 gdbpy_print_stack ();
1290 do_cleanups (cleanups
);
1294 /* Free the result of start_type_printers. */
1297 free_type_printers (void *arg
)
1299 struct cleanup
*cleanups
;
1300 PyObject
*printers
= arg
;
1302 if (printers
== NULL
)
1305 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1306 Py_DECREF (printers
);
1307 do_cleanups (cleanups
);
1310 #else /* HAVE_PYTHON */
1312 /* Dummy implementation of the gdb "python-interactive" and "python"
1316 python_interactive_command (char *arg
, int from_tty
)
1318 while (arg
&& *arg
&& isspace (*arg
))
1321 error (_("Python scripting is not supported in this copy of GDB."));
1324 struct command_line
*l
= get_command_line (python_control
, "");
1325 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1327 execute_control_command_untraced (l
);
1328 do_cleanups (cleanups
);
1333 python_command (char *arg
, int from_tty
)
1335 python_interactive_command (arg
, from_tty
);
1339 eval_python_from_control_command (struct command_line
*cmd
)
1341 error (_("Python scripting is not supported in this copy of GDB."));
1345 source_python_script (FILE *file
, const char *filename
)
1347 throw_error (UNSUPPORTED_ERROR
,
1348 _("Python scripting is not supported in this copy of GDB."));
1352 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1354 internal_error (__FILE__
, __LINE__
,
1355 _("gdbpy_should_stop called when Python scripting is " \
1360 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1362 internal_error (__FILE__
, __LINE__
,
1363 _("gdbpy_breakpoint_has_py_cond called when Python " \
1364 "scripting is not supported."));
1368 start_type_printers (void)
1374 apply_type_printers (void *ignore
, struct type
*type
)
1380 free_type_printers (void *arg
)
1384 #endif /* HAVE_PYTHON */
1388 /* Lists for 'set python' commands. */
1390 static struct cmd_list_element
*user_set_python_list
;
1391 static struct cmd_list_element
*user_show_python_list
;
1393 /* Function for use by 'set python' prefix command. */
1396 user_set_python (char *args
, int from_tty
)
1398 help_list (user_set_python_list
, "set python ", all_commands
,
1402 /* Function for use by 'show python' prefix command. */
1405 user_show_python (char *args
, int from_tty
)
1407 cmd_show_list (user_show_python_list
, from_tty
, "");
1410 /* Initialize the Python code. */
1414 /* This is installed as a final cleanup and cleans up the
1415 interpreter. This lets Python's 'atexit' work. */
1418 finalize_python (void *ignore
)
1420 /* We don't use ensure_python_env here because if we ever ran the
1421 cleanup, gdb would crash -- because the cleanup calls into the
1422 Python interpreter, which we are about to destroy. It seems
1423 clearer to make the needed calls explicitly here than to create a
1424 cleanup and then mysteriously discard it. */
1425 (void) PyGILState_Ensure ();
1426 python_gdbarch
= target_gdbarch ();
1427 python_language
= current_language
;
1433 /* Provide a prototype to silence -Wmissing-prototypes. */
1434 extern initialize_file_ftype _initialize_python
;
1437 _initialize_python (void)
1440 struct cmd_list_element
*cmd
;
1444 size_t progsize
, count
;
1446 wchar_t *progname_copy
;
1449 add_com ("python-interactive", class_obscure
,
1450 python_interactive_command
,
1453 Start an interactive Python prompt.\n\
1455 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1458 Alternatively, a single-line Python command can be given as an\n\
1459 argument, and if the command is an expression, the result will be\n\
1460 printed. For example:\n\
1462 (gdb) python-interactive 2 + 3\n\
1465 #else /* HAVE_PYTHON */
1467 Start a Python interactive prompt.\n\
1469 Python scripting is not supported in this copy of GDB.\n\
1470 This command is only a placeholder.")
1471 #endif /* HAVE_PYTHON */
1473 add_com_alias ("pi", "python-interactive", class_obscure
, 1);
1475 add_com ("python", class_obscure
, python_command
,
1478 Evaluate a Python command.\n\
1480 The command can be given as an argument, for instance:\n\
1484 If no argument is given, the following lines are read and used\n\
1485 as the Python commands. Type a line containing \"end\" to indicate\n\
1486 the end of the command.")
1487 #else /* HAVE_PYTHON */
1489 Evaluate a Python command.\n\
1491 Python scripting is not supported in this copy of GDB.\n\
1492 This command is only a placeholder.")
1493 #endif /* HAVE_PYTHON */
1495 add_com_alias ("py", "python", class_obscure
, 1);
1497 /* Add set/show python print-stack. */
1498 add_prefix_cmd ("python", no_class
, user_show_python
,
1499 _("Prefix command for python preference settings."),
1500 &user_show_python_list
, "show python ", 0,
1503 add_prefix_cmd ("python", no_class
, user_set_python
,
1504 _("Prefix command for python preference settings."),
1505 &user_set_python_list
, "set python ", 0,
1508 add_setshow_enum_cmd ("print-stack", no_class
, python_excp_enums
,
1509 &gdbpy_should_print_stack
, _("\
1510 Set mode for Python stack dump on error."), _("\
1511 Show the mode of Python stack printing on error."), _("\
1512 none == no stack or message will be printed.\n\
1513 full == a message and a stack will be printed.\n\
1514 message == an error message without a stack will be printed."),
1516 &user_set_python_list
,
1517 &user_show_python_list
);
1520 #ifdef WITH_PYTHON_PATH
1521 /* Work around problem where python gets confused about where it is,
1522 and then can't find its libraries, etc.
1523 NOTE: Python assumes the following layout:
1525 /foo/lib/pythonX.Y/...
1526 This must be done before calling Py_Initialize. */
1527 progname
= concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1528 SLASH_STRING
, "python", NULL
);
1530 oldloc
= setlocale (LC_ALL
, NULL
);
1531 setlocale (LC_ALL
, "");
1532 progsize
= strlen (progname
);
1533 if (progsize
== (size_t) -1)
1535 fprintf (stderr
, "Could not convert python path to string\n");
1538 progname_copy
= PyMem_Malloc ((progsize
+ 1) * sizeof (wchar_t));
1541 fprintf (stderr
, "out of memory\n");
1544 count
= mbstowcs (progname_copy
, progname
, progsize
+ 1);
1545 if (count
== (size_t) -1)
1547 fprintf (stderr
, "Could not convert python path to string\n");
1550 setlocale (LC_ALL
, oldloc
);
1552 /* Note that Py_SetProgramName expects the string it is passed to
1553 remain alive for the duration of the program's execution, so
1554 it is not freed after this call. */
1555 Py_SetProgramName (progname_copy
);
1557 Py_SetProgramName (progname
);
1562 PyEval_InitThreads ();
1565 gdb_module
= PyModule_Create (&GdbModuleDef
);
1566 /* Add _gdb module to the list of known built-in modules. */
1567 _PyImport_FixupBuiltin (gdb_module
, "_gdb");
1569 gdb_module
= Py_InitModule ("_gdb", GdbMethods
);
1572 /* The casts to (char*) are for python 2.4. */
1573 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1574 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1575 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1576 (char*) target_name
);
1578 /* Add stream constants. */
1579 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1580 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1581 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1583 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1584 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1586 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1587 gdbpy_gdb_error
, NULL
);
1588 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1590 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1591 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1593 gdbpy_initialize_gdb_readline ();
1594 gdbpy_initialize_auto_load ();
1595 gdbpy_initialize_values ();
1596 gdbpy_initialize_frames ();
1597 gdbpy_initialize_commands ();
1598 gdbpy_initialize_symbols ();
1599 gdbpy_initialize_symtabs ();
1600 gdbpy_initialize_blocks ();
1601 gdbpy_initialize_functions ();
1602 gdbpy_initialize_parameters ();
1603 gdbpy_initialize_types ();
1604 gdbpy_initialize_pspace ();
1605 gdbpy_initialize_objfile ();
1606 gdbpy_initialize_breakpoints ();
1607 gdbpy_initialize_finishbreakpoints ();
1608 gdbpy_initialize_lazy_string ();
1609 gdbpy_initialize_thread ();
1610 gdbpy_initialize_inferior ();
1611 gdbpy_initialize_events ();
1613 gdbpy_initialize_eventregistry ();
1614 gdbpy_initialize_py_events ();
1615 gdbpy_initialize_event ();
1616 gdbpy_initialize_stop_event ();
1617 gdbpy_initialize_signal_event ();
1618 gdbpy_initialize_breakpoint_event ();
1619 gdbpy_initialize_continue_event ();
1620 gdbpy_initialize_exited_event ();
1621 gdbpy_initialize_thread_event ();
1622 gdbpy_initialize_new_objfile_event () ;
1624 observer_attach_before_prompt (before_prompt_hook
);
1626 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1627 gdbpy_children_cst
= PyString_FromString ("children");
1628 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1629 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1630 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1631 gdbpy_value_cst
= PyString_FromString ("value");
1633 /* Release the GIL while gdb runs. */
1634 PyThreadState_Swap (NULL
);
1635 PyEval_ReleaseLock ();
1637 make_final_cleanup (finalize_python
, NULL
);
1638 #endif /* HAVE_PYTHON */
1643 /* Perform the remaining python initializations.
1644 These must be done after GDB is at least mostly initialized.
1645 E.g., The "info pretty-printer" command needs the "info" prefix
1646 command installed. */
1649 finish_python_initialization (void)
1652 char *gdb_pythondir
;
1654 struct cleanup
*cleanup
;
1656 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1658 /* Add the initial data-directory to sys.path. */
1660 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1661 make_cleanup (xfree
, gdb_pythondir
);
1663 sys_path
= PySys_GetObject ("path");
1665 /* If sys.path is not defined yet, define it first. */
1666 if (!(sys_path
&& PyList_Check (sys_path
)))
1669 PySys_SetPath (L
"");
1673 sys_path
= PySys_GetObject ("path");
1675 if (sys_path
&& PyList_Check (sys_path
))
1677 PyObject
*pythondir
;
1680 pythondir
= PyString_FromString (gdb_pythondir
);
1681 if (pythondir
== NULL
)
1684 err
= PyList_Insert (sys_path
, 0, pythondir
);
1688 Py_DECREF (pythondir
);
1693 /* Import the gdb module to finish the initialization, and
1694 add it to __main__ for convenience. */
1695 m
= PyImport_AddModule ("__main__");
1699 gdb_python_module
= PyImport_ImportModule ("gdb");
1700 if (gdb_python_module
== NULL
)
1702 gdbpy_print_stack ();
1703 warning (_("Could not load the Python gdb module from `%s'."),
1705 warning (_("Limited Python support is available from the _gdb module."));
1706 do_cleanups (cleanup
);
1710 if (PyModule_AddObject (m
, "gdb", gdb_python_module
))
1713 /* Keep the reference to gdb_python_module since it is in a global
1716 do_cleanups (cleanup
);
1720 gdbpy_print_stack ();
1721 warning (_("internal error: Unhandled Python exception"));
1722 do_cleanups (cleanup
);
1725 #endif /* HAVE_PYTHON */
1731 static PyMethodDef GdbMethods
[] =
1733 { "history", gdbpy_history
, METH_VARARGS
,
1734 "Get a value from history" },
1735 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1736 "Execute a gdb command" },
1737 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1738 "Return a gdb parameter's value" },
1740 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1741 "Return a tuple of all breakpoint objects" },
1743 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1744 "Find the default visualizer for a Value." },
1746 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1747 "Return the current Progspace." },
1748 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1749 "Return a sequence of all progspaces." },
1751 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1752 "Return the current Objfile being loaded, or None." },
1753 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1754 "Return a sequence of all loaded objfiles." },
1756 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1757 "newest_frame () -> gdb.Frame.\n\
1758 Return the newest frame object." },
1759 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1760 "selected_frame () -> gdb.Frame.\n\
1761 Return the selected frame object." },
1762 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1763 "stop_reason_string (Integer) -> String.\n\
1764 Return a string explaining unwind stop reason." },
1766 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1767 METH_VARARGS
| METH_KEYWORDS
,
1768 "lookup_type (name [, block]) -> type\n\
1769 Return a Type corresponding to the given name." },
1770 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1771 METH_VARARGS
| METH_KEYWORDS
,
1772 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1773 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1774 a boolean indicating if name is a field of the current implied argument\n\
1775 `this' (when the current language is object-oriented)." },
1776 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1777 METH_VARARGS
| METH_KEYWORDS
,
1778 "lookup_global_symbol (name [, domain]) -> symbol\n\
1779 Return the symbol corresponding to the given name (or None)." },
1780 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1781 "Return the block containing the given pc value, or None." },
1782 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1783 "solib_name (Long) -> String.\n\
1784 Return the name of the shared library holding a given address, or None." },
1785 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1786 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1787 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1788 The first element contains any unparsed portion of the String parameter\n\
1789 (or None if the string was fully parsed). The second element contains\n\
1790 a tuple that contains all the locations that match, represented as\n\
1791 gdb.Symtab_and_line objects (or None)."},
1792 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1793 "parse_and_eval (String) -> Value.\n\
1794 Parse String as an expression, evaluate it, and return the result as a Value."
1796 { "find_pc_line", gdbpy_find_pc_line
, METH_VARARGS
,
1797 "find_pc_line (pc) -> Symtab_and_line.\n\
1798 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1800 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1801 "Post an event into gdb's event loop." },
1803 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1804 "target_charset () -> string.\n\
1805 Return the name of the current target charset." },
1806 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1807 "target_wide_charset () -> string.\n\
1808 Return the name of the current target wide charset." },
1810 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1811 "string_to_argv (String) -> Array.\n\
1812 Parse String and return an argv-like array.\n\
1813 Arguments are separate by spaces and may be quoted."
1815 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1816 "Write a string using gdb's filtered stream." },
1817 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1818 "Flush gdb's filtered stdout stream." },
1819 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1820 "selected_thread () -> gdb.InferiorThread.\n\
1821 Return the selected thread object." },
1822 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1823 "selected_inferior () -> gdb.Inferior.\n\
1824 Return the selected inferior object." },
1825 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1826 "inferiors () -> (gdb.Inferior, ...).\n\
1827 Return a tuple containing all inferiors." },
1828 {NULL
, NULL
, 0, NULL
}
1832 static struct PyModuleDef GdbModuleDef
=
1834 PyModuleDef_HEAD_INIT
,
1845 #endif /* HAVE_PYTHON */