1 /* General utility routines for GDB/Python.
3 Copyright (C) 2008-2022 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))
50 PyErr_SetString (PyExc_TypeError,
51 _("Expected a string object."));
55 return gdbpy_ref<> (unicode_str);
58 /* Returns a newly allocated string with the contents of the given unicode
59 string object converted to CHARSET. If an error occurs during the
60 conversion, NULL will be returned and a python exception will be
62 static gdb::unique_xmalloc_ptr<char>
63 unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
65 /* Translate string to named charset. */
66 gdbpy_ref<> string (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
70 return gdb::unique_xmalloc_ptr<char>
71 (xstrdup (PyBytes_AsString (string.get ())));
74 /* Returns a PyObject with the contents of the given unicode string
75 object converted to a named charset. If an error occurs during
76 the conversion, NULL will be returned and a python exception will
79 unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
81 /* Translate string to named charset. */
82 return gdbpy_ref<> (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
85 /* Returns a newly allocated string with the contents of the given
86 unicode string object converted to the target's charset. If an
87 error occurs during the conversion, NULL will be returned and a
88 python exception will be set. */
89 gdb::unique_xmalloc_ptr<char>
90 unicode_to_target_string (PyObject *unicode_str)
92 return (unicode_to_encoded_string
94 target_charset (gdbpy_enter::get_gdbarch ())));
97 /* Returns a PyObject with the contents of the given unicode string
98 object converted to the target's charset. If an error occurs
99 during the conversion, NULL will be returned and a python exception
102 unicode_to_target_python_string (PyObject *unicode_str)
104 return (unicode_to_encoded_python_string
106 target_charset (gdbpy_enter::get_gdbarch ())));
109 /* Converts a python string (8-bit or unicode) to a target string in
110 the target's charset. Returns NULL on error, with a python
112 gdb::unique_xmalloc_ptr<char>
113 python_string_to_target_string (PyObject *obj)
115 gdbpy_ref<> str = python_string_to_unicode (obj);
119 return unicode_to_target_string (str.get ());
122 /* Converts a python string (8-bit or unicode) to a target string in the
123 target's charset. Returns NULL on error, with a python exception
126 In Python 3, the returned object is a "bytes" object (not a string). */
128 python_string_to_target_python_string (PyObject *obj)
130 gdbpy_ref<> str = python_string_to_unicode (obj);
134 return unicode_to_target_python_string (str.get ());
137 /* Converts a python string (8-bit or unicode) to a target string in
138 the host's charset. Returns NULL on error, with a python exception
140 gdb::unique_xmalloc_ptr<char>
141 python_string_to_host_string (PyObject *obj)
143 gdbpy_ref<> str = python_string_to_unicode (obj);
147 return unicode_to_encoded_string (str.get (), host_charset ());
150 /* Convert a host string to a python string. */
153 host_string_to_python_string (const char *str)
155 return gdbpy_ref<> (PyUnicode_Decode (str, strlen (str), host_charset (),
159 /* Return true if OBJ is a Python string or unicode object, false
163 gdbpy_is_string (PyObject *obj)
165 return PyUnicode_Check (obj);
168 /* Return the string representation of OBJ, i.e., str (obj).
169 If the result is NULL a python error occurred, the caller must clear it. */
171 gdb::unique_xmalloc_ptr<char>
172 gdbpy_obj_to_string (PyObject *obj)
174 gdbpy_ref<> str_obj (PyObject_Str (obj));
177 return python_string_to_host_string (str_obj.get ());
182 /* See python-internal.h. */
184 gdb::unique_xmalloc_ptr<char>
185 gdbpy_err_fetch::to_string () const
187 /* There are a few cases to consider.
189 value is a string when PyErr_SetString is used.
190 value is not a string when raise "foo" is used, instead it is None
192 So the algorithm we use is to print `str (value)' if it's not
193 None, otherwise we print `str (type)'.
194 Using str (aka PyObject_Str) will fetch the error message from
195 gdb.GdbError ("message"). */
197 if (m_error_value && m_error_value != Py_None)
198 return gdbpy_obj_to_string (m_error_value);
200 return gdbpy_obj_to_string (m_error_type);
203 /* See python-internal.h. */
205 gdb::unique_xmalloc_ptr<char>
206 gdbpy_err_fetch::type_to_string () const
208 return gdbpy_obj_to_string (m_error_type);
211 /* Convert a GDB exception to the appropriate Python exception.
213 This sets the Python error indicator. */
216 gdbpy_convert_exception (const struct gdb_exception &exception)
220 if (exception.reason == RETURN_QUIT)
221 exc_class = PyExc_KeyboardInterrupt;
222 else if (exception.error == MEMORY_ERROR)
223 exc_class = gdbpy_gdb_memory_error;
225 exc_class = gdbpy_gdb_error;
227 PyErr_Format (exc_class, "%s", exception.what ());
230 /* Converts OBJ to a CORE_ADDR value.
232 Returns 0 on success or -1 on failure, with a Python exception set.
236 get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
238 if (gdbpy_is_value_object (obj))
243 *addr = value_as_address (value_object_to_value (obj));
245 catch (const gdb_exception &except)
247 GDB_PY_SET_HANDLE_EXCEPTION (except);
252 gdbpy_ref<> num (PyNumber_Long (obj));
258 val = gdb_py_long_as_ulongest (num.get ());
259 if (PyErr_Occurred ())
262 if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
264 PyErr_SetString (PyExc_ValueError,
265 _("Overflow converting to address."));
275 /* Convert a LONGEST to the appropriate Python object -- either an
276 integer object or a long object, depending on its value. */
279 gdb_py_object_from_longest (LONGEST l)
281 if (sizeof (l) > sizeof (long))
282 return gdbpy_ref<> (PyLong_FromLongLong (l));
283 return gdbpy_ref<> (PyLong_FromLong (l));
286 /* Convert a ULONGEST to the appropriate Python object -- either an
287 integer object or a long object, depending on its value. */
290 gdb_py_object_from_ulongest (ULONGEST l)
292 if (sizeof (l) > sizeof (unsigned long))
293 return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
294 return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
297 /* Like PyLong_AsLong, but returns 0 on failure, 1 on success, and puts
298 the value into an out parameter. */
301 gdb_py_int_as_long (PyObject *obj, long *result)
303 *result = PyLong_AsLong (obj);
304 return ! (*result == -1 && PyErr_Occurred ());
309 /* Generic implementation of the __dict__ attribute for objects that
310 have a dictionary. The CLOSURE argument should be the type object.
311 This only handles positive values for tp_dictoffset. */
314 gdb_py_generic_dict (PyObject *self, void *closure)
317 PyTypeObject *type_obj = (PyTypeObject *) closure;
320 raw_ptr = (char *) self + type_obj->tp_dictoffset;
321 result = * (PyObject **) raw_ptr;
327 /* Like PyModule_AddObject, but does not steal a reference to
331 gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
336 result = PyModule_AddObject (module, name, object);
342 /* See python-internal.h. */
345 gdbpy_error (const char *fmt, ...)
349 std::string str = string_vprintf (fmt, ap);
352 const char *msg = str.c_str ();
353 if (msg != nullptr && *msg != '\0')
354 error (_("Error occurred in Python: %s"), msg);
356 error (_("Error occurred in Python."));
359 /* Handle a Python exception when the special gdb.GdbError treatment
360 is desired. This should only be called when an exception is set.
361 If the exception is a gdb.GdbError, throw a gdb exception with the
362 exception text. For other exceptions, print the Python stack and
363 then throw a gdb exception. */
366 gdbpy_handle_exception ()
368 gdbpy_err_fetch fetched_error;
369 gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
373 /* An error occurred computing the string representation of the
374 error message. This is rare, but we should inform the user. */
375 printf_filtered (_("An error occurred in Python "
376 "and then another occurred computing the "
377 "error message.\n"));
378 gdbpy_print_stack ();
381 /* Don't print the stack for gdb.GdbError exceptions.
382 It is generally used to flag user errors.
384 We also don't want to print "Error occurred in Python command"
385 for user errors. However, a missing message for gdb.GdbError
386 exceptions is arguably a bug, so we flag it as such. */
388 if (fetched_error.type_matches (PyExc_KeyboardInterrupt))
390 else if (! fetched_error.type_matches (gdbpy_gdberror_exc)
391 || msg == NULL || *msg == '\0')
393 fetched_error.restore ();
394 gdbpy_print_stack ();
395 if (msg != NULL && *msg != '\0')
396 error (_("Error occurred in Python: %s"), msg.get ());
398 error (_("Error occurred in Python."));
401 error ("%s", msg.get ());