/*1** $Id: ldo.c $2** Stack and Call structure of Lua3** See Copyright Notice in lua.h4*/56#define ldo_c7#define LUA_CORE89#include "lprefix.h"101112#include <setjmp.h>13#include <stdlib.h>14#include <string.h>1516#include "lua.h"1718#include "lapi.h"19#include "ldebug.h"20#include "ldo.h"21#include "lfunc.h"22#include "lgc.h"23#include "lmem.h"24#include "lobject.h"25#include "lopcodes.h"26#include "lparser.h"27#include "lstate.h"28#include "lstring.h"29#include "ltable.h"30#include "ltm.h"31#include "lundump.h"32#include "lvm.h"33#include "lzio.h"34353637#define errorstatus(s) ((s) > LUA_YIELD)383940/*41** {======================================================42** Error-recovery functions43** =======================================================44*/4546/*47** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By48** default, Lua handles errors with exceptions when compiling as49** C++ code, with _longjmp/_setjmp when asked to use them, and with50** longjmp/setjmp otherwise.51*/52#if !defined(LUAI_THROW) /* { */5354#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */5556/* C++ exceptions */57#define LUAI_THROW(L,c) throw(c)58#define LUAI_TRY(L,c,a) \59try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }60#define luai_jmpbuf int /* dummy variable */6162#elif defined(LUA_USE_POSIX) /* }{ */6364/* in POSIX, try _longjmp/_setjmp (more efficient) */65#define LUAI_THROW(L,c) _longjmp((c)->b, 1)66#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }67#define luai_jmpbuf jmp_buf6869#else /* }{ */7071/* ISO C handling with long jumps */72#define LUAI_THROW(L,c) longjmp((c)->b, 1)73#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }74#define luai_jmpbuf jmp_buf7576#endif /* } */7778#endif /* } */79808182/* chain list of long jump buffers */83struct lua_longjmp {84struct lua_longjmp *previous;85luai_jmpbuf b;86volatile int status; /* error code */87};888990void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {91switch (errcode) {92case LUA_ERRMEM: { /* memory error? */93setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */94break;95}96case LUA_ERRERR: {97setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));98break;99}100case LUA_OK: { /* special case only for closing upvalues */101setnilvalue(s2v(oldtop)); /* no error message */102break;103}104default: {105lua_assert(errorstatus(errcode)); /* real error */106setobjs2s(L, oldtop, L->top.p - 1); /* error message on current top */107break;108}109}110L->top.p = oldtop + 1;111}112113114l_noret luaD_throw (lua_State *L, int errcode) {115if (L->errorJmp) { /* thread has an error handler? */116L->errorJmp->status = errcode; /* set status */117LUAI_THROW(L, L->errorJmp); /* jump to it */118}119else { /* thread has no error handler */120global_State *g = G(L);121errcode = luaE_resetthread(L, errcode); /* close all upvalues */122if (g->mainthread->errorJmp) { /* main thread has a handler? */123setobjs2s(L, g->mainthread->top.p++, L->top.p - 1); /* copy error obj. */124luaD_throw(g->mainthread, errcode); /* re-throw in main thread */125}126else { /* no handler at all; abort */127if (g->panic) { /* panic function? */128lua_unlock(L);129g->panic(L); /* call panic function (last chance to jump out) */130}131abort();132}133}134}135136137int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {138l_uint32 oldnCcalls = L->nCcalls;139struct lua_longjmp lj;140lj.status = LUA_OK;141lj.previous = L->errorJmp; /* chain new error handler */142L->errorJmp = &lj;143LUAI_TRY(L, &lj,144(*f)(L, ud);145);146L->errorJmp = lj.previous; /* restore old error handler */147L->nCcalls = oldnCcalls;148return lj.status;149}150151/* }====================================================== */152153154/*155** {==================================================================156** Stack reallocation157** ===================================================================158*/159160161/*162** Change all pointers to the stack into offsets.163*/164static void relstack (lua_State *L) {165CallInfo *ci;166UpVal *up;167L->top.offset = savestack(L, L->top.p);168L->tbclist.offset = savestack(L, L->tbclist.p);169for (up = L->openupval; up != NULL; up = up->u.open.next)170up->v.offset = savestack(L, uplevel(up));171for (ci = L->ci; ci != NULL; ci = ci->previous) {172ci->top.offset = savestack(L, ci->top.p);173ci->func.offset = savestack(L, ci->func.p);174}175}176177178/*179** Change back all offsets into pointers.180*/181static void correctstack (lua_State *L) {182CallInfo *ci;183UpVal *up;184L->top.p = restorestack(L, L->top.offset);185L->tbclist.p = restorestack(L, L->tbclist.offset);186for (up = L->openupval; up != NULL; up = up->u.open.next)187up->v.p = s2v(restorestack(L, up->v.offset));188for (ci = L->ci; ci != NULL; ci = ci->previous) {189ci->top.p = restorestack(L, ci->top.offset);190ci->func.p = restorestack(L, ci->func.offset);191if (isLua(ci))192ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */193}194}195196197/* some space for error handling */198#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)199200/*201** Reallocate the stack to a new size, correcting all pointers into it.202** In ISO C, any pointer use after the pointer has been deallocated is203** undefined behavior. So, before the reallocation, all pointers are204** changed to offsets, and after the reallocation they are changed back205** to pointers. As during the reallocation the pointers are invalid, the206** reallocation cannot run emergency collections.207**208** In case of allocation error, raise an error or return false according209** to 'raiseerror'.210*/211int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {212int oldsize = stacksize(L);213int i;214StkId newstack;215int oldgcstop = G(L)->gcstopem;216lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);217relstack(L); /* change pointers to offsets */218G(L)->gcstopem = 1; /* stop emergency collection */219newstack = luaM_reallocvector(L, L->stack.p, oldsize + EXTRA_STACK,220newsize + EXTRA_STACK, StackValue);221G(L)->gcstopem = oldgcstop; /* restore emergency collection */222if (l_unlikely(newstack == NULL)) { /* reallocation failed? */223correctstack(L); /* change offsets back to pointers */224if (raiseerror)225luaM_error(L);226else return 0; /* do not raise an error */227}228L->stack.p = newstack;229correctstack(L); /* change offsets back to pointers */230L->stack_last.p = L->stack.p + newsize;231for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)232setnilvalue(s2v(newstack + i)); /* erase new segment */233return 1;234}235236237/*238** Try to grow the stack by at least 'n' elements. When 'raiseerror'239** is true, raises any error; otherwise, return 0 in case of errors.240*/241int luaD_growstack (lua_State *L, int n, int raiseerror) {242int size = stacksize(L);243if (l_unlikely(size > LUAI_MAXSTACK)) {244/* if stack is larger than maximum, thread is already using the245extra space reserved for errors, that is, thread is handling246a stack error; cannot grow further than that. */247lua_assert(stacksize(L) == ERRORSTACKSIZE);248if (raiseerror)249luaD_throw(L, LUA_ERRERR); /* error inside message handler */250return 0; /* if not 'raiseerror', just signal it */251}252else if (n < LUAI_MAXSTACK) { /* avoids arithmetic overflows */253int newsize = 2 * size; /* tentative new size */254int needed = cast_int(L->top.p - L->stack.p) + n;255if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */256newsize = LUAI_MAXSTACK;257if (newsize < needed) /* but must respect what was asked for */258newsize = needed;259if (l_likely(newsize <= LUAI_MAXSTACK))260return luaD_reallocstack(L, newsize, raiseerror);261}262/* else stack overflow */263/* add extra size to be able to handle the error message */264luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);265if (raiseerror)266luaG_runerror(L, "stack overflow");267return 0;268}269270271/*272** Compute how much of the stack is being used, by computing the273** maximum top of all call frames in the stack and the current top.274*/275static int stackinuse (lua_State *L) {276CallInfo *ci;277int res;278StkId lim = L->top.p;279for (ci = L->ci; ci != NULL; ci = ci->previous) {280if (lim < ci->top.p) lim = ci->top.p;281}282lua_assert(lim <= L->stack_last.p + EXTRA_STACK);283res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */284if (res < LUA_MINSTACK)285res = LUA_MINSTACK; /* ensure a minimum size */286return res;287}288289290/*291** If stack size is more than 3 times the current use, reduce that size292** to twice the current use. (So, the final stack size is at most 2/3 the293** previous size, and half of its entries are empty.)294** As a particular case, if stack was handling a stack overflow and now295** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than296** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack297** will be reduced to a "regular" size.298*/299void luaD_shrinkstack (lua_State *L) {300int inuse = stackinuse(L);301int max = (inuse > LUAI_MAXSTACK / 3) ? LUAI_MAXSTACK : inuse * 3;302/* if thread is currently not handling a stack overflow and its303size is larger than maximum "reasonable" size, shrink it */304if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) {305int nsize = (inuse > LUAI_MAXSTACK / 2) ? LUAI_MAXSTACK : inuse * 2;306luaD_reallocstack(L, nsize, 0); /* ok if that fails */307}308else /* don't change stack */309condmovestack(L,{},{}); /* (change only for debugging) */310luaE_shrinkCI(L); /* shrink CI list */311}312313314void luaD_inctop (lua_State *L) {315luaD_checkstack(L, 1);316L->top.p++;317}318319/* }================================================================== */320321322/*323** Call a hook for the given event. Make sure there is a hook to be324** called. (Both 'L->hook' and 'L->hookmask', which trigger this325** function, can be changed asynchronously by signals.)326*/327void luaD_hook (lua_State *L, int event, int line,328int ftransfer, int ntransfer) {329lua_Hook hook = L->hook;330if (hook && L->allowhook) { /* make sure there is a hook */331int mask = CIST_HOOKED;332CallInfo *ci = L->ci;333ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */334ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */335lua_Debug ar;336ar.event = event;337ar.currentline = line;338ar.i_ci = ci;339if (ntransfer != 0) {340mask |= CIST_TRAN; /* 'ci' has transfer information */341ci->u2.transferinfo.ftransfer = ftransfer;342ci->u2.transferinfo.ntransfer = ntransfer;343}344if (isLua(ci) && L->top.p < ci->top.p)345L->top.p = ci->top.p; /* protect entire activation register */346luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */347if (ci->top.p < L->top.p + LUA_MINSTACK)348ci->top.p = L->top.p + LUA_MINSTACK;349L->allowhook = 0; /* cannot call hooks inside a hook */350ci->callstatus |= mask;351lua_unlock(L);352(*hook)(L, &ar);353lua_lock(L);354lua_assert(!L->allowhook);355L->allowhook = 1;356ci->top.p = restorestack(L, ci_top);357L->top.p = restorestack(L, top);358ci->callstatus &= ~mask;359}360}361362363/*364** Executes a call hook for Lua functions. This function is called365** whenever 'hookmask' is not zero, so it checks whether call hooks are366** active.367*/368void luaD_hookcall (lua_State *L, CallInfo *ci) {369L->oldpc = 0; /* set 'oldpc' for new function */370if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */371int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL372: LUA_HOOKCALL;373Proto *p = ci_func(ci)->p;374ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */375luaD_hook(L, event, -1, 1, p->numparams);376ci->u.l.savedpc--; /* correct 'pc' */377}378}379380381/*382** Executes a return hook for Lua and C functions and sets/corrects383** 'oldpc'. (Note that this correction is needed by the line hook, so it384** is done even when return hooks are off.)385*/386static void rethook (lua_State *L, CallInfo *ci, int nres) {387if (L->hookmask & LUA_MASKRET) { /* is return hook on? */388StkId firstres = L->top.p - nres; /* index of first result */389int delta = 0; /* correction for vararg functions */390int ftransfer;391if (isLua(ci)) {392Proto *p = ci_func(ci)->p;393if (p->is_vararg)394delta = ci->u.l.nextraargs + p->numparams + 1;395}396ci->func.p += delta; /* if vararg, back to virtual 'func' */397ftransfer = cast(unsigned short, firstres - ci->func.p);398luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */399ci->func.p -= delta;400}401if (isLua(ci = ci->previous))402L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */403}404405406/*407** Check whether 'func' has a '__call' metafield. If so, put it in the408** stack, below original 'func', so that 'luaD_precall' can call it. Raise409** an error if there is no '__call' metafield.410*/411static StkId tryfuncTM (lua_State *L, StkId func) {412const TValue *tm;413StkId p;414checkstackGCp(L, 1, func); /* space for metamethod */415tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */416if (l_unlikely(ttisnil(tm)))417luaG_callerror(L, s2v(func)); /* nothing to call */418for (p = L->top.p; p > func; p--) /* open space for metamethod */419setobjs2s(L, p, p-1);420L->top.p++; /* stack space pre-allocated by the caller */421setobj2s(L, func, tm); /* metamethod is the new function to be called */422return func;423}424425426/*427** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.428** Handle most typical cases (zero results for commands, one result for429** expressions, multiple results for tail calls/single parameters)430** separated.431*/432l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {433StkId firstresult;434int i;435switch (wanted) { /* handle typical cases separately */436case 0: /* no values needed */437L->top.p = res;438return;439case 1: /* one value needed */440if (nres == 0) /* no results? */441setnilvalue(s2v(res)); /* adjust with nil */442else /* at least one result */443setobjs2s(L, res, L->top.p - nres); /* move it to proper place */444L->top.p = res + 1;445return;446case LUA_MULTRET:447wanted = nres; /* we want all results */448break;449default: /* two/more results and/or to-be-closed variables */450if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */451L->ci->callstatus |= CIST_CLSRET; /* in case of yields */452L->ci->u2.nres = nres;453res = luaF_close(L, res, CLOSEKTOP, 1);454L->ci->callstatus &= ~CIST_CLSRET;455if (L->hookmask) { /* if needed, call hook after '__close's */456ptrdiff_t savedres = savestack(L, res);457rethook(L, L->ci, nres);458res = restorestack(L, savedres); /* hook can move stack */459}460wanted = decodeNresults(wanted);461if (wanted == LUA_MULTRET)462wanted = nres; /* we want all results */463}464break;465}466/* generic case */467firstresult = L->top.p - nres; /* index of first result */468if (nres > wanted) /* extra results? */469nres = wanted; /* don't need them */470for (i = 0; i < nres; i++) /* move all results to correct place */471setobjs2s(L, res + i, firstresult + i);472for (; i < wanted; i++) /* complete wanted number of results */473setnilvalue(s2v(res + i));474L->top.p = res + wanted; /* top points after the last result */475}476477478/*479** Finishes a function call: calls hook if necessary, moves current480** number of results to proper place, and returns to previous call481** info. If function has to close variables, hook must be called after482** that.483*/484void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {485int wanted = ci->nresults;486if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))487rethook(L, ci, nres);488/* move results to proper place */489moveresults(L, ci->func.p, nres, wanted);490/* function cannot be in any of these cases when returning */491lua_assert(!(ci->callstatus &492(CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));493L->ci = ci->previous; /* back to caller (after closing variables) */494}495496497498#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))499500501l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,502int mask, StkId top) {503CallInfo *ci = L->ci = next_ci(L); /* new frame */504ci->func.p = func;505ci->nresults = nret;506ci->callstatus = mask;507ci->top.p = top;508return ci;509}510511512/*513** precall for C functions514*/515l_sinline int precallC (lua_State *L, StkId func, int nresults,516lua_CFunction f) {517int n; /* number of returns */518CallInfo *ci;519checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */520L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,521L->top.p + LUA_MINSTACK);522lua_assert(ci->top.p <= L->stack_last.p);523if (l_unlikely(L->hookmask & LUA_MASKCALL)) {524int narg = cast_int(L->top.p - func) - 1;525luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);526}527lua_unlock(L);528n = (*f)(L); /* do the actual call */529lua_lock(L);530api_checknelems(L, n);531luaD_poscall(L, ci, n);532return n;533}534535536/*537** Prepare a function for a tail call, building its call info on top538** of the current call info. 'narg1' is the number of arguments plus 1539** (so that it includes the function itself). Return the number of540** results, if it was a C function, or -1 for a Lua function.541*/542int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,543int narg1, int delta) {544retry:545switch (ttypetag(s2v(func))) {546case LUA_VCCL: /* C closure */547return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);548case LUA_VLCF: /* light C function */549return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));550case LUA_VLCL: { /* Lua function */551Proto *p = clLvalue(s2v(func))->p;552int fsize = p->maxstacksize; /* frame size */553int nfixparams = p->numparams;554int i;555checkstackGCp(L, fsize - delta, func);556ci->func.p -= delta; /* restore 'func' (if vararg) */557for (i = 0; i < narg1; i++) /* move down function and arguments */558setobjs2s(L, ci->func.p + i, func + i);559func = ci->func.p; /* moved-down function */560for (; narg1 <= nfixparams; narg1++)561setnilvalue(s2v(func + narg1)); /* complete missing arguments */562ci->top.p = func + 1 + fsize; /* top for new function */563lua_assert(ci->top.p <= L->stack_last.p);564ci->u.l.savedpc = p->code; /* starting point */565ci->callstatus |= CIST_TAIL;566L->top.p = func + narg1; /* set top */567return -1;568}569default: { /* not a function */570func = tryfuncTM(L, func); /* try to get '__call' metamethod */571/* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */572narg1++;573goto retry; /* try again */574}575}576}577578579/*580** Prepares the call to a function (C or Lua). For C functions, also do581** the call. The function to be called is at '*func'. The arguments582** are on the stack, right after the function. Returns the CallInfo583** to be executed, if it was a Lua function. Otherwise (a C function)584** returns NULL, with all the results on the stack, starting at the585** original function position.586*/587CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {588retry:589switch (ttypetag(s2v(func))) {590case LUA_VCCL: /* C closure */591precallC(L, func, nresults, clCvalue(s2v(func))->f);592return NULL;593case LUA_VLCF: /* light C function */594precallC(L, func, nresults, fvalue(s2v(func)));595return NULL;596case LUA_VLCL: { /* Lua function */597CallInfo *ci;598Proto *p = clLvalue(s2v(func))->p;599int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */600int nfixparams = p->numparams;601int fsize = p->maxstacksize; /* frame size */602checkstackGCp(L, fsize, func);603L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);604ci->u.l.savedpc = p->code; /* starting point */605for (; narg < nfixparams; narg++)606setnilvalue(s2v(L->top.p++)); /* complete missing arguments */607lua_assert(ci->top.p <= L->stack_last.p);608return ci;609}610default: { /* not a function */611func = tryfuncTM(L, func); /* try to get '__call' metamethod */612/* return luaD_precall(L, func, nresults); */613goto retry; /* try again with metamethod */614}615}616}617618619/*620** Call a function (C or Lua) through C. 'inc' can be 1 (increment621** number of recursive invocations in the C stack) or nyci (the same622** plus increment number of non-yieldable calls).623** This function can be called with some use of EXTRA_STACK, so it should624** check the stack before doing anything else. 'luaD_precall' already625** does that.626*/627l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {628CallInfo *ci;629L->nCcalls += inc;630if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {631checkstackp(L, 0, func); /* free any use of EXTRA_STACK */632luaE_checkcstack(L);633}634if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */635ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */636luaV_execute(L, ci); /* call it */637}638L->nCcalls -= inc;639}640641642/*643** External interface for 'ccall'644*/645void luaD_call (lua_State *L, StkId func, int nResults) {646ccall(L, func, nResults, 1);647}648649650/*651** Similar to 'luaD_call', but does not allow yields during the call.652*/653void luaD_callnoyield (lua_State *L, StkId func, int nResults) {654ccall(L, func, nResults, nyci);655}656657658/*659** Finish the job of 'lua_pcallk' after it was interrupted by an yield.660** (The caller, 'finishCcall', does the final call to 'adjustresults'.)661** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.662** If a '__close' method yields here, eventually control will be back663** to 'finishCcall' (when that '__close' method finally returns) and664** 'finishpcallk' will run again and close any still pending '__close'665** methods. Similarly, if a '__close' method errs, 'precover' calls666** 'unroll' which calls ''finishCcall' and we are back here again, to667** close any pending '__close' methods.668** Note that, up to the call to 'luaF_close', the corresponding669** 'CallInfo' is not modified, so that this repeated run works like the670** first one (except that it has at least one less '__close' to do). In671** particular, field CIST_RECST preserves the error status across these672** multiple runs, changing only if there is a new error.673*/674static int finishpcallk (lua_State *L, CallInfo *ci) {675int status = getcistrecst(ci); /* get original status */676if (l_likely(status == LUA_OK)) /* no error? */677status = LUA_YIELD; /* was interrupted by an yield */678else { /* error */679StkId func = restorestack(L, ci->u2.funcidx);680L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */681func = luaF_close(L, func, status, 1); /* can yield or raise an error */682luaD_seterrorobj(L, status, func);683luaD_shrinkstack(L); /* restore stack size in case of overflow */684setcistrecst(ci, LUA_OK); /* clear original status */685}686ci->callstatus &= ~CIST_YPCALL;687L->errfunc = ci->u.c.old_errfunc;688/* if it is here, there were errors or yields; unlike 'lua_pcallk',689do not change status */690return status;691}692693694/*695** Completes the execution of a C function interrupted by an yield.696** The interruption must have happened while the function was either697** closing its tbc variables in 'moveresults' or executing698** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes699** 'luaD_poscall'. In the second case, the call to 'finishpcallk'700** finishes the interrupted execution of 'lua_pcallk'. After that, it701** calls the continuation of the interrupted function and finally it702** completes the job of the 'luaD_call' that called the function. In703** the call to 'adjustresults', we do not know the number of results704** of the function called by 'lua_callk'/'lua_pcallk', so we are705** conservative and use LUA_MULTRET (always adjust).706*/707static void finishCcall (lua_State *L, CallInfo *ci) {708int n; /* actual number of results from C function */709if (ci->callstatus & CIST_CLSRET) { /* was returning? */710lua_assert(hastocloseCfunc(ci->nresults));711n = ci->u2.nres; /* just redo 'luaD_poscall' */712/* don't need to reset CIST_CLSRET, as it will be set again anyway */713}714else {715int status = LUA_YIELD; /* default if there were no errors */716/* must have a continuation and must be able to call it */717lua_assert(ci->u.c.k != NULL && yieldable(L));718if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */719status = finishpcallk(L, ci); /* finish it */720adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */721lua_unlock(L);722n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */723lua_lock(L);724api_checknelems(L, n);725}726luaD_poscall(L, ci, n); /* finish 'luaD_call' */727}728729730/*731** Executes "full continuation" (everything in the stack) of a732** previously interrupted coroutine until the stack is empty (or another733** interruption long-jumps out of the loop).734*/735static void unroll (lua_State *L, void *ud) {736CallInfo *ci;737UNUSED(ud);738while ((ci = L->ci) != &L->base_ci) { /* something in the stack */739if (!isLua(ci)) /* C function? */740finishCcall(L, ci); /* complete its execution */741else { /* Lua function */742luaV_finishOp(L); /* finish interrupted instruction */743luaV_execute(L, ci); /* execute down to higher C 'boundary' */744}745}746}747748749/*750** Try to find a suspended protected call (a "recover point") for the751** given thread.752*/753static CallInfo *findpcall (lua_State *L) {754CallInfo *ci;755for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */756if (ci->callstatus & CIST_YPCALL)757return ci;758}759return NULL; /* no pending pcall */760}761762763/*764** Signal an error in the call to 'lua_resume', not in the execution765** of the coroutine itself. (Such errors should not be handled by any766** coroutine error handler and should not kill the coroutine.)767*/768static int resume_error (lua_State *L, const char *msg, int narg) {769L->top.p -= narg; /* remove args from the stack */770setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */771api_incr_top(L);772lua_unlock(L);773return LUA_ERRRUN;774}775776777/*778** Do the work for 'lua_resume' in protected mode. Most of the work779** depends on the status of the coroutine: initial state, suspended780** inside a hook, or regularly suspended (optionally with a continuation781** function), plus erroneous cases: non-suspended coroutine or dead782** coroutine.783*/784static void resume (lua_State *L, void *ud) {785int n = *(cast(int*, ud)); /* number of arguments */786StkId firstArg = L->top.p - n; /* first argument */787CallInfo *ci = L->ci;788if (L->status == LUA_OK) /* starting a coroutine? */789ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */790else { /* resuming from previous yield */791lua_assert(L->status == LUA_YIELD);792L->status = LUA_OK; /* mark that it is running (again) */793if (isLua(ci)) { /* yielded inside a hook? */794/* undo increment made by 'luaG_traceexec': instruction was not795executed yet */796lua_assert(ci->callstatus & CIST_HOOKYIELD);797ci->u.l.savedpc--;798L->top.p = firstArg; /* discard arguments */799luaV_execute(L, ci); /* just continue running Lua code */800}801else { /* 'common' yield */802if (ci->u.c.k != NULL) { /* does it have a continuation function? */803lua_unlock(L);804n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */805lua_lock(L);806api_checknelems(L, n);807}808luaD_poscall(L, ci, n); /* finish 'luaD_call' */809}810unroll(L, NULL); /* run continuation */811}812}813814815/*816** Unrolls a coroutine in protected mode while there are recoverable817** errors, that is, errors inside a protected call. (Any error818** interrupts 'unroll', and this loop protects it again so it can819** continue.) Stops with a normal end (status == LUA_OK), an yield820** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't821** find a recover point).822*/823static int precover (lua_State *L, int status) {824CallInfo *ci;825while (errorstatus(status) && (ci = findpcall(L)) != NULL) {826L->ci = ci; /* go down to recovery functions */827setcistrecst(ci, status); /* status to finish 'pcall' */828status = luaD_rawrunprotected(L, unroll, NULL);829}830return status;831}832833834LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,835int *nresults) {836int status;837lua_lock(L);838if (L->status == LUA_OK) { /* may be starting a coroutine */839if (L->ci != &L->base_ci) /* not in base level? */840return resume_error(L, "cannot resume non-suspended coroutine", nargs);841else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */842return resume_error(L, "cannot resume dead coroutine", nargs);843}844else if (L->status != LUA_YIELD) /* ended with errors? */845return resume_error(L, "cannot resume dead coroutine", nargs);846L->nCcalls = (from) ? getCcalls(from) : 0;847if (getCcalls(L) >= LUAI_MAXCCALLS)848return resume_error(L, "C stack overflow", nargs);849L->nCcalls++;850luai_userstateresume(L, nargs);851api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);852status = luaD_rawrunprotected(L, resume, &nargs);853/* continue running after recoverable errors */854status = precover(L, status);855if (l_likely(!errorstatus(status)))856lua_assert(status == L->status); /* normal end or yield */857else { /* unrecoverable error */858L->status = cast_byte(status); /* mark thread as 'dead' */859luaD_seterrorobj(L, status, L->top.p); /* push error message */860L->ci->top.p = L->top.p;861}862*nresults = (status == LUA_YIELD) ? L->ci->u2.nyield863: cast_int(L->top.p - (L->ci->func.p + 1));864lua_unlock(L);865return status;866}867868869LUA_API int lua_isyieldable (lua_State *L) {870return yieldable(L);871}872873874LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,875lua_KFunction k) {876CallInfo *ci;877luai_userstateyield(L, nresults);878lua_lock(L);879ci = L->ci;880api_checknelems(L, nresults);881if (l_unlikely(!yieldable(L))) {882if (L != G(L)->mainthread)883luaG_runerror(L, "attempt to yield across a C-call boundary");884else885luaG_runerror(L, "attempt to yield from outside a coroutine");886}887L->status = LUA_YIELD;888ci->u2.nyield = nresults; /* save number of results */889if (isLua(ci)) { /* inside a hook? */890lua_assert(!isLuacode(ci));891api_check(L, nresults == 0, "hooks cannot yield values");892api_check(L, k == NULL, "hooks cannot continue after yielding");893}894else {895if ((ci->u.c.k = k) != NULL) /* is there a continuation? */896ci->u.c.ctx = ctx; /* save context */897luaD_throw(L, LUA_YIELD);898}899lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */900lua_unlock(L);901return 0; /* return to 'luaD_hook' */902}903904905/*906** Auxiliary structure to call 'luaF_close' in protected mode.907*/908struct CloseP {909StkId level;910int status;911};912913914/*915** Auxiliary function to call 'luaF_close' in protected mode.916*/917static void closepaux (lua_State *L, void *ud) {918struct CloseP *pcl = cast(struct CloseP *, ud);919luaF_close(L, pcl->level, pcl->status, 0);920}921922923/*924** Calls 'luaF_close' in protected mode. Return the original status925** or, in case of errors, the new status.926*/927int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {928CallInfo *old_ci = L->ci;929lu_byte old_allowhooks = L->allowhook;930for (;;) { /* keep closing upvalues until no more errors */931struct CloseP pcl;932pcl.level = restorestack(L, level); pcl.status = status;933status = luaD_rawrunprotected(L, &closepaux, &pcl);934if (l_likely(status == LUA_OK)) /* no more errors? */935return pcl.status;936else { /* an error occurred; restore saved state and repeat */937L->ci = old_ci;938L->allowhook = old_allowhooks;939}940}941}942943944/*945** Call the C function 'func' in protected mode, restoring basic946** thread information ('allowhook', etc.) and in particular947** its stack level in case of errors.948*/949int luaD_pcall (lua_State *L, Pfunc func, void *u,950ptrdiff_t old_top, ptrdiff_t ef) {951int status;952CallInfo *old_ci = L->ci;953lu_byte old_allowhooks = L->allowhook;954ptrdiff_t old_errfunc = L->errfunc;955L->errfunc = ef;956status = luaD_rawrunprotected(L, func, u);957if (l_unlikely(status != LUA_OK)) { /* an error occurred? */958L->ci = old_ci;959L->allowhook = old_allowhooks;960status = luaD_closeprotected(L, old_top, status);961luaD_seterrorobj(L, status, restorestack(L, old_top));962luaD_shrinkstack(L); /* restore stack size in case of overflow */963}964L->errfunc = old_errfunc;965return status;966}967968969970/*971** Execute a protected parser.972*/973struct SParser { /* data to 'f_parser' */974ZIO *z;975Mbuffer buff; /* dynamic structure used by the scanner */976Dyndata dyd; /* dynamic structures used by the parser */977const char *mode;978const char *name;979};980981982static void checkmode (lua_State *L, const char *mode, const char *x) {983if (mode && strchr(mode, x[0]) == NULL) {984luaO_pushfstring(L,985"attempt to load a %s chunk (mode is '%s')", x, mode);986luaD_throw(L, LUA_ERRSYNTAX);987}988}989990991static void f_parser (lua_State *L, void *ud) {992LClosure *cl;993struct SParser *p = cast(struct SParser *, ud);994int c = zgetc(p->z); /* read first character */995if (c == LUA_SIGNATURE[0]) {996checkmode(L, p->mode, "binary");997cl = luaU_undump(L, p->z, p->name);998}999else {1000checkmode(L, p->mode, "text");1001cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);1002}1003lua_assert(cl->nupvalues == cl->p->sizeupvalues);1004luaF_initupvals(L, cl);1005}100610071008int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,1009const char *mode) {1010struct SParser p;1011int status;1012incnny(L); /* cannot yield during parsing */1013p.z = z; p.name = name; p.mode = mode;1014p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;1015p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;1016p.dyd.label.arr = NULL; p.dyd.label.size = 0;1017luaZ_initbuffer(L, &p.buff);1018status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);1019luaZ_freebuffer(L, &p.buff);1020luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);1021luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);1022luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);1023decnny(L);1024return status;1025}10261027102810291030