xref: /netbsd-src/external/mit/lua/dist/src/ldo.c (revision e89934bbf778a6d6d6894877c4da59d0c7835b0f)
1 /*	$NetBSD: ldo.c,v 1.6 2016/09/08 02:21:31 salazar Exp $	*/
2 
3 /*
4 ** Id: ldo.c,v 2.151 2015/12/16 16:40:07 roberto Exp
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 static void 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     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     L->status = cast_byte(errcode);  /* mark it as dead */
122     if (g->mainthread->errorJmp) {  /* main thread has a handler? */
123       setobjs2s(L, g->mainthread->top++, L->top - 1);  /* copy error obj. */
124       luaD_throw(g->mainthread, errcode);  /* re-throw in main thread */
125     }
126     else {  /* no handler at all; abort */
127       if (g->panic) {  /* panic function? */
128         seterrorobj(L, errcode, L->top);  /* assume EXTRA_STACK */
129         if (L->ci->top < L->top)
130           L->ci->top = L->top;  /* pushing msg. can break this invariant */
131         lua_unlock(L);
132         g->panic(L);  /* call panic function (last chance to jump out) */
133       }
134       abort();
135     }
136   }
137 }
138 
139 
140 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
141   unsigned short oldnCcalls = L->nCcalls;
142   struct lua_longjmp lj;
143   lj.status = LUA_OK;
144   lj.previous = L->errorJmp;  /* chain new error handler */
145   L->errorJmp = &lj;
146   LUAI_TRY(L, &lj,
147     (*f)(L, ud);
148   );
149   L->errorJmp = lj.previous;  /* restore old error handler */
150   L->nCcalls = oldnCcalls;
151   return lj.status;
152 }
153 
154 /* }====================================================== */
155 
156 
157 /*
158 ** {==================================================================
159 ** Stack reallocation
160 ** ===================================================================
161 */
162 static void correctstack (lua_State *L, TValue *oldstack) {
163   CallInfo *ci;
164   UpVal *up;
165   L->top = (L->top - oldstack) + L->stack;
166   for (up = L->openupval; up != NULL; up = up->u.open.next)
167     up->v = (up->v - oldstack) + L->stack;
168   for (ci = L->ci; ci != NULL; ci = ci->previous) {
169     ci->top = (ci->top - oldstack) + L->stack;
170     ci->func = (ci->func - oldstack) + L->stack;
171     if (isLua(ci))
172       ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;
173   }
174 }
175 
176 
177 /* some space for error handling */
178 #define ERRORSTACKSIZE	(LUAI_MAXSTACK + 200)
179 
180 
181 void luaD_reallocstack (lua_State *L, int newsize) {
182   TValue *oldstack = L->stack;
183   int lim = L->stacksize;
184   lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
185   lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
186   luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);
187   for (; lim < newsize; lim++)
188     setnilvalue(L->stack + lim); /* erase new segment */
189   L->stacksize = newsize;
190   L->stack_last = L->stack + newsize - EXTRA_STACK;
191   correctstack(L, oldstack);
192 }
193 
194 
195 void luaD_growstack (lua_State *L, int n) {
196   int size = L->stacksize;
197   if (size > LUAI_MAXSTACK)  /* error after extra size? */
198     luaD_throw(L, LUA_ERRERR);
199   else {
200     int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
201     int newsize = 2 * size;
202     if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;
203     if (newsize < needed) newsize = needed;
204     if (newsize > LUAI_MAXSTACK) {  /* stack overflow? */
205       luaD_reallocstack(L, ERRORSTACKSIZE);
206       luaG_runerror(L, "stack overflow");
207     }
208     else
209       luaD_reallocstack(L, newsize);
210   }
211 }
212 
213 
214 static int stackinuse (lua_State *L) {
215   CallInfo *ci;
216   StkId lim = L->top;
217   for (ci = L->ci; ci != NULL; ci = ci->previous) {
218     lua_assert(ci->top <= L->stack_last);
219     if (lim < ci->top) lim = ci->top;
220   }
221   return cast_int(lim - L->stack) + 1;  /* part of stack in use */
222 }
223 
224 
225 void luaD_shrinkstack (lua_State *L) {
226   int inuse = stackinuse(L);
227   int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
228   if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
229   if (L->stacksize > LUAI_MAXSTACK)  /* was handling stack overflow? */
230     luaE_freeCI(L);  /* free all CIs (list grew because of an error) */
231   else
232     luaE_shrinkCI(L);  /* shrink list */
233   if (inuse <= LUAI_MAXSTACK &&  /* not handling stack overflow? */
234       goodsize < L->stacksize)  /* trying to shrink? */
235     luaD_reallocstack(L, goodsize);  /* shrink it */
236   else
237     condmovestack(L,,);  /* don't change stack (change only for debugging) */
238 }
239 
240 
241 void luaD_inctop (lua_State *L) {
242   luaD_checkstack(L, 1);
243   L->top++;
244 }
245 
246 /* }================================================================== */
247 
248 
249 /*
250 ** Call a hook for the given event. Make sure there is a hook to be
251 ** called. (Both 'L->hook' and 'L->hookmask', which triggers this
252 ** function, can be changed asynchronously by signals.)
253 */
254 void luaD_hook (lua_State *L, int event, int line) {
255   lua_Hook hook = L->hook;
256   if (hook && L->allowhook) {  /* make sure there is a hook */
257     CallInfo *ci = L->ci;
258     ptrdiff_t top = savestack(L, L->top);
259     ptrdiff_t ci_top = savestack(L, ci->top);
260     lua_Debug ar;
261     ar.event = event;
262     ar.currentline = line;
263     ar.i_ci = ci;
264     luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
265     ci->top = L->top + LUA_MINSTACK;
266     lua_assert(ci->top <= L->stack_last);
267     L->allowhook = 0;  /* cannot call hooks inside a hook */
268     ci->callstatus |= CIST_HOOKED;
269     lua_unlock(L);
270     (*hook)(L, &ar);
271     lua_lock(L);
272     lua_assert(!L->allowhook);
273     L->allowhook = 1;
274     ci->top = restorestack(L, ci_top);
275     L->top = restorestack(L, top);
276     ci->callstatus &= ~CIST_HOOKED;
277   }
278 }
279 
280 
281 static void callhook (lua_State *L, CallInfo *ci) {
282   int hook = LUA_HOOKCALL;
283   ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
284   if (isLua(ci->previous) &&
285       GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {
286     ci->callstatus |= CIST_TAIL;
287     hook = LUA_HOOKTAILCALL;
288   }
289   luaD_hook(L, hook, -1);
290   ci->u.l.savedpc--;  /* correct 'pc' */
291 }
292 
293 
294 static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
295   int i;
296   int nfixargs = p->numparams;
297   StkId base, fixed;
298   /* move fixed parameters to final position */
299   fixed = L->top - actual;  /* first fixed argument */
300   base = L->top;  /* final position of first argument */
301   for (i = 0; i < nfixargs && i < actual; i++) {
302     setobjs2s(L, L->top++, fixed + i);
303     setnilvalue(fixed + i);  /* erase original copy (for GC) */
304   }
305   for (; i < nfixargs; i++)
306     setnilvalue(L->top++);  /* complete missing arguments */
307   return base;
308 }
309 
310 
311 /*
312 ** Check whether __call metafield of 'func' is a function. If so, put
313 ** it in stack below original 'func' so that 'luaD_precall' can call
314 ** it. Raise an error if __call metafield is not a function.
315 */
316 static void tryfuncTM (lua_State *L, StkId func) {
317   const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
318   StkId p;
319   if (!ttisfunction(tm))
320     luaG_typeerror(L, func, "call");
321   /* Open a hole inside the stack at 'func' */
322   for (p = L->top; p > func; p--)
323     setobjs2s(L, p, p-1);
324   L->top++;  /* slot ensured by caller */
325   setobj2s(L, func, tm);  /* tag method is the new function to be called */
326 }
327 
328 
329 
330 #define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
331 
332 
333 /* macro to check stack size, preserving 'p' */
334 #define checkstackp(L,n,p)  \
335   luaD_checkstackaux(L, n, \
336     ptrdiff_t t__ = savestack(L, p);  /* save 'p' */ \
337     luaC_checkGC(L),  /* stack grow uses memory */ \
338     p = restorestack(L, t__))  /* 'pos' part: restore 'p' */
339 
340 
341 /*
342 ** Prepares a function call: checks the stack, creates a new CallInfo
343 ** entry, fills in the relevant information, calls hook if needed.
344 ** If function is a C function, does the call, too. (Otherwise, leave
345 ** the execution ('luaV_execute') to the caller, to allow stackless
346 ** calls.) Returns true iff function has been executed (C function).
347 */
348 int luaD_precall (lua_State *L, StkId func, int nresults) {
349   lua_CFunction f;
350   CallInfo *ci;
351   switch (ttype(func)) {
352     case LUA_TCCL:  /* C closure */
353       f = clCvalue(func)->f;
354       goto Cfunc;
355     case LUA_TLCF:  /* light C function */
356       f = fvalue(func);
357      Cfunc: {
358       int n;  /* number of returns */
359       checkstackp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
360       ci = next_ci(L);  /* now 'enter' new function */
361       ci->nresults = nresults;
362       ci->func = func;
363       ci->top = L->top + LUA_MINSTACK;
364       lua_assert(ci->top <= L->stack_last);
365       ci->callstatus = 0;
366       if (L->hookmask & LUA_MASKCALL)
367         luaD_hook(L, LUA_HOOKCALL, -1);
368       lua_unlock(L);
369       n = (*f)(L);  /* do the actual call */
370       lua_lock(L);
371       api_checknelems(L, n);
372       luaD_poscall(L, ci, L->top - n, n);
373       return 1;
374     }
375     case LUA_TLCL: {  /* Lua function: prepare its call */
376       StkId base;
377       Proto *p = clLvalue(func)->p;
378       int n = cast_int(L->top - func) - 1;  /* number of real arguments */
379       int fsize = p->maxstacksize;  /* frame size */
380       checkstackp(L, fsize, func);
381       if (p->is_vararg != 1) {  /* do not use vararg? */
382         for (; n < p->numparams; n++)
383           setnilvalue(L->top++);  /* complete missing arguments */
384         base = func + 1;
385       }
386       else
387         base = adjust_varargs(L, p, n);
388       ci = next_ci(L);  /* now 'enter' new function */
389       ci->nresults = nresults;
390       ci->func = func;
391       ci->u.l.base = base;
392       L->top = ci->top = base + fsize;
393       lua_assert(ci->top <= L->stack_last);
394       ci->u.l.savedpc = p->code;  /* starting point */
395       ci->callstatus = CIST_LUA;
396       if (L->hookmask & LUA_MASKCALL)
397         callhook(L, ci);
398       return 0;
399     }
400     default: {  /* not a function */
401       checkstackp(L, 1, func);  /* ensure space for metamethod */
402       tryfuncTM(L, func);  /* try to get '__call' metamethod */
403       return luaD_precall(L, func, nresults);  /* now it must be a function */
404     }
405   }
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 static int moveresults (lua_State *L, const TValue *firstResult, StkId res,
416                                       int nres, int wanted) {
417   switch (wanted) {  /* handle typical cases separately */
418     case 0: break;  /* nothing to move */
419     case 1: {  /* one result needed */
420       if (nres == 0)   /* no results? */
421         firstResult = luaO_nilobject;  /* adjust with nil */
422       setobjs2s(L, res, firstResult);  /* move it to proper place */
423       break;
424     }
425     case LUA_MULTRET: {
426       int i;
427       for (i = 0; i < nres; i++)  /* move all results to correct place */
428         setobjs2s(L, res + i, firstResult + i);
429       L->top = res + nres;
430       return 0;  /* wanted == LUA_MULTRET */
431     }
432     default: {
433       int i;
434       if (wanted <= nres) {  /* enough results? */
435         for (i = 0; i < wanted; i++)  /* move wanted results to correct place */
436           setobjs2s(L, res + i, firstResult + i);
437       }
438       else {  /* not enough results; use all of them plus nils */
439         for (i = 0; i < nres; i++)  /* move all results to correct place */
440           setobjs2s(L, res + i, firstResult + i);
441         for (; i < wanted; i++)  /* complete wanted number of results */
442           setnilvalue(res + i);
443       }
444       break;
445     }
446   }
447   L->top = res + wanted;  /* top points after the last result */
448   return 1;
449 }
450 
451 
452 /*
453 ** Finishes a function call: calls hook if necessary, removes CallInfo,
454 ** moves current number of results to proper place; returns 0 iff call
455 ** wanted multiple (variable number of) results.
456 */
457 int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, int nres) {
458   StkId res;
459   int wanted = ci->nresults;
460   if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
461     if (L->hookmask & LUA_MASKRET) {
462       ptrdiff_t fr = savestack(L, firstResult);  /* hook may change stack */
463       luaD_hook(L, LUA_HOOKRET, -1);
464       firstResult = restorestack(L, fr);
465     }
466     L->oldpc = ci->previous->u.l.savedpc;  /* 'oldpc' for caller function */
467   }
468   res = ci->func;  /* res == final position of 1st result */
469   L->ci = ci->previous;  /* back to caller */
470   /* move results to proper place */
471   return moveresults(L, firstResult, res, nres, wanted);
472 }
473 
474 
475 /*
476 ** Check appropriate error for stack overflow ("regular" overflow or
477 ** overflow while handling stack overflow). If 'nCalls' is larger than
478 ** LUAI_MAXCCALLS (which means it is handling a "regular" overflow) but
479 ** smaller than 9/8 of LUAI_MAXCCALLS, does not report an error (to
480 ** allow overflow handling to work)
481 */
482 static void stackerror (lua_State *L) {
483   if (L->nCcalls == LUAI_MAXCCALLS)
484     luaG_runerror(L, "C stack overflow");
485   else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
486     luaD_throw(L, LUA_ERRERR);  /* error while handing stack error */
487 }
488 
489 
490 /*
491 ** Call a function (C or Lua). The function to be called is at *func.
492 ** The arguments are on the stack, right after the function.
493 ** When returns, all the results are on the stack, starting at the original
494 ** function position.
495 */
496 void luaD_call (lua_State *L, StkId func, int nResults) {
497   if (++L->nCcalls >= LUAI_MAXCCALLS)
498     stackerror(L);
499   if (!luaD_precall(L, func, nResults))  /* is a Lua function? */
500     luaV_execute(L);  /* call it */
501   L->nCcalls--;
502 }
503 
504 
505 /*
506 ** Similar to 'luaD_call', but does not allow yields during the call
507 */
508 void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
509   L->nny++;
510   luaD_call(L, func, nResults);
511   L->nny--;
512 }
513 
514 
515 /*
516 ** Completes the execution of an interrupted C function, calling its
517 ** continuation function.
518 */
519 static void finishCcall (lua_State *L, int status) {
520   CallInfo *ci = L->ci;
521   int n;
522   /* must have a continuation and must be able to call it */
523   lua_assert(ci->u.c.k != NULL && L->nny == 0);
524   /* error status can only happen in a protected call */
525   lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
526   if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */
527     ci->callstatus &= ~CIST_YPCALL;  /* finish 'lua_pcall' */
528     L->errfunc = ci->u.c.old_errfunc;
529   }
530   /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
531      handled */
532   adjustresults(L, ci->nresults);
533   /* call continuation function */
534   lua_unlock(L);
535   n = (*ci->u.c.k)(L, status, ci->u.c.ctx);
536   lua_lock(L);
537   api_checknelems(L, n);
538   /* finish 'luaD_precall' */
539   luaD_poscall(L, ci, L->top - n, n);
540 }
541 
542 
543 /*
544 ** Executes "full continuation" (everything in the stack) of a
545 ** previously interrupted coroutine until the stack is empty (or another
546 ** interruption long-jumps out of the loop). If the coroutine is
547 ** recovering from an error, 'ud' points to the error status, which must
548 ** be passed to the first continuation function (otherwise the default
549 ** status is LUA_YIELD).
550 */
551 static void unroll (lua_State *L, void *ud) {
552   if (ud != NULL)  /* error status? */
553     finishCcall(L, *(int *)ud);  /* finish 'lua_pcallk' callee */
554   while (L->ci != &L->base_ci) {  /* something in the stack */
555     if (!isLua(L->ci))  /* C function? */
556       finishCcall(L, LUA_YIELD);  /* complete its execution */
557     else {  /* Lua function */
558       luaV_finishOp(L);  /* finish interrupted instruction */
559       luaV_execute(L);  /* execute down to higher C 'boundary' */
560     }
561   }
562 }
563 
564 
565 /*
566 ** Try to find a suspended protected call (a "recover point") for the
567 ** given thread.
568 */
569 static CallInfo *findpcall (lua_State *L) {
570   CallInfo *ci;
571   for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
572     if (ci->callstatus & CIST_YPCALL)
573       return ci;
574   }
575   return NULL;  /* no pending pcall */
576 }
577 
578 
579 /*
580 ** Recovers from an error in a coroutine. Finds a recover point (if
581 ** there is one) and completes the execution of the interrupted
582 ** 'luaD_pcall'. If there is no recover point, returns zero.
583 */
584 static int recover (lua_State *L, int status) {
585   StkId oldtop;
586   CallInfo *ci = findpcall(L);
587   if (ci == NULL) return 0;  /* no recovery point */
588   /* "finish" luaD_pcall */
589   oldtop = restorestack(L, ci->extra);
590   luaF_close(L, oldtop);
591   seterrorobj(L, status, oldtop);
592   L->ci = ci;
593   L->allowhook = getoah(ci->callstatus);  /* restore original 'allowhook' */
594   L->nny = 0;  /* should be zero to be yieldable */
595   luaD_shrinkstack(L);
596   L->errfunc = ci->u.c.old_errfunc;
597   return 1;  /* continue running the coroutine */
598 }
599 
600 
601 /*
602 ** signal an error in the call to 'resume', not in the execution of the
603 ** coroutine itself. (Such errors should not be handled by any coroutine
604 ** error handler and should not kill the coroutine.)
605 */
606 static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
607   L->top = firstArg;  /* remove args from the stack */
608   setsvalue2s(L, L->top, luaS_new(L, msg));  /* push error message */
609   api_incr_top(L);
610   luaD_throw(L, -1);  /* jump back to 'lua_resume' */
611 }
612 
613 
614 /*
615 ** Do the work for 'lua_resume' in protected mode. Most of the work
616 ** depends on the status of the coroutine: initial state, suspended
617 ** inside a hook, or regularly suspended (optionally with a continuation
618 ** function), plus erroneous cases: non-suspended coroutine or dead
619 ** coroutine.
620 */
621 static void resume (lua_State *L, void *ud) {
622   int nCcalls = L->nCcalls;
623   int n = *(cast(int*, ud));  /* number of arguments */
624   StkId firstArg = L->top - n;  /* first argument */
625   CallInfo *ci = L->ci;
626   if (nCcalls >= LUAI_MAXCCALLS)
627     resume_error(L, "C stack overflow", firstArg);
628   if (L->status == LUA_OK) {  /* may be starting a coroutine */
629     if (ci != &L->base_ci)  /* not in base level? */
630       resume_error(L, "cannot resume non-suspended coroutine", firstArg);
631     /* coroutine is in base level; start running it */
632     if (!luaD_precall(L, firstArg - 1, LUA_MULTRET))  /* Lua function? */
633       luaV_execute(L);  /* call it */
634   }
635   else if (L->status != LUA_YIELD)
636     resume_error(L, "cannot resume dead coroutine", firstArg);
637   else {  /* resuming from previous yield */
638     L->status = LUA_OK;  /* mark that it is running (again) */
639     ci->func = restorestack(L, ci->extra);
640     if (isLua(ci))  /* yielded inside a hook? */
641       luaV_execute(L);  /* just continue running Lua code */
642     else {  /* 'common' yield */
643       if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
644         lua_unlock(L);
645         n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
646         lua_lock(L);
647         api_checknelems(L, n);
648         firstArg = L->top - n;  /* yield results come from continuation */
649       }
650       luaD_poscall(L, ci, firstArg, n);  /* finish 'luaD_precall' */
651     }
652     unroll(L, NULL);  /* run continuation */
653   }
654   lua_assert(nCcalls == L->nCcalls);
655 }
656 
657 
658 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
659   int status;
660   unsigned short oldnny = L->nny;  /* save "number of non-yieldable" calls */
661   lua_lock(L);
662   luai_userstateresume(L, nargs);
663   L->nCcalls = (from) ? from->nCcalls + 1 : 1;
664   L->nny = 0;  /* allow yields */
665   api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
666   status = luaD_rawrunprotected(L, resume, &nargs);
667   if (status == -1)  /* error calling 'lua_resume'? */
668     status = LUA_ERRRUN;
669   else {  /* continue running after recoverable errors */
670     while (errorstatus(status) && recover(L, status)) {
671       /* unroll continuation */
672       status = luaD_rawrunprotected(L, unroll, &status);
673     }
674     if (errorstatus(status)) {  /* unrecoverable error? */
675       L->status = cast_byte(status);  /* mark thread as 'dead' */
676       seterrorobj(L, status, L->top);  /* push error message */
677       L->ci->top = L->top;
678     }
679     else lua_assert(status == L->status);  /* normal end or yield */
680   }
681   L->nny = oldnny;  /* restore 'nny' */
682   L->nCcalls--;
683   lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
684   lua_unlock(L);
685   return status;
686 }
687 
688 
689 LUA_API int lua_isyieldable (lua_State *L) {
690   return (L->nny == 0);
691 }
692 
693 
694 LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
695                         lua_KFunction k) {
696   CallInfo *ci = L->ci;
697   luai_userstateyield(L, nresults);
698   lua_lock(L);
699   api_checknelems(L, nresults);
700   if (L->nny > 0) {
701     if (L != G(L)->mainthread)
702       luaG_runerror(L, "attempt to yield across a C-call boundary");
703     else
704       luaG_runerror(L, "attempt to yield from outside a coroutine");
705   }
706   L->status = LUA_YIELD;
707   ci->extra = savestack(L, ci->func);  /* save current 'func' */
708   if (isLua(ci)) {  /* inside a hook? */
709     api_check(L, k == NULL, "hooks cannot continue after yielding");
710   }
711   else {
712     if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
713       ci->u.c.ctx = ctx;  /* save context */
714     ci->func = L->top - nresults - 1;  /* protect stack below results */
715     luaD_throw(L, LUA_YIELD);
716   }
717   lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */
718   lua_unlock(L);
719   return 0;  /* return to 'luaD_hook' */
720 }
721 
722 
723 int luaD_pcall (lua_State *L, Pfunc func, void *u,
724                 ptrdiff_t old_top, ptrdiff_t ef) {
725   int status;
726   CallInfo *old_ci = L->ci;
727   lu_byte old_allowhooks = L->allowhook;
728   unsigned short old_nny = L->nny;
729   ptrdiff_t old_errfunc = L->errfunc;
730   L->errfunc = ef;
731   status = luaD_rawrunprotected(L, func, u);
732   if (status != LUA_OK) {  /* an error occurred? */
733     StkId oldtop = restorestack(L, old_top);
734     luaF_close(L, oldtop);  /* close possible pending closures */
735     seterrorobj(L, status, oldtop);
736     L->ci = old_ci;
737     L->allowhook = old_allowhooks;
738     L->nny = old_nny;
739     luaD_shrinkstack(L);
740   }
741   L->errfunc = old_errfunc;
742   return status;
743 }
744 
745 
746 
747 /*
748 ** Execute a protected parser.
749 */
750 struct SParser {  /* data to 'f_parser' */
751   ZIO *z;
752   Mbuffer buff;  /* dynamic structure used by the scanner */
753   Dyndata dyd;  /* dynamic structures used by the parser */
754   const char *mode;
755   const char *name;
756 };
757 
758 
759 static void checkmode (lua_State *L, const char *mode, const char *x) {
760   if (mode && strchr(mode, x[0]) == NULL) {
761     luaO_pushfstring(L,
762        "attempt to load a %s chunk (mode is '%s')", x, mode);
763     luaD_throw(L, LUA_ERRSYNTAX);
764   }
765 }
766 
767 
768 static void f_parser (lua_State *L, void *ud) {
769   LClosure *cl;
770   struct SParser *p = cast(struct SParser *, ud);
771   int c = zgetc(p->z);  /* read first character */
772   if (c == LUA_SIGNATURE[0]) {
773     checkmode(L, p->mode, "binary");
774     cl = luaU_undump(L, p->z, p->name);
775   }
776   else {
777     checkmode(L, p->mode, "text");
778     cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
779   }
780   lua_assert(cl->nupvalues == cl->p->sizeupvalues);
781   luaF_initupvals(L, cl);
782 }
783 
784 
785 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
786                                         const char *mode) {
787   struct SParser p;
788   int status;
789   L->nny++;  /* cannot yield during parsing */
790   p.z = z; p.name = name; p.mode = mode;
791   p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
792   p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
793   p.dyd.label.arr = NULL; p.dyd.label.size = 0;
794   luaZ_initbuffer(L, &p.buff);
795   status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
796   luaZ_freebuffer(L, &p.buff);
797   luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
798   luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
799   luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
800   L->nny--;
801   return status;
802 }
803 
804 
805