py-utils.c revision 1.6
1/* General utility routines for GDB/Python.
2
3   Copyright (C) 2008-2016 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
26/* This is a cleanup function which decrements the refcount on a
27   Python object.  */
28
29static void
30py_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
40struct cleanup *
41make_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
50static void
51py_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
62struct cleanup *
63make_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.  */
79PyObject *
80python_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.  */
110static char *
111unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
112{
113  char *result;
114  PyObject *string;
115
116  /* Translate string to named charset.  */
117  string = PyUnicode_AsEncodedString (unicode_str, charset, NULL);
118  if (string == NULL)
119    return NULL;
120
121#ifdef IS_PY3K
122  result = xstrdup (PyBytes_AsString (string));
123#else
124  result = xstrdup (PyString_AsString (string));
125#endif
126
127  Py_DECREF (string);
128
129  return result;
130}
131
132/* Returns a PyObject with the contents of the given unicode string
133   object converted to a named charset.  If an error occurs during
134   the conversion, NULL will be returned and a python exception will
135   be set.  */
136static PyObject *
137unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
138{
139  /* Translate string to named charset.  */
140  return PyUnicode_AsEncodedString (unicode_str, charset, NULL);
141}
142
143/* Returns a newly allocated string with the contents of the given unicode
144   string object converted to the target's charset.  If an error occurs during
145   the conversion, NULL will be returned and a python exception will be set.
146
147   The caller is responsible for xfree'ing the string.  */
148char *
149unicode_to_target_string (PyObject *unicode_str)
150{
151  return unicode_to_encoded_string (unicode_str,
152				    target_charset (python_gdbarch));
153}
154
155/* Returns a PyObject with the contents of the given unicode string
156   object converted to the target's charset.  If an error occurs
157   during the conversion, NULL will be returned and a python exception
158   will be set.  */
159static PyObject *
160unicode_to_target_python_string (PyObject *unicode_str)
161{
162  return unicode_to_encoded_python_string (unicode_str,
163					   target_charset (python_gdbarch));
164}
165
166/* Converts a python string (8-bit or unicode) to a target string in
167   the target's charset.  Returns NULL on error, with a python exception set.
168
169   The caller is responsible for xfree'ing the string.  */
170char *
171python_string_to_target_string (PyObject *obj)
172{
173  PyObject *str;
174  char *result;
175
176  str = python_string_to_unicode (obj);
177  if (str == NULL)
178    return NULL;
179
180  result = unicode_to_target_string (str);
181  Py_DECREF (str);
182  return result;
183}
184
185/* Converts a python string (8-bit or unicode) to a target string in the
186   target's charset.  Returns NULL on error, with a python exception
187   set.
188
189   In Python 3, the returned object is a "bytes" object (not a string).  */
190PyObject *
191python_string_to_target_python_string (PyObject *obj)
192{
193  PyObject *str;
194  PyObject *result;
195
196  str = python_string_to_unicode (obj);
197  if (str == NULL)
198    return NULL;
199
200  result = unicode_to_target_python_string (str);
201  Py_DECREF (str);
202  return result;
203}
204
205/* Converts a python string (8-bit or unicode) to a target string in
206   the host's charset.  Returns NULL on error, with a python exception set.
207
208   The caller is responsible for xfree'ing the string.  */
209char *
210python_string_to_host_string (PyObject *obj)
211{
212  PyObject *str;
213  char *result;
214
215  str = python_string_to_unicode (obj);
216  if (str == NULL)
217    return NULL;
218
219  result = unicode_to_encoded_string (str, host_charset ());
220  Py_DECREF (str);
221  return result;
222}
223
224/* Convert a host string to a python string.  */
225
226PyObject *
227host_string_to_python_string (const char *str)
228{
229  return PyString_Decode (str, strlen (str), host_charset (), NULL);
230}
231
232/* Return true if OBJ is a Python string or unicode object, false
233   otherwise.  */
234
235int
236gdbpy_is_string (PyObject *obj)
237{
238#ifdef IS_PY3K
239  return PyUnicode_Check (obj);
240#else
241  return PyString_Check (obj) || PyUnicode_Check (obj);
242#endif
243}
244
245/* Return the string representation of OBJ, i.e., str (obj).
246   Space for the result is malloc'd, the caller must free.
247   If the result is NULL a python error occurred, the caller must clear it.  */
248
249char *
250gdbpy_obj_to_string (PyObject *obj)
251{
252  PyObject *str_obj = PyObject_Str (obj);
253
254  if (str_obj != NULL)
255    {
256#ifdef IS_PY3K
257      char *msg = python_string_to_host_string (str_obj);
258#else
259      char *msg = xstrdup (PyString_AsString (str_obj));
260#endif
261
262      Py_DECREF (str_obj);
263      return msg;
264    }
265
266  return NULL;
267}
268
269/* Return the string representation of the exception represented by
270   TYPE, VALUE which is assumed to have been obtained with PyErr_Fetch,
271   i.e., the error indicator is currently clear.
272   Space for the result is malloc'd, the caller must free.
273   If the result is NULL a python error occurred, the caller must clear it.  */
274
275char *
276gdbpy_exception_to_string (PyObject *ptype, PyObject *pvalue)
277{
278  char *str;
279
280  /* There are a few cases to consider.
281     For example:
282     pvalue is a string when PyErr_SetString is used.
283     pvalue is not a string when raise "foo" is used, instead it is None
284     and ptype is "foo".
285     So the algorithm we use is to print `str (pvalue)' if it's not
286     None, otherwise we print `str (ptype)'.
287     Using str (aka PyObject_Str) will fetch the error message from
288     gdb.GdbError ("message").  */
289
290  if (pvalue && pvalue != Py_None)
291    str = gdbpy_obj_to_string (pvalue);
292  else
293    str = gdbpy_obj_to_string (ptype);
294
295  return str;
296}
297
298/* Convert a GDB exception to the appropriate Python exception.
299
300   This sets the Python error indicator.  */
301
302void
303gdbpy_convert_exception (struct gdb_exception exception)
304{
305  PyObject *exc_class;
306
307  if (exception.reason == RETURN_QUIT)
308    exc_class = PyExc_KeyboardInterrupt;
309  else if (exception.error == MEMORY_ERROR)
310    exc_class = gdbpy_gdb_memory_error;
311  else
312    exc_class = gdbpy_gdb_error;
313
314  PyErr_Format (exc_class, "%s", exception.message);
315}
316
317/* Converts OBJ to a CORE_ADDR value.
318
319   Returns 0 on success or -1 on failure, with a Python exception set.
320*/
321
322int
323get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
324{
325  if (gdbpy_is_value_object (obj))
326    {
327
328      TRY
329	{
330	  *addr = value_as_address (value_object_to_value (obj));
331	}
332      CATCH (except, RETURN_MASK_ALL)
333	{
334	  GDB_PY_SET_HANDLE_EXCEPTION (except);
335	}
336      END_CATCH
337    }
338  else
339    {
340      PyObject *num = PyNumber_Long (obj);
341      gdb_py_ulongest val;
342
343      if (num == NULL)
344	return -1;
345
346      val = gdb_py_long_as_ulongest (num);
347      Py_XDECREF (num);
348      if (PyErr_Occurred ())
349	return -1;
350
351      if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
352	{
353	  PyErr_SetString (PyExc_ValueError,
354			   _("Overflow converting to address."));
355	  return -1;
356	}
357
358      *addr = val;
359    }
360
361  return 0;
362}
363
364/* Convert a LONGEST to the appropriate Python object -- either an
365   integer object or a long object, depending on its value.  */
366
367PyObject *
368gdb_py_object_from_longest (LONGEST l)
369{
370#ifdef IS_PY3K
371  if (sizeof (l) > sizeof (long))
372    return PyLong_FromLongLong (l);
373  return PyLong_FromLong (l);
374#else
375#ifdef HAVE_LONG_LONG		/* Defined by Python.  */
376  /* If we have 'long long', and the value overflows a 'long', use a
377     Python Long; otherwise use a Python Int.  */
378  if (sizeof (l) > sizeof (long)
379      && (l > PyInt_GetMax () || l < (- (LONGEST) PyInt_GetMax ()) - 1))
380    return PyLong_FromLongLong (l);
381#endif
382  return PyInt_FromLong (l);
383#endif
384}
385
386/* Convert a ULONGEST to the appropriate Python object -- either an
387   integer object or a long object, depending on its value.  */
388
389PyObject *
390gdb_py_object_from_ulongest (ULONGEST l)
391{
392#ifdef IS_PY3K
393  if (sizeof (l) > sizeof (unsigned long))
394    return PyLong_FromUnsignedLongLong (l);
395  return PyLong_FromUnsignedLong (l);
396#else
397#ifdef HAVE_LONG_LONG		/* Defined by Python.  */
398  /* If we have 'long long', and the value overflows a 'long', use a
399     Python Long; otherwise use a Python Int.  */
400  if (sizeof (l) > sizeof (unsigned long) && l > PyInt_GetMax ())
401    return PyLong_FromUnsignedLongLong (l);
402#endif
403
404  if (l > PyInt_GetMax ())
405    return PyLong_FromUnsignedLong (l);
406
407  return PyInt_FromLong (l);
408#endif
409}
410
411/* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
412   the value into an out parameter.  */
413
414int
415gdb_py_int_as_long (PyObject *obj, long *result)
416{
417  *result = PyInt_AsLong (obj);
418  return ! (*result == -1 && PyErr_Occurred ());
419}
420
421
422
423/* Generic implementation of the __dict__ attribute for objects that
424   have a dictionary.  The CLOSURE argument should be the type object.
425   This only handles positive values for tp_dictoffset.  */
426
427PyObject *
428gdb_py_generic_dict (PyObject *self, void *closure)
429{
430  PyObject *result;
431  PyTypeObject *type_obj = (PyTypeObject *) closure;
432  char *raw_ptr;
433
434  raw_ptr = (char *) self + type_obj->tp_dictoffset;
435  result = * (PyObject **) raw_ptr;
436
437  Py_INCREF (result);
438  return result;
439}
440
441/* Like PyModule_AddObject, but does not steal a reference to
442   OBJECT.  */
443
444int
445gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
446{
447  int result;
448
449  Py_INCREF (object);
450  /* Python 2.4 did not have a 'const' here.  */
451  result = PyModule_AddObject (module, (char *) name, object);
452  if (result < 0)
453    Py_DECREF (object);
454  return result;
455}
456