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