objexcept.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <string.h>
  27. #include <stdarg.h>
  28. #include <assert.h>
  29. #include <stdio.h>
  30. #include "py/objlist.h"
  31. #include "py/objstr.h"
  32. #include "py/objtuple.h"
  33. #include "py/objtype.h"
  34. #include "py/runtime.h"
  35. #include "py/gc.h"
  36. #include "py/mperrno.h"
  37. // Number of items per traceback entry (file, line, block)
  38. #define TRACEBACK_ENTRY_LEN (3)
  39. // Optionally allocated buffer for storing some traceback, the tuple argument,
  40. // and possible string object and data, for when the heap is locked.
  41. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  42. // When used the layout of the emergency exception buffer is:
  43. // - traceback entry (file, line, block)
  44. // - traceback entry (file, line, block)
  45. // - mp_obj_tuple_t object
  46. // - n_args * mp_obj_t for tuple
  47. // - mp_obj_str_t object
  48. // - string data
  49. #define EMG_BUF_TRACEBACK_OFFSET (0)
  50. #define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t))
  51. #define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE)
  52. #define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t))
  53. #define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1))
  54. # if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
  55. #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
  56. void mp_init_emergency_exception_buf(void) {
  57. // Nothing to do since the buffer was declared statically. We put this
  58. // definition here so that the calling code can call this function
  59. // regardless of how its configured (makes the calling code a bit cleaner).
  60. }
  61. #else
  62. #define mp_emergency_exception_buf_size MP_STATE_VM(mp_emergency_exception_buf_size)
  63. void mp_init_emergency_exception_buf(void) {
  64. mp_emergency_exception_buf_size = 0;
  65. MP_STATE_VM(mp_emergency_exception_buf) = NULL;
  66. }
  67. mp_obj_t mp_alloc_emergency_exception_buf(mp_obj_t size_in) {
  68. mp_int_t size = mp_obj_get_int(size_in);
  69. void *buf = NULL;
  70. if (size > 0) {
  71. buf = m_new(byte, size);
  72. }
  73. int old_size = mp_emergency_exception_buf_size;
  74. void *old_buf = MP_STATE_VM(mp_emergency_exception_buf);
  75. // Update the 2 variables atomically so that an interrupt can't occur
  76. // between the assignments.
  77. mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
  78. mp_emergency_exception_buf_size = size;
  79. MP_STATE_VM(mp_emergency_exception_buf) = buf;
  80. MICROPY_END_ATOMIC_SECTION(atomic_state);
  81. if (old_buf != NULL) {
  82. m_del(byte, old_buf, old_size);
  83. }
  84. return mp_const_none;
  85. }
  86. #endif
  87. #endif // MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  88. // Instance of GeneratorExit exception - needed by generator.close()
  89. // This would belong to objgenerator.c, but to keep mp_obj_exception_t
  90. // definition module-private so far, have it here.
  91. const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
  92. void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
  93. mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in);
  94. mp_print_kind_t k = kind & ~PRINT_EXC_SUBCLASS;
  95. bool is_subclass = kind & PRINT_EXC_SUBCLASS;
  96. if (!is_subclass && (k == PRINT_REPR || k == PRINT_EXC)) {
  97. mp_print_str(print, qstr_str(o->base.type->name));
  98. }
  99. if (k == PRINT_EXC) {
  100. mp_print_str(print, ": ");
  101. }
  102. if (k == PRINT_STR || k == PRINT_EXC) {
  103. if (o->args == NULL || o->args->len == 0) {
  104. mp_print_str(print, "");
  105. return;
  106. } else if (o->args->len == 1) {
  107. #if MICROPY_PY_UERRNO
  108. // try to provide a nice OSError error message
  109. if (o->base.type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(o->args->items[0])) {
  110. qstr qst = mp_errno_to_str(o->args->items[0]);
  111. if (qst != MP_QSTR_NULL) {
  112. mp_printf(print, "[Errno " INT_FMT "] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst);
  113. return;
  114. }
  115. }
  116. #endif
  117. mp_obj_print_helper(print, o->args->items[0], PRINT_STR);
  118. return;
  119. }
  120. }
  121. mp_obj_tuple_print(print, MP_OBJ_FROM_PTR(o->args), kind);
  122. }
  123. mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  124. mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
  125. // Try to allocate memory for the exception, with fallback to emergency exception object
  126. mp_obj_exception_t *o_exc = m_new_obj_maybe(mp_obj_exception_t);
  127. if (o_exc == NULL) {
  128. o_exc = &MP_STATE_VM(mp_emergency_exception_obj);
  129. }
  130. // Populate the exception object
  131. o_exc->base.type = type;
  132. o_exc->traceback_data = NULL;
  133. mp_obj_tuple_t *o_tuple;
  134. if (n_args == 0) {
  135. // No args, can use the empty tuple straightaway
  136. o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
  137. } else {
  138. // Try to allocate memory for the tuple containing the args
  139. o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args);
  140. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  141. // If we are called by mp_obj_new_exception_msg_varg then it will have
  142. // reserved room (after the traceback data) for a tuple with 1 element.
  143. // Otherwise we are free to use the whole buffer after the traceback data.
  144. if (o_tuple == NULL && mp_emergency_exception_buf_size >=
  145. EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) {
  146. o_tuple = (mp_obj_tuple_t*)
  147. ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET);
  148. }
  149. #endif
  150. if (o_tuple == NULL) {
  151. // No memory for a tuple, fallback to an empty tuple
  152. o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
  153. } else {
  154. // Have memory for a tuple so populate it
  155. o_tuple->base.type = &mp_type_tuple;
  156. o_tuple->len = n_args;
  157. memcpy(o_tuple->items, args, n_args * sizeof(mp_obj_t));
  158. }
  159. }
  160. // Store the tuple of args in the exception object
  161. o_exc->args = o_tuple;
  162. return MP_OBJ_FROM_PTR(o_exc);
  163. }
  164. // Get exception "value" - that is, first argument, or None
  165. mp_obj_t mp_obj_exception_get_value(mp_obj_t self_in) {
  166. mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
  167. if (self->args->len == 0) {
  168. return mp_const_none;
  169. } else {
  170. return self->args->items[0];
  171. }
  172. }
  173. void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  174. mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
  175. if (dest[0] != MP_OBJ_NULL) {
  176. // store/delete attribute
  177. if (attr == MP_QSTR___traceback__ && dest[1] == mp_const_none) {
  178. // We allow 'exc.__traceback__ = None' assignment as low-level
  179. // optimization of pre-allocating exception instance and raising
  180. // it repeatedly - this avoids memory allocation during raise.
  181. // However, uPy will keep adding traceback entries to such
  182. // exception instance, so before throwing it, traceback should
  183. // be cleared like above.
  184. self->traceback_len = 0;
  185. dest[0] = MP_OBJ_NULL; // indicate success
  186. }
  187. return;
  188. }
  189. if (attr == MP_QSTR_args) {
  190. dest[0] = MP_OBJ_FROM_PTR(self->args);
  191. } else if (self->base.type == &mp_type_StopIteration && attr == MP_QSTR_value) {
  192. dest[0] = mp_obj_exception_get_value(self_in);
  193. }
  194. }
  195. const mp_obj_type_t mp_type_BaseException = {
  196. { &mp_type_type },
  197. .name = MP_QSTR_BaseException,
  198. .print = mp_obj_exception_print,
  199. .make_new = mp_obj_exception_make_new,
  200. .attr = mp_obj_exception_attr,
  201. };
  202. // List of all exceptions, arranged as in the table at:
  203. // http://docs.python.org/3/library/exceptions.html
  204. MP_DEFINE_EXCEPTION(SystemExit, BaseException)
  205. MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
  206. MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
  207. MP_DEFINE_EXCEPTION(Exception, BaseException)
  208. #if MICROPY_PY_ASYNC_AWAIT
  209. MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
  210. #endif
  211. MP_DEFINE_EXCEPTION(StopIteration, Exception)
  212. MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
  213. //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
  214. MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
  215. MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
  216. MP_DEFINE_EXCEPTION(AssertionError, Exception)
  217. MP_DEFINE_EXCEPTION(AttributeError, Exception)
  218. //MP_DEFINE_EXCEPTION(BufferError, Exception)
  219. //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead
  220. MP_DEFINE_EXCEPTION(EOFError, Exception)
  221. MP_DEFINE_EXCEPTION(ImportError, Exception)
  222. //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead
  223. MP_DEFINE_EXCEPTION(LookupError, Exception)
  224. MP_DEFINE_EXCEPTION(IndexError, LookupError)
  225. MP_DEFINE_EXCEPTION(KeyError, LookupError)
  226. MP_DEFINE_EXCEPTION(MemoryError, Exception)
  227. MP_DEFINE_EXCEPTION(NameError, Exception)
  228. /*
  229. MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
  230. */
  231. MP_DEFINE_EXCEPTION(OSError, Exception)
  232. #if MICROPY_PY_BUILTINS_TIMEOUTERROR
  233. MP_DEFINE_EXCEPTION(TimeoutError, OSError)
  234. #endif
  235. /*
  236. MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
  237. MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
  238. MP_DEFINE_EXCEPTION(ConnectionError, OSError)
  239. MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
  240. MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
  241. MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
  242. MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
  243. MP_DEFINE_EXCEPTION(InterruptedError, OSError)
  244. MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
  245. MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
  246. MP_DEFINE_EXCEPTION(PermissionError, OSError)
  247. MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
  248. MP_DEFINE_EXCEPTION(FileExistsError, OSError)
  249. MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
  250. MP_DEFINE_EXCEPTION(ReferenceError, Exception)
  251. */
  252. MP_DEFINE_EXCEPTION(RuntimeError, Exception)
  253. MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
  254. MP_DEFINE_EXCEPTION(SyntaxError, Exception)
  255. MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
  256. /*
  257. MP_DEFINE_EXCEPTION(TabError, IndentationError)
  258. */
  259. //MP_DEFINE_EXCEPTION(SystemError, Exception)
  260. MP_DEFINE_EXCEPTION(TypeError, Exception)
  261. #if MICROPY_EMIT_NATIVE
  262. MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
  263. #endif
  264. MP_DEFINE_EXCEPTION(ValueError, Exception)
  265. #if MICROPY_PY_BUILTINS_STR_UNICODE
  266. MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
  267. //TODO: Implement more UnicodeError subclasses which take arguments
  268. #endif
  269. /*
  270. MP_DEFINE_EXCEPTION(Warning, Exception)
  271. MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
  272. MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
  273. MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
  274. MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
  275. MP_DEFINE_EXCEPTION(UserWarning, Warning)
  276. MP_DEFINE_EXCEPTION(FutureWarning, Warning)
  277. MP_DEFINE_EXCEPTION(ImportWarning, Warning)
  278. MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
  279. MP_DEFINE_EXCEPTION(BytesWarning, Warning)
  280. MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
  281. */
  282. mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
  283. return mp_obj_new_exception_args(exc_type, 0, NULL);
  284. }
  285. // "Optimized" version for common(?) case of having 1 exception arg
  286. mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
  287. return mp_obj_new_exception_args(exc_type, 1, &arg);
  288. }
  289. mp_obj_t mp_obj_new_exception_args(const mp_obj_type_t *exc_type, size_t n_args, const mp_obj_t *args) {
  290. assert(exc_type->make_new == mp_obj_exception_make_new);
  291. return exc_type->make_new(exc_type, n_args, 0, args);
  292. }
  293. mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg) {
  294. // Check that the given type is an exception type
  295. assert(exc_type->make_new == mp_obj_exception_make_new);
  296. // Try to allocate memory for the message
  297. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
  298. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  299. // If memory allocation failed and there is an emergency buffer then try to use
  300. // that buffer to store the string object, reserving room at the start for the
  301. // traceback and 1-tuple.
  302. if (o_str == NULL
  303. && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t)) {
  304. o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  305. + EMG_BUF_STR_OFFSET);
  306. }
  307. #endif
  308. if (o_str == NULL) {
  309. // No memory for the string object so create the exception with no args
  310. return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
  311. }
  312. // Create the string object and call mp_obj_exception_make_new to create the exception
  313. o_str->base.type = &mp_type_str;
  314. o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
  315. o_str->len = strlen(msg);
  316. o_str->data = (const byte*)msg;
  317. mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
  318. return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
  319. }
  320. // The following struct and function implement a simple printer that conservatively
  321. // allocates memory and truncates the output data if no more memory can be obtained.
  322. // It leaves room for a null byte at the end of the buffer.
  323. struct _exc_printer_t {
  324. bool allow_realloc;
  325. size_t alloc;
  326. size_t len;
  327. byte *buf;
  328. };
  329. STATIC void exc_add_strn(void *data, const char *str, size_t len) {
  330. struct _exc_printer_t *pr = data;
  331. if (pr->len + len >= pr->alloc) {
  332. // Not enough room for data plus a null byte so try to grow the buffer
  333. if (pr->allow_realloc) {
  334. size_t new_alloc = pr->alloc + len + 16;
  335. byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
  336. if (new_buf == NULL) {
  337. pr->allow_realloc = false;
  338. len = pr->alloc - pr->len - 1;
  339. } else {
  340. pr->alloc = new_alloc;
  341. pr->buf = new_buf;
  342. }
  343. } else {
  344. len = pr->alloc - pr->len - 1;
  345. }
  346. }
  347. memcpy(pr->buf + pr->len, str, len);
  348. pr->len += len;
  349. }
  350. mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...) {
  351. assert(fmt != NULL);
  352. // Check that the given type is an exception type
  353. assert(exc_type->make_new == mp_obj_exception_make_new);
  354. // Try to allocate memory for the message
  355. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
  356. size_t o_str_alloc = strlen(fmt) + 1;
  357. byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
  358. bool used_emg_buf = false;
  359. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  360. // If memory allocation failed and there is an emergency buffer then try to use
  361. // that buffer to store the string object and its data (at least 16 bytes for
  362. // the string data), reserving room at the start for the traceback and 1-tuple.
  363. if ((o_str == NULL || o_str_buf == NULL)
  364. && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) {
  365. used_emg_buf = true;
  366. o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  367. + EMG_BUF_STR_OFFSET);
  368. o_str_buf = (byte*)&o_str[1];
  369. o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  370. + mp_emergency_exception_buf_size - o_str_buf;
  371. }
  372. #endif
  373. if (o_str == NULL) {
  374. // No memory for the string object so create the exception with no args
  375. return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
  376. }
  377. if (o_str_buf == NULL) {
  378. // No memory for the string buffer: assume that the fmt string is in ROM
  379. // and use that data as the data of the string
  380. o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
  381. o_str->data = (const byte*)fmt;
  382. } else {
  383. // We have some memory to format the string
  384. struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
  385. mp_print_t print = {&exc_pr, exc_add_strn};
  386. va_list ap;
  387. va_start(ap, fmt);
  388. mp_vprintf(&print, fmt, ap);
  389. va_end(ap);
  390. exc_pr.buf[exc_pr.len] = '\0';
  391. o_str->len = exc_pr.len;
  392. o_str->data = exc_pr.buf;
  393. }
  394. // Create the string object and call mp_obj_exception_make_new to create the exception
  395. o_str->base.type = &mp_type_str;
  396. o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
  397. mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
  398. return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
  399. }
  400. // return true if the given object is an exception type
  401. bool mp_obj_is_exception_type(mp_obj_t self_in) {
  402. if (MP_OBJ_IS_TYPE(self_in, &mp_type_type)) {
  403. // optimisation when self_in is a builtin exception
  404. mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
  405. if (self->make_new == mp_obj_exception_make_new) {
  406. return true;
  407. }
  408. }
  409. return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
  410. }
  411. // return true if the given object is an instance of an exception type
  412. bool mp_obj_is_exception_instance(mp_obj_t self_in) {
  413. return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
  414. }
  415. // Return true if exception (type or instance) is a subclass of given
  416. // exception type. Assumes exc_type is a subclass of BaseException, as
  417. // defined by mp_obj_is_exception_type(exc_type).
  418. bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
  419. // if exc is an instance of an exception, then extract and use its type
  420. if (mp_obj_is_exception_instance(exc)) {
  421. exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
  422. }
  423. return mp_obj_is_subclass_fast(exc, exc_type);
  424. }
  425. // traceback handling functions
  426. #define GET_NATIVE_EXCEPTION(self, self_in) \
  427. /* make sure self_in is an exception instance */ \
  428. assert(mp_obj_is_exception_instance(self_in)); \
  429. mp_obj_exception_t *self; \
  430. if (mp_obj_is_native_exception_instance(self_in)) { \
  431. self = MP_OBJ_TO_PTR(self_in); \
  432. } else { \
  433. self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
  434. }
  435. void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
  436. GET_NATIVE_EXCEPTION(self, self_in);
  437. // just set the traceback to the null object
  438. // we don't want to call any memory management functions here
  439. self->traceback_data = NULL;
  440. }
  441. void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
  442. GET_NATIVE_EXCEPTION(self, self_in);
  443. // append this traceback info to traceback data
  444. // if memory allocation fails (eg because gc is locked), just return
  445. if (self->traceback_data == NULL) {
  446. self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
  447. if (self->traceback_data == NULL) {
  448. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  449. if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) {
  450. // There is room in the emergency buffer for traceback data
  451. size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  452. + EMG_BUF_TRACEBACK_OFFSET);
  453. self->traceback_data = tb;
  454. self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t);
  455. } else {
  456. // Can't allocate and no room in emergency buffer
  457. return;
  458. }
  459. #else
  460. // Can't allocate
  461. return;
  462. #endif
  463. } else {
  464. // Allocated the traceback data on the heap
  465. self->traceback_alloc = TRACEBACK_ENTRY_LEN;
  466. }
  467. self->traceback_len = 0;
  468. } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
  469. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  470. if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
  471. // Can't resize the emergency buffer
  472. return;
  473. }
  474. #endif
  475. // be conservative with growing traceback data
  476. size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
  477. self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
  478. if (tb_data == NULL) {
  479. return;
  480. }
  481. self->traceback_data = tb_data;
  482. self->traceback_alloc += TRACEBACK_ENTRY_LEN;
  483. }
  484. size_t *tb_data = &self->traceback_data[self->traceback_len];
  485. self->traceback_len += TRACEBACK_ENTRY_LEN;
  486. tb_data[0] = file;
  487. tb_data[1] = line;
  488. tb_data[2] = block;
  489. }
  490. void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
  491. GET_NATIVE_EXCEPTION(self, self_in);
  492. if (self->traceback_data == NULL) {
  493. *n = 0;
  494. *values = NULL;
  495. } else {
  496. *n = self->traceback_len;
  497. *values = self->traceback_data;
  498. }
  499. }