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