ldo.c 16 KB

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