ldo.c 14 KB

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