2
0

lj_err.c 34 KB

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