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