py-cmd.c revision 1.8 1 /* gdb commands implemented in Python
2
3 Copyright (C) 2008-2019 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 "python-internal.h"
25 #include "charset.h"
26 #include "gdbcmd.h"
27 #include "cli/cli-decode.h"
28 #include "completer.h"
29 #include "language.h"
30
31 /* Struct representing built-in completion types. */
32 struct cmdpy_completer
33 {
34 /* Python symbol name. */
35 const char *name;
36 /* Completion function. */
37 completer_ftype *completer;
38 };
39
40 static const struct cmdpy_completer completers[] =
41 {
42 { "COMPLETE_NONE", noop_completer },
43 { "COMPLETE_FILENAME", filename_completer },
44 { "COMPLETE_LOCATION", location_completer },
45 { "COMPLETE_COMMAND", command_completer },
46 { "COMPLETE_SYMBOL", symbol_completer },
47 { "COMPLETE_EXPRESSION", expression_completer },
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 extern 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
79
81 /* Python function which wraps dont_repeat. */
82 static PyObject *
83 cmdpy_dont_repeat (PyObject *self, PyObject *args)
84 {
85 dont_repeat ();
86 Py_RETURN_NONE;
87 }
88
89
90
92 /* Called if the gdb cmd_list_element is destroyed. */
93
94 static void
95 cmdpy_destroyer (struct cmd_list_element *self, void *context)
96 {
97 gdbpy_enter enter_py (get_current_arch (), current_language);
98
99 /* Release our hold on the command object. */
100 gdbpy_ref<cmdpy_object> cmd ((cmdpy_object *) context);
101 cmd->command = NULL;
102
103 /* We allocated the name, doc string, and perhaps the prefix
104 name. */
105 xfree ((char *) self->name);
106 xfree ((char *) self->doc);
107 xfree ((char *) self->prefixname);
108 }
109
110 /* Called by gdb to invoke the command. */
111
112 static void
113 cmdpy_function (struct cmd_list_element *command,
114 const char *args, int from_tty)
115 {
116 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
117
118 gdbpy_enter enter_py (get_current_arch (), current_language);
119
120 if (! obj)
121 error (_("Invalid invocation of Python command object."));
122 if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst))
123 {
124 if (obj->command->prefixname)
125 {
126 /* A prefix command does not need an invoke method. */
127 return;
128 }
129 error (_("Python command object missing 'invoke' method."));
130 }
131
132 if (! args)
133 args = "";
134 gdbpy_ref<> argobj (PyUnicode_Decode (args, strlen (args), host_charset (),
135 NULL));
136 if (argobj == NULL)
137 {
138 gdbpy_print_stack ();
139 error (_("Could not convert arguments to Python string."));
140 }
141
142 gdbpy_ref<> ttyobj
143 = gdbpy_ref<>::new_reference (from_tty ? Py_True : Py_False);
144 gdbpy_ref<> result (PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst,
145 argobj.get (), ttyobj.get (),
146 NULL));
147
148 if (result == NULL)
149 gdbpy_handle_exception ();
150 }
151
152 /* Helper function for the Python command completers (both "pure"
153 completer and brkchar handler). This function takes COMMAND, TEXT
154 and WORD and tries to call the Python method for completion with
155 these arguments.
156
157 This function is usually called twice: once when we are figuring out
158 the break characters to be used, and another to perform the real
159 completion itself. The reason for this two step dance is that we
160 need to know the set of "brkchars" to use early on, before we
161 actually try to perform the completion. But if a Python command
162 supplies a "complete" method then we have to call that method
163 first: it may return as its result the kind of completion to
164 perform and that will in turn specify which brkchars to use. IOW,
165 we need the result of the "complete" method before we actually
166 perform the completion. The only situation when this function is
167 not called twice is when the user uses the "complete" command: in
168 this scenario, there is no call to determine the "brkchars".
169
170 Ideally, it would be nice to cache the result of the first call (to
171 determine the "brkchars") and return this value directly in the
172 second call (to perform the actual completion). However, due to
173 the peculiarity of the "complete" command mentioned above, it is
174 possible to put GDB in a bad state if you perform a TAB-completion
175 and then a "complete"-completion sequentially. Therefore, we just
176 recalculate everything twice for TAB-completions.
177
178 This function returns a reference to the PyObject representing the
179 Python method call. */
180
181 static gdbpy_ref<>
182 cmdpy_completer_helper (struct cmd_list_element *command,
183 const char *text, const char *word)
184 {
185 cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
186
187 if (obj == NULL)
188 error (_("Invalid invocation of Python command object."));
189 if (!PyObject_HasAttr ((PyObject *) obj, complete_cst))
190 {
191 /* If there is no complete method, don't error. */
192 return NULL;
193 }
194
195 gdbpy_ref<> textobj (PyUnicode_Decode (text, strlen (text), host_charset (),
196 NULL));
197 if (textobj == NULL)
198 error (_("Could not convert argument to Python string."));
199
200 gdbpy_ref<> wordobj;
201 if (word == NULL)
202 {
203 /* "brkchars" phase. */
204 wordobj = gdbpy_ref<>::new_reference (Py_None);
205 }
206 else
207 {
208 wordobj.reset (PyUnicode_Decode (word, strlen (word), host_charset (),
209 NULL));
210 if (wordobj == NULL)
211 error (_("Could not convert argument to Python string."));
212 }
213
214 gdbpy_ref<> resultobj (PyObject_CallMethodObjArgs ((PyObject *) obj,
215 complete_cst,
216 textobj.get (),
217 wordobj.get (), NULL));
218 if (resultobj == NULL)
219 {
220 /* Just swallow errors here. */
221 PyErr_Clear ();
222 }
223
224 return resultobj;
225 }
226
227 /* Python function called to determine the break characters of a
228 certain completer. We are only interested in knowing if the
229 completer registered by the user will return one of the integer
230 codes (see COMPLETER_* symbols). */
231
232 static void
233 cmdpy_completer_handle_brkchars (struct cmd_list_element *command,
234 completion_tracker &tracker,
235 const char *text, const char *word)
236 {
237 gdbpy_enter enter_py (get_current_arch (), current_language);
238
239 /* Calling our helper to obtain a reference to the PyObject of the Python
240 function. */
241 gdbpy_ref<> resultobj = cmdpy_completer_helper (command, text, word);
242
243 /* Check if there was an error. */
244 if (resultobj == NULL)
245 return;
246
247 if (PyInt_Check (resultobj.get ()))
248 {
249 /* User code may also return one of the completion constants,
250 thus requesting that sort of completion. We are only
251 interested in this kind of return. */
252 long value;
253
254 if (!gdb_py_int_as_long (resultobj.get (), &value))
255 {
256 /* Ignore. */
257 PyErr_Clear ();
258 }
259 else if (value >= 0 && value < (long) N_COMPLETERS)
260 {
261 completer_handle_brkchars_ftype *brkchars_fn;
262
263 /* This is the core of this function. Depending on which
264 completer type the Python function returns, we have to
265 adjust the break characters accordingly. */
266 brkchars_fn = (completer_handle_brkchars_func_for_completer
267 (completers[value].completer));
268 brkchars_fn (command, tracker, text, word);
269 }
270 }
271 }
272
273 /* Called by gdb for command completion. */
274
275 static void
276 cmdpy_completer (struct cmd_list_element *command,
277 completion_tracker &tracker,
278 const char *text, const char *word)
279 {
280 gdbpy_enter enter_py (get_current_arch (), current_language);
281
282 /* Calling our helper to obtain a reference to the PyObject of the Python
283 function. */
284 gdbpy_ref<> resultobj = cmdpy_completer_helper (command, text, word);
285
286 /* If the result object of calling the Python function is NULL, it
287 means that there was an error. In this case, just give up. */
288 if (resultobj == NULL)
289 return;
290
291 if (PyInt_Check (resultobj.get ()))
292 {
293 /* User code may also return one of the completion constants,
294 thus requesting that sort of completion. */
295 long value;
296
297 if (! gdb_py_int_as_long (resultobj.get (), &value))
298 {
299 /* Ignore. */
300 PyErr_Clear ();
301 }
302 else if (value >= 0 && value < (long) N_COMPLETERS)
303 completers[value].completer (command, tracker, text, word);
304 }
305 else
306 {
307 gdbpy_ref<> iter (PyObject_GetIter (resultobj.get ()));
308
309 if (iter == NULL)
310 return;
311
312 bool got_matches = false;
313 while (true)
314 {
315 gdbpy_ref<> elt (PyIter_Next (iter.get ()));
316 if (elt == NULL)
317 break;
318
319 if (! gdbpy_is_string (elt.get ()))
320 {
321 /* Skip problem elements. */
322 continue;
323 }
324 gdb::unique_xmalloc_ptr<char>
325 item (python_string_to_host_string (elt.get ()));
326 if (item == NULL)
327 {
328 /* Skip problem elements. */
329 PyErr_Clear ();
330 continue;
331 }
332 tracker.add_completion (std::move (item));
333 got_matches = true;
334 }
335
336 /* If we got some results, ignore problems. Otherwise, report
337 the problem. */
338 if (got_matches && PyErr_Occurred ())
339 PyErr_Clear ();
340 }
341 }
342
343 /* Helper for cmdpy_init which locates the command list to use and
344 pulls out the command name.
345
346 NAME is the command name list. The final word in the list is the
347 name of the new command. All earlier words must be existing prefix
348 commands.
349
350 *BASE_LIST is set to the final prefix command's list of
351 *sub-commands.
352
353 START_LIST is the list in which the search starts.
354
355 This function returns the xmalloc()d name of the new command. On
356 error sets the Python error and returns NULL. */
357
358 char *
359 gdbpy_parse_command_name (const char *name,
360 struct cmd_list_element ***base_list,
361 struct cmd_list_element **start_list)
362 {
363 struct cmd_list_element *elt;
364 int len = strlen (name);
365 int i, lastchar;
366 const char *prefix_text2;
367 char *result;
368
369 /* Skip trailing whitespace. */
370 for (i = len - 1; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
371 ;
372 if (i < 0)
373 {
374 PyErr_SetString (PyExc_RuntimeError, _("No command name found."));
375 return NULL;
376 }
377 lastchar = i;
378
379 /* Find first character of the final word. */
380 for (; i > 0 && (isalnum (name[i - 1])
381 || name[i - 1] == '-'
382 || name[i - 1] == '_');
383 --i)
384 ;
385 result = (char *) xmalloc (lastchar - i + 2);
386 memcpy (result, &name[i], lastchar - i + 1);
387 result[lastchar - i + 1] = '\0';
388
389 /* Skip whitespace again. */
390 for (--i; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
391 ;
392 if (i < 0)
393 {
394 *base_list = start_list;
395 return result;
396 }
397
398 std::string prefix_text (name, i + 1);
399
400 prefix_text2 = prefix_text.c_str ();
401 elt = lookup_cmd_1 (&prefix_text2, *start_list, NULL, 1);
402 if (elt == NULL || elt == CMD_LIST_AMBIGUOUS)
403 {
404 PyErr_Format (PyExc_RuntimeError, _("Could not find command prefix %s."),
405 prefix_text.c_str ());
406 xfree (result);
407 return NULL;
408 }
409
410 if (elt->prefixlist)
411 {
412 *base_list = elt->prefixlist;
413 return result;
414 }
415
416 PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command."),
417 prefix_text.c_str ());
418 xfree (result);
419 return NULL;
420 }
421
422 /* Object initializer; sets up gdb-side structures for command.
423
424 Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
425
426 NAME is the name of the command. It may consist of multiple words,
427 in which case the final word is the name of the new command, and
428 earlier words must be prefix commands.
429
430 COMMAND_CLASS is the kind of command. It should be one of the COMMAND_*
431 constants defined in the gdb module.
432
433 COMPLETER_CLASS is the kind of completer. If not given, the
434 "complete" method will be used. Otherwise, it should be one of the
435 COMPLETE_* constants defined in the gdb module.
436
437 If PREFIX is True, then this command is a prefix command.
438
439 The documentation for the command is taken from the doc string for
440 the python class. */
441
442 static int
443 cmdpy_init (PyObject *self, PyObject *args, PyObject *kw)
444 {
445 cmdpy_object *obj = (cmdpy_object *) self;
446 const char *name;
447 int cmdtype;
448 int completetype = -1;
449 char *docstring = NULL;
450 struct cmd_list_element **cmd_list;
451 char *cmd_name, *pfx_name;
452 static const char *keywords[] = { "name", "command_class", "completer_class",
453 "prefix", NULL };
454 PyObject *is_prefix = NULL;
455 int cmp;
456
457 if (obj->command)
458 {
459 /* Note: this is apparently not documented in Python. We return
460 0 for success, -1 for failure. */
461 PyErr_Format (PyExc_RuntimeError,
462 _("Command object already initialized."));
463 return -1;
464 }
465
466 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "si|iO",
467 keywords, &name, &cmdtype,
468 &completetype, &is_prefix))
469 return -1;
470
471 if (cmdtype != no_class && cmdtype != class_run
472 && cmdtype != class_vars && cmdtype != class_stack
473 && cmdtype != class_files && cmdtype != class_support
474 && cmdtype != class_info && cmdtype != class_breakpoint
475 && cmdtype != class_trace && cmdtype != class_obscure
476 && cmdtype != class_maintenance && cmdtype != class_user)
477 {
478 PyErr_Format (PyExc_RuntimeError, _("Invalid command class argument."));
479 return -1;
480 }
481
482 if (completetype < -1 || completetype >= (int) N_COMPLETERS)
483 {
484 PyErr_Format (PyExc_RuntimeError,
485 _("Invalid completion type argument."));
486 return -1;
487 }
488
489 cmd_name = gdbpy_parse_command_name (name, &cmd_list, &cmdlist);
490 if (! cmd_name)
491 return -1;
492
493 pfx_name = NULL;
494 if (is_prefix != NULL)
495 {
496 cmp = PyObject_IsTrue (is_prefix);
497 if (cmp == 1)
498 {
499 int i, out;
500
501 /* Make a normalized form of the command name. */
502 pfx_name = (char *) xmalloc (strlen (name) + 2);
503
504 i = 0;
505 out = 0;
506 while (name[i])
507 {
508 /* Skip whitespace. */
509 while (name[i] == ' ' || name[i] == '\t')
510 ++i;
511 /* Copy non-whitespace characters. */
512 while (name[i] && name[i] != ' ' && name[i] != '\t')
513 pfx_name[out++] = name[i++];
514 /* Add a single space after each word -- including the final
515 word. */
516 pfx_name[out++] = ' ';
517 }
518 pfx_name[out] = '\0';
519 }
520 else if (cmp < 0)
521 {
522 xfree (cmd_name);
523 return -1;
524 }
525 }
526 if (PyObject_HasAttr (self, gdbpy_doc_cst))
527 {
528 gdbpy_ref<> ds_obj (PyObject_GetAttr (self, gdbpy_doc_cst));
529
530 if (ds_obj != NULL && gdbpy_is_string (ds_obj.get ()))
531 {
532 docstring = python_string_to_host_string (ds_obj.get ()).release ();
533 if (docstring == NULL)
534 {
535 xfree (cmd_name);
536 xfree (pfx_name);
537 return -1;
538 }
539 }
540 }
541 if (! docstring)
542 docstring = xstrdup (_("This command is not documented."));
543
544 gdbpy_ref<> self_ref = gdbpy_ref<>::new_reference (self);
545
546 TRY
547 {
548 struct cmd_list_element *cmd;
549
550 if (pfx_name)
551 {
552 int allow_unknown;
553
554 /* If we have our own "invoke" method, then allow unknown
555 sub-commands. */
556 allow_unknown = PyObject_HasAttr (self, invoke_cst);
557 cmd = add_prefix_cmd (cmd_name, (enum command_class) cmdtype,
558 NULL, docstring, &obj->sub_list,
559 pfx_name, allow_unknown, cmd_list);
560 }
561 else
562 cmd = add_cmd (cmd_name, (enum command_class) cmdtype,
563 docstring, cmd_list);
564
565 /* There appears to be no API to set this. */
566 cmd->func = cmdpy_function;
567 cmd->destroyer = cmdpy_destroyer;
568
569 obj->command = cmd;
570 set_cmd_context (cmd, self_ref.release ());
571 set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer
572 : completers[completetype].completer));
573 if (completetype == -1)
574 set_cmd_completer_handle_brkchars (cmd,
575 cmdpy_completer_handle_brkchars);
576 }
577 CATCH (except, RETURN_MASK_ALL)
578 {
579 xfree (cmd_name);
580 xfree (docstring);
581 xfree (pfx_name);
582 gdbpy_convert_exception (except);
583 return -1;
584 }
585 END_CATCH
586
587 return 0;
588 }
589
590
591
593 /* Initialize the 'commands' code. */
594
595 int
596 gdbpy_initialize_commands (void)
597 {
598 int i;
599
600 cmdpy_object_type.tp_new = PyType_GenericNew;
601 if (PyType_Ready (&cmdpy_object_type) < 0)
602 return -1;
603
604 /* Note: alias and user are special; pseudo appears to be unused,
605 and there is no reason to expose tui, I think. */
606 if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0
607 || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0
608 || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0
609 || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0
610 || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0
611 || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT",
612 class_support) < 0
613 || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0
614 || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS",
615 class_breakpoint) < 0
616 || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS",
617 class_trace) < 0
618 || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE",
619 class_obscure) < 0
620 || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE",
621 class_maintenance) < 0
622 || PyModule_AddIntConstant (gdb_module, "COMMAND_USER", class_user) < 0)
623 return -1;
624
625 for (i = 0; i < N_COMPLETERS; ++i)
626 {
627 if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0)
628 return -1;
629 }
630
631 if (gdb_pymodule_addobject (gdb_module, "Command",
632 (PyObject *) &cmdpy_object_type) < 0)
633 return -1;
634
635 invoke_cst = PyString_FromString ("invoke");
636 if (invoke_cst == NULL)
637 return -1;
638 complete_cst = PyString_FromString ("complete");
639 if (complete_cst == NULL)
640 return -1;
641
642 return 0;
643 }
644
645
646
648 static PyMethodDef cmdpy_object_methods[] =
649 {
650 { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS,
651 "Prevent command repetition when user enters empty line." },
652
653 { 0 }
654 };
655
656 PyTypeObject cmdpy_object_type =
657 {
658 PyVarObject_HEAD_INIT (NULL, 0)
659 "gdb.Command", /*tp_name*/
660 sizeof (cmdpy_object), /*tp_basicsize*/
661 0, /*tp_itemsize*/
662 0, /*tp_dealloc*/
663 0, /*tp_print*/
664 0, /*tp_getattr*/
665 0, /*tp_setattr*/
666 0, /*tp_compare*/
667 0, /*tp_repr*/
668 0, /*tp_as_number*/
669 0, /*tp_as_sequence*/
670 0, /*tp_as_mapping*/
671 0, /*tp_hash */
672 0, /*tp_call*/
673 0, /*tp_str*/
674 0, /*tp_getattro*/
675 0, /*tp_setattro*/
676 0, /*tp_as_buffer*/
677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
678 "GDB command object", /* tp_doc */
679 0, /* tp_traverse */
680 0, /* tp_clear */
681 0, /* tp_richcompare */
682 0, /* tp_weaklistoffset */
683 0, /* tp_iter */
684 0, /* tp_iternext */
685 cmdpy_object_methods, /* tp_methods */
686 0, /* tp_members */
687 0, /* tp_getset */
688 0, /* tp_base */
689 0, /* tp_dict */
690 0, /* tp_descr_get */
691 0, /* tp_descr_set */
692 0, /* tp_dictoffset */
693 cmdpy_init, /* tp_init */
694 0, /* tp_alloc */
695 };
696
697
698
700 /* Utility to build a buildargv-like result from ARGS.
701 This intentionally parses arguments the way libiberty/argv.c:buildargv
702 does. It splits up arguments in a reasonable way, and we want a standard
703 way of parsing arguments. Several gdb commands use buildargv to parse their
704 arguments. Plus we want to be able to write compatible python
705 implementations of gdb commands. */
706
707 PyObject *
708 gdbpy_string_to_argv (PyObject *self, PyObject *args)
709 {
710 const char *input;
711
712 if (!PyArg_ParseTuple (args, "s", &input))
713 return NULL;
714
715 gdbpy_ref<> py_argv (PyList_New (0));
716 if (py_argv == NULL)
717 return NULL;
718
719 /* buildargv uses NULL to represent an empty argument list, but we can't use
720 that in Python. Instead, if ARGS is "" then return an empty list.
721 This undoes the NULL -> "" conversion that cmdpy_function does. */
722
723 if (*input != '\0')
724 {
725 gdb_argv c_argv (input);
726
727 for (char *arg : c_argv)
728 {
729 gdbpy_ref<> argp (PyString_FromString (arg));
730
731 if (argp == NULL
732 || PyList_Append (py_argv.get (), argp.get ()) < 0)
733 return NULL;
734 }
735 }
736
737 return py_argv.release ();
738 }
739