1 /* General python/gdb code
3 Copyright (C) 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "arch-utils.h"
24 #include "cli/cli-script.h"
26 #include "progspace.h"
30 #include "exceptions.h"
31 #include "event-loop.h"
37 /* True if we should print the stack when catching a Python error,
39 static int gdbpy_should_print_stack
= 0;
43 #include "libiberty.h"
44 #include "cli/cli-decode.h"
48 #include "python-internal.h"
53 #include "gdbthread.h"
57 static PyMethodDef GdbMethods
[];
61 /* Some string constants we may wish to use. */
62 PyObject
*gdbpy_to_string_cst
;
63 PyObject
*gdbpy_children_cst
;
64 PyObject
*gdbpy_display_hint_cst
;
65 PyObject
*gdbpy_doc_cst
;
66 PyObject
*gdbpy_enabled_cst
;
67 PyObject
*gdbpy_value_cst
;
69 /* The GdbError exception. */
70 PyObject
*gdbpy_gdberror_exc
;
72 /* The `gdb.error' base class. */
73 PyObject
*gdbpy_gdb_error
;
75 /* The `gdb.MemoryError' exception. */
76 PyObject
*gdbpy_gdb_memory_error
;
78 /* Architecture and language to be used in callbacks from
79 the Python interpreter. */
80 struct gdbarch
*python_gdbarch
;
81 const struct language_defn
*python_language
;
83 /* Restore global language and architecture and Python GIL state
84 when leaving the Python interpreter. */
88 PyGILState_STATE state
;
89 struct gdbarch
*gdbarch
;
90 const struct language_defn
*language
;
91 PyObject
*error_type
, *error_value
, *error_traceback
;
95 restore_python_env (void *p
)
97 struct python_env
*env
= (struct python_env
*)p
;
99 /* Leftover Python error is forbidden by Python Exception Handling. */
100 if (PyErr_Occurred ())
102 /* This order is similar to the one calling error afterwards. */
103 gdbpy_print_stack ();
104 warning (_("internal error: Unhandled Python exception"));
107 PyErr_Restore (env
->error_type
, env
->error_value
, env
->error_traceback
);
109 PyGILState_Release (env
->state
);
110 python_gdbarch
= env
->gdbarch
;
111 python_language
= env
->language
;
115 /* Called before entering the Python interpreter to install the
116 current language and architecture to be used for Python values. */
119 ensure_python_env (struct gdbarch
*gdbarch
,
120 const struct language_defn
*language
)
122 struct python_env
*env
= xmalloc (sizeof *env
);
124 env
->state
= PyGILState_Ensure ();
125 env
->gdbarch
= python_gdbarch
;
126 env
->language
= python_language
;
128 python_gdbarch
= gdbarch
;
129 python_language
= language
;
131 /* Save it and ensure ! PyErr_Occurred () afterwards. */
132 PyErr_Fetch (&env
->error_type
, &env
->error_value
, &env
->error_traceback
);
134 return make_cleanup (restore_python_env
, env
);
137 /* A wrapper around PyRun_SimpleFile. FILENAME is the name of
138 the Python script to run.
140 One of the parameters of PyRun_SimpleFile is a FILE *.
141 The problem is that type FILE is extremely system and compiler
142 dependent. So, unless the Python library has been compiled using
143 the same build environment as GDB, we run the risk of getting
144 a crash due to inconsistencies between the definition used by GDB,
145 and the definition used by Python. A mismatch can very likely
148 There is also the situation where the Python library and GDB
149 are using two different versions of the C runtime library.
150 This is particularly visible on Windows, where few users would
151 build Python themselves (this is no trivial task on this platform),
152 and thus use binaries built by someone else instead. Python,
153 being built with VC, would use one version of the msvcr DLL
154 (Eg. msvcr100.dll), while MinGW uses msvcrt.dll. A FILE *
155 from one runtime does not necessarily operate correctly in
158 To work around this potential issue, we create the FILE object
159 using Python routines, thus making sure that it is compatible
160 with the Python library. */
163 python_run_simple_file (const char *filename
)
166 PyObject
*python_file
;
167 struct cleanup
*cleanup
;
169 filename_copy
= xstrdup (filename
);
170 cleanup
= make_cleanup (xfree
, filename_copy
);
171 python_file
= PyFile_FromString (filename_copy
, "r");
172 make_cleanup_py_decref (python_file
);
173 PyRun_SimpleFile (PyFile_AsFile (python_file
), filename
);
174 do_cleanups (cleanup
);
177 /* Given a command_line, return a command string suitable for passing
178 to Python. Lines in the string are separated by newlines. The
179 return value is allocated using xmalloc and the caller is
180 responsible for freeing it. */
183 compute_python_string (struct command_line
*l
)
185 struct command_line
*iter
;
190 for (iter
= l
; iter
; iter
= iter
->next
)
191 size
+= strlen (iter
->line
) + 1;
193 script
= xmalloc (size
+ 1);
195 for (iter
= l
; iter
; iter
= iter
->next
)
197 int len
= strlen (iter
->line
);
199 strcpy (&script
[here
], iter
->line
);
201 script
[here
++] = '\n';
207 /* Take a command line structure representing a 'python' command, and
208 evaluate its body using the Python interpreter. */
211 eval_python_from_control_command (struct command_line
*cmd
)
215 struct cleanup
*cleanup
;
217 if (cmd
->body_count
!= 1)
218 error (_("Invalid \"python\" block structure."));
220 cleanup
= ensure_python_env (get_current_arch (), current_language
);
222 script
= compute_python_string (cmd
->body_list
[0]);
223 ret
= PyRun_SimpleString (script
);
227 gdbpy_print_stack ();
228 error (_("Error while executing Python code."));
231 do_cleanups (cleanup
);
234 /* Implementation of the gdb "python" command. */
237 python_command (char *arg
, int from_tty
)
239 struct cleanup
*cleanup
;
241 cleanup
= ensure_python_env (get_current_arch (), current_language
);
243 make_cleanup_restore_integer (&interpreter_async
);
244 interpreter_async
= 0;
246 while (arg
&& *arg
&& isspace (*arg
))
250 if (PyRun_SimpleString (arg
))
252 gdbpy_print_stack ();
253 error (_("Error while executing Python code."));
258 struct command_line
*l
= get_command_line (python_control
, "");
260 make_cleanup_free_command_lines (&l
);
261 execute_control_command_untraced (l
);
264 do_cleanups (cleanup
);
269 /* Transform a gdb parameters's value into a Python value. May return
270 NULL (and set a Python exception) on error. Helper function for
273 gdbpy_parameter_value (enum var_types type
, void *var
)
278 case var_string_noescape
:
279 case var_optional_filename
:
283 char *str
= * (char **) var
;
287 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
298 case var_auto_boolean
:
300 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
302 if (ab
== AUTO_BOOLEAN_TRUE
)
304 else if (ab
== AUTO_BOOLEAN_FALSE
)
311 if ((* (int *) var
) == INT_MAX
)
315 return PyLong_FromLong (* (int *) var
);
319 unsigned int val
= * (unsigned int *) var
;
323 return PyLong_FromUnsignedLong (val
);
327 return PyErr_Format (PyExc_RuntimeError
,
328 _("Programmer error: unhandled type."));
331 /* A Python function which returns a gdb parameter's value as a Python
335 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
337 struct cmd_list_element
*alias
, *prefix
, *cmd
;
341 volatile struct gdb_exception except
;
343 if (! PyArg_ParseTuple (args
, "s", &arg
))
346 newarg
= concat ("show ", arg
, (char *) NULL
);
348 TRY_CATCH (except
, RETURN_MASK_ALL
)
350 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
353 GDB_PY_HANDLE_EXCEPTION (except
);
355 return PyErr_Format (PyExc_RuntimeError
,
356 _("Could not find parameter `%s'."), arg
);
359 return PyErr_Format (PyExc_RuntimeError
,
360 _("`%s' is not a parameter."), arg
);
361 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
364 /* Wrapper for target_charset. */
367 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
369 const char *cset
= target_charset (python_gdbarch
);
371 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
374 /* Wrapper for target_wide_charset. */
377 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
379 const char *cset
= target_wide_charset (python_gdbarch
);
381 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
384 /* A Python function which evaluates a string using the gdb CLI. */
387 execute_gdb_command (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
390 PyObject
*from_tty_obj
= NULL
, *to_string_obj
= NULL
;
391 int from_tty
, to_string
;
392 volatile struct gdb_exception except
;
393 static char *keywords
[] = {"command", "from_tty", "to_string", NULL
};
396 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|O!O!", keywords
, &arg
,
397 &PyBool_Type
, &from_tty_obj
,
398 &PyBool_Type
, &to_string_obj
))
404 int cmp
= PyObject_IsTrue (from_tty_obj
);
413 int cmp
= PyObject_IsTrue (to_string_obj
);
419 TRY_CATCH (except
, RETURN_MASK_ALL
)
421 /* Copy the argument text in case the command modifies it. */
422 char *copy
= xstrdup (arg
);
423 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
425 make_cleanup_restore_integer (&interpreter_async
);
426 interpreter_async
= 0;
428 prevent_dont_repeat ();
430 result
= execute_command_to_string (copy
, from_tty
);
434 execute_command (copy
, from_tty
);
437 do_cleanups (cleanup
);
439 GDB_PY_HANDLE_EXCEPTION (except
);
441 /* Do any commands attached to breakpoint we stopped at. */
442 bpstat_do_actions ();
446 PyObject
*r
= PyString_FromString (result
);
453 /* Implementation of gdb.solib_name (Long) -> String.
454 Returns the name of the shared library holding a given address, or None. */
457 gdbpy_solib_name (PyObject
*self
, PyObject
*args
)
463 if (!PyArg_ParseTuple (args
, GDB_PY_LL_ARG
, &pc
))
466 soname
= solib_name_from_address (current_program_space
, pc
);
468 str_obj
= PyString_Decode (soname
, strlen (soname
), host_charset (), NULL
);
478 /* A Python function which is a wrapper for decode_line_1. */
481 gdbpy_decode_line (PyObject
*self
, PyObject
*args
)
483 struct symtabs_and_lines sals
= { NULL
, 0 }; /* Initialize to
485 struct symtab_and_line sal
;
486 const char *arg
= NULL
;
488 struct cleanup
*cleanups
;
489 PyObject
*result
= NULL
;
490 PyObject
*return_result
= NULL
;
491 PyObject
*unparsed
= NULL
;
492 volatile struct gdb_exception except
;
494 if (! PyArg_ParseTuple (args
, "|s", &arg
))
497 cleanups
= ensure_python_env (get_current_arch (), current_language
);
499 TRY_CATCH (except
, RETURN_MASK_ALL
)
503 copy
= xstrdup (arg
);
504 make_cleanup (xfree
, copy
);
505 sals
= decode_line_1 (©
, 0, 0, 0, 0);
506 make_cleanup (xfree
, sals
.sals
);
510 set_default_source_symtab_and_line ();
511 sal
= get_current_source_symtab_and_line ();
516 if (except
.reason
< 0)
518 do_cleanups (cleanups
);
519 /* We know this will always throw. */
520 GDB_PY_HANDLE_EXCEPTION (except
);
527 result
= PyTuple_New (sals
.nelts
);
530 for (i
= 0; i
< sals
.nelts
; ++i
)
535 obj
= symtab_and_line_to_sal_object (sals
.sals
[i
]);
542 PyTuple_SetItem (result
, i
, obj
);
551 return_result
= PyTuple_New (2);
558 if (copy
&& strlen (copy
) > 0)
559 unparsed
= PyString_FromString (copy
);
566 PyTuple_SetItem (return_result
, 0, unparsed
);
567 PyTuple_SetItem (return_result
, 1, result
);
569 do_cleanups (cleanups
);
571 return return_result
;
574 do_cleanups (cleanups
);
578 /* Parse a string and evaluate it as an expression. */
580 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
582 const char *expr_str
;
583 struct value
*result
= NULL
;
584 volatile struct gdb_exception except
;
586 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
589 TRY_CATCH (except
, RETURN_MASK_ALL
)
591 char *copy
= xstrdup (expr_str
);
592 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
594 result
= parse_and_eval (copy
);
595 do_cleanups (cleanup
);
597 GDB_PY_HANDLE_EXCEPTION (except
);
599 return value_to_value_object (result
);
602 /* Read a file as Python code. STREAM is the input file; FILE is the
604 STREAM is not closed, that is the caller's responsibility. */
607 source_python_script (FILE *stream
, const char *file
)
609 struct cleanup
*cleanup
;
611 cleanup
= ensure_python_env (get_current_arch (), current_language
);
613 /* Note: If an exception occurs python will print the traceback and
614 clear the error indicator. */
615 python_run_simple_file (file
);
617 do_cleanups (cleanup
);
622 /* Posting and handling events. */
624 /* A single event. */
627 /* The Python event. This is just a callable object. */
629 /* The next event. */
630 struct gdbpy_event
*next
;
633 /* All pending events. */
634 static struct gdbpy_event
*gdbpy_event_list
;
635 /* The final link of the event list. */
636 static struct gdbpy_event
**gdbpy_event_list_end
;
638 /* We use a file handler, and not an async handler, so that we can
639 wake up the main thread even when it is blocked in poll(). */
640 static struct serial
*gdbpy_event_fds
[2];
642 /* The file handler callback. This reads from the internal pipe, and
643 then processes the Python event queue. This will always be run in
644 the main gdb thread. */
647 gdbpy_run_events (struct serial
*scb
, void *context
)
649 struct cleanup
*cleanup
;
652 cleanup
= ensure_python_env (get_current_arch (), current_language
);
654 /* Flush the fd. Do this before flushing the events list, so that
655 any new event post afterwards is sure to re-awake the event
657 while (serial_readchar (gdbpy_event_fds
[0], 0) >= 0)
660 while (gdbpy_event_list
)
662 /* Dispatching the event might push a new element onto the event
663 loop, so we update here "atomically enough". */
664 struct gdbpy_event
*item
= gdbpy_event_list
;
665 gdbpy_event_list
= gdbpy_event_list
->next
;
666 if (gdbpy_event_list
== NULL
)
667 gdbpy_event_list_end
= &gdbpy_event_list
;
670 if (PyObject_CallObject (item
->event
, NULL
) == NULL
)
673 Py_DECREF (item
->event
);
677 do_cleanups (cleanup
);
680 /* Submit an event to the gdb thread. */
682 gdbpy_post_event (PyObject
*self
, PyObject
*args
)
684 struct gdbpy_event
*event
;
688 if (!PyArg_ParseTuple (args
, "O", &func
))
691 if (!PyCallable_Check (func
))
693 PyErr_SetString (PyExc_RuntimeError
,
694 _("Posted event is not callable"));
700 /* From here until the end of the function, we have the GIL, so we
701 can operate on our global data structures without worrying. */
702 wakeup
= gdbpy_event_list
== NULL
;
704 event
= XNEW (struct gdbpy_event
);
707 *gdbpy_event_list_end
= event
;
708 gdbpy_event_list_end
= &event
->next
;
710 /* Wake up gdb when needed. */
713 char c
= 'q'; /* Anything. */
715 if (serial_write (gdbpy_event_fds
[1], &c
, 1))
716 return PyErr_SetFromErrno (PyExc_IOError
);
722 /* Initialize the Python event handler. */
724 gdbpy_initialize_events (void)
726 if (serial_pipe (gdbpy_event_fds
) == 0)
728 gdbpy_event_list_end
= &gdbpy_event_list
;
729 serial_async (gdbpy_event_fds
[0], gdbpy_run_events
, NULL
);
736 before_prompt_hook (const char *current_gdb_prompt
)
738 struct cleanup
*cleanup
;
741 cleanup
= ensure_python_env (get_current_arch (), current_language
);
743 if (PyObject_HasAttrString (gdb_module
, "prompt_hook"))
747 hook
= PyObject_GetAttrString (gdb_module
, "prompt_hook");
751 if (PyCallable_Check (hook
))
754 PyObject
*current_prompt
;
756 current_prompt
= PyString_FromString (current_gdb_prompt
);
757 if (current_prompt
== NULL
)
760 result
= PyObject_CallFunctionObjArgs (hook
, current_prompt
, NULL
);
762 Py_DECREF (current_prompt
);
767 make_cleanup_py_decref (result
);
769 /* Return type should be None, or a String. If it is None,
770 fall through, we will not set a prompt. If it is a
771 string, set PROMPT. Anything else, set an exception. */
772 if (result
!= Py_None
&& ! PyString_Check (result
))
774 PyErr_Format (PyExc_RuntimeError
,
775 _("Return from prompt_hook must " \
776 "be either a Python string, or None"));
780 if (result
!= Py_None
)
782 prompt
= python_string_to_host_string (result
);
787 make_cleanup (xfree
, prompt
);
792 /* If a prompt has been set, PROMPT will not be NULL. If it is
793 NULL, do not set the prompt. */
797 do_cleanups (cleanup
);
801 gdbpy_print_stack ();
802 do_cleanups (cleanup
);
810 /* A python function to write a single string using gdb's filtered
811 output stream . The optional keyword STREAM can be used to write
812 to a particular stream. The default stream is to gdb_stdout. */
815 gdbpy_write (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
818 static char *keywords
[] = {"text", "stream", NULL
};
821 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "s|i", keywords
, &arg
,
829 fprintf_filtered (gdb_stderr
, "%s", arg
);
834 fprintf_filtered (gdb_stdlog
, "%s", arg
);
838 fprintf_filtered (gdb_stdout
, "%s", arg
);
844 /* A python function to flush a gdb stream. The optional keyword
845 STREAM can be used to flush a particular stream. The default stream
849 gdbpy_flush (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
851 static char *keywords
[] = {"stream", NULL
};
854 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "|i", keywords
,
862 gdb_flush (gdb_stderr
);
867 gdb_flush (gdb_stdlog
);
871 gdb_flush (gdb_stdout
);
877 /* Print a python exception trace, or print nothing and clear the
878 python exception, depending on gdbpy_should_print_stack. Only call
879 this if a python exception is set. */
881 gdbpy_print_stack (void)
883 if (gdbpy_should_print_stack
)
886 /* PyErr_Print doesn't necessarily end output with a newline.
887 This works because Python's stdout/stderr is fed through
897 /* Return the current Progspace.
898 There always is one. */
901 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
905 result
= pspace_to_pspace_object (current_program_space
);
911 /* Return a sequence holding all the Progspaces. */
914 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
916 struct program_space
*ps
;
919 list
= PyList_New (0);
925 PyObject
*item
= pspace_to_pspace_object (ps
);
927 if (!item
|| PyList_Append (list
, item
) == -1)
939 /* The "current" objfile. This is set when gdb detects that a new
940 objfile has been loaded. It is only set for the duration of a call to
941 source_python_script_for_objfile; it is NULL at other times. */
942 static struct objfile
*gdbpy_current_objfile
;
944 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
946 STREAM is left open, it is up to the caller to close it.
947 If an exception occurs python will print the traceback and
948 clear the error indicator. */
951 source_python_script_for_objfile (struct objfile
*objfile
,
952 FILE *stream
, const char *file
)
954 struct cleanup
*cleanups
;
956 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
957 gdbpy_current_objfile
= objfile
;
959 python_run_simple_file (file
);
961 do_cleanups (cleanups
);
962 gdbpy_current_objfile
= NULL
;
965 /* Return the current Objfile, or None if there isn't one. */
968 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
972 if (! gdbpy_current_objfile
)
975 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
981 /* Return a sequence holding all the Objfiles. */
984 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
986 struct objfile
*objf
;
989 list
= PyList_New (0);
995 PyObject
*item
= objfile_to_objfile_object (objf
);
997 if (!item
|| PyList_Append (list
, item
) == -1)
1007 #else /* HAVE_PYTHON */
1009 /* Dummy implementation of the gdb "python" command. */
1012 python_command (char *arg
, int from_tty
)
1014 while (arg
&& *arg
&& isspace (*arg
))
1017 error (_("Python scripting is not supported in this copy of GDB."));
1020 struct command_line
*l
= get_command_line (python_control
, "");
1021 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
1023 execute_control_command_untraced (l
);
1024 do_cleanups (cleanups
);
1029 eval_python_from_control_command (struct command_line
*cmd
)
1031 error (_("Python scripting is not supported in this copy of GDB."));
1035 source_python_script (FILE *stream
, const char *file
)
1037 throw_error (UNSUPPORTED_ERROR
,
1038 _("Python scripting is not supported in this copy of GDB."));
1042 gdbpy_should_stop (struct breakpoint_object
*bp_obj
)
1044 internal_error (__FILE__
, __LINE__
,
1045 _("gdbpy_should_stop called when Python scripting is " \
1050 gdbpy_breakpoint_has_py_cond (struct breakpoint_object
*bp_obj
)
1052 internal_error (__FILE__
, __LINE__
,
1053 _("gdbpy_breakpoint_has_py_cond called when Python " \
1054 "scripting is not supported."));
1057 #endif /* HAVE_PYTHON */
1061 /* Lists for 'maint set python' commands. */
1063 static struct cmd_list_element
*maint_set_python_list
;
1064 static struct cmd_list_element
*maint_show_python_list
;
1066 /* Lists for 'set python' commands. */
1068 static struct cmd_list_element
*user_set_python_list
;
1069 static struct cmd_list_element
*user_show_python_list
;
1071 /* Function for use by 'maint set python' prefix command. */
1074 maint_set_python (char *args
, int from_tty
)
1076 help_list (maint_set_python_list
, "maintenance set python ",
1077 class_deprecated
, gdb_stdout
);
1080 /* Function for use by 'maint show python' prefix command. */
1083 maint_show_python (char *args
, int from_tty
)
1085 cmd_show_list (maint_show_python_list
, from_tty
, "");
1088 /* Function for use by 'set python' prefix command. */
1091 user_set_python (char *args
, int from_tty
)
1093 help_list (user_set_python_list
, "set python ", all_commands
,
1097 /* Function for use by 'show python' prefix command. */
1100 user_show_python (char *args
, int from_tty
)
1102 cmd_show_list (user_show_python_list
, from_tty
, "");
1105 /* Initialize the Python code. */
1107 /* Provide a prototype to silence -Wmissing-prototypes. */
1108 extern initialize_file_ftype _initialize_python
;
1111 _initialize_python (void)
1114 struct cmd_list_element
*cmd
;
1116 add_com ("python", class_obscure
, python_command
,
1119 Evaluate a Python command.\n\
1121 The command can be given as an argument, for instance:\n\
1125 If no argument is given, the following lines are read and used\n\
1126 as the Python commands. Type a line containing \"end\" to indicate\n\
1127 the end of the command.")
1128 #else /* HAVE_PYTHON */
1130 Evaluate a Python command.\n\
1132 Python scripting is not supported in this copy of GDB.\n\
1133 This command is only a placeholder.")
1134 #endif /* HAVE_PYTHON */
1137 add_prefix_cmd ("python", no_class
, maint_show_python
,
1138 _("Prefix command for python maintenance settings."),
1139 &maint_show_python_list
, "maintenance show python ", 0,
1140 &maintenance_show_cmdlist
);
1141 add_prefix_cmd ("python", no_class
, maint_set_python
,
1142 _("Prefix command for python maintenance settings."),
1143 &maint_set_python_list
, "maintenance set python ", 0,
1144 &maintenance_set_cmdlist
);
1146 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
1147 &gdbpy_should_print_stack
, _("\
1148 Enable or disable printing of Python stack dump on error."), _("\
1149 Show whether Python stack will be printed on error."), _("\
1150 Enables or disables printing of Python stack traces."),
1152 &maint_set_python_list
,
1153 &maint_show_python_list
);
1155 /* Deprecate maint set/show python print-stack in favour of
1156 non-maintenance alternatives. */
1157 cmd_name
= "print-stack";
1158 cmd
= lookup_cmd (&cmd_name
, maint_set_python_list
, "", -1, 0);
1159 deprecate_cmd (cmd
, "set python print-stack");
1160 cmd_name
= "print-stack"; /* Reset name. */
1161 cmd
= lookup_cmd (&cmd_name
, maint_show_python_list
, "", -1, 0);
1162 deprecate_cmd (cmd
, "show python print-stack");
1164 /* Add set/show python print-stack. */
1165 add_prefix_cmd ("python", no_class
, user_show_python
,
1166 _("Prefix command for python preference settings."),
1167 &user_show_python_list
, "show python ", 0,
1170 add_prefix_cmd ("python", no_class
, user_set_python
,
1171 _("Prefix command for python preference settings."),
1172 &user_set_python_list
, "set python ", 0,
1175 add_setshow_boolean_cmd ("print-stack", no_class
,
1176 &gdbpy_should_print_stack
, _("\
1177 Enable or disable printing of Python stack dump on error."), _("\
1178 Show whether Python stack will be printed on error."), _("\
1179 Enables or disables printing of Python stack traces."),
1181 &user_set_python_list
,
1182 &user_show_python_list
);
1185 #ifdef WITH_PYTHON_PATH
1186 /* Work around problem where python gets confused about where it is,
1187 and then can't find its libraries, etc.
1188 NOTE: Python assumes the following layout:
1190 /foo/lib/pythonX.Y/...
1191 This must be done before calling Py_Initialize. */
1192 Py_SetProgramName (concat (ldirname (python_libdir
), SLASH_STRING
, "bin",
1193 SLASH_STRING
, "python", NULL
));
1197 PyEval_InitThreads ();
1199 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
1201 /* The casts to (char*) are for python 2.4. */
1202 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
1203 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
1204 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG",
1205 (char*) target_name
);
1207 /* Add stream constants. */
1208 PyModule_AddIntConstant (gdb_module
, "STDOUT", 0);
1209 PyModule_AddIntConstant (gdb_module
, "STDERR", 1);
1210 PyModule_AddIntConstant (gdb_module
, "STDLOG", 2);
1212 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1213 script below is run (depending on order of _initialize_* functions).
1214 Define the initial value of gdb.PYTHONDIR here. */
1216 char *gdb_pythondir
;
1218 gdb_pythondir
= concat (gdb_datadir
, SLASH_STRING
, "python", NULL
);
1219 PyModule_AddStringConstant (gdb_module
, "PYTHONDIR", gdb_pythondir
);
1220 xfree (gdb_pythondir
);
1223 gdbpy_gdb_error
= PyErr_NewException ("gdb.error", PyExc_RuntimeError
, NULL
);
1224 PyModule_AddObject (gdb_module
, "error", gdbpy_gdb_error
);
1226 gdbpy_gdb_memory_error
= PyErr_NewException ("gdb.MemoryError",
1227 gdbpy_gdb_error
, NULL
);
1228 PyModule_AddObject (gdb_module
, "MemoryError", gdbpy_gdb_memory_error
);
1230 gdbpy_gdberror_exc
= PyErr_NewException ("gdb.GdbError", NULL
, NULL
);
1231 PyModule_AddObject (gdb_module
, "GdbError", gdbpy_gdberror_exc
);
1233 gdbpy_initialize_auto_load ();
1234 gdbpy_initialize_values ();
1235 gdbpy_initialize_frames ();
1236 gdbpy_initialize_commands ();
1237 gdbpy_initialize_symbols ();
1238 gdbpy_initialize_symtabs ();
1239 gdbpy_initialize_blocks ();
1240 gdbpy_initialize_functions ();
1241 gdbpy_initialize_parameters ();
1242 gdbpy_initialize_types ();
1243 gdbpy_initialize_pspace ();
1244 gdbpy_initialize_objfile ();
1245 gdbpy_initialize_breakpoints ();
1246 gdbpy_initialize_lazy_string ();
1247 gdbpy_initialize_thread ();
1248 gdbpy_initialize_inferior ();
1249 gdbpy_initialize_events ();
1251 gdbpy_initialize_eventregistry ();
1252 gdbpy_initialize_py_events ();
1253 gdbpy_initialize_event ();
1254 gdbpy_initialize_stop_event ();
1255 gdbpy_initialize_signal_event ();
1256 gdbpy_initialize_breakpoint_event ();
1257 gdbpy_initialize_continue_event ();
1258 gdbpy_initialize_exited_event ();
1259 gdbpy_initialize_thread_event ();
1260 gdbpy_initialize_new_objfile_event () ;
1262 observer_attach_before_prompt (before_prompt_hook
);
1264 PyRun_SimpleString ("import gdb");
1265 PyRun_SimpleString ("gdb.pretty_printers = []");
1267 gdbpy_to_string_cst
= PyString_FromString ("to_string");
1268 gdbpy_children_cst
= PyString_FromString ("children");
1269 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
1270 gdbpy_doc_cst
= PyString_FromString ("__doc__");
1271 gdbpy_enabled_cst
= PyString_FromString ("enabled");
1272 gdbpy_value_cst
= PyString_FromString ("value");
1274 /* Release the GIL while gdb runs. */
1275 PyThreadState_Swap (NULL
);
1276 PyEval_ReleaseLock ();
1278 #endif /* HAVE_PYTHON */
1283 /* Perform the remaining python initializations.
1284 These must be done after GDB is at least mostly initialized.
1285 E.g., The "info pretty-printer" command needs the "info" prefix
1286 command installed. */
1289 finish_python_initialization (void)
1291 struct cleanup
*cleanup
;
1293 cleanup
= ensure_python_env (get_current_arch (), current_language
);
1295 PyRun_SimpleString ("\
1299 class GdbOutputFile:\n\
1304 def isatty(self):\n\
1307 def write(self, s):\n\
1308 gdb.write(s, stream=gdb.STDOUT)\n \
1310 def writelines(self, iterable):\n\
1311 for line in iterable:\n\
1317 sys.stdout = GdbOutputFile()\n\
1319 class GdbOutputErrorFile:\n\
1324 def isatty(self):\n\
1327 def write(self, s):\n\
1328 gdb.write(s, stream=gdb.STDERR)\n \
1330 def writelines(self, iterable):\n\
1331 for line in iterable:\n\
1332 self.write(line)\n \
1337 sys.stderr = GdbOutputErrorFile()\n\
1339 # Ideally this would live in the gdb module, but it's intentionally written\n\
1340 # in python, and we need this to bootstrap the gdb module.\n\
1342 def GdbSetPythonDirectory (dir):\n\
1343 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1344 old_dir = gdb.PYTHONDIR\n\
1345 gdb.PYTHONDIR = dir\n\
1346 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1347 # that directory name at the start of sys.path to allow the Python\n\
1348 # interpreter to find them.\n\
1349 if old_dir in sys.path:\n\
1350 sys.path.remove (old_dir)\n\
1351 sys.path.insert (0, gdb.PYTHONDIR)\n\
1353 # Tell python where to find submodules of gdb.\n\
1354 gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1356 # The gdb module is implemented in C rather than in Python. As a result,\n\
1357 # the associated __init.py__ script is not not executed by default when\n\
1358 # the gdb module gets imported. Execute that script manually if it\n\
1360 ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1361 if os.path.exists (ipy):\n\
1364 # Install the default gdb.PYTHONDIR.\n\
1365 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1366 # Default prompt hook does nothing.\n\
1367 prompt_hook = None\n\
1370 do_cleanups (cleanup
);
1373 #endif /* HAVE_PYTHON */
1379 static PyMethodDef GdbMethods
[] =
1381 { "history", gdbpy_history
, METH_VARARGS
,
1382 "Get a value from history" },
1383 { "execute", (PyCFunction
) execute_gdb_command
, METH_VARARGS
| METH_KEYWORDS
,
1384 "Execute a gdb command" },
1385 { "parameter", gdbpy_parameter
, METH_VARARGS
,
1386 "Return a gdb parameter's value" },
1388 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
1389 "Return a tuple of all breakpoint objects" },
1391 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
1392 "Find the default visualizer for a Value." },
1394 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
1395 "Return the current Progspace." },
1396 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
1397 "Return a sequence of all progspaces." },
1399 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
1400 "Return the current Objfile being loaded, or None." },
1401 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
1402 "Return a sequence of all loaded objfiles." },
1404 { "newest_frame", gdbpy_newest_frame
, METH_NOARGS
,
1405 "newest_frame () -> gdb.Frame.\n\
1406 Return the newest frame object." },
1407 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
1408 "selected_frame () -> gdb.Frame.\n\
1409 Return the selected frame object." },
1410 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
1411 "stop_reason_string (Integer) -> String.\n\
1412 Return a string explaining unwind stop reason." },
1414 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
1415 METH_VARARGS
| METH_KEYWORDS
,
1416 "lookup_type (name [, block]) -> type\n\
1417 Return a Type corresponding to the given name." },
1418 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
1419 METH_VARARGS
| METH_KEYWORDS
,
1420 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1421 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1422 a boolean indicating if name is a field of the current implied argument\n\
1423 `this' (when the current language is object-oriented)." },
1424 { "lookup_global_symbol", (PyCFunction
) gdbpy_lookup_global_symbol
,
1425 METH_VARARGS
| METH_KEYWORDS
,
1426 "lookup_global_symbol (name [, domain]) -> symbol\n\
1427 Return the symbol corresponding to the given name (or None)." },
1428 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
1429 "Return the block containing the given pc value, or None." },
1430 { "solib_name", gdbpy_solib_name
, METH_VARARGS
,
1431 "solib_name (Long) -> String.\n\
1432 Return the name of the shared library holding a given address, or None." },
1433 { "decode_line", gdbpy_decode_line
, METH_VARARGS
,
1434 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1435 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1436 The first element contains any unparsed portion of the String parameter\n\
1437 (or None if the string was fully parsed). The second element contains\n\
1438 a tuple that contains all the locations that match, represented as\n\
1439 gdb.Symtab_and_line objects (or None)."},
1440 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
1441 "parse_and_eval (String) -> Value.\n\
1442 Parse String as an expression, evaluate it, and return the result as a Value."
1445 { "post_event", gdbpy_post_event
, METH_VARARGS
,
1446 "Post an event into gdb's event loop." },
1448 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
1449 "target_charset () -> string.\n\
1450 Return the name of the current target charset." },
1451 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
1452 "target_wide_charset () -> string.\n\
1453 Return the name of the current target wide charset." },
1455 { "string_to_argv", gdbpy_string_to_argv
, METH_VARARGS
,
1456 "string_to_argv (String) -> Array.\n\
1457 Parse String and return an argv-like array.\n\
1458 Arguments are separate by spaces and may be quoted."
1460 { "write", (PyCFunction
)gdbpy_write
, METH_VARARGS
| METH_KEYWORDS
,
1461 "Write a string using gdb's filtered stream." },
1462 { "flush", (PyCFunction
)gdbpy_flush
, METH_VARARGS
| METH_KEYWORDS
,
1463 "Flush gdb's filtered stdout stream." },
1464 { "selected_thread", gdbpy_selected_thread
, METH_NOARGS
,
1465 "selected_thread () -> gdb.InferiorThread.\n\
1466 Return the selected thread object." },
1467 { "selected_inferior", gdbpy_selected_inferior
, METH_NOARGS
,
1468 "selected_inferior () -> gdb.Inferior.\n\
1469 Return the selected inferior object." },
1470 { "inferiors", gdbpy_inferiors
, METH_NOARGS
,
1471 "inferiors () -> (gdb.Inferior, ...).\n\
1472 Return a tuple containing all inferiors." },
1473 {NULL
, NULL
, 0, NULL
}
1476 #endif /* HAVE_PYTHON */