Coverage Report

Created: 2025-07-18 06:59

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