Coverage Report

Created: 2026-01-25 07:04

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