objexcept.c 20 KB

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