Coverage Report

Created: 2025-10-10 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/testdir/build/lua-master/source/ldo.c
Line
Count
Source
1
/*
2
** $Id: ldo.c $
3
** Stack and Call structure of Lua
4
** See Copyright Notice in lua.h
5
*/
6
7
#define ldo_c
8
#define LUA_CORE
9
10
#include "lprefix.h"
11
12
13
#include <setjmp.h>
14
#include <stdlib.h>
15
#include <string.h>
16
17
#include "lua.h"
18
19
#include "lapi.h"
20
#include "ldebug.h"
21
#include "ldo.h"
22
#include "lfunc.h"
23
#include "lgc.h"
24
#include "lmem.h"
25
#include "lobject.h"
26
#include "lopcodes.h"
27
#include "lparser.h"
28
#include "lstate.h"
29
#include "lstring.h"
30
#include "ltable.h"
31
#include "ltm.h"
32
#include "lundump.h"
33
#include "lvm.h"
34
#include "lzio.h"
35
36
37
38
39.8k
#define errorstatus(s)  ((s) > LUA_YIELD)
39
40
41
/*
42
** these macros allow user-specific actions when a thread is
43
** resumed/yielded.
44
*/
45
#if !defined(luai_userstateresume)
46
19.4k
#define luai_userstateresume(L,n) ((void)L)
47
#endif
48
49
#if !defined(luai_userstateyield)
50
2.74k
#define luai_userstateyield(L,n)  ((void)L)
51
#endif
52
53
54
/*
55
** {======================================================
56
** Error-recovery functions
57
** =======================================================
58
*/
59
60
/* chained list of long jump buffers */
61
typedef struct lua_longjmp {
62
  struct lua_longjmp *previous;
63
  jmp_buf b;
64
  volatile TStatus status;  /* error code */
65
} lua_longjmp;
66
67
68
/*
69
** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
70
** default, Lua handles errors with exceptions when compiling as
71
** C++ code, with _longjmp/_setjmp when available (POSIX), and with
72
** longjmp/setjmp otherwise.
73
*/
74
#if !defined(LUAI_THROW)        /* { */
75
76
#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
77
78
/* C++ exceptions */
79
#define LUAI_THROW(L,c)   throw(c)
80
81
static void LUAI_TRY (lua_State *L, lua_longjmp *c, Pfunc f, void *ud) {
82
  try {
83
    f(L, ud);  /* call function protected */
84
  }
85
  catch (lua_longjmp *c1) { /* Lua error */
86
    if (c1 != c)  /* not the correct level? */
87
      throw;  /* rethrow to upper level */
88
  }
89
  catch (...) {  /* non-Lua exception */
90
    c->status = -1;  /* create some error code */
91
  }
92
}
93
94
95
#elif defined(LUA_USE_POSIX)        /* }{ */
96
97
/* in POSIX, use _longjmp/_setjmp (more efficient) */
98
5.65M
#define LUAI_THROW(L,c)   _longjmp((c)->b, 1)
99
47.0M
#define LUAI_TRY(L,c,f,ud)  if (_setjmp((c)->b) == 0) ((f)(L, ud))
100
101
#else             /* }{ */
102
103
/* ISO C handling with long jumps */
104
#define LUAI_THROW(L,c)   longjmp((c)->b, 1)
105
#define LUAI_TRY(L,c,f,ud)  if (setjmp((c)->b) == 0) ((f)(L, ud))
106
107
#endif              /* } */
108
109
#endif              /* } */
110
111
112
5.65M
void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) {
113
5.65M
  if (errcode == LUA_ERRMEM) {  /* memory error? */
114
3.30k
    setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
115
3.30k
  }
116
5.65M
  else {
117
5.65M
    lua_assert(errorstatus(errcode));  /* must be a real error */
118
5.65M
    lua_assert(!ttisnil(s2v(L->top.p - 1)));  /* with a non-nil object */
119
11.3M
    setobjs2s(L, oldtop, L->top.p - 1);  /* move it to 'oldtop' */
120
5.65M
  }
121
5.65M
  L->top.p = oldtop + 1;  /* top goes back to old top plus error object */
122
5.65M
}
123
124
125
5.65M
l_noret luaD_throw (lua_State *L, TStatus errcode) {
126
5.65M
  if (L->errorJmp) {  /* thread has an error handler? */
127
5.65M
    L->errorJmp->status = errcode;  /* set status */
128
5.65M
    LUAI_THROW(L, L->errorJmp);  /* jump to it */
129
5.65M
  }
130
0
  else {  /* thread has no error handler */
131
0
    global_State *g = G(L);
132
0
    lua_State *mainth = mainthread(g);
133
0
    errcode = luaE_resetthread(L, errcode);  /* close all upvalues */
134
0
    L->status = errcode;
135
0
    if (mainth->errorJmp) {  /* main thread has a handler? */
136
0
      setobjs2s(L, mainth->top.p++, L->top.p - 1);  /* copy error obj. */
137
0
      luaD_throw(mainth, errcode);  /* re-throw in main thread */
138
0
    }
139
0
    else {  /* no handler at all; abort */
140
0
      if (g->panic) {  /* panic function? */
141
0
        lua_unlock(L);
142
0
        g->panic(L);  /* call panic function (last chance to jump out) */
143
0
      }
144
0
      abort();
145
0
    }
146
0
  }
147
5.65M
}
148
149
150
0
l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode) {
151
0
  if (L->errorJmp) {
152
    /* unroll error entries up to the first level */
153
0
    while (L->errorJmp->previous != NULL)
154
0
      L->errorJmp = L->errorJmp->previous;
155
0
  }
156
0
  luaD_throw(L, errcode);
157
0
}
158
159
160
47.0M
TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
161
47.0M
  l_uint32 oldnCcalls = L->nCcalls;
162
47.0M
  lua_longjmp lj;
163
47.0M
  lj.status = LUA_OK;
164
47.0M
  lj.previous = L->errorJmp;  /* chain new error handler */
165
47.0M
  L->errorJmp = &lj;
166
47.0M
  LUAI_TRY(L, &lj, f, ud);  /* call 'f' catching errors */
167
47.0M
  L->errorJmp = lj.previous;  /* restore old error handler */
168
47.0M
  L->nCcalls = oldnCcalls;
169
47.0M
  return lj.status;
170
47.0M
}
171
172
/* }====================================================== */
173
174
175
/*
176
** {==================================================================
177
** Stack reallocation
178
** ===================================================================
179
*/
180
181
/* some stack space for error handling */
182
315
#define STACKERRSPACE 200
183
184
185
/*
186
** LUAI_MAXSTACK limits the size of the Lua stack.
187
** It must fit into INT_MAX/2.
188
*/
189
190
#if !defined(LUAI_MAXSTACK)
191
#if 1000000 < (INT_MAX / 2)
192
#define LUAI_MAXSTACK           1000000
193
#else
194
#define LUAI_MAXSTACK           (INT_MAX / 2u)
195
#endif
196
#endif
197
198
199
/* maximum stack size that respects size_t */
200
#define MAXSTACK_BYSIZET  ((MAX_SIZET / sizeof(StackValue)) - STACKERRSPACE)
201
202
/*
203
** Minimum between LUAI_MAXSTACK and MAXSTACK_BYSIZET
204
** (Maximum size for the stack must respect size_t.)
205
*/
206
44.0M
#define MAXSTACK  cast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET  \
207
43.4M
              ? LUAI_MAXSTACK : MAXSTACK_BYSIZET)
208
209
210
/* stack size with extra space for error handling */
211
315
#define ERRORSTACKSIZE  (MAXSTACK + STACKERRSPACE)
212
213
214
/* raise a stack error while running the message handler */
215
144k
l_noret luaD_errerr (lua_State *L) {
216
144k
  TString *msg = luaS_newliteral(L, "error in error handling");
217
144k
  setsvalue2s(L, L->top.p, msg);
218
144k
  L->top.p++;  /* assume EXTRA_STACK */
219
144k
  luaD_throw(L, LUA_ERRERR);
220
144k
}
221
222
223
/*
224
** In ISO C, any pointer use after the pointer has been deallocated is
225
** undefined behavior. So, before a stack reallocation, all pointers
226
** should be changed to offsets, and after the reallocation they should
227
** be changed back to pointers. As during the reallocation the pointers
228
** are invalid, the reallocation cannot run emergency collections.
229
** Alternatively, we can use the old address after the deallocation.
230
** That is not strict ISO C, but seems to work fine everywhere.
231
** The following macro chooses how strict is the code.
232
*/
233
#if !defined(LUAI_STRICT_ADDRESS)
234
#define LUAI_STRICT_ADDRESS 1
235
#endif
236
237
#if LUAI_STRICT_ADDRESS
238
/*
239
** Change all pointers to the stack into offsets.
240
*/
241
329k
static void relstack (lua_State *L) {
242
329k
  CallInfo *ci;
243
329k
  UpVal *up;
244
329k
  L->top.offset = savestack(L, L->top.p);
245
329k
  L->tbclist.offset = savestack(L, L->tbclist.p);
246
26.8M
  for (up = L->openupval; up != NULL; up = up->u.open.next)
247
26.4M
    up->v.offset = savestack(L, uplevel(up));
248
244M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
249
244M
    ci->top.offset = savestack(L, ci->top.p);
250
244M
    ci->func.offset = savestack(L, ci->func.p);
251
244M
  }
252
329k
}
253
254
255
/*
256
** Change back all offsets into pointers.
257
*/
258
329k
static void correctstack (lua_State *L, StkId oldstack) {
259
329k
  CallInfo *ci;
260
329k
  UpVal *up;
261
329k
  UNUSED(oldstack);
262
329k
  L->top.p = restorestack(L, L->top.offset);
263
329k
  L->tbclist.p = restorestack(L, L->tbclist.offset);
264
26.8M
  for (up = L->openupval; up != NULL; up = up->u.open.next)
265
26.4M
    up->v.p = s2v(restorestack(L, up->v.offset));
266
244M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
267
244M
    ci->top.p = restorestack(L, ci->top.offset);
268
244M
    ci->func.p = restorestack(L, ci->func.offset);
269
244M
    if (isLua(ci))
270
240M
      ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */
271
244M
  }
272
329k
}
273
274
#else
275
/*
276
** Assume that it is fine to use an address after its deallocation,
277
** as long as we do not dereference it.
278
*/
279
280
static void relstack (lua_State *L) { UNUSED(L); }  /* do nothing */
281
282
283
/*
284
** Correct pointers into 'oldstack' to point into 'L->stack'.
285
*/
286
static void correctstack (lua_State *L, StkId oldstack) {
287
  CallInfo *ci;
288
  UpVal *up;
289
  StkId newstack = L->stack.p;
290
  if (oldstack == newstack)
291
    return;
292
  L->top.p = L->top.p - oldstack + newstack;
293
  L->tbclist.p = L->tbclist.p - oldstack + newstack;
294
  for (up = L->openupval; up != NULL; up = up->u.open.next)
295
    up->v.p = s2v(uplevel(up) - oldstack + newstack);
296
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
297
    ci->top.p = ci->top.p - oldstack + newstack;
298
    ci->func.p = ci->func.p - oldstack + newstack;
299
    if (isLua(ci))
300
      ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */
301
  }
302
}
303
#endif
304
305
306
/*
307
** Reallocate the stack to a new size, correcting all pointers into it.
308
** In case of allocation error, raise an error or return false according
309
** to 'raiseerror'.
310
*/
311
329k
int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
312
329k
  int oldsize = stacksize(L);
313
329k
  int i;
314
329k
  StkId newstack;
315
329k
  StkId oldstack = L->stack.p;
316
329k
  lu_byte oldgcstop = G(L)->gcstopem;
317
329k
  lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE);
318
329k
  relstack(L);  /* change pointers to offsets */
319
329k
  G(L)->gcstopem = 1;  /* stop emergency collection */
320
329k
  newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK,
321
329k
                                   newsize + EXTRA_STACK, StackValue);
322
329k
  G(L)->gcstopem = oldgcstop;  /* restore emergency collection */
323
329k
  if (l_unlikely(newstack == NULL)) {  /* reallocation failed? */
324
0
    correctstack(L, oldstack);  /* change offsets back to pointers */
325
0
    if (raiseerror)
326
0
      luaM_error(L);
327
0
    else return 0;  /* do not raise an error */
328
0
  }
329
329k
  L->stack.p = newstack;
330
329k
  correctstack(L, oldstack);  /* change offsets back to pointers */
331
329k
  L->stack_last.p = L->stack.p + newsize;
332
345M
  for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
333
345M
    setnilvalue(s2v(newstack + i)); /* erase new segment */
334
329k
  return 1;
335
329k
}
336
337
338
/*
339
** Try to grow the stack by at least 'n' elements. When 'raiseerror'
340
** is true, raises any error; otherwise, return 0 in case of errors.
341
*/
342
258k
int luaD_growstack (lua_State *L, int n, int raiseerror) {
343
258k
  int size = stacksize(L);
344
258k
  if (l_unlikely(size > MAXSTACK)) {
345
    /* if stack is larger than maximum, thread is already using the
346
       extra space reserved for errors, that is, thread is handling
347
       a stack error; cannot grow further than that. */
348
64
    lua_assert(stacksize(L) == ERRORSTACKSIZE);
349
64
    if (raiseerror)
350
64
      luaD_errerr(L);  /* stack error inside message handler */
351
0
    return 0;  /* if not 'raiseerror', just signal it */
352
64
  }
353
258k
  else if (n < MAXSTACK) {  /* avoids arithmetic overflows */
354
258k
    int newsize = size + (size >> 1);  /* tentative new size (size * 1.5) */
355
258k
    int needed = cast_int(L->top.p - L->stack.p) + n;
356
258k
    if (newsize > MAXSTACK)  /* cannot cross the limit */
357
737
      newsize = MAXSTACK;
358
258k
    if (newsize < needed)  /* but must respect what was asked for */
359
39.7k
      newsize = needed;
360
258k
    if (l_likely(newsize <= MAXSTACK))
361
258k
      return luaD_reallocstack(L, newsize, raiseerror);
362
258k
  }
363
  /* else stack overflow */
364
  /* add extra size to be able to handle the error message */
365
315
  luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
366
315
  if (raiseerror)
367
315
    luaG_runerror(L, "stack overflow");
368
0
  return 0;
369
315
}
370
371
372
/*
373
** Compute how much of the stack is being used, by computing the
374
** maximum top of all call frames in the stack and the current top.
375
*/
376
14.4M
static int stackinuse (lua_State *L) {
377
14.4M
  CallInfo *ci;
378
14.4M
  int res;
379
14.4M
  StkId lim = L->top.p;
380
709M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
381
694M
    if (lim < ci->top.p) lim = ci->top.p;
382
694M
  }
383
14.4M
  lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
384
14.4M
  res = cast_int(lim - L->stack.p) + 1;  /* part of stack in use */
385
14.4M
  if (res < LUA_MINSTACK)
386
818
    res = LUA_MINSTACK;  /* ensure a minimum size */
387
14.4M
  return res;
388
14.4M
}
389
390
391
/*
392
** If stack size is more than 3 times the current use, reduce that size
393
** to twice the current use. (So, the final stack size is at most 2/3 the
394
** previous size, and half of its entries are empty.)
395
** As a particular case, if stack was handling a stack overflow and now
396
** it is not, 'max' (limited by MAXSTACK) will be smaller than
397
** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
398
** will be reduced to a "regular" size.
399
*/
400
14.4M
void luaD_shrinkstack (lua_State *L) {
401
14.4M
  int inuse = stackinuse(L);
402
14.4M
  int max = (inuse > MAXSTACK / 3) ? MAXSTACK : inuse * 3;
403
  /* if thread is currently not handling a stack overflow and its
404
     size is larger than maximum "reasonable" size, shrink it */
405
14.4M
  if (inuse <= MAXSTACK && stacksize(L) > max) {
406
71.3k
    int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2;
407
71.3k
    luaD_reallocstack(L, nsize, 0);  /* ok if that fails */
408
71.3k
  }
409
14.3M
  else  /* don't change stack */
410
14.3M
    condmovestack(L,(void)0,(void)0);  /* (change only for debugging) */
411
14.4M
  luaE_shrinkCI(L);  /* shrink CI list */
412
14.4M
}
413
414
415
26.4M
void luaD_inctop (lua_State *L) {
416
26.4M
  L->top.p++;
417
26.4M
  luaD_checkstack(L, 1);
418
26.4M
}
419
420
/* }================================================================== */
421
422
423
/*
424
** Call a hook for the given event. Make sure there is a hook to be
425
** called. (Both 'L->hook' and 'L->hookmask', which trigger this
426
** function, can be changed asynchronously by signals.)
427
*/
428
void luaD_hook (lua_State *L, int event, int line,
429
59.0M
                              int ftransfer, int ntransfer) {
430
59.0M
  lua_Hook hook = L->hook;
431
59.0M
  if (hook && L->allowhook) {  /* make sure there is a hook */
432
4.53M
    CallInfo *ci = L->ci;
433
4.53M
    ptrdiff_t top = savestack(L, L->top.p);  /* preserve original 'top' */
434
4.53M
    ptrdiff_t ci_top = savestack(L, ci->top.p);  /* idem for 'ci->top' */
435
4.53M
    lua_Debug ar;
436
4.53M
    ar.event = event;
437
4.53M
    ar.currentline = line;
438
4.53M
    ar.i_ci = ci;
439
4.53M
    L->transferinfo.ftransfer = ftransfer;
440
4.53M
    L->transferinfo.ntransfer = ntransfer;
441
4.53M
    if (isLua(ci) && L->top.p < ci->top.p)
442
194k
      L->top.p = ci->top.p;  /* protect entire activation register */
443
4.53M
    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
444
4.53M
    if (ci->top.p < L->top.p + LUA_MINSTACK)
445
3.96M
      ci->top.p = L->top.p + LUA_MINSTACK;
446
4.53M
    L->allowhook = 0;  /* cannot call hooks inside a hook */
447
4.53M
    ci->callstatus |= CIST_HOOKED;
448
4.53M
    lua_unlock(L);
449
4.53M
    (*hook)(L, &ar);
450
4.53M
    lua_lock(L);
451
4.53M
    lua_assert(!L->allowhook);
452
4.53M
    L->allowhook = 1;
453
4.53M
    ci->top.p = restorestack(L, ci_top);
454
4.53M
    L->top.p = restorestack(L, top);
455
4.53M
    ci->callstatus &= ~CIST_HOOKED;
456
4.53M
  }
457
59.0M
}
458
459
460
/*
461
** Executes a call hook for Lua functions. This function is called
462
** whenever 'hookmask' is not zero, so it checks whether call hooks are
463
** active.
464
*/
465
6.32M
void luaD_hookcall (lua_State *L, CallInfo *ci) {
466
6.32M
  L->oldpc = 0;  /* set 'oldpc' for new function */
467
6.32M
  if (L->hookmask & LUA_MASKCALL) {  /* is call hook on? */
468
2.46M
    int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
469
2.46M
                                             : LUA_HOOKCALL;
470
4.92M
    Proto *p = ci_func(ci)->p;
471
4.92M
    ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
472
4.92M
    luaD_hook(L, event, -1, 1, p->numparams);
473
4.92M
    ci->u.l.savedpc--;  /* correct 'pc' */
474
4.92M
  }
475
6.32M
}
476
477
478
/*
479
** Executes a return hook for Lua and C functions and sets/corrects
480
** 'oldpc'. (Note that this correction is needed by the line hook, so it
481
** is done even when return hooks are off.)
482
*/
483
12.9M
static void rethook (lua_State *L, CallInfo *ci, int nres) {
484
12.9M
  if (L->hookmask & LUA_MASKRET) {  /* is return hook on? */
485
6.10M
    StkId firstres = L->top.p - nres;  /* index of first result */
486
6.10M
    int delta = 0;  /* correction for vararg functions */
487
6.10M
    int ftransfer;
488
6.10M
    if (isLua(ci)) {
489
5.79M
      Proto *p = ci_func(ci)->p;
490
5.79M
      if (p->flag & PF_ISVARARG)
491
38.0k
        delta = ci->u.l.nextraargs + p->numparams + 1;
492
5.79M
    }
493
6.10M
    ci->func.p += delta;  /* if vararg, back to virtual 'func' */
494
6.10M
    ftransfer = cast_int(firstres - ci->func.p);
495
6.10M
    luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres);  /* call it */
496
6.10M
    ci->func.p -= delta;
497
6.10M
  }
498
12.9M
  if (isLua(ci = ci->previous))
499
11.1M
    L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p);  /* set 'oldpc' */
500
12.9M
}
501
502
503
/*
504
** Check whether 'func' has a '__call' metafield. If so, put it in the
505
** stack, below original 'func', so that 'luaD_precall' can call it.
506
** Raise an error if there is no '__call' metafield.
507
** Bits CIST_CCMT in status count how many _call metamethods were
508
** invoked and how many corresponding extra arguments were pushed.
509
** (This count will be saved in the 'callstatus' of the call).
510
**  Raise an error if this counter overflows.
511
*/
512
33.5M
static unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) {
513
33.5M
  const TValue *tm;
514
33.5M
  StkId p;
515
33.5M
  tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
516
33.5M
  if (l_unlikely(ttisnil(tm)))  /* no metamethod? */
517
705k
    luaG_callerror(L, s2v(func));
518
107M
  for (p = L->top.p; p > func; p--)  /* open space for metamethod */
519
74.5M
    setobjs2s(L, p, p-1);
520
32.8M
  L->top.p++;  /* stack space pre-allocated by the caller */
521
32.8M
  setobj2s(L, func, tm);  /* metamethod is the new function to be called */
522
32.8M
  if ((status & MAX_CCMT) == MAX_CCMT)  /* is counter full? */
523
0
    luaG_runerror(L, "'__call' chain too long");
524
32.8M
  return status + (1u << CIST_CCMT);  /* increment counter */
525
32.8M
}
526
527
528
/* Generic case for 'moveresult' */
529
l_sinline void genmoveresults (lua_State *L, StkId res, int nres,
530
2.81M
                                             int wanted) {
531
2.81M
  StkId firstresult = L->top.p - nres;  /* index of first result */
532
2.81M
  int i;
533
2.81M
  if (nres > wanted)  /* extra results? */
534
427k
    nres = wanted;  /* don't need them */
535
6.36M
  for (i = 0; i < nres; i++)  /* move all results to correct place */
536
3.54M
    setobjs2s(L, res + i, firstresult + i);
537
4.97M
  for (; i < wanted; i++)  /* complete wanted number of results */
538
2.81M
    setnilvalue(s2v(res + i));
539
2.81M
  L->top.p = res + wanted;  /* top points after the last result */
540
2.81M
}
541
542
543
/*
544
** Given 'nres' results at 'firstResult', move 'fwanted-1' of them
545
** to 'res'.  Handle most typical cases (zero results for commands,
546
** one result for expressions, multiple results for tail calls/single
547
** parameters) separated. The flag CIST_TBC in 'fwanted', if set,
548
** forces the switch to go to the default case.
549
*/
550
l_sinline void moveresults (lua_State *L, StkId res, int nres,
551
316M
                                          l_uint32 fwanted) {
552
316M
  switch (fwanted) {  /* handle typical cases separately */
553
25.2M
    case 0 + 1:  /* no values needed */
554
25.2M
      L->top.p = res;
555
25.2M
      return;
556
288M
    case 1 + 1:  /* one value needed */
557
288M
      if (nres == 0)   /* no results? */
558
288M
        setnilvalue(s2v(res));  /* adjust with nil */
559
285M
      else  /* at least one result */
560
288M
        setobjs2s(L, res, L->top.p - nres);  /* move it to proper place */
561
288M
      L->top.p = res + 1;
562
288M
      return;
563
932k
    case LUA_MULTRET + 1:
564
932k
      genmoveresults(L, res, nres, nres);  /* we want all results */
565
932k
      break;
566
1.88M
    default: {  /* two/more results and/or to-be-closed variables */
567
1.88M
      int wanted = get_nresults(fwanted);
568
1.88M
      if (fwanted & CIST_TBC) {  /* to-be-closed variables? */
569
787k
        L->ci->u2.nres = nres;
570
787k
        L->ci->callstatus |= CIST_CLSRET;  /* in case of yields */
571
787k
        res = luaF_close(L, res, CLOSEKTOP, 1);
572
787k
        L->ci->callstatus &= ~CIST_CLSRET;
573
787k
        if (L->hookmask) {  /* if needed, call hook after '__close's */
574
58.9k
          ptrdiff_t savedres = savestack(L, res);
575
58.9k
          rethook(L, L->ci, nres);
576
58.9k
          res = restorestack(L, savedres);  /* hook can move stack */
577
58.9k
        }
578
787k
        if (wanted == LUA_MULTRET)
579
5.57k
          wanted = nres;  /* we want all results */
580
787k
      }
581
1.88M
      genmoveresults(L, res, nres, wanted);
582
1.88M
      break;
583
288M
    }
584
316M
  }
585
316M
}
586
587
588
/*
589
** Finishes a function call: calls hook if necessary, moves current
590
** number of results to proper place, and returns to previous call
591
** info. If function has to close variables, hook must be called after
592
** that.
593
*/
594
316M
void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
595
316M
  l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS);
596
316M
  if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC))
597
12.8M
    rethook(L, ci, nres);
598
  /* move results to proper place */
599
316M
  moveresults(L, ci->func.p, nres, fwanted);
600
  /* function cannot be in any of these cases when returning */
601
316M
  lua_assert(!(ci->callstatus &
602
316M
        (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET)));
603
316M
  L->ci = ci->previous;  /* back to caller (after closing variables) */
604
316M
}
605
606
607
608
583M
#define next_ci(L)  (L->ci->next ? L->ci->next : luaE_extendCI(L))
609
610
611
/*
612
** Allocate and initialize CallInfo structure. At this point, the
613
** only valid fields in the call status are number of results,
614
** CIST_C (if it's a C function), and number of extra arguments.
615
** (All these bit-fields fit in 16-bit values.)
616
*/
617
l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, unsigned status,
618
583M
                                                StkId top) {
619
583M
  CallInfo *ci = L->ci = next_ci(L);  /* new frame */
620
583M
  ci->func.p = func;
621
583M
  lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0);
622
583M
  ci->callstatus = status;
623
583M
  ci->top.p = top;
624
583M
  return ci;
625
583M
}
626
627
628
/*
629
** precall for C functions
630
*/
631
l_sinline int precallC (lua_State *L, StkId func, unsigned status,
632
310M
                                            lua_CFunction f) {
633
310M
  int n;  /* number of returns */
634
310M
  CallInfo *ci;
635
310M
  checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
636
310M
  L->ci = ci = prepCallInfo(L, func, status | CIST_C,
637
310M
                               L->top.p + LUA_MINSTACK);
638
310M
  lua_assert(ci->top.p <= L->stack_last.p);
639
310M
  if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
640
3.92M
    int narg = cast_int(L->top.p - func) - 1;
641
3.92M
    luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
642
3.92M
  }
643
310M
  lua_unlock(L);
644
310M
  n = (*f)(L);  /* do the actual call */
645
310M
  lua_lock(L);
646
310M
  api_checknelems(L, n);
647
310M
  luaD_poscall(L, ci, n);
648
308M
  return n;
649
310M
}
650
651
652
/*
653
** Prepare a function for a tail call, building its call info on top
654
** of the current call info. 'narg1' is the number of arguments plus 1
655
** (so that it includes the function itself). Return the number of
656
** results, if it was a C function, or -1 for a Lua function.
657
*/
658
int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
659
91.1M
                                    int narg1, int delta) {
660
91.1M
  unsigned status = LUA_MULTRET + 1;
661
91.1M
 retry:
662
91.1M
  switch (ttypetag(s2v(func))) {
663
68
    case LUA_VCCL:  /* C closure */
664
68
      return precallC(L, func, status, clCvalue(s2v(func))->f);
665
12.1k
    case LUA_VLCF:  /* light C function */
666
12.1k
      return precallC(L, func, status, fvalue(s2v(func)));
667
91.1M
    case LUA_VLCL: {  /* Lua function */
668
182M
      Proto *p = clLvalue(s2v(func))->p;
669
182M
      int fsize = p->maxstacksize;  /* frame size */
670
182M
      int nfixparams = p->numparams;
671
182M
      int i;
672
182M
      checkstackp(L, fsize - delta, func);
673
182M
      ci->func.p -= delta;  /* restore 'func' (if vararg) */
674
274M
      for (i = 0; i < narg1; i++)  /* move down function and arguments */
675
183M
        setobjs2s(L, ci->func.p + i, func + i);
676
91.1M
      func = ci->func.p;  /* moved-down function */
677
93.2M
      for (; narg1 <= nfixparams; narg1++)
678
91.1M
        setnilvalue(s2v(func + narg1));  /* complete missing arguments */
679
91.1M
      ci->top.p = func + 1 + fsize;  /* top for new function */
680
91.1M
      lua_assert(ci->top.p <= L->stack_last.p);
681
91.1M
      ci->u.l.savedpc = p->code;  /* starting point */
682
91.1M
      ci->callstatus |= CIST_TAIL;
683
91.1M
      L->top.p = func + narg1;  /* set top */
684
91.1M
      return -1;
685
91.1M
    }
686
8.14k
    default: {  /* not a function */
687
8.14k
      checkstackp(L, 1, func);  /* space for metamethod */
688
8.14k
      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */
689
8.14k
      narg1++;
690
8.14k
      goto retry;  /* try again */
691
91.1M
    }
692
91.1M
  }
693
91.1M
}
694
695
696
/*
697
** Prepares the call to a function (C or Lua). For C functions, also do
698
** the call. The function to be called is at '*func'.  The arguments
699
** are on the stack, right after the function.  Returns the CallInfo
700
** to be executed, if it was a Lua function. Otherwise (a C function)
701
** returns NULL, with all the results on the stack, starting at the
702
** original function position.
703
*/
704
584M
CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
705
584M
  unsigned status = cast_uint(nresults + 1);
706
584M
  lua_assert(status <= MAXRESULTS + 1);
707
616M
 retry:
708
616M
  switch (ttypetag(s2v(func))) {
709
1.11M
    case LUA_VCCL:  /* C closure */
710
1.11M
      precallC(L, func, status, clCvalue(s2v(func))->f);
711
1.11M
      return NULL;
712
309M
    case LUA_VLCF:  /* light C function */
713
309M
      precallC(L, func, status, fvalue(s2v(func)));
714
309M
      return NULL;
715
272M
    case LUA_VLCL: {  /* Lua function */
716
272M
      CallInfo *ci;
717
545M
      Proto *p = clLvalue(s2v(func))->p;
718
545M
      int narg = cast_int(L->top.p - func) - 1;  /* number of real arguments */
719
545M
      int nfixparams = p->numparams;
720
545M
      int fsize = p->maxstacksize;  /* frame size */
721
545M
      checkstackp(L, fsize, func);
722
545M
      L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize);
723
545M
      ci->u.l.savedpc = p->code;  /* starting point */
724
545M
      for (; narg < nfixparams; narg++)
725
272M
        setnilvalue(s2v(L->top.p++));  /* complete missing arguments */
726
545M
      lua_assert(ci->top.p <= L->stack_last.p);
727
545M
      return ci;
728
545M
    }
729
33.5M
    default: {  /* not a function */
730
33.5M
      checkstackp(L, 1, func);  /* space for metamethod */
731
33.5M
      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */
732
33.5M
      goto retry;  /* try again with metamethod */
733
545M
    }
734
616M
  }
735
616M
}
736
737
738
/*
739
** Call a function (C or Lua) through C. 'inc' can be 1 (increment
740
** number of recursive invocations in the C stack) or nyci (the same
741
** plus increment number of non-yieldable calls).
742
** This function can be called with some use of EXTRA_STACK, so it should
743
** check the stack before doing anything else. 'luaD_precall' already
744
** does that.
745
*/
746
160M
l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
747
160M
  CallInfo *ci;
748
160M
  L->nCcalls += inc;
749
160M
  if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
750
837k
    checkstackp(L, 0, func);  /* free any use of EXTRA_STACK */
751
837k
    luaE_checkcstack(L);
752
837k
  }
753
160M
  if ((ci = luaD_precall(L, func, nResults)) != NULL) {  /* Lua function? */
754
152M
    ci->callstatus |= CIST_FRESH;  /* mark that it is a "fresh" execute */
755
152M
    luaV_execute(L, ci);  /* call it */
756
152M
  }
757
160M
  L->nCcalls -= inc;
758
160M
}
759
760
761
/*
762
** External interface for 'ccall'
763
*/
764
143M
void luaD_call (lua_State *L, StkId func, int nResults) {
765
143M
  ccall(L, func, nResults, 1);
766
143M
}
767
768
769
/*
770
** Similar to 'luaD_call', but does not allow yields during the call.
771
*/
772
17.2M
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
773
17.2M
  ccall(L, func, nResults, nyci);
774
17.2M
}
775
776
777
/*
778
** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
779
** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
780
** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
781
** If a '__close' method yields here, eventually control will be back
782
** to 'finishCcall' (when that '__close' method finally returns) and
783
** 'finishpcallk' will run again and close any still pending '__close'
784
** methods. Similarly, if a '__close' method errs, 'precover' calls
785
** 'unroll' which calls ''finishCcall' and we are back here again, to
786
** close any pending '__close' methods.
787
** Note that, up to the call to 'luaF_close', the corresponding
788
** 'CallInfo' is not modified, so that this repeated run works like the
789
** first one (except that it has at least one less '__close' to do). In
790
** particular, field CIST_RECST preserves the error status across these
791
** multiple runs, changing only if there is a new error.
792
*/
793
462
static TStatus finishpcallk (lua_State *L,  CallInfo *ci) {
794
462
  TStatus status = getcistrecst(ci);  /* get original status */
795
462
  if (l_likely(status == LUA_OK))  /* no error? */
796
21
    status = LUA_YIELD;  /* was interrupted by an yield */
797
441
  else {  /* error */
798
441
    StkId func = restorestack(L, ci->u2.funcidx);
799
441
    L->allowhook = getoah(ci);  /* restore 'allowhook' */
800
441
    func = luaF_close(L, func, status, 1);  /* can yield or raise an error */
801
441
    luaD_seterrorobj(L, status, func);
802
441
    luaD_shrinkstack(L);   /* restore stack size in case of overflow */
803
441
    setcistrecst(ci, LUA_OK);  /* clear original status */
804
441
  }
805
462
  ci->callstatus &= ~CIST_YPCALL;
806
462
  L->errfunc = ci->u.c.old_errfunc;
807
  /* if it is here, there were errors or yields; unlike 'lua_pcallk',
808
     do not change status */
809
462
  return status;
810
462
}
811
812
813
/*
814
** Completes the execution of a C function interrupted by an yield.
815
** The interruption must have happened while the function was either
816
** closing its tbc variables in 'moveresults' or executing
817
** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
818
** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
819
** finishes the interrupted execution of 'lua_pcallk'.  After that, it
820
** calls the continuation of the interrupted function and finally it
821
** completes the job of the 'luaD_call' that called the function.  In
822
** the call to 'adjustresults', we do not know the number of results
823
** of the function called by 'lua_callk'/'lua_pcallk', so we are
824
** conservative and use LUA_MULTRET (always adjust).
825
*/
826
462
static void finishCcall (lua_State *L, CallInfo *ci) {
827
462
  int n;  /* actual number of results from C function */
828
462
  if (ci->callstatus & CIST_CLSRET) {  /* was closing TBC variable? */
829
0
    lua_assert(ci->callstatus & CIST_TBC);
830
0
    n = ci->u2.nres;  /* just redo 'luaD_poscall' */
831
    /* don't need to reset CIST_CLSRET, as it will be set again anyway */
832
0
  }
833
462
  else {
834
462
    TStatus status = LUA_YIELD;  /* default if there were no errors */
835
462
    lua_KFunction kf = ci->u.c.k;  /* continuation function */
836
    /* must have a continuation and must be able to call it */
837
462
    lua_assert(kf != NULL && yieldable(L));
838
462
    if (ci->callstatus & CIST_YPCALL)   /* was inside a 'lua_pcallk'? */
839
462
      status = finishpcallk(L, ci);  /* finish it */
840
462
    adjustresults(L, LUA_MULTRET);  /* finish 'lua_callk' */
841
462
    lua_unlock(L);
842
462
    n = (*kf)(L, APIstatus(status), ci->u.c.ctx);  /* call continuation */
843
462
    lua_lock(L);
844
462
    api_checknelems(L, n);
845
462
  }
846
462
  luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
847
462
}
848
849
850
/*
851
** Executes "full continuation" (everything in the stack) of a
852
** previously interrupted coroutine until the stack is empty (or another
853
** interruption long-jumps out of the loop).
854
*/
855
687
static void unroll (lua_State *L, void *ud) {
856
687
  CallInfo *ci;
857
687
  UNUSED(ud);
858
1.86k
  while ((ci = L->ci) != &L->base_ci) {  /* something in the stack */
859
1.17k
    if (!isLua(ci))  /* C function? */
860
462
      finishCcall(L, ci);  /* complete its execution */
861
712
    else {  /* Lua function */
862
712
      luaV_finishOp(L);  /* finish interrupted instruction */
863
712
      luaV_execute(L, ci);  /* execute down to higher C 'boundary' */
864
712
    }
865
1.17k
  }
866
687
}
867
868
869
/*
870
** Try to find a suspended protected call (a "recover point") for the
871
** given thread.
872
*/
873
15.5k
static CallInfo *findpcall (lua_State *L) {
874
15.5k
  CallInfo *ci;
875
59.7k
  for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
876
44.6k
    if (ci->callstatus & CIST_YPCALL)
877
441
      return ci;
878
44.6k
  }
879
15.0k
  return NULL;  /* no pending pcall */
880
15.5k
}
881
882
883
/*
884
** Signal an error in the call to 'lua_resume', not in the execution
885
** of the coroutine itself. (Such errors should not be handled by any
886
** coroutine error handler and should not kill the coroutine.)
887
*/
888
5.27k
static int resume_error (lua_State *L, const char *msg, int narg) {
889
5.27k
  api_checkpop(L, narg);
890
5.27k
  L->top.p -= narg;  /* remove args from the stack */
891
5.27k
  setsvalue2s(L, L->top.p, luaS_new(L, msg));  /* push error message */
892
5.27k
  api_incr_top(L);
893
5.27k
  lua_unlock(L);
894
5.27k
  return LUA_ERRRUN;
895
5.27k
}
896
897
898
/*
899
** Do the work for 'lua_resume' in protected mode. Most of the work
900
** depends on the status of the coroutine: initial state, suspended
901
** inside a hook, or regularly suspended (optionally with a continuation
902
** function), plus erroneous cases: non-suspended coroutine or dead
903
** coroutine.
904
*/
905
19.4k
static void resume (lua_State *L, void *ud) {
906
19.4k
  int n = *(cast(int*, ud));  /* number of arguments */
907
19.4k
  StkId firstArg = L->top.p - n;  /* first argument */
908
19.4k
  CallInfo *ci = L->ci;
909
19.4k
  if (L->status == LUA_OK)  /* starting a coroutine? */
910
19.2k
    ccall(L, firstArg - 1, LUA_MULTRET, 0);  /* just call its body */
911
246
  else {  /* resuming from previous yield */
912
246
    lua_assert(L->status == LUA_YIELD);
913
246
    L->status = LUA_OK;  /* mark that it is running (again) */
914
246
    if (isLua(ci)) {  /* yielded inside a hook? */
915
      /* undo increment made by 'luaG_traceexec': instruction was not
916
         executed yet */
917
0
      lua_assert(ci->callstatus & CIST_HOOKYIELD);
918
0
      ci->u.l.savedpc--;
919
0
      L->top.p = firstArg;  /* discard arguments */
920
0
      luaV_execute(L, ci);  /* just continue running Lua code */
921
0
    }
922
246
    else {  /* 'common' yield */
923
246
      if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
924
0
        lua_unlock(L);
925
0
        n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
926
0
        lua_lock(L);
927
0
        api_checknelems(L, n);
928
0
      }
929
246
      luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
930
246
    }
931
246
    unroll(L, NULL);  /* run continuation */
932
246
  }
933
19.4k
}
934
935
936
/*
937
** Unrolls a coroutine in protected mode while there are recoverable
938
** errors, that is, errors inside a protected call. (Any error
939
** interrupts 'unroll', and this loop protects it again so it can
940
** continue.) Stops with a normal end (status == LUA_OK), an yield
941
** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
942
** find a recover point).
943
*/
944
19.4k
static TStatus precover (lua_State *L, TStatus status) {
945
19.4k
  CallInfo *ci;
946
19.9k
  while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
947
441
    L->ci = ci;  /* go down to recovery functions */
948
441
    setcistrecst(ci, status);  /* status to finish 'pcall' */
949
441
    status = luaD_rawrunprotected(L, unroll, NULL);
950
441
  }
951
19.4k
  return status;
952
19.4k
}
953
954
955
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
956
24.7k
                                      int *nresults) {
957
24.7k
  TStatus status;
958
24.7k
  lua_lock(L);
959
24.7k
  if (L->status == LUA_OK) {  /* may be starting a coroutine */
960
21.7k
    if (L->ci != &L->base_ci)  /* not in base level? */
961
1.29k
      return resume_error(L, "cannot resume non-suspended coroutine", nargs);
962
20.4k
    else if (L->top.p - (L->ci->func.p + 1) == nargs)  /* no function? */
963
100
      return resume_error(L, "cannot resume dead coroutine", nargs);
964
21.7k
  }
965
3.03k
  else if (L->status != LUA_YIELD)  /* ended with errors? */
966
2.78k
    return resume_error(L, "cannot resume dead coroutine", nargs);
967
20.5k
  L->nCcalls = (from) ? getCcalls(from) : 0;
968
20.5k
  if (getCcalls(L) >= LUAI_MAXCCALLS)
969
1.09k
    return resume_error(L, "C stack overflow", nargs);
970
19.4k
  L->nCcalls++;
971
19.4k
  luai_userstateresume(L, nargs);
972
19.4k
  api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
973
19.4k
  status = luaD_rawrunprotected(L, resume, &nargs);
974
   /* continue running after recoverable errors */
975
19.4k
  status = precover(L, status);
976
19.4k
  if (l_likely(!errorstatus(status)))
977
19.4k
    lua_assert(status == L->status);  /* normal end or yield */
978
15.0k
  else {  /* unrecoverable error */
979
15.0k
    L->status = status;  /* mark thread as 'dead' */
980
15.0k
    luaD_seterrorobj(L, status, L->top.p);  /* push error message */
981
15.0k
    L->ci->top.p = L->top.p;
982
15.0k
  }
983
19.4k
  *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
984
19.4k
                                    : cast_int(L->top.p - (L->ci->func.p + 1));
985
19.4k
  lua_unlock(L);
986
19.4k
  return APIstatus(status);
987
19.4k
}
988
989
990
1
LUA_API int lua_isyieldable (lua_State *L) {
991
1
  return yieldable(L);
992
1
}
993
994
995
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
996
2.74k
                        lua_KFunction k) {
997
2.74k
  CallInfo *ci;
998
2.74k
  luai_userstateyield(L, nresults);
999
2.74k
  lua_lock(L);
1000
2.74k
  ci = L->ci;
1001
2.74k
  api_checkpop(L, nresults);
1002
2.74k
  if (l_unlikely(!yieldable(L))) {
1003
7
    if (L != mainthread(G(L)))
1004
0
      luaG_runerror(L, "attempt to yield across a C-call boundary");
1005
7
    else
1006
7
      luaG_runerror(L, "attempt to yield from outside a coroutine");
1007
7
  }
1008
2.73k
  L->status = LUA_YIELD;
1009
2.73k
  ci->u2.nyield = nresults;  /* save number of results */
1010
2.73k
  if (isLua(ci)) {  /* inside a hook? */
1011
0
    lua_assert(!isLuacode(ci));
1012
0
    api_check(L, nresults == 0, "hooks cannot yield values");
1013
0
    api_check(L, k == NULL, "hooks cannot continue after yielding");
1014
0
  }
1015
2.73k
  else {
1016
2.73k
    if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
1017
0
      ci->u.c.ctx = ctx;  /* save context */
1018
2.73k
    luaD_throw(L, LUA_YIELD);
1019
2.73k
  }
1020
0
  lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */
1021
0
  lua_unlock(L);
1022
0
  return 0;  /* return to 'luaD_hook' */
1023
0
}
1024
1025
1026
/*
1027
** Auxiliary structure to call 'luaF_close' in protected mode.
1028
*/
1029
struct CloseP {
1030
  StkId level;
1031
  TStatus status;
1032
};
1033
1034
1035
/*
1036
** Auxiliary function to call 'luaF_close' in protected mode.
1037
*/
1038
5.69M
static void closepaux (lua_State *L, void *ud) {
1039
5.69M
  struct CloseP *pcl = cast(struct CloseP *, ud);
1040
5.69M
  luaF_close(L, pcl->level, pcl->status, 0);
1041
5.69M
}
1042
1043
1044
/*
1045
** Calls 'luaF_close' in protected mode. Return the original status
1046
** or, in case of errors, the new status.
1047
*/
1048
5.69M
TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) {
1049
5.69M
  CallInfo *old_ci = L->ci;
1050
5.69M
  lu_byte old_allowhooks = L->allowhook;
1051
5.69M
  for (;;) {  /* keep closing upvalues until no more errors */
1052
5.69M
    struct CloseP pcl;
1053
5.69M
    pcl.level = restorestack(L, level); pcl.status = status;
1054
5.69M
    status = luaD_rawrunprotected(L, &closepaux, &pcl);
1055
5.69M
    if (l_likely(status == LUA_OK))  /* no more errors? */
1056
5.69M
      return pcl.status;
1057
1
    else {  /* an error occurred; restore saved state and repeat */
1058
1
      L->ci = old_ci;
1059
1
      L->allowhook = old_allowhooks;
1060
1
    }
1061
5.69M
  }
1062
5.69M
}
1063
1064
1065
/*
1066
** Call the C function 'func' in protected mode, restoring basic
1067
** thread information ('allowhook', etc.) and in particular
1068
** its stack level in case of errors.
1069
*/
1070
TStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top,
1071
13.7M
                                  ptrdiff_t ef) {
1072
13.7M
  TStatus status;
1073
13.7M
  CallInfo *old_ci = L->ci;
1074
13.7M
  lu_byte old_allowhooks = L->allowhook;
1075
13.7M
  ptrdiff_t old_errfunc = L->errfunc;
1076
13.7M
  L->errfunc = ef;
1077
13.7M
  status = luaD_rawrunprotected(L, func, u);
1078
13.7M
  if (l_unlikely(status != LUA_OK)) {  /* an error occurred? */
1079
5.63M
    L->ci = old_ci;
1080
5.63M
    L->allowhook = old_allowhooks;
1081
5.63M
    status = luaD_closeprotected(L, old_top, status);
1082
5.63M
    luaD_seterrorobj(L, status, restorestack(L, old_top));
1083
5.63M
    luaD_shrinkstack(L);   /* restore stack size in case of overflow */
1084
5.63M
  }
1085
13.7M
  L->errfunc = old_errfunc;
1086
13.7M
  return status;
1087
13.7M
}
1088
1089
1090
1091
/*
1092
** Execute a protected parser.
1093
*/
1094
struct SParser {  /* data to 'f_parser' */
1095
  ZIO *z;
1096
  Mbuffer buff;  /* dynamic structure used by the scanner */
1097
  Dyndata dyd;  /* dynamic structures used by the parser */
1098
  const char *mode;
1099
  const char *name;
1100
};
1101
1102
1103
8.31M
static void checkmode (lua_State *L, const char *mode, const char *x) {
1104
8.31M
  if (strchr(mode, x[0]) == NULL) {
1105
12.0k
    luaO_pushfstring(L,
1106
12.0k
       "attempt to load a %s chunk (mode is '%s')", x, mode);
1107
12.0k
    luaD_throw(L, LUA_ERRSYNTAX);
1108
12.0k
  }
1109
8.31M
}
1110
1111
1112
8.74M
static void f_parser (lua_State *L, void *ud) {
1113
8.74M
  LClosure *cl;
1114
8.74M
  struct SParser *p = cast(struct SParser *, ud);
1115
8.74M
  const char *mode = p->mode ? p->mode : "bt";
1116
8.74M
  int c = zgetc(p->z);  /* read first character */
1117
8.74M
  if (c == LUA_SIGNATURE[0]) {
1118
67.1k
    int fixed = 0;
1119
67.1k
    if (strchr(mode, 'B') != NULL)
1120
0
      fixed = 1;
1121
67.1k
    else
1122
67.1k
      checkmode(L, mode, "binary");
1123
67.1k
    cl = luaU_undump(L, p->z, p->name, fixed);
1124
67.1k
  }
1125
8.67M
  else {
1126
8.67M
    checkmode(L, mode, "text");
1127
8.67M
    cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
1128
8.67M
  }
1129
8.74M
  lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1130
8.74M
  luaF_initupvals(L, cl);
1131
3.37M
}
1132
1133
1134
TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1135
8.74M
                                            const char *mode) {
1136
8.74M
  struct SParser p;
1137
8.74M
  TStatus status;
1138
8.74M
  incnny(L);  /* cannot yield during parsing */
1139
8.74M
  p.z = z; p.name = name; p.mode = mode;
1140
8.74M
  p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1141
8.74M
  p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1142
8.74M
  p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1143
8.74M
  luaZ_initbuffer(L, &p.buff);
1144
8.74M
  status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1145
8.74M
  luaZ_freebuffer(L, &p.buff);
1146
8.74M
  luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size));
1147
8.74M
  luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size));
1148
8.74M
  luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size));
1149
8.74M
  decnny(L);
1150
8.74M
  return status;
1151
8.74M
}
1152
1153