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