xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/python/py-utils.c (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
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 /* 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 PyObject *
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 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 set.
66 
67    The caller is responsible for xfree'ing the string.  */
68 static gdb::unique_xmalloc_ptr<char>
69 unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
70 {
71   gdb::unique_xmalloc_ptr<char> result;
72 
73   /* Translate string to named charset.  */
74   gdbpy_ref<> string (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
75   if (string == NULL)
76     return NULL;
77 
78 #ifdef IS_PY3K
79   result.reset (xstrdup (PyBytes_AsString (string.get ())));
80 #else
81   result.reset (xstrdup (PyString_AsString (string.get ())));
82 #endif
83 
84   return result;
85 }
86 
87 /* Returns a PyObject with the contents of the given unicode string
88    object converted to a named charset.  If an error occurs during
89    the conversion, NULL will be returned and a python exception will
90    be set.  */
91 static PyObject *
92 unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
93 {
94   /* Translate string to named charset.  */
95   return PyUnicode_AsEncodedString (unicode_str, charset, NULL);
96 }
97 
98 /* Returns a newly allocated string with the contents of the given
99    unicode string object converted to the target's charset.  If an
100    error occurs during the conversion, NULL will be returned and a
101    python exception will be set.  */
102 gdb::unique_xmalloc_ptr<char>
103 unicode_to_target_string (PyObject *unicode_str)
104 {
105   return unicode_to_encoded_string (unicode_str,
106 				    target_charset (python_gdbarch));
107 }
108 
109 /* Returns a PyObject with the contents of the given unicode string
110    object converted to the target's charset.  If an error occurs
111    during the conversion, NULL will be returned and a python exception
112    will be set.  */
113 static PyObject *
114 unicode_to_target_python_string (PyObject *unicode_str)
115 {
116   return unicode_to_encoded_python_string (unicode_str,
117 					   target_charset (python_gdbarch));
118 }
119 
120 /* Converts a python string (8-bit or unicode) to a target string in
121    the target's charset.  Returns NULL on error, with a python
122    exception set.  */
123 gdb::unique_xmalloc_ptr<char>
124 python_string_to_target_string (PyObject *obj)
125 {
126   gdbpy_ref<> str (python_string_to_unicode (obj));
127   if (str == NULL)
128     return NULL;
129 
130   return unicode_to_target_string (str.get ());
131 }
132 
133 /* Converts a python string (8-bit or unicode) to a target string in the
134    target's charset.  Returns NULL on error, with a python exception
135    set.
136 
137    In Python 3, the returned object is a "bytes" object (not a string).  */
138 PyObject *
139 python_string_to_target_python_string (PyObject *obj)
140 {
141   gdbpy_ref<> str (python_string_to_unicode (obj));
142   if (str == NULL)
143     return NULL;
144 
145   return unicode_to_target_python_string (str.get ());
146 }
147 
148 /* Converts a python string (8-bit or unicode) to a target string in
149    the host's charset.  Returns NULL on error, with a python exception
150    set.  */
151 gdb::unique_xmalloc_ptr<char>
152 python_string_to_host_string (PyObject *obj)
153 {
154   gdbpy_ref<> str (python_string_to_unicode (obj));
155   if (str == NULL)
156     return NULL;
157 
158   return unicode_to_encoded_string (str.get (), host_charset ());
159 }
160 
161 /* Convert a host string to a python string.  */
162 
163 PyObject *
164 host_string_to_python_string (const char *str)
165 {
166   return PyString_Decode (str, strlen (str), host_charset (), 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 /* Return the string representation of the exception represented by
207    TYPE, VALUE which is assumed to have been obtained with PyErr_Fetch,
208    i.e., the error indicator is currently clear.
209    If the result is NULL a python error occurred, the caller must clear it.  */
210 
211 gdb::unique_xmalloc_ptr<char>
212 gdbpy_exception_to_string (PyObject *ptype, PyObject *pvalue)
213 {
214   /* There are a few cases to consider.
215      For example:
216      pvalue is a string when PyErr_SetString is used.
217      pvalue is not a string when raise "foo" is used, instead it is None
218      and ptype is "foo".
219      So the algorithm we use is to print `str (pvalue)' if it's not
220      None, otherwise we print `str (ptype)'.
221      Using str (aka PyObject_Str) will fetch the error message from
222      gdb.GdbError ("message").  */
223 
224   if (pvalue && pvalue != Py_None)
225     return gdbpy_obj_to_string (pvalue);
226   else
227     return gdbpy_obj_to_string (ptype);
228 }
229 
230 /* Convert a GDB exception to the appropriate Python exception.
231 
232    This sets the Python error indicator.  */
233 
234 void
235 gdbpy_convert_exception (struct gdb_exception exception)
236 {
237   PyObject *exc_class;
238 
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 
246   PyErr_Format (exc_class, "%s", exception.message);
247 }
248 
249 /* Converts OBJ to a CORE_ADDR value.
250 
251    Returns 0 on success or -1 on failure, with a Python exception set.
252 */
253 
254 int
255 get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
256 {
257   if (gdbpy_is_value_object (obj))
258     {
259 
260       TRY
261 	{
262 	  *addr = value_as_address (value_object_to_value (obj));
263 	}
264       CATCH (except, RETURN_MASK_ALL)
265 	{
266 	  GDB_PY_SET_HANDLE_EXCEPTION (except);
267 	}
268       END_CATCH
269     }
270   else
271     {
272       gdbpy_ref<> num (PyNumber_Long (obj));
273       gdb_py_ulongest val;
274 
275       if (num == NULL)
276 	return -1;
277 
278       val = gdb_py_long_as_ulongest (num.get ());
279       if (PyErr_Occurred ())
280 	return -1;
281 
282       if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
283 	{
284 	  PyErr_SetString (PyExc_ValueError,
285 			   _("Overflow converting to address."));
286 	  return -1;
287 	}
288 
289       *addr = val;
290     }
291 
292   return 0;
293 }
294 
295 /* Convert a LONGEST to the appropriate Python object -- either an
296    integer object or a long object, depending on its value.  */
297 
298 PyObject *
299 gdb_py_object_from_longest (LONGEST l)
300 {
301 #ifdef IS_PY3K
302   if (sizeof (l) > sizeof (long))
303     return PyLong_FromLongLong (l);
304   return PyLong_FromLong (l);
305 #else
306 #ifdef HAVE_LONG_LONG		/* Defined by Python.  */
307   /* If we have 'long long', and the value overflows a 'long', use a
308      Python Long; otherwise use a Python Int.  */
309   if (sizeof (l) > sizeof (long)
310       && (l > PyInt_GetMax () || l < (- (LONGEST) PyInt_GetMax ()) - 1))
311     return PyLong_FromLongLong (l);
312 #endif
313   return PyInt_FromLong (l);
314 #endif
315 }
316 
317 /* Convert a ULONGEST to the appropriate Python object -- either an
318    integer object or a long object, depending on its value.  */
319 
320 PyObject *
321 gdb_py_object_from_ulongest (ULONGEST l)
322 {
323 #ifdef IS_PY3K
324   if (sizeof (l) > sizeof (unsigned long))
325     return PyLong_FromUnsignedLongLong (l);
326   return PyLong_FromUnsignedLong (l);
327 #else
328 #ifdef HAVE_LONG_LONG		/* Defined by Python.  */
329   /* If we have 'long long', and the value overflows a 'long', use a
330      Python Long; otherwise use a Python Int.  */
331   if (sizeof (l) > sizeof (unsigned long) && l > PyInt_GetMax ())
332     return PyLong_FromUnsignedLongLong (l);
333 #endif
334 
335   if (l > PyInt_GetMax ())
336     return PyLong_FromUnsignedLong (l);
337 
338   return PyInt_FromLong (l);
339 #endif
340 }
341 
342 /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
343    the value into an out parameter.  */
344 
345 int
346 gdb_py_int_as_long (PyObject *obj, long *result)
347 {
348   *result = PyInt_AsLong (obj);
349   return ! (*result == -1 && PyErr_Occurred ());
350 }
351 
352 
353 
354 /* Generic implementation of the __dict__ attribute for objects that
355    have a dictionary.  The CLOSURE argument should be the type object.
356    This only handles positive values for tp_dictoffset.  */
357 
358 PyObject *
359 gdb_py_generic_dict (PyObject *self, void *closure)
360 {
361   PyObject *result;
362   PyTypeObject *type_obj = (PyTypeObject *) closure;
363   char *raw_ptr;
364 
365   raw_ptr = (char *) self + type_obj->tp_dictoffset;
366   result = * (PyObject **) raw_ptr;
367 
368   Py_INCREF (result);
369   return result;
370 }
371 
372 /* Like PyModule_AddObject, but does not steal a reference to
373    OBJECT.  */
374 
375 int
376 gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
377 {
378   int result;
379 
380   Py_INCREF (object);
381   /* Python 2.4 did not have a 'const' here.  */
382   result = PyModule_AddObject (module, (char *) name, object);
383   if (result < 0)
384     Py_DECREF (object);
385   return result;
386 }
387