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