ldo.c 35 KB

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