ldo.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. ** $Id: ldo.c,v 1.164 2002/03/15 17:17:16 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 restore_stack_limit (lua_State *L) {
  61. if (L->stacksize > LUA_MAXSTACK) { /* there was an overflow? */
  62. int inuse = (L->top - L->stack);
  63. if (inuse + MAXSTACK < LUA_MAXSTACK) /* can `undo' overflow? */
  64. luaD_reallocstack(L, LUA_MAXSTACK);
  65. }
  66. }
  67. void luaD_growstack (lua_State *L, int n) {
  68. if (L->stacksize > LUA_MAXSTACK) { /* overflow while handling overflow? */
  69. luaD_breakrun(L, LUA_ERRERR); /* break run without error message */
  70. }
  71. else {
  72. if (n <= L->stacksize && 2*L->stacksize < LUA_MAXSTACK) /* can double? */
  73. luaD_reallocstack(L, 2*L->stacksize);
  74. else if ((L->top - L->stack) + n <= LUA_MAXSTACK) /* no overflow? */
  75. luaD_reallocstack(L, LUA_MAXSTACK);
  76. else {
  77. /* resize to maximum + some extra space to handle error */
  78. luaD_reallocstack(L, LUA_MAXSTACK+4*LUA_MINSTACK);
  79. luaD_error(L, "stack overflow");
  80. }
  81. }
  82. }
  83. /*
  84. ** Open a hole inside the stack at `pos'
  85. */
  86. static void luaD_openstack (lua_State *L, StkId pos) {
  87. StkId p;
  88. for (p = L->top; p > pos; p--) setobj(p, p-1);
  89. incr_top(L);
  90. }
  91. static void dohook (lua_State *L, lua_Debug *ar, lua_Hook hook) {
  92. ptrdiff_t top = savestack(L, L->top);
  93. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  94. L->ci->top += LUA_MINSTACK;
  95. L->allowhooks = 0; /* cannot call hooks inside a hook */
  96. lua_unlock(L);
  97. (*hook)(L, ar);
  98. lua_lock(L);
  99. lua_assert(L->allowhooks == 0);
  100. L->allowhooks = 1;
  101. L->ci->top -= LUA_MINSTACK;
  102. L->top = restorestack(L, top);
  103. }
  104. void luaD_lineHook (lua_State *L, int line, lua_Hook linehook) {
  105. if (L->allowhooks) {
  106. lua_Debug ar;
  107. ar.event = "line";
  108. ar.i_ci = L->ci - L->base_ci;
  109. ar.currentline = line;
  110. dohook(L, &ar, linehook);
  111. }
  112. }
  113. static void luaD_callHook (lua_State *L, lua_Hook callhook, const char *event) {
  114. if (L->allowhooks) {
  115. lua_Debug ar;
  116. ar.event = event;
  117. ar.i_ci = L->ci - L->base_ci;
  118. L->ci->pc = NULL; /* function is not active */
  119. dohook(L, &ar, callhook);
  120. }
  121. }
  122. static void correctCI (lua_State *L, CallInfo *oldci) {
  123. struct lua_longjmp *lj;
  124. for (lj = L->errorJmp; lj != NULL; lj = lj->previous) {
  125. lj->ci = (lj->ci - oldci) + L->base_ci;
  126. }
  127. }
  128. void luaD_reallocCI (lua_State *L, int newsize) {
  129. CallInfo *oldci = L->base_ci;
  130. luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo);
  131. L->size_ci = newsize;
  132. if (oldci != L->ci) {
  133. L->ci = (L->ci - oldci) + L->base_ci;
  134. L->end_ci = L->base_ci + L->size_ci;
  135. correctCI(L, oldci);
  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_reallocCI(L, 2*L->size_ci);
  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->line = 0;
  192. ci->top = ci->base + p->maxstacksize;
  193. while (L->top < ci->top)
  194. setnilvalue(L->top++);
  195. L->top = ci->top;
  196. return NULL;
  197. }
  198. else { /* if is a C function, call it */
  199. int n;
  200. luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
  201. ci->top = L->top + LUA_MINSTACK;
  202. lua_unlock(L);
  203. #if LUA_COMPATUPVALUES
  204. lua_pushupvalues(L);
  205. #endif
  206. n = (*clvalue(ci->base-1)->c.f)(L); /* do the actual call */
  207. lua_lock(L);
  208. return L->top - n;
  209. }
  210. }
  211. void luaD_poscall (lua_State *L, int wanted, StkId firstResult) {
  212. StkId res;
  213. if (L->callhook) {
  214. ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */
  215. luaD_callHook(L, L->callhook, "return");
  216. firstResult = restorestack(L, fr);
  217. }
  218. res = L->ci->base - 1; /* func == final position of 1st result */
  219. L->ci--;
  220. /* move results to correct place */
  221. while (wanted != 0 && firstResult < L->top) {
  222. setobj(res++, firstResult++);
  223. wanted--;
  224. }
  225. while (wanted-- > 0)
  226. setnilvalue(res++);
  227. L->top = res;
  228. luaC_checkGC(L);
  229. }
  230. /*
  231. ** Call a function (C or Lua). The function to be called is at *func.
  232. ** The arguments are on the stack, right after the function.
  233. ** When returns, all the results are on the stack, starting at the original
  234. ** function position.
  235. */
  236. void luaD_call (lua_State *L, StkId func, int nResults) {
  237. StkId firstResult = luaD_precall(L, func);
  238. if (firstResult == NULL) { /* is a Lua function? */
  239. firstResult = luaV_execute(L); /* call it */
  240. if (firstResult == NULL) {
  241. luaD_poscall(L, 0, L->top);
  242. luaD_error(L, "attempt to `yield' across tag-method/C-call boundary");
  243. }
  244. }
  245. luaD_poscall(L, nResults, firstResult);
  246. }
  247. LUA_API void lua_cobegin (lua_State *L, int nargs) {
  248. lua_lock(L);
  249. luaD_precall(L, L->top - (nargs+1));
  250. lua_unlock(L);
  251. }
  252. static void move_results (lua_State *L, TObject *from, TObject *to) {
  253. while (from < to) {
  254. setobj(L->top, from);
  255. from++;
  256. incr_top(L);
  257. }
  258. }
  259. static void resume (lua_State *L, void *numres) {
  260. StkId firstResult;
  261. CallInfo *ci = L->ci;
  262. if (ci->savedpc != ci_func(ci)->l.p->code) { /* not first time? */
  263. /* finish interupted execution of `OP_CALL' */
  264. int nresults;
  265. lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL);
  266. nresults = GETARG_C(*((ci-1)->savedpc - 1)) - 1;
  267. luaD_poscall(L, nresults, L->top); /* complete it */
  268. if (nresults >= 0) L->top = L->ci->top;
  269. }
  270. firstResult = luaV_execute(L);
  271. if (firstResult == NULL) /* yield? */
  272. *(int *)numres = L->ci->yield_results;
  273. else { /* return */
  274. *(int *)numres = L->top - firstResult;
  275. luaD_poscall(L, LUA_MULTRET, firstResult); /* finalize this coroutine */
  276. }
  277. }
  278. LUA_API int lua_resume (lua_State *L, lua_State *co) {
  279. CallInfo *ci;
  280. int numres;
  281. int status;
  282. lua_lock(L);
  283. ci = co->ci;
  284. if (ci == co->base_ci) /* no activation record? ?? */
  285. luaD_error(L, "thread is dead - cannot be resumed");
  286. if (co->errorJmp != NULL) /* ?? */
  287. luaD_error(L, "thread is active - cannot be resumed");
  288. status = luaD_runprotected(co, resume, &numres);
  289. if (status == 0)
  290. move_results(L, co->top - numres, co->top);
  291. lua_unlock(L);
  292. return status;
  293. }
  294. LUA_API int lua_yield (lua_State *L, int nresults) {
  295. CallInfo *ci;
  296. lua_lock(L);
  297. ci = L->ci;
  298. if (ci_func(ci-1)->c.isC)
  299. luaD_error(L, "cannot `yield' a C function");
  300. ci->yield_results = nresults;
  301. lua_unlock(L);
  302. return -1;
  303. }
  304. /*
  305. ** Execute a protected call.
  306. */
  307. struct CallS { /* data to `f_call' */
  308. StkId func;
  309. int nresults;
  310. };
  311. static void f_call (lua_State *L, void *ud) {
  312. struct CallS *c = cast(struct CallS *, ud);
  313. luaD_call(L, c->func, c->nresults);
  314. }
  315. LUA_API int lua_call (lua_State *L, int nargs, int nresults) {
  316. struct CallS c;
  317. int status;
  318. lua_lock(L);
  319. c.func = L->top - (nargs+1); /* function to be called */
  320. c.nresults = nresults;
  321. status = luaD_runprotected(L, f_call, &c);
  322. if (status != 0) { /* an error occurred? */
  323. L->top -= nargs+1; /* remove parameters and func from the stack */
  324. luaF_close(L, L->top); /* close eventual pending closures */
  325. }
  326. lua_unlock(L);
  327. return status;
  328. }
  329. /*
  330. ** Execute a protected parser.
  331. */
  332. struct SParser { /* data to `f_parser' */
  333. ZIO *z;
  334. int bin;
  335. };
  336. static void f_parser (lua_State *L, void *ud) {
  337. struct SParser *p = cast(struct SParser *, ud);
  338. Proto *tf = p->bin ? luaU_undump(L, p->z) : luaY_parser(L, p->z);
  339. Closure *cl = luaF_newLclosure(L, 0);
  340. cl->l.p = tf;
  341. setclvalue(L->top, cl);
  342. incr_top(L);
  343. }
  344. static int protectedparser (lua_State *L, ZIO *z, int bin) {
  345. struct SParser p;
  346. lu_mem old_blocks;
  347. int status;
  348. lua_lock(L);
  349. p.z = z; p.bin = bin;
  350. /* before parsing, give a (good) chance to GC */
  351. if (G(L)->nblocks/8 >= G(L)->GCthreshold/10)
  352. luaC_collectgarbage(L);
  353. old_blocks = G(L)->nblocks;
  354. status = luaD_runprotected(L, f_parser, &p);
  355. if (status == 0) {
  356. /* add new memory to threshold (as it probably will stay) */
  357. lua_assert(G(L)->nblocks >= old_blocks);
  358. G(L)->GCthreshold += (G(L)->nblocks - old_blocks);
  359. }
  360. else if (status == LUA_ERRRUN) /* an error occurred: correct error code */
  361. status = LUA_ERRSYNTAX;
  362. lua_unlock(L);
  363. return status;
  364. }
  365. LUA_API int lua_loadfile (lua_State *L, const char *filename) {
  366. ZIO z;
  367. int status;
  368. int bin; /* flag for file mode */
  369. int nlevel; /* level on the stack of filename */
  370. FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
  371. if (f == NULL) return LUA_ERRFILE; /* unable to open file */
  372. bin = (ungetc(getc(f), f) == LUA_SIGNATURE[0]);
  373. if (bin && f != stdin) {
  374. fclose(f);
  375. f = fopen(filename, "rb"); /* reopen in binary mode */
  376. if (f == NULL) return LUA_ERRFILE; /* unable to reopen file */
  377. }
  378. if (filename == NULL)
  379. lua_pushstring(L, "=stdin");
  380. else {
  381. lua_pushliteral(L, "@");
  382. lua_pushstring(L, filename);
  383. lua_concat(L, 2);
  384. }
  385. nlevel = lua_gettop(L);
  386. filename = lua_tostring(L, -1); /* filename = `@'..filename */
  387. luaZ_Fopen(&z, f, filename);
  388. status = protectedparser(L, &z, bin);
  389. lua_remove(L, nlevel); /* remove filename */
  390. if (f != stdin)
  391. fclose(f);
  392. return status;
  393. }
  394. LUA_API int lua_loadbuffer (lua_State *L, const char *buff, size_t size,
  395. const char *name) {
  396. ZIO z;
  397. if (!name) name = "?";
  398. luaZ_mopen(&z, buff, size, name);
  399. return protectedparser(L, &z, buff[0]==LUA_SIGNATURE[0]);
  400. }
  401. /*
  402. ** {======================================================
  403. ** Error-recovery functions (based on long jumps)
  404. ** =======================================================
  405. */
  406. static void message (lua_State *L, const char *s) {
  407. TObject o, m;
  408. setsvalue(&o, luaS_newliteral(L, LUA_ERRORMESSAGE));
  409. luaV_gettable(L, gt(L), &o, &m);
  410. if (ttype(&m) == LUA_TFUNCTION) {
  411. setobj(L->top, &m);
  412. incr_top(L);
  413. setsvalue(L->top, luaS_new(L, s));
  414. incr_top(L);
  415. luaD_call(L, L->top-2, 0);
  416. }
  417. }
  418. /*
  419. ** Reports an error, and jumps up to the available recovery label
  420. */
  421. void luaD_error (lua_State *L, const char *s) {
  422. if (s) message(L, s);
  423. luaD_breakrun(L, LUA_ERRRUN);
  424. }
  425. void luaD_breakrun (lua_State *L, int errcode) {
  426. if (L->errorJmp) {
  427. L->errorJmp->status = errcode;
  428. longjmp(L->errorJmp->b, 1);
  429. }
  430. else {
  431. if (errcode != LUA_ERRMEM && errcode != LUA_ERRERR)
  432. message(L, "unable to recover; exiting\n");
  433. exit(EXIT_FAILURE);
  434. }
  435. }
  436. int luaD_runprotected (lua_State *L, void (*f)(lua_State *, void *), void *ud) {
  437. struct lua_longjmp lj;
  438. lj.ci = L->ci;
  439. lj.top = L->top;
  440. lj.allowhooks = L->allowhooks;
  441. lj.status = 0;
  442. lj.previous = L->errorJmp; /* chain new error handler */
  443. L->errorJmp = &lj;
  444. if (setjmp(lj.b) == 0)
  445. (*f)(L, ud);
  446. else { /* an error occurred: restore the state */
  447. L->ci = lj.ci;
  448. L->top = lj.top;
  449. L->allowhooks = lj.allowhooks;
  450. restore_stack_limit(L);
  451. }
  452. L->errorJmp = lj.previous; /* restore old error handler */
  453. return lj.status;
  454. }
  455. /* }====================================================== */