blob: b5c1693279a27d97033d02ec12ce00ca08729676 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovsky016d9a42019-05-14 15:51:57 +03007 * Copyright (c) 2014-2016 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
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
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
Damien George6c73ca12014-01-08 18:11:23 +000029#include <stdarg.h>
Damiend99b0522013-12-21 18:17:45 +000030#include <assert.h>
Dave Hylands5b7fd202014-07-01 23:46:53 -070031#include <stdio.h>
Damiend99b0522013-12-21 18:17:45 +000032
Damien George51dfcb42015-01-01 20:27:54 +000033#include "py/objlist.h"
34#include "py/objstr.h"
35#include "py/objtuple.h"
36#include "py/objtype.h"
Damien George50149a52015-01-20 14:11:27 +000037#include "py/runtime.h"
Damien George51dfcb42015-01-01 20:27:54 +000038#include "py/gc.h"
Damien Georged45e5f82016-05-12 13:20:40 +010039#include "py/mperrno.h"
Damiend99b0522013-12-21 18:17:45 +000040
Damien George96fd80d2017-09-21 15:24:57 +100041// Number of items per traceback entry (file, line, block)
42#define TRACEBACK_ENTRY_LEN (3)
43
Damien Georgebad4e152018-12-08 01:50:20 +110044// Optionally allocated buffer for storing some traceback, the tuple argument,
45// and possible string object and data, for when the heap is locked.
Dave Hylands5b7fd202014-07-01 23:46:53 -070046#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
Damien Georgebad4e152018-12-08 01:50:20 +110047
48// When used the layout of the emergency exception buffer is:
49// - traceback entry (file, line, block)
50// - traceback entry (file, line, block)
51// - mp_obj_tuple_t object
52// - n_args * mp_obj_t for tuple
53// - mp_obj_str_t object
54// - string data
55#define EMG_BUF_TRACEBACK_OFFSET (0)
56#define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t))
57#define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE)
58#define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t))
59#define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1))
60
Dave Hylands5b7fd202014-07-01 23:46:53 -070061# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
Dave Hylands5b7fd202014-07-01 23:46:53 -070062#define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
63
64void mp_init_emergency_exception_buf(void) {
65 // Nothing to do since the buffer was declared statically. We put this
66 // definition here so that the calling code can call this function
67 // regardless of how its configured (makes the calling code a bit cleaner).
68}
69
70#else
Damien Georgeb4b10fd2015-01-01 23:30:53 +000071#define mp_emergency_exception_buf_size MP_STATE_VM(mp_emergency_exception_buf_size)
Dave Hylands5b7fd202014-07-01 23:46:53 -070072
73void mp_init_emergency_exception_buf(void) {
74 mp_emergency_exception_buf_size = 0;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000075 MP_STATE_VM(mp_emergency_exception_buf) = NULL;
Dave Hylands5b7fd202014-07-01 23:46:53 -070076}
77
78mp_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) {
Damien George4d77e1a2015-02-27 09:34:51 +000082 buf = m_new(byte, size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070083 }
84
85 int old_size = mp_emergency_exception_buf_size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000086 void *old_buf = MP_STATE_VM(mp_emergency_exception_buf);
Dave Hylands5b7fd202014-07-01 23:46:53 -070087
88 // Update the 2 variables atomically so that an interrupt can't occur
89 // between the assignments.
Damien George4859edb2014-10-15 17:33:24 +000090 mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
Dave Hylands5b7fd202014-07-01 23:46:53 -070091 mp_emergency_exception_buf_size = size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000092 MP_STATE_VM(mp_emergency_exception_buf) = buf;
Damien George4859edb2014-10-15 17:33:24 +000093 MICROPY_END_ATOMIC_SECTION(atomic_state);
Dave Hylands5b7fd202014-07-01 23:46:53 -070094
95 if (old_buf != NULL) {
Damien George4d77e1a2015-02-27 09:34:51 +000096 m_del(byte, old_buf, old_size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070097 }
98 return mp_const_none;
99}
100#endif
101#endif // MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
102
Damien George5edce452018-03-17 00:31:40 +1100103void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
Damien George999cedb2015-11-27 17:01:44 +0000104 mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in);
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300105 mp_print_kind_t k = kind & ~PRINT_EXC_SUBCLASS;
106 bool is_subclass = kind & PRINT_EXC_SUBCLASS;
107 if (!is_subclass && (k == PRINT_REPR || k == PRINT_EXC)) {
Damien George044c4732015-04-11 13:03:37 +0100108 mp_print_str(print, qstr_str(o->base.type->name));
Damiend99b0522013-12-21 18:17:45 +0000109 }
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300110
111 if (k == PRINT_EXC) {
Damien George7f9d1d62015-04-09 23:56:15 +0100112 mp_print_str(print, ": ");
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300113 }
114
115 if (k == PRINT_STR || k == PRINT_EXC) {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300116 if (o->args == NULL || o->args->len == 0) {
Damien George7f9d1d62015-04-09 23:56:15 +0100117 mp_print_str(print, "");
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300118 return;
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300119 } else if (o->args->len == 1) {
Damien George9a924992016-05-12 14:27:52 +0100120 #if MICROPY_PY_UERRNO
121 // try to provide a nice OSError error message
Damien Georgeeee1e882019-01-30 18:49:52 +1100122 if (o->base.type == &mp_type_OSError && mp_obj_is_small_int(o->args->items[0])) {
Damien George9a924992016-05-12 14:27:52 +0100123 qstr qst = mp_errno_to_str(o->args->items[0]);
Josh Lloyd7d58a192019-09-25 17:53:30 +1200124 if (qst != MP_QSTRnull) {
Damien George9c027072017-12-11 22:38:30 +1100125 mp_printf(print, "[Errno " INT_FMT "] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst);
Damien George9a924992016-05-12 14:27:52 +0100126 return;
127 }
128 }
129 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100130 mp_obj_print_helper(print, o->args->items[0], PRINT_STR);
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300131 return;
132 }
133 }
Damien George999cedb2015-11-27 17:01:44 +0000134 mp_obj_tuple_print(print, MP_OBJ_FROM_PTR(o->args), kind);
Damiend99b0522013-12-21 18:17:45 +0000135}
136
Damien George5b3f0b72016-01-03 15:55:55 +0000137mp_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) {
Damien George50149a52015-01-20 14:11:27 +0000138 mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
Damien George96fd80d2017-09-21 15:24:57 +1000139
140 // Try to allocate memory for the exception, with fallback to emergency exception object
141 mp_obj_exception_t *o_exc = m_new_obj_maybe(mp_obj_exception_t);
142 if (o_exc == NULL) {
143 o_exc = &MP_STATE_VM(mp_emergency_exception_obj);
Damien Georgef0954e32014-04-10 14:38:25 +0100144 }
Damien George96fd80d2017-09-21 15:24:57 +1000145
146 // Populate the exception object
147 o_exc->base.type = type;
148 o_exc->traceback_data = NULL;
149
150 mp_obj_tuple_t *o_tuple;
151 if (n_args == 0) {
152 // No args, can use the empty tuple straightaway
153 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
154 } else {
155 // Try to allocate memory for the tuple containing the args
156 o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args);
157
158 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
159 // If we are called by mp_obj_new_exception_msg_varg then it will have
160 // reserved room (after the traceback data) for a tuple with 1 element.
161 // Otherwise we are free to use the whole buffer after the traceback data.
162 if (o_tuple == NULL && mp_emergency_exception_buf_size >=
Damien Georgebad4e152018-12-08 01:50:20 +1100163 EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) {
Damien George96fd80d2017-09-21 15:24:57 +1000164 o_tuple = (mp_obj_tuple_t*)
Damien Georgebad4e152018-12-08 01:50:20 +1100165 ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000166 }
167 #endif
168
169 if (o_tuple == NULL) {
170 // No memory for a tuple, fallback to an empty tuple
171 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
172 } else {
173 // Have memory for a tuple so populate it
174 o_tuple->base.type = &mp_type_tuple;
175 o_tuple->len = n_args;
176 memcpy(o_tuple->items, args, n_args * sizeof(mp_obj_t));
177 }
178 }
179
180 // Store the tuple of args in the exception object
181 o_exc->args = o_tuple;
182
183 return MP_OBJ_FROM_PTR(o_exc);
Paul Sokolovskyddf21782014-01-12 23:30:20 +0200184}
185
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200186// Get exception "value" - that is, first argument, or None
187mp_obj_t mp_obj_exception_get_value(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000188 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300189 if (self->args->len == 0) {
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200190 return mp_const_none;
191 } else {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300192 return self->args->items[0];
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200193 }
194}
195
Damien George5edce452018-03-17 00:31:40 +1100196void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300197 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb1bbe962015-04-01 14:10:50 +0000198 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300199 // store/delete attribute
200 if (attr == MP_QSTR___traceback__ && dest[1] == mp_const_none) {
201 // We allow 'exc.__traceback__ = None' assignment as low-level
202 // optimization of pre-allocating exception instance and raising
203 // it repeatedly - this avoids memory allocation during raise.
204 // However, uPy will keep adding traceback entries to such
205 // exception instance, so before throwing it, traceback should
206 // be cleared like above.
207 self->traceback_len = 0;
208 dest[0] = MP_OBJ_NULL; // indicate success
209 }
Damien Georgeb1bbe962015-04-01 14:10:50 +0000210 return;
211 }
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200212 if (attr == MP_QSTR_args) {
Damien George999cedb2015-11-27 17:01:44 +0000213 dest[0] = MP_OBJ_FROM_PTR(self->args);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200214 } else if (self->base.type == &mp_type_StopIteration && attr == MP_QSTR_value) {
Damien George999cedb2015-11-27 17:01:44 +0000215 dest[0] = mp_obj_exception_get_value(self_in);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200216 }
217}
218
Damien Georgec5966122014-02-15 16:10:44 +0000219const mp_obj_type_t mp_type_BaseException = {
220 { &mp_type_type },
221 .name = MP_QSTR_BaseException,
222 .print = mp_obj_exception_print,
223 .make_new = mp_obj_exception_make_new,
Damien George5edce452018-03-17 00:31:40 +1100224 .attr = mp_obj_exception_attr,
Damien Georgec5966122014-02-15 16:10:44 +0000225};
226
Damien George3f39d182020-02-26 11:58:42 +1100227// *FORMAT-OFF*
228
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000229// List of all exceptions, arranged as in the table at:
Chris Angelicodaf973a2014-06-06 03:51:03 +1000230// http://docs.python.org/3/library/exceptions.html
Damien George7a4ddd22014-05-24 23:32:19 +0100231MP_DEFINE_EXCEPTION(SystemExit, BaseException)
Damien George124df6f2014-10-25 18:19:55 +0100232MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000233MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
234MP_DEFINE_EXCEPTION(Exception, BaseException)
pohmelie81ebba72016-01-27 23:23:11 +0300235 #if MICROPY_PY_ASYNC_AWAIT
236 MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
237 #endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000238 MP_DEFINE_EXCEPTION(StopIteration, Exception)
239 MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000240 //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000241 MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
242 MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
243 MP_DEFINE_EXCEPTION(AssertionError, Exception)
244 MP_DEFINE_EXCEPTION(AttributeError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000245 //MP_DEFINE_EXCEPTION(BufferError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000246 MP_DEFINE_EXCEPTION(EOFError, Exception)
247 MP_DEFINE_EXCEPTION(ImportError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000248 MP_DEFINE_EXCEPTION(LookupError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000249 MP_DEFINE_EXCEPTION(IndexError, LookupError)
250 MP_DEFINE_EXCEPTION(KeyError, LookupError)
251 MP_DEFINE_EXCEPTION(MemoryError, Exception)
252 MP_DEFINE_EXCEPTION(NameError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000253 /*
Antonin ENFRUNda1fffa2014-05-12 00:21:50 +0200254 MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
255 */
256 MP_DEFINE_EXCEPTION(OSError, Exception)
Daniel Campora077812b2015-06-29 22:45:39 +0200257#if MICROPY_PY_BUILTINS_TIMEOUTERROR
Daniel Campora077812b2015-06-29 22:45:39 +0200258 MP_DEFINE_EXCEPTION(TimeoutError, OSError)
259#endif
260 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000261 MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000262 MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
263 MP_DEFINE_EXCEPTION(ConnectionError, OSError)
264 MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
265 MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
266 MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
267 MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000268 MP_DEFINE_EXCEPTION(InterruptedError, OSError)
269 MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
270 MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
271 MP_DEFINE_EXCEPTION(PermissionError, OSError)
272 MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
Damien Georgec9109722014-03-22 23:40:02 +0000273 MP_DEFINE_EXCEPTION(FileExistsError, OSError)
274 MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
Damien Georgec63f9842014-03-27 23:49:06 +0000275 MP_DEFINE_EXCEPTION(ReferenceError, Exception)
276 */
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000277 MP_DEFINE_EXCEPTION(RuntimeError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000278 MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
279 MP_DEFINE_EXCEPTION(SyntaxError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000280 MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
Damien Georgec63f9842014-03-27 23:49:06 +0000281 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000282 MP_DEFINE_EXCEPTION(TabError, IndentationError)
283 */
Damien Georgee7a47822014-10-22 19:42:55 +0100284 //MP_DEFINE_EXCEPTION(SystemError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000285 MP_DEFINE_EXCEPTION(TypeError, Exception)
Damien Georgec8b60f02015-04-20 13:29:31 +0000286#if MICROPY_EMIT_NATIVE
Damien Georgec8b60f02015-04-20 13:29:31 +0000287 MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
288#endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000289 MP_DEFINE_EXCEPTION(ValueError, Exception)
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200290#if MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200291 MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
292 //TODO: Implement more UnicodeError subclasses which take arguments
293#endif
Damien Georgec9109722014-03-22 23:40:02 +0000294 /*
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000295 MP_DEFINE_EXCEPTION(Warning, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000296 MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
297 MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
298 MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
299 MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
300 MP_DEFINE_EXCEPTION(UserWarning, Warning)
301 MP_DEFINE_EXCEPTION(FutureWarning, Warning)
302 MP_DEFINE_EXCEPTION(ImportWarning, Warning)
303 MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
304 MP_DEFINE_EXCEPTION(BytesWarning, Warning)
305 MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
Damien Georgec9109722014-03-22 23:40:02 +0000306 */
Damien Georgec5966122014-02-15 16:10:44 +0000307
Damien George3f39d182020-02-26 11:58:42 +1100308// *FORMAT-ON*
309
Damien Georgec5966122014-02-15 16:10:44 +0000310mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
Damien Georgee2c12262020-01-23 13:03:00 +1100311 assert(exc_type->make_new == mp_obj_exception_make_new);
312 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
Damiend99b0522013-12-21 18:17:45 +0000313}
314
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300315// "Optimized" version for common(?) case of having 1 exception arg
316mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
Damien Georgee2c12262020-01-23 13:03:00 +1100317 assert(exc_type->make_new == mp_obj_exception_make_new);
318 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300319}
320
Damien Georgefa5a5912017-02-16 16:38:14 +1100321mp_obj_t mp_obj_new_exception_args(const mp_obj_type_t *exc_type, size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200322 assert(exc_type->make_new == mp_obj_exception_make_new);
Damien Georgee2c12262020-01-23 13:03:00 +1100323 return mp_obj_exception_make_new(exc_type, n_args, 0, args);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200324}
325
Damien Georgec5966122014-02-15 16:10:44 +0000326mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg) {
Damien George55830dd2018-12-10 15:57:03 +1100327 // Check that the given type is an exception type
328 assert(exc_type->make_new == mp_obj_exception_make_new);
329
330 // Try to allocate memory for the message
331 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
332
333 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
334 // If memory allocation failed and there is an emergency buffer then try to use
335 // that buffer to store the string object, reserving room at the start for the
336 // traceback and 1-tuple.
337 if (o_str == NULL
338 && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t)) {
339 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
340 + EMG_BUF_STR_OFFSET);
341 }
342 #endif
343
344 if (o_str == NULL) {
345 // No memory for the string object so create the exception with no args
346 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
347 }
348
349 // Create the string object and call mp_obj_exception_make_new to create the exception
350 o_str->base.type = &mp_type_str;
Damien George55830dd2018-12-10 15:57:03 +1100351 o_str->len = strlen(msg);
352 o_str->data = (const byte*)msg;
Tom Collins2d644ac2019-03-01 19:57:07 -0500353 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
Damien George55830dd2018-12-10 15:57:03 +1100354 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
355 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000356}
357
Damien George96fd80d2017-09-21 15:24:57 +1000358// The following struct and function implement a simple printer that conservatively
359// allocates memory and truncates the output data if no more memory can be obtained.
360// It leaves room for a null byte at the end of the buffer.
Damien Georgec5966122014-02-15 16:10:44 +0000361
Damien George96fd80d2017-09-21 15:24:57 +1000362struct _exc_printer_t {
363 bool allow_realloc;
364 size_t alloc;
365 size_t len;
366 byte *buf;
367};
Dave Hylands5b7fd202014-07-01 23:46:53 -0700368
Damien George96fd80d2017-09-21 15:24:57 +1000369STATIC void exc_add_strn(void *data, const char *str, size_t len) {
370 struct _exc_printer_t *pr = data;
371 if (pr->len + len >= pr->alloc) {
372 // Not enough room for data plus a null byte so try to grow the buffer
373 if (pr->allow_realloc) {
374 size_t new_alloc = pr->alloc + len + 16;
375 byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
376 if (new_buf == NULL) {
377 pr->allow_realloc = false;
378 len = pr->alloc - pr->len - 1;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300379 } else {
Damien George96fd80d2017-09-21 15:24:57 +1000380 pr->alloc = new_alloc;
381 pr->buf = new_buf;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300382 }
Damien George96fd80d2017-09-21 15:24:57 +1000383 } else {
384 len = pr->alloc - pr->len - 1;
Damien Georgef0954e32014-04-10 14:38:25 +0100385 }
Damien George6c73ca12014-01-08 18:11:23 +0000386 }
Damien George96fd80d2017-09-21 15:24:57 +1000387 memcpy(pr->buf + pr->len, str, len);
388 pr->len += len;
389}
Damien George6c73ca12014-01-08 18:11:23 +0000390
Damien George96fd80d2017-09-21 15:24:57 +1000391mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...) {
Damien Georgead7213d2020-02-11 11:48:28 +1100392 va_list args;
393 va_start(args, fmt);
Damien George1fccda02020-02-18 21:00:42 +1100394 mp_obj_t exc = mp_obj_new_exception_msg_vlist(exc_type, fmt, args);
Damien Georgead7213d2020-02-11 11:48:28 +1100395 va_end(args);
396 return exc;
397}
398
Damien George1fccda02020-02-18 21:00:42 +1100399mp_obj_t mp_obj_new_exception_msg_vlist(const mp_obj_type_t *exc_type, const char *fmt, va_list args) {
Damien George96fd80d2017-09-21 15:24:57 +1000400 assert(fmt != NULL);
401
402 // Check that the given type is an exception type
403 assert(exc_type->make_new == mp_obj_exception_make_new);
404
405 // Try to allocate memory for the message
406 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
407 size_t o_str_alloc = strlen(fmt) + 1;
408 byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
409
410 bool used_emg_buf = false;
411 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
412 // If memory allocation failed and there is an emergency buffer then try to use
413 // that buffer to store the string object and its data (at least 16 bytes for
414 // the string data), reserving room at the start for the traceback and 1-tuple.
415 if ((o_str == NULL || o_str_buf == NULL)
Damien Georgebad4e152018-12-08 01:50:20 +1100416 && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) {
Damien George96fd80d2017-09-21 15:24:57 +1000417 used_emg_buf = true;
418 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
Damien Georgebad4e152018-12-08 01:50:20 +1100419 + EMG_BUF_STR_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000420 o_str_buf = (byte*)&o_str[1];
421 o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
422 + mp_emergency_exception_buf_size - o_str_buf;
423 }
424 #endif
425
426 if (o_str == NULL) {
427 // No memory for the string object so create the exception with no args
428 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
429 }
430
431 if (o_str_buf == NULL) {
432 // No memory for the string buffer: assume that the fmt string is in ROM
433 // and use that data as the data of the string
434 o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
435 o_str->data = (const byte*)fmt;
436 } else {
437 // We have some memory to format the string
438 struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
439 mp_print_t print = {&exc_pr, exc_add_strn};
Damien Georgead7213d2020-02-11 11:48:28 +1100440 mp_vprintf(&print, fmt, args);
Damien George96fd80d2017-09-21 15:24:57 +1000441 exc_pr.buf[exc_pr.len] = '\0';
442 o_str->len = exc_pr.len;
443 o_str->data = exc_pr.buf;
444 }
445
446 // Create the string object and call mp_obj_exception_make_new to create the exception
447 o_str->base.type = &mp_type_str;
448 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
449 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
450 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damien George6c73ca12014-01-08 18:11:23 +0000451}
452
Damien Georgec5966122014-02-15 16:10:44 +0000453// return true if the given object is an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000454bool mp_obj_is_exception_type(mp_obj_t self_in) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100455 if (mp_obj_is_type(self_in, &mp_type_type)) {
Damien George9e6e9352014-03-26 18:37:06 +0000456 // optimisation when self_in is a builtin exception
Damien George999cedb2015-11-27 17:01:44 +0000457 mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
Damien George9e6e9352014-03-26 18:37:06 +0000458 if (self->make_new == mp_obj_exception_make_new) {
459 return true;
460 }
Damien Georgec5966122014-02-15 16:10:44 +0000461 }
Damien George999cedb2015-11-27 17:01:44 +0000462 return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
Damien Georgec5966122014-02-15 16:10:44 +0000463}
464
465// return true if the given object is an instance of an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000466bool mp_obj_is_exception_instance(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000467 return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
Damien Georgec5966122014-02-15 16:10:44 +0000468}
469
Damien George4bcd04b2014-09-24 14:05:40 +0100470// Return true if exception (type or instance) is a subclass of given
471// exception type. Assumes exc_type is a subclass of BaseException, as
472// defined by mp_obj_is_exception_type(exc_type).
473bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
474 // if exc is an instance of an exception, then extract and use its type
475 if (mp_obj_is_exception_instance(exc)) {
Damien George999cedb2015-11-27 17:01:44 +0000476 exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
Damien George4bcd04b2014-09-24 14:05:40 +0100477 }
478 return mp_obj_is_subclass_fast(exc, exc_type);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200479}
480
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300481// traceback handling functions
Damien Georgec5966122014-02-15 16:10:44 +0000482
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300483#define GET_NATIVE_EXCEPTION(self, self_in) \
484 /* make sure self_in is an exception instance */ \
485 assert(mp_obj_is_exception_instance(self_in)); \
486 mp_obj_exception_t *self; \
487 if (mp_obj_is_native_exception_instance(self_in)) { \
Damien George999cedb2015-11-27 17:01:44 +0000488 self = MP_OBJ_TO_PTR(self_in); \
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300489 } else { \
Damien George999cedb2015-11-27 17:01:44 +0000490 self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
Damien George9e6e9352014-03-26 18:37:06 +0000491 }
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300492
493void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
494 GET_NATIVE_EXCEPTION(self, self_in);
495 // just set the traceback to the null object
496 // we don't want to call any memory management functions here
Damien George4852e092015-02-27 00:36:39 +0000497 self->traceback_data = NULL;
Damienb86e3f92013-12-29 17:17:43 +0000498}
Damien George08335002014-01-18 23:24:36 +0000499
Damien George3d2daa22016-01-02 22:04:12 +0000500void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
Dave Hylands5b7fd202014-07-01 23:46:53 -0700501 GET_NATIVE_EXCEPTION(self, self_in);
502
Damien George4852e092015-02-27 00:36:39 +0000503 // append this traceback info to traceback data
504 // if memory allocation fails (eg because gc is locked), just return
Damien Georgef0b29722014-07-01 14:28:09 +0100505
Damien George4852e092015-02-27 00:36:39 +0000506 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000507 self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
Damien George4852e092015-02-27 00:36:39 +0000508 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000509 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
Damien Georgebad4e152018-12-08 01:50:20 +1100510 if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) {
Damien George96fd80d2017-09-21 15:24:57 +1000511 // There is room in the emergency buffer for traceback data
Damien Georgebad4e152018-12-08 01:50:20 +1100512 size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
513 + EMG_BUF_TRACEBACK_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000514 self->traceback_data = tb;
Damien Georgebad4e152018-12-08 01:50:20 +1100515 self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t);
Damien George96fd80d2017-09-21 15:24:57 +1000516 } else {
517 // Can't allocate and no room in emergency buffer
518 return;
519 }
520 #else
521 // Can't allocate
522 return;
523 #endif
524 } else {
525 // Allocated the traceback data on the heap
526 self->traceback_alloc = TRACEBACK_ENTRY_LEN;
527 }
528 self->traceback_len = 0;
529 } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
530 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
531 if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
532 // Can't resize the emergency buffer
Paul Sokolovskyfa3b8952015-02-15 22:24:03 +0300533 return;
534 }
Damien George96fd80d2017-09-21 15:24:57 +1000535 #endif
Damien George4852e092015-02-27 00:36:39 +0000536 // be conservative with growing traceback data
Damien George96fd80d2017-09-21 15:24:57 +1000537 size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
538 self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
Damien George4852e092015-02-27 00:36:39 +0000539 if (tb_data == NULL) {
540 return;
541 }
542 self->traceback_data = tb_data;
Damien George96fd80d2017-09-21 15:24:57 +1000543 self->traceback_alloc += TRACEBACK_ENTRY_LEN;
Damien George08335002014-01-18 23:24:36 +0000544 }
Damien George4852e092015-02-27 00:36:39 +0000545
Damien George3d2daa22016-01-02 22:04:12 +0000546 size_t *tb_data = &self->traceback_data[self->traceback_len];
Damien George96fd80d2017-09-21 15:24:57 +1000547 self->traceback_len += TRACEBACK_ENTRY_LEN;
Damien George3d2daa22016-01-02 22:04:12 +0000548 tb_data[0] = file;
549 tb_data[1] = line;
550 tb_data[2] = block;
Damien George08335002014-01-18 23:24:36 +0000551}
552
Damien George3d2daa22016-01-02 22:04:12 +0000553void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300554 GET_NATIVE_EXCEPTION(self, self_in);
Damien Georgec5966122014-02-15 16:10:44 +0000555
Damien George4852e092015-02-27 00:36:39 +0000556 if (self->traceback_data == NULL) {
Damien George136b1492014-01-19 12:38:49 +0000557 *n = 0;
558 *values = NULL;
559 } else {
Damien George4852e092015-02-27 00:36:39 +0000560 *n = self->traceback_len;
561 *values = self->traceback_data;
Damien George136b1492014-01-19 12:38:49 +0000562 }
Damien George08335002014-01-18 23:24:36 +0000563}