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