ldo.c 34 KB

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