Coverage Report

Created: 2026-03-12 07:14

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
200k
#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
97.3k
#define luai_userstateresume(L,n) ((void)L)
47
#endif
48
49
#if !defined(luai_userstateyield)
50
5.88k
#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
1.93M
#define LUAI_THROW(L,c)   longjmp((c)->b, 1)
105
15.1M
#define LUAI_TRY(L,c,f,ud)  if (setjmp((c)->b) == 0) ((f)(L, ud))
106
107
#endif              /* } */
108
109
#endif              /* } */
110
111
112
1.99M
void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) {
113
1.99M
  if (errcode == LUA_ERRMEM) {  /* memory error? */
114
6.35k
    setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
115
6.35k
  }
116
1.98M
  else {
117
1.98M
    lua_assert(errorstatus(errcode));  /* must be a real error */
118
1.98M
    lua_assert(!ttisnil(s2v(L->top.p - 1)));  /* with a non-nil object */
119
3.97M
    setobjs2s(L, oldtop, L->top.p - 1);  /* move it to 'oldtop' */
120
1.98M
  }
121
1.99M
  L->top.p = oldtop + 1;  /* top goes back to old top plus error object */
122
1.99M
}
123
124
125
1.93M
l_noret luaD_throw (lua_State *L, TStatus errcode) {
126
1.93M
  if (L->errorJmp) {  /* thread has an error handler? */
127
1.93M
    L->errorJmp->status = errcode;  /* set status */
128
1.93M
    LUAI_THROW(L, L->errorJmp);  /* jump to it */
129
1.93M
  }
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
1.93M
}
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
15.1M
TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
161
15.1M
  l_uint32 oldnCcalls = L->nCcalls;
162
15.1M
  lua_longjmp lj;
163
15.1M
  lj.status = LUA_OK;
164
15.1M
  lj.previous = L->errorJmp;  /* chain new error handler */
165
15.1M
  L->errorJmp = &lj;
166
15.1M
  LUAI_TRY(L, &lj, f, ud);  /* call 'f' catching errors */
167
15.1M
  L->errorJmp = lj.previous;  /* restore old error handler */
168
15.1M
  L->nCcalls = oldnCcalls;
169
15.1M
  return lj.status;
170
15.1M
}
171
172
/* }====================================================== */
173
174
175
/*
176
** {==================================================================
177
** Stack reallocation
178
** ===================================================================
179
*/
180
181
/* some stack space for error handling */
182
344
#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
30.6M
#define MAXSTACK  cast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET  \
207
30.4M
              ? LUAI_MAXSTACK : MAXSTACK_BYSIZET)
208
209
210
/* stack size with extra space for error handling */
211
344
#define ERRORSTACKSIZE  (MAXSTACK + STACKERRSPACE)
212
213
214
/* raise a stack error while running the message handler */
215
78.8k
l_noret luaD_errerr (lua_State *L) {
216
78.8k
  TString *msg = luaS_newliteral(L, "error in error handling");
217
78.8k
  setsvalue2s(L, L->top.p, msg);
218
78.8k
  L->top.p++;  /* assume EXTRA_STACK */
219
78.8k
  luaD_throw(L, LUA_ERRERR);
220
78.8k
}
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
763k
int luaD_checkminstack (lua_State *L) {
229
763k
  if (getCcalls(L) >= LUAI_MAXCCALLS - 2)
230
4.91k
    return 0;  /* not enough C-stack slots */
231
758k
  if (L->ci->next == NULL && luaE_extendCI(L, 0) == NULL)
232
0
    return 0;  /* unable to allocate first ci */
233
758k
  if (L->ci->next->next == NULL && luaE_extendCI(L, 0) == NULL)
234
0
    return 0;  /* unable to allocate second ci */
235
758k
  if (L->stack_last.p - L->top.p >= BASIC_STACK_SIZE)
236
757k
    return 1;  /* enough (BASIC_STACK_SIZE) free slots in the Lua stack */
237
1.25k
  else  /* try to grow stack to a size with enough free slots */
238
1.25k
    return luaD_growstack(L, BASIC_STACK_SIZE, 0);
239
758k
}
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
189k
static void relstack (lua_State *L) {
261
189k
  CallInfo *ci;
262
189k
  UpVal *up;
263
189k
  L->top.offset = savestack(L, L->top.p);
264
189k
  L->tbclist.offset = savestack(L, L->tbclist.p);
265
538k
  for (up = L->openupval; up != NULL; up = up->u.open.next)
266
349k
    up->v.offset = savestack(L, uplevel(up));
267
48.7M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
268
48.5M
    ci->top.offset = savestack(L, ci->top.p);
269
48.5M
    ci->func.offset = savestack(L, ci->func.p);
270
48.5M
  }
271
189k
}
272
273
274
/*
275
** Change back all offsets into pointers.
276
*/
277
189k
static void correctstack (lua_State *L, StkId oldstack) {
278
189k
  CallInfo *ci;
279
189k
  UpVal *up;
280
189k
  UNUSED(oldstack);
281
189k
  L->top.p = restorestack(L, L->top.offset);
282
189k
  L->tbclist.p = restorestack(L, L->tbclist.offset);
283
538k
  for (up = L->openupval; up != NULL; up = up->u.open.next)
284
349k
    up->v.p = s2v(restorestack(L, up->v.offset));
285
48.7M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
286
48.5M
    ci->top.p = restorestack(L, ci->top.offset);
287
48.5M
    ci->func.p = restorestack(L, ci->func.offset);
288
48.5M
    if (isLua(ci))
289
45.9M
      ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */
290
48.5M
  }
291
189k
}
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
189k
int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
331
189k
  int oldsize = stacksize(L);
332
189k
  int i;
333
189k
  StkId newstack;
334
189k
  StkId oldstack = L->stack.p;
335
189k
  lu_byte oldgcstop = G(L)->gcstopem;
336
189k
  lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE);
337
189k
  relstack(L);  /* change pointers to offsets */
338
189k
  G(L)->gcstopem = 1;  /* stop emergency collection */
339
189k
  newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK,
340
189k
                                   newsize + EXTRA_STACK, StackValue);
341
189k
  G(L)->gcstopem = oldgcstop;  /* restore emergency collection */
342
189k
  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
189k
  L->stack.p = newstack;
349
189k
  correctstack(L, oldstack);  /* change offsets back to pointers */
350
189k
  L->stack_last.p = L->stack.p + newsize;
351
191M
  for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
352
190M
    setnilvalue(s2v(newstack + i)); /* erase new segment */
353
189k
  return 1;
354
189k
}
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
133k
int luaD_growstack (lua_State *L, int n, int raiseerror) {
362
133k
  int size = stacksize(L);
363
133k
  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
119
    lua_assert(stacksize(L) == ERRORSTACKSIZE);
368
119
    if (raiseerror)
369
119
      luaD_errerr(L);  /* stack error inside message handler */
370
0
    return 0;  /* if not 'raiseerror', just signal it */
371
119
  }
372
133k
  else if (n < MAXSTACK) {  /* avoids arithmetic overflows */
373
133k
    int newsize = size + (size >> 1);  /* tentative new size (size * 1.5) */
374
133k
    int needed = cast_int(L->top.p - L->stack.p) + n;
375
133k
    if (newsize > MAXSTACK)  /* cannot cross the limit */
376
524
      newsize = MAXSTACK;
377
133k
    if (newsize < needed)  /* but must respect what was asked for */
378
2.01k
      newsize = needed;
379
133k
    if (l_likely(newsize <= MAXSTACK))
380
132k
      return luaD_reallocstack(L, newsize, raiseerror);
381
133k
  }
382
  /* else stack overflow */
383
  /* add extra size to be able to handle the error message */
384
344
  luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
385
344
  if (raiseerror)
386
341
    luaG_runerror(L, "stack overflow");
387
3
  return 0;
388
344
}
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
10.1M
static int stackinuse (lua_State *L) {
396
10.1M
  CallInfo *ci;
397
10.1M
  int res;
398
10.1M
  StkId lim = L->top.p;
399
301M
  for (ci = L->ci; ci != NULL; ci = ci->previous) {
400
291M
    if (lim < ci->top.p) lim = ci->top.p;
401
291M
  }
402
10.1M
  lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
403
10.1M
  res = cast_int(lim - L->stack.p) + 1;  /* part of stack in use */
404
10.1M
  if (res < LUA_MINSTACK)
405
834
    res = LUA_MINSTACK;  /* ensure a minimum size */
406
10.1M
  return res;
407
10.1M
}
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
10.1M
void luaD_shrinkstack (lua_State *L) {
420
10.1M
  int inuse = stackinuse(L);
421
10.1M
  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
10.1M
  if (inuse <= MAXSTACK && stacksize(L) > max) {
425
17.8k
    int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2;
426
17.8k
    luaD_reallocstack(L, nsize, 0);  /* ok if that fails */
427
17.8k
  }
428
10.1M
  else  /* don't change stack */
429
10.1M
    condmovestack(L,(void)0,(void)0);  /* (change only for debugging) */
430
10.1M
  luaE_shrinkCI(L);  /* shrink CI list */
431
10.1M
}
432
433
434
6.37M
void luaD_inctop (lua_State *L) {
435
6.37M
  L->top.p++;
436
6.37M
  luaD_checkstack(L, 1);
437
6.37M
}
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
39.3M
                              int ftransfer, int ntransfer) {
449
39.3M
  lua_Hook hook = L->hook;
450
39.3M
  if (hook && L->allowhook) {  /* make sure there is a hook */
451
3.96M
    CallInfo *ci = L->ci;
452
3.96M
    ptrdiff_t top = savestack(L, L->top.p);  /* preserve original 'top' */
453
3.96M
    ptrdiff_t ci_top = savestack(L, ci->top.p);  /* idem for 'ci->top' */
454
3.96M
    lua_Debug ar;
455
3.96M
    ar.event = event;
456
3.96M
    ar.currentline = line;
457
3.96M
    ar.i_ci = ci;
458
3.96M
    L->transferinfo.ftransfer = ftransfer;
459
3.96M
    L->transferinfo.ntransfer = ntransfer;
460
3.96M
    if (isLua(ci) && L->top.p < ci->top.p)
461
67.1k
      L->top.p = ci->top.p;  /* protect entire activation register */
462
3.96M
    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
463
3.96M
    if (ci->top.p < L->top.p + LUA_MINSTACK)
464
3.64M
      ci->top.p = L->top.p + LUA_MINSTACK;
465
3.96M
    L->allowhook = 0;  /* cannot call hooks inside a hook */
466
3.96M
    ci->callstatus |= CIST_HOOKED;
467
3.96M
    lua_unlock(L);
468
3.96M
    (*hook)(L, &ar);
469
3.96M
    lua_lock(L);
470
3.96M
    lua_assert(!L->allowhook);
471
3.96M
    L->allowhook = 1;
472
3.96M
    ci->top.p = restorestack(L, ci_top);
473
3.96M
    L->top.p = restorestack(L, top);
474
3.96M
    ci->callstatus &= ~CIST_HOOKED;
475
3.96M
  }
476
39.3M
}
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.55M
void luaD_hookcall (lua_State *L, CallInfo *ci) {
485
3.55M
  L->oldpc = 0;  /* set 'oldpc' for new function */
486
3.55M
  if (L->hookmask & LUA_MASKCALL) {  /* is call hook on? */
487
1.61M
    int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
488
1.61M
                                             : LUA_HOOKCALL;
489
3.22M
    Proto *p = ci_func(ci)->p;
490
3.22M
    ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
491
3.22M
    luaD_hook(L, event, -1, 1, p->numparams);
492
3.22M
    ci->u.l.savedpc--;  /* correct 'pc' */
493
3.22M
  }
494
3.55M
}
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
6.70M
static void rethook (lua_State *L, CallInfo *ci, int nres) {
503
6.70M
  if (L->hookmask & LUA_MASKRET) {  /* is return hook on? */
504
4.69M
    StkId firstres = L->top.p - nres;  /* index of first result */
505
4.69M
    int delta = 0;  /* correction for vararg functions */
506
4.69M
    int ftransfer;
507
4.69M
    if (isLua(ci)) {
508
4.63M
      Proto *p = ci_func(ci)->p;
509
4.63M
      if (p->flag & PF_VAHID)
510
24.2k
        delta = ci->u.l.nextraargs + p->numparams + 1;
511
4.63M
    }
512
4.69M
    ci->func.p += delta;  /* if vararg, back to virtual 'func' */
513
4.69M
    ftransfer = cast_int(firstres - ci->func.p);
514
4.69M
    luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres);  /* call it */
515
4.69M
    ci->func.p -= delta;
516
4.69M
  }
517
6.70M
  if (isLua(ci = ci->previous))
518
5.84M
    L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p);  /* set 'oldpc' */
519
6.70M
}
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
2.10M
static unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) {
532
2.10M
  const TValue *tm;
533
2.10M
  StkId p;
534
2.10M
  tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
535
2.10M
  if (l_unlikely(ttisnil(tm)))  /* no metamethod? */
536
338k
    luaG_callerror(L, s2v(func));
537
5.15M
  for (p = L->top.p; p > func; p--)  /* open space for metamethod */
538
3.38M
    setobjs2s(L, p, p-1);
539
1.77M
  L->top.p++;  /* stack space pre-allocated by the caller */
540
1.77M
  setobj2s(L, func, tm);  /* metamethod is the new function to be called */
541
1.77M
  if ((status & MAX_CCMT) == MAX_CCMT)  /* is counter full? */
542
0
    luaG_runerror(L, "'__call' chain too long");
543
1.77M
  return status + (1u << CIST_CCMT);  /* increment counter */
544
1.77M
}
545
546
547
/* Generic case for 'moveresult' */
548
l_sinline void genmoveresults (lua_State *L, StkId res, int nres,
549
2.11M
                                             int wanted) {
550
2.11M
  StkId firstresult = L->top.p - nres;  /* index of first result */
551
2.11M
  int i;
552
2.11M
  if (nres > wanted)  /* extra results? */
553
71.2k
    nres = wanted;  /* don't need them */
554
4.15M
  for (i = 0; i < nres; i++)  /* move all results to correct place */
555
2.11M
    setobjs2s(L, res + i, firstresult + i);
556
4.04M
  for (; i < wanted; i++)  /* complete wanted number of results */
557
2.11M
    setnilvalue(s2v(res + i));
558
2.11M
  L->top.p = res + wanted;  /* top points after the last result */
559
2.11M
}
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
38.5M
                                          l_uint32 fwanted) {
571
38.5M
  switch (fwanted) {  /* handle typical cases separately */
572
12.2M
    case 0 + 1:  /* no values needed */
573
12.2M
      L->top.p = res;
574
12.2M
      return;
575
24.2M
    case 1 + 1:  /* one value needed */
576
24.2M
      if (nres == 0)   /* no results? */
577
24.2M
        setnilvalue(s2v(res));  /* adjust with nil */
578
23.5M
      else  /* at least one result */
579
24.2M
        setobjs2s(L, res, L->top.p - nres);  /* move it to proper place */
580
24.2M
      L->top.p = res + 1;
581
24.2M
      return;
582
490k
    case LUA_MULTRET + 1:
583
490k
      genmoveresults(L, res, nres, nres);  /* we want all results */
584
490k
      break;
585
1.62M
    default: {  /* two/more results and/or to-be-closed variables */
586
1.62M
      int wanted = get_nresults(fwanted);
587
1.62M
      if (fwanted & CIST_TBC) {  /* to-be-closed variables? */
588
288k
        L->ci->u2.nres = nres;
589
288k
        L->ci->callstatus |= CIST_CLSRET;  /* in case of yields */
590
288k
        res = luaF_close(L, res, CLOSEKTOP, 1);
591
288k
        L->ci->callstatus &= ~CIST_CLSRET;
592
288k
        if (L->hookmask) {  /* if needed, call hook after '__close's */
593
11.8k
          ptrdiff_t savedres = savestack(L, res);
594
11.8k
          rethook(L, L->ci, nres);
595
11.8k
          res = restorestack(L, savedres);  /* hook can move stack */
596
11.8k
        }
597
288k
        if (wanted == LUA_MULTRET)
598
7.92k
          wanted = nres;  /* we want all results */
599
288k
      }
600
1.62M
      genmoveresults(L, res, nres, wanted);
601
1.62M
      break;
602
24.2M
    }
603
38.5M
  }
604
38.5M
}
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
38.5M
void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
614
38.5M
  l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS);
615
38.5M
  if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC))
616
6.69M
    rethook(L, ci, nres);
617
  /* move results to proper place */
618
38.5M
  moveresults(L, ci->func.p, nres, fwanted);
619
  /* function cannot be in any of these cases when returning */
620
38.5M
  lua_assert(!(ci->callstatus &
621
38.5M
        (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET)));
622
38.5M
  L->ci = ci->previous;  /* back to caller (after closing variables) */
623
38.5M
}
624
625
626
627
64.8M
#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
64.8M
                                                StkId top) {
638
64.8M
  CallInfo *ci = L->ci = next_ci(L);  /* new frame */
639
64.8M
  ci->func.p = func;
640
64.8M
  lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0);
641
64.8M
  ci->callstatus = status;
642
64.8M
  ci->top.p = top;
643
64.8M
  return ci;
644
64.8M
}
645
646
647
/*
648
** precall for C functions
649
*/
650
l_sinline int precallC (lua_State *L, StkId func, unsigned status,
651
36.4M
                                            lua_CFunction f) {
652
36.4M
  int n;  /* number of returns */
653
36.4M
  CallInfo *ci;
654
36.4M
  checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
655
36.4M
  L->ci = ci = prepCallInfo(L, func, status | CIST_C,
656
36.4M
                               L->top.p + LUA_MINSTACK);
657
36.4M
  lua_assert(ci->top.p <= L->stack_last.p);
658
36.4M
  if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
659
1.87M
    int narg = cast_int(L->top.p - func) - 1;
660
1.87M
    luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
661
1.87M
  }
662
36.4M
  lua_unlock(L);
663
36.4M
  n = (*f)(L);  /* do the actual call */
664
36.4M
  lua_lock(L);
665
36.4M
  api_checknelems(L, n);
666
36.4M
  luaD_poscall(L, ci, n);
667
35.1M
  return n;
668
36.4M
}
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
5.24M
                                    int narg1, int delta) {
679
5.24M
  unsigned status = LUA_MULTRET + 1;
680
5.24M
 retry:
681
5.24M
  switch (ttypetag(s2v(func))) {
682
121
    case LUA_VCCL:  /* C closure */
683
121
      return precallC(L, func, status, clCvalue(s2v(func))->f);
684
4.74k
    case LUA_VLCF:  /* light C function */
685
4.74k
      return precallC(L, func, status, fvalue(s2v(func)));
686
5.23M
    case LUA_VLCL: {  /* Lua function */
687
10.4M
      Proto *p = clLvalue(s2v(func))->p;
688
10.4M
      int fsize = p->maxstacksize;  /* frame size */
689
10.4M
      int nfixparams = p->numparams;
690
10.4M
      int i;
691
10.4M
      checkstackp(L, fsize - delta, func);
692
10.4M
      ci->func.p -= delta;  /* restore 'func' (if vararg) */
693
16.0M
      for (i = 0; i < narg1; i++)  /* move down function and arguments */
694
10.8M
        setobjs2s(L, ci->func.p + i, func + i);
695
5.23M
      func = ci->func.p;  /* moved-down function */
696
8.09M
      for (; narg1 <= nfixparams; narg1++)
697
5.23M
        setnilvalue(s2v(func + narg1));  /* complete missing arguments */
698
5.23M
      ci->top.p = func + 1 + fsize;  /* top for new function */
699
5.23M
      lua_assert(ci->top.p <= L->stack_last.p);
700
5.23M
      ci->u.l.savedpc = p->code;  /* starting point */
701
5.23M
      ci->callstatus |= CIST_TAIL;
702
5.23M
      L->top.p = func + narg1;  /* set top */
703
5.23M
      return -1;
704
5.23M
    }
705
5.79k
    default: {  /* not a function */
706
5.79k
      checkstackp(L, 1, func);  /* space for metamethod */
707
5.79k
      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */
708
5.79k
      narg1++;
709
5.79k
      goto retry;  /* try again */
710
5.23M
    }
711
5.24M
  }
712
5.24M
}
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
65.1M
CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
724
65.1M
  unsigned status = cast_uint(nresults + 1);
725
65.1M
  lua_assert(status <= MAXRESULTS + 1);
726
66.9M
 retry:
727
66.9M
  switch (ttypetag(s2v(func))) {
728
1.11M
    case LUA_VCCL:  /* C closure */
729
1.11M
      precallC(L, func, status, clCvalue(s2v(func))->f);
730
1.11M
      return NULL;
731
35.3M
    case LUA_VLCF:  /* light C function */
732
35.3M
      precallC(L, func, status, fvalue(s2v(func)));
733
35.3M
      return NULL;
734
28.3M
    case LUA_VLCL: {  /* Lua function */
735
28.3M
      CallInfo *ci;
736
56.6M
      Proto *p = clLvalue(s2v(func))->p;
737
56.6M
      int narg = cast_int(L->top.p - func) - 1;  /* number of real arguments */
738
56.6M
      int nfixparams = p->numparams;
739
56.6M
      int fsize = p->maxstacksize;  /* frame size */
740
56.6M
      checkstackp(L, fsize, func);
741
56.6M
      L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize);
742
56.6M
      ci->u.l.savedpc = p->code;  /* starting point */
743
56.6M
      for (; narg < nfixparams; narg++)
744
28.3M
        setnilvalue(s2v(L->top.p++));  /* complete missing arguments */
745
56.6M
      lua_assert(ci->top.p <= L->stack_last.p);
746
56.6M
      return ci;
747
56.6M
    }
748
2.10M
    default: {  /* not a function */
749
2.10M
      checkstackp(L, 1, func);  /* space for metamethod */
750
2.10M
      status = tryfuncTM(L, func, status);  /* try '__call' metamethod */
751
2.10M
      goto retry;  /* try again with metamethod */
752
56.6M
    }
753
66.9M
  }
754
66.9M
}
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
20.1M
l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
766
20.1M
  CallInfo *ci;
767
20.1M
  L->nCcalls += inc;
768
20.1M
  if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
769
253k
    checkstackp(L, 0, func);  /* free any use of EXTRA_STACK */
770
253k
    luaE_checkcstack(L);
771
253k
  }
772
20.1M
  if ((ci = luaD_precall(L, func, nResults)) != NULL) {  /* Lua function? */
773
13.6M
    ci->callstatus |= CIST_FRESH;  /* mark that it is a "fresh" execute */
774
13.6M
    luaV_execute(L, ci);  /* call it */
775
13.6M
  }
776
20.1M
  L->nCcalls -= inc;
777
20.1M
}
778
779
780
/*
781
** External interface for 'ccall'
782
*/
783
12.6M
void luaD_call (lua_State *L, StkId func, int nResults) {
784
12.6M
  ccall(L, func, nResults, 1);
785
12.6M
}
786
787
788
/*
789
** Similar to 'luaD_call', but does not allow yields during the call.
790
*/
791
7.38M
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
792
7.38M
  ccall(L, func, nResults, nyci);
793
7.38M
}
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
2.96k
static TStatus finishpcallk (lua_State *L,  CallInfo *ci) {
813
2.96k
  TStatus status = getcistrecst(ci);  /* get original status */
814
2.96k
  if (l_likely(status == LUA_OK))  /* no error? */
815
10
    status = LUA_YIELD;  /* was interrupted by an yield */
816
2.95k
  else {  /* error */
817
2.95k
    StkId func = restorestack(L, ci->u2.funcidx);
818
2.95k
    L->allowhook = getoah(ci);  /* restore 'allowhook' */
819
2.95k
    func = luaF_close(L, func, status, 1);  /* can yield or raise an error */
820
2.95k
    luaD_seterrorobj(L, status, func);
821
2.95k
    luaD_shrinkstack(L);   /* restore stack size in case of overflow */
822
2.95k
    setcistrecst(ci, LUA_OK);  /* clear original status */
823
2.95k
  }
824
2.96k
  ci->callstatus &= ~CIST_YPCALL;
825
2.96k
  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
2.96k
  return status;
829
2.96k
}
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
2.96k
static void finishCcall (lua_State *L, CallInfo *ci) {
846
2.96k
  int n;  /* actual number of results from C function */
847
2.96k
  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
2.96k
  else {
853
2.96k
    TStatus status = LUA_YIELD;  /* default if there were no errors */
854
2.96k
    lua_KFunction kf = ci->u.c.k;  /* continuation function */
855
    /* must have a continuation and must be able to call it */
856
2.96k
    lua_assert(kf != NULL && yieldable(L));
857
2.96k
    if (ci->callstatus & CIST_YPCALL)   /* was inside a 'lua_pcallk'? */
858
2.96k
      status = finishpcallk(L, ci);  /* finish it */
859
2.96k
    adjustresults(L, LUA_MULTRET);  /* finish 'lua_callk' */
860
2.96k
    lua_unlock(L);
861
2.96k
    n = (*kf)(L, APIstatus(status), ci->u.c.ctx);  /* call continuation */
862
2.96k
    lua_lock(L);
863
2.96k
    api_checknelems(L, n);
864
2.96k
  }
865
2.96k
  luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
866
2.96k
}
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
5.06k
static void unroll (lua_State *L, void *ud) {
875
5.06k
  CallInfo *ci;
876
5.06k
  UNUSED(ud);
877
13.1k
  while ((ci = L->ci) != &L->base_ci) {  /* something in the stack */
878
8.04k
    if (!isLua(ci))  /* C function? */
879
2.96k
      finishCcall(L, ci);  /* complete its execution */
880
5.07k
    else {  /* Lua function */
881
5.07k
      luaV_finishOp(L);  /* finish interrupted instruction */
882
5.07k
      luaV_execute(L, ci);  /* execute down to higher C 'boundary' */
883
5.07k
    }
884
8.04k
  }
885
5.06k
}
886
887
888
/*
889
** Try to find a suspended protected call (a "recover point") for the
890
** given thread.
891
*/
892
50.5k
static CallInfo *findpcall (lua_State *L) {
893
50.5k
  CallInfo *ci;
894
650k
  for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
895
603k
    if (ci->callstatus & CIST_YPCALL)
896
2.95k
      return ci;
897
603k
  }
898
47.5k
  return NULL;  /* no pending pcall */
899
50.5k
}
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
8.83k
static int resume_error (lua_State *L, const char *msg, int narg) {
908
8.83k
  api_checkpop(L, narg);
909
8.83k
  L->top.p -= narg;  /* remove args from the stack */
910
8.83k
  setsvalue2s(L, L->top.p, luaS_new(L, msg));  /* push error message */
911
8.83k
  api_incr_top(L);
912
8.83k
  lua_unlock(L);
913
8.83k
  return LUA_ERRRUN;
914
8.83k
}
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
97.3k
static void resume (lua_State *L, void *ud) {
925
97.3k
  int n = *(cast(int*, ud));  /* number of arguments */
926
97.3k
  StkId firstArg = L->top.p - n;  /* first argument */
927
97.3k
  CallInfo *ci = L->ci;
928
97.3k
  if (L->status == LUA_OK)  /* starting a coroutine? */
929
95.2k
    ccall(L, firstArg - 1, LUA_MULTRET, 0);  /* just call its body */
930
2.10k
  else {  /* resuming from previous yield */
931
2.10k
    lua_assert(L->status == LUA_YIELD);
932
2.10k
    L->status = LUA_OK;  /* mark that it is running (again) */
933
2.10k
    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
2.10k
    else {  /* 'common' yield */
942
2.10k
      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
2.10k
      luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
949
2.10k
    }
950
2.10k
    unroll(L, NULL);  /* run continuation */
951
2.10k
  }
952
97.3k
}
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
97.3k
static TStatus precover (lua_State *L, TStatus status) {
964
97.3k
  CallInfo *ci;
965
100k
  while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
966
2.95k
    L->ci = ci;  /* go down to recovery functions */
967
2.95k
    setcistrecst(ci, status);  /* status to finish 'pcall' */
968
2.95k
    status = luaD_rawrunprotected(L, unroll, NULL);
969
2.95k
  }
970
97.3k
  return status;
971
97.3k
}
972
973
974
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
975
106k
                                      int *nresults) {
976
106k
  TStatus status;
977
106k
  lua_lock(L);
978
106k
  if (L->status == LUA_OK) {  /* may be starting a coroutine */
979
99.2k
    if (L->ci != &L->base_ci)  /* not in base level? */
980
1.29k
      return resume_error(L, "cannot resume non-suspended coroutine", nargs);
981
97.9k
    else if (L->top.p - (L->ci->func.p + 1) == nargs)  /* no function? */
982
1.34k
      return resume_error(L, "cannot resume dead coroutine", nargs);
983
99.2k
  }
984
6.87k
  else if (L->status != LUA_YIELD)  /* ended with errors? */
985
4.77k
    return resume_error(L, "cannot resume dead coroutine", nargs);
986
98.7k
  L->nCcalls = (from) ? getCcalls(from) : 0;
987
98.7k
  if (getCcalls(L) >= LUAI_MAXCCALLS)
988
1.42k
    return resume_error(L, "C stack overflow", nargs);
989
97.3k
  L->nCcalls++;
990
97.3k
  luai_userstateresume(L, nargs);
991
97.3k
  api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
992
97.3k
  status = luaD_rawrunprotected(L, resume, &nargs);
993
   /* continue running after recoverable errors */
994
97.3k
  status = precover(L, status);
995
97.3k
  if (l_likely(!errorstatus(status)))
996
97.3k
    lua_assert(status == L->status);  /* normal end or yield */
997
47.5k
  else {  /* unrecoverable error */
998
47.5k
    L->status = status;  /* mark thread as 'dead' */
999
47.5k
    luaD_seterrorobj(L, status, L->top.p);  /* push error message */
1000
47.5k
    L->ci->top.p = L->top.p;
1001
47.5k
  }
1002
97.3k
  *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
1003
97.3k
                                    : cast_int(L->top.p - (L->ci->func.p + 1));
1004
97.3k
  lua_unlock(L);
1005
97.3k
  return APIstatus(status);
1006
97.3k
}
1007
1008
1009
1
LUA_API int lua_isyieldable (lua_State *L) {
1010
1
  return yieldable(L);
1011
1
}
1012
1013
1014
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
1015
5.88k
                        lua_KFunction k) {
1016
5.88k
  CallInfo *ci;
1017
5.88k
  luai_userstateyield(L, nresults);
1018
5.88k
  lua_lock(L);
1019
5.88k
  ci = L->ci;
1020
5.88k
  api_checkpop(L, nresults);
1021
5.88k
  if (l_unlikely(!yieldable(L))) {
1022
1.17k
    if (L != mainthread(G(L)))
1023
65
      luaG_runerror(L, "attempt to yield across a C-call boundary");
1024
1.10k
    else
1025
1.10k
      luaG_runerror(L, "attempt to yield from outside a coroutine");
1026
1.17k
  }
1027
4.71k
  L->status = LUA_YIELD;
1028
4.71k
  ci->u2.nyield = nresults;  /* save number of results */
1029
4.71k
  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
4.71k
  else {
1035
4.71k
    if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
1036
0
      ci->u.c.ctx = ctx;  /* save context */
1037
4.71k
    luaD_throw(L, LUA_YIELD);
1038
4.71k
  }
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
1.95M
static void closepaux (lua_State *L, void *ud) {
1058
1.95M
  struct CloseP *pcl = cast(struct CloseP *, ud);
1059
1.95M
  luaF_close(L, pcl->level, pcl->status, 0);
1060
1.95M
}
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
1.95M
TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) {
1068
1.95M
  CallInfo *old_ci = L->ci;
1069
1.95M
  lu_byte old_allowhooks = L->allowhook;
1070
1.95M
  for (;;) {  /* keep closing upvalues until no more errors */
1071
1.95M
    struct CloseP pcl;
1072
1.95M
    pcl.level = restorestack(L, level); pcl.status = status;
1073
1.95M
    status = luaD_rawrunprotected(L, &closepaux, &pcl);
1074
1.95M
    if (l_likely(status == LUA_OK))  /* no more errors? */
1075
1.95M
      return pcl.status;
1076
1
    else {  /* an error occurred; restore saved state and repeat */
1077
1
      L->ci = old_ci;
1078
1
      L->allowhook = old_allowhooks;
1079
1
    }
1080
1.95M
  }
1081
1.95M
}
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
3.52M
                                  ptrdiff_t ef) {
1091
3.52M
  TStatus status;
1092
3.52M
  CallInfo *old_ci = L->ci;
1093
3.52M
  lu_byte old_allowhooks = L->allowhook;
1094
3.52M
  ptrdiff_t old_errfunc = L->errfunc;
1095
3.52M
  L->errfunc = ef;
1096
3.52M
  status = luaD_rawrunprotected(L, func, u);
1097
3.52M
  if (l_unlikely(status != LUA_OK)) {  /* an error occurred? */
1098
1.87M
    L->ci = old_ci;
1099
1.87M
    L->allowhook = old_allowhooks;
1100
1.87M
    status = luaD_closeprotected(L, old_top, status);
1101
1.87M
    luaD_seterrorobj(L, status, restorestack(L, old_top));
1102
1.87M
    luaD_shrinkstack(L);   /* restore stack size in case of overflow */
1103
1.87M
  }
1104
3.52M
  L->errfunc = old_errfunc;
1105
3.52M
  return status;
1106
3.52M
}
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
1.78M
static void checkmode (lua_State *L, const char *mode, const char *x) {
1123
1.78M
  if (strchr(mode, x[0]) == NULL) {
1124
994
    luaO_pushfstring(L,
1125
994
       "attempt to load a %s chunk (mode is '%s')", x, mode);
1126
994
    luaD_throw(L, LUA_ERRSYNTAX);
1127
994
  }
1128
1.78M
}
1129
1130
1131
2.31M
static void f_parser (lua_State *L, void *ud) {
1132
2.31M
  LClosure *cl;
1133
2.31M
  struct SParser *p = cast(struct SParser *, ud);
1134
2.31M
  const char *mode = p->mode ? p->mode : "bt";
1135
2.31M
  int c = zgetc(p->z);  /* read first character */
1136
2.31M
  if (c == LUA_SIGNATURE[0]) {
1137
57.7k
    int fixed = 0;
1138
57.7k
    if (strchr(mode, 'B') != NULL)
1139
0
      fixed = 1;
1140
57.7k
    else
1141
57.7k
      checkmode(L, mode, "binary");
1142
57.7k
    cl = luaU_undump(L, p->z, p->name, fixed);
1143
57.7k
  }
1144
2.25M
  else {
1145
2.25M
    checkmode(L, mode, "text");
1146
2.25M
    cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
1147
2.25M
  }
1148
2.31M
  lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1149
2.31M
  luaF_initupvals(L, cl);
1150
519k
}
1151
1152
1153
TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1154
2.31M
                                            const char *mode) {
1155
2.31M
  struct SParser p;
1156
2.31M
  TStatus status;
1157
2.31M
  incnny(L);  /* cannot yield during parsing */
1158
2.31M
  p.z = z; p.name = name; p.mode = mode;
1159
2.31M
  p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1160
2.31M
  p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1161
2.31M
  p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1162
2.31M
  luaZ_initbuffer(L, &p.buff);
1163
2.31M
  status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1164
2.31M
  luaZ_freebuffer(L, &p.buff);
1165
2.31M
  luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size));
1166
2.31M
  luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size));
1167
2.31M
  luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size));
1168
2.31M
  decnny(L);
1169
2.31M
  return status;
1170
2.31M
}
1171
1172