FFI: Use correct PC in FFI metamethod error message.
[luajit-2.0.git] / src / lj_err.c
blob05813cf836ae92cd6761de0668e7b73c8a638d10
1 /*
2 ** Error handling.
3 ** Copyright (C) 2005-2012 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 ** EXT is mandatory on POSIX/x64 since the interpreter doesn't save r12/r13.
63 #if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL))
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 L->cframe = NULL;
140 L->status = (uint8_t)errcode;
142 return cf;
144 if (errcode) {
145 L->cframe = cframe_prev(cf);
146 L->base = frame_prevd(frame) + 1;
147 unwindstack(L, frame);
149 return cf;
150 case FRAME_CONT: /* Continuation frame. */
151 #if LJ_HASFFI
152 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
153 goto unwind_c;
154 #endif
155 case FRAME_VARG: /* Vararg frame. */
156 frame = frame_prevd(frame);
157 break;
158 case FRAME_PCALL: /* FF pcall() frame. */
159 case FRAME_PCALLH: /* FF pcall() frame inside hook. */
160 if (errcode) {
161 if (errcode == LUA_YIELD) {
162 frame = frame_prevd(frame);
163 break;
165 if (frame_typep(frame) == FRAME_PCALL)
166 hook_leave(G(L));
167 L->cframe = cf;
168 L->base = frame_prevd(frame) + 1;
169 unwindstack(L, L->base);
171 return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
174 /* No C frame. */
175 if (errcode) {
176 L->cframe = NULL;
177 L->base = tvref(L->stack)+1;
178 unwindstack(L, L->base);
179 if (G(L)->panic)
180 G(L)->panic(L);
181 exit(EXIT_FAILURE);
183 return L; /* Anything non-NULL will do. */
186 /* -- External frame unwinding -------------------------------------------- */
188 #if defined(__GNUC__) && !defined(LUAJIT_NO_UNWIND)
191 ** We have to use our own definitions instead of the mandatory (!) unwind.h,
192 ** since various OS, distros and compilers mess up the header installation.
195 typedef struct _Unwind_Exception
197 uint64_t exclass;
198 void (*excleanup)(int, struct _Unwind_Exception);
199 uintptr_t p1, p2;
200 } __attribute__((__aligned__)) _Unwind_Exception;
202 typedef struct _Unwind_Context _Unwind_Context;
204 #define _URC_OK 0
205 #define _URC_FATAL_PHASE1_ERROR 3
206 #define _URC_HANDLER_FOUND 6
207 #define _URC_INSTALL_CONTEXT 7
208 #define _URC_CONTINUE_UNWIND 8
209 #define _URC_FAILURE 9
211 #if !LJ_TARGET_ARM
213 extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
214 extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
215 extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
216 extern void _Unwind_DeleteException(_Unwind_Exception *);
217 extern int _Unwind_RaiseException(_Unwind_Exception *);
219 #define _UA_SEARCH_PHASE 1
220 #define _UA_CLEANUP_PHASE 2
221 #define _UA_HANDLER_FRAME 4
222 #define _UA_FORCE_UNWIND 8
224 #define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */
225 #define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c))
226 #define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff)
227 #define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff))
229 /* DWARF2 personality handler referenced from interpreter .eh_frame. */
230 LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
231 uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
233 void *cf;
234 lua_State *L;
235 if (version != 1)
236 return _URC_FATAL_PHASE1_ERROR;
237 UNUSED(uexclass);
238 cf = (void *)_Unwind_GetCFA(ctx);
239 L = cframe_L(cf);
240 if ((actions & _UA_SEARCH_PHASE)) {
241 #if LJ_UNWIND_EXT
242 if (err_unwind(L, cf, 0) == NULL)
243 return _URC_CONTINUE_UNWIND;
244 #endif
245 if (!LJ_UEXCLASS_CHECK(uexclass)) {
246 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
248 return _URC_HANDLER_FOUND;
250 if ((actions & _UA_CLEANUP_PHASE)) {
251 int errcode;
252 if (LJ_UEXCLASS_CHECK(uexclass)) {
253 errcode = LJ_UEXCLASS_ERRCODE(uexclass);
254 } else {
255 if ((actions & _UA_HANDLER_FRAME))
256 _Unwind_DeleteException(uex);
257 errcode = LUA_ERRRUN;
259 #if LJ_UNWIND_EXT
260 cf = err_unwind(L, cf, errcode);
261 if ((actions & _UA_FORCE_UNWIND)) {
262 return _URC_CONTINUE_UNWIND;
263 } else if (cf) {
264 _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
265 _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ?
266 lj_vm_unwind_ff_eh :
267 lj_vm_unwind_c_eh));
268 return _URC_INSTALL_CONTEXT;
270 #if LJ_TARGET_X86ORX64
271 else if ((actions & _UA_HANDLER_FRAME)) {
272 /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
273 ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
275 _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
276 _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
277 return _URC_INSTALL_CONTEXT;
279 #endif
280 #else
281 /* This is not the proper way to escape from the unwinder. We get away with
282 ** it on non-x64 because the interpreter restores all callee-saved regs.
284 lj_err_throw(L, errcode);
285 #endif
287 return _URC_CONTINUE_UNWIND;
290 #if LJ_UNWIND_EXT
291 #if LJ_TARGET_OSX || defined(__OpenBSD__)
292 /* Sorry, no thread safety for OSX. Complain to Apple, not me. */
293 static _Unwind_Exception static_uex;
294 #else
295 static __thread _Unwind_Exception static_uex;
296 #endif
298 /* Raise DWARF2 exception. */
299 static void err_raise_ext(int errcode)
301 static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
302 static_uex.excleanup = NULL;
303 _Unwind_RaiseException(&static_uex);
305 #endif
307 #else
309 extern void _Unwind_DeleteException(void *);
310 extern int __gnu_unwind_frame (void *, _Unwind_Context *);
311 extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
312 extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
314 static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
316 uint32_t v;
317 _Unwind_VRS_Get(ctx, 0, r, 0, &v);
318 return v;
321 static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
323 _Unwind_VRS_Set(ctx, 0, r, 0, &v);
326 #define _US_VIRTUAL_UNWIND_FRAME 0
327 #define _US_UNWIND_FRAME_STARTING 1
328 #define _US_ACTION_MASK 3
329 #define _US_FORCE_UNWIND 8
331 /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
332 LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx)
334 void *cf = (void *)_Unwind_GetGR(ctx, 13);
335 lua_State *L = cframe_L(cf);
336 if ((state & _US_ACTION_MASK) == _US_VIRTUAL_UNWIND_FRAME) {
337 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
338 return _URC_HANDLER_FOUND;
340 if ((state&(_US_ACTION_MASK|_US_FORCE_UNWIND)) == _US_UNWIND_FRAME_STARTING) {
341 _Unwind_DeleteException(ucb);
342 _Unwind_SetGR(ctx, 15, (uint32_t)(void *)lj_err_throw);
343 _Unwind_SetGR(ctx, 0, (uint32_t)L);
344 _Unwind_SetGR(ctx, 1, (uint32_t)LUA_ERRRUN);
345 return _URC_INSTALL_CONTEXT;
347 if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
348 return _URC_FAILURE;
349 return _URC_CONTINUE_UNWIND;
352 #endif
354 #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS
357 ** Someone in Redmond owes me several days of my life. A lot of this is
358 ** undocumented or just plain wrong on MSDN. Some of it can be gathered
359 ** from 3rd party docs or must be found by trial-and-error. They really
360 ** don't want you to write your own language-specific exception handler
361 ** or to interact gracefully with MSVC. :-(
363 ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
364 ** unless you compile your C++ code with /EHa. Unfortunately this means
365 ** catch (...) also catches things like access violations. The use of
366 ** _set_se_translator doesn't really help, because it requires /EHa, too.
369 #define WIN32_LEAN_AND_MEAN
370 #include <windows.h>
372 /* Taken from: http://www.nynaeve.net/?p=99 */
373 typedef struct UndocumentedDispatcherContext {
374 ULONG64 ControlPc;
375 ULONG64 ImageBase;
376 PRUNTIME_FUNCTION FunctionEntry;
377 ULONG64 EstablisherFrame;
378 ULONG64 TargetIp;
379 PCONTEXT ContextRecord;
380 PEXCEPTION_ROUTINE LanguageHandler;
381 PVOID HandlerData;
382 PUNWIND_HISTORY_TABLE HistoryTable;
383 ULONG ScopeIndex;
384 ULONG Fill0;
385 } UndocumentedDispatcherContext;
387 #ifdef _MSC_VER
388 /* Another wild guess. */
389 extern __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
390 #endif
392 #define LJ_MSVC_EXCODE ((DWORD)0xe06d7363)
394 #define LJ_EXCODE ((DWORD)0xe24c4a00)
395 #define LJ_EXCODE_MAKE(c) (LJ_EXCODE | (DWORD)(c))
396 #define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff)
397 #define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff))
399 /* Win64 exception handler for interpreter frame. */
400 LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
401 void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
403 lua_State *L = cframe_L(cf);
404 int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
405 LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
406 if ((rec->ExceptionFlags & 6)) { /* EH_UNWINDING|EH_EXIT_UNWIND */
407 /* Unwind internal frames. */
408 err_unwind(L, cf, errcode);
409 } else {
410 void *cf2 = err_unwind(L, cf, 0);
411 if (cf2) { /* We catch it, so start unwinding the upper frames. */
412 if (rec->ExceptionCode == LJ_MSVC_EXCODE) {
413 #ifdef _MSC_VER
414 __DestructExceptionObject(rec, 1);
415 #endif
416 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
417 } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
418 /* Don't catch access violations etc. */
419 return ExceptionContinueSearch;
421 /* Unwind the stack and call all handlers for all lower C frames
422 ** (including ourselves) again with EH_UNWINDING set. Then set
423 ** rsp = cf, rax = errcode and jump to the specified target.
425 RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
426 lj_vm_unwind_ff_eh :
427 lj_vm_unwind_c_eh),
428 rec, (void *)errcode, ctx, dispatch->HistoryTable);
429 /* RtlUnwindEx should never return. */
432 return ExceptionContinueSearch;
435 /* Raise Windows exception. */
436 static void err_raise_ext(int errcode)
438 RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
441 #endif
443 /* -- Error handling ------------------------------------------------------ */
445 /* Throw error. Find catch frame, unwind stack and continue. */
446 LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
448 global_State *g = G(L);
449 lj_trace_abort(g);
450 setgcrefnull(g->jit_L);
451 L->status = 0;
452 #if LJ_UNWIND_EXT
453 err_raise_ext(errcode);
455 ** A return from this function signals a corrupt C stack that cannot be
456 ** unwound. We have no choice but to call the panic function and exit.
458 ** Usually this is caused by a C function without unwind information.
459 ** This should never happen on x64, but may happen if you've manually
460 ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every*
461 ** non-C++ file with -funwind-tables.
463 if (G(L)->panic)
464 G(L)->panic(L);
465 #else
467 void *cf = err_unwind(L, NULL, errcode);
468 if (cframe_unwind_ff(cf))
469 lj_vm_unwind_ff(cframe_raw(cf));
470 else
471 lj_vm_unwind_c(cframe_raw(cf), errcode);
473 #endif
474 exit(EXIT_FAILURE);
477 /* Return string object for error message. */
478 LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
480 return lj_str_newz(L, err2msg(em));
483 /* Out-of-memory error. */
484 LJ_NOINLINE void lj_err_mem(lua_State *L)
486 if (L->status == LUA_ERRERR+1) /* Don't touch the stack during lua_open. */
487 lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
488 L->top = L->base;
489 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
490 lj_err_throw(L, LUA_ERRMEM);
493 /* Find error function for runtime errors. Requires an extra stack traversal. */
494 static ptrdiff_t finderrfunc(lua_State *L)
496 cTValue *frame = L->base-1, *bot = tvref(L->stack);
497 void *cf = L->cframe;
498 while (frame > bot) {
499 lua_assert(cf != NULL);
500 while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */
501 if (frame >= restorestack(L, -cframe_nres(cf)))
502 break;
503 if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */
504 return cframe_errfunc(cf);
505 cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */
506 if (cf == NULL)
507 return 0;
509 switch (frame_typep(frame)) {
510 case FRAME_LUA:
511 case FRAME_LUAP:
512 frame = frame_prevl(frame);
513 break;
514 case FRAME_C:
515 cf = cframe_prev(cf);
516 /* fallthrough */
517 case FRAME_CONT:
518 #if LJ_HASFFI
519 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
520 cf = cframe_prev(cf);
521 #endif
522 case FRAME_VARG:
523 frame = frame_prevd(frame);
524 break;
525 case FRAME_CP:
526 if (cframe_canyield(cf)) return 0;
527 if (cframe_errfunc(cf) >= 0)
528 return cframe_errfunc(cf);
529 frame = frame_prevd(frame);
530 break;
531 case FRAME_PCALL:
532 case FRAME_PCALLH:
533 if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue))) /* xpcall? */
534 return savestack(L, frame-1); /* Point to xpcall's errorfunc. */
535 return 0;
536 default:
537 lua_assert(0);
538 return 0;
541 return 0;
544 /* Runtime error. */
545 LJ_NOINLINE void lj_err_run(lua_State *L)
547 ptrdiff_t ef = finderrfunc(L);
548 if (ef) {
549 TValue *errfunc = restorestack(L, ef);
550 TValue *top = L->top;
551 lj_trace_abort(G(L));
552 if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
553 setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
554 lj_err_throw(L, LUA_ERRERR);
556 L->status = LUA_ERRERR;
557 copyTV(L, top, top-1);
558 copyTV(L, top-1, errfunc);
559 L->top = top+1;
560 lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */
562 lj_err_throw(L, LUA_ERRRUN);
565 /* Formatted runtime error message. */
566 LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
568 const char *msg;
569 va_list argp;
570 va_start(argp, em);
571 if (curr_funcisL(L)) L->top = curr_topL(L);
572 msg = lj_str_pushvf(L, err2msg(em), argp);
573 va_end(argp);
574 lj_debug_addloc(L, msg, L->base-1, NULL);
575 lj_err_run(L);
578 /* Non-vararg variant for better calling conventions. */
579 LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
581 err_msgv(L, em);
584 /* Lexer error. */
585 LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
586 BCLine line, ErrMsg em, va_list argp)
588 char buff[LUA_IDSIZE];
589 const char *msg;
590 lj_debug_shortname(buff, src);
591 msg = lj_str_pushvf(L, err2msg(em), argp);
592 msg = lj_str_pushf(L, "%s:%d: %s", buff, line, msg);
593 if (tok)
594 lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
595 lj_err_throw(L, LUA_ERRSYNTAX);
598 /* Typecheck error for operands. */
599 LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
601 const char *tname = typename(o);
602 const char *opname = err2msg(opm);
603 if (curr_funcisL(L)) {
604 GCproto *pt = curr_proto(L);
605 const BCIns *pc = cframe_Lpc(L) - 1;
606 const char *oname = NULL;
607 const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
608 if (kind)
609 err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
611 err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
614 /* Typecheck error for ordered comparisons. */
615 LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
617 const char *t1 = typename(o1);
618 const char *t2 = typename(o2);
619 err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
620 /* This assumes the two "boolean" entries are commoned by the C compiler. */
623 /* Typecheck error for __call. */
624 LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
626 /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
627 ** L->base still points to the caller. So add a dummy frame with L instead
628 ** of a function. See lua_getstack().
630 const BCIns *pc = cframe_Lpc(L);
631 if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
632 const char *tname = typename(o);
633 setframe_pc(o, pc);
634 setframe_gc(o, obj2gco(L));
635 L->top = L->base = o+1;
636 err_msgv(L, LJ_ERR_BADCALL, tname);
638 lj_err_optype(L, o, LJ_ERR_OPCALL);
641 /* Error in context of caller. */
642 LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
644 TValue *frame = L->base-1;
645 TValue *pframe = NULL;
646 if (frame_islua(frame)) {
647 pframe = frame_prevl(frame);
648 } else if (frame_iscont(frame)) {
649 #if LJ_HASFFI
650 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) {
651 pframe = frame;
652 frame = NULL;
653 } else
654 #endif
656 pframe = frame_prevd(frame);
657 #if LJ_HASFFI
658 /* Remove frame for FFI metamethods. */
659 if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
660 frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
661 L->base = pframe+1;
662 L->top = frame;
663 setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
665 #endif
668 lj_debug_addloc(L, msg, pframe, frame);
669 lj_err_run(L);
672 /* Formatted error in context of caller. */
673 LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
675 const char *msg;
676 va_list argp;
677 va_start(argp, em);
678 msg = lj_str_pushvf(L, err2msg(em), argp);
679 va_end(argp);
680 lj_err_callermsg(L, msg);
683 /* Error in context of caller. */
684 LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
686 lj_err_callermsg(L, err2msg(em));
689 /* Argument error message. */
690 LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
691 const char *msg)
693 const char *fname = "?";
694 const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
695 if (narg < 0 && narg > LUA_REGISTRYINDEX)
696 narg = (int)(L->top - L->base) + narg + 1;
697 if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */
698 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
699 else
700 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
701 lj_err_callermsg(L, msg);
704 /* Formatted argument error. */
705 LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
707 const char *msg;
708 va_list argp;
709 va_start(argp, em);
710 msg = lj_str_pushvf(L, err2msg(em), argp);
711 va_end(argp);
712 err_argmsg(L, narg, msg);
715 /* Argument error. */
716 LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
718 err_argmsg(L, narg, err2msg(em));
721 /* Typecheck error for arguments. */
722 LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
724 TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
725 const char *tname = o < L->top ? typename(o) : lj_obj_typename[0];
726 const char *msg = lj_str_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
727 err_argmsg(L, narg, msg);
730 /* Typecheck error for arguments. */
731 LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
733 lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
736 /* -- Public error handling API ------------------------------------------- */
738 LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
740 lua_CFunction old = G(L)->panic;
741 G(L)->panic = panicf;
742 return old;
745 /* Forwarders for the public API (C calling convention and no LJ_NORET). */
746 LUA_API int lua_error(lua_State *L)
748 lj_err_run(L);
749 return 0; /* unreachable */
752 LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
754 err_argmsg(L, narg, msg);
755 return 0; /* unreachable */
758 LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
760 lj_err_argtype(L, narg, xname);
761 return 0; /* unreachable */
764 LUALIB_API void luaL_where(lua_State *L, int level)
766 int size;
767 cTValue *frame = lj_debug_frame(L, level, &size);
768 lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
771 LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
773 const char *msg;
774 va_list argp;
775 va_start(argp, fmt);
776 msg = lj_str_pushvf(L, fmt, argp);
777 va_end(argp);
778 lj_err_callermsg(L, msg);
779 return 0; /* unreachable */