Coverage Report

Created: 2026-01-10 06:54

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