ldo.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /*
  2. ** $Id: ldo.c $
  3. ** Stack and Call structure of Lua
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ldo_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <setjmp.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include "lua.h"
  13. #include "lapi.h"
  14. #include "ldebug.h"
  15. #include "ldo.h"
  16. #include "lfunc.h"
  17. #include "lgc.h"
  18. #include "lmem.h"
  19. #include "lobject.h"
  20. #include "lopcodes.h"
  21. #include "lparser.h"
  22. #include "lstate.h"
  23. #include "lstring.h"
  24. #include "ltable.h"
  25. #include "ltm.h"
  26. #include "lundump.h"
  27. #include "lvm.h"
  28. #include "lzio.h"
  29. #define errorstatus(s) ((s) > LUA_YIELD)
  30. /*
  31. ** {======================================================
  32. ** Error-recovery functions
  33. ** =======================================================
  34. */
  35. /*
  36. ** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
  37. ** default, Lua handles errors with exceptions when compiling as
  38. ** C++ code, with _longjmp/_setjmp when asked to use them, and with
  39. ** longjmp/setjmp otherwise.
  40. */
  41. #if !defined(LUAI_THROW) /* { */
  42. #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
  43. /* C++ exceptions */
  44. #define LUAI_THROW(L,c) throw(c)
  45. #define LUAI_TRY(L,c,a) \
  46. try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
  47. #define luai_jmpbuf int /* dummy variable */
  48. #elif defined(LUA_USE_POSIX) /* }{ */
  49. /* in POSIX, try _longjmp/_setjmp (more efficient) */
  50. #define LUAI_THROW(L,c) _longjmp((c)->b, 1)
  51. #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
  52. #define luai_jmpbuf jmp_buf
  53. #else /* }{ */
  54. /* ISO C handling with long jumps */
  55. #define LUAI_THROW(L,c) longjmp((c)->b, 1)
  56. #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
  57. #define luai_jmpbuf jmp_buf
  58. #endif /* } */
  59. #endif /* } */
  60. /* chain list of long jump buffers */
  61. struct lua_longjmp {
  62. struct lua_longjmp *previous;
  63. luai_jmpbuf b;
  64. volatile int status; /* error code */
  65. };
  66. void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
  67. switch (errcode) {
  68. case LUA_ERRMEM: { /* memory error? */
  69. setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
  70. break;
  71. }
  72. case LUA_ERRERR: {
  73. setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
  74. break;
  75. }
  76. case LUA_OK: { /* special case only for closing upvalues */
  77. setnilvalue(s2v(oldtop)); /* no error message */
  78. break;
  79. }
  80. default: {
  81. lua_assert(errorstatus(errcode)); /* real error */
  82. setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
  83. break;
  84. }
  85. }
  86. L->top = oldtop + 1;
  87. }
  88. l_noret luaD_throw (lua_State *L, int errcode) {
  89. if (L->errorJmp) { /* thread has an error handler? */
  90. L->errorJmp->status = errcode; /* set status */
  91. LUAI_THROW(L, L->errorJmp); /* jump to it */
  92. }
  93. else { /* thread has no error handler */
  94. global_State *g = G(L);
  95. errcode = luaE_resetthread(L, errcode); /* close all upvalues */
  96. if (g->mainthread->errorJmp) { /* main thread has a handler? */
  97. setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
  98. luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
  99. }
  100. else { /* no handler at all; abort */
  101. if (g->panic) { /* panic function? */
  102. lua_unlock(L);
  103. g->panic(L); /* call panic function (last chance to jump out) */
  104. }
  105. abort();
  106. }
  107. }
  108. }
  109. int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
  110. l_uint32 oldnCcalls = L->nCcalls;
  111. struct lua_longjmp lj;
  112. lj.status = LUA_OK;
  113. lj.previous = L->errorJmp; /* chain new error handler */
  114. L->errorJmp = &lj;
  115. LUAI_TRY(L, &lj,
  116. (*f)(L, ud);
  117. );
  118. L->errorJmp = lj.previous; /* restore old error handler */
  119. L->nCcalls = oldnCcalls;
  120. return lj.status;
  121. }
  122. /* }====================================================== */
  123. /*
  124. ** {==================================================================
  125. ** Stack reallocation
  126. ** ===================================================================
  127. */
  128. static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
  129. CallInfo *ci;
  130. UpVal *up;
  131. if (oldstack == newstack)
  132. return; /* stack address did not change */
  133. L->top = (L->top - oldstack) + newstack;
  134. lua_assert(L->ptbc == NULL);
  135. for (up = L->openupval; up != NULL; up = up->u.open.next)
  136. up->v = s2v((uplevel(up) - oldstack) + newstack);
  137. for (ci = L->ci; ci != NULL; ci = ci->previous) {
  138. ci->top = (ci->top - oldstack) + newstack;
  139. ci->func = (ci->func - oldstack) + newstack;
  140. if (isLua(ci))
  141. ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
  142. }
  143. }
  144. /* some space for error handling */
  145. #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
  146. int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
  147. int lim = stacksize(L);
  148. StkId newstack = luaM_reallocvector(L, L->stack,
  149. lim + EXTRA_STACK, newsize + EXTRA_STACK, StackValue);
  150. lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
  151. if (unlikely(newstack == NULL)) { /* reallocation failed? */
  152. if (raiseerror)
  153. luaM_error(L);
  154. else return 0; /* do not raise an error */
  155. }
  156. for (; lim < newsize; lim++)
  157. setnilvalue(s2v(newstack + lim + EXTRA_STACK)); /* erase new segment */
  158. correctstack(L, L->stack, newstack);
  159. L->stack = newstack;
  160. L->stack_last = L->stack + newsize;
  161. return 1;
  162. }
  163. /*
  164. ** Try to grow the stack by at least 'n' elements. when 'raiseerror'
  165. ** is true, raises any error; otherwise, return 0 in case of errors.
  166. */
  167. int luaD_growstack (lua_State *L, int n, int raiseerror) {
  168. int size = stacksize(L);
  169. if (unlikely(size > LUAI_MAXSTACK)) {
  170. /* if stack is larger than maximum, thread is already using the
  171. extra space reserved for errors, that is, thread is handling
  172. a stack error; cannot grow further than that. */
  173. lua_assert(stacksize(L) == ERRORSTACKSIZE);
  174. if (raiseerror)
  175. luaD_throw(L, LUA_ERRERR); /* error inside message handler */
  176. return 0; /* if not 'raiseerror', just signal it */
  177. }
  178. else {
  179. int newsize = 2 * size; /* tentative new size */
  180. int needed = cast_int(L->top - L->stack) + n;
  181. if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
  182. newsize = LUAI_MAXSTACK;
  183. if (newsize < needed) /* but must respect what was asked for */
  184. newsize = needed;
  185. if (likely(newsize <= LUAI_MAXSTACK))
  186. return luaD_reallocstack(L, newsize, raiseerror);
  187. else { /* stack overflow */
  188. /* add extra size to be able to handle the error message */
  189. luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
  190. if (raiseerror)
  191. luaG_runerror(L, "stack overflow");
  192. return 0;
  193. }
  194. }
  195. }
  196. static int stackinuse (lua_State *L) {
  197. CallInfo *ci;
  198. int res;
  199. StkId lim = L->top;
  200. for (ci = L->ci; ci != NULL; ci = ci->previous) {
  201. if (lim < ci->top) lim = ci->top;
  202. }
  203. lua_assert(lim <= L->stack_last);
  204. res = cast_int(lim - L->stack) + 1; /* part of stack in use */
  205. if (res < LUA_MINSTACK)
  206. res = LUA_MINSTACK; /* ensure a minimum size */
  207. return res;
  208. }
  209. /*
  210. ** If stack size is more than 3 times the current use, reduce that size
  211. ** to twice the current use. (So, the final stack size is at most 2/3 the
  212. ** previous size, and half of its entries are empty.)
  213. ** As a particular case, if stack was handling a stack overflow and now
  214. ** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
  215. ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
  216. ** will be reduced to a "regular" size.
  217. */
  218. void luaD_shrinkstack (lua_State *L) {
  219. int inuse = stackinuse(L);
  220. int nsize = inuse * 2; /* proposed new size */
  221. int max = inuse * 3; /* maximum "reasonable" size */
  222. if (max > LUAI_MAXSTACK) {
  223. max = LUAI_MAXSTACK; /* respect stack limit */
  224. if (nsize > LUAI_MAXSTACK)
  225. nsize = LUAI_MAXSTACK;
  226. }
  227. /* if thread is currently not handling a stack overflow and its
  228. size is larger than maximum "reasonable" size, shrink it */
  229. if (inuse <= LUAI_MAXSTACK && stacksize(L) > max)
  230. luaD_reallocstack(L, nsize, 0); /* ok if that fails */
  231. else /* don't change stack */
  232. condmovestack(L,{},{}); /* (change only for debugging) */
  233. luaE_shrinkCI(L); /* shrink CI list */
  234. }
  235. void luaD_inctop (lua_State *L) {
  236. luaD_checkstack(L, 1);
  237. L->top++;
  238. }
  239. /* }================================================================== */
  240. /*
  241. ** Call a hook for the given event. Make sure there is a hook to be
  242. ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
  243. ** function, can be changed asynchronously by signals.)
  244. */
  245. void luaD_hook (lua_State *L, int event, int line,
  246. int ftransfer, int ntransfer) {
  247. lua_Hook hook = L->hook;
  248. if (hook && L->allowhook) { /* make sure there is a hook */
  249. int mask = CIST_HOOKED;
  250. CallInfo *ci = L->ci;
  251. ptrdiff_t top = savestack(L, L->top); /* preserve original 'top' */
  252. ptrdiff_t ci_top = savestack(L, ci->top); /* idem for 'ci->top' */
  253. lua_Debug ar;
  254. ar.event = event;
  255. ar.currentline = line;
  256. ar.i_ci = ci;
  257. if (ntransfer != 0) {
  258. mask |= CIST_TRAN; /* 'ci' has transfer information */
  259. ci->u2.transferinfo.ftransfer = ftransfer;
  260. ci->u2.transferinfo.ntransfer = ntransfer;
  261. }
  262. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  263. if (ci->top < L->top + LUA_MINSTACK)
  264. ci->top = L->top + LUA_MINSTACK;
  265. L->allowhook = 0; /* cannot call hooks inside a hook */
  266. ci->callstatus |= mask;
  267. lua_unlock(L);
  268. (*hook)(L, &ar);
  269. lua_lock(L);
  270. lua_assert(!L->allowhook);
  271. L->allowhook = 1;
  272. ci->top = restorestack(L, ci_top);
  273. L->top = restorestack(L, top);
  274. ci->callstatus &= ~mask;
  275. }
  276. }
  277. /*
  278. ** Executes a call hook for Lua functions. This function is called
  279. ** whenever 'hookmask' is not zero, so it checks whether call hooks are
  280. ** active.
  281. */
  282. void luaD_hookcall (lua_State *L, CallInfo *ci) {
  283. if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
  284. int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
  285. : LUA_HOOKCALL;
  286. Proto *p = ci_func(ci)->p;
  287. L->top = ci->top; /* prepare top */
  288. ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
  289. luaD_hook(L, event, -1, 1, p->numparams);
  290. ci->u.l.savedpc--; /* correct 'pc' */
  291. }
  292. }
  293. /*
  294. ** Executes a call hook for Lua and C functions. This function is called
  295. ** whenever 'hookmask' is not zero, so it checks whether return hooks are
  296. ** active.
  297. */
  298. static void rethook (lua_State *L, CallInfo *ci, int nres) {
  299. if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
  300. StkId firstres = L->top - nres; /* index of first result */
  301. ptrdiff_t oldtop = savestack(L, L->top); /* hook may change top */
  302. int delta = 0; /* correction for vararg functions */
  303. int ftransfer;
  304. if (isLuacode(ci)) {
  305. Proto *p = ci_func(ci)->p;
  306. if (p->is_vararg)
  307. delta = ci->u.l.nextraargs + p->numparams + 1;
  308. if (L->top < ci->top)
  309. L->top = ci->top; /* correct top to run hook */
  310. }
  311. ci->func += delta; /* if vararg, back to virtual 'func' */
  312. ftransfer = cast(unsigned short, firstres - ci->func);
  313. luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
  314. ci->func -= delta;
  315. L->top = restorestack(L, oldtop);
  316. }
  317. if (isLua(ci = ci->previous))
  318. L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* update 'oldpc' */
  319. }
  320. /*
  321. ** Check whether 'func' has a '__call' metafield. If so, put it in the
  322. ** stack, below original 'func', so that 'luaD_precall' can call it. Raise
  323. ** an error if there is no '__call' metafield.
  324. */
  325. void luaD_tryfuncTM (lua_State *L, StkId func) {
  326. const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
  327. StkId p;
  328. if (unlikely(ttisnil(tm)))
  329. luaG_callerror(L, s2v(func)); /* nothing to call */
  330. for (p = L->top; p > func; p--) /* open space for metamethod */
  331. setobjs2s(L, p, p-1);
  332. L->top++; /* stack space pre-allocated by the caller */
  333. setobj2s(L, func, tm); /* metamethod is the new function to be called */
  334. }
  335. /*
  336. ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
  337. ** Handle most typical cases (zero results for commands, one result for
  338. ** expressions, multiple results for tail calls/single parameters)
  339. ** separated.
  340. */
  341. static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
  342. StkId firstresult;
  343. int i;
  344. switch (wanted) { /* handle typical cases separately */
  345. case 0: /* no values needed */
  346. L->top = res;
  347. return;
  348. case 1: /* one value needed */
  349. if (nres == 0) /* no results? */
  350. setnilvalue(s2v(res)); /* adjust with nil */
  351. else /* at least one result */
  352. setobjs2s(L, res, L->top - nres); /* move it to proper place */
  353. L->top = res + 1;
  354. return;
  355. case LUA_MULTRET:
  356. wanted = nres; /* we want all results */
  357. break;
  358. default: /* multiple results (or to-be-closed variables) */
  359. if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
  360. ptrdiff_t savedres = savestack(L, res);
  361. luaF_close(L, res, CLOSEKTOP, 0); /* may change the stack */
  362. res = restorestack(L, savedres);
  363. wanted = codeNresults(wanted); /* correct value */
  364. if (wanted == LUA_MULTRET)
  365. wanted = nres;
  366. if (L->hookmask) /* if needed, call hook after '__close's */
  367. rethook(L, L->ci, nres);
  368. }
  369. break;
  370. }
  371. firstresult = L->top - nres; /* index of first result */
  372. /* move all results to correct place */
  373. if (nres > wanted)
  374. nres = wanted; /* don't need more than that */
  375. for (i = 0; i < nres; i++)
  376. setobjs2s(L, res + i, firstresult + i);
  377. for (; i < wanted; i++) /* complete wanted number of results */
  378. setnilvalue(s2v(res + i));
  379. L->top = res + wanted; /* top points after the last result */
  380. }
  381. /*
  382. ** Finishes a function call: calls hook if necessary, moves current
  383. ** number of results to proper place, and returns to previous call
  384. ** info. If function has to close variables, hook must be called after
  385. ** that.
  386. */
  387. void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
  388. int wanted = ci->nresults;
  389. if (L->hookmask && !hastocloseCfunc(wanted))
  390. rethook(L, ci, nres);
  391. /* move results to proper place */
  392. moveresults(L, ci->func, nres, wanted);
  393. L->ci = ci->previous; /* back to caller (after closing variables) */
  394. }
  395. #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
  396. /*
  397. ** Prepare a function for a tail call, building its call info on top
  398. ** of the current call info. 'narg1' is the number of arguments plus 1
  399. ** (so that it includes the function itself).
  400. */
  401. void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
  402. Proto *p = clLvalue(s2v(func))->p;
  403. int fsize = p->maxstacksize; /* frame size */
  404. int nfixparams = p->numparams;
  405. int i;
  406. for (i = 0; i < narg1; i++) /* move down function and arguments */
  407. setobjs2s(L, ci->func + i, func + i);
  408. checkstackGC(L, fsize);
  409. func = ci->func; /* moved-down function */
  410. for (; narg1 <= nfixparams; narg1++)
  411. setnilvalue(s2v(func + narg1)); /* complete missing arguments */
  412. ci->top = func + 1 + fsize; /* top for new function */
  413. lua_assert(ci->top <= L->stack_last);
  414. ci->u.l.savedpc = p->code; /* starting point */
  415. ci->callstatus |= CIST_TAIL;
  416. L->top = func + narg1; /* set top */
  417. }
  418. /*
  419. ** Prepares the call to a function (C or Lua). For C functions, also do
  420. ** the call. The function to be called is at '*func'. The arguments
  421. ** are on the stack, right after the function. Returns the CallInfo
  422. ** to be executed, if it was a Lua function. Otherwise (a C function)
  423. ** returns NULL, with all the results on the stack, starting at the
  424. ** original function position.
  425. */
  426. CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
  427. lua_CFunction f;
  428. retry:
  429. switch (ttypetag(s2v(func))) {
  430. case LUA_VCCL: /* C closure */
  431. f = clCvalue(s2v(func))->f;
  432. goto Cfunc;
  433. case LUA_VLCF: /* light C function */
  434. f = fvalue(s2v(func));
  435. Cfunc: {
  436. int n; /* number of returns */
  437. CallInfo *ci;
  438. checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
  439. L->ci = ci = next_ci(L);
  440. ci->nresults = nresults;
  441. ci->callstatus = CIST_C;
  442. ci->top = L->top + LUA_MINSTACK;
  443. ci->func = func;
  444. lua_assert(ci->top <= L->stack_last);
  445. if (L->hookmask & LUA_MASKCALL) {
  446. int narg = cast_int(L->top - func) - 1;
  447. luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
  448. }
  449. lua_unlock(L);
  450. n = (*f)(L); /* do the actual call */
  451. lua_lock(L);
  452. api_checknelems(L, n);
  453. luaD_poscall(L, ci, n);
  454. return NULL;
  455. }
  456. case LUA_VLCL: { /* Lua function */
  457. CallInfo *ci;
  458. Proto *p = clLvalue(s2v(func))->p;
  459. int narg = cast_int(L->top - func) - 1; /* number of real arguments */
  460. int nfixparams = p->numparams;
  461. int fsize = p->maxstacksize; /* frame size */
  462. checkstackGCp(L, fsize, func);
  463. L->ci = ci = next_ci(L);
  464. ci->nresults = nresults;
  465. ci->u.l.savedpc = p->code; /* starting point */
  466. ci->top = func + 1 + fsize;
  467. ci->func = func;
  468. L->ci = ci;
  469. for (; narg < nfixparams; narg++)
  470. setnilvalue(s2v(L->top++)); /* complete missing arguments */
  471. lua_assert(ci->top <= L->stack_last);
  472. return ci;
  473. }
  474. default: { /* not a function */
  475. checkstackGCp(L, 1, func); /* space for metamethod */
  476. luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
  477. goto retry; /* try again with metamethod */
  478. }
  479. }
  480. }
  481. /*
  482. ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
  483. ** number of recursive invocations in the C stack) or nyci (the same
  484. ** plus increment number of non-yieldable calls).
  485. */
  486. static void ccall (lua_State *L, StkId func, int nResults, int inc) {
  487. CallInfo *ci;
  488. L->nCcalls += inc;
  489. if (unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
  490. luaE_checkcstack(L);
  491. if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
  492. ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
  493. luaV_execute(L, ci); /* call it */
  494. }
  495. L->nCcalls -= inc;
  496. }
  497. /*
  498. ** External interface for 'ccall'
  499. */
  500. void luaD_call (lua_State *L, StkId func, int nResults) {
  501. ccall(L, func, nResults, 1);
  502. }
  503. /*
  504. ** Similar to 'luaD_call', but does not allow yields during the call.
  505. */
  506. void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
  507. ccall(L, func, nResults, nyci);
  508. }
  509. /*
  510. ** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
  511. ** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
  512. ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
  513. ** If a '__close' method yields here, eventually control will be back
  514. ** to 'finishCcall' (when that '__close' method finally returns) and
  515. ** 'finishpcallk' will run again and close any still pending '__close'
  516. ** methods. Similarly, if a '__close' method errs, 'precover' calls
  517. ** 'unroll' which calls ''finishCcall' and we are back here again, to
  518. ** close any pending '__close' methods.
  519. ** Note that, up to the call to 'luaF_close', the corresponding
  520. ** 'CallInfo' is not modified, so that this repeated run works like the
  521. ** first one (except that it has at least one less '__close' to do). In
  522. ** particular, field CIST_RECST preserves the error status across these
  523. ** multiple runs, changing only if there is a new error.
  524. */
  525. static int finishpcallk (lua_State *L, CallInfo *ci) {
  526. int status = getcistrecst(ci); /* get original status */
  527. if (status == LUA_OK) /* no error? */
  528. status = LUA_YIELD; /* was interrupted by an yield */
  529. else { /* error */
  530. StkId func = restorestack(L, ci->u2.funcidx);
  531. L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
  532. luaF_close(L, func, status, 1); /* can yield or raise an error */
  533. func = restorestack(L, ci->u2.funcidx); /* stack may be moved */
  534. luaD_seterrorobj(L, status, func);
  535. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  536. setcistrecst(ci, LUA_OK); /* clear original status */
  537. }
  538. ci->callstatus &= ~CIST_YPCALL;
  539. L->errfunc = ci->u.c.old_errfunc;
  540. /* if it is here, there were errors or yields; unlike 'lua_pcallk',
  541. do not change status */
  542. return status;
  543. }
  544. /*
  545. ** Completes the execution of a C function interrupted by an yield.
  546. ** The interruption must have happened while the function was
  547. ** executing 'lua_callk' or 'lua_pcallk'. In the second case, the
  548. ** call to 'finishpcallk' finishes the interrupted execution of
  549. ** 'lua_pcallk'. After that, it calls the continuation of the
  550. ** interrupted function and finally it completes the job of the
  551. ** 'luaD_call' that called the function.
  552. ** In the call to 'adjustresults', we do not know the number of
  553. ** results of the function called by 'lua_callk'/'lua_pcallk',
  554. ** so we are conservative and use LUA_MULTRET (always adjust).
  555. */
  556. static void finishCcall (lua_State *L, CallInfo *ci) {
  557. int n;
  558. int status = LUA_YIELD; /* default if there were no errors */
  559. /* must have a continuation and must be able to call it */
  560. lua_assert(ci->u.c.k != NULL && yieldable(L));
  561. if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
  562. status = finishpcallk(L, ci); /* finish it */
  563. adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
  564. lua_unlock(L);
  565. n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
  566. lua_lock(L);
  567. api_checknelems(L, n);
  568. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  569. }
  570. /*
  571. ** Executes "full continuation" (everything in the stack) of a
  572. ** previously interrupted coroutine until the stack is empty (or another
  573. ** interruption long-jumps out of the loop).
  574. */
  575. static void unroll (lua_State *L, void *ud) {
  576. CallInfo *ci;
  577. UNUSED(ud);
  578. while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
  579. if (!isLua(ci)) /* C function? */
  580. finishCcall(L, ci); /* complete its execution */
  581. else { /* Lua function */
  582. luaV_finishOp(L); /* finish interrupted instruction */
  583. luaV_execute(L, ci); /* execute down to higher C 'boundary' */
  584. }
  585. }
  586. }
  587. /*
  588. ** Try to find a suspended protected call (a "recover point") for the
  589. ** given thread.
  590. */
  591. static CallInfo *findpcall (lua_State *L) {
  592. CallInfo *ci;
  593. for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
  594. if (ci->callstatus & CIST_YPCALL)
  595. return ci;
  596. }
  597. return NULL; /* no pending pcall */
  598. }
  599. /*
  600. ** Signal an error in the call to 'lua_resume', not in the execution
  601. ** of the coroutine itself. (Such errors should not be handled by any
  602. ** coroutine error handler and should not kill the coroutine.)
  603. */
  604. static int resume_error (lua_State *L, const char *msg, int narg) {
  605. L->top -= narg; /* remove args from the stack */
  606. setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
  607. api_incr_top(L);
  608. lua_unlock(L);
  609. return LUA_ERRRUN;
  610. }
  611. /*
  612. ** Do the work for 'lua_resume' in protected mode. Most of the work
  613. ** depends on the status of the coroutine: initial state, suspended
  614. ** inside a hook, or regularly suspended (optionally with a continuation
  615. ** function), plus erroneous cases: non-suspended coroutine or dead
  616. ** coroutine.
  617. */
  618. static void resume (lua_State *L, void *ud) {
  619. int n = *(cast(int*, ud)); /* number of arguments */
  620. StkId firstArg = L->top - n; /* first argument */
  621. CallInfo *ci = L->ci;
  622. if (L->status == LUA_OK) /* starting a coroutine? */
  623. ccall(L, firstArg - 1, LUA_MULTRET, 1); /* just call its body */
  624. else { /* resuming from previous yield */
  625. lua_assert(L->status == LUA_YIELD);
  626. L->status = LUA_OK; /* mark that it is running (again) */
  627. luaE_incCstack(L); /* control the C stack */
  628. if (isLua(ci)) /* yielded inside a hook? */
  629. luaV_execute(L, ci); /* just continue running Lua code */
  630. else { /* 'common' yield */
  631. if (ci->u.c.k != NULL) { /* does it have a continuation function? */
  632. lua_unlock(L);
  633. n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
  634. lua_lock(L);
  635. api_checknelems(L, n);
  636. }
  637. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  638. }
  639. unroll(L, NULL); /* run continuation */
  640. }
  641. }
  642. /*
  643. ** Unrolls a coroutine in protected mode while there are recoverable
  644. ** errors, that is, errors inside a protected call. (Any error
  645. ** interrupts 'unroll', and this loop protects it again so it can
  646. ** continue.) Stops with a normal end (status == LUA_OK), an yield
  647. ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
  648. ** find a recover point).
  649. */
  650. static int precover (lua_State *L, int status) {
  651. CallInfo *ci;
  652. while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
  653. L->ci = ci; /* go down to recovery functions */
  654. setcistrecst(ci, status); /* status to finish 'pcall' */
  655. status = luaD_rawrunprotected(L, unroll, NULL);
  656. }
  657. return status;
  658. }
  659. LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
  660. int *nresults) {
  661. int status;
  662. lua_lock(L);
  663. if (L->status == LUA_OK) { /* may be starting a coroutine */
  664. if (L->ci != &L->base_ci) /* not in base level? */
  665. return resume_error(L, "cannot resume non-suspended coroutine", nargs);
  666. else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
  667. return resume_error(L, "cannot resume dead coroutine", nargs);
  668. }
  669. else if (L->status != LUA_YIELD) /* ended with errors? */
  670. return resume_error(L, "cannot resume dead coroutine", nargs);
  671. L->nCcalls = (from) ? getCcalls(from) : 0;
  672. luai_userstateresume(L, nargs);
  673. api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
  674. status = luaD_rawrunprotected(L, resume, &nargs);
  675. /* continue running after recoverable errors */
  676. status = precover(L, status);
  677. if (likely(!errorstatus(status)))
  678. lua_assert(status == L->status); /* normal end or yield */
  679. else { /* unrecoverable error */
  680. L->status = cast_byte(status); /* mark thread as 'dead' */
  681. luaD_seterrorobj(L, status, L->top); /* push error message */
  682. L->ci->top = L->top;
  683. }
  684. *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
  685. : cast_int(L->top - (L->ci->func + 1));
  686. lua_unlock(L);
  687. return status;
  688. }
  689. LUA_API int lua_isyieldable (lua_State *L) {
  690. return yieldable(L);
  691. }
  692. LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
  693. lua_KFunction k) {
  694. CallInfo *ci;
  695. luai_userstateyield(L, nresults);
  696. lua_lock(L);
  697. ci = L->ci;
  698. api_checknelems(L, nresults);
  699. if (unlikely(!yieldable(L))) {
  700. if (L != G(L)->mainthread)
  701. luaG_runerror(L, "attempt to yield across a C-call boundary");
  702. else
  703. luaG_runerror(L, "attempt to yield from outside a coroutine");
  704. }
  705. L->status = LUA_YIELD;
  706. if (isLua(ci)) { /* inside a hook? */
  707. lua_assert(!isLuacode(ci));
  708. api_check(L, k == NULL, "hooks cannot continue after yielding");
  709. ci->u2.nyield = 0; /* no results */
  710. }
  711. else {
  712. if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
  713. ci->u.c.ctx = ctx; /* save context */
  714. ci->u2.nyield = nresults; /* save number of results */
  715. luaD_throw(L, LUA_YIELD);
  716. }
  717. lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
  718. lua_unlock(L);
  719. return 0; /* return to 'luaD_hook' */
  720. }
  721. /*
  722. ** Auxiliary structure to call 'luaF_close' in protected mode.
  723. */
  724. struct CloseP {
  725. StkId level;
  726. int status;
  727. };
  728. /*
  729. ** Auxiliary function to call 'luaF_close' in protected mode.
  730. */
  731. static void closepaux (lua_State *L, void *ud) {
  732. struct CloseP *pcl = cast(struct CloseP *, ud);
  733. luaF_close(L, pcl->level, pcl->status, 0);
  734. }
  735. /*
  736. ** Calls 'luaF_close' in protected mode. Return the original status
  737. ** or, in case of errors, the new status.
  738. */
  739. int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
  740. CallInfo *old_ci = L->ci;
  741. lu_byte old_allowhooks = L->allowhook;
  742. for (;;) { /* keep closing upvalues until no more errors */
  743. struct CloseP pcl;
  744. pcl.level = restorestack(L, level); pcl.status = status;
  745. status = luaD_rawrunprotected(L, &closepaux, &pcl);
  746. if (likely(status == LUA_OK)) /* no more errors? */
  747. return pcl.status;
  748. else { /* an error occurred; restore saved state and repeat */
  749. L->ci = old_ci;
  750. L->allowhook = old_allowhooks;
  751. }
  752. }
  753. }
  754. /*
  755. ** Call the C function 'func' in protected mode, restoring basic
  756. ** thread information ('allowhook', etc.) and in particular
  757. ** its stack level in case of errors.
  758. */
  759. int luaD_pcall (lua_State *L, Pfunc func, void *u,
  760. ptrdiff_t old_top, ptrdiff_t ef) {
  761. int status;
  762. CallInfo *old_ci = L->ci;
  763. lu_byte old_allowhooks = L->allowhook;
  764. ptrdiff_t old_errfunc = L->errfunc;
  765. L->errfunc = ef;
  766. status = luaD_rawrunprotected(L, func, u);
  767. if (unlikely(status != LUA_OK)) { /* an error occurred? */
  768. L->ci = old_ci;
  769. L->allowhook = old_allowhooks;
  770. status = luaD_closeprotected(L, old_top, status);
  771. luaD_seterrorobj(L, status, restorestack(L, old_top));
  772. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  773. }
  774. L->errfunc = old_errfunc;
  775. return status;
  776. }
  777. /*
  778. ** Execute a protected parser.
  779. */
  780. struct SParser { /* data to 'f_parser' */
  781. ZIO *z;
  782. Mbuffer buff; /* dynamic structure used by the scanner */
  783. Dyndata dyd; /* dynamic structures used by the parser */
  784. const char *mode;
  785. const char *name;
  786. };
  787. static void checkmode (lua_State *L, const char *mode, const char *x) {
  788. if (mode && strchr(mode, x[0]) == NULL) {
  789. luaO_pushfstring(L,
  790. "attempt to load a %s chunk (mode is '%s')", x, mode);
  791. luaD_throw(L, LUA_ERRSYNTAX);
  792. }
  793. }
  794. static void f_parser (lua_State *L, void *ud) {
  795. LClosure *cl;
  796. struct SParser *p = cast(struct SParser *, ud);
  797. int c = zgetc(p->z); /* read first character */
  798. if (c == LUA_SIGNATURE[0]) {
  799. checkmode(L, p->mode, "binary");
  800. cl = luaU_undump(L, p->z, p->name);
  801. }
  802. else {
  803. checkmode(L, p->mode, "text");
  804. cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
  805. }
  806. lua_assert(cl->nupvalues == cl->p->sizeupvalues);
  807. luaF_initupvals(L, cl);
  808. }
  809. int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
  810. const char *mode) {
  811. struct SParser p;
  812. int status;
  813. incnny(L); /* cannot yield during parsing */
  814. p.z = z; p.name = name; p.mode = mode;
  815. p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
  816. p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
  817. p.dyd.label.arr = NULL; p.dyd.label.size = 0;
  818. luaZ_initbuffer(L, &p.buff);
  819. status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
  820. luaZ_freebuffer(L, &p.buff);
  821. luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
  822. luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
  823. luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
  824. decnny(L);
  825. return status;
  826. }