ldo.c 38 KB

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