1 /* gdb commands implemented in Python
3 Copyright (C) 2008, 2009 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 char **(*completer
) (struct cmd_list_element
*, char *, char *);
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
;
74 /* Constants used by this module. */
75 static PyObject
*invoke_cst
;
76 static PyObject
*complete_cst
;
80 /* Python function which wraps dont_repeat. */
82 cmdpy_dont_repeat (PyObject
*self
, PyObject
*args
)
90 /* 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
108 xfree (self
->prefixname
);
110 do_cleanups (cleanup
);
113 /* Called by gdb to invoke the command. */
115 cmdpy_function (struct cmd_list_element
*command
, char *args
, int from_tty
)
117 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
118 PyObject
*argobj
, *ttyobj
, *result
;
119 struct cleanup
*cleanup
;
121 cleanup
= ensure_python_env (get_current_arch (), current_language
);
124 error (_("Invalid invocation of Python command object."));
125 if (! PyObject_HasAttr ((PyObject
*) obj
, invoke_cst
))
127 if (obj
->command
->prefixname
)
129 /* A prefix command does not need an invoke method. */
130 do_cleanups (cleanup
);
133 error (_("Python command object missing 'invoke' method."));
138 argobj
= PyUnicode_Decode (args
, strlen (args
), host_charset (), NULL
);
140 error (_("Could not convert arguments to Python string."));
142 ttyobj
= from_tty
? Py_True
: Py_False
;
144 result
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, invoke_cst
, argobj
,
150 PyObject
*ptype
, *pvalue
, *ptraceback
;
153 PyErr_Fetch (&ptype
, &pvalue
, &ptraceback
);
155 if (pvalue
&& PyString_Check (pvalue
))
157 /* Make a temporary copy of the string data. */
158 char *s
= PyString_AsString (pvalue
);
159 char *copy
= alloca (strlen (s
) + 1);
162 PyErr_Restore (ptype
, pvalue
, ptraceback
);
163 gdbpy_print_stack ();
164 error (_("Error occurred in Python command: %s"), copy
);
168 PyErr_Restore (ptype
, pvalue
, ptraceback
);
169 gdbpy_print_stack ();
170 error (_("Error occurred in Python command."));
174 do_cleanups (cleanup
);
177 /* Called by gdb for command completion. */
179 cmdpy_completer (struct cmd_list_element
*command
, char *text
, char *word
)
181 cmdpy_object
*obj
= (cmdpy_object
*) get_cmd_context (command
);
182 PyObject
*textobj
, *wordobj
, *resultobj
= NULL
;
183 char **result
= NULL
;
184 struct cleanup
*cleanup
;
186 cleanup
= ensure_python_env (get_current_arch (), current_language
);
189 error (_("Invalid invocation of Python command object."));
190 if (! PyObject_HasAttr ((PyObject
*) obj
, complete_cst
))
192 /* If there is no complete method, don't error -- instead, just
193 say that there are no completions. */
197 textobj
= PyUnicode_Decode (text
, strlen (text
), host_charset (), NULL
);
199 error (_("Could not convert argument to Python string."));
200 wordobj
= PyUnicode_Decode (word
, strlen (word
), host_charset (), NULL
);
202 error (_("Could not convert argument to Python string."));
204 resultobj
= PyObject_CallMethodObjArgs ((PyObject
*) obj
, complete_cst
,
205 textobj
, wordobj
, NULL
);
210 /* Just swallow errors here. */
214 make_cleanup_py_decref (resultobj
);
217 if (PySequence_Check (resultobj
))
219 Py_ssize_t i
, len
= PySequence_Size (resultobj
);
224 result
= (char **) xmalloc ((len
+ 1) * sizeof (char *));
225 for (i
= out
= 0; i
< len
; ++i
)
228 PyObject
*elt
= PySequence_GetItem (resultobj
, i
);
229 if (elt
== NULL
|| ! gdbpy_is_string (elt
))
231 /* Skip problem elements. */
235 result
[out
] = python_string_to_host_string (elt
);
240 else if (PyInt_Check (resultobj
))
242 /* User code may also return one of the completion constants,
243 thus requesting that sort of completion. */
244 long value
= PyInt_AsLong (resultobj
);
245 if (value
>= 0 && value
< (long) N_COMPLETERS
)
246 result
= completers
[value
].completer (command
, text
, word
);
251 do_cleanups (cleanup
);
256 /* Helper for cmdpy_init which locates the command list to use and
257 pulls out the command name.
259 TEXT is the command name list. The final word in the list is the
260 name of the new command. All earlier words must be existing prefix
263 *BASE_LIST is set to the final prefix command's list of
266 This function returns the xmalloc()d name of the new command. On
267 error sets the Python error and returns NULL. */
269 parse_command_name (char *text
, struct cmd_list_element
***base_list
)
271 struct cmd_list_element
*elt
;
272 int len
= strlen (text
);
277 /* Skip trailing whitespace. */
278 for (i
= len
- 1; i
>= 0 && (text
[i
] == ' ' || text
[i
] == '\t'); --i
)
282 PyErr_SetString (PyExc_RuntimeError
, _("no command name found"));
287 /* Find first character of the final word. */
288 for (; i
> 0 && (isalnum (text
[i
- 1])
289 || text
[i
- 1] == '-'
290 || text
[i
- 1] == '_');
293 result
= xmalloc (lastchar
- i
+ 2);
294 memcpy (result
, &text
[i
], lastchar
- i
+ 1);
295 result
[lastchar
- i
+ 1] = '\0';
297 /* Skip whitespace again. */
298 for (--i
; i
>= 0 && (text
[i
] == ' ' || text
[i
] == '\t'); --i
)
302 *base_list
= &cmdlist
;
306 prefix_text
= xmalloc (i
+ 2);
307 memcpy (prefix_text
, text
, i
+ 1);
308 prefix_text
[i
+ 1] = '\0';
311 elt
= lookup_cmd_1 (&text
, cmdlist
, NULL
, 1);
312 if (!elt
|| elt
== (struct cmd_list_element
*) -1)
314 PyErr_Format (PyExc_RuntimeError
, _("could not find command prefix %s"),
324 *base_list
= elt
->prefixlist
;
328 PyErr_Format (PyExc_RuntimeError
, _("'%s' is not a prefix command"),
335 /* Object initializer; sets up gdb-side structures for command.
337 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
339 NAME is the name of the command. It may consist of multiple words,
340 in which case the final word is the name of the new command, and
341 earlier words must be prefix commands.
343 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
344 constants defined in the gdb module.
346 COMPLETER_CLASS is the kind of completer. If not given, the
347 "complete" method will be used. Otherwise, it should be one of the
348 COMPLETE_* constants defined in the gdb module.
350 If PREFIX is True, then this command is a prefix command.
352 The documentation for the command is taken from the doc string for
357 cmdpy_init (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
359 cmdpy_object
*obj
= (cmdpy_object
*) self
;
362 int completetype
= -1;
363 char *docstring
= NULL
;
364 volatile struct gdb_exception except
;
365 struct cmd_list_element
**cmd_list
;
366 char *cmd_name
, *pfx_name
;
367 static char *keywords
[] = { "name", "command_class", "completer_class",
369 PyObject
*is_prefix
= NULL
;
374 /* Note: this is apparently not documented in Python. We return
375 0 for success, -1 for failure. */
376 PyErr_Format (PyExc_RuntimeError
,
377 _("command object already initialized"));
381 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "si|iO", keywords
, &name
, &cmdtype
,
382 &completetype
, &is_prefix
))
385 if (cmdtype
!= no_class
&& cmdtype
!= class_run
386 && cmdtype
!= class_vars
&& cmdtype
!= class_stack
387 && cmdtype
!= class_files
&& cmdtype
!= class_support
388 && cmdtype
!= class_info
&& cmdtype
!= class_breakpoint
389 && cmdtype
!= class_trace
&& cmdtype
!= class_obscure
390 && cmdtype
!= class_maintenance
)
392 PyErr_Format (PyExc_RuntimeError
, _("invalid command class argument"));
396 if (completetype
< -1 || completetype
>= (int) N_COMPLETERS
)
398 PyErr_Format (PyExc_RuntimeError
, _("invalid completion type argument"));
402 cmd_name
= parse_command_name (name
, &cmd_list
);
407 if (is_prefix
!= NULL
)
409 cmp
= PyObject_IsTrue (is_prefix
);
414 /* Make a normalized form of the command name. */
415 pfx_name
= xmalloc (strlen (name
) + 2);
421 /* Skip whitespace. */
422 while (name
[i
] == ' ' || name
[i
] == '\t')
424 /* Copy non-whitespace characters. */
425 while (name
[i
] && name
[i
] != ' ' && name
[i
] != '\t')
426 pfx_name
[out
++] = name
[i
++];
427 /* Add a single space after each word -- including the final
429 pfx_name
[out
++] = ' ';
431 pfx_name
[out
] = '\0';
436 if (PyObject_HasAttr (self
, gdbpy_doc_cst
))
438 PyObject
*ds_obj
= PyObject_GetAttr (self
, gdbpy_doc_cst
);
439 if (ds_obj
&& gdbpy_is_string (ds_obj
))
440 docstring
= python_string_to_host_string (ds_obj
);
443 docstring
= xstrdup (_("This command is not documented."));
447 TRY_CATCH (except
, RETURN_MASK_ALL
)
449 struct cmd_list_element
*cmd
;
455 /* If we have our own "invoke" method, then allow unknown
457 allow_unknown
= PyObject_HasAttr (self
, invoke_cst
);
458 cmd
= add_prefix_cmd (cmd_name
, (enum command_class
) cmdtype
,
459 NULL
, docstring
, &obj
->sub_list
,
460 pfx_name
, allow_unknown
, cmd_list
);
463 cmd
= add_cmd (cmd_name
, (enum command_class
) cmdtype
, NULL
,
464 docstring
, cmd_list
);
466 /* There appears to be no API to set this. */
467 cmd
->func
= cmdpy_function
;
468 cmd
->destroyer
= cmdpy_destroyer
;
471 set_cmd_context (cmd
, self
);
472 set_cmd_completer (cmd
, ((completetype
== -1) ? cmdpy_completer
473 : completers
[completetype
].completer
));
475 if (except
.reason
< 0)
481 PyErr_Format (except
.reason
== RETURN_QUIT
482 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
483 "%s", except
.message
);
491 /* Initialize the 'commands' code. */
493 gdbpy_initialize_commands (void)
497 if (PyType_Ready (&cmdpy_object_type
) < 0)
500 /* Note: alias and user are special; pseudo appears to be unused,
501 and there is no reason to expose tui or xdb, I think. */
502 if (PyModule_AddIntConstant (gdb_module
, "COMMAND_NONE", no_class
) < 0
503 || PyModule_AddIntConstant (gdb_module
, "COMMAND_RUNNING", class_run
) < 0
504 || PyModule_AddIntConstant (gdb_module
, "COMMAND_DATA", class_vars
) < 0
505 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STACK", class_stack
) < 0
506 || PyModule_AddIntConstant (gdb_module
, "COMMAND_FILES", class_files
) < 0
507 || PyModule_AddIntConstant (gdb_module
, "COMMAND_SUPPORT",
509 || PyModule_AddIntConstant (gdb_module
, "COMMAND_STATUS", class_info
) < 0
510 || PyModule_AddIntConstant (gdb_module
, "COMMAND_BREAKPOINTS",
511 class_breakpoint
) < 0
512 || PyModule_AddIntConstant (gdb_module
, "COMMAND_TRACEPOINTS",
514 || PyModule_AddIntConstant (gdb_module
, "COMMAND_OBSCURE",
516 || PyModule_AddIntConstant (gdb_module
, "COMMAND_MAINTENANCE",
517 class_maintenance
) < 0)
520 for (i
= 0; i
< N_COMPLETERS
; ++i
)
522 if (PyModule_AddIntConstant (gdb_module
, completers
[i
].name
, i
) < 0)
526 Py_INCREF (&cmdpy_object_type
);
527 PyModule_AddObject (gdb_module
, "Command",
528 (PyObject
*) &cmdpy_object_type
);
530 invoke_cst
= PyString_FromString ("invoke");
531 complete_cst
= PyString_FromString ("complete");
536 static PyMethodDef cmdpy_object_methods
[] =
538 { "dont_repeat", cmdpy_dont_repeat
, METH_NOARGS
,
539 "Prevent command repetition when user enters empty line." },
544 static PyTypeObject cmdpy_object_type
=
546 PyObject_HEAD_INIT (NULL
)
548 "gdb.Command", /*tp_name*/
549 sizeof (cmdpy_object
), /*tp_basicsize*/
558 0, /*tp_as_sequence*/
566 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
567 "GDB command object", /* tp_doc */
570 0, /* tp_richcompare */
571 0, /* tp_weaklistoffset */
574 cmdpy_object_methods
, /* tp_methods */
579 0, /* tp_descr_get */
580 0, /* tp_descr_set */
581 0, /* tp_dictoffset */
582 cmdpy_init
, /* tp_init */
584 PyType_GenericNew
/* tp_new */