1 /* General utility routines for GDB/Python.
3 Copyright (C) 2008-2019 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
23 #include "python-internal.h"
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.
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
31 got. In Python 3, all strings are Unicode so this case is always the
34 If the given object is not one of the mentioned string types, NULL is
35 returned, with the TypeError python exception set. */
37 python_string_to_unicode (PyObject
*obj
)
39 PyObject
*unicode_str
;
41 /* If obj is already a unicode string, just return it.
42 I wish life was always that simple... */
43 if (PyUnicode_Check (obj
))
49 else if (PyString_Check (obj
))
50 unicode_str
= PyUnicode_FromEncodedObject (obj
, host_charset (), NULL
);
54 PyErr_SetString (PyExc_TypeError
,
55 _("Expected a string or unicode object."));
59 return gdbpy_ref
<> (unicode_str
);
62 /* Returns a newly allocated string with the contents of the given unicode
63 string object converted to CHARSET. If an error occurs during the
64 conversion, NULL will be returned and a python exception will be
66 static gdb::unique_xmalloc_ptr
<char>
67 unicode_to_encoded_string (PyObject
*unicode_str
, const char *charset
)
69 gdb::unique_xmalloc_ptr
<char> result
;
71 /* Translate string to named charset. */
72 gdbpy_ref
<> string (PyUnicode_AsEncodedString (unicode_str
, charset
, NULL
));
77 result
.reset (xstrdup (PyBytes_AsString (string
.get ())));
79 result
.reset (xstrdup (PyString_AsString (string
.get ())));
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
90 unicode_to_encoded_python_string (PyObject
*unicode_str
, const char *charset
)
92 /* Translate string to named charset. */
93 return gdbpy_ref
<> (PyUnicode_AsEncodedString (unicode_str
, charset
, NULL
));
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. */
100 gdb::unique_xmalloc_ptr
<char>
101 unicode_to_target_string (PyObject
*unicode_str
)
103 return unicode_to_encoded_string (unicode_str
,
104 target_charset (python_gdbarch
));
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
112 unicode_to_target_python_string (PyObject
*unicode_str
)
114 return unicode_to_encoded_python_string (unicode_str
,
115 target_charset (python_gdbarch
));
118 /* Converts a python string (8-bit or unicode) to a target string in
119 the target's charset. Returns NULL on error, with a python
121 gdb::unique_xmalloc_ptr
<char>
122 python_string_to_target_string (PyObject
*obj
)
124 gdbpy_ref
<> str
= python_string_to_unicode (obj
);
128 return unicode_to_target_string (str
.get ());
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
135 In Python 3, the returned object is a "bytes" object (not a string). */
137 python_string_to_target_python_string (PyObject
*obj
)
139 gdbpy_ref
<> str
= python_string_to_unicode (obj
);
143 return unicode_to_target_python_string (str
.get ());
146 /* Converts a python string (8-bit or unicode) to a target string in
147 the host's charset. Returns NULL on error, with a python exception
149 gdb::unique_xmalloc_ptr
<char>
150 python_string_to_host_string (PyObject
*obj
)
152 gdbpy_ref
<> str
= python_string_to_unicode (obj
);
156 return unicode_to_encoded_string (str
.get (), host_charset ());
159 /* Convert a host string to a python string. */
162 host_string_to_python_string (const char *str
)
164 return gdbpy_ref
<> (PyString_Decode (str
, strlen (str
), host_charset (),
168 /* Return true if OBJ is a Python string or unicode object, false
172 gdbpy_is_string (PyObject
*obj
)
175 return PyUnicode_Check (obj
);
177 return PyString_Check (obj
) || PyUnicode_Check (obj
);
181 /* Return the string representation of OBJ, i.e., str (obj).
182 If the result is NULL a python error occurred, the caller must clear it. */
184 gdb::unique_xmalloc_ptr
<char>
185 gdbpy_obj_to_string (PyObject
*obj
)
187 gdbpy_ref
<> str_obj (PyObject_Str (obj
));
191 gdb::unique_xmalloc_ptr
<char> msg
;
194 msg
= python_string_to_host_string (str_obj
.get ());
196 msg
.reset (xstrdup (PyString_AsString (str_obj
.get ())));
205 /* See python-internal.h. */
207 gdb::unique_xmalloc_ptr
<char>
208 gdbpy_err_fetch::to_string () const
210 /* There are a few cases to consider.
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
215 So the algorithm we use is to print `str (value)' if it's not
216 None, otherwise we print `str (type)'.
217 Using str (aka PyObject_Str) will fetch the error message from
218 gdb.GdbError ("message"). */
220 if (m_error_value
&& m_error_value
!= Py_None
)
221 return gdbpy_obj_to_string (m_error_value
);
223 return gdbpy_obj_to_string (m_error_type
);
226 /* See python-internal.h. */
228 gdb::unique_xmalloc_ptr
<char>
229 gdbpy_err_fetch::type_to_string () const
231 return gdbpy_obj_to_string (m_error_type
);
234 /* Convert a GDB exception to the appropriate Python exception.
236 This sets the Python error indicator. */
239 gdbpy_convert_exception (struct gdb_exception exception
)
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
;
248 exc_class
= gdbpy_gdb_error
;
250 PyErr_Format (exc_class
, "%s", exception
.message
);
253 /* Converts OBJ to a CORE_ADDR value.
255 Returns 0 on success or -1 on failure, with a Python exception set.
259 get_addr_from_python (PyObject
*obj
, CORE_ADDR
*addr
)
261 if (gdbpy_is_value_object (obj
))
266 *addr
= value_as_address (value_object_to_value (obj
));
268 CATCH (except
, RETURN_MASK_ALL
)
270 GDB_PY_SET_HANDLE_EXCEPTION (except
);
276 gdbpy_ref
<> num (PyNumber_Long (obj
));
282 val
= gdb_py_long_as_ulongest (num
.get ());
283 if (PyErr_Occurred ())
286 if (sizeof (val
) > sizeof (CORE_ADDR
) && ((CORE_ADDR
) val
) != val
)
288 PyErr_SetString (PyExc_ValueError
,
289 _("Overflow converting to address."));
299 /* Convert a LONGEST to the appropriate Python object -- either an
300 integer object or a long object, depending on its value. */
303 gdb_py_object_from_longest (LONGEST l
)
306 if (sizeof (l
) > sizeof (long))
307 return gdbpy_ref
<> (PyLong_FromLongLong (l
));
308 return gdbpy_ref
<> (PyLong_FromLong (l
));
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))
315 return gdbpy_ref
<> (PyLong_FromLongLong (l
));
317 return gdbpy_ref
<> (PyInt_FromLong (l
));
321 /* Convert a ULONGEST to the appropriate Python object -- either an
322 integer object or a long object, depending on its value. */
325 gdb_py_object_from_ulongest (ULONGEST l
)
328 if (sizeof (l
) > sizeof (unsigned long))
329 return gdbpy_ref
<> (PyLong_FromUnsignedLongLong (l
));
330 return gdbpy_ref
<> (PyLong_FromUnsignedLong (l
));
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 ())
336 return gdbpy_ref
<> (PyLong_FromUnsignedLongLong (l
));
339 if (l
> PyInt_GetMax ())
340 return gdbpy_ref
<> (PyLong_FromUnsignedLong (l
));
342 return gdbpy_ref
<> (PyInt_FromLong (l
));
346 /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
347 the value into an out parameter. */
350 gdb_py_int_as_long (PyObject
*obj
, long *result
)
352 *result
= PyInt_AsLong (obj
);
353 return ! (*result
== -1 && PyErr_Occurred ());
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. */
363 gdb_py_generic_dict (PyObject
*self
, void *closure
)
366 PyTypeObject
*type_obj
= (PyTypeObject
*) closure
;
369 raw_ptr
= (char *) self
+ type_obj
->tp_dictoffset
;
370 result
= * (PyObject
**) raw_ptr
;
376 /* Like PyModule_AddObject, but does not steal a reference to
380 gdb_pymodule_addobject (PyObject
*module
, const char *name
, PyObject
*object
)
385 /* Python 2.4 did not have a 'const' here. */
386 result
= PyModule_AddObject (module
, (char *) name
, object
);
392 /* Handle a Python exception when the special gdb.GdbError treatment
393 is desired. This should only be called when an exception is set.
394 If the exception is a gdb.GdbError, throw a gdb exception with the
395 exception text. For other exceptions, print the Python stack and
396 then throw a gdb exception. */
399 gdbpy_handle_exception ()
401 gdbpy_err_fetch fetched_error
;
402 gdb::unique_xmalloc_ptr
<char> msg
= fetched_error
.to_string ();
406 /* An error occurred computing the string representation of the
407 error message. This is rare, but we should inform the user. */
408 printf_filtered (_("An error occurred in Python "
409 "and then another occurred computing the "
410 "error message.\n"));
411 gdbpy_print_stack ();
414 /* Don't print the stack for gdb.GdbError exceptions.
415 It is generally used to flag user errors.
417 We also don't want to print "Error occurred in Python command"
418 for user errors. However, a missing message for gdb.GdbError
419 exceptions is arguably a bug, so we flag it as such. */
421 if (fetched_error
.type_matches (PyExc_KeyboardInterrupt
))
423 else if (! fetched_error
.type_matches (gdbpy_gdberror_exc
)
424 || msg
== NULL
|| *msg
== '\0')
426 fetched_error
.restore ();
427 gdbpy_print_stack ();
428 if (msg
!= NULL
&& *msg
!= '\0')
429 error (_("Error occurred in Python: %s"), msg
.get ());
431 error (_("Error occurred in Python."));
434 error ("%s", msg
.get ());