ldo.c 25 KB

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