* python/py-arch.c (arch_object_type): Use
[deliverable/binutils-gdb.git] / gdb / python / py-cmd.c
1 /* gdb commands implemented in Python
2
3 Copyright (C) 2008-2013 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 "arch-utils.h"
23 #include "value.h"
24 #include "exceptions.h"
25 #include "python-internal.h"
26 #include "charset.h"
27 #include "gdbcmd.h"
28 #include "cli/cli-decode.h"
29 #include "completer.h"
30 #include "language.h"
31
32 /* Struct representing built-in completion types. */
33 struct cmdpy_completer
34 {
35 /* Python symbol name. */
36 char *name;
37 /* Completion function. */
38 completer_ftype *completer;
39 };
40
41 static struct cmdpy_completer completers[] =
42 {
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 },
48 };
49
50 #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))
51
52 /* A gdb command. For the time being only ordinary commands (not
53 set/show commands) are allowed. */
54 struct cmdpy_object
55 {
56 PyObject_HEAD
57
58 /* The corresponding gdb command object, or NULL if the command is
59 no longer installed. */
60 struct cmd_list_element *command;
61
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;
67 };
68
69 typedef struct cmdpy_object cmdpy_object;
70
71 static PyTypeObject cmdpy_object_type
72 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("cmdpy_object");
73
74 /* Constants used by this module. */
75 static PyObject *invoke_cst;
76 static PyObject *complete_cst;
77
78 \f
79
80 /* Python function which wraps dont_repeat. */
81 static PyObject *
82 cmdpy_dont_repeat (PyObject *self, PyObject *args)
83 {
84 dont_repeat ();
85 Py_RETURN_NONE;
86 }
87
88 \f
89
90 /* Called if the gdb cmd_list_element is destroyed. */
91
92 static void
93 cmdpy_destroyer (struct cmd_list_element *self, void *context)
94 {
95 cmdpy_object *cmd;
96 struct cleanup *cleanup;
97
98 cleanup = ensure_python_env (get_current_arch (), current_language);
99
100 /* Release our hold on the command object. */
101 cmd = (cmdpy_object *) context;
102 cmd->command = NULL;
103 Py_DECREF (cmd);
104
105 /* We allocated the name, doc string, and perhaps the prefix
106 name. */
107 xfree ((char *) self->name);
108 xfree (self->doc);
109 xfree (self->prefixname);
110
111 do_cleanups (cleanup);
112 }
113
114 /* Called by gdb to invoke the command. */
115
116 static void
117 cmdpy_function (struct cmd_list_element *command, char *args, int from_tty)
118 {
119 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
120 PyObject *argobj, *ttyobj, *result;
121 struct cleanup *cleanup;
122
123 cleanup = ensure_python_env (get_current_arch (), current_language);
124
125 if (! obj)
126 error (_("Invalid invocation of Python command object."));
127 if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst))
128 {
129 if (obj->command->prefixname)
130 {
131 /* A prefix command does not need an invoke method. */
132 do_cleanups (cleanup);
133 return;
134 }
135 error (_("Python command object missing 'invoke' method."));
136 }
137
138 if (! args)
139 args = "";
140 argobj = PyUnicode_Decode (args, strlen (args), host_charset (), NULL);
141 if (! argobj)
142 {
143 gdbpy_print_stack ();
144 error (_("Could not convert arguments to Python string."));
145 }
146
147 ttyobj = from_tty ? Py_True : Py_False;
148 Py_INCREF (ttyobj);
149 result = PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst, argobj,
150 ttyobj, NULL);
151 Py_DECREF (argobj);
152 Py_DECREF (ttyobj);
153
154 if (! result)
155 {
156 PyObject *ptype, *pvalue, *ptraceback;
157 char *msg;
158
159 PyErr_Fetch (&ptype, &pvalue, &ptraceback);
160
161 /* Try to fetch an error message contained within ptype, pvalue.
162 When fetching the error message we need to make our own copy,
163 we no longer own ptype, pvalue after the call to PyErr_Restore. */
164
165 msg = gdbpy_exception_to_string (ptype, pvalue);
166 make_cleanup (xfree, msg);
167
168 if (msg == NULL)
169 {
170 /* An error occurred computing the string representation of the
171 error message. This is rare, but we should inform the user. */
172 printf_filtered (_("An error occurred in a Python command\n"
173 "and then another occurred computing the "
174 "error message.\n"));
175 gdbpy_print_stack ();
176 }
177
178 /* Don't print the stack for gdb.GdbError exceptions.
179 It is generally used to flag user errors.
180
181 We also don't want to print "Error occurred in Python command"
182 for user errors. However, a missing message for gdb.GdbError
183 exceptions is arguably a bug, so we flag it as such. */
184
185 if (! PyErr_GivenExceptionMatches (ptype, gdbpy_gdberror_exc)
186 || msg == NULL || *msg == '\0')
187 {
188 PyErr_Restore (ptype, pvalue, ptraceback);
189 gdbpy_print_stack ();
190 if (msg != NULL && *msg != '\0')
191 error (_("Error occurred in Python command: %s"), msg);
192 else
193 error (_("Error occurred in Python command."));
194 }
195 else
196 {
197 Py_XDECREF (ptype);
198 Py_XDECREF (pvalue);
199 Py_XDECREF (ptraceback);
200 error ("%s", msg);
201 }
202 }
203
204 Py_DECREF (result);
205 do_cleanups (cleanup);
206 }
207
208 /* Called by gdb for command completion. */
209
210 static VEC (char_ptr) *
211 cmdpy_completer (struct cmd_list_element *command,
212 const char *text, const char *word)
213 {
214 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
215 PyObject *textobj, *wordobj, *resultobj = NULL;
216 VEC (char_ptr) *result = NULL;
217 struct cleanup *cleanup;
218
219 cleanup = ensure_python_env (get_current_arch (), current_language);
220
221 if (! obj)
222 error (_("Invalid invocation of Python command object."));
223 if (! PyObject_HasAttr ((PyObject *) obj, complete_cst))
224 {
225 /* If there is no complete method, don't error -- instead, just
226 say that there are no completions. */
227 goto done;
228 }
229
230 textobj = PyUnicode_Decode (text, strlen (text), host_charset (), NULL);
231 if (! textobj)
232 error (_("Could not convert argument to Python string."));
233 wordobj = PyUnicode_Decode (word, strlen (word), host_charset (), NULL);
234 if (! wordobj)
235 error (_("Could not convert argument to Python string."));
236
237 resultobj = PyObject_CallMethodObjArgs ((PyObject *) obj, complete_cst,
238 textobj, wordobj, NULL);
239 Py_DECREF (textobj);
240 Py_DECREF (wordobj);
241 if (! resultobj)
242 {
243 /* Just swallow errors here. */
244 PyErr_Clear ();
245 goto done;
246 }
247 make_cleanup_py_decref (resultobj);
248
249 result = NULL;
250 if (PySequence_Check (resultobj))
251 {
252 Py_ssize_t i, len = PySequence_Size (resultobj);
253 Py_ssize_t out;
254
255 if (len < 0)
256 goto done;
257
258 for (i = out = 0; i < len; ++i)
259 {
260 PyObject *elt = PySequence_GetItem (resultobj, i);
261 char *item;
262
263 if (elt == NULL || ! gdbpy_is_string (elt))
264 {
265 /* Skip problem elements. */
266 PyErr_Clear ();
267 continue;
268 }
269 item = python_string_to_host_string (elt);
270 if (item == NULL)
271 {
272 /* Skip problem elements. */
273 PyErr_Clear ();
274 continue;
275 }
276 VEC_safe_push (char_ptr, result, item);
277 }
278 }
279 else if (PyInt_Check (resultobj))
280 {
281 /* User code may also return one of the completion constants,
282 thus requesting that sort of completion. */
283 long value;
284
285 if (! gdb_py_int_as_long (resultobj, &value))
286 {
287 /* Ignore. */
288 PyErr_Clear ();
289 }
290 else if (value >= 0 && value < (long) N_COMPLETERS)
291 result = completers[value].completer (command, text, word);
292 }
293
294 done:
295
296 do_cleanups (cleanup);
297
298 return result;
299 }
300
301 /* Helper for cmdpy_init which locates the command list to use and
302 pulls out the command name.
303
304 NAME is the command name list. The final word in the list is the
305 name of the new command. All earlier words must be existing prefix
306 commands.
307
308 *BASE_LIST is set to the final prefix command's list of
309 *sub-commands.
310
311 START_LIST is the list in which the search starts.
312
313 This function returns the xmalloc()d name of the new command. On
314 error sets the Python error and returns NULL. */
315
316 char *
317 gdbpy_parse_command_name (const char *name,
318 struct cmd_list_element ***base_list,
319 struct cmd_list_element **start_list)
320 {
321 struct cmd_list_element *elt;
322 int len = strlen (name);
323 int i, lastchar;
324 char *prefix_text;
325 const char *prefix_text2;
326 char *result;
327
328 /* Skip trailing whitespace. */
329 for (i = len - 1; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
330 ;
331 if (i < 0)
332 {
333 PyErr_SetString (PyExc_RuntimeError, _("No command name found."));
334 return NULL;
335 }
336 lastchar = i;
337
338 /* Find first character of the final word. */
339 for (; i > 0 && (isalnum (name[i - 1])
340 || name[i - 1] == '-'
341 || name[i - 1] == '_');
342 --i)
343 ;
344 result = xmalloc (lastchar - i + 2);
345 memcpy (result, &name[i], lastchar - i + 1);
346 result[lastchar - i + 1] = '\0';
347
348 /* Skip whitespace again. */
349 for (--i; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
350 ;
351 if (i < 0)
352 {
353 *base_list = start_list;
354 return result;
355 }
356
357 prefix_text = xmalloc (i + 2);
358 memcpy (prefix_text, name, i + 1);
359 prefix_text[i + 1] = '\0';
360
361 prefix_text2 = prefix_text;
362 elt = lookup_cmd_1 (&prefix_text2, *start_list, NULL, 1);
363 if (!elt || elt == (struct cmd_list_element *) -1)
364 {
365 PyErr_Format (PyExc_RuntimeError, _("Could not find command prefix %s."),
366 prefix_text);
367 xfree (prefix_text);
368 xfree (result);
369 return NULL;
370 }
371
372 if (elt->prefixlist)
373 {
374 xfree (prefix_text);
375 *base_list = elt->prefixlist;
376 return result;
377 }
378
379 PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command."),
380 prefix_text);
381 xfree (prefix_text);
382 xfree (result);
383 return NULL;
384 }
385
386 /* Object initializer; sets up gdb-side structures for command.
387
388 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
389
390 NAME is the name of the command. It may consist of multiple words,
391 in which case the final word is the name of the new command, and
392 earlier words must be prefix commands.
393
394 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
395 constants defined in the gdb module.
396
397 COMPLETER_CLASS is the kind of completer. If not given, the
398 "complete" method will be used. Otherwise, it should be one of the
399 COMPLETE_* constants defined in the gdb module.
400
401 If PREFIX is True, then this command is a prefix command.
402
403 The documentation for the command is taken from the doc string for
404 the python class. */
405
406 static int
407 cmdpy_init (PyObject *self, PyObject *args, PyObject *kw)
408 {
409 cmdpy_object *obj = (cmdpy_object *) self;
410 const char *name;
411 int cmdtype;
412 int completetype = -1;
413 char *docstring = NULL;
414 volatile struct gdb_exception except;
415 struct cmd_list_element **cmd_list;
416 char *cmd_name, *pfx_name;
417 static char *keywords[] = { "name", "command_class", "completer_class",
418 "prefix", NULL };
419 PyObject *is_prefix = NULL;
420 int cmp;
421
422 if (obj->command)
423 {
424 /* Note: this is apparently not documented in Python. We return
425 0 for success, -1 for failure. */
426 PyErr_Format (PyExc_RuntimeError,
427 _("Command object already initialized."));
428 return -1;
429 }
430
431 if (! PyArg_ParseTupleAndKeywords (args, kw, "si|iO",
432 keywords, &name, &cmdtype,
433 &completetype, &is_prefix))
434 return -1;
435
436 if (cmdtype != no_class && cmdtype != class_run
437 && cmdtype != class_vars && cmdtype != class_stack
438 && cmdtype != class_files && cmdtype != class_support
439 && cmdtype != class_info && cmdtype != class_breakpoint
440 && cmdtype != class_trace && cmdtype != class_obscure
441 && cmdtype != class_maintenance && cmdtype != class_user)
442 {
443 PyErr_Format (PyExc_RuntimeError, _("Invalid command class argument."));
444 return -1;
445 }
446
447 if (completetype < -1 || completetype >= (int) N_COMPLETERS)
448 {
449 PyErr_Format (PyExc_RuntimeError,
450 _("Invalid completion type argument."));
451 return -1;
452 }
453
454 cmd_name = gdbpy_parse_command_name (name, &cmd_list, &cmdlist);
455 if (! cmd_name)
456 return -1;
457
458 pfx_name = NULL;
459 if (is_prefix != NULL)
460 {
461 cmp = PyObject_IsTrue (is_prefix);
462 if (cmp == 1)
463 {
464 int i, out;
465
466 /* Make a normalized form of the command name. */
467 pfx_name = xmalloc (strlen (name) + 2);
468
469 i = 0;
470 out = 0;
471 while (name[i])
472 {
473 /* Skip whitespace. */
474 while (name[i] == ' ' || name[i] == '\t')
475 ++i;
476 /* Copy non-whitespace characters. */
477 while (name[i] && name[i] != ' ' && name[i] != '\t')
478 pfx_name[out++] = name[i++];
479 /* Add a single space after each word -- including the final
480 word. */
481 pfx_name[out++] = ' ';
482 }
483 pfx_name[out] = '\0';
484 }
485 else if (cmp < 0)
486 {
487 xfree (cmd_name);
488 return -1;
489 }
490 }
491 if (PyObject_HasAttr (self, gdbpy_doc_cst))
492 {
493 PyObject *ds_obj = PyObject_GetAttr (self, gdbpy_doc_cst);
494
495 if (ds_obj && gdbpy_is_string (ds_obj))
496 {
497 docstring = python_string_to_host_string (ds_obj);
498 if (docstring == NULL)
499 {
500 xfree (cmd_name);
501 xfree (pfx_name);
502 return -1;
503 }
504 }
505 }
506 if (! docstring)
507 docstring = xstrdup (_("This command is not documented."));
508
509 Py_INCREF (self);
510
511 TRY_CATCH (except, RETURN_MASK_ALL)
512 {
513 struct cmd_list_element *cmd;
514
515 if (pfx_name)
516 {
517 int allow_unknown;
518
519 /* If we have our own "invoke" method, then allow unknown
520 sub-commands. */
521 allow_unknown = PyObject_HasAttr (self, invoke_cst);
522 cmd = add_prefix_cmd (cmd_name, (enum command_class) cmdtype,
523 NULL, docstring, &obj->sub_list,
524 pfx_name, allow_unknown, cmd_list);
525 }
526 else
527 cmd = add_cmd (cmd_name, (enum command_class) cmdtype, NULL,
528 docstring, cmd_list);
529
530 /* There appears to be no API to set this. */
531 cmd->func = cmdpy_function;
532 cmd->destroyer = cmdpy_destroyer;
533
534 obj->command = cmd;
535 set_cmd_context (cmd, self);
536 set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer
537 : completers[completetype].completer));
538 }
539 if (except.reason < 0)
540 {
541 xfree (cmd_name);
542 xfree (docstring);
543 xfree (pfx_name);
544 Py_DECREF (self);
545 PyErr_Format (except.reason == RETURN_QUIT
546 ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
547 "%s", except.message);
548 return -1;
549 }
550 return 0;
551 }
552
553 \f
554
555 /* Initialize the 'commands' code. */
556
557 void
558 gdbpy_initialize_commands (void)
559 {
560 int i;
561
562 cmdpy_object_type.tp_new = PyType_GenericNew;
563 if (PyType_Ready (&cmdpy_object_type) < 0)
564 return;
565
566 /* Note: alias and user are special; pseudo appears to be unused,
567 and there is no reason to expose tui or xdb, I think. */
568 if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0
569 || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0
570 || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0
571 || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0
572 || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0
573 || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT",
574 class_support) < 0
575 || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0
576 || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS",
577 class_breakpoint) < 0
578 || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS",
579 class_trace) < 0
580 || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE",
581 class_obscure) < 0
582 || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE",
583 class_maintenance) < 0
584 || PyModule_AddIntConstant (gdb_module, "COMMAND_USER", class_user) < 0)
585 return;
586
587 for (i = 0; i < N_COMPLETERS; ++i)
588 {
589 if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0)
590 return;
591 }
592
593 Py_INCREF (&cmdpy_object_type);
594 PyModule_AddObject (gdb_module, "Command",
595 (PyObject *) &cmdpy_object_type);
596
597 invoke_cst = PyString_FromString ("invoke");
598 complete_cst = PyString_FromString ("complete");
599 }
600
601 \f
602
603 static PyMethodDef cmdpy_object_methods[] =
604 {
605 { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS,
606 "Prevent command repetition when user enters empty line." },
607
608 { 0 }
609 };
610
611 static PyTypeObject cmdpy_object_type =
612 {
613 PyVarObject_HEAD_INIT (NULL, 0)
614 "gdb.Command", /*tp_name*/
615 sizeof (cmdpy_object), /*tp_basicsize*/
616 0, /*tp_itemsize*/
617 0, /*tp_dealloc*/
618 0, /*tp_print*/
619 0, /*tp_getattr*/
620 0, /*tp_setattr*/
621 0, /*tp_compare*/
622 0, /*tp_repr*/
623 0, /*tp_as_number*/
624 0, /*tp_as_sequence*/
625 0, /*tp_as_mapping*/
626 0, /*tp_hash */
627 0, /*tp_call*/
628 0, /*tp_str*/
629 0, /*tp_getattro*/
630 0, /*tp_setattro*/
631 0, /*tp_as_buffer*/
632 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
633 "GDB command object", /* tp_doc */
634 0, /* tp_traverse */
635 0, /* tp_clear */
636 0, /* tp_richcompare */
637 0, /* tp_weaklistoffset */
638 0, /* tp_iter */
639 0, /* tp_iternext */
640 cmdpy_object_methods, /* tp_methods */
641 0, /* tp_members */
642 0, /* tp_getset */
643 0, /* tp_base */
644 0, /* tp_dict */
645 0, /* tp_descr_get */
646 0, /* tp_descr_set */
647 0, /* tp_dictoffset */
648 cmdpy_init, /* tp_init */
649 0, /* tp_alloc */
650 };
651
652 \f
653
654 /* Utility to build a buildargv-like result from ARGS.
655 This intentionally parses arguments the way libiberty/argv.c:buildargv
656 does. It splits up arguments in a reasonable way, and we want a standard
657 way of parsing arguments. Several gdb commands use buildargv to parse their
658 arguments. Plus we want to be able to write compatible python
659 implementations of gdb commands. */
660
661 PyObject *
662 gdbpy_string_to_argv (PyObject *self, PyObject *args)
663 {
664 PyObject *py_argv;
665 const char *input;
666
667 if (!PyArg_ParseTuple (args, "s", &input))
668 return NULL;
669
670 py_argv = PyList_New (0);
671
672 /* buildargv uses NULL to represent an empty argument list, but we can't use
673 that in Python. Instead, if ARGS is "" then return an empty list.
674 This undoes the NULL -> "" conversion that cmdpy_function does. */
675
676 if (*input != '\0')
677 {
678 char **c_argv = gdb_buildargv (input);
679 int i;
680
681 for (i = 0; c_argv[i] != NULL; ++i)
682 {
683 PyObject *argp = PyString_FromString (c_argv[i]);
684
685 if (argp == NULL
686 || PyList_Append (py_argv, argp) < 0)
687 {
688 Py_XDECREF (argp);
689 Py_DECREF (py_argv);
690 freeargv (c_argv);
691 return NULL;
692 }
693 Py_DECREF (argp);
694 }
695
696 freeargv (c_argv);
697 }
698
699 return py_argv;
700 }
This page took 0.060886 seconds and 5 git commands to generate.