ldo.c 23 KB

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