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