Coverage Report

Created: 2026-01-25 07:00

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