1 /* General python/gdb code
3 Copyright (C) 2008, 2009, 2010 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"
34 /* True if we should print the stack when catching a Python error,
36 static int gdbpy_should_print_stack
= 1;
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
45 #include "python-internal.h"
48 #include "gdbthread.h"
50 static PyMethodDef GdbMethods
[];
54 /* Some string constants we may wish to use. */
55 PyObject
*gdbpy_to_string_cst
;
56 PyObject
*gdbpy_children_cst
;
57 PyObject
*gdbpy_display_hint_cst
;
58 PyObject
*gdbpy_doc_cst
;
61 /* Architecture and language to be used in callbacks from
62 the Python interpreter. */
63 struct gdbarch
*python_gdbarch
;
64 const struct language_defn
*python_language
;
66 /* Restore global language and architecture and Python GIL state
67 when leaving the Python interpreter. */
71 PyGILState_STATE state
;
72 struct gdbarch
*gdbarch
;
73 const struct language_defn
*language
;
77 restore_python_env (void *p
)
79 struct python_env
*env
= (struct python_env
*)p
;
81 PyGILState_Release (env
->state
);
82 python_gdbarch
= env
->gdbarch
;
83 python_language
= env
->language
;
87 /* Called before entering the Python interpreter to install the
88 current language and architecture to be used for Python values. */
91 ensure_python_env (struct gdbarch
*gdbarch
,
92 const struct language_defn
*language
)
94 struct python_env
*env
= xmalloc (sizeof *env
);
96 env
->state
= PyGILState_Ensure ();
97 env
->gdbarch
= python_gdbarch
;
98 env
->language
= python_language
;
100 python_gdbarch
= gdbarch
;
101 python_language
= language
;
103 return make_cleanup (restore_python_env
, env
);
107 /* Given a command_line, return a command string suitable for passing
108 to Python. Lines in the string are separated by newlines. The
109 return value is allocated using xmalloc and the caller is
110 responsible for freeing it. */
113 compute_python_string (struct command_line
*l
)
115 struct command_line
*iter
;
120 for (iter
= l
; iter
; iter
= iter
->next
)
121 size
+= strlen (iter
->line
) + 1;
123 script
= xmalloc (size
+ 1);
125 for (iter
= l
; iter
; iter
= iter
->next
)
127 int len
= strlen (iter
->line
);
129 strcpy (&script
[here
], iter
->line
);
131 script
[here
++] = '\n';
137 /* Take a command line structure representing a 'python' command, and
138 evaluate its body using the Python interpreter. */
141 eval_python_from_control_command (struct command_line
*cmd
)
145 struct cleanup
*cleanup
;
147 if (cmd
->body_count
!= 1)
148 error (_("Invalid \"python\" block structure."));
150 cleanup
= ensure_python_env (get_current_arch (), current_language
);
152 script
= compute_python_string (cmd
->body_list
[0]);
153 ret
= PyRun_SimpleString (script
);
157 gdbpy_print_stack ();
158 error (_("Error while executing Python code."));
161 do_cleanups (cleanup
);
164 /* Implementation of the gdb "python" command. */
167 python_command (char *arg
, int from_tty
)
169 struct cleanup
*cleanup
;
171 cleanup
= ensure_python_env (get_current_arch (), current_language
);
172 while (arg
&& *arg
&& isspace (*arg
))
176 if (PyRun_SimpleString (arg
))
178 gdbpy_print_stack ();
179 error (_("Error while executing Python code."));
184 struct command_line
*l
= get_command_line (python_control
, "");
186 make_cleanup_free_command_lines (&l
);
187 execute_control_command_untraced (l
);
190 do_cleanups (cleanup
);
195 /* Transform a gdb parameters's value into a Python value. May return
196 NULL (and set a Python exception) on error. Helper function for
199 gdbpy_parameter_value (enum var_types type
, void *var
)
204 case var_string_noescape
:
205 case var_optional_filename
:
209 char *str
= * (char **) var
;
213 return PyString_Decode (str
, strlen (str
), host_charset (), NULL
);
224 case var_auto_boolean
:
226 enum auto_boolean ab
= * (enum auto_boolean
*) var
;
228 if (ab
== AUTO_BOOLEAN_TRUE
)
230 else if (ab
== AUTO_BOOLEAN_FALSE
)
237 if ((* (int *) var
) == INT_MAX
)
241 return PyLong_FromLong (* (int *) var
);
245 unsigned int val
= * (unsigned int *) var
;
249 return PyLong_FromUnsignedLong (val
);
253 return PyErr_Format (PyExc_RuntimeError
,
254 _("Programmer error: unhandled type."));
257 /* A Python function which returns a gdb parameter's value as a Python
261 gdbpy_parameter (PyObject
*self
, PyObject
*args
)
263 struct cmd_list_element
*alias
, *prefix
, *cmd
;
266 volatile struct gdb_exception except
;
268 if (! PyArg_ParseTuple (args
, "s", &arg
))
271 newarg
= concat ("show ", arg
, (char *) NULL
);
273 TRY_CATCH (except
, RETURN_MASK_ALL
)
275 found
= lookup_cmd_composition (newarg
, &alias
, &prefix
, &cmd
);
278 GDB_PY_HANDLE_EXCEPTION (except
);
280 return PyErr_Format (PyExc_RuntimeError
,
281 _("Could not find parameter `%s'."), arg
);
284 return PyErr_Format (PyExc_RuntimeError
,
285 _("`%s' is not a parameter."), arg
);
286 return gdbpy_parameter_value (cmd
->var_type
, cmd
->var
);
289 /* Wrapper for target_charset. */
292 gdbpy_target_charset (PyObject
*self
, PyObject
*args
)
294 const char *cset
= target_charset (python_gdbarch
);
296 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
299 /* Wrapper for target_wide_charset. */
302 gdbpy_target_wide_charset (PyObject
*self
, PyObject
*args
)
304 const char *cset
= target_wide_charset (python_gdbarch
);
306 return PyUnicode_Decode (cset
, strlen (cset
), host_charset (), NULL
);
309 /* A Python function which evaluates a string using the gdb CLI. */
312 execute_gdb_command (PyObject
*self
, PyObject
*args
)
315 PyObject
*from_tty_obj
= NULL
;
318 volatile struct gdb_exception except
;
320 if (! PyArg_ParseTuple (args
, "s|O!", &arg
, &PyBool_Type
, &from_tty_obj
))
326 cmp
= PyObject_IsTrue (from_tty_obj
);
332 TRY_CATCH (except
, RETURN_MASK_ALL
)
334 /* Copy the argument text in case the command modifies it. */
335 char *copy
= xstrdup (arg
);
336 struct cleanup
*cleanup
= make_cleanup (xfree
, copy
);
338 execute_command (copy
, from_tty
);
339 do_cleanups (cleanup
);
341 GDB_PY_HANDLE_EXCEPTION (except
);
343 /* Do any commands attached to breakpoint we stopped at. */
344 bpstat_do_actions ();
349 /* Parse a string and evaluate it as an expression. */
351 gdbpy_parse_and_eval (PyObject
*self
, PyObject
*args
)
354 struct value
*result
= NULL
;
355 volatile struct gdb_exception except
;
357 if (!PyArg_ParseTuple (args
, "s", &expr_str
))
360 TRY_CATCH (except
, RETURN_MASK_ALL
)
362 result
= parse_and_eval (expr_str
);
364 GDB_PY_HANDLE_EXCEPTION (except
);
366 return value_to_value_object (result
);
369 /* Read a file as Python code. STREAM is the input file; FILE is the
371 STREAM is not closed, that is the caller's responsibility. */
374 source_python_script (FILE *stream
, const char *file
)
376 struct cleanup
*cleanup
;
378 cleanup
= ensure_python_env (get_current_arch (), current_language
);
380 PyRun_SimpleFile (stream
, file
);
382 do_cleanups (cleanup
);
389 /* A python function to write a single string using gdb's filtered
392 gdbpy_write (PyObject
*self
, PyObject
*args
)
396 if (! PyArg_ParseTuple (args
, "s", &arg
))
398 printf_filtered ("%s", arg
);
402 /* A python function to flush gdb's filtered output stream. */
404 gdbpy_flush (PyObject
*self
, PyObject
*args
)
406 gdb_flush (gdb_stdout
);
410 /* Print a python exception trace, or print nothing and clear the
411 python exception, depending on gdbpy_should_print_stack. Only call
412 this if a python exception is set. */
414 gdbpy_print_stack (void)
416 if (gdbpy_should_print_stack
)
424 /* Return the current Progspace.
425 There always is one. */
428 gdbpy_get_current_progspace (PyObject
*unused1
, PyObject
*unused2
)
432 result
= pspace_to_pspace_object (current_program_space
);
438 /* Return a sequence holding all the Progspaces. */
441 gdbpy_progspaces (PyObject
*unused1
, PyObject
*unused2
)
443 struct program_space
*ps
;
446 list
= PyList_New (0);
452 PyObject
*item
= pspace_to_pspace_object (ps
);
454 if (!item
|| PyList_Append (list
, item
) == -1)
466 /* The "current" objfile. This is set when gdb detects that a new
467 objfile has been loaded. It is only set for the duration of a call to
468 source_python_script_for_objfile; it is NULL at other times. */
469 static struct objfile
*gdbpy_current_objfile
;
471 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
475 source_python_script_for_objfile (struct objfile
*objfile
,
476 FILE *stream
, const char *file
)
478 struct cleanup
*cleanups
;
480 cleanups
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
481 gdbpy_current_objfile
= objfile
;
483 /* We don't want to throw an exception here -- but the user
484 would like to know that something went wrong. */
485 if (PyRun_SimpleFile (stream
, file
))
486 gdbpy_print_stack ();
488 do_cleanups (cleanups
);
489 gdbpy_current_objfile
= NULL
;
492 /* Return the current Objfile, or None if there isn't one. */
495 gdbpy_get_current_objfile (PyObject
*unused1
, PyObject
*unused2
)
499 if (! gdbpy_current_objfile
)
502 result
= objfile_to_objfile_object (gdbpy_current_objfile
);
508 /* Return a sequence holding all the Objfiles. */
511 gdbpy_objfiles (PyObject
*unused1
, PyObject
*unused2
)
513 struct objfile
*objf
;
516 list
= PyList_New (0);
522 PyObject
*item
= objfile_to_objfile_object (objf
);
524 if (!item
|| PyList_Append (list
, item
) == -1)
534 #else /* HAVE_PYTHON */
536 /* Dummy implementation of the gdb "python" command. */
539 python_command (char *arg
, int from_tty
)
541 while (arg
&& *arg
&& isspace (*arg
))
544 error (_("Python scripting is not supported in this copy of GDB."));
547 struct command_line
*l
= get_command_line (python_control
, "");
548 struct cleanup
*cleanups
= make_cleanup_free_command_lines (&l
);
550 execute_control_command_untraced (l
);
551 do_cleanups (cleanups
);
556 eval_python_from_control_command (struct command_line
*cmd
)
558 error (_("Python scripting is not supported in this copy of GDB."));
562 source_python_script (FILE *stream
, const char *file
)
564 throw_error (UNSUPPORTED_ERROR
,
565 _("Python scripting is not supported in this copy of GDB."));
568 #endif /* HAVE_PYTHON */
572 /* Lists for 'maint set python' commands. */
574 struct cmd_list_element
*set_python_list
;
575 struct cmd_list_element
*show_python_list
;
577 /* Function for use by 'maint set python' prefix command. */
580 set_python (char *args
, int from_tty
)
582 help_list (set_python_list
, "maintenance set python ", -1, gdb_stdout
);
585 /* Function for use by 'maint show python' prefix command. */
588 show_python (char *args
, int from_tty
)
590 cmd_show_list (show_python_list
, from_tty
, "");
593 /* Initialize the Python code. */
595 /* Provide a prototype to silence -Wmissing-prototypes. */
596 extern initialize_file_ftype _initialize_python
;
599 _initialize_python (void)
601 add_com ("python", class_obscure
, python_command
,
604 Evaluate a Python command.\n\
606 The command can be given as an argument, for instance:\n\
610 If no argument is given, the following lines are read and used\n\
611 as the Python commands. Type a line containing \"end\" to indicate\n\
612 the end of the command.")
613 #else /* HAVE_PYTHON */
615 Evaluate a Python command.\n\
617 Python scripting is not supported in this copy of GDB.\n\
618 This command is only a placeholder.")
619 #endif /* HAVE_PYTHON */
622 add_prefix_cmd ("python", no_class
, show_python
,
623 _("Prefix command for python maintenance settings."),
624 &show_python_list
, "maintenance show python ", 0,
625 &maintenance_show_cmdlist
);
626 add_prefix_cmd ("python", no_class
, set_python
,
627 _("Prefix command for python maintenance settings."),
628 &set_python_list
, "maintenance set python ", 0,
629 &maintenance_set_cmdlist
);
631 add_setshow_boolean_cmd ("print-stack", class_maintenance
,
632 &gdbpy_should_print_stack
, _("\
633 Enable or disable printing of Python stack dump on error."), _("\
634 Show whether Python stack will be printed on error."), _("\
635 Enables or disables printing of Python stack traces."),
642 PyEval_InitThreads ();
644 gdb_module
= Py_InitModule ("gdb", GdbMethods
);
646 /* The casts to (char*) are for python 2.4. */
647 PyModule_AddStringConstant (gdb_module
, "VERSION", (char*) version
);
648 PyModule_AddStringConstant (gdb_module
, "HOST_CONFIG", (char*) host_name
);
649 PyModule_AddStringConstant (gdb_module
, "TARGET_CONFIG", (char*) target_name
);
651 gdbpy_initialize_auto_load ();
652 gdbpy_initialize_values ();
653 gdbpy_initialize_frames ();
654 gdbpy_initialize_commands ();
655 gdbpy_initialize_symbols ();
656 gdbpy_initialize_symtabs ();
657 gdbpy_initialize_blocks ();
658 gdbpy_initialize_functions ();
659 gdbpy_initialize_parameters ();
660 gdbpy_initialize_types ();
661 gdbpy_initialize_pspace ();
662 gdbpy_initialize_objfile ();
663 gdbpy_initialize_breakpoints ();
664 gdbpy_initialize_lazy_string ();
666 PyRun_SimpleString ("import gdb");
667 PyRun_SimpleString ("gdb.pretty_printers = []");
669 gdbpy_to_string_cst
= PyString_FromString ("to_string");
670 gdbpy_children_cst
= PyString_FromString ("children");
671 gdbpy_display_hint_cst
= PyString_FromString ("display_hint");
672 gdbpy_doc_cst
= PyString_FromString ("__doc__");
674 /* Create a couple objects which are used for Python's stdout and
676 PyRun_SimpleString ("\
678 class GdbOutputFile:\n\
686 def write(self, s):\n\
689 def writelines(self, iterable):\n\
690 for line in iterable:\n\
696 sys.stderr = GdbOutputFile()\n\
697 sys.stdout = GdbOutputFile()\n\
700 /* Release the GIL while gdb runs. */
701 PyThreadState_Swap (NULL
);
702 PyEval_ReleaseLock ();
704 #endif /* HAVE_PYTHON */
711 static PyMethodDef GdbMethods
[] =
713 { "history", gdbpy_history
, METH_VARARGS
,
714 "Get a value from history" },
715 { "execute", execute_gdb_command
, METH_VARARGS
,
716 "Execute a gdb command" },
717 { "parameter", gdbpy_parameter
, METH_VARARGS
,
718 "Return a gdb parameter's value" },
720 { "breakpoints", gdbpy_breakpoints
, METH_NOARGS
,
721 "Return a tuple of all breakpoint objects" },
723 { "default_visualizer", gdbpy_default_visualizer
, METH_VARARGS
,
724 "Find the default visualizer for a Value." },
726 { "current_progspace", gdbpy_get_current_progspace
, METH_NOARGS
,
727 "Return the current Progspace." },
728 { "progspaces", gdbpy_progspaces
, METH_NOARGS
,
729 "Return a sequence of all progspaces." },
731 { "current_objfile", gdbpy_get_current_objfile
, METH_NOARGS
,
732 "Return the current Objfile being loaded, or None." },
733 { "objfiles", gdbpy_objfiles
, METH_NOARGS
,
734 "Return a sequence of all loaded objfiles." },
736 { "selected_frame", gdbpy_selected_frame
, METH_NOARGS
,
737 "selected_frame () -> gdb.Frame.\n\
738 Return the selected frame object." },
739 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string
, METH_VARARGS
,
740 "stop_reason_string (Integer) -> String.\n\
741 Return a string explaining unwind stop reason." },
743 { "lookup_type", (PyCFunction
) gdbpy_lookup_type
,
744 METH_VARARGS
| METH_KEYWORDS
,
745 "lookup_type (name [, block]) -> type\n\
746 Return a Type corresponding to the given name." },
747 { "lookup_symbol", (PyCFunction
) gdbpy_lookup_symbol
,
748 METH_VARARGS
| METH_KEYWORDS
,
749 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
750 Return a tuple with the symbol corresponding to the given name (or None) and\n\
751 a boolean indicating if name is a field of the current implied argument\n\
752 `this' (when the current language is object-oriented)." },
753 { "block_for_pc", gdbpy_block_for_pc
, METH_VARARGS
,
754 "Return the block containing the given pc value, or None." },
755 { "parse_and_eval", gdbpy_parse_and_eval
, METH_VARARGS
,
756 "parse_and_eval (String) -> Value.\n\
757 Parse String as an expression, evaluate it, and return the result as a Value."
760 { "target_charset", gdbpy_target_charset
, METH_NOARGS
,
761 "target_charset () -> string.\n\
762 Return the name of the current target charset." },
763 { "target_wide_charset", gdbpy_target_wide_charset
, METH_NOARGS
,
764 "target_wide_charset () -> string.\n\
765 Return the name of the current target wide charset." },
767 { "write", gdbpy_write
, METH_VARARGS
,
768 "Write a string using gdb's filtered stream." },
769 { "flush", gdbpy_flush
, METH_NOARGS
,
770 "Flush gdb's filtered stdout stream." },
772 {NULL
, NULL
, 0, NULL
}
775 #endif /* HAVE_PYTHON */