ldo.c 25 KB

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