ldo.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. ** $Id: ldo.c,v 2.62 2009/04/26 21:55:35 roberto Exp roberto $
  3. ** Stack and Call structure of Lua
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <setjmp.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #define ldo_c
  10. #define LUA_CORE
  11. #include "lua.h"
  12. #include "lapi.h"
  13. #include "ldebug.h"
  14. #include "ldo.h"
  15. #include "lfunc.h"
  16. #include "lgc.h"
  17. #include "lmem.h"
  18. #include "lobject.h"
  19. #include "lopcodes.h"
  20. #include "lparser.h"
  21. #include "lstate.h"
  22. #include "lstring.h"
  23. #include "ltable.h"
  24. #include "ltm.h"
  25. #include "lundump.h"
  26. #include "lvm.h"
  27. #include "lzio.h"
  28. /*
  29. ** {======================================================
  30. ** Error-recovery functions
  31. ** =======================================================
  32. */
  33. /* chain list of long jump buffers */
  34. struct lua_longjmp {
  35. struct lua_longjmp *previous;
  36. luai_jmpbuf b;
  37. volatile int status; /* error code */
  38. };
  39. void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
  40. switch (errcode) {
  41. case LUA_ERRMEM: {
  42. setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG));
  43. break;
  44. }
  45. case LUA_ERRERR: {
  46. setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
  47. break;
  48. }
  49. case LUA_ERRSYNTAX:
  50. case LUA_ERRRUN: {
  51. setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
  52. break;
  53. }
  54. }
  55. L->top = oldtop + 1;
  56. }
  57. static void restore_stack_limit (lua_State *L) {
  58. if (L->nci >= LUAI_MAXCALLS) /* stack overflow? */
  59. luaE_freeCI(L); /* erase all extras CIs */
  60. }
  61. void luaD_throw (lua_State *L, int errcode) {
  62. if (L->errorJmp) { /* thread has an error handler? */
  63. L->errorJmp->status = errcode; /* set status */
  64. LUAI_THROW(L, L->errorJmp); /* jump to it */
  65. }
  66. else { /* thread has no error handler */
  67. L->status = cast_byte(errcode); /* mark it as dead */
  68. if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */
  69. setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */
  70. luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */
  71. }
  72. else { /* no handler at all; abort */
  73. if (G(L)->panic) { /* panic function? */
  74. lua_unlock(L);
  75. G(L)->panic(L); /* call it (last chance to jump out) */
  76. }
  77. abort();
  78. }
  79. }
  80. }
  81. int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
  82. unsigned short oldnCcalls = G(L)->nCcalls;
  83. struct lua_longjmp lj;
  84. lj.status = LUA_OK;
  85. lj.previous = L->errorJmp; /* chain new error handler */
  86. L->errorJmp = &lj;
  87. LUAI_TRY(L, &lj,
  88. (*f)(L, ud);
  89. );
  90. L->errorJmp = lj.previous; /* restore old error handler */
  91. G(L)->nCcalls = oldnCcalls;
  92. return lj.status;
  93. }
  94. /* }====================================================== */
  95. static void correctstack (lua_State *L, TValue *oldstack) {
  96. CallInfo *ci;
  97. GCObject *up;
  98. L->top = (L->top - oldstack) + L->stack;
  99. for (up = L->openupval; up != NULL; up = up->gch.next)
  100. gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
  101. for (ci = L->ci; ci != NULL; ci = ci->previous) {
  102. ci->top = (ci->top - oldstack) + L->stack;
  103. ci->base = (ci->base - oldstack) + L->stack;
  104. ci->func = (ci->func - oldstack) + L->stack;
  105. }
  106. L->base = (L->base - oldstack) + L->stack;
  107. }
  108. void luaD_reallocstack (lua_State *L, int newsize) {
  109. TValue *oldstack = L->stack;
  110. int lim = L->stacksize;
  111. int realsize = newsize + 1 + EXTRA_STACK;
  112. lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
  113. luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue);
  114. for (; lim < realsize; lim++)
  115. setnilvalue(L->stack + lim); /* erase new segment */
  116. L->stacksize = realsize;
  117. L->stack_last = L->stack+newsize;
  118. correctstack(L, oldstack);
  119. }
  120. void luaD_growstack (lua_State *L, int n) {
  121. if (n <= L->stacksize) /* double size is enough? */
  122. luaD_reallocstack(L, 2*L->stacksize);
  123. else
  124. luaD_reallocstack(L, L->stacksize + n);
  125. }
  126. void luaD_callhook (lua_State *L, int event, int line) {
  127. lua_Hook hook = L->hook;
  128. if (hook && L->allowhook) {
  129. CallInfo *ci = L->ci;
  130. ptrdiff_t top = savestack(L, L->top);
  131. ptrdiff_t ci_top = savestack(L, ci->top);
  132. lua_Debug ar;
  133. ar.event = event;
  134. ar.currentline = line;
  135. if (event == LUA_HOOKTAILRET)
  136. ar.i_ci = NULL; /* tail call; no debug information about it */
  137. else
  138. ar.i_ci = ci;
  139. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  140. ci->top = L->top + LUA_MINSTACK;
  141. lua_assert(ci->top <= L->stack_last);
  142. L->allowhook = 0; /* cannot call hooks inside a hook */
  143. ci->callstatus |= CIST_HOOKED;
  144. lua_unlock(L);
  145. (*hook)(L, &ar);
  146. lua_lock(L);
  147. lua_assert(!L->allowhook);
  148. L->allowhook = 1;
  149. ci->top = restorestack(L, ci_top);
  150. L->top = restorestack(L, top);
  151. ci->callstatus &= ~CIST_HOOKED;
  152. }
  153. }
  154. static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
  155. int i;
  156. int nfixargs = p->numparams;
  157. StkId base, fixed;
  158. lua_assert(actual >= nfixargs);
  159. /* move fixed parameters to final position */
  160. fixed = L->top - actual; /* first fixed argument */
  161. base = L->top; /* final position of first argument */
  162. for (i=0; i<nfixargs; i++) {
  163. setobjs2s(L, L->top++, fixed + i);
  164. setnilvalue(fixed + i);
  165. }
  166. return base;
  167. }
  168. static StkId tryfuncTM (lua_State *L, StkId func) {
  169. const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
  170. StkId p;
  171. ptrdiff_t funcr = savestack(L, func);
  172. if (!ttisfunction(tm))
  173. luaG_typeerror(L, func, "call");
  174. /* Open a hole inside the stack at `func' */
  175. for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
  176. incr_top(L);
  177. func = restorestack(L, funcr); /* previous call may change stack */
  178. setobj2s(L, func, tm); /* tag method is the new function to be called */
  179. return func;
  180. }
  181. #define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
  182. /*
  183. ** returns true if function has been executed (C function)
  184. */
  185. int luaD_precall (lua_State *L, StkId func, int nresults) {
  186. LClosure *cl;
  187. ptrdiff_t funcr;
  188. if (!ttisfunction(func)) /* `func' is not a function? */
  189. func = tryfuncTM(L, func); /* check the `function' tag method */
  190. funcr = savestack(L, func);
  191. cl = &clvalue(func)->l;
  192. L->ci->nresults = nresults;
  193. if (!cl->isC) { /* Lua function? prepare its call */
  194. CallInfo *ci;
  195. int nparams, nargs;
  196. StkId base;
  197. Proto *p = cl->p;
  198. luaD_checkstack(L, p->maxstacksize);
  199. func = restorestack(L, funcr);
  200. nargs = cast_int(L->top - func) - 1; /* number of real arguments */
  201. nparams = p->numparams; /* number of expected parameters */
  202. for (; nargs < nparams; nargs++)
  203. setnilvalue(L->top++); /* complete missing arguments */
  204. if (!p->is_vararg) /* no varargs? */
  205. base = func + 1;
  206. else /* vararg function */
  207. base = adjust_varargs(L, p, nargs);
  208. ci = next_ci(L); /* now 'enter' new function */
  209. ci->func = func;
  210. L->base = ci->base = base;
  211. ci->top = L->base + p->maxstacksize;
  212. lua_assert(ci->top <= L->stack_last);
  213. ci->u.l.savedpc = p->code; /* starting point */
  214. ci->u.l.tailcalls = 0;
  215. ci->callstatus = CIST_LUA;
  216. L->top = ci->top;
  217. if (L->hookmask & LUA_MASKCALL) {
  218. ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
  219. luaD_callhook(L, LUA_HOOKCALL, -1);
  220. ci->u.l.savedpc--; /* correct 'pc' */
  221. }
  222. return 0;
  223. }
  224. else { /* if is a C function, call it */
  225. CallInfo *ci;
  226. int n;
  227. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  228. ci = next_ci(L); /* now 'enter' new function */
  229. ci->func = restorestack(L, funcr);
  230. L->base = ci->base = ci->func + 1;
  231. ci->top = L->top + LUA_MINSTACK;
  232. lua_assert(ci->top <= L->stack_last);
  233. ci->callstatus = 0;
  234. if (L->hookmask & LUA_MASKCALL)
  235. luaD_callhook(L, LUA_HOOKCALL, -1);
  236. lua_unlock(L);
  237. n = (*curr_func(L)->c.f)(L); /* do the actual call */
  238. lua_lock(L);
  239. luaD_poscall(L, L->top - n);
  240. return 1;
  241. }
  242. }
  243. static StkId callrethooks (lua_State *L, StkId firstResult) {
  244. ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */
  245. luaD_callhook(L, LUA_HOOKRET, -1);
  246. if (isLua(L->ci)) { /* Lua function? */
  247. while ((L->hookmask & LUA_MASKRET) && L->ci->u.l.tailcalls--)
  248. luaD_callhook(L, LUA_HOOKTAILRET, -1); /* ret. hooks for tail calls */
  249. }
  250. return restorestack(L, fr);
  251. }
  252. int luaD_poscall (lua_State *L, StkId firstResult) {
  253. StkId res;
  254. int wanted, i;
  255. CallInfo *ci = L->ci;
  256. if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
  257. if (L->hookmask & LUA_MASKRET)
  258. firstResult = callrethooks(L, firstResult);
  259. L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for returning function */
  260. }
  261. res = ci->func; /* res == final position of 1st result */
  262. L->ci = ci = ci->previous; /* back to caller */
  263. wanted = ci->nresults;
  264. L->base = ci->base; /* restore base */
  265. /* move results to correct place */
  266. for (i = wanted; i != 0 && firstResult < L->top; i--)
  267. setobjs2s(L, res++, firstResult++);
  268. while (i-- > 0)
  269. setnilvalue(res++);
  270. L->top = res;
  271. return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */
  272. }
  273. /*
  274. ** Call a function (C or Lua). The function to be called is at *func.
  275. ** The arguments are on the stack, right after the function.
  276. ** When returns, all the results are on the stack, starting at the original
  277. ** function position.
  278. */
  279. void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {
  280. global_State *g = G(L);
  281. if (++g->nCcalls >= LUAI_MAXCCALLS) {
  282. if (g->nCcalls == LUAI_MAXCCALLS)
  283. luaG_runerror(L, "C stack overflow");
  284. else if (g->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
  285. luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
  286. }
  287. if (!allowyield) L->nny++;
  288. if (!luaD_precall(L, func, nResults)) /* is a Lua function? */
  289. luaV_execute(L); /* call it */
  290. if (!allowyield) L->nny--;
  291. g->nCcalls--;
  292. luaC_checkGC(L);
  293. }
  294. static void finishCcall (lua_State *L) {
  295. CallInfo *ci = L->ci;
  296. int n;
  297. lua_assert(ci->u.c.k != NULL); /* must have a continuation */
  298. lua_assert(L->nny == 0);
  299. /* finish 'luaD_call' */
  300. G(L)->nCcalls--;
  301. /* finish 'lua_callk' */
  302. adjustresults(L, ci->nresults);
  303. /* call continuation function */
  304. if (!(ci->callstatus & CIST_STAT)) /* no call status? */
  305. ci->u.c.status = LUA_YIELD; /* 'default' status */
  306. lua_assert(ci->u.c.status != LUA_OK);
  307. ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED;
  308. lua_unlock(L);
  309. n = (*ci->u.c.k)(L);
  310. lua_lock(L);
  311. /* finish 'luaD_precall' */
  312. luaD_poscall(L, L->top - n);
  313. }
  314. static void unroll (lua_State *L, void *ud) {
  315. UNUSED(ud);
  316. for (;;) {
  317. if (L->ci == &L->base_ci) /* stack is empty? */
  318. return; /* coroutine finished normally */
  319. if (!isLua(L->ci)) /* C function? */
  320. finishCcall(L);
  321. else { /* Lua function */
  322. luaV_finishOp(L); /* finish interrupted instruction */
  323. luaV_execute(L); /* execute down to higher C 'boundary' */
  324. }
  325. }
  326. }
  327. static void resume (lua_State *L, void *ud) {
  328. StkId firstArg = cast(StkId, ud);
  329. CallInfo *ci = L->ci;
  330. if (L->status == LUA_OK) { /* start coroutine? */
  331. lua_assert(ci == &L->base_ci && firstArg > L->base);
  332. if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */
  333. luaV_execute(L); /* call it */
  334. }
  335. else { /* resuming from previous yield */
  336. lua_assert(L->status == LUA_YIELD);
  337. L->status = LUA_OK;
  338. if (isLua(ci)) { /* yielded inside a hook? */
  339. L->base = ci->base; /* just continue its execution */
  340. luaV_execute(L);
  341. }
  342. else { /* 'common' yield */
  343. G(L)->nCcalls--; /* finish 'luaD_call' */
  344. luaD_poscall(L, firstArg); /* finish 'luaD_precall' */
  345. }
  346. unroll(L, NULL);
  347. }
  348. }
  349. static int resume_error (lua_State *L, const char *msg) {
  350. L->top = L->ci->base;
  351. setsvalue2s(L, L->top, luaS_new(L, msg));
  352. incr_top(L);
  353. lua_unlock(L);
  354. return LUA_ERRRUN;
  355. }
  356. /*
  357. ** check whether thread has a suspended protected call
  358. */
  359. static CallInfo *findpcall (lua_State *L) {
  360. CallInfo *ci;
  361. for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
  362. if (ci->callstatus & CIST_YPCALL)
  363. return ci;
  364. }
  365. return NULL; /* no pending pcall */
  366. }
  367. static int recover (lua_State *L, int status) {
  368. StkId oldtop;
  369. CallInfo *ci = findpcall(L);
  370. if (ci == NULL) return 0; /* no recovery point */
  371. /* "finish" luaD_pcall */
  372. oldtop = restorestack(L, ci->u.c.oldtop);
  373. luaF_close(L, oldtop);
  374. luaD_seterrorobj(L, status, oldtop);
  375. L->ci = ci;
  376. L->base = ci->base;
  377. L->allowhook = ci->u.c.old_allowhook;
  378. L->nny = 0; /* should be zero to be yieldable */
  379. restore_stack_limit(L);
  380. L->errfunc = ci->u.c.old_errfunc;
  381. ci->callstatus |= CIST_STAT; /* call has error status */
  382. ci->u.c.status = status; /* (here it is) */
  383. return 1; /* continue running the coroutine */
  384. }
  385. LUA_API int lua_resume (lua_State *L, int nargs) {
  386. int status;
  387. lua_lock(L);
  388. if (L->status != LUA_YIELD) {
  389. if (L->status != LUA_OK)
  390. return resume_error(L, "cannot resume dead coroutine");
  391. else if (L->ci != &L->base_ci)
  392. return resume_error(L, "cannot resume non-suspended coroutine");
  393. }
  394. luai_userstateresume(L, nargs);
  395. if (G(L)->nCcalls >= LUAI_MAXCCALLS)
  396. return resume_error(L, "C stack overflow");
  397. ++G(L)->nCcalls; /* count resume */
  398. L->nny = 0; /* allow yields */
  399. status = luaD_rawrunprotected(L, resume, L->top - nargs);
  400. while (status != LUA_OK && status != LUA_YIELD) { /* error? */
  401. if (recover(L, status)) /* recover point? */
  402. status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */
  403. else { /* unrecoverable error */
  404. L->status = cast_byte(status); /* mark thread as `dead' */
  405. luaD_seterrorobj(L, status, L->top);
  406. L->ci->top = L->top;
  407. break;
  408. }
  409. }
  410. lua_assert(status == L->status);
  411. L->nny = 1; /* do not allow yields */
  412. --G(L)->nCcalls;
  413. lua_unlock(L);
  414. return status;
  415. }
  416. LUA_API int lua_yield (lua_State *L, int nresults) {
  417. luai_userstateyield(L, nresults);
  418. lua_lock(L);
  419. if (L->nny > 0)
  420. luaG_runerror(L, "attempt to yield across metamethod/C-call boundary");
  421. L->base = L->top - nresults; /* protect stack slots below */
  422. L->status = LUA_YIELD;
  423. if (!isLua(L->ci)) /* not inside a hook? */
  424. luaD_throw(L, LUA_YIELD);
  425. lua_assert(L->ci->callstatus & CIST_HOOKED); /* must be inside a hook */
  426. lua_unlock(L);
  427. return 0; /* otherwise, return to 'luaD_callhook' */
  428. }
  429. int luaD_pcall (lua_State *L, Pfunc func, void *u,
  430. ptrdiff_t old_top, ptrdiff_t ef) {
  431. int status;
  432. CallInfo *old_ci = L->ci;
  433. lu_byte old_allowhooks = L->allowhook;
  434. unsigned short old_nny = L->nny;
  435. ptrdiff_t old_errfunc = L->errfunc;
  436. L->errfunc = ef;
  437. status = luaD_rawrunprotected(L, func, u);
  438. if (status != LUA_OK) { /* an error occurred? */
  439. StkId oldtop = restorestack(L, old_top);
  440. luaF_close(L, oldtop); /* close possible pending closures */
  441. luaD_seterrorobj(L, status, oldtop);
  442. L->ci = old_ci;
  443. L->base = old_ci->base;
  444. L->allowhook = old_allowhooks;
  445. L->nny = old_nny;
  446. restore_stack_limit(L);
  447. }
  448. L->errfunc = old_errfunc;
  449. return status;
  450. }
  451. /*
  452. ** Execute a protected parser.
  453. */
  454. struct SParser { /* data to `f_parser' */
  455. ZIO *z;
  456. Mbuffer buff; /* buffer to be used by the scanner */
  457. const char *name;
  458. };
  459. static void f_parser (lua_State *L, void *ud) {
  460. int i;
  461. Proto *tf;
  462. Closure *cl;
  463. struct SParser *p = cast(struct SParser *, ud);
  464. int c = luaZ_lookahead(p->z);
  465. luaC_checkGC(L);
  466. tf = (c == LUA_SIGNATURE[0]) ? luaU_undump(L, p->z, &p->buff, p->name)
  467. : luaY_parser(L, p->z, &p->buff, p->name);
  468. setptvalue2s(L, L->top, tf);
  469. incr_top(L);
  470. cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
  471. cl->l.p = tf;
  472. setclvalue(L, L->top - 1, cl);
  473. for (i = 0; i < tf->nups; i++) /* initialize upvalues */
  474. cl->l.upvals[i] = luaF_newupval(L);
  475. }
  476. int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) {
  477. struct SParser p;
  478. int status;
  479. p.z = z; p.name = name;
  480. luaZ_initbuffer(L, &p.buff);
  481. status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
  482. luaZ_freebuffer(L, &p.buff);
  483. return status;
  484. }