objexcept.c 26 KB

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