ldo.c 37 KB

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