lj_err.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. /*
  2. ** Error handling.
  3. ** Copyright (C) 2005-2022 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. C modules used by Lua code can
  30. ** throw errors, so these need to have unwind tables, too. Transitively
  31. ** this applies to all system libraries used by C modules -- at least
  32. ** when they have callbacks which may throw an error.
  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. ** - INT needs to save *all* callee-saved registers when entering the
  38. ** interpreter. EXT only needs to save those actually used inside the
  39. ** interpreter. JIT-compiled code may need to save some more.
  40. **
  41. ** - EXT provides full interoperability with C++ exceptions. You can throw
  42. ** Lua errors or C++ exceptions through a mix of Lua frames and C++ frames.
  43. ** C++ destructors are called as needed. C++ exceptions caught by pcall
  44. ** are converted to the string "C++ exception". Lua errors can be caught
  45. ** with catch (...) in C++.
  46. **
  47. ** - INT has only limited support for automatically catching C++ exceptions
  48. ** on POSIX systems using DWARF2 stack unwinding. Other systems may use
  49. ** the wrapper function feature. Lua errors thrown through C++ frames
  50. ** cannot be caught by C++ code and C++ destructors are not run.
  51. **
  52. ** - EXT can handle errors from internal helper functions that are called
  53. ** from JIT-compiled code (except for Windows/x86 and 32 bit ARM).
  54. ** INT has no choice but to call the panic handler, if this happens.
  55. ** Note: this is mainly relevant for out-of-memory errors.
  56. **
  57. ** EXT is the default on all systems where the toolchain produces unwind
  58. ** tables by default (*). This is hard-coded and/or detected in src/Makefile.
  59. ** You can thwart the detection with: TARGET_XCFLAGS=-DLUAJIT_UNWIND_INTERNAL
  60. **
  61. ** INT is the default on all other systems.
  62. **
  63. ** EXT can be manually enabled for toolchains that are able to produce
  64. ** conforming unwind tables:
  65. ** "TARGET_XCFLAGS=-funwind-tables -DLUAJIT_UNWIND_EXTERNAL"
  66. ** As explained above, *all* C code used directly or indirectly by LuaJIT
  67. ** must be compiled with -funwind-tables (or -fexceptions). C++ code must
  68. ** *not* be compiled with -fno-exceptions.
  69. **
  70. ** If you're unsure whether error handling inside the VM works correctly,
  71. ** try running this and check whether it prints "OK":
  72. **
  73. ** luajit -e "print(select(2, load('OK')):match('OK'))"
  74. **
  75. ** (*) Originally, toolchains only generated unwind tables for C++ code. For
  76. ** interoperability reasons, this can be manually enabled for plain C code,
  77. ** too (with -funwind-tables). With the introduction of the x64 architecture,
  78. ** the corresponding POSIX and Windows ABIs mandated unwind tables for all
  79. ** code. Over the following years most desktop and server platforms have
  80. ** enabled unwind tables by default on all architectures. OTOH mobile and
  81. ** embedded platforms do not consistently mandate unwind tables.
  82. */
  83. /* -- Error messages ------------------------------------------------------ */
  84. /* Error message strings. */
  85. LJ_DATADEF const char *lj_err_allmsg =
  86. #define ERRDEF(name, msg) msg "\0"
  87. #include "lj_errmsg.h"
  88. ;
  89. /* -- Internal frame unwinding -------------------------------------------- */
  90. /* Unwind Lua stack and move error message to new top. */
  91. LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
  92. {
  93. lj_func_closeuv(L, top);
  94. if (top < L->top-1) {
  95. copyTV(L, top, L->top-1);
  96. L->top = top+1;
  97. }
  98. lj_state_relimitstack(L);
  99. }
  100. /* Unwind until stop frame. Optionally cleanup frames. */
  101. static void *err_unwind(lua_State *L, void *stopcf, int errcode)
  102. {
  103. TValue *frame = L->base-1;
  104. void *cf = L->cframe;
  105. while (cf) {
  106. int32_t nres = cframe_nres(cframe_raw(cf));
  107. if (nres < 0) { /* C frame without Lua frame? */
  108. TValue *top = restorestack(L, -nres);
  109. if (frame < top) { /* Frame reached? */
  110. if (errcode) {
  111. L->base = frame+1;
  112. L->cframe = cframe_prev(cf);
  113. unwindstack(L, top);
  114. }
  115. return cf;
  116. }
  117. }
  118. if (frame <= tvref(L->stack)+LJ_FR2)
  119. break;
  120. switch (frame_typep(frame)) {
  121. case FRAME_LUA: /* Lua frame. */
  122. case FRAME_LUAP:
  123. frame = frame_prevl(frame);
  124. break;
  125. case FRAME_C: /* C frame. */
  126. unwind_c:
  127. #if LJ_UNWIND_EXT
  128. if (errcode) {
  129. L->base = frame_prevd(frame) + 1;
  130. L->cframe = cframe_prev(cf);
  131. unwindstack(L, frame - LJ_FR2);
  132. } else if (cf != stopcf) {
  133. cf = cframe_prev(cf);
  134. frame = frame_prevd(frame);
  135. break;
  136. }
  137. return NULL; /* Continue unwinding. */
  138. #else
  139. UNUSED(stopcf);
  140. cf = cframe_prev(cf);
  141. frame = frame_prevd(frame);
  142. break;
  143. #endif
  144. case FRAME_CP: /* Protected C frame. */
  145. if (cframe_canyield(cf)) { /* Resume? */
  146. if (errcode) {
  147. hook_leave(G(L)); /* Assumes nobody uses coroutines inside hooks. */
  148. L->cframe = NULL;
  149. L->status = (uint8_t)errcode;
  150. }
  151. return cf;
  152. }
  153. if (errcode) {
  154. L->base = frame_prevd(frame) + 1;
  155. L->cframe = cframe_prev(cf);
  156. unwindstack(L, frame - LJ_FR2);
  157. }
  158. return cf;
  159. case FRAME_CONT: /* Continuation frame. */
  160. if (frame_iscont_fficb(frame))
  161. goto unwind_c;
  162. /* fallthrough */
  163. case FRAME_VARG: /* Vararg frame. */
  164. frame = frame_prevd(frame);
  165. break;
  166. case FRAME_PCALL: /* FF pcall() frame. */
  167. case FRAME_PCALLH: /* FF pcall() frame inside hook. */
  168. if (errcode) {
  169. if (errcode == LUA_YIELD) {
  170. frame = frame_prevd(frame);
  171. break;
  172. }
  173. if (frame_typep(frame) == FRAME_PCALL)
  174. hook_leave(G(L));
  175. L->base = frame_prevd(frame) + 1;
  176. L->cframe = cf;
  177. unwindstack(L, L->base);
  178. }
  179. return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
  180. }
  181. }
  182. /* No C frame. */
  183. if (errcode) {
  184. L->base = tvref(L->stack)+1+LJ_FR2;
  185. L->cframe = NULL;
  186. unwindstack(L, L->base);
  187. if (G(L)->panic)
  188. G(L)->panic(L);
  189. exit(EXIT_FAILURE);
  190. }
  191. return L; /* Anything non-NULL will do. */
  192. }
  193. /* -- External frame unwinding -------------------------------------------- */
  194. #if LJ_ABI_WIN
  195. /*
  196. ** Someone in Redmond owes me several days of my life. A lot of this is
  197. ** undocumented or just plain wrong on MSDN. Some of it can be gathered
  198. ** from 3rd party docs or must be found by trial-and-error. They really
  199. ** don't want you to write your own language-specific exception handler
  200. ** or to interact gracefully with MSVC. :-(
  201. **
  202. ** Apparently MSVC doesn't call C++ destructors for foreign exceptions
  203. ** unless you compile your C++ code with /EHa. Unfortunately this means
  204. ** catch (...) also catches things like access violations. The use of
  205. ** _set_se_translator doesn't really help, because it requires /EHa, too.
  206. */
  207. #define WIN32_LEAN_AND_MEAN
  208. #include <windows.h>
  209. #if LJ_TARGET_X86
  210. typedef void *UndocumentedDispatcherContext; /* Unused on x86. */
  211. #else
  212. /* Taken from: http://www.nynaeve.net/?p=99 */
  213. typedef struct UndocumentedDispatcherContext {
  214. ULONG64 ControlPc;
  215. ULONG64 ImageBase;
  216. PRUNTIME_FUNCTION FunctionEntry;
  217. ULONG64 EstablisherFrame;
  218. ULONG64 TargetIp;
  219. PCONTEXT ContextRecord;
  220. void (*LanguageHandler)(void);
  221. PVOID HandlerData;
  222. PUNWIND_HISTORY_TABLE HistoryTable;
  223. ULONG ScopeIndex;
  224. ULONG Fill0;
  225. } UndocumentedDispatcherContext;
  226. #endif
  227. /* Another wild guess. */
  228. extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
  229. #if LJ_TARGET_X64 && defined(MINGW_SDK_INIT)
  230. /* Workaround for broken MinGW64 declaration. */
  231. VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
  232. #define RtlUnwindEx RtlUnwindEx_FIXED
  233. #endif
  234. #define LJ_MSVC_EXCODE ((DWORD)0xe06d7363)
  235. #define LJ_GCC_EXCODE ((DWORD)0x20474343)
  236. #define LJ_EXCODE ((DWORD)0xe24c4a00)
  237. #define LJ_EXCODE_MAKE(c) (LJ_EXCODE | (DWORD)(c))
  238. #define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff)
  239. #define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff))
  240. /* Windows exception handler for interpreter frame. */
  241. LJ_FUNCA int lj_err_unwind_win(EXCEPTION_RECORD *rec,
  242. void *f, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
  243. {
  244. #if LJ_TARGET_X86
  245. void *cf = (char *)f - CFRAME_OFS_SEH;
  246. #else
  247. void *cf = f;
  248. #endif
  249. lua_State *L = cframe_L(cf);
  250. int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
  251. LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
  252. if ((rec->ExceptionFlags & 6)) { /* EH_UNWINDING|EH_EXIT_UNWIND */
  253. /* Unwind internal frames. */
  254. err_unwind(L, cf, errcode);
  255. } else {
  256. void *cf2 = err_unwind(L, cf, 0);
  257. if (cf2) { /* We catch it, so start unwinding the upper frames. */
  258. if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
  259. rec->ExceptionCode == LJ_GCC_EXCODE) {
  260. #if !LJ_TARGET_CYGWIN
  261. __DestructExceptionObject(rec, 1);
  262. #endif
  263. setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  264. } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
  265. /* Don't catch access violations etc. */
  266. return 1; /* ExceptionContinueSearch */
  267. }
  268. #if LJ_TARGET_X86
  269. UNUSED(ctx);
  270. UNUSED(dispatch);
  271. /* Call all handlers for all lower C frames (including ourselves) again
  272. ** with EH_UNWINDING set. Then call the specified function, passing cf
  273. ** and errcode.
  274. */
  275. lj_vm_rtlunwind(cf, (void *)rec,
  276. (cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
  277. (void *)lj_vm_unwind_ff : (void *)lj_vm_unwind_c, errcode);
  278. /* lj_vm_rtlunwind does not return. */
  279. #else
  280. /* Unwind the stack and call all handlers for all lower C frames
  281. ** (including ourselves) again with EH_UNWINDING set. Then set
  282. ** stack pointer = cf, result = errcode and jump to the specified target.
  283. */
  284. RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
  285. lj_vm_unwind_ff_eh :
  286. lj_vm_unwind_c_eh),
  287. rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
  288. /* RtlUnwindEx should never return. */
  289. #endif
  290. }
  291. }
  292. return 1; /* ExceptionContinueSearch */
  293. }
  294. #if LJ_UNWIND_JIT
  295. #if LJ_TARGET_X64
  296. #define CONTEXT_REG_PC Rip
  297. #elif LJ_TARGET_ARM64
  298. #define CONTEXT_REG_PC Pc
  299. #else
  300. #error "NYI: Windows arch-specific unwinder for JIT-compiled code"
  301. #endif
  302. /* Windows unwinder for JIT-compiled code. */
  303. static void err_unwind_win_jit(global_State *g, int errcode)
  304. {
  305. CONTEXT ctx;
  306. UNWIND_HISTORY_TABLE hist;
  307. memset(&hist, 0, sizeof(hist));
  308. RtlCaptureContext(&ctx);
  309. while (1) {
  310. DWORD64 frame, base, addr = ctx.CONTEXT_REG_PC;
  311. void *hdata;
  312. PRUNTIME_FUNCTION func = RtlLookupFunctionEntry(addr, &base, &hist);
  313. if (!func) { /* Found frame without .pdata: must be JIT-compiled code. */
  314. ExitNo exitno;
  315. uintptr_t stub = lj_trace_unwind(G2J(g), (uintptr_t)(addr - sizeof(MCode)), &exitno);
  316. if (stub) { /* Jump to side exit to unwind the trace. */
  317. ctx.CONTEXT_REG_PC = stub;
  318. G2J(g)->exitcode = errcode;
  319. RtlRestoreContext(&ctx, NULL); /* Does not return. */
  320. }
  321. break;
  322. }
  323. RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, addr, func,
  324. &ctx, &hdata, &frame, NULL);
  325. if (!addr) break;
  326. }
  327. /* Unwinding failed, if we end up here. */
  328. }
  329. #endif
  330. /* Raise Windows exception. */
  331. static void err_raise_ext(global_State *g, int errcode)
  332. {
  333. #if LJ_UNWIND_JIT
  334. if (tvref(g->jit_base)) {
  335. err_unwind_win_jit(g, errcode);
  336. return; /* Unwinding failed. */
  337. }
  338. #elif LJ_HASJIT
  339. /* Cannot catch on-trace errors for Windows/x86 SEH. Unwind to interpreter. */
  340. setmref(g->jit_base, NULL);
  341. #endif
  342. UNUSED(g);
  343. RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
  344. }
  345. #elif !LJ_NO_UNWIND && (defined(__GNUC__) || defined(__clang__))
  346. /*
  347. ** We have to use our own definitions instead of the mandatory (!) unwind.h,
  348. ** since various OS, distros and compilers mess up the header installation.
  349. */
  350. typedef struct _Unwind_Context _Unwind_Context;
  351. #define _URC_OK 0
  352. #define _URC_FATAL_PHASE2_ERROR 2
  353. #define _URC_FATAL_PHASE1_ERROR 3
  354. #define _URC_HANDLER_FOUND 6
  355. #define _URC_INSTALL_CONTEXT 7
  356. #define _URC_CONTINUE_UNWIND 8
  357. #define _URC_FAILURE 9
  358. #define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */
  359. #define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c))
  360. #define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff)
  361. #define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff))
  362. #if !LJ_TARGET_ARM
  363. typedef struct _Unwind_Exception
  364. {
  365. uint64_t exclass;
  366. void (*excleanup)(int, struct _Unwind_Exception *);
  367. uintptr_t p1, p2;
  368. } __attribute__((__aligned__)) _Unwind_Exception;
  369. #define UNWIND_EXCEPTION_TYPE _Unwind_Exception
  370. extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
  371. extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
  372. extern uintptr_t _Unwind_GetIP(_Unwind_Context *);
  373. extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
  374. extern void _Unwind_DeleteException(_Unwind_Exception *);
  375. extern int _Unwind_RaiseException(_Unwind_Exception *);
  376. #define _UA_SEARCH_PHASE 1
  377. #define _UA_CLEANUP_PHASE 2
  378. #define _UA_HANDLER_FRAME 4
  379. #define _UA_FORCE_UNWIND 8
  380. /* DWARF2 personality handler referenced from interpreter .eh_frame. */
  381. LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
  382. uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
  383. {
  384. void *cf;
  385. lua_State *L;
  386. if (version != 1)
  387. return _URC_FATAL_PHASE1_ERROR;
  388. cf = (void *)_Unwind_GetCFA(ctx);
  389. L = cframe_L(cf);
  390. if ((actions & _UA_SEARCH_PHASE)) {
  391. #if LJ_UNWIND_EXT
  392. if (err_unwind(L, cf, 0) == NULL)
  393. return _URC_CONTINUE_UNWIND;
  394. #endif
  395. if (!LJ_UEXCLASS_CHECK(uexclass)) {
  396. setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  397. }
  398. return _URC_HANDLER_FOUND;
  399. }
  400. if ((actions & _UA_CLEANUP_PHASE)) {
  401. int errcode;
  402. if (LJ_UEXCLASS_CHECK(uexclass)) {
  403. errcode = LJ_UEXCLASS_ERRCODE(uexclass);
  404. } else {
  405. if ((actions & _UA_HANDLER_FRAME))
  406. _Unwind_DeleteException(uex);
  407. errcode = LUA_ERRRUN;
  408. }
  409. #if LJ_UNWIND_EXT
  410. cf = err_unwind(L, cf, errcode);
  411. if ((actions & _UA_FORCE_UNWIND)) {
  412. return _URC_CONTINUE_UNWIND;
  413. } else if (cf) {
  414. ASMFunction ip;
  415. _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
  416. ip = cframe_unwind_ff(cf) ? lj_vm_unwind_ff_eh : lj_vm_unwind_c_eh;
  417. _Unwind_SetIP(ctx, (uintptr_t)lj_ptr_strip(ip));
  418. return _URC_INSTALL_CONTEXT;
  419. }
  420. #if LJ_TARGET_X86ORX64
  421. else if ((actions & _UA_HANDLER_FRAME)) {
  422. /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
  423. ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
  424. */
  425. _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
  426. _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
  427. return _URC_INSTALL_CONTEXT;
  428. }
  429. #endif
  430. #else
  431. /* This is not the proper way to escape from the unwinder. We get away with
  432. ** it on non-x64 because the interpreter restores all callee-saved regs.
  433. */
  434. lj_err_throw(L, errcode);
  435. #if LJ_TARGET_X64
  436. #error "Broken build system -- only use the provided Makefiles!"
  437. #endif
  438. #endif
  439. }
  440. return _URC_CONTINUE_UNWIND;
  441. }
  442. #if LJ_UNWIND_EXT && defined(LUA_USE_ASSERT)
  443. struct dwarf_eh_bases { void *tbase, *dbase, *func; };
  444. extern const void *_Unwind_Find_FDE(void *pc, struct dwarf_eh_bases *bases);
  445. /* Verify that external error handling actually has a chance to work. */
  446. void lj_err_verify(void)
  447. {
  448. #if !LJ_TARGET_OSX
  449. /* Check disabled on MacOS due to brilliant software engineering at Apple. */
  450. struct dwarf_eh_bases ehb;
  451. lj_assertX(_Unwind_Find_FDE((void *)lj_err_throw, &ehb), "broken build: external frame unwinding enabled, but missing -funwind-tables");
  452. #endif
  453. /* Check disabled, because of broken Fedora/ARM64. See #722.
  454. lj_assertX(_Unwind_Find_FDE((void *)_Unwind_RaiseException, &ehb), "broken build: external frame unwinding enabled, but system libraries have no unwind tables");
  455. */
  456. }
  457. #endif
  458. #if LJ_UNWIND_JIT
  459. /* DWARF2 personality handler for JIT-compiled code. */
  460. static int err_unwind_jit(int version, int actions,
  461. uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
  462. {
  463. /* NYI: FFI C++ exception interoperability. */
  464. if (version != 1 || !LJ_UEXCLASS_CHECK(uexclass))
  465. return _URC_FATAL_PHASE1_ERROR;
  466. if ((actions & _UA_SEARCH_PHASE)) {
  467. return _URC_HANDLER_FOUND;
  468. }
  469. if ((actions & _UA_CLEANUP_PHASE)) {
  470. global_State *g = *(global_State **)(uex+1);
  471. ExitNo exitno;
  472. uintptr_t addr = _Unwind_GetIP(ctx); /* Return address _after_ call. */
  473. uintptr_t stub = lj_trace_unwind(G2J(g), addr - sizeof(MCode), &exitno);
  474. lj_assertG(tvref(g->jit_base), "unexpected throw across mcode frame");
  475. if (stub) { /* Jump to side exit to unwind the trace. */
  476. G2J(g)->exitcode = LJ_UEXCLASS_ERRCODE(uexclass);
  477. #ifdef LJ_TARGET_MIPS
  478. _Unwind_SetGR(ctx, 4, stub);
  479. _Unwind_SetGR(ctx, 5, exitno);
  480. _Unwind_SetIP(ctx, (uintptr_t)(void *)lj_vm_unwind_stub);
  481. #else
  482. _Unwind_SetIP(ctx, stub);
  483. #endif
  484. return _URC_INSTALL_CONTEXT;
  485. }
  486. return _URC_FATAL_PHASE2_ERROR;
  487. }
  488. return _URC_FATAL_PHASE1_ERROR;
  489. }
  490. /* DWARF2 template frame info for JIT-compiled code.
  491. **
  492. ** After copying the template to the start of the mcode segment,
  493. ** the frame handler function and the code size is patched.
  494. ** The frame handler always installs a new context to jump to the exit,
  495. ** so don't bother to add any unwind opcodes.
  496. */
  497. static const uint8_t err_frame_jit_template[] = {
  498. #if LJ_BE
  499. 0,0,0,
  500. #endif
  501. LJ_64 ? 0x1c : 0x14, /* CIE length. */
  502. #if LJ_LE
  503. 0,0,0,
  504. #endif
  505. 0,0,0,0, 1, 'z','P','R',0, /* CIE mark, CIE version, augmentation. */
  506. 1, LJ_64 ? 0x78 : 0x7c, LJ_TARGET_EHRAREG, /* Code/data align, RA. */
  507. #if LJ_64
  508. 10, 0, 0,0,0,0,0,0,0,0, 0x1b, /* Aug. data ABS handler, PCREL|SDATA4 code. */
  509. 0,0,0,0,0, /* Alignment. */
  510. #else
  511. 6, 0, 0,0,0,0, 0x1b, /* Aug. data ABS handler, PCREL|SDATA4 code. */
  512. 0, /* Alignment. */
  513. #endif
  514. #if LJ_BE
  515. 0,0,0,
  516. #endif
  517. LJ_64 ? 0x14 : 0x10, /* FDE length. */
  518. 0,0,0,
  519. LJ_64 ? 0x24 : 0x1c, /* CIE offset. */
  520. 0,0,0,
  521. LJ_64 ? 0x14 : 0x10, /* Code offset. After Final FDE. */
  522. #if LJ_LE
  523. 0,0,0,
  524. #endif
  525. 0,0,0,0, 0, 0,0,0, /* Code size, augmentation length, alignment. */
  526. #if LJ_64
  527. 0,0,0,0, /* Alignment. */
  528. #endif
  529. 0,0,0,0 /* Final FDE. */
  530. };
  531. #define ERR_FRAME_JIT_OFS_HANDLER 0x12
  532. #define ERR_FRAME_JIT_OFS_FDE (LJ_64 ? 0x20 : 0x18)
  533. #define ERR_FRAME_JIT_OFS_CODE_SIZE (LJ_64 ? 0x2c : 0x24)
  534. #if LJ_TARGET_OSX
  535. #define ERR_FRAME_JIT_OFS_REGISTER ERR_FRAME_JIT_OFS_FDE
  536. #else
  537. #define ERR_FRAME_JIT_OFS_REGISTER 0
  538. #endif
  539. extern void __register_frame(const void *);
  540. extern void __deregister_frame(const void *);
  541. uint8_t *lj_err_register_mcode(void *base, size_t sz, uint8_t *info)
  542. {
  543. ASMFunction handler = (ASMFunction)err_unwind_jit;
  544. memcpy(info, err_frame_jit_template, sizeof(err_frame_jit_template));
  545. #if LJ_ABI_PAUTH
  546. #if LJ_TARGET_ARM64
  547. handler = ptrauth_auth_and_resign(handler,
  548. ptrauth_key_function_pointer, 0,
  549. ptrauth_key_process_independent_code, info + ERR_FRAME_JIT_OFS_HANDLER);
  550. #else
  551. #error "missing pointer authentication support for this architecture"
  552. #endif
  553. #endif
  554. memcpy(info + ERR_FRAME_JIT_OFS_HANDLER, &handler, sizeof(handler));
  555. *(uint32_t *)(info + ERR_FRAME_JIT_OFS_CODE_SIZE) =
  556. (uint32_t)(sz - sizeof(err_frame_jit_template) - (info - (uint8_t *)base));
  557. __register_frame(info + ERR_FRAME_JIT_OFS_REGISTER);
  558. #ifdef LUA_USE_ASSERT
  559. {
  560. struct dwarf_eh_bases ehb;
  561. lj_assertX(_Unwind_Find_FDE(info + sizeof(err_frame_jit_template)+1, &ehb),
  562. "bad JIT unwind table registration");
  563. }
  564. #endif
  565. return info + sizeof(err_frame_jit_template);
  566. }
  567. void lj_err_deregister_mcode(void *base, size_t sz, uint8_t *info)
  568. {
  569. UNUSED(base); UNUSED(sz);
  570. __deregister_frame(info + ERR_FRAME_JIT_OFS_REGISTER);
  571. }
  572. #endif
  573. #else /* LJ_TARGET_ARM */
  574. #define _US_VIRTUAL_UNWIND_FRAME 0
  575. #define _US_UNWIND_FRAME_STARTING 1
  576. #define _US_ACTION_MASK 3
  577. #define _US_FORCE_UNWIND 8
  578. typedef struct _Unwind_Control_Block _Unwind_Control_Block;
  579. #define UNWIND_EXCEPTION_TYPE _Unwind_Control_Block
  580. struct _Unwind_Control_Block {
  581. uint64_t exclass;
  582. uint32_t misc[20];
  583. };
  584. extern int _Unwind_RaiseException(_Unwind_Control_Block *);
  585. extern int __gnu_unwind_frame(_Unwind_Control_Block *, _Unwind_Context *);
  586. extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
  587. extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
  588. static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
  589. {
  590. uint32_t v;
  591. _Unwind_VRS_Get(ctx, 0, r, 0, &v);
  592. return v;
  593. }
  594. static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
  595. {
  596. _Unwind_VRS_Set(ctx, 0, r, 0, &v);
  597. }
  598. extern void lj_vm_unwind_ext(void);
  599. /* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
  600. LJ_FUNCA int lj_err_unwind_arm(int state, _Unwind_Control_Block *ucb,
  601. _Unwind_Context *ctx)
  602. {
  603. void *cf = (void *)_Unwind_GetGR(ctx, 13);
  604. lua_State *L = cframe_L(cf);
  605. int errcode;
  606. switch ((state & _US_ACTION_MASK)) {
  607. case _US_VIRTUAL_UNWIND_FRAME:
  608. if ((state & _US_FORCE_UNWIND)) break;
  609. return _URC_HANDLER_FOUND;
  610. case _US_UNWIND_FRAME_STARTING:
  611. if (LJ_UEXCLASS_CHECK(ucb->exclass)) {
  612. errcode = LJ_UEXCLASS_ERRCODE(ucb->exclass);
  613. } else {
  614. errcode = LUA_ERRRUN;
  615. setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
  616. }
  617. cf = err_unwind(L, cf, errcode);
  618. if ((state & _US_FORCE_UNWIND) || cf == NULL) break;
  619. _Unwind_SetGR(ctx, 15, (uint32_t)lj_vm_unwind_ext);
  620. _Unwind_SetGR(ctx, 0, (uint32_t)ucb);
  621. _Unwind_SetGR(ctx, 1, (uint32_t)errcode);
  622. _Unwind_SetGR(ctx, 2, cframe_unwind_ff(cf) ?
  623. (uint32_t)lj_vm_unwind_ff_eh :
  624. (uint32_t)lj_vm_unwind_c_eh);
  625. return _URC_INSTALL_CONTEXT;
  626. default:
  627. return _URC_FAILURE;
  628. }
  629. if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
  630. return _URC_FAILURE;
  631. #ifdef LUA_USE_ASSERT
  632. /* We should never get here unless this is a forced unwind aka backtrace. */
  633. if (_Unwind_GetGR(ctx, 0) == 0xff33aa77) {
  634. _Unwind_SetGR(ctx, 0, 0xff33aa88);
  635. }
  636. #endif
  637. return _URC_CONTINUE_UNWIND;
  638. }
  639. #if LJ_UNWIND_EXT && defined(LUA_USE_ASSERT)
  640. typedef int (*_Unwind_Trace_Fn)(_Unwind_Context *, void *);
  641. extern int _Unwind_Backtrace(_Unwind_Trace_Fn, void *);
  642. static int err_verify_bt(_Unwind_Context *ctx, int *got)
  643. {
  644. if (_Unwind_GetGR(ctx, 0) == 0xff33aa88) { *got = 2; }
  645. else if (*got == 0) { *got = 1; _Unwind_SetGR(ctx, 0, 0xff33aa77); }
  646. return _URC_OK;
  647. }
  648. /* Verify that external error handling actually has a chance to work. */
  649. void lj_err_verify(void)
  650. {
  651. int got = 0;
  652. _Unwind_Backtrace((_Unwind_Trace_Fn)err_verify_bt, &got);
  653. lj_assertX(got == 2, "broken build: external frame unwinding enabled, but missing -funwind-tables");
  654. }
  655. #endif
  656. /*
  657. ** Note: LJ_UNWIND_JIT is not implemented for 32 bit ARM.
  658. **
  659. ** The quirky ARM unwind API doesn't have __register_frame().
  660. ** A potential workaround might involve _Unwind_Backtrace.
  661. ** But most 32 bit ARM targets don't qualify for LJ_UNWIND_EXT, anyway,
  662. ** since they are built without unwind tables by default.
  663. */
  664. #endif /* LJ_TARGET_ARM */
  665. #if LJ_UNWIND_EXT
  666. static __thread struct {
  667. UNWIND_EXCEPTION_TYPE ex;
  668. global_State *g;
  669. } static_uex;
  670. /* Raise external exception. */
  671. static void err_raise_ext(global_State *g, int errcode)
  672. {
  673. memset(&static_uex, 0, sizeof(static_uex));
  674. static_uex.ex.exclass = LJ_UEXCLASS_MAKE(errcode);
  675. static_uex.g = g;
  676. _Unwind_RaiseException(&static_uex.ex);
  677. }
  678. #endif
  679. #endif
  680. /* -- Error handling ------------------------------------------------------ */
  681. /* Throw error. Find catch frame, unwind stack and continue. */
  682. LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
  683. {
  684. global_State *g = G(L);
  685. lj_trace_abort(g);
  686. L->status = LUA_OK;
  687. #if LJ_UNWIND_EXT
  688. err_raise_ext(g, errcode);
  689. /*
  690. ** A return from this function signals a corrupt C stack that cannot be
  691. ** unwound. We have no choice but to call the panic function and exit.
  692. **
  693. ** Usually this is caused by a C function without unwind information.
  694. ** This may happen if you've manually enabled LUAJIT_UNWIND_EXTERNAL
  695. ** and forgot to recompile *every* non-C++ file with -funwind-tables.
  696. */
  697. if (G(L)->panic)
  698. G(L)->panic(L);
  699. #else
  700. #if LJ_HASJIT
  701. setmref(g->jit_base, NULL);
  702. #endif
  703. {
  704. void *cf = err_unwind(L, NULL, errcode);
  705. if (cframe_unwind_ff(cf))
  706. lj_vm_unwind_ff(cframe_raw(cf));
  707. else
  708. lj_vm_unwind_c(cframe_raw(cf), errcode);
  709. }
  710. #endif
  711. exit(EXIT_FAILURE);
  712. }
  713. /* Return string object for error message. */
  714. LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
  715. {
  716. return lj_str_newz(L, err2msg(em));
  717. }
  718. /* Out-of-memory error. */
  719. LJ_NOINLINE void lj_err_mem(lua_State *L)
  720. {
  721. if (L->status == LUA_ERRERR+1) /* Don't touch the stack during lua_open. */
  722. lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
  723. if (LJ_HASJIT) {
  724. TValue *base = tvref(G(L)->jit_base);
  725. if (base) L->base = base;
  726. }
  727. if (curr_funcisL(L)) L->top = curr_topL(L);
  728. setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
  729. lj_err_throw(L, LUA_ERRMEM);
  730. }
  731. /* Find error function for runtime errors. Requires an extra stack traversal. */
  732. static ptrdiff_t finderrfunc(lua_State *L)
  733. {
  734. cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2;
  735. void *cf = L->cframe;
  736. while (frame > bot && cf) {
  737. while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */
  738. if (frame >= restorestack(L, -cframe_nres(cf)))
  739. break;
  740. if (cframe_errfunc(cf) >= 0) /* Error handler not inherited (-1)? */
  741. return cframe_errfunc(cf);
  742. cf = cframe_prev(cf); /* Else unwind cframe and continue searching. */
  743. if (cf == NULL)
  744. return 0;
  745. }
  746. switch (frame_typep(frame)) {
  747. case FRAME_LUA:
  748. case FRAME_LUAP:
  749. frame = frame_prevl(frame);
  750. break;
  751. case FRAME_C:
  752. cf = cframe_prev(cf);
  753. /* fallthrough */
  754. case FRAME_VARG:
  755. frame = frame_prevd(frame);
  756. break;
  757. case FRAME_CONT:
  758. if (frame_iscont_fficb(frame))
  759. cf = cframe_prev(cf);
  760. frame = frame_prevd(frame);
  761. break;
  762. case FRAME_CP:
  763. if (cframe_canyield(cf)) return 0;
  764. if (cframe_errfunc(cf) >= 0)
  765. return cframe_errfunc(cf);
  766. cf = cframe_prev(cf);
  767. frame = frame_prevd(frame);
  768. break;
  769. case FRAME_PCALL:
  770. case FRAME_PCALLH:
  771. if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall)
  772. return savestack(L, frame_prevd(frame)+1); /* xpcall's errorfunc. */
  773. return 0;
  774. default:
  775. lj_assertL(0, "bad frame type");
  776. return 0;
  777. }
  778. }
  779. return 0;
  780. }
  781. /* Runtime error. */
  782. LJ_NOINLINE void LJ_FASTCALL lj_err_run(lua_State *L)
  783. {
  784. ptrdiff_t ef = (LJ_HASJIT && tvref(G(L)->jit_base)) ? 0 : finderrfunc(L);
  785. if (ef) {
  786. TValue *errfunc = restorestack(L, ef);
  787. TValue *top = L->top;
  788. lj_trace_abort(G(L));
  789. if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
  790. setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
  791. lj_err_throw(L, LUA_ERRERR);
  792. }
  793. L->status = LUA_ERRERR;
  794. copyTV(L, top+LJ_FR2, top-1);
  795. copyTV(L, top-1, errfunc);
  796. if (LJ_FR2) setnilV(top++);
  797. L->top = top+1;
  798. lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */
  799. }
  800. lj_err_throw(L, LUA_ERRRUN);
  801. }
  802. #if LJ_HASJIT
  803. LJ_NOINLINE void LJ_FASTCALL lj_err_trace(lua_State *L, int errcode)
  804. {
  805. if (errcode == LUA_ERRRUN)
  806. lj_err_run(L);
  807. else
  808. lj_err_throw(L, errcode);
  809. }
  810. #endif
  811. /* Formatted runtime error message. */
  812. LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
  813. {
  814. const char *msg;
  815. va_list argp;
  816. va_start(argp, em);
  817. if (LJ_HASJIT) {
  818. TValue *base = tvref(G(L)->jit_base);
  819. if (base) L->base = base;
  820. }
  821. if (curr_funcisL(L)) L->top = curr_topL(L);
  822. msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  823. va_end(argp);
  824. lj_debug_addloc(L, msg, L->base-1, NULL);
  825. lj_err_run(L);
  826. }
  827. /* Non-vararg variant for better calling conventions. */
  828. LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
  829. {
  830. err_msgv(L, em);
  831. }
  832. /* Lexer error. */
  833. LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
  834. BCLine line, ErrMsg em, va_list argp)
  835. {
  836. char buff[LUA_IDSIZE];
  837. const char *msg;
  838. lj_debug_shortname(buff, src, line);
  839. msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  840. msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg);
  841. if (tok)
  842. lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
  843. lj_err_throw(L, LUA_ERRSYNTAX);
  844. }
  845. /* Typecheck error for operands. */
  846. LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
  847. {
  848. const char *tname = lj_typename(o);
  849. const char *opname = err2msg(opm);
  850. if (curr_funcisL(L)) {
  851. GCproto *pt = curr_proto(L);
  852. const BCIns *pc = cframe_Lpc(L) - 1;
  853. const char *oname = NULL;
  854. const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
  855. if (kind)
  856. err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
  857. }
  858. err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
  859. }
  860. /* Typecheck error for ordered comparisons. */
  861. LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
  862. {
  863. const char *t1 = lj_typename(o1);
  864. const char *t2 = lj_typename(o2);
  865. err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
  866. /* This assumes the two "boolean" entries are commoned by the C compiler. */
  867. }
  868. /* Typecheck error for __call. */
  869. LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
  870. {
  871. /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
  872. ** L->base still points to the caller. So add a dummy frame with L instead
  873. ** of a function. See lua_getstack().
  874. */
  875. const BCIns *pc = cframe_Lpc(L);
  876. if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
  877. const char *tname = lj_typename(o);
  878. setframe_gc(o, obj2gco(L), LJ_TTHREAD);
  879. if (LJ_FR2) o++;
  880. setframe_pc(o, pc);
  881. L->top = L->base = o+1;
  882. err_msgv(L, LJ_ERR_BADCALL, tname);
  883. }
  884. lj_err_optype(L, o, LJ_ERR_OPCALL);
  885. }
  886. /* Error in context of caller. */
  887. LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
  888. {
  889. TValue *frame = NULL, *pframe = NULL;
  890. if (!(LJ_HASJIT && tvref(G(L)->jit_base))) {
  891. frame = L->base-1;
  892. if (frame_islua(frame)) {
  893. pframe = frame_prevl(frame);
  894. } else if (frame_iscont(frame)) {
  895. if (frame_iscont_fficb(frame)) {
  896. pframe = frame;
  897. frame = NULL;
  898. } else {
  899. pframe = frame_prevd(frame);
  900. #if LJ_HASFFI
  901. /* Remove frame for FFI metamethods. */
  902. if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
  903. frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
  904. L->base = pframe+1;
  905. L->top = frame;
  906. setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
  907. }
  908. #endif
  909. }
  910. }
  911. }
  912. lj_debug_addloc(L, msg, pframe, frame);
  913. lj_err_run(L);
  914. }
  915. /* Formatted error in context of caller. */
  916. LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
  917. {
  918. const char *msg;
  919. va_list argp;
  920. va_start(argp, em);
  921. msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  922. va_end(argp);
  923. lj_err_callermsg(L, msg);
  924. }
  925. /* Error in context of caller. */
  926. LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
  927. {
  928. lj_err_callermsg(L, err2msg(em));
  929. }
  930. /* Argument error message. */
  931. LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
  932. const char *msg)
  933. {
  934. const char *fname = "?";
  935. const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
  936. if (narg < 0 && narg > LUA_REGISTRYINDEX)
  937. narg = (int)(L->top - L->base) + narg + 1;
  938. if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */
  939. msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
  940. else
  941. msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
  942. lj_err_callermsg(L, msg);
  943. }
  944. /* Formatted argument error. */
  945. LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
  946. {
  947. const char *msg;
  948. va_list argp;
  949. va_start(argp, em);
  950. msg = lj_strfmt_pushvf(L, err2msg(em), argp);
  951. va_end(argp);
  952. err_argmsg(L, narg, msg);
  953. }
  954. /* Argument error. */
  955. LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
  956. {
  957. err_argmsg(L, narg, err2msg(em));
  958. }
  959. /* Typecheck error for arguments. */
  960. LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
  961. {
  962. const char *tname, *msg;
  963. if (narg <= LUA_REGISTRYINDEX) {
  964. if (narg >= LUA_GLOBALSINDEX) {
  965. tname = lj_obj_itypename[~LJ_TTAB];
  966. } else {
  967. GCfunc *fn = curr_func(L);
  968. int idx = LUA_GLOBALSINDEX - narg;
  969. if (idx <= fn->c.nupvalues)
  970. tname = lj_typename(&fn->c.upvalue[idx-1]);
  971. else
  972. tname = lj_obj_typename[0];
  973. }
  974. } else {
  975. TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
  976. tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
  977. }
  978. msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
  979. err_argmsg(L, narg, msg);
  980. }
  981. /* Typecheck error for arguments. */
  982. LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
  983. {
  984. lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
  985. }
  986. /* -- Public error handling API ------------------------------------------- */
  987. LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
  988. {
  989. lua_CFunction old = G(L)->panic;
  990. G(L)->panic = panicf;
  991. return old;
  992. }
  993. /* Forwarders for the public API (C calling convention and no LJ_NORET). */
  994. LUA_API int lua_error(lua_State *L)
  995. {
  996. lj_err_run(L);
  997. return 0; /* unreachable */
  998. }
  999. LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
  1000. {
  1001. err_argmsg(L, narg, msg);
  1002. return 0; /* unreachable */
  1003. }
  1004. LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
  1005. {
  1006. lj_err_argtype(L, narg, xname);
  1007. return 0; /* unreachable */
  1008. }
  1009. LUALIB_API void luaL_where(lua_State *L, int level)
  1010. {
  1011. int size;
  1012. cTValue *frame = lj_debug_frame(L, level, &size);
  1013. lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
  1014. }
  1015. LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
  1016. {
  1017. const char *msg;
  1018. va_list argp;
  1019. va_start(argp, fmt);
  1020. msg = lj_strfmt_pushvf(L, fmt, argp);
  1021. va_end(argp);
  1022. lj_err_callermsg(L, msg);
  1023. return 0; /* unreachable */
  1024. }