ldo.c 38 KB

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