1 /*
2 ** Error handling.
3 ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
4 */
5 
6 // Modified by Lasse Oorni for Urho3D
7 
8 #define lj_err_c
9 #define LUA_CORE
10 
11 #include "lj_obj.h"
12 #include "lj_err.h"
13 #include "lj_debug.h"
14 #include "lj_str.h"
15 #include "lj_func.h"
16 #include "lj_state.h"
17 #include "lj_frame.h"
18 #include "lj_ff.h"
19 #include "lj_trace.h"
20 #include "lj_vm.h"
21 #include "lj_strfmt.h"
22 
23 /*
24 ** LuaJIT can either use internal or external frame unwinding:
25 **
26 ** - Internal frame unwinding (INT) is free-standing and doesn't require
27 **   any OS or library support.
28 **
29 ** - External frame unwinding (EXT) uses the system-provided unwind handler.
30 **
31 ** Pros and Cons:
32 **
33 ** - EXT requires unwind tables for *all* functions on the C stack between
34 **   the pcall/catch and the error/throw. This is the default on x64,
35 **   but needs to be manually enabled on x86/PPC for non-C++ code.
36 **
37 ** - INT is faster when actually throwing errors (but this happens rarely).
38 **   Setting up error handlers is zero-cost in any case.
39 **
40 ** - EXT provides full interoperability with C++ exceptions. You can throw
41 **   Lua errors or C++ exceptions through a mix of Lua frames and C++ frames.
42 **   C++ destructors are called as needed. C++ exceptions caught by pcall
43 **   are converted to the string "C++ exception". Lua errors can be caught
44 **   with catch (...) in C++.
45 **
46 ** - INT has only limited support for automatically catching C++ exceptions
47 **   on POSIX systems using DWARF2 stack unwinding. Other systems may use
48 **   the wrapper function feature. Lua errors thrown through C++ frames
49 **   cannot be caught by C++ code and C++ destructors are not run.
50 **
51 ** EXT is the default on x64 systems, INT is the default on all other systems.
52 **
53 ** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack
54 ** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled
55 ** with -funwind-tables (or -fexceptions). This includes LuaJIT itself (set
56 ** TARGET_CFLAGS), all of your C/Lua binding code, all loadable C modules
57 ** and all C libraries that have callbacks which may be used to call back
58 ** into Lua. C++ code must *not* be compiled with -fno-exceptions.
59 **
60 ** EXT cannot be enabled on WIN32 since system exceptions use code-driven SEH.
61 ** EXT is mandatory on WIN64 since the calling convention has an abundance
62 ** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15).
63 ** The POSIX/x64 interpreter only saves r12/r13 for INT (e.g. PS4).
64 */
65 
66 #if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL)) && !LJ_NO_UNWIND
67 #define LJ_UNWIND_EXT	1
68 #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS
69 #define LJ_UNWIND_EXT	1
70 #endif
71 
72 /* -- Error messages ------------------------------------------------------ */
73 
74 /* Error message strings. */
75 LJ_DATADEF const char *lj_err_allmsg =
76 #define ERRDEF(name, msg)	msg "\0"
77 #include "lj_errmsg.h"
78 ;
79 
80 /* -- Internal frame unwinding -------------------------------------------- */
81 
82 /* Unwind Lua stack and move error message to new top. */
unwindstack(lua_State * L,TValue * top)83 LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
84 {
85   lj_func_closeuv(L, top);
86   if (top < L->top-1) {
87     copyTV(L, top, L->top-1);
88     L->top = top+1;
89   }
90   lj_state_relimitstack(L);
91 }
92 
93 /* Unwind until stop frame. Optionally cleanup frames. */
err_unwind(lua_State * L,void * stopcf,int errcode)94 static void *err_unwind(lua_State *L, void *stopcf, int errcode)
95 {
96   TValue *frame = L->base-1;
97   void *cf = L->cframe;
98   while (cf) {
99     int32_t nres = cframe_nres(cframe_raw(cf));
100     if (nres < 0) {  /* C frame without Lua frame? */
101       TValue *top = restorestack(L, -nres);
102       if (frame < top) {  /* Frame reached? */
103 	if (errcode) {
104 	  L->base = frame+1;
105 	  L->cframe = cframe_prev(cf);
106 	  unwindstack(L, top);
107 	}
108 	return cf;
109       }
110     }
111     if (frame <= tvref(L->stack)+LJ_FR2)
112       break;
113     switch (frame_typep(frame)) {
114     case FRAME_LUA:  /* Lua frame. */
115     case FRAME_LUAP:
116       frame = frame_prevl(frame);
117       break;
118     case FRAME_C:  /* C frame. */
119     unwind_c:
120 #if LJ_UNWIND_EXT
121       if (errcode) {
122 	L->base = frame_prevd(frame) + 1;
123 	L->cframe = cframe_prev(cf);
124 	unwindstack(L, frame - LJ_FR2);
125       } else if (cf != stopcf) {
126 	cf = cframe_prev(cf);
127 	frame = frame_prevd(frame);
128 	break;
129       }
130       return NULL;  /* Continue unwinding. */
131 #else
132       UNUSED(stopcf);
133       cf = cframe_prev(cf);
134       frame = frame_prevd(frame);
135       break;
136 #endif
137     case FRAME_CP:  /* Protected C frame. */
138       if (cframe_canyield(cf)) {  /* Resume? */
139 	if (errcode) {
140 	  hook_leave(G(L));  /* Assumes nobody uses coroutines inside hooks. */
141 	  L->cframe = NULL;
142 	  L->status = (uint8_t)errcode;
143 	}
144 	return cf;
145       }
146       if (errcode) {
147 	L->base = frame_prevd(frame) + 1;
148 	L->cframe = cframe_prev(cf);
149 	unwindstack(L, frame - LJ_FR2);
150       }
151       return cf;
152     case FRAME_CONT:  /* Continuation frame. */
153       if (frame_iscont_fficb(frame))
154 	goto unwind_c;
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;
164 	}
165 	if (frame_typep(frame) == FRAME_PCALL)
166 	  hook_leave(G(L));
167 	L->base = frame_prevd(frame) + 1;
168 	L->cframe = cf;
169 	unwindstack(L, L->base);
170       }
171       return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
172     }
173   }
174   /* No C frame. */
175   if (errcode) {
176     L->base = tvref(L->stack)+1+LJ_FR2;
177     L->cframe = NULL;
178     unwindstack(L, L->base);
179     if (G(L)->panic)
180       G(L)->panic(L);
181     exit(EXIT_FAILURE);
182   }
183   return L;  /* Anything non-NULL will do. */
184 }
185 
186 /* -- External frame unwinding -------------------------------------------- */
187 
188 #if defined(__GNUC__) && !LJ_NO_UNWIND && !LJ_ABI_WIN
189 
190 /*
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.
193 */
194 
195 typedef struct _Unwind_Context _Unwind_Context;
196 
197 #define _URC_OK			0
198 #define _URC_FATAL_PHASE1_ERROR	3
199 #define _URC_HANDLER_FOUND	6
200 #define _URC_INSTALL_CONTEXT	7
201 #define _URC_CONTINUE_UNWIND	8
202 #define _URC_FAILURE		9
203 
204 #define LJ_UEXCLASS		0x4c55414a49543200ULL	/* LUAJIT2\0 */
205 #define LJ_UEXCLASS_MAKE(c)	(LJ_UEXCLASS | (uint64_t)(c))
206 #define LJ_UEXCLASS_CHECK(cl)	(((cl) ^ LJ_UEXCLASS) <= 0xff)
207 #define LJ_UEXCLASS_ERRCODE(cl)	((int)((cl) & 0xff))
208 
209 #if !LJ_TARGET_ARM
210 
211 typedef struct _Unwind_Exception
212 {
213   uint64_t exclass;
214   void (*excleanup)(int, struct _Unwind_Exception *);
215   uintptr_t p1, p2;
216 } __attribute__((__aligned__)) _Unwind_Exception;
217 
218 extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
219 extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
220 extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
221 extern void _Unwind_DeleteException(_Unwind_Exception *);
222 extern int _Unwind_RaiseException(_Unwind_Exception *);
223 
224 #define _UA_SEARCH_PHASE	1
225 #define _UA_CLEANUP_PHASE	2
226 #define _UA_HANDLER_FRAME	4
227 #define _UA_FORCE_UNWIND	8
228 
229 /* 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)230 LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
231   uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
232 {
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));
247     }
248     return _URC_HANDLER_FOUND;
249   }
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;
258     }
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;
269     }
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
274       */
275       _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
276       _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
277       return _URC_INSTALL_CONTEXT;
278     }
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.
283     */
284     lj_err_throw(L, errcode);
285 #endif
286   }
287   return _URC_CONTINUE_UNWIND;
288 }
289 
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
297 
298 /* Raise DWARF2 exception. */
err_raise_ext(int errcode)299 static void err_raise_ext(int errcode)
300 {
301   static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
302   static_uex.excleanup = NULL;
303   _Unwind_RaiseException(&static_uex);
304 }
305 #endif
306 
307 #else /* LJ_TARGET_ARM */
308 
309 #define _US_VIRTUAL_UNWIND_FRAME	0
310 #define _US_UNWIND_FRAME_STARTING	1
311 #define _US_ACTION_MASK			3
312 #define _US_FORCE_UNWIND		8
313 
314 typedef struct _Unwind_Control_Block _Unwind_Control_Block;
315 
316 struct _Unwind_Control_Block {
317   uint64_t exclass;
318   uint32_t misc[20];
319 };
320 
321 extern int _Unwind_RaiseException(_Unwind_Control_Block *);
322 extern int __gnu_unwind_frame(_Unwind_Control_Block *, _Unwind_Context *);
323 extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
324 extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
325 
_Unwind_GetGR(_Unwind_Context * ctx,int r)326 static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
327 {
328   uint32_t v;
329   _Unwind_VRS_Get(ctx, 0, r, 0, &v);
330   return v;
331 }
332 
_Unwind_SetGR(_Unwind_Context * ctx,int r,uint32_t v)333 static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
334 {
335   _Unwind_VRS_Set(ctx, 0, r, 0, &v);
336 }
337 
338 extern void lj_vm_unwind_ext(void);
339 
340 /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
lj_err_unwind_arm(int state,_Unwind_Control_Block * ucb,_Unwind_Context * ctx)341 LJ_FUNCA int lj_err_unwind_arm(int state, _Unwind_Control_Block *ucb,
342 			       _Unwind_Context *ctx)
343 {
344   void *cf = (void *)_Unwind_GetGR(ctx, 13);
345   lua_State *L = cframe_L(cf);
346   int errcode;
347 
348   switch ((state & _US_ACTION_MASK)) {
349   case _US_VIRTUAL_UNWIND_FRAME:
350     if ((state & _US_FORCE_UNWIND)) break;
351     return _URC_HANDLER_FOUND;
352   case _US_UNWIND_FRAME_STARTING:
353     if (LJ_UEXCLASS_CHECK(ucb->exclass)) {
354       errcode = LJ_UEXCLASS_ERRCODE(ucb->exclass);
355     } else {
356       errcode = LUA_ERRRUN;
357       setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
358     }
359     cf = err_unwind(L, cf, errcode);
360     if ((state & _US_FORCE_UNWIND) || cf == NULL) break;
361     _Unwind_SetGR(ctx, 15, (uint32_t)lj_vm_unwind_ext);
362     _Unwind_SetGR(ctx, 0, (uint32_t)ucb);
363     _Unwind_SetGR(ctx, 1, (uint32_t)errcode);
364     _Unwind_SetGR(ctx, 2, cframe_unwind_ff(cf) ?
365 			    (uint32_t)lj_vm_unwind_ff_eh :
366 			    (uint32_t)lj_vm_unwind_c_eh);
367     return _URC_INSTALL_CONTEXT;
368   default:
369     return _URC_FAILURE;
370   }
371   if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
372     return _URC_FAILURE;
373   return _URC_CONTINUE_UNWIND;
374 }
375 
376 #if LJ_UNWIND_EXT
377 static __thread _Unwind_Control_Block static_uex;
378 
err_raise_ext(int errcode)379 static void err_raise_ext(int errcode)
380 {
381   memset(&static_uex, 0, sizeof(static_uex));
382   static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
383   _Unwind_RaiseException(&static_uex);
384 }
385 #endif
386 
387 #endif /* LJ_TARGET_ARM */
388 
389 #elif LJ_TARGET_X64 && LJ_ABI_WIN
390 
391 /*
392 ** Someone in Redmond owes me several days of my life. A lot of this is
393 ** undocumented or just plain wrong on MSDN. Some of it can be gathered
394 ** from 3rd party docs or must be found by trial-and-error. They really
395 ** don't want you to write your own language-specific exception handler
396 ** or to interact gracefully with MSVC. :-(
397 **
398 ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
399 ** unless you compile your C++ code with /EHa. Unfortunately this means
400 ** catch (...) also catches things like access violations. The use of
401 ** _set_se_translator doesn't really help, because it requires /EHa, too.
402 */
403 
404 #define WIN32_LEAN_AND_MEAN
405 #include <windows.h>
406 
407 // Urho3D: added Visual Studio 2008 64-bit workaround
408 #if defined(_MSC_VER) && _MSC_VER <= 1500
409 typedef void* PEXCEPTION_ROUTINE;
410 typedef void* PUNWIND_HISTORY_TABLE;
411 #endif
412 
413 /* Taken from: http://www.nynaeve.net/?p=99 */
414 typedef struct UndocumentedDispatcherContext {
415   ULONG64 ControlPc;
416   ULONG64 ImageBase;
417   PRUNTIME_FUNCTION FunctionEntry;
418   ULONG64 EstablisherFrame;
419   ULONG64 TargetIp;
420   PCONTEXT ContextRecord;
421   void (*LanguageHandler)(void);
422   PVOID HandlerData;
423   PUNWIND_HISTORY_TABLE HistoryTable;
424   ULONG ScopeIndex;
425   ULONG Fill0;
426 } UndocumentedDispatcherContext;
427 
428 /* Another wild guess. */
429 extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
430 
431 #ifdef MINGW_SDK_INIT
432 /* Workaround for broken MinGW64 declaration. */
433 VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
434 #define RtlUnwindEx RtlUnwindEx_FIXED
435 #endif
436 
437 #define LJ_MSVC_EXCODE		((DWORD)0xe06d7363)
438 #define LJ_GCC_EXCODE		((DWORD)0x20474343)
439 
440 #define LJ_EXCODE		((DWORD)0xe24c4a00)
441 #define LJ_EXCODE_MAKE(c)	(LJ_EXCODE | (DWORD)(c))
442 #define LJ_EXCODE_CHECK(cl)	(((cl) ^ LJ_EXCODE) <= 0xff)
443 #define LJ_EXCODE_ERRCODE(cl)	((int)((cl) & 0xff))
444 
445 /* Win64 exception handler for interpreter frame. */
lj_err_unwind_win64(EXCEPTION_RECORD * rec,void * cf,CONTEXT * ctx,UndocumentedDispatcherContext * dispatch)446 LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
447   void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
448 {
449   lua_State *L = cframe_L(cf);
450   int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
451 		LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
452   if ((rec->ExceptionFlags & 6)) {  /* EH_UNWINDING|EH_EXIT_UNWIND */
453     /* Unwind internal frames. */
454     err_unwind(L, cf, errcode);
455   } else {
456     void *cf2 = err_unwind(L, cf, 0);
457     if (cf2) {  /* We catch it, so start unwinding the upper frames. */
458       if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
459 	  rec->ExceptionCode == LJ_GCC_EXCODE) {
460 #if LJ_TARGET_WINDOWS
461 	__DestructExceptionObject(rec, 1);
462 #endif
463 	setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
464       } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
465 	/* Don't catch access violations etc. */
466 	return ExceptionContinueSearch;
467       }
468       /* Unwind the stack and call all handlers for all lower C frames
469       ** (including ourselves) again with EH_UNWINDING set. Then set
470       ** rsp = cf, rax = errcode and jump to the specified target.
471       */
472       RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
473 			       lj_vm_unwind_ff_eh :
474 			       lj_vm_unwind_c_eh),
475 		  rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
476       /* RtlUnwindEx should never return. */
477     }
478   }
479   return ExceptionContinueSearch;
480 }
481 
482 /* Raise Windows exception. */
err_raise_ext(int errcode)483 static void err_raise_ext(int errcode)
484 {
485   RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
486 }
487 
488 #endif
489 
490 /* -- Error handling ------------------------------------------------------ */
491 
492 /* Throw error. Find catch frame, unwind stack and continue. */
lj_err_throw(lua_State * L,int errcode)493 LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
494 {
495   global_State *g = G(L);
496   lj_trace_abort(g);
497   setmref(g->jit_base, NULL);
498   L->status = 0;
499 #if LJ_UNWIND_EXT
500   err_raise_ext(errcode);
501   /*
502   ** A return from this function signals a corrupt C stack that cannot be
503   ** unwound. We have no choice but to call the panic function and exit.
504   **
505   ** Usually this is caused by a C function without unwind information.
506   ** This should never happen on x64, but may happen if you've manually
507   ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every*
508   ** non-C++ file with -funwind-tables.
509   */
510   if (G(L)->panic)
511     G(L)->panic(L);
512 #else
513   {
514     void *cf = err_unwind(L, NULL, errcode);
515     if (cframe_unwind_ff(cf))
516       lj_vm_unwind_ff(cframe_raw(cf));
517     else
518       lj_vm_unwind_c(cframe_raw(cf), errcode);
519   }
520 #endif
521   exit(EXIT_FAILURE);
522 }
523 
524 /* Return string object for error message. */
lj_err_str(lua_State * L,ErrMsg em)525 LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
526 {
527   return lj_str_newz(L, err2msg(em));
528 }
529 
530 /* Out-of-memory error. */
lj_err_mem(lua_State * L)531 LJ_NOINLINE void lj_err_mem(lua_State *L)
532 {
533   if (L->status == LUA_ERRERR+1)  /* Don't touch the stack during lua_open. */
534     lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
535   setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
536   lj_err_throw(L, LUA_ERRMEM);
537 }
538 
539 /* Find error function for runtime errors. Requires an extra stack traversal. */
finderrfunc(lua_State * L)540 static ptrdiff_t finderrfunc(lua_State *L)
541 {
542   cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2;
543   void *cf = L->cframe;
544   while (frame > bot && cf) {
545     while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */
546       if (frame >= restorestack(L, -cframe_nres(cf)))
547 	break;
548       if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */
549 	return cframe_errfunc(cf);
550       cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */
551       if (cf == NULL)
552 	return 0;
553     }
554     switch (frame_typep(frame)) {
555     case FRAME_LUA:
556     case FRAME_LUAP:
557       frame = frame_prevl(frame);
558       break;
559     case FRAME_C:
560       cf = cframe_prev(cf);
561       /* fallthrough */
562     case FRAME_VARG:
563       frame = frame_prevd(frame);
564       break;
565     case FRAME_CONT:
566       if (frame_iscont_fficb(frame))
567 	cf = cframe_prev(cf);
568       frame = frame_prevd(frame);
569       break;
570     case FRAME_CP:
571       if (cframe_canyield(cf)) return 0;
572       if (cframe_errfunc(cf) >= 0)
573 	return cframe_errfunc(cf);
574       frame = frame_prevd(frame);
575       break;
576     case FRAME_PCALL:
577     case FRAME_PCALLH:
578       if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall)
579 	return savestack(L, frame_prevd(frame)+1);  /* xpcall's errorfunc. */
580       return 0;
581     default:
582       lua_assert(0);
583       return 0;
584     }
585   }
586   return 0;
587 }
588 
589 /* Runtime error. */
lj_err_run(lua_State * L)590 LJ_NOINLINE void lj_err_run(lua_State *L)
591 {
592   ptrdiff_t ef = finderrfunc(L);
593   if (ef) {
594     TValue *errfunc = restorestack(L, ef);
595     TValue *top = L->top;
596     lj_trace_abort(G(L));
597     if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
598       setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
599       lj_err_throw(L, LUA_ERRERR);
600     }
601     L->status = LUA_ERRERR;
602     copyTV(L, top+LJ_FR2, top-1);
603     copyTV(L, top-1, errfunc);
604     if (LJ_FR2) setnilV(top++);
605     L->top = top+1;
606     lj_vm_call(L, top, 1+1);  /* Stack: |errfunc|msg| -> |msg| */
607   }
608   lj_err_throw(L, LUA_ERRRUN);
609 }
610 
611 /* Formatted runtime error message. */
err_msgv(lua_State * L,ErrMsg em,...)612 LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
613 {
614   const char *msg;
615   va_list argp;
616   va_start(argp, em);
617   if (curr_funcisL(L)) L->top = curr_topL(L);
618   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
619   va_end(argp);
620   lj_debug_addloc(L, msg, L->base-1, NULL);
621   lj_err_run(L);
622 }
623 
624 /* Non-vararg variant for better calling conventions. */
lj_err_msg(lua_State * L,ErrMsg em)625 LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
626 {
627   err_msgv(L, em);
628 }
629 
630 /* Lexer error. */
lj_err_lex(lua_State * L,GCstr * src,const char * tok,BCLine line,ErrMsg em,va_list argp)631 LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
632 			    BCLine line, ErrMsg em, va_list argp)
633 {
634   char buff[LUA_IDSIZE];
635   const char *msg;
636   lj_debug_shortname(buff, src, line);
637   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
638   msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg);
639   if (tok)
640     lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
641   lj_err_throw(L, LUA_ERRSYNTAX);
642 }
643 
644 /* Typecheck error for operands. */
lj_err_optype(lua_State * L,cTValue * o,ErrMsg opm)645 LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
646 {
647   const char *tname = lj_typename(o);
648   const char *opname = err2msg(opm);
649   if (curr_funcisL(L)) {
650     GCproto *pt = curr_proto(L);
651     const BCIns *pc = cframe_Lpc(L) - 1;
652     const char *oname = NULL;
653     const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
654     if (kind)
655       err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
656   }
657   err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
658 }
659 
660 /* Typecheck error for ordered comparisons. */
lj_err_comp(lua_State * L,cTValue * o1,cTValue * o2)661 LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
662 {
663   const char *t1 = lj_typename(o1);
664   const char *t2 = lj_typename(o2);
665   err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
666   /* This assumes the two "boolean" entries are commoned by the C compiler. */
667 }
668 
669 /* Typecheck error for __call. */
lj_err_optype_call(lua_State * L,TValue * o)670 LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
671 {
672   /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
673   ** L->base still points to the caller. So add a dummy frame with L instead
674   ** of a function. See lua_getstack().
675   */
676   const BCIns *pc = cframe_Lpc(L);
677   if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
678     const char *tname = lj_typename(o);
679     if (LJ_FR2) o++;
680     setframe_pc(o, pc);
681     setframe_gc(o, obj2gco(L), LJ_TTHREAD);
682     L->top = L->base = o+1;
683     err_msgv(L, LJ_ERR_BADCALL, tname);
684   }
685   lj_err_optype(L, o, LJ_ERR_OPCALL);
686 }
687 
688 /* Error in context of caller. */
lj_err_callermsg(lua_State * L,const char * msg)689 LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
690 {
691   TValue *frame = L->base-1;
692   TValue *pframe = NULL;
693   if (frame_islua(frame)) {
694     pframe = frame_prevl(frame);
695   } else if (frame_iscont(frame)) {
696     if (frame_iscont_fficb(frame)) {
697       pframe = frame;
698       frame = NULL;
699     } else {
700       pframe = frame_prevd(frame);
701 #if LJ_HASFFI
702       /* Remove frame for FFI metamethods. */
703       if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
704 	  frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
705 	L->base = pframe+1;
706 	L->top = frame;
707 	setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
708       }
709 #endif
710     }
711   }
712   lj_debug_addloc(L, msg, pframe, frame);
713   lj_err_run(L);
714 }
715 
716 /* Formatted error in context of caller. */
lj_err_callerv(lua_State * L,ErrMsg em,...)717 LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
718 {
719   const char *msg;
720   va_list argp;
721   va_start(argp, em);
722   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
723   va_end(argp);
724   lj_err_callermsg(L, msg);
725 }
726 
727 /* Error in context of caller. */
lj_err_caller(lua_State * L,ErrMsg em)728 LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
729 {
730   lj_err_callermsg(L, err2msg(em));
731 }
732 
733 /* Argument error message. */
err_argmsg(lua_State * L,int narg,const char * msg)734 LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
735 					    const char *msg)
736 {
737   const char *fname = "?";
738   const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
739   if (narg < 0 && narg > LUA_REGISTRYINDEX)
740     narg = (int)(L->top - L->base) + narg + 1;
741   if (ftype && ftype[3] == 'h' && --narg == 0)  /* Check for "method". */
742     msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
743   else
744     msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
745   lj_err_callermsg(L, msg);
746 }
747 
748 /* Formatted argument error. */
lj_err_argv(lua_State * L,int narg,ErrMsg em,...)749 LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
750 {
751   const char *msg;
752   va_list argp;
753   va_start(argp, em);
754   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
755   va_end(argp);
756   err_argmsg(L, narg, msg);
757 }
758 
759 /* Argument error. */
lj_err_arg(lua_State * L,int narg,ErrMsg em)760 LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
761 {
762   err_argmsg(L, narg, err2msg(em));
763 }
764 
765 /* Typecheck error for arguments. */
lj_err_argtype(lua_State * L,int narg,const char * xname)766 LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
767 {
768   const char *tname, *msg;
769   if (narg <= LUA_REGISTRYINDEX) {
770     if (narg >= LUA_GLOBALSINDEX) {
771       tname = lj_obj_itypename[~LJ_TTAB];
772     } else {
773       GCfunc *fn = curr_func(L);
774       int idx = LUA_GLOBALSINDEX - narg;
775       if (idx <= fn->c.nupvalues)
776 	tname = lj_typename(&fn->c.upvalue[idx-1]);
777       else
778 	tname = lj_obj_typename[0];
779     }
780   } else {
781     TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
782     tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
783   }
784   msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
785   err_argmsg(L, narg, msg);
786 }
787 
788 /* Typecheck error for arguments. */
lj_err_argt(lua_State * L,int narg,int tt)789 LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
790 {
791   lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
792 }
793 
794 /* -- Public error handling API ------------------------------------------- */
795 
lua_atpanic(lua_State * L,lua_CFunction panicf)796 LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
797 {
798   lua_CFunction old = G(L)->panic;
799   G(L)->panic = panicf;
800   return old;
801 }
802 
803 /* Forwarders for the public API (C calling convention and no LJ_NORET). */
lua_error(lua_State * L)804 LUA_API int lua_error(lua_State *L)
805 {
806   lj_err_run(L);
807   return 0;  /* unreachable */
808 }
809 
luaL_argerror(lua_State * L,int narg,const char * msg)810 LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
811 {
812   err_argmsg(L, narg, msg);
813   return 0;  /* unreachable */
814 }
815 
luaL_typerror(lua_State * L,int narg,const char * xname)816 LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
817 {
818   lj_err_argtype(L, narg, xname);
819   return 0;  /* unreachable */
820 }
821 
luaL_where(lua_State * L,int level)822 LUALIB_API void luaL_where(lua_State *L, int level)
823 {
824   int size;
825   cTValue *frame = lj_debug_frame(L, level, &size);
826   lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
827 }
828 
luaL_error(lua_State * L,const char * fmt,...)829 LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
830 {
831   const char *msg;
832   va_list argp;
833   va_start(argp, fmt);
834   msg = lj_strfmt_pushvf(L, fmt, argp);
835   va_end(argp);
836   lj_err_callermsg(L, msg);
837   return 0;  /* unreachable */
838 }
839 
840