1 /* gdb commands implemented in Python
3 Copyright (C) 2008-2014 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/>. */
22 #include "arch-utils.h"
24 #include "exceptions.h"
25 #include "python-internal.h"
28 #include "cli/cli-decode.h"
29 #include "completer.h"
32 /* Struct representing built-in completion types. */
33 struct cmdpy_completer
35 /* Python symbol name.
36 This isn't a const char * for Python 2.4's sake.
37 PyModule_AddIntConstant only takes a char *, sigh. */
39 /* Completion function. */
40 completer_ftype
*completer
;
43 static const struct cmdpy_completer completers
[] =
45 { "COMPLETE_NONE", noop_completer
},
46 { "COMPLETE_FILENAME", filename_completer
},
47 { "COMPLETE_LOCATION", location_completer
},
48 { "COMPLETE_COMMAND", command_completer
},
49 { "COMPLETE_SYMBOL", make_symbol_completion_list_fn
},
50 { "COMPLETE_EXPRESSION", expression_completer
},
53 #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))
55 /* A gdb command. For the time being only ordinary commands (not
56 set/show commands) are allowed. */
61 /* The corresponding gdb command object, or NULL if the command is
62 no longer installed. */
63 struct cmd_list_element
*command
;
65 /* A prefix command requires storage for a list of its sub-commands.
66 A pointer to this is passed to add_prefix_command, and to add_cmd
67 for sub-commands of that prefix. If this Command is not a prefix
68 command, then this field is unused. */
69 struct cmd_list_element
*sub_list
;
72 typedef struct cmdpy_object cmdpy_object
;
74 static PyTypeObject cmdpy_object_type
75 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("cmdpy_object");
77 /* Constants used by this module. */
78 static PyObject
*invoke_cst
;
79 static PyObject
*complete_cst
;
83 /* Python function which wraps dont_repeat. */
85 cmdpy_dont_repeat (PyObject
*self
, PyObject
*args
)
93 /* Called if the gdb cmd_list_element is destroyed. */
96 cmdpy_destroyer (struct cmd_list_element
*self
, void *context
)
99 struct cleanup
*cleanup
;
101 cleanup
= ensure_python_env (get_current_arch (), current_language
);
103 /* Release our hold on the command object. */
104 cmd
= (cmdpy_object
*) context
;
108 /* We allocated the name, doc string, and perhaps the prefix
110 xfree ((char *) self
->name
);
111 xfree ((char *) self
->doc
);
112 xfree ((char *) self
->prefixname
);
114 do_cleanups (cleanup
);
117 /* Called by gdb to invoke the command. */
120 cmdpy_function (struct cmd_list_element
*command
, char *args
, int from_tty
)
122 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
123 PyObject
*argobj
, *ttyobj
, *result
;
124 struct cleanup
*cleanup
;
126 cleanup
= ensure_python_env (get_current_arch (), current_language
);
129 error (_("Invalid invocation of Python command object."));
130 if (! PyObject_HasAttr ((PyObject
*) obj
, invoke_cst
))
132 if (obj
->command
->prefixname
)
134 /* A prefix command does not need an invoke method. */
135 do_cleanups (cleanup
);
138 error (_("Python command object missing 'invoke' method."));
143 argobj
= PyUnicode_Decode (args
, strlen (args
), host_charset (), NULL
);
146 gdbpy_print_stack ();
147 error (_("Could not convert arguments to Python string."));
150 ttyobj
= from_tty
? Py_True
: Py_False
;
152 result
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, invoke_cst
, argobj
,
159 PyObject
*ptype
, *pvalue
, *ptraceback
;
162 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
164 /* Try to fetch an error message contained within ptype, pvalue.
165 When fetching the error message we need to make our own copy,
166 we no longer own ptype, pvalue after the call to PyErr_Restore. */
168 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
169 make_cleanup (xfree
, msg
);
173 /* An error occurred computing the string representation of the
174 error message. This is rare, but we should inform the user. */
175 printf_filtered (_("An error occurred in a Python command\n"
176 "and then another occurred computing the "
177 "error message.\n"));
178 gdbpy_print_stack ();
181 /* Don't print the stack for gdb.GdbError exceptions.
182 It is generally used to flag user errors.
184 We also don't want to print "Error occurred in Python command"
185 for user errors. However, a missing message for gdb.GdbError
186 exceptions is arguably a bug, so we flag it as such. */
188 if (! PyErr_GivenExceptionMatches (ptype
, gdbpy_gdberror_exc
)
189 || msg
== NULL
|| *msg
== '\0')
191 PyErr_Restore (ptype
, pvalue
, ptraceback
);
192 gdbpy_print_stack ();
193 if (msg
!= NULL
&& *msg
!= '\0')
194 error (_("Error occurred in Python command: %s"), msg
);
196 error (_("Error occurred in Python command."));
202 Py_XDECREF (ptraceback
);
208 do_cleanups (cleanup
);
211 /* Helper function for the Python command completers (both "pure"
212 completer and brkchar handler). This function takes COMMAND, TEXT
213 and WORD and tries to call the Python method for completion with
214 these arguments. It also takes HANDLE_BRKCHARS_P, an argument to
215 identify whether it is being called from the brkchar handler or
216 from the "pure" completer. In the first case, it effectively calls
217 the Python method for completion, and records the PyObject in a
218 static variable (used as a "cache"). In the second case, it just
219 returns that variable, without actually calling the Python method
220 again. This saves us one Python method call.
222 The reason for this two step dance is that we need to know the set
223 of "brkchars" to use early on, before we actually try to perform
224 the completion. But if a Python command supplies a "complete"
225 method then we have to call that method first: it may return as its
226 result the kind of completion to perform and that will in turn
227 specify which brkchars to use. IOW, we need the result of the
228 "complete" method before we actually perform the completion.
230 It is important to mention that this function is built on the
231 assumption that the calls to cmdpy_completer_handle_brkchars and
232 cmdpy_completer will be subsequent with nothing intervening. This
233 is true for our completer mechanism.
235 This function returns the PyObject representing the Python method
239 cmdpy_completer_helper (struct cmd_list_element
*command
,
240 const char *text
, const char *word
,
241 int handle_brkchars_p
)
243 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
244 PyObject
*textobj
, *wordobj
;
245 /* This static variable will server as a "cache" for us, in order to
246 store the PyObject that results from calling the Python
248 static PyObject
*resultobj
= NULL
;
250 if (handle_brkchars_p
)
252 /* If we were called to handle brkchars, it means this is the
253 first function call of two that will happen in a row.
254 Therefore, we need to call the completer ourselves, and cache
255 the return value in the static variable RESULTOBJ. Then, in
256 the second call, we can just use the value of RESULTOBJ to do
258 if (resultobj
!= NULL
)
259 Py_DECREF (resultobj
);
263 error (_("Invalid invocation of Python command object."));
264 if (!PyObject_HasAttr ((PyObject
*) obj
, complete_cst
))
266 /* If there is no complete method, don't error. */
270 textobj
= PyUnicode_Decode (text
, strlen (text
), host_charset (), NULL
);
272 error (_("Could not convert argument to Python string."));
273 wordobj
= PyUnicode_Decode (word
, sizeof (word
), host_charset (), NULL
);
277 error (_("Could not convert argument to Python string."));
280 resultobj
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, complete_cst
,
281 textobj
, wordobj
, NULL
);
286 /* Just swallow errors here. */
290 Py_XINCREF (resultobj
);
296 /* Python function called to determine the break characters of a
297 certain completer. We are only interested in knowing if the
298 completer registered by the user will return one of the integer
299 codes (see COMPLETER_* symbols). */
302 cmdpy_completer_handle_brkchars (struct cmd_list_element
*command
,
303 const char *text
, const char *word
)
305 PyObject
*resultobj
= NULL
;
306 struct cleanup
*cleanup
;
308 cleanup
= ensure_python_env (get_current_arch (), current_language
);
310 /* Calling our helper to obtain the PyObject of the Python
312 resultobj
= cmdpy_completer_helper (command
, text
, word
, 1);
314 /* Check if there was an error. */
315 if (resultobj
== NULL
)
318 if (PyInt_Check (resultobj
))
320 /* User code may also return one of the completion constants,
321 thus requesting that sort of completion. We are only
322 interested in this kind of return. */
325 if (!gdb_py_int_as_long (resultobj
, &value
))
330 else if (value
>= 0 && value
< (long) N_COMPLETERS
)
332 /* This is the core of this function. Depending on which
333 completer type the Python function returns, we have to
334 adjust the break characters accordingly. */
335 set_gdb_completion_word_break_characters
336 (completers
[value
].completer
);
342 /* We do not call Py_XDECREF here because RESULTOBJ will be used in
343 the subsequent call to cmdpy_completer function. */
344 do_cleanups (cleanup
);
347 /* Called by gdb for command completion. */
349 static VEC (char_ptr
) *
350 cmdpy_completer (struct cmd_list_element
*command
,
351 const char *text
, const char *word
)
353 PyObject
*resultobj
= NULL
;
354 VEC (char_ptr
) *result
= NULL
;
355 struct cleanup
*cleanup
;
357 cleanup
= ensure_python_env (get_current_arch (), current_language
);
359 /* Calling our helper to obtain the PyObject of the Python
361 resultobj
= cmdpy_completer_helper (command
, text
, word
, 0);
363 /* If the result object of calling the Python function is NULL, it
364 means that there was an error. In this case, just give up and
366 if (resultobj
== NULL
)
370 if (PyInt_Check (resultobj
))
372 /* User code may also return one of the completion constants,
373 thus requesting that sort of completion. */
376 if (! gdb_py_int_as_long (resultobj
, &value
))
381 else if (value
>= 0 && value
< (long) N_COMPLETERS
)
382 result
= completers
[value
].completer (command
, text
, word
);
386 PyObject
*iter
= PyObject_GetIter (resultobj
);
392 while ((elt
= PyIter_Next (iter
)) != NULL
)
396 if (! gdbpy_is_string (elt
))
398 /* Skip problem elements. */
402 item
= python_string_to_host_string (elt
);
406 /* Skip problem elements. */
410 VEC_safe_push (char_ptr
, result
, item
);
415 /* If we got some results, ignore problems. Otherwise, report
417 if (result
!= NULL
&& PyErr_Occurred ())
423 do_cleanups (cleanup
);
428 /* Helper for cmdpy_init which locates the command list to use and
429 pulls out the command name.
431 NAME is the command name list. The final word in the list is the
432 name of the new command. All earlier words must be existing prefix
435 *BASE_LIST is set to the final prefix command's list of
438 START_LIST is the list in which the search starts.
440 This function returns the xmalloc()d name of the new command. On
441 error sets the Python error and returns NULL. */
444 gdbpy_parse_command_name (const char *name
,
445 struct cmd_list_element
***base_list
,
446 struct cmd_list_element
**start_list
)
448 struct cmd_list_element
*elt
;
449 int len
= strlen (name
);
452 const char *prefix_text2
;
455 /* Skip trailing whitespace. */
456 for (i
= len
- 1; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
460 PyErr_SetString (PyExc_RuntimeError
, _("No command name found."));
465 /* Find first character of the final word. */
466 for (; i
> 0 && (isalnum (name
[i
- 1])
467 || name
[i
- 1] == '-'
468 || name
[i
- 1] == '_');
471 result
= xmalloc (lastchar
- i
+ 2);
472 memcpy (result
, &name
[i
], lastchar
- i
+ 1);
473 result
[lastchar
- i
+ 1] = '\0';
475 /* Skip whitespace again. */
476 for (--i
; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
480 *base_list
= start_list
;
484 prefix_text
= xmalloc (i
+ 2);
485 memcpy (prefix_text
, name
, i
+ 1);
486 prefix_text
[i
+ 1] = '\0';
488 prefix_text2
= prefix_text
;
489 elt
= lookup_cmd_1 (&prefix_text2
, *start_list
, NULL
, 1);
490 if (elt
== NULL
|| elt
== CMD_LIST_AMBIGUOUS
)
492 PyErr_Format (PyExc_RuntimeError
, _("Could not find command prefix %s."),
502 *base_list
= elt
->prefixlist
;
506 PyErr_Format (PyExc_RuntimeError
, _("'%s' is not a prefix command."),
513 /* Object initializer; sets up gdb-side structures for command.
515 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
517 NAME is the name of the command. It may consist of multiple words,
518 in which case the final word is the name of the new command, and
519 earlier words must be prefix commands.
521 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
522 constants defined in the gdb module.
524 COMPLETER_CLASS is the kind of completer. If not given, the
525 "complete" method will be used. Otherwise, it should be one of the
526 COMPLETE_* constants defined in the gdb module.
528 If PREFIX is True, then this command is a prefix command.
530 The documentation for the command is taken from the doc string for
534 cmdpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
536 cmdpy_object
*obj
= (cmdpy_object
*) self
;
539 int completetype
= -1;
540 char *docstring
= NULL
;
541 volatile struct gdb_exception except
;
542 struct cmd_list_element
**cmd_list
;
543 char *cmd_name
, *pfx_name
;
544 static char *keywords
[] = { "name", "command_class", "completer_class",
546 PyObject
*is_prefix
= NULL
;
551 /* Note: this is apparently not documented in Python. We return
552 0 for success, -1 for failure. */
553 PyErr_Format (PyExc_RuntimeError
,
554 _("Command object already initialized."));
558 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "si|iO",
559 keywords
, &name
, &cmdtype
,
560 &completetype
, &is_prefix
))
563 if (cmdtype
!= no_class
&& cmdtype
!= class_run
564 && cmdtype
!= class_vars
&& cmdtype
!= class_stack
565 && cmdtype
!= class_files
&& cmdtype
!= class_support
566 && cmdtype
!= class_info
&& cmdtype
!= class_breakpoint
567 && cmdtype
!= class_trace
&& cmdtype
!= class_obscure
568 && cmdtype
!= class_maintenance
&& cmdtype
!= class_user
)
570 PyErr_Format (PyExc_RuntimeError
, _("Invalid command class argument."));
574 if (completetype
< -1 || completetype
>= (int) N_COMPLETERS
)
576 PyErr_Format (PyExc_RuntimeError
,
577 _("Invalid completion type argument."));
581 cmd_name
= gdbpy_parse_command_name (name
, &cmd_list
, &cmdlist
);
586 if (is_prefix
!= NULL
)
588 cmp
= PyObject_IsTrue (is_prefix
);
593 /* Make a normalized form of the command name. */
594 pfx_name
= xmalloc (strlen (name
) + 2);
600 /* Skip whitespace. */
601 while (name
[i
] == ' ' || name
[i
] == '\t')
603 /* Copy non-whitespace characters. */
604 while (name
[i
] && name
[i
] != ' ' && name
[i
] != '\t')
605 pfx_name
[out
++] = name
[i
++];
606 /* Add a single space after each word -- including the final
608 pfx_name
[out
++] = ' ';
610 pfx_name
[out
] = '\0';
618 if (PyObject_HasAttr (self
, gdbpy_doc_cst
))
620 PyObject
*ds_obj
= PyObject_GetAttr (self
, gdbpy_doc_cst
);
622 if (ds_obj
&& gdbpy_is_string (ds_obj
))
624 docstring
= python_string_to_host_string (ds_obj
);
625 if (docstring
== NULL
)
637 docstring
= xstrdup (_("This command is not documented."));
641 TRY_CATCH (except
, RETURN_MASK_ALL
)
643 struct cmd_list_element
*cmd
;
649 /* If we have our own "invoke" method, then allow unknown
651 allow_unknown
= PyObject_HasAttr (self
, invoke_cst
);
652 cmd
= add_prefix_cmd (cmd_name
, (enum command_class
) cmdtype
,
653 NULL
, docstring
, &obj
->sub_list
,
654 pfx_name
, allow_unknown
, cmd_list
);
657 cmd
= add_cmd (cmd_name
, (enum command_class
) cmdtype
, NULL
,
658 docstring
, cmd_list
);
660 /* There appears to be no API to set this. */
661 cmd
->func
= cmdpy_function
;
662 cmd
->destroyer
= cmdpy_destroyer
;
665 set_cmd_context (cmd
, self
);
666 set_cmd_completer (cmd
, ((completetype
== -1) ? cmdpy_completer
667 : completers
[completetype
].completer
));
668 if (completetype
== -1)
669 set_cmd_completer_handle_brkchars (cmd
,
670 cmdpy_completer_handle_brkchars
);
672 if (except
.reason
< 0)
678 PyErr_Format (except
.reason
== RETURN_QUIT
679 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
680 "%s", except
.message
);
688 /* Initialize the 'commands' code. */
691 gdbpy_initialize_commands (void)
695 cmdpy_object_type
.tp_new
= PyType_GenericNew
;
696 if (PyType_Ready (&cmdpy_object_type
) < 0)
699 /* Note: alias and user are special; pseudo appears to be unused,
700 and there is no reason to expose tui or xdb, I think. */
701 if (PyModule_AddIntConstant (gdb_module
, "COMMAND_NONE", no_class
) < 0
702 || PyModule_AddIntConstant (gdb_module
, "COMMAND_RUNNING", class_run
) < 0
703 || PyModule_AddIntConstant (gdb_module
, "COMMAND_DATA", class_vars
) < 0
704 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STACK", class_stack
) < 0
705 || PyModule_AddIntConstant (gdb_module
, "COMMAND_FILES", class_files
) < 0
706 || PyModule_AddIntConstant (gdb_module
, "COMMAND_SUPPORT",
708 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STATUS", class_info
) < 0
709 || PyModule_AddIntConstant (gdb_module
, "COMMAND_BREAKPOINTS",
710 class_breakpoint
) < 0
711 || PyModule_AddIntConstant (gdb_module
, "COMMAND_TRACEPOINTS",
713 || PyModule_AddIntConstant (gdb_module
, "COMMAND_OBSCURE",
715 || PyModule_AddIntConstant (gdb_module
, "COMMAND_MAINTENANCE",
716 class_maintenance
) < 0
717 || PyModule_AddIntConstant (gdb_module
, "COMMAND_USER", class_user
) < 0)
720 for (i
= 0; i
< N_COMPLETERS
; ++i
)
722 if (PyModule_AddIntConstant (gdb_module
, completers
[i
].name
, i
) < 0)
726 if (gdb_pymodule_addobject (gdb_module
, "Command",
727 (PyObject
*) &cmdpy_object_type
) < 0)
730 invoke_cst
= PyString_FromString ("invoke");
731 if (invoke_cst
== NULL
)
733 complete_cst
= PyString_FromString ("complete");
734 if (complete_cst
== NULL
)
742 static PyMethodDef cmdpy_object_methods
[] =
744 { "dont_repeat", cmdpy_dont_repeat
, METH_NOARGS
,
745 "Prevent command repetition when user enters empty line." },
750 static PyTypeObject cmdpy_object_type
=
752 PyVarObject_HEAD_INIT (NULL
, 0)
753 "gdb.Command", /*tp_name*/
754 sizeof (cmdpy_object
), /*tp_basicsize*/
763 0, /*tp_as_sequence*/
771 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
772 "GDB command object", /* tp_doc */
775 0, /* tp_richcompare */
776 0, /* tp_weaklistoffset */
779 cmdpy_object_methods
, /* tp_methods */
784 0, /* tp_descr_get */
785 0, /* tp_descr_set */
786 0, /* tp_dictoffset */
787 cmdpy_init
, /* tp_init */
793 /* Utility to build a buildargv-like result from ARGS.
794 This intentionally parses arguments the way libiberty/argv.c:buildargv
795 does. It splits up arguments in a reasonable way, and we want a standard
796 way of parsing arguments. Several gdb commands use buildargv to parse their
797 arguments. Plus we want to be able to write compatible python
798 implementations of gdb commands. */
801 gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
)
806 if (!PyArg_ParseTuple (args
, "s", &input
))
809 py_argv
= PyList_New (0);
813 /* buildargv uses NULL to represent an empty argument list, but we can't use
814 that in Python. Instead, if ARGS is "" then return an empty list.
815 This undoes the NULL -> "" conversion that cmdpy_function does. */
819 char **c_argv
= gdb_buildargv (input
);
822 for (i
= 0; c_argv
[i
] != NULL
; ++i
)
824 PyObject
*argp
= PyString_FromString (c_argv
[i
]);
827 || PyList_Append (py_argv
, argp
) < 0)