lj_err.c 23 KB

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