OpenCores
URL https://opencores.org/ocsvn/openrisc_me/openrisc_me/trunk

Subversion Repositories openrisc_me

[/] [openrisc/] [trunk/] [gnu-src/] [gdb-7.2/] [gdb/] [python/] [py-cmd.c] - Blame information for rev 330

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.