xref: /freebsd/contrib/lua/src/ldo.c (revision 3068d706eabe99f930fb01d3cbfd74ff1f0eb5a2)
1 /*
2 ** $Id: ldo.c $
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 
luaD_seterrorobj(lua_State * L,int errcode,StkId oldtop)91 void luaD_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_OK: {  /* special case only for closing upvalues */
98       setnilvalue(s2v(oldtop));  /* no error message */
99       break;
100     }
101     default: {
102       lua_assert(errorstatus(errcode));  /* real error */
103       setobjs2s(L, oldtop, L->top.p - 1);  /* error message on current top */
104       break;
105     }
106   }
107   L->top.p = oldtop + 1;
108 }
109 
110 
luaD_throw(lua_State * L,int errcode)111 l_noret luaD_throw (lua_State *L, int errcode) {
112   if (L->errorJmp) {  /* thread has an error handler? */
113     L->errorJmp->status = errcode;  /* set status */
114     LUAI_THROW(L, L->errorJmp);  /* jump to it */
115   }
116   else {  /* thread has no error handler */
117     global_State *g = G(L);
118     errcode = luaE_resetthread(L, errcode);  /* close all upvalues */
119     L->status = errcode;
120     if (g->mainthread->errorJmp) {  /* main thread has a handler? */
121       setobjs2s(L, g->mainthread->top.p++, L->top.p - 1);  /* copy error obj. */
122       luaD_throw(g->mainthread, errcode);  /* re-throw in main thread */
123     }
124     else {  /* no handler at all; abort */
125       if (g->panic) {  /* panic function? */
126         lua_unlock(L);
127         g->panic(L);  /* call panic function (last chance to jump out) */
128       }
129       abort();
130     }
131   }
132 }
133 
134 
luaD_rawrunprotected(lua_State * L,Pfunc f,void * ud)135 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
136   l_uint32 oldnCcalls = L->nCcalls;
137   struct lua_longjmp lj;
138   lj.status = LUA_OK;
139   lj.previous = L->errorJmp;  /* chain new error handler */
140   L->errorJmp = &lj;
141   LUAI_TRY(L, &lj,
142     (*f)(L, ud);
143   );
144   L->errorJmp = lj.previous;  /* restore old error handler */
145   L->nCcalls = oldnCcalls;
146   return lj.status;
147 }
148 
149 /* }====================================================== */
150 
151 
152 /*
153 ** {==================================================================
154 ** Stack reallocation
155 ** ===================================================================
156 */
157 
158 
159 /*
160 ** Change all pointers to the stack into offsets.
161 */
relstack(lua_State * L)162 static void relstack (lua_State *L) {
163   CallInfo *ci;
164   UpVal *up;
165   L->top.offset = savestack(L, L->top.p);
166   L->tbclist.offset = savestack(L, L->tbclist.p);
167   for (up = L->openupval; up != NULL; up = up->u.open.next)
168     up->v.offset = savestack(L, uplevel(up));
169   for (ci = L->ci; ci != NULL; ci = ci->previous) {
170     ci->top.offset = savestack(L, ci->top.p);
171     ci->func.offset = savestack(L, ci->func.p);
172   }
173 }
174 
175 
176 /*
177 ** Change back all offsets into pointers.
178 */
correctstack(lua_State * L)179 static void correctstack (lua_State *L) {
180   CallInfo *ci;
181   UpVal *up;
182   L->top.p = restorestack(L, L->top.offset);
183   L->tbclist.p = restorestack(L, L->tbclist.offset);
184   for (up = L->openupval; up != NULL; up = up->u.open.next)
185     up->v.p = s2v(restorestack(L, up->v.offset));
186   for (ci = L->ci; ci != NULL; ci = ci->previous) {
187     ci->top.p = restorestack(L, ci->top.offset);
188     ci->func.p = restorestack(L, ci->func.offset);
189     if (isLua(ci))
190       ci->u.l.trap = 1;  /* signal to update 'trap' in 'luaV_execute' */
191   }
192 }
193 
194 
195 /* some space for error handling */
196 #define ERRORSTACKSIZE	(LUAI_MAXSTACK + 200)
197 
198 
199 /* raise an error while running the message handler */
luaD_errerr(lua_State * L)200 l_noret luaD_errerr (lua_State *L) {
201   TString *msg = luaS_newliteral(L, "error in error handling");
202   setsvalue2s(L, L->top.p, msg);
203   L->top.p++;  /* assume EXTRA_STACK */
204   luaD_throw(L, LUA_ERRERR);
205 }
206 
207 
208 /*
209 ** Reallocate the stack to a new size, correcting all pointers into it.
210 ** In ISO C, any pointer use after the pointer has been deallocated is
211 ** undefined behavior. So, before the reallocation, all pointers are
212 ** changed to offsets, and after the reallocation they are changed back
213 ** to pointers. As during the reallocation the pointers are invalid, the
214 ** reallocation cannot run emergency collections.
215 **
216 ** In case of allocation error, raise an error or return false according
217 ** to 'raiseerror'.
218 */
luaD_reallocstack(lua_State * L,int newsize,int raiseerror)219 int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
220   int oldsize = stacksize(L);
221   int i;
222   StkId newstack;
223   int oldgcstop = G(L)->gcstopem;
224   lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
225   relstack(L);  /* change pointers to offsets */
226   G(L)->gcstopem = 1;  /* stop emergency collection */
227   newstack = luaM_reallocvector(L, L->stack.p, oldsize + EXTRA_STACK,
228                                    newsize + EXTRA_STACK, StackValue);
229   G(L)->gcstopem = oldgcstop;  /* restore emergency collection */
230   if (l_unlikely(newstack == NULL)) {  /* reallocation failed? */
231     correctstack(L);  /* change offsets back to pointers */
232     if (raiseerror)
233       luaM_error(L);
234     else return 0;  /* do not raise an error */
235   }
236   L->stack.p = newstack;
237   correctstack(L);  /* change offsets back to pointers */
238   L->stack_last.p = L->stack.p + newsize;
239   for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
240     setnilvalue(s2v(newstack + i)); /* erase new segment */
241   return 1;
242 }
243 
244 
245 /*
246 ** Try to grow the stack by at least 'n' elements. When 'raiseerror'
247 ** is true, raises any error; otherwise, return 0 in case of errors.
248 */
luaD_growstack(lua_State * L,int n,int raiseerror)249 int luaD_growstack (lua_State *L, int n, int raiseerror) {
250   int size = stacksize(L);
251   if (l_unlikely(size > LUAI_MAXSTACK)) {
252     /* if stack is larger than maximum, thread is already using the
253        extra space reserved for errors, that is, thread is handling
254        a stack error; cannot grow further than that. */
255     lua_assert(stacksize(L) == ERRORSTACKSIZE);
256     if (raiseerror)
257       luaD_errerr(L);  /* error inside message handler */
258     return 0;  /* if not 'raiseerror', just signal it */
259   }
260   else if (n < LUAI_MAXSTACK) {  /* avoids arithmetic overflows */
261     int newsize = 2 * size;  /* tentative new size */
262     int needed = cast_int(L->top.p - L->stack.p) + n;
263     if (newsize > LUAI_MAXSTACK)  /* cannot cross the limit */
264       newsize = LUAI_MAXSTACK;
265     if (newsize < needed)  /* but must respect what was asked for */
266       newsize = needed;
267     if (l_likely(newsize <= LUAI_MAXSTACK))
268       return luaD_reallocstack(L, newsize, raiseerror);
269   }
270   /* else stack overflow */
271   /* add extra size to be able to handle the error message */
272   luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
273   if (raiseerror)
274     luaG_runerror(L, "stack overflow");
275   return 0;
276 }
277 
278 
279 /*
280 ** Compute how much of the stack is being used, by computing the
281 ** maximum top of all call frames in the stack and the current top.
282 */
stackinuse(lua_State * L)283 static int stackinuse (lua_State *L) {
284   CallInfo *ci;
285   int res;
286   StkId lim = L->top.p;
287   for (ci = L->ci; ci != NULL; ci = ci->previous) {
288     if (lim < ci->top.p) lim = ci->top.p;
289   }
290   lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
291   res = cast_int(lim - L->stack.p) + 1;  /* part of stack in use */
292   if (res < LUA_MINSTACK)
293     res = LUA_MINSTACK;  /* ensure a minimum size */
294   return res;
295 }
296 
297 
298 /*
299 ** If stack size is more than 3 times the current use, reduce that size
300 ** to twice the current use. (So, the final stack size is at most 2/3 the
301 ** previous size, and half of its entries are empty.)
302 ** As a particular case, if stack was handling a stack overflow and now
303 ** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
304 ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
305 ** will be reduced to a "regular" size.
306 */
luaD_shrinkstack(lua_State * L)307 void luaD_shrinkstack (lua_State *L) {
308   int inuse = stackinuse(L);
309   int max = (inuse > LUAI_MAXSTACK / 3) ? LUAI_MAXSTACK : inuse * 3;
310   /* if thread is currently not handling a stack overflow and its
311      size is larger than maximum "reasonable" size, shrink it */
312   if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) {
313     int nsize = (inuse > LUAI_MAXSTACK / 2) ? LUAI_MAXSTACK : inuse * 2;
314     luaD_reallocstack(L, nsize, 0);  /* ok if that fails */
315   }
316   else  /* don't change stack */
317     condmovestack(L,{},{});  /* (change only for debugging) */
318   luaE_shrinkCI(L);  /* shrink CI list */
319 }
320 
321 
luaD_inctop(lua_State * L)322 void luaD_inctop (lua_State *L) {
323   luaD_checkstack(L, 1);
324   L->top.p++;
325 }
326 
327 /* }================================================================== */
328 
329 
330 /*
331 ** Call a hook for the given event. Make sure there is a hook to be
332 ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
333 ** function, can be changed asynchronously by signals.)
334 */
luaD_hook(lua_State * L,int event,int line,int ftransfer,int ntransfer)335 void luaD_hook (lua_State *L, int event, int line,
336                               int ftransfer, int ntransfer) {
337   lua_Hook hook = L->hook;
338   if (hook && L->allowhook) {  /* make sure there is a hook */
339     int mask = CIST_HOOKED;
340     CallInfo *ci = L->ci;
341     ptrdiff_t top = savestack(L, L->top.p);  /* preserve original 'top' */
342     ptrdiff_t ci_top = savestack(L, ci->top.p);  /* idem for 'ci->top' */
343     lua_Debug ar;
344     ar.event = event;
345     ar.currentline = line;
346     ar.i_ci = ci;
347     if (ntransfer != 0) {
348       mask |= CIST_TRAN;  /* 'ci' has transfer information */
349       ci->u2.transferinfo.ftransfer = ftransfer;
350       ci->u2.transferinfo.ntransfer = ntransfer;
351     }
352     if (isLua(ci) && L->top.p < ci->top.p)
353       L->top.p = ci->top.p;  /* protect entire activation register */
354     luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
355     if (ci->top.p < L->top.p + LUA_MINSTACK)
356       ci->top.p = L->top.p + LUA_MINSTACK;
357     L->allowhook = 0;  /* cannot call hooks inside a hook */
358     ci->callstatus |= mask;
359     lua_unlock(L);
360     (*hook)(L, &ar);
361     lua_lock(L);
362     lua_assert(!L->allowhook);
363     L->allowhook = 1;
364     ci->top.p = restorestack(L, ci_top);
365     L->top.p = restorestack(L, top);
366     ci->callstatus &= ~mask;
367   }
368 }
369 
370 
371 /*
372 ** Executes a call hook for Lua functions. This function is called
373 ** whenever 'hookmask' is not zero, so it checks whether call hooks are
374 ** active.
375 */
luaD_hookcall(lua_State * L,CallInfo * ci)376 void luaD_hookcall (lua_State *L, CallInfo *ci) {
377   L->oldpc = 0;  /* set 'oldpc' for new function */
378   if (L->hookmask & LUA_MASKCALL) {  /* is call hook on? */
379     int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
380                                              : LUA_HOOKCALL;
381     Proto *p = ci_func(ci)->p;
382     ci->u.l.savedpc++;  /* hooks assume 'pc' is already incremented */
383     luaD_hook(L, event, -1, 1, p->numparams);
384     ci->u.l.savedpc--;  /* correct 'pc' */
385   }
386 }
387 
388 
389 /*
390 ** Executes a return hook for Lua and C functions and sets/corrects
391 ** 'oldpc'. (Note that this correction is needed by the line hook, so it
392 ** is done even when return hooks are off.)
393 */
rethook(lua_State * L,CallInfo * ci,int nres)394 static void rethook (lua_State *L, CallInfo *ci, int nres) {
395   if (L->hookmask & LUA_MASKRET) {  /* is return hook on? */
396     StkId firstres = L->top.p - nres;  /* index of first result */
397     int delta = 0;  /* correction for vararg functions */
398     int ftransfer;
399     if (isLua(ci)) {
400       Proto *p = ci_func(ci)->p;
401       if (p->is_vararg)
402         delta = ci->u.l.nextraargs + p->numparams + 1;
403     }
404     ci->func.p += delta;  /* if vararg, back to virtual 'func' */
405     ftransfer = cast(unsigned short, firstres - ci->func.p);
406     luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres);  /* call it */
407     ci->func.p -= delta;
408   }
409   if (isLua(ci = ci->previous))
410     L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p);  /* set 'oldpc' */
411 }
412 
413 
414 /*
415 ** Check whether 'func' has a '__call' metafield. If so, put it in the
416 ** stack, below original 'func', so that 'luaD_precall' can call it. Raise
417 ** an error if there is no '__call' metafield.
418 */
tryfuncTM(lua_State * L,StkId func)419 static StkId tryfuncTM (lua_State *L, StkId func) {
420   const TValue *tm;
421   StkId p;
422   checkstackGCp(L, 1, func);  /* space for metamethod */
423   tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);  /* (after previous GC) */
424   if (l_unlikely(ttisnil(tm)))
425     luaG_callerror(L, s2v(func));  /* nothing to call */
426   for (p = L->top.p; p > func; p--)  /* open space for metamethod */
427     setobjs2s(L, p, p-1);
428   L->top.p++;  /* stack space pre-allocated by the caller */
429   setobj2s(L, func, tm);  /* metamethod is the new function to be called */
430   return func;
431 }
432 
433 
434 /*
435 ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
436 ** Handle most typical cases (zero results for commands, one result for
437 ** expressions, multiple results for tail calls/single parameters)
438 ** separated.
439 */
moveresults(lua_State * L,StkId res,int nres,int wanted)440 l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
441   StkId firstresult;
442   int i;
443   switch (wanted) {  /* handle typical cases separately */
444     case 0:  /* no values needed */
445       L->top.p = res;
446       return;
447     case 1:  /* one value needed */
448       if (nres == 0)   /* no results? */
449         setnilvalue(s2v(res));  /* adjust with nil */
450       else  /* at least one result */
451         setobjs2s(L, res, L->top.p - nres);  /* move it to proper place */
452       L->top.p = res + 1;
453       return;
454     case LUA_MULTRET:
455       wanted = nres;  /* we want all results */
456       break;
457     default:  /* two/more results and/or to-be-closed variables */
458       if (hastocloseCfunc(wanted)) {  /* to-be-closed variables? */
459         L->ci->callstatus |= CIST_CLSRET;  /* in case of yields */
460         L->ci->u2.nres = nres;
461         res = luaF_close(L, res, CLOSEKTOP, 1);
462         L->ci->callstatus &= ~CIST_CLSRET;
463         if (L->hookmask) {  /* if needed, call hook after '__close's */
464           ptrdiff_t savedres = savestack(L, res);
465           rethook(L, L->ci, nres);
466           res = restorestack(L, savedres);  /* hook can move stack */
467         }
468         wanted = decodeNresults(wanted);
469         if (wanted == LUA_MULTRET)
470           wanted = nres;  /* we want all results */
471       }
472       break;
473   }
474   /* generic case */
475   firstresult = L->top.p - nres;  /* index of first result */
476   if (nres > wanted)  /* extra results? */
477     nres = wanted;  /* don't need them */
478   for (i = 0; i < nres; i++)  /* move all results to correct place */
479     setobjs2s(L, res + i, firstresult + i);
480   for (; i < wanted; i++)  /* complete wanted number of results */
481     setnilvalue(s2v(res + i));
482   L->top.p = res + wanted;  /* top points after the last result */
483 }
484 
485 
486 /*
487 ** Finishes a function call: calls hook if necessary, moves current
488 ** number of results to proper place, and returns to previous call
489 ** info. If function has to close variables, hook must be called after
490 ** that.
491 */
luaD_poscall(lua_State * L,CallInfo * ci,int nres)492 void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
493   int wanted = ci->nresults;
494   if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
495     rethook(L, ci, nres);
496   /* move results to proper place */
497   moveresults(L, ci->func.p, nres, wanted);
498   /* function cannot be in any of these cases when returning */
499   lua_assert(!(ci->callstatus &
500         (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
501   L->ci = ci->previous;  /* back to caller (after closing variables) */
502 }
503 
504 
505 
506 #define next_ci(L)  (L->ci->next ? L->ci->next : luaE_extendCI(L))
507 
508 
prepCallInfo(lua_State * L,StkId func,int nret,int mask,StkId top)509 l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
510                                                 int mask, StkId top) {
511   CallInfo *ci = L->ci = next_ci(L);  /* new frame */
512   ci->func.p = func;
513   ci->nresults = nret;
514   ci->callstatus = mask;
515   ci->top.p = top;
516   return ci;
517 }
518 
519 
520 /*
521 ** precall for C functions
522 */
precallC(lua_State * L,StkId func,int nresults,lua_CFunction f)523 l_sinline int precallC (lua_State *L, StkId func, int nresults,
524                                             lua_CFunction f) {
525   int n;  /* number of returns */
526   CallInfo *ci;
527   checkstackGCp(L, LUA_MINSTACK, func);  /* ensure minimum stack size */
528   L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
529                                L->top.p + LUA_MINSTACK);
530   lua_assert(ci->top.p <= L->stack_last.p);
531   if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
532     int narg = cast_int(L->top.p - func) - 1;
533     luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
534   }
535   lua_unlock(L);
536   n = (*f)(L);  /* do the actual call */
537   lua_lock(L);
538   api_checknelems(L, n);
539   luaD_poscall(L, ci, n);
540   return n;
541 }
542 
543 
544 /*
545 ** Prepare a function for a tail call, building its call info on top
546 ** of the current call info. 'narg1' is the number of arguments plus 1
547 ** (so that it includes the function itself). Return the number of
548 ** results, if it was a C function, or -1 for a Lua function.
549 */
luaD_pretailcall(lua_State * L,CallInfo * ci,StkId func,int narg1,int delta)550 int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
551                                     int narg1, int delta) {
552  retry:
553   switch (ttypetag(s2v(func))) {
554     case LUA_VCCL:  /* C closure */
555       return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);
556     case LUA_VLCF:  /* light C function */
557       return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));
558     case LUA_VLCL: {  /* Lua function */
559       Proto *p = clLvalue(s2v(func))->p;
560       int fsize = p->maxstacksize;  /* frame size */
561       int nfixparams = p->numparams;
562       int i;
563       checkstackGCp(L, fsize - delta, func);
564       ci->func.p -= delta;  /* restore 'func' (if vararg) */
565       for (i = 0; i < narg1; i++)  /* move down function and arguments */
566         setobjs2s(L, ci->func.p + i, func + i);
567       func = ci->func.p;  /* moved-down function */
568       for (; narg1 <= nfixparams; narg1++)
569         setnilvalue(s2v(func + narg1));  /* complete missing arguments */
570       ci->top.p = func + 1 + fsize;  /* top for new function */
571       lua_assert(ci->top.p <= L->stack_last.p);
572       ci->u.l.savedpc = p->code;  /* starting point */
573       ci->callstatus |= CIST_TAIL;
574       L->top.p = func + narg1;  /* set top */
575       return -1;
576     }
577     default: {  /* not a function */
578       func = tryfuncTM(L, func);  /* try to get '__call' metamethod */
579       /* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */
580       narg1++;
581       goto retry;  /* try again */
582     }
583   }
584 }
585 
586 
587 /*
588 ** Prepares the call to a function (C or Lua). For C functions, also do
589 ** the call. The function to be called is at '*func'.  The arguments
590 ** are on the stack, right after the function.  Returns the CallInfo
591 ** to be executed, if it was a Lua function. Otherwise (a C function)
592 ** returns NULL, with all the results on the stack, starting at the
593 ** original function position.
594 */
luaD_precall(lua_State * L,StkId func,int nresults)595 CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
596  retry:
597   switch (ttypetag(s2v(func))) {
598     case LUA_VCCL:  /* C closure */
599       precallC(L, func, nresults, clCvalue(s2v(func))->f);
600       return NULL;
601     case LUA_VLCF:  /* light C function */
602       precallC(L, func, nresults, fvalue(s2v(func)));
603       return NULL;
604     case LUA_VLCL: {  /* Lua function */
605       CallInfo *ci;
606       Proto *p = clLvalue(s2v(func))->p;
607       int narg = cast_int(L->top.p - func) - 1;  /* number of real arguments */
608       int nfixparams = p->numparams;
609       int fsize = p->maxstacksize;  /* frame size */
610       checkstackGCp(L, fsize, func);
611       L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
612       ci->u.l.savedpc = p->code;  /* starting point */
613       for (; narg < nfixparams; narg++)
614         setnilvalue(s2v(L->top.p++));  /* complete missing arguments */
615       lua_assert(ci->top.p <= L->stack_last.p);
616       return ci;
617     }
618     default: {  /* not a function */
619       func = tryfuncTM(L, func);  /* try to get '__call' metamethod */
620       /* return luaD_precall(L, func, nresults); */
621       goto retry;  /* try again with metamethod */
622     }
623   }
624 }
625 
626 
627 /*
628 ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
629 ** number of recursive invocations in the C stack) or nyci (the same
630 ** plus increment number of non-yieldable calls).
631 ** This function can be called with some use of EXTRA_STACK, so it should
632 ** check the stack before doing anything else. 'luaD_precall' already
633 ** does that.
634 */
ccall(lua_State * L,StkId func,int nResults,l_uint32 inc)635 l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
636   CallInfo *ci;
637   L->nCcalls += inc;
638   if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
639     checkstackp(L, 0, func);  /* free any use of EXTRA_STACK */
640     luaE_checkcstack(L);
641   }
642   if ((ci = luaD_precall(L, func, nResults)) != NULL) {  /* Lua function? */
643     ci->callstatus = CIST_FRESH;  /* mark that it is a "fresh" execute */
644     luaV_execute(L, ci);  /* call it */
645   }
646   L->nCcalls -= inc;
647 }
648 
649 
650 /*
651 ** External interface for 'ccall'
652 */
luaD_call(lua_State * L,StkId func,int nResults)653 void luaD_call (lua_State *L, StkId func, int nResults) {
654   ccall(L, func, nResults, 1);
655 }
656 
657 
658 /*
659 ** Similar to 'luaD_call', but does not allow yields during the call.
660 */
luaD_callnoyield(lua_State * L,StkId func,int nResults)661 void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
662   ccall(L, func, nResults, nyci);
663 }
664 
665 
666 /*
667 ** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
668 ** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
669 ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
670 ** If a '__close' method yields here, eventually control will be back
671 ** to 'finishCcall' (when that '__close' method finally returns) and
672 ** 'finishpcallk' will run again and close any still pending '__close'
673 ** methods. Similarly, if a '__close' method errs, 'precover' calls
674 ** 'unroll' which calls ''finishCcall' and we are back here again, to
675 ** close any pending '__close' methods.
676 ** Note that, up to the call to 'luaF_close', the corresponding
677 ** 'CallInfo' is not modified, so that this repeated run works like the
678 ** first one (except that it has at least one less '__close' to do). In
679 ** particular, field CIST_RECST preserves the error status across these
680 ** multiple runs, changing only if there is a new error.
681 */
finishpcallk(lua_State * L,CallInfo * ci)682 static int finishpcallk (lua_State *L,  CallInfo *ci) {
683   int status = getcistrecst(ci);  /* get original status */
684   if (l_likely(status == LUA_OK))  /* no error? */
685     status = LUA_YIELD;  /* was interrupted by an yield */
686   else {  /* error */
687     StkId func = restorestack(L, ci->u2.funcidx);
688     L->allowhook = getoah(ci->callstatus);  /* restore 'allowhook' */
689     func = luaF_close(L, func, status, 1);  /* can yield or raise an error */
690     luaD_seterrorobj(L, status, func);
691     luaD_shrinkstack(L);   /* restore stack size in case of overflow */
692     setcistrecst(ci, LUA_OK);  /* clear original status */
693   }
694   ci->callstatus &= ~CIST_YPCALL;
695   L->errfunc = ci->u.c.old_errfunc;
696   /* if it is here, there were errors or yields; unlike 'lua_pcallk',
697      do not change status */
698   return status;
699 }
700 
701 
702 /*
703 ** Completes the execution of a C function interrupted by an yield.
704 ** The interruption must have happened while the function was either
705 ** closing its tbc variables in 'moveresults' or executing
706 ** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
707 ** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
708 ** finishes the interrupted execution of 'lua_pcallk'.  After that, it
709 ** calls the continuation of the interrupted function and finally it
710 ** completes the job of the 'luaD_call' that called the function.  In
711 ** the call to 'adjustresults', we do not know the number of results
712 ** of the function called by 'lua_callk'/'lua_pcallk', so we are
713 ** conservative and use LUA_MULTRET (always adjust).
714 */
finishCcall(lua_State * L,CallInfo * ci)715 static void finishCcall (lua_State *L, CallInfo *ci) {
716   int n;  /* actual number of results from C function */
717   if (ci->callstatus & CIST_CLSRET) {  /* was returning? */
718     lua_assert(hastocloseCfunc(ci->nresults));
719     n = ci->u2.nres;  /* just redo 'luaD_poscall' */
720     /* don't need to reset CIST_CLSRET, as it will be set again anyway */
721   }
722   else {
723     int status = LUA_YIELD;  /* default if there were no errors */
724     /* must have a continuation and must be able to call it */
725     lua_assert(ci->u.c.k != NULL && yieldable(L));
726     if (ci->callstatus & CIST_YPCALL)   /* was inside a 'lua_pcallk'? */
727       status = finishpcallk(L, ci);  /* finish it */
728     adjustresults(L, LUA_MULTRET);  /* finish 'lua_callk' */
729     lua_unlock(L);
730     n = (*ci->u.c.k)(L, status, ci->u.c.ctx);  /* call continuation */
731     lua_lock(L);
732     api_checknelems(L, n);
733   }
734   luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
735 }
736 
737 
738 /*
739 ** Executes "full continuation" (everything in the stack) of a
740 ** previously interrupted coroutine until the stack is empty (or another
741 ** interruption long-jumps out of the loop).
742 */
unroll(lua_State * L,void * ud)743 static void unroll (lua_State *L, void *ud) {
744   CallInfo *ci;
745   UNUSED(ud);
746   while ((ci = L->ci) != &L->base_ci) {  /* something in the stack */
747     if (!isLua(ci))  /* C function? */
748       finishCcall(L, ci);  /* complete its execution */
749     else {  /* Lua function */
750       luaV_finishOp(L);  /* finish interrupted instruction */
751       luaV_execute(L, ci);  /* execute down to higher C 'boundary' */
752     }
753   }
754 }
755 
756 
757 /*
758 ** Try to find a suspended protected call (a "recover point") for the
759 ** given thread.
760 */
findpcall(lua_State * L)761 static CallInfo *findpcall (lua_State *L) {
762   CallInfo *ci;
763   for (ci = L->ci; ci != NULL; ci = ci->previous) {  /* search for a pcall */
764     if (ci->callstatus & CIST_YPCALL)
765       return ci;
766   }
767   return NULL;  /* no pending pcall */
768 }
769 
770 
771 /*
772 ** Signal an error in the call to 'lua_resume', not in the execution
773 ** of the coroutine itself. (Such errors should not be handled by any
774 ** coroutine error handler and should not kill the coroutine.)
775 */
resume_error(lua_State * L,const char * msg,int narg)776 static int resume_error (lua_State *L, const char *msg, int narg) {
777   L->top.p -= narg;  /* remove args from the stack */
778   setsvalue2s(L, L->top.p, luaS_new(L, msg));  /* push error message */
779   api_incr_top(L);
780   lua_unlock(L);
781   return LUA_ERRRUN;
782 }
783 
784 
785 /*
786 ** Do the work for 'lua_resume' in protected mode. Most of the work
787 ** depends on the status of the coroutine: initial state, suspended
788 ** inside a hook, or regularly suspended (optionally with a continuation
789 ** function), plus erroneous cases: non-suspended coroutine or dead
790 ** coroutine.
791 */
resume(lua_State * L,void * ud)792 static void resume (lua_State *L, void *ud) {
793   int n = *(cast(int*, ud));  /* number of arguments */
794   StkId firstArg = L->top.p - n;  /* first argument */
795   CallInfo *ci = L->ci;
796   if (L->status == LUA_OK)  /* starting a coroutine? */
797     ccall(L, firstArg - 1, LUA_MULTRET, 0);  /* just call its body */
798   else {  /* resuming from previous yield */
799     lua_assert(L->status == LUA_YIELD);
800     L->status = LUA_OK;  /* mark that it is running (again) */
801     if (isLua(ci)) {  /* yielded inside a hook? */
802       /* undo increment made by 'luaG_traceexec': instruction was not
803          executed yet */
804       lua_assert(ci->callstatus & CIST_HOOKYIELD);
805       ci->u.l.savedpc--;
806       L->top.p = firstArg;  /* discard arguments */
807       luaV_execute(L, ci);  /* just continue running Lua code */
808     }
809     else {  /* 'common' yield */
810       if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
811         lua_unlock(L);
812         n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
813         lua_lock(L);
814         api_checknelems(L, n);
815       }
816       luaD_poscall(L, ci, n);  /* finish 'luaD_call' */
817     }
818     unroll(L, NULL);  /* run continuation */
819   }
820 }
821 
822 
823 /*
824 ** Unrolls a coroutine in protected mode while there are recoverable
825 ** errors, that is, errors inside a protected call. (Any error
826 ** interrupts 'unroll', and this loop protects it again so it can
827 ** continue.) Stops with a normal end (status == LUA_OK), an yield
828 ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
829 ** find a recover point).
830 */
precover(lua_State * L,int status)831 static int precover (lua_State *L, int status) {
832   CallInfo *ci;
833   while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
834     L->ci = ci;  /* go down to recovery functions */
835     setcistrecst(ci, status);  /* status to finish 'pcall' */
836     status = luaD_rawrunprotected(L, unroll, NULL);
837   }
838   return status;
839 }
840 
841 
lua_resume(lua_State * L,lua_State * from,int nargs,int * nresults)842 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
843                                       int *nresults) {
844   int status;
845   lua_lock(L);
846   if (L->status == LUA_OK) {  /* may be starting a coroutine */
847     if (L->ci != &L->base_ci)  /* not in base level? */
848       return resume_error(L, "cannot resume non-suspended coroutine", nargs);
849     else if (L->top.p - (L->ci->func.p + 1) == nargs)  /* no function? */
850       return resume_error(L, "cannot resume dead coroutine", nargs);
851   }
852   else if (L->status != LUA_YIELD)  /* ended with errors? */
853     return resume_error(L, "cannot resume dead coroutine", nargs);
854   L->nCcalls = (from) ? getCcalls(from) : 0;
855   if (getCcalls(L) >= LUAI_MAXCCALLS)
856     return resume_error(L, "C stack overflow", nargs);
857   L->nCcalls++;
858   luai_userstateresume(L, nargs);
859   api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
860   status = luaD_rawrunprotected(L, resume, &nargs);
861    /* continue running after recoverable errors */
862   status = precover(L, status);
863   if (l_likely(!errorstatus(status)))
864     lua_assert(status == L->status);  /* normal end or yield */
865   else {  /* unrecoverable error */
866     L->status = cast_byte(status);  /* mark thread as 'dead' */
867     luaD_seterrorobj(L, status, L->top.p);  /* push error message */
868     L->ci->top.p = L->top.p;
869   }
870   *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
871                                     : cast_int(L->top.p - (L->ci->func.p + 1));
872   lua_unlock(L);
873   return status;
874 }
875 
876 
lua_isyieldable(lua_State * L)877 LUA_API int lua_isyieldable (lua_State *L) {
878   return yieldable(L);
879 }
880 
881 
lua_yieldk(lua_State * L,int nresults,lua_KContext ctx,lua_KFunction k)882 LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
883                         lua_KFunction k) {
884   CallInfo *ci;
885   luai_userstateyield(L, nresults);
886   lua_lock(L);
887   ci = L->ci;
888   api_checknelems(L, nresults);
889   if (l_unlikely(!yieldable(L))) {
890     if (L != G(L)->mainthread)
891       luaG_runerror(L, "attempt to yield across a C-call boundary");
892     else
893       luaG_runerror(L, "attempt to yield from outside a coroutine");
894   }
895   L->status = LUA_YIELD;
896   ci->u2.nyield = nresults;  /* save number of results */
897   if (isLua(ci)) {  /* inside a hook? */
898     lua_assert(!isLuacode(ci));
899     api_check(L, nresults == 0, "hooks cannot yield values");
900     api_check(L, k == NULL, "hooks cannot continue after yielding");
901   }
902   else {
903     if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
904       ci->u.c.ctx = ctx;  /* save context */
905     luaD_throw(L, LUA_YIELD);
906   }
907   lua_assert(ci->callstatus & CIST_HOOKED);  /* must be inside a hook */
908   lua_unlock(L);
909   return 0;  /* return to 'luaD_hook' */
910 }
911 
912 
913 /*
914 ** Auxiliary structure to call 'luaF_close' in protected mode.
915 */
916 struct CloseP {
917   StkId level;
918   int status;
919 };
920 
921 
922 /*
923 ** Auxiliary function to call 'luaF_close' in protected mode.
924 */
closepaux(lua_State * L,void * ud)925 static void closepaux (lua_State *L, void *ud) {
926   struct CloseP *pcl = cast(struct CloseP *, ud);
927   luaF_close(L, pcl->level, pcl->status, 0);
928 }
929 
930 
931 /*
932 ** Calls 'luaF_close' in protected mode. Return the original status
933 ** or, in case of errors, the new status.
934 */
luaD_closeprotected(lua_State * L,ptrdiff_t level,int status)935 int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
936   CallInfo *old_ci = L->ci;
937   lu_byte old_allowhooks = L->allowhook;
938   for (;;) {  /* keep closing upvalues until no more errors */
939     struct CloseP pcl;
940     pcl.level = restorestack(L, level); pcl.status = status;
941     status = luaD_rawrunprotected(L, &closepaux, &pcl);
942     if (l_likely(status == LUA_OK))  /* no more errors? */
943       return pcl.status;
944     else {  /* an error occurred; restore saved state and repeat */
945       L->ci = old_ci;
946       L->allowhook = old_allowhooks;
947     }
948   }
949 }
950 
951 
952 /*
953 ** Call the C function 'func' in protected mode, restoring basic
954 ** thread information ('allowhook', etc.) and in particular
955 ** its stack level in case of errors.
956 */
luaD_pcall(lua_State * L,Pfunc func,void * u,ptrdiff_t old_top,ptrdiff_t ef)957 int luaD_pcall (lua_State *L, Pfunc func, void *u,
958                 ptrdiff_t old_top, ptrdiff_t ef) {
959   int status;
960   CallInfo *old_ci = L->ci;
961   lu_byte old_allowhooks = L->allowhook;
962   ptrdiff_t old_errfunc = L->errfunc;
963   L->errfunc = ef;
964   status = luaD_rawrunprotected(L, func, u);
965   if (l_unlikely(status != LUA_OK)) {  /* an error occurred? */
966     L->ci = old_ci;
967     L->allowhook = old_allowhooks;
968     status = luaD_closeprotected(L, old_top, status);
969     luaD_seterrorobj(L, status, restorestack(L, old_top));
970     luaD_shrinkstack(L);   /* restore stack size in case of overflow */
971   }
972   L->errfunc = old_errfunc;
973   return status;
974 }
975 
976 
977 
978 /*
979 ** Execute a protected parser.
980 */
981 struct SParser {  /* data to 'f_parser' */
982   ZIO *z;
983   Mbuffer buff;  /* dynamic structure used by the scanner */
984   Dyndata dyd;  /* dynamic structures used by the parser */
985   const char *mode;
986   const char *name;
987 };
988 
989 
checkmode(lua_State * L,const char * mode,const char * x)990 static void checkmode (lua_State *L, const char *mode, const char *x) {
991   if (mode && strchr(mode, x[0]) == NULL) {
992     luaO_pushfstring(L,
993        "attempt to load a %s chunk (mode is '%s')", x, mode);
994     luaD_throw(L, LUA_ERRSYNTAX);
995   }
996 }
997 
998 
f_parser(lua_State * L,void * ud)999 static void f_parser (lua_State *L, void *ud) {
1000   LClosure *cl;
1001   struct SParser *p = cast(struct SParser *, ud);
1002   int c = zgetc(p->z);  /* read first character */
1003   if (c == LUA_SIGNATURE[0]) {
1004     checkmode(L, p->mode, "binary");
1005     cl = luaU_undump(L, p->z, p->name);
1006   }
1007   else {
1008     checkmode(L, p->mode, "text");
1009     cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
1010   }
1011   lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1012   luaF_initupvals(L, cl);
1013 }
1014 
1015 
luaD_protectedparser(lua_State * L,ZIO * z,const char * name,const char * mode)1016 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1017                                         const char *mode) {
1018   struct SParser p;
1019   int status;
1020   incnny(L);  /* cannot yield during parsing */
1021   p.z = z; p.name = name; p.mode = mode;
1022   p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1023   p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1024   p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1025   luaZ_initbuffer(L, &p.buff);
1026   status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1027   luaZ_freebuffer(L, &p.buff);
1028   luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
1029   luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
1030   luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
1031   decnny(L);
1032   return status;
1033 }
1034 
1035 
1036