ldo.c 34 KB

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