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