1 /* gdb commands implemented in Python
3 Copyright (C) 2008-2013 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
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. */
37 /* Completion function. */
38 completer_ftype
*completer
;
41 static struct cmdpy_completer completers
[] =
43 { "COMPLETE_NONE", noop_completer
},
44 { "COMPLETE_FILENAME", filename_completer
},
45 { "COMPLETE_LOCATION", location_completer
},
46 { "COMPLETE_COMMAND", command_completer
},
47 { "COMPLETE_SYMBOL", make_symbol_completion_list_fn
},
50 #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))
52 /* A gdb command. For the time being only ordinary commands (not
53 set/show commands) are allowed. */
58 /* The corresponding gdb command object, or NULL if the command is
59 no longer installed. */
60 struct cmd_list_element
*command
;
62 /* A prefix command requires storage for a list of its sub-commands.
63 A pointer to this is passed to add_prefix_command, and to add_cmd
64 for sub-commands of that prefix. If this Command is not a prefix
65 command, then this field is unused. */
66 struct cmd_list_element
*sub_list
;
69 typedef struct cmdpy_object cmdpy_object
;
71 static PyTypeObject cmdpy_object_type
;
73 /* Constants used by this module. */
74 static PyObject
*invoke_cst
;
75 static PyObject
*complete_cst
;
79 /* Python function which wraps dont_repeat. */
81 cmdpy_dont_repeat (PyObject
*self
, PyObject
*args
)
89 /* Called if the gdb cmd_list_element is destroyed. */
92 cmdpy_destroyer (struct cmd_list_element
*self
, void *context
)
95 struct cleanup
*cleanup
;
97 cleanup
= ensure_python_env (get_current_arch (), current_language
);
99 /* Release our hold on the command object. */
100 cmd
= (cmdpy_object
*) context
;
104 /* We allocated the name, doc string, and perhaps the prefix
106 xfree ((char *) self
->name
);
108 xfree (self
->prefixname
);
110 do_cleanups (cleanup
);
113 /* Called by gdb to invoke the command. */
116 cmdpy_function (struct cmd_list_element
*command
, char *args
, int from_tty
)
118 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
119 PyObject
*argobj
, *ttyobj
, *result
;
120 struct cleanup
*cleanup
;
122 cleanup
= ensure_python_env (get_current_arch (), current_language
);
125 error (_("Invalid invocation of Python command object."));
126 if (! PyObject_HasAttr ((PyObject
*) obj
, invoke_cst
))
128 if (obj
->command
->prefixname
)
130 /* A prefix command does not need an invoke method. */
131 do_cleanups (cleanup
);
134 error (_("Python command object missing 'invoke' method."));
139 argobj
= PyUnicode_Decode (args
, strlen (args
), host_charset (), NULL
);
142 gdbpy_print_stack ();
143 error (_("Could not convert arguments to Python string."));
146 ttyobj
= from_tty
? Py_True
: Py_False
;
148 result
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, invoke_cst
, argobj
,
155 PyObject
*ptype
, *pvalue
, *ptraceback
;
158 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
160 /* Try to fetch an error message contained within ptype, pvalue.
161 When fetching the error message we need to make our own copy,
162 we no longer own ptype, pvalue after the call to PyErr_Restore. */
164 msg
= gdbpy_exception_to_string (ptype
, pvalue
);
165 make_cleanup (xfree
, msg
);
169 /* An error occurred computing the string representation of the
170 error message. This is rare, but we should inform the user. */
171 printf_filtered (_("An error occurred in a Python command\n"
172 "and then another occurred computing the "
173 "error message.\n"));
174 gdbpy_print_stack ();
177 /* Don't print the stack for gdb.GdbError exceptions.
178 It is generally used to flag user errors.
180 We also don't want to print "Error occurred in Python command"
181 for user errors. However, a missing message for gdb.GdbError
182 exceptions is arguably a bug, so we flag it as such. */
184 if (! PyErr_GivenExceptionMatches (ptype
, gdbpy_gdberror_exc
)
185 || msg
== NULL
|| *msg
== '\0')
187 PyErr_Restore (ptype
, pvalue
, ptraceback
);
188 gdbpy_print_stack ();
189 if (msg
!= NULL
&& *msg
!= '\0')
190 error (_("Error occurred in Python command: %s"), msg
);
192 error (_("Error occurred in Python command."));
198 Py_XDECREF (ptraceback
);
204 do_cleanups (cleanup
);
207 /* Called by gdb for command completion. */
209 static VEC (char_ptr
) *
210 cmdpy_completer (struct cmd_list_element
*command
,
211 const char *text
, const char *word
)
213 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
214 PyObject
*textobj
, *wordobj
, *resultobj
= NULL
;
215 VEC (char_ptr
) *result
= NULL
;
216 struct cleanup
*cleanup
;
218 cleanup
= ensure_python_env (get_current_arch (), current_language
);
221 error (_("Invalid invocation of Python command object."));
222 if (! PyObject_HasAttr ((PyObject
*) obj
, complete_cst
))
224 /* If there is no complete method, don't error -- instead, just
225 say that there are no completions. */
229 textobj
= PyUnicode_Decode (text
, strlen (text
), host_charset (), NULL
);
231 error (_("Could not convert argument to Python string."));
232 wordobj
= PyUnicode_Decode (word
, strlen (word
), host_charset (), NULL
);
234 error (_("Could not convert argument to Python string."));
236 resultobj
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, complete_cst
,
237 textobj
, wordobj
, NULL
);
242 /* Just swallow errors here. */
246 make_cleanup_py_decref (resultobj
);
249 if (PySequence_Check (resultobj
))
251 Py_ssize_t i
, len
= PySequence_Size (resultobj
);
257 for (i
= out
= 0; i
< len
; ++i
)
259 PyObject
*elt
= PySequence_GetItem (resultobj
, i
);
262 if (elt
== NULL
|| ! gdbpy_is_string (elt
))
264 /* Skip problem elements. */
268 item
= python_string_to_host_string (elt
);
271 /* Skip problem elements. */
275 VEC_safe_push (char_ptr
, result
, item
);
278 else if (PyInt_Check (resultobj
))
280 /* User code may also return one of the completion constants,
281 thus requesting that sort of completion. */
284 if (! gdb_py_int_as_long (resultobj
, &value
))
289 else if (value
>= 0 && value
< (long) N_COMPLETERS
)
290 result
= completers
[value
].completer (command
, text
, word
);
295 do_cleanups (cleanup
);
300 /* Helper for cmdpy_init which locates the command list to use and
301 pulls out the command name.
303 NAME is the command name list. The final word in the list is the
304 name of the new command. All earlier words must be existing prefix
307 *BASE_LIST is set to the final prefix command's list of
310 START_LIST is the list in which the search starts.
312 This function returns the xmalloc()d name of the new command. On
313 error sets the Python error and returns NULL. */
316 gdbpy_parse_command_name (const char *name
,
317 struct cmd_list_element
***base_list
,
318 struct cmd_list_element
**start_list
)
320 struct cmd_list_element
*elt
;
321 int len
= strlen (name
);
324 const char *prefix_text2
;
327 /* Skip trailing whitespace. */
328 for (i
= len
- 1; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
332 PyErr_SetString (PyExc_RuntimeError
, _("No command name found."));
337 /* Find first character of the final word. */
338 for (; i
> 0 && (isalnum (name
[i
- 1])
339 || name
[i
- 1] == '-'
340 || name
[i
- 1] == '_');
343 result
= xmalloc (lastchar
- i
+ 2);
344 memcpy (result
, &name
[i
], lastchar
- i
+ 1);
345 result
[lastchar
- i
+ 1] = '\0';
347 /* Skip whitespace again. */
348 for (--i
; i
>= 0 && (name
[i
] == ' ' || name
[i
] == '\t'); --i
)
352 *base_list
= start_list
;
356 prefix_text
= xmalloc (i
+ 2);
357 memcpy (prefix_text
, name
, i
+ 1);
358 prefix_text
[i
+ 1] = '\0';
360 prefix_text2
= prefix_text
;
361 elt
= lookup_cmd_1 (&prefix_text2
, *start_list
, NULL
, 1);
362 if (!elt
|| elt
== (struct cmd_list_element
*) -1)
364 PyErr_Format (PyExc_RuntimeError
, _("Could not find command prefix %s."),
374 *base_list
= elt
->prefixlist
;
378 PyErr_Format (PyExc_RuntimeError
, _("'%s' is not a prefix command."),
385 /* Object initializer; sets up gdb-side structures for command.
387 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
389 NAME is the name of the command. It may consist of multiple words,
390 in which case the final word is the name of the new command, and
391 earlier words must be prefix commands.
393 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
394 constants defined in the gdb module.
396 COMPLETER_CLASS is the kind of completer. If not given, the
397 "complete" method will be used. Otherwise, it should be one of the
398 COMPLETE_* constants defined in the gdb module.
400 If PREFIX is True, then this command is a prefix command.
402 The documentation for the command is taken from the doc string for
406 cmdpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
408 cmdpy_object
*obj
= (cmdpy_object
*) self
;
411 int completetype
= -1;
412 char *docstring
= NULL
;
413 volatile struct gdb_exception except
;
414 struct cmd_list_element
**cmd_list
;
415 char *cmd_name
, *pfx_name
;
416 static char *keywords
[] = { "name", "command_class", "completer_class",
418 PyObject
*is_prefix
= NULL
;
423 /* Note: this is apparently not documented in Python. We return
424 0 for success, -1 for failure. */
425 PyErr_Format (PyExc_RuntimeError
,
426 _("Command object already initialized."));
430 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "si|iO",
431 keywords
, &name
, &cmdtype
,
432 &completetype
, &is_prefix
))
435 if (cmdtype
!= no_class
&& cmdtype
!= class_run
436 && cmdtype
!= class_vars
&& cmdtype
!= class_stack
437 && cmdtype
!= class_files
&& cmdtype
!= class_support
438 && cmdtype
!= class_info
&& cmdtype
!= class_breakpoint
439 && cmdtype
!= class_trace
&& cmdtype
!= class_obscure
440 && cmdtype
!= class_maintenance
&& cmdtype
!= class_user
)
442 PyErr_Format (PyExc_RuntimeError
, _("Invalid command class argument."));
446 if (completetype
< -1 || completetype
>= (int) N_COMPLETERS
)
448 PyErr_Format (PyExc_RuntimeError
,
449 _("Invalid completion type argument."));
453 cmd_name
= gdbpy_parse_command_name (name
, &cmd_list
, &cmdlist
);
458 if (is_prefix
!= NULL
)
460 cmp
= PyObject_IsTrue (is_prefix
);
465 /* Make a normalized form of the command name. */
466 pfx_name
= xmalloc (strlen (name
) + 2);
472 /* Skip whitespace. */
473 while (name
[i
] == ' ' || name
[i
] == '\t')
475 /* Copy non-whitespace characters. */
476 while (name
[i
] && name
[i
] != ' ' && name
[i
] != '\t')
477 pfx_name
[out
++] = name
[i
++];
478 /* Add a single space after each word -- including the final
480 pfx_name
[out
++] = ' ';
482 pfx_name
[out
] = '\0';
490 if (PyObject_HasAttr (self
, gdbpy_doc_cst
))
492 PyObject
*ds_obj
= PyObject_GetAttr (self
, gdbpy_doc_cst
);
494 if (ds_obj
&& gdbpy_is_string (ds_obj
))
496 docstring
= python_string_to_host_string (ds_obj
);
497 if (docstring
== NULL
)
506 docstring
= xstrdup (_("This command is not documented."));
510 TRY_CATCH (except
, RETURN_MASK_ALL
)
512 struct cmd_list_element
*cmd
;
518 /* If we have our own "invoke" method, then allow unknown
520 allow_unknown
= PyObject_HasAttr (self
, invoke_cst
);
521 cmd
= add_prefix_cmd (cmd_name
, (enum command_class
) cmdtype
,
522 NULL
, docstring
, &obj
->sub_list
,
523 pfx_name
, allow_unknown
, cmd_list
);
526 cmd
= add_cmd (cmd_name
, (enum command_class
) cmdtype
, NULL
,
527 docstring
, cmd_list
);
529 /* There appears to be no API to set this. */
530 cmd
->func
= cmdpy_function
;
531 cmd
->destroyer
= cmdpy_destroyer
;
534 set_cmd_context (cmd
, self
);
535 set_cmd_completer (cmd
, ((completetype
== -1) ? cmdpy_completer
536 : completers
[completetype
].completer
));
538 if (except
.reason
< 0)
544 PyErr_Format (except
.reason
== RETURN_QUIT
545 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
546 "%s", except
.message
);
554 /* Initialize the 'commands' code. */
557 gdbpy_initialize_commands (void)
561 cmdpy_object_type
.tp_new
= PyType_GenericNew
;
562 if (PyType_Ready (&cmdpy_object_type
) < 0)
565 /* Note: alias and user are special; pseudo appears to be unused,
566 and there is no reason to expose tui or xdb, I think. */
567 if (PyModule_AddIntConstant (gdb_module
, "COMMAND_NONE", no_class
) < 0
568 || PyModule_AddIntConstant (gdb_module
, "COMMAND_RUNNING", class_run
) < 0
569 || PyModule_AddIntConstant (gdb_module
, "COMMAND_DATA", class_vars
) < 0
570 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STACK", class_stack
) < 0
571 || PyModule_AddIntConstant (gdb_module
, "COMMAND_FILES", class_files
) < 0
572 || PyModule_AddIntConstant (gdb_module
, "COMMAND_SUPPORT",
574 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STATUS", class_info
) < 0
575 || PyModule_AddIntConstant (gdb_module
, "COMMAND_BREAKPOINTS",
576 class_breakpoint
) < 0
577 || PyModule_AddIntConstant (gdb_module
, "COMMAND_TRACEPOINTS",
579 || PyModule_AddIntConstant (gdb_module
, "COMMAND_OBSCURE",
581 || PyModule_AddIntConstant (gdb_module
, "COMMAND_MAINTENANCE",
582 class_maintenance
) < 0
583 || PyModule_AddIntConstant (gdb_module
, "COMMAND_USER", class_user
) < 0)
586 for (i
= 0; i
< N_COMPLETERS
; ++i
)
588 if (PyModule_AddIntConstant (gdb_module
, completers
[i
].name
, i
) < 0)
592 Py_INCREF (&cmdpy_object_type
);
593 PyModule_AddObject (gdb_module
, "Command",
594 (PyObject
*) &cmdpy_object_type
);
596 invoke_cst
= PyString_FromString ("invoke");
597 complete_cst
= PyString_FromString ("complete");
602 static PyMethodDef cmdpy_object_methods
[] =
604 { "dont_repeat", cmdpy_dont_repeat
, METH_NOARGS
,
605 "Prevent command repetition when user enters empty line." },
610 static PyTypeObject cmdpy_object_type
=
612 PyVarObject_HEAD_INIT (NULL
, 0)
613 "gdb.Command", /*tp_name*/
614 sizeof (cmdpy_object
), /*tp_basicsize*/
623 0, /*tp_as_sequence*/
631 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
632 "GDB command object", /* tp_doc */
635 0, /* tp_richcompare */
636 0, /* tp_weaklistoffset */
639 cmdpy_object_methods
, /* tp_methods */
644 0, /* tp_descr_get */
645 0, /* tp_descr_set */
646 0, /* tp_dictoffset */
647 cmdpy_init
, /* tp_init */
653 /* Utility to build a buildargv-like result from ARGS.
654 This intentionally parses arguments the way libiberty/argv.c:buildargv
655 does. It splits up arguments in a reasonable way, and we want a standard
656 way of parsing arguments. Several gdb commands use buildargv to parse their
657 arguments. Plus we want to be able to write compatible python
658 implementations of gdb commands. */
661 gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
)
666 if (!PyArg_ParseTuple (args
, "s", &input
))
669 py_argv
= PyList_New (0);
671 /* buildargv uses NULL to represent an empty argument list, but we can't use
672 that in Python. Instead, if ARGS is "" then return an empty list.
673 This undoes the NULL -> "" conversion that cmdpy_function does. */
677 char **c_argv
= gdb_buildargv (input
);
680 for (i
= 0; c_argv
[i
] != NULL
; ++i
)
682 PyObject
*argp
= PyString_FromString (c_argv
[i
]);
685 || PyList_Append (py_argv
, argp
) < 0)