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