gdb/python/py-utils.c - gdb

Functions defined

Source code

  1. /* General utility routines for GDB/Python.

  2.    Copyright (C) 2008-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "charset.h"
  16. #include "value.h"
  17. #include "python-internal.h"


  18. /* This is a cleanup function which decrements the refcount on a
  19.    Python object.  */

  20. static void
  21. py_decref (void *p)
  22. {
  23.   PyObject *py = p;

  24.   Py_DECREF (py);
  25. }

  26. /* Return a new cleanup which will decrement the Python object's
  27.    refcount when run.  */

  28. struct cleanup *
  29. make_cleanup_py_decref (PyObject *py)
  30. {
  31.   return make_cleanup (py_decref, (void *) py);
  32. }

  33. /* This is a cleanup function which decrements the refcount on a
  34.    Python object.  This function accounts appropriately for NULL
  35.    references.  */

  36. static void
  37. py_xdecref (void *p)
  38. {
  39.   PyObject *py = p;

  40.   Py_XDECREF (py);
  41. }

  42. /* Return a new cleanup which will decrement the Python object's
  43.    refcount when run.  Account for and operate on NULL references
  44.    correctly.  */

  45. struct cleanup *
  46. make_cleanup_py_xdecref (PyObject *py)
  47. {
  48.   return make_cleanup (py_xdecref, py);
  49. }

  50. /* Converts a Python 8-bit string to a unicode string object.  Assumes the
  51.    8-bit string is in the host charset.  If an error occurs during conversion,
  52.    returns NULL with a python exception set.

  53.    As an added bonus, the functions accepts a unicode string and returns it
  54.    right away, so callers don't need to check which kind of string they've
  55.    got.  In Python 3, all strings are Unicode so this case is always the
  56.    one that applies.

  57.    If the given object is not one of the mentioned string types, NULL is
  58.    returned, with the TypeError python exception set.  */
  59. PyObject *
  60. python_string_to_unicode (PyObject *obj)
  61. {
  62.   PyObject *unicode_str;

  63.   /* If obj is already a unicode string, just return it.
  64.      I wish life was always that simple...  */
  65.   if (PyUnicode_Check (obj))
  66.     {
  67.       unicode_str = obj;
  68.       Py_INCREF (obj);
  69.     }
  70. #ifndef IS_PY3K
  71.   else if (PyString_Check (obj))
  72.     unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
  73. #endif
  74.   else
  75.     {
  76.       PyErr_SetString (PyExc_TypeError,
  77.                        _("Expected a string or unicode object."));
  78.       unicode_str = NULL;
  79.     }

  80.   return unicode_str;
  81. }

  82. /* Returns a newly allocated string with the contents of the given unicode
  83.    string object converted to CHARSET.  If an error occurs during the
  84.    conversion, NULL will be returned and a python exception will be set.

  85.    The caller is responsible for xfree'ing the string.  */
  86. static char *
  87. unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
  88. {
  89.   char *result;
  90.   PyObject *string;

  91.   /* Translate string to named charset.  */
  92.   string = PyUnicode_AsEncodedString (unicode_str, charset, NULL);
  93.   if (string == NULL)
  94.     return NULL;

  95. #ifdef IS_PY3K
  96.   result = xstrdup (PyBytes_AsString (string));
  97. #else
  98.   result = xstrdup (PyString_AsString (string));
  99. #endif

  100.   Py_DECREF (string);

  101.   return result;
  102. }

  103. /* Returns a PyObject with the contents of the given unicode string
  104.    object converted to a named charset.  If an error occurs during
  105.    the conversion, NULL will be returned and a python exception will
  106.    be set.  */
  107. static PyObject *
  108. unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
  109. {
  110.   /* Translate string to named charset.  */
  111.   return PyUnicode_AsEncodedString (unicode_str, charset, NULL);
  112. }

  113. /* Returns a newly allocated string with the contents of the given unicode
  114.    string object converted to the target's charset.  If an error occurs during
  115.    the conversion, NULL will be returned and a python exception will be set.

  116.    The caller is responsible for xfree'ing the string.  */
  117. char *
  118. unicode_to_target_string (PyObject *unicode_str)
  119. {
  120.   return unicode_to_encoded_string (unicode_str,
  121.                                     target_charset (python_gdbarch));
  122. }

  123. /* Returns a PyObject with the contents of the given unicode string
  124.    object converted to the target's charset.  If an error occurs
  125.    during the conversion, NULL will be returned and a python exception
  126.    will be set.  */
  127. static PyObject *
  128. unicode_to_target_python_string (PyObject *unicode_str)
  129. {
  130.   return unicode_to_encoded_python_string (unicode_str,
  131.                                            target_charset (python_gdbarch));
  132. }

  133. /* Converts a python string (8-bit or unicode) to a target string in
  134.    the target's charset.  Returns NULL on error, with a python exception set.

  135.    The caller is responsible for xfree'ing the string.  */
  136. char *
  137. python_string_to_target_string (PyObject *obj)
  138. {
  139.   PyObject *str;
  140.   char *result;

  141.   str = python_string_to_unicode (obj);
  142.   if (str == NULL)
  143.     return NULL;

  144.   result = unicode_to_target_string (str);
  145.   Py_DECREF (str);
  146.   return result;
  147. }

  148. /* Converts a python string (8-bit or unicode) to a target string in the
  149.    target's charset.  Returns NULL on error, with a python exception
  150.    set.

  151.    In Python 3, the returned object is a "bytes" object (not a string).  */
  152. PyObject *
  153. python_string_to_target_python_string (PyObject *obj)
  154. {
  155.   PyObject *str;
  156.   PyObject *result;

  157.   str = python_string_to_unicode (obj);
  158.   if (str == NULL)
  159.     return NULL;

  160.   result = unicode_to_target_python_string (str);
  161.   Py_DECREF (str);
  162.   return result;
  163. }

  164. /* Converts a python string (8-bit or unicode) to a target string in
  165.    the host's charset.  Returns NULL on error, with a python exception set.

  166.    The caller is responsible for xfree'ing the string.  */
  167. char *
  168. python_string_to_host_string (PyObject *obj)
  169. {
  170.   PyObject *str;
  171.   char *result;

  172.   str = python_string_to_unicode (obj);
  173.   if (str == NULL)
  174.     return NULL;

  175.   result = unicode_to_encoded_string (str, host_charset ());
  176.   Py_DECREF (str);
  177.   return result;
  178. }

  179. /* Return true if OBJ is a Python string or unicode object, false
  180.    otherwise.  */

  181. int
  182. gdbpy_is_string (PyObject *obj)
  183. {
  184. #ifdef IS_PY3K
  185.   return PyUnicode_Check (obj);
  186. #else
  187.   return PyString_Check (obj) || PyUnicode_Check (obj);
  188. #endif
  189. }

  190. /* Return the string representation of OBJ, i.e., str (obj).
  191.    Space for the result is malloc'd, the caller must free.
  192.    If the result is NULL a python error occurred, the caller must clear it.  */

  193. char *
  194. gdbpy_obj_to_string (PyObject *obj)
  195. {
  196.   PyObject *str_obj = PyObject_Str (obj);

  197.   if (str_obj != NULL)
  198.     {
  199. #ifdef IS_PY3K
  200.       char *msg = python_string_to_host_string (str_obj);
  201. #else
  202.       char *msg = xstrdup (PyString_AsString (str_obj));
  203. #endif

  204.       Py_DECREF (str_obj);
  205.       return msg;
  206.     }

  207.   return NULL;
  208. }

  209. /* Return the string representation of the exception represented by
  210.    TYPE, VALUE which is assumed to have been obtained with PyErr_Fetch,
  211.    i.e., the error indicator is currently clear.
  212.    Space for the result is malloc'd, the caller must free.
  213.    If the result is NULL a python error occurred, the caller must clear it.  */

  214. char *
  215. gdbpy_exception_to_string (PyObject *ptype, PyObject *pvalue)
  216. {
  217.   char *str;

  218.   /* There are a few cases to consider.
  219.      For example:
  220.      pvalue is a string when PyErr_SetString is used.
  221.      pvalue is not a string when raise "foo" is used, instead it is None
  222.      and ptype is "foo".
  223.      So the algorithm we use is to print `str (pvalue)' if it's not
  224.      None, otherwise we print `str (ptype)'.
  225.      Using str (aka PyObject_Str) will fetch the error message from
  226.      gdb.GdbError ("message").  */

  227.   if (pvalue && pvalue != Py_None)
  228.     str = gdbpy_obj_to_string (pvalue);
  229.   else
  230.     str = gdbpy_obj_to_string (ptype);

  231.   return str;
  232. }

  233. /* Convert a GDB exception to the appropriate Python exception.

  234.    This sets the Python error indicator.  */

  235. void
  236. gdbpy_convert_exception (struct gdb_exception exception)
  237. {
  238.   PyObject *exc_class;

  239.   if (exception.reason == RETURN_QUIT)
  240.     exc_class = PyExc_KeyboardInterrupt;
  241.   else if (exception.error == MEMORY_ERROR)
  242.     exc_class = gdbpy_gdb_memory_error;
  243.   else
  244.     exc_class = gdbpy_gdb_error;

  245.   PyErr_Format (exc_class, "%s", exception.message);
  246. }

  247. /* Converts OBJ to a CORE_ADDR value.

  248.    Returns 0 on success or -1 on failure, with a Python exception set.
  249. */

  250. int
  251. get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
  252. {
  253.   if (gdbpy_is_value_object (obj))
  254.     {
  255.       volatile struct gdb_exception except;

  256.       TRY_CATCH (except, RETURN_MASK_ALL)
  257.         {
  258.           *addr = value_as_address (value_object_to_value (obj));
  259.         }
  260.       GDB_PY_SET_HANDLE_EXCEPTION (except);
  261.     }
  262.   else
  263.     {
  264.       PyObject *num = PyNumber_Long (obj);
  265.       gdb_py_ulongest val;

  266.       if (num == NULL)
  267.         return -1;

  268.       val = gdb_py_long_as_ulongest (num);
  269.       Py_XDECREF (num);
  270.       if (PyErr_Occurred ())
  271.         return -1;

  272.       if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
  273.         {
  274.           PyErr_SetString (PyExc_ValueError,
  275.                            _("Overflow converting to address."));
  276.           return -1;
  277.         }

  278.       *addr = val;
  279.     }

  280.   return 0;
  281. }

  282. /* Convert a LONGEST to the appropriate Python object -- either an
  283.    integer object or a long object, depending on its value.  */

  284. PyObject *
  285. gdb_py_object_from_longest (LONGEST l)
  286. {
  287. #ifdef IS_PY3K
  288.   if (sizeof (l) > sizeof (long))
  289.     return PyLong_FromLongLong (l);
  290.   return PyLong_FromLong (l);
  291. #else
  292. #ifdef HAVE_LONG_LONG                /* Defined by Python.  */
  293.   /* If we have 'long long', and the value overflows a 'long', use a
  294.      Python Long; otherwise use a Python Int.  */
  295.   if (sizeof (l) > sizeof (long)
  296.       && (l > PyInt_GetMax () || l < (- (LONGEST) PyInt_GetMax ()) - 1))
  297.     return PyLong_FromLongLong (l);
  298. #endif
  299.   return PyInt_FromLong (l);
  300. #endif
  301. }

  302. /* Convert a ULONGEST to the appropriate Python object -- either an
  303.    integer object or a long object, depending on its value.  */

  304. PyObject *
  305. gdb_py_object_from_ulongest (ULONGEST l)
  306. {
  307. #ifdef IS_PY3K
  308.   if (sizeof (l) > sizeof (unsigned long))
  309.     return PyLong_FromUnsignedLongLong (l);
  310.   return PyLong_FromUnsignedLong (l);
  311. #else
  312. #ifdef HAVE_LONG_LONG                /* Defined by Python.  */
  313.   /* If we have 'long long', and the value overflows a 'long', use a
  314.      Python Long; otherwise use a Python Int.  */
  315.   if (sizeof (l) > sizeof (unsigned long) && l > PyInt_GetMax ())
  316.     return PyLong_FromUnsignedLongLong (l);
  317. #endif

  318.   if (l > PyInt_GetMax ())
  319.     return PyLong_FromUnsignedLong (l);

  320.   return PyInt_FromLong (l);
  321. #endif
  322. }

  323. /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
  324.    the value into an out parameter.  */

  325. int
  326. gdb_py_int_as_long (PyObject *obj, long *result)
  327. {
  328.   *result = PyInt_AsLong (obj);
  329.   return ! (*result == -1 && PyErr_Occurred ());
  330. }



  331. /* Generic implementation of the __dict__ attribute for objects that
  332.    have a dictionary.  The CLOSURE argument should be the type object.
  333.    This only handles positive values for tp_dictoffset.  */

  334. PyObject *
  335. gdb_py_generic_dict (PyObject *self, void *closure)
  336. {
  337.   PyObject *result;
  338.   PyTypeObject *type_obj = closure;
  339.   char *raw_ptr;

  340.   raw_ptr = (char *) self + type_obj->tp_dictoffset;
  341.   result = * (PyObject **) raw_ptr;

  342.   Py_INCREF (result);
  343.   return result;
  344. }

  345. /* Like PyModule_AddObject, but does not steal a reference to
  346.    OBJECT.  */

  347. int
  348. gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
  349. {
  350.   int result;

  351.   Py_INCREF (object);
  352.   /* Python 2.4 did not have a 'const' here.  */
  353.   result = PyModule_AddObject (module, (char *) name, object);
  354.   if (result < 0)
  355.     Py_DECREF (object);
  356.   return result;
  357. }