xref: /freebsd/contrib/lua/src/ldo.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
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 #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 #define LUAI_THROW(L,c)		longjmp((c)->b, 1)
74 #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 void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
92   switch (errcode) {
93     case LUA_ERRMEM: {  /* memory error? */
94       setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
95       break;
96     }
97     case LUA_ERRERR: {
98       setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
99       break;
100     }
101     case CLOSEPROTECT: {
102       setnilvalue(s2v(oldtop));  /* no error message */
103       break;
104     }
105     default: {
106       setobjs2s(L, oldtop, L->top - 1);  /* error message on current top */
107       break;
108     }
109   }
110   L->top = oldtop + 1;
111 }
112 
113 
114 l_noret luaD_throw (lua_State *L, int errcode) {
115   if (L->errorJmp) {  /* thread has an error handler? */
116     L->errorJmp->status = errcode;  /* set status */
117     LUAI_THROW(L, L->errorJmp);  /* jump to it */
118   }
119   else {  /* thread has no error handler */
120     global_State *g = G(L);
121     errcode = luaF_close(L, L->stack, errcode);  /* close all upvalues */
122     L->status = cast_byte(errcode);  /* mark it as dead */
123     if (g->mainthread->errorJmp) {  /* main thread has a handler? */
124       setobjs2s(L, g->mainthread->top++, L->top - 1);  /* copy error obj. */
125       luaD_throw(g->mainthread, errcode);  /* re-throw in main thread */
126     }
127     else {  /* no handler at all; abort */
128       if (g->panic) {  /* panic function? */
129         luaD_seterrorobj(L, errcode, L->top);  /* assume EXTRA_STACK */
130         if (L->ci->top < L->top)
131           L->ci->top = L->top;  /* pushing msg. can break this invariant */
132         lua_unlock(L);
133         g->panic(L);  /* call panic function (last chance to jump out) */
134       }
135       abort();
136     }
137   }
138 }
139 
140 
141 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
142   l_uint32 oldnCcalls = L->nCcalls;
143   struct lua_longjmp lj;
144   lj.status = LUA_OK;
145   lj.previous = L->errorJmp;  /* chain new error handler */
146   L->errorJmp = &lj;
147   LUAI_TRY(L, &lj,
148     (*f)(L, ud);
149   );
150   L->errorJmp = lj.previous;  /* restore old error handler */
151   L->nCcalls = oldnCcalls;
152   return lj.status;
153 }
154 
155 /* }====================================================== */
156 
157 
158 /*
159 ** {==================================================================
160 ** Stack reallocation
161 ** ===================================================================
162 */
163 static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
164   CallInfo *ci;
165   UpVal *up;
166   if (oldstack == newstack)
167     return;  /* stack address did not change */
168   L->top = (L->top - 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 int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
185   int lim = stacksize(L);
186   StkId newstack = luaM_reallocvector(L, L->stack,
187                       lim + EXTRA_STACK, newsize + EXTRA_STACK, StackValue);
188   lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
189   if (unlikely(newstack == NULL)) {  /* reallocation failed? */
190     if (raiseerror)
191       luaM_error(L);
192     else return 0;  /* do not raise an error */
193   }
194   for (; lim < newsize; lim++)
195     setnilvalue(s2v(newstack + lim + EXTRA_STACK)); /* erase new segment */
196   correctstack(L, L->stack, newstack);
197   L->stack = newstack;
198   L->stack_last = L->stack + newsize;
199   return 1;
200 }
201 
202 
203 /*
204 ** Try to grow the stack by at least 'n' elements. when 'raiseerror'
205 ** is true, raises any error; otherwise, return 0 in case of errors.
206 */
207 int luaD_growstack (lua_State *L, int n, int raiseerror) {
208   int size = stacksize(L);
209   if (unlikely(size > LUAI_MAXSTACK)) {
210     /* if stack is larger than maximum, thread is already using the
211        extra space reserved for errors, that is, thread is handling
212        a stack error; cannot grow further than that. */
213     lua_assert(stacksize(L) == ERRORSTACKSIZE);
214     if (raiseerror)
215       luaD_throw(L, LUA_ERRERR);  /* error inside message handler */
216     return 0;  /* if not 'raiseerror', just signal it */
217   }
218   else {
219     int newsize = 2 * size;  /* tentative new size */
220     int needed = cast_int(L->top - L->stack) + n;
221     if (newsize > LUAI_MAXSTACK)  /* cannot cross the limit */
222       newsize = LUAI_MAXSTACK;
223     if (newsize < needed)  /* but must respect what was asked for */
224       newsize = needed;
225     if (likely(newsize <= LUAI_MAXSTACK))
226       return luaD_reallocstack(L, newsize, raiseerror);
227     else {  /* stack overflow */
228       /* add extra size to be able to handle the error message */
229       luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
230       if (raiseerror)
231         luaG_runerror(L, "stack overflow");
232       return 0;
233     }
234   }
235 }
236 
237 
238 static int stackinuse (lua_State *L) {
239   CallInfo *ci;
240   int res;
241   StkId lim = L->top;
242   for (ci = L->ci; ci != NULL; ci = ci->previous) {
243     if (lim < ci->top) lim = ci->top;
244   }
245   lua_assert(lim <= L->stack_last);
246   res = cast_int(lim - L->stack) + 1;  /* part of stack in use */
247   if (res < LUA_MINSTACK)
248     res = LUA_MINSTACK;  /* ensure a minimum size */
249   return res;
250 }
251 
252 
253 /*
254 ** If stack size is more than 3 times the current use, reduce that size
255 ** to twice the current use. (So, the final stack size is at most 2/3 the
256 ** previous size, and half of its entries are empty.)
257 ** As a particular case, if stack was handling a stack overflow and now
258 ** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
259 ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
260 ** will be reduced to a "regular" size.
261 */
262 void luaD_shrinkstack (lua_State *L) {
263   int inuse = stackinuse(L);
264   int nsize = inuse * 2;  /* proposed new size */
265   int max = inuse * 3;  /* maximum "reasonable" size */
266   if (max > LUAI_MAXSTACK) {
267     max = LUAI_MAXSTACK;  /* respect stack limit */
268     if (nsize > LUAI_MAXSTACK)
269       nsize = LUAI_MAXSTACK;
270   }
271   /* if thread is currently not handling a stack overflow and its
272      size is larger than maximum "reasonable" size, shrink it */
273   if (inuse <= LUAI_MAXSTACK && stacksize(L) > max)
274     luaD_reallocstack(L, nsize, 0);  /* ok if that fails */
275   else  /* don't change stack */
276     condmovestack(L,{},{});  /* (change only for debugging) */
277   luaE_shrinkCI(L);  /* shrink CI list */
278 }
279 
280 
281 void luaD_inctop (lua_State *L) {
282   luaD_checkstack(L, 1);
283   L->top++;
284 }
285 
286 /* }================================================================== */
287 
288 
289 /*
290 ** Call a hook for the given event. Make sure there is a hook to be
291 ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
292 ** function, can be changed asynchronously by signals.)
293 */
294 void luaD_hook (lua_State *L, int event, int line,
295                               int ftransfer, int ntransfer) {
296   lua_Hook hook = L->hook;
297   if (hook && L->allowhook) {  /* make sure there is a hook */
298     int mask = CIST_HOOKED;
299     CallInfo *ci = L->ci;
300     ptrdiff_t top = savestack(L, L->top);
301     ptrdiff_t ci_top = savestack(L, ci->top);
302     lua_Debug ar;
303     ar.event = event;
304     ar.currentline = line;
305     ar.i_ci = ci;
306     if (ntransfer != 0) {
307       mask |= CIST_TRAN;  /* 'ci' has transfer information */
308       ci->u2.transferinfo.ftransfer = ftransfer;
309       ci->u2.transferinfo.ntransfer = ntransfer;
310     }
311     luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
312     if (L->top + LUA_MINSTACK > ci->top)
313       ci->top = L->top + LUA_MINSTACK;
314     L->allowhook = 0;  /* cannot call hooks inside a hook */
315     ci->callstatus |= mask;
316     lua_unlock(L);
317     (*hook)(L, &ar);
318     lua_lock(L);
319     lua_assert(!L->allowhook);
320     L->allowhook = 1;
321     ci->top = restorestack(L, ci_top);
322     L->top = restorestack(L, top);
323     ci->callstatus &= ~mask;
324   }
325 }
326 
327 
328 /*
329 ** Executes a call hook for Lua functions. This function is called
330 ** whenever 'hookmask' is not zero, so it checks whether call hooks are
331 ** active.
332 */
333 void luaD_hookcall (lua_State *L, CallInfo *ci) {
334   int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL;
335   Proto *p;
336   if (!(L->hookmask & LUA_MASKCALL))  /* some other hook? */
337     return;  /* don't call hook */
338   p = clLvalue(s2v(ci->func))->p;
339   L->top = ci->top;  /* prepare top */
340   ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
341   luaD_hook(L, hook, -1, 1, p->numparams);
342   ci->u.l.savedpc--;  /* correct 'pc' */
343 }
344 
345 
346 static StkId rethook (lua_State *L, CallInfo *ci, StkId firstres, int nres) {
347   ptrdiff_t oldtop = savestack(L, L->top);  /* hook may change top */
348   int delta = 0;
349   if (isLuacode(ci)) {
350     Proto *p = ci_func(ci)->p;
351     if (p->is_vararg)
352       delta = ci->u.l.nextraargs + p->numparams + 1;
353     if (L->top < ci->top)
354       L->top = ci->top;  /* correct top to run hook */
355   }
356   if (L->hookmask & LUA_MASKRET) {  /* is return hook on? */
357     int ftransfer;
358     ci->func += delta;  /* if vararg, back to virtual 'func' */
359     ftransfer = cast(unsigned short, firstres - ci->func);
360     luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres);  /* call it */
361     ci->func -= delta;
362   }
363   if (isLua(ci = ci->previous))
364     L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p);  /* update 'oldpc' */
365   return restorestack(L, oldtop);
366 }
367 
368 
369 /*
370 ** Check whether 'func' has a '__call' metafield. If so, put it in the
371 ** stack, below original 'func', so that 'luaD_precall' can call it. Raise
372 ** an error if there is no '__call' metafield.
373 */
374 void luaD_tryfuncTM (lua_State *L, StkId func) {
375   const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
376   StkId p;
377   if (unlikely(ttisnil(tm)))
378     luaG_typeerror(L, s2v(func), "call");  /* nothing to call */
379   for (p = L->top; p > func; p--)  /* open space for metamethod */
380     setobjs2s(L, p, p-1);
381   L->top++;  /* stack space pre-allocated by the caller */
382   setobj2s(L, func, tm);  /* metamethod is the new function to be called */
383 }
384 
385 
386 /*
387 ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
388 ** Handle most typical cases (zero results for commands, one result for
389 ** expressions, multiple results for tail calls/single parameters)
390 ** separated.
391 */
392 static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
393   StkId firstresult;
394   int i;
395   switch (wanted) {  /* handle typical cases separately */
396     case 0:  /* no values needed */
397       L->top = res;
398       return;
399     case 1:  /* one value needed */
400       if (nres == 0)   /* no results? */
401         setnilvalue(s2v(res));  /* adjust with nil */
402       else
403         setobjs2s(L, res, L->top - nres);  /* move it to proper place */
404       L->top = res + 1;
405       return;
406     case LUA_MULTRET:
407       wanted = nres;  /* we want all results */
408       break;
409     default:  /* multiple results (or to-be-closed variables) */
410       if (hastocloseCfunc(wanted)) {  /* to-be-closed variables? */
411         ptrdiff_t savedres = savestack(L, res);
412         luaF_close(L, res, LUA_OK);  /* may change the stack */
413         res = restorestack(L, savedres);
414         wanted = codeNresults(wanted);  /* correct value */
415         if (wanted == LUA_MULTRET)
416           wanted = nres;
417       }
418       break;
419   }
420   firstresult = L->top - nres;  /* index of first result */
421   /* move all results to correct place */
422   for (i = 0; i < nres && i < wanted; i++)
423     setobjs2s(L, res + i, firstresult + i);
424   for (; i < wanted; i++)  /* complete wanted number of results */
425     setnilvalue(s2v(res + i));
426   L->top = res + wanted;  /* top points after the last result */
427 }
428 
429 
430 /*
431 ** Finishes a function call: calls hook if necessary, removes CallInfo,
432 ** moves current number of results to proper place.
433 */
434 void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
435   if (L->hookmask)
436     L->top = rethook(L, ci, L->top - nres, nres);
437   L->ci = ci->previous;  /* back to caller */
438   /* move results to proper place */
439   moveresults(L, ci->func, nres, ci->nresults);
440 }
441 
442 
443 
444 #define next_ci(L)  (L->ci->next ? L->ci->next : luaE_extendCI(L))
445 
446 
447 /*
448 ** Prepare a function for a tail call, building its call info on top
449 ** of the current call info. 'narg1' is the number of arguments plus 1
450 ** (so that it includes the function itself).
451 */
452 void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
453   Proto *p = clLvalue(s2v(func))->p;
454   int fsize = p->maxstacksize;  /* frame size */
455   int nfixparams = p->numparams;
456   int i;
457   for (i = 0; i < narg1; i++)  /* move down function and arguments */
458     setobjs2s(L, ci->func + i, func + i);
459   checkstackGC(L, fsize);
460   func = ci->func;  /* moved-down function */
461   for (; narg1 <= nfixparams; narg1++)
462     setnilvalue(s2v(func + narg1));  /* complete missing arguments */
463   ci->top = func + 1 + fsize;  /* top for new function */
464   lua_assert(ci->top <= L->stack_last);
465   ci->u.l.savedpc = p->code;  /* starting point */
466   ci->callstatus |= CIST_TAIL;
467   L->top = func + narg1;  /* set top */
468 }
469 
470 
471 /*
472 ** Prepares the call to a function (C or Lua). For C functions, also do
473 ** the call. The function to be called is at '*func'.  The arguments
474 ** are on the stack, right after the function.  Returns the CallInfo
475 ** to be executed, if it was a Lua function. Otherwise (a C function)
476 ** returns NULL, with all the results on the stack, starting at the
477 ** original function position.
478 */
479 CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
480   lua_CFunction f;
481  retry:
482   switch (ttypetag(s2v(func))) {
483     case LUA_VCCL:  /* C closure */
484       f = clCvalue(s2v(func))->f;
485       goto Cfunc;
486     case LUA_VLCF:  /* light C function */
487       f = fvalue(s2v(func));
488      Cfunc: {
489       int n;  /* number of returns */
490       CallInfo *ci;
491       checkstackGCp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
492       L->ci = ci = next_ci(L);
493       ci->nresults = nresults;
494       ci->callstatus = CIST_C;
495       ci->top = L->top + LUA_MINSTACK;
496       ci->func = func;
497       lua_assert(ci->top <= L->stack_last);
498       if (L->hookmask & LUA_MASKCALL) {
499         int narg = cast_int(L->top - func) - 1;
500         luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
501       }
502       lua_unlock(L);
503       n = (*f)(L);  /* do the actual call */
504       lua_lock(L);
505       api_checknelems(L, n);
506       luaD_poscall(L, ci, n);
507       return NULL;
508     }
509     case LUA_VLCL: {  /* Lua function */
510       CallInfo *ci;
511       Proto *p = clLvalue(s2v(func))->p;
512       int narg = cast_int(L->top - func) - 1;  /* number of real arguments */
513       int nfixparams = p->numparams;
514       int fsize = p->maxstacksize;  /* frame size */
515       checkstackGCp(L, fsize, func);
516       L->ci = ci = next_ci(L);
517       ci->nresults = nresults;
518       ci->u.l.savedpc = p->code;  /* starting point */
519       ci->top = func + 1 + fsize;
520       ci->func = func;
521       L->ci = ci;
522       for (; narg < nfixparams; narg++)
523         setnilvalue(s2v(L->top++));  /* complete missing arguments */
524       lua_assert(ci->top <= L->stack_last);
525       return ci;
526     }
527     default: {  /* not a function */
528       checkstackGCp(L, 1, func);  /* space for metamethod */
529       luaD_tryfuncTM(L, func);  /* try to get '__call' metamethod */
530       goto retry;  /* try again with metamethod */
531     }
532   }
533 }
534 
535 
536 /*
537 ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
538 ** number of recursive invocations in the C stack) or nyci (the same
539 ** plus increment number of non-yieldable calls).
540 */
541 static void ccall (lua_State *L, StkId func, int nResults, int inc) {
542   CallInfo *ci;
543   L->nCcalls += inc;
544   if (unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
545     luaE_checkcstack(L);
546   if ((ci = luaD_precall(L, func, nResults)) != NULL) {  /* Lua function? */
547     ci->callstatus = CIST_FRESH;  /* mark that it is a "fresh" execute */
548     luaV_execute(L, ci);  /* call it */
549   }
550   L->nCcalls -= inc;
551 }
552 
553 
554 /*
555 ** External interface for 'ccall'
556 */
557 void luaD_call (lua_State *L, StkId func, int nResults) {
558   ccall(L, func, nResults, 1);
559 }
560 
561 
562 /*
563 ** Similar to 'luaD_call', but does not allow yields during the call.
564 */
565 void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
566   ccall(L, func, nResults, nyci);
567 }
568 
569 
570 /*
571 ** Completes the execution of an interrupted C function, calling its
572 ** continuation function.
573 */
574 static void finishCcall (lua_State *L, int status) {
575   CallInfo *ci = L->ci;
576   int n;
577   /* must have a continuation and must be able to call it */
578   lua_assert(ci->u.c.k != NULL && yieldable(L));
579   /* error status can only happen in a protected call */
580   lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
581   if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */
582     ci->callstatus &= ~CIST_YPCALL;  /* continuation is also inside it */
583     L->errfunc = ci->u.c.old_errfunc;  /* with the same error function */
584   }
585   /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
586      handled */
587   adjustresults(L, ci->nresults);
588   lua_unlock(L);
589   n = (*ci->u.c.k)(L, status, ci->u.c.ctx);  /* call continuation function */
590   lua_lock(L);
591   api_checknelems(L, n);
592   luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
593 }
594 
595 
596 /*
597 ** Executes "full continuation" (everything in the stack) of a
598 ** previously interrupted coroutine until the stack is empty (or another
599 ** interruption long-jumps out of the loop). If the coroutine is
600 ** recovering from an error, 'ud' points to the error status, which must
601 ** be passed to the first continuation function (otherwise the default
602 ** status is LUA_YIELD).
603 */
604 static void unroll (lua_State *L, void *ud) {
605   CallInfo *ci;
606   if (ud != NULL)  /* error status? */
607     finishCcall(L, *(int *)ud);  /* finish 'lua_pcallk' callee */
608   while ((ci = L->ci) != &L->base_ci) {  /* something in the stack */
609     if (!isLua(ci))  /* C function? */
610       finishCcall(L, LUA_YIELD);  /* complete its execution */
611     else {  /* Lua function */
612       luaV_finishOp(L);  /* finish interrupted instruction */
613       luaV_execute(L, ci);  /* execute down to higher C 'boundary' */
614     }
615   }
616 }
617 
618 
619 /*
620 ** Try to find a suspended protected call (a "recover point") for the
621 ** given thread.
622 */
623 static CallInfo *findpcall (lua_State *L) {
624   CallInfo *ci;
625   for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
626     if (ci->callstatus & CIST_YPCALL)
627       return ci;
628   }
629   return NULL;  /* no pending pcall */
630 }
631 
632 
633 /*
634 ** Recovers from an error in a coroutine. Finds a recover point (if
635 ** there is one) and completes the execution of the interrupted
636 ** 'luaD_pcall'. If there is no recover point, returns zero.
637 */
638 static int recover (lua_State *L, int status) {
639   StkId oldtop;
640   CallInfo *ci = findpcall(L);
641   if (ci == NULL) return 0;  /* no recovery point */
642   /* "finish" luaD_pcall */
643   oldtop = restorestack(L, ci->u2.funcidx);
644   L->ci = ci;
645   L->allowhook = getoah(ci->callstatus);  /* restore original 'allowhook' */
646   status = luaF_close(L, oldtop, status);  /* may change the stack */
647   oldtop = restorestack(L, ci->u2.funcidx);
648   luaD_seterrorobj(L, status, oldtop);
649   luaD_shrinkstack(L);   /* restore stack size in case of overflow */
650   L->errfunc = ci->u.c.old_errfunc;
651   return 1;  /* continue running the coroutine */
652 }
653 
654 
655 /*
656 ** Signal an error in the call to 'lua_resume', not in the execution
657 ** of the coroutine itself. (Such errors should not be handled by any
658 ** coroutine error handler and should not kill the coroutine.)
659 */
660 static int resume_error (lua_State *L, const char *msg, int narg) {
661   L->top -= narg;  /* remove args from the stack */
662   setsvalue2s(L, L->top, luaS_new(L, msg));  /* push error message */
663   api_incr_top(L);
664   lua_unlock(L);
665   return LUA_ERRRUN;
666 }
667 
668 
669 /*
670 ** Do the work for 'lua_resume' in protected mode. Most of the work
671 ** depends on the status of the coroutine: initial state, suspended
672 ** inside a hook, or regularly suspended (optionally with a continuation
673 ** function), plus erroneous cases: non-suspended coroutine or dead
674 ** coroutine.
675 */
676 static void resume (lua_State *L, void *ud) {
677   int n = *(cast(int*, ud));  /* number of arguments */
678   StkId firstArg = L->top - n;  /* first argument */
679   CallInfo *ci = L->ci;
680   if (L->status == LUA_OK)  /* starting a coroutine? */
681     ccall(L, firstArg - 1, LUA_MULTRET, 1);  /* just call its body */
682   else {  /* resuming from previous yield */
683     lua_assert(L->status == LUA_YIELD);
684     L->status = LUA_OK;  /* mark that it is running (again) */
685     luaE_incCstack(L);  /* control the C stack */
686     if (isLua(ci))  /* yielded inside a hook? */
687       luaV_execute(L, ci);  /* just continue running Lua code */
688     else {  /* 'common' yield */
689       if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
690         lua_unlock(L);
691         n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
692         lua_lock(L);
693         api_checknelems(L, n);
694       }
695       luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
696     }
697     unroll(L, NULL);  /* run continuation */
698   }
699 }
700 
701 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
702                                       int *nresults) {
703   int status;
704   lua_lock(L);
705   if (L->status == LUA_OK) {  /* may be starting a coroutine */
706     if (L->ci != &L->base_ci)  /* not in base level? */
707       return resume_error(L, "cannot resume non-suspended coroutine", nargs);
708     else if (L->top - (L->ci->func + 1) == nargs)  /* no function? */
709       return resume_error(L, "cannot resume dead coroutine", nargs);
710   }
711   else if (L->status != LUA_YIELD)  /* ended with errors? */
712     return resume_error(L, "cannot resume dead coroutine", nargs);
713   L->nCcalls = (from) ? getCcalls(from) : 0;
714   luai_userstateresume(L, nargs);
715   api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
716   status = luaD_rawrunprotected(L, resume, &nargs);
717    /* continue running after recoverable errors */
718   while (errorstatus(status) && recover(L, status)) {
719     /* unroll continuation */
720     status = luaD_rawrunprotected(L, unroll, &status);
721   }
722   if (likely(!errorstatus(status)))
723     lua_assert(status == L->status);  /* normal end or yield */
724   else {  /* unrecoverable error */
725     L->status = cast_byte(status);  /* mark thread as 'dead' */
726     luaD_seterrorobj(L, status, L->top);  /* push error message */
727     L->ci->top = L->top;
728   }
729   *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
730                                     : cast_int(L->top - (L->ci->func + 1));
731   lua_unlock(L);
732   return status;
733 }
734 
735 
736 LUA_API int lua_isyieldable (lua_State *L) {
737   return yieldable(L);
738 }
739 
740 
741 LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
742                         lua_KFunction k) {
743   CallInfo *ci;
744   luai_userstateyield(L, nresults);
745   lua_lock(L);
746   ci = L->ci;
747   api_checknelems(L, nresults);
748   if (unlikely(!yieldable(L))) {
749     if (L != G(L)->mainthread)
750       luaG_runerror(L, "attempt to yield across a C-call boundary");
751     else
752       luaG_runerror(L, "attempt to yield from outside a coroutine");
753   }
754   L->status = LUA_YIELD;
755   if (isLua(ci)) {  /* inside a hook? */
756     lua_assert(!isLuacode(ci));
757     api_check(L, k == NULL, "hooks cannot continue after yielding");
758     ci->u2.nyield = 0;  /* no results */
759   }
760   else {
761     if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
762       ci->u.c.ctx = ctx;  /* save context */
763     ci->u2.nyield = nresults;  /* save number of results */
764     luaD_throw(L, LUA_YIELD);
765   }
766   lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */
767   lua_unlock(L);
768   return 0;  /* return to 'luaD_hook' */
769 }
770 
771 
772 /*
773 ** Call the C function 'func' in protected mode, restoring basic
774 ** thread information ('allowhook', etc.) and in particular
775 ** its stack level in case of errors.
776 */
777 int luaD_pcall (lua_State *L, Pfunc func, void *u,
778                 ptrdiff_t old_top, ptrdiff_t ef) {
779   int status;
780   CallInfo *old_ci = L->ci;
781   lu_byte old_allowhooks = L->allowhook;
782   ptrdiff_t old_errfunc = L->errfunc;
783   L->errfunc = ef;
784   status = luaD_rawrunprotected(L, func, u);
785   if (unlikely(status != LUA_OK)) {  /* an error occurred? */
786     StkId oldtop = restorestack(L, old_top);
787     L->ci = old_ci;
788     L->allowhook = old_allowhooks;
789     status = luaF_close(L, oldtop, status);
790     oldtop = restorestack(L, old_top);  /* previous call may change stack */
791     luaD_seterrorobj(L, status, oldtop);
792     luaD_shrinkstack(L);   /* restore stack size in case of overflow */
793   }
794   L->errfunc = old_errfunc;
795   return status;
796 }
797 
798 
799 
800 /*
801 ** Execute a protected parser.
802 */
803 struct SParser {  /* data to 'f_parser' */
804   ZIO *z;
805   Mbuffer buff;  /* dynamic structure used by the scanner */
806   Dyndata dyd;  /* dynamic structures used by the parser */
807   const char *mode;
808   const char *name;
809 };
810 
811 
812 static void checkmode (lua_State *L, const char *mode, const char *x) {
813   if (mode && strchr(mode, x[0]) == NULL) {
814     luaO_pushfstring(L,
815        "attempt to load a %s chunk (mode is '%s')", x, mode);
816     luaD_throw(L, LUA_ERRSYNTAX);
817   }
818 }
819 
820 
821 static void f_parser (lua_State *L, void *ud) {
822   LClosure *cl;
823   struct SParser *p = cast(struct SParser *, ud);
824   int c = zgetc(p->z);  /* read first character */
825   if (c == LUA_SIGNATURE[0]) {
826     checkmode(L, p->mode, "binary");
827     cl = luaU_undump(L, p->z, p->name);
828   }
829   else {
830     checkmode(L, p->mode, "text");
831     cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
832   }
833   lua_assert(cl->nupvalues == cl->p->sizeupvalues);
834   luaF_initupvals(L, cl);
835 }
836 
837 
838 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
839                                         const char *mode) {
840   struct SParser p;
841   int status;
842   incnny(L);  /* cannot yield during parsing */
843   p.z = z; p.name = name; p.mode = mode;
844   p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
845   p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
846   p.dyd.label.arr = NULL; p.dyd.label.size = 0;
847   luaZ_initbuffer(L, &p.buff);
848   status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
849   luaZ_freebuffer(L, &p.buff);
850   luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
851   luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
852   luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
853   decnny(L);
854   return status;
855 }
856 
857 
858