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