blob: 059caa7ae08886085210169c477db954bdebeff6 [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
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damiend99b0522013-12-21 18:17:45 +000027#include <string.h>
Damien George6c73ca12014-01-08 18:11:23 +000028#include <stdarg.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <assert.h>
Dave Hylands5b7fd202014-07-01 23:46:53 -070030#include <stdio.h>
Damiend99b0522013-12-21 18:17:45 +000031
Damien George51dfcb42015-01-01 20:27:54 +000032#include "py/objlist.h"
33#include "py/objstr.h"
34#include "py/objtuple.h"
35#include "py/objtype.h"
Damien George50149a52015-01-20 14:11:27 +000036#include "py/runtime.h"
Damien George51dfcb42015-01-01 20:27:54 +000037#include "py/gc.h"
Damien Georged45e5f82016-05-12 13:20:40 +010038#include "py/mperrno.h"
Damiend99b0522013-12-21 18:17:45 +000039
Damien George96fd80d2017-09-21 15:24:57 +100040// Number of items per traceback entry (file, line, block)
41#define TRACEBACK_ENTRY_LEN (3)
42
Damien Georgebad4e152018-12-08 01:50:20 +110043// Optionally allocated buffer for storing some traceback, the tuple argument,
44// and possible string object and data, for when the heap is locked.
Dave Hylands5b7fd202014-07-01 23:46:53 -070045#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
Damien Georgebad4e152018-12-08 01:50:20 +110046
47// When used the layout of the emergency exception buffer is:
48// - traceback entry (file, line, block)
49// - traceback entry (file, line, block)
50// - mp_obj_tuple_t object
51// - n_args * mp_obj_t for tuple
52// - mp_obj_str_t object
53// - string data
54#define EMG_BUF_TRACEBACK_OFFSET (0)
55#define EMG_BUF_TRACEBACK_SIZE (2 * TRACEBACK_ENTRY_LEN * sizeof(size_t))
56#define EMG_BUF_TUPLE_OFFSET (EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE)
57#define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t))
58#define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1))
59
Dave Hylands5b7fd202014-07-01 23:46:53 -070060# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
Dave Hylands5b7fd202014-07-01 23:46:53 -070061#define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
62
63void mp_init_emergency_exception_buf(void) {
64 // Nothing to do since the buffer was declared statically. We put this
65 // definition here so that the calling code can call this function
66 // regardless of how its configured (makes the calling code a bit cleaner).
67}
68
69#else
Damien Georgeb4b10fd2015-01-01 23:30:53 +000070#define mp_emergency_exception_buf_size MP_STATE_VM(mp_emergency_exception_buf_size)
Dave Hylands5b7fd202014-07-01 23:46:53 -070071
72void mp_init_emergency_exception_buf(void) {
73 mp_emergency_exception_buf_size = 0;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000074 MP_STATE_VM(mp_emergency_exception_buf) = NULL;
Dave Hylands5b7fd202014-07-01 23:46:53 -070075}
76
77mp_obj_t mp_alloc_emergency_exception_buf(mp_obj_t size_in) {
78 mp_int_t size = mp_obj_get_int(size_in);
79 void *buf = NULL;
80 if (size > 0) {
Damien George4d77e1a2015-02-27 09:34:51 +000081 buf = m_new(byte, size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070082 }
83
84 int old_size = mp_emergency_exception_buf_size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000085 void *old_buf = MP_STATE_VM(mp_emergency_exception_buf);
Dave Hylands5b7fd202014-07-01 23:46:53 -070086
87 // Update the 2 variables atomically so that an interrupt can't occur
88 // between the assignments.
Damien George4859edb2014-10-15 17:33:24 +000089 mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
Dave Hylands5b7fd202014-07-01 23:46:53 -070090 mp_emergency_exception_buf_size = size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000091 MP_STATE_VM(mp_emergency_exception_buf) = buf;
Damien George4859edb2014-10-15 17:33:24 +000092 MICROPY_END_ATOMIC_SECTION(atomic_state);
Dave Hylands5b7fd202014-07-01 23:46:53 -070093
94 if (old_buf != NULL) {
Damien George4d77e1a2015-02-27 09:34:51 +000095 m_del(byte, old_buf, old_size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070096 }
97 return mp_const_none;
98}
99#endif
100#endif // MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
101
Paul Sokolovskyc4d589e2014-03-28 02:37:28 +0200102// Instance of GeneratorExit exception - needed by generator.close()
103// This would belong to objgenerator.c, but to keep mp_obj_exception_t
104// definition module-private so far, have it here.
Damien George999cedb2015-11-27 17:01:44 +0000105const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
Paul Sokolovskyc4d589e2014-03-28 02:37:28 +0200106
Damien George5edce452018-03-17 00:31:40 +1100107void 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 +0000108 mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in);
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300109 mp_print_kind_t k = kind & ~PRINT_EXC_SUBCLASS;
110 bool is_subclass = kind & PRINT_EXC_SUBCLASS;
111 if (!is_subclass && (k == PRINT_REPR || k == PRINT_EXC)) {
Damien George044c4732015-04-11 13:03:37 +0100112 mp_print_str(print, qstr_str(o->base.type->name));
Damiend99b0522013-12-21 18:17:45 +0000113 }
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300114
115 if (k == PRINT_EXC) {
Damien George7f9d1d62015-04-09 23:56:15 +0100116 mp_print_str(print, ": ");
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300117 }
118
119 if (k == PRINT_STR || k == PRINT_EXC) {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300120 if (o->args == NULL || o->args->len == 0) {
Damien George7f9d1d62015-04-09 23:56:15 +0100121 mp_print_str(print, "");
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300122 return;
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300123 } else if (o->args->len == 1) {
Damien George9a924992016-05-12 14:27:52 +0100124 #if MICROPY_PY_UERRNO
125 // try to provide a nice OSError error message
126 if (o->base.type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(o->args->items[0])) {
127 qstr qst = mp_errno_to_str(o->args->items[0]);
128 if (qst != MP_QSTR_NULL) {
Damien George9c027072017-12-11 22:38:30 +1100129 mp_printf(print, "[Errno " INT_FMT "] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst);
Damien George9a924992016-05-12 14:27:52 +0100130 return;
131 }
132 }
133 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100134 mp_obj_print_helper(print, o->args->items[0], PRINT_STR);
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300135 return;
136 }
137 }
Damien George999cedb2015-11-27 17:01:44 +0000138 mp_obj_tuple_print(print, MP_OBJ_FROM_PTR(o->args), kind);
Damiend99b0522013-12-21 18:17:45 +0000139}
140
Damien George5b3f0b72016-01-03 15:55:55 +0000141mp_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 +0000142 mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
Damien George96fd80d2017-09-21 15:24:57 +1000143
144 // Try to allocate memory for the exception, with fallback to emergency exception object
145 mp_obj_exception_t *o_exc = m_new_obj_maybe(mp_obj_exception_t);
146 if (o_exc == NULL) {
147 o_exc = &MP_STATE_VM(mp_emergency_exception_obj);
Damien Georgef0954e32014-04-10 14:38:25 +0100148 }
Damien George96fd80d2017-09-21 15:24:57 +1000149
150 // Populate the exception object
151 o_exc->base.type = type;
152 o_exc->traceback_data = NULL;
153
154 mp_obj_tuple_t *o_tuple;
155 if (n_args == 0) {
156 // No args, can use the empty tuple straightaway
157 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
158 } else {
159 // Try to allocate memory for the tuple containing the args
160 o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args);
161
162 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
163 // If we are called by mp_obj_new_exception_msg_varg then it will have
164 // reserved room (after the traceback data) for a tuple with 1 element.
165 // Otherwise we are free to use the whole buffer after the traceback data.
166 if (o_tuple == NULL && mp_emergency_exception_buf_size >=
Damien Georgebad4e152018-12-08 01:50:20 +1100167 EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) {
Damien George96fd80d2017-09-21 15:24:57 +1000168 o_tuple = (mp_obj_tuple_t*)
Damien Georgebad4e152018-12-08 01:50:20 +1100169 ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000170 }
171 #endif
172
173 if (o_tuple == NULL) {
174 // No memory for a tuple, fallback to an empty tuple
175 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
176 } else {
177 // Have memory for a tuple so populate it
178 o_tuple->base.type = &mp_type_tuple;
179 o_tuple->len = n_args;
180 memcpy(o_tuple->items, args, n_args * sizeof(mp_obj_t));
181 }
182 }
183
184 // Store the tuple of args in the exception object
185 o_exc->args = o_tuple;
186
187 return MP_OBJ_FROM_PTR(o_exc);
Paul Sokolovskyddf21782014-01-12 23:30:20 +0200188}
189
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200190// Get exception "value" - that is, first argument, or None
191mp_obj_t mp_obj_exception_get_value(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000192 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300193 if (self->args->len == 0) {
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200194 return mp_const_none;
195 } else {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300196 return self->args->items[0];
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200197 }
198}
199
Damien George5edce452018-03-17 00:31:40 +1100200void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300201 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb1bbe962015-04-01 14:10:50 +0000202 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300203 // store/delete attribute
204 if (attr == MP_QSTR___traceback__ && dest[1] == mp_const_none) {
205 // We allow 'exc.__traceback__ = None' assignment as low-level
206 // optimization of pre-allocating exception instance and raising
207 // it repeatedly - this avoids memory allocation during raise.
208 // However, uPy will keep adding traceback entries to such
209 // exception instance, so before throwing it, traceback should
210 // be cleared like above.
211 self->traceback_len = 0;
212 dest[0] = MP_OBJ_NULL; // indicate success
213 }
Damien Georgeb1bbe962015-04-01 14:10:50 +0000214 return;
215 }
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200216 if (attr == MP_QSTR_args) {
Damien George999cedb2015-11-27 17:01:44 +0000217 dest[0] = MP_OBJ_FROM_PTR(self->args);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200218 } else if (self->base.type == &mp_type_StopIteration && attr == MP_QSTR_value) {
Damien George999cedb2015-11-27 17:01:44 +0000219 dest[0] = mp_obj_exception_get_value(self_in);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200220 }
221}
222
Damien Georgec5966122014-02-15 16:10:44 +0000223const mp_obj_type_t mp_type_BaseException = {
224 { &mp_type_type },
225 .name = MP_QSTR_BaseException,
226 .print = mp_obj_exception_print,
227 .make_new = mp_obj_exception_make_new,
Damien George5edce452018-03-17 00:31:40 +1100228 .attr = mp_obj_exception_attr,
Damien Georgec5966122014-02-15 16:10:44 +0000229};
230
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000231// List of all exceptions, arranged as in the table at:
Chris Angelicodaf973a2014-06-06 03:51:03 +1000232// http://docs.python.org/3/library/exceptions.html
Damien George7a4ddd22014-05-24 23:32:19 +0100233MP_DEFINE_EXCEPTION(SystemExit, BaseException)
Damien George124df6f2014-10-25 18:19:55 +0100234MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000235MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
236MP_DEFINE_EXCEPTION(Exception, BaseException)
pohmelie81ebba72016-01-27 23:23:11 +0300237 #if MICROPY_PY_ASYNC_AWAIT
238 MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
239 #endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000240 MP_DEFINE_EXCEPTION(StopIteration, Exception)
241 MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000242 //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000243 MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
244 MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
245 MP_DEFINE_EXCEPTION(AssertionError, Exception)
246 MP_DEFINE_EXCEPTION(AttributeError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000247 //MP_DEFINE_EXCEPTION(BufferError, Exception)
Damien George8b03d942014-09-30 13:59:30 +0000248 //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000249 MP_DEFINE_EXCEPTION(EOFError, Exception)
250 MP_DEFINE_EXCEPTION(ImportError, Exception)
Damien George8b03d942014-09-30 13:59:30 +0000251 //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000252 MP_DEFINE_EXCEPTION(LookupError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000253 MP_DEFINE_EXCEPTION(IndexError, LookupError)
254 MP_DEFINE_EXCEPTION(KeyError, LookupError)
255 MP_DEFINE_EXCEPTION(MemoryError, Exception)
256 MP_DEFINE_EXCEPTION(NameError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000257 /*
Antonin ENFRUNda1fffa2014-05-12 00:21:50 +0200258 MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
259 */
260 MP_DEFINE_EXCEPTION(OSError, Exception)
Daniel Campora077812b2015-06-29 22:45:39 +0200261#if MICROPY_PY_BUILTINS_TIMEOUTERROR
Daniel Campora077812b2015-06-29 22:45:39 +0200262 MP_DEFINE_EXCEPTION(TimeoutError, OSError)
263#endif
264 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000265 MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000266 MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
267 MP_DEFINE_EXCEPTION(ConnectionError, OSError)
268 MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
269 MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
270 MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
271 MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000272 MP_DEFINE_EXCEPTION(InterruptedError, OSError)
273 MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
274 MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
275 MP_DEFINE_EXCEPTION(PermissionError, OSError)
276 MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
Damien Georgec9109722014-03-22 23:40:02 +0000277 MP_DEFINE_EXCEPTION(FileExistsError, OSError)
278 MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
Damien Georgec63f9842014-03-27 23:49:06 +0000279 MP_DEFINE_EXCEPTION(ReferenceError, Exception)
280 */
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000281 MP_DEFINE_EXCEPTION(RuntimeError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000282 MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
283 MP_DEFINE_EXCEPTION(SyntaxError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000284 MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
Damien Georgec63f9842014-03-27 23:49:06 +0000285 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000286 MP_DEFINE_EXCEPTION(TabError, IndentationError)
287 */
Damien Georgee7a47822014-10-22 19:42:55 +0100288 //MP_DEFINE_EXCEPTION(SystemError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000289 MP_DEFINE_EXCEPTION(TypeError, Exception)
Damien Georgec8b60f02015-04-20 13:29:31 +0000290#if MICROPY_EMIT_NATIVE
Damien Georgec8b60f02015-04-20 13:29:31 +0000291 MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
292#endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000293 MP_DEFINE_EXCEPTION(ValueError, Exception)
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200294#if MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200295 MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
296 //TODO: Implement more UnicodeError subclasses which take arguments
297#endif
Damien Georgec9109722014-03-22 23:40:02 +0000298 /*
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000299 MP_DEFINE_EXCEPTION(Warning, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000300 MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
301 MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
302 MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
303 MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
304 MP_DEFINE_EXCEPTION(UserWarning, Warning)
305 MP_DEFINE_EXCEPTION(FutureWarning, Warning)
306 MP_DEFINE_EXCEPTION(ImportWarning, Warning)
307 MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
308 MP_DEFINE_EXCEPTION(BytesWarning, Warning)
309 MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
Damien Georgec9109722014-03-22 23:40:02 +0000310 */
Damien Georgec5966122014-02-15 16:10:44 +0000311
312mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300313 return mp_obj_new_exception_args(exc_type, 0, NULL);
Damiend99b0522013-12-21 18:17:45 +0000314}
315
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300316// "Optimized" version for common(?) case of having 1 exception arg
317mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
318 return mp_obj_new_exception_args(exc_type, 1, &arg);
319}
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 George5b3f0b72016-01-03 15:55:55 +0000323 return exc_type->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) {
327 return mp_obj_new_exception_msg_varg(exc_type, msg);
Damiend99b0522013-12-21 18:17:45 +0000328}
329
Damien George96fd80d2017-09-21 15:24:57 +1000330// The following struct and function implement a simple printer that conservatively
331// allocates memory and truncates the output data if no more memory can be obtained.
332// It leaves room for a null byte at the end of the buffer.
Damien Georgec5966122014-02-15 16:10:44 +0000333
Damien George96fd80d2017-09-21 15:24:57 +1000334struct _exc_printer_t {
335 bool allow_realloc;
336 size_t alloc;
337 size_t len;
338 byte *buf;
339};
Dave Hylands5b7fd202014-07-01 23:46:53 -0700340
Damien George96fd80d2017-09-21 15:24:57 +1000341STATIC void exc_add_strn(void *data, const char *str, size_t len) {
342 struct _exc_printer_t *pr = data;
343 if (pr->len + len >= pr->alloc) {
344 // Not enough room for data plus a null byte so try to grow the buffer
345 if (pr->allow_realloc) {
346 size_t new_alloc = pr->alloc + len + 16;
347 byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
348 if (new_buf == NULL) {
349 pr->allow_realloc = false;
350 len = pr->alloc - pr->len - 1;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300351 } else {
Damien George96fd80d2017-09-21 15:24:57 +1000352 pr->alloc = new_alloc;
353 pr->buf = new_buf;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300354 }
Damien George96fd80d2017-09-21 15:24:57 +1000355 } else {
356 len = pr->alloc - pr->len - 1;
Damien Georgef0954e32014-04-10 14:38:25 +0100357 }
Damien George6c73ca12014-01-08 18:11:23 +0000358 }
Damien George96fd80d2017-09-21 15:24:57 +1000359 memcpy(pr->buf + pr->len, str, len);
360 pr->len += len;
361}
Damien George6c73ca12014-01-08 18:11:23 +0000362
Damien George96fd80d2017-09-21 15:24:57 +1000363mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...) {
364 assert(fmt != NULL);
365
366 // Check that the given type is an exception type
367 assert(exc_type->make_new == mp_obj_exception_make_new);
368
369 // Try to allocate memory for the message
370 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
371 size_t o_str_alloc = strlen(fmt) + 1;
372 byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
373
374 bool used_emg_buf = false;
375 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
376 // If memory allocation failed and there is an emergency buffer then try to use
377 // that buffer to store the string object and its data (at least 16 bytes for
378 // the string data), reserving room at the start for the traceback and 1-tuple.
379 if ((o_str == NULL || o_str_buf == NULL)
Damien Georgebad4e152018-12-08 01:50:20 +1100380 && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) {
Damien George96fd80d2017-09-21 15:24:57 +1000381 used_emg_buf = true;
382 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
Damien Georgebad4e152018-12-08 01:50:20 +1100383 + EMG_BUF_STR_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000384 o_str_buf = (byte*)&o_str[1];
385 o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
386 + mp_emergency_exception_buf_size - o_str_buf;
387 }
388 #endif
389
390 if (o_str == NULL) {
391 // No memory for the string object so create the exception with no args
392 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
393 }
394
395 if (o_str_buf == NULL) {
396 // No memory for the string buffer: assume that the fmt string is in ROM
397 // and use that data as the data of the string
398 o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
399 o_str->data = (const byte*)fmt;
400 } else {
401 // We have some memory to format the string
402 struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
403 mp_print_t print = {&exc_pr, exc_add_strn};
404 va_list ap;
405 va_start(ap, fmt);
406 mp_vprintf(&print, fmt, ap);
407 va_end(ap);
408 exc_pr.buf[exc_pr.len] = '\0';
409 o_str->len = exc_pr.len;
410 o_str->data = exc_pr.buf;
411 }
412
413 // Create the string object and call mp_obj_exception_make_new to create the exception
414 o_str->base.type = &mp_type_str;
415 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
416 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
417 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damien George6c73ca12014-01-08 18:11:23 +0000418}
419
Damien Georgec5966122014-02-15 16:10:44 +0000420// return true if the given object is an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000421bool mp_obj_is_exception_type(mp_obj_t self_in) {
422 if (MP_OBJ_IS_TYPE(self_in, &mp_type_type)) {
Damien George9e6e9352014-03-26 18:37:06 +0000423 // optimisation when self_in is a builtin exception
Damien George999cedb2015-11-27 17:01:44 +0000424 mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
Damien George9e6e9352014-03-26 18:37:06 +0000425 if (self->make_new == mp_obj_exception_make_new) {
426 return true;
427 }
Damien Georgec5966122014-02-15 16:10:44 +0000428 }
Damien George999cedb2015-11-27 17:01:44 +0000429 return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
Damien Georgec5966122014-02-15 16:10:44 +0000430}
431
432// return true if the given object is an instance of an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000433bool mp_obj_is_exception_instance(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000434 return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
Damien Georgec5966122014-02-15 16:10:44 +0000435}
436
Damien George4bcd04b2014-09-24 14:05:40 +0100437// Return true if exception (type or instance) is a subclass of given
438// exception type. Assumes exc_type is a subclass of BaseException, as
439// defined by mp_obj_is_exception_type(exc_type).
440bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
441 // if exc is an instance of an exception, then extract and use its type
442 if (mp_obj_is_exception_instance(exc)) {
Damien George999cedb2015-11-27 17:01:44 +0000443 exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
Damien George4bcd04b2014-09-24 14:05:40 +0100444 }
445 return mp_obj_is_subclass_fast(exc, exc_type);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200446}
447
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300448// traceback handling functions
Damien Georgec5966122014-02-15 16:10:44 +0000449
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300450#define GET_NATIVE_EXCEPTION(self, self_in) \
451 /* make sure self_in is an exception instance */ \
452 assert(mp_obj_is_exception_instance(self_in)); \
453 mp_obj_exception_t *self; \
454 if (mp_obj_is_native_exception_instance(self_in)) { \
Damien George999cedb2015-11-27 17:01:44 +0000455 self = MP_OBJ_TO_PTR(self_in); \
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300456 } else { \
Damien George999cedb2015-11-27 17:01:44 +0000457 self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
Damien George9e6e9352014-03-26 18:37:06 +0000458 }
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300459
460void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
461 GET_NATIVE_EXCEPTION(self, self_in);
462 // just set the traceback to the null object
463 // we don't want to call any memory management functions here
Damien George4852e092015-02-27 00:36:39 +0000464 self->traceback_data = NULL;
Damienb86e3f92013-12-29 17:17:43 +0000465}
Damien George08335002014-01-18 23:24:36 +0000466
Damien George3d2daa22016-01-02 22:04:12 +0000467void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
Dave Hylands5b7fd202014-07-01 23:46:53 -0700468 GET_NATIVE_EXCEPTION(self, self_in);
469
Damien George4852e092015-02-27 00:36:39 +0000470 // append this traceback info to traceback data
471 // if memory allocation fails (eg because gc is locked), just return
Damien Georgef0b29722014-07-01 14:28:09 +0100472
Damien George4852e092015-02-27 00:36:39 +0000473 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000474 self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
Damien George4852e092015-02-27 00:36:39 +0000475 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000476 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
Damien Georgebad4e152018-12-08 01:50:20 +1100477 if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) {
Damien George96fd80d2017-09-21 15:24:57 +1000478 // There is room in the emergency buffer for traceback data
Damien Georgebad4e152018-12-08 01:50:20 +1100479 size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
480 + EMG_BUF_TRACEBACK_OFFSET);
Damien George96fd80d2017-09-21 15:24:57 +1000481 self->traceback_data = tb;
Damien Georgebad4e152018-12-08 01:50:20 +1100482 self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t);
Damien George96fd80d2017-09-21 15:24:57 +1000483 } else {
484 // Can't allocate and no room in emergency buffer
485 return;
486 }
487 #else
488 // Can't allocate
489 return;
490 #endif
491 } else {
492 // Allocated the traceback data on the heap
493 self->traceback_alloc = TRACEBACK_ENTRY_LEN;
494 }
495 self->traceback_len = 0;
496 } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
497 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
498 if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
499 // Can't resize the emergency buffer
Paul Sokolovskyfa3b8952015-02-15 22:24:03 +0300500 return;
501 }
Damien George96fd80d2017-09-21 15:24:57 +1000502 #endif
Damien George4852e092015-02-27 00:36:39 +0000503 // be conservative with growing traceback data
Damien George96fd80d2017-09-21 15:24:57 +1000504 size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
505 self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
Damien George4852e092015-02-27 00:36:39 +0000506 if (tb_data == NULL) {
507 return;
508 }
509 self->traceback_data = tb_data;
Damien George96fd80d2017-09-21 15:24:57 +1000510 self->traceback_alloc += TRACEBACK_ENTRY_LEN;
Damien George08335002014-01-18 23:24:36 +0000511 }
Damien George4852e092015-02-27 00:36:39 +0000512
Damien George3d2daa22016-01-02 22:04:12 +0000513 size_t *tb_data = &self->traceback_data[self->traceback_len];
Damien George96fd80d2017-09-21 15:24:57 +1000514 self->traceback_len += TRACEBACK_ENTRY_LEN;
Damien George3d2daa22016-01-02 22:04:12 +0000515 tb_data[0] = file;
516 tb_data[1] = line;
517 tb_data[2] = block;
Damien George08335002014-01-18 23:24:36 +0000518}
519
Damien George3d2daa22016-01-02 22:04:12 +0000520void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300521 GET_NATIVE_EXCEPTION(self, self_in);
Damien Georgec5966122014-02-15 16:10:44 +0000522
Damien George4852e092015-02-27 00:36:39 +0000523 if (self->traceback_data == NULL) {
Damien George136b1492014-01-19 12:38:49 +0000524 *n = 0;
525 *values = NULL;
526 } else {
Damien George4852e092015-02-27 00:36:39 +0000527 *n = self->traceback_len;
528 *values = self->traceback_data;
Damien George136b1492014-01-19 12:38:49 +0000529 }
Damien George08335002014-01-18 23:24:36 +0000530}