blob: 524f105ce1a6ebe888e5a138b8a61085c29e7cfe [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
43// Number of traceback entries to reserve in the emergency exception buffer
44#define EMG_TRACEBACK_ALLOC (2 * TRACEBACK_ENTRY_LEN)
45
Damien George6902eed2014-04-04 10:52:59 +000046// Instance of MemoryError exception - needed by mp_malloc_fail
Damien George999cedb2015-11-27 17:01:44 +000047const mp_obj_exception_t mp_const_MemoryError_obj = {{&mp_type_MemoryError}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj};
Damien George6902eed2014-04-04 10:52:59 +000048
Dave Hylands5b7fd202014-07-01 23:46:53 -070049// Optionally allocated buffer for storing the first argument of an exception
50// allocated when the heap is locked.
51#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
52# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0
Dave Hylands5b7fd202014-07-01 23:46:53 -070053#define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE
54
55void mp_init_emergency_exception_buf(void) {
56 // Nothing to do since the buffer was declared statically. We put this
57 // definition here so that the calling code can call this function
58 // regardless of how its configured (makes the calling code a bit cleaner).
59}
60
61#else
Damien Georgeb4b10fd2015-01-01 23:30:53 +000062#define mp_emergency_exception_buf_size MP_STATE_VM(mp_emergency_exception_buf_size)
Dave Hylands5b7fd202014-07-01 23:46:53 -070063
64void mp_init_emergency_exception_buf(void) {
65 mp_emergency_exception_buf_size = 0;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000066 MP_STATE_VM(mp_emergency_exception_buf) = NULL;
Dave Hylands5b7fd202014-07-01 23:46:53 -070067}
68
69mp_obj_t mp_alloc_emergency_exception_buf(mp_obj_t size_in) {
70 mp_int_t size = mp_obj_get_int(size_in);
71 void *buf = NULL;
72 if (size > 0) {
Damien George4d77e1a2015-02-27 09:34:51 +000073 buf = m_new(byte, size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070074 }
75
76 int old_size = mp_emergency_exception_buf_size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000077 void *old_buf = MP_STATE_VM(mp_emergency_exception_buf);
Dave Hylands5b7fd202014-07-01 23:46:53 -070078
79 // Update the 2 variables atomically so that an interrupt can't occur
80 // between the assignments.
Damien George4859edb2014-10-15 17:33:24 +000081 mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
Dave Hylands5b7fd202014-07-01 23:46:53 -070082 mp_emergency_exception_buf_size = size;
Damien Georgeb4b10fd2015-01-01 23:30:53 +000083 MP_STATE_VM(mp_emergency_exception_buf) = buf;
Damien George4859edb2014-10-15 17:33:24 +000084 MICROPY_END_ATOMIC_SECTION(atomic_state);
Dave Hylands5b7fd202014-07-01 23:46:53 -070085
86 if (old_buf != NULL) {
Damien George4d77e1a2015-02-27 09:34:51 +000087 m_del(byte, old_buf, old_size);
Dave Hylands5b7fd202014-07-01 23:46:53 -070088 }
89 return mp_const_none;
90}
91#endif
92#endif // MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
93
Paul Sokolovskyc4d589e2014-03-28 02:37:28 +020094// Instance of GeneratorExit exception - needed by generator.close()
95// This would belong to objgenerator.c, but to keep mp_obj_exception_t
96// definition module-private so far, have it here.
Damien George999cedb2015-11-27 17:01:44 +000097const 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 +020098
Damien George7f9d1d62015-04-09 23:56:15 +010099STATIC void 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 +0000100 mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in);
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300101 mp_print_kind_t k = kind & ~PRINT_EXC_SUBCLASS;
102 bool is_subclass = kind & PRINT_EXC_SUBCLASS;
103 if (!is_subclass && (k == PRINT_REPR || k == PRINT_EXC)) {
Damien George044c4732015-04-11 13:03:37 +0100104 mp_print_str(print, qstr_str(o->base.type->name));
Damiend99b0522013-12-21 18:17:45 +0000105 }
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300106
107 if (k == PRINT_EXC) {
Damien George7f9d1d62015-04-09 23:56:15 +0100108 mp_print_str(print, ": ");
Paul Sokolovskyd8351ca2014-05-02 01:51:25 +0300109 }
110
111 if (k == PRINT_STR || k == PRINT_EXC) {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300112 if (o->args == NULL || o->args->len == 0) {
Damien George7f9d1d62015-04-09 23:56:15 +0100113 mp_print_str(print, "");
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300114 return;
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300115 } else if (o->args->len == 1) {
Damien George9a924992016-05-12 14:27:52 +0100116 #if MICROPY_PY_UERRNO
117 // try to provide a nice OSError error message
118 if (o->base.type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(o->args->items[0])) {
119 qstr qst = mp_errno_to_str(o->args->items[0]);
120 if (qst != MP_QSTR_NULL) {
Damien George9c027072017-12-11 22:38:30 +1100121 mp_printf(print, "[Errno " INT_FMT "] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst);
Damien George9a924992016-05-12 14:27:52 +0100122 return;
123 }
124 }
125 #endif
Damien George7f9d1d62015-04-09 23:56:15 +0100126 mp_obj_print_helper(print, o->args->items[0], PRINT_STR);
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300127 return;
128 }
129 }
Damien George999cedb2015-11-27 17:01:44 +0000130 mp_obj_tuple_print(print, MP_OBJ_FROM_PTR(o->args), kind);
Damiend99b0522013-12-21 18:17:45 +0000131}
132
Damien George5b3f0b72016-01-03 15:55:55 +0000133mp_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 +0000134 mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
Damien George96fd80d2017-09-21 15:24:57 +1000135
136 // Try to allocate memory for the exception, with fallback to emergency exception object
137 mp_obj_exception_t *o_exc = m_new_obj_maybe(mp_obj_exception_t);
138 if (o_exc == NULL) {
139 o_exc = &MP_STATE_VM(mp_emergency_exception_obj);
Damien Georgef0954e32014-04-10 14:38:25 +0100140 }
Damien George96fd80d2017-09-21 15:24:57 +1000141
142 // Populate the exception object
143 o_exc->base.type = type;
144 o_exc->traceback_data = NULL;
145
146 mp_obj_tuple_t *o_tuple;
147 if (n_args == 0) {
148 // No args, can use the empty tuple straightaway
149 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
150 } else {
151 // Try to allocate memory for the tuple containing the args
152 o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args);
153
154 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
155 // If we are called by mp_obj_new_exception_msg_varg then it will have
156 // reserved room (after the traceback data) for a tuple with 1 element.
157 // Otherwise we are free to use the whole buffer after the traceback data.
158 if (o_tuple == NULL && mp_emergency_exception_buf_size >=
159 EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) {
160 o_tuple = (mp_obj_tuple_t*)
161 ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t));
162 }
163 #endif
164
165 if (o_tuple == NULL) {
166 // No memory for a tuple, fallback to an empty tuple
167 o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
168 } else {
169 // Have memory for a tuple so populate it
170 o_tuple->base.type = &mp_type_tuple;
171 o_tuple->len = n_args;
172 memcpy(o_tuple->items, args, n_args * sizeof(mp_obj_t));
173 }
174 }
175
176 // Store the tuple of args in the exception object
177 o_exc->args = o_tuple;
178
179 return MP_OBJ_FROM_PTR(o_exc);
Paul Sokolovskyddf21782014-01-12 23:30:20 +0200180}
181
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200182// Get exception "value" - that is, first argument, or None
183mp_obj_t mp_obj_exception_get_value(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000184 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300185 if (self->args->len == 0) {
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200186 return mp_const_none;
187 } else {
Paul Sokolovsky1acf22f2014-04-23 02:19:18 +0300188 return self->args->items[0];
Paul Sokolovskyaf1ae302014-03-26 19:17:20 +0200189 }
190}
191
Damien Georgeb1bbe962015-04-01 14:10:50 +0000192STATIC void exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300193 mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb1bbe962015-04-01 14:10:50 +0000194 if (dest[0] != MP_OBJ_NULL) {
Paul Sokolovskyc3d96d32016-11-14 02:23:30 +0300195 // store/delete attribute
196 if (attr == MP_QSTR___traceback__ && dest[1] == mp_const_none) {
197 // We allow 'exc.__traceback__ = None' assignment as low-level
198 // optimization of pre-allocating exception instance and raising
199 // it repeatedly - this avoids memory allocation during raise.
200 // However, uPy will keep adding traceback entries to such
201 // exception instance, so before throwing it, traceback should
202 // be cleared like above.
203 self->traceback_len = 0;
204 dest[0] = MP_OBJ_NULL; // indicate success
205 }
Damien Georgeb1bbe962015-04-01 14:10:50 +0000206 return;
207 }
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200208 if (attr == MP_QSTR_args) {
Damien George999cedb2015-11-27 17:01:44 +0000209 dest[0] = MP_OBJ_FROM_PTR(self->args);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200210 } else if (self->base.type == &mp_type_StopIteration && attr == MP_QSTR_value) {
Damien George999cedb2015-11-27 17:01:44 +0000211 dest[0] = mp_obj_exception_get_value(self_in);
Paul Sokolovsky9512e9e2014-03-25 01:29:09 +0200212 }
213}
214
Damien Georgec5966122014-02-15 16:10:44 +0000215const mp_obj_type_t mp_type_BaseException = {
216 { &mp_type_type },
217 .name = MP_QSTR_BaseException,
218 .print = mp_obj_exception_print,
219 .make_new = mp_obj_exception_make_new,
Damien Georgeb1bbe962015-04-01 14:10:50 +0000220 .attr = exception_attr,
Damiend99b0522013-12-21 18:17:45 +0000221};
222
Damien George22a08652014-02-15 21:05:25 +0000223#define MP_DEFINE_EXCEPTION(exc_name, base_name) \
Damien Georgec5966122014-02-15 16:10:44 +0000224const mp_obj_type_t mp_type_ ## exc_name = { \
225 { &mp_type_type }, \
226 .name = MP_QSTR_ ## exc_name, \
227 .print = mp_obj_exception_print, \
228 .make_new = mp_obj_exception_make_new, \
Damien Georgeb1bbe962015-04-01 14:10:50 +0000229 .attr = exception_attr, \
Damien George816413e2017-04-06 12:09:01 +1000230 .parent = &mp_type_ ## base_name, \
Damien Georgec5966122014-02-15 16:10:44 +0000231};
232
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000233// List of all exceptions, arranged as in the table at:
Chris Angelicodaf973a2014-06-06 03:51:03 +1000234// http://docs.python.org/3/library/exceptions.html
Damien George7a4ddd22014-05-24 23:32:19 +0100235MP_DEFINE_EXCEPTION(SystemExit, BaseException)
Damien George124df6f2014-10-25 18:19:55 +0100236MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000237MP_DEFINE_EXCEPTION(GeneratorExit, BaseException)
238MP_DEFINE_EXCEPTION(Exception, BaseException)
pohmelie81ebba72016-01-27 23:23:11 +0300239 #if MICROPY_PY_ASYNC_AWAIT
240 MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception)
241 #endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000242 MP_DEFINE_EXCEPTION(StopIteration, Exception)
243 MP_DEFINE_EXCEPTION(ArithmeticError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000244 //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000245 MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError)
246 MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError)
247 MP_DEFINE_EXCEPTION(AssertionError, Exception)
248 MP_DEFINE_EXCEPTION(AttributeError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000249 //MP_DEFINE_EXCEPTION(BufferError, Exception)
Damien George8b03d942014-09-30 13:59:30 +0000250 //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000251 MP_DEFINE_EXCEPTION(EOFError, Exception)
252 MP_DEFINE_EXCEPTION(ImportError, Exception)
Damien George8b03d942014-09-30 13:59:30 +0000253 //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000254 MP_DEFINE_EXCEPTION(LookupError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000255 MP_DEFINE_EXCEPTION(IndexError, LookupError)
256 MP_DEFINE_EXCEPTION(KeyError, LookupError)
257 MP_DEFINE_EXCEPTION(MemoryError, Exception)
258 MP_DEFINE_EXCEPTION(NameError, Exception)
Damien Georgec63f9842014-03-27 23:49:06 +0000259 /*
Antonin ENFRUNda1fffa2014-05-12 00:21:50 +0200260 MP_DEFINE_EXCEPTION(UnboundLocalError, NameError)
261 */
262 MP_DEFINE_EXCEPTION(OSError, Exception)
Daniel Campora077812b2015-06-29 22:45:39 +0200263#if MICROPY_PY_BUILTINS_TIMEOUTERROR
Daniel Campora077812b2015-06-29 22:45:39 +0200264 MP_DEFINE_EXCEPTION(TimeoutError, OSError)
265#endif
266 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000267 MP_DEFINE_EXCEPTION(BlockingIOError, OSError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000268 MP_DEFINE_EXCEPTION(ChildProcessError, OSError)
269 MP_DEFINE_EXCEPTION(ConnectionError, OSError)
270 MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError)
271 MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError)
272 MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError)
273 MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000274 MP_DEFINE_EXCEPTION(InterruptedError, OSError)
275 MP_DEFINE_EXCEPTION(IsADirectoryError, OSError)
276 MP_DEFINE_EXCEPTION(NotADirectoryError, OSError)
277 MP_DEFINE_EXCEPTION(PermissionError, OSError)
278 MP_DEFINE_EXCEPTION(ProcessLookupError, OSError)
Damien Georgec9109722014-03-22 23:40:02 +0000279 MP_DEFINE_EXCEPTION(FileExistsError, OSError)
280 MP_DEFINE_EXCEPTION(FileNotFoundError, OSError)
Damien Georgec63f9842014-03-27 23:49:06 +0000281 MP_DEFINE_EXCEPTION(ReferenceError, Exception)
282 */
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000283 MP_DEFINE_EXCEPTION(RuntimeError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000284 MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError)
285 MP_DEFINE_EXCEPTION(SyntaxError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000286 MP_DEFINE_EXCEPTION(IndentationError, SyntaxError)
Damien Georgec63f9842014-03-27 23:49:06 +0000287 /*
Damien Georgec63f9842014-03-27 23:49:06 +0000288 MP_DEFINE_EXCEPTION(TabError, IndentationError)
289 */
Damien Georgee7a47822014-10-22 19:42:55 +0100290 //MP_DEFINE_EXCEPTION(SystemError, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000291 MP_DEFINE_EXCEPTION(TypeError, Exception)
Damien Georgec8b60f02015-04-20 13:29:31 +0000292#if MICROPY_EMIT_NATIVE
Damien Georgec8b60f02015-04-20 13:29:31 +0000293 MP_DEFINE_EXCEPTION(ViperTypeError, TypeError)
294#endif
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000295 MP_DEFINE_EXCEPTION(ValueError, Exception)
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200296#if MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovsky71ebd4b2015-02-23 23:18:36 +0200297 MP_DEFINE_EXCEPTION(UnicodeError, ValueError)
298 //TODO: Implement more UnicodeError subclasses which take arguments
299#endif
Damien Georgec9109722014-03-22 23:40:02 +0000300 /*
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000301 MP_DEFINE_EXCEPTION(Warning, Exception)
Rachel Dowdall721c55d2014-03-22 15:28:16 +0000302 MP_DEFINE_EXCEPTION(DeprecationWarning, Warning)
303 MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning)
304 MP_DEFINE_EXCEPTION(RuntimeWarning, Warning)
305 MP_DEFINE_EXCEPTION(SyntaxWarning, Warning)
306 MP_DEFINE_EXCEPTION(UserWarning, Warning)
307 MP_DEFINE_EXCEPTION(FutureWarning, Warning)
308 MP_DEFINE_EXCEPTION(ImportWarning, Warning)
309 MP_DEFINE_EXCEPTION(UnicodeWarning, Warning)
310 MP_DEFINE_EXCEPTION(BytesWarning, Warning)
311 MP_DEFINE_EXCEPTION(ResourceWarning, Warning)
Damien Georgec9109722014-03-22 23:40:02 +0000312 */
Damien Georgec5966122014-02-15 16:10:44 +0000313
314mp_obj_t mp_obj_new_exception(const mp_obj_type_t *exc_type) {
Paul Sokolovskya96d3d02014-03-31 01:10:10 +0300315 return mp_obj_new_exception_args(exc_type, 0, NULL);
Damiend99b0522013-12-21 18:17:45 +0000316}
317
Paul Sokolovskydec31bb2014-04-22 00:01:13 +0300318// "Optimized" version for common(?) case of having 1 exception arg
319mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) {
320 return mp_obj_new_exception_args(exc_type, 1, &arg);
321}
322
Damien Georgefa5a5912017-02-16 16:38:14 +1100323mp_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 +0200324 assert(exc_type->make_new == mp_obj_exception_make_new);
Damien George5b3f0b72016-01-03 15:55:55 +0000325 return exc_type->make_new(exc_type, n_args, 0, args);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200326}
327
Damien Georgec5966122014-02-15 16:10:44 +0000328mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg) {
329 return mp_obj_new_exception_msg_varg(exc_type, msg);
Damiend99b0522013-12-21 18:17:45 +0000330}
331
Damien George96fd80d2017-09-21 15:24:57 +1000332// The following struct and function implement a simple printer that conservatively
333// allocates memory and truncates the output data if no more memory can be obtained.
334// It leaves room for a null byte at the end of the buffer.
Damien Georgec5966122014-02-15 16:10:44 +0000335
Damien George96fd80d2017-09-21 15:24:57 +1000336struct _exc_printer_t {
337 bool allow_realloc;
338 size_t alloc;
339 size_t len;
340 byte *buf;
341};
Dave Hylands5b7fd202014-07-01 23:46:53 -0700342
Damien George96fd80d2017-09-21 15:24:57 +1000343STATIC void exc_add_strn(void *data, const char *str, size_t len) {
344 struct _exc_printer_t *pr = data;
345 if (pr->len + len >= pr->alloc) {
346 // Not enough room for data plus a null byte so try to grow the buffer
347 if (pr->allow_realloc) {
348 size_t new_alloc = pr->alloc + len + 16;
349 byte *new_buf = m_renew_maybe(byte, pr->buf, pr->alloc, new_alloc, true);
350 if (new_buf == NULL) {
351 pr->allow_realloc = false;
352 len = pr->alloc - pr->len - 1;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300353 } else {
Damien George96fd80d2017-09-21 15:24:57 +1000354 pr->alloc = new_alloc;
355 pr->buf = new_buf;
Paul Sokolovsky29c4f922015-02-15 22:19:30 +0300356 }
Damien George96fd80d2017-09-21 15:24:57 +1000357 } else {
358 len = pr->alloc - pr->len - 1;
Damien Georgef0954e32014-04-10 14:38:25 +0100359 }
Damien George6c73ca12014-01-08 18:11:23 +0000360 }
Damien George96fd80d2017-09-21 15:24:57 +1000361 memcpy(pr->buf + pr->len, str, len);
362 pr->len += len;
363}
Damien George6c73ca12014-01-08 18:11:23 +0000364
Damien George96fd80d2017-09-21 15:24:57 +1000365mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...) {
366 assert(fmt != NULL);
367
368 // Check that the given type is an exception type
369 assert(exc_type->make_new == mp_obj_exception_make_new);
370
371 // Try to allocate memory for the message
372 mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t);
373 size_t o_str_alloc = strlen(fmt) + 1;
374 byte *o_str_buf = m_new_maybe(byte, o_str_alloc);
375
376 bool used_emg_buf = false;
377 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
378 // If memory allocation failed and there is an emergency buffer then try to use
379 // that buffer to store the string object and its data (at least 16 bytes for
380 // the string data), reserving room at the start for the traceback and 1-tuple.
381 if ((o_str == NULL || o_str_buf == NULL)
382 && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)
383 + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) {
384 used_emg_buf = true;
385 o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
386 + EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t));
387 o_str_buf = (byte*)&o_str[1];
388 o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf)
389 + mp_emergency_exception_buf_size - o_str_buf;
390 }
391 #endif
392
393 if (o_str == NULL) {
394 // No memory for the string object so create the exception with no args
395 return mp_obj_exception_make_new(exc_type, 0, 0, NULL);
396 }
397
398 if (o_str_buf == NULL) {
399 // No memory for the string buffer: assume that the fmt string is in ROM
400 // and use that data as the data of the string
401 o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt)
402 o_str->data = (const byte*)fmt;
403 } else {
404 // We have some memory to format the string
405 struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf};
406 mp_print_t print = {&exc_pr, exc_add_strn};
407 va_list ap;
408 va_start(ap, fmt);
409 mp_vprintf(&print, fmt, ap);
410 va_end(ap);
411 exc_pr.buf[exc_pr.len] = '\0';
412 o_str->len = exc_pr.len;
413 o_str->data = exc_pr.buf;
414 }
415
416 // Create the string object and call mp_obj_exception_make_new to create the exception
417 o_str->base.type = &mp_type_str;
418 o_str->hash = qstr_compute_hash(o_str->data, o_str->len);
419 mp_obj_t arg = MP_OBJ_FROM_PTR(o_str);
420 return mp_obj_exception_make_new(exc_type, 1, 0, &arg);
Damien George6c73ca12014-01-08 18:11:23 +0000421}
422
Damien Georgec5966122014-02-15 16:10:44 +0000423// return true if the given object is an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000424bool mp_obj_is_exception_type(mp_obj_t self_in) {
425 if (MP_OBJ_IS_TYPE(self_in, &mp_type_type)) {
Damien George9e6e9352014-03-26 18:37:06 +0000426 // optimisation when self_in is a builtin exception
Damien George999cedb2015-11-27 17:01:44 +0000427 mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
Damien George9e6e9352014-03-26 18:37:06 +0000428 if (self->make_new == mp_obj_exception_make_new) {
429 return true;
430 }
Damien Georgec5966122014-02-15 16:10:44 +0000431 }
Damien George999cedb2015-11-27 17:01:44 +0000432 return mp_obj_is_subclass_fast(self_in, MP_OBJ_FROM_PTR(&mp_type_BaseException));
Damien Georgec5966122014-02-15 16:10:44 +0000433}
434
435// return true if the given object is an instance of an exception type
Damien Georgec5966122014-02-15 16:10:44 +0000436bool mp_obj_is_exception_instance(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +0000437 return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)));
Damien Georgec5966122014-02-15 16:10:44 +0000438}
439
Damien George4bcd04b2014-09-24 14:05:40 +0100440// Return true if exception (type or instance) is a subclass of given
441// exception type. Assumes exc_type is a subclass of BaseException, as
442// defined by mp_obj_is_exception_type(exc_type).
443bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) {
444 // if exc is an instance of an exception, then extract and use its type
445 if (mp_obj_is_exception_instance(exc)) {
Damien George999cedb2015-11-27 17:01:44 +0000446 exc = MP_OBJ_FROM_PTR(mp_obj_get_type(exc));
Damien George4bcd04b2014-09-24 14:05:40 +0100447 }
448 return mp_obj_is_subclass_fast(exc, exc_type);
Paul Sokolovsky962b1cd2014-03-23 21:48:29 +0200449}
450
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300451// traceback handling functions
Damien Georgec5966122014-02-15 16:10:44 +0000452
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300453#define GET_NATIVE_EXCEPTION(self, self_in) \
454 /* make sure self_in is an exception instance */ \
455 assert(mp_obj_is_exception_instance(self_in)); \
456 mp_obj_exception_t *self; \
457 if (mp_obj_is_native_exception_instance(self_in)) { \
Damien George999cedb2015-11-27 17:01:44 +0000458 self = MP_OBJ_TO_PTR(self_in); \
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300459 } else { \
Damien George999cedb2015-11-27 17:01:44 +0000460 self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \
Damien George9e6e9352014-03-26 18:37:06 +0000461 }
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300462
463void mp_obj_exception_clear_traceback(mp_obj_t self_in) {
464 GET_NATIVE_EXCEPTION(self, self_in);
465 // just set the traceback to the null object
466 // we don't want to call any memory management functions here
Damien George4852e092015-02-27 00:36:39 +0000467 self->traceback_data = NULL;
Damienb86e3f92013-12-29 17:17:43 +0000468}
Damien George08335002014-01-18 23:24:36 +0000469
Damien George3d2daa22016-01-02 22:04:12 +0000470void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block) {
Dave Hylands5b7fd202014-07-01 23:46:53 -0700471 GET_NATIVE_EXCEPTION(self, self_in);
472
Damien George4852e092015-02-27 00:36:39 +0000473 // append this traceback info to traceback data
474 // if memory allocation fails (eg because gc is locked), just return
Damien Georgef0b29722014-07-01 14:28:09 +0100475
Damien George4852e092015-02-27 00:36:39 +0000476 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000477 self->traceback_data = m_new_maybe(size_t, TRACEBACK_ENTRY_LEN);
Damien George4852e092015-02-27 00:36:39 +0000478 if (self->traceback_data == NULL) {
Damien George96fd80d2017-09-21 15:24:57 +1000479 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
480 if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) {
481 // There is room in the emergency buffer for traceback data
482 size_t *tb = (size_t*)MP_STATE_VM(mp_emergency_exception_buf);
483 self->traceback_data = tb;
484 self->traceback_alloc = EMG_TRACEBACK_ALLOC;
485 } else {
486 // Can't allocate and no room in emergency buffer
487 return;
488 }
489 #else
490 // Can't allocate
491 return;
492 #endif
493 } else {
494 // Allocated the traceback data on the heap
495 self->traceback_alloc = TRACEBACK_ENTRY_LEN;
496 }
497 self->traceback_len = 0;
498 } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) {
499 #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
500 if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) {
501 // Can't resize the emergency buffer
Paul Sokolovskyfa3b8952015-02-15 22:24:03 +0300502 return;
503 }
Damien George96fd80d2017-09-21 15:24:57 +1000504 #endif
Damien George4852e092015-02-27 00:36:39 +0000505 // be conservative with growing traceback data
Damien George96fd80d2017-09-21 15:24:57 +1000506 size_t *tb_data = m_renew_maybe(size_t, self->traceback_data, self->traceback_alloc,
507 self->traceback_alloc + TRACEBACK_ENTRY_LEN, true);
Damien George4852e092015-02-27 00:36:39 +0000508 if (tb_data == NULL) {
509 return;
510 }
511 self->traceback_data = tb_data;
Damien George96fd80d2017-09-21 15:24:57 +1000512 self->traceback_alloc += TRACEBACK_ENTRY_LEN;
Damien George08335002014-01-18 23:24:36 +0000513 }
Damien George4852e092015-02-27 00:36:39 +0000514
Damien George3d2daa22016-01-02 22:04:12 +0000515 size_t *tb_data = &self->traceback_data[self->traceback_len];
Damien George96fd80d2017-09-21 15:24:57 +1000516 self->traceback_len += TRACEBACK_ENTRY_LEN;
Damien George3d2daa22016-01-02 22:04:12 +0000517 tb_data[0] = file;
518 tb_data[1] = line;
519 tb_data[2] = block;
Damien George08335002014-01-18 23:24:36 +0000520}
521
Damien George3d2daa22016-01-02 22:04:12 +0000522void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values) {
Paul Sokolovsky91e556a2014-05-02 02:27:00 +0300523 GET_NATIVE_EXCEPTION(self, self_in);
Damien Georgec5966122014-02-15 16:10:44 +0000524
Damien George4852e092015-02-27 00:36:39 +0000525 if (self->traceback_data == NULL) {
Damien George136b1492014-01-19 12:38:49 +0000526 *n = 0;
527 *values = NULL;
528 } else {
Damien George4852e092015-02-27 00:36:39 +0000529 *n = self->traceback_len;
530 *values = self->traceback_data;
Damien George136b1492014-01-19 12:38:49 +0000531 }
Damien George08335002014-01-18 23:24:36 +0000532}