/
exceptions.c
561 lines (488 loc) · 20.5 KB
/
exceptions.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#include "moar.h"
#include <stdarg.h>
#if _MSC_VER
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
static int crash_on_error = 0;
/* Maps ID of exception category to its name. */
static const char * cat_name(MVMThreadContext *tc, MVMint32 cat) {
switch (cat) {
case MVM_EX_CAT_CATCH:
return "catch";
case MVM_EX_CAT_CONTROL:
return "control";
case MVM_EX_CAT_NEXT:
return "next";
case MVM_EX_CAT_REDO:
return "redo";
case MVM_EX_CAT_LAST:
return "last";
case MVM_EX_CAT_RETURN:
return "return";
case MVM_EX_CAT_TAKE:
return "take";
case MVM_EX_CAT_WARN:
return "warn";
case MVM_EX_CAT_SUCCEED:
return "succeed";
case MVM_EX_CAT_PROCEED:
return "proceed";
default:
return "unknown";
}
}
/* Checks if an exception handler is already on the active handler stack,
* so we don't re-trigger the same exception handler. */
static MVMuint8 in_handler_stack(MVMThreadContext *tc, MVMFrameHandler *fh) {
if (tc->active_handlers) {
MVMActiveHandler *ah = tc->active_handlers;
while (ah) {
if (ah->handler == fh)
return 1;
ah = ah->next_handler;
}
}
return 0;
}
/* Checks if a frame is still active. Naively, we could scan the call stack
* for it, but we can use the same thing the GC uses to know if to scan the
* work area. */
static MVMuint8 in_caller_chain(MVMThreadContext *tc, MVMFrame *f_maybe) {
return f_maybe->tc ? 1 : 0;
}
/* Looks through the handlers of a particular scope, and sees if one will
* match what we're looking for. Returns a pointer to it if so; if not,
* returns NULL. */
static MVMFrameHandler * search_frame_handlers(MVMThreadContext *tc, MVMFrame *f, MVMuint32 cat) {
MVMStaticFrame *sf = f->static_info;
MVMuint32 pc, i;
if (f == tc->cur_frame)
pc = (MVMuint32)(*tc->interp_cur_op - *tc->interp_bytecode_start);
else
pc = (MVMuint32)(f->return_address - sf->body.bytecode);
for (i = 0; i < sf->body.num_handlers; i++) {
if (sf->body.handlers[i].category_mask & cat)
if (pc >= sf->body.handlers[i].start_offset && pc <= sf->body.handlers[i].end_offset)
if (!in_handler_stack(tc, &sf->body.handlers[i]))
return &sf->body.handlers[i];
}
return NULL;
}
/* Information about a located handler. */
typedef struct {
MVMFrame *frame;
MVMFrameHandler *handler;
} LocatedHandler;
/* Searches for a handler of the specified category, relative to the given
* starting frame, searching according to the chosen mode. */
static LocatedHandler search_for_handler_from(MVMThreadContext *tc, MVMFrame *f,
MVMuint8 mode, MVMuint32 cat) {
LocatedHandler lh;
lh.frame = NULL;
lh.handler = NULL;
if (mode == MVM_EX_THROW_LEXOTIC) {
while (f != NULL) {
lh = search_for_handler_from(tc, f, MVM_EX_THROW_LEX, cat);
if (lh.frame != NULL)
return lh;
f = f->caller;
}
}
else {
while (f != NULL) {
MVMFrameHandler *h = search_frame_handlers(tc, f, cat);
if (h != NULL) {
lh.frame = f;
lh.handler = h;
return lh;
}
if (mode == MVM_EX_THROW_DYN) {
f = f->caller;
}
else {
MVMFrame *f_maybe = f->outer;
while (f_maybe != NULL && !in_caller_chain(tc, f_maybe))
f_maybe = f_maybe->outer;
f = f_maybe;
}
}
}
return lh;
}
/* Unwinds execution state to the specified frame. */
static void unwind_to_frame(MVMThreadContext *tc, MVMFrame *target) {
while (tc->cur_frame != target)
if (!MVM_frame_try_unwind(tc))
MVM_panic(1, "Internal error: Unwound entire stack and missed handler");
}
/* Dummy, 0-arg callsite for invoking handlers. */
static MVMCallsite no_arg_callsite = { NULL, 0, 0, 0 };
/* Runs an exception handler (which really means updating interpreter state
* so that when we return to the runloop, we're in the handler). If there is
* an exception object already, it will be used; NULL can be passed if there
* is not one, meaning it will be created if needed. */
static void unwind_after_handler(MVMThreadContext *tc, void *sr_data);
static void run_handler(MVMThreadContext *tc, LocatedHandler lh, MVMObject *ex_obj) {
switch (lh.handler->action) {
case MVM_EX_ACTION_GOTO:
unwind_to_frame(tc, lh.frame);
*tc->interp_cur_op = *tc->interp_bytecode_start + lh.handler->goto_offset;
break;
case MVM_EX_ACTION_INVOKE: {
/* Create active handler record. */
MVMActiveHandler *ah = malloc(sizeof(MVMActiveHandler));
/* Find frame to invoke. */
MVMObject *handler_code = MVM_frame_find_invokee(tc,
lh.frame->work[lh.handler->block_reg].o);
/* Ensure we have an exception object. */
/* TODO: Can make one up. */
if (ex_obj == NULL)
MVM_panic(1, "Exception object creation NYI");
/* Install active handler record. */
ah->frame = MVM_frame_inc_ref(tc, lh.frame);
ah->handler = lh.handler;
ah->ex_obj = ex_obj;
ah->next_handler = tc->active_handlers;
tc->active_handlers = ah;
/* Set up special return to unwinding after running the
* handler. */
tc->cur_frame->return_value = (MVMRegister *)&tc->last_handler_result;
tc->cur_frame->return_type = MVM_RETURN_OBJ;
tc->cur_frame->special_return = unwind_after_handler;
tc->cur_frame->special_return_data = ah;
/* Invoke the handler frame and return to runloop. */
STABLE(handler_code)->invoke(tc, handler_code, &no_arg_callsite,
tc->cur_frame->args);
break;
}
default:
MVM_panic(1, "Unimplemented handler action");
}
}
/* Unwinds after a handler. */
static void unwind_after_handler(MVMThreadContext *tc, void *sr_data) {
/* Get active handler; sanity check (though it's possible other cases
* should be supported). */
MVMActiveHandler *ah = (MVMActiveHandler *)sr_data;
if (tc->active_handlers != ah)
MVM_panic(1, "Trying to unwind from wrong handler");
tc->active_handlers = ah->next_handler;
/* Do the unwinding as needed. */
unwind_to_frame(tc, ah->frame);
*tc->interp_cur_op = *tc->interp_bytecode_start + ah->handler->goto_offset;
/* Clean up. */
MVM_frame_dec_ref(tc, ah->frame);
free(ah);
}
char * MVM_exception_backtrace_line(MVMThreadContext *tc, MVMFrame *cur_frame, MVMuint16 not_top) {
MVMString *filename = cur_frame->static_info->body.cu->body.filename;
MVMString *name = cur_frame->static_info->body.name;
/* XXX TODO: make the caller pass in a char ** and a length pointer so
* we can update it if necessary, and the caller can cache it. */
char *o = malloc(1024);
MVMuint8 *cur_op = not_top ? cur_frame->return_address : cur_frame->throw_address;
MVMuint32 offset = cur_op - cur_frame->static_info->body.bytecode;
MVMuint32 instr = MVM_bytecode_offset_to_instr_idx(tc, cur_frame->static_info, offset);
MVMBytecodeAnnotation *annot = MVM_bytecode_resolve_annotation(tc, &cur_frame->static_info->body, offset);
MVMuint32 line_number = annot ? annot->line_number + 1 : 1;
MVMuint16 string_heap_index = annot ? annot->filename_string_heap_index : 0;
char *tmp1 = annot && string_heap_index < cur_frame->static_info->body.cu->body.num_strings
? MVM_string_utf8_encode(tc,
cur_frame->static_info->body.cu->body.strings[string_heap_index], NULL)
: NULL;
/* We may be mid-instruction if exception was thrown at an unfortunate
* point; try to cope with that. */
if (instr == MVM_BC_ILLEGAL_OFFSET && offset >= 2)
instr = MVM_bytecode_offset_to_instr_idx(tc, cur_frame->static_info, offset - 2);
snprintf(o, 1024, " %s %s:%u (%s:%s:%u)",
not_top ? "from" : " at",
tmp1 ? tmp1 : "<unknown>",
line_number,
filename ? (char *) MVM_string_utf8_encode(tc, filename, NULL) : "<ephemeral file>",
name ? (char *) MVM_string_utf8_encode(tc, name, NULL) : "<anonymous frame>",
instr
);
if (tmp1)
free(tmp1);
if (annot)
free(annot);
return o;
}
/* Returns a list of hashes containing file, line, sub and annotations. */
MVMObject * MVM_exception_backtrace(MVMThreadContext *tc, MVMObject *ex_obj) {
MVMException *ex;
MVMFrame *cur_frame;
MVMObject *arr, *annotations, *row, *value;
MVMuint32 count = 0;
MVMString *k_file, *k_line, *k_sub, *k_anno;
if (IS_CONCRETE(ex_obj) && REPR(ex_obj)->ID == MVM_REPR_ID_MVMException)
ex = (MVMException *)ex_obj;
else
MVM_exception_throw_adhoc(tc, "Op 'backtrace' needs an exception object");
MVM_gc_root_temp_push(tc, (MVMCollectable **)&arr);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&annotations);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&row);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&value);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&k_file);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&k_line);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&k_sub);
MVM_gc_root_temp_push(tc, (MVMCollectable **)&k_anno);
k_file = MVM_string_ascii_decode_nt(tc, tc->instance->VMString, "file");
k_line = MVM_string_ascii_decode_nt(tc, tc->instance->VMString, "line");
k_sub = MVM_string_ascii_decode_nt(tc, tc->instance->VMString, "sub");
k_anno = MVM_string_ascii_decode_nt(tc, tc->instance->VMString, "annotations");
cur_frame = ex->body.origin;
arr = MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTArray);
while (cur_frame != NULL) {
MVMuint8 *cur_op = count ? cur_frame->return_address : cur_frame->throw_address;
MVMuint32 offset = cur_op - cur_frame->static_info->body.bytecode;
MVMBytecodeAnnotation *annot = MVM_bytecode_resolve_annotation(tc, &cur_frame->static_info->body, offset);
char *line_number = malloc(16);
snprintf(line_number, 16, "%d", annot ? annot->line_number + 1 : 1);
/* annotations hash will contain "file" and "line" */
annotations = MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTHash);
/* file */
value = MVM_repr_box_str(tc, MVM_hll_current(tc)->str_box_type,
cur_frame->static_info->body.cu->body.filename);
MVM_repr_bind_key_o(tc, annotations, k_file, value);
/* line */
value = (MVMObject *)MVM_string_ascii_decode_nt(tc, tc->instance->VMString, line_number);
value = MVM_repr_box_str(tc, MVM_hll_current(tc)->str_box_type, (MVMString *)value);
MVM_repr_bind_key_o(tc, annotations, k_line, value);
free(line_number);
/* row will contain "sub" and "annotations" */
row = MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTHash);
MVM_repr_bind_key_o(tc, row, k_sub, cur_frame->code_ref);
MVM_repr_bind_key_o(tc, row, k_anno, annotations);
MVM_repr_push_o(tc, arr, row);
cur_frame = cur_frame->caller;
count++;
}
MVM_gc_root_temp_pop_n(tc, 8);
return arr;
}
/* Returns the lines (backtrace) of an exception-object as an array. */
MVMObject * MVM_exception_backtrace_strings(MVMThreadContext *tc, MVMObject *ex_obj) {
MVMException *ex;
MVMFrame *cur_frame;
MVMObject *arr;
if (IS_CONCRETE(ex_obj) && REPR(ex_obj)->ID == MVM_REPR_ID_MVMException)
ex = (MVMException *)ex_obj;
else
MVM_exception_throw_adhoc(tc, "Op 'backtracestrings' needs an exception object");
cur_frame = ex->body.origin;
arr = MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTArray);
MVMROOT(tc, arr, {
MVMuint32 count = 0;
while (cur_frame != NULL) {
char *line = MVM_exception_backtrace_line(tc, cur_frame, count++);
MVMString *line_str = MVM_string_utf8_decode(tc, tc->instance->VMString, line, strlen(line));
MVMObject *line_obj = MVM_repr_box_str(tc, tc->instance->boot_types.BOOTStr, line_str);
MVM_repr_push_o(tc, arr, line_obj);
cur_frame = cur_frame->caller;
free(line);
}
});
return arr;
}
/* Dumps a backtrace relative to the current frame to stderr. */
static void dump_backtrace(MVMThreadContext *tc) {
MVMFrame *cur_frame = tc->cur_frame;
MVMuint32 count = 0;
while (cur_frame != NULL) {
char *line = MVM_exception_backtrace_line(tc, cur_frame, count++);
fprintf(stderr, "%s\n", line);
free(line);
cur_frame = cur_frame->caller;
}
}
/* Panic over an unhandled exception throw by category. */
static void panic_unhandled_cat(MVMThreadContext *tc, MVMuint32 cat) {
fprintf(stderr, "No exception handler located for %s\n", cat_name(tc, cat));
dump_backtrace(tc);
if (crash_on_error)
abort();
else
exit(1);
}
/* Panic over an unhandled exception object. */
static void panic_unhandled_ex(MVMThreadContext *tc, MVMException *ex) {
/* If there's no message, fall back to category. */
if (!ex->body.message)
panic_unhandled_cat(tc, ex->body.category);
/* Otherwise, dump message and a backtrace. */
fprintf(stderr, "Unhandled exception: %s\n",
MVM_string_utf8_encode_C_string(tc, ex->body.message));
dump_backtrace(tc);
if (crash_on_error)
abort();
else
exit(1);
}
/* Throws an exception by category, searching for a handler according to
* the specified mode. If the handler resumes, the resumption result will
* be put into resume_result. Leaves the interpreter in a state where it
* will next run the instruction of the handler. If there is no handler,
* it will panic and exit with a backtrace. */
void MVM_exception_throwcat(MVMThreadContext *tc, MVMuint8 mode, MVMuint32 cat, MVMRegister *resume_result) {
LocatedHandler lh = search_for_handler_from(tc, tc->cur_frame, mode, cat);
if (lh.frame == NULL)
panic_unhandled_cat(tc, cat);
run_handler(tc, lh, NULL);
}
/* Throws the specified exception object, taking the category from it. If
* the handler resumes, the resumption result will be put into resume_result.
* Leaves the interpreter in a state where it will next run the instruction of
* the handler. If there is no handler, it will panic and exit with a backtrace. */
void MVM_exception_throwobj(MVMThreadContext *tc, MVMuint8 mode, MVMObject *ex_obj, MVMRegister *resume_result) {
LocatedHandler lh;
MVMException *ex;
if (IS_CONCRETE(ex_obj) && REPR(ex_obj)->ID == MVM_REPR_ID_MVMException)
ex = (MVMException *)ex_obj;
else
MVM_exception_throw_adhoc(tc, "Can only throw an exception object");
lh = search_for_handler_from(tc, tc->cur_frame, mode, ex->body.category);
if (lh.frame == NULL)
panic_unhandled_ex(tc, ex);
if (!ex->body.origin) {
ex->body.origin = MVM_frame_inc_ref(tc, tc->cur_frame);
tc->cur_frame->throw_address = *(tc->interp_cur_op);
}
run_handler(tc, lh, ex_obj);
}
void MVM_exception_resume(MVMThreadContext *tc, MVMObject *ex_obj) {
MVMException *ex;
MVMActiveHandler *ah;
if (IS_CONCRETE(ex_obj) && REPR(ex_obj)->ID == MVM_REPR_ID_MVMException)
ex = (MVMException *)ex_obj;
else
MVM_exception_throw_adhoc(tc, "Can only resume an exception object");
if (ex->body.origin->special_return == unwind_after_handler) {
/* A handler was already installed, just use it. */
ah = (MVMActiveHandler *)ex->body.origin->special_return_data;
}
else {
/* We need to allocate/register a handler and set some defaults. */
ah = malloc(sizeof(MVMActiveHandler));
ah->ex_obj = ex_obj;
ah->next_handler = tc->active_handlers;
tc->active_handlers = ah;
tc->cur_frame->return_value = NULL;
tc->cur_frame->return_type = MVM_RETURN_VOID;
ex->body.origin->special_return_data = (void *)ah;
}
ah->frame = (void *)MVM_frame_inc_ref(tc, ex->body.origin);
ah->handler->goto_offset = ex->body.goto_offset;
}
/* Creates a new lexotic. */
MVMObject * MVM_exception_newlexotic(MVMThreadContext *tc, MVMuint32 offset) {
MVMLexotic *lexotic;
/* Locate handler associated with the specified label. */
MVMStaticFrame *sf = tc->cur_frame->static_info;
MVMFrameHandler *h = NULL;
MVMuint32 i;
for (i = 0; i < sf->body.num_handlers; i++) {
if (sf->body.handlers[i].action == MVM_EX_ACTION_GOTO &&
sf->body.handlers[i].goto_offset == offset) {
h = &sf->body.handlers[i];
break;
}
}
if (h == NULL)
MVM_exception_throw_adhoc(tc, "Label with no handler passed to newlexotic");
/* Allocate lexotic object and set it up. */
lexotic = (MVMLexotic *)MVM_repr_alloc_init(tc, tc->instance->Lexotic);
lexotic->body.handler = h;
lexotic->body.frame = MVM_frame_inc_ref(tc, tc->cur_frame);
return (MVMObject *)lexotic;
}
/* Unwinds to a lexotic captured handler. */
void MVM_exception_gotolexotic(MVMThreadContext *tc, MVMFrameHandler *h, MVMFrame *f) {
if (in_caller_chain(tc, f)) {
LocatedHandler lh;
lh.frame = f;
lh.handler = h;
run_handler(tc, lh, NULL);
}
else {
MVM_exception_throw_adhoc(tc, "Too late to invoke lexotic return");
}
}
/* Panics and shuts down the VM. Don't do this unless it's something quite
* unrecoverable.
* TODO: Some hook for embedders.
*/
MVM_NO_RETURN
void MVM_panic(MVMint32 exitCode, const char *messageFormat, ...) {
va_list args;
va_start(args, messageFormat);
vfprintf(stderr, messageFormat, args);
va_end(args);
fwrite("\n", 1, 1, stderr);
if (crash_on_error)
abort();
else
exit(exitCode);
}
/* Throws an ad-hoc (untyped) exception. */
MVM_NO_RETURN
void MVM_exception_throw_adhoc(MVMThreadContext *tc, const char *messageFormat, ...) {
va_list args;
va_start(args, messageFormat);
MVM_exception_throw_adhoc_va(tc, messageFormat, args);
va_end(args);
}
/* Throws an ad-hoc (untyped) exception. */
MVM_NO_RETURN
void MVM_exception_throw_adhoc_va(MVMThreadContext *tc, const char *messageFormat, va_list args) {
LocatedHandler lh;
/* Create and set up an exception object. */
MVMException *ex = (MVMException *)MVM_repr_alloc_init(tc, tc->instance->boot_types.BOOTException);
MVMROOT(tc, ex, {
char *c_message = malloc(1024);
int bytes = vsnprintf(c_message, 1024, messageFormat, args);
MVMString *message = MVM_string_utf8_decode(tc, tc->instance->VMString, c_message, bytes);
free(c_message);
MVM_ASSIGN_REF(tc, ex, ex->body.message, message);
if (tc->cur_frame) {
ex->body.origin = MVM_frame_inc_ref(tc, tc->cur_frame);
tc->cur_frame->throw_address = *(tc->interp_cur_op);
}
else {
ex->body.origin = NULL;
}
ex->body.category = MVM_EX_CAT_CATCH;
});
/* Try to locate a handler, so long as we're in the interpreter. */
if (tc->interp_cur_op)
lh = search_for_handler_from(tc, tc->cur_frame, MVM_EX_THROW_DYN, ex->body.category);
else
lh.frame = NULL;
/* Do we have a handler to unwind to? */
if (lh.frame == NULL) {
/* No handler. Should we crash on these? */
if (crash_on_error) {
/* Yes, abort. */
vfprintf(stderr, messageFormat, args);
fwrite("\n", 1, 1, stderr);
dump_backtrace(tc);
abort();
}
else {
/* No, just the usual panic. */
panic_unhandled_ex(tc, ex);
}
}
/* Run the handler, which doesn't actually run it but rather sets up the
* interpreter so that when we return to it, we'll be at the handler. */
run_handler(tc, lh, (MVMObject *)ex);
/* Clear an C stack temporaries that code may have pushed before throwing
* the exception. */
MVM_gc_root_temp_pop_all(tc);
/* Jump back into the interpreter. */
longjmp(tc->interp_jump, 1);
}
void MVM_crash_on_error(void) {
crash_on_error = 1;
}