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