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 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
157 On Windows hosts few users would build Python themselves (this is no
158 trivial task on this platform), and thus use binaries built by
159 someone else instead. There may happen situation where the Python
160 library and GDB are using two different versions of the C runtime
161 library. Python, being built with VC, would use one version of the
162 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
163 A FILE * from one runtime does not necessarily operate correctly in
166 To work around this potential issue, we create on Windows hosts the
167 FILE object using Python routines, thus making sure that it is
168 compatible with the Python library. */
171 python_run_simple_file (FILE *file
, const char *filename
)
175 PyRun_SimpleFile (file
, filename
);
180 PyObject
*python_file
;
181 struct cleanup
*cleanup
;
183 /* Because we have a string for a filename, and are using Python to
184 open the file, we need to expand any tilde in the path first. */
185 full_path
= tilde_expand (filename
);
186 cleanup
= make_cleanup (xfree
, full_path
);
187 python_file
= PyFile_FromString (full_path
, "r");
190 do_cleanups (cleanup
);
191 gdbpy_print_stack ();
192 error (_("Error while opening file: %s"), full_path
);
195 make_cleanup_py_decref (python_file
);
196 PyRun_SimpleFile (PyFile_AsFile (python_file
), filename
);
197 do_cleanups (cleanup
);
202 /* Given a command_line, return a command string suitable for passing
203 to Python. Lines in the string are separated by newlines. The
204 return value is allocated using xmalloc and the caller is
205 responsible for freeing it. */
208 compute_python_string (struct command_line
*l
)
210 struct command_line
*iter
;
215 for (iter
= l
; iter
; iter
= iter
->next
)
216 size
+= strlen (iter
->line
) + 1;
218 script
= xmalloc (size
+ 1);
220 for (iter
= l
; iter
; iter
= iter
->next
)
222 int len
= strlen (iter
->line
);
224 strcpy (&script
[here
], iter
->line
);
226 script
[here
++] = '\n';
232 /* Take a command line structure representing a 'python' command, and
233 evaluate its body using the Python interpreter. */
236 eval_python_from_control_command (struct command_line
*cmd
)
240 struct cleanup
*cleanup
;
242 if (cmd
->body_count
!= 1)
243 error (_("Invalid \"python\" block structure."));
245 cleanup
= ensure_python_env (get_current_arch (), current_language
);
247 script
= compute_python_string (cmd
->body_list
[0]);
248 ret
= PyRun_SimpleString (script
);
251 error (_("Error while executing Python code."));
253 do_cleanups (cleanup
);
256 /* Implementation of the gdb "python" command. */
259 python_command (char *arg
, int from_tty
)
261 struct cleanup
*cleanup
;
263 cleanup
= ensure_python_env (get_current_arch (), current_language
);
265 make_cleanup_restore_integer (&interpreter_async
);
266 interpreter_async
= 0;
268 while (arg
&& *arg
&& isspace (*arg
))
272 if (PyRun_SimpleString (arg
))
273 error (_("Error while executing Python code."));
277 struct command_line
*l
= get_command_line (python_control
, "");
279 make_cleanup_free_command_lines (&l
);
280 execute_control_command_untraced (l
);
283 do_cleanups (cleanup
);
288 /* Transform a gdb parameters's value into a Python value. May return
289 NULL (and set a Python exception) on error. Helper function for
292 gdbpy_parameter_value (enum var_types type
, void *var
)
297 case var_string_noescape
:
298 case var_optional_filename
:
302 char *str
= * (char **) var
;
306 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
317 case var_auto_boolean
:
319 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
321 if (ab
== AUTO_BOOLEAN_TRUE
)
323 else if (ab
== AUTO_BOOLEAN_FALSE
)
330 if ((* (int *) var
) == INT_MAX
)
334 return PyLong_FromLong (* (int *) var
);
338 unsigned int val
= * (unsigned int *) var
;
342 return PyLong_FromUnsignedLong (val
);
346 return PyErr_Format (PyExc_RuntimeError
,
347 _("Programmer error: unhandled type."));
350 /* A Python function which returns a gdb parameter's value as a Python
354 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
356 struct cmd_list_element
*alias
, *prefix
, *cmd
;
360 volatile struct gdb_exception except
;
362 if (! PyArg_ParseTuple (args
, "s", &arg
))
365 newarg
= concat ("show ", arg
, (char *) NULL
);
367 TRY_CATCH (except
, RETURN_MASK_ALL
)
369 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
372 GDB_PY_HANDLE_EXCEPTION (except
);
374 return PyErr_Format (PyExc_RuntimeError
,
375 _("Could not find parameter `%s'."), arg
);
378 return PyErr_Format (PyExc_RuntimeError
,
379 _("`%s' is not a parameter."), arg
);
380 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
383 /* Wrapper for target_charset. */
386 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
388 const char *cset
= target_charset (python_gdbarch
);
390 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
393 /* Wrapper for target_wide_charset. */
396 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
398 const char *cset
= target_wide_charset (python_gdbarch
);
400 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
403 /* A Python function which evaluates a string using the gdb CLI. */
406 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
409 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
410 int from_tty
, to_string
;
411 volatile struct gdb_exception except
;
412 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
415 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
416 &PyBool_Type
, &from_tty_obj
,
417 &PyBool_Type
, &to_string_obj
))
423 int cmp
= PyObject_IsTrue (from_tty_obj
);
432 int cmp
= PyObject_IsTrue (to_string_obj
);
438 TRY_CATCH (except
, RETURN_MASK_ALL
)
440 /* Copy the argument text in case the command modifies it. */
441 char *copy
= xstrdup (arg
);
442 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
444 make_cleanup_restore_integer (&interpreter_async
);
445 interpreter_async
= 0;
447 prevent_dont_repeat ();
449 result
= execute_command_to_string (copy
, from_tty
);
453 execute_command (copy
, from_tty
);
456 do_cleanups (cleanup
);
458 GDB_PY_HANDLE_EXCEPTION (except
);
460 /* Do any commands attached to breakpoint we stopped at. */
461 bpstat_do_actions ();
465 PyObject
*r
= PyString_FromString (result
);
472 /* Implementation of gdb.solib_name (Long) -> String.
473 Returns the name of the shared library holding a given address, or None. */
476 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
482 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
485 soname
= solib_name_from_address (current_program_space
, pc
);
487 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
497 /* A Python function which is a wrapper for decode_line_1. */
500 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
502 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
504 struct symtab_and_line sal
;
505 const char *arg
= NULL
;
506 char *copy_to_free
= NULL
, *copy
= NULL
;
507 struct cleanup
*cleanups
;
508 PyObject
*result
= NULL
;
509 PyObject
*return_result
= NULL
;
510 PyObject
*unparsed
= NULL
;
511 volatile struct gdb_exception except
;
513 if (! PyArg_ParseTuple (args
, "|s", &arg
))
516 cleanups
= make_cleanup (null_cleanup
, NULL
);
519 TRY_CATCH (except
, RETURN_MASK_ALL
)
523 copy
= xstrdup (arg
);
525 sals
= decode_line_1 (©
, 0, 0, 0);
529 set_default_source_symtab_and_line ();
530 sal
= get_current_source_symtab_and_line ();
536 if (sals
.sals
!= NULL
&& sals
.sals
!= &sal
)
538 make_cleanup (xfree
, copy_to_free
);
539 make_cleanup (xfree
, sals
.sals
);
542 if (except
.reason
< 0)
544 do_cleanups (cleanups
);
545 /* We know this will always throw. */
546 GDB_PY_HANDLE_EXCEPTION (except
);
553 result
= PyTuple_New (sals
.nelts
);
556 for (i
= 0; i
< sals
.nelts
; ++i
)
560 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
567 PyTuple_SetItem (result
, i
, obj
);
576 return_result
= PyTuple_New (2);
583 if (copy
&& strlen (copy
) > 0)
585 unparsed
= PyString_FromString (copy
);
586 if (unparsed
== NULL
)
589 Py_DECREF (return_result
);
590 return_result
= NULL
;
600 PyTuple_SetItem (return_result
, 0, unparsed
);
601 PyTuple_SetItem (return_result
, 1, result
);
604 do_cleanups (cleanups
);
606 return return_result
;
609 /* Parse a string and evaluate it as an expression. */
611 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
613 const char *expr_str
;
614 struct value
*result
= NULL
;
615 volatile struct gdb_exception except
;
617 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
620 TRY_CATCH (except
, RETURN_MASK_ALL
)
622 char *copy
= xstrdup (expr_str
);
623 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
625 result
= parse_and_eval (copy
);
626 do_cleanups (cleanup
);
628 GDB_PY_HANDLE_EXCEPTION (except
);
630 return value_to_value_object (result
);
633 /* Implementation of gdb.find_pc_line function.
634 Returns the gdb.Symtab_and_line object corresponding to a PC value. */
637 gdbpy_find_pc_line (PyObject
*self
, PyObject
*args
)
639 struct symtab_and_line sal
;
641 gdb_py_ulongest pc_llu
;
643 if (!PyArg_ParseTuple (args
, GDB_PY_LLU_ARG
, &pc_llu
))
646 pc
= (CORE_ADDR
) pc_llu
;
647 sal
= find_pc_line (pc
, 0);
648 return symtab_and_line_to_sal_object (sal
);
651 /* Read a file as Python code.
652 FILE is the file to run. FILENAME is name of the file FILE.
653 This does not throw any errors. If an exception occurs python will print
654 the traceback and clear the error indicator. */
657 source_python_script (FILE *file
, const char *filename
)
659 struct cleanup
*cleanup
;
661 cleanup
= ensure_python_env (get_current_arch (), current_language
);
662 python_run_simple_file (file
, filename
);
663 do_cleanups (cleanup
);
668 /* Posting and handling events. */
670 /* A single event. */
673 /* The Python event. This is just a callable object. */
675 /* The next event. */
676 struct gdbpy_event
*next
;
679 /* All pending events. */
680 static struct gdbpy_event
*gdbpy_event_list
;
681 /* The final link of the event list. */
682 static struct gdbpy_event
**gdbpy_event_list_end
;
684 /* We use a file handler, and not an async handler, so that we can
685 wake up the main thread even when it is blocked in poll(). */
686 static struct serial
*gdbpy_event_fds
[2];
688 /* The file handler callback. This reads from the internal pipe, and
689 then processes the Python event queue. This will always be run in
690 the main gdb thread. */
693 gdbpy_run_events (struct serial
*scb
, void *context
)
695 struct cleanup
*cleanup
;
697 cleanup
= ensure_python_env (get_current_arch (), current_language
);
699 /* Flush the fd. Do this before flushing the events list, so that
700 any new event post afterwards is sure to re-awake the event
702 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
705 while (gdbpy_event_list
)
707 /* Dispatching the event might push a new element onto the event
708 loop, so we update here "atomically enough". */
709 struct gdbpy_event
*item
= gdbpy_event_list
;
710 gdbpy_event_list
= gdbpy_event_list
->next
;
711 if (gdbpy_event_list
== NULL
)
712 gdbpy_event_list_end
= &gdbpy_event_list
;
715 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
718 Py_DECREF (item
->event
);
722 do_cleanups (cleanup
);
725 /* Submit an event to the gdb thread. */
727 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
729 struct gdbpy_event
*event
;
733 if (!PyArg_ParseTuple (args
, "O", &func
))
736 if (!PyCallable_Check (func
))
738 PyErr_SetString (PyExc_RuntimeError
,
739 _("Posted event is not callable"));
745 /* From here until the end of the function, we have the GIL, so we
746 can operate on our global data structures without worrying. */
747 wakeup
= gdbpy_event_list
== NULL
;
749 event
= XNEW (struct gdbpy_event
);
752 *gdbpy_event_list_end
= event
;
753 gdbpy_event_list_end
= &event
->next
;
755 /* Wake up gdb when needed. */
758 char c
= 'q'; /* Anything. */
760 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
761 return PyErr_SetFromErrno (PyExc_IOError
);
767 /* Initialize the Python event handler. */
769 gdbpy_initialize_events (void)
771 if (serial_pipe (gdbpy_event_fds
) == 0)
773 gdbpy_event_list_end
= &gdbpy_event_list
;
774 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
781 before_prompt_hook (const char *current_gdb_prompt
)
783 struct cleanup
*cleanup
;
786 cleanup
= ensure_python_env (get_current_arch (), current_language
);
788 if (PyObject_HasAttrString (gdb_module
, "prompt_hook"))
792 hook
= PyObject_GetAttrString (gdb_module
, "prompt_hook");
796 if (PyCallable_Check (hook
))
799 PyObject
*current_prompt
;
801 current_prompt
= PyString_FromString (current_gdb_prompt
);
802 if (current_prompt
== NULL
)
805 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
807 Py_DECREF (current_prompt
);
812 make_cleanup_py_decref (result
);
814 /* Return type should be None, or a String. If it is None,
815 fall through, we will not set a prompt. If it is a
816 string, set PROMPT. Anything else, set an exception. */
817 if (result
!= Py_None
&& ! PyString_Check (result
))
819 PyErr_Format (PyExc_RuntimeError
,
820 _("Return from prompt_hook must " \
821 "be either a Python string, or None"));
825 if (result
!= Py_None
)
827 prompt
= python_string_to_host_string (result
);
832 make_cleanup (xfree
, prompt
);
837 /* If a prompt has been set, PROMPT will not be NULL. If it is
838 NULL, do not set the prompt. */
842 do_cleanups (cleanup
);
846 gdbpy_print_stack ();
847 do_cleanups (cleanup
);
855 /* A python function to write a single string using gdb's filtered
856 output stream . The optional keyword STREAM can be used to write
857 to a particular stream. The default stream is to gdb_stdout. */
860 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
863 static char *keywords
[] = {"text", "stream", NULL
};
865 volatile struct gdb_exception except
;
867 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
871 TRY_CATCH (except
, RETURN_MASK_ALL
)
877 fprintf_filtered (gdb_stderr
, "%s", arg
);
882 fprintf_filtered (gdb_stdlog
, "%s", arg
);
886 fprintf_filtered (gdb_stdout
, "%s", arg
);
889 GDB_PY_HANDLE_EXCEPTION (except
);
894 /* A python function to flush a gdb stream. The optional keyword
895 STREAM can be used to flush a particular stream. The default stream
899 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
901 static char *keywords
[] = {"stream", NULL
};
904 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
912 gdb_flush (gdb_stderr
);
917 gdb_flush (gdb_stdlog
);
921 gdb_flush (gdb_stdout
);
927 /* Print a python exception trace, print just a message, or print
928 nothing and clear the python exception, depending on
929 gdbpy_should_print_stack. Only call this if a python exception is
932 gdbpy_print_stack (void)
934 /* Print "none", just clear exception. */
935 if (gdbpy_should_print_stack
== python_excp_none
)
939 /* Print "full" message and backtrace. */
940 else if (gdbpy_should_print_stack
== python_excp_full
)
943 /* PyErr_Print doesn't necessarily end output with a newline.
944 This works because Python's stdout/stderr is fed through
948 /* Print "message", just error print message. */
951 PyObject
*ptype
, *pvalue
, *ptraceback
;
952 char *msg
= NULL
, *type
= NULL
;
954 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
956 /* Fetch the error message contained within ptype, pvalue. */
957 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
958 type
= gdbpy_obj_to_string (ptype
);
961 /* An error occurred computing the string representation of the
963 fprintf_filtered (gdb_stderr
,
964 _("Error occurred computing Python error" \
968 fprintf_filtered (gdb_stderr
, "Python Exception %s %s: \n",
973 Py_XDECREF (ptraceback
);
980 /* Return the current Progspace.
981 There always is one. */
984 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
988 result
= pspace_to_pspace_object (current_program_space
);
994 /* Return a sequence holding all the Progspaces. */
997 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
999 struct program_space
*ps
;
1002 list
= PyList_New (0);
1008 PyObject
*item
= pspace_to_pspace_object (ps
);
1010 if (!item
|| PyList_Append (list
, item
) == -1)
1022 /* The "current" objfile. This is set when gdb detects that a new
1023 objfile has been loaded. It is only set for the duration of a call to
1024 source_python_script_for_objfile; it is NULL at other times. */
1025 static struct objfile
*gdbpy_current_objfile
;
1027 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1028 as Python code. This does not throw any errors. If an exception
1029 occurs python will print the traceback and clear the error indicator. */
1032 source_python_script_for_objfile (struct objfile
*objfile
, FILE *file
,
1033 const char *filename
)
1035 struct cleanup
*cleanups
;
1037 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
1038 gdbpy_current_objfile
= objfile
;
1040 python_run_simple_file (file
, filename
);
1042 do_cleanups (cleanups
);
1043 gdbpy_current_objfile
= NULL
;
1046 /* Return the current Objfile, or None if there isn't one. */
1049 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
1053 if (! gdbpy_current_objfile
)
1056 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
1062 /* Return a sequence holding all the Objfiles. */
1065 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
1067 struct objfile
*objf
;
1070 list
= PyList_New (0);
1076 PyObject
*item
= objfile_to_objfile_object (objf
);
1078 if (!item
|| PyList_Append (list
, item
) == -1)
1088 #else /* HAVE_PYTHON */
1090 /* Dummy implementation of the gdb "python" command. */
1093 python_command (char *arg
, int from_tty
)
1095 while (arg
&& *arg
&& isspace (*arg
))
1098 error (_("Python scripting is not supported in this copy of GDB."));
1101 struct command_line
*l
= get_command_line (python_control
, "");
1102 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1104 execute_control_command_untraced (l
);
1105 do_cleanups (cleanups
);
1110 eval_python_from_control_command (struct command_line
*cmd
)
1112 error (_("Python scripting is not supported in this copy of GDB."));
1116 source_python_script (FILE *file
, const char *filename
)
1118 throw_error (UNSUPPORTED_ERROR
,
1119 _("Python scripting is not supported in this copy of GDB."));
1123 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1125 internal_error (__FILE__
, __LINE__
,
1126 _("gdbpy_should_stop called when Python scripting is " \
1131 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1133 internal_error (__FILE__
, __LINE__
,
1134 _("gdbpy_breakpoint_has_py_cond called when Python " \
1135 "scripting is not supported."));
1138 #endif /* HAVE_PYTHON */
1142 /* Lists for 'set python' commands. */
1144 static struct cmd_list_element
*user_set_python_list
;
1145 static struct cmd_list_element
*user_show_python_list
;
1147 /* Function for use by 'set python' prefix command. */
1150 user_set_python (char *args
, int from_tty
)
1152 help_list (user_set_python_list
, "set python ", all_commands
,
1156 /* Function for use by 'show python' prefix command. */
1159 user_show_python (char *args
, int from_tty
)
1161 cmd_show_list (user_show_python_list
, from_tty
, "");
1164 /* Initialize the Python code. */
1166 /* Provide a prototype to silence -Wmissing-prototypes. */
1167 extern initialize_file_ftype _initialize_python
;
1170 _initialize_python (void)
1173 struct cmd_list_element
*cmd
;
1175 add_com ("python", class_obscure
, python_command
,
1178 Evaluate a Python command.\n\
1180 The command can be given as an argument, for instance:\n\
1184 If no argument is given, the following lines are read and used\n\
1185 as the Python commands. Type a line containing \"end\" to indicate\n\
1186 the end of the command.")
1187 #else /* HAVE_PYTHON */
1189 Evaluate a Python command.\n\
1191 Python scripting is not supported in this copy of GDB.\n\
1192 This command is only a placeholder.")
1193 #endif /* HAVE_PYTHON */
1196 /* Add set/show python print-stack. */
1197 add_prefix_cmd ("python", no_class
, user_show_python
,
1198 _("Prefix command for python preference settings."),
1199 &user_show_python_list
, "show python ", 0,
1202 add_prefix_cmd ("python", no_class
, user_set_python
,
1203 _("Prefix command for python preference settings."),
1204 &user_set_python_list
, "set python ", 0,
1207 add_setshow_enum_cmd ("print-stack", no_class
, python_excp_enums
,
1208 &gdbpy_should_print_stack
, _("\
1209 Set mode for Python stack dump on error."), _("\
1210 Show the mode of Python stack printing on error."), _("\
1211 none == no stack or message will be printed.\n\
1212 full == a message and a stack will be printed.\n\
1213 message == an error message without a stack will be printed."),
1215 &user_set_python_list
,
1216 &user_show_python_list
);
1219 #ifdef WITH_PYTHON_PATH
1220 /* Work around problem where python gets confused about where it is,
1221 and then can't find its libraries, etc.
1222 NOTE: Python assumes the following layout:
1224 /foo/lib/pythonX.Y/...
1225 This must be done before calling Py_Initialize. */
1226 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1227 SLASH_STRING
, "python", NULL
));
1231 PyEval_InitThreads ();
1233 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
1235 /* The casts to (char*) are for python 2.4. */
1236 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1237 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1238 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1239 (char*) target_name
);
1241 /* Add stream constants. */
1242 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1243 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1244 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1246 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1247 script below is run (depending on order of _initialize_* functions).
1248 Define the initial value of gdb.PYTHONDIR here. */
1250 char *gdb_pythondir
;
1252 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1253 PyModule_AddStringConstant (gdb_module
, "PYTHONDIR", gdb_pythondir
);
1254 xfree (gdb_pythondir
);
1257 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1258 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1260 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1261 gdbpy_gdb_error
, NULL
);
1262 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1264 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1265 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1267 gdbpy_initialize_auto_load ();
1268 gdbpy_initialize_values ();
1269 gdbpy_initialize_frames ();
1270 gdbpy_initialize_commands ();
1271 gdbpy_initialize_symbols ();
1272 gdbpy_initialize_symtabs ();
1273 gdbpy_initialize_blocks ();
1274 gdbpy_initialize_functions ();
1275 gdbpy_initialize_parameters ();
1276 gdbpy_initialize_types ();
1277 gdbpy_initialize_pspace ();
1278 gdbpy_initialize_objfile ();
1279 gdbpy_initialize_breakpoints ();
1280 gdbpy_initialize_finishbreakpoints ();
1281 gdbpy_initialize_lazy_string ();
1282 gdbpy_initialize_thread ();
1283 gdbpy_initialize_inferior ();
1284 gdbpy_initialize_events ();
1286 gdbpy_initialize_eventregistry ();
1287 gdbpy_initialize_py_events ();
1288 gdbpy_initialize_event ();
1289 gdbpy_initialize_stop_event ();
1290 gdbpy_initialize_signal_event ();
1291 gdbpy_initialize_breakpoint_event ();
1292 gdbpy_initialize_continue_event ();
1293 gdbpy_initialize_exited_event ();
1294 gdbpy_initialize_thread_event ();
1295 gdbpy_initialize_new_objfile_event () ;
1297 observer_attach_before_prompt (before_prompt_hook
);
1299 PyRun_SimpleString ("import gdb");
1300 PyRun_SimpleString ("gdb.pretty_printers = []");
1302 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1303 gdbpy_children_cst
= PyString_FromString ("children");
1304 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1305 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1306 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1307 gdbpy_value_cst
= PyString_FromString ("value");
1309 /* Release the GIL while gdb runs. */
1310 PyThreadState_Swap (NULL
);
1311 PyEval_ReleaseLock ();
1313 #endif /* HAVE_PYTHON */
1318 /* Perform the remaining python initializations.
1319 These must be done after GDB is at least mostly initialized.
1320 E.g., The "info pretty-printer" command needs the "info" prefix
1321 command installed. */
1324 finish_python_initialization (void)
1326 struct cleanup
*cleanup
;
1328 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1330 PyRun_SimpleString ("\
1334 class GdbOutputFile:\n\
1339 def isatty(self):\n\
1342 def write(self, s):\n\
1343 gdb.write(s, stream=gdb.STDOUT)\n \
1345 def writelines(self, iterable):\n\
1346 for line in iterable:\n\
1352 sys.stdout = GdbOutputFile()\n\
1354 class GdbOutputErrorFile:\n\
1359 def isatty(self):\n\
1362 def write(self, s):\n\
1363 gdb.write(s, stream=gdb.STDERR)\n \
1365 def writelines(self, iterable):\n\
1366 for line in iterable:\n\
1367 self.write(line)\n \
1372 sys.stderr = GdbOutputErrorFile()\n\
1374 # Ideally this would live in the gdb module, but it's intentionally written\n\
1375 # in python, and we need this to bootstrap the gdb module.\n\
1377 def GdbSetPythonDirectory (dir):\n\
1378 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1379 old_dir = gdb.PYTHONDIR\n\
1380 gdb.PYTHONDIR = dir\n\
1381 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1382 # that directory name at the start of sys.path to allow the Python\n\
1383 # interpreter to find them.\n\
1384 if old_dir in sys.path:\n\
1385 sys.path.remove (old_dir)\n\
1386 sys.path.insert (0, gdb.PYTHONDIR)\n\
1388 # Tell python where to find submodules of gdb.\n\
1389 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1391 # The gdb module is implemented in C rather than in Python. As a result,\n\
1392 # the associated __init.py__ script is not not executed by default when\n\
1393 # the gdb module gets imported. Execute that script manually if it\n\
1395 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1396 if os.path.exists (ipy):\n\
1399 # Install the default gdb.PYTHONDIR.\n\
1400 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1401 # Default prompt hook does nothing.\n\
1402 prompt_hook = None\n\
1403 # Ensure that sys.argv is set to something.\n\
1404 # We do not use PySys_SetArgvEx because it did not appear until 2.6.6.\n\
1408 do_cleanups (cleanup
);
1411 #endif /* HAVE_PYTHON */
1417 static PyMethodDef GdbMethods
[] =
1419 { "history", gdbpy_history
, METH_VARARGS
,
1420 "Get a value from history" },
1421 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1422 "Execute a gdb command" },
1423 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1424 "Return a gdb parameter's value" },
1426 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1427 "Return a tuple of all breakpoint objects" },
1429 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1430 "Find the default visualizer for a Value." },
1432 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1433 "Return the current Progspace." },
1434 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1435 "Return a sequence of all progspaces." },
1437 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1438 "Return the current Objfile being loaded, or None." },
1439 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1440 "Return a sequence of all loaded objfiles." },
1442 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1443 "newest_frame () -> gdb.Frame.\n\
1444 Return the newest frame object." },
1445 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1446 "selected_frame () -> gdb.Frame.\n\
1447 Return the selected frame object." },
1448 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1449 "stop_reason_string (Integer) -> String.\n\
1450 Return a string explaining unwind stop reason." },
1452 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1453 METH_VARARGS
| METH_KEYWORDS
,
1454 "lookup_type (name [, block]) -> type\n\
1455 Return a Type corresponding to the given name." },
1456 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1457 METH_VARARGS
| METH_KEYWORDS
,
1458 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1459 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1460 a boolean indicating if name is a field of the current implied argument\n\
1461 `this' (when the current language is object-oriented)." },
1462 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1463 METH_VARARGS
| METH_KEYWORDS
,
1464 "lookup_global_symbol (name [, domain]) -> symbol\n\
1465 Return the symbol corresponding to the given name (or None)." },
1466 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1467 "Return the block containing the given pc value, or None." },
1468 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1469 "solib_name (Long) -> String.\n\
1470 Return the name of the shared library holding a given address, or None." },
1471 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1472 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1473 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1474 The first element contains any unparsed portion of the String parameter\n\
1475 (or None if the string was fully parsed). The second element contains\n\
1476 a tuple that contains all the locations that match, represented as\n\
1477 gdb.Symtab_and_line objects (or None)."},
1478 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1479 "parse_and_eval (String) -> Value.\n\
1480 Parse String as an expression, evaluate it, and return the result as a Value."
1482 { "find_pc_line", gdbpy_find_pc_line
, METH_VARARGS
,
1483 "find_pc_line (pc) -> Symtab_and_line.\n\
1484 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1486 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1487 "Post an event into gdb's event loop." },
1489 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1490 "target_charset () -> string.\n\
1491 Return the name of the current target charset." },
1492 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1493 "target_wide_charset () -> string.\n\
1494 Return the name of the current target wide charset." },
1496 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1497 "string_to_argv (String) -> Array.\n\
1498 Parse String and return an argv-like array.\n\
1499 Arguments are separate by spaces and may be quoted."
1501 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1502 "Write a string using gdb's filtered stream." },
1503 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1504 "Flush gdb's filtered stdout stream." },
1505 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1506 "selected_thread () -> gdb.InferiorThread.\n\
1507 Return the selected thread object." },
1508 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1509 "selected_inferior () -> gdb.Inferior.\n\
1510 Return the selected inferior object." },
1511 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1512 "inferiors () -> (gdb.Inferior, ...).\n\
1513 Return a tuple containing all inferiors." },
1514 {NULL
, NULL
, 0, NULL
}
1517 #endif /* HAVE_PYTHON */