root/lj_err.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. unwindstack
  2. err_unwind
  3. lj_err_unwind_dwarf
  4. err_raise_ext
  5. _Unwind_GetGR
  6. _Unwind_SetGR
  7. lj_err_unwind_arm
  8. lj_err_unwind_win64
  9. err_raise_ext
  10. lj_err_throw
  11. lj_err_str
  12. lj_err_mem
  13. finderrfunc
  14. lj_err_run
  15. err_msgv
  16. lj_err_msg
  17. lj_err_lex
  18. lj_err_optype
  19. lj_err_comp
  20. lj_err_optype_call
  21. lj_err_callermsg
  22. lj_err_callerv
  23. lj_err_caller
  24. err_argmsg
  25. lj_err_argv
  26. lj_err_arg
  27. lj_err_argtype
  28. lj_err_argt
  29. lua_atpanic
  30. lua_error
  31. luaL_argerror
  32. luaL_typerror
  33. luaL_where
  34. luaL_error

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

/* [<][>][^][v][top][bottom][index][help] */