• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tarantool / luajit / 6340880138

28 Sep 2023 03:15PM UTC coverage: 88.298% (+0.06%) from 88.241%
6340880138

push

github

fckxorg
Restore cur_L for specific Lua/C API use case.

Thanks to Peter Cawley.

(cherry-picked from commit e86990f7f)

Consider the following Lua C API function:

```
static int error_after_coroutine_return(lua_State *L)
{
	lua_State *innerL = lua_newthread(L);
	luaL_loadstring(innerL, "print('inner coro')");
	lua_pcall(innerL, 0, 0, 0);
	luaL_error(L, "my fancy error");
	return 0;
}
```

And the following Lua script:
```
local libcur_L = require('libcur_L')

local function onesnap_f(var)
  if var then
    return 1
  else
    return 0
  end
end

-- Compile function to trace with snapshot.
if jit then jit.opt.start('hotloop=1') end
onesnap_f(true)
onesnap_f(true)

local r, s = pcall(libcur_L.error_after_coroutine_return)
onesnap_f(false)
```

This is the only case when `cur_L` is not restored, according to
the analysis done in https://github.com/LuaJIT/LuaJIT/issues/1066.

This patch changes the error-catching routine, so now the patch
sets the actual cur_L there.
Now it is possible to throw errors on non-executing coroutines,
which is a violation of the Lua C API. So, even though it is now
possible, that behavior should be avoided anyway.

Maxim Kokryashkin:
* added the description for the problem

Resolves tarantool/tarantool#6323

5344 of 5972 branches covered (0.0%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 1 file covered. (100.0%)

20499 of 23296 relevant lines covered (87.99%)

2744986.07 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.38
/src/lj_err.c
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
#include "lj_strfmt.h"
20

21
/*
22
** LuaJIT can either use internal or external frame unwinding:
23
**
24
** - Internal frame unwinding (INT) is free-standing and doesn't require
25
**   any OS or library support.
26
**
27
** - External frame unwinding (EXT) uses the system-provided unwind handler.
28
**
29
** Pros and Cons:
30
**
31
** - EXT requires unwind tables for *all* functions on the C stack between
32
**   the pcall/catch and the error/throw. C modules used by Lua code can
33
**   throw errors, so these need to have unwind tables, too. Transitively
34
**   this applies to all system libraries used by C modules -- at least
35
**   when they have callbacks which may throw an error.
36
**
37
** - INT is faster when actually throwing errors, but this happens rarely.
38
**   Setting up error handlers is zero-cost in any case.
39
**
40
** - INT needs to save *all* callee-saved registers when entering the
41
**   interpreter. EXT only needs to save those actually used inside the
42
**   interpreter. JIT-compiled code may need to save some more.
43
**
44
** - EXT provides full interoperability with C++ exceptions. You can throw
45
**   Lua errors or C++ exceptions through a mix of Lua frames and C++ frames.
46
**   C++ destructors are called as needed. C++ exceptions caught by pcall
47
**   are converted to the string "C++ exception". Lua errors can be caught
48
**   with catch (...) in C++.
49
**
50
** - INT has only limited support for automatically catching C++ exceptions
51
**   on POSIX systems using DWARF2 stack unwinding. Other systems may use
52
**   the wrapper function feature. Lua errors thrown through C++ frames
53
**   cannot be caught by C++ code and C++ destructors are not run.
54
**
55
** - EXT can handle errors from internal helper functions that are called
56
**   from JIT-compiled code (except for Windows/x86 and 32 bit ARM).
57
**   INT has no choice but to call the panic handler, if this happens.
58
**   Note: this is mainly relevant for out-of-memory errors.
59
**
60
** EXT is the default on all systems where the toolchain produces unwind
61
** tables by default (*). This is hard-coded and/or detected in src/Makefile.
62
** You can thwart the detection with: TARGET_XCFLAGS=-DLUAJIT_UNWIND_INTERNAL
63
**
64
** INT is the default on all other systems.
65
**
66
** EXT can be manually enabled for toolchains that are able to produce
67
** conforming unwind tables:
68
**   "TARGET_XCFLAGS=-funwind-tables -DLUAJIT_UNWIND_EXTERNAL"
69
** As explained above, *all* C code used directly or indirectly by LuaJIT
70
** must be compiled with -funwind-tables (or -fexceptions). C++ code must
71
** *not* be compiled with -fno-exceptions.
72
**
73
** If you're unsure whether error handling inside the VM works correctly,
74
** try running this and check whether it prints "OK":
75
**
76
**   luajit -e "print(select(2, load('OK')):match('OK'))"
77
**
78
** (*) Originally, toolchains only generated unwind tables for C++ code. For
79
** interoperability reasons, this can be manually enabled for plain C code,
80
** too (with -funwind-tables). With the introduction of the x64 architecture,
81
** the corresponding POSIX and Windows ABIs mandated unwind tables for all
82
** code. Over the following years most desktop and server platforms have
83
** enabled unwind tables by default on all architectures. OTOH mobile and
84
** embedded platforms do not consistently mandate unwind tables.
85
*/
86

87
/* -- Error messages ------------------------------------------------------ */
88

89
/* Error message strings. */
90
LJ_DATADEF const char *lj_err_allmsg =
91
#define ERRDEF(name, msg)        msg "\0"
92
#include "lj_errmsg.h"
93
;
94

95
/* -- Internal frame unwinding -------------------------------------------- */
96

97
/* Unwind Lua stack and move error message to new top. */
98
LJ_NOINLINE static void unwindstack(lua_State *L, TValue *top)
26,974✔
99
{
100
  lj_func_closeuv(L, top);
26,974✔
101
  if (top < L->top-1) {
26,974✔
102
    copyTV(L, top, L->top-1);
26,111✔
103
    L->top = top+1;
26,111✔
104
  }
105
  lj_state_relimitstack(L);
26,974✔
106
}
26,974✔
107

108
/* Unwind until stop frame. Optionally cleanup frames. */
109
static void *err_unwind(lua_State *L, void *stopcf, int errcode)
53,968✔
110
{
111
  TValue *frame = L->base-1;
53,968✔
112
  void *cf = L->cframe;
53,968✔
113
  while (cf) {
319,004✔
114
    int32_t nres = cframe_nres(cframe_raw(cf));
319,004✔
115
    if (nres < 0) {  /* C frame without Lua frame? */
319,004✔
116
      TValue *top = restorestack(L, -nres);
27,132✔
117
      if (frame < top) {  /* Frame reached? */
27,132✔
118
        if (errcode) {
27,132✔
119
          L->base = frame+1;
13,566✔
120
          L->cframe = cframe_prev(cf);
13,566✔
121
          unwindstack(L, top);
13,566✔
122
        }
123
        return cf;
27,132✔
124
      }
125
    }
126
    if (frame <= tvref(L->stack)+LJ_FR2)
291,872✔
127
      break;
128
    switch (frame_typep(frame)) {
291,872✔
129
    case FRAME_LUA:  /* Lua frame. */
262,239✔
130
    case FRAME_LUAP:
131
      frame = frame_prevl(frame);
262,239✔
132
      break;
262,239✔
133
    case FRAME_C:  /* C frame. */
134
    unwind_c:
23✔
135
#if LJ_UNWIND_EXT
136
      if (errcode) {
23✔
137
        L->base = frame_prevd(frame) + 1;
8✔
138
        L->cframe = cframe_prev(cf);
8✔
139
        unwindstack(L, frame - LJ_FR2);
8✔
140
      } else if (cf != stopcf) {
15✔
141
        cf = cframe_prev(cf);
7✔
142
        frame = frame_prevd(frame);
7✔
143
        break;
7✔
144
      }
145
      return NULL;  /* Continue unwinding. */
146
#else
147
      UNUSED(stopcf);
148
      cf = cframe_prev(cf);
149
      frame = frame_prevd(frame);
150
      break;
151
#endif
152
    case FRAME_CP:  /* Protected C frame. */
64✔
153
      if (cframe_canyield(cf)) {  /* Resume? */
64✔
154
        if (errcode) {
20✔
155
          hook_leave(G(L));  /* Assumes nobody uses coroutines inside hooks. */
10✔
156
          L->cframe = NULL;
10✔
157
          L->status = (uint8_t)errcode;
10✔
158
        }
159
        return cf;
20✔
160
      }
161
      if (errcode) {
44✔
162
        L->base = frame_prevd(frame) + 1;
22✔
163
        L->cframe = cframe_prev(cf);
22✔
164
        unwindstack(L, frame - LJ_FR2);
22✔
165
      }
166
      return cf;
167
    case FRAME_CONT:  /* Continuation frame. */
13✔
168
      if (frame_iscont_fficb(frame))
13✔
169
        goto unwind_c;
3✔
170
      /* fallthrough */
171
    case FRAME_VARG:  /* Vararg frame. */
172
      frame = frame_prevd(frame);
2,790✔
173
      break;
2,790✔
174
    case FRAME_PCALL:  /* FF pcall() frame. */
26,756✔
175
    case FRAME_PCALLH:  /* FF pcall() frame inside hook. */
176
      if (errcode) {
26,756✔
177
        global_State *g;
13,378✔
178
        if (errcode == LUA_YIELD) {
13,378✔
179
          frame = frame_prevd(frame);
×
180
          break;
×
181
        }
182
        g = G(L);
13,378✔
183
        setgcref(g->cur_L, obj2gco(L));
13,378✔
184
        if (frame_typep(frame) == FRAME_PCALL)
13,378✔
185
          hook_leave(g);
13,377✔
186
        L->base = frame_prevd(frame) + 1;
13,378✔
187
        L->cframe = cf;
13,378✔
188
        unwindstack(L, L->base);
13,378✔
189
      }
190
      return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
26,756✔
191
    }
192
  }
193
  /* No C frame. */
194
  if (errcode) {
×
195
    L->base = tvref(L->stack)+1+LJ_FR2;
×
196
    L->cframe = NULL;
×
197
    unwindstack(L, L->base);
×
198
    if (G(L)->panic)
×
199
      G(L)->panic(L);
×
200
    exit(EXIT_FAILURE);
×
201
  }
202
  return L;  /* Anything non-NULL will do. */
203
}
204

205
/* -- External frame unwinding -------------------------------------------- */
206

207
#if LJ_ABI_WIN
208

209
/*
210
** Someone in Redmond owes me several days of my life. A lot of this is
211
** undocumented or just plain wrong on MSDN. Some of it can be gathered
212
** from 3rd party docs or must be found by trial-and-error. They really
213
** don't want you to write your own language-specific exception handler
214
** or to interact gracefully with MSVC. :-(
215
**
216
** Apparently MSVC doesn't call C++ destructors for foreign exceptions
217
** unless you compile your C++ code with /EHa. Unfortunately this means
218
** catch (...) also catches things like access violations. The use of
219
** _set_se_translator doesn't really help, because it requires /EHa, too.
220
*/
221

222
#define WIN32_LEAN_AND_MEAN
223
#include <windows.h>
224

225
#if LJ_TARGET_X86
226
typedef void *UndocumentedDispatcherContext;  /* Unused on x86. */
227
#else
228
/* Taken from: http://www.nynaeve.net/?p=99 */
229
typedef struct UndocumentedDispatcherContext {
230
  ULONG64 ControlPc;
231
  ULONG64 ImageBase;
232
  PRUNTIME_FUNCTION FunctionEntry;
233
  ULONG64 EstablisherFrame;
234
  ULONG64 TargetIp;
235
  PCONTEXT ContextRecord;
236
  void (*LanguageHandler)(void);
237
  PVOID HandlerData;
238
  PUNWIND_HISTORY_TABLE HistoryTable;
239
  ULONG ScopeIndex;
240
  ULONG Fill0;
241
} UndocumentedDispatcherContext;
242
#endif
243

244
/* Another wild guess. */
245
extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
246

247
#if LJ_TARGET_X64 && defined(MINGW_SDK_INIT)
248
/* Workaround for broken MinGW64 declaration. */
249
VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
250
#define RtlUnwindEx RtlUnwindEx_FIXED
251
#endif
252

253
#define LJ_MSVC_EXCODE                ((DWORD)0xe06d7363)
254
#define LJ_GCC_EXCODE                ((DWORD)0x20474343)
255

256
#define LJ_EXCODE                ((DWORD)0xe24c4a00)
257
#define LJ_EXCODE_MAKE(c)        (LJ_EXCODE | (DWORD)(c))
258
#define LJ_EXCODE_CHECK(cl)        (((cl) ^ LJ_EXCODE) <= 0xff)
259
#define LJ_EXCODE_ERRCODE(cl)        ((int)((cl) & 0xff))
260

261
/* Windows exception handler for interpreter frame. */
262
LJ_FUNCA int lj_err_unwind_win(EXCEPTION_RECORD *rec,
263
  void *f, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
264
{
265
#if LJ_TARGET_X86
266
  void *cf = (char *)f - CFRAME_OFS_SEH;
267
#else
268
  void *cf = f;
269
#endif
270
  lua_State *L = cframe_L(cf);
271
  int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
272
                LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
273
  if ((rec->ExceptionFlags & 6)) {  /* EH_UNWINDING|EH_EXIT_UNWIND */
274
    /* Unwind internal frames. */
275
    err_unwind(L, cf, errcode);
276
  } else {
277
    void *cf2 = err_unwind(L, cf, 0);
278
    if (cf2) {  /* We catch it, so start unwinding the upper frames. */
279
      if (rec->ExceptionCode == LJ_MSVC_EXCODE ||
280
          rec->ExceptionCode == LJ_GCC_EXCODE) {
281
#if !LJ_TARGET_CYGWIN
282
        __DestructExceptionObject(rec, 1);
283
#endif
284
        setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
285
      } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
286
        /* Don't catch access violations etc. */
287
        return 1;  /* ExceptionContinueSearch */
288
      }
289
#if LJ_TARGET_X86
290
      UNUSED(ctx);
291
      UNUSED(dispatch);
292
      /* Call all handlers for all lower C frames (including ourselves) again
293
      ** with EH_UNWINDING set. Then call the specified function, passing cf
294
      ** and errcode.
295
      */
296
      lj_vm_rtlunwind(cf, (void *)rec,
297
        (cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
298
        (void *)lj_vm_unwind_ff : (void *)lj_vm_unwind_c, errcode);
299
      /* lj_vm_rtlunwind does not return. */
300
#else
301
      /* Unwind the stack and call all handlers for all lower C frames
302
      ** (including ourselves) again with EH_UNWINDING set. Then set
303
      ** stack pointer = cf, result = errcode and jump to the specified target.
304
      */
305
      RtlUnwindEx(cf, (void *)((cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
306
                               lj_vm_unwind_ff_eh :
307
                               lj_vm_unwind_c_eh),
308
                  rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
309
      /* RtlUnwindEx should never return. */
310
#endif
311
    }
312
  }
313
  return 1;  /* ExceptionContinueSearch */
314
}
315

316
#if LJ_UNWIND_JIT
317

318
#if LJ_TARGET_X64
319
#define CONTEXT_REG_PC        Rip
320
#elif LJ_TARGET_ARM64
321
#define CONTEXT_REG_PC        Pc
322
#else
323
#error "NYI: Windows arch-specific unwinder for JIT-compiled code"
324
#endif
325

326
/* Windows unwinder for JIT-compiled code. */
327
static void err_unwind_win_jit(global_State *g, int errcode)
328
{
329
  CONTEXT ctx;
330
  UNWIND_HISTORY_TABLE hist;
331

332
  memset(&hist, 0, sizeof(hist));
333
  RtlCaptureContext(&ctx);
334
  while (1) {
335
    uintptr_t frame, base, addr = ctx.CONTEXT_REG_PC;
336
    void *hdata;
337
    PRUNTIME_FUNCTION func = RtlLookupFunctionEntry(addr, &base, &hist);
338
    if (!func) {  /* Found frame without .pdata: must be JIT-compiled code. */
339
      ExitNo exitno;
340
      uintptr_t stub = lj_trace_unwind(G2J(g), addr - sizeof(MCode), &exitno);
341
      if (stub) {  /* Jump to side exit to unwind the trace. */
342
        ctx.CONTEXT_REG_PC = stub;
343
        G2J(g)->exitcode = errcode;
344
        RtlRestoreContext(&ctx, NULL);  /* Does not return. */
345
      }
346
      break;
347
    }
348
    RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, addr, func,
349
                     &ctx, &hdata, &frame, NULL);
350
    if (!addr) break;
351
  }
352
  /* Unwinding failed, if we end up here. */
353
}
354
#endif
355

356
/* Raise Windows exception. */
357
static void err_raise_ext(global_State *g, int errcode)
358
{
359
#if LJ_UNWIND_JIT
360
  if (tvref(g->jit_base)) {
361
    err_unwind_win_jit(g, errcode);
362
    return;  /* Unwinding failed. */
363
  }
364
#elif LJ_HASJIT
365
  /* Cannot catch on-trace errors for Windows/x86 SEH. Unwind to interpreter. */
366
  setmref(g->jit_base, NULL);
367
#endif
368
  UNUSED(g);
369
  RaiseException(LJ_EXCODE_MAKE(errcode), 1 /* EH_NONCONTINUABLE */, 0, NULL);
370
}
371

372
#elif !LJ_NO_UNWIND && (defined(__GNUC__) || defined(__clang__))
373

374
/*
375
** We have to use our own definitions instead of the mandatory (!) unwind.h,
376
** since various OS, distros and compilers mess up the header installation.
377
*/
378

379
typedef struct _Unwind_Context _Unwind_Context;
380

381
#define _URC_OK                        0
382
#define _URC_FATAL_PHASE2_ERROR        2
383
#define _URC_FATAL_PHASE1_ERROR        3
384
#define _URC_HANDLER_FOUND        6
385
#define _URC_INSTALL_CONTEXT        7
386
#define _URC_CONTINUE_UNWIND        8
387
#define _URC_FAILURE                9
388

389
#define LJ_UEXCLASS                0x4c55414a49543200ULL        /* LUAJIT2\0 */
390
#define LJ_UEXCLASS_MAKE(c)        (LJ_UEXCLASS | (uint64_t)(c))
391
#define LJ_UEXCLASS_CHECK(cl)        (((cl) ^ LJ_UEXCLASS) <= 0xff)
392
#define LJ_UEXCLASS_ERRCODE(cl)        ((int)((cl) & 0xff))
393

394
#if !LJ_TARGET_ARM
395

396
typedef struct _Unwind_Exception
397
{
398
  uint64_t exclass;
399
  void (*excleanup)(int, struct _Unwind_Exception *);
400
  uintptr_t p1, p2;
401
} __attribute__((__aligned__)) _Unwind_Exception;
402
#define UNWIND_EXCEPTION_TYPE        _Unwind_Exception
403

404
extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
405
extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
406
extern uintptr_t _Unwind_GetIP(_Unwind_Context *);
407
extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
408
extern void _Unwind_DeleteException(_Unwind_Exception *);
409
extern int _Unwind_RaiseException(_Unwind_Exception *);
410

411
#define _UA_SEARCH_PHASE        1
412
#define _UA_CLEANUP_PHASE        2
413
#define _UA_HANDLER_FRAME        4
414
#define _UA_FORCE_UNWIND        8
415

416
/* DWARF2 personality handler referenced from interpreter .eh_frame. */
417
LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
53,968✔
418
  uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
419
{
420
  void *cf;
53,968✔
421
  lua_State *L;
53,968✔
422
  if (version != 1)
53,968✔
423
    return _URC_FATAL_PHASE1_ERROR;
424
  cf = (void *)_Unwind_GetCFA(ctx);
53,968✔
425
  L = cframe_L(cf);
53,968✔
426
  if ((actions & _UA_SEARCH_PHASE)) {
53,968✔
427
#if LJ_UNWIND_EXT
428
    if (err_unwind(L, cf, 0) == NULL)
26,984✔
429
      return _URC_CONTINUE_UNWIND;
430
#endif
431
    if (!LJ_UEXCLASS_CHECK(uexclass)) {
26,976✔
432
      setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
×
433
    }
434
    return _URC_HANDLER_FOUND;
26,976✔
435
  }
436
  if ((actions & _UA_CLEANUP_PHASE)) {
26,984✔
437
    int errcode;
26,984✔
438
    if (LJ_UEXCLASS_CHECK(uexclass)) {
26,984✔
439
      errcode = LJ_UEXCLASS_ERRCODE(uexclass);
26,984✔
440
    } else {
441
      if ((actions & _UA_HANDLER_FRAME))
×
442
        _Unwind_DeleteException(uex);
×
443
      errcode = LUA_ERRRUN;
444
    }
445
#if LJ_UNWIND_EXT
446
    cf = err_unwind(L, cf, errcode);
26,984✔
447
    if ((actions & _UA_FORCE_UNWIND)) {
26,984✔
448
      return _URC_CONTINUE_UNWIND;
449
    } else if (cf) {
26,984✔
450
      _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
26,976✔
451
      _Unwind_SetIP(ctx, (uintptr_t)(cframe_unwind_ff(cf) ?
26,976✔
452
                                     lj_vm_unwind_ff_eh :
453
                                     lj_vm_unwind_c_eh));
454
      return _URC_INSTALL_CONTEXT;
26,976✔
455
    }
456
#if LJ_TARGET_X86ORX64
457
    else if ((actions & _UA_HANDLER_FRAME)) {
8✔
458
      /* Workaround for ancient libgcc bug. Still present in RHEL 5.5. :-/
459
      ** Real fix: http://gcc.gnu.org/viewcvs/trunk/gcc/unwind-dw2.c?r1=121165&r2=124837&pathrev=153877&diff_format=h
460
      */
461
      _Unwind_SetGR(ctx, LJ_TARGET_EHRETREG, errcode);
×
462
      _Unwind_SetIP(ctx, (uintptr_t)lj_vm_unwind_rethrow);
×
463
      return _URC_INSTALL_CONTEXT;
×
464
    }
465
#endif
466
#else
467
    /* This is not the proper way to escape from the unwinder. We get away with
468
    ** it on non-x64 because the interpreter restores all callee-saved regs.
469
    */
470
    lj_err_throw(L, errcode);
471
#if LJ_TARGET_X64
472
#error "Broken build system -- only use the provided Makefiles!"
473
#endif
474
#endif
475
  }
476
  return _URC_CONTINUE_UNWIND;
477
}
478

479
#if LJ_UNWIND_EXT && defined(LUA_USE_ASSERT)
480
struct dwarf_eh_bases { void *tbase, *dbase, *func; };
481
extern const void *_Unwind_Find_FDE(void *pc, struct dwarf_eh_bases *bases);
482

483
/* Verify that external error handling actually has a chance to work. */
484
void lj_err_verify(void)
485
{
486
#if !LJ_TARGET_OSX
487
  /* Check disabled on MacOS due to brilliant software engineering at Apple. */
488
  struct dwarf_eh_bases ehb;
489
  lj_assertX(_Unwind_Find_FDE((void *)lj_err_throw, &ehb), "broken build: external frame unwinding enabled, but missing -funwind-tables");
490
#endif
491
  /* Check disabled, because of broken Fedora/ARM64. See #722.
492
  lj_assertX(_Unwind_Find_FDE((void *)_Unwind_RaiseException, &ehb), "broken build: external frame unwinding enabled, but system libraries have no unwind tables");
493
  */
494
}
495
#endif
496

497
#if LJ_UNWIND_JIT
498
/* DWARF2 personality handler for JIT-compiled code. */
499
static int err_unwind_jit(int version, int actions,
6✔
500
  uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
501
{
502
  /* NYI: FFI C++ exception interoperability. */
503
  if (version != 1 || !LJ_UEXCLASS_CHECK(uexclass))
6✔
504
    return _URC_FATAL_PHASE1_ERROR;
505
  if ((actions & _UA_SEARCH_PHASE)) {
6✔
506
    return _URC_HANDLER_FOUND;
507
  }
508
  if ((actions & _UA_CLEANUP_PHASE)) {
3✔
509
    global_State *g = *(global_State **)(uex+1);
3✔
510
    ExitNo exitno;
3✔
511
    uintptr_t addr = _Unwind_GetIP(ctx);  /* Return address _after_ call. */
3✔
512
    uintptr_t stub = lj_trace_unwind(G2J(g), addr - sizeof(MCode), &exitno);
3✔
513
    lj_assertG(tvref(g->jit_base), "unexpected throw across mcode frame");
3✔
514
    if (stub) {  /* Jump to side exit to unwind the trace. */
3✔
515
      G2J(g)->exitcode = LJ_UEXCLASS_ERRCODE(uexclass);
3✔
516
#ifdef LJ_TARGET_MIPS
517
      _Unwind_SetGR(ctx, 4, stub);
518
      _Unwind_SetGR(ctx, 5, exitno);
519
      _Unwind_SetIP(ctx, (uintptr_t)(void *)lj_vm_unwind_stub);
520
#else
521
      _Unwind_SetIP(ctx, stub);
3✔
522
#endif
523
      return _URC_INSTALL_CONTEXT;
3✔
524
    }
525
    return _URC_FATAL_PHASE2_ERROR;
526
  }
527
  return _URC_FATAL_PHASE1_ERROR;
528
}
529

530
/* DWARF2 template frame info for JIT-compiled code.
531
**
532
** After copying the template to the start of the mcode segment,
533
** the frame handler function and the code size is patched.
534
** The frame handler always installs a new context to jump to the exit,
535
** so don't bother to add any unwind opcodes.
536
*/
537
static const uint8_t err_frame_jit_template[] = {
538
#if LJ_BE
539
  0,0,0,
540
#endif
541
  LJ_64 ? 0x1c : 0x14,  /* CIE length. */
542
#if LJ_LE
543
  0,0,0,
544
#endif
545
  0,0,0,0, 1, 'z','P','R',0,  /* CIE mark, CIE version, augmentation. */
546
  1, LJ_64 ? 0x78 : 0x7c, LJ_TARGET_EHRAREG,  /* Code/data align, RA. */
547
#if LJ_64
548
  10, 0, 0,0,0,0,0,0,0,0, 0x1b,  /* Aug. data ABS handler, PCREL|SDATA4 code. */
549
  0,0,0,0,0,  /* Alignment. */
550
#else
551
  6, 0, 0,0,0,0, 0x1b,  /* Aug. data ABS handler, PCREL|SDATA4 code. */
552
  0,  /* Alignment. */
553
#endif
554
#if LJ_BE
555
  0,0,0,
556
#endif
557
  LJ_64 ? 0x14 : 0x10,  /* FDE length. */
558
  0,0,0,
559
  LJ_64 ? 0x24 : 0x1c,  /* CIE offset. */
560
  0,0,0,
561
  LJ_64 ? 0x14 : 0x10,  /* Code offset. After Final FDE. */
562
#if LJ_LE
563
  0,0,0,
564
#endif
565
  0,0,0,0, 0, 0,0,0, /* Code size, augmentation length, alignment. */
566
#if LJ_64
567
  0,0,0,0,  /* Alignment. */
568
#endif
569
  0,0,0,0  /* Final FDE. */
570
};
571

572
#define ERR_FRAME_JIT_OFS_HANDLER        0x12
573
#define ERR_FRAME_JIT_OFS_FDE                (LJ_64 ? 0x20 : 0x18)
574
#define ERR_FRAME_JIT_OFS_CODE_SIZE        (LJ_64 ? 0x2c : 0x24)
575
#if LJ_TARGET_OSX
576
#define ERR_FRAME_JIT_OFS_REGISTER        ERR_FRAME_JIT_OFS_FDE
577
#else
578
#define ERR_FRAME_JIT_OFS_REGISTER        0
579
#endif
580

581
extern void __register_frame(const void *);
582
extern void __deregister_frame(const void *);
583

584
uint8_t *lj_err_register_mcode(void *base, size_t sz, uint8_t *info)
359✔
585
{
586
  void **handler;
359✔
587
  memcpy(info, err_frame_jit_template, sizeof(err_frame_jit_template));
359✔
588
  handler = (void *)err_unwind_jit;
359✔
589
  memcpy(info + ERR_FRAME_JIT_OFS_HANDLER, &handler, sizeof(handler));
359✔
590
  *(uint32_t *)(info + ERR_FRAME_JIT_OFS_CODE_SIZE) =
359✔
591
    (uint32_t)(sz - sizeof(err_frame_jit_template) - (info - (uint8_t *)base));
359✔
592
  __register_frame(info + ERR_FRAME_JIT_OFS_REGISTER);
359✔
593
#ifdef LUA_USE_ASSERT
594
  {
595
    struct dwarf_eh_bases ehb;
596
    lj_assertX(_Unwind_Find_FDE(info + sizeof(err_frame_jit_template)+1, &ehb),
597
               "bad JIT unwind table registration");
598
  }
599
#endif
600
  return info + sizeof(err_frame_jit_template);
359✔
601
}
602

603
void lj_err_deregister_mcode(void *base, size_t sz, uint8_t *info)
356✔
604
{
605
  UNUSED(base); UNUSED(sz);
356✔
606
  __deregister_frame(info + ERR_FRAME_JIT_OFS_REGISTER);
356✔
607
}
356✔
608
#endif
609

610
#else /* LJ_TARGET_ARM */
611

612
#define _US_VIRTUAL_UNWIND_FRAME        0
613
#define _US_UNWIND_FRAME_STARTING        1
614
#define _US_ACTION_MASK                        3
615
#define _US_FORCE_UNWIND                8
616

617
typedef struct _Unwind_Control_Block _Unwind_Control_Block;
618
#define UNWIND_EXCEPTION_TYPE        _Unwind_Control_Block
619

620
struct _Unwind_Control_Block {
621
  uint64_t exclass;
622
  uint32_t misc[20];
623
};
624

625
extern int _Unwind_RaiseException(_Unwind_Control_Block *);
626
extern int __gnu_unwind_frame(_Unwind_Control_Block *, _Unwind_Context *);
627
extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
628
extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
629

630
static inline uint32_t _Unwind_GetGR(_Unwind_Context *ctx, int r)
631
{
632
  uint32_t v;
633
  _Unwind_VRS_Get(ctx, 0, r, 0, &v);
634
  return v;
635
}
636

637
static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
638
{
639
  _Unwind_VRS_Set(ctx, 0, r, 0, &v);
640
}
641

642
extern void lj_vm_unwind_ext(void);
643

644
/* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
645
LJ_FUNCA int lj_err_unwind_arm(int state, _Unwind_Control_Block *ucb,
646
                               _Unwind_Context *ctx)
647
{
648
  void *cf = (void *)_Unwind_GetGR(ctx, 13);
649
  lua_State *L = cframe_L(cf);
650
  int errcode;
651

652
  switch ((state & _US_ACTION_MASK)) {
653
  case _US_VIRTUAL_UNWIND_FRAME:
654
    if ((state & _US_FORCE_UNWIND)) break;
655
    return _URC_HANDLER_FOUND;
656
  case _US_UNWIND_FRAME_STARTING:
657
    if (LJ_UEXCLASS_CHECK(ucb->exclass)) {
658
      errcode = LJ_UEXCLASS_ERRCODE(ucb->exclass);
659
    } else {
660
      errcode = LUA_ERRRUN;
661
      setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
662
    }
663
    cf = err_unwind(L, cf, errcode);
664
    if ((state & _US_FORCE_UNWIND) || cf == NULL) break;
665
    _Unwind_SetGR(ctx, 15, (uint32_t)lj_vm_unwind_ext);
666
    _Unwind_SetGR(ctx, 0, (uint32_t)ucb);
667
    _Unwind_SetGR(ctx, 1, (uint32_t)errcode);
668
    _Unwind_SetGR(ctx, 2, cframe_unwind_ff(cf) ?
669
                            (uint32_t)lj_vm_unwind_ff_eh :
670
                            (uint32_t)lj_vm_unwind_c_eh);
671
    return _URC_INSTALL_CONTEXT;
672
  default:
673
    return _URC_FAILURE;
674
  }
675
  if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
676
    return _URC_FAILURE;
677
#ifdef LUA_USE_ASSERT
678
  /* We should never get here unless this is a forced unwind aka backtrace. */
679
  if (_Unwind_GetGR(ctx, 0) == 0xff33aa77) {
680
    _Unwind_SetGR(ctx, 0, 0xff33aa88);
681
  }
682
#endif
683
  return _URC_CONTINUE_UNWIND;
684
}
685

686
#if LJ_UNWIND_EXT && defined(LUA_USE_ASSERT)
687
typedef int (*_Unwind_Trace_Fn)(_Unwind_Context *, void *);
688
extern int _Unwind_Backtrace(_Unwind_Trace_Fn, void *);
689

690
static int err_verify_bt(_Unwind_Context *ctx, int *got)
691
{
692
  if (_Unwind_GetGR(ctx, 0) == 0xff33aa88) { *got = 2; }
693
  else if (*got == 0) { *got = 1; _Unwind_SetGR(ctx, 0, 0xff33aa77); }
694
  return _URC_OK;
695
}
696

697
/* Verify that external error handling actually has a chance to work. */
698
void lj_err_verify(void)
699
{
700
  int got = 0;
701
  _Unwind_Backtrace((_Unwind_Trace_Fn)err_verify_bt, &got);
702
  lj_assertX(got == 2, "broken build: external frame unwinding enabled, but missing -funwind-tables");
703
}
704
#endif
705

706
/*
707
** Note: LJ_UNWIND_JIT is not implemented for 32 bit ARM.
708
**
709
** The quirky ARM unwind API doesn't have __register_frame().
710
** A potential workaround might involve _Unwind_Backtrace.
711
** But most 32 bit ARM targets don't qualify for LJ_UNWIND_EXT, anyway,
712
** since they are built without unwind tables by default.
713
*/
714

715
#endif /* LJ_TARGET_ARM */
716

717

718
#if LJ_UNWIND_EXT
719
static __thread struct {
720
  UNWIND_EXCEPTION_TYPE ex;
721
  global_State *g;
722
} static_uex;
723

724
/* Raise external exception. */
725
static void err_raise_ext(global_State *g, int errcode)
26,979✔
726
{
727
  memset(&static_uex, 0, sizeof(static_uex));
26,979✔
728
  static_uex.ex.exclass = LJ_UEXCLASS_MAKE(errcode);
26,979✔
729
  static_uex.g = g;
26,979✔
730
  _Unwind_RaiseException(&static_uex.ex);
26,979✔
731
}
×
732

733
#endif
734

735
#endif
736

737
/* -- Error handling ------------------------------------------------------ */
738

739
/* Throw error. Find catch frame, unwind stack and continue. */
740
LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
26,979✔
741
{
742
  global_State *g = G(L);
26,979✔
743
  lj_trace_abort(g);
26,979✔
744
  L->status = LUA_OK;
26,979✔
745
#if LJ_UNWIND_EXT
746
  err_raise_ext(g, errcode);
26,979✔
747
  /*
748
  ** A return from this function signals a corrupt C stack that cannot be
749
  ** unwound. We have no choice but to call the panic function and exit.
750
  **
751
  ** Usually this is caused by a C function without unwind information.
752
  ** This may happen if you've manually enabled LUAJIT_UNWIND_EXTERNAL
753
  ** and forgot to recompile *every* non-C++ file with -funwind-tables.
754
  */
755
  if (G(L)->panic)
×
756
    G(L)->panic(L);
×
757
#else
758
#if LJ_HASJIT
759
  setmref(g->jit_base, NULL);
760
#endif
761
  {
762
    void *cf = err_unwind(L, NULL, errcode);
763
    if (cframe_unwind_ff(cf))
764
      lj_vm_unwind_ff(cframe_raw(cf));
765
    else
766
      lj_vm_unwind_c(cframe_raw(cf), errcode);
767
  }
768
#endif
769
  exit(EXIT_FAILURE);
×
770
}
771

772
/* Return string object for error message. */
773
LJ_NOINLINE GCstr *lj_err_str(lua_State *L, ErrMsg em)
262✔
774
{
775
  return lj_str_newz(L, err2msg(em));
262✔
776
}
777

778
/* Out-of-memory error. */
779
LJ_NOINLINE void lj_err_mem(lua_State *L)
1✔
780
{
781
  if (L->status == LUA_ERRERR+1)  /* Don't touch the stack during lua_open. */
1✔
782
    lj_vm_unwind_c(L->cframe, LUA_ERRMEM);
×
783
  if (LJ_HASJIT) {
1✔
784
    TValue *base = tvref(G(L)->jit_base);
1✔
785
    if (base) L->base = base;
1✔
786
  }
787
  if (curr_funcisL(L)) L->top = curr_topL(L);
1✔
788
  setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRMEM));
1✔
789
  lj_err_throw(L, LUA_ERRMEM);
1✔
790
}
791

792
/* Find error function for runtime errors. Requires an extra stack traversal. */
793
static ptrdiff_t finderrfunc(lua_State *L)
13,412✔
794
{
795
  cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2;
13,412✔
796
  void *cf = L->cframe;
13,412✔
797
  while (frame > bot && cf) {
145,949✔
798
    while (cframe_nres(cframe_raw(cf)) < 0) {  /* cframe without frame? */
145,940✔
799
      if (frame >= restorestack(L, -cframe_nres(cf)))
4✔
800
        break;
801
      if (cframe_errfunc(cf) >= 0)  /* Error handler not inherited (-1)? */
4✔
802
        return cframe_errfunc(cf);
2✔
803
      cf = cframe_prev(cf);  /* Else unwind cframe and continue searching. */
2✔
804
      if (cf == NULL)
2✔
805
        return 0;
806
    }
807
    switch (frame_typep(frame)) {
145,936✔
808
    case FRAME_LUA:
131,121✔
809
    case FRAME_LUAP:
810
      frame = frame_prevl(frame);
131,121✔
811
      break;
131,121✔
812
    case FRAME_C:
6✔
813
      cf = cframe_prev(cf);
6✔
814
      /* fallthrough */
815
    case FRAME_VARG:
1,399✔
816
      frame = frame_prevd(frame);
1,399✔
817
      break;
1,399✔
818
    case FRAME_CONT:
4✔
819
      if (frame_iscont_fficb(frame))
4✔
820
        cf = cframe_prev(cf);
1✔
821
      frame = frame_prevd(frame);
4✔
822
      break;
4✔
823
    case FRAME_CP:
32✔
824
      if (cframe_canyield(cf)) return 0;
32✔
825
      if (cframe_errfunc(cf) >= 0)
24✔
826
        return cframe_errfunc(cf);
11✔
827
      cf = cframe_prev(cf);
13✔
828
      frame = frame_prevd(frame);
13✔
829
      break;
13✔
830
    case FRAME_PCALL:
13,380✔
831
    case FRAME_PCALLH:
832
      if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall)
13,380✔
833
        return savestack(L, frame_prevd(frame)+1);  /* xpcall's errorfunc. */
18✔
834
      return 0;
835
    default:
836
      lj_assertL(0, "bad frame type");
837
      return 0;
838
    }
839
  }
840
  return 0;
841
}
842

843
/* Runtime error. */
844
LJ_NOINLINE void LJ_FASTCALL lj_err_run(lua_State *L)
13,415✔
845
{
846
  ptrdiff_t ef = (LJ_HASJIT && tvref(G(L)->jit_base)) ? 0 : finderrfunc(L);
13,415✔
847
  if (ef) {
13,412✔
848
    TValue *errfunc = restorestack(L, ef);
22✔
849
    TValue *top = L->top;
22✔
850
    lj_trace_abort(G(L));
22✔
851
    if (!tvisfunc(errfunc) || L->status == LUA_ERRERR) {
22✔
852
      setstrV(L, top-1, lj_err_str(L, LJ_ERR_ERRERR));
3✔
853
      lj_err_throw(L, LUA_ERRERR);
3✔
854
    }
855
    L->status = LUA_ERRERR;
19✔
856
    copyTV(L, top+LJ_FR2, top-1);
19✔
857
    copyTV(L, top-1, errfunc);
19✔
858
    if (LJ_FR2) setnilV(top++);
19✔
859
    L->top = top+1;
19✔
860
    lj_vm_call(L, top, 1+1);  /* Stack: |errfunc|msg| -> |msg| */
19✔
861
  }
862
  lj_err_throw(L, LUA_ERRRUN);
13,409✔
863
}
864

865
#if LJ_HASJIT
866
LJ_NOINLINE void LJ_FASTCALL lj_err_trace(lua_State *L, int errcode)
4✔
867
{
868
  if (errcode == LUA_ERRRUN)
4✔
869
    lj_err_run(L);
4✔
870
  else
871
    lj_err_throw(L, errcode);
×
872
}
873
#endif
874

875
/* Formatted runtime error message. */
876
LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
13,098✔
877
{
878
  const char *msg;
13,098✔
879
  va_list argp;
13,098✔
880
  va_start(argp, em);
13,098✔
881
  if (LJ_HASJIT) {
13,098✔
882
    TValue *base = tvref(G(L)->jit_base);
13,098✔
883
    if (base) L->base = base;
13,098✔
884
  }
885
  if (curr_funcisL(L)) L->top = curr_topL(L);
13,098✔
886
  msg = lj_strfmt_pushvf(L, err2msg(em), argp);
13,098✔
887
  va_end(argp);
13,098✔
888
  lj_debug_addloc(L, msg, L->base-1, NULL);
13,098✔
889
  lj_err_run(L);
13,098✔
890
}
891

892
/* Non-vararg variant for better calling conventions. */
893
LJ_NOINLINE void lj_err_msg(lua_State *L, ErrMsg em)
26✔
894
{
895
  err_msgv(L, em);
26✔
896
}
897

898
/* Lexer error. */
899
LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
12,702✔
900
                            BCLine line, ErrMsg em, va_list argp)
901
{
902
  char buff[LUA_IDSIZE];
12,702✔
903
  const char *msg;
12,702✔
904
  lj_debug_shortname(buff, src, line);
12,702✔
905
  msg = lj_strfmt_pushvf(L, err2msg(em), argp);
12,702✔
906
  msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg);
12,702✔
907
  if (tok)
12,702✔
908
    lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
12,675✔
909
  lj_err_throw(L, LUA_ERRSYNTAX);
12,702✔
910
}
911

912
/* Typecheck error for operands. */
913
LJ_NOINLINE void lj_err_optype(lua_State *L, cTValue *o, ErrMsg opm)
1,487✔
914
{
915
  const char *tname = lj_typename(o);
1,487✔
916
  const char *opname = err2msg(opm);
1,487✔
917
  if (curr_funcisL(L)) {
1,487✔
918
    GCproto *pt = curr_proto(L);
1,487✔
919
    const BCIns *pc = cframe_Lpc(L) - 1;
1,487✔
920
    const char *oname = NULL;
1,487✔
921
    const char *kind = lj_debug_slotname(pt, pc, (BCReg)(o-L->base), &oname);
1,487✔
922
    if (kind)
1,487✔
923
      err_msgv(L, LJ_ERR_BADOPRT, opname, kind, oname, tname);
423✔
924
  }
925
  err_msgv(L, LJ_ERR_BADOPRV, opname, tname);
1,064✔
926
}
927

928
/* Typecheck error for ordered comparisons. */
929
LJ_NOINLINE void lj_err_comp(lua_State *L, cTValue *o1, cTValue *o2)
78✔
930
{
931
  const char *t1 = lj_typename(o1);
78✔
932
  const char *t2 = lj_typename(o2);
78✔
933
  err_msgv(L, t1 == t2 ? LJ_ERR_BADCMPV : LJ_ERR_BADCMPT, t1, t2);
78✔
934
  /* This assumes the two "boolean" entries are commoned by the C compiler. */
935
}
936

937
/* Typecheck error for __call. */
938
LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
11,713✔
939
{
940
  /* Gross hack if lua_[p]call or pcall/xpcall fail for a non-callable object:
941
  ** L->base still points to the caller. So add a dummy frame with L instead
942
  ** of a function. See lua_getstack().
943
  */
944
  const BCIns *pc = cframe_Lpc(L);
11,713✔
945
  if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
11,713✔
946
    const char *tname = lj_typename(o);
11,507✔
947
    setframe_gc(o, obj2gco(L), LJ_TTHREAD);
11,507✔
948
    if (LJ_FR2) o++;
11,507✔
949
    setframe_pc(o, pc);
11,507✔
950
    L->top = L->base = o+1;
11,507✔
951
    err_msgv(L, LJ_ERR_BADCALL, tname);
11,507✔
952
  }
953
  lj_err_optype(L, o, LJ_ERR_OPCALL);
206✔
954
}
955

956
/* Error in context of caller. */
957
LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
232✔
958
{
959
  TValue *frame = L->base-1;
232✔
960
  TValue *pframe = NULL;
232✔
961
  if (frame_islua(frame)) {
232✔
962
    pframe = frame_prevl(frame);
100✔
963
  } else if (frame_iscont(frame)) {
132✔
964
    if (frame_iscont_fficb(frame)) {
4✔
965
      pframe = frame;
966
      frame = NULL;
967
    } else {
968
      pframe = frame_prevd(frame);
4✔
969
#if LJ_HASFFI
970
      /* Remove frame for FFI metamethods. */
971
      if (frame_func(frame)->c.ffid >= FF_ffi_meta___index &&
4✔
972
          frame_func(frame)->c.ffid <= FF_ffi_meta___tostring) {
973
        L->base = pframe+1;
3✔
974
        L->top = frame;
3✔
975
        setcframe_pc(cframe_raw(L->cframe), frame_contpc(frame));
3✔
976
      }
977
#endif
978
    }
979
  }
980
  lj_debug_addloc(L, msg, pframe, frame);
232✔
981
  lj_err_run(L);
232✔
982
}
983

984
/* Formatted error in context of caller. */
985
LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
17✔
986
{
987
  const char *msg;
17✔
988
  va_list argp;
17✔
989
  va_start(argp, em);
17✔
990
  msg = lj_strfmt_pushvf(L, err2msg(em), argp);
17✔
991
  va_end(argp);
17✔
992
  lj_err_callermsg(L, msg);
17✔
993
}
994

995
/* Error in context of caller. */
996
LJ_NOINLINE void lj_err_caller(lua_State *L, ErrMsg em)
44✔
997
{
998
  lj_err_callermsg(L, err2msg(em));
44✔
999
}
1000

1001
/* Argument error message. */
1002
LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
107✔
1003
                                            const char *msg)
1004
{
1005
  const char *fname = "?";
107✔
1006
  const char *ftype = lj_debug_funcname(L, L->base - 1, &fname);
107✔
1007
  if (narg < 0 && narg > LUA_REGISTRYINDEX)
107✔
1008
    narg = (int)(L->top - L->base) + narg + 1;
×
1009
  if (ftype && ftype[3] == 'h' && --narg == 0)  /* Check for "method". */
107✔
1010
    msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
×
1011
  else
1012
    msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
107✔
1013
  lj_err_callermsg(L, msg);
107✔
1014
}
1015

1016
/* Formatted argument error. */
1017
LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
4✔
1018
{
1019
  const char *msg;
4✔
1020
  va_list argp;
4✔
1021
  va_start(argp, em);
4✔
1022
  msg = lj_strfmt_pushvf(L, err2msg(em), argp);
4✔
1023
  va_end(argp);
4✔
1024
  err_argmsg(L, narg, msg);
4✔
1025
}
1026

1027
/* Argument error. */
1028
LJ_NOINLINE void lj_err_arg(lua_State *L, int narg, ErrMsg em)
30✔
1029
{
1030
  err_argmsg(L, narg, err2msg(em));
30✔
1031
}
1032

1033
/* Typecheck error for arguments. */
1034
LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
71✔
1035
{
1036
  const char *tname, *msg;
71✔
1037
  if (narg <= LUA_REGISTRYINDEX) {
71✔
1038
    if (narg >= LUA_GLOBALSINDEX) {
×
1039
      tname = lj_obj_itypename[~LJ_TTAB];
×
1040
    } else {
1041
      GCfunc *fn = curr_func(L);
×
1042
      int idx = LUA_GLOBALSINDEX - narg;
×
1043
      if (idx <= fn->c.nupvalues)
×
1044
        tname = lj_typename(&fn->c.upvalue[idx-1]);
×
1045
      else
1046
        tname = lj_obj_typename[0];
×
1047
    }
1048
  } else {
1049
    TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
71✔
1050
    tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
71✔
1051
  }
1052
  msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
71✔
1053
  err_argmsg(L, narg, msg);
71✔
1054
}
1055

1056
/* Typecheck error for arguments. */
1057
LJ_NOINLINE void lj_err_argt(lua_State *L, int narg, int tt)
69✔
1058
{
1059
  lj_err_argtype(L, narg, lj_obj_typename[tt+1]);
69✔
1060
}
1061

1062
/* -- Public error handling API ------------------------------------------- */
1063

1064
LUA_API lua_CFunction lua_atpanic(lua_State *L, lua_CFunction panicf)
×
1065
{
1066
  lua_CFunction old = G(L)->panic;
×
1067
  G(L)->panic = panicf;
×
1068
  return old;
×
1069
}
1070

1071
/* Forwarders for the public API (C calling convention and no LJ_NORET). */
1072
LUA_API int lua_error(lua_State *L)
78✔
1073
{
1074
  lj_err_run(L);
78✔
1075
  return 0;  /* unreachable */
1076
}
1077

1078
LUALIB_API int luaL_argerror(lua_State *L, int narg, const char *msg)
2✔
1079
{
1080
  err_argmsg(L, narg, msg);
2✔
1081
  return 0;  /* unreachable */
1082
}
1083

1084
LUALIB_API int luaL_typerror(lua_State *L, int narg, const char *xname)
×
1085
{
1086
  lj_err_argtype(L, narg, xname);
×
1087
  return 0;  /* unreachable */
1088
}
1089

1090
LUALIB_API void luaL_where(lua_State *L, int level)
22✔
1091
{
1092
  int size;
22✔
1093
  cTValue *frame = lj_debug_frame(L, level, &size);
22✔
1094
  lj_debug_addloc(L, "", frame, size ? frame+size : NULL);
22✔
1095
}
22✔
1096

1097
LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
55✔
1098
{
1099
  const char *msg;
55✔
1100
  va_list argp;
55✔
1101
  va_start(argp, fmt);
55✔
1102
  msg = lj_strfmt_pushvf(L, fmt, argp);
55✔
1103
  va_end(argp);
55✔
1104
  lj_err_callermsg(L, msg);
55✔
1105
  return 0;  /* unreachable */
1106
}
1107

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc