ldo.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. ** $Id: ldo.c,v 1.167 2002/03/25 19:45:06 roberto Exp roberto $
  3. ** Stack and Call structure of Lua
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <setjmp.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "lua.h"
  11. #include "ldebug.h"
  12. #include "ldo.h"
  13. #include "lfunc.h"
  14. #include "lgc.h"
  15. #include "lmem.h"
  16. #include "lobject.h"
  17. #include "lopcodes.h"
  18. #include "lparser.h"
  19. #include "lstate.h"
  20. #include "lstring.h"
  21. #include "ltable.h"
  22. #include "ltm.h"
  23. #include "lundump.h"
  24. #include "lvm.h"
  25. #include "lzio.h"
  26. /* chain list of long jump buffers */
  27. struct lua_longjmp {
  28. struct lua_longjmp *previous;
  29. CallInfo *ci; /* index of call info of active function that set protection */
  30. StkId top; /* top stack when protection was set */
  31. jmp_buf b;
  32. int allowhooks; /* `allowhook' state when protection was set */
  33. volatile int status; /* error code */
  34. };
  35. static void correctstack (lua_State *L, TObject *oldstack) {
  36. struct lua_longjmp *lj;
  37. CallInfo *ci;
  38. UpVal *up;
  39. L->top = (L->top - oldstack) + L->stack;
  40. for (lj = L->errorJmp; lj != NULL; lj = lj->previous)
  41. lj->top = (lj->top - oldstack) + L->stack;
  42. for (up = L->openupval; up != NULL; up = up->next)
  43. up->v = (up->v - oldstack) + L->stack;
  44. for (ci = L->base_ci; ci <= L->ci; ci++) {
  45. ci->base = (ci->base - oldstack) + L->stack;
  46. ci->top = (ci->top - oldstack) + L->stack;
  47. if (ci->pc) { /* entry is of an active Lua function? */
  48. if (ci->pc != (ci-1)->pc)
  49. *ci->pb = (*ci->pb - oldstack) + L->stack;
  50. }
  51. }
  52. }
  53. void luaD_reallocstack (lua_State *L, int newsize) {
  54. TObject *oldstack = L->stack;
  55. luaM_reallocvector(L, L->stack, L->stacksize, newsize, TObject);
  56. L->stacksize = newsize;
  57. L->stack_last = L->stack+(newsize-EXTRA_STACK)-1;
  58. correctstack(L, oldstack);
  59. }
  60. static void correctCI (lua_State *L, CallInfo *oldci) {
  61. struct lua_longjmp *lj;
  62. for (lj = L->errorJmp; lj != NULL; lj = lj->previous) {
  63. lj->ci = (lj->ci - oldci) + L->base_ci;
  64. }
  65. }
  66. void luaD_reallocCI (lua_State *L, int newsize) {
  67. CallInfo *oldci = L->base_ci;
  68. luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo);
  69. L->size_ci = newsize;
  70. L->ci = (L->ci - oldci) + L->base_ci;
  71. L->end_ci = L->base_ci + L->size_ci;
  72. correctCI(L, oldci);
  73. }
  74. static void restore_stack_limit (lua_State *L) {
  75. if (L->size_ci > LUA_MAXCALLS) { /* there was an overflow? */
  76. int inuse = (L->ci - L->base_ci);
  77. if (inuse + 1 < LUA_MAXCALLS) /* can `undo' overflow? */
  78. luaD_reallocCI(L, LUA_MAXCALLS);
  79. }
  80. }
  81. void luaD_growstack (lua_State *L, int n) {
  82. if (n <= L->stacksize) /* double size is enough? */
  83. luaD_reallocstack(L, 2*L->stacksize);
  84. else
  85. luaD_reallocstack(L, L->stacksize + n + EXTRA_STACK);
  86. }
  87. static void luaD_growCI (lua_State *L) {
  88. L->ci--;
  89. if (L->size_ci > LUA_MAXCALLS) /* overflow while handling overflow? */
  90. luaD_breakrun(L, LUA_ERRERR); /* break run without error message */
  91. else {
  92. luaD_reallocCI(L, 2*L->size_ci);
  93. if (L->size_ci > LUA_MAXCALLS)
  94. luaD_error(L, "stack overflow");
  95. }
  96. L->ci++;
  97. }
  98. /*
  99. ** Open a hole inside the stack at `pos'
  100. */
  101. static void luaD_openstack (lua_State *L, StkId pos) {
  102. StkId p;
  103. for (p = L->top; p > pos; p--) setobj(p, p-1);
  104. incr_top(L);
  105. }
  106. static void dohook (lua_State *L, lua_Debug *ar, lua_Hook hook) {
  107. ptrdiff_t top = savestack(L, L->top);
  108. ptrdiff_t ci_top = savestack(L, L->ci->top);
  109. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  110. L->ci->top = L->top + LUA_MINSTACK;
  111. L->allowhooks = 0; /* cannot call hooks inside a hook */
  112. lua_unlock(L);
  113. (*hook)(L, ar);
  114. lua_lock(L);
  115. lua_assert(L->allowhooks == 0);
  116. L->allowhooks = 1;
  117. L->ci->top = restorestack(L, ci_top);
  118. L->top = restorestack(L, top);
  119. }
  120. void luaD_lineHook (lua_State *L, int line) {
  121. if (L->allowhooks) {
  122. lua_Debug ar;
  123. ar.event = "line";
  124. ar.i_ci = L->ci - L->base_ci;
  125. ar.currentline = line;
  126. dohook(L, &ar, L->linehook);
  127. }
  128. }
  129. static void luaD_callHook (lua_State *L, lua_Hook callhook, const char *event) {
  130. if (L->allowhooks) {
  131. lua_Debug ar;
  132. ar.event = event;
  133. ar.i_ci = L->ci - L->base_ci;
  134. L->ci->pc = NULL; /* function is not active */
  135. dohook(L, &ar, callhook);
  136. }
  137. }
  138. static void adjust_varargs (lua_State *L, int nfixargs) {
  139. int i;
  140. Table *htab;
  141. TObject n, nname;
  142. int actual = L->top - L->ci->base; /* actual number of arguments */
  143. if (actual < nfixargs) {
  144. luaD_checkstack(L, nfixargs - actual);
  145. for (; actual < nfixargs; ++actual)
  146. setnilvalue(L->top++);
  147. }
  148. actual -= nfixargs; /* number of extra arguments */
  149. htab = luaH_new(L, 0, 0); /* create `arg' table */
  150. for (i=0; i<actual; i++) /* put extra arguments into `arg' table */
  151. luaH_setnum(L, htab, i+1, L->top - actual + i);
  152. /* store counter in field `n' */
  153. setnvalue(&n, actual);
  154. setsvalue(&nname, luaS_newliteral(L, "n"));
  155. luaH_set(L, htab, &nname, &n);
  156. L->top -= actual; /* remove extra elements from the stack */
  157. sethvalue(L->top, htab);
  158. incr_top(L);
  159. }
  160. static StkId tryfuncTM (lua_State *L, StkId func) {
  161. const TObject *tm = luaT_gettmbyobj(L, func, TM_CALL);
  162. if (ttype(tm) != LUA_TFUNCTION) {
  163. L->ci--; /* undo increment (no function here) */
  164. luaG_typeerror(L, func, "call");
  165. }
  166. luaD_openstack(L, func);
  167. func = L->ci->base - 1; /* previous call may change stack */
  168. setobj(func, tm); /* tag method is the new function to be called */
  169. return func;
  170. }
  171. StkId luaD_precall (lua_State *L, StkId func) {
  172. CallInfo *ci;
  173. LClosure *cl;
  174. if (++L->ci == L->end_ci) luaD_growCI(L);
  175. ci = L->ci;
  176. ci->base = ci->top = func+1; /* pre-init `top' in case of errors */
  177. ci->pc = NULL;
  178. if (ttype(func) != LUA_TFUNCTION) /* `func' is not a function? */
  179. func = tryfuncTM(L, func); /* check the `function' tag method */
  180. cl = &clvalue(func)->l;
  181. if (L->callhook) {
  182. luaD_callHook(L, L->callhook, "call");
  183. ci = L->ci; /* previous call may realocate `ci' */
  184. }
  185. if (!cl->isC) { /* Lua function? prepare its call */
  186. Proto *p = cl->p;
  187. ci->savedpc = p->code; /* starting point */
  188. if (p->is_vararg) /* varargs? */
  189. adjust_varargs(L, p->numparams);
  190. luaD_checkstack(L, p->maxstacksize);
  191. ci->top = ci->base + p->maxstacksize;
  192. while (L->top < ci->top)
  193. setnilvalue(L->top++);
  194. L->top = ci->top;
  195. return NULL;
  196. }
  197. else { /* if is a C function, call it */
  198. int n;
  199. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  200. ci->top = L->top + LUA_MINSTACK;
  201. lua_unlock(L);
  202. #if LUA_COMPATUPVALUES
  203. lua_pushupvalues(L);
  204. #endif
  205. n = (*clvalue(ci->base-1)->c.f)(L); /* do the actual call */
  206. lua_lock(L);
  207. return L->top - n;
  208. }
  209. }
  210. void luaD_poscall (lua_State *L, int wanted, StkId firstResult) {
  211. StkId res;
  212. if (L->callhook) {
  213. ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */
  214. luaD_callHook(L, L->callhook, "return");
  215. firstResult = restorestack(L, fr);
  216. }
  217. res = L->ci->base - 1; /* res == final position of 1st result */
  218. L->ci--;
  219. /* move results to correct place */
  220. while (wanted != 0 && firstResult < L->top) {
  221. setobj(res++, firstResult++);
  222. wanted--;
  223. }
  224. while (wanted-- > 0)
  225. setnilvalue(res++);
  226. L->top = res;
  227. luaC_checkGC(L);
  228. }
  229. /*
  230. ** Call a function (C or Lua). The function to be called is at *func.
  231. ** The arguments are on the stack, right after the function.
  232. ** When returns, all the results are on the stack, starting at the original
  233. ** function position.
  234. */
  235. void luaD_call (lua_State *L, StkId func, int nResults) {
  236. StkId firstResult = luaD_precall(L, func);
  237. if (firstResult == NULL) { /* is a Lua function? */
  238. firstResult = luaV_execute(L); /* call it */
  239. if (firstResult == NULL) {
  240. luaD_poscall(L, 0, L->top);
  241. luaD_error(L, "attempt to `yield' across tag-method/C-call boundary");
  242. }
  243. }
  244. luaD_poscall(L, nResults, firstResult);
  245. }
  246. LUA_API void lua_cobegin (lua_State *L, int nargs) {
  247. lua_lock(L);
  248. luaD_precall(L, L->top - (nargs+1));
  249. lua_unlock(L);
  250. }
  251. static void move_results (lua_State *L, TObject *from, TObject *to) {
  252. while (from < to) {
  253. setobj(L->top, from);
  254. from++;
  255. incr_top(L);
  256. }
  257. }
  258. static void resume (lua_State *L, void *numres) {
  259. StkId firstResult;
  260. CallInfo *ci = L->ci;
  261. if (ci->savedpc != ci_func(ci)->l.p->code) { /* not first time? */
  262. /* finish interupted execution of `OP_CALL' */
  263. int nresults;
  264. lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL);
  265. nresults = GETARG_C(*((ci-1)->savedpc - 1)) - 1;
  266. luaD_poscall(L, nresults, L->top); /* complete it */
  267. if (nresults >= 0) L->top = L->ci->top;
  268. }
  269. firstResult = luaV_execute(L);
  270. if (firstResult == NULL) /* yield? */
  271. *(int *)numres = L->ci->yield_results;
  272. else { /* return */
  273. *(int *)numres = L->top - firstResult;
  274. luaD_poscall(L, LUA_MULTRET, firstResult); /* finalize this coroutine */
  275. }
  276. }
  277. LUA_API int lua_resume (lua_State *L, lua_State *co) {
  278. CallInfo *ci;
  279. int numres;
  280. int status;
  281. lua_lock(L);
  282. ci = co->ci;
  283. if (ci == co->base_ci) /* no activation record? ?? */
  284. luaD_error(L, "thread is dead - cannot be resumed");
  285. if (co->errorJmp != NULL) /* ?? */
  286. luaD_error(L, "thread is active - cannot be resumed");
  287. status = luaD_runprotected(co, resume, &numres);
  288. if (status == 0)
  289. move_results(L, co->top - numres, co->top);
  290. lua_unlock(L);
  291. return status;
  292. }
  293. LUA_API int lua_yield (lua_State *L, int nresults) {
  294. CallInfo *ci;
  295. lua_lock(L);
  296. ci = L->ci;
  297. if (ci_func(ci-1)->c.isC)
  298. luaD_error(L, "cannot `yield' a C function");
  299. ci->yield_results = nresults;
  300. lua_unlock(L);
  301. return -1;
  302. }
  303. /*
  304. ** Execute a protected call.
  305. */
  306. struct CallS { /* data to `f_call' */
  307. StkId func;
  308. int nresults;
  309. };
  310. static void f_call (lua_State *L, void *ud) {
  311. struct CallS *c = cast(struct CallS *, ud);
  312. luaD_call(L, c->func, c->nresults);
  313. }
  314. LUA_API int lua_call (lua_State *L, int nargs, int nresults) {
  315. struct CallS c;
  316. int status;
  317. lua_lock(L);
  318. c.func = L->top - (nargs+1); /* function to be called */
  319. c.nresults = nresults;
  320. status = luaD_runprotected(L, f_call, &c);
  321. if (status != 0) { /* an error occurred? */
  322. L->top -= nargs+1; /* remove parameters and func from the stack */
  323. luaF_close(L, L->top); /* close eventual pending closures */
  324. }
  325. lua_unlock(L);
  326. return status;
  327. }
  328. /*
  329. ** Execute a protected parser.
  330. */
  331. struct SParser { /* data to `f_parser' */
  332. ZIO *z;
  333. int bin;
  334. };
  335. static void f_parser (lua_State *L, void *ud) {
  336. struct SParser *p = cast(struct SParser *, ud);
  337. Proto *tf = p->bin ? luaU_undump(L, p->z) : luaY_parser(L, p->z);
  338. Closure *cl = luaF_newLclosure(L, 0);
  339. cl->l.p = tf;
  340. setclvalue(L->top, cl);
  341. incr_top(L);
  342. }
  343. static int protectedparser (lua_State *L, ZIO *z, int bin) {
  344. struct SParser p;
  345. lu_mem old_blocks;
  346. int status;
  347. lua_lock(L);
  348. p.z = z; p.bin = bin;
  349. /* before parsing, give a (good) chance to GC */
  350. if (G(L)->nblocks/8 >= G(L)->GCthreshold/10)
  351. luaC_collectgarbage(L);
  352. old_blocks = G(L)->nblocks;
  353. status = luaD_runprotected(L, f_parser, &p);
  354. if (status == 0) {
  355. /* add new memory to threshold (as it probably will stay) */
  356. lua_assert(G(L)->nblocks >= old_blocks);
  357. G(L)->GCthreshold += (G(L)->nblocks - old_blocks);
  358. }
  359. else if (status == LUA_ERRRUN) /* an error occurred: correct error code */
  360. status = LUA_ERRSYNTAX;
  361. lua_unlock(L);
  362. return status;
  363. }
  364. LUA_API int lua_loadfile (lua_State *L, const char *filename) {
  365. ZIO z;
  366. int status;
  367. int bin; /* flag for file mode */
  368. int nlevel; /* level on the stack of filename */
  369. FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
  370. if (f == NULL) return LUA_ERRFILE; /* unable to open file */
  371. bin = (ungetc(getc(f), f) == LUA_SIGNATURE[0]);
  372. if (bin && f != stdin) {
  373. fclose(f);
  374. f = fopen(filename, "rb"); /* reopen in binary mode */
  375. if (f == NULL) return LUA_ERRFILE; /* unable to reopen file */
  376. }
  377. if (filename == NULL)
  378. lua_pushstring(L, "=stdin");
  379. else {
  380. lua_pushliteral(L, "@");
  381. lua_pushstring(L, filename);
  382. lua_concat(L, 2);
  383. }
  384. nlevel = lua_gettop(L);
  385. filename = lua_tostring(L, -1); /* filename = `@'..filename */
  386. luaZ_Fopen(&z, f, filename);
  387. status = protectedparser(L, &z, bin);
  388. lua_remove(L, nlevel); /* remove filename */
  389. if (f != stdin)
  390. fclose(f);
  391. return status;
  392. }
  393. LUA_API int lua_loadbuffer (lua_State *L, const char *buff, size_t size,
  394. const char *name) {
  395. ZIO z;
  396. if (!name) name = "?";
  397. luaZ_mopen(&z, buff, size, name);
  398. return protectedparser(L, &z, buff[0]==LUA_SIGNATURE[0]);
  399. }
  400. /*
  401. ** {======================================================
  402. ** Error-recovery functions (based on long jumps)
  403. ** =======================================================
  404. */
  405. static void message (lua_State *L, const char *s) {
  406. TObject o, m;
  407. setsvalue(&o, luaS_newliteral(L, LUA_ERRORMESSAGE));
  408. luaV_gettable(L, gt(L), &o, &m);
  409. if (ttype(&m) == LUA_TFUNCTION) {
  410. setobj(L->top, &m);
  411. incr_top(L);
  412. setsvalue(L->top, luaS_new(L, s));
  413. incr_top(L);
  414. luaD_call(L, L->top-2, 0);
  415. }
  416. }
  417. /*
  418. ** Reports an error, and jumps up to the available recovery label
  419. */
  420. void luaD_error (lua_State *L, const char *s) {
  421. if (s) message(L, s);
  422. luaD_breakrun(L, LUA_ERRRUN);
  423. }
  424. void luaD_breakrun (lua_State *L, int errcode) {
  425. if (L->errorJmp) {
  426. L->errorJmp->status = errcode;
  427. longjmp(L->errorJmp->b, 1);
  428. }
  429. else {
  430. if (errcode != LUA_ERRMEM && errcode != LUA_ERRERR)
  431. message(L, "unable to recover; exiting\n");
  432. exit(EXIT_FAILURE);
  433. }
  434. }
  435. int luaD_runprotected (lua_State *L, void (*f)(lua_State *, void *), void *ud) {
  436. struct lua_longjmp lj;
  437. lj.ci = L->ci;
  438. lj.top = L->top;
  439. lj.allowhooks = L->allowhooks;
  440. lj.status = 0;
  441. lj.previous = L->errorJmp; /* chain new error handler */
  442. L->errorJmp = &lj;
  443. if (setjmp(lj.b) == 0)
  444. (*f)(L, ud);
  445. else { /* an error occurred: restore the state */
  446. L->ci = lj.ci;
  447. L->top = lj.top;
  448. L->allowhooks = lj.allowhooks;
  449. restore_stack_limit(L);
  450. }
  451. L->errorJmp = lj.previous; /* restore old error handler */
  452. return lj.status;
  453. }
  454. /* }====================================================== */