blob: 30592fd560f4340f3e35075dec60ac0e2172526b [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
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000227// List of all exceptions, arranged as in the table at:
Chris Angelicodaf973a2014-06-06 03:51:03 +1000228// http://docs.python.org/3/library/exceptions.html
Damien George7a4ddd22014-05-24 23:32:19 +0100229MP_DEFINE_EXCEPTION(SystemExit, BaseException)
Damien George124df6f2014-10-25 18:19:55 +0100230MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000231MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
232MP_DEFINE_EXCEPTION(Exception, BaseException)
pohmelie81ebba72016-01-27 23:23:11 +0300233 #if MICROPY_PY_ASYNC_AWAIT
234 MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
235 #endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000236 MP_DEFINE_EXCEPTION(StopIteration, Exception)
237 MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000238 //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000239 MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
240 MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
241 MP_DEFINE_EXCEPTION(AssertionError, Exception)
242 MP_DEFINE_EXCEPTION(AttributeError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000243 //MP_DEFINE_EXCEPTION(BufferError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000244 MP_DEFINE_EXCEPTION(EOFError, Exception)
245 MP_DEFINE_EXCEPTION(ImportError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000246 MP_DEFINE_EXCEPTION(LookupError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000247 MP_DEFINE_EXCEPTION(IndexError, LookupError)
248 MP_DEFINE_EXCEPTION(KeyError, LookupError)
249 MP_DEFINE_EXCEPTION(MemoryError, Exception)
250 MP_DEFINE_EXCEPTION(NameError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000251 /*
Antonin ENFRUNda1fffa2014-05-12 00:21:50 +0200252 MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
253 */
254 MP_DEFINE_EXCEPTION(OSError, Exception)
Daniel Campora077812b2015-06-29 22:45:39 +0200255#if MICROPY_PY_BUILTINS_TIMEOUTERROR
Daniel Campora077812b2015-06-29 22:45:39 +0200256 MP_DEFINE_EXCEPTION(TimeoutError, OSError)
257#endif
258 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000259 MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000260 MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
261 MP_DEFINE_EXCEPTION(ConnectionError, OSError)
262 MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
263 MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
264 MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
265 MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000266 MP_DEFINE_EXCEPTION(InterruptedError, OSError)
267 MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
268 MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
269 MP_DEFINE_EXCEPTION(PermissionError, OSError)
270 MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
Damien Georgec9109722014-03-22 23:40:02 +0000271 MP_DEFINE_EXCEPTION(FileExistsError, OSError)
272 MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
Damien Georgec63f9842014-03-27 23:49:06 +0000273 MP_DEFINE_EXCEPTION(ReferenceError, Exception)
274 */
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000275 MP_DEFINE_EXCEPTION(RuntimeError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000276 MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
277 MP_DEFINE_EXCEPTION(SyntaxError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000278 MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
Damien Georgec63f9842014-03-27 23:49:06 +0000279 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000280 MP_DEFINE_EXCEPTION(TabError, IndentationError)
281 */
Damien Georgee7a47822014-10-22 19:42:55 +0100282 //MP_DEFINE_EXCEPTION(SystemError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000283 MP_DEFINE_EXCEPTION(TypeError, Exception)
Damien Georgec8b60f02015-04-20 13:29:31 +0000284#if MICROPY_EMIT_NATIVE
Damien Georgec8b60f02015-04-20 13:29:31 +0000285 MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
286#endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000287 MP_DEFINE_EXCEPTION(ValueError, Exception)
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200288#if MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200289 MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
290 //TODO: Implement more UnicodeError subclasses which take arguments
291#endif
Damien Georgec9109722014-03-22 23:40:02 +0000292 /*
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000293 MP_DEFINE_EXCEPTION(Warning, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000294 MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
295 MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
296 MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
297 MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
298 MP_DEFINE_EXCEPTION(UserWarning, Warning)
299 MP_DEFINE_EXCEPTION(FutureWarning, Warning)
300 MP_DEFINE_EXCEPTION(ImportWarning, Warning)
301 MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
302 MP_DEFINE_EXCEPTION(BytesWarning, Warning)
303 MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
Damien Georgec9109722014-03-22 23:40:02 +0000304 */
Damien Georgec5966122014-02-15 16:10:44 +0000305
306mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
Damien Georgee2c12262020-01-23 13:03:00 +1100307 assert(exc_type->make_new == mp_obj_exception_make_new);
308 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
Damiend99b0522013-12-21 18:17:45 +0000309}
310
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300311// "Optimized" version for common(?) case of having 1 exception arg
312mp_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 +1100313 assert(exc_type->make_new == mp_obj_exception_make_new);
314 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300315}
316
Damien Georgefa5a5912017-02-16 16:38:14 +1100317mp_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 +0200318 assert(exc_type->make_new == mp_obj_exception_make_new);
Damien Georgee2c12262020-01-23 13:03:00 +1100319 return mp_obj_exception_make_new(exc_type, n_args, 0, args);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200320}
321
Damien Georgec5966122014-02-15 16:10:44 +0000322mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg) {
Damien George55830dd2018-12-10 15:57:03 +1100323 // Check that the given type is an exception type
324 assert(exc_type->make_new == mp_obj_exception_make_new);
325
326 // Try to allocate memory for the message
327 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
328
329 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
330 // If memory allocation failed and there is an emergency buffer then try to use
331 // that buffer to store the string object, reserving room at the start for the
332 // traceback and 1-tuple.
333 if (o_str == NULL
334 && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t)) {
335 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
336 + EMG_BUF_STR_OFFSET);
337 }
338 #endif
339
340 if (o_str == NULL) {
341 // No memory for the string object so create the exception with no args
342 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
343 }
344
345 // Create the string object and call mp_obj_exception_make_new to create the exception
346 o_str->base.type = &mp_type_str;
Damien George55830dd2018-12-10 15:57:03 +1100347 o_str->len = strlen(msg);
348 o_str->data = (const byte*)msg;
Tom Collins2d644ac2019-03-01 19:57:07 -0500349 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
Damien George55830dd2018-12-10 15:57:03 +1100350 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
351 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000352}
353
Damien George96fd80d2017-09-21 15:24:57 +1000354// The following struct and function implement a simple printer that conservatively
355// allocates memory and truncates the output data if no more memory can be obtained.
356// It leaves room for a null byte at the end of the buffer.
Damien Georgec5966122014-02-15 16:10:44 +0000357
Damien George96fd80d2017-09-21 15:24:57 +1000358struct _exc_printer_t {
359 bool allow_realloc;
360 size_t alloc;
361 size_t len;
362 byte *buf;
363};
Dave Hylands5b7fd202014-07-01 23:46:53 -0700364
Damien George96fd80d2017-09-21 15:24:57 +1000365STATIC void exc_add_strn(void *data, const char *str, size_t len) {
366 struct _exc_printer_t *pr = data;
367 if (pr->len + len >= pr->alloc) {
368 // Not enough room for data plus a null byte so try to grow the buffer
369 if (pr->allow_realloc) {
370 size_t new_alloc = pr->alloc + len + 16;
371 byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
372 if (new_buf == NULL) {
373 pr->allow_realloc = false;
374 len = pr->alloc - pr->len - 1;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300375 } else {
Damien George96fd80d2017-09-21 15:24:57 +1000376 pr->alloc = new_alloc;
377 pr->buf = new_buf;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300378 }
Damien George96fd80d2017-09-21 15:24:57 +1000379 } else {
380 len = pr->alloc - pr->len - 1;
Damien Georgef0954e32014-04-10 14:38:25 +0100381 }
Damien George6c73ca12014-01-08 18:11:23 +0000382 }
Damien George96fd80d2017-09-21 15:24:57 +1000383 memcpy(pr->buf + pr->len, str, len);
384 pr->len += len;
385}
Damien George6c73ca12014-01-08 18:11:23 +0000386
Damien George96fd80d2017-09-21 15:24:57 +1000387mp_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 +1100388 va_list args;
389 va_start(args, fmt);
390 mp_obj_t exc = mp_obj_new_exception_msg_varg2(exc_type, fmt, args);
391 va_end(args);
392 return exc;
393}
394
395mp_obj_t mp_obj_new_exception_msg_varg2(const mp_obj_type_t *exc_type, const char *fmt, va_list args) {
Damien George96fd80d2017-09-21 15:24:57 +1000396 assert(fmt != NULL);
397
398 // Check that the given type is an exception type
399 assert(exc_type->make_new == mp_obj_exception_make_new);
400
401 // Try to allocate memory for the message
402 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
403 size_t o_str_alloc = strlen(fmt) + 1;
404 byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
405
406 bool used_emg_buf = false;
407 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
408 // If memory allocation failed and there is an emergency buffer then try to use
409 // that buffer to store the string object and its data (at least 16 bytes for
410 // the string data), reserving room at the start for the traceback and 1-tuple.
411 if ((o_str == NULL || o_str_buf == NULL)
Damien Georgebad4e152018-12-08 01:50:20 +1100412 && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) {
Damien George96fd80d2017-09-21 15:24:57 +1000413 used_emg_buf = true;
414 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
Damien Georgebad4e152018-12-08 01:50:20 +1100415 + EMG_BUF_STR_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000416 o_str_buf = (byte*)&o_str[1];
417 o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
418 + mp_emergency_exception_buf_size - o_str_buf;
419 }
420 #endif
421
422 if (o_str == NULL) {
423 // No memory for the string object so create the exception with no args
424 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
425 }
426
427 if (o_str_buf == NULL) {
428 // No memory for the string buffer: assume that the fmt string is in ROM
429 // and use that data as the data of the string
430 o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
431 o_str->data = (const byte*)fmt;
432 } else {
433 // We have some memory to format the string
434 struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
435 mp_print_t print = {&exc_pr, exc_add_strn};
Damien Georgead7213d2020-02-11 11:48:28 +1100436 mp_vprintf(&print, fmt, args);
Damien George96fd80d2017-09-21 15:24:57 +1000437 exc_pr.buf[exc_pr.len] = '\0';
438 o_str->len = exc_pr.len;
439 o_str->data = exc_pr.buf;
440 }
441
442 // Create the string object and call mp_obj_exception_make_new to create the exception
443 o_str->base.type = &mp_type_str;
444 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
445 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
446 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damien George6c73ca12014-01-08 18:11:23 +0000447}
448
Damien Georgec5966122014-02-15 16:10:44 +0000449// return true if the given object is an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000450bool mp_obj_is_exception_type(mp_obj_t self_in) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100451 if (mp_obj_is_type(self_in, &mp_type_type)) {
Damien George9e6e9352014-03-26 18:37:06 +0000452 // optimisation when self_in is a builtin exception
Damien George999cedb2015-11-27 17:01:44 +0000453 mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
Damien George9e6e9352014-03-26 18:37:06 +0000454 if (self->make_new == mp_obj_exception_make_new) {
455 return true;
456 }
Damien Georgec5966122014-02-15 16:10:44 +0000457 }
Damien George999cedb2015-11-27 17:01:44 +0000458 return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
Damien Georgec5966122014-02-15 16:10:44 +0000459}
460
461// return true if the given object is an instance of an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000462bool mp_obj_is_exception_instance(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000463 return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
Damien Georgec5966122014-02-15 16:10:44 +0000464}
465
Damien George4bcd04b2014-09-24 14:05:40 +0100466// Return true if exception (type or instance) is a subclass of given
467// exception type. Assumes exc_type is a subclass of BaseException, as
468// defined by mp_obj_is_exception_type(exc_type).
469bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
470 // if exc is an instance of an exception, then extract and use its type
471 if (mp_obj_is_exception_instance(exc)) {
Damien George999cedb2015-11-27 17:01:44 +0000472 exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
Damien George4bcd04b2014-09-24 14:05:40 +0100473 }
474 return mp_obj_is_subclass_fast(exc, exc_type);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200475}
476
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300477// traceback handling functions
Damien Georgec5966122014-02-15 16:10:44 +0000478
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300479#define GET_NATIVE_EXCEPTION(self, self_in) \
480 /* make sure self_in is an exception instance */ \
481 assert(mp_obj_is_exception_instance(self_in)); \
482 mp_obj_exception_t *self; \
483 if (mp_obj_is_native_exception_instance(self_in)) { \
Damien George999cedb2015-11-27 17:01:44 +0000484 self = MP_OBJ_TO_PTR(self_in); \
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300485 } else { \
Damien George999cedb2015-11-27 17:01:44 +0000486 self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
Damien George9e6e9352014-03-26 18:37:06 +0000487 }
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300488
489void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
490 GET_NATIVE_EXCEPTION(self, self_in);
491 // just set the traceback to the null object
492 // we don't want to call any memory management functions here
Damien George4852e092015-02-27 00:36:39 +0000493 self->traceback_data = NULL;
Damienb86e3f92013-12-29 17:17:43 +0000494}
Damien George08335002014-01-18 23:24:36 +0000495
Damien George3d2daa22016-01-02 22:04:12 +0000496void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
Dave Hylands5b7fd202014-07-01 23:46:53 -0700497 GET_NATIVE_EXCEPTION(self, self_in);
498
Damien George4852e092015-02-27 00:36:39 +0000499 // append this traceback info to traceback data
500 // if memory allocation fails (eg because gc is locked), just return
Damien Georgef0b29722014-07-01 14:28:09 +0100501
Damien George4852e092015-02-27 00:36:39 +0000502 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000503 self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
Damien George4852e092015-02-27 00:36:39 +0000504 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000505 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
Damien Georgebad4e152018-12-08 01:50:20 +1100506 if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) {
Damien George96fd80d2017-09-21 15:24:57 +1000507 // There is room in the emergency buffer for traceback data
Damien Georgebad4e152018-12-08 01:50:20 +1100508 size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
509 + EMG_BUF_TRACEBACK_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000510 self->traceback_data = tb;
Damien Georgebad4e152018-12-08 01:50:20 +1100511 self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t);
Damien George96fd80d2017-09-21 15:24:57 +1000512 } else {
513 // Can't allocate and no room in emergency buffer
514 return;
515 }
516 #else
517 // Can't allocate
518 return;
519 #endif
520 } else {
521 // Allocated the traceback data on the heap
522 self->traceback_alloc = TRACEBACK_ENTRY_LEN;
523 }
524 self->traceback_len = 0;
525 } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
526 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
527 if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
528 // Can't resize the emergency buffer
Paul Sokolovskyfa3b8952015-02-15 22:24:03 +0300529 return;
530 }
Damien George96fd80d2017-09-21 15:24:57 +1000531 #endif
Damien George4852e092015-02-27 00:36:39 +0000532 // be conservative with growing traceback data
Damien George96fd80d2017-09-21 15:24:57 +1000533 size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
534 self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
Damien George4852e092015-02-27 00:36:39 +0000535 if (tb_data == NULL) {
536 return;
537 }
538 self->traceback_data = tb_data;
Damien George96fd80d2017-09-21 15:24:57 +1000539 self->traceback_alloc += TRACEBACK_ENTRY_LEN;
Damien George08335002014-01-18 23:24:36 +0000540 }
Damien George4852e092015-02-27 00:36:39 +0000541
Damien George3d2daa22016-01-02 22:04:12 +0000542 size_t *tb_data = &self->traceback_data[self->traceback_len];
Damien George96fd80d2017-09-21 15:24:57 +1000543 self->traceback_len += TRACEBACK_ENTRY_LEN;
Damien George3d2daa22016-01-02 22:04:12 +0000544 tb_data[0] = file;
545 tb_data[1] = line;
546 tb_data[2] = block;
Damien George08335002014-01-18 23:24:36 +0000547}
548
Damien George3d2daa22016-01-02 22:04:12 +0000549void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300550 GET_NATIVE_EXCEPTION(self, self_in);
Damien Georgec5966122014-02-15 16:10:44 +0000551
Damien George4852e092015-02-27 00:36:39 +0000552 if (self->traceback_data == NULL) {
Damien George136b1492014-01-19 12:38:49 +0000553 *n = 0;
554 *values = NULL;
555 } else {
Damien George4852e092015-02-27 00:36:39 +0000556 *n = self->traceback_len;
557 *values = self->traceback_data;
Damien George136b1492014-01-19 12:38:49 +0000558 }
Damien George08335002014-01-18 23:24:36 +0000559}