ldo.c 33 KB

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