ldo.c 34 KB

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