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