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