src/lj_err.c - luajit-2.0-src

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** Error handling.
  3. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
  4. */

  5. #define lj_err_c
  6. #define LUA_CORE

  7. #include "lj_obj.h"
  8. #include "lj_err.h"
  9. #include "lj_debug.h"
  10. #include "lj_str.h"
  11. #include "lj_func.h"
  12. #include "lj_state.h"
  13. #include "lj_frame.h"
  14. #include "lj_ff.h"
  15. #include "lj_trace.h"
  16. #include "lj_vm.h"
  17. #include "lj_strfmt.h"

  18. /*
  19. ** LuaJIT can either use internal or external frame unwinding:
  20. **
  21. ** - Internal frame unwinding (INT) is free-standing and doesn't require
  22. **   any OS or library support.
  23. **
  24. ** - External frame unwinding (EXT) uses the system-provided unwind handler.
  25. **
  26. ** Pros and Cons:
  27. **
  28. ** - EXT requires unwind tables for *all* functions on the C stack between
  29. **   the pcall/catch and the error/throw. This is the default on x64,
  30. **   but needs to be manually enabled on x86/PPC for non-C++ code.
  31. **
  32. ** - INT is faster when actually throwing errors (but this happens rarely).
  33. **   Setting up error handlers is zero-cost in any case.
  34. **
  35. ** - EXT provides full interoperability with C++ exceptions. You can throw
  36. **   Lua errors or C++ exceptions through a mix of Lua frames and C++ frames.
  37. **   C++ destructors are called as needed. C++ exceptions caught by pcall
  38. **   are converted to the string "C++ exception". Lua errors can be caught
  39. **   with catch (...) in C++.
  40. **
  41. ** - INT has only limited support for automatically catching C++ exceptions
  42. **   on POSIX systems using DWARF2 stack unwinding. Other systems may use
  43. **   the wrapper function feature. Lua errors thrown through C++ frames
  44. **   cannot be caught by C++ code and C++ destructors are not run.
  45. **
  46. ** EXT is the default on x64 systems, INT is the default on all other systems.
  47. **
  48. ** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack
  49. ** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled
  50. ** with -funwind-tables (or -fexceptions). This includes LuaJIT itself (set
  51. ** TARGET_CFLAGS), all of your C/Lua binding code, all loadable C modules
  52. ** and all C libraries that have callbacks which may be used to call back
  53. ** into Lua. C++ code must *not* be compiled with -fno-exceptions.
  54. **
  55. ** EXT cannot be enabled on WIN32 since system exceptions use code-driven SEH.
  56. ** EXT is mandatory on WIN64 since the calling convention has an abundance
  57. ** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15).
  58. ** EXT is mandatory on POSIX/x64 since the interpreter doesn't save r12/r13.
  59. */

  60. #if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL))
  61. #define LJ_UNWIND_EXT        1
  62. #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS
  63. #define LJ_UNWIND_EXT        1
  64. #endif

  65. /* -- Error messages ------------------------------------------------------ */

  66. /* Error message strings. */
  67. LJ_DATADEF const char *lj_err_allmsg =
  68. #define ERRDEF(name, msg)        msg "\0"
  69. #include "lj_errmsg.h"
  70. ;

  71. /* -- Internal frame unwinding -------------------------------------------- */

  72. /* Unwind Lua stack and move error message to new top. */
  73. LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
  74. {
  75.   lj_func_closeuv(L, top);
  76.   if (top < L->top-1) {
  77.     copyTV(L, top, L->top-1);
  78.     L->top = top+1;
  79.   }
  80.   lj_state_relimitstack(L);
  81. }

  82. /* Unwind until stop frame. Optionally cleanup frames. */
  83. static void *err_unwind(lua_State *L, void *stopcf, int errcode)
  84. {
  85.   TValue *frame = L->base-1;
  86.   void *cf = L->cframe;
  87.   while (cf) {
  88.     int32_t nres = cframe_nres(cframe_raw(cf));
  89.     if (nres < 0) {  /* C frame without Lua frame? */
  90.       TValue *top = restorestack(L, -nres);
  91.       if (frame < top) {  /* Frame reached? */
  92.         if (errcode) {
  93.           L->base = frame+1;
  94.           L->cframe = cframe_prev(cf);
  95.           unwindstack(L, top);
  96.         }
  97.         return cf;
  98.       }
  99.     }
  100.     if (frame <= tvref(L->stack)+LJ_FR2)
  101.       break;
  102.     switch (frame_typep(frame)) {
  103.     case FRAME_LUA:  /* Lua frame. */
  104.     case FRAME_LUAP:
  105.       frame = frame_prevl(frame);
  106.       break;
  107.     case FRAME_C:  /* C frame. */
  108.     unwind_c:
  109. #if LJ_UNWIND_EXT
  110.       if (errcode) {
  111.         L->base = frame_prevd(frame) + 1;
  112.         L->cframe = cframe_prev(cf);
  113.         unwindstack(L, frame);
  114.       } else if (cf != stopcf) {
  115.         cf = cframe_prev(cf);
  116.         frame = frame_prevd(frame);
  117.         break;
  118.       }
  119.       return NULL/* Continue unwinding. */
  120. #else
  121.       UNUSED(stopcf);
  122.       cf = cframe_prev(cf);
  123.       frame = frame_prevd(frame);
  124.       break;
  125. #endif
  126.     case FRAME_CP:  /* Protected C frame. */
  127.       if (cframe_canyield(cf)) {  /* Resume? */
  128.         if (errcode) {
  129.           hook_leave(G(L));  /* Assumes nobody uses coroutines inside hooks. */
  130.           L->cframe = NULL;
  131.           L->status = (uint8_t)errcode;
  132.         }
  133.         return cf;
  134.       }
  135.       if (errcode) {
  136.         L->base = frame_prevd(frame) + 1;
  137.         L->cframe = cframe_prev(cf);
  138.         unwindstack(L, frame);
  139.       }
  140.       return cf;
  141.     case FRAME_CONT:  /* Continuation frame. */
  142.       if (frame_iscont_fficb(frame))
  143.         goto unwind_c;
  144.     case FRAME_VARG:  /* Vararg frame. */
  145.       frame = frame_prevd(frame);
  146.       break;
  147.     case FRAME_PCALL:  /* FF pcall() frame. */
  148.     case FRAME_PCALLH:  /* FF pcall() frame inside hook. */
  149.       if (errcode) {
  150.         if (errcode == LUA_YIELD) {
  151.           frame = frame_prevd(frame);
  152.           break;
  153.         }
  154.         if (frame_typep(frame) == FRAME_PCALL)
  155.           hook_leave(G(L));
  156.         L->base = frame_prevd(frame) + 1;
  157.         L->cframe = cf;
  158.         unwindstack(L, L->base);
  159.       }
  160.       return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
  161.     }
  162.   }
  163.   /* No C frame. */
  164.   if (errcode) {
  165.     L->base = tvref(L->stack)+1+LJ_FR2;
  166.     L->cframe = NULL;
  167.     unwindstack(L, L->base);
  168.     if (G(L)->panic)
  169.       G(L)->panic(L);
  170.     exit(EXIT_FAILURE);
  171.   }
  172.   return L;  /* Anything non-NULL will do. */
  173. }

  174. /* -- External frame unwinding -------------------------------------------- */

  175. #if defined(__GNUC__) && !LJ_NO_UNWIND && !LJ_TARGET_WINDOWS

  176. /*
  177. ** We have to use our own definitions instead of the mandatory (!) unwind.h,
  178. ** since various OS, distros and compilers mess up the header installation.
  179. */

  180. typedef struct _Unwind_Exception
  181. {
  182.   uint64_t exclass;
  183.   void (*excleanup)(int, struct _Unwind_Exception *);
  184.   uintptr_t p1, p2;
  185. } __attribute__((__aligned__)) _Unwind_Exception;

  186. typedef struct _Unwind_Context _Unwind_Context;

  187. #define _URC_OK                        0
  188. #define _URC_FATAL_PHASE1_ERROR        3
  189. #define _URC_HANDLER_FOUND        6
  190. #define _URC_INSTALL_CONTEXT        7
  191. #define _URC_CONTINUE_UNWIND        8
  192. #define _URC_FAILURE                9

  193. #if !LJ_TARGET_ARM

  194. extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
  195. extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
  196. extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
  197. extern void _Unwind_DeleteException(_Unwind_Exception *);
  198. extern int _Unwind_RaiseException(_Unwind_Exception *);

  199. #define _UA_SEARCH_PHASE        1
  200. #define _UA_CLEANUP_PHASE        2
  201. #define _UA_HANDLER_FRAME        4
  202. #define _UA_FORCE_UNWIND        8

  203. #define LJ_UEXCLASS                0x4c55414a49543200ULL        /* LUAJIT2\0 */
  204. #define LJ_UEXCLASS_MAKE(c)        (LJ_UEXCLASS | (uint64_t)(c))
  205. #define LJ_UEXCLASS_CHECK(cl)        (((cl) ^ LJ_UEXCLASS) <= 0xff)
  206. #define LJ_UEXCLASS_ERRCODE(cl)        ((int)((cl) & 0xff))

  207. /* DWARF2 personality handler referenced from interpreter .eh_frame. */
  208. LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
  209.   uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
  210. {
  211.   void *cf;
  212.   lua_State *L;
  213.   if (version != 1)
  214.     return _URC_FATAL_PHASE1_ERROR;
  215.   UNUSED(uexclass);
  216.   cf = (void *)_Unwind_GetCFA(ctx);
  217.   L = cframe_L(cf);
  218.   if ((actions & _UA_SEARCH_PHASE)) {
  219. #if LJ_UNWIND_EXT
  220.     if (err_unwind(L, cf, 0) == NULL)
  221.       return _URC_CONTINUE_UNWIND;
  222. #endif
  223.     if (!LJ_UEXCLASS_CHECK(uexclass)) {
  224.       setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  225.     }
  226.     return _URC_HANDLER_FOUND;
  227.   }
  228.   if ((actions & _UA_CLEANUP_PHASE)) {
  229.     int errcode;
  230.     if (LJ_UEXCLASS_CHECK(uexclass)) {
  231.       errcode = LJ_UEXCLASS_ERRCODE(uexclass);
  232.     } else {
  233.       if ((actions & _UA_HANDLER_FRAME))
  234.         _Unwind_DeleteException(uex);
  235.       errcode = LUA_ERRRUN;
  236.     }
  237. #if LJ_UNWIND_EXT
  238.     cf = err_unwind(L, cf, errcode);
  239.     if ((actions & _UA_FORCE_UNWIND)) {
  240.       return _URC_CONTINUE_UNWIND;
  241.     } else if (cf) {
  242.       _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
  243.       _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ?
  244.                                      lj_vm_unwind_ff_eh :
  245.                                      lj_vm_unwind_c_eh));
  246.       return _URC_INSTALL_CONTEXT;
  247.     }
  248. #if LJ_TARGET_X86ORX64
  249.     else if ((actions & _UA_HANDLER_FRAME)) {
  250.       /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
  251.       ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
  252.       */
  253.       _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
  254.       _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
  255.       return _URC_INSTALL_CONTEXT;
  256.     }
  257. #endif
  258. #else
  259.     /* This is not the proper way to escape from the unwinder. We get away with
  260.     ** it on non-x64 because the interpreter restores all callee-saved regs.
  261.     */
  262.     lj_err_throw(L, errcode);
  263. #endif
  264.   }
  265.   return _URC_CONTINUE_UNWIND;
  266. }

  267. #if LJ_UNWIND_EXT
  268. #if LJ_TARGET_OSX || defined(__OpenBSD__)
  269. /* Sorry, no thread safety for OSX. Complain to Apple, not me. */
  270. static _Unwind_Exception static_uex;
  271. #else
  272. static __thread _Unwind_Exception static_uex;
  273. #endif

  274. /* Raise DWARF2 exception. */
  275. static void err_raise_ext(int errcode)
  276. {
  277.   static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
  278.   static_uex.excleanup = NULL;
  279.   _Unwind_RaiseException(&static_uex);
  280. }
  281. #endif

  282. #else

  283. extern void _Unwind_DeleteException(void *);
  284. extern int __gnu_unwind_frame (void *, _Unwind_Context *);
  285. extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
  286. extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);

  287. static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
  288. {
  289.   uint32_t v;
  290.   _Unwind_VRS_Get(ctx, 0, r, 0, &v);
  291.   return v;
  292. }

  293. static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
  294. {
  295.   _Unwind_VRS_Set(ctx, 0, r, 0, &v);
  296. }

  297. #define _US_VIRTUAL_UNWIND_FRAME        0
  298. #define _US_UNWIND_FRAME_STARTING        1
  299. #define _US_ACTION_MASK                        3
  300. #define _US_FORCE_UNWIND                8

  301. /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
  302. LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx)
  303. {
  304.   void *cf = (void *)_Unwind_GetGR(ctx, 13);
  305.   lua_State *L = cframe_L(cf);
  306.   if ((state & _US_ACTION_MASK) == _US_VIRTUAL_UNWIND_FRAME) {
  307.     setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  308.     return _URC_HANDLER_FOUND;
  309.   }
  310.   if ((state&(_US_ACTION_MASK|_US_FORCE_UNWIND)) == _US_UNWIND_FRAME_STARTING) {
  311.     _Unwind_DeleteException(ucb);
  312.     _Unwind_SetGR(ctx, 15, (uint32_t)(void *)lj_err_throw);
  313.     _Unwind_SetGR(ctx, 0, (uint32_t)L);
  314.     _Unwind_SetGR(ctx, 1, (uint32_t)LUA_ERRRUN);
  315.     return _URC_INSTALL_CONTEXT;
  316.   }
  317.   if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
  318.     return _URC_FAILURE;
  319.   return _URC_CONTINUE_UNWIND;
  320. }

  321. #endif

  322. #elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS

  323. /*
  324. ** Someone in Redmond owes me several days of my life. A lot of this is
  325. ** undocumented or just plain wrong on MSDN. Some of it can be gathered
  326. ** from 3rd party docs or must be found by trial-and-error. They really
  327. ** don't want you to write your own language-specific exception handler
  328. ** or to interact gracefully with MSVC. :-(
  329. **
  330. ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
  331. ** unless you compile your C++ code with /EHa. Unfortunately this means
  332. ** catch (...) also catches things like access violations. The use of
  333. ** _set_se_translator doesn't really help, because it requires /EHa, too.
  334. */

  335. #define WIN32_LEAN_AND_MEAN
  336. #include <windows.h>

  337. /* Taken from: http://www.nynaeve.net/?p=99 */
  338. typedef struct UndocumentedDispatcherContext {
  339.   ULONG64 ControlPc;
  340.   ULONG64 ImageBase;
  341.   PRUNTIME_FUNCTION FunctionEntry;
  342.   ULONG64 EstablisherFrame;
  343.   ULONG64 TargetIp;
  344.   PCONTEXT ContextRecord;
  345.   void (*LanguageHandler)(void);
  346.   PVOID HandlerData;
  347.   PUNWIND_HISTORY_TABLE HistoryTable;
  348.   ULONG ScopeIndex;
  349.   ULONG Fill0;
  350. } UndocumentedDispatcherContext;

  351. /* Another wild guess. */
  352. extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);

  353. #ifdef MINGW_SDK_INIT
  354. /* Workaround for broken MinGW64 declaration. */
  355. VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
  356. #define RtlUnwindEx RtlUnwindEx_FIXED
  357. #endif

  358. #define LJ_MSVC_EXCODE                ((DWORD)0xe06d7363)
  359. #define LJ_GCC_EXCODE                ((DWORD)0x20474343)

  360. #define LJ_EXCODE                ((DWORD)0xe24c4a00)
  361. #define LJ_EXCODE_MAKE(c)        (LJ_EXCODE | (DWORD)(c))
  362. #define LJ_EXCODE_CHECK(cl)        (((cl) ^ LJ_EXCODE) <= 0xff)
  363. #define LJ_EXCODE_ERRCODE(cl)        ((int)((cl) & 0xff))

  364. /* Win64 exception handler for interpreter frame. */
  365. LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
  366.   void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
  367. {
  368.   lua_State *L = cframe_L(cf);
  369.   int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
  370.                 LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
  371.   if ((rec->ExceptionFlags & 6)) {  /* EH_UNWINDING|EH_EXIT_UNWIND */
  372.     /* Unwind internal frames. */
  373.     err_unwind(L, cf, errcode);
  374.   } else {
  375.     void *cf2 = err_unwind(L, cf, 0);
  376.     if (cf2) {  /* We catch it, so start unwinding the upper frames. */
  377.       if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
  378.           rec->ExceptionCode == LJ_GCC_EXCODE) {
  379.         __DestructExceptionObject(rec, 1);
  380.         setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  381.       } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
  382.         /* Don't catch access violations etc. */
  383.         return ExceptionContinueSearch;
  384.       }
  385.       /* Unwind the stack and call all handlers for all lower C frames
  386.       ** (including ourselves) again with EH_UNWINDING set. Then set
  387.       ** rsp = cf, rax = errcode and jump to the specified target.
  388.       */
  389.       RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
  390.                                lj_vm_unwind_ff_eh :
  391.                                lj_vm_unwind_c_eh),
  392.                   rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
  393.       /* RtlUnwindEx should never return. */
  394.     }
  395.   }
  396.   return ExceptionContinueSearch;
  397. }

  398. /* Raise Windows exception. */
  399. static void err_raise_ext(int errcode)
  400. {
  401.   RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
  402. }

  403. #endif

  404. /* -- Error handling ------------------------------------------------------ */

  405. /* Throw error. Find catch frame, unwind stack and continue. */
  406. LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
  407. {
  408.   global_State *g = G(L);
  409.   lj_trace_abort(g);
  410.   setmref(g->jit_base, NULL);
  411.   L->status = 0;
  412. #if LJ_UNWIND_EXT
  413.   err_raise_ext(errcode);
  414.   /*
  415.   ** A return from this function signals a corrupt C stack that cannot be
  416.   ** unwound. We have no choice but to call the panic function and exit.
  417.   **
  418.   ** Usually this is caused by a C function without unwind information.
  419.   ** This should never happen on x64, but may happen if you've manually
  420.   ** enabled LUAJIT_UNWIND_EXTERNAL and forgot to recompile *every*
  421.   ** non-C++ file with -funwind-tables.
  422.   */
  423.   if (G(L)->panic)
  424.     G(L)->panic(L);
  425. #else
  426.   {
  427.     void *cf = err_unwind(L, NULL, errcode);
  428.     if (cframe_unwind_ff(cf))
  429.       lj_vm_unwind_ff(cframe_raw(cf));
  430.     else
  431.       lj_vm_unwind_c(cframe_raw(cf), errcode);
  432.   }
  433. #endif
  434.   exit(EXIT_FAILURE);
  435. }

  436. /* Return string object for error message. */
  437. LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
  438. {
  439.   return lj_str_newz(L, err2msg(em));
  440. }

  441. /* Out-of-memory error. */
  442. LJ_NOINLINE void lj_err_mem(lua_State *L)
  443. {
  444.   if (L->status == LUA_ERRERR+1/* Don't touch the stack during lua_open. */
  445.     lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
  446.   setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
  447.   lj_err_throw(L, LUA_ERRMEM);
  448. }

  449. /* Find error function for runtime errors. Requires an extra stack traversal. */
  450. static ptrdiff_t finderrfunc(lua_State *L)
  451. {
  452.   cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2;
  453.   void *cf = L->cframe;
  454.   while (frame > bot && cf) {
  455.     while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */
  456.       if (frame >= restorestack(L, -cframe_nres(cf)))
  457.         break;
  458.       if (cframe_errfunc(cf) >= 0/* Error handler not inherited (-1)? */
  459.         return cframe_errfunc(cf);
  460.       cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */
  461.       if (cf == NULL)
  462.         return 0;
  463.     }
  464.     switch (frame_typep(frame)) {
  465.     case FRAME_LUA:
  466.     case FRAME_LUAP:
  467.       frame = frame_prevl(frame);
  468.       break;
  469.     case FRAME_C:
  470.       cf = cframe_prev(cf);
  471.       /* fallthrough */
  472.     case FRAME_VARG:
  473.       frame = frame_prevd(frame);
  474.       break;
  475.     case FRAME_CONT:
  476.       if (frame_iscont_fficb(frame))
  477.         cf = cframe_prev(cf);
  478.       frame = frame_prevd(frame);
  479.       break;
  480.     case FRAME_CP:
  481.       if (cframe_canyield(cf)) return 0;
  482.       if (cframe_errfunc(cf) >= 0)
  483.         return cframe_errfunc(cf);
  484.       frame = frame_prevd(frame);
  485.       break;
  486.     case FRAME_PCALL:
  487.     case FRAME_PCALLH:
  488.       if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall)
  489.         return savestack(L, frame_prevd(frame)+1);  /* xpcall's errorfunc. */
  490.       return 0;
  491.     default:
  492.       lua_assert(0);
  493.       return 0;
  494.     }
  495.   }
  496.   return 0;
  497. }

  498. /* Runtime error. */
  499. LJ_NOINLINE void lj_err_run(lua_State *L)
  500. {
  501.   ptrdiff_t ef = finderrfunc(L);
  502.   if (ef) {
  503.     TValue *errfunc = restorestack(L, ef);
  504.     TValue *top = L->top;
  505.     lj_trace_abort(G(L));
  506.     if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
  507.       setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
  508.       lj_err_throw(L, LUA_ERRERR);
  509.     }
  510.     L->status = LUA_ERRERR;
  511.     copyTV(L, top+LJ_FR2, top-1);
  512.     copyTV(L, top-1, errfunc);
  513.     if (LJ_FR2) setnilV(top++);
  514.     L->top = top+1;
  515.     lj_vm_call(L, top, 1+1);  /* Stack: |errfunc|msg| -> |msg| */
  516.   }
  517.   lj_err_throw(L, LUA_ERRRUN);
  518. }

  519. /* Formatted runtime error message. */
  520. LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
  521. {
  522.   const char *msg;
  523.   va_list argp;
  524.   va_start(argp, em);
  525.   if (curr_funcisL(L)) L->top = curr_topL(L);
  526.   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  527.   va_end(argp);
  528.   lj_debug_addloc(L, msg, L->base-1, NULL);
  529.   lj_err_run(L);
  530. }

  531. /* Non-vararg variant for better calling conventions. */
  532. LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
  533. {
  534.   err_msgv(L, em);
  535. }

  536. /* Lexer error. */
  537. LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
  538.                             BCLine line, ErrMsg em, va_list argp)
  539. {
  540.   char buff[LUA_IDSIZE];
  541.   const char *msg;
  542.   lj_debug_shortname(buff, src, line);
  543.   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  544.   msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg);
  545.   if (tok)
  546.     lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
  547.   lj_err_throw(L, LUA_ERRSYNTAX);
  548. }

  549. /* Typecheck error for operands. */
  550. LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
  551. {
  552.   const char *tname = lj_typename(o);
  553.   const char *opname = err2msg(opm);
  554.   if (curr_funcisL(L)) {
  555.     GCproto *pt = curr_proto(L);
  556.     const BCIns *pc = cframe_Lpc(L) - 1;
  557.     const char *oname = NULL;
  558.     const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
  559.     if (kind)
  560.       err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
  561.   }
  562.   err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
  563. }

  564. /* Typecheck error for ordered comparisons. */
  565. LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
  566. {
  567.   const char *t1 = lj_typename(o1);
  568.   const char *t2 = lj_typename(o2);
  569.   err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
  570.   /* This assumes the two "boolean" entries are commoned by the C compiler. */
  571. }

  572. /* Typecheck error for __call. */
  573. LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
  574. {
  575.   /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
  576.   ** L->base still points to the caller. So add a dummy frame with L instead
  577.   ** of a function. See lua_getstack().
  578.   */
  579.   const BCIns *pc = cframe_Lpc(L);
  580.   if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
  581.     const char *tname = lj_typename(o);
  582.     if (LJ_FR2) o++;
  583.     setframe_pc(o, pc);
  584.     setframe_gc(o, obj2gco(L), LJ_TTHREAD);
  585.     L->top = L->base = o+1;
  586.     err_msgv(L, LJ_ERR_BADCALL, tname);
  587.   }
  588.   lj_err_optype(L, o, LJ_ERR_OPCALL);
  589. }

  590. /* Error in context of caller. */
  591. LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
  592. {
  593.   TValue *frame = L->base-1;
  594.   TValue *pframe = NULL;
  595.   if (frame_islua(frame)) {
  596.     pframe = frame_prevl(frame);
  597.   } else if (frame_iscont(frame)) {
  598.     if (frame_iscont_fficb(frame)) {
  599.       pframe = frame;
  600.       frame = NULL;
  601.     } else {
  602.       pframe = frame_prevd(frame);
  603. #if LJ_HASFFI
  604.       /* Remove frame for FFI metamethods. */
  605.       if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
  606.           frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
  607.         L->base = pframe+1;
  608.         L->top = frame;
  609.         setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
  610.       }
  611. #endif
  612.     }
  613.   }
  614.   lj_debug_addloc(L, msg, pframe, frame);
  615.   lj_err_run(L);
  616. }

  617. /* Formatted error in context of caller. */
  618. LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
  619. {
  620.   const char *msg;
  621.   va_list argp;
  622.   va_start(argp, em);
  623.   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  624.   va_end(argp);
  625.   lj_err_callermsg(L, msg);
  626. }

  627. /* Error in context of caller. */
  628. LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
  629. {
  630.   lj_err_callermsg(L, err2msg(em));
  631. }

  632. /* Argument error message. */
  633. LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
  634.                                             const char *msg)
  635. {
  636.   const char *fname = "?";
  637.   const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
  638.   if (narg < 0 && narg > LUA_REGISTRYINDEX)
  639.     narg = (int)(L->top - L->base) + narg + 1;
  640.   if (ftype && ftype[3] == 'h' && --narg == 0/* Check for "method". */
  641.     msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
  642.   else
  643.     msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
  644.   lj_err_callermsg(L, msg);
  645. }

  646. /* Formatted argument error. */
  647. LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
  648. {
  649.   const char *msg;
  650.   va_list argp;
  651.   va_start(argp, em);
  652.   msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  653.   va_end(argp);
  654.   err_argmsg(L, narg, msg);
  655. }

  656. /* Argument error. */
  657. LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
  658. {
  659.   err_argmsg(L, narg, err2msg(em));
  660. }

  661. /* Typecheck error for arguments. */
  662. LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
  663. {
  664.   const char *tname, *msg;
  665.   if (narg <= LUA_REGISTRYINDEX) {
  666.     if (narg >= LUA_GLOBALSINDEX) {
  667.       tname = lj_obj_itypename[~LJ_TTAB];
  668.     } else {
  669.       GCfunc *fn = curr_func(L);
  670.       int idx = LUA_GLOBALSINDEX - narg;
  671.       if (idx <= fn->c.nupvalues)
  672.         tname = lj_typename(&fn->c.upvalue[idx-1]);
  673.       else
  674.         tname = lj_obj_typename[0];
  675.     }
  676.   } else {
  677.     TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
  678.     tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
  679.   }
  680.   msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
  681.   err_argmsg(L, narg, msg);
  682. }

  683. /* Typecheck error for arguments. */
  684. LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
  685. {
  686.   lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
  687. }

  688. /* -- Public error handling API ------------------------------------------- */

  689. LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
  690. {
  691.   lua_CFunction old = G(L)->panic;
  692.   G(L)->panic = panicf;
  693.   return old;
  694. }

  695. /* Forwarders for the public API (C calling convention and no LJ_NORET). */
  696. LUA_API int lua_error(lua_State *L)
  697. {
  698.   lj_err_run(L);
  699.   return 0/* unreachable */
  700. }

  701. LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
  702. {
  703.   err_argmsg(L, narg, msg);
  704.   return 0/* unreachable */
  705. }

  706. LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
  707. {
  708.   lj_err_argtype(L, narg, xname);
  709.   return 0/* unreachable */
  710. }

  711. LUALIB_API void luaL_where(lua_State *L, int level)
  712. {
  713.   int size;
  714.   cTValue *frame = lj_debug_frame(L, level, &size);
  715.   lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
  716. }

  717. LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
  718. {
  719.   const char *msg;
  720.   va_list argp;
  721.   va_start(argp, fmt);
  722.   msg = lj_strfmt_pushvf(L, fmt, argp);
  723.   va_end(argp);
  724.   lj_err_callermsg(L, msg);
  725.   return 0/* unreachable */
  726. }