Fix redefinition errors in C++ mode
[external/binutils.git] / gdb / python / py-objfile.c
1 /* Python interface to objfiles.
2
3    Copyright (C) 2008-2015 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 "python-internal.h"
22 #include "charset.h"
23 #include "objfiles.h"
24 #include "language.h"
25 #include "build-id.h"
26 #include "elf-bfd.h"
27 #include "symtab.h"
28
29 typedef struct
30 {
31   PyObject_HEAD
32
33   /* The corresponding objfile.  */
34   struct objfile *objfile;
35
36   /* Dictionary holding user-added attributes.
37      This is the __dict__ attribute of the object.  */
38   PyObject *dict;
39
40   /* The pretty-printer list of functions.  */
41   PyObject *printers;
42
43   /* The frame filter list of functions.  */
44   PyObject *frame_filters;
45   /* The type-printer list.  */
46   PyObject *type_printers;
47
48   /* The debug method matcher list.  */
49   PyObject *xmethods;
50 } objfile_object;
51
52 extern PyTypeObject objfile_object_type
53     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("objfile_object");
54
55 static const struct objfile_data *objfpy_objfile_data_key;
56
57 /* Require that OBJF be a valid objfile.  */
58 #define OBJFPY_REQUIRE_VALID(obj)                               \
59   do {                                                          \
60     if (!(obj)->objfile)                                        \
61       {                                                         \
62         PyErr_SetString (PyExc_RuntimeError,                    \
63                          _("Objfile no longer exists."));       \
64         return NULL;                                            \
65       }                                                         \
66   } while (0)
67
68 \f
69
70 /* An Objfile method which returns the objfile's file name, or None.  */
71
72 static PyObject *
73 objfpy_get_filename (PyObject *self, void *closure)
74 {
75   objfile_object *obj = (objfile_object *) self;
76
77   if (obj->objfile)
78     return PyString_Decode (objfile_name (obj->objfile),
79                             strlen (objfile_name (obj->objfile)),
80                             host_charset (), NULL);
81   Py_RETURN_NONE;
82 }
83
84 /* An Objfile method which returns the objfile's file name, as specified
85    by the user, or None.  */
86
87 static PyObject *
88 objfpy_get_username (PyObject *self, void *closure)
89 {
90   objfile_object *obj = (objfile_object *) self;
91
92   if (obj->objfile)
93     {
94       const char *username = obj->objfile->original_name;
95
96       return PyString_Decode (username, strlen (username),
97                               host_charset (), NULL);
98     }
99
100   Py_RETURN_NONE;
101 }
102
103 /* If SELF is a separate debug-info file, return the "backlink" field.
104    Otherwise return None.  */
105
106 static PyObject *
107 objfpy_get_owner (PyObject *self, void *closure)
108 {
109   objfile_object *obj = (objfile_object *) self;
110   struct objfile *objfile = obj->objfile;
111   struct objfile *owner;
112
113   OBJFPY_REQUIRE_VALID (obj);
114
115   owner = objfile->separate_debug_objfile_backlink;
116   if (owner != NULL)
117     {
118       PyObject *result = objfile_to_objfile_object (owner);
119
120       Py_XINCREF (result);
121       return result;
122     }
123   Py_RETURN_NONE;
124 }
125
126 /* An Objfile method which returns the objfile's build id, or None.  */
127
128 static PyObject *
129 objfpy_get_build_id (PyObject *self, void *closure)
130 {
131   objfile_object *obj = (objfile_object *) self;
132   struct objfile *objfile = obj->objfile;
133   const struct elf_build_id *build_id = NULL;
134   volatile struct gdb_exception except;
135
136   OBJFPY_REQUIRE_VALID (obj);
137
138   TRY_CATCH (except, RETURN_MASK_ALL)
139     {
140       build_id = build_id_bfd_get (objfile->obfd);
141     }
142   GDB_PY_HANDLE_EXCEPTION (except);
143
144   if (build_id != NULL)
145     {
146       char *hex_form = make_hex_string (build_id->data, build_id->size);
147       PyObject *result;
148
149       result = PyString_Decode (hex_form, strlen (hex_form),
150                                 host_charset (), NULL);
151       xfree (hex_form);
152       return result;
153     }
154
155   Py_RETURN_NONE;
156 }
157
158 /* An Objfile method which returns the objfile's progspace, or None.  */
159
160 static PyObject *
161 objfpy_get_progspace (PyObject *self, void *closure)
162 {
163   objfile_object *obj = (objfile_object *) self;
164
165   if (obj->objfile)
166     {
167       PyObject *pspace =  pspace_to_pspace_object (obj->objfile->pspace);
168
169       Py_XINCREF (pspace);
170       return pspace;
171     }
172
173   Py_RETURN_NONE;
174 }
175
176 static void
177 objfpy_dealloc (PyObject *o)
178 {
179   objfile_object *self = (objfile_object *) o;
180
181   Py_XDECREF (self->dict);
182   Py_XDECREF (self->printers);
183   Py_XDECREF (self->frame_filters);
184   Py_XDECREF (self->type_printers);
185   Py_XDECREF (self->xmethods);
186   Py_TYPE (self)->tp_free (self);
187 }
188
189 /* Initialize an objfile_object.
190    The result is a boolean indicating success.  */
191
192 static int
193 objfpy_initialize (objfile_object *self)
194 {
195   self->objfile = NULL;
196   self->dict = NULL;
197
198   self->printers = PyList_New (0);
199   if (self->printers == NULL)
200     return 0;
201
202   self->frame_filters = PyDict_New ();
203   if (self->frame_filters == NULL)
204     return 0;
205
206   self->type_printers = PyList_New (0);
207   if (self->type_printers == NULL)
208     return 0;
209
210   self->xmethods = PyList_New (0);
211   if (self->xmethods == NULL)
212     return 0;
213
214   return 1;
215 }
216
217 static PyObject *
218 objfpy_new (PyTypeObject *type, PyObject *args, PyObject *keywords)
219 {
220   objfile_object *self = (objfile_object *) type->tp_alloc (type, 0);
221
222   if (self)
223     {
224       if (!objfpy_initialize (self))
225         {
226           Py_DECREF (self);
227           return NULL;
228         }
229     }
230
231   return (PyObject *) self;
232 }
233
234 PyObject *
235 objfpy_get_printers (PyObject *o, void *ignore)
236 {
237   objfile_object *self = (objfile_object *) o;
238
239   Py_INCREF (self->printers);
240   return self->printers;
241 }
242
243 static int
244 objfpy_set_printers (PyObject *o, PyObject *value, void *ignore)
245 {
246   PyObject *tmp;
247   objfile_object *self = (objfile_object *) o;
248
249   if (! value)
250     {
251       PyErr_SetString (PyExc_TypeError,
252                        _("Cannot delete the pretty_printers attribute."));
253       return -1;
254     }
255
256   if (! PyList_Check (value))
257     {
258       PyErr_SetString (PyExc_TypeError,
259                        _("The pretty_printers attribute must be a list."));
260       return -1;
261     }
262
263   /* Take care in case the LHS and RHS are related somehow.  */
264   tmp = self->printers;
265   Py_INCREF (value);
266   self->printers = value;
267   Py_XDECREF (tmp);
268
269   return 0;
270 }
271
272 /* Return the Python dictionary attribute containing frame filters for
273    this object file.  */
274 PyObject *
275 objfpy_get_frame_filters (PyObject *o, void *ignore)
276 {
277   objfile_object *self = (objfile_object *) o;
278
279   Py_INCREF (self->frame_filters);
280   return self->frame_filters;
281 }
282
283 /* Set this object file's frame filters dictionary to FILTERS.  */
284 static int
285 objfpy_set_frame_filters (PyObject *o, PyObject *filters, void *ignore)
286 {
287   PyObject *tmp;
288   objfile_object *self = (objfile_object *) o;
289
290   if (! filters)
291     {
292       PyErr_SetString (PyExc_TypeError,
293                        _("Cannot delete the frame filters attribute."));
294       return -1;
295     }
296
297   if (! PyDict_Check (filters))
298     {
299       PyErr_SetString (PyExc_TypeError,
300                        _("The frame_filters attribute must be a dictionary."));
301       return -1;
302     }
303
304   /* Take care in case the LHS and RHS are related somehow.  */
305   tmp = self->frame_filters;
306   Py_INCREF (filters);
307   self->frame_filters = filters;
308   Py_XDECREF (tmp);
309
310   return 0;
311 }
312
313 /* Get the 'type_printers' attribute.  */
314
315 static PyObject *
316 objfpy_get_type_printers (PyObject *o, void *ignore)
317 {
318   objfile_object *self = (objfile_object *) o;
319
320   Py_INCREF (self->type_printers);
321   return self->type_printers;
322 }
323
324 /* Get the 'xmethods' attribute.  */
325
326 PyObject *
327 objfpy_get_xmethods (PyObject *o, void *ignore)
328 {
329   objfile_object *self = (objfile_object *) o;
330
331   Py_INCREF (self->xmethods);
332   return self->xmethods;
333 }
334
335 /* Set the 'type_printers' attribute.  */
336
337 static int
338 objfpy_set_type_printers (PyObject *o, PyObject *value, void *ignore)
339 {
340   PyObject *tmp;
341   objfile_object *self = (objfile_object *) o;
342
343   if (! value)
344     {
345       PyErr_SetString (PyExc_TypeError,
346                        _("Cannot delete the type_printers attribute."));
347       return -1;
348     }
349
350   if (! PyList_Check (value))
351     {
352       PyErr_SetString (PyExc_TypeError,
353                        _("The type_printers attribute must be a list."));
354       return -1;
355     }
356
357   /* Take care in case the LHS and RHS are related somehow.  */
358   tmp = self->type_printers;
359   Py_INCREF (value);
360   self->type_printers = value;
361   Py_XDECREF (tmp);
362
363   return 0;
364 }
365
366 /* Implementation of gdb.Objfile.is_valid (self) -> Boolean.
367    Returns True if this object file still exists in GDB.  */
368
369 static PyObject *
370 objfpy_is_valid (PyObject *self, PyObject *args)
371 {
372   objfile_object *obj = (objfile_object *) self;
373
374   if (! obj->objfile)
375     Py_RETURN_FALSE;
376
377   Py_RETURN_TRUE;
378 }
379
380 /* Implementation of gdb.Objfile.add_separate_debug_file (self) -> Boolean.  */
381
382 static PyObject *
383 objfpy_add_separate_debug_file (PyObject *self, PyObject *args, PyObject *kw)
384 {
385   static char *keywords[] = { "file_name", NULL };
386   objfile_object *obj = (objfile_object *) self;
387   const char *file_name;
388   int symfile_flags = 0;
389   volatile struct gdb_exception except;
390
391   OBJFPY_REQUIRE_VALID (obj);
392
393   if (!PyArg_ParseTupleAndKeywords (args, kw, "s", keywords, &file_name))
394     return NULL;
395
396   TRY_CATCH (except, RETURN_MASK_ALL)
397     {
398       bfd *abfd = symfile_bfd_open (file_name);
399
400       symbol_file_add_separate (abfd, file_name, symfile_flags, obj->objfile);
401     }
402   GDB_PY_HANDLE_EXCEPTION (except);
403
404   Py_RETURN_NONE;
405 }
406
407 /* Subroutine of gdbpy_lookup_objfile_by_build_id to simplify it.
408    Return non-zero if STRING is a potentially valid build id.  */
409
410 static int
411 objfpy_build_id_ok (const char *string)
412 {
413   size_t i, n = strlen (string);
414
415   if (n % 2 != 0)
416     return 0;
417   for (i = 0; i < n; ++i)
418     {
419       if (!isxdigit (string[i]))
420         return 0;
421     }
422   return 1;
423 }
424
425 /* Subroutine of gdbpy_lookup_objfile_by_build_id to simplify it.
426    Returns non-zero if BUILD_ID matches STRING.
427    It is assumed that objfpy_build_id_ok (string) returns TRUE.  */
428
429 static int
430 objfpy_build_id_matches (const struct elf_build_id *build_id,
431                          const char *string)
432 {
433   size_t i;
434
435   if (strlen (string) != 2 * build_id->size)
436     return 0;
437
438   for (i = 0; i < build_id->size; ++i)
439     {
440       char c1 = string[i * 2], c2 = string[i * 2 + 1];
441       int byte = (host_hex_value (c1) << 4) | host_hex_value (c2);
442
443       if (byte != build_id->data[i])
444         return 0;
445     }
446
447   return 1;
448 }
449
450 /* Subroutine of gdbpy_lookup_objfile to simplify it.
451    Look up an objfile by its file name.  */
452
453 static struct objfile *
454 objfpy_lookup_objfile_by_name (const char *name)
455 {
456   struct objfile *objfile;
457
458   ALL_OBJFILES (objfile)
459     {
460       const char *filename;
461
462       if ((objfile->flags & OBJF_NOT_FILENAME) != 0)
463         continue;
464       /* Don't return separate debug files.  */
465       if (objfile->separate_debug_objfile_backlink != NULL)
466         continue;
467
468       filename = objfile_filename (objfile);
469       if (filename != NULL && compare_filenames_for_search (filename, name))
470         return objfile;
471       if (compare_filenames_for_search (objfile->original_name, name))
472         return objfile;
473     }
474
475   return NULL;
476 }
477
478 /* Subroutine of gdbpy_lookup_objfile to simplify it.
479    Look up an objfile by its build id.  */
480
481 static struct objfile *
482 objfpy_lookup_objfile_by_build_id (const char *build_id)
483 {
484   struct objfile *objfile;
485
486   ALL_OBJFILES (objfile)
487     {
488       const struct elf_build_id *obfd_build_id;
489
490       if (objfile->obfd == NULL)
491         continue;
492       /* Don't return separate debug files.  */
493       if (objfile->separate_debug_objfile_backlink != NULL)
494         continue;
495       obfd_build_id = build_id_bfd_get (objfile->obfd);
496       if (obfd_build_id == NULL)
497         continue;
498       if (objfpy_build_id_matches (obfd_build_id, build_id))
499         return objfile;
500     }
501
502   return NULL;
503 }
504
505 /* Implementation of gdb.lookup_objfile.  */
506
507 PyObject *
508 gdbpy_lookup_objfile (PyObject *self, PyObject *args, PyObject *kw)
509 {
510   static char *keywords[] = { "name", "by_build_id", NULL };
511   const char *name;
512   PyObject *by_build_id_obj = NULL;
513   int by_build_id;
514   struct objfile *objfile;
515
516   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!", keywords,
517                                      &name, &PyBool_Type, &by_build_id_obj))
518     return NULL;
519
520   by_build_id = 0;
521   if (by_build_id_obj != NULL)
522     {
523       int cmp = PyObject_IsTrue (by_build_id_obj);
524
525       if (cmp < 0)
526         return NULL;
527       by_build_id = cmp;
528     }
529
530   if (by_build_id)
531     {
532       if (!objfpy_build_id_ok (name))
533         {
534           PyErr_SetString (PyExc_TypeError, _("Not a valid build id."));
535           return NULL;
536         }
537       objfile = objfpy_lookup_objfile_by_build_id (name);
538     }
539   else
540     objfile = objfpy_lookup_objfile_by_name (name);
541
542   if (objfile != NULL)
543     {
544       PyObject *result = objfile_to_objfile_object (objfile);
545
546       Py_XINCREF (result);
547       return result;
548     }
549
550   PyErr_SetString (PyExc_ValueError, _("Objfile not found."));
551   return NULL;
552 }
553
554 \f
555
556 /* Clear the OBJFILE pointer in an Objfile object and remove the
557    reference.  */
558 static void
559 py_free_objfile (struct objfile *objfile, void *datum)
560 {
561   struct cleanup *cleanup;
562   objfile_object *object = datum;
563
564   cleanup = ensure_python_env (get_objfile_arch (objfile), current_language);
565   object->objfile = NULL;
566   Py_DECREF ((PyObject *) object);
567   do_cleanups (cleanup);
568 }
569
570 /* Return a borrowed reference to the Python object of type Objfile
571    representing OBJFILE.  If the object has already been created,
572    return it.  Otherwise, create it.  Return NULL and set the Python
573    error on failure.  */
574
575 PyObject *
576 objfile_to_objfile_object (struct objfile *objfile)
577 {
578   objfile_object *object;
579
580   object = objfile_data (objfile, objfpy_objfile_data_key);
581   if (!object)
582     {
583       object = PyObject_New (objfile_object, &objfile_object_type);
584       if (object)
585         {
586           if (!objfpy_initialize (object))
587             {
588               Py_DECREF (object);
589               return NULL;
590             }
591
592           object->objfile = objfile;
593           set_objfile_data (objfile, objfpy_objfile_data_key, object);
594         }
595     }
596
597   return (PyObject *) object;
598 }
599
600 int
601 gdbpy_initialize_objfile (void)
602 {
603   objfpy_objfile_data_key
604     = register_objfile_data_with_cleanup (NULL, py_free_objfile);
605
606   if (PyType_Ready (&objfile_object_type) < 0)
607     return -1;
608
609   return gdb_pymodule_addobject (gdb_module, "Objfile",
610                                  (PyObject *) &objfile_object_type);
611 }
612
613 \f
614
615 static PyMethodDef objfile_object_methods[] =
616 {
617   { "is_valid", objfpy_is_valid, METH_NOARGS,
618     "is_valid () -> Boolean.\n\
619 Return true if this object file is valid, false if not." },
620
621   { "add_separate_debug_file", (PyCFunction) objfpy_add_separate_debug_file,
622     METH_VARARGS | METH_KEYWORDS,
623     "add_separate_debug_file (file_name).\n\
624 Add FILE_NAME to the list of files containing debug info for the objfile." },
625
626   { NULL }
627 };
628
629 static PyGetSetDef objfile_getset[] =
630 {
631   { "__dict__", gdb_py_generic_dict, NULL,
632     "The __dict__ for this objfile.", &objfile_object_type },
633   { "filename", objfpy_get_filename, NULL,
634     "The objfile's filename, or None.", NULL },
635   { "username", objfpy_get_username, NULL,
636     "The name of the objfile as provided by the user, or None.", NULL },
637   { "owner", objfpy_get_owner, NULL,
638     "The objfile owner of separate debug info objfiles, or None.",
639     NULL },
640   { "build_id", objfpy_get_build_id, NULL,
641     "The objfile's build id, or None.", NULL },
642   { "progspace", objfpy_get_progspace, NULL,
643     "The objfile's progspace, or None.", NULL },
644   { "pretty_printers", objfpy_get_printers, objfpy_set_printers,
645     "Pretty printers.", NULL },
646   { "frame_filters", objfpy_get_frame_filters,
647     objfpy_set_frame_filters, "Frame Filters.", NULL },
648   { "type_printers", objfpy_get_type_printers, objfpy_set_type_printers,
649     "Type printers.", NULL },
650   { "xmethods", objfpy_get_xmethods, NULL,
651     "Debug methods.", NULL },
652   { NULL }
653 };
654
655 PyTypeObject objfile_object_type =
656 {
657   PyVarObject_HEAD_INIT (NULL, 0)
658   "gdb.Objfile",                  /*tp_name*/
659   sizeof (objfile_object),        /*tp_basicsize*/
660   0,                              /*tp_itemsize*/
661   objfpy_dealloc,                 /*tp_dealloc*/
662   0,                              /*tp_print*/
663   0,                              /*tp_getattr*/
664   0,                              /*tp_setattr*/
665   0,                              /*tp_compare*/
666   0,                              /*tp_repr*/
667   0,                              /*tp_as_number*/
668   0,                              /*tp_as_sequence*/
669   0,                              /*tp_as_mapping*/
670   0,                              /*tp_hash */
671   0,                              /*tp_call*/
672   0,                              /*tp_str*/
673   0,                              /*tp_getattro*/
674   0,                              /*tp_setattro*/
675   0,                              /*tp_as_buffer*/
676   Py_TPFLAGS_DEFAULT,             /*tp_flags*/
677   "GDB objfile object",           /* tp_doc */
678   0,                              /* tp_traverse */
679   0,                              /* tp_clear */
680   0,                              /* tp_richcompare */
681   0,                              /* tp_weaklistoffset */
682   0,                              /* tp_iter */
683   0,                              /* tp_iternext */
684   objfile_object_methods,         /* tp_methods */
685   0,                              /* tp_members */
686   objfile_getset,                 /* tp_getset */
687   0,                              /* tp_base */
688   0,                              /* tp_dict */
689   0,                              /* tp_descr_get */
690   0,                              /* tp_descr_set */
691   offsetof (objfile_object, dict), /* tp_dictoffset */
692   0,                              /* tp_init */
693   0,                              /* tp_alloc */
694   objfpy_new,                     /* tp_new */
695 };