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