ldo.c 27 KB

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