xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/python/py-micmd.c (revision 6881a4007f077b54e5f51159c52b9b25f57deb0d)
1*6881a400Schristos /* MI Command Set for GDB, the GNU debugger.
2*6881a400Schristos 
3*6881a400Schristos    Copyright (C) 2019-2023 Free Software Foundation, Inc.
4*6881a400Schristos 
5*6881a400Schristos    This file is part of GDB.
6*6881a400Schristos 
7*6881a400Schristos    This program is free software; you can redistribute it and/or modify
8*6881a400Schristos    it under the terms of the GNU General Public License as published by
9*6881a400Schristos    the Free Software Foundation; either version 3 of the License, or
10*6881a400Schristos    (at your option) any later version.
11*6881a400Schristos 
12*6881a400Schristos    This program is distributed in the hope that it will be useful,
13*6881a400Schristos    but WITHOUT ANY WARRANTY; without even the implied warranty of
14*6881a400Schristos    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15*6881a400Schristos    GNU General Public License for more details.
16*6881a400Schristos 
17*6881a400Schristos    You should have received a copy of the GNU General Public License
18*6881a400Schristos    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19*6881a400Schristos 
20*6881a400Schristos /* GDB/MI commands implemented in Python.  */
21*6881a400Schristos 
22*6881a400Schristos #include "defs.h"
23*6881a400Schristos #include "python-internal.h"
24*6881a400Schristos #include "arch-utils.h"
25*6881a400Schristos #include "charset.h"
26*6881a400Schristos #include "language.h"
27*6881a400Schristos #include "mi/mi-cmds.h"
28*6881a400Schristos #include "mi/mi-parse.h"
29*6881a400Schristos #include "cli/cli-cmds.h"
30*6881a400Schristos #include <string>
31*6881a400Schristos 
32*6881a400Schristos /* Debugging of Python MI commands.  */
33*6881a400Schristos 
34*6881a400Schristos static bool pymicmd_debug;
35*6881a400Schristos 
36*6881a400Schristos /* Implementation of "show debug py-micmd".  */
37*6881a400Schristos 
38*6881a400Schristos static void
39*6881a400Schristos show_pymicmd_debug (struct ui_file *file, int from_tty,
40*6881a400Schristos 		    struct cmd_list_element *c, const char *value)
41*6881a400Schristos {
42*6881a400Schristos   gdb_printf (file, _("Python MI command debugging is %s.\n"), value);
43*6881a400Schristos }
44*6881a400Schristos 
45*6881a400Schristos /* Print a "py-micmd" debug statement.  */
46*6881a400Schristos 
47*6881a400Schristos #define pymicmd_debug_printf(fmt, ...) \
48*6881a400Schristos   debug_prefixed_printf_cond (pymicmd_debug, "py-micmd", fmt, ##__VA_ARGS__)
49*6881a400Schristos 
50*6881a400Schristos /* Print a "py-micmd" enter/exit debug statements.  */
51*6881a400Schristos 
52*6881a400Schristos #define PYMICMD_SCOPED_DEBUG_ENTER_EXIT \
53*6881a400Schristos   scoped_debug_enter_exit (pymicmd_debug, "py-micmd")
54*6881a400Schristos 
55*6881a400Schristos struct mi_command_py;
56*6881a400Schristos 
57*6881a400Schristos /* Representation of a Python gdb.MICommand object.  */
58*6881a400Schristos 
59*6881a400Schristos struct micmdpy_object
60*6881a400Schristos {
61*6881a400Schristos   PyObject_HEAD
62*6881a400Schristos 
63*6881a400Schristos   /* The object representing this command in the MI command table.  This
64*6881a400Schristos      pointer can be nullptr if the command is not currently installed into
65*6881a400Schristos      the MI command table (see gdb.MICommand.installed property).  */
66*6881a400Schristos   struct mi_command_py *mi_command;
67*6881a400Schristos 
68*6881a400Schristos   /* The string representing the name of this command, without the leading
69*6881a400Schristos      dash.  This string is never nullptr once the Python object has been
70*6881a400Schristos      initialised.
71*6881a400Schristos 
72*6881a400Schristos      The memory for this string was allocated with malloc, and needs to be
73*6881a400Schristos      deallocated with free when the Python object is deallocated.
74*6881a400Schristos 
75*6881a400Schristos      When the MI_COMMAND field is not nullptr, then the mi_command_py
76*6881a400Schristos      object's name will point back to this string.  */
77*6881a400Schristos   char *mi_command_name;
78*6881a400Schristos };
79*6881a400Schristos 
80*6881a400Schristos /* The MI command implemented in Python.  */
81*6881a400Schristos 
82*6881a400Schristos struct mi_command_py : public mi_command
83*6881a400Schristos {
84*6881a400Schristos   /* Constructs a new mi_command_py object.  NAME is command name without
85*6881a400Schristos      leading dash.  OBJECT is a reference to a Python object implementing
86*6881a400Schristos      the command.  This object must inherit from gdb.MICommand and must
87*6881a400Schristos      implement the invoke method.  */
88*6881a400Schristos 
89*6881a400Schristos   mi_command_py (const char *name, micmdpy_object *object)
90*6881a400Schristos     : mi_command (name, nullptr),
91*6881a400Schristos       m_pyobj (gdbpy_ref<micmdpy_object>::new_reference (object))
92*6881a400Schristos   {
93*6881a400Schristos     pymicmd_debug_printf ("this = %p", this);
94*6881a400Schristos     m_pyobj->mi_command = this;
95*6881a400Schristos   }
96*6881a400Schristos 
97*6881a400Schristos   ~mi_command_py ()
98*6881a400Schristos   {
99*6881a400Schristos     /* The Python object representing a MI command contains a pointer back
100*6881a400Schristos        to this c++ object.  We can safely set this pointer back to nullptr
101*6881a400Schristos        now, to indicate the Python object no longer references a valid c++
102*6881a400Schristos        object.
103*6881a400Schristos 
104*6881a400Schristos        However, the Python object also holds the storage for our name
105*6881a400Schristos        string.  We can't clear that here as our parent's destructor might
106*6881a400Schristos        still want to reference that string.  Instead we rely on the Python
107*6881a400Schristos        object deallocator to free that memory, and reset the pointer.  */
108*6881a400Schristos     m_pyobj->mi_command = nullptr;
109*6881a400Schristos 
110*6881a400Schristos     pymicmd_debug_printf ("this = %p", this);
111*6881a400Schristos   };
112*6881a400Schristos 
113*6881a400Schristos   /* Validate that CMD_OBJ, a non-nullptr pointer, is installed into the MI
114*6881a400Schristos      command table correctly.  This function looks up the command in the MI
115*6881a400Schristos      command table and checks that the object we get back references
116*6881a400Schristos      CMD_OBJ.  This function is only intended for calling within a
117*6881a400Schristos      gdb_assert.  This function performs many assertions internally, and
118*6881a400Schristos      then always returns true.  */
119*6881a400Schristos   static void validate_installation (micmdpy_object *cmd_obj);
120*6881a400Schristos 
121*6881a400Schristos   /* Update M_PYOBJ to NEW_PYOBJ.  The pointer from M_PYOBJ that points
122*6881a400Schristos      back to this object is swapped with the pointer in NEW_PYOBJ, which
123*6881a400Schristos      must be nullptr, so that NEW_PYOBJ now points back to this object.
124*6881a400Schristos      Additionally our parent's name string is stored in M_PYOBJ, so we
125*6881a400Schristos      swap the name string with NEW_PYOBJ.
126*6881a400Schristos 
127*6881a400Schristos      Before this call M_PYOBJ is the Python object representing this MI
128*6881a400Schristos      command object.  After this call has completed, NEW_PYOBJ now
129*6881a400Schristos      represents this MI command object.  */
130*6881a400Schristos   void swap_python_object (micmdpy_object *new_pyobj)
131*6881a400Schristos   {
132*6881a400Schristos     /* Current object has a backlink, new object doesn't have a backlink.  */
133*6881a400Schristos     gdb_assert (m_pyobj->mi_command != nullptr);
134*6881a400Schristos     gdb_assert (new_pyobj->mi_command == nullptr);
135*6881a400Schristos 
136*6881a400Schristos     /* Clear the current M_PYOBJ's backlink, set NEW_PYOBJ's backlink.  */
137*6881a400Schristos     std::swap (new_pyobj->mi_command, m_pyobj->mi_command);
138*6881a400Schristos 
139*6881a400Schristos     /* Both object have names.  */
140*6881a400Schristos     gdb_assert (m_pyobj->mi_command_name != nullptr);
141*6881a400Schristos     gdb_assert (new_pyobj->mi_command_name != nullptr);
142*6881a400Schristos 
143*6881a400Schristos     /* mi_command::m_name is the string owned by the current object.  */
144*6881a400Schristos     gdb_assert (m_pyobj->mi_command_name == this->name ());
145*6881a400Schristos 
146*6881a400Schristos     /* The name in mi_command::m_name is owned by the current object.  Rather
147*6881a400Schristos        than changing the value of mi_command::m_name (which is not accessible
148*6881a400Schristos        from here) to point to the name owned by the new object, swap the names
149*6881a400Schristos        of the two objects, since we know they are identical strings.  */
150*6881a400Schristos     gdb_assert (strcmp (new_pyobj->mi_command_name,
151*6881a400Schristos 			m_pyobj->mi_command_name) == 0);
152*6881a400Schristos     std::swap (new_pyobj->mi_command_name, m_pyobj->mi_command_name);
153*6881a400Schristos 
154*6881a400Schristos     /* Take a reference to the new object, drop the reference to the current
155*6881a400Schristos        object.  */
156*6881a400Schristos     m_pyobj = gdbpy_ref<micmdpy_object>::new_reference (new_pyobj);
157*6881a400Schristos   }
158*6881a400Schristos 
159*6881a400Schristos   /* Called when the MI command is invoked.  */
160*6881a400Schristos   virtual void invoke(struct mi_parse *parse) const override;
161*6881a400Schristos 
162*6881a400Schristos private:
163*6881a400Schristos   /* The Python object representing this MI command.  */
164*6881a400Schristos   gdbpy_ref<micmdpy_object> m_pyobj;
165*6881a400Schristos };
166*6881a400Schristos 
167*6881a400Schristos using mi_command_py_up = std::unique_ptr<mi_command_py>;
168*6881a400Schristos 
169*6881a400Schristos extern PyTypeObject micmdpy_object_type
170*6881a400Schristos 	CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("micmdpy_object");
171*6881a400Schristos 
172*6881a400Schristos /* Holds a Python object containing the string 'invoke'.  */
173*6881a400Schristos 
174*6881a400Schristos static PyObject *invoke_cst;
175*6881a400Schristos 
176*6881a400Schristos /* Convert KEY_OBJ into a string that can be used as a field name in MI
177*6881a400Schristos    output.  KEY_OBJ must be a Python string object, and must only contain
178*6881a400Schristos    characters suitable for use as an MI field name.
179*6881a400Schristos 
180*6881a400Schristos    If KEY_OBJ is not a string, or if KEY_OBJ contains invalid characters,
181*6881a400Schristos    then an error is thrown.  Otherwise, KEY_OBJ is converted to a string
182*6881a400Schristos    and returned.  */
183*6881a400Schristos 
184*6881a400Schristos static gdb::unique_xmalloc_ptr<char>
185*6881a400Schristos py_object_to_mi_key (PyObject *key_obj)
186*6881a400Schristos {
187*6881a400Schristos   /* The key must be a string.  */
188*6881a400Schristos   if (!PyUnicode_Check (key_obj))
189*6881a400Schristos     {
190*6881a400Schristos       gdbpy_ref<> key_repr (PyObject_Repr (key_obj));
191*6881a400Schristos       gdb::unique_xmalloc_ptr<char> key_repr_string;
192*6881a400Schristos       if (key_repr != nullptr)
193*6881a400Schristos 	key_repr_string = python_string_to_target_string (key_repr.get ());
194*6881a400Schristos       if (key_repr_string == nullptr)
195*6881a400Schristos 	gdbpy_handle_exception ();
196*6881a400Schristos 
197*6881a400Schristos       gdbpy_error (_("non-string object used as key: %s"),
198*6881a400Schristos 		   key_repr_string.get ());
199*6881a400Schristos     }
200*6881a400Schristos 
201*6881a400Schristos   gdb::unique_xmalloc_ptr<char> key_string
202*6881a400Schristos     = python_string_to_target_string (key_obj);
203*6881a400Schristos   if (key_string == nullptr)
204*6881a400Schristos     gdbpy_handle_exception ();
205*6881a400Schristos 
206*6881a400Schristos   /* Predicate function, returns true if NAME is a valid field name for use
207*6881a400Schristos      in MI result output, otherwise, returns false.  */
208*6881a400Schristos   auto is_valid_key_name = [] (const char *name) -> bool
209*6881a400Schristos   {
210*6881a400Schristos     gdb_assert (name != nullptr);
211*6881a400Schristos 
212*6881a400Schristos     if (*name == '\0' || !isalpha (*name))
213*6881a400Schristos       return false;
214*6881a400Schristos 
215*6881a400Schristos     for (; *name != '\0'; ++name)
216*6881a400Schristos       if (!isalnum (*name) && *name != '_' && *name != '-')
217*6881a400Schristos 	return false;
218*6881a400Schristos 
219*6881a400Schristos     return true;
220*6881a400Schristos   };
221*6881a400Schristos 
222*6881a400Schristos   if (!is_valid_key_name (key_string.get ()))
223*6881a400Schristos     {
224*6881a400Schristos       if (*key_string.get () == '\0')
225*6881a400Schristos 	gdbpy_error (_("Invalid empty key in MI result"));
226*6881a400Schristos       else
227*6881a400Schristos 	gdbpy_error (_("Invalid key in MI result: %s"), key_string.get ());
228*6881a400Schristos     }
229*6881a400Schristos 
230*6881a400Schristos   return key_string;
231*6881a400Schristos }
232*6881a400Schristos 
233*6881a400Schristos /* Serialize RESULT and print it in MI format to the current_uiout.
234*6881a400Schristos    FIELD_NAME is used as the name of this result field.
235*6881a400Schristos 
236*6881a400Schristos    RESULT can be a dictionary, a sequence, an iterator, or an object that
237*6881a400Schristos    can be converted to a string, these are converted to the matching MI
238*6881a400Schristos    output format (dictionaries as tuples, sequences and iterators as lists,
239*6881a400Schristos    and strings as named fields).
240*6881a400Schristos 
241*6881a400Schristos    If anything goes wrong while formatting the output then an error is
242*6881a400Schristos    thrown.
243*6881a400Schristos 
244*6881a400Schristos    This function is the recursive inner core of serialize_mi_result, and
245*6881a400Schristos    should only be called from that function.  */
246*6881a400Schristos 
247*6881a400Schristos static void
248*6881a400Schristos serialize_mi_result_1 (PyObject *result, const char *field_name)
249*6881a400Schristos {
250*6881a400Schristos   struct ui_out *uiout = current_uiout;
251*6881a400Schristos 
252*6881a400Schristos   if (PyDict_Check (result))
253*6881a400Schristos     {
254*6881a400Schristos       PyObject *key, *value;
255*6881a400Schristos       Py_ssize_t pos = 0;
256*6881a400Schristos       ui_out_emit_tuple tuple_emitter (uiout, field_name);
257*6881a400Schristos       while (PyDict_Next (result, &pos, &key, &value))
258*6881a400Schristos 	{
259*6881a400Schristos 	  gdb::unique_xmalloc_ptr<char> key_string
260*6881a400Schristos 	    (py_object_to_mi_key (key));
261*6881a400Schristos 	  serialize_mi_result_1 (value, key_string.get ());
262*6881a400Schristos 	}
263*6881a400Schristos     }
264*6881a400Schristos   else if (PySequence_Check (result) && !PyUnicode_Check (result))
265*6881a400Schristos     {
266*6881a400Schristos       ui_out_emit_list list_emitter (uiout, field_name);
267*6881a400Schristos       Py_ssize_t len = PySequence_Size (result);
268*6881a400Schristos       if (len == -1)
269*6881a400Schristos 	gdbpy_handle_exception ();
270*6881a400Schristos       for (Py_ssize_t i = 0; i < len; ++i)
271*6881a400Schristos 	{
272*6881a400Schristos           gdbpy_ref<> item (PySequence_ITEM (result, i));
273*6881a400Schristos 	  if (item == nullptr)
274*6881a400Schristos 	    gdbpy_handle_exception ();
275*6881a400Schristos 	  serialize_mi_result_1 (item.get (), nullptr);
276*6881a400Schristos 	}
277*6881a400Schristos     }
278*6881a400Schristos   else if (PyIter_Check (result))
279*6881a400Schristos     {
280*6881a400Schristos       gdbpy_ref<> item;
281*6881a400Schristos       ui_out_emit_list list_emitter (uiout, field_name);
282*6881a400Schristos       while (true)
283*6881a400Schristos 	{
284*6881a400Schristos 	  item.reset (PyIter_Next (result));
285*6881a400Schristos 	  if (item == nullptr)
286*6881a400Schristos 	    {
287*6881a400Schristos 	      if (PyErr_Occurred () != nullptr)
288*6881a400Schristos 		gdbpy_handle_exception ();
289*6881a400Schristos 	      break;
290*6881a400Schristos 	    }
291*6881a400Schristos 	  serialize_mi_result_1 (item.get (), nullptr);
292*6881a400Schristos 	}
293*6881a400Schristos     }
294*6881a400Schristos   else
295*6881a400Schristos     {
296*6881a400Schristos       gdb::unique_xmalloc_ptr<char> string (gdbpy_obj_to_string (result));
297*6881a400Schristos       if (string == nullptr)
298*6881a400Schristos 	gdbpy_handle_exception ();
299*6881a400Schristos       uiout->field_string (field_name, string.get ());
300*6881a400Schristos     }
301*6881a400Schristos }
302*6881a400Schristos 
303*6881a400Schristos /* Serialize RESULT and print it in MI format to the current_uiout.
304*6881a400Schristos 
305*6881a400Schristos    This function handles the top-level result initially returned from the
306*6881a400Schristos    invoke method of the Python command implementation.  At the top-level
307*6881a400Schristos    the result must be a dictionary.  The values within this dictionary can
308*6881a400Schristos    be a wider range of types.  Handling the values of the top-level
309*6881a400Schristos    dictionary is done by serialize_mi_result_1, see that function for more
310*6881a400Schristos    details.
311*6881a400Schristos 
312*6881a400Schristos    If anything goes wrong while parsing and printing the MI output then an
313*6881a400Schristos    error is thrown.  */
314*6881a400Schristos 
315*6881a400Schristos static void
316*6881a400Schristos serialize_mi_result (PyObject *result)
317*6881a400Schristos {
318*6881a400Schristos   /* At the top-level, the result must be a dictionary.  */
319*6881a400Schristos 
320*6881a400Schristos   if (!PyDict_Check (result))
321*6881a400Schristos     gdbpy_error (_("Result from invoke must be a dictionary"));
322*6881a400Schristos 
323*6881a400Schristos   PyObject *key, *value;
324*6881a400Schristos   Py_ssize_t pos = 0;
325*6881a400Schristos   while (PyDict_Next (result, &pos, &key, &value))
326*6881a400Schristos     {
327*6881a400Schristos       gdb::unique_xmalloc_ptr<char> key_string
328*6881a400Schristos 	(py_object_to_mi_key (key));
329*6881a400Schristos       serialize_mi_result_1 (value, key_string.get ());
330*6881a400Schristos     }
331*6881a400Schristos }
332*6881a400Schristos 
333*6881a400Schristos /* Called when the MI command is invoked.  PARSE contains the parsed
334*6881a400Schristos    command line arguments from the user.  */
335*6881a400Schristos 
336*6881a400Schristos void
337*6881a400Schristos mi_command_py::invoke (struct mi_parse *parse) const
338*6881a400Schristos {
339*6881a400Schristos   PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
340*6881a400Schristos 
341*6881a400Schristos   pymicmd_debug_printf ("this = %p, name = %s", this, name ());
342*6881a400Schristos 
343*6881a400Schristos   mi_parse_argv (parse->args, parse);
344*6881a400Schristos 
345*6881a400Schristos   if (parse->argv == nullptr)
346*6881a400Schristos     error (_("Problem parsing arguments: %s %s"), parse->command, parse->args);
347*6881a400Schristos 
348*6881a400Schristos 
349*6881a400Schristos   gdbpy_enter enter_py;
350*6881a400Schristos 
351*6881a400Schristos   /* Place all the arguments into a list which we pass as a single argument
352*6881a400Schristos      to the MI command's invoke method.  */
353*6881a400Schristos   gdbpy_ref<> argobj (PyList_New (parse->argc));
354*6881a400Schristos   if (argobj == nullptr)
355*6881a400Schristos     gdbpy_handle_exception ();
356*6881a400Schristos 
357*6881a400Schristos   for (int i = 0; i < parse->argc; ++i)
358*6881a400Schristos     {
359*6881a400Schristos       gdbpy_ref<> str (PyUnicode_Decode (parse->argv[i],
360*6881a400Schristos 					 strlen (parse->argv[i]),
361*6881a400Schristos 					 host_charset (), nullptr));
362*6881a400Schristos       if (PyList_SetItem (argobj.get (), i, str.release ()) < 0)
363*6881a400Schristos 	gdbpy_handle_exception ();
364*6881a400Schristos     }
365*6881a400Schristos 
366*6881a400Schristos   gdb_assert (this->m_pyobj != nullptr);
367*6881a400Schristos   gdb_assert (PyErr_Occurred () == nullptr);
368*6881a400Schristos   gdbpy_ref<> result
369*6881a400Schristos     (PyObject_CallMethodObjArgs ((PyObject *) this->m_pyobj.get (), invoke_cst,
370*6881a400Schristos 				 argobj.get (), nullptr));
371*6881a400Schristos   if (result == nullptr)
372*6881a400Schristos     gdbpy_handle_exception ();
373*6881a400Schristos 
374*6881a400Schristos   if (result != Py_None)
375*6881a400Schristos     serialize_mi_result (result.get ());
376*6881a400Schristos }
377*6881a400Schristos 
378*6881a400Schristos /* See declaration above.  */
379*6881a400Schristos 
380*6881a400Schristos void
381*6881a400Schristos mi_command_py::validate_installation (micmdpy_object *cmd_obj)
382*6881a400Schristos {
383*6881a400Schristos   gdb_assert (cmd_obj != nullptr);
384*6881a400Schristos   mi_command_py *cmd = cmd_obj->mi_command;
385*6881a400Schristos   gdb_assert (cmd != nullptr);
386*6881a400Schristos   const char *name = cmd_obj->mi_command_name;
387*6881a400Schristos   gdb_assert (name != nullptr);
388*6881a400Schristos   gdb_assert (name == cmd->name ());
389*6881a400Schristos   mi_command *mi_cmd = mi_cmd_lookup (name);
390*6881a400Schristos   gdb_assert (mi_cmd == cmd);
391*6881a400Schristos   gdb_assert (cmd->m_pyobj == cmd_obj);
392*6881a400Schristos }
393*6881a400Schristos 
394*6881a400Schristos /* Return CMD as an mi_command_py if it is a Python MI command, else
395*6881a400Schristos    nullptr.  */
396*6881a400Schristos 
397*6881a400Schristos static mi_command_py *
398*6881a400Schristos as_mi_command_py (mi_command *cmd)
399*6881a400Schristos {
400*6881a400Schristos   return dynamic_cast<mi_command_py *> (cmd);
401*6881a400Schristos }
402*6881a400Schristos 
403*6881a400Schristos /* Uninstall OBJ, making the MI command represented by OBJ unavailable for
404*6881a400Schristos    use by the user.  On success 0 is returned, otherwise -1 is returned
405*6881a400Schristos    and a Python exception will be set.  */
406*6881a400Schristos 
407*6881a400Schristos static int
408*6881a400Schristos micmdpy_uninstall_command (micmdpy_object *obj)
409*6881a400Schristos {
410*6881a400Schristos   PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
411*6881a400Schristos 
412*6881a400Schristos   gdb_assert (obj->mi_command != nullptr);
413*6881a400Schristos   gdb_assert (obj->mi_command_name != nullptr);
414*6881a400Schristos 
415*6881a400Schristos   pymicmd_debug_printf ("name = %s", obj->mi_command_name);
416*6881a400Schristos 
417*6881a400Schristos   /* Remove the command from the internal MI table of commands.  This will
418*6881a400Schristos      cause the mi_command_py object to be deleted, which will clear the
419*6881a400Schristos      backlink in OBJ.  */
420*6881a400Schristos   bool removed = remove_mi_cmd_entry (obj->mi_command->name ());
421*6881a400Schristos   gdb_assert (removed);
422*6881a400Schristos   gdb_assert (obj->mi_command == nullptr);
423*6881a400Schristos 
424*6881a400Schristos   return 0;
425*6881a400Schristos }
426*6881a400Schristos 
427*6881a400Schristos /* Install OBJ as a usable MI command.  Return 0 on success, and -1 on
428*6881a400Schristos    error, in which case, a Python error will have been set.
429*6881a400Schristos 
430*6881a400Schristos    After successful completion the command name associated with OBJ will
431*6881a400Schristos    be installed in the MI command table (so it can be found if the user
432*6881a400Schristos    enters that command name), additionally, OBJ will have been added to
433*6881a400Schristos    the gdb._mi_commands dictionary (using the command name as its key),
434*6881a400Schristos    this will ensure that OBJ remains live even if the user gives up all
435*6881a400Schristos    references.  */
436*6881a400Schristos 
437*6881a400Schristos static int
438*6881a400Schristos micmdpy_install_command (micmdpy_object *obj)
439*6881a400Schristos {
440*6881a400Schristos   PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
441*6881a400Schristos 
442*6881a400Schristos   gdb_assert (obj->mi_command == nullptr);
443*6881a400Schristos   gdb_assert (obj->mi_command_name != nullptr);
444*6881a400Schristos 
445*6881a400Schristos   pymicmd_debug_printf ("name = %s", obj->mi_command_name);
446*6881a400Schristos 
447*6881a400Schristos   /* Look up this command name in MI_COMMANDS, a command with this name may
448*6881a400Schristos      already exist.  */
449*6881a400Schristos   mi_command *cmd = mi_cmd_lookup (obj->mi_command_name);
450*6881a400Schristos   mi_command_py *cmd_py = as_mi_command_py (cmd);
451*6881a400Schristos 
452*6881a400Schristos   if (cmd != nullptr && cmd_py == nullptr)
453*6881a400Schristos     {
454*6881a400Schristos       /* There is already an MI command registered with that name, and it's not
455*6881a400Schristos          a Python one.  Forbid replacing a non-Python MI command.  */
456*6881a400Schristos       PyErr_SetString (PyExc_RuntimeError,
457*6881a400Schristos 		       _("unable to add command, name is already in use"));
458*6881a400Schristos       return -1;
459*6881a400Schristos     }
460*6881a400Schristos 
461*6881a400Schristos   if (cmd_py != nullptr)
462*6881a400Schristos     {
463*6881a400Schristos       /* There is already a Python MI command registered with that name, swap
464*6881a400Schristos          in the new gdb.MICommand implementation.  */
465*6881a400Schristos       cmd_py->swap_python_object (obj);
466*6881a400Schristos     }
467*6881a400Schristos   else
468*6881a400Schristos     {
469*6881a400Schristos       /* There's no MI command registered with that name at all, create one.  */
470*6881a400Schristos       mi_command_py_up mi_cmd (new mi_command_py (obj->mi_command_name, obj));
471*6881a400Schristos 
472*6881a400Schristos       /* Add the command to the gdb internal MI command table.  */
473*6881a400Schristos       bool result = insert_mi_cmd_entry (std::move (mi_cmd));
474*6881a400Schristos       gdb_assert (result);
475*6881a400Schristos     }
476*6881a400Schristos 
477*6881a400Schristos   return 0;
478*6881a400Schristos }
479*6881a400Schristos 
480*6881a400Schristos /* Implement gdb.MICommand.__init__.  The init method takes the name of
481*6881a400Schristos    the MI command as the first argument, which must be a string, starting
482*6881a400Schristos    with a single dash.  */
483*6881a400Schristos 
484*6881a400Schristos static int
485*6881a400Schristos micmdpy_init (PyObject *self, PyObject *args, PyObject *kwargs)
486*6881a400Schristos {
487*6881a400Schristos   PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
488*6881a400Schristos 
489*6881a400Schristos   micmdpy_object *cmd = (micmdpy_object *) self;
490*6881a400Schristos 
491*6881a400Schristos   static const char *keywords[] = { "name", nullptr };
492*6881a400Schristos   const char *name;
493*6881a400Schristos 
494*6881a400Schristos   if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "s", keywords,
495*6881a400Schristos 					&name))
496*6881a400Schristos     return -1;
497*6881a400Schristos 
498*6881a400Schristos   /* Validate command name */
499*6881a400Schristos   const int name_len = strlen (name);
500*6881a400Schristos   if (name_len == 0)
501*6881a400Schristos     {
502*6881a400Schristos       PyErr_SetString (PyExc_ValueError, _("MI command name is empty."));
503*6881a400Schristos       return -1;
504*6881a400Schristos     }
505*6881a400Schristos   else if ((name_len < 2) || (name[0] != '-') || !isalnum (name[1]))
506*6881a400Schristos     {
507*6881a400Schristos       PyErr_SetString (PyExc_ValueError,
508*6881a400Schristos 		       _("MI command name does not start with '-'"
509*6881a400Schristos 			 " followed by at least one letter or digit."));
510*6881a400Schristos       return -1;
511*6881a400Schristos     }
512*6881a400Schristos   else
513*6881a400Schristos     {
514*6881a400Schristos       for (int i = 2; i < name_len; i++)
515*6881a400Schristos 	{
516*6881a400Schristos 	  if (!isalnum (name[i]) && name[i] != '-')
517*6881a400Schristos 	    {
518*6881a400Schristos 	      PyErr_Format
519*6881a400Schristos 		(PyExc_ValueError,
520*6881a400Schristos 		 _("MI command name contains invalid character: %c."),
521*6881a400Schristos 		 name[i]);
522*6881a400Schristos 	      return -1;
523*6881a400Schristos 	    }
524*6881a400Schristos 	}
525*6881a400Schristos 
526*6881a400Schristos       /* Skip over the leading dash.  For the rest of this function the
527*6881a400Schristos 	 dash is not important.  */
528*6881a400Schristos       ++name;
529*6881a400Schristos     }
530*6881a400Schristos 
531*6881a400Schristos   /* If this object already has a name set, then this object has been
532*6881a400Schristos      initialized before.  We handle this case a little differently.  */
533*6881a400Schristos   if (cmd->mi_command_name != nullptr)
534*6881a400Schristos     {
535*6881a400Schristos       /* First, we don't allow the user to change the MI command name.
536*6881a400Schristos 	 Supporting this would be tricky as we would need to delete the
537*6881a400Schristos 	 mi_command_py from the MI command table, however, the user might
538*6881a400Schristos 	 be trying to perform this reinitialization from within the very
539*6881a400Schristos 	 command we're about to delete... it all gets very messy.
540*6881a400Schristos 
541*6881a400Schristos 	 So, for now at least, we don't allow this.  This doesn't seem like
542*6881a400Schristos 	 an excessive restriction.  */
543*6881a400Schristos       if (strcmp (cmd->mi_command_name, name) != 0)
544*6881a400Schristos 	{
545*6881a400Schristos 	  PyErr_SetString
546*6881a400Schristos 	    (PyExc_ValueError,
547*6881a400Schristos 	     _("can't reinitialize object with a different command name"));
548*6881a400Schristos 	  return -1;
549*6881a400Schristos 	}
550*6881a400Schristos 
551*6881a400Schristos       /* If there's already an object registered with the MI command table,
552*6881a400Schristos 	 then we're done.  That object must be a mi_command_py, which
553*6881a400Schristos 	 should reference back to this micmdpy_object.  */
554*6881a400Schristos       if (cmd->mi_command != nullptr)
555*6881a400Schristos 	{
556*6881a400Schristos 	  mi_command_py::validate_installation (cmd);
557*6881a400Schristos 	  return 0;
558*6881a400Schristos 	}
559*6881a400Schristos     }
560*6881a400Schristos   else
561*6881a400Schristos     cmd->mi_command_name = xstrdup (name);
562*6881a400Schristos 
563*6881a400Schristos   /* Now we can install this mi_command_py in the MI command table.  */
564*6881a400Schristos   return micmdpy_install_command (cmd);
565*6881a400Schristos }
566*6881a400Schristos 
567*6881a400Schristos /* Called when a gdb.MICommand object is deallocated.  */
568*6881a400Schristos 
569*6881a400Schristos static void
570*6881a400Schristos micmdpy_dealloc (PyObject *obj)
571*6881a400Schristos {
572*6881a400Schristos   PYMICMD_SCOPED_DEBUG_ENTER_EXIT;
573*6881a400Schristos 
574*6881a400Schristos   micmdpy_object *cmd = (micmdpy_object *) obj;
575*6881a400Schristos 
576*6881a400Schristos   /* If the Python object failed to initialize, then the name field might
577*6881a400Schristos      be nullptr.  */
578*6881a400Schristos   pymicmd_debug_printf ("obj = %p, name = %s", cmd,
579*6881a400Schristos 			(cmd->mi_command_name == nullptr
580*6881a400Schristos 			 ? "(null)" : cmd->mi_command_name));
581*6881a400Schristos 
582*6881a400Schristos   /* As the mi_command_py object holds a reference to the micmdpy_object,
583*6881a400Schristos      the only way the dealloc function can be called is if the mi_command_py
584*6881a400Schristos      object has been deleted, in which case the following assert will
585*6881a400Schristos      hold.  */
586*6881a400Schristos   gdb_assert (cmd->mi_command == nullptr);
587*6881a400Schristos 
588*6881a400Schristos   /* Free the memory that holds the command name.  */
589*6881a400Schristos   xfree (cmd->mi_command_name);
590*6881a400Schristos   cmd->mi_command_name = nullptr;
591*6881a400Schristos 
592*6881a400Schristos   /* Finally, free the memory for this Python object.  */
593*6881a400Schristos   Py_TYPE (obj)->tp_free (obj);
594*6881a400Schristos }
595*6881a400Schristos 
596*6881a400Schristos /* Python initialization for the MI commands components.  */
597*6881a400Schristos 
598*6881a400Schristos int
599*6881a400Schristos gdbpy_initialize_micommands ()
600*6881a400Schristos {
601*6881a400Schristos   micmdpy_object_type.tp_new = PyType_GenericNew;
602*6881a400Schristos   if (PyType_Ready (&micmdpy_object_type) < 0)
603*6881a400Schristos     return -1;
604*6881a400Schristos 
605*6881a400Schristos   if (gdb_pymodule_addobject (gdb_module, "MICommand",
606*6881a400Schristos 			      (PyObject *) &micmdpy_object_type)
607*6881a400Schristos       < 0)
608*6881a400Schristos     return -1;
609*6881a400Schristos 
610*6881a400Schristos   invoke_cst = PyUnicode_FromString ("invoke");
611*6881a400Schristos   if (invoke_cst == nullptr)
612*6881a400Schristos     return -1;
613*6881a400Schristos 
614*6881a400Schristos   return 0;
615*6881a400Schristos }
616*6881a400Schristos 
617*6881a400Schristos void
618*6881a400Schristos gdbpy_finalize_micommands ()
619*6881a400Schristos {
620*6881a400Schristos   /* mi_command_py objects hold references to micmdpy_object objects.  They must
621*6881a400Schristos      be dropped before the Python interpreter is finalized.  Do so by removing
622*6881a400Schristos      those MI command entries, thus deleting the mi_command_py objects.  */
623*6881a400Schristos   remove_mi_cmd_entries ([] (mi_command *cmd)
624*6881a400Schristos     {
625*6881a400Schristos       return as_mi_command_py (cmd) != nullptr;
626*6881a400Schristos     });
627*6881a400Schristos }
628*6881a400Schristos 
629*6881a400Schristos /* Get the gdb.MICommand.name attribute, returns a string, the name of this
630*6881a400Schristos    MI command.  */
631*6881a400Schristos 
632*6881a400Schristos static PyObject *
633*6881a400Schristos micmdpy_get_name (PyObject *self, void *closure)
634*6881a400Schristos {
635*6881a400Schristos   struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
636*6881a400Schristos 
637*6881a400Schristos   gdb_assert (micmd_obj->mi_command_name != nullptr);
638*6881a400Schristos   std::string name_str = string_printf ("-%s", micmd_obj->mi_command_name);
639*6881a400Schristos   return PyUnicode_FromString (name_str.c_str ());
640*6881a400Schristos }
641*6881a400Schristos 
642*6881a400Schristos /* Get the gdb.MICommand.installed property.  Returns true if this MI
643*6881a400Schristos    command is installed into the MI command table, otherwise returns
644*6881a400Schristos    false.  */
645*6881a400Schristos 
646*6881a400Schristos static PyObject *
647*6881a400Schristos micmdpy_get_installed (PyObject *self, void *closure)
648*6881a400Schristos {
649*6881a400Schristos   struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
650*6881a400Schristos 
651*6881a400Schristos   if (micmd_obj->mi_command == nullptr)
652*6881a400Schristos     Py_RETURN_FALSE;
653*6881a400Schristos   Py_RETURN_TRUE;
654*6881a400Schristos }
655*6881a400Schristos 
656*6881a400Schristos /* Set the gdb.MICommand.installed property.  The property can be set to
657*6881a400Schristos    either true or false.  Setting the property to true will cause the
658*6881a400Schristos    command to be installed into the MI command table (if it isn't
659*6881a400Schristos    already), while setting this property to false will cause the command
660*6881a400Schristos    to be removed from the MI command table (if it is present).  */
661*6881a400Schristos 
662*6881a400Schristos static int
663*6881a400Schristos micmdpy_set_installed (PyObject *self, PyObject *newvalue, void *closure)
664*6881a400Schristos {
665*6881a400Schristos   struct micmdpy_object *micmd_obj = (struct micmdpy_object *) self;
666*6881a400Schristos 
667*6881a400Schristos   bool installed_p = PyObject_IsTrue (newvalue);
668*6881a400Schristos   if (installed_p == (micmd_obj->mi_command != nullptr))
669*6881a400Schristos     return 0;
670*6881a400Schristos 
671*6881a400Schristos   if (installed_p)
672*6881a400Schristos     return micmdpy_install_command (micmd_obj);
673*6881a400Schristos   else
674*6881a400Schristos     return micmdpy_uninstall_command (micmd_obj);
675*6881a400Schristos }
676*6881a400Schristos 
677*6881a400Schristos /* The gdb.MICommand properties.   */
678*6881a400Schristos 
679*6881a400Schristos static gdb_PyGetSetDef micmdpy_object_getset[] = {
680*6881a400Schristos   { "name", micmdpy_get_name, nullptr, "The command's name.", nullptr },
681*6881a400Schristos   { "installed", micmdpy_get_installed, micmdpy_set_installed,
682*6881a400Schristos     "Is this command installed for use.", nullptr },
683*6881a400Schristos   { nullptr }	/* Sentinel.  */
684*6881a400Schristos };
685*6881a400Schristos 
686*6881a400Schristos /* The gdb.MICommand descriptor.  */
687*6881a400Schristos 
688*6881a400Schristos PyTypeObject micmdpy_object_type = {
689*6881a400Schristos   PyVarObject_HEAD_INIT (nullptr, 0) "gdb.MICommand", /*tp_name */
690*6881a400Schristos   sizeof (micmdpy_object),			   /*tp_basicsize */
691*6881a400Schristos   0,						   /*tp_itemsize */
692*6881a400Schristos   micmdpy_dealloc,				   /*tp_dealloc */
693*6881a400Schristos   0,						   /*tp_print */
694*6881a400Schristos   0,						   /*tp_getattr */
695*6881a400Schristos   0,						   /*tp_setattr */
696*6881a400Schristos   0,						   /*tp_compare */
697*6881a400Schristos   0,						   /*tp_repr */
698*6881a400Schristos   0,						   /*tp_as_number */
699*6881a400Schristos   0,						   /*tp_as_sequence */
700*6881a400Schristos   0,						   /*tp_as_mapping */
701*6881a400Schristos   0,						   /*tp_hash */
702*6881a400Schristos   0,						   /*tp_call */
703*6881a400Schristos   0,						   /*tp_str */
704*6881a400Schristos   0,						   /*tp_getattro */
705*6881a400Schristos   0,						   /*tp_setattro */
706*6881a400Schristos   0,						   /*tp_as_buffer */
707*6881a400Schristos   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,	/*tp_flags */
708*6881a400Schristos   "GDB mi-command object",			   /* tp_doc */
709*6881a400Schristos   0,						   /* tp_traverse */
710*6881a400Schristos   0,						   /* tp_clear */
711*6881a400Schristos   0,						   /* tp_richcompare */
712*6881a400Schristos   0,						   /* tp_weaklistoffset */
713*6881a400Schristos   0,						   /* tp_iter */
714*6881a400Schristos   0,						   /* tp_iternext */
715*6881a400Schristos   0,						   /* tp_methods */
716*6881a400Schristos   0,						   /* tp_members */
717*6881a400Schristos   micmdpy_object_getset,			   /* tp_getset */
718*6881a400Schristos   0,						   /* tp_base */
719*6881a400Schristos   0,						   /* tp_dict */
720*6881a400Schristos   0,						   /* tp_descr_get */
721*6881a400Schristos   0,						   /* tp_descr_set */
722*6881a400Schristos   0,						   /* tp_dictoffset */
723*6881a400Schristos   micmdpy_init,					   /* tp_init */
724*6881a400Schristos   0,						   /* tp_alloc */
725*6881a400Schristos };
726*6881a400Schristos 
727*6881a400Schristos void _initialize_py_micmd ();
728*6881a400Schristos void
729*6881a400Schristos _initialize_py_micmd ()
730*6881a400Schristos {
731*6881a400Schristos   add_setshow_boolean_cmd
732*6881a400Schristos     ("py-micmd", class_maintenance, &pymicmd_debug,
733*6881a400Schristos      _("Set Python micmd debugging."),
734*6881a400Schristos      _("Show Python micmd debugging."),
735*6881a400Schristos      _("When on, Python micmd debugging is enabled."),
736*6881a400Schristos      nullptr,
737*6881a400Schristos      show_pymicmd_debug,
738*6881a400Schristos      &setdebuglist, &showdebuglist);
739*6881a400Schristos }
740