Coverage Report

Created: 2025-07-11 06:33

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