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