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