ldo.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. /*
  2. ** $Id: ldo.c $
  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. void luaD_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. case LUA_OK: { /* special case only for closing upvalues */
  77. setnilvalue(s2v(oldtop)); /* no error message */
  78. break;
  79. }
  80. default: {
  81. lua_assert(errorstatus(errcode)); /* real error */
  82. setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
  83. break;
  84. }
  85. }
  86. L->top = oldtop + 1;
  87. }
  88. l_noret luaD_throw (lua_State *L, int errcode) {
  89. if (L->errorJmp) { /* thread has an error handler? */
  90. L->errorJmp->status = errcode; /* set status */
  91. LUAI_THROW(L, L->errorJmp); /* jump to it */
  92. }
  93. else { /* thread has no error handler */
  94. global_State *g = G(L);
  95. errcode = luaE_resetthread(L, errcode); /* close all upvalues */
  96. if (g->mainthread->errorJmp) { /* main thread has a handler? */
  97. setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
  98. luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
  99. }
  100. else { /* no handler at all; abort */
  101. if (g->panic) { /* panic function? */
  102. lua_unlock(L);
  103. g->panic(L); /* call panic function (last chance to jump out) */
  104. }
  105. abort();
  106. }
  107. }
  108. }
  109. int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
  110. l_uint32 oldnCcalls = L->nCcalls;
  111. struct lua_longjmp lj;
  112. lj.status = LUA_OK;
  113. lj.previous = L->errorJmp; /* chain new error handler */
  114. L->errorJmp = &lj;
  115. LUAI_TRY(L, &lj,
  116. (*f)(L, ud);
  117. );
  118. L->errorJmp = lj.previous; /* restore old error handler */
  119. L->nCcalls = oldnCcalls;
  120. return lj.status;
  121. }
  122. /* }====================================================== */
  123. /*
  124. ** {==================================================================
  125. ** Stack reallocation
  126. ** ===================================================================
  127. */
  128. static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
  129. CallInfo *ci;
  130. UpVal *up;
  131. L->top = (L->top - oldstack) + newstack;
  132. L->tbclist = (L->tbclist - oldstack) + newstack;
  133. for (up = L->openupval; up != NULL; up = up->u.open.next)
  134. up->v = s2v((uplevel(up) - oldstack) + newstack);
  135. for (ci = L->ci; ci != NULL; ci = ci->previous) {
  136. ci->top = (ci->top - oldstack) + newstack;
  137. ci->func = (ci->func - oldstack) + newstack;
  138. if (isLua(ci))
  139. ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
  140. }
  141. }
  142. /* some space for error handling */
  143. #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
  144. /*
  145. ** Reallocate the stack to a new size, correcting all pointers into
  146. ** it. (There are pointers to a stack from its upvalues, from its list
  147. ** of call infos, plus a few individual pointers.) The reallocation is
  148. ** done in two steps (allocation + free) because the correction must be
  149. ** done while both addresses (the old stack and the new one) are valid.
  150. ** (In ISO C, any pointer use after the pointer has been deallocated is
  151. ** undefined behavior.)
  152. ** In case of allocation error, raise an error or return false according
  153. ** to 'raiseerror'.
  154. */
  155. int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
  156. int oldsize = stacksize(L);
  157. int i;
  158. StkId newstack = luaM_reallocvector(L, NULL, 0,
  159. newsize + EXTRA_STACK, StackValue);
  160. lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
  161. if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
  162. if (raiseerror)
  163. luaM_error(L);
  164. else return 0; /* do not raise an error */
  165. }
  166. /* number of elements to be copied to the new stack */
  167. i = ((oldsize <= newsize) ? oldsize : newsize) + EXTRA_STACK;
  168. memcpy(newstack, L->stack, i * sizeof(StackValue));
  169. for (; i < newsize + EXTRA_STACK; i++)
  170. setnilvalue(s2v(newstack + i)); /* erase new segment */
  171. correctstack(L, L->stack, newstack);
  172. luaM_freearray(L, L->stack, oldsize + EXTRA_STACK);
  173. L->stack = newstack;
  174. L->stack_last = L->stack + newsize;
  175. return 1;
  176. }
  177. /*
  178. ** Try to grow the stack by at least 'n' elements. when 'raiseerror'
  179. ** is true, raises any error; otherwise, return 0 in case of errors.
  180. */
  181. int luaD_growstack (lua_State *L, int n, int raiseerror) {
  182. int size = stacksize(L);
  183. if (l_unlikely(size > LUAI_MAXSTACK)) {
  184. /* if stack is larger than maximum, thread is already using the
  185. extra space reserved for errors, that is, thread is handling
  186. a stack error; cannot grow further than that. */
  187. lua_assert(stacksize(L) == ERRORSTACKSIZE);
  188. if (raiseerror)
  189. luaD_throw(L, LUA_ERRERR); /* error inside message handler */
  190. return 0; /* if not 'raiseerror', just signal it */
  191. }
  192. else {
  193. int newsize = 2 * size; /* tentative new size */
  194. int needed = cast_int(L->top - L->stack) + n;
  195. if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
  196. newsize = LUAI_MAXSTACK;
  197. if (newsize < needed) /* but must respect what was asked for */
  198. newsize = needed;
  199. if (l_likely(newsize <= LUAI_MAXSTACK))
  200. return luaD_reallocstack(L, newsize, raiseerror);
  201. else { /* stack overflow */
  202. /* add extra size to be able to handle the error message */
  203. luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
  204. if (raiseerror)
  205. luaG_runerror(L, "stack overflow");
  206. return 0;
  207. }
  208. }
  209. }
  210. static int stackinuse (lua_State *L) {
  211. CallInfo *ci;
  212. int res;
  213. StkId lim = L->top;
  214. for (ci = L->ci; ci != NULL; ci = ci->previous) {
  215. if (lim < ci->top) lim = ci->top;
  216. }
  217. lua_assert(lim <= L->stack_last);
  218. res = cast_int(lim - L->stack) + 1; /* part of stack in use */
  219. if (res < LUA_MINSTACK)
  220. res = LUA_MINSTACK; /* ensure a minimum size */
  221. return res;
  222. }
  223. /*
  224. ** If stack size is more than 3 times the current use, reduce that size
  225. ** to twice the current use. (So, the final stack size is at most 2/3 the
  226. ** previous size, and half of its entries are empty.)
  227. ** As a particular case, if stack was handling a stack overflow and now
  228. ** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
  229. ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
  230. ** will be reduced to a "regular" size.
  231. */
  232. void luaD_shrinkstack (lua_State *L) {
  233. int inuse = stackinuse(L);
  234. int nsize = inuse * 2; /* proposed new size */
  235. int max = inuse * 3; /* maximum "reasonable" size */
  236. if (max > LUAI_MAXSTACK) {
  237. max = LUAI_MAXSTACK; /* respect stack limit */
  238. if (nsize > LUAI_MAXSTACK)
  239. nsize = LUAI_MAXSTACK;
  240. }
  241. /* if thread is currently not handling a stack overflow and its
  242. size is larger than maximum "reasonable" size, shrink it */
  243. if (inuse <= LUAI_MAXSTACK && stacksize(L) > max)
  244. luaD_reallocstack(L, nsize, 0); /* ok if that fails */
  245. else /* don't change stack */
  246. condmovestack(L,{},{}); /* (change only for debugging) */
  247. luaE_shrinkCI(L); /* shrink CI list */
  248. }
  249. void luaD_inctop (lua_State *L) {
  250. luaD_checkstack(L, 1);
  251. L->top++;
  252. }
  253. /* }================================================================== */
  254. /*
  255. ** Call a hook for the given event. Make sure there is a hook to be
  256. ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
  257. ** function, can be changed asynchronously by signals.)
  258. */
  259. void luaD_hook (lua_State *L, int event, int line,
  260. int ftransfer, int ntransfer) {
  261. lua_Hook hook = L->hook;
  262. if (hook && L->allowhook) { /* make sure there is a hook */
  263. int mask = CIST_HOOKED;
  264. CallInfo *ci = L->ci;
  265. ptrdiff_t top = savestack(L, L->top); /* preserve original 'top' */
  266. ptrdiff_t ci_top = savestack(L, ci->top); /* idem for 'ci->top' */
  267. lua_Debug ar;
  268. ar.event = event;
  269. ar.currentline = line;
  270. ar.i_ci = ci;
  271. if (ntransfer != 0) {
  272. mask |= CIST_TRAN; /* 'ci' has transfer information */
  273. ci->u2.transferinfo.ftransfer = ftransfer;
  274. ci->u2.transferinfo.ntransfer = ntransfer;
  275. }
  276. if (isLua(ci) && L->top < ci->top)
  277. L->top = ci->top; /* protect entire activation register */
  278. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  279. if (ci->top < L->top + LUA_MINSTACK)
  280. ci->top = L->top + LUA_MINSTACK;
  281. L->allowhook = 0; /* cannot call hooks inside a hook */
  282. ci->callstatus |= mask;
  283. lua_unlock(L);
  284. (*hook)(L, &ar);
  285. lua_lock(L);
  286. lua_assert(!L->allowhook);
  287. L->allowhook = 1;
  288. ci->top = restorestack(L, ci_top);
  289. L->top = restorestack(L, top);
  290. ci->callstatus &= ~mask;
  291. }
  292. }
  293. /*
  294. ** Executes a call hook for Lua functions. This function is called
  295. ** whenever 'hookmask' is not zero, so it checks whether call hooks are
  296. ** active.
  297. */
  298. void luaD_hookcall (lua_State *L, CallInfo *ci) {
  299. L->oldpc = 0; /* set 'oldpc' for new function */
  300. if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
  301. int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
  302. : LUA_HOOKCALL;
  303. Proto *p = ci_func(ci)->p;
  304. ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
  305. luaD_hook(L, event, -1, 1, p->numparams);
  306. ci->u.l.savedpc--; /* correct 'pc' */
  307. }
  308. }
  309. /*
  310. ** Executes a return hook for Lua and C functions and sets/corrects
  311. ** 'oldpc'. (Note that this correction is needed by the line hook, so it
  312. ** is done even when return hooks are off.)
  313. */
  314. static void rethook (lua_State *L, CallInfo *ci, int nres) {
  315. if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
  316. StkId firstres = L->top - nres; /* index of first result */
  317. int delta = 0; /* correction for vararg functions */
  318. int ftransfer;
  319. if (isLua(ci)) {
  320. Proto *p = ci_func(ci)->p;
  321. if (p->is_vararg)
  322. delta = ci->u.l.nextraargs + p->numparams + 1;
  323. }
  324. ci->func += delta; /* if vararg, back to virtual 'func' */
  325. ftransfer = cast(unsigned short, firstres - ci->func);
  326. luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
  327. ci->func -= delta;
  328. }
  329. if (isLua(ci = ci->previous))
  330. L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
  331. }
  332. /*
  333. ** Check whether 'func' has a '__call' metafield. If so, put it in the
  334. ** stack, below original 'func', so that 'luaD_precall' can call it. Raise
  335. ** an error if there is no '__call' metafield.
  336. */
  337. StkId luaD_tryfuncTM (lua_State *L, StkId func) {
  338. const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
  339. StkId p;
  340. checkstackGCp(L, 1, func); /* space for metamethod */
  341. if (l_unlikely(ttisnil(tm)))
  342. luaG_callerror(L, s2v(func)); /* nothing to call */
  343. for (p = L->top; p > func; p--) /* open space for metamethod */
  344. setobjs2s(L, p, p-1);
  345. L->top++; /* stack space pre-allocated by the caller */
  346. setobj2s(L, func, tm); /* metamethod is the new function to be called */
  347. return func;
  348. }
  349. /*
  350. ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
  351. ** Handle most typical cases (zero results for commands, one result for
  352. ** expressions, multiple results for tail calls/single parameters)
  353. ** separated.
  354. */
  355. l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
  356. StkId firstresult;
  357. int i;
  358. switch (wanted) { /* handle typical cases separately */
  359. case 0: /* no values needed */
  360. L->top = res;
  361. return;
  362. case 1: /* one value needed */
  363. if (nres == 0) /* no results? */
  364. setnilvalue(s2v(res)); /* adjust with nil */
  365. else /* at least one result */
  366. setobjs2s(L, res, L->top - nres); /* move it to proper place */
  367. L->top = res + 1;
  368. return;
  369. case LUA_MULTRET:
  370. wanted = nres; /* we want all results */
  371. break;
  372. default: /* two/more results and/or to-be-closed variables */
  373. if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
  374. ptrdiff_t savedres = savestack(L, res);
  375. L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
  376. L->ci->u2.nres = nres;
  377. luaF_close(L, res, CLOSEKTOP, 1);
  378. L->ci->callstatus &= ~CIST_CLSRET;
  379. if (L->hookmask) /* if needed, call hook after '__close's */
  380. rethook(L, L->ci, nres);
  381. res = restorestack(L, savedres); /* close and hook can move stack */
  382. wanted = decodeNresults(wanted);
  383. if (wanted == LUA_MULTRET)
  384. wanted = nres; /* we want all results */
  385. }
  386. break;
  387. }
  388. /* generic case */
  389. firstresult = L->top - nres; /* index of first result */
  390. if (nres > wanted) /* extra results? */
  391. nres = wanted; /* don't need them */
  392. for (i = 0; i < nres; i++) /* move all results to correct place */
  393. setobjs2s(L, res + i, firstresult + i);
  394. for (; i < wanted; i++) /* complete wanted number of results */
  395. setnilvalue(s2v(res + i));
  396. L->top = res + wanted; /* top points after the last result */
  397. }
  398. /*
  399. ** Finishes a function call: calls hook if necessary, moves current
  400. ** number of results to proper place, and returns to previous call
  401. ** info. If function has to close variables, hook must be called after
  402. ** that.
  403. */
  404. void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
  405. int wanted = ci->nresults;
  406. if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
  407. rethook(L, ci, nres);
  408. /* move results to proper place */
  409. moveresults(L, ci->func, nres, wanted);
  410. /* function cannot be in any of these cases when returning */
  411. lua_assert(!(ci->callstatus &
  412. (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
  413. L->ci = ci->previous; /* back to caller (after closing variables) */
  414. }
  415. #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
  416. /*
  417. ** Prepare a function for a tail call, building its call info on top
  418. ** of the current call info. 'narg1' is the number of arguments plus 1
  419. ** (so that it includes the function itself).
  420. */
  421. void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
  422. Proto *p = clLvalue(s2v(func))->p;
  423. int fsize = p->maxstacksize; /* frame size */
  424. int nfixparams = p->numparams;
  425. int i;
  426. for (i = 0; i < narg1; i++) /* move down function and arguments */
  427. setobjs2s(L, ci->func + i, func + i);
  428. checkstackGC(L, fsize);
  429. func = ci->func; /* moved-down function */
  430. for (; narg1 <= nfixparams; narg1++)
  431. setnilvalue(s2v(func + narg1)); /* complete missing arguments */
  432. ci->top = func + 1 + fsize; /* top for new function */
  433. lua_assert(ci->top <= L->stack_last);
  434. ci->u.l.savedpc = p->code; /* starting point */
  435. ci->callstatus |= CIST_TAIL;
  436. L->top = func + narg1; /* set top */
  437. }
  438. l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
  439. int mask, StkId top) {
  440. CallInfo *ci = L->ci = next_ci(L); /* new frame */
  441. ci->func = func;
  442. ci->nresults = nret;
  443. ci->callstatus = mask;
  444. ci->top = top;
  445. return ci;
  446. }
  447. /*
  448. ** Prepares the call to a function (C or Lua). For C functions, also do
  449. ** the call. The function to be called is at '*func'. The arguments
  450. ** are on the stack, right after the function. Returns the CallInfo
  451. ** to be executed, if it was a Lua function. Otherwise (a C function)
  452. ** returns NULL, with all the results on the stack, starting at the
  453. ** original function position.
  454. */
  455. CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
  456. lua_CFunction f;
  457. retry:
  458. switch (ttypetag(s2v(func))) {
  459. case LUA_VCCL: /* C closure */
  460. f = clCvalue(s2v(func))->f;
  461. goto Cfunc;
  462. case LUA_VLCF: /* light C function */
  463. f = fvalue(s2v(func));
  464. Cfunc: {
  465. int n; /* number of returns */
  466. CallInfo *ci;
  467. checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
  468. L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
  469. L->top + LUA_MINSTACK);
  470. lua_assert(ci->top <= L->stack_last);
  471. if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
  472. int narg = cast_int(L->top - func) - 1;
  473. luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
  474. }
  475. lua_unlock(L);
  476. n = (*f)(L); /* do the actual call */
  477. lua_lock(L);
  478. api_checknelems(L, n);
  479. luaD_poscall(L, ci, n);
  480. return NULL;
  481. }
  482. case LUA_VLCL: { /* Lua function */
  483. CallInfo *ci;
  484. Proto *p = clLvalue(s2v(func))->p;
  485. int narg = cast_int(L->top - func) - 1; /* number of real arguments */
  486. int nfixparams = p->numparams;
  487. int fsize = p->maxstacksize; /* frame size */
  488. checkstackGCp(L, fsize, func);
  489. L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
  490. ci->u.l.savedpc = p->code; /* starting point */
  491. for (; narg < nfixparams; narg++)
  492. setnilvalue(s2v(L->top++)); /* complete missing arguments */
  493. lua_assert(ci->top <= L->stack_last);
  494. return ci;
  495. }
  496. default: { /* not a function */
  497. func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
  498. goto retry; /* try again with metamethod */
  499. }
  500. }
  501. }
  502. /*
  503. ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
  504. ** number of recursive invocations in the C stack) or nyci (the same
  505. ** plus increment number of non-yieldable calls).
  506. */
  507. l_sinline void ccall (lua_State *L, StkId func, int nResults, int inc) {
  508. CallInfo *ci;
  509. L->nCcalls += inc;
  510. if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
  511. luaE_checkcstack(L);
  512. if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
  513. ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
  514. luaV_execute(L, ci); /* call it */
  515. }
  516. L->nCcalls -= inc;
  517. }
  518. /*
  519. ** External interface for 'ccall'
  520. */
  521. void luaD_call (lua_State *L, StkId func, int nResults) {
  522. ccall(L, func, nResults, 1);
  523. }
  524. /*
  525. ** Similar to 'luaD_call', but does not allow yields during the call.
  526. */
  527. void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
  528. ccall(L, func, nResults, nyci);
  529. }
  530. /*
  531. ** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
  532. ** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
  533. ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
  534. ** If a '__close' method yields here, eventually control will be back
  535. ** to 'finishCcall' (when that '__close' method finally returns) and
  536. ** 'finishpcallk' will run again and close any still pending '__close'
  537. ** methods. Similarly, if a '__close' method errs, 'precover' calls
  538. ** 'unroll' which calls ''finishCcall' and we are back here again, to
  539. ** close any pending '__close' methods.
  540. ** Note that, up to the call to 'luaF_close', the corresponding
  541. ** 'CallInfo' is not modified, so that this repeated run works like the
  542. ** first one (except that it has at least one less '__close' to do). In
  543. ** particular, field CIST_RECST preserves the error status across these
  544. ** multiple runs, changing only if there is a new error.
  545. */
  546. static int finishpcallk (lua_State *L, CallInfo *ci) {
  547. int status = getcistrecst(ci); /* get original status */
  548. if (l_likely(status == LUA_OK)) /* no error? */
  549. status = LUA_YIELD; /* was interrupted by an yield */
  550. else { /* error */
  551. StkId func = restorestack(L, ci->u2.funcidx);
  552. L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
  553. luaF_close(L, func, status, 1); /* can yield or raise an error */
  554. func = restorestack(L, ci->u2.funcidx); /* stack may be moved */
  555. luaD_seterrorobj(L, status, func);
  556. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  557. setcistrecst(ci, LUA_OK); /* clear original status */
  558. }
  559. ci->callstatus &= ~CIST_YPCALL;
  560. L->errfunc = ci->u.c.old_errfunc;
  561. /* if it is here, there were errors or yields; unlike 'lua_pcallk',
  562. do not change status */
  563. return status;
  564. }
  565. /*
  566. ** Completes the execution of a C function interrupted by an yield.
  567. ** The interruption must have happened while the function was either
  568. ** closing its tbc variables in 'moveresults' or executing
  569. ** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
  570. ** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
  571. ** finishes the interrupted execution of 'lua_pcallk'. After that, it
  572. ** calls the continuation of the interrupted function and finally it
  573. ** completes the job of the 'luaD_call' that called the function. In
  574. ** the call to 'adjustresults', we do not know the number of results
  575. ** of the function called by 'lua_callk'/'lua_pcallk', so we are
  576. ** conservative and use LUA_MULTRET (always adjust).
  577. */
  578. static void finishCcall (lua_State *L, CallInfo *ci) {
  579. int n; /* actual number of results from C function */
  580. if (ci->callstatus & CIST_CLSRET) { /* was returning? */
  581. lua_assert(hastocloseCfunc(ci->nresults));
  582. n = ci->u2.nres; /* just redo 'luaD_poscall' */
  583. /* don't need to reset CIST_CLSRET, as it will be set again anyway */
  584. }
  585. else {
  586. int status = LUA_YIELD; /* default if there were no errors */
  587. /* must have a continuation and must be able to call it */
  588. lua_assert(ci->u.c.k != NULL && yieldable(L));
  589. if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
  590. status = finishpcallk(L, ci); /* finish it */
  591. adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
  592. lua_unlock(L);
  593. n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
  594. lua_lock(L);
  595. api_checknelems(L, n);
  596. }
  597. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  598. }
  599. /*
  600. ** Executes "full continuation" (everything in the stack) of a
  601. ** previously interrupted coroutine until the stack is empty (or another
  602. ** interruption long-jumps out of the loop).
  603. */
  604. static void unroll (lua_State *L, void *ud) {
  605. CallInfo *ci;
  606. UNUSED(ud);
  607. while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
  608. if (!isLua(ci)) /* C function? */
  609. finishCcall(L, ci); /* complete its execution */
  610. else { /* Lua function */
  611. luaV_finishOp(L); /* finish interrupted instruction */
  612. luaV_execute(L, ci); /* execute down to higher C 'boundary' */
  613. }
  614. }
  615. }
  616. /*
  617. ** Try to find a suspended protected call (a "recover point") for the
  618. ** given thread.
  619. */
  620. static CallInfo *findpcall (lua_State *L) {
  621. CallInfo *ci;
  622. for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
  623. if (ci->callstatus & CIST_YPCALL)
  624. return ci;
  625. }
  626. return NULL; /* no pending pcall */
  627. }
  628. /*
  629. ** Signal an error in the call to 'lua_resume', not in the execution
  630. ** of the coroutine itself. (Such errors should not be handled by any
  631. ** coroutine error handler and should not kill the coroutine.)
  632. */
  633. static int resume_error (lua_State *L, const char *msg, int narg) {
  634. L->top -= narg; /* remove args from the stack */
  635. setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
  636. api_incr_top(L);
  637. lua_unlock(L);
  638. return LUA_ERRRUN;
  639. }
  640. /*
  641. ** Do the work for 'lua_resume' in protected mode. Most of the work
  642. ** depends on the status of the coroutine: initial state, suspended
  643. ** inside a hook, or regularly suspended (optionally with a continuation
  644. ** function), plus erroneous cases: non-suspended coroutine or dead
  645. ** coroutine.
  646. */
  647. static void resume (lua_State *L, void *ud) {
  648. int n = *(cast(int*, ud)); /* number of arguments */
  649. StkId firstArg = L->top - n; /* first argument */
  650. CallInfo *ci = L->ci;
  651. if (L->status == LUA_OK) /* starting a coroutine? */
  652. ccall(L, firstArg - 1, LUA_MULTRET, 1); /* just call its body */
  653. else { /* resuming from previous yield */
  654. lua_assert(L->status == LUA_YIELD);
  655. L->status = LUA_OK; /* mark that it is running (again) */
  656. luaE_incCstack(L); /* control the C stack */
  657. if (isLua(ci)) { /* yielded inside a hook? */
  658. L->top = firstArg; /* discard arguments */
  659. luaV_execute(L, ci); /* just continue running Lua code */
  660. }
  661. else { /* 'common' yield */
  662. if (ci->u.c.k != NULL) { /* does it have a continuation function? */
  663. lua_unlock(L);
  664. n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
  665. lua_lock(L);
  666. api_checknelems(L, n);
  667. }
  668. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  669. }
  670. unroll(L, NULL); /* run continuation */
  671. }
  672. }
  673. /*
  674. ** Unrolls a coroutine in protected mode while there are recoverable
  675. ** errors, that is, errors inside a protected call. (Any error
  676. ** interrupts 'unroll', and this loop protects it again so it can
  677. ** continue.) Stops with a normal end (status == LUA_OK), an yield
  678. ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
  679. ** find a recover point).
  680. */
  681. static int precover (lua_State *L, int status) {
  682. CallInfo *ci;
  683. while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
  684. L->ci = ci; /* go down to recovery functions */
  685. setcistrecst(ci, status); /* status to finish 'pcall' */
  686. status = luaD_rawrunprotected(L, unroll, NULL);
  687. }
  688. return status;
  689. }
  690. LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
  691. int *nresults) {
  692. int status;
  693. lua_lock(L);
  694. if (L->status == LUA_OK) { /* may be starting a coroutine */
  695. if (L->ci != &L->base_ci) /* not in base level? */
  696. return resume_error(L, "cannot resume non-suspended coroutine", nargs);
  697. else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
  698. return resume_error(L, "cannot resume dead coroutine", nargs);
  699. }
  700. else if (L->status != LUA_YIELD) /* ended with errors? */
  701. return resume_error(L, "cannot resume dead coroutine", nargs);
  702. L->nCcalls = (from) ? getCcalls(from) : 0;
  703. luai_userstateresume(L, nargs);
  704. api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
  705. status = luaD_rawrunprotected(L, resume, &nargs);
  706. /* continue running after recoverable errors */
  707. status = precover(L, status);
  708. if (l_likely(!errorstatus(status)))
  709. lua_assert(status == L->status); /* normal end or yield */
  710. else { /* unrecoverable error */
  711. L->status = cast_byte(status); /* mark thread as 'dead' */
  712. luaD_seterrorobj(L, status, L->top); /* push error message */
  713. L->ci->top = L->top;
  714. }
  715. *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
  716. : cast_int(L->top - (L->ci->func + 1));
  717. lua_unlock(L);
  718. return status;
  719. }
  720. LUA_API int lua_isyieldable (lua_State *L) {
  721. return yieldable(L);
  722. }
  723. LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
  724. lua_KFunction k) {
  725. CallInfo *ci;
  726. luai_userstateyield(L, nresults);
  727. lua_lock(L);
  728. ci = L->ci;
  729. api_checknelems(L, nresults);
  730. if (l_unlikely(!yieldable(L))) {
  731. if (L != G(L)->mainthread)
  732. luaG_runerror(L, "attempt to yield across a C-call boundary");
  733. else
  734. luaG_runerror(L, "attempt to yield from outside a coroutine");
  735. }
  736. L->status = LUA_YIELD;
  737. ci->u2.nyield = nresults; /* save number of results */
  738. if (isLua(ci)) { /* inside a hook? */
  739. lua_assert(!isLuacode(ci));
  740. api_check(L, nresults == 0, "hooks cannot yield values");
  741. api_check(L, k == NULL, "hooks cannot continue after yielding");
  742. }
  743. else {
  744. if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
  745. ci->u.c.ctx = ctx; /* save context */
  746. luaD_throw(L, LUA_YIELD);
  747. }
  748. lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
  749. lua_unlock(L);
  750. return 0; /* return to 'luaD_hook' */
  751. }
  752. /*
  753. ** Auxiliary structure to call 'luaF_close' in protected mode.
  754. */
  755. struct CloseP {
  756. StkId level;
  757. int status;
  758. };
  759. /*
  760. ** Auxiliary function to call 'luaF_close' in protected mode.
  761. */
  762. static void closepaux (lua_State *L, void *ud) {
  763. struct CloseP *pcl = cast(struct CloseP *, ud);
  764. luaF_close(L, pcl->level, pcl->status, 0);
  765. }
  766. /*
  767. ** Calls 'luaF_close' in protected mode. Return the original status
  768. ** or, in case of errors, the new status.
  769. */
  770. int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
  771. CallInfo *old_ci = L->ci;
  772. lu_byte old_allowhooks = L->allowhook;
  773. for (;;) { /* keep closing upvalues until no more errors */
  774. struct CloseP pcl;
  775. pcl.level = restorestack(L, level); pcl.status = status;
  776. status = luaD_rawrunprotected(L, &closepaux, &pcl);
  777. if (l_likely(status == LUA_OK)) /* no more errors? */
  778. return pcl.status;
  779. else { /* an error occurred; restore saved state and repeat */
  780. L->ci = old_ci;
  781. L->allowhook = old_allowhooks;
  782. }
  783. }
  784. }
  785. /*
  786. ** Call the C function 'func' in protected mode, restoring basic
  787. ** thread information ('allowhook', etc.) and in particular
  788. ** its stack level in case of errors.
  789. */
  790. int luaD_pcall (lua_State *L, Pfunc func, void *u,
  791. ptrdiff_t old_top, ptrdiff_t ef) {
  792. int status;
  793. CallInfo *old_ci = L->ci;
  794. lu_byte old_allowhooks = L->allowhook;
  795. ptrdiff_t old_errfunc = L->errfunc;
  796. L->errfunc = ef;
  797. status = luaD_rawrunprotected(L, func, u);
  798. if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
  799. L->ci = old_ci;
  800. L->allowhook = old_allowhooks;
  801. status = luaD_closeprotected(L, old_top, status);
  802. luaD_seterrorobj(L, status, restorestack(L, old_top));
  803. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  804. }
  805. L->errfunc = old_errfunc;
  806. return status;
  807. }
  808. /*
  809. ** Execute a protected parser.
  810. */
  811. struct SParser { /* data to 'f_parser' */
  812. ZIO *z;
  813. Mbuffer buff; /* dynamic structure used by the scanner */
  814. Dyndata dyd; /* dynamic structures used by the parser */
  815. const char *mode;
  816. const char *name;
  817. };
  818. static void checkmode (lua_State *L, const char *mode, const char *x) {
  819. if (mode && strchr(mode, x[0]) == NULL) {
  820. luaO_pushfstring(L,
  821. "attempt to load a %s chunk (mode is '%s')", x, mode);
  822. luaD_throw(L, LUA_ERRSYNTAX);
  823. }
  824. }
  825. static void f_parser (lua_State *L, void *ud) {
  826. LClosure *cl;
  827. struct SParser *p = cast(struct SParser *, ud);
  828. int c = zgetc(p->z); /* read first character */
  829. if (c == LUA_SIGNATURE[0]) {
  830. checkmode(L, p->mode, "binary");
  831. cl = luaU_undump(L, p->z, p->name);
  832. }
  833. else {
  834. checkmode(L, p->mode, "text");
  835. cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
  836. }
  837. lua_assert(cl->nupvalues == cl->p->sizeupvalues);
  838. luaF_initupvals(L, cl);
  839. }
  840. int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
  841. const char *mode) {
  842. struct SParser p;
  843. int status;
  844. incnny(L); /* cannot yield during parsing */
  845. p.z = z; p.name = name; p.mode = mode;
  846. p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
  847. p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
  848. p.dyd.label.arr = NULL; p.dyd.label.size = 0;
  849. luaZ_initbuffer(L, &p.buff);
  850. status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
  851. luaZ_freebuffer(L, &p.buff);
  852. luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
  853. luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
  854. luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
  855. decnny(L);
  856. return status;
  857. }