ldo.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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;
  339. StkId p;
  340. checkstackGCp(L, 1, func); /* space for metamethod */
  341. tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */
  342. if (l_unlikely(ttisnil(tm)))
  343. luaG_callerror(L, s2v(func)); /* nothing to call */
  344. for (p = L->top; p > func; p--) /* open space for metamethod */
  345. setobjs2s(L, p, p-1);
  346. L->top++; /* stack space pre-allocated by the caller */
  347. setobj2s(L, func, tm); /* metamethod is the new function to be called */
  348. return func;
  349. }
  350. /*
  351. ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
  352. ** Handle most typical cases (zero results for commands, one result for
  353. ** expressions, multiple results for tail calls/single parameters)
  354. ** separated.
  355. */
  356. l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
  357. StkId firstresult;
  358. int i;
  359. switch (wanted) { /* handle typical cases separately */
  360. case 0: /* no values needed */
  361. L->top = res;
  362. return;
  363. case 1: /* one value needed */
  364. if (nres == 0) /* no results? */
  365. setnilvalue(s2v(res)); /* adjust with nil */
  366. else /* at least one result */
  367. setobjs2s(L, res, L->top - nres); /* move it to proper place */
  368. L->top = res + 1;
  369. return;
  370. case LUA_MULTRET:
  371. wanted = nres; /* we want all results */
  372. break;
  373. default: /* two/more results and/or to-be-closed variables */
  374. if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
  375. ptrdiff_t savedres = savestack(L, res);
  376. L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
  377. L->ci->u2.nres = nres;
  378. luaF_close(L, res, CLOSEKTOP, 1);
  379. L->ci->callstatus &= ~CIST_CLSRET;
  380. if (L->hookmask) /* if needed, call hook after '__close's */
  381. rethook(L, L->ci, nres);
  382. res = restorestack(L, savedres); /* close and hook can move stack */
  383. wanted = decodeNresults(wanted);
  384. if (wanted == LUA_MULTRET)
  385. wanted = nres; /* we want all results */
  386. }
  387. break;
  388. }
  389. /* generic case */
  390. firstresult = L->top - nres; /* index of first result */
  391. if (nres > wanted) /* extra results? */
  392. nres = wanted; /* don't need them */
  393. for (i = 0; i < nres; i++) /* move all results to correct place */
  394. setobjs2s(L, res + i, firstresult + i);
  395. for (; i < wanted; i++) /* complete wanted number of results */
  396. setnilvalue(s2v(res + i));
  397. L->top = res + wanted; /* top points after the last result */
  398. }
  399. /*
  400. ** Finishes a function call: calls hook if necessary, moves current
  401. ** number of results to proper place, and returns to previous call
  402. ** info. If function has to close variables, hook must be called after
  403. ** that.
  404. */
  405. void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
  406. int wanted = ci->nresults;
  407. if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
  408. rethook(L, ci, nres);
  409. /* move results to proper place */
  410. moveresults(L, ci->func, nres, wanted);
  411. /* function cannot be in any of these cases when returning */
  412. lua_assert(!(ci->callstatus &
  413. (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
  414. L->ci = ci->previous; /* back to caller (after closing variables) */
  415. }
  416. #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
  417. l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
  418. int mask, StkId top) {
  419. CallInfo *ci = L->ci = next_ci(L); /* new frame */
  420. ci->func = func;
  421. ci->nresults = nret;
  422. ci->callstatus = mask;
  423. ci->top = top;
  424. return ci;
  425. }
  426. /*
  427. ** precall for C functions
  428. */
  429. l_sinline int precallC (lua_State *L, StkId func, int nresults,
  430. lua_CFunction f) {
  431. int n; /* number of returns */
  432. CallInfo *ci;
  433. checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
  434. L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
  435. L->top + LUA_MINSTACK);
  436. lua_assert(ci->top <= L->stack_last);
  437. if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
  438. int narg = cast_int(L->top - func) - 1;
  439. luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
  440. }
  441. lua_unlock(L);
  442. n = (*f)(L); /* do the actual call */
  443. lua_lock(L);
  444. api_checknelems(L, n);
  445. luaD_poscall(L, ci, n);
  446. return n;
  447. }
  448. /*
  449. ** Prepare a function for a tail call, building its call info on top
  450. ** of the current call info. 'narg1' is the number of arguments plus 1
  451. ** (so that it includes the function itself). Return the number of
  452. ** results, if it was a C function, or -1 for a Lua function.
  453. */
  454. int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
  455. int narg1, int delta) {
  456. retry:
  457. switch (ttypetag(s2v(func))) {
  458. case LUA_VCCL: /* C closure */
  459. return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);
  460. case LUA_VLCF: /* light C function */
  461. return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));
  462. case LUA_VLCL: { /* Lua function */
  463. Proto *p = clLvalue(s2v(func))->p;
  464. int fsize = p->maxstacksize; /* frame size */
  465. int nfixparams = p->numparams;
  466. int i;
  467. checkstackGCp(L, fsize - delta, func);
  468. ci->func -= delta; /* restore 'func' (if vararg) */
  469. for (i = 0; i < narg1; i++) /* move down function and arguments */
  470. setobjs2s(L, ci->func + i, func + i);
  471. func = ci->func; /* moved-down function */
  472. for (; narg1 <= nfixparams; narg1++)
  473. setnilvalue(s2v(func + narg1)); /* complete missing arguments */
  474. ci->top = func + 1 + fsize; /* top for new function */
  475. lua_assert(ci->top <= L->stack_last);
  476. ci->u.l.savedpc = p->code; /* starting point */
  477. ci->callstatus |= CIST_TAIL;
  478. L->top = func + narg1; /* set top */
  479. return -1;
  480. }
  481. default: { /* not a function */
  482. func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
  483. /* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */
  484. narg1++;
  485. goto retry; /* try again */
  486. }
  487. }
  488. }
  489. /*
  490. ** Prepares the call to a function (C or Lua). For C functions, also do
  491. ** the call. The function to be called is at '*func'. The arguments
  492. ** are on the stack, right after the function. Returns the CallInfo
  493. ** to be executed, if it was a Lua function. Otherwise (a C function)
  494. ** returns NULL, with all the results on the stack, starting at the
  495. ** original function position.
  496. */
  497. CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
  498. retry:
  499. switch (ttypetag(s2v(func))) {
  500. case LUA_VCCL: /* C closure */
  501. precallC(L, func, nresults, clCvalue(s2v(func))->f);
  502. return NULL;
  503. case LUA_VLCF: /* light C function */
  504. precallC(L, func, nresults, fvalue(s2v(func)));
  505. return NULL;
  506. case LUA_VLCL: { /* Lua function */
  507. CallInfo *ci;
  508. Proto *p = clLvalue(s2v(func))->p;
  509. int narg = cast_int(L->top - func) - 1; /* number of real arguments */
  510. int nfixparams = p->numparams;
  511. int fsize = p->maxstacksize; /* frame size */
  512. checkstackGCp(L, fsize, func);
  513. L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
  514. ci->u.l.savedpc = p->code; /* starting point */
  515. for (; narg < nfixparams; narg++)
  516. setnilvalue(s2v(L->top++)); /* complete missing arguments */
  517. lua_assert(ci->top <= L->stack_last);
  518. return ci;
  519. }
  520. default: { /* not a function */
  521. func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
  522. /* return luaD_precall(L, func, nresults); */
  523. goto retry; /* try again with metamethod */
  524. }
  525. }
  526. }
  527. /*
  528. ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
  529. ** number of recursive invocations in the C stack) or nyci (the same
  530. ** plus increment number of non-yieldable calls).
  531. */
  532. l_sinline void ccall (lua_State *L, StkId func, int nResults, int inc) {
  533. CallInfo *ci;
  534. L->nCcalls += inc;
  535. if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
  536. luaE_checkcstack(L);
  537. if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
  538. ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
  539. luaV_execute(L, ci); /* call it */
  540. }
  541. L->nCcalls -= inc;
  542. }
  543. /*
  544. ** External interface for 'ccall'
  545. */
  546. void luaD_call (lua_State *L, StkId func, int nResults) {
  547. ccall(L, func, nResults, 1);
  548. }
  549. /*
  550. ** Similar to 'luaD_call', but does not allow yields during the call.
  551. */
  552. void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
  553. ccall(L, func, nResults, nyci);
  554. }
  555. /*
  556. ** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
  557. ** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
  558. ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
  559. ** If a '__close' method yields here, eventually control will be back
  560. ** to 'finishCcall' (when that '__close' method finally returns) and
  561. ** 'finishpcallk' will run again and close any still pending '__close'
  562. ** methods. Similarly, if a '__close' method errs, 'precover' calls
  563. ** 'unroll' which calls ''finishCcall' and we are back here again, to
  564. ** close any pending '__close' methods.
  565. ** Note that, up to the call to 'luaF_close', the corresponding
  566. ** 'CallInfo' is not modified, so that this repeated run works like the
  567. ** first one (except that it has at least one less '__close' to do). In
  568. ** particular, field CIST_RECST preserves the error status across these
  569. ** multiple runs, changing only if there is a new error.
  570. */
  571. static int finishpcallk (lua_State *L, CallInfo *ci) {
  572. int status = getcistrecst(ci); /* get original status */
  573. if (l_likely(status == LUA_OK)) /* no error? */
  574. status = LUA_YIELD; /* was interrupted by an yield */
  575. else { /* error */
  576. StkId func = restorestack(L, ci->u2.funcidx);
  577. L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
  578. luaF_close(L, func, status, 1); /* can yield or raise an error */
  579. func = restorestack(L, ci->u2.funcidx); /* stack may be moved */
  580. luaD_seterrorobj(L, status, func);
  581. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  582. setcistrecst(ci, LUA_OK); /* clear original status */
  583. }
  584. ci->callstatus &= ~CIST_YPCALL;
  585. L->errfunc = ci->u.c.old_errfunc;
  586. /* if it is here, there were errors or yields; unlike 'lua_pcallk',
  587. do not change status */
  588. return status;
  589. }
  590. /*
  591. ** Completes the execution of a C function interrupted by an yield.
  592. ** The interruption must have happened while the function was either
  593. ** closing its tbc variables in 'moveresults' or executing
  594. ** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
  595. ** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
  596. ** finishes the interrupted execution of 'lua_pcallk'. After that, it
  597. ** calls the continuation of the interrupted function and finally it
  598. ** completes the job of the 'luaD_call' that called the function. In
  599. ** the call to 'adjustresults', we do not know the number of results
  600. ** of the function called by 'lua_callk'/'lua_pcallk', so we are
  601. ** conservative and use LUA_MULTRET (always adjust).
  602. */
  603. static void finishCcall (lua_State *L, CallInfo *ci) {
  604. int n; /* actual number of results from C function */
  605. if (ci->callstatus & CIST_CLSRET) { /* was returning? */
  606. lua_assert(hastocloseCfunc(ci->nresults));
  607. n = ci->u2.nres; /* just redo 'luaD_poscall' */
  608. /* don't need to reset CIST_CLSRET, as it will be set again anyway */
  609. }
  610. else {
  611. int status = LUA_YIELD; /* default if there were no errors */
  612. /* must have a continuation and must be able to call it */
  613. lua_assert(ci->u.c.k != NULL && yieldable(L));
  614. if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
  615. status = finishpcallk(L, ci); /* finish it */
  616. adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
  617. lua_unlock(L);
  618. n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
  619. lua_lock(L);
  620. api_checknelems(L, n);
  621. }
  622. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  623. }
  624. /*
  625. ** Executes "full continuation" (everything in the stack) of a
  626. ** previously interrupted coroutine until the stack is empty (or another
  627. ** interruption long-jumps out of the loop).
  628. */
  629. static void unroll (lua_State *L, void *ud) {
  630. CallInfo *ci;
  631. UNUSED(ud);
  632. while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
  633. if (!isLua(ci)) /* C function? */
  634. finishCcall(L, ci); /* complete its execution */
  635. else { /* Lua function */
  636. luaV_finishOp(L); /* finish interrupted instruction */
  637. luaV_execute(L, ci); /* execute down to higher C 'boundary' */
  638. }
  639. }
  640. }
  641. /*
  642. ** Try to find a suspended protected call (a "recover point") for the
  643. ** given thread.
  644. */
  645. static CallInfo *findpcall (lua_State *L) {
  646. CallInfo *ci;
  647. for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
  648. if (ci->callstatus & CIST_YPCALL)
  649. return ci;
  650. }
  651. return NULL; /* no pending pcall */
  652. }
  653. /*
  654. ** Signal an error in the call to 'lua_resume', not in the execution
  655. ** of the coroutine itself. (Such errors should not be handled by any
  656. ** coroutine error handler and should not kill the coroutine.)
  657. */
  658. static int resume_error (lua_State *L, const char *msg, int narg) {
  659. L->top -= narg; /* remove args from the stack */
  660. setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
  661. api_incr_top(L);
  662. lua_unlock(L);
  663. return LUA_ERRRUN;
  664. }
  665. /*
  666. ** Do the work for 'lua_resume' in protected mode. Most of the work
  667. ** depends on the status of the coroutine: initial state, suspended
  668. ** inside a hook, or regularly suspended (optionally with a continuation
  669. ** function), plus erroneous cases: non-suspended coroutine or dead
  670. ** coroutine.
  671. */
  672. static void resume (lua_State *L, void *ud) {
  673. int n = *(cast(int*, ud)); /* number of arguments */
  674. StkId firstArg = L->top - n; /* first argument */
  675. CallInfo *ci = L->ci;
  676. if (L->status == LUA_OK) /* starting a coroutine? */
  677. ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
  678. else { /* resuming from previous yield */
  679. lua_assert(L->status == LUA_YIELD);
  680. L->status = LUA_OK; /* mark that it is running (again) */
  681. if (isLua(ci)) { /* yielded inside a hook? */
  682. L->top = firstArg; /* discard arguments */
  683. luaV_execute(L, ci); /* just continue running Lua code */
  684. }
  685. else { /* 'common' yield */
  686. if (ci->u.c.k != NULL) { /* does it have a continuation function? */
  687. lua_unlock(L);
  688. n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
  689. lua_lock(L);
  690. api_checknelems(L, n);
  691. }
  692. luaD_poscall(L, ci, n); /* finish 'luaD_call' */
  693. }
  694. unroll(L, NULL); /* run continuation */
  695. }
  696. }
  697. /*
  698. ** Unrolls a coroutine in protected mode while there are recoverable
  699. ** errors, that is, errors inside a protected call. (Any error
  700. ** interrupts 'unroll', and this loop protects it again so it can
  701. ** continue.) Stops with a normal end (status == LUA_OK), an yield
  702. ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
  703. ** find a recover point).
  704. */
  705. static int precover (lua_State *L, int status) {
  706. CallInfo *ci;
  707. while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
  708. L->ci = ci; /* go down to recovery functions */
  709. setcistrecst(ci, status); /* status to finish 'pcall' */
  710. status = luaD_rawrunprotected(L, unroll, NULL);
  711. }
  712. return status;
  713. }
  714. LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
  715. int *nresults) {
  716. int status;
  717. lua_lock(L);
  718. if (L->status == LUA_OK) { /* may be starting a coroutine */
  719. if (L->ci != &L->base_ci) /* not in base level? */
  720. return resume_error(L, "cannot resume non-suspended coroutine", nargs);
  721. else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
  722. return resume_error(L, "cannot resume dead coroutine", nargs);
  723. }
  724. else if (L->status != LUA_YIELD) /* ended with errors? */
  725. return resume_error(L, "cannot resume dead coroutine", nargs);
  726. L->nCcalls = (from) ? getCcalls(from) : 0;
  727. if (getCcalls(L) >= LUAI_MAXCCALLS)
  728. return resume_error(L, "C stack overflow", nargs);
  729. L->nCcalls++;
  730. luai_userstateresume(L, nargs);
  731. api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
  732. status = luaD_rawrunprotected(L, resume, &nargs);
  733. /* continue running after recoverable errors */
  734. status = precover(L, status);
  735. if (l_likely(!errorstatus(status)))
  736. lua_assert(status == L->status); /* normal end or yield */
  737. else { /* unrecoverable error */
  738. L->status = cast_byte(status); /* mark thread as 'dead' */
  739. luaD_seterrorobj(L, status, L->top); /* push error message */
  740. L->ci->top = L->top;
  741. }
  742. *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
  743. : cast_int(L->top - (L->ci->func + 1));
  744. lua_unlock(L);
  745. return status;
  746. }
  747. LUA_API int lua_isyieldable (lua_State *L) {
  748. return yieldable(L);
  749. }
  750. LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
  751. lua_KFunction k) {
  752. CallInfo *ci;
  753. luai_userstateyield(L, nresults);
  754. lua_lock(L);
  755. ci = L->ci;
  756. api_checknelems(L, nresults);
  757. if (l_unlikely(!yieldable(L))) {
  758. if (L != G(L)->mainthread)
  759. luaG_runerror(L, "attempt to yield across a C-call boundary");
  760. else
  761. luaG_runerror(L, "attempt to yield from outside a coroutine");
  762. }
  763. L->status = LUA_YIELD;
  764. ci->u2.nyield = nresults; /* save number of results */
  765. if (isLua(ci)) { /* inside a hook? */
  766. lua_assert(!isLuacode(ci));
  767. api_check(L, nresults == 0, "hooks cannot yield values");
  768. api_check(L, k == NULL, "hooks cannot continue after yielding");
  769. }
  770. else {
  771. if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
  772. ci->u.c.ctx = ctx; /* save context */
  773. luaD_throw(L, LUA_YIELD);
  774. }
  775. lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
  776. lua_unlock(L);
  777. return 0; /* return to 'luaD_hook' */
  778. }
  779. /*
  780. ** Auxiliary structure to call 'luaF_close' in protected mode.
  781. */
  782. struct CloseP {
  783. StkId level;
  784. int status;
  785. };
  786. /*
  787. ** Auxiliary function to call 'luaF_close' in protected mode.
  788. */
  789. static void closepaux (lua_State *L, void *ud) {
  790. struct CloseP *pcl = cast(struct CloseP *, ud);
  791. luaF_close(L, pcl->level, pcl->status, 0);
  792. }
  793. /*
  794. ** Calls 'luaF_close' in protected mode. Return the original status
  795. ** or, in case of errors, the new status.
  796. */
  797. int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
  798. CallInfo *old_ci = L->ci;
  799. lu_byte old_allowhooks = L->allowhook;
  800. for (;;) { /* keep closing upvalues until no more errors */
  801. struct CloseP pcl;
  802. pcl.level = restorestack(L, level); pcl.status = status;
  803. status = luaD_rawrunprotected(L, &closepaux, &pcl);
  804. if (l_likely(status == LUA_OK)) /* no more errors? */
  805. return pcl.status;
  806. else { /* an error occurred; restore saved state and repeat */
  807. L->ci = old_ci;
  808. L->allowhook = old_allowhooks;
  809. }
  810. }
  811. }
  812. /*
  813. ** Call the C function 'func' in protected mode, restoring basic
  814. ** thread information ('allowhook', etc.) and in particular
  815. ** its stack level in case of errors.
  816. */
  817. int luaD_pcall (lua_State *L, Pfunc func, void *u,
  818. ptrdiff_t old_top, ptrdiff_t ef) {
  819. int status;
  820. CallInfo *old_ci = L->ci;
  821. lu_byte old_allowhooks = L->allowhook;
  822. ptrdiff_t old_errfunc = L->errfunc;
  823. L->errfunc = ef;
  824. status = luaD_rawrunprotected(L, func, u);
  825. if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
  826. L->ci = old_ci;
  827. L->allowhook = old_allowhooks;
  828. status = luaD_closeprotected(L, old_top, status);
  829. luaD_seterrorobj(L, status, restorestack(L, old_top));
  830. luaD_shrinkstack(L); /* restore stack size in case of overflow */
  831. }
  832. L->errfunc = old_errfunc;
  833. return status;
  834. }
  835. /*
  836. ** Execute a protected parser.
  837. */
  838. struct SParser { /* data to 'f_parser' */
  839. ZIO *z;
  840. Mbuffer buff; /* dynamic structure used by the scanner */
  841. Dyndata dyd; /* dynamic structures used by the parser */
  842. const char *mode;
  843. const char *name;
  844. };
  845. static void checkmode (lua_State *L, const char *mode, const char *x) {
  846. if (mode && strchr(mode, x[0]) == NULL) {
  847. luaO_pushfstring(L,
  848. "attempt to load a %s chunk (mode is '%s')", x, mode);
  849. luaD_throw(L, LUA_ERRSYNTAX);
  850. }
  851. }
  852. static void f_parser (lua_State *L, void *ud) {
  853. LClosure *cl;
  854. struct SParser *p = cast(struct SParser *, ud);
  855. int c = zgetc(p->z); /* read first character */
  856. if (c == LUA_SIGNATURE[0]) {
  857. checkmode(L, p->mode, "binary");
  858. cl = luaU_undump(L, p->z, p->name);
  859. }
  860. else {
  861. checkmode(L, p->mode, "text");
  862. cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
  863. }
  864. lua_assert(cl->nupvalues == cl->p->sizeupvalues);
  865. luaF_initupvals(L, cl);
  866. }
  867. int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
  868. const char *mode) {
  869. struct SParser p;
  870. int status;
  871. incnny(L); /* cannot yield during parsing */
  872. p.z = z; p.name = name; p.mode = mode;
  873. p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
  874. p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
  875. p.dyd.label.arr = NULL; p.dyd.label.size = 0;
  876. luaZ_initbuffer(L, &p.buff);
  877. status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
  878. luaZ_freebuffer(L, &p.buff);
  879. luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
  880. luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
  881. luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
  882. decnny(L);
  883. return status;
  884. }