ldo.c 35 KB

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