ldo.c 16 KB

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