py-utils.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /* General utility routines for GDB/Python.
  2. Copyright (C) 2008-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include "defs.h"
  15. #include "charset.h"
  16. #include "value.h"
  17. #include "python-internal.h"
  18. /* Converts a Python 8-bit string to a unicode string object. Assumes the
  19. 8-bit string is in the host charset. If an error occurs during conversion,
  20. returns NULL with a python exception set.
  21. As an added bonus, the functions accepts a unicode string and returns it
  22. right away, so callers don't need to check which kind of string they've
  23. got. In Python 3, all strings are Unicode so this case is always the
  24. one that applies.
  25. If the given object is not one of the mentioned string types, NULL is
  26. returned, with the TypeError python exception set. */
  27. gdbpy_ref<>
  28. python_string_to_unicode (PyObject *obj)
  29. {
  30. PyObject *unicode_str;
  31. /* If obj is already a unicode string, just return it.
  32. I wish life was always that simple... */
  33. if (PyUnicode_Check (obj))
  34. {
  35. unicode_str = obj;
  36. Py_INCREF (obj);
  37. }
  38. else
  39. {
  40. PyErr_SetString (PyExc_TypeError,
  41. _("Expected a string object."));
  42. unicode_str = NULL;
  43. }
  44. return gdbpy_ref<> (unicode_str);
  45. }
  46. /* Returns a newly allocated string with the contents of the given unicode
  47. string object converted to CHARSET. If an error occurs during the
  48. conversion, NULL will be returned and a python exception will be
  49. set. */
  50. static gdb::unique_xmalloc_ptr<char>
  51. unicode_to_encoded_string (PyObject *unicode_str, const char *charset)
  52. {
  53. /* Translate string to named charset. */
  54. gdbpy_ref<> string (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
  55. if (string == NULL)
  56. return NULL;
  57. return gdb::unique_xmalloc_ptr<char>
  58. (xstrdup (PyBytes_AsString (string.get ())));
  59. }
  60. /* Returns a PyObject with the contents of the given unicode string
  61. object converted to a named charset. If an error occurs during
  62. the conversion, NULL will be returned and a python exception will
  63. be set. */
  64. static gdbpy_ref<>
  65. unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
  66. {
  67. /* Translate string to named charset. */
  68. return gdbpy_ref<> (PyUnicode_AsEncodedString (unicode_str, charset, NULL));
  69. }
  70. /* Returns a newly allocated string with the contents of the given
  71. unicode string object converted to the target's charset. If an
  72. error occurs during the conversion, NULL will be returned and a
  73. python exception will be set. */
  74. gdb::unique_xmalloc_ptr<char>
  75. unicode_to_target_string (PyObject *unicode_str)
  76. {
  77. return (unicode_to_encoded_string
  78. (unicode_str,
  79. target_charset (gdbpy_enter::get_gdbarch ())));
  80. }
  81. /* Returns a PyObject with the contents of the given unicode string
  82. object converted to the target's charset. If an error occurs
  83. during the conversion, NULL will be returned and a python exception
  84. will be set. */
  85. static gdbpy_ref<>
  86. unicode_to_target_python_string (PyObject *unicode_str)
  87. {
  88. return (unicode_to_encoded_python_string
  89. (unicode_str,
  90. target_charset (gdbpy_enter::get_gdbarch ())));
  91. }
  92. /* Converts a python string (8-bit or unicode) to a target string in
  93. the target's charset. Returns NULL on error, with a python
  94. exception set. */
  95. gdb::unique_xmalloc_ptr<char>
  96. python_string_to_target_string (PyObject *obj)
  97. {
  98. gdbpy_ref<> str = python_string_to_unicode (obj);
  99. if (str == NULL)
  100. return NULL;
  101. return unicode_to_target_string (str.get ());
  102. }
  103. /* Converts a python string (8-bit or unicode) to a target string in the
  104. target's charset. Returns NULL on error, with a python exception
  105. set.
  106. In Python 3, the returned object is a "bytes" object (not a string). */
  107. gdbpy_ref<>
  108. python_string_to_target_python_string (PyObject *obj)
  109. {
  110. gdbpy_ref<> str = python_string_to_unicode (obj);
  111. if (str == NULL)
  112. return str;
  113. return unicode_to_target_python_string (str.get ());
  114. }
  115. /* Converts a python string (8-bit or unicode) to a target string in
  116. the host's charset. Returns NULL on error, with a python exception
  117. set. */
  118. gdb::unique_xmalloc_ptr<char>
  119. python_string_to_host_string (PyObject *obj)
  120. {
  121. gdbpy_ref<> str = python_string_to_unicode (obj);
  122. if (str == NULL)
  123. return NULL;
  124. return unicode_to_encoded_string (str.get (), host_charset ());
  125. }
  126. /* Convert a host string to a python string. */
  127. gdbpy_ref<>
  128. host_string_to_python_string (const char *str)
  129. {
  130. return gdbpy_ref<> (PyUnicode_Decode (str, strlen (str), host_charset (),
  131. NULL));
  132. }
  133. /* Return true if OBJ is a Python string or unicode object, false
  134. otherwise. */
  135. int
  136. gdbpy_is_string (PyObject *obj)
  137. {
  138. return PyUnicode_Check (obj);
  139. }
  140. /* Return the string representation of OBJ, i.e., str (obj).
  141. If the result is NULL a python error occurred, the caller must clear it. */
  142. gdb::unique_xmalloc_ptr<char>
  143. gdbpy_obj_to_string (PyObject *obj)
  144. {
  145. gdbpy_ref<> str_obj (PyObject_Str (obj));
  146. if (str_obj != NULL)
  147. return python_string_to_host_string (str_obj.get ());
  148. return NULL;
  149. }
  150. /* See python-internal.h. */
  151. gdb::unique_xmalloc_ptr<char>
  152. gdbpy_err_fetch::to_string () const
  153. {
  154. /* There are a few cases to consider.
  155. For example:
  156. value is a string when PyErr_SetString is used.
  157. value is not a string when raise "foo" is used, instead it is None
  158. and type is "foo".
  159. So the algorithm we use is to print `str (value)' if it's not
  160. None, otherwise we print `str (type)'.
  161. Using str (aka PyObject_Str) will fetch the error message from
  162. gdb.GdbError ("message"). */
  163. if (m_error_value && m_error_value != Py_None)
  164. return gdbpy_obj_to_string (m_error_value);
  165. else
  166. return gdbpy_obj_to_string (m_error_type);
  167. }
  168. /* See python-internal.h. */
  169. gdb::unique_xmalloc_ptr<char>
  170. gdbpy_err_fetch::type_to_string () const
  171. {
  172. return gdbpy_obj_to_string (m_error_type);
  173. }
  174. /* Convert a GDB exception to the appropriate Python exception.
  175. This sets the Python error indicator. */
  176. void
  177. gdbpy_convert_exception (const struct gdb_exception &exception)
  178. {
  179. PyObject *exc_class;
  180. if (exception.reason == RETURN_QUIT)
  181. exc_class = PyExc_KeyboardInterrupt;
  182. else if (exception.error == MEMORY_ERROR)
  183. exc_class = gdbpy_gdb_memory_error;
  184. else
  185. exc_class = gdbpy_gdb_error;
  186. PyErr_Format (exc_class, "%s", exception.what ());
  187. }
  188. /* Converts OBJ to a CORE_ADDR value.
  189. Returns 0 on success or -1 on failure, with a Python exception set.
  190. */
  191. int
  192. get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
  193. {
  194. if (gdbpy_is_value_object (obj))
  195. {
  196. try
  197. {
  198. *addr = value_as_address (value_object_to_value (obj));
  199. }
  200. catch (const gdb_exception &except)
  201. {
  202. GDB_PY_SET_HANDLE_EXCEPTION (except);
  203. }
  204. }
  205. else
  206. {
  207. gdbpy_ref<> num (PyNumber_Long (obj));
  208. gdb_py_ulongest val;
  209. if (num == NULL)
  210. return -1;
  211. val = gdb_py_long_as_ulongest (num.get ());
  212. if (PyErr_Occurred ())
  213. return -1;
  214. if (sizeof (val) > sizeof (CORE_ADDR) && ((CORE_ADDR) val) != val)
  215. {
  216. PyErr_SetString (PyExc_ValueError,
  217. _("Overflow converting to address."));
  218. return -1;
  219. }
  220. *addr = val;
  221. }
  222. return 0;
  223. }
  224. /* Convert a LONGEST to the appropriate Python object -- either an
  225. integer object or a long object, depending on its value. */
  226. gdbpy_ref<>
  227. gdb_py_object_from_longest (LONGEST l)
  228. {
  229. if (sizeof (l) > sizeof (long))
  230. return gdbpy_ref<> (PyLong_FromLongLong (l));
  231. return gdbpy_ref<> (PyLong_FromLong (l));
  232. }
  233. /* Convert a ULONGEST to the appropriate Python object -- either an
  234. integer object or a long object, depending on its value. */
  235. gdbpy_ref<>
  236. gdb_py_object_from_ulongest (ULONGEST l)
  237. {
  238. if (sizeof (l) > sizeof (unsigned long))
  239. return gdbpy_ref<> (PyLong_FromUnsignedLongLong (l));
  240. return gdbpy_ref<> (PyLong_FromUnsignedLong (l));
  241. }
  242. /* Like PyLong_AsLong, but returns 0 on failure, 1 on success, and puts
  243. the value into an out parameter. */
  244. int
  245. gdb_py_int_as_long (PyObject *obj, long *result)
  246. {
  247. *result = PyLong_AsLong (obj);
  248. return ! (*result == -1 && PyErr_Occurred ());
  249. }
  250. /* Generic implementation of the __dict__ attribute for objects that
  251. have a dictionary. The CLOSURE argument should be the type object.
  252. This only handles positive values for tp_dictoffset. */
  253. PyObject *
  254. gdb_py_generic_dict (PyObject *self, void *closure)
  255. {
  256. PyObject *result;
  257. PyTypeObject *type_obj = (PyTypeObject *) closure;
  258. char *raw_ptr;
  259. raw_ptr = (char *) self + type_obj->tp_dictoffset;
  260. result = * (PyObject **) raw_ptr;
  261. Py_INCREF (result);
  262. return result;
  263. }
  264. /* Like PyModule_AddObject, but does not steal a reference to
  265. OBJECT. */
  266. int
  267. gdb_pymodule_addobject (PyObject *module, const char *name, PyObject *object)
  268. {
  269. int result;
  270. Py_INCREF (object);
  271. result = PyModule_AddObject (module, name, object);
  272. if (result < 0)
  273. Py_DECREF (object);
  274. return result;
  275. }
  276. /* See python-internal.h. */
  277. void
  278. gdbpy_error (const char *fmt, ...)
  279. {
  280. va_list ap;
  281. va_start (ap, fmt);
  282. std::string str = string_vprintf (fmt, ap);
  283. va_end (ap);
  284. const char *msg = str.c_str ();
  285. if (msg != nullptr && *msg != '\0')
  286. error (_("Error occurred in Python: %s"), msg);
  287. else
  288. error (_("Error occurred in Python."));
  289. }
  290. /* Handle a Python exception when the special gdb.GdbError treatment
  291. is desired. This should only be called when an exception is set.
  292. If the exception is a gdb.GdbError, throw a gdb exception with the
  293. exception text. For other exceptions, print the Python stack and
  294. then throw a gdb exception. */
  295. void
  296. gdbpy_handle_exception ()
  297. {
  298. gdbpy_err_fetch fetched_error;
  299. gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
  300. if (msg == NULL)
  301. {
  302. /* An error occurred computing the string representation of the
  303. error message. This is rare, but we should inform the user. */
  304. gdb_printf (_("An error occurred in Python "
  305. "and then another occurred computing the "
  306. "error message.\n"));
  307. gdbpy_print_stack ();
  308. }
  309. /* Don't print the stack for gdb.GdbError exceptions.
  310. It is generally used to flag user errors.
  311. We also don't want to print "Error occurred in Python command"
  312. for user errors. However, a missing message for gdb.GdbError
  313. exceptions is arguably a bug, so we flag it as such. */
  314. if (fetched_error.type_matches (PyExc_KeyboardInterrupt))
  315. throw_quit ("Quit");
  316. else if (! fetched_error.type_matches (gdbpy_gdberror_exc)
  317. || msg == NULL || *msg == '\0')
  318. {
  319. fetched_error.restore ();
  320. gdbpy_print_stack ();
  321. if (msg != NULL && *msg != '\0')
  322. error (_("Error occurred in Python: %s"), msg.get ());
  323. else
  324. error (_("Error occurred in Python."));
  325. }
  326. else
  327. error ("%s", msg.get ());
  328. }