gdb/python/py-cmd.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* gdb commands implemented in Python

  2.    Copyright (C) 2008-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */


  14. #include "defs.h"
  15. #include "arch-utils.h"
  16. #include "value.h"
  17. #include "python-internal.h"
  18. #include "charset.h"
  19. #include "gdbcmd.h"
  20. #include "cli/cli-decode.h"
  21. #include "completer.h"
  22. #include "language.h"

  23. /* Struct representing built-in completion types.  */
  24. struct cmdpy_completer
  25. {
  26.   /* Python symbol name.
  27.      This isn't a const char * for Python 2.4's sake.
  28.      PyModule_AddIntConstant only takes a char *, sigh.  */
  29.   char *name;
  30.   /* Completion function.  */
  31.   completer_ftype *completer;
  32. };

  33. static const struct cmdpy_completer completers[] =
  34. {
  35.   { "COMPLETE_NONE", noop_completer },
  36.   { "COMPLETE_FILENAME", filename_completer },
  37.   { "COMPLETE_LOCATION", location_completer },
  38.   { "COMPLETE_COMMAND", command_completer },
  39.   { "COMPLETE_SYMBOL", make_symbol_completion_list_fn },
  40.   { "COMPLETE_EXPRESSION", expression_completer },
  41. };

  42. #define N_COMPLETERS (sizeof (completers) / sizeof (completers[0]))

  43. /* A gdb command.  For the time being only ordinary commands (not
  44.    set/show commands) are allowed.  */
  45. struct cmdpy_object
  46. {
  47.   PyObject_HEAD

  48.   /* The corresponding gdb command object, or NULL if the command is
  49.      no longer installed.  */
  50.   struct cmd_list_element *command;

  51.   /* A prefix command requires storage for a list of its sub-commands.
  52.      A pointer to this is passed to add_prefix_command, and to add_cmd
  53.      for sub-commands of that prefix.  If this Command is not a prefix
  54.      command, then this field is unused.  */
  55.   struct cmd_list_element *sub_list;
  56. };

  57. typedef struct cmdpy_object cmdpy_object;

  58. static PyTypeObject cmdpy_object_type
  59.     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("cmdpy_object");

  60. /* Constants used by this module.  */
  61. static PyObject *invoke_cst;
  62. static PyObject *complete_cst;



  63. /* Python function which wraps dont_repeat.  */
  64. static PyObject *
  65. cmdpy_dont_repeat (PyObject *self, PyObject *args)
  66. {
  67.   dont_repeat ();
  68.   Py_RETURN_NONE;
  69. }



  70. /* Called if the gdb cmd_list_element is destroyed.  */

  71. static void
  72. cmdpy_destroyer (struct cmd_list_element *self, void *context)
  73. {
  74.   cmdpy_object *cmd;
  75.   struct cleanup *cleanup;

  76.   cleanup = ensure_python_env (get_current_arch (), current_language);

  77.   /* Release our hold on the command object.  */
  78.   cmd = (cmdpy_object *) context;
  79.   cmd->command = NULL;
  80.   Py_DECREF (cmd);

  81.   /* We allocated the name, doc string, and perhaps the prefix
  82.      name.  */
  83.   xfree ((char *) self->name);
  84.   xfree ((char *) self->doc);
  85.   xfree ((char *) self->prefixname);

  86.   do_cleanups (cleanup);
  87. }

  88. /* Called by gdb to invoke the command.  */

  89. static void
  90. cmdpy_function (struct cmd_list_element *command, char *args, int from_tty)
  91. {
  92.   cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
  93.   PyObject *argobj, *ttyobj, *result;
  94.   struct cleanup *cleanup;

  95.   cleanup = ensure_python_env (get_current_arch (), current_language);

  96.   if (! obj)
  97.     error (_("Invalid invocation of Python command object."));
  98.   if (! PyObject_HasAttr ((PyObject *) obj, invoke_cst))
  99.     {
  100.       if (obj->command->prefixname)
  101.         {
  102.           /* A prefix command does not need an invoke method.  */
  103.           do_cleanups (cleanup);
  104.           return;
  105.         }
  106.       error (_("Python command object missing 'invoke' method."));
  107.     }

  108.   if (! args)
  109.     args = "";
  110.   argobj = PyUnicode_Decode (args, strlen (args), host_charset (), NULL);
  111.   if (! argobj)
  112.     {
  113.       gdbpy_print_stack ();
  114.       error (_("Could not convert arguments to Python string."));
  115.     }

  116.   ttyobj = from_tty ? Py_True : Py_False;
  117.   Py_INCREF (ttyobj);
  118.   result = PyObject_CallMethodObjArgs ((PyObject *) obj, invoke_cst, argobj,
  119.                                        ttyobj, NULL);
  120.   Py_DECREF (argobj);
  121.   Py_DECREF (ttyobj);

  122.   if (! result)
  123.     {
  124.       PyObject *ptype, *pvalue, *ptraceback;
  125.       char *msg;

  126.       PyErr_Fetch (&ptype, &pvalue, &ptraceback);

  127.       /* Try to fetch an error message contained within ptype, pvalue.
  128.          When fetching the error message we need to make our own copy,
  129.          we no longer own ptype, pvalue after the call to PyErr_Restore.  */

  130.       msg = gdbpy_exception_to_string (ptype, pvalue);
  131.       make_cleanup (xfree, msg);

  132.       if (msg == NULL)
  133.         {
  134.           /* An error occurred computing the string representation of the
  135.              error message.  This is rare, but we should inform the user.  */
  136.           printf_filtered (_("An error occurred in a Python command\n"
  137.                              "and then another occurred computing the "
  138.                              "error message.\n"));
  139.           gdbpy_print_stack ();
  140.         }

  141.       /* Don't print the stack for gdb.GdbError exceptions.
  142.          It is generally used to flag user errors.

  143.          We also don't want to print "Error occurred in Python command"
  144.          for user errors.  However, a missing message for gdb.GdbError
  145.          exceptions is arguably a bug, so we flag it as such.  */

  146.       if (! PyErr_GivenExceptionMatches (ptype, gdbpy_gdberror_exc)
  147.           || msg == NULL || *msg == '\0')
  148.         {
  149.           PyErr_Restore (ptype, pvalue, ptraceback);
  150.           gdbpy_print_stack ();
  151.           if (msg != NULL && *msg != '\0')
  152.             error (_("Error occurred in Python command: %s"), msg);
  153.           else
  154.             error (_("Error occurred in Python command."));
  155.         }
  156.       else
  157.         {
  158.           Py_XDECREF (ptype);
  159.           Py_XDECREF (pvalue);
  160.           Py_XDECREF (ptraceback);
  161.           error ("%s", msg);
  162.         }
  163.     }

  164.   Py_DECREF (result);
  165.   do_cleanups (cleanup);
  166. }

  167. /* Helper function for the Python command completers (both "pure"
  168.    completer and brkchar handler).  This function takes COMMAND, TEXT
  169.    and WORD and tries to call the Python method for completion with
  170.    these arguments.  It also takes HANDLE_BRKCHARS_P, an argument to
  171.    identify whether it is being called from the brkchar handler or
  172.    from the "pure" completer.  In the first case, it effectively calls
  173.    the Python method for completion, and records the PyObject in a
  174.    static variable (used as a "cache").  In the second case, it just
  175.    returns that variable, without actually calling the Python method
  176.    again.  This saves us one Python method call.

  177.    The reason for this two step dance is that we need to know the set
  178.    of "brkchars" to use early on, before we actually try to perform
  179.    the completion.  But if a Python command supplies a "complete"
  180.    method then we have to call that method first: it may return as its
  181.    result the kind of completion to perform and that will in turn
  182.    specify which brkchars to use.  IOW, we need the result of the
  183.    "complete" method before we actually perform the completion.

  184.    It is important to mention that this function is built on the
  185.    assumption that the calls to cmdpy_completer_handle_brkchars and
  186.    cmdpy_completer will be subsequent with nothing intervening.  This
  187.    is true for our completer mechanism.

  188.    This function returns the PyObject representing the Python method
  189.    call.  */

  190. static PyObject *
  191. cmdpy_completer_helper (struct cmd_list_element *command,
  192.                         const char *text, const char *word,
  193.                         int handle_brkchars_p)
  194. {
  195.   cmdpy_object *obj = (cmdpy_object *) get_cmd_context (command);
  196.   PyObject *textobj, *wordobj;
  197.   /* This static variable will server as a "cache" for us, in order to
  198.      store the PyObject that results from calling the Python
  199.      function.  */
  200.   static PyObject *resultobj = NULL;

  201.   if (handle_brkchars_p)
  202.     {
  203.       /* If we were called to handle brkchars, it means this is the
  204.          first function call of two that will happen in a row.
  205.          Therefore, we need to call the completer ourselves, and cache
  206.          the return value in the static variable RESULTOBJ.  Then, in
  207.          the second call, we can just use the value of RESULTOBJ to do
  208.          our job.  */
  209.       if (resultobj != NULL)
  210.         Py_DECREF (resultobj);

  211.       resultobj = NULL;
  212.       if (obj == NULL)
  213.         error (_("Invalid invocation of Python command object."));
  214.       if (!PyObject_HasAttr ((PyObject *) obj, complete_cst))
  215.         {
  216.           /* If there is no complete method, don't error.  */
  217.           return NULL;
  218.         }

  219.       textobj = PyUnicode_Decode (text, strlen (text), host_charset (), NULL);
  220.       if (textobj == NULL)
  221.         error (_("Could not convert argument to Python string."));
  222.       wordobj = PyUnicode_Decode (word, sizeof (word), host_charset (), NULL);
  223.       if (wordobj == NULL)
  224.         {
  225.           Py_DECREF (textobj);
  226.           error (_("Could not convert argument to Python string."));
  227.         }

  228.       resultobj = PyObject_CallMethodObjArgs ((PyObject *) obj, complete_cst,
  229.                                               textobj, wordobj, NULL);
  230.       Py_DECREF (textobj);
  231.       Py_DECREF (wordobj);
  232.       if (!resultobj)
  233.         {
  234.           /* Just swallow errors here.  */
  235.           PyErr_Clear ();
  236.         }

  237.       Py_XINCREF (resultobj);
  238.     }

  239.   return resultobj;
  240. }

  241. /* Python function called to determine the break characters of a
  242.    certain completer.  We are only interested in knowing if the
  243.    completer registered by the user will return one of the integer
  244.    codes (see COMPLETER_* symbols).  */

  245. static void
  246. cmdpy_completer_handle_brkchars (struct cmd_list_element *command,
  247.                                  const char *text, const char *word)
  248. {
  249.   PyObject *resultobj = NULL;
  250.   struct cleanup *cleanup;

  251.   cleanup = ensure_python_env (get_current_arch (), current_language);

  252.   /* Calling our helper to obtain the PyObject of the Python
  253.      function.  */
  254.   resultobj = cmdpy_completer_helper (command, text, word, 1);

  255.   /* Check if there was an error.  */
  256.   if (resultobj == NULL)
  257.     goto done;

  258.   if (PyInt_Check (resultobj))
  259.     {
  260.       /* User code may also return one of the completion constants,
  261.          thus requesting that sort of completion.  We are only
  262.          interested in this kind of return.  */
  263.       long value;

  264.       if (!gdb_py_int_as_long (resultobj, &value))
  265.         {
  266.           /* Ignore.  */
  267.           PyErr_Clear ();
  268.         }
  269.       else if (value >= 0 && value < (long) N_COMPLETERS)
  270.         {
  271.           /* This is the core of this function.  Depending on which
  272.              completer type the Python function returns, we have to
  273.              adjust the break characters accordingly.  */
  274.           set_gdb_completion_word_break_characters
  275.             (completers[value].completer);
  276.         }
  277.     }

  278. done:

  279.   /* We do not call Py_XDECREF here because RESULTOBJ will be used in
  280.      the subsequent call to cmdpy_completer function.  */
  281.   do_cleanups (cleanup);
  282. }

  283. /* Called by gdb for command completion.  */

  284. static VEC (char_ptr) *
  285. cmdpy_completer (struct cmd_list_element *command,
  286.                  const char *text, const char *word)
  287. {
  288.   PyObject *resultobj = NULL;
  289.   VEC (char_ptr) *result = NULL;
  290.   struct cleanup *cleanup;

  291.   cleanup = ensure_python_env (get_current_arch (), current_language);

  292.   /* Calling our helper to obtain the PyObject of the Python
  293.      function.  */
  294.   resultobj = cmdpy_completer_helper (command, text, word, 0);

  295.   /* If the result object of calling the Python function is NULL, it
  296.      means that there was an error.  In this case, just give up and
  297.      return NULL.  */
  298.   if (resultobj == NULL)
  299.     goto done;

  300.   result = NULL;
  301.   if (PyInt_Check (resultobj))
  302.     {
  303.       /* User code may also return one of the completion constants,
  304.          thus requesting that sort of completion.  */
  305.       long value;

  306.       if (! gdb_py_int_as_long (resultobj, &value))
  307.         {
  308.           /* Ignore.  */
  309.           PyErr_Clear ();
  310.         }
  311.       else if (value >= 0 && value < (long) N_COMPLETERS)
  312.         result = completers[value].completer (command, text, word);
  313.     }
  314.   else
  315.     {
  316.       PyObject *iter = PyObject_GetIter (resultobj);
  317.       PyObject *elt;

  318.       if (iter == NULL)
  319.         goto done;

  320.       while ((elt = PyIter_Next (iter)) != NULL)
  321.         {
  322.           char *item;

  323.           if (! gdbpy_is_string (elt))
  324.             {
  325.               /* Skip problem elements.  */
  326.               Py_DECREF (elt);
  327.               continue;
  328.             }
  329.           item = python_string_to_host_string (elt);
  330.           Py_DECREF (elt);
  331.           if (item == NULL)
  332.             {
  333.               /* Skip problem elements.  */
  334.               PyErr_Clear ();
  335.               continue;
  336.             }
  337.           VEC_safe_push (char_ptr, result, item);
  338.         }

  339.       Py_DECREF (iter);

  340.       /* If we got some results, ignore problems.  Otherwise, report
  341.          the problem.  */
  342.       if (result != NULL && PyErr_Occurred ())
  343.         PyErr_Clear ();
  344.     }

  345. done:

  346.   do_cleanups (cleanup);

  347.   return result;
  348. }

  349. /* Helper for cmdpy_init which locates the command list to use and
  350.    pulls out the command name.

  351.    NAME is the command name list.  The final word in the list is the
  352.    name of the new command.  All earlier words must be existing prefix
  353.    commands.

  354.    *BASE_LIST is set to the final prefix command's list of
  355.    *sub-commands.

  356.    START_LIST is the list in which the search starts.

  357.    This function returns the xmalloc()d name of the new command.  On
  358.    error sets the Python error and returns NULL.  */

  359. char *
  360. gdbpy_parse_command_name (const char *name,
  361.                           struct cmd_list_element ***base_list,
  362.                           struct cmd_list_element **start_list)
  363. {
  364.   struct cmd_list_element *elt;
  365.   int len = strlen (name);
  366.   int i, lastchar;
  367.   char *prefix_text;
  368.   const char *prefix_text2;
  369.   char *result;

  370.   /* Skip trailing whitespace.  */
  371.   for (i = len - 1; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
  372.     ;
  373.   if (i < 0)
  374.     {
  375.       PyErr_SetString (PyExc_RuntimeError, _("No command name found."));
  376.       return NULL;
  377.     }
  378.   lastchar = i;

  379.   /* Find first character of the final word.  */
  380.   for (; i > 0 && (isalnum (name[i - 1])
  381.                    || name[i - 1] == '-'
  382.                    || name[i - 1] == '_');
  383.        --i)
  384.     ;
  385.   result = xmalloc (lastchar - i + 2);
  386.   memcpy (result, &name[i], lastchar - i + 1);
  387.   result[lastchar - i + 1] = '\0';

  388.   /* Skip whitespace again.  */
  389.   for (--i; i >= 0 && (name[i] == ' ' || name[i] == '\t'); --i)
  390.     ;
  391.   if (i < 0)
  392.     {
  393.       *base_list = start_list;
  394.       return result;
  395.     }

  396.   prefix_text = xmalloc (i + 2);
  397.   memcpy (prefix_text, name, i + 1);
  398.   prefix_text[i + 1] = '\0';

  399.   prefix_text2 = prefix_text;
  400.   elt = lookup_cmd_1 (&prefix_text2, *start_list, NULL, 1);
  401.   if (elt == NULL || elt == CMD_LIST_AMBIGUOUS)
  402.     {
  403.       PyErr_Format (PyExc_RuntimeError, _("Could not find command prefix %s."),
  404.                     prefix_text);
  405.       xfree (prefix_text);
  406.       xfree (result);
  407.       return NULL;
  408.     }

  409.   if (elt->prefixlist)
  410.     {
  411.       xfree (prefix_text);
  412.       *base_list = elt->prefixlist;
  413.       return result;
  414.     }

  415.   PyErr_Format (PyExc_RuntimeError, _("'%s' is not a prefix command."),
  416.                 prefix_text);
  417.   xfree (prefix_text);
  418.   xfree (result);
  419.   return NULL;
  420. }

  421. /* Object initializer; sets up gdb-side structures for command.

  422.    Use: __init__(NAME, COMMAND_CLASS [, COMPLETER_CLASS][, PREFIX]]).

  423.    NAME is the name of the command.  It may consist of multiple words,
  424.    in which case the final word is the name of the new command, and
  425.    earlier words must be prefix commands.

  426.    COMMAND_CLASS is the kind of command.  It should be one of the COMMAND_*
  427.    constants defined in the gdb module.

  428.    COMPLETER_CLASS is the kind of completer.  If not given, the
  429.    "complete" method will be used.  Otherwise, it should be one of the
  430.    COMPLETE_* constants defined in the gdb module.

  431.    If PREFIX is True, then this command is a prefix command.

  432.    The documentation for the command is taken from the doc string for
  433.    the python class.  */

  434. static int
  435. cmdpy_init (PyObject *self, PyObject *args, PyObject *kw)
  436. {
  437.   cmdpy_object *obj = (cmdpy_object *) self;
  438.   const char *name;
  439.   int cmdtype;
  440.   int completetype = -1;
  441.   char *docstring = NULL;
  442.   volatile struct gdb_exception except;
  443.   struct cmd_list_element **cmd_list;
  444.   char *cmd_name, *pfx_name;
  445.   static char *keywords[] = { "name", "command_class", "completer_class",
  446.                               "prefix", NULL };
  447.   PyObject *is_prefix = NULL;
  448.   int cmp;

  449.   if (obj->command)
  450.     {
  451.       /* Note: this is apparently not documented in Python.  We return
  452.          0 for success, -1 for failure.  */
  453.       PyErr_Format (PyExc_RuntimeError,
  454.                     _("Command object already initialized."));
  455.       return -1;
  456.     }

  457.   if (! PyArg_ParseTupleAndKeywords (args, kw, "si|iO",
  458.                                      keywords, &name, &cmdtype,
  459.                           &completetype, &is_prefix))
  460.     return -1;

  461.   if (cmdtype != no_class && cmdtype != class_run
  462.       && cmdtype != class_vars && cmdtype != class_stack
  463.       && cmdtype != class_files && cmdtype != class_support
  464.       && cmdtype != class_info && cmdtype != class_breakpoint
  465.       && cmdtype != class_trace && cmdtype != class_obscure
  466.       && cmdtype != class_maintenance && cmdtype != class_user)
  467.     {
  468.       PyErr_Format (PyExc_RuntimeError, _("Invalid command class argument."));
  469.       return -1;
  470.     }

  471.   if (completetype < -1 || completetype >= (int) N_COMPLETERS)
  472.     {
  473.       PyErr_Format (PyExc_RuntimeError,
  474.                     _("Invalid completion type argument."));
  475.       return -1;
  476.     }

  477.   cmd_name = gdbpy_parse_command_name (name, &cmd_list, &cmdlist);
  478.   if (! cmd_name)
  479.     return -1;

  480.   pfx_name = NULL;
  481.   if (is_prefix != NULL)
  482.     {
  483.       cmp = PyObject_IsTrue (is_prefix);
  484.       if (cmp == 1)
  485.         {
  486.           int i, out;

  487.           /* Make a normalized form of the command name.  */
  488.           pfx_name = xmalloc (strlen (name) + 2);

  489.           i = 0;
  490.           out = 0;
  491.           while (name[i])
  492.             {
  493.               /* Skip whitespace.  */
  494.               while (name[i] == ' ' || name[i] == '\t')
  495.                 ++i;
  496.               /* Copy non-whitespace characters.  */
  497.               while (name[i] && name[i] != ' ' && name[i] != '\t')
  498.                 pfx_name[out++] = name[i++];
  499.               /* Add a single space after each word -- including the final
  500.                  word.  */
  501.               pfx_name[out++] = ' ';
  502.             }
  503.           pfx_name[out] = '\0';
  504.         }
  505.       else if (cmp < 0)
  506.         {
  507.           xfree (cmd_name);
  508.           return -1;
  509.         }
  510.     }
  511.   if (PyObject_HasAttr (self, gdbpy_doc_cst))
  512.     {
  513.       PyObject *ds_obj = PyObject_GetAttr (self, gdbpy_doc_cst);

  514.       if (ds_obj && gdbpy_is_string (ds_obj))
  515.         {
  516.           docstring = python_string_to_host_string (ds_obj);
  517.           if (docstring == NULL)
  518.             {
  519.               xfree (cmd_name);
  520.               xfree (pfx_name);
  521.               Py_DECREF (ds_obj);
  522.               return -1;
  523.             }
  524.         }

  525.       Py_XDECREF (ds_obj);
  526.     }
  527.   if (! docstring)
  528.     docstring = xstrdup (_("This command is not documented."));

  529.   Py_INCREF (self);

  530.   TRY_CATCH (except, RETURN_MASK_ALL)
  531.     {
  532.       struct cmd_list_element *cmd;

  533.       if (pfx_name)
  534.         {
  535.           int allow_unknown;

  536.           /* If we have our own "invoke" method, then allow unknown
  537.              sub-commands.  */
  538.           allow_unknown = PyObject_HasAttr (self, invoke_cst);
  539.           cmd = add_prefix_cmd (cmd_name, (enum command_class) cmdtype,
  540.                                 NULL, docstring, &obj->sub_list,
  541.                                 pfx_name, allow_unknown, cmd_list);
  542.         }
  543.       else
  544.         cmd = add_cmd (cmd_name, (enum command_class) cmdtype, NULL,
  545.                        docstring, cmd_list);

  546.       /* There appears to be no API to set this.  */
  547.       cmd->func = cmdpy_function;
  548.       cmd->destroyer = cmdpy_destroyer;

  549.       obj->command = cmd;
  550.       set_cmd_context (cmd, self);
  551.       set_cmd_completer (cmd, ((completetype == -1) ? cmdpy_completer
  552.                                : completers[completetype].completer));
  553.       if (completetype == -1)
  554.         set_cmd_completer_handle_brkchars (cmd,
  555.                                            cmdpy_completer_handle_brkchars);
  556.     }
  557.   if (except.reason < 0)
  558.     {
  559.       xfree (cmd_name);
  560.       xfree (docstring);
  561.       xfree (pfx_name);
  562.       Py_DECREF (self);
  563.       PyErr_Format (except.reason == RETURN_QUIT
  564.                     ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
  565.                     "%s", except.message);
  566.       return -1;
  567.     }
  568.   return 0;
  569. }



  570. /* Initialize the 'commands' code.  */

  571. int
  572. gdbpy_initialize_commands (void)
  573. {
  574.   int i;

  575.   cmdpy_object_type.tp_new = PyType_GenericNew;
  576.   if (PyType_Ready (&cmdpy_object_type) < 0)
  577.     return -1;

  578.   /* Note: alias and user are special; pseudo appears to be unused,
  579.      and there is no reason to expose tui or xdb, I think.  */
  580.   if (PyModule_AddIntConstant (gdb_module, "COMMAND_NONE", no_class) < 0
  581.       || PyModule_AddIntConstant (gdb_module, "COMMAND_RUNNING", class_run) < 0
  582.       || PyModule_AddIntConstant (gdb_module, "COMMAND_DATA", class_vars) < 0
  583.       || PyModule_AddIntConstant (gdb_module, "COMMAND_STACK", class_stack) < 0
  584.       || PyModule_AddIntConstant (gdb_module, "COMMAND_FILES", class_files) < 0
  585.       || PyModule_AddIntConstant (gdb_module, "COMMAND_SUPPORT",
  586.                                   class_support) < 0
  587.       || PyModule_AddIntConstant (gdb_module, "COMMAND_STATUS", class_info) < 0
  588.       || PyModule_AddIntConstant (gdb_module, "COMMAND_BREAKPOINTS",
  589.                                   class_breakpoint) < 0
  590.       || PyModule_AddIntConstant (gdb_module, "COMMAND_TRACEPOINTS",
  591.                                   class_trace) < 0
  592.       || PyModule_AddIntConstant (gdb_module, "COMMAND_OBSCURE",
  593.                                   class_obscure) < 0
  594.       || PyModule_AddIntConstant (gdb_module, "COMMAND_MAINTENANCE",
  595.                                   class_maintenance) < 0
  596.       || PyModule_AddIntConstant (gdb_module, "COMMAND_USER", class_user) < 0)
  597.     return -1;

  598.   for (i = 0; i < N_COMPLETERS; ++i)
  599.     {
  600.       if (PyModule_AddIntConstant (gdb_module, completers[i].name, i) < 0)
  601.         return -1;
  602.     }

  603.   if (gdb_pymodule_addobject (gdb_module, "Command",
  604.                               (PyObject *) &cmdpy_object_type) < 0)
  605.     return -1;

  606.   invoke_cst = PyString_FromString ("invoke");
  607.   if (invoke_cst == NULL)
  608.     return -1;
  609.   complete_cst = PyString_FromString ("complete");
  610.   if (complete_cst == NULL)
  611.     return -1;

  612.   return 0;
  613. }



  614. static PyMethodDef cmdpy_object_methods[] =
  615. {
  616.   { "dont_repeat", cmdpy_dont_repeat, METH_NOARGS,
  617.     "Prevent command repetition when user enters empty line." },

  618.   { 0 }
  619. };

  620. static PyTypeObject cmdpy_object_type =
  621. {
  622.   PyVarObject_HEAD_INIT (NULL, 0)
  623.   "gdb.Command",                  /*tp_name*/
  624.   sizeof (cmdpy_object),          /*tp_basicsize*/
  625.   0,                                  /*tp_itemsize*/
  626.   0,                                  /*tp_dealloc*/
  627.   0,                                  /*tp_print*/
  628.   0,                                  /*tp_getattr*/
  629.   0,                                  /*tp_setattr*/
  630.   0,                                  /*tp_compare*/
  631.   0,                                  /*tp_repr*/
  632.   0,                                  /*tp_as_number*/
  633.   0,                                  /*tp_as_sequence*/
  634.   0,                                  /*tp_as_mapping*/
  635.   0,                                  /*tp_hash */
  636.   0,                                  /*tp_call*/
  637.   0,                                  /*tp_str*/
  638.   0,                                  /*tp_getattro*/
  639.   0,                                  /*tp_setattro*/
  640.   0,                                  /*tp_as_buffer*/
  641.   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
  642.   "GDB command object",                  /* tp_doc */
  643.   0,                                  /* tp_traverse */
  644.   0,                                  /* tp_clear */
  645.   0,                                  /* tp_richcompare */
  646.   0,                                  /* tp_weaklistoffset */
  647.   0,                                  /* tp_iter */
  648.   0,                                  /* tp_iternext */
  649.   cmdpy_object_methods,                  /* tp_methods */
  650.   0,                                  /* tp_members */
  651.   0,                                  /* tp_getset */
  652.   0,                                  /* tp_base */
  653.   0,                                  /* tp_dict */
  654.   0,                                  /* tp_descr_get */
  655.   0,                                  /* tp_descr_set */
  656.   0,                                  /* tp_dictoffset */
  657.   cmdpy_init,                          /* tp_init */
  658.   0,                                  /* tp_alloc */
  659. };



  660. /* Utility to build a buildargv-like result from ARGS.
  661.    This intentionally parses arguments the way libiberty/argv.c:buildargv
  662.    does.  It splits up arguments in a reasonable way, and we want a standard
  663.    way of parsing arguments.  Several gdb commands use buildargv to parse their
  664.    arguments.  Plus we want to be able to write compatible python
  665.    implementations of gdb commands.  */

  666. PyObject *
  667. gdbpy_string_to_argv (PyObject *self, PyObject *args)
  668. {
  669.   PyObject *py_argv;
  670.   const char *input;

  671.   if (!PyArg_ParseTuple (args, "s", &input))
  672.     return NULL;

  673.   py_argv = PyList_New (0);
  674.   if (py_argv == NULL)
  675.     return NULL;

  676.   /* buildargv uses NULL to represent an empty argument list, but we can't use
  677.      that in Python.  Instead, if ARGS is "" then return an empty list.
  678.      This undoes the NULL -> "" conversion that cmdpy_function does.  */

  679.   if (*input != '\0')
  680.     {
  681.       char **c_argv = gdb_buildargv (input);
  682.       int i;

  683.       for (i = 0; c_argv[i] != NULL; ++i)
  684.         {
  685.           PyObject *argp = PyString_FromString (c_argv[i]);

  686.           if (argp == NULL
  687.               || PyList_Append (py_argv, argp) < 0)
  688.             {
  689.               Py_XDECREF (argp);
  690.               Py_DECREF (py_argv);
  691.               freeargv (c_argv);
  692.               return NULL;
  693.             }
  694.           Py_DECREF (argp);
  695.         }

  696.       freeargv (c_argv);
  697.     }

  698.   return py_argv;
  699. }