ldo.c 24 KB

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