xref: /freebsd/sys/contrib/openzfs/module/lua/ldo.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*
2 ** $Id: ldo.c,v 2.108.1.3 2013/11/08 18:22:50 roberto Exp $
3 ** Stack and Call structure of Lua
4 ** See Copyright Notice in lua.h
5 */
6 
7 
8 #define ldo_c
9 #define LUA_CORE
10 
11 #include <sys/lua/lua.h>
12 
13 #include "lapi.h"
14 #include "ldebug.h"
15 #include "ldo.h"
16 #include "lfunc.h"
17 #include "lgc.h"
18 #include "lmem.h"
19 #include "lobject.h"
20 #include "lopcodes.h"
21 #include "lparser.h"
22 #include "lstate.h"
23 #include "lstring.h"
24 #include "ltable.h"
25 #include "ltm.h"
26 #include "lvm.h"
27 #include "lzio.h"
28 
29 
30 
31 /* Return the number of bytes available on the stack. */
32 #if defined (_KERNEL) && defined(__linux__)
33 #include <asm/current.h>
34 static intptr_t stack_remaining(void) {
35   intptr_t local;
36   local = (intptr_t)&local - (intptr_t)current->stack;
37   return local;
38 }
39 #elif defined (_KERNEL) && defined(__FreeBSD__)
40 #include <sys/pcpu.h>
41 static intptr_t stack_remaining(void) {
42   intptr_t local;
43   local = (intptr_t)&local - (intptr_t)curthread->td_kstack;
44   return local;
45 }
46 #else
47 static intptr_t stack_remaining(void) {
48   return INTPTR_MAX;
49 }
50 #endif
51 
52 /*
53 ** {======================================================
54 ** Error-recovery functions
55 ** =======================================================
56 */
57 
58 /*
59 ** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
60 ** default, Lua handles errors with exceptions when compiling as
61 ** C++ code, with _longjmp/_setjmp when asked to use them, and with
62 ** longjmp/setjmp otherwise.
63 */
64 #if !defined(LUAI_THROW)
65 
66 #ifdef _KERNEL
67 
68 #ifdef __linux__
69 #if defined(__i386__)
70 #define	JMP_BUF_CNT	6
71 #elif defined(__x86_64__)
72 #define	JMP_BUF_CNT	8
73 #elif defined(__sparc__) && defined(__arch64__)
74 #define	JMP_BUF_CNT	6
75 #elif defined(__powerpc__)
76 #define	JMP_BUF_CNT	26
77 #elif defined(__aarch64__)
78 #define	JMP_BUF_CNT	64
79 #elif defined(__arm__)
80 #define	JMP_BUF_CNT	65
81 #elif defined(__mips__)
82 #define JMP_BUF_CNT	12
83 #elif defined(__s390x__)
84 #define JMP_BUF_CNT	18
85 #elif defined(__riscv)
86 #define JMP_BUF_CNT     64
87 #else
88 #define	JMP_BUF_CNT	1
89 #endif
90 
91 typedef	struct _label_t { long long unsigned val[JMP_BUF_CNT]; } label_t;
92 
93 int setjmp(label_t *) __attribute__ ((__nothrow__));
94 extern __attribute__((noreturn)) void longjmp(label_t *);
95 
96 #define LUAI_THROW(L,c)		longjmp(&(c)->b)
97 #define LUAI_TRY(L,c,a)		if (setjmp(&(c)->b) == 0) { a }
98 #define luai_jmpbuf		label_t
99 
100 /* unsupported arches will build but not be able to run lua programs */
101 #if JMP_BUF_CNT == 1
102 int setjmp (label_t *buf) {
103 	return 1;
104 }
105 
106 void longjmp (label_t * buf) {
107 	for (;;);
108 }
109 #endif
110 #else
111 #define LUAI_THROW(L,c)		longjmp((c)->b, 1)
112 #define LUAI_TRY(L,c,a)		if (setjmp((c)->b) == 0) { a }
113 #define luai_jmpbuf		jmp_buf
114 #endif
115 
116 #else /* _KERNEL */
117 
118 #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
119 /* C++ exceptions */
120 #define LUAI_THROW(L,c)		throw(c)
121 #define LUAI_TRY(L,c,a) \
122 	try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
123 #define luai_jmpbuf		int  /* dummy variable */
124 
125 #elif defined(LUA_USE_ULONGJMP)
126 /* in Unix, try _longjmp/_setjmp (more efficient) */
127 #define LUAI_THROW(L,c)		_longjmp((c)->b, 1)
128 #define LUAI_TRY(L,c,a)		if (_setjmp((c)->b) == 0) { a }
129 #define luai_jmpbuf		jmp_buf
130 
131 #else
132 /* default handling with long jumps */
133 #define LUAI_THROW(L,c)		longjmp((c)->b, 1)
134 #define LUAI_TRY(L,c,a)		if (setjmp((c)->b) == 0) { a }
135 #define luai_jmpbuf		jmp_buf
136 
137 #endif
138 
139 #endif /* _KERNEL */
140 
141 #endif /* LUAI_THROW */
142 
143 
144 /* chain list of long jump buffers */
145 struct lua_longjmp {
146   struct lua_longjmp *previous;
147   luai_jmpbuf b;
148   volatile int status;  /* error code */
149 };
150 
151 
152 static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
153   switch (errcode) {
154     case LUA_ERRMEM: {  /* memory error? */
155       setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
156       break;
157     }
158     case LUA_ERRERR: {
159       setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
160       break;
161     }
162     default: {
163       setobjs2s(L, oldtop, L->top - 1);  /* error message on current top */
164       break;
165     }
166   }
167   L->top = oldtop + 1;
168 }
169 
170 /*
171  * Silence infinite recursion warning which was added to -Wall in gcc 12.1
172  */
173 #if defined(HAVE_INFINITE_RECURSION)
174 #pragma GCC diagnostic push
175 #pragma GCC diagnostic ignored "-Winfinite-recursion"
176 #endif
177 
178 l_noret luaD_throw (lua_State *L, int errcode) {
179   if (L->errorJmp) {  /* thread has an error handler? */
180     L->errorJmp->status = errcode;  /* set status */
181     LUAI_THROW(L, L->errorJmp);  /* jump to it */
182   }
183   else {  /* thread has no error handler */
184     L->status = cast_byte(errcode);  /* mark it as dead */
185     if (G(L)->mainthread->errorJmp) {  /* main thread has a handler? */
186       setobjs2s(L, G(L)->mainthread->top++, L->top - 1);  /* copy error obj. */
187       luaD_throw(G(L)->mainthread, errcode);  /* re-throw in main thread */
188     }
189     else {  /* no handler at all; abort */
190       if (G(L)->panic) {  /* panic function? */
191         lua_unlock(L);
192         G(L)->panic(L);  /* call it (last chance to jump out) */
193       }
194       panic("no error handler");
195     }
196   }
197 }
198 
199 #if defined(HAVE_INFINITE_RECURSION)
200 #pragma GCC diagnostic pop
201 #endif
202 
203 
204 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
205   unsigned short oldnCcalls = L->nCcalls;
206   struct lua_longjmp lj;
207   lj.status = LUA_OK;
208   lj.previous = L->errorJmp;  /* chain new error handler */
209   L->errorJmp = &lj;
210   LUAI_TRY(L, &lj,
211     (*f)(L, ud);
212   );
213   L->errorJmp = lj.previous;  /* restore old error handler */
214   L->nCcalls = oldnCcalls;
215   return lj.status;
216 }
217 
218 /* }====================================================== */
219 
220 
221 static void correctstack (lua_State *L, TValue *oldstack) {
222   CallInfo *ci;
223   GCObject *up;
224   L->top = (L->top - oldstack) + L->stack;
225   for (up = L->openupval; up != NULL; up = up->gch.next)
226     gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
227   for (ci = L->ci; ci != NULL; ci = ci->previous) {
228     ci->top = (ci->top - oldstack) + L->stack;
229     ci->func = (ci->func - oldstack) + L->stack;
230     if (isLua(ci))
231       ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;
232   }
233 }
234 
235 
236 /* some space for error handling */
237 #define ERRORSTACKSIZE	(LUAI_MAXSTACK + 200)
238 
239 
240 void luaD_reallocstack (lua_State *L, int newsize) {
241   TValue *oldstack = L->stack;
242   int lim = L->stacksize;
243   lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
244   lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
245   luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);
246   for (; lim < newsize; lim++)
247     setnilvalue(L->stack + lim); /* erase new segment */
248   L->stacksize = newsize;
249   L->stack_last = L->stack + newsize - EXTRA_STACK;
250   correctstack(L, oldstack);
251 }
252 
253 
254 void luaD_growstack (lua_State *L, int n) {
255   int size = L->stacksize;
256   if (size > LUAI_MAXSTACK)  /* error after extra size? */
257     luaD_throw(L, LUA_ERRERR);
258   else {
259     int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
260     int newsize = 2 * size;
261     if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;
262     if (newsize < needed) newsize = needed;
263     if (newsize > LUAI_MAXSTACK) {  /* stack overflow? */
264       luaD_reallocstack(L, ERRORSTACKSIZE);
265       luaG_runerror(L, "stack overflow");
266     }
267     else
268       luaD_reallocstack(L, newsize);
269   }
270 }
271 
272 
273 static int stackinuse (lua_State *L) {
274   CallInfo *ci;
275   StkId lim = L->top;
276   for (ci = L->ci; ci != NULL; ci = ci->previous) {
277     lua_assert(ci->top <= L->stack_last);
278     if (lim < ci->top) lim = ci->top;
279   }
280   return cast_int(lim - L->stack) + 1;  /* part of stack in use */
281 }
282 
283 
284 void luaD_shrinkstack (lua_State *L) {
285   int inuse = stackinuse(L);
286   int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
287   if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
288   if (inuse > LUAI_MAXSTACK ||  /* handling stack overflow? */
289       goodsize >= L->stacksize)  /* would grow instead of shrink? */
290     condmovestack(L);  /* don't change stack (change only for debugging) */
291   else
292     luaD_reallocstack(L, goodsize);  /* shrink it */
293 }
294 
295 
296 void luaD_hook (lua_State *L, int event, int line) {
297   lua_Hook hook = L->hook;
298   if (hook && L->allowhook) {
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     luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
307     ci->top = L->top + LUA_MINSTACK;
308     lua_assert(ci->top <= L->stack_last);
309     L->allowhook = 0;  /* cannot call hooks inside a hook */
310     ci->callstatus |= CIST_HOOKED;
311     lua_unlock(L);
312     (*hook)(L, &ar);
313     lua_lock(L);
314     lua_assert(!L->allowhook);
315     L->allowhook = 1;
316     ci->top = restorestack(L, ci_top);
317     L->top = restorestack(L, top);
318     ci->callstatus &= ~CIST_HOOKED;
319   }
320 }
321 
322 
323 static void callhook (lua_State *L, CallInfo *ci) {
324   int hook = LUA_HOOKCALL;
325   ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
326   if (isLua(ci->previous) &&
327       GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {
328     ci->callstatus |= CIST_TAIL;
329     hook = LUA_HOOKTAILCALL;
330   }
331   luaD_hook(L, hook, -1);
332   ci->u.l.savedpc--;  /* correct 'pc' */
333 }
334 
335 
336 static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
337   int i;
338   int nfixargs = p->numparams;
339   StkId base, fixed;
340   lua_assert(actual >= nfixargs);
341   /* move fixed parameters to final position */
342   luaD_checkstack(L, p->maxstacksize);  /* check again for new 'base' */
343   fixed = L->top - actual;  /* first fixed argument */
344   base = L->top;  /* final position of first argument */
345   for (i=0; i<nfixargs; i++) {
346     setobjs2s(L, L->top++, fixed + i);
347     setnilvalue(fixed + i);
348   }
349   return base;
350 }
351 
352 
353 static StkId tryfuncTM (lua_State *L, StkId func) {
354   const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
355   StkId p;
356   ptrdiff_t funcr = savestack(L, func);
357   if (!ttisfunction(tm))
358     luaG_typeerror(L, func, "call");
359   /* Open a hole inside the stack at `func' */
360   for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
361   incr_top(L);
362   func = restorestack(L, funcr);  /* previous call may change stack */
363   setobj2s(L, func, tm);  /* tag method is the new function to be called */
364   return func;
365 }
366 
367 
368 
369 #define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
370 
371 
372 /*
373 ** returns true if function has been executed (C function)
374 */
375 int luaD_precall (lua_State *L, StkId func, int nresults) {
376   lua_CFunction f;
377   CallInfo *ci;
378   int n;  /* number of arguments (Lua) or returns (C) */
379   ptrdiff_t funcr = savestack(L, func);
380   switch (ttype(func)) {
381     case LUA_TLCF:  /* light C function */
382       f = fvalue(func);
383       goto Cfunc;
384     case LUA_TCCL: {  /* C closure */
385       f = clCvalue(func)->f;
386      Cfunc:
387       luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
388       ci = next_ci(L);  /* now 'enter' new function */
389       ci->nresults = nresults;
390       ci->func = restorestack(L, funcr);
391       ci->top = L->top + LUA_MINSTACK;
392       lua_assert(ci->top <= L->stack_last);
393       ci->callstatus = 0;
394       luaC_checkGC(L);  /* stack grow uses memory */
395       if (L->hookmask & LUA_MASKCALL)
396         luaD_hook(L, LUA_HOOKCALL, -1);
397       lua_unlock(L);
398       n = (*f)(L);  /* do the actual call */
399       lua_lock(L);
400       api_checknelems(L, n);
401       luaD_poscall(L, L->top - n);
402       return 1;
403     }
404     case LUA_TLCL: {  /* Lua function: prepare its call */
405       StkId base;
406       Proto *p = clLvalue(func)->p;
407       n = cast_int(L->top - func) - 1;  /* number of real arguments */
408       luaD_checkstack(L, p->maxstacksize);
409       for (; n < p->numparams; n++)
410         setnilvalue(L->top++);  /* complete missing arguments */
411       if (!p->is_vararg) {
412         func = restorestack(L, funcr);
413         base = func + 1;
414       }
415       else {
416         base = adjust_varargs(L, p, n);
417         func = restorestack(L, funcr);  /* previous call can change stack */
418       }
419       ci = next_ci(L);  /* now 'enter' new function */
420       ci->nresults = nresults;
421       ci->func = func;
422       ci->u.l.base = base;
423       ci->top = base + p->maxstacksize;
424       lua_assert(ci->top <= L->stack_last);
425       ci->u.l.savedpc = p->code;  /* starting point */
426       ci->callstatus = CIST_LUA;
427       L->top = ci->top;
428       luaC_checkGC(L);  /* stack grow uses memory */
429       if (L->hookmask & LUA_MASKCALL)
430         callhook(L, ci);
431       return 0;
432     }
433     default: {  /* not a function */
434       func = tryfuncTM(L, func);  /* retry with 'function' tag method */
435       return luaD_precall(L, func, nresults);  /* now it must be a function */
436     }
437   }
438 }
439 
440 
441 int luaD_poscall (lua_State *L, StkId firstResult) {
442   StkId res;
443   int wanted, i;
444   CallInfo *ci = L->ci;
445   if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
446     if (L->hookmask & LUA_MASKRET) {
447       ptrdiff_t fr = savestack(L, firstResult);  /* hook may change stack */
448       luaD_hook(L, LUA_HOOKRET, -1);
449       firstResult = restorestack(L, fr);
450     }
451     L->oldpc = ci->previous->u.l.savedpc;  /* 'oldpc' for caller function */
452   }
453   res = ci->func;  /* res == final position of 1st result */
454   wanted = ci->nresults;
455   L->ci = ci = ci->previous;  /* back to caller */
456   /* move results to correct place */
457   for (i = wanted; i != 0 && firstResult < L->top; i--)
458     setobjs2s(L, res++, firstResult++);
459   while (i-- > 0)
460     setnilvalue(res++);
461   L->top = res;
462   return (wanted - LUA_MULTRET);  /* 0 iff wanted == LUA_MULTRET */
463 }
464 
465 
466 /*
467 ** Call a function (C or Lua). The function to be called is at *func.
468 ** The arguments are on the stack, right after the function.
469 ** When returns, all the results are on the stack, starting at the original
470 ** function position.
471 */
472 void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {
473   if (++L->nCcalls >= LUAI_MAXCCALLS) {
474     if (L->nCcalls == LUAI_MAXCCALLS)
475       luaG_runerror(L, "C stack overflow");
476     else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
477       luaD_throw(L, LUA_ERRERR);  /* error while handling stack error */
478   }
479   intptr_t remaining = stack_remaining();
480   if (L->runerror == 0 && remaining < LUAI_MINCSTACK)
481     luaG_runerror(L, "C stack overflow");
482   if (L->runerror != 0 && remaining < LUAI_MINCSTACK / 2)
483     luaD_throw(L, LUA_ERRERR);  /* error while handling stack error */
484   if (!allowyield) L->nny++;
485   if (!luaD_precall(L, func, nResults))  /* is a Lua function? */
486     luaV_execute(L);  /* call it */
487   if (!allowyield) L->nny--;
488   L->nCcalls--;
489 }
490 
491 
492 static void finishCcall (lua_State *L) {
493   CallInfo *ci = L->ci;
494   int n;
495   lua_assert(ci->u.c.k != NULL);  /* must have a continuation */
496   lua_assert(L->nny == 0);
497   if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */
498     ci->callstatus &= ~CIST_YPCALL;  /* finish 'lua_pcall' */
499     L->errfunc = ci->u.c.old_errfunc;
500   }
501   /* finish 'lua_callk'/'lua_pcall' */
502   adjustresults(L, ci->nresults);
503   /* call continuation function */
504   if (!(ci->callstatus & CIST_STAT))  /* no call status? */
505     ci->u.c.status = LUA_YIELD;  /* 'default' status */
506   lua_assert(ci->u.c.status != LUA_OK);
507   ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED;
508   lua_unlock(L);
509   n = (*ci->u.c.k)(L);
510   lua_lock(L);
511   api_checknelems(L, n);
512   /* finish 'luaD_precall' */
513   luaD_poscall(L, L->top - n);
514 }
515 
516 
517 static void unroll (lua_State *L, void *ud) {
518   UNUSED(ud);
519   for (;;) {
520     if (L->ci == &L->base_ci)  /* stack is empty? */
521       return;  /* coroutine finished normally */
522     if (!isLua(L->ci))  /* C function? */
523       finishCcall(L);
524     else {  /* Lua function */
525       luaV_finishOp(L);  /* finish interrupted instruction */
526       luaV_execute(L);  /* execute down to higher C 'boundary' */
527     }
528   }
529 }
530 
531 
532 /*
533 ** check whether thread has a suspended protected call
534 */
535 static CallInfo *findpcall (lua_State *L) {
536   CallInfo *ci;
537   for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
538     if (ci->callstatus & CIST_YPCALL)
539       return ci;
540   }
541   return NULL;  /* no pending pcall */
542 }
543 
544 
545 static int recover (lua_State *L, int status) {
546   StkId oldtop;
547   CallInfo *ci = findpcall(L);
548   if (ci == NULL) return 0;  /* no recovery point */
549   /* "finish" luaD_pcall */
550   oldtop = restorestack(L, ci->extra);
551   luaF_close(L, oldtop);
552   seterrorobj(L, status, oldtop);
553   L->ci = ci;
554   L->allowhook = ci->u.c.old_allowhook;
555   L->nny = 0;  /* should be zero to be yieldable */
556   luaD_shrinkstack(L);
557   L->errfunc = ci->u.c.old_errfunc;
558   ci->callstatus |= CIST_STAT;  /* call has error status */
559   ci->u.c.status = status;  /* (here it is) */
560   return 1;  /* continue running the coroutine */
561 }
562 
563 
564 /*
565 ** signal an error in the call to 'resume', not in the execution of the
566 ** coroutine itself. (Such errors should not be handled by any coroutine
567 ** error handler and should not kill the coroutine.)
568 */
569 static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
570   L->top = firstArg;  /* remove args from the stack */
571   setsvalue2s(L, L->top, luaS_new(L, msg));  /* push error message */
572   api_incr_top(L);
573   luaD_throw(L, -1);  /* jump back to 'lua_resume' */
574 }
575 
576 
577 /*
578 ** do the work for 'lua_resume' in protected mode
579 */
580 static void resume_cb (lua_State *L, void *ud) {
581   int nCcalls = L->nCcalls;
582   StkId firstArg = cast(StkId, ud);
583   CallInfo *ci = L->ci;
584   if (nCcalls >= LUAI_MAXCCALLS)
585     resume_error(L, "C stack overflow", firstArg);
586   if (L->status == LUA_OK) {  /* may be starting a coroutine */
587     if (ci != &L->base_ci)  /* not in base level? */
588       resume_error(L, "cannot resume non-suspended coroutine", firstArg);
589     /* coroutine is in base level; start running it */
590     if (!luaD_precall(L, firstArg - 1, LUA_MULTRET))  /* Lua function? */
591       luaV_execute(L);  /* call it */
592   }
593   else if (L->status != LUA_YIELD)
594     resume_error(L, "cannot resume dead coroutine", firstArg);
595   else {  /* resuming from previous yield */
596     L->status = LUA_OK;
597     ci->func = restorestack(L, ci->extra);
598     if (isLua(ci))  /* yielded inside a hook? */
599       luaV_execute(L);  /* just continue running Lua code */
600     else {  /* 'common' yield */
601       if (ci->u.c.k != NULL) {  /* does it have a continuation? */
602         int n;
603         ci->u.c.status = LUA_YIELD;  /* 'default' status */
604         ci->callstatus |= CIST_YIELDED;
605         lua_unlock(L);
606         n = (*ci->u.c.k)(L);  /* call continuation */
607         lua_lock(L);
608         api_checknelems(L, n);
609         firstArg = L->top - n;  /* yield results come from continuation */
610       }
611       luaD_poscall(L, firstArg);  /* finish 'luaD_precall' */
612     }
613     unroll(L, NULL);
614   }
615   lua_assert(nCcalls == L->nCcalls);
616 }
617 
618 
619 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
620   int status;
621   int oldnny = L->nny;  /* save 'nny' */
622   lua_lock(L);
623   luai_userstateresume(L, nargs);
624   L->nCcalls = (from) ? from->nCcalls + 1 : 1;
625   L->nny = 0;  /* allow yields */
626   api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
627   status = luaD_rawrunprotected(L, resume_cb, L->top - nargs);
628   if (status == -1)  /* error calling 'lua_resume'? */
629     status = LUA_ERRRUN;
630   else {  /* yield or regular error */
631     while (status != LUA_OK && status != LUA_YIELD) {  /* error? */
632       if (recover(L, status))  /* recover point? */
633         status = luaD_rawrunprotected(L, unroll, NULL);  /* run continuation */
634       else {  /* unrecoverable error */
635         L->status = cast_byte(status);  /* mark thread as `dead' */
636         seterrorobj(L, status, L->top);
637         L->ci->top = L->top;
638         break;
639       }
640     }
641     lua_assert(status == L->status);
642   }
643   L->nny = oldnny;  /* restore 'nny' */
644   L->nCcalls--;
645   lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
646   lua_unlock(L);
647   return status;
648 }
649 
650 
651 LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) {
652   CallInfo *ci = L->ci;
653   luai_userstateyield(L, nresults);
654   lua_lock(L);
655   api_checknelems(L, nresults);
656   if (L->nny > 0) {
657     if (L != G(L)->mainthread)
658       luaG_runerror(L, "attempt to yield across a C-call boundary");
659     else
660       luaG_runerror(L, "attempt to yield from outside a coroutine");
661   }
662   L->status = LUA_YIELD;
663   ci->extra = savestack(L, ci->func);  /* save current 'func' */
664   if (isLua(ci)) {  /* inside a hook? */
665     api_check(L, k == NULL, "hooks cannot continue after yielding");
666   }
667   else {
668     if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
669       ci->u.c.ctx = ctx;  /* save context */
670     ci->func = L->top - nresults - 1;  /* protect stack below results */
671     luaD_throw(L, LUA_YIELD);
672   }
673   lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */
674   lua_unlock(L);
675   return 0;  /* return to 'luaD_hook' */
676 }
677 
678 
679 int luaD_pcall (lua_State *L, Pfunc func, void *u,
680                 ptrdiff_t old_top, ptrdiff_t ef) {
681   int status;
682   CallInfo *old_ci = L->ci;
683   lu_byte old_allowhooks = L->allowhook;
684   unsigned short old_nny = L->nny;
685   ptrdiff_t old_errfunc = L->errfunc;
686   L->errfunc = ef;
687   status = luaD_rawrunprotected(L, func, u);
688   if (status != LUA_OK) {  /* an error occurred? */
689     StkId oldtop = restorestack(L, old_top);
690     luaF_close(L, oldtop);  /* close possible pending closures */
691     seterrorobj(L, status, oldtop);
692     L->ci = old_ci;
693     L->allowhook = old_allowhooks;
694     L->nny = old_nny;
695     luaD_shrinkstack(L);
696   }
697   L->errfunc = old_errfunc;
698   return status;
699 }
700 
701 
702 
703 /*
704 ** Execute a protected parser.
705 */
706 struct SParser {  /* data to `f_parser' */
707   ZIO *z;
708   Mbuffer buff;  /* dynamic structure used by the scanner */
709   Dyndata dyd;  /* dynamic structures used by the parser */
710   const char *mode;
711   const char *name;
712 };
713 
714 
715 static void checkmode (lua_State *L, const char *mode, const char *x) {
716   if (mode && strchr(mode, x[0]) == NULL) {
717     luaO_pushfstring(L,
718        "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
719     luaD_throw(L, LUA_ERRSYNTAX);
720   }
721 }
722 
723 
724 static void f_parser (lua_State *L, void *ud) {
725   int i;
726   Closure *cl;
727   struct SParser *p = cast(struct SParser *, ud);
728   int c = zgetc(p->z);  /* read first character */
729   lua_assert(c != LUA_SIGNATURE[0]);	/* binary not supported */
730   checkmode(L, p->mode, "text");
731   cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
732   lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
733   for (i = 0; i < cl->l.nupvalues; i++) {  /* initialize upvalues */
734     UpVal *up = luaF_newupval(L);
735     cl->l.upvals[i] = up;
736     luaC_objbarrier(L, cl, up);
737   }
738 }
739 
740 
741 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
742                                         const char *mode) {
743   struct SParser p;
744   int status;
745   L->nny++;  /* cannot yield during parsing */
746   p.z = z; p.name = name; p.mode = mode;
747   p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
748   p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
749   p.dyd.label.arr = NULL; p.dyd.label.size = 0;
750   luaZ_initbuffer(L, &p.buff);
751   status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
752   luaZ_freebuffer(L, &p.buff);
753   luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
754   luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
755   luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
756   L->nny--;
757   return status;
758 }
759