]> Git Repo - binutils.git/blob - gdb/python/py-arch.c
e6dfb241617c05077a138da37cc544a1d9fb83fc
[binutils.git] / gdb / python / py-arch.c
1 /* Python interface to architecture
2
3    Copyright (C) 2013-2022 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 #include "defs.h"
21 #include "gdbarch.h"
22 #include "arch-utils.h"
23 #include "disasm.h"
24 #include "python-internal.h"
25
26 struct arch_object {
27   PyObject_HEAD
28   struct gdbarch *gdbarch;
29 };
30
31 static struct gdbarch_data *arch_object_data = NULL;
32
33 /* Require a valid Architecture.  */
34 #define ARCHPY_REQUIRE_VALID(arch_obj, arch)                    \
35   do {                                                          \
36     arch = arch_object_to_gdbarch (arch_obj);                   \
37     if (arch == NULL)                                           \
38       {                                                         \
39         PyErr_SetString (PyExc_RuntimeError,                    \
40                          _("Architecture is invalid."));        \
41         return NULL;                                            \
42       }                                                         \
43   } while (0)
44
45 extern PyTypeObject arch_object_type
46     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("arch_object");
47
48 /* Associates an arch_object with GDBARCH as gdbarch_data via the gdbarch
49    post init registration mechanism (gdbarch_data_register_post_init).  */
50
51 static void *
52 arch_object_data_init (struct gdbarch *gdbarch)
53 {
54   arch_object *arch_obj = PyObject_New (arch_object, &arch_object_type);
55
56   if (arch_obj == NULL)
57     return NULL;
58
59   arch_obj->gdbarch = gdbarch;
60
61   return (void *) arch_obj;
62 }
63
64 /* Returns the struct gdbarch value corresponding to the given Python
65    architecture object OBJ, which must be a gdb.Architecture object.  */
66
67 struct gdbarch *
68 arch_object_to_gdbarch (PyObject *obj)
69 {
70   gdb_assert (gdbpy_is_architecture (obj));
71
72   arch_object *py_arch = (arch_object *) obj;
73   return py_arch->gdbarch;
74 }
75
76 /* See python-internal.h.  */
77
78 bool
79 gdbpy_is_architecture (PyObject *obj)
80 {
81   return PyObject_TypeCheck (obj, &arch_object_type);
82 }
83
84 /* Returns the Python architecture object corresponding to GDBARCH.
85    Returns a new reference to the arch_object associated as data with
86    GDBARCH.  */
87
88 PyObject *
89 gdbarch_to_arch_object (struct gdbarch *gdbarch)
90 {
91   PyObject *new_ref = (PyObject *) gdbarch_data (gdbarch, arch_object_data);
92
93   /* new_ref could be NULL if registration of arch_object with GDBARCH failed
94      in arch_object_data_init.  */
95   Py_XINCREF (new_ref);
96
97   return new_ref;
98 }
99
100 /* Implementation of gdb.Architecture.name (self) -> String.
101    Returns the name of the architecture as a string value.  */
102
103 static PyObject *
104 archpy_name (PyObject *self, PyObject *args)
105 {
106   struct gdbarch *gdbarch = NULL;
107   const char *name;
108
109   ARCHPY_REQUIRE_VALID (self, gdbarch);
110
111   name = (gdbarch_bfd_arch_info (gdbarch))->printable_name;
112   return PyString_FromString (name);
113 }
114
115 /* Implementation of
116    gdb.Architecture.disassemble (self, start_pc [, end_pc [,count]]) -> List.
117    Returns a list of instructions in a memory address range.  Each instruction
118    in the list is a Python dict object.
119 */
120
121 static PyObject *
122 archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw)
123 {
124   static const char *keywords[] = { "start_pc", "end_pc", "count", NULL };
125   CORE_ADDR start, end = 0;
126   CORE_ADDR pc;
127   gdb_py_ulongest start_temp;
128   long count = 0, i;
129   PyObject *end_obj = NULL, *count_obj = NULL;
130   struct gdbarch *gdbarch = NULL;
131
132   ARCHPY_REQUIRE_VALID (self, gdbarch);
133
134   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO",
135                                         keywords, &start_temp, &end_obj,
136                                         &count_obj))
137     return NULL;
138
139   start = start_temp;
140   if (end_obj)
141     {
142       /* Make a long logic check first.  In Python 3.x, internally,
143          all integers are represented as longs.  In Python 2.x, there
144          is still a differentiation internally between a PyInt and a
145          PyLong.  Explicitly do this long check conversion first. In
146          GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
147          to be done first to ensure we do not lose information in the
148          conversion process.  */
149       if (PyLong_Check (end_obj))
150         end = PyLong_AsUnsignedLongLong (end_obj);
151 #if PY_MAJOR_VERSION == 2
152       else if (PyInt_Check (end_obj))
153         /* If the end_pc value is specified without a trailing 'L', end_obj will
154            be an integer and not a long integer.  */
155         end = PyInt_AsLong (end_obj);
156 #endif
157       else
158         {
159           PyErr_SetString (PyExc_TypeError,
160                            _("Argument 'end_pc' should be a (long) integer."));
161
162           return NULL;
163         }
164
165       if (end < start)
166         {
167           PyErr_SetString (PyExc_ValueError,
168                            _("Argument 'end_pc' should be greater than or "
169                              "equal to the argument 'start_pc'."));
170
171           return NULL;
172         }
173     }
174   if (count_obj)
175     {
176       count = PyInt_AsLong (count_obj);
177       if (PyErr_Occurred () || count < 0)
178         {
179           PyErr_SetString (PyExc_TypeError,
180                            _("Argument 'count' should be an non-negative "
181                              "integer."));
182
183           return NULL;
184         }
185     }
186
187   gdbpy_ref<> result_list (PyList_New (0));
188   if (result_list == NULL)
189     return NULL;
190
191   for (pc = start, i = 0;
192        /* All args are specified.  */
193        (end_obj && count_obj && pc <= end && i < count)
194        /* end_pc is specified, but no count.  */
195        || (end_obj && count_obj == NULL && pc <= end)
196        /* end_pc is not specified, but a count is.  */
197        || (end_obj == NULL && count_obj && i < count)
198        /* Both end_pc and count are not specified.  */
199        || (end_obj == NULL && count_obj == NULL && pc == start);)
200     {
201       int insn_len = 0;
202       gdbpy_ref<> insn_dict (PyDict_New ());
203
204       if (insn_dict == NULL)
205         return NULL;
206       if (PyList_Append (result_list.get (), insn_dict.get ()))
207         return NULL;  /* PyList_Append Sets the exception.  */
208
209       string_file stb;
210
211       try
212         {
213           insn_len = gdb_print_insn (gdbarch, pc, &stb, NULL);
214         }
215       catch (const gdb_exception &except)
216         {
217           gdbpy_convert_exception (except);
218           return NULL;
219         }
220
221       gdbpy_ref<> pc_obj = gdb_py_object_from_ulongest (pc);
222       if (pc_obj == nullptr)
223         return nullptr;
224
225       gdbpy_ref<> asm_obj (PyString_FromString (!stb.empty ()
226                                                 ? stb.c_str ()
227                                                 : "<unknown>"));
228       if (asm_obj == nullptr)
229         return nullptr;
230
231       gdbpy_ref<> len_obj = gdb_py_object_from_longest (insn_len);
232       if (len_obj == nullptr)
233         return nullptr;
234
235       if (PyDict_SetItemString (insn_dict.get (), "addr", pc_obj.get ())
236           || PyDict_SetItemString (insn_dict.get (), "asm", asm_obj.get ())
237           || PyDict_SetItemString (insn_dict.get (), "length", len_obj.get ()))
238         return NULL;
239
240       pc += insn_len;
241       i++;
242     }
243
244   return result_list.release ();
245 }
246
247 /* Implementation of gdb.Architecture.registers (self, reggroup) -> Iterator.
248    Returns an iterator over register descriptors for registers in GROUP
249    within the architecture SELF.  */
250
251 static PyObject *
252 archpy_registers (PyObject *self, PyObject *args, PyObject *kw)
253 {
254   static const char *keywords[] = { "reggroup", NULL };
255   struct gdbarch *gdbarch = NULL;
256   const char *group_name = NULL;
257
258   /* Parse method arguments.  */
259   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|s", keywords,
260                                         &group_name))
261     return NULL;
262
263   /* Extract the gdbarch from the self object.  */
264   ARCHPY_REQUIRE_VALID (self, gdbarch);
265
266   return gdbpy_new_register_descriptor_iterator (gdbarch, group_name);
267 }
268
269 /* Implementation of gdb.Architecture.register_groups (self) -> Iterator.
270    Returns an iterator that will give up all valid register groups in the
271    architecture SELF.  */
272
273 static PyObject *
274 archpy_register_groups (PyObject *self, PyObject *args)
275 {
276   struct gdbarch *gdbarch = NULL;
277
278   /* Extract the gdbarch from the self object.  */
279   ARCHPY_REQUIRE_VALID (self, gdbarch);
280   return gdbpy_new_reggroup_iterator (gdbarch);
281 }
282
283 /* Implementation of gdb.integer_type.  */
284 static PyObject *
285 archpy_integer_type (PyObject *self, PyObject *args, PyObject *kw)
286 {
287   static const char *keywords[] = { "size", "signed", NULL };
288   int size;
289   PyObject *is_signed_obj = nullptr;
290
291   if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "i|O", keywords,
292                                         &size, &is_signed_obj))
293     return nullptr;
294
295   /* Assume signed by default.  */
296   bool is_signed = (is_signed_obj == nullptr
297                     || PyObject_IsTrue (is_signed_obj));
298
299   struct gdbarch *gdbarch;
300   ARCHPY_REQUIRE_VALID (self, gdbarch);
301
302   const struct builtin_type *builtins = builtin_type (gdbarch);
303   struct type *type = nullptr;
304   switch (size)
305     {
306     case 0:
307       type = builtins->builtin_int0;
308       break;
309     case 8:
310       type = is_signed ? builtins->builtin_int8 : builtins->builtin_uint8;
311       break;
312     case 16:
313       type = is_signed ? builtins->builtin_int16 : builtins->builtin_uint16;
314       break;
315     case 24:
316       type = is_signed ? builtins->builtin_int24 : builtins->builtin_uint24;
317       break;
318     case 32:
319       type = is_signed ? builtins->builtin_int32 : builtins->builtin_uint32;
320       break;
321     case 64:
322       type = is_signed ? builtins->builtin_int64 : builtins->builtin_uint64;
323       break;
324     case 128:
325       type = is_signed ? builtins->builtin_int128 : builtins->builtin_uint128;
326       break;
327
328     default:
329       PyErr_SetString (PyExc_ValueError,
330                        _("no integer type of that size is available"));
331       return nullptr;
332     }
333
334   return type_to_type_object (type);
335 }
336
337 /* Implementation of gdb.architecture_names().  Return a list of all the
338    BFD architecture names that GDB understands.  */
339
340 PyObject *
341 gdbpy_all_architecture_names (PyObject *self, PyObject *args)
342 {
343   gdbpy_ref<> list (PyList_New (0));
344   if (list == nullptr)
345     return nullptr;
346
347   std::vector<const char *> name_list = gdbarch_printable_names ();
348   for (const char *name : name_list)
349     {
350       gdbpy_ref <> py_name (PyString_FromString (name));
351       if (py_name == nullptr)
352         return nullptr;
353       if (PyList_Append (list.get (), py_name.get ()) < 0)
354         return nullptr;
355     }
356
357  return list.release ();
358 }
359
360 void _initialize_py_arch ();
361 void
362 _initialize_py_arch ()
363 {
364   arch_object_data = gdbarch_data_register_post_init (arch_object_data_init);
365 }
366
367 /* Initializes the Architecture class in the gdb module.  */
368
369 int
370 gdbpy_initialize_arch (void)
371 {
372   arch_object_type.tp_new = PyType_GenericNew;
373   if (PyType_Ready (&arch_object_type) < 0)
374     return -1;
375
376   return gdb_pymodule_addobject (gdb_module, "Architecture",
377                                  (PyObject *) &arch_object_type);
378 }
379
380 static PyMethodDef arch_object_methods [] = {
381   { "name", archpy_name, METH_NOARGS,
382     "name () -> String.\n\
383 Return the name of the architecture as a string value." },
384   { "disassemble", (PyCFunction) archpy_disassemble,
385     METH_VARARGS | METH_KEYWORDS,
386     "disassemble (start_pc [, end_pc [, count]]) -> List.\n\
387 Return a list of at most COUNT disassembled instructions from START_PC to\n\
388 END_PC." },
389   { "integer_type", (PyCFunction) archpy_integer_type,
390     METH_VARARGS | METH_KEYWORDS,
391     "integer_type (size [, signed]) -> type\n\
392 Return an integer Type corresponding to the given bitsize and signed-ness.\n\
393 If not specified, the type defaults to signed." },
394   { "registers", (PyCFunction) archpy_registers,
395     METH_VARARGS | METH_KEYWORDS,
396     "registers ([ group-name ]) -> Iterator.\n\
397 Return an iterator of register descriptors for the registers in register\n\
398 group GROUP-NAME." },
399   { "register_groups", archpy_register_groups,
400     METH_NOARGS,
401     "register_groups () -> Iterator.\n\
402 Return an iterator over all of the register groups in this architecture." },
403   {NULL}  /* Sentinel */
404 };
405
406 PyTypeObject arch_object_type = {
407   PyVarObject_HEAD_INIT (NULL, 0)
408   "gdb.Architecture",                 /* tp_name */
409   sizeof (arch_object),               /* tp_basicsize */
410   0,                                  /* tp_itemsize */
411   0,                                  /* tp_dealloc */
412   0,                                  /* tp_print */
413   0,                                  /* tp_getattr */
414   0,                                  /* tp_setattr */
415   0,                                  /* tp_compare */
416   0,                                  /* tp_repr */
417   0,                                  /* tp_as_number */
418   0,                                  /* tp_as_sequence */
419   0,                                  /* tp_as_mapping */
420   0,                                  /* tp_hash  */
421   0,                                  /* tp_call */
422   0,                                  /* tp_str */
423   0,                                  /* tp_getattro */
424   0,                                  /* tp_setattro */
425   0,                                  /* tp_as_buffer */
426   Py_TPFLAGS_DEFAULT,                 /* tp_flags */
427   "GDB architecture object",          /* tp_doc */
428   0,                                  /* tp_traverse */
429   0,                                  /* tp_clear */
430   0,                                  /* tp_richcompare */
431   0,                                  /* tp_weaklistoffset */
432   0,                                  /* tp_iter */
433   0,                                  /* tp_iternext */
434   arch_object_methods,                /* tp_methods */
435   0,                                  /* tp_members */
436   0,                                  /* tp_getset */
437   0,                                  /* tp_base */
438   0,                                  /* tp_dict */
439   0,                                  /* tp_descr_get */
440   0,                                  /* tp_descr_set */
441   0,                                  /* tp_dictoffset */
442   0,                                  /* tp_init */
443   0,                                  /* tp_alloc */
444 };
This page took 0.040531 seconds and 2 git commands to generate.