objexcept.c 25 KB

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