gdb/
[deliverable/binutils-gdb.git] / gdb / python / python-cmd.c
CommitLineData
d8906c6f
TJB
1/* gdb commands implemented in Python
2
3 Copyright (C) 2008, 2009 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20
21#include "defs.h"
22#include "value.h"
23#include "exceptions.h"
24#include "python-internal.h"
25#include "charset.h"
26#include "gdbcmd.h"
27#include "cli/cli-decode.h"
28#include "completer.h"
29
30/* Struct representing built-in completion types. */
31struct cmdpy_completer
32{
33 /* Python symbol name. */
34 char *name;
35 /* Completion function. */
36 char **(*completer) (struct cmd_list_element *, char *, char *);
37};
38
39static struct cmdpy_completer completers[] =
40{
41 { "COMPLETE_NONE", noop_completer },
42 { "COMPLETE_FILENAME", filename_completer },
43 { "COMPLETE_LOCATION", location_completer },
44 { "COMPLETE_COMMAND", command_completer },
45 { "COMPLETE_SYMBOL", make_symbol_completion_list_fn },
46};
47
48#define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))
49
50/* A gdb command. For the time being only ordinary commands (not
51 set/show commands) are allowed. */
52struct cmdpy_object
53{
54 PyObject_HEAD
55
56 /* The corresponding gdb command object, or NULL if the command is
57 no longer installed. */
58 struct cmd_list_element *command;
59
60 /* A prefix command requires storage for a list of its sub-commands.
61 A pointer to this is passed to add_prefix_command, and to add_cmd
62 for sub-commands of that prefix. If this Command is not a prefix
63 command, then this field is unused. */
64 struct cmd_list_element *sub_list;
65};
66
67typedef struct cmdpy_object cmdpy_object;
68
69static PyTypeObject cmdpy_object_type;
70
71
72/* Constants used by this module. */
73static PyObject *invoke_cst;
74static PyObject *complete_cst;
75
76\f
77
78/* Python function which wraps dont_repeat. */
79static PyObject *
80cmdpy_dont_repeat (PyObject *self, PyObject *args)
81{
82 dont_repeat ();
83 Py_RETURN_NONE;
84}
85
86\f
87
88/* Called if the gdb cmd_list_element is destroyed. */
89static void
90cmdpy_destroyer (struct cmd_list_element *self, void *context)
91{
92 cmdpy_object *cmd;
93 PyGILState_STATE state;
94
95 state = PyGILState_Ensure ();
96
97 /* Release our hold on the command object. */
98 cmd = (cmdpy_object *) context;
99 cmd->command = NULL;
100 Py_DECREF (cmd);
101
102 /* We allocated the name, doc string, and perhaps the prefix
103 name. */
104 xfree (self->name);
105 xfree (self->doc);
106 xfree (self->prefixname);
107
108 PyGILState_Release (state);
109}
110
111/* Called by gdb to invoke the command. */
112static void
113cmdpy_function (struct cmd_list_element *command, char *args, int from_tty)
114{
115 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
116 PyObject *argobj, *ttyobj, *result;
117 struct cleanup *cleanup;
118 PyGILState_STATE state;
119
120 state = PyGILState_Ensure ();
121 cleanup = make_cleanup_py_restore_gil (&state);
122
123 if (! obj)
124 error (_("Invalid invocation of Python command object."));
125 if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst))
126 {
127 if (obj->command->prefixname)
128 {
129 /* A prefix command does not need an invoke method. */
130 do_cleanups (cleanup);
131 return;
132 }
133 error (_("Python command object missing 'invoke' method."));
134 }
135
136 if (! args)
137 args = "";
138 argobj = PyUnicode_Decode (args, strlen (args), host_charset (), NULL);
139 if (! argobj)
140 error (_("Could not convert arguments to Python string."));
141
142 ttyobj = from_tty ? Py_True : Py_False;
143 Py_INCREF (ttyobj);
144 result = PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst, argobj,
145 ttyobj, NULL);
146 Py_DECREF (argobj);
147 Py_DECREF (ttyobj);
148 if (! result)
149 {
150 PyObject *ptype, *pvalue, *ptraceback;
151 char *s, *str;
152
153 PyErr_Fetch (&ptype, &pvalue, &ptraceback);
154
155 if (pvalue && PyString_Check (pvalue))
156 {
157 /* Make a temporary copy of the string data. */
158 char *s = PyString_AsString (pvalue);
159 char *copy = alloca (strlen (s) + 1);
160 strcpy (copy, s);
161
162 PyErr_Restore (ptype, pvalue, ptraceback);
163 gdbpy_print_stack ();
164 error (_("Error occurred in Python command: %s"), copy);
165 }
166 else
167 {
168 PyErr_Restore (ptype, pvalue, ptraceback);
169 gdbpy_print_stack ();
170 error (_("Error occurred in Python command."));
171 }
172 }
173 Py_DECREF (result);
174 do_cleanups (cleanup);
175}
176
177/* Called by gdb for command completion. */
178static char **
179cmdpy_completer (struct cmd_list_element *command, char *text, char *word)
180{
181 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
182 PyObject *textobj, *wordobj, *resultobj = NULL;
183 char **result = NULL;
184 struct cleanup *cleanup;
185 PyGILState_STATE state;
186
187 state = PyGILState_Ensure ();
188 cleanup = make_cleanup_py_restore_gil (&state);
189
190 if (! obj)
191 error (_("Invalid invocation of Python command object."));
192 if (! PyObject_HasAttr ((PyObject *) obj, complete_cst))
193 {
194 /* If there is no complete method, don't error -- instead, just
195 say that there are no completions. */
196 goto done;
197 }
198
199 textobj = PyUnicode_Decode (text, strlen (text), host_charset (), NULL);
200 if (! textobj)
201 error (_("Could not convert argument to Python string."));
202 wordobj = PyUnicode_Decode (word, strlen (word), host_charset (), NULL);
203 if (! wordobj)
204 error (_("Could not convert argument to Python string."));
205
206 resultobj = PyObject_CallMethodObjArgs ((PyObject *) obj, complete_cst,
207 textobj, wordobj, NULL);
208 Py_DECREF (textobj);
209 Py_DECREF (wordobj);
210 if (! resultobj)
211 {
212 /* Just swallow errors here. */
213 PyErr_Clear ();
214 goto done;
215 }
216 make_cleanup_py_decref (resultobj);
217
218 result = NULL;
219 if (PySequence_Check (resultobj))
220 {
221 Py_ssize_t i, len = PySequence_Size (resultobj);
222 Py_ssize_t out;
223 if (len < 0)
224 goto done;
225
226 result = (char **) xmalloc ((len + 1) * sizeof (char *));
227 for (i = out = 0; i < len; ++i)
228 {
229 int l;
230 PyObject *elt = PySequence_GetItem (resultobj, i);
231 if (elt == NULL || ! gdbpy_is_string (elt))
232 {
233 /* Skip problem elements. */
234 PyErr_Clear ();
235 continue;
236 }
237 result[out] = python_string_to_host_string (elt);
238 ++out;
239 }
240 result[out] = NULL;
241 }
242 else if (PyInt_Check (resultobj))
243 {
244 /* User code may also return one of the completion constants,
245 thus requesting that sort of completion. */
246 long value = PyInt_AsLong (resultobj);
247 if (value >= 0 && value < (long) N_COMPLETERS)
248 result = completers[value].completer (command, text, word);
249 }
250
251 done:
252
253 do_cleanups (cleanup);
254
255 return result;
256}
257
258/* Helper for cmdpy_init which locates the command list to use and
259 pulls out the command name.
260
261 TEXT is the command name list. The final word in the list is the
262 name of the new command. All earlier words must be existing prefix
263 commands.
264
265 *BASE_LIST is set to the final prefix command's list of
266 *sub-commands.
267
268 This function returns the xmalloc()d name of the new command. On
269 error sets the Python error and returns NULL. */
270static char *
271parse_command_name (char *text, struct cmd_list_element ***base_list)
272{
273 struct cmd_list_element *elt;
274 int len = strlen (text);
275 int i, lastchar;
276 char *prefix_text;
277 char *result;
278
279 /* Skip trailing whitespace. */
280 for (i = len - 1; i >= 0 && (text[i] == ' ' || text[i] == '\t'); --i)
281 ;
282 if (i < 0)
283 {
284 PyErr_SetString (PyExc_RuntimeError, _("no command name found"));
285 return NULL;
286 }
287 lastchar = i;
288
289 /* Find first character of the final word. */
290 for (; i > 0 && (isalnum (text[i - 1])
291 || text[i - 1] == '-'
292 || text[i - 1] == '_');
293 --i)
294 ;
295 result = xmalloc (lastchar - i + 2);
296 memcpy (result, &text[i], lastchar - i + 1);
297 result[lastchar - i + 1] = '\0';
298
299 /* Skip whitespace again. */
300 for (--i; i >= 0 && (text[i] == ' ' || text[i] == '\t'); --i)
301 ;
302 if (i < 0)
303 {
304 *base_list = &cmdlist;
305 return result;
306 }
307
308 prefix_text = xmalloc (i + 2);
309 memcpy (prefix_text, text, i + 1);
310 prefix_text[i + 1] = '\0';
311
312 text = prefix_text;
313 elt = lookup_cmd_1 (&text, cmdlist, NULL, 1);
314 if (!elt || elt == (struct cmd_list_element *) -1)
315 {
316 PyErr_Format (PyExc_RuntimeError, _("could not find command prefix %s"),
317 prefix_text);
318 xfree (prefix_text);
319 xfree (result);
320 return NULL;
321 }
322
323 if (elt->prefixlist)
324 {
325 xfree (prefix_text);
326 *base_list = elt->prefixlist;
327 return result;
328 }
329
330 PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command"),
331 prefix_text);
332 xfree (prefix_text);
333 xfree (result);
334 return NULL;
335}
336
337/* Object initializer; sets up gdb-side structures for command.
338
cc924cad 339 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
d8906c6f
TJB
340
341 NAME is the name of the command. It may consist of multiple words,
342 in which case the final word is the name of the new command, and
343 earlier words must be prefix commands.
344
cc924cad 345 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
d8906c6f
TJB
346 constants defined in the gdb module.
347
cc924cad 348 COMPLETER_CLASS is the kind of completer. If not given, the
d8906c6f
TJB
349 "complete" method will be used. Otherwise, it should be one of the
350 COMPLETE_* constants defined in the gdb module.
351
352 If PREFIX is True, then this command is a prefix command.
353
354 The documentation for the command is taken from the doc string for
355 the python class.
356
357*/
358static int
cc924cad 359cmdpy_init (PyObject *self, PyObject *args, PyObject *kw)
d8906c6f
TJB
360{
361 cmdpy_object *obj = (cmdpy_object *) self;
362 char *name;
363 int cmdtype;
364 int completetype = -1;
365 char *docstring = NULL;
366 volatile struct gdb_exception except;
367 struct cmd_list_element **cmd_list;
368 char *cmd_name, *pfx_name;
cc924cad
TJB
369 static char *keywords[] = { "name", "command_class", "completer_class",
370 "prefix", NULL };
d8906c6f
TJB
371 PyObject *is_prefix = NULL;
372 int cmp;
373
374 if (obj->command)
375 {
376 /* Note: this is apparently not documented in Python. We return
377 0 for success, -1 for failure. */
378 PyErr_Format (PyExc_RuntimeError,
379 _("command object already initialized"));
380 return -1;
381 }
382
cc924cad 383 if (! PyArg_ParseTupleAndKeywords (args, kw, "si|iO", keywords, &name, &cmdtype,
d8906c6f
TJB
384 &completetype, &is_prefix))
385 return -1;
386
387 if (cmdtype != no_class && cmdtype != class_run
388 && cmdtype != class_vars && cmdtype != class_stack
389 && cmdtype != class_files && cmdtype != class_support
390 && cmdtype != class_info && cmdtype != class_breakpoint
391 && cmdtype != class_trace && cmdtype != class_obscure
392 && cmdtype != class_maintenance)
393 {
394 PyErr_Format (PyExc_RuntimeError, _("invalid command class argument"));
395 return -1;
396 }
397
398 if (completetype < -1 || completetype >= (int) N_COMPLETERS)
399 {
400 PyErr_Format (PyExc_RuntimeError, _("invalid completion type argument"));
401 return -1;
402 }
403
404 cmd_name = parse_command_name (name, &cmd_list);
405 if (! cmd_name)
406 return -1;
407
408 pfx_name = NULL;
409 if (is_prefix != NULL)
410 {
411 cmp = PyObject_IsTrue (is_prefix);
412 if (cmp == 1)
413 {
414 int i, out;
415
416 /* Make a normalized form of the command name. */
417 pfx_name = xmalloc (strlen (name) + 2);
418
419 i = 0;
420 out = 0;
421 while (name[i])
422 {
423 /* Skip whitespace. */
424 while (name[i] == ' ' || name[i] == '\t')
425 ++i;
426 /* Copy non-whitespace characters. */
427 while (name[i] && name[i] != ' ' && name[i] != '\t')
428 pfx_name[out++] = name[i++];
429 /* Add a single space after each word -- including the final
430 word. */
431 pfx_name[out++] = ' ';
432 }
433 pfx_name[out] = '\0';
434 }
435 else if (cmp < 0)
436 return -1;
437 }
438 if (PyObject_HasAttr (self, gdbpy_doc_cst))
439 {
440 PyObject *ds_obj = PyObject_GetAttr (self, gdbpy_doc_cst);
441 if (ds_obj && gdbpy_is_string (ds_obj))
442 docstring = python_string_to_host_string (ds_obj);
443 }
444 if (! docstring)
445 docstring = xstrdup (_("This command is not documented."));
446
447 Py_INCREF (self);
448
449 TRY_CATCH (except, RETURN_MASK_ALL)
450 {
451 struct cmd_list_element *cmd;
452
453 if (pfx_name)
454 {
455 int allow_unknown;
456
457 /* If we have our own "invoke" method, then allow unknown
458 sub-commands. */
459 allow_unknown = PyObject_HasAttr (self, invoke_cst);
460 cmd = add_prefix_cmd (cmd_name, (enum command_class) cmdtype,
461 NULL, docstring, &obj->sub_list,
462 pfx_name, allow_unknown, cmd_list);
463 }
464 else
465 cmd = add_cmd (cmd_name, (enum command_class) cmdtype, NULL,
466 docstring, cmd_list);
467
468 /* There appears to be no API to set this. */
469 cmd->func = cmdpy_function;
470 cmd->destroyer = cmdpy_destroyer;
471
472 obj->command = cmd;
473 set_cmd_context (cmd, self);
474 set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer
475 : completers[completetype].completer));
476 }
477 if (except.reason < 0)
478 {
479 xfree (cmd_name);
480 xfree (docstring);
481 xfree (pfx_name);
482 Py_DECREF (self);
483 PyErr_Format (except.reason == RETURN_QUIT
484 ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
485 "%s", except.message);
486 return -1;
487 }
488 return 0;
489}
490
491\f
492
493/* Initialize the 'commands' code. */
494void
495gdbpy_initialize_commands (void)
496{
497 int i;
498
499 if (PyType_Ready (&cmdpy_object_type) < 0)
500 return;
501
502 /* Note: alias and user are special; pseudo appears to be unused,
503 and there is no reason to expose tui or xdb, I think. */
504 if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0
505 || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0
506 || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0
507 || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0
508 || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0
509 || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT",
510 class_support) < 0
511 || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0
512 || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS",
513 class_breakpoint) < 0
514 || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS",
515 class_trace) < 0
516 || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE",
517 class_obscure) < 0
518 || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE",
519 class_maintenance) < 0)
520 return;
521
522 for (i = 0; i < N_COMPLETERS; ++i)
523 {
524 if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0)
525 return;
526 }
527
528 Py_INCREF (&cmdpy_object_type);
529 PyModule_AddObject (gdb_module, "Command",
530 (PyObject *) &cmdpy_object_type);
531
532 invoke_cst = PyString_FromString ("invoke");
533 complete_cst = PyString_FromString ("complete");
534}
535
536\f
537
538static PyMethodDef cmdpy_object_methods[] =
539{
540 { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS,
541 "Prevent command repetition when user enters empty line." },
542
543 { 0 }
544};
545
546static PyTypeObject cmdpy_object_type =
547{
548 PyObject_HEAD_INIT (NULL)
549 0, /*ob_size*/
550 "gdb.Command", /*tp_name*/
551 sizeof (cmdpy_object), /*tp_basicsize*/
552 0, /*tp_itemsize*/
553 0, /*tp_dealloc*/
554 0, /*tp_print*/
555 0, /*tp_getattr*/
556 0, /*tp_setattr*/
557 0, /*tp_compare*/
558 0, /*tp_repr*/
559 0, /*tp_as_number*/
560 0, /*tp_as_sequence*/
561 0, /*tp_as_mapping*/
562 0, /*tp_hash */
563 0, /*tp_call*/
564 0, /*tp_str*/
565 0, /*tp_getattro*/
566 0, /*tp_setattro*/
567 0, /*tp_as_buffer*/
568 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
569 "GDB command object", /* tp_doc */
570 0, /* tp_traverse */
571 0, /* tp_clear */
572 0, /* tp_richcompare */
573 0, /* tp_weaklistoffset */
574 0, /* tp_iter */
575 0, /* tp_iternext */
576 cmdpy_object_methods, /* tp_methods */
577 0, /* tp_members */
578 0, /* tp_getset */
579 0, /* tp_base */
580 0, /* tp_dict */
581 0, /* tp_descr_get */
582 0, /* tp_descr_set */
583 0, /* tp_dictoffset */
584 cmdpy_init, /* tp_init */
585 0, /* tp_alloc */
586 PyType_GenericNew /* tp_new */
587};
This page took 0.055642 seconds and 4 git commands to generate.