objexcept.c 21 KB

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