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