objexcept.c 21 KB

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