1 /*
2 ** Error handling.
3 ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4 */
5 
6 #define lj_err_c
7 #define LUA_CORE
8 
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"
19 
20 /*
21 ** LuaJIT can either use internal or external frame unwinding:
22 **
23 ** - Internal frame unwinding (INT) is free-standing and doesn't require
24 **   any OS or library support.
25 **
26 ** - External frame unwinding (EXT) uses the system-provided unwind handler.
27 **
28 ** Pros and Cons:
29 **
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.
33 **
34 ** - INT is faster when actually throwing errors (but this happens rarely).
35 **   Setting up error handlers is zero-cost in any case.
36 **
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++.
42 **
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.
47 **
48 ** EXT is the default on x64 systems, INT is the default on all other systems.
49 **
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.
56 **
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.
61 */
62 
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
68 
69 /* -- Error messages ------------------------------------------------------ */
70 
71 /* Error message strings. */
72 LJ_DATADEF const char *lj_err_allmsg =
73 #define ERRDEF(name, msg)	msg "\0"
74 #include "lj_errmsg.h"
75 ;
76 
77 /* -- Internal frame unwinding -------------------------------------------- */
78 
79 /* Unwind Lua stack and move error message to new top. */
unwindstack(lua_State * L,TValue * top)80 LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
81 {
82   lj_func_closeuv(L, top);
83   if (top < L->top-1) {
84     copyTV(L, top, L->top-1);
85     L->top = top+1;
86   }
87   lj_state_relimitstack(L);
88 }
89 
90 /* Unwind until stop frame. Optionally cleanup frames. */
err_unwind(lua_State * L,void * stopcf,int errcode)91 static void *err_unwind(lua_State *L, void *stopcf, int errcode)
92 {
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);
104 	}
105 	return cf;
106       }
107     }
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;
128       }
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;
142 	}
143 	return cf;
144       }
145       if (errcode) {
146 	L->cframe = cframe_prev(cf);
147 	L->base = frame_prevd(frame) + 1;
148 	unwindstack(L, frame);
149       }
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     case FRAME_VARG:  /* Vararg frame. */
157       frame = frame_prevd(frame);
158       break;
159     case FRAME_PCALL:  /* FF pcall() frame. */
160     case FRAME_PCALLH:  /* FF pcall() frame inside hook. */
161       if (errcode) {
162 	if (errcode == LUA_YIELD) {
163 	  frame = frame_prevd(frame);
164 	  break;
165 	}
166 	if (frame_typep(frame) == FRAME_PCALL)
167 	  hook_leave(G(L));
168 	L->cframe = cf;
169 	L->base = frame_prevd(frame) + 1;
170 	unwindstack(L, L->base);
171       }
172       return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
173     }
174   }
175   /* No C frame. */
176   if (errcode) {
177     L->cframe = NULL;
178     L->base = tvref(L->stack)+1;
179     unwindstack(L, L->base);
180     if (G(L)->panic)
181       G(L)->panic(L);
182     exit(EXIT_FAILURE);
183   }
184   return L;  /* Anything non-NULL will do. */
185 }
186 
187 /* -- External frame unwinding -------------------------------------------- */
188 
189 #if defined(__GNUC__) && !LJ_NO_UNWIND && !LJ_TARGET_WINDOWS
190 
191 /*
192 ** We have to use our own definitions instead of the mandatory (!) unwind.h,
193 ** since various OS, distros and compilers mess up the header installation.
194 */
195 
196 typedef struct _Unwind_Exception
197 {
198   uint64_t exclass;
199   void (*excleanup)(int, struct _Unwind_Exception *);
200   uintptr_t p1, p2;
201 } __attribute__((__aligned__)) _Unwind_Exception;
202 
203 typedef struct _Unwind_Context _Unwind_Context;
204 
205 #define _URC_OK			0
206 #define _URC_FATAL_PHASE1_ERROR	3
207 #define _URC_HANDLER_FOUND	6
208 #define _URC_INSTALL_CONTEXT	7
209 #define _URC_CONTINUE_UNWIND	8
210 #define _URC_FAILURE		9
211 
212 #if !LJ_TARGET_ARM
213 
214 extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
215 extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
216 extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
217 extern void _Unwind_DeleteException(_Unwind_Exception *);
218 extern int _Unwind_RaiseException(_Unwind_Exception *);
219 
220 #define _UA_SEARCH_PHASE	1
221 #define _UA_CLEANUP_PHASE	2
222 #define _UA_HANDLER_FRAME	4
223 #define _UA_FORCE_UNWIND	8
224 
225 #define LJ_UEXCLASS		0x4c55414a49543200ULL	/* LUAJIT2\0 */
226 #define LJ_UEXCLASS_MAKE(c)	(LJ_UEXCLASS | (uint64_t)(c))
227 #define LJ_UEXCLASS_CHECK(cl)	(((cl) ^ LJ_UEXCLASS) <= 0xff)
228 #define LJ_UEXCLASS_ERRCODE(cl)	((int)((cl) & 0xff))
229 
230 /* DWARF2 personality handler referenced from interpreter .eh_frame. */
lj_err_unwind_dwarf(int version,int actions,uint64_t uexclass,_Unwind_Exception * uex,_Unwind_Context * ctx)231 LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
232   uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
233 {
234   void *cf;
235   lua_State *L;
236   if (version != 1)
237     return _URC_FATAL_PHASE1_ERROR;
238   UNUSED(uexclass);
239   cf = (void *)_Unwind_GetCFA(ctx);
240   L = cframe_L(cf);
241   if ((actions & _UA_SEARCH_PHASE)) {
242 #if LJ_UNWIND_EXT
243     if (err_unwind(L, cf, 0) == NULL)
244       return _URC_CONTINUE_UNWIND;
245 #endif
246     if (!LJ_UEXCLASS_CHECK(uexclass)) {
247       setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
248     }
249     return _URC_HANDLER_FOUND;
250   }
251   if ((actions & _UA_CLEANUP_PHASE)) {
252     int errcode;
253     if (LJ_UEXCLASS_CHECK(uexclass)) {
254       errcode = LJ_UEXCLASS_ERRCODE(uexclass);
255     } else {
256       if ((actions & _UA_HANDLER_FRAME))
257 	_Unwind_DeleteException(uex);
258       errcode = LUA_ERRRUN;
259     }
260 #if LJ_UNWIND_EXT
261     cf = err_unwind(L, cf, errcode);
262     if ((actions & _UA_FORCE_UNWIND)) {
263       return _URC_CONTINUE_UNWIND;
264     } else if (cf) {
265       _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
266       _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ?
267 				     lj_vm_unwind_ff_eh :
268 				     lj_vm_unwind_c_eh));
269       return _URC_INSTALL_CONTEXT;
270     }
271 #if LJ_TARGET_X86ORX64
272     else if ((actions & _UA_HANDLER_FRAME)) {
273       /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
274       ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
275       */
276       _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
277       _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
278       return _URC_INSTALL_CONTEXT;
279     }
280 #endif
281 #else
282     /* This is not the proper way to escape from the unwinder. We get away with
283     ** it on non-x64 because the interpreter restores all callee-saved regs.
284     */
285     lj_err_throw(L, errcode);
286 #endif
287   }
288   return _URC_CONTINUE_UNWIND;
289 }
290 
291 #if LJ_UNWIND_EXT
292 #if LJ_TARGET_OSX || defined(__OpenBSD__)
293 /* Sorry, no thread safety for OSX. Complain to Apple, not me. */
294 static _Unwind_Exception static_uex;
295 #else
296 static __thread _Unwind_Exception static_uex;
297 #endif
298 
299 /* Raise DWARF2 exception. */
err_raise_ext(int errcode)300 static void err_raise_ext(int errcode)
301 {
302   static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
303   static_uex.excleanup = NULL;
304   _Unwind_RaiseException(&static_uex);
305 }
306 #endif
307 
308 #else
309 
310 extern void _Unwind_DeleteException(void *);
311 extern int __gnu_unwind_frame (void *, _Unwind_Context *);
312 extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
313 extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
314 
_Unwind_GetGR(_Unwind_Context * ctx,int r)315 static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
316 {
317   uint32_t v;
318   _Unwind_VRS_Get(ctx, 0, r, 0, &v);
319   return v;
320 }
321 
_Unwind_SetGR(_Unwind_Context * ctx,int r,uint32_t v)322 static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
323 {
324   _Unwind_VRS_Set(ctx, 0, r, 0, &v);
325 }
326 
327 #define _US_VIRTUAL_UNWIND_FRAME	0
328 #define _US_UNWIND_FRAME_STARTING	1
329 #define _US_ACTION_MASK			3
330 #define _US_FORCE_UNWIND		8
331 
332 /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
lj_err_unwind_arm(int state,void * ucb,_Unwind_Context * ctx)333 LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx)
334 {
335   void *cf = (void *)_Unwind_GetGR(ctx, 13);
336   lua_State *L = cframe_L(cf);
337   if ((state & _US_ACTION_MASK) == _US_VIRTUAL_UNWIND_FRAME) {
338     setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
339     return _URC_HANDLER_FOUND;
340   }
341   if ((state&(_US_ACTION_MASK|_US_FORCE_UNWIND)) == _US_UNWIND_FRAME_STARTING) {
342     _Unwind_DeleteException(ucb);
343     _Unwind_SetGR(ctx, 15, (uint32_t)(void *)lj_err_throw);
344     _Unwind_SetGR(ctx, 0, (uint32_t)L);
345     _Unwind_SetGR(ctx, 1, (uint32_t)LUA_ERRRUN);
346     return _URC_INSTALL_CONTEXT;
347   }
348   if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
349     return _URC_FAILURE;
350   return _URC_CONTINUE_UNWIND;
351 }
352 
353 #endif
354 
355 #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS
356 
357 /*
358 ** Someone in Redmond owes me several days of my life. A lot of this is
359 ** undocumented or just plain wrong on MSDN. Some of it can be gathered
360 ** from 3rd party docs or must be found by trial-and-error. They really
361 ** don't want you to write your own language-specific exception handler
362 ** or to interact gracefully with MSVC. :-(
363 **
364 ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
365 ** unless you compile your C++ code with /EHa. Unfortunately this means
366 ** catch (...) also catches things like access violations. The use of
367 ** _set_se_translator doesn't really help, because it requires /EHa, too.
368 */
369 
370 #define WIN32_LEAN_AND_MEAN
371 #include <windows.h>
372 
373 /* Taken from: http://www.nynaeve.net/?p=99 */
374 typedef struct UndocumentedDispatcherContext {
375   ULONG64 ControlPc;
376   ULONG64 ImageBase;
377   PRUNTIME_FUNCTION FunctionEntry;
378   ULONG64 EstablisherFrame;
379   ULONG64 TargetIp;
380   PCONTEXT ContextRecord;
381   PEXCEPTION_ROUTINE LanguageHandler;
382   PVOID HandlerData;
383   PUNWIND_HISTORY_TABLE HistoryTable;
384   ULONG ScopeIndex;
385   ULONG Fill0;
386 } UndocumentedDispatcherContext;
387 
388 /* Another wild guess. */
389 extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
390 
391 #ifdef MINGW_SDK_INIT
392 /* Workaround for broken MinGW64 declaration. */
393 VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
394 #define RtlUnwindEx RtlUnwindEx_FIXED
395 #endif
396 
397 #define LJ_MSVC_EXCODE		((DWORD)0xe06d7363)
398 #define LJ_GCC_EXCODE		((DWORD)0x20474343)
399 
400 #define LJ_EXCODE		((DWORD)0xe24c4a00)
401 #define LJ_EXCODE_MAKE(c)	(LJ_EXCODE | (DWORD)(c))
402 #define LJ_EXCODE_CHECK(cl)	(((cl) ^ LJ_EXCODE) <= 0xff)
403 #define LJ_EXCODE_ERRCODE(cl)	((int)((cl) & 0xff))
404 
405 /* Win64 exception handler for interpreter frame. */
lj_err_unwind_win64(EXCEPTION_RECORD * rec,void * cf,CONTEXT * ctx,UndocumentedDispatcherContext * dispatch)406 LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
407   void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
408 {
409   lua_State *L = cframe_L(cf);
410   int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
411 		LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
412   if ((rec->ExceptionFlags & 6)) {  /* EH_UNWINDING|EH_EXIT_UNWIND */
413     /* Unwind internal frames. */
414     err_unwind(L, cf, errcode);
415   } else {
416     void *cf2 = err_unwind(L, cf, 0);
417     if (cf2) {  /* We catch it, so start unwinding the upper frames. */
418       if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
419 	  rec->ExceptionCode == LJ_GCC_EXCODE) {
420 	__DestructExceptionObject(rec, 1);
421 	setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
422       } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
423 	/* Don't catch access violations etc. */
424 	return ExceptionContinueSearch;
425       }
426       /* Unwind the stack and call all handlers for all lower C frames
427       ** (including ourselves) again with EH_UNWINDING set. Then set
428       ** rsp = cf, rax = errcode and jump to the specified target.
429       */
430       RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
431 			       lj_vm_unwind_ff_eh :
432 			       lj_vm_unwind_c_eh),
433 		  rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
434       /* RtlUnwindEx should never return. */
435     }
436   }
437   return ExceptionContinueSearch;
438 }
439 
440 /* Raise Windows exception. */
err_raise_ext(int errcode)441 static void err_raise_ext(int errcode)
442 {
443   RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
444 }
445 
446 #endif
447 
448 /* -- Error handling ------------------------------------------------------ */
449 
450 /* Throw error. Find catch frame, unwind stack and continue. */
lj_err_throw(lua_State * L,int errcode)451 LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
452 {
453   global_State *g = G(L);
454   lj_trace_abort(g);
455   setgcrefnull(g->jit_L);
456   L->status = 0;
457 #if LJ_UNWIND_EXT
458   err_raise_ext(errcode);
459   /*
460   ** A return from this function signals a corrupt C stack that cannot be
461   ** unwound. We have no choice but to call the panic function and exit.
462   **
463   ** Usually this is caused by a C function without unwind information.
464   ** This should never happen on x64, but may happen if you've manually
465   ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every*
466   ** non-C++ file with -funwind-tables.
467   */
468   if (G(L)->panic)
469     G(L)->panic(L);
470 #else
471   {
472     void *cf = err_unwind(L, NULL, errcode);
473     if (cframe_unwind_ff(cf))
474       lj_vm_unwind_ff(cframe_raw(cf));
475     else
476       lj_vm_unwind_c(cframe_raw(cf), errcode);
477   }
478 #endif
479   exit(EXIT_FAILURE);
480 }
481 
482 /* Return string object for error message. */
lj_err_str(lua_State * L,ErrMsg em)483 LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
484 {
485   return lj_str_newz(L, err2msg(em));
486 }
487 
488 /* Out-of-memory error. */
lj_err_mem(lua_State * L)489 LJ_NOINLINE void lj_err_mem(lua_State *L)
490 {
491   if (L->status == LUA_ERRERR+1)  /* Don't touch the stack during lua_open. */
492     lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
493   setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
494   lj_err_throw(L, LUA_ERRMEM);
495 }
496 
497 /* Find error function for runtime errors. Requires an extra stack traversal. */
finderrfunc(lua_State * L)498 static ptrdiff_t finderrfunc(lua_State *L)
499 {
500   cTValue *frame = L->base-1, *bot = tvref(L->stack);
501   void *cf = L->cframe;
502   while (frame > bot) {
503     lua_assert(cf != NULL);
504     while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */
505       if (frame >= restorestack(L, -cframe_nres(cf)))
506 	break;
507       if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */
508 	return cframe_errfunc(cf);
509       cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */
510       if (cf == NULL)
511 	return 0;
512     }
513     switch (frame_typep(frame)) {
514     case FRAME_LUA:
515     case FRAME_LUAP:
516       frame = frame_prevl(frame);
517       break;
518     case FRAME_C:
519       cf = cframe_prev(cf);
520       /* fallthrough */
521     case FRAME_CONT:
522 #if LJ_HASFFI
523       if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
524 	cf = cframe_prev(cf);
525 #endif
526     case FRAME_VARG:
527       frame = frame_prevd(frame);
528       break;
529     case FRAME_CP:
530       if (cframe_canyield(cf)) return 0;
531       if (cframe_errfunc(cf) >= 0)
532 	return cframe_errfunc(cf);
533       frame = frame_prevd(frame);
534       break;
535     case FRAME_PCALL:
536     case FRAME_PCALLH:
537       if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue)))  /* xpcall? */
538 	return savestack(L, frame-1);  /* Point to xpcall's errorfunc. */
539       return 0;
540     default:
541       lua_assert(0);
542       return 0;
543     }
544   }
545   return 0;
546 }
547 
548 /* Runtime error. */
lj_err_run(lua_State * L)549 LJ_NOINLINE void lj_err_run(lua_State *L)
550 {
551   ptrdiff_t ef = finderrfunc(L);
552   if (ef) {
553     TValue *errfunc = restorestack(L, ef);
554     TValue *top = L->top;
555     lj_trace_abort(G(L));
556     if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
557       setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
558       lj_err_throw(L, LUA_ERRERR);
559     }
560     L->status = LUA_ERRERR;
561     copyTV(L, top, top-1);
562     copyTV(L, top-1, errfunc);
563     L->top = top+1;
564     lj_vm_call(L, top, 1+1);  /* Stack: |errfunc|msg| -> |msg| */
565   }
566   lj_err_throw(L, LUA_ERRRUN);
567 }
568 
569 /* Formatted runtime error message. */
err_msgv(lua_State * L,ErrMsg em,...)570 LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
571 {
572   const char *msg;
573   va_list argp;
574   va_start(argp, em);
575   if (curr_funcisL(L)) L->top = curr_topL(L);
576   msg = lj_str_pushvf(L, err2msg(em), argp);
577   va_end(argp);
578   lj_debug_addloc(L, msg, L->base-1, NULL);
579   lj_err_run(L);
580 }
581 
582 /* Non-vararg variant for better calling conventions. */
lj_err_msg(lua_State * L,ErrMsg em)583 LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
584 {
585   err_msgv(L, em);
586 }
587 
588 /* Lexer error. */
lj_err_lex(lua_State * L,GCstr * src,const char * tok,BCLine line,ErrMsg em,va_list argp)589 LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
590 			    BCLine line, ErrMsg em, va_list argp)
591 {
592   char buff[LUA_IDSIZE];
593   const char *msg;
594   lj_debug_shortname(buff, src);
595   msg = lj_str_pushvf(L, err2msg(em), argp);
596   msg = lj_str_pushf(L, "%s:%d: %s", buff, line, msg);
597   if (tok)
598     lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
599   lj_err_throw(L, LUA_ERRSYNTAX);
600 }
601 
602 /* Typecheck error for operands. */
lj_err_optype(lua_State * L,cTValue * o,ErrMsg opm)603 LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
604 {
605   const char *tname = lj_typename(o);
606   const char *opname = err2msg(opm);
607   if (curr_funcisL(L)) {
608     GCproto *pt = curr_proto(L);
609     const BCIns *pc = cframe_Lpc(L) - 1;
610     const char *oname = NULL;
611     const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
612     if (kind)
613       err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
614   }
615   err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
616 }
617 
618 /* Typecheck error for ordered comparisons. */
lj_err_comp(lua_State * L,cTValue * o1,cTValue * o2)619 LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
620 {
621   const char *t1 = lj_typename(o1);
622   const char *t2 = lj_typename(o2);
623   err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
624   /* This assumes the two "boolean" entries are commoned by the C compiler. */
625 }
626 
627 /* Typecheck error for __call. */
lj_err_optype_call(lua_State * L,TValue * o)628 LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
629 {
630   /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
631   ** L->base still points to the caller. So add a dummy frame with L instead
632   ** of a function. See lua_getstack().
633   */
634   const BCIns *pc = cframe_Lpc(L);
635   if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
636     const char *tname = lj_typename(o);
637     setframe_pc(o, pc);
638     setframe_gc(o, obj2gco(L));
639     L->top = L->base = o+1;
640     err_msgv(L, LJ_ERR_BADCALL, tname);
641   }
642   lj_err_optype(L, o, LJ_ERR_OPCALL);
643 }
644 
645 /* Error in context of caller. */
lj_err_callermsg(lua_State * L,const char * msg)646 LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
647 {
648   TValue *frame = L->base-1;
649   TValue *pframe = NULL;
650   if (frame_islua(frame)) {
651     pframe = frame_prevl(frame);
652   } else if (frame_iscont(frame)) {
653 #if LJ_HASFFI
654     if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) {
655       pframe = frame;
656       frame = NULL;
657     } else
658 #endif
659     {
660       pframe = frame_prevd(frame);
661 #if LJ_HASFFI
662       /* Remove frame for FFI metamethods. */
663       if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
664 	  frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
665 	L->base = pframe+1;
666 	L->top = frame;
667 	setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
668       }
669 #endif
670     }
671   }
672   lj_debug_addloc(L, msg, pframe, frame);
673   lj_err_run(L);
674 }
675 
676 /* Formatted error in context of caller. */
lj_err_callerv(lua_State * L,ErrMsg em,...)677 LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
678 {
679   const char *msg;
680   va_list argp;
681   va_start(argp, em);
682   msg = lj_str_pushvf(L, err2msg(em), argp);
683   va_end(argp);
684   lj_err_callermsg(L, msg);
685 }
686 
687 /* Error in context of caller. */
lj_err_caller(lua_State * L,ErrMsg em)688 LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
689 {
690   lj_err_callermsg(L, err2msg(em));
691 }
692 
693 /* Argument error message. */
err_argmsg(lua_State * L,int narg,const char * msg)694 LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
695 					    const char *msg)
696 {
697   const char *fname = "?";
698   const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
699   if (narg < 0 && narg > LUA_REGISTRYINDEX)
700     narg = (int)(L->top - L->base) + narg + 1;
701   if (ftype && ftype[3] == 'h' && --narg == 0)  /* Check for "method". */
702     msg = lj_str_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
703   else
704     msg = lj_str_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
705   lj_err_callermsg(L, msg);
706 }
707 
708 /* Formatted argument error. */
lj_err_argv(lua_State * L,int narg,ErrMsg em,...)709 LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
710 {
711   const char *msg;
712   va_list argp;
713   va_start(argp, em);
714   msg = lj_str_pushvf(L, err2msg(em), argp);
715   va_end(argp);
716   err_argmsg(L, narg, msg);
717 }
718 
719 /* Argument error. */
lj_err_arg(lua_State * L,int narg,ErrMsg em)720 LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
721 {
722   err_argmsg(L, narg, err2msg(em));
723 }
724 
725 /* Typecheck error for arguments. */
lj_err_argtype(lua_State * L,int narg,const char * xname)726 LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
727 {
728   TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
729   const char *tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
730   const char *msg = lj_str_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
731   err_argmsg(L, narg, msg);
732 }
733 
734 /* Typecheck error for arguments. */
lj_err_argt(lua_State * L,int narg,int tt)735 LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
736 {
737   lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
738 }
739 
740 /* -- Public error handling API ------------------------------------------- */
741 
lua_atpanic(lua_State * L,lua_CFunction panicf)742 LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
743 {
744   lua_CFunction old = G(L)->panic;
745   G(L)->panic = panicf;
746   return old;
747 }
748 
749 /* Forwarders for the public API (C calling convention and no LJ_NORET). */
lua_error(lua_State * L)750 LUA_API int lua_error(lua_State *L)
751 {
752   lj_err_run(L);
753   return 0;  /* unreachable */
754 }
755 
luaL_argerror(lua_State * L,int narg,const char * msg)756 LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
757 {
758   err_argmsg(L, narg, msg);
759   return 0;  /* unreachable */
760 }
761 
luaL_typerror(lua_State * L,int narg,const char * xname)762 LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
763 {
764   lj_err_argtype(L, narg, xname);
765   return 0;  /* unreachable */
766 }
767 
luaL_where(lua_State * L,int level)768 LUALIB_API void luaL_where(lua_State *L, int level)
769 {
770   int size;
771   cTValue *frame = lj_debug_frame(L, level, &size);
772   lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
773 }
774 
luaL_error(lua_State * L,const char * fmt,...)775 LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
776 {
777   const char *msg;
778   va_list argp;
779   va_start(argp, fmt);
780   msg = lj_str_pushvf(L, fmt, argp);
781   va_end(argp);
782   lj_err_callermsg(L, msg);
783   return 0;  /* unreachable */
784 }
785 
786