1 /* General python/gdb code
3 Copyright (C) 2008-2012 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
26 #include "progspace.h"
30 #include "exceptions.h"
31 #include "event-loop.h"
33 #include "readline/tilde.h"
38 /* Declared constants and enum for python stack printing. */
39 static const char python_excp_none
[] = "none";
40 static const char python_excp_full
[] = "full";
41 static const char python_excp_message
[] = "message";
43 /* "set python print-stack" choices. */
44 static const char *const python_excp_enums
[] =
52 /* The exception printing variable. 'full' if we want to print the
53 error message and stack, 'none' if we want to print nothing, and
54 'message' if we only want to print the error message. 'message' is
56 static const char *gdbpy_should_print_stack
= python_excp_message
;
60 #include "libiberty.h"
61 #include "cli/cli-decode.h"
65 #include "python-internal.h"
70 #include "gdbthread.h"
74 static PyMethodDef GdbMethods
[];
78 /* Some string constants we may wish to use. */
79 PyObject
*gdbpy_to_string_cst
;
80 PyObject
*gdbpy_children_cst
;
81 PyObject
*gdbpy_display_hint_cst
;
82 PyObject
*gdbpy_doc_cst
;
83 PyObject
*gdbpy_enabled_cst
;
84 PyObject
*gdbpy_value_cst
;
86 /* The GdbError exception. */
87 PyObject
*gdbpy_gdberror_exc
;
89 /* The `gdb.error' base class. */
90 PyObject
*gdbpy_gdb_error
;
92 /* The `gdb.MemoryError' exception. */
93 PyObject
*gdbpy_gdb_memory_error
;
95 /* Architecture and language to be used in callbacks from
96 the Python interpreter. */
97 struct gdbarch
*python_gdbarch
;
98 const struct language_defn
*python_language
;
100 /* Restore global language and architecture and Python GIL state
101 when leaving the Python interpreter. */
105 PyGILState_STATE state
;
106 struct gdbarch
*gdbarch
;
107 const struct language_defn
*language
;
108 PyObject
*error_type
, *error_value
, *error_traceback
;
112 restore_python_env (void *p
)
114 struct python_env
*env
= (struct python_env
*)p
;
116 /* Leftover Python error is forbidden by Python Exception Handling. */
117 if (PyErr_Occurred ())
119 /* This order is similar to the one calling error afterwards. */
120 gdbpy_print_stack ();
121 warning (_("internal error: Unhandled Python exception"));
124 PyErr_Restore (env
->error_type
, env
->error_value
, env
->error_traceback
);
126 PyGILState_Release (env
->state
);
127 python_gdbarch
= env
->gdbarch
;
128 python_language
= env
->language
;
132 /* Called before entering the Python interpreter to install the
133 current language and architecture to be used for Python values. */
136 ensure_python_env (struct gdbarch
*gdbarch
,
137 const struct language_defn
*language
)
139 struct python_env
*env
= xmalloc (sizeof *env
);
141 env
->state
= PyGILState_Ensure ();
142 env
->gdbarch
= python_gdbarch
;
143 env
->language
= python_language
;
145 python_gdbarch
= gdbarch
;
146 python_language
= language
;
148 /* Save it and ensure ! PyErr_Occurred () afterwards. */
149 PyErr_Fetch (&env
->error_type
, &env
->error_value
, &env
->error_traceback
);
151 return make_cleanup (restore_python_env
, env
);
154 /* Clear the quit flag. */
157 clear_quit_flag (void)
159 /* This clears the flag as a side effect. */
160 PyOS_InterruptOccurred ();
163 /* Set the quit flag. */
168 PyErr_SetInterrupt ();
171 /* Return true if the quit flag has been set, false otherwise. */
174 check_quit_flag (void)
176 return PyOS_InterruptOccurred ();
179 /* Evaluate a Python command like PyRun_SimpleString, but uses
180 Py_single_input which prints the result of expressions, and does
181 not automatically print the stack on errors. */
184 eval_python_command (const char *command
)
188 m
= PyImport_AddModule ("__main__");
192 d
= PyModule_GetDict (m
);
195 v
= PyRun_StringFlags (command
, Py_single_input
, d
, d
, NULL
);
206 /* Implementation of the gdb "python-interactive" command. */
209 python_interactive_command (char *arg
, int from_tty
)
211 struct cleanup
*cleanup
;
214 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
215 interpreter_async
= 0;
217 while (arg
&& *arg
&& isspace (*arg
))
220 ensure_python_env (get_current_arch (), current_language
);
224 int len
= strlen (arg
);
225 char *script
= xmalloc (len
+ 2);
227 strcpy (script
, arg
);
229 script
[len
+ 1] = '\0';
230 err
= eval_python_command (script
);
235 err
= PyRun_InteractiveLoop (instream
, "<stdin>");
241 gdbpy_print_stack ();
242 error (_("Error while executing Python code."));
245 do_cleanups (cleanup
);
248 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
251 On Windows hosts few users would build Python themselves (this is no
252 trivial task on this platform), and thus use binaries built by
253 someone else instead. There may happen situation where the Python
254 library and GDB are using two different versions of the C runtime
255 library. Python, being built with VC, would use one version of the
256 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
257 A FILE * from one runtime does not necessarily operate correctly in
260 To work around this potential issue, we create on Windows hosts the
261 FILE object using Python routines, thus making sure that it is
262 compatible with the Python library. */
265 python_run_simple_file (FILE *file
, const char *filename
)
269 PyRun_SimpleFile (file
, filename
);
274 PyObject
*python_file
;
275 struct cleanup
*cleanup
;
277 /* Because we have a string for a filename, and are using Python to
278 open the file, we need to expand any tilde in the path first. */
279 full_path
= tilde_expand (filename
);
280 cleanup
= make_cleanup (xfree
, full_path
);
281 python_file
= PyFile_FromString (full_path
, "r");
284 do_cleanups (cleanup
);
285 gdbpy_print_stack ();
286 error (_("Error while opening file: %s"), full_path
);
289 make_cleanup_py_decref (python_file
);
290 PyRun_SimpleFile (PyFile_AsFile (python_file
), filename
);
291 do_cleanups (cleanup
);
296 /* Given a command_line, return a command string suitable for passing
297 to Python. Lines in the string are separated by newlines. The
298 return value is allocated using xmalloc and the caller is
299 responsible for freeing it. */
302 compute_python_string (struct command_line
*l
)
304 struct command_line
*iter
;
309 for (iter
= l
; iter
; iter
= iter
->next
)
310 size
+= strlen (iter
->line
) + 1;
312 script
= xmalloc (size
+ 1);
314 for (iter
= l
; iter
; iter
= iter
->next
)
316 int len
= strlen (iter
->line
);
318 strcpy (&script
[here
], iter
->line
);
320 script
[here
++] = '\n';
326 /* Take a command line structure representing a 'python' command, and
327 evaluate its body using the Python interpreter. */
330 eval_python_from_control_command (struct command_line
*cmd
)
334 struct cleanup
*cleanup
;
336 if (cmd
->body_count
!= 1)
337 error (_("Invalid \"python\" block structure."));
339 cleanup
= ensure_python_env (get_current_arch (), current_language
);
341 script
= compute_python_string (cmd
->body_list
[0]);
342 ret
= PyRun_SimpleString (script
);
345 error (_("Error while executing Python code."));
347 do_cleanups (cleanup
);
350 /* Implementation of the gdb "python" command. */
353 python_command (char *arg
, int from_tty
)
355 struct cleanup
*cleanup
;
357 cleanup
= ensure_python_env (get_current_arch (), current_language
);
359 make_cleanup_restore_integer (&interpreter_async
);
360 interpreter_async
= 0;
362 while (arg
&& *arg
&& isspace (*arg
))
366 if (PyRun_SimpleString (arg
))
367 error (_("Error while executing Python code."));
371 struct command_line
*l
= get_command_line (python_control
, "");
373 make_cleanup_free_command_lines (&l
);
374 execute_control_command_untraced (l
);
377 do_cleanups (cleanup
);
382 /* Transform a gdb parameters's value into a Python value. May return
383 NULL (and set a Python exception) on error. Helper function for
386 gdbpy_parameter_value (enum var_types type
, void *var
)
391 case var_string_noescape
:
392 case var_optional_filename
:
396 char *str
= * (char **) var
;
400 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
411 case var_auto_boolean
:
413 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
415 if (ab
== AUTO_BOOLEAN_TRUE
)
417 else if (ab
== AUTO_BOOLEAN_FALSE
)
424 if ((* (int *) var
) == INT_MAX
)
428 return PyLong_FromLong (* (int *) var
);
432 unsigned int val
= * (unsigned int *) var
;
436 return PyLong_FromUnsignedLong (val
);
440 return PyErr_Format (PyExc_RuntimeError
,
441 _("Programmer error: unhandled type."));
444 /* A Python function which returns a gdb parameter's value as a Python
448 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
450 struct cmd_list_element
*alias
, *prefix
, *cmd
;
454 volatile struct gdb_exception except
;
456 if (! PyArg_ParseTuple (args
, "s", &arg
))
459 newarg
= concat ("show ", arg
, (char *) NULL
);
461 TRY_CATCH (except
, RETURN_MASK_ALL
)
463 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
466 GDB_PY_HANDLE_EXCEPTION (except
);
468 return PyErr_Format (PyExc_RuntimeError
,
469 _("Could not find parameter `%s'."), arg
);
472 return PyErr_Format (PyExc_RuntimeError
,
473 _("`%s' is not a parameter."), arg
);
474 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
477 /* Wrapper for target_charset. */
480 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
482 const char *cset
= target_charset (python_gdbarch
);
484 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
487 /* Wrapper for target_wide_charset. */
490 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
492 const char *cset
= target_wide_charset (python_gdbarch
);
494 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
497 /* A Python function which evaluates a string using the gdb CLI. */
500 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
503 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
504 int from_tty
, to_string
;
505 volatile struct gdb_exception except
;
506 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
509 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
510 &PyBool_Type
, &from_tty_obj
,
511 &PyBool_Type
, &to_string_obj
))
517 int cmp
= PyObject_IsTrue (from_tty_obj
);
526 int cmp
= PyObject_IsTrue (to_string_obj
);
532 TRY_CATCH (except
, RETURN_MASK_ALL
)
534 /* Copy the argument text in case the command modifies it. */
535 char *copy
= xstrdup (arg
);
536 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
538 make_cleanup_restore_integer (&interpreter_async
);
539 interpreter_async
= 0;
541 prevent_dont_repeat ();
543 result
= execute_command_to_string (copy
, from_tty
);
547 execute_command (copy
, from_tty
);
550 do_cleanups (cleanup
);
552 GDB_PY_HANDLE_EXCEPTION (except
);
554 /* Do any commands attached to breakpoint we stopped at. */
555 bpstat_do_actions ();
559 PyObject
*r
= PyString_FromString (result
);
566 /* Implementation of gdb.solib_name (Long) -> String.
567 Returns the name of the shared library holding a given address, or None. */
570 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
576 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
579 soname
= solib_name_from_address (current_program_space
, pc
);
581 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
591 /* A Python function which is a wrapper for decode_line_1. */
594 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
596 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
598 struct symtab_and_line sal
;
599 const char *arg
= NULL
;
600 char *copy_to_free
= NULL
, *copy
= NULL
;
601 struct cleanup
*cleanups
;
602 PyObject
*result
= NULL
;
603 PyObject
*return_result
= NULL
;
604 PyObject
*unparsed
= NULL
;
605 volatile struct gdb_exception except
;
607 if (! PyArg_ParseTuple (args
, "|s", &arg
))
610 cleanups
= make_cleanup (null_cleanup
, NULL
);
613 TRY_CATCH (except
, RETURN_MASK_ALL
)
617 copy
= xstrdup (arg
);
619 sals
= decode_line_1 (©
, 0, 0, 0);
623 set_default_source_symtab_and_line ();
624 sal
= get_current_source_symtab_and_line ();
630 if (sals
.sals
!= NULL
&& sals
.sals
!= &sal
)
632 make_cleanup (xfree
, copy_to_free
);
633 make_cleanup (xfree
, sals
.sals
);
636 if (except
.reason
< 0)
638 do_cleanups (cleanups
);
639 /* We know this will always throw. */
640 GDB_PY_HANDLE_EXCEPTION (except
);
647 result
= PyTuple_New (sals
.nelts
);
650 for (i
= 0; i
< sals
.nelts
; ++i
)
654 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
661 PyTuple_SetItem (result
, i
, obj
);
670 return_result
= PyTuple_New (2);
677 if (copy
&& strlen (copy
) > 0)
679 unparsed
= PyString_FromString (copy
);
680 if (unparsed
== NULL
)
683 Py_DECREF (return_result
);
684 return_result
= NULL
;
694 PyTuple_SetItem (return_result
, 0, unparsed
);
695 PyTuple_SetItem (return_result
, 1, result
);
698 do_cleanups (cleanups
);
700 return return_result
;
703 /* Parse a string and evaluate it as an expression. */
705 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
707 const char *expr_str
;
708 struct value
*result
= NULL
;
709 volatile struct gdb_exception except
;
711 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
714 TRY_CATCH (except
, RETURN_MASK_ALL
)
716 char *copy
= xstrdup (expr_str
);
717 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
719 result
= parse_and_eval (copy
);
720 do_cleanups (cleanup
);
722 GDB_PY_HANDLE_EXCEPTION (except
);
724 return value_to_value_object (result
);
727 /* Implementation of gdb.find_pc_line function.
728 Returns the gdb.Symtab_and_line object corresponding to a PC value. */
731 gdbpy_find_pc_line (PyObject
*self
, PyObject
*args
)
733 struct symtab_and_line sal
;
735 gdb_py_ulongest pc_llu
;
737 if (!PyArg_ParseTuple (args
, GDB_PY_LLU_ARG
, &pc_llu
))
740 pc
= (CORE_ADDR
) pc_llu
;
741 sal
= find_pc_line (pc
, 0);
742 return symtab_and_line_to_sal_object (sal
);
745 /* Read a file as Python code.
746 FILE is the file to run. FILENAME is name of the file FILE.
747 This does not throw any errors. If an exception occurs python will print
748 the traceback and clear the error indicator. */
751 source_python_script (FILE *file
, const char *filename
)
753 struct cleanup
*cleanup
;
755 cleanup
= ensure_python_env (get_current_arch (), current_language
);
756 python_run_simple_file (file
, filename
);
757 do_cleanups (cleanup
);
762 /* Posting and handling events. */
764 /* A single event. */
767 /* The Python event. This is just a callable object. */
769 /* The next event. */
770 struct gdbpy_event
*next
;
773 /* All pending events. */
774 static struct gdbpy_event
*gdbpy_event_list
;
775 /* The final link of the event list. */
776 static struct gdbpy_event
**gdbpy_event_list_end
;
778 /* We use a file handler, and not an async handler, so that we can
779 wake up the main thread even when it is blocked in poll(). */
780 static struct serial
*gdbpy_event_fds
[2];
782 /* The file handler callback. This reads from the internal pipe, and
783 then processes the Python event queue. This will always be run in
784 the main gdb thread. */
787 gdbpy_run_events (struct serial
*scb
, void *context
)
789 struct cleanup
*cleanup
;
791 cleanup
= ensure_python_env (get_current_arch (), current_language
);
793 /* Flush the fd. Do this before flushing the events list, so that
794 any new event post afterwards is sure to re-awake the event
796 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
799 while (gdbpy_event_list
)
801 /* Dispatching the event might push a new element onto the event
802 loop, so we update here "atomically enough". */
803 struct gdbpy_event
*item
= gdbpy_event_list
;
804 gdbpy_event_list
= gdbpy_event_list
->next
;
805 if (gdbpy_event_list
== NULL
)
806 gdbpy_event_list_end
= &gdbpy_event_list
;
809 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
812 Py_DECREF (item
->event
);
816 do_cleanups (cleanup
);
819 /* Submit an event to the gdb thread. */
821 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
823 struct gdbpy_event
*event
;
827 if (!PyArg_ParseTuple (args
, "O", &func
))
830 if (!PyCallable_Check (func
))
832 PyErr_SetString (PyExc_RuntimeError
,
833 _("Posted event is not callable"));
839 /* From here until the end of the function, we have the GIL, so we
840 can operate on our global data structures without worrying. */
841 wakeup
= gdbpy_event_list
== NULL
;
843 event
= XNEW (struct gdbpy_event
);
846 *gdbpy_event_list_end
= event
;
847 gdbpy_event_list_end
= &event
->next
;
849 /* Wake up gdb when needed. */
852 char c
= 'q'; /* Anything. */
854 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
855 return PyErr_SetFromErrno (PyExc_IOError
);
861 /* Initialize the Python event handler. */
863 gdbpy_initialize_events (void)
865 if (serial_pipe (gdbpy_event_fds
) == 0)
867 gdbpy_event_list_end
= &gdbpy_event_list
;
868 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
875 before_prompt_hook (const char *current_gdb_prompt
)
877 struct cleanup
*cleanup
;
880 cleanup
= ensure_python_env (get_current_arch (), current_language
);
882 if (PyObject_HasAttrString (gdb_module
, "prompt_hook"))
886 hook
= PyObject_GetAttrString (gdb_module
, "prompt_hook");
890 if (PyCallable_Check (hook
))
893 PyObject
*current_prompt
;
895 current_prompt
= PyString_FromString (current_gdb_prompt
);
896 if (current_prompt
== NULL
)
899 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
901 Py_DECREF (current_prompt
);
906 make_cleanup_py_decref (result
);
908 /* Return type should be None, or a String. If it is None,
909 fall through, we will not set a prompt. If it is a
910 string, set PROMPT. Anything else, set an exception. */
911 if (result
!= Py_None
&& ! PyString_Check (result
))
913 PyErr_Format (PyExc_RuntimeError
,
914 _("Return from prompt_hook must " \
915 "be either a Python string, or None"));
919 if (result
!= Py_None
)
921 prompt
= python_string_to_host_string (result
);
926 make_cleanup (xfree
, prompt
);
931 /* If a prompt has been set, PROMPT will not be NULL. If it is
932 NULL, do not set the prompt. */
936 do_cleanups (cleanup
);
940 gdbpy_print_stack ();
941 do_cleanups (cleanup
);
949 /* A python function to write a single string using gdb's filtered
950 output stream . The optional keyword STREAM can be used to write
951 to a particular stream. The default stream is to gdb_stdout. */
954 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
957 static char *keywords
[] = {"text", "stream", NULL
};
959 volatile struct gdb_exception except
;
961 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
965 TRY_CATCH (except
, RETURN_MASK_ALL
)
971 fprintf_filtered (gdb_stderr
, "%s", arg
);
976 fprintf_filtered (gdb_stdlog
, "%s", arg
);
980 fprintf_filtered (gdb_stdout
, "%s", arg
);
983 GDB_PY_HANDLE_EXCEPTION (except
);
988 /* A python function to flush a gdb stream. The optional keyword
989 STREAM can be used to flush a particular stream. The default stream
993 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
995 static char *keywords
[] = {"stream", NULL
};
998 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
1002 switch (stream_type
)
1006 gdb_flush (gdb_stderr
);
1011 gdb_flush (gdb_stdlog
);
1015 gdb_flush (gdb_stdout
);
1021 /* Print a python exception trace, print just a message, or print
1022 nothing and clear the python exception, depending on
1023 gdbpy_should_print_stack. Only call this if a python exception is
1026 gdbpy_print_stack (void)
1028 /* Print "none", just clear exception. */
1029 if (gdbpy_should_print_stack
== python_excp_none
)
1033 /* Print "full" message and backtrace. */
1034 else if (gdbpy_should_print_stack
== python_excp_full
)
1037 /* PyErr_Print doesn't necessarily end output with a newline.
1038 This works because Python's stdout/stderr is fed through
1042 /* Print "message", just error print message. */
1045 PyObject
*ptype
, *pvalue
, *ptraceback
;
1046 char *msg
= NULL
, *type
= NULL
;
1048 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
1050 /* Fetch the error message contained within ptype, pvalue. */
1051 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
1052 type
= gdbpy_obj_to_string (ptype
);
1055 /* An error occurred computing the string representation of the
1057 fprintf_filtered (gdb_stderr
,
1058 _("Error occurred computing Python error" \
1062 fprintf_filtered (gdb_stderr
, "Python Exception %s %s: \n",
1066 Py_XDECREF (pvalue
);
1067 Py_XDECREF (ptraceback
);
1074 /* Return the current Progspace.
1075 There always is one. */
1078 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
1082 result
= pspace_to_pspace_object (current_program_space
);
1088 /* Return a sequence holding all the Progspaces. */
1091 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
1093 struct program_space
*ps
;
1096 list
= PyList_New (0);
1102 PyObject
*item
= pspace_to_pspace_object (ps
);
1104 if (!item
|| PyList_Append (list
, item
) == -1)
1116 /* The "current" objfile. This is set when gdb detects that a new
1117 objfile has been loaded. It is only set for the duration of a call to
1118 source_python_script_for_objfile; it is NULL at other times. */
1119 static struct objfile
*gdbpy_current_objfile
;
1121 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1122 as Python code. This does not throw any errors. If an exception
1123 occurs python will print the traceback and clear the error indicator. */
1126 source_python_script_for_objfile (struct objfile
*objfile
, FILE *file
,
1127 const char *filename
)
1129 struct cleanup
*cleanups
;
1131 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
1132 gdbpy_current_objfile
= objfile
;
1134 python_run_simple_file (file
, filename
);
1136 do_cleanups (cleanups
);
1137 gdbpy_current_objfile
= NULL
;
1140 /* Return the current Objfile, or None if there isn't one. */
1143 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
1147 if (! gdbpy_current_objfile
)
1150 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
1156 /* Return a sequence holding all the Objfiles. */
1159 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
1161 struct objfile
*objf
;
1164 list
= PyList_New (0);
1170 PyObject
*item
= objfile_to_objfile_object (objf
);
1172 if (!item
|| PyList_Append (list
, item
) == -1)
1182 #else /* HAVE_PYTHON */
1184 /* Dummy implementation of the gdb "python-interactive" and "python"
1188 python_interactive_command (char *arg
, int from_tty
)
1190 while (arg
&& *arg
&& isspace (*arg
))
1193 error (_("Python scripting is not supported in this copy of GDB."));
1196 struct command_line
*l
= get_command_line (python_control
, "");
1197 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1199 execute_control_command_untraced (l
);
1200 do_cleanups (cleanups
);
1205 python_command (char *arg
, int from_tty
)
1207 python_interactive_command (arg
, from_tty
);
1211 eval_python_from_control_command (struct command_line
*cmd
)
1213 error (_("Python scripting is not supported in this copy of GDB."));
1217 source_python_script (FILE *file
, const char *filename
)
1219 throw_error (UNSUPPORTED_ERROR
,
1220 _("Python scripting is not supported in this copy of GDB."));
1224 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1226 internal_error (__FILE__
, __LINE__
,
1227 _("gdbpy_should_stop called when Python scripting is " \
1232 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1234 internal_error (__FILE__
, __LINE__
,
1235 _("gdbpy_breakpoint_has_py_cond called when Python " \
1236 "scripting is not supported."));
1239 #endif /* HAVE_PYTHON */
1243 /* Lists for 'set python' commands. */
1245 static struct cmd_list_element
*user_set_python_list
;
1246 static struct cmd_list_element
*user_show_python_list
;
1248 /* Function for use by 'set python' prefix command. */
1251 user_set_python (char *args
, int from_tty
)
1253 help_list (user_set_python_list
, "set python ", all_commands
,
1257 /* Function for use by 'show python' prefix command. */
1260 user_show_python (char *args
, int from_tty
)
1262 cmd_show_list (user_show_python_list
, from_tty
, "");
1265 /* Initialize the Python code. */
1267 /* Provide a prototype to silence -Wmissing-prototypes. */
1268 extern initialize_file_ftype _initialize_python
;
1271 _initialize_python (void)
1274 struct cmd_list_element
*cmd
;
1276 add_com ("python-interactive", class_obscure
,
1277 python_interactive_command
,
1280 Start a Python interactive prompt.\n\
1282 Alternatively, a single-line Python command can be given as an\n\
1283 argument, and if the command is an expression, the result will be\n\
1284 printed. For example:\n\
1286 (gdb) python-interactive 2 + 3\n\
1289 #else /* HAVE_PYTHON */
1291 Start a Python interactive prompt.\n\
1293 Python scripting is not supported in this copy of GDB.\n\
1294 This command is only a placeholder.")
1295 #endif /* HAVE_PYTHON */
1297 add_com_alias ("pi", "python-interactive", class_obscure
, 1);
1299 add_com ("python", class_obscure
, python_command
,
1302 Evaluate a Python command.\n\
1304 The command can be given as an argument, for instance:\n\
1308 If no argument is given, the following lines are read and used\n\
1309 as the Python commands. Type a line containing \"end\" to indicate\n\
1310 the end of the command.")
1311 #else /* HAVE_PYTHON */
1313 Evaluate a Python command.\n\
1315 Python scripting is not supported in this copy of GDB.\n\
1316 This command is only a placeholder.")
1317 #endif /* HAVE_PYTHON */
1319 add_com_alias ("py", "python", class_obscure
, 1);
1321 /* Add set/show python print-stack. */
1322 add_prefix_cmd ("python", no_class
, user_show_python
,
1323 _("Prefix command for python preference settings."),
1324 &user_show_python_list
, "show python ", 0,
1327 add_prefix_cmd ("python", no_class
, user_set_python
,
1328 _("Prefix command for python preference settings."),
1329 &user_set_python_list
, "set python ", 0,
1332 add_setshow_enum_cmd ("print-stack", no_class
, python_excp_enums
,
1333 &gdbpy_should_print_stack
, _("\
1334 Set mode for Python stack dump on error."), _("\
1335 Show the mode of Python stack printing on error."), _("\
1336 none == no stack or message will be printed.\n\
1337 full == a message and a stack will be printed.\n\
1338 message == an error message without a stack will be printed."),
1340 &user_set_python_list
,
1341 &user_show_python_list
);
1344 #ifdef WITH_PYTHON_PATH
1345 /* Work around problem where python gets confused about where it is,
1346 and then can't find its libraries, etc.
1347 NOTE: Python assumes the following layout:
1349 /foo/lib/pythonX.Y/...
1350 This must be done before calling Py_Initialize. */
1351 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1352 SLASH_STRING
, "python", NULL
));
1356 PyEval_InitThreads ();
1358 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
1360 /* The casts to (char*) are for python 2.4. */
1361 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1362 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1363 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1364 (char*) target_name
);
1366 /* Add stream constants. */
1367 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1368 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1369 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1371 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1372 script below is run (depending on order of _initialize_* functions).
1373 Define the initial value of gdb.PYTHONDIR here. */
1375 char *gdb_pythondir
;
1377 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1378 PyModule_AddStringConstant (gdb_module
, "PYTHONDIR", gdb_pythondir
);
1379 xfree (gdb_pythondir
);
1382 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1383 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1385 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1386 gdbpy_gdb_error
, NULL
);
1387 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1389 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1390 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1392 gdbpy_initialize_auto_load ();
1393 gdbpy_initialize_values ();
1394 gdbpy_initialize_frames ();
1395 gdbpy_initialize_commands ();
1396 gdbpy_initialize_symbols ();
1397 gdbpy_initialize_symtabs ();
1398 gdbpy_initialize_blocks ();
1399 gdbpy_initialize_functions ();
1400 gdbpy_initialize_parameters ();
1401 gdbpy_initialize_types ();
1402 gdbpy_initialize_pspace ();
1403 gdbpy_initialize_objfile ();
1404 gdbpy_initialize_breakpoints ();
1405 gdbpy_initialize_finishbreakpoints ();
1406 gdbpy_initialize_lazy_string ();
1407 gdbpy_initialize_thread ();
1408 gdbpy_initialize_inferior ();
1409 gdbpy_initialize_events ();
1411 gdbpy_initialize_eventregistry ();
1412 gdbpy_initialize_py_events ();
1413 gdbpy_initialize_event ();
1414 gdbpy_initialize_stop_event ();
1415 gdbpy_initialize_signal_event ();
1416 gdbpy_initialize_breakpoint_event ();
1417 gdbpy_initialize_continue_event ();
1418 gdbpy_initialize_exited_event ();
1419 gdbpy_initialize_thread_event ();
1420 gdbpy_initialize_new_objfile_event () ;
1422 observer_attach_before_prompt (before_prompt_hook
);
1424 PyRun_SimpleString ("import gdb");
1425 PyRun_SimpleString ("gdb.pretty_printers = []");
1427 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1428 gdbpy_children_cst
= PyString_FromString ("children");
1429 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1430 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1431 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1432 gdbpy_value_cst
= PyString_FromString ("value");
1434 /* Release the GIL while gdb runs. */
1435 PyThreadState_Swap (NULL
);
1436 PyEval_ReleaseLock ();
1438 #endif /* HAVE_PYTHON */
1443 /* Perform the remaining python initializations.
1444 These must be done after GDB is at least mostly initialized.
1445 E.g., The "info pretty-printer" command needs the "info" prefix
1446 command installed. */
1449 finish_python_initialization (void)
1451 struct cleanup
*cleanup
;
1453 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1455 PyRun_SimpleString ("\
1459 class GdbOutputFile:\n\
1464 def isatty(self):\n\
1467 def write(self, s):\n\
1468 gdb.write(s, stream=gdb.STDOUT)\n \
1470 def writelines(self, iterable):\n\
1471 for line in iterable:\n\
1477 sys.stdout = GdbOutputFile()\n\
1479 class GdbOutputErrorFile:\n\
1484 def isatty(self):\n\
1487 def write(self, s):\n\
1488 gdb.write(s, stream=gdb.STDERR)\n \
1490 def writelines(self, iterable):\n\
1491 for line in iterable:\n\
1492 self.write(line)\n \
1497 sys.stderr = GdbOutputErrorFile()\n\
1499 # Ideally this would live in the gdb module, but it's intentionally written\n\
1500 # in python, and we need this to bootstrap the gdb module.\n\
1502 def GdbSetPythonDirectory (dir):\n\
1503 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1504 old_dir = gdb.PYTHONDIR\n\
1505 gdb.PYTHONDIR = dir\n\
1506 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1507 # that directory name at the start of sys.path to allow the Python\n\
1508 # interpreter to find them.\n\
1509 if old_dir in sys.path:\n\
1510 sys.path.remove (old_dir)\n\
1511 sys.path.insert (0, gdb.PYTHONDIR)\n\
1513 # Tell python where to find submodules of gdb.\n\
1514 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1516 # The gdb module is implemented in C rather than in Python. As a result,\n\
1517 # the associated __init.py__ script is not not executed by default when\n\
1518 # the gdb module gets imported. Execute that script manually if it\n\
1520 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1521 if os.path.exists (ipy):\n\
1524 # Install the default gdb.PYTHONDIR.\n\
1525 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1526 # Default prompt hook does nothing.\n\
1527 prompt_hook = None\n\
1528 # Ensure that sys.argv is set to something.\n\
1529 # We do not use PySys_SetArgvEx because it did not appear until 2.6.6.\n\
1533 do_cleanups (cleanup
);
1536 #endif /* HAVE_PYTHON */
1542 static PyMethodDef GdbMethods
[] =
1544 { "history", gdbpy_history
, METH_VARARGS
,
1545 "Get a value from history" },
1546 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1547 "Execute a gdb command" },
1548 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1549 "Return a gdb parameter's value" },
1551 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1552 "Return a tuple of all breakpoint objects" },
1554 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1555 "Find the default visualizer for a Value." },
1557 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1558 "Return the current Progspace." },
1559 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1560 "Return a sequence of all progspaces." },
1562 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1563 "Return the current Objfile being loaded, or None." },
1564 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1565 "Return a sequence of all loaded objfiles." },
1567 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1568 "newest_frame () -> gdb.Frame.\n\
1569 Return the newest frame object." },
1570 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1571 "selected_frame () -> gdb.Frame.\n\
1572 Return the selected frame object." },
1573 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1574 "stop_reason_string (Integer) -> String.\n\
1575 Return a string explaining unwind stop reason." },
1577 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1578 METH_VARARGS
| METH_KEYWORDS
,
1579 "lookup_type (name [, block]) -> type\n\
1580 Return a Type corresponding to the given name." },
1581 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1582 METH_VARARGS
| METH_KEYWORDS
,
1583 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1584 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1585 a boolean indicating if name is a field of the current implied argument\n\
1586 `this' (when the current language is object-oriented)." },
1587 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1588 METH_VARARGS
| METH_KEYWORDS
,
1589 "lookup_global_symbol (name [, domain]) -> symbol\n\
1590 Return the symbol corresponding to the given name (or None)." },
1591 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1592 "Return the block containing the given pc value, or None." },
1593 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1594 "solib_name (Long) -> String.\n\
1595 Return the name of the shared library holding a given address, or None." },
1596 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1597 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1598 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1599 The first element contains any unparsed portion of the String parameter\n\
1600 (or None if the string was fully parsed). The second element contains\n\
1601 a tuple that contains all the locations that match, represented as\n\
1602 gdb.Symtab_and_line objects (or None)."},
1603 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1604 "parse_and_eval (String) -> Value.\n\
1605 Parse String as an expression, evaluate it, and return the result as a Value."
1607 { "find_pc_line", gdbpy_find_pc_line
, METH_VARARGS
,
1608 "find_pc_line (pc) -> Symtab_and_line.\n\
1609 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1611 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1612 "Post an event into gdb's event loop." },
1614 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1615 "target_charset () -> string.\n\
1616 Return the name of the current target charset." },
1617 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1618 "target_wide_charset () -> string.\n\
1619 Return the name of the current target wide charset." },
1621 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1622 "string_to_argv (String) -> Array.\n\
1623 Parse String and return an argv-like array.\n\
1624 Arguments are separate by spaces and may be quoted."
1626 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1627 "Write a string using gdb's filtered stream." },
1628 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1629 "Flush gdb's filtered stdout stream." },
1630 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1631 "selected_thread () -> gdb.InferiorThread.\n\
1632 Return the selected thread object." },
1633 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1634 "selected_inferior () -> gdb.Inferior.\n\
1635 Return the selected inferior object." },
1636 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1637 "inferiors () -> (gdb.Inferior, ...).\n\
1638 Return a tuple containing all inferiors." },
1639 {NULL
, NULL
, 0, NULL
}
1642 #endif /* HAVE_PYTHON */