]> Git Repo - binutils.git/blob - gdb/python/py-cmd.c
0998713491d32e6565b9b1ddab3a2abd76a7e743
[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 static void
92 cmdpy_destroyer (struct cmd_list_element *self, void *context)
93 {
94   cmdpy_object *cmd;
95   struct cleanup *cleanup;
96
97   cleanup = ensure_python_env (get_current_arch (), current_language);
98
99   /* Release our hold on the command object.  */
100   cmd = (cmdpy_object *) context;
101   cmd->command = NULL;
102   Py_DECREF (cmd);
103
104   /* We allocated the name, doc string, and perhaps the prefix
105      name.  */
106   xfree (self->name);
107   xfree (self->doc);
108   xfree (self->prefixname);
109
110   do_cleanups (cleanup);
111 }
112
113 /* Called by gdb to invoke the command.  */
114 static void
115 cmdpy_function (struct cmd_list_element *command, char *args, int from_tty)
116 {
117   cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
118   PyObject *argobj, *ttyobj, *result;
119   struct cleanup *cleanup;
120
121   cleanup = ensure_python_env (get_current_arch (), current_language);
122
123   if (! obj)
124     error (_("Invalid invocation of Python command object."));
125   if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst))
126     {
127       if (obj->command->prefixname)
128         {
129           /* A prefix command does not need an invoke method.  */
130           do_cleanups (cleanup);
131           return;
132         }
133       error (_("Python command object missing 'invoke' method."));
134     }
135
136   if (! args)
137     args = "";
138   argobj = PyUnicode_Decode (args, strlen (args), host_charset (), NULL);
139   if (! argobj)
140     error (_("Could not convert arguments to Python string."));
141
142   ttyobj = from_tty ? Py_True : Py_False;
143   Py_INCREF (ttyobj);
144   result = PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst, argobj,
145                                        ttyobj, NULL);
146   Py_DECREF (argobj);
147   Py_DECREF (ttyobj);
148   if (! result)
149     {
150       PyObject *ptype, *pvalue, *ptraceback;
151       char *s, *str;
152
153       PyErr_Fetch (&ptype, &pvalue, &ptraceback);
154
155       if (pvalue && PyString_Check (pvalue))
156         {
157           /* Make a temporary copy of the string data.  */
158           char *s = PyString_AsString (pvalue);
159           char *copy = alloca (strlen (s) + 1);
160           strcpy (copy, s);
161
162           PyErr_Restore (ptype, pvalue, ptraceback);
163           gdbpy_print_stack ();
164           error (_("Error occurred in Python command: %s"), copy);
165         }
166       else
167         {
168           PyErr_Restore (ptype, pvalue, ptraceback);
169           gdbpy_print_stack ();
170           error (_("Error occurred in Python command."));
171         }
172     }
173   Py_DECREF (result);
174   do_cleanups (cleanup);
175 }
176
177 /* Called by gdb for command completion.  */
178 static char **
179 cmdpy_completer (struct cmd_list_element *command, char *text, char *word)
180 {
181   cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
182   PyObject *textobj, *wordobj, *resultobj = NULL;
183   char **result = NULL;
184   struct cleanup *cleanup;
185
186   cleanup = ensure_python_env (get_current_arch (), current_language);
187
188   if (! obj)
189     error (_("Invalid invocation of Python command object."));
190   if (! PyObject_HasAttr ((PyObject *) obj, complete_cst))
191     {
192       /* If there is no complete method, don't error -- instead, just
193          say that there are no completions.  */
194       goto done;
195     }
196
197   textobj = PyUnicode_Decode (text, strlen (text), host_charset (), NULL);
198   if (! textobj)
199     error (_("Could not convert argument to Python string."));
200   wordobj = PyUnicode_Decode (word, strlen (word), host_charset (), NULL);
201   if (! wordobj)
202     error (_("Could not convert argument to Python string."));
203
204   resultobj = PyObject_CallMethodObjArgs ((PyObject *) obj, complete_cst,
205                                           textobj, wordobj, NULL);
206   Py_DECREF (textobj);
207   Py_DECREF (wordobj);
208   if (! resultobj)
209     {
210       /* Just swallow errors here.  */
211       PyErr_Clear ();
212       goto done;
213     }
214   make_cleanup_py_decref (resultobj);
215
216   result = NULL;
217   if (PySequence_Check (resultobj))
218     {
219       Py_ssize_t i, len = PySequence_Size (resultobj);
220       Py_ssize_t out;
221       if (len < 0)
222         goto done;
223
224       result = (char **) xmalloc ((len + 1) * sizeof (char *));
225       for (i = out = 0; i < len; ++i)
226         {
227           int l;
228           PyObject *elt = PySequence_GetItem (resultobj, i);
229           if (elt == NULL || ! gdbpy_is_string (elt))
230             {
231               /* Skip problem elements.  */
232               PyErr_Clear ();
233               continue;
234             }
235           result[out] = python_string_to_host_string (elt);
236           ++out;
237         }
238       result[out] = NULL;
239     }
240   else if (PyInt_Check (resultobj))
241     {
242       /* User code may also return one of the completion constants,
243          thus requesting that sort of completion.  */
244       long value = PyInt_AsLong (resultobj);
245       if (value >= 0 && value < (long) N_COMPLETERS)
246         result = completers[value].completer (command, text, word);
247     }
248
249  done:
250
251   do_cleanups (cleanup);
252
253   return result;
254 }
255
256 /* Helper for cmdpy_init which locates the command list to use and
257    pulls out the command name.
258    
259    TEXT is the command name list.  The final word in the list is the
260    name of the new command.  All earlier words must be existing prefix
261    commands.
262
263    *BASE_LIST is set to the final prefix command's list of
264    *sub-commands.
265    
266    START_LIST is the list in which the search starts.
267
268    This function returns the xmalloc()d name of the new command.  On
269    error sets the Python error and returns NULL.  */
270 char *
271 gdbpy_parse_command_name (char *text,
272                           struct cmd_list_element ***base_list,
273                           struct cmd_list_element **start_list)
274 {
275   struct cmd_list_element *elt;
276   int len = strlen (text);
277   int i, lastchar;
278   char *prefix_text;
279   char *result;
280
281   /* Skip trailing whitespace.  */
282   for (i = len - 1; i >= 0 && (text[i] == ' ' || text[i] == '\t'); --i)
283     ;
284   if (i < 0)
285     {
286       PyErr_SetString (PyExc_RuntimeError, _("No command name found."));
287       return NULL;
288     }
289   lastchar = i;
290
291   /* Find first character of the final word.  */
292   for (; i > 0 && (isalnum (text[i - 1])
293                    || text[i - 1] == '-'
294                    || text[i - 1] == '_');
295        --i)
296     ;
297   result = xmalloc (lastchar - i + 2);
298   memcpy (result, &text[i], lastchar - i + 1);
299   result[lastchar - i + 1] = '\0';
300
301   /* Skip whitespace again.  */
302   for (--i; i >= 0 && (text[i] == ' ' || text[i] == '\t'); --i)
303     ;
304   if (i < 0)
305     {
306       *base_list = start_list;
307       return result;
308     }
309
310   prefix_text = xmalloc (i + 2);
311   memcpy (prefix_text, text, i + 1);
312   prefix_text[i + 1] = '\0';
313
314   text = prefix_text;
315   elt = lookup_cmd_1 (&text, *start_list, NULL, 1);
316   if (!elt || elt == (struct cmd_list_element *) -1)
317     {
318       PyErr_Format (PyExc_RuntimeError, _("Could not find command prefix %s."),
319                     prefix_text);
320       xfree (prefix_text);
321       xfree (result);
322       return NULL;
323     }
324
325   if (elt->prefixlist)
326     {
327       xfree (prefix_text);
328       *base_list = elt->prefixlist;
329       return result;
330     }
331
332   PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command."),
333                 prefix_text);
334   xfree (prefix_text);
335   xfree (result);
336   return NULL;
337 }
338
339 /* Object initializer; sets up gdb-side structures for command.
340
341    Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).
342
343    NAME is the name of the command.  It may consist of multiple words,
344    in which case the final word is the name of the new command, and
345    earlier words must be prefix commands.
346
347    COMMAND_CLASS is the kind of command.  It should be one of the COMMAND_*
348    constants defined in the gdb module.
349
350    COMPLETER_CLASS is the kind of completer.  If not given, the
351    "complete" method will be used.  Otherwise, it should be one of the
352    COMPLETE_* constants defined in the gdb module.
353
354    If PREFIX is True, then this command is a prefix command.
355
356    The documentation for the command is taken from the doc string for
357    the python class.
358    
359 */
360 static int
361 cmdpy_init (PyObject *self, PyObject *args, PyObject *kw)
362 {
363   cmdpy_object *obj = (cmdpy_object *) self;
364   char *name;
365   int cmdtype;
366   int completetype = -1;
367   char *docstring = NULL;
368   volatile struct gdb_exception except;
369   struct cmd_list_element **cmd_list;
370   char *cmd_name, *pfx_name;
371   static char *keywords[] = { "name", "command_class", "completer_class",
372                               "prefix", NULL };
373   PyObject *is_prefix = NULL;
374   int cmp;
375
376   if (obj->command)
377     {
378       /* Note: this is apparently not documented in Python.  We return
379          0 for success, -1 for failure.  */
380       PyErr_Format (PyExc_RuntimeError,
381                     _("Command object already initialized."));
382       return -1;
383     }
384
385   if (! PyArg_ParseTupleAndKeywords (args, kw, "si|iO", keywords, &name, &cmdtype,
386                           &completetype, &is_prefix))
387     return -1;
388
389   if (cmdtype != no_class && cmdtype != class_run
390       && cmdtype != class_vars && cmdtype != class_stack
391       && cmdtype != class_files && cmdtype != class_support
392       && cmdtype != class_info && cmdtype != class_breakpoint
393       && cmdtype != class_trace && cmdtype != class_obscure
394       && cmdtype != class_maintenance)
395     {
396       PyErr_Format (PyExc_RuntimeError, _("Invalid command class argument."));
397       return -1;
398     }
399
400   if (completetype < -1 || completetype >= (int) N_COMPLETERS)
401     {
402       PyErr_Format (PyExc_RuntimeError, _("Invalid completion type argument."));
403       return -1;
404     }
405
406   cmd_name = gdbpy_parse_command_name (name, &cmd_list, &cmdlist);
407   if (! cmd_name)
408     return -1;
409
410   pfx_name = NULL;
411   if (is_prefix != NULL) 
412     {
413       cmp = PyObject_IsTrue (is_prefix);
414       if (cmp == 1)
415         {
416           int i, out;
417           
418           /* Make a normalized form of the command name.  */
419           pfx_name = xmalloc (strlen (name) + 2);
420           
421           i = 0;
422           out = 0;
423           while (name[i])
424             {
425               /* Skip whitespace.  */
426               while (name[i] == ' ' || name[i] == '\t')
427                 ++i;
428               /* Copy non-whitespace characters.  */
429               while (name[i] && name[i] != ' ' && name[i] != '\t')
430                 pfx_name[out++] = name[i++];
431               /* Add a single space after each word -- including the final
432                  word.  */
433               pfx_name[out++] = ' ';
434             }
435           pfx_name[out] = '\0';
436         }
437       else if (cmp < 0)
438           return -1;
439     }
440   if (PyObject_HasAttr (self, gdbpy_doc_cst))
441     {
442       PyObject *ds_obj = PyObject_GetAttr (self, gdbpy_doc_cst);
443       if (ds_obj && gdbpy_is_string (ds_obj))
444         docstring = python_string_to_host_string (ds_obj);
445     }
446   if (! docstring)
447     docstring = xstrdup (_("This command is not documented."));
448
449   Py_INCREF (self);
450
451   TRY_CATCH (except, RETURN_MASK_ALL)
452     {
453       struct cmd_list_element *cmd;
454
455       if (pfx_name)
456         {
457           int allow_unknown;
458
459           /* If we have our own "invoke" method, then allow unknown
460              sub-commands.  */
461           allow_unknown = PyObject_HasAttr (self, invoke_cst);
462           cmd = add_prefix_cmd (cmd_name, (enum command_class) cmdtype,
463                                 NULL, docstring, &obj->sub_list,
464                                 pfx_name, allow_unknown, cmd_list);
465         }
466       else
467         cmd = add_cmd (cmd_name, (enum command_class) cmdtype, NULL,
468                        docstring, cmd_list);
469
470       /* There appears to be no API to set this.  */
471       cmd->func = cmdpy_function;
472       cmd->destroyer = cmdpy_destroyer;
473
474       obj->command = cmd;
475       set_cmd_context (cmd, self);
476       set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer
477                                : completers[completetype].completer));
478     }
479   if (except.reason < 0)
480     {
481       xfree (cmd_name);
482       xfree (docstring);
483       xfree (pfx_name);
484       Py_DECREF (self);
485       PyErr_Format (except.reason == RETURN_QUIT
486                     ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
487                     "%s", except.message);
488       return -1;
489     }
490   return 0;
491 }
492
493 \f
494
495 /* Initialize the 'commands' code.  */
496 void
497 gdbpy_initialize_commands (void)
498 {
499   int i;
500
501   if (PyType_Ready (&cmdpy_object_type) < 0)
502     return;
503
504   /* Note: alias and user are special; pseudo appears to be unused,
505      and there is no reason to expose tui or xdb, I think.  */
506   if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0
507       || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0
508       || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0
509       || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0
510       || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0
511       || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT",
512                                   class_support) < 0
513       || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0
514       || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS",
515                                   class_breakpoint) < 0
516       || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS",
517                                   class_trace) < 0
518       || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE",
519                                   class_obscure) < 0
520       || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE",
521                                   class_maintenance) < 0)
522     return;
523
524   for (i = 0; i < N_COMPLETERS; ++i)
525     {
526       if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0)
527         return;
528     }
529
530   Py_INCREF (&cmdpy_object_type);
531   PyModule_AddObject (gdb_module, "Command",
532                       (PyObject *) &cmdpy_object_type);
533
534   invoke_cst = PyString_FromString ("invoke");
535   complete_cst = PyString_FromString ("complete");
536 }
537
538 \f
539
540 static PyMethodDef cmdpy_object_methods[] =
541 {
542   { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS,
543     "Prevent command repetition when user enters empty line." },
544
545   { 0 }
546 };
547
548 static PyTypeObject cmdpy_object_type =
549 {
550   PyObject_HEAD_INIT (NULL)
551   0,                              /*ob_size*/
552   "gdb.Command",                  /*tp_name*/
553   sizeof (cmdpy_object),          /*tp_basicsize*/
554   0,                              /*tp_itemsize*/
555   0,                              /*tp_dealloc*/
556   0,                              /*tp_print*/
557   0,                              /*tp_getattr*/
558   0,                              /*tp_setattr*/
559   0,                              /*tp_compare*/
560   0,                              /*tp_repr*/
561   0,                              /*tp_as_number*/
562   0,                              /*tp_as_sequence*/
563   0,                              /*tp_as_mapping*/
564   0,                              /*tp_hash */
565   0,                              /*tp_call*/
566   0,                              /*tp_str*/
567   0,                              /*tp_getattro*/
568   0,                              /*tp_setattro*/
569   0,                              /*tp_as_buffer*/
570   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
571   "GDB command object",           /* tp_doc */
572   0,                              /* tp_traverse */
573   0,                              /* tp_clear */
574   0,                              /* tp_richcompare */
575   0,                              /* tp_weaklistoffset */
576   0,                              /* tp_iter */
577   0,                              /* tp_iternext */
578   cmdpy_object_methods,           /* tp_methods */
579   0,                              /* tp_members */
580   0,                              /* tp_getset */
581   0,                              /* tp_base */
582   0,                              /* tp_dict */
583   0,                              /* tp_descr_get */
584   0,                              /* tp_descr_set */
585   0,                              /* tp_dictoffset */
586   cmdpy_init,                     /* tp_init */
587   0,                              /* tp_alloc */
588   PyType_GenericNew               /* tp_new */
589 };
This page took 0.050262 seconds and 2 git commands to generate.