ldo.c 38 KB

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