exc_ops.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Exception related primitive operations
  2. //
  3. // These are registered in mypyc.primitives.exc_ops.
  4. #include <Python.h>
  5. #include "CPy.h"
  6. void CPy_Raise(PyObject *exc) {
  7. if (PyObject_IsInstance(exc, (PyObject *)&PyType_Type)) {
  8. PyObject *obj = PyObject_CallNoArgs(exc);
  9. if (!obj)
  10. return;
  11. PyErr_SetObject(exc, obj);
  12. Py_DECREF(obj);
  13. } else {
  14. PyErr_SetObject((PyObject *)Py_TYPE(exc), exc);
  15. }
  16. }
  17. void CPy_Reraise(void) {
  18. PyObject *p_type, *p_value, *p_traceback;
  19. PyErr_GetExcInfo(&p_type, &p_value, &p_traceback);
  20. PyErr_Restore(p_type, p_value, p_traceback);
  21. }
  22. void CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *traceback) {
  23. // Set the value and traceback of an error. Because calling
  24. // PyErr_Restore takes away a reference to each object passed in
  25. // as an argument, we manually increase the reference count of
  26. // each argument before calling it.
  27. Py_INCREF(type);
  28. Py_INCREF(value);
  29. Py_INCREF(traceback);
  30. PyErr_Restore(type, value, traceback);
  31. }
  32. tuple_T3OOO CPy_CatchError(void) {
  33. // We need to return the existing sys.exc_info() information, so
  34. // that it can be restored when we finish handling the error we
  35. // are catching now. Grab that triple and convert NULL values to
  36. // the ExcDummy object in order to simplify refcount handling in
  37. // generated code.
  38. tuple_T3OOO ret;
  39. PyErr_GetExcInfo(&ret.f0, &ret.f1, &ret.f2);
  40. _CPy_ToDummy(&ret.f0);
  41. _CPy_ToDummy(&ret.f1);
  42. _CPy_ToDummy(&ret.f2);
  43. if (!PyErr_Occurred()) {
  44. PyErr_SetString(PyExc_RuntimeError, "CPy_CatchError called with no error!");
  45. }
  46. // Retrieve the error info and normalize it so that it looks like
  47. // what python code needs it to be.
  48. PyObject *type, *value, *traceback;
  49. PyErr_Fetch(&type, &value, &traceback);
  50. // Could we avoid always normalizing?
  51. PyErr_NormalizeException(&type, &value, &traceback);
  52. if (traceback != NULL) {
  53. PyException_SetTraceback(value, traceback);
  54. }
  55. // Indicate that we are now handling this exception by stashing it
  56. // in sys.exc_info(). mypyc routines that need access to the
  57. // exception will read it out of there.
  58. PyErr_SetExcInfo(type, value, traceback);
  59. // Clear the error indicator, since the exception isn't
  60. // propagating anymore.
  61. PyErr_Clear();
  62. return ret;
  63. }
  64. void CPy_RestoreExcInfo(tuple_T3OOO info) {
  65. PyErr_SetExcInfo(_CPy_FromDummy(info.f0), _CPy_FromDummy(info.f1), _CPy_FromDummy(info.f2));
  66. }
  67. bool CPy_ExceptionMatches(PyObject *type) {
  68. return PyErr_GivenExceptionMatches((PyObject *)Py_TYPE(CPy_ExcState()->exc_value), type);
  69. }
  70. PyObject *CPy_GetExcValue(void) {
  71. PyObject *exc = CPy_ExcState()->exc_value;
  72. Py_INCREF(exc);
  73. return exc;
  74. }
  75. static inline void _CPy_ToNone(PyObject **p) {
  76. if (*p == NULL) {
  77. Py_INCREF(Py_None);
  78. *p = Py_None;
  79. }
  80. }
  81. void _CPy_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) {
  82. PyErr_GetExcInfo(p_type, p_value, p_traceback);
  83. _CPy_ToNone(p_type);
  84. _CPy_ToNone(p_value);
  85. _CPy_ToNone(p_traceback);
  86. }
  87. tuple_T3OOO CPy_GetExcInfo(void) {
  88. tuple_T3OOO ret;
  89. _CPy_GetExcInfo(&ret.f0, &ret.f1, &ret.f2);
  90. return ret;
  91. }
  92. void CPyError_OutOfMemory(void) {
  93. fprintf(stderr, "fatal: out of memory\n");
  94. fflush(stderr);
  95. abort();
  96. }
  97. // Construct a nicely formatted type name based on __module__ and __name__.
  98. static PyObject *CPy_GetTypeName(PyObject *type) {
  99. PyObject *module = NULL, *name = NULL;
  100. PyObject *full = NULL;
  101. module = PyObject_GetAttrString(type, "__module__");
  102. if (!module || !PyUnicode_Check(module)) {
  103. goto out;
  104. }
  105. name = PyObject_GetAttrString(type, "__qualname__");
  106. if (!name || !PyUnicode_Check(name)) {
  107. goto out;
  108. }
  109. if (PyUnicode_CompareWithASCIIString(module, "builtins") == 0) {
  110. Py_INCREF(name);
  111. full = name;
  112. } else {
  113. full = PyUnicode_FromFormat("%U.%U", module, name);
  114. }
  115. out:
  116. Py_XDECREF(module);
  117. Py_XDECREF(name);
  118. return full;
  119. }
  120. // Get the type of a value as a string, expanding tuples to include
  121. // all the element types.
  122. static PyObject *CPy_FormatTypeName(PyObject *value) {
  123. if (Py_IsNone(value)) {
  124. return PyUnicode_FromString("None");
  125. }
  126. if (!PyTuple_CheckExact(value)) {
  127. return CPy_GetTypeName((PyObject *)Py_TYPE(value));
  128. }
  129. if (PyTuple_GET_SIZE(value) > 10) {
  130. return PyUnicode_FromFormat("tuple[<%d items>]", PyTuple_GET_SIZE(value));
  131. }
  132. // Most of the logic is all for tuples, which is the only interesting case
  133. PyObject *output = PyUnicode_FromString("tuple[");
  134. if (!output) {
  135. return NULL;
  136. }
  137. /* This is quadratic but if that ever matters something is really weird. */
  138. int i;
  139. for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
  140. PyObject *s = CPy_FormatTypeName(PyTuple_GET_ITEM(value, i));
  141. if (!s) {
  142. Py_DECREF(output);
  143. return NULL;
  144. }
  145. PyObject *next = PyUnicode_FromFormat("%U%U%s", output, s,
  146. i + 1 == PyTuple_GET_SIZE(value) ? "]" : ", ");
  147. Py_DECREF(output);
  148. Py_DECREF(s);
  149. if (!next) {
  150. return NULL;
  151. }
  152. output = next;
  153. }
  154. return output;
  155. }
  156. CPy_NOINLINE
  157. void CPy_TypeError(const char *expected, PyObject *value) {
  158. PyObject *out = CPy_FormatTypeName(value);
  159. if (out) {
  160. PyErr_Format(PyExc_TypeError, "%s object expected; got %U", expected, out);
  161. Py_DECREF(out);
  162. } else {
  163. PyErr_Format(PyExc_TypeError, "%s object expected; and errored formatting real type!",
  164. expected);
  165. }
  166. }
  167. // The PyFrameObject type definition (struct _frame) has been moved
  168. // to the internal C API: to the pycore_frame.h header file.
  169. // https://github.com/python/cpython/pull/31530
  170. #if PY_VERSION_HEX >= 0x030b00a6
  171. #include "internal/pycore_frame.h"
  172. #endif
  173. // This function is basically exactly the same with _PyTraceback_Add
  174. // which is available in all the versions we support.
  175. // We're continuing to use this because we'll probably optimize this later.
  176. void CPy_AddTraceback(const char *filename, const char *funcname, int line, PyObject *globals) {
  177. PyObject *exc, *val, *tb;
  178. PyThreadState *thread_state = PyThreadState_GET();
  179. PyFrameObject *frame_obj;
  180. // We need to save off the exception state because in 3.8,
  181. // PyFrame_New fails if there is an error set and it fails to look
  182. // up builtins in the globals. (_PyTraceback_Add documents that it
  183. // needs to do it because it decodes the filename according to the
  184. // FS encoding, which could have a decoder in Python. We don't do
  185. // that so *that* doesn't apply to us.)
  186. PyErr_Fetch(&exc, &val, &tb);
  187. PyCodeObject *code_obj = PyCode_NewEmpty(filename, funcname, line);
  188. if (code_obj == NULL) {
  189. goto error;
  190. }
  191. frame_obj = PyFrame_New(thread_state, code_obj, globals, 0);
  192. if (frame_obj == NULL) {
  193. Py_DECREF(code_obj);
  194. goto error;
  195. }
  196. frame_obj->f_lineno = line;
  197. PyErr_Restore(exc, val, tb);
  198. PyTraceBack_Here(frame_obj);
  199. Py_DECREF(code_obj);
  200. Py_DECREF(frame_obj);
  201. return;
  202. error:
  203. _PyErr_ChainExceptions(exc, val, tb);
  204. }
  205. CPy_NOINLINE
  206. void CPy_TypeErrorTraceback(const char *filename, const char *funcname, int line,
  207. PyObject *globals, const char *expected, PyObject *value) {
  208. CPy_TypeError(expected, value);
  209. CPy_AddTraceback(filename, funcname, line, globals);
  210. }
  211. void CPy_AttributeError(const char *filename, const char *funcname, const char *classname,
  212. const char *attrname, int line, PyObject *globals) {
  213. char buf[500];
  214. snprintf(buf, sizeof(buf), "attribute '%.200s' of '%.200s' undefined", attrname, classname);
  215. PyErr_SetString(PyExc_AttributeError, buf);
  216. CPy_AddTraceback(filename, funcname, line, globals);
  217. }