]> Git Repo - binutils.git/blob - gdb/python/py-utils.c
gdb: remove SYMTAB_COMPUNIT macro, add getter/setter
[binutils.git] / gdb / python / py-utils.c
1 /* General utility routines for GDB/Python.
2
3    Copyright (C) 2008-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 "charset.h"
22 #include "value.h"
23 #include "python-internal.h"
24
25 /* Converts a Python 8-bit string to a unicode string object.  Assumes the
26    8-bit string is in the host charset.  If an error occurs during conversion,
27    returns NULL with a python exception set.
28
29    As an added bonus, the functions accepts a unicode string and returns it
30    right away, so callers don't need to check which kind of string they've
31    got.  In Python 3, all strings are Unicode so this case is always the
32    one that applies.
33
34    If the given object is not one of the mentioned string types, NULL is
35    returned, with the TypeError python exception set.  */
36 gdbpy_ref<>
37 python_string_to_unicode (PyObject *obj)
38 {
39   PyObject *unicode_str;
40
41   /* If obj is already a unicode string, just return it.
42      I wish life was always that simple...  */
43   if (PyUnicode_Check (obj))
44     {
45       unicode_str = obj;
46       Py_INCREF (obj);
47     }
48 #ifndef IS_PY3K
49   else if (PyString_Check (obj))
50     unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
51 #endif
52   else
53     {
54       PyErr_SetString (PyExc_TypeError,
55                        _("Expected a string or unicode object."));
56       unicode_str = NULL;
57     }
58
59   return gdbpy_ref<> (unicode_str);
60 }
61
62 /* Returns a newly allocated string with the contents of the given unicode
63    string object converted to CHARSET.  If an error occurs during the
64    conversion, NULL will be returned and a python exception will be
65    set.  */
66 static gdb::unique_xmalloc_ptr<char>
67 unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
68 {
69   /* Translate string to named charset.  */
70   gdbpy_ref<> string (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
71   if (string == NULL)
72     return NULL;
73
74   return gdb::unique_xmalloc_ptr<char>
75     (xstrdup (PyBytes_AsString (string.get ())));
76 }
77
78 /* Returns a PyObject with the contents of the given unicode string
79    object converted to a named charset.  If an error occurs during
80    the conversion, NULL will be returned and a python exception will
81    be set.  */
82 static gdbpy_ref<>
83 unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
84 {
85   /* Translate string to named charset.  */
86   return gdbpy_ref<> (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
87 }
88
89 /* Returns a newly allocated string with the contents of the given
90    unicode string object converted to the target's charset.  If an
91    error occurs during the conversion, NULL will be returned and a
92    python exception will be set.  */
93 gdb::unique_xmalloc_ptr<char>
94 unicode_to_target_string (PyObject *unicode_str)
95 {
96   return (unicode_to_encoded_string
97           (unicode_str,
98            target_charset (gdbpy_enter::get_gdbarch ())));
99 }
100
101 /* Returns a PyObject with the contents of the given unicode string
102    object converted to the target's charset.  If an error occurs
103    during the conversion, NULL will be returned and a python exception
104    will be set.  */
105 static gdbpy_ref<>
106 unicode_to_target_python_string (PyObject *unicode_str)
107 {
108   return (unicode_to_encoded_python_string
109           (unicode_str,
110            target_charset (gdbpy_enter::get_gdbarch ())));
111 }
112
113 /* Converts a python string (8-bit or unicode) to a target string in
114    the target's charset.  Returns NULL on error, with a python
115    exception set.  */
116 gdb::unique_xmalloc_ptr<char>
117 python_string_to_target_string (PyObject *obj)
118 {
119   gdbpy_ref<> str = python_string_to_unicode (obj);
120   if (str == NULL)
121     return NULL;
122
123   return unicode_to_target_string (str.get ());
124 }
125
126 /* Converts a python string (8-bit or unicode) to a target string in the
127    target's charset.  Returns NULL on error, with a python exception
128    set.
129
130    In Python 3, the returned object is a "bytes" object (not a string).  */
131 gdbpy_ref<>
132 python_string_to_target_python_string (PyObject *obj)
133 {
134   gdbpy_ref<> str = python_string_to_unicode (obj);
135   if (str == NULL)
136     return str;
137
138   return unicode_to_target_python_string (str.get ());
139 }
140
141 /* Converts a python string (8-bit or unicode) to a target string in
142    the host's charset.  Returns NULL on error, with a python exception
143    set.  */
144 gdb::unique_xmalloc_ptr<char>
145 python_string_to_host_string (PyObject *obj)
146 {
147   gdbpy_ref<> str = python_string_to_unicode (obj);
148   if (str == NULL)
149     return NULL;
150
151   return unicode_to_encoded_string (str.get (), host_charset ());
152 }
153
154 /* Convert a host string to a python string.  */
155
156 gdbpy_ref<>
157 host_string_to_python_string (const char *str)
158 {
159   return gdbpy_ref<> (PyString_Decode (str, strlen (str), host_charset (),
160                                        NULL));
161 }
162
163 /* Return true if OBJ is a Python string or unicode object, false
164    otherwise.  */
165
166 int
167 gdbpy_is_string (PyObject *obj)
168 {
169 #ifdef IS_PY3K
170   return PyUnicode_Check (obj);
171 #else
172   return PyString_Check (obj) || PyUnicode_Check (obj);
173 #endif
174 }
175
176 /* Return the string representation of OBJ, i.e., str (obj).
177    If the result is NULL a python error occurred, the caller must clear it.  */
178
179 gdb::unique_xmalloc_ptr<char>
180 gdbpy_obj_to_string (PyObject *obj)
181 {
182   gdbpy_ref<> str_obj (PyObject_Str (obj));
183
184   if (str_obj != NULL)
185     {
186       gdb::unique_xmalloc_ptr<char> msg;
187
188 #ifdef IS_PY3K
189       msg = python_string_to_host_string (str_obj.get ());
190 #else
191       msg.reset (xstrdup (PyString_AsString (str_obj.get ())));
192 #endif
193
194       return msg;
195     }
196
197   return NULL;
198 }
199
200 /* See python-internal.h.  */
201
202 gdb::unique_xmalloc_ptr<char>
203 gdbpy_err_fetch::to_string () const
204 {
205   /* There are a few cases to consider.
206      For example:
207      value is a string when PyErr_SetString is used.
208      value is not a string when raise "foo" is used, instead it is None
209      and type is "foo".
210      So the algorithm we use is to print `str (value)' if it's not
211      None, otherwise we print `str (type)'.
212      Using str (aka PyObject_Str) will fetch the error message from
213      gdb.GdbError ("message").  */
214
215   if (m_error_value && m_error_value != Py_None)
216     return gdbpy_obj_to_string (m_error_value);
217   else
218     return gdbpy_obj_to_string (m_error_type);
219 }
220
221 /* See python-internal.h.  */
222
223 gdb::unique_xmalloc_ptr<char>
224 gdbpy_err_fetch::type_to_string () const
225 {
226   return gdbpy_obj_to_string (m_error_type);
227 }
228
229 /* Convert a GDB exception to the appropriate Python exception.
230
231    This sets the Python error indicator.  */
232
233 void
234 gdbpy_convert_exception (const struct gdb_exception &exception)
235 {
236   PyObject *exc_class;
237
238   if (exception.reason == RETURN_QUIT)
239     exc_class = PyExc_KeyboardInterrupt;
240   else if (exception.error == MEMORY_ERROR)
241     exc_class = gdbpy_gdb_memory_error;
242   else
243     exc_class = gdbpy_gdb_error;
244
245   PyErr_Format (exc_class, "%s", exception.what ());
246 }
247
248 /* Converts OBJ to a CORE_ADDR value.
249
250    Returns 0 on success or -1 on failure, with a Python exception set.
251 */
252
253 int
254 get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
255 {
256   if (gdbpy_is_value_object (obj))
257     {
258
259       try
260         {
261           *addr = value_as_address (value_object_to_value (obj));
262         }
263       catch (const gdb_exception &except)
264         {
265           GDB_PY_SET_HANDLE_EXCEPTION (except);
266         }
267     }
268   else
269     {
270       gdbpy_ref<> num (PyNumber_Long (obj));
271       gdb_py_ulongest val;
272
273       if (num == NULL)
274         return -1;
275
276       val = gdb_py_long_as_ulongest (num.get ());
277       if (PyErr_Occurred ())
278         return -1;
279
280       if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
281         {
282           PyErr_SetString (PyExc_ValueError,
283                            _("Overflow converting to address."));
284           return -1;
285         }
286
287       *addr = val;
288     }
289
290   return 0;
291 }
292
293 /* Convert a LONGEST to the appropriate Python object -- either an
294    integer object or a long object, depending on its value.  */
295
296 gdbpy_ref<>
297 gdb_py_object_from_longest (LONGEST l)
298 {
299 #ifdef IS_PY3K
300   if (sizeof (l) > sizeof (long))
301     return gdbpy_ref<> (PyLong_FromLongLong (l));
302   return gdbpy_ref<> (PyLong_FromLong (l));
303 #else
304 #ifdef HAVE_LONG_LONG           /* Defined by Python.  */
305   /* If we have 'long long', and the value overflows a 'long', use a
306      Python Long; otherwise use a Python Int.  */
307   if (sizeof (l) > sizeof (long)
308       && (l > PyInt_GetMax () || l < (- (LONGEST) PyInt_GetMax ()) - 1))
309     return gdbpy_ref<> (PyLong_FromLongLong (l));
310 #endif
311   return gdbpy_ref<> (PyInt_FromLong (l));
312 #endif
313 }
314
315 /* Convert a ULONGEST to the appropriate Python object -- either an
316    integer object or a long object, depending on its value.  */
317
318 gdbpy_ref<>
319 gdb_py_object_from_ulongest (ULONGEST l)
320 {
321 #ifdef IS_PY3K
322   if (sizeof (l) > sizeof (unsigned long))
323     return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
324   return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
325 #else
326 #ifdef HAVE_LONG_LONG           /* Defined by Python.  */
327   /* If we have 'long long', and the value overflows a 'long', use a
328      Python Long; otherwise use a Python Int.  */
329   if (sizeof (l) > sizeof (unsigned long) && l > PyInt_GetMax ())
330     return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
331 #endif
332
333   if (l > PyInt_GetMax ())
334     return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
335
336   return gdbpy_ref<> (PyInt_FromLong (l));
337 #endif
338 }
339
340 /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
341    the value into an out parameter.  */
342
343 int
344 gdb_py_int_as_long (PyObject *obj, long *result)
345 {
346   *result = PyInt_AsLong (obj);
347   return ! (*result == -1 && PyErr_Occurred ());
348 }
349
350 \f
351
352 /* Generic implementation of the __dict__ attribute for objects that
353    have a dictionary.  The CLOSURE argument should be the type object.
354    This only handles positive values for tp_dictoffset.  */
355
356 PyObject *
357 gdb_py_generic_dict (PyObject *self, void *closure)
358 {
359   PyObject *result;
360   PyTypeObject *type_obj = (PyTypeObject *) closure;
361   char *raw_ptr;
362
363   raw_ptr = (char *) self + type_obj->tp_dictoffset;
364   result = * (PyObject **) raw_ptr;
365
366   Py_INCREF (result);
367   return result;
368 }
369
370 /* Like PyModule_AddObject, but does not steal a reference to
371    OBJECT.  */
372
373 int
374 gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
375 {
376   int result;
377
378   Py_INCREF (object);
379   result = PyModule_AddObject (module, name, object);
380   if (result < 0)
381     Py_DECREF (object);
382   return result;
383 }
384
385 /* Handle a Python exception when the special gdb.GdbError treatment
386    is desired.  This should only be called when an exception is set.
387    If the exception is a gdb.GdbError, throw a gdb exception with the
388    exception text.  For other exceptions, print the Python stack and
389    then throw a gdb exception.  */
390
391 void
392 gdbpy_handle_exception ()
393 {
394   gdbpy_err_fetch fetched_error;
395   gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
396
397   if (msg == NULL)
398     {
399       /* An error occurred computing the string representation of the
400          error message.  This is rare, but we should inform the user.  */
401       printf_filtered (_("An error occurred in Python "
402                          "and then another occurred computing the "
403                          "error message.\n"));
404       gdbpy_print_stack ();
405     }
406
407   /* Don't print the stack for gdb.GdbError exceptions.
408      It is generally used to flag user errors.
409
410      We also don't want to print "Error occurred in Python command"
411      for user errors.  However, a missing message for gdb.GdbError
412      exceptions is arguably a bug, so we flag it as such.  */
413
414   if (fetched_error.type_matches (PyExc_KeyboardInterrupt))
415     throw_quit ("Quit");
416   else if (! fetched_error.type_matches (gdbpy_gdberror_exc)
417            || msg == NULL || *msg == '\0')
418     {
419       fetched_error.restore ();
420       gdbpy_print_stack ();
421       if (msg != NULL && *msg != '\0')
422         error (_("Error occurred in Python: %s"), msg.get ());
423       else
424         error (_("Error occurred in Python."));
425     }
426   else
427     error ("%s", msg.get ());
428 }
This page took 0.049672 seconds and 4 git commands to generate.