objexcept.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 " INT_FMT "] %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. const mp_obj_type_t mp_type_BaseException = {
  188. { &mp_type_type },
  189. .name = MP_QSTR_BaseException,
  190. .print = mp_obj_exception_print,
  191. .make_new = mp_obj_exception_make_new,
  192. .attr = exception_attr,
  193. };
  194. #define MP_DEFINE_EXCEPTION(exc_name, base_name) \
  195. const mp_obj_type_t mp_type_ ## exc_name = { \
  196. { &mp_type_type }, \
  197. .name = MP_QSTR_ ## exc_name, \
  198. .print = mp_obj_exception_print, \
  199. .make_new = mp_obj_exception_make_new, \
  200. .attr = exception_attr, \
  201. .parent = &mp_type_ ## base_name, \
  202. };
  203. // List of all exceptions, arranged as in the table at:
  204. // http://docs.python.org/3/library/exceptions.html
  205. MP_DEFINE_EXCEPTION(SystemExit, BaseException)
  206. MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
  207. MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
  208. MP_DEFINE_EXCEPTION(Exception, BaseException)
  209. #if MICROPY_PY_ASYNC_AWAIT
  210. MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
  211. #endif
  212. MP_DEFINE_EXCEPTION(StopIteration, Exception)
  213. MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
  214. //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
  215. MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
  216. MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
  217. MP_DEFINE_EXCEPTION(AssertionError, Exception)
  218. MP_DEFINE_EXCEPTION(AttributeError, Exception)
  219. //MP_DEFINE_EXCEPTION(BufferError, Exception)
  220. //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead
  221. MP_DEFINE_EXCEPTION(EOFError, Exception)
  222. MP_DEFINE_EXCEPTION(ImportError, Exception)
  223. //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead
  224. MP_DEFINE_EXCEPTION(LookupError, Exception)
  225. MP_DEFINE_EXCEPTION(IndexError, LookupError)
  226. MP_DEFINE_EXCEPTION(KeyError, LookupError)
  227. MP_DEFINE_EXCEPTION(MemoryError, Exception)
  228. MP_DEFINE_EXCEPTION(NameError, Exception)
  229. /*
  230. MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
  231. */
  232. MP_DEFINE_EXCEPTION(OSError, Exception)
  233. #if MICROPY_PY_BUILTINS_TIMEOUTERROR
  234. MP_DEFINE_EXCEPTION(TimeoutError, OSError)
  235. #endif
  236. /*
  237. MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
  238. MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
  239. MP_DEFINE_EXCEPTION(ConnectionError, OSError)
  240. MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
  241. MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
  242. MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
  243. MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
  244. MP_DEFINE_EXCEPTION(InterruptedError, OSError)
  245. MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
  246. MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
  247. MP_DEFINE_EXCEPTION(PermissionError, OSError)
  248. MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
  249. MP_DEFINE_EXCEPTION(FileExistsError, OSError)
  250. MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
  251. MP_DEFINE_EXCEPTION(ReferenceError, Exception)
  252. */
  253. MP_DEFINE_EXCEPTION(RuntimeError, Exception)
  254. MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
  255. MP_DEFINE_EXCEPTION(SyntaxError, Exception)
  256. MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
  257. /*
  258. MP_DEFINE_EXCEPTION(TabError, IndentationError)
  259. */
  260. //MP_DEFINE_EXCEPTION(SystemError, Exception)
  261. MP_DEFINE_EXCEPTION(TypeError, Exception)
  262. #if MICROPY_EMIT_NATIVE
  263. MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
  264. #endif
  265. MP_DEFINE_EXCEPTION(ValueError, Exception)
  266. #if MICROPY_PY_BUILTINS_STR_UNICODE
  267. MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
  268. //TODO: Implement more UnicodeError subclasses which take arguments
  269. #endif
  270. /*
  271. MP_DEFINE_EXCEPTION(Warning, Exception)
  272. MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
  273. MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
  274. MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
  275. MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
  276. MP_DEFINE_EXCEPTION(UserWarning, Warning)
  277. MP_DEFINE_EXCEPTION(FutureWarning, Warning)
  278. MP_DEFINE_EXCEPTION(ImportWarning, Warning)
  279. MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
  280. MP_DEFINE_EXCEPTION(BytesWarning, Warning)
  281. MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
  282. */
  283. mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
  284. return mp_obj_new_exception_args(exc_type, 0, NULL);
  285. }
  286. // "Optimized" version for common(?) case of having 1 exception arg
  287. mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
  288. return mp_obj_new_exception_args(exc_type, 1, &arg);
  289. }
  290. mp_obj_t mp_obj_new_exception_args(const mp_obj_type_t *exc_type, size_t n_args, const mp_obj_t *args) {
  291. assert(exc_type->make_new == mp_obj_exception_make_new);
  292. return exc_type->make_new(exc_type, n_args, 0, args);
  293. }
  294. mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg) {
  295. return mp_obj_new_exception_msg_varg(exc_type, msg);
  296. }
  297. // The following struct and function implement a simple printer that conservatively
  298. // allocates memory and truncates the output data if no more memory can be obtained.
  299. // It leaves room for a null byte at the end of the buffer.
  300. struct _exc_printer_t {
  301. bool allow_realloc;
  302. size_t alloc;
  303. size_t len;
  304. byte *buf;
  305. };
  306. STATIC void exc_add_strn(void *data, const char *str, size_t len) {
  307. struct _exc_printer_t *pr = data;
  308. if (pr->len + len >= pr->alloc) {
  309. // Not enough room for data plus a null byte so try to grow the buffer
  310. if (pr->allow_realloc) {
  311. size_t new_alloc = pr->alloc + len + 16;
  312. byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
  313. if (new_buf == NULL) {
  314. pr->allow_realloc = false;
  315. len = pr->alloc - pr->len - 1;
  316. } else {
  317. pr->alloc = new_alloc;
  318. pr->buf = new_buf;
  319. }
  320. } else {
  321. len = pr->alloc - pr->len - 1;
  322. }
  323. }
  324. memcpy(pr->buf + pr->len, str, len);
  325. pr->len += len;
  326. }
  327. mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...) {
  328. assert(fmt != NULL);
  329. // Check that the given type is an exception type
  330. assert(exc_type->make_new == mp_obj_exception_make_new);
  331. // Try to allocate memory for the message
  332. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
  333. size_t o_str_alloc = strlen(fmt) + 1;
  334. byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
  335. bool used_emg_buf = false;
  336. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  337. // If memory allocation failed and there is an emergency buffer then try to use
  338. // that buffer to store the string object and its data (at least 16 bytes for
  339. // the string data), reserving room at the start for the traceback and 1-tuple.
  340. if ((o_str == NULL || o_str_buf == NULL)
  341. && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)
  342. + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) {
  343. used_emg_buf = true;
  344. o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  345. + EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t));
  346. o_str_buf = (byte*)&o_str[1];
  347. o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
  348. + mp_emergency_exception_buf_size - o_str_buf;
  349. }
  350. #endif
  351. if (o_str == NULL) {
  352. // No memory for the string object so create the exception with no args
  353. return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
  354. }
  355. if (o_str_buf == NULL) {
  356. // No memory for the string buffer: assume that the fmt string is in ROM
  357. // and use that data as the data of the string
  358. o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
  359. o_str->data = (const byte*)fmt;
  360. } else {
  361. // We have some memory to format the string
  362. struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
  363. mp_print_t print = {&exc_pr, exc_add_strn};
  364. va_list ap;
  365. va_start(ap, fmt);
  366. mp_vprintf(&print, fmt, ap);
  367. va_end(ap);
  368. exc_pr.buf[exc_pr.len] = '\0';
  369. o_str->len = exc_pr.len;
  370. o_str->data = exc_pr.buf;
  371. }
  372. // Create the string object and call mp_obj_exception_make_new to create the exception
  373. o_str->base.type = &mp_type_str;
  374. o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
  375. mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
  376. return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
  377. }
  378. // return true if the given object is an exception type
  379. bool mp_obj_is_exception_type(mp_obj_t self_in) {
  380. if (MP_OBJ_IS_TYPE(self_in, &mp_type_type)) {
  381. // optimisation when self_in is a builtin exception
  382. mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
  383. if (self->make_new == mp_obj_exception_make_new) {
  384. return true;
  385. }
  386. }
  387. return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
  388. }
  389. // return true if the given object is an instance of an exception type
  390. bool mp_obj_is_exception_instance(mp_obj_t self_in) {
  391. return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
  392. }
  393. // Return true if exception (type or instance) is a subclass of given
  394. // exception type. Assumes exc_type is a subclass of BaseException, as
  395. // defined by mp_obj_is_exception_type(exc_type).
  396. bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
  397. // if exc is an instance of an exception, then extract and use its type
  398. if (mp_obj_is_exception_instance(exc)) {
  399. exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
  400. }
  401. return mp_obj_is_subclass_fast(exc, exc_type);
  402. }
  403. // traceback handling functions
  404. #define GET_NATIVE_EXCEPTION(self, self_in) \
  405. /* make sure self_in is an exception instance */ \
  406. assert(mp_obj_is_exception_instance(self_in)); \
  407. mp_obj_exception_t *self; \
  408. if (mp_obj_is_native_exception_instance(self_in)) { \
  409. self = MP_OBJ_TO_PTR(self_in); \
  410. } else { \
  411. self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
  412. }
  413. void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
  414. GET_NATIVE_EXCEPTION(self, self_in);
  415. // just set the traceback to the null object
  416. // we don't want to call any memory management functions here
  417. self->traceback_data = NULL;
  418. }
  419. void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
  420. GET_NATIVE_EXCEPTION(self, self_in);
  421. // append this traceback info to traceback data
  422. // if memory allocation fails (eg because gc is locked), just return
  423. if (self->traceback_data == NULL) {
  424. self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
  425. if (self->traceback_data == NULL) {
  426. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  427. if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) {
  428. // There is room in the emergency buffer for traceback data
  429. size_t *tb = (size_t*)MP_STATE_VM(mp_emergency_exception_buf);
  430. self->traceback_data = tb;
  431. self->traceback_alloc = EMG_TRACEBACK_ALLOC;
  432. } else {
  433. // Can't allocate and no room in emergency buffer
  434. return;
  435. }
  436. #else
  437. // Can't allocate
  438. return;
  439. #endif
  440. } else {
  441. // Allocated the traceback data on the heap
  442. self->traceback_alloc = TRACEBACK_ENTRY_LEN;
  443. }
  444. self->traceback_len = 0;
  445. } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
  446. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
  447. if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
  448. // Can't resize the emergency buffer
  449. return;
  450. }
  451. #endif
  452. // be conservative with growing traceback data
  453. size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
  454. self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
  455. if (tb_data == NULL) {
  456. return;
  457. }
  458. self->traceback_data = tb_data;
  459. self->traceback_alloc += TRACEBACK_ENTRY_LEN;
  460. }
  461. size_t *tb_data = &self->traceback_data[self->traceback_len];
  462. self->traceback_len += TRACEBACK_ENTRY_LEN;
  463. tb_data[0] = file;
  464. tb_data[1] = line;
  465. tb_data[2] = block;
  466. }
  467. void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
  468. GET_NATIVE_EXCEPTION(self, self_in);
  469. if (self->traceback_data == NULL) {
  470. *n = 0;
  471. *values = NULL;
  472. } else {
  473. *n = self->traceback_len;
  474. *values = self->traceback_data;
  475. }
  476. }