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