1 /* General python/gdb code
3 Copyright (C) 2008-2013 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"
35 #include "cli/cli-utils.h"
39 /* Declared constants and enum for python stack printing. */
40 static const char python_excp_none
[] = "none";
41 static const char python_excp_full
[] = "full";
42 static const char python_excp_message
[] = "message";
44 /* "set python print-stack" choices. */
45 static const char *const python_excp_enums
[] =
53 /* The exception printing variable. 'full' if we want to print the
54 error message and stack, 'none' if we want to print nothing, and
55 'message' if we only want to print the error message. 'message' is
57 static const char *gdbpy_should_print_stack
= python_excp_message
;
61 #include "libiberty.h"
62 #include "cli/cli-decode.h"
66 #include "python-internal.h"
71 #include "gdbthread.h"
74 #include "event-top.h"
76 static PyMethodDef GdbMethods
[];
79 static struct PyModuleDef GdbModuleDef
;
83 PyObject
*gdb_python_module
;
85 /* Some string constants we may wish to use. */
86 PyObject
*gdbpy_to_string_cst
;
87 PyObject
*gdbpy_children_cst
;
88 PyObject
*gdbpy_display_hint_cst
;
89 PyObject
*gdbpy_doc_cst
;
90 PyObject
*gdbpy_enabled_cst
;
91 PyObject
*gdbpy_value_cst
;
93 /* The GdbError exception. */
94 PyObject
*gdbpy_gdberror_exc
;
96 /* The `gdb.error' base class. */
97 PyObject
*gdbpy_gdb_error
;
99 /* The `gdb.MemoryError' exception. */
100 PyObject
*gdbpy_gdb_memory_error
;
102 /* Architecture and language to be used in callbacks from
103 the Python interpreter. */
104 struct gdbarch
*python_gdbarch
;
105 const struct language_defn
*python_language
;
107 /* Restore global language and architecture and Python GIL state
108 when leaving the Python interpreter. */
112 PyGILState_STATE state
;
113 struct gdbarch
*gdbarch
;
114 const struct language_defn
*language
;
115 PyObject
*error_type
, *error_value
, *error_traceback
;
119 restore_python_env (void *p
)
121 struct python_env
*env
= (struct python_env
*)p
;
123 /* Leftover Python error is forbidden by Python Exception Handling. */
124 if (PyErr_Occurred ())
126 /* This order is similar to the one calling error afterwards. */
127 gdbpy_print_stack ();
128 warning (_("internal error: Unhandled Python exception"));
131 PyErr_Restore (env
->error_type
, env
->error_value
, env
->error_traceback
);
133 PyGILState_Release (env
->state
);
134 python_gdbarch
= env
->gdbarch
;
135 python_language
= env
->language
;
139 /* Called before entering the Python interpreter to install the
140 current language and architecture to be used for Python values. */
143 ensure_python_env (struct gdbarch
*gdbarch
,
144 const struct language_defn
*language
)
146 struct python_env
*env
= xmalloc (sizeof *env
);
148 env
->state
= PyGILState_Ensure ();
149 env
->gdbarch
= python_gdbarch
;
150 env
->language
= python_language
;
152 python_gdbarch
= gdbarch
;
153 python_language
= language
;
155 /* Save it and ensure ! PyErr_Occurred () afterwards. */
156 PyErr_Fetch (&env
->error_type
, &env
->error_value
, &env
->error_traceback
);
158 return make_cleanup (restore_python_env
, env
);
161 /* Clear the quit flag. */
164 clear_quit_flag (void)
166 /* This clears the flag as a side effect. */
167 PyOS_InterruptOccurred ();
170 /* Set the quit flag. */
175 PyErr_SetInterrupt ();
178 /* Return true if the quit flag has been set, false otherwise. */
181 check_quit_flag (void)
183 return PyOS_InterruptOccurred ();
186 /* Evaluate a Python command like PyRun_SimpleString, but uses
187 Py_single_input which prints the result of expressions, and does
188 not automatically print the stack on errors. */
191 eval_python_command (const char *command
)
195 m
= PyImport_AddModule ("__main__");
199 d
= PyModule_GetDict (m
);
202 v
= PyRun_StringFlags (command
, Py_single_input
, d
, d
, NULL
);
215 /* Implementation of the gdb "python-interactive" command. */
218 python_interactive_command (char *arg
, int from_tty
)
220 struct cleanup
*cleanup
;
223 cleanup
= make_cleanup_restore_integer (&interpreter_async
);
224 interpreter_async
= 0;
226 arg
= skip_spaces (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 arg
= skip_spaces (arg
);
373 if (PyRun_SimpleString (arg
))
374 error (_("Error while executing Python code."));
378 struct command_line
*l
= get_command_line (python_control
, "");
380 make_cleanup_free_command_lines (&l
);
381 execute_control_command_untraced (l
);
384 do_cleanups (cleanup
);
389 /* Transform a gdb parameters's value into a Python value. May return
390 NULL (and set a Python exception) on error. Helper function for
393 gdbpy_parameter_value (enum var_types type
, void *var
)
398 case var_string_noescape
:
399 case var_optional_filename
:
403 char *str
= * (char **) var
;
407 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
418 case var_auto_boolean
:
420 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
422 if (ab
== AUTO_BOOLEAN_TRUE
)
424 else if (ab
== AUTO_BOOLEAN_FALSE
)
431 if ((* (int *) var
) == INT_MAX
)
435 return PyLong_FromLong (* (int *) var
);
439 unsigned int val
= * (unsigned int *) var
;
443 return PyLong_FromUnsignedLong (val
);
447 return PyErr_Format (PyExc_RuntimeError
,
448 _("Programmer error: unhandled type."));
451 /* A Python function which returns a gdb parameter's value as a Python
455 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
457 struct cmd_list_element
*alias
, *prefix
, *cmd
;
461 volatile struct gdb_exception except
;
463 if (! PyArg_ParseTuple (args
, "s", &arg
))
466 newarg
= concat ("show ", arg
, (char *) NULL
);
468 TRY_CATCH (except
, RETURN_MASK_ALL
)
470 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
473 GDB_PY_HANDLE_EXCEPTION (except
);
475 return PyErr_Format (PyExc_RuntimeError
,
476 _("Could not find parameter `%s'."), arg
);
479 return PyErr_Format (PyExc_RuntimeError
,
480 _("`%s' is not a parameter."), arg
);
481 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
484 /* Wrapper for target_charset. */
487 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
489 const char *cset
= target_charset (python_gdbarch
);
491 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
494 /* Wrapper for target_wide_charset. */
497 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
499 const char *cset
= target_wide_charset (python_gdbarch
);
501 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
504 /* A Python function which evaluates a string using the gdb CLI. */
507 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
510 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
511 int from_tty
, to_string
;
512 volatile struct gdb_exception except
;
513 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
516 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
517 &PyBool_Type
, &from_tty_obj
,
518 &PyBool_Type
, &to_string_obj
))
524 int cmp
= PyObject_IsTrue (from_tty_obj
);
533 int cmp
= PyObject_IsTrue (to_string_obj
);
539 TRY_CATCH (except
, RETURN_MASK_ALL
)
541 /* Copy the argument text in case the command modifies it. */
542 char *copy
= xstrdup (arg
);
543 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
545 make_cleanup_restore_integer (&interpreter_async
);
546 interpreter_async
= 0;
548 prevent_dont_repeat ();
550 result
= execute_command_to_string (copy
, from_tty
);
554 execute_command (copy
, from_tty
);
557 do_cleanups (cleanup
);
559 GDB_PY_HANDLE_EXCEPTION (except
);
561 /* Do any commands attached to breakpoint we stopped at. */
562 bpstat_do_actions ();
566 PyObject
*r
= PyString_FromString (result
);
573 /* Implementation of gdb.solib_name (Long) -> String.
574 Returns the name of the shared library holding a given address, or None. */
577 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
583 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
586 soname
= solib_name_from_address (current_program_space
, pc
);
588 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
598 /* A Python function which is a wrapper for decode_line_1. */
601 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
603 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
605 struct symtab_and_line sal
;
606 const char *arg
= NULL
;
607 char *copy_to_free
= NULL
, *copy
= NULL
;
608 struct cleanup
*cleanups
;
609 PyObject
*result
= NULL
;
610 PyObject
*return_result
= NULL
;
611 PyObject
*unparsed
= NULL
;
612 volatile struct gdb_exception except
;
614 if (! PyArg_ParseTuple (args
, "|s", &arg
))
617 cleanups
= make_cleanup (null_cleanup
, NULL
);
620 TRY_CATCH (except
, RETURN_MASK_ALL
)
624 copy
= xstrdup (arg
);
626 sals
= decode_line_1 (©
, 0, 0, 0);
630 set_default_source_symtab_and_line ();
631 sal
= get_current_source_symtab_and_line ();
637 if (sals
.sals
!= NULL
&& sals
.sals
!= &sal
)
639 make_cleanup (xfree
, copy_to_free
);
640 make_cleanup (xfree
, sals
.sals
);
643 if (except
.reason
< 0)
645 do_cleanups (cleanups
);
646 /* We know this will always throw. */
647 GDB_PY_HANDLE_EXCEPTION (except
);
654 result
= PyTuple_New (sals
.nelts
);
657 for (i
= 0; i
< sals
.nelts
; ++i
)
661 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
668 PyTuple_SetItem (result
, i
, obj
);
677 return_result
= PyTuple_New (2);
684 if (copy
&& strlen (copy
) > 0)
686 unparsed
= PyString_FromString (copy
);
687 if (unparsed
== NULL
)
690 Py_DECREF (return_result
);
691 return_result
= NULL
;
701 PyTuple_SetItem (return_result
, 0, unparsed
);
702 PyTuple_SetItem (return_result
, 1, result
);
705 do_cleanups (cleanups
);
707 return return_result
;
710 /* Parse a string and evaluate it as an expression. */
712 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
714 const char *expr_str
;
715 struct value
*result
= NULL
;
716 volatile struct gdb_exception except
;
718 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
721 TRY_CATCH (except
, RETURN_MASK_ALL
)
723 result
= parse_and_eval (expr_str
);
725 GDB_PY_HANDLE_EXCEPTION (except
);
727 return value_to_value_object (result
);
730 /* Implementation of gdb.find_pc_line function.
731 Returns the gdb.Symtab_and_line object corresponding to a PC value. */
734 gdbpy_find_pc_line (PyObject
*self
, PyObject
*args
)
736 gdb_py_ulongest pc_llu
;
737 volatile struct gdb_exception except
;
738 PyObject
*result
= NULL
; /* init for gcc -Wall */
740 if (!PyArg_ParseTuple (args
, GDB_PY_LLU_ARG
, &pc_llu
))
743 TRY_CATCH (except
, RETURN_MASK_ALL
)
745 struct symtab_and_line sal
;
748 pc
= (CORE_ADDR
) pc_llu
;
749 sal
= find_pc_line (pc
, 0);
750 result
= symtab_and_line_to_sal_object (sal
);
752 GDB_PY_HANDLE_EXCEPTION (except
);
757 /* Read a file as Python code.
758 FILE is the file to run. FILENAME is name of the file FILE.
759 This does not throw any errors. If an exception occurs python will print
760 the traceback and clear the error indicator. */
763 source_python_script (FILE *file
, const char *filename
)
765 struct cleanup
*cleanup
;
767 cleanup
= ensure_python_env (get_current_arch (), current_language
);
768 python_run_simple_file (file
, filename
);
769 do_cleanups (cleanup
);
774 /* Posting and handling events. */
776 /* A single event. */
779 /* The Python event. This is just a callable object. */
781 /* The next event. */
782 struct gdbpy_event
*next
;
785 /* All pending events. */
786 static struct gdbpy_event
*gdbpy_event_list
;
787 /* The final link of the event list. */
788 static struct gdbpy_event
**gdbpy_event_list_end
;
790 /* We use a file handler, and not an async handler, so that we can
791 wake up the main thread even when it is blocked in poll(). */
792 static struct serial
*gdbpy_event_fds
[2];
794 /* The file handler callback. This reads from the internal pipe, and
795 then processes the Python event queue. This will always be run in
796 the main gdb thread. */
799 gdbpy_run_events (struct serial
*scb
, void *context
)
801 struct cleanup
*cleanup
;
803 cleanup
= ensure_python_env (get_current_arch (), current_language
);
805 /* Flush the fd. Do this before flushing the events list, so that
806 any new event post afterwards is sure to re-awake the event
808 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
811 while (gdbpy_event_list
)
813 /* Dispatching the event might push a new element onto the event
814 loop, so we update here "atomically enough". */
815 struct gdbpy_event
*item
= gdbpy_event_list
;
816 gdbpy_event_list
= gdbpy_event_list
->next
;
817 if (gdbpy_event_list
== NULL
)
818 gdbpy_event_list_end
= &gdbpy_event_list
;
821 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
824 Py_DECREF (item
->event
);
828 do_cleanups (cleanup
);
831 /* Submit an event to the gdb thread. */
833 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
835 struct gdbpy_event
*event
;
839 if (!PyArg_ParseTuple (args
, "O", &func
))
842 if (!PyCallable_Check (func
))
844 PyErr_SetString (PyExc_RuntimeError
,
845 _("Posted event is not callable"));
851 /* From here until the end of the function, we have the GIL, so we
852 can operate on our global data structures without worrying. */
853 wakeup
= gdbpy_event_list
== NULL
;
855 event
= XNEW (struct gdbpy_event
);
858 *gdbpy_event_list_end
= event
;
859 gdbpy_event_list_end
= &event
->next
;
861 /* Wake up gdb when needed. */
864 char c
= 'q'; /* Anything. */
866 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
867 return PyErr_SetFromErrno (PyExc_IOError
);
873 /* Initialize the Python event handler. */
875 gdbpy_initialize_events (void)
877 if (serial_pipe (gdbpy_event_fds
) == 0)
879 gdbpy_event_list_end
= &gdbpy_event_list
;
880 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
887 before_prompt_hook (const char *current_gdb_prompt
)
889 struct cleanup
*cleanup
;
892 cleanup
= ensure_python_env (get_current_arch (), current_language
);
894 if (gdb_python_module
895 && PyObject_HasAttrString (gdb_python_module
, "prompt_hook"))
899 hook
= PyObject_GetAttrString (gdb_python_module
, "prompt_hook");
903 if (PyCallable_Check (hook
))
906 PyObject
*current_prompt
;
908 current_prompt
= PyString_FromString (current_gdb_prompt
);
909 if (current_prompt
== NULL
)
912 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
914 Py_DECREF (current_prompt
);
919 make_cleanup_py_decref (result
);
921 /* Return type should be None, or a String. If it is None,
922 fall through, we will not set a prompt. If it is a
923 string, set PROMPT. Anything else, set an exception. */
924 if (result
!= Py_None
&& ! PyString_Check (result
))
926 PyErr_Format (PyExc_RuntimeError
,
927 _("Return from prompt_hook must " \
928 "be either a Python string, or None"));
932 if (result
!= Py_None
)
934 prompt
= python_string_to_host_string (result
);
939 make_cleanup (xfree
, prompt
);
944 /* If a prompt has been set, PROMPT will not be NULL. If it is
945 NULL, do not set the prompt. */
949 do_cleanups (cleanup
);
953 gdbpy_print_stack ();
954 do_cleanups (cleanup
);
962 /* A python function to write a single string using gdb's filtered
963 output stream . The optional keyword STREAM can be used to write
964 to a particular stream. The default stream is to gdb_stdout. */
967 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
970 static char *keywords
[] = {"text", "stream", NULL
};
972 volatile struct gdb_exception except
;
974 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
978 TRY_CATCH (except
, RETURN_MASK_ALL
)
984 fprintf_filtered (gdb_stderr
, "%s", arg
);
989 fprintf_filtered (gdb_stdlog
, "%s", arg
);
993 fprintf_filtered (gdb_stdout
, "%s", arg
);
996 GDB_PY_HANDLE_EXCEPTION (except
);
1001 /* A python function to flush a gdb stream. The optional keyword
1002 STREAM can be used to flush a particular stream. The default stream
1006 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1008 static char *keywords
[] = {"stream", NULL
};
1009 int stream_type
= 0;
1011 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
1015 switch (stream_type
)
1019 gdb_flush (gdb_stderr
);
1024 gdb_flush (gdb_stdlog
);
1028 gdb_flush (gdb_stdout
);
1034 /* Print a python exception trace, print just a message, or print
1035 nothing and clear the python exception, depending on
1036 gdbpy_should_print_stack. Only call this if a python exception is
1039 gdbpy_print_stack (void)
1041 volatile struct gdb_exception except
;
1043 /* Print "none", just clear exception. */
1044 if (gdbpy_should_print_stack
== python_excp_none
)
1048 /* Print "full" message and backtrace. */
1049 else if (gdbpy_should_print_stack
== python_excp_full
)
1052 /* PyErr_Print doesn't necessarily end output with a newline.
1053 This works because Python's stdout/stderr is fed through
1055 TRY_CATCH (except
, RETURN_MASK_ALL
)
1060 /* Print "message", just error print message. */
1063 PyObject
*ptype
, *pvalue
, *ptraceback
;
1064 char *msg
= NULL
, *type
= NULL
;
1066 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
1068 /* Fetch the error message contained within ptype, pvalue. */
1069 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
1070 type
= gdbpy_obj_to_string (ptype
);
1072 TRY_CATCH (except
, RETURN_MASK_ALL
)
1076 /* An error occurred computing the string representation of the
1078 fprintf_filtered (gdb_stderr
,
1079 _("Error occurred computing Python error" \
1083 fprintf_filtered (gdb_stderr
, "Python Exception %s %s: \n",
1088 Py_XDECREF (pvalue
);
1089 Py_XDECREF (ptraceback
);
1096 /* Return the current Progspace.
1097 There always is one. */
1100 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
1104 result
= pspace_to_pspace_object (current_program_space
);
1110 /* Return a sequence holding all the Progspaces. */
1113 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
1115 struct program_space
*ps
;
1118 list
= PyList_New (0);
1124 PyObject
*item
= pspace_to_pspace_object (ps
);
1126 if (!item
|| PyList_Append (list
, item
) == -1)
1138 /* The "current" objfile. This is set when gdb detects that a new
1139 objfile has been loaded. It is only set for the duration of a call to
1140 source_python_script_for_objfile; it is NULL at other times. */
1141 static struct objfile
*gdbpy_current_objfile
;
1143 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1144 as Python code. This does not throw any errors. If an exception
1145 occurs python will print the traceback and clear the error indicator. */
1148 source_python_script_for_objfile (struct objfile
*objfile
, FILE *file
,
1149 const char *filename
)
1151 struct cleanup
*cleanups
;
1153 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
1154 gdbpy_current_objfile
= objfile
;
1156 python_run_simple_file (file
, filename
);
1158 do_cleanups (cleanups
);
1159 gdbpy_current_objfile
= NULL
;
1162 /* Return the current Objfile, or None if there isn't one. */
1165 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
1169 if (! gdbpy_current_objfile
)
1172 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
1178 /* Return a sequence holding all the Objfiles. */
1181 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
1183 struct objfile
*objf
;
1186 list
= PyList_New (0);
1192 PyObject
*item
= objfile_to_objfile_object (objf
);
1194 if (!item
|| PyList_Append (list
, item
) == -1)
1204 /* Compute the list of active type printers and return it. The result
1205 of this function can be passed to apply_type_printers, and should
1206 be freed by free_type_printers. */
1209 start_type_printers (void)
1211 struct cleanup
*cleanups
;
1212 PyObject
*type_module
, *func
, *result_obj
= NULL
;
1214 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1216 type_module
= PyImport_ImportModule ("gdb.types");
1217 if (type_module
== NULL
)
1219 gdbpy_print_stack ();
1222 make_cleanup_py_decref (type_module
);
1224 func
= PyObject_GetAttrString (type_module
, "get_type_recognizers");
1227 gdbpy_print_stack ();
1230 make_cleanup_py_decref (func
);
1232 result_obj
= PyObject_CallFunctionObjArgs (func
, (char *) NULL
);
1233 if (result_obj
== NULL
)
1234 gdbpy_print_stack ();
1237 do_cleanups (cleanups
);
1241 /* If TYPE is recognized by some type printer, return a newly
1242 allocated string holding the type's replacement name. The caller
1243 is responsible for freeing the string. Otherwise, return NULL.
1245 This function has a bit of a funny name, since it actually applies
1246 recognizers, but this seemed clearer given the start_type_printers
1247 and free_type_printers functions. */
1250 apply_type_printers (void *printers
, struct type
*type
)
1252 struct cleanup
*cleanups
;
1253 PyObject
*type_obj
, *type_module
, *func
, *result_obj
;
1254 PyObject
*printers_obj
= printers
;
1255 char *result
= NULL
;
1257 if (printers_obj
== NULL
)
1260 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1262 type_obj
= type_to_type_object (type
);
1263 if (type_obj
== NULL
)
1265 gdbpy_print_stack ();
1268 make_cleanup_py_decref (type_obj
);
1270 type_module
= PyImport_ImportModule ("gdb.types");
1271 if (type_module
== NULL
)
1273 gdbpy_print_stack ();
1276 make_cleanup_py_decref (type_module
);
1278 func
= PyObject_GetAttrString (type_module
, "apply_type_recognizers");
1281 gdbpy_print_stack ();
1284 make_cleanup_py_decref (func
);
1286 result_obj
= PyObject_CallFunctionObjArgs (func
, printers_obj
,
1287 type_obj
, (char *) NULL
);
1288 if (result_obj
== NULL
)
1290 gdbpy_print_stack ();
1293 make_cleanup_py_decref (result_obj
);
1295 if (result_obj
!= Py_None
)
1297 result
= python_string_to_host_string (result_obj
);
1299 gdbpy_print_stack ();
1303 do_cleanups (cleanups
);
1307 /* Free the result of start_type_printers. */
1310 free_type_printers (void *arg
)
1312 struct cleanup
*cleanups
;
1313 PyObject
*printers
= arg
;
1315 if (printers
== NULL
)
1318 cleanups
= ensure_python_env (get_current_arch (), current_language
);
1319 Py_DECREF (printers
);
1320 do_cleanups (cleanups
);
1323 #else /* HAVE_PYTHON */
1325 /* Dummy implementation of the gdb "python-interactive" and "python"
1329 python_interactive_command (char *arg
, int from_tty
)
1331 arg
= skip_spaces (arg
);
1333 error (_("Python scripting is not supported in this copy of GDB."));
1336 struct command_line
*l
= get_command_line (python_control
, "");
1337 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1339 execute_control_command_untraced (l
);
1340 do_cleanups (cleanups
);
1345 python_command (char *arg
, int from_tty
)
1347 python_interactive_command (arg
, from_tty
);
1351 eval_python_from_control_command (struct command_line
*cmd
)
1353 error (_("Python scripting is not supported in this copy of GDB."));
1357 source_python_script (FILE *file
, const char *filename
)
1359 throw_error (UNSUPPORTED_ERROR
,
1360 _("Python scripting is not supported in this copy of GDB."));
1364 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1366 internal_error (__FILE__
, __LINE__
,
1367 _("gdbpy_should_stop called when Python scripting is " \
1372 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1374 internal_error (__FILE__
, __LINE__
,
1375 _("gdbpy_breakpoint_has_py_cond called when Python " \
1376 "scripting is not supported."));
1380 start_type_printers (void)
1386 apply_type_printers (void *ignore
, struct type
*type
)
1392 free_type_printers (void *arg
)
1396 #endif /* HAVE_PYTHON */
1400 /* Lists for 'set python' commands. */
1402 static struct cmd_list_element
*user_set_python_list
;
1403 static struct cmd_list_element
*user_show_python_list
;
1405 /* Function for use by 'set python' prefix command. */
1408 user_set_python (char *args
, int from_tty
)
1410 help_list (user_set_python_list
, "set python ", all_commands
,
1414 /* Function for use by 'show python' prefix command. */
1417 user_show_python (char *args
, int from_tty
)
1419 cmd_show_list (user_show_python_list
, from_tty
, "");
1422 /* Initialize the Python code. */
1426 /* This is installed as a final cleanup and cleans up the
1427 interpreter. This lets Python's 'atexit' work. */
1430 finalize_python (void *ignore
)
1432 /* We don't use ensure_python_env here because if we ever ran the
1433 cleanup, gdb would crash -- because the cleanup calls into the
1434 Python interpreter, which we are about to destroy. It seems
1435 clearer to make the needed calls explicitly here than to create a
1436 cleanup and then mysteriously discard it. */
1437 (void) PyGILState_Ensure ();
1438 python_gdbarch
= target_gdbarch ();
1439 python_language
= current_language
;
1445 /* Provide a prototype to silence -Wmissing-prototypes. */
1446 extern initialize_file_ftype _initialize_python
;
1449 _initialize_python (void)
1454 size_t progsize
, count
;
1456 wchar_t *progname_copy
;
1459 add_com ("python-interactive", class_obscure
,
1460 python_interactive_command
,
1463 Start an interactive Python prompt.\n\
1465 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1468 Alternatively, a single-line Python command can be given as an\n\
1469 argument, and if the command is an expression, the result will be\n\
1470 printed. For example:\n\
1472 (gdb) python-interactive 2 + 3\n\
1475 #else /* HAVE_PYTHON */
1477 Start a Python interactive prompt.\n\
1479 Python scripting is not supported in this copy of GDB.\n\
1480 This command is only a placeholder.")
1481 #endif /* HAVE_PYTHON */
1483 add_com_alias ("pi", "python-interactive", class_obscure
, 1);
1485 add_com ("python", class_obscure
, python_command
,
1488 Evaluate a Python command.\n\
1490 The command can be given as an argument, for instance:\n\
1494 If no argument is given, the following lines are read and used\n\
1495 as the Python commands. Type a line containing \"end\" to indicate\n\
1496 the end of the command.")
1497 #else /* HAVE_PYTHON */
1499 Evaluate a Python command.\n\
1501 Python scripting is not supported in this copy of GDB.\n\
1502 This command is only a placeholder.")
1503 #endif /* HAVE_PYTHON */
1505 add_com_alias ("py", "python", class_obscure
, 1);
1507 /* Add set/show python print-stack. */
1508 add_prefix_cmd ("python", no_class
, user_show_python
,
1509 _("Prefix command for python preference settings."),
1510 &user_show_python_list
, "show python ", 0,
1513 add_prefix_cmd ("python", no_class
, user_set_python
,
1514 _("Prefix command for python preference settings."),
1515 &user_set_python_list
, "set python ", 0,
1518 add_setshow_enum_cmd ("print-stack", no_class
, python_excp_enums
,
1519 &gdbpy_should_print_stack
, _("\
1520 Set mode for Python stack dump on error."), _("\
1521 Show the mode of Python stack printing on error."), _("\
1522 none == no stack or message will be printed.\n\
1523 full == a message and a stack will be printed.\n\
1524 message == an error message without a stack will be printed."),
1526 &user_set_python_list
,
1527 &user_show_python_list
);
1530 #ifdef WITH_PYTHON_PATH
1531 /* Work around problem where python gets confused about where it is,
1532 and then can't find its libraries, etc.
1533 NOTE: Python assumes the following layout:
1535 /foo/lib/pythonX.Y/...
1536 This must be done before calling Py_Initialize. */
1537 progname
= concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1538 SLASH_STRING
, "python", NULL
);
1540 oldloc
= setlocale (LC_ALL
, NULL
);
1541 setlocale (LC_ALL
, "");
1542 progsize
= strlen (progname
);
1543 if (progsize
== (size_t) -1)
1545 fprintf (stderr
, "Could not convert python path to string\n");
1548 progname_copy
= PyMem_Malloc ((progsize
+ 1) * sizeof (wchar_t));
1551 fprintf (stderr
, "out of memory\n");
1554 count
= mbstowcs (progname_copy
, progname
, progsize
+ 1);
1555 if (count
== (size_t) -1)
1557 fprintf (stderr
, "Could not convert python path to string\n");
1560 setlocale (LC_ALL
, oldloc
);
1562 /* Note that Py_SetProgramName expects the string it is passed to
1563 remain alive for the duration of the program's execution, so
1564 it is not freed after this call. */
1565 Py_SetProgramName (progname_copy
);
1567 Py_SetProgramName (progname
);
1572 PyEval_InitThreads ();
1575 gdb_module
= PyModule_Create (&GdbModuleDef
);
1576 /* Add _gdb module to the list of known built-in modules. */
1577 _PyImport_FixupBuiltin (gdb_module
, "_gdb");
1579 gdb_module
= Py_InitModule ("_gdb", GdbMethods
);
1582 /* The casts to (char*) are for python 2.4. */
1583 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1584 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1585 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1586 (char*) target_name
);
1588 /* Add stream constants. */
1589 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1590 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1591 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1593 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1594 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1596 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1597 gdbpy_gdb_error
, NULL
);
1598 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1600 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1601 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1603 gdbpy_initialize_gdb_readline ();
1604 gdbpy_initialize_auto_load ();
1605 gdbpy_initialize_values ();
1606 gdbpy_initialize_frames ();
1607 gdbpy_initialize_commands ();
1608 gdbpy_initialize_symbols ();
1609 gdbpy_initialize_symtabs ();
1610 gdbpy_initialize_blocks ();
1611 gdbpy_initialize_functions ();
1612 gdbpy_initialize_parameters ();
1613 gdbpy_initialize_types ();
1614 gdbpy_initialize_pspace ();
1615 gdbpy_initialize_objfile ();
1616 gdbpy_initialize_breakpoints ();
1617 gdbpy_initialize_finishbreakpoints ();
1618 gdbpy_initialize_lazy_string ();
1619 gdbpy_initialize_thread ();
1620 gdbpy_initialize_inferior ();
1621 gdbpy_initialize_events ();
1623 gdbpy_initialize_eventregistry ();
1624 gdbpy_initialize_py_events ();
1625 gdbpy_initialize_event ();
1626 gdbpy_initialize_stop_event ();
1627 gdbpy_initialize_signal_event ();
1628 gdbpy_initialize_breakpoint_event ();
1629 gdbpy_initialize_continue_event ();
1630 gdbpy_initialize_exited_event ();
1631 gdbpy_initialize_thread_event ();
1632 gdbpy_initialize_new_objfile_event () ;
1633 gdbpy_initialize_arch ();
1635 observer_attach_before_prompt (before_prompt_hook
);
1637 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1638 gdbpy_children_cst
= PyString_FromString ("children");
1639 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1640 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1641 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1642 gdbpy_value_cst
= PyString_FromString ("value");
1644 /* Release the GIL while gdb runs. */
1645 PyThreadState_Swap (NULL
);
1646 PyEval_ReleaseLock ();
1648 make_final_cleanup (finalize_python
, NULL
);
1649 #endif /* HAVE_PYTHON */
1654 /* Perform the remaining python initializations.
1655 These must be done after GDB is at least mostly initialized.
1656 E.g., The "info pretty-printer" command needs the "info" prefix
1657 command installed. */
1660 finish_python_initialization (void)
1663 char *gdb_pythondir
;
1665 struct cleanup
*cleanup
;
1667 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1669 /* Add the initial data-directory to sys.path. */
1671 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1672 make_cleanup (xfree
, gdb_pythondir
);
1674 sys_path
= PySys_GetObject ("path");
1676 /* If sys.path is not defined yet, define it first. */
1677 if (!(sys_path
&& PyList_Check (sys_path
)))
1680 PySys_SetPath (L
"");
1684 sys_path
= PySys_GetObject ("path");
1686 if (sys_path
&& PyList_Check (sys_path
))
1688 PyObject
*pythondir
;
1691 pythondir
= PyString_FromString (gdb_pythondir
);
1692 if (pythondir
== NULL
)
1695 err
= PyList_Insert (sys_path
, 0, pythondir
);
1699 Py_DECREF (pythondir
);
1704 /* Import the gdb module to finish the initialization, and
1705 add it to __main__ for convenience. */
1706 m
= PyImport_AddModule ("__main__");
1710 gdb_python_module
= PyImport_ImportModule ("gdb");
1711 if (gdb_python_module
== NULL
)
1713 gdbpy_print_stack ();
1714 /* This is passed in one call to warning so that blank lines aren't
1715 inserted between each line of text. */
1717 "Could not load the Python gdb module from `%s'.\n"
1718 "Limited Python support is available from the _gdb module.\n"
1719 "Suggest passing --data-directory=/path/to/gdb/data-directory.\n"),
1721 do_cleanups (cleanup
);
1725 if (PyModule_AddObject (m
, "gdb", gdb_python_module
))
1728 /* Keep the reference to gdb_python_module since it is in a global
1731 do_cleanups (cleanup
);
1735 gdbpy_print_stack ();
1736 warning (_("internal error: Unhandled Python exception"));
1737 do_cleanups (cleanup
);
1740 #endif /* HAVE_PYTHON */
1746 static PyMethodDef GdbMethods
[] =
1748 { "history", gdbpy_history
, METH_VARARGS
,
1749 "Get a value from history" },
1750 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1751 "Execute a gdb command" },
1752 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1753 "Return a gdb parameter's value" },
1755 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1756 "Return a tuple of all breakpoint objects" },
1758 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1759 "Find the default visualizer for a Value." },
1761 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1762 "Return the current Progspace." },
1763 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1764 "Return a sequence of all progspaces." },
1766 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1767 "Return the current Objfile being loaded, or None." },
1768 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1769 "Return a sequence of all loaded objfiles." },
1771 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1772 "newest_frame () -> gdb.Frame.\n\
1773 Return the newest frame object." },
1774 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1775 "selected_frame () -> gdb.Frame.\n\
1776 Return the selected frame object." },
1777 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1778 "stop_reason_string (Integer) -> String.\n\
1779 Return a string explaining unwind stop reason." },
1781 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1782 METH_VARARGS
| METH_KEYWORDS
,
1783 "lookup_type (name [, block]) -> type\n\
1784 Return a Type corresponding to the given name." },
1785 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1786 METH_VARARGS
| METH_KEYWORDS
,
1787 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1788 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1789 a boolean indicating if name is a field of the current implied argument\n\
1790 `this' (when the current language is object-oriented)." },
1791 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1792 METH_VARARGS
| METH_KEYWORDS
,
1793 "lookup_global_symbol (name [, domain]) -> symbol\n\
1794 Return the symbol corresponding to the given name (or None)." },
1795 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1796 "Return the block containing the given pc value, or None." },
1797 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1798 "solib_name (Long) -> String.\n\
1799 Return the name of the shared library holding a given address, or None." },
1800 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1801 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1802 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1803 The first element contains any unparsed portion of the String parameter\n\
1804 (or None if the string was fully parsed). The second element contains\n\
1805 a tuple that contains all the locations that match, represented as\n\
1806 gdb.Symtab_and_line objects (or None)."},
1807 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1808 "parse_and_eval (String) -> Value.\n\
1809 Parse String as an expression, evaluate it, and return the result as a Value."
1811 { "find_pc_line", gdbpy_find_pc_line
, METH_VARARGS
,
1812 "find_pc_line (pc) -> Symtab_and_line.\n\
1813 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1815 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1816 "Post an event into gdb's event loop." },
1818 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1819 "target_charset () -> string.\n\
1820 Return the name of the current target charset." },
1821 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1822 "target_wide_charset () -> string.\n\
1823 Return the name of the current target wide charset." },
1825 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1826 "string_to_argv (String) -> Array.\n\
1827 Parse String and return an argv-like array.\n\
1828 Arguments are separate by spaces and may be quoted."
1830 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1831 "Write a string using gdb's filtered stream." },
1832 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1833 "Flush gdb's filtered stdout stream." },
1834 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1835 "selected_thread () -> gdb.InferiorThread.\n\
1836 Return the selected thread object." },
1837 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1838 "selected_inferior () -> gdb.Inferior.\n\
1839 Return the selected inferior object." },
1840 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1841 "inferiors () -> (gdb.Inferior, ...).\n\
1842 Return a tuple containing all inferiors." },
1843 {NULL
, NULL
, 0, NULL
}
1847 static struct PyModuleDef GdbModuleDef
=
1849 PyModuleDef_HEAD_INIT
,
1860 #endif /* HAVE_PYTHON */