ldo.c 36 KB

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