ldo.c 25 KB

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