GDB (API)
/home/stan/gdb/src/gdb/python/py-utils.c
Go to the documentation of this file.
00001 /* General utility routines for GDB/Python.
00002 
00003    Copyright (C) 2008-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 #include "defs.h"
00021 #include "charset.h"
00022 #include "value.h"
00023 #include "python-internal.h"
00024 
00025 
00026 /* This is a cleanup function which decrements the refcount on a
00027    Python object.  */
00028 
00029 static void
00030 py_decref (void *p)
00031 {
00032   PyObject *py = p;
00033 
00034   Py_DECREF (py);
00035 }
00036 
00037 /* Return a new cleanup which will decrement the Python object's
00038    refcount when run.  */
00039 
00040 struct cleanup *
00041 make_cleanup_py_decref (PyObject *py)
00042 {
00043   return make_cleanup (py_decref, (void *) py);
00044 }
00045 
00046 /* This is a cleanup function which decrements the refcount on a
00047    Python object.  This function accounts appropriately for NULL
00048    references.  */
00049 
00050 static void
00051 py_xdecref (void *p)
00052 {
00053   PyObject *py = p;
00054 
00055   Py_XDECREF (py);
00056 }
00057 
00058 /* Return a new cleanup which will decrement the Python object's
00059    refcount when run.  Account for and operate on NULL references
00060    correctly.  */
00061 
00062 struct cleanup *
00063 make_cleanup_py_xdecref (PyObject *py)
00064 {
00065   return make_cleanup (py_xdecref, py);
00066 }
00067 
00068 /* Converts a Python 8-bit string to a unicode string object.  Assumes the
00069    8-bit string is in the host charset.  If an error occurs during conversion,
00070    returns NULL with a python exception set.
00071 
00072    As an added bonus, the functions accepts a unicode string and returns it
00073    right away, so callers don't need to check which kind of string they've
00074    got.  In Python 3, all strings are Unicode so this case is always the 
00075    one that applies.
00076 
00077    If the given object is not one of the mentioned string types, NULL is
00078    returned, with the TypeError python exception set.  */
00079 PyObject *
00080 python_string_to_unicode (PyObject *obj)
00081 {
00082   PyObject *unicode_str;
00083 
00084   /* If obj is already a unicode string, just return it.
00085      I wish life was always that simple...  */
00086   if (PyUnicode_Check (obj))
00087     {
00088       unicode_str = obj;
00089       Py_INCREF (obj);
00090     }
00091 #ifndef IS_PY3K
00092   else if (PyString_Check (obj))
00093     unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
00094 #endif
00095   else
00096     {
00097       PyErr_SetString (PyExc_TypeError,
00098                        _("Expected a string or unicode object."));
00099       unicode_str = NULL;
00100     }
00101 
00102   return unicode_str;
00103 }
00104 
00105 /* Returns a newly allocated string with the contents of the given unicode
00106    string object converted to CHARSET.  If an error occurs during the
00107    conversion, NULL will be returned and a python exception will be set.
00108 
00109    The caller is responsible for xfree'ing the string.  */
00110 static char *
00111 unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
00112 {
00113   char *result;
00114   PyObject *string;
00115 
00116   /* Translate string to named charset.  */
00117   string = PyUnicode_AsEncodedString (unicode_str, charset, NULL);
00118   if (string == NULL)
00119     return NULL;
00120 
00121 #ifdef IS_PY3K
00122   result = xstrdup (PyBytes_AsString (string));
00123 #else
00124   result = xstrdup (PyString_AsString (string));
00125 #endif
00126 
00127   Py_DECREF (string);
00128 
00129   return result;
00130 }
00131 
00132 /* Returns a PyObject with the contents of the given unicode string
00133    object converted to a named charset.  If an error occurs during
00134    the conversion, NULL will be returned and a python exception will
00135    be set.  */
00136 static PyObject *
00137 unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
00138 {
00139   /* Translate string to named charset.  */
00140   return PyUnicode_AsEncodedString (unicode_str, charset, NULL);
00141 }
00142 
00143 /* Returns a newly allocated string with the contents of the given unicode
00144    string object converted to the target's charset.  If an error occurs during
00145    the conversion, NULL will be returned and a python exception will be set.
00146 
00147    The caller is responsible for xfree'ing the string.  */
00148 char *
00149 unicode_to_target_string (PyObject *unicode_str)
00150 {
00151   return unicode_to_encoded_string (unicode_str,
00152                                     target_charset (python_gdbarch));
00153 }
00154 
00155 /* Returns a PyObject with the contents of the given unicode string
00156    object converted to the target's charset.  If an error occurs
00157    during the conversion, NULL will be returned and a python exception
00158    will be set.  */
00159 static PyObject *
00160 unicode_to_target_python_string (PyObject *unicode_str)
00161 {
00162   return unicode_to_encoded_python_string (unicode_str,
00163                                            target_charset (python_gdbarch));
00164 }
00165 
00166 /* Converts a python string (8-bit or unicode) to a target string in
00167    the target's charset.  Returns NULL on error, with a python exception set.
00168 
00169    The caller is responsible for xfree'ing the string.  */
00170 char *
00171 python_string_to_target_string (PyObject *obj)
00172 {
00173   PyObject *str;
00174   char *result;
00175 
00176   str = python_string_to_unicode (obj);
00177   if (str == NULL)
00178     return NULL;
00179 
00180   result = unicode_to_target_string (str);
00181   Py_DECREF (str);
00182   return result;
00183 }
00184 
00185 /* Converts a python string (8-bit or unicode) to a target string in the
00186    target's charset.  Returns NULL on error, with a python exception
00187    set.
00188 
00189    In Python 3, the returned object is a "bytes" object (not a string).  */
00190 PyObject *
00191 python_string_to_target_python_string (PyObject *obj)
00192 {
00193   PyObject *str;
00194   PyObject *result;
00195 
00196   str = python_string_to_unicode (obj);
00197   if (str == NULL)
00198     return NULL;
00199 
00200   result = unicode_to_target_python_string (str);
00201   Py_DECREF (str);
00202   return result;
00203 }
00204 
00205 /* Converts a python string (8-bit or unicode) to a target string in
00206    the host's charset.  Returns NULL on error, with a python exception set.
00207 
00208    The caller is responsible for xfree'ing the string.  */
00209 char *
00210 python_string_to_host_string (PyObject *obj)
00211 {
00212   PyObject *str;
00213   char *result;
00214 
00215   str = python_string_to_unicode (obj);
00216   if (str == NULL)
00217     return NULL;
00218 
00219   result = unicode_to_encoded_string (str, host_charset ()); 
00220   Py_DECREF (str);
00221   return result;
00222 }
00223 
00224 /* Return true if OBJ is a Python string or unicode object, false
00225    otherwise.  */
00226 
00227 int
00228 gdbpy_is_string (PyObject *obj)
00229 {
00230 #ifdef IS_PY3K
00231   return PyUnicode_Check (obj);
00232 #else
00233   return PyString_Check (obj) || PyUnicode_Check (obj);
00234 #endif
00235 }
00236 
00237 /* Return the string representation of OBJ, i.e., str (obj).
00238    Space for the result is malloc'd, the caller must free.
00239    If the result is NULL a python error occurred, the caller must clear it.  */
00240 
00241 char *
00242 gdbpy_obj_to_string (PyObject *obj)
00243 {
00244   PyObject *str_obj = PyObject_Str (obj);
00245 
00246   if (str_obj != NULL)
00247     {
00248 #ifdef IS_PY3K
00249       char *msg = python_string_to_host_string (str_obj);
00250 #else
00251       char *msg = xstrdup (PyString_AsString (str_obj));
00252 #endif
00253 
00254       Py_DECREF (str_obj);
00255       return msg;
00256     }
00257 
00258   return NULL;
00259 }
00260 
00261 /* Return the string representation of the exception represented by
00262    TYPE, VALUE which is assumed to have been obtained with PyErr_Fetch,
00263    i.e., the error indicator is currently clear.
00264    Space for the result is malloc'd, the caller must free.
00265    If the result is NULL a python error occurred, the caller must clear it.  */
00266 
00267 char *
00268 gdbpy_exception_to_string (PyObject *ptype, PyObject *pvalue)
00269 {
00270   char *str;
00271 
00272   /* There are a few cases to consider.
00273      For example:
00274      pvalue is a string when PyErr_SetString is used.
00275      pvalue is not a string when raise "foo" is used, instead it is None
00276      and ptype is "foo".
00277      So the algorithm we use is to print `str (pvalue)' if it's not
00278      None, otherwise we print `str (ptype)'.
00279      Using str (aka PyObject_Str) will fetch the error message from
00280      gdb.GdbError ("message").  */
00281 
00282   if (pvalue && pvalue != Py_None)
00283     str = gdbpy_obj_to_string (pvalue);
00284   else
00285     str = gdbpy_obj_to_string (ptype);
00286 
00287   return str;
00288 }
00289 
00290 /* Convert a GDB exception to the appropriate Python exception.
00291    
00292    This sets the Python error indicator.  */
00293 
00294 void
00295 gdbpy_convert_exception (struct gdb_exception exception)
00296 {
00297   PyObject *exc_class;
00298 
00299   if (exception.reason == RETURN_QUIT)
00300     exc_class = PyExc_KeyboardInterrupt;
00301   else if (exception.error == MEMORY_ERROR)
00302     exc_class = gdbpy_gdb_memory_error;
00303   else
00304     exc_class = gdbpy_gdb_error;
00305 
00306   PyErr_Format (exc_class, "%s", exception.message);
00307 }
00308 
00309 /* Converts OBJ to a CORE_ADDR value.
00310 
00311    Returns 0 on success or -1 on failure, with a Python exception set.
00312 */
00313 
00314 int
00315 get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
00316 {
00317   if (gdbpy_is_value_object (obj))
00318     {
00319       volatile struct gdb_exception except;
00320 
00321       TRY_CATCH (except, RETURN_MASK_ALL)
00322         {
00323           *addr = value_as_address (value_object_to_value (obj));
00324         }
00325       GDB_PY_SET_HANDLE_EXCEPTION (except);
00326     }
00327   else
00328     {
00329       PyObject *num = PyNumber_Long (obj);
00330       gdb_py_ulongest val;
00331 
00332       if (num == NULL)
00333         return -1;
00334 
00335       val = gdb_py_long_as_ulongest (num);
00336       Py_XDECREF (num);
00337       if (PyErr_Occurred ())
00338         return -1;
00339 
00340       if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
00341         {
00342           PyErr_SetString (PyExc_ValueError,
00343                            _("Overflow converting to address."));
00344           return -1;
00345         }
00346 
00347       *addr = val;
00348     }
00349 
00350   return 0;
00351 }
00352 
00353 /* Convert a LONGEST to the appropriate Python object -- either an
00354    integer object or a long object, depending on its value.  */
00355 
00356 PyObject *
00357 gdb_py_object_from_longest (LONGEST l)
00358 {
00359 #ifdef IS_PY3K
00360   if (sizeof (l) > sizeof (long))
00361     return PyLong_FromLongLong (l);
00362   return PyLong_FromLong (l);
00363 #else
00364 #ifdef HAVE_LONG_LONG           /* Defined by Python.  */
00365   /* If we have 'long long', and the value overflows a 'long', use a
00366      Python Long; otherwise use a Python Int.  */
00367   if (sizeof (l) > sizeof (long)
00368       && (l > PyInt_GetMax () || l < (- (LONGEST) PyInt_GetMax ()) - 1))
00369     return PyLong_FromLongLong (l);
00370 #endif
00371   return PyInt_FromLong (l);
00372 #endif
00373 }
00374 
00375 /* Convert a ULONGEST to the appropriate Python object -- either an
00376    integer object or a long object, depending on its value.  */
00377 
00378 PyObject *
00379 gdb_py_object_from_ulongest (ULONGEST l)
00380 {
00381 #ifdef IS_PY3K
00382   if (sizeof (l) > sizeof (unsigned long))
00383     return PyLong_FromUnsignedLongLong (l);
00384   return PyLong_FromUnsignedLong (l);
00385 #else
00386 #ifdef HAVE_LONG_LONG           /* Defined by Python.  */
00387   /* If we have 'long long', and the value overflows a 'long', use a
00388      Python Long; otherwise use a Python Int.  */
00389   if (sizeof (l) > sizeof (unsigned long) && l > PyInt_GetMax ())
00390     return PyLong_FromUnsignedLongLong (l);
00391 #endif
00392 
00393   if (l > PyInt_GetMax ())
00394     return PyLong_FromUnsignedLong (l);
00395 
00396   return PyInt_FromLong (l);
00397 #endif
00398 }
00399 
00400 /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
00401    the value into an out parameter.  */
00402 
00403 int
00404 gdb_py_int_as_long (PyObject *obj, long *result)
00405 {
00406   *result = PyInt_AsLong (obj);
00407   return ! (*result == -1 && PyErr_Occurred ());
00408 }
00409 
00410 
00411 
00412 /* Generic implementation of the __dict__ attribute for objects that
00413    have a dictionary.  The CLOSURE argument should be the type object.
00414    This only handles positive values for tp_dictoffset.  */
00415 
00416 PyObject *
00417 gdb_py_generic_dict (PyObject *self, void *closure)
00418 {
00419   PyObject *result;
00420   PyTypeObject *type_obj = closure;
00421   char *raw_ptr;
00422 
00423   raw_ptr = (char *) self + type_obj->tp_dictoffset;
00424   result = * (PyObject **) raw_ptr;
00425 
00426   Py_INCREF (result);
00427   return result;
00428 }
00429 
00430 /* Like PyModule_AddObject, but does not steal a reference to
00431    OBJECT.  */
00432 
00433 int
00434 gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
00435 {
00436   int result;
00437 
00438   Py_INCREF (object);
00439   /* Python 2.4 did not have a 'const' here.  */
00440   result = PyModule_AddObject (module, (char *) name, object);
00441   if (result < 0)
00442     Py_DECREF (object);
00443   return result;
00444 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines