Rework stack overflow handling.
[luajit-2.0.git] / src / lj_err.c
blob7afe1e291eb4d120f6f97b76f4d2cd4e580f6928
1 /*
2 ** Error handling.
3 ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #define lj_err_c
7 #define LUA_CORE
9 #include "lj_obj.h"
10 #include "lj_err.h"
11 #include "lj_debug.h"
12 #include "lj_str.h"
13 #include "lj_func.h"
14 #include "lj_state.h"
15 #include "lj_frame.h"
16 #include "lj_ff.h"
17 #include "lj_trace.h"
18 #include "lj_vm.h"
21 ** LuaJIT can either use internal or external frame unwinding:
23 ** - Internal frame unwinding (INT) is free-standing and doesn't require
24 ** any OS or library support.
26 ** - External frame unwinding (EXT) uses the system-provided unwind handler.
28 ** Pros and Cons:
30 ** - EXT requires unwind tables for *all* functions on the C stack between
31 ** the pcall/catch and the error/throw. This is the default on x64,
32 ** but needs to be manually enabled on x86/PPC for non-C++ code.
34 ** - INT is faster when actually throwing errors (but this happens rarely).
35 ** Setting up error handlers is zero-cost in any case.
37 ** - EXT provides full interoperability with C++ exceptions. You can throw
38 ** Lua errors or C++ exceptions through a mix of Lua frames and C++ frames.
39 ** C++ destructors are called as needed. C++ exceptions caught by pcall
40 ** are converted to the string "C++ exception". Lua errors can be caught
41 ** with catch (...) in C++.
43 ** - INT has only limited support for automatically catching C++ exceptions
44 ** on POSIX systems using DWARF2 stack unwinding. Other systems may use
45 ** the wrapper function feature. Lua errors thrown through C++ frames
46 ** cannot be caught by C++ code and C++ destructors are not run.
48 ** EXT is the default on x64 systems, INT is the default on all other systems.
50 ** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack
51 ** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled
52 ** with -funwind-tables (or -fexceptions). This includes LuaJIT itself (set
53 ** TARGET_CFLAGS), all of your C/Lua binding code, all loadable C modules
54 ** and all C libraries that have callbacks which may be used to call back
55 ** into Lua. C++ code must *not* be compiled with -fno-exceptions.
57 ** EXT cannot be enabled on WIN32 since system exceptions use code-driven SEH.
58 ** EXT is mandatory on WIN64 since the calling convention has an abundance
59 ** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15).
60 ** The POSIX/x64 interpreter only saves r12/r13 for INT (e.g. PS4).
63 #if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL)) && !LJ_NO_UNWIND
64 #define LJ_UNWIND_EXT 1
65 #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS
66 #define LJ_UNWIND_EXT 1
67 #endif
69 /* -- Error messages ------------------------------------------------------ */
71 /* Error message strings. */
72 LJ_DATADEF const char *lj_err_allmsg =
73 #define ERRDEF(name, msg) msg "\0"
74 #include "lj_errmsg.h"
77 /* -- Internal frame unwinding -------------------------------------------- */
79 /* Unwind Lua stack and move error message to new top. */
80 LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
82 lj_func_closeuv(L, top);
83 if (top < L->top-1) {
84 copyTV(L, top, L->top-1);
85 L->top = top+1;
87 lj_state_relimitstack(L);
90 /* Unwind until stop frame. Optionally cleanup frames. */
91 static void *err_unwind(lua_State *L, void *stopcf, int errcode)
93 TValue *frame = L->base-1;
94 void *cf = L->cframe;
95 while (cf) {
96 int32_t nres = cframe_nres(cframe_raw(cf));
97 if (nres < 0) { /* C frame without Lua frame? */
98 TValue *top = restorestack(L, -nres);
99 if (frame < top) { /* Frame reached? */
100 if (errcode) {
101 L->cframe = cframe_prev(cf);
102 L->base = frame+1;
103 unwindstack(L, top);
105 return cf;
108 if (frame <= tvref(L->stack))
109 break;
110 switch (frame_typep(frame)) {
111 case FRAME_LUA: /* Lua frame. */
112 case FRAME_LUAP:
113 frame = frame_prevl(frame);
114 break;
115 case FRAME_C: /* C frame. */
116 #if LJ_HASFFI
117 unwind_c:
118 #endif
119 #if LJ_UNWIND_EXT
120 if (errcode) {
121 L->cframe = cframe_prev(cf);
122 L->base = frame_prevd(frame) + 1;
123 unwindstack(L, frame);
124 } else if (cf != stopcf) {
125 cf = cframe_prev(cf);
126 frame = frame_prevd(frame);
127 break;
129 return NULL; /* Continue unwinding. */
130 #else
131 UNUSED(stopcf);
132 cf = cframe_prev(cf);
133 frame = frame_prevd(frame);
134 break;
135 #endif
136 case FRAME_CP: /* Protected C frame. */
137 if (cframe_canyield(cf)) { /* Resume? */
138 if (errcode) {
139 hook_leave(G(L)); /* Assumes nobody uses coroutines inside hooks. */
140 L->cframe = NULL;
141 L->status = (uint8_t)errcode;
143 return cf;
145 if (errcode) {
146 L->cframe = cframe_prev(cf);
147 L->base = frame_prevd(frame) + 1;
148 unwindstack(L, frame);
150 return cf;
151 case FRAME_CONT: /* Continuation frame. */
152 #if LJ_HASFFI
153 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
154 goto unwind_c;
155 #endif
156 /* fallthrough */
157 case FRAME_VARG: /* Vararg frame. */
158 frame = frame_prevd(frame);
159 break;
160 case FRAME_PCALL: /* FF pcall() frame. */
161 case FRAME_PCALLH: /* FF pcall() frame inside hook. */
162 if (errcode) {
163 if (errcode == LUA_YIELD) {
164 frame = frame_prevd(frame);
165 break;
167 if (frame_typep(frame) == FRAME_PCALL)
168 hook_leave(G(L));
169 L->cframe = cf;
170 L->base = frame_prevd(frame) + 1;
171 unwindstack(L, L->base);
173 return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
176 /* No C frame. */
177 if (errcode) {
178 L->cframe = NULL;
179 L->base = tvref(L->stack)+1;
180 unwindstack(L, L->base);
181 if (G(L)->panic)
182 G(L)->panic(L);
183 exit(EXIT_FAILURE);
185 return L; /* Anything non-NULL will do. */
188 /* -- External frame unwinding -------------------------------------------- */
190 #if defined(__GNUC__) && !LJ_NO_UNWIND && !LJ_ABI_WIN
193 ** We have to use our own definitions instead of the mandatory (!) unwind.h,
194 ** since various OS, distros and compilers mess up the header installation.
197 typedef struct _Unwind_Exception
199 uint64_t exclass;
200 void (*excleanup)(int, struct _Unwind_Exception *);
201 uintptr_t p1, p2;
202 } __attribute__((__aligned__)) _Unwind_Exception;
204 typedef struct _Unwind_Context _Unwind_Context;
206 #define _URC_OK 0
207 #define _URC_FATAL_PHASE1_ERROR 3
208 #define _URC_HANDLER_FOUND 6
209 #define _URC_INSTALL_CONTEXT 7
210 #define _URC_CONTINUE_UNWIND 8
211 #define _URC_FAILURE 9
213 #if !LJ_TARGET_ARM
215 extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
216 extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
217 extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
218 extern void _Unwind_DeleteException(_Unwind_Exception *);
219 extern int _Unwind_RaiseException(_Unwind_Exception *);
221 #define _UA_SEARCH_PHASE 1
222 #define _UA_CLEANUP_PHASE 2
223 #define _UA_HANDLER_FRAME 4
224 #define _UA_FORCE_UNWIND 8
226 #define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */
227 #define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c))
228 #define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff)
229 #define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff))
231 /* DWARF2 personality handler referenced from interpreter .eh_frame. */
232 LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
233 uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
235 void *cf;
236 lua_State *L;
237 if (version != 1)
238 return _URC_FATAL_PHASE1_ERROR;
239 UNUSED(uexclass);
240 cf = (void *)_Unwind_GetCFA(ctx);
241 L = cframe_L(cf);
242 if ((actions & _UA_SEARCH_PHASE)) {
243 #if LJ_UNWIND_EXT
244 if (err_unwind(L, cf, 0) == NULL)
245 return _URC_CONTINUE_UNWIND;
246 #endif
247 if (!LJ_UEXCLASS_CHECK(uexclass)) {
248 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
250 return _URC_HANDLER_FOUND;
252 if ((actions & _UA_CLEANUP_PHASE)) {
253 int errcode;
254 if (LJ_UEXCLASS_CHECK(uexclass)) {
255 errcode = LJ_UEXCLASS_ERRCODE(uexclass);
256 } else {
257 if ((actions & _UA_HANDLER_FRAME))
258 _Unwind_DeleteException(uex);
259 errcode = LUA_ERRRUN;
261 #if LJ_UNWIND_EXT
262 cf = err_unwind(L, cf, errcode);
263 if ((actions & _UA_FORCE_UNWIND)) {
264 return _URC_CONTINUE_UNWIND;
265 } else if (cf) {
266 _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
267 _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ?
268 lj_vm_unwind_ff_eh :
269 lj_vm_unwind_c_eh));
270 return _URC_INSTALL_CONTEXT;
272 #if LJ_TARGET_X86ORX64
273 else if ((actions & _UA_HANDLER_FRAME)) {
274 /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
275 ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
277 _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
278 _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
279 return _URC_INSTALL_CONTEXT;
281 #endif
282 #else
283 /* This is not the proper way to escape from the unwinder. We get away with
284 ** it on non-x64 because the interpreter restores all callee-saved regs.
286 lj_err_throw(L, errcode);
287 #endif
289 return _URC_CONTINUE_UNWIND;
292 #if LJ_UNWIND_EXT
293 static __thread _Unwind_Exception static_uex;
295 /* Raise DWARF2 exception. */
296 static void err_raise_ext(int errcode)
298 static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
299 static_uex.excleanup = NULL;
300 _Unwind_RaiseException(&static_uex);
302 #endif
304 #else
306 extern void _Unwind_DeleteException(void *);
307 extern int __gnu_unwind_frame (void *, _Unwind_Context *);
308 extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
309 extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
311 static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
313 uint32_t v;
314 _Unwind_VRS_Get(ctx, 0, r, 0, &v);
315 return v;
318 static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
320 _Unwind_VRS_Set(ctx, 0, r, 0, &v);
323 #define _US_VIRTUAL_UNWIND_FRAME 0
324 #define _US_UNWIND_FRAME_STARTING 1
325 #define _US_ACTION_MASK 3
326 #define _US_FORCE_UNWIND 8
328 /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
329 LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx)
331 void *cf = (void *)_Unwind_GetGR(ctx, 13);
332 lua_State *L = cframe_L(cf);
333 if ((state & _US_ACTION_MASK) == _US_VIRTUAL_UNWIND_FRAME) {
334 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
335 return _URC_HANDLER_FOUND;
337 if ((state&(_US_ACTION_MASK|_US_FORCE_UNWIND)) == _US_UNWIND_FRAME_STARTING) {
338 _Unwind_DeleteException(ucb);
339 _Unwind_SetGR(ctx, 15, (uint32_t)(void *)lj_err_throw);
340 _Unwind_SetGR(ctx, 0, (uint32_t)L);
341 _Unwind_SetGR(ctx, 1, (uint32_t)LUA_ERRRUN);
342 return _URC_INSTALL_CONTEXT;
344 if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
345 return _URC_FAILURE;
346 return _URC_CONTINUE_UNWIND;
349 #endif
351 #elif LJ_TARGET_X64 && LJ_ABI_WIN
354 ** Someone in Redmond owes me several days of my life. A lot of this is
355 ** undocumented or just plain wrong on MSDN. Some of it can be gathered
356 ** from 3rd party docs or must be found by trial-and-error. They really
357 ** don't want you to write your own language-specific exception handler
358 ** or to interact gracefully with MSVC. :-(
360 ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
361 ** unless you compile your C++ code with /EHa. Unfortunately this means
362 ** catch (...) also catches things like access violations. The use of
363 ** _set_se_translator doesn't really help, because it requires /EHa, too.
366 #define WIN32_LEAN_AND_MEAN
367 #include <windows.h>
369 /* Taken from: http://www.nynaeve.net/?p=99 */
370 typedef struct UndocumentedDispatcherContext {
371 ULONG64 ControlPc;
372 ULONG64 ImageBase;
373 PRUNTIME_FUNCTION FunctionEntry;
374 ULONG64 EstablisherFrame;
375 ULONG64 TargetIp;
376 PCONTEXT ContextRecord;
377 void (*LanguageHandler)(void);
378 PVOID HandlerData;
379 PUNWIND_HISTORY_TABLE HistoryTable;
380 ULONG ScopeIndex;
381 ULONG Fill0;
382 } UndocumentedDispatcherContext;
384 /* Another wild guess. */
385 extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
387 #ifdef MINGW_SDK_INIT
388 /* Workaround for broken MinGW64 declaration. */
389 VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
390 #define RtlUnwindEx RtlUnwindEx_FIXED
391 #endif
393 #define LJ_MSVC_EXCODE ((DWORD)0xe06d7363)
394 #define LJ_GCC_EXCODE ((DWORD)0x20474343)
396 #define LJ_EXCODE ((DWORD)0xe24c4a00)
397 #define LJ_EXCODE_MAKE(c) (LJ_EXCODE | (DWORD)(c))
398 #define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff)
399 #define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff))
401 /* Win64 exception handler for interpreter frame. */
402 LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
403 void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
405 lua_State *L = cframe_L(cf);
406 int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
407 LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
408 if ((rec->ExceptionFlags & 6)) { /* EH_UNWINDING|EH_EXIT_UNWIND */
409 /* Unwind internal frames. */
410 err_unwind(L, cf, errcode);
411 } else {
412 void *cf2 = err_unwind(L, cf, 0);
413 if (cf2) { /* We catch it, so start unwinding the upper frames. */
414 if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
415 rec->ExceptionCode == LJ_GCC_EXCODE) {
416 #if LJ_TARGET_WINDOWS
417 __DestructExceptionObject(rec, 1);
418 #endif
419 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
420 } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
421 /* Don't catch access violations etc. */
422 return ExceptionContinueSearch;
424 /* Unwind the stack and call all handlers for all lower C frames
425 ** (including ourselves) again with EH_UNWINDING set. Then set
426 ** rsp = cf, rax = errcode and jump to the specified target.
428 RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
429 lj_vm_unwind_ff_eh :
430 lj_vm_unwind_c_eh),
431 rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
432 /* RtlUnwindEx should never return. */
435 return ExceptionContinueSearch;
438 /* Raise Windows exception. */
439 static void err_raise_ext(int errcode)
441 RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
444 #endif
446 /* -- Error handling ------------------------------------------------------ */
448 /* Throw error. Find catch frame, unwind stack and continue. */
449 LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
451 global_State *g = G(L);
452 lj_trace_abort(g);
453 setgcrefnull(g->jit_L);
454 L->status = 0;
455 #if LJ_UNWIND_EXT
456 err_raise_ext(errcode);
458 ** A return from this function signals a corrupt C stack that cannot be
459 ** unwound. We have no choice but to call the panic function and exit.
461 ** Usually this is caused by a C function without unwind information.
462 ** This should never happen on x64, but may happen if you've manually
463 ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every*
464 ** non-C++ file with -funwind-tables.
466 if (G(L)->panic)
467 G(L)->panic(L);
468 #else
470 void *cf = err_unwind(L, NULL, errcode);
471 if (cframe_unwind_ff(cf))
472 lj_vm_unwind_ff(cframe_raw(cf));
473 else
474 lj_vm_unwind_c(cframe_raw(cf), errcode);
476 #endif
477 exit(EXIT_FAILURE);
480 /* Return string object for error message. */
481 LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
483 return lj_str_newz(L, err2msg(em));
486 /* Out-of-memory error. */
487 LJ_NOINLINE void lj_err_mem(lua_State *L)
489 if (L->status == LUA_ERRERR+1) /* Don't touch the stack during lua_open. */
490 lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
491 if (curr_funcisL(L)) {
492 L->top = curr_topL(L);
493 if (LJ_UNLIKELY(L->top > tvref(L->maxstack))) {
494 /* The current Lua frame violates the stack. Replace it with a dummy. */
495 L->top = L->base;
496 setframe_gc(L->base - 1, obj2gco(L));
499 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
500 lj_err_throw(L, LUA_ERRMEM);
503 /* Find error function for runtime errors. Requires an extra stack traversal. */
504 static ptrdiff_t finderrfunc(lua_State *L)
506 cTValue *frame = L->base-1, *bot = tvref(L->stack);
507 void *cf = L->cframe;
508 while (frame > bot && cf) {
509 while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */
510 if (frame >= restorestack(L, -cframe_nres(cf)))
511 break;
512 if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */
513 return cframe_errfunc(cf);
514 cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */
515 if (cf == NULL)
516 return 0;
518 switch (frame_typep(frame)) {
519 case FRAME_LUA:
520 case FRAME_LUAP:
521 frame = frame_prevl(frame);
522 break;
523 case FRAME_C:
524 cf = cframe_prev(cf);
525 /* fallthrough */
526 case FRAME_VARG:
527 frame = frame_prevd(frame);
528 break;
529 case FRAME_CONT:
530 #if LJ_HASFFI
531 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
532 cf = cframe_prev(cf);
533 #endif
534 frame = frame_prevd(frame);
535 break;
536 case FRAME_CP:
537 if (cframe_canyield(cf)) return 0;
538 if (cframe_errfunc(cf) >= 0)
539 return cframe_errfunc(cf);
540 cf = cframe_prev(cf);
541 frame = frame_prevd(frame);
542 break;
543 case FRAME_PCALL:
544 case FRAME_PCALLH:
545 if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue))) /* xpcall? */
546 return savestack(L, frame-1); /* Point to xpcall's errorfunc. */
547 return 0;
548 default:
549 lua_assert(0);
550 return 0;
553 return 0;
556 /* Runtime error. */
557 LJ_NOINLINE void LJ_FASTCALL lj_err_run(lua_State *L)
559 ptrdiff_t ef = finderrfunc(L);
560 if (ef) {
561 TValue *errfunc, *top;
562 lj_state_checkstack(L, LUA_MINSTACK * 2); /* Might raise new error. */
563 lj_trace_abort(G(L));
564 errfunc = restorestack(L, ef);
565 top = L->top;
566 if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
567 setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
568 lj_err_throw(L, LUA_ERRERR);
570 L->status = LUA_ERRERR;
571 copyTV(L, top, top-1);
572 copyTV(L, top-1, errfunc);
573 L->top = top+1;
574 lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */
576 lj_err_throw(L, LUA_ERRRUN);
579 /* Stack overflow error. */
580 void LJ_FASTCALL lj_err_stkov(lua_State *L)
582 lj_debug_addloc(L, err2msg(LJ_ERR_STKOV), L->base-1, NULL);
583 lj_err_run(L);
586 /* Formatted runtime error message. */
587 LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
589 const char *msg;
590 va_list argp;
591 va_start(argp, em);
592 if (curr_funcisL(L)) L->top = curr_topL(L);
593 msg = lj_str_pushvf(L, err2msg(em), argp);
594 va_end(argp);
595 lj_debug_addloc(L, msg, L->base-1, NULL);
596 lj_err_run(L);
599 /* Non-vararg variant for better calling conventions. */
600 LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
602 err_msgv(L, em);
605 /* Lexer error. */
606 LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
607 BCLine line, ErrMsg em, va_list argp)
609 char buff[LUA_IDSIZE];
610 const char *msg;
611 lj_debug_shortname(buff, src);
612 msg = lj_str_pushvf(L, err2msg(em), argp);
613 msg = lj_str_pushf(L, "%s:%d: %s", buff, line, msg);
614 if (tok)
615 lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
616 lj_err_throw(L, LUA_ERRSYNTAX);
619 /* Typecheck error for operands. */
620 LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
622 const char *tname = lj_typename(o);
623 const char *opname = err2msg(opm);
624 if (curr_funcisL(L)) {
625 GCproto *pt = curr_proto(L);
626 const BCIns *pc = cframe_Lpc(L) - 1;
627 const char *oname = NULL;
628 const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
629 if (kind)
630 err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
632 err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
635 /* Typecheck error for ordered comparisons. */
636 LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
638 const char *t1 = lj_typename(o1);
639 const char *t2 = lj_typename(o2);
640 err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
641 /* This assumes the two "boolean" entries are commoned by the C compiler. */
644 /* Typecheck error for __call. */
645 LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
647 /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
648 ** L->base still points to the caller. So add a dummy frame with L instead
649 ** of a function. See lua_getstack().
651 const BCIns *pc = cframe_Lpc(L);
652 if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
653 const char *tname = lj_typename(o);
654 setframe_pc(o, pc);
655 setframe_gc(o, obj2gco(L));
656 L->top = L->base = o+1;
657 err_msgv(L, LJ_ERR_BADCALL, tname);
659 lj_err_optype(L, o, LJ_ERR_OPCALL);
662 /* Error in context of caller. */
663 LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
665 TValue *frame = L->base-1;
666 TValue *pframe = NULL;
667 if (frame_islua(frame)) {
668 pframe = frame_prevl(frame);
669 } else if (frame_iscont(frame)) {
670 #if LJ_HASFFI
671 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) {
672 pframe = frame;
673 frame = NULL;
674 } else
675 #endif
677 pframe = frame_prevd(frame);
678 #if LJ_HASFFI
679 /* Remove frame for FFI metamethods. */
680 if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
681 frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
682 L->base = pframe+1;
683 L->top = frame;
684 setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
686 #endif
689 lj_debug_addloc(L, msg, pframe, frame);
690 lj_err_run(L);
693 /* Formatted error in context of caller. */
694 LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
696 const char *msg;
697 va_list argp;
698 va_start(argp, em);
699 msg = lj_str_pushvf(L, err2msg(em), argp);
700 va_end(argp);
701 lj_err_callermsg(L, msg);
704 /* Error in context of caller. */
705 LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
707 lj_err_callermsg(L, err2msg(em));
710 /* Argument error message. */
711 LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
712 const char *msg)
714 const char *fname = "?";
715 const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
716 if (narg < 0 && narg > LUA_REGISTRYINDEX)
717 narg = (int)(L->top - L->base) + narg + 1;
718 if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */
719 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
720 else
721 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
722 lj_err_callermsg(L, msg);
725 /* Formatted argument error. */
726 LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
728 const char *msg;
729 va_list argp;
730 va_start(argp, em);
731 msg = lj_str_pushvf(L, err2msg(em), argp);
732 va_end(argp);
733 err_argmsg(L, narg, msg);
736 /* Argument error. */
737 LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
739 err_argmsg(L, narg, err2msg(em));
742 /* Typecheck error for arguments. */
743 LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
745 const char *tname, *msg;
746 if (narg <= LUA_REGISTRYINDEX) {
747 if (narg >= LUA_GLOBALSINDEX) {
748 tname = lj_obj_itypename[~LJ_TTAB];
749 } else {
750 GCfunc *fn = curr_func(L);
751 int idx = LUA_GLOBALSINDEX - narg;
752 if (idx <= fn->c.nupvalues)
753 tname = lj_typename(&fn->c.upvalue[idx-1]);
754 else
755 tname = lj_obj_typename[0];
757 } else {
758 TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
759 tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
761 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
762 err_argmsg(L, narg, msg);
765 /* Typecheck error for arguments. */
766 LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
768 lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
771 /* -- Public error handling API ------------------------------------------- */
773 LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
775 lua_CFunction old = G(L)->panic;
776 G(L)->panic = panicf;
777 return old;
780 /* Forwarders for the public API (C calling convention and no LJ_NORET). */
781 LUA_API int lua_error(lua_State *L)
783 lj_err_run(L);
784 return 0; /* unreachable */
787 LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
789 err_argmsg(L, narg, msg);
790 return 0; /* unreachable */
793 LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
795 lj_err_argtype(L, narg, xname);
796 return 0; /* unreachable */
799 LUALIB_API void luaL_where(lua_State *L, int level)
801 int size;
802 cTValue *frame = lj_debug_frame(L, level, &size);
803 lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
806 LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
808 const char *msg;
809 va_list argp;
810 va_start(argp, fmt);
811 msg = lj_str_pushvf(L, fmt, argp);
812 va_end(argp);
813 lj_err_callermsg(L, msg);
814 return 0; /* unreachable */