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