Coverage Report

Created: 2023-09-15 06:20

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