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