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