Update copyright year range in all GDB files.
[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"
830a4934 24#include "py-ref.h"
d57a3c85 25
d57a3c85
TJB
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
256458bc 32 got. In Python 3, all strings are Unicode so this case is always the
9a27f2c6 33 one that applies.
d57a3c85
TJB
34
35 If the given object is not one of the mentioned string types, NULL is
36 returned, with the TypeError python exception set. */
833d985d 37gdbpy_ref<>
d57a3c85
TJB
38python_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))
83390453
PM
45 {
46 unicode_str = obj;
47 Py_INCREF (obj);
48 }
9a27f2c6 49#ifndef IS_PY3K
d57a3c85
TJB
50 else if (PyString_Check (obj))
51 unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
9a27f2c6 52#endif
d57a3c85
TJB
53 else
54 {
55 PyErr_SetString (PyExc_TypeError,
56 _("Expected a string or unicode object."));
57 unicode_str = NULL;
58 }
59
833d985d 60 return gdbpy_ref<> (unicode_str);
d57a3c85
TJB
61}
62
63/* Returns a newly allocated string with the contents of the given unicode
08c637de 64 string object converted to CHARSET. If an error occurs during the
075c55e0
TT
65 conversion, NULL will be returned and a python exception will be
66 set. */
9b972014 67static gdb::unique_xmalloc_ptr<char>
08c637de 68unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
d57a3c85 69{
9b972014 70 gdb::unique_xmalloc_ptr<char> result;
d57a3c85 71
08c637de 72 /* Translate string to named charset. */
7780f186 73 gdbpy_ref<> string (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
d57a3c85
TJB
74 if (string == NULL)
75 return NULL;
76
9a27f2c6 77#ifdef IS_PY3K
830a4934 78 result.reset (xstrdup (PyBytes_AsString (string.get ())));
9a27f2c6 79#else
830a4934 80 result.reset (xstrdup (PyString_AsString (string.get ())));
9a27f2c6 81#endif
d57a3c85 82
08c637de
TJB
83 return result;
84}
85
fbb8f299
PM
86/* Returns a PyObject with the contents of the given unicode string
87 object converted to a named charset. If an error occurs during
88 the conversion, NULL will be returned and a python exception will
89 be set. */
833d985d 90static gdbpy_ref<>
fbb8f299
PM
91unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
92{
fbb8f299 93 /* Translate string to named charset. */
833d985d 94 return gdbpy_ref<> (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
fbb8f299
PM
95}
96
9b972014
TT
97/* Returns a newly allocated string with the contents of the given
98 unicode string object converted to the target's charset. If an
99 error occurs during the conversion, NULL will be returned and a
100 python exception will be set. */
101gdb::unique_xmalloc_ptr<char>
08c637de
TJB
102unicode_to_target_string (PyObject *unicode_str)
103{
f870a310
TT
104 return unicode_to_encoded_string (unicode_str,
105 target_charset (python_gdbarch));
d57a3c85
TJB
106}
107
fbb8f299
PM
108/* Returns a PyObject with the contents of the given unicode string
109 object converted to the target's charset. If an error occurs
110 during the conversion, NULL will be returned and a python exception
111 will be set. */
833d985d 112static gdbpy_ref<>
fbb8f299
PM
113unicode_to_target_python_string (PyObject *unicode_str)
114{
f870a310
TT
115 return unicode_to_encoded_python_string (unicode_str,
116 target_charset (python_gdbarch));
fbb8f299
PM
117}
118
d57a3c85 119/* Converts a python string (8-bit or unicode) to a target string in
9b972014
TT
120 the target's charset. Returns NULL on error, with a python
121 exception set. */
122gdb::unique_xmalloc_ptr<char>
d57a3c85
TJB
123python_string_to_target_string (PyObject *obj)
124{
833d985d 125 gdbpy_ref<> str = python_string_to_unicode (obj);
d57a3c85
TJB
126 if (str == NULL)
127 return NULL;
128
830a4934 129 return unicode_to_target_string (str.get ());
d57a3c85 130}
08c637de 131
fbb8f299
PM
132/* Converts a python string (8-bit or unicode) to a target string in the
133 target's charset. Returns NULL on error, with a python exception
9a27f2c6
PK
134 set.
135
136 In Python 3, the returned object is a "bytes" object (not a string). */
833d985d 137gdbpy_ref<>
fbb8f299
PM
138python_string_to_target_python_string (PyObject *obj)
139{
833d985d 140 gdbpy_ref<> str = python_string_to_unicode (obj);
fbb8f299 141 if (str == NULL)
833d985d 142 return str;
fbb8f299 143
830a4934 144 return unicode_to_target_python_string (str.get ());
fbb8f299
PM
145}
146
08c637de 147/* Converts a python string (8-bit or unicode) to a target string in
9b972014
TT
148 the host's charset. Returns NULL on error, with a python exception
149 set. */
150gdb::unique_xmalloc_ptr<char>
08c637de
TJB
151python_string_to_host_string (PyObject *obj)
152{
833d985d 153 gdbpy_ref<> str = python_string_to_unicode (obj);
08c637de
TJB
154 if (str == NULL)
155 return NULL;
156
830a4934 157 return unicode_to_encoded_string (str.get (), host_charset ());
08c637de
TJB
158}
159
4ae6cc19
DE
160/* Convert a host string to a python string. */
161
833d985d 162gdbpy_ref<>
4ae6cc19
DE
163host_string_to_python_string (const char *str)
164{
833d985d
TT
165 return gdbpy_ref<> (PyString_Decode (str, strlen (str), host_charset (),
166 NULL));
4ae6cc19
DE
167}
168
08c637de
TJB
169/* Return true if OBJ is a Python string or unicode object, false
170 otherwise. */
171
172int
173gdbpy_is_string (PyObject *obj)
174{
9a27f2c6
PK
175#ifdef IS_PY3K
176 return PyUnicode_Check (obj);
177#else
08c637de 178 return PyString_Check (obj) || PyUnicode_Check (obj);
9a27f2c6 179#endif
08c637de 180}
07ca107c
DE
181
182/* Return the string representation of OBJ, i.e., str (obj).
07ca107c
DE
183 If the result is NULL a python error occurred, the caller must clear it. */
184
9b972014 185gdb::unique_xmalloc_ptr<char>
07ca107c
DE
186gdbpy_obj_to_string (PyObject *obj)
187{
7780f186 188 gdbpy_ref<> str_obj (PyObject_Str (obj));
07ca107c
DE
189
190 if (str_obj != NULL)
191 {
9b972014
TT
192 gdb::unique_xmalloc_ptr<char> msg;
193
9a27f2c6 194#ifdef IS_PY3K
830a4934 195 msg = python_string_to_host_string (str_obj.get ());
9a27f2c6 196#else
830a4934 197 msg.reset (xstrdup (PyString_AsString (str_obj.get ())));
9a27f2c6 198#endif
07ca107c 199
07ca107c
DE
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.
07ca107c
DE
209 If the result is NULL a python error occurred, the caller must clear it. */
210
9b972014 211gdb::unique_xmalloc_ptr<char>
07ca107c
DE
212gdbpy_exception_to_string (PyObject *ptype, PyObject *pvalue)
213{
07ca107c
DE
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)
9b972014 225 return gdbpy_obj_to_string (pvalue);
07ca107c 226 else
9b972014 227 return gdbpy_obj_to_string (ptype);
07ca107c 228}
595939de 229
621c8364 230/* Convert a GDB exception to the appropriate Python exception.
256458bc 231
56cc411c 232 This sets the Python error indicator. */
621c8364 233
56cc411c 234void
621c8364
TT
235gdbpy_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
56cc411c 246 PyErr_Format (exc_class, "%s", exception.message);
621c8364
TT
247}
248
595939de
PM
249/* Converts OBJ to a CORE_ADDR value.
250
b86af38a 251 Returns 0 on success or -1 on failure, with a Python exception set.
595939de
PM
252*/
253
254int
255get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
256{
257 if (gdbpy_is_value_object (obj))
b86af38a 258 {
b86af38a 259
492d29ea 260 TRY
b86af38a
TT
261 {
262 *addr = value_as_address (value_object_to_value (obj));
263 }
492d29ea
PA
264 CATCH (except, RETURN_MASK_ALL)
265 {
266 GDB_PY_SET_HANDLE_EXCEPTION (except);
267 }
268 END_CATCH
b86af38a 269 }
74aedc46 270 else
595939de 271 {
7780f186 272 gdbpy_ref<> num (PyNumber_Long (obj));
74aedc46
TT
273 gdb_py_ulongest val;
274
275 if (num == NULL)
b86af38a 276 return -1;
595939de 277
830a4934 278 val = gdb_py_long_as_ulongest (num.get ());
74aedc46 279 if (PyErr_Occurred ())
b86af38a 280 return -1;
595939de 281
74aedc46
TT
282 if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
283 {
284 PyErr_SetString (PyExc_ValueError,
285 _("Overflow converting to address."));
b86af38a 286 return -1;
74aedc46 287 }
595939de 288
74aedc46 289 *addr = val;
595939de
PM
290 }
291
b86af38a 292 return 0;
595939de 293}
74aedc46
TT
294
295/* Convert a LONGEST to the appropriate Python object -- either an
296 integer object or a long object, depending on its value. */
297
12dfa12a 298gdbpy_ref<>
74aedc46
TT
299gdb_py_object_from_longest (LONGEST l)
300{
9a27f2c6
PK
301#ifdef IS_PY3K
302 if (sizeof (l) > sizeof (long))
12dfa12a
TT
303 return gdbpy_ref<> (PyLong_FromLongLong (l));
304 return gdbpy_ref<> (PyLong_FromLong (l));
9a27f2c6 305#else
74aedc46
TT
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))
12dfa12a 311 return gdbpy_ref<> (PyLong_FromLongLong (l));
74aedc46 312#endif
12dfa12a 313 return gdbpy_ref<> (PyInt_FromLong (l));
9a27f2c6 314#endif
74aedc46
TT
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
12dfa12a 320gdbpy_ref<>
74aedc46
TT
321gdb_py_object_from_ulongest (ULONGEST l)
322{
9a27f2c6
PK
323#ifdef IS_PY3K
324 if (sizeof (l) > sizeof (unsigned long))
12dfa12a
TT
325 return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
326 return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
9a27f2c6 327#else
74aedc46
TT
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 ())
12dfa12a 332 return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
74aedc46
TT
333#endif
334
335 if (l > PyInt_GetMax ())
12dfa12a 336 return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
74aedc46 337
12dfa12a 338 return gdbpy_ref<> (PyInt_FromLong (l));
9a27f2c6 339#endif
74aedc46
TT
340}
341
342/* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
343 the value into an out parameter. */
344
345int
346gdb_py_int_as_long (PyObject *obj, long *result)
347{
348 *result = PyInt_AsLong (obj);
349 return ! (*result == -1 && PyErr_Occurred ());
350}
2e8265fd
TT
351
352\f
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
358PyObject *
359gdb_py_generic_dict (PyObject *self, void *closure)
360{
361 PyObject *result;
19ba03f4 362 PyTypeObject *type_obj = (PyTypeObject *) closure;
2e8265fd
TT
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}
aa36459a
TT
371
372/* Like PyModule_AddObject, but does not steal a reference to
373 OBJECT. */
374
375int
376gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
377{
378 int result;
379
380 Py_INCREF (object);
351a6f02
TT
381 /* Python 2.4 did not have a 'const' here. */
382 result = PyModule_AddObject (module, (char *) name, object);
aa36459a 383 if (result < 0)
1915daeb 384 Py_DECREF (object);
aa36459a
TT
385 return result;
386}
2b4ad2fe
TT
387
388/* Handle a Python exception when the special gdb.GdbError treatment
389 is desired. This should only be called when an exception is set.
390 If the exception is a gdb.GdbError, throw a gdb exception with the
391 exception text. For other exceptions, print the Python stack and
392 then throw a gdb exception. */
393
394void
395gdbpy_handle_exception ()
396{
397 PyObject *ptype, *pvalue, *ptraceback;
398
399 PyErr_Fetch (&ptype, &pvalue, &ptraceback);
400
401 /* Try to fetch an error message contained within ptype, pvalue.
402 When fetching the error message we need to make our own copy,
403 we no longer own ptype, pvalue after the call to PyErr_Restore. */
404
405 gdb::unique_xmalloc_ptr<char>
406 msg (gdbpy_exception_to_string (ptype, pvalue));
407
408 if (msg == NULL)
409 {
410 /* An error occurred computing the string representation of the
411 error message. This is rare, but we should inform the user. */
412 printf_filtered (_("An error occurred in Python "
413 "and then another occurred computing the "
414 "error message.\n"));
415 gdbpy_print_stack ();
416 }
417
418 /* Don't print the stack for gdb.GdbError exceptions.
419 It is generally used to flag user errors.
420
421 We also don't want to print "Error occurred in Python command"
422 for user errors. However, a missing message for gdb.GdbError
423 exceptions is arguably a bug, so we flag it as such. */
424
bc543c90
TT
425 if (PyErr_GivenExceptionMatches (ptype, PyExc_KeyboardInterrupt))
426 throw_quit ("Quit");
427 else if (! PyErr_GivenExceptionMatches (ptype, gdbpy_gdberror_exc)
2b4ad2fe
TT
428 || msg == NULL || *msg == '\0')
429 {
430 PyErr_Restore (ptype, pvalue, ptraceback);
431 gdbpy_print_stack ();
432 if (msg != NULL && *msg != '\0')
433 error (_("Error occurred in Python: %s"), msg.get ());
434 else
435 error (_("Error occurred in Python."));
436 }
437 else
438 {
439 Py_XDECREF (ptype);
440 Py_XDECREF (pvalue);
441 Py_XDECREF (ptraceback);
442 error ("%s", msg.get ());
443 }
444}
This page took 1.097951 seconds and 4 git commands to generate.