lvm.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /*
  2. ** $Id: lvm.c,v 2.151 2012/05/14 17:50:49 roberto Exp roberto $
  3. ** Lua virtual machine
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #define lvm_c
  10. #define LUA_CORE
  11. #include "lua.h"
  12. #include "ldebug.h"
  13. #include "ldo.h"
  14. #include "lfunc.h"
  15. #include "lgc.h"
  16. #include "lobject.h"
  17. #include "lopcodes.h"
  18. #include "lstate.h"
  19. #include "lstring.h"
  20. #include "ltable.h"
  21. #include "ltm.h"
  22. #include "lvm.h"
  23. /* limit for table tag-method chains (to avoid loops) */
  24. #define MAXTAGLOOP 100
  25. const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
  26. lua_Number num;
  27. if (ttisnumber(obj)) return obj;
  28. if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) {
  29. setnvalue(n, num);
  30. return n;
  31. }
  32. else
  33. return NULL;
  34. }
  35. int luaV_tostring (lua_State *L, StkId obj) {
  36. if (!ttisnumber(obj))
  37. return 0;
  38. else {
  39. char s[LUAI_MAXNUMBER2STR];
  40. lua_Number n = nvalue(obj);
  41. int l = lua_number2str(s, n);
  42. setsvalue2s(L, obj, luaS_newlstr(L, s, l));
  43. return 1;
  44. }
  45. }
  46. static void traceexec (lua_State *L) {
  47. CallInfo *ci = L->ci;
  48. lu_byte mask = L->hookmask;
  49. int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);
  50. if (counthook)
  51. resethookcount(L); /* reset count */
  52. if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */
  53. ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
  54. return; /* do not call hook again (VM yielded, so it did not move) */
  55. }
  56. if (counthook)
  57. luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */
  58. if (mask & LUA_MASKLINE) {
  59. Proto *p = ci_func(ci)->p;
  60. int npc = pcRel(ci->u.l.savedpc, p);
  61. int newline = getfuncline(p, npc);
  62. if (npc == 0 || /* call linehook when enter a new function, */
  63. ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */
  64. newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */
  65. luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */
  66. }
  67. L->oldpc = ci->u.l.savedpc;
  68. if (L->status == LUA_YIELD) { /* did hook yield? */
  69. if (counthook)
  70. L->hookcount = 1; /* undo decrement to zero */
  71. ci->u.l.savedpc--; /* undo increment (resume will increment it again) */
  72. ci->callstatus |= CIST_HOOKYIELD; /* mark that it yieled */
  73. ci->func = L->top - 1; /* protect stack below results */
  74. luaD_throw(L, LUA_YIELD);
  75. }
  76. }
  77. static void callTM (lua_State *L, const TValue *f, const TValue *p1,
  78. const TValue *p2, TValue *p3, int hasres) {
  79. ptrdiff_t result = savestack(L, p3);
  80. setobj2s(L, L->top++, f); /* push function */
  81. setobj2s(L, L->top++, p1); /* 1st argument */
  82. setobj2s(L, L->top++, p2); /* 2nd argument */
  83. if (!hasres) /* no result? 'p3' is third argument */
  84. setobj2s(L, L->top++, p3); /* 3rd argument */
  85. luaD_checkstack(L, 0);
  86. /* metamethod may yield only when called from Lua code */
  87. luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci));
  88. if (hasres) { /* if has result, move it to its place */
  89. p3 = restorestack(L, result);
  90. setobjs2s(L, p3, --L->top);
  91. }
  92. }
  93. void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
  94. int loop;
  95. for (loop = 0; loop < MAXTAGLOOP; loop++) {
  96. const TValue *tm;
  97. if (ttistable(t)) { /* `t' is a table? */
  98. Table *h = hvalue(t);
  99. const TValue *res = luaH_get(h, key); /* do a primitive get */
  100. if (!ttisnil(res) || /* result is not nil? */
  101. (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
  102. setobj2s(L, val, res);
  103. return;
  104. }
  105. /* else will try the tag method */
  106. }
  107. else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
  108. luaG_typeerror(L, t, "index");
  109. if (ttisfunction(tm)) {
  110. callTM(L, tm, t, key, val, 1);
  111. return;
  112. }
  113. t = tm; /* else repeat with 'tm' */
  114. }
  115. luaG_runerror(L, "loop in gettable");
  116. }
  117. void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
  118. int loop;
  119. for (loop = 0; loop < MAXTAGLOOP; loop++) {
  120. const TValue *tm;
  121. if (ttistable(t)) { /* `t' is a table? */
  122. Table *h = hvalue(t);
  123. TValue *oldval = cast(TValue *, luaH_get(h, key));
  124. /* if previous value is not nil, there must be a previous entry
  125. in the table; moreover, a metamethod has no relevance */
  126. if (!ttisnil(oldval) ||
  127. /* previous value is nil; must check the metamethod */
  128. ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&
  129. /* no metamethod; is there a previous entry in the table? */
  130. (oldval != luaO_nilobject ||
  131. /* no previous entry; must create one. (The next test is
  132. always true; we only need the assignment.) */
  133. (oldval = luaH_newkey(L, h, key), 1)))) {
  134. /* no metamethod and (now) there is an entry with given key */
  135. setobj2t(L, oldval, val); /* assign new value to that entry */
  136. invalidateTMcache(h);
  137. luaC_barrierback(L, obj2gco(h), val);
  138. return;
  139. }
  140. /* else will try the metamethod */
  141. }
  142. else /* not a table; check metamethod */
  143. if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
  144. luaG_typeerror(L, t, "index");
  145. /* there is a metamethod */
  146. if (ttisfunction(tm)) {
  147. callTM(L, tm, t, key, val, 0);
  148. return;
  149. }
  150. t = tm; /* else repeat with 'tm' */
  151. }
  152. luaG_runerror(L, "loop in settable");
  153. }
  154. static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
  155. StkId res, TMS event) {
  156. const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
  157. if (ttisnil(tm))
  158. tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
  159. if (ttisnil(tm)) return 0;
  160. callTM(L, tm, p1, p2, res, 1);
  161. return 1;
  162. }
  163. static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2,
  164. TMS event) {
  165. const TValue *tm1 = fasttm(L, mt1, event);
  166. const TValue *tm2;
  167. if (tm1 == NULL) return NULL; /* no metamethod */
  168. if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
  169. tm2 = fasttm(L, mt2, event);
  170. if (tm2 == NULL) return NULL; /* no metamethod */
  171. if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */
  172. return tm1;
  173. return NULL;
  174. }
  175. static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
  176. TMS event) {
  177. if (!call_binTM(L, p1, p2, L->top, event))
  178. return -1; /* no metamethod */
  179. else
  180. return !l_isfalse(L->top);
  181. }
  182. static int l_strcmp (const TString *ls, const TString *rs) {
  183. const char *l = getstr(ls);
  184. size_t ll = ls->tsv.len;
  185. const char *r = getstr(rs);
  186. size_t lr = rs->tsv.len;
  187. for (;;) {
  188. int temp = strcoll(l, r);
  189. if (temp != 0) return temp;
  190. else { /* strings are equal up to a `\0' */
  191. size_t len = strlen(l); /* index of first `\0' in both strings */
  192. if (len == lr) /* r is finished? */
  193. return (len == ll) ? 0 : 1;
  194. else if (len == ll) /* l is finished? */
  195. return -1; /* l is smaller than r (because r is not finished) */
  196. /* both strings longer than `len'; go on comparing (after the `\0') */
  197. len++;
  198. l += len; ll -= len; r += len; lr -= len;
  199. }
  200. }
  201. }
  202. int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
  203. int res;
  204. if (ttisnumber(l) && ttisnumber(r))
  205. return luai_numlt(L, nvalue(l), nvalue(r));
  206. else if (ttisstring(l) && ttisstring(r))
  207. return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
  208. else if ((res = call_orderTM(L, l, r, TM_LT)) < 0)
  209. luaG_ordererror(L, l, r);
  210. return res;
  211. }
  212. int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
  213. int res;
  214. if (ttisnumber(l) && ttisnumber(r))
  215. return luai_numle(L, nvalue(l), nvalue(r));
  216. else if (ttisstring(l) && ttisstring(r))
  217. return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
  218. else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */
  219. return res;
  220. else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */
  221. luaG_ordererror(L, l, r);
  222. return !res;
  223. }
  224. /*
  225. ** equality of Lua values. L == NULL means raw equality (no metamethods)
  226. */
  227. int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {
  228. const TValue *tm;
  229. lua_assert(ttisequal(t1, t2));
  230. switch (ttype(t1)) {
  231. case LUA_TNIL: return 1;
  232. case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
  233. case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
  234. case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
  235. case LUA_TLCF: return fvalue(t1) == fvalue(t2);
  236. case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2));
  237. case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2));
  238. case LUA_TUSERDATA: {
  239. if (uvalue(t1) == uvalue(t2)) return 1;
  240. else if (L == NULL) return 0;
  241. tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
  242. break; /* will try TM */
  243. }
  244. case LUA_TTABLE: {
  245. if (hvalue(t1) == hvalue(t2)) return 1;
  246. else if (L == NULL) return 0;
  247. tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
  248. break; /* will try TM */
  249. }
  250. default:
  251. lua_assert(iscollectable(t1));
  252. return gcvalue(t1) == gcvalue(t2);
  253. }
  254. if (tm == NULL) return 0; /* no TM? */
  255. callTM(L, tm, t1, t2, L->top, 1); /* call TM */
  256. return !l_isfalse(L->top);
  257. }
  258. void luaV_concat (lua_State *L, int total) {
  259. lua_assert(total >= 2);
  260. do {
  261. StkId top = L->top;
  262. int n = 2; /* number of elements handled in this pass (at least 2) */
  263. if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
  264. if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
  265. luaG_concaterror(L, top-2, top-1);
  266. }
  267. else if (tsvalue(top-1)->len == 0) /* second operand is empty? */
  268. (void)tostring(L, top - 2); /* result is first operand */
  269. else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {
  270. setobjs2s(L, top - 2, top - 1); /* result is second op. */
  271. }
  272. else {
  273. /* at least two non-empty string values; get as many as possible */
  274. size_t tl = tsvalue(top-1)->len;
  275. char *buffer;
  276. int i;
  277. /* collect total length */
  278. for (i = 1; i < total && tostring(L, top-i-1); i++) {
  279. size_t l = tsvalue(top-i-1)->len;
  280. if (l >= (MAX_SIZET/sizeof(char)) - tl)
  281. luaG_runerror(L, "string length overflow");
  282. tl += l;
  283. }
  284. buffer = luaZ_openspace(L, &G(L)->buff, tl);
  285. tl = 0;
  286. n = i;
  287. do { /* concat all strings */
  288. size_t l = tsvalue(top-i)->len;
  289. memcpy(buffer+tl, svalue(top-i), l * sizeof(char));
  290. tl += l;
  291. } while (--i > 0);
  292. setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
  293. }
  294. total -= n-1; /* got 'n' strings to create 1 new */
  295. L->top -= n-1; /* popped 'n' strings and pushed one */
  296. } while (total > 1); /* repeat until only 1 result left */
  297. }
  298. void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
  299. const TValue *tm;
  300. switch (ttypenv(rb)) {
  301. case LUA_TTABLE: {
  302. Table *h = hvalue(rb);
  303. tm = fasttm(L, h->metatable, TM_LEN);
  304. if (tm) break; /* metamethod? break switch to call it */
  305. setnvalue(ra, cast_num(luaH_getn(h))); /* else primitive len */
  306. return;
  307. }
  308. case LUA_TSTRING: {
  309. setnvalue(ra, cast_num(tsvalue(rb)->len));
  310. return;
  311. }
  312. default: { /* try metamethod */
  313. tm = luaT_gettmbyobj(L, rb, TM_LEN);
  314. if (ttisnil(tm)) /* no metamethod? */
  315. luaG_typeerror(L, rb, "get length of");
  316. break;
  317. }
  318. }
  319. callTM(L, tm, rb, rb, ra, 1);
  320. }
  321. void luaV_arith (lua_State *L, StkId ra, const TValue *rb,
  322. const TValue *rc, TMS op) {
  323. TValue tempb, tempc;
  324. const TValue *b, *c;
  325. if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
  326. (c = luaV_tonumber(rc, &tempc)) != NULL) {
  327. lua_Number res = luaO_arith(op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c));
  328. setnvalue(ra, res);
  329. }
  330. else if (!call_binTM(L, rb, rc, ra, op))
  331. luaG_aritherror(L, rb, rc);
  332. }
  333. /*
  334. ** check whether cached closure in prototype 'p' may be reused, that is,
  335. ** whether there is a cached closure with the same upvalues needed by
  336. ** new closure to be created.
  337. */
  338. static Closure *getcached (Proto *p, UpVal **encup, StkId base) {
  339. Closure *c = p->cache;
  340. if (c != NULL) { /* is there a cached closure? */
  341. int nup = p->sizeupvalues;
  342. Upvaldesc *uv = p->upvalues;
  343. int i;
  344. for (i = 0; i < nup; i++) { /* check whether it has right upvalues */
  345. TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;
  346. if (c->l.upvals[i]->v != v)
  347. return NULL; /* wrong upvalue; cannot reuse closure */
  348. }
  349. }
  350. return c; /* return cached closure (or NULL if no cached closure) */
  351. }
  352. /*
  353. ** create a new Lua closure, push it in the stack, and initialize
  354. ** its upvalues. Note that the call to 'luaC_barrierproto' must come
  355. ** before the assignment to 'p->cache', as the function needs the
  356. ** original value of that field.
  357. */
  358. static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
  359. StkId ra) {
  360. int nup = p->sizeupvalues;
  361. Upvaldesc *uv = p->upvalues;
  362. int i;
  363. Closure *ncl = luaF_newLclosure(L, nup);
  364. ncl->l.p = p;
  365. setclLvalue(L, ra, ncl); /* anchor new closure in stack */
  366. for (i = 0; i < nup; i++) { /* fill in its upvalues */
  367. if (uv[i].instack) /* upvalue refers to local variable? */
  368. ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
  369. else /* get upvalue from enclosing function */
  370. ncl->l.upvals[i] = encup[uv[i].idx];
  371. }
  372. luaC_barrierproto(L, p, ncl);
  373. p->cache = ncl; /* save it on cache for reuse */
  374. }
  375. /*
  376. ** finish execution of an opcode interrupted by an yield
  377. */
  378. void luaV_finishOp (lua_State *L) {
  379. CallInfo *ci = L->ci;
  380. StkId base = ci->u.l.base;
  381. Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */
  382. OpCode op = GET_OPCODE(inst);
  383. switch (op) { /* finish its execution */
  384. case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV:
  385. case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN:
  386. case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
  387. setobjs2s(L, base + GETARG_A(inst), --L->top);
  388. break;
  389. }
  390. case OP_LE: case OP_LT: case OP_EQ: {
  391. int res = !l_isfalse(L->top - 1);
  392. L->top--;
  393. /* metamethod should not be called when operand is K */
  394. lua_assert(!ISK(GETARG_B(inst)));
  395. if (op == OP_LE && /* "<=" using "<" instead? */
  396. ttisnil(luaT_gettmbyobj(L, base + GETARG_B(inst), TM_LE)))
  397. res = !res; /* invert result */
  398. lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
  399. if (res != GETARG_A(inst)) /* condition failed? */
  400. ci->u.l.savedpc++; /* skip jump instruction */
  401. break;
  402. }
  403. case OP_CONCAT: {
  404. StkId top = L->top - 1; /* top when 'call_binTM' was called */
  405. int b = GETARG_B(inst); /* first element to concatenate */
  406. int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */
  407. setobj2s(L, top - 2, top); /* put TM result in proper position */
  408. if (total > 1) { /* are there elements to concat? */
  409. L->top = top - 1; /* top is one after last element (at top-2) */
  410. luaV_concat(L, total); /* concat them (may yield again) */
  411. }
  412. /* move final result to final position */
  413. setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1);
  414. L->top = ci->top; /* restore top */
  415. break;
  416. }
  417. case OP_TFORCALL: {
  418. lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP);
  419. L->top = ci->top; /* correct top */
  420. break;
  421. }
  422. case OP_CALL: {
  423. if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */
  424. L->top = ci->top; /* adjust results */
  425. break;
  426. }
  427. case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE:
  428. break;
  429. default: lua_assert(0);
  430. }
  431. }
  432. /*
  433. ** some macros for common tasks in `luaV_execute'
  434. */
  435. #if !defined luai_runtimecheck
  436. #define luai_runtimecheck(L, c) /* void */
  437. #endif
  438. #define RA(i) (base+GETARG_A(i))
  439. /* to be used after possible stack reallocation */
  440. #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
  441. #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
  442. #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
  443. ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
  444. #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
  445. ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
  446. #define KBx(i) \
  447. (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))
  448. /* execute a jump instruction */
  449. #define dojump(ci,i,e) \
  450. { int a = GETARG_A(i); \
  451. if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \
  452. ci->u.l.savedpc += GETARG_sBx(i) + e; }
  453. /* for test instructions, execute the jump instruction that follows it */
  454. #define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); }
  455. #define Protect(x) { {x;}; base = ci->u.l.base; }
  456. #define checkGC(L,c) \
  457. Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \
  458. luaC_step(L); \
  459. L->top = ci->top;}) /* restore top */ \
  460. luai_threadyield(L); )
  461. #define arith_op(op,tm) { \
  462. TValue *rb = RKB(i); \
  463. TValue *rc = RKC(i); \
  464. if (ttisnumber(rb) && ttisnumber(rc)) { \
  465. lua_Number nb = nvalue(rb), nc = nvalue(rc); \
  466. setnvalue(ra, op(L, nb, nc)); \
  467. } \
  468. else { Protect(luaV_arith(L, ra, rb, rc, tm)); } }
  469. #define vmdispatch(o) switch(o)
  470. #define vmcase(l,b) case l: {b} break;
  471. #define vmcasenb(l,b) case l: {b} /* nb = no break */
  472. void luaV_execute (lua_State *L) {
  473. CallInfo *ci = L->ci;
  474. LClosure *cl;
  475. TValue *k;
  476. StkId base;
  477. newframe: /* reentry point when frame changes (call/return) */
  478. lua_assert(ci == L->ci);
  479. cl = clLvalue(ci->func);
  480. k = cl->p->k;
  481. base = ci->u.l.base;
  482. /* main loop of interpreter */
  483. for (;;) {
  484. Instruction i = *(ci->u.l.savedpc++);
  485. StkId ra;
  486. if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
  487. (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
  488. Protect(traceexec(L));
  489. }
  490. /* WARNING: several calls may realloc the stack and invalidate `ra' */
  491. ra = RA(i);
  492. lua_assert(base == ci->u.l.base);
  493. lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
  494. vmdispatch (GET_OPCODE(i)) {
  495. vmcase(OP_MOVE,
  496. setobjs2s(L, ra, RB(i));
  497. )
  498. vmcase(OP_LOADK,
  499. TValue *rb = k + GETARG_Bx(i);
  500. setobj2s(L, ra, rb);
  501. )
  502. vmcase(OP_LOADKX,
  503. TValue *rb;
  504. lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
  505. rb = k + GETARG_Ax(*ci->u.l.savedpc++);
  506. setobj2s(L, ra, rb);
  507. )
  508. vmcase(OP_LOADBOOL,
  509. setbvalue(ra, GETARG_B(i));
  510. if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */
  511. )
  512. vmcase(OP_LOADNIL,
  513. int b = GETARG_B(i);
  514. do {
  515. setnilvalue(ra++);
  516. } while (b--);
  517. )
  518. vmcase(OP_GETUPVAL,
  519. int b = GETARG_B(i);
  520. setobj2s(L, ra, cl->upvals[b]->v);
  521. )
  522. vmcase(OP_GETTABUP,
  523. int b = GETARG_B(i);
  524. Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
  525. )
  526. vmcase(OP_GETTABLE,
  527. Protect(luaV_gettable(L, RB(i), RKC(i), ra));
  528. )
  529. vmcase(OP_SETTABUP,
  530. int a = GETARG_A(i);
  531. Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));
  532. )
  533. vmcase(OP_SETUPVAL,
  534. UpVal *uv = cl->upvals[GETARG_B(i)];
  535. setobj(L, uv->v, ra);
  536. luaC_barrier(L, uv, ra);
  537. )
  538. vmcase(OP_SETTABLE,
  539. Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
  540. )
  541. vmcase(OP_NEWTABLE,
  542. int b = GETARG_B(i);
  543. int c = GETARG_C(i);
  544. Table *t = luaH_new(L);
  545. sethvalue(L, ra, t);
  546. if (b != 0 || c != 0)
  547. luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
  548. checkGC(L, ra + 1);
  549. )
  550. vmcase(OP_SELF,
  551. StkId rb = RB(i);
  552. setobjs2s(L, ra+1, rb);
  553. Protect(luaV_gettable(L, rb, RKC(i), ra));
  554. )
  555. vmcase(OP_ADD,
  556. arith_op(luai_numadd, TM_ADD);
  557. )
  558. vmcase(OP_SUB,
  559. arith_op(luai_numsub, TM_SUB);
  560. )
  561. vmcase(OP_MUL,
  562. arith_op(luai_nummul, TM_MUL);
  563. )
  564. vmcase(OP_DIV,
  565. arith_op(luai_numdiv, TM_DIV);
  566. )
  567. vmcase(OP_MOD,
  568. arith_op(luai_nummod, TM_MOD);
  569. )
  570. vmcase(OP_POW,
  571. arith_op(luai_numpow, TM_POW);
  572. )
  573. vmcase(OP_UNM,
  574. TValue *rb = RB(i);
  575. if (ttisnumber(rb)) {
  576. lua_Number nb = nvalue(rb);
  577. setnvalue(ra, luai_numunm(L, nb));
  578. }
  579. else {
  580. Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
  581. }
  582. )
  583. vmcase(OP_NOT,
  584. TValue *rb = RB(i);
  585. int res = l_isfalse(rb); /* next assignment may change this value */
  586. setbvalue(ra, res);
  587. )
  588. vmcase(OP_LEN,
  589. Protect(luaV_objlen(L, ra, RB(i)));
  590. )
  591. vmcase(OP_CONCAT,
  592. int b = GETARG_B(i);
  593. int c = GETARG_C(i);
  594. StkId rb;
  595. L->top = base + c + 1; /* mark the end of concat operands */
  596. Protect(luaV_concat(L, c - b + 1));
  597. ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */
  598. rb = b + base;
  599. setobjs2s(L, ra, rb);
  600. checkGC(L, (ra >= rb ? ra + 1 : rb));
  601. L->top = ci->top; /* restore top */
  602. )
  603. vmcase(OP_JMP,
  604. dojump(ci, i, 0);
  605. )
  606. vmcase(OP_EQ,
  607. TValue *rb = RKB(i);
  608. TValue *rc = RKC(i);
  609. Protect(
  610. if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i))
  611. ci->u.l.savedpc++;
  612. else
  613. donextjump(ci);
  614. )
  615. )
  616. vmcase(OP_LT,
  617. Protect(
  618. if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
  619. ci->u.l.savedpc++;
  620. else
  621. donextjump(ci);
  622. )
  623. )
  624. vmcase(OP_LE,
  625. Protect(
  626. if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
  627. ci->u.l.savedpc++;
  628. else
  629. donextjump(ci);
  630. )
  631. )
  632. vmcase(OP_TEST,
  633. if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
  634. ci->u.l.savedpc++;
  635. else
  636. donextjump(ci);
  637. )
  638. vmcase(OP_TESTSET,
  639. TValue *rb = RB(i);
  640. if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
  641. ci->u.l.savedpc++;
  642. else {
  643. setobjs2s(L, ra, rb);
  644. donextjump(ci);
  645. }
  646. )
  647. vmcase(OP_CALL,
  648. int b = GETARG_B(i);
  649. int nresults = GETARG_C(i) - 1;
  650. if (b != 0) L->top = ra+b; /* else previous instruction set top */
  651. if (luaD_precall(L, ra, nresults)) { /* C function? */
  652. if (nresults >= 0) L->top = ci->top; /* adjust results */
  653. base = ci->u.l.base;
  654. }
  655. else { /* Lua function */
  656. ci = L->ci;
  657. ci->callstatus |= CIST_REENTRY;
  658. goto newframe; /* restart luaV_execute over new Lua function */
  659. }
  660. )
  661. vmcase(OP_TAILCALL,
  662. int b = GETARG_B(i);
  663. if (b != 0) L->top = ra+b; /* else previous instruction set top */
  664. lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
  665. if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */
  666. base = ci->u.l.base;
  667. else {
  668. /* tail call: put called frame (n) in place of caller one (o) */
  669. CallInfo *nci = L->ci; /* called frame */
  670. CallInfo *oci = nci->previous; /* caller frame */
  671. StkId nfunc = nci->func; /* called function */
  672. StkId ofunc = oci->func; /* caller function */
  673. /* last stack slot filled by 'precall' */
  674. StkId lim = nci->u.l.base + getproto(nfunc)->numparams;
  675. int aux;
  676. /* close all upvalues from previous call */
  677. if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base);
  678. /* move new frame into old one */
  679. for (aux = 0; nfunc + aux < lim; aux++)
  680. setobjs2s(L, ofunc + aux, nfunc + aux);
  681. oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */
  682. oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */
  683. oci->u.l.savedpc = nci->u.l.savedpc;
  684. oci->callstatus |= CIST_TAIL; /* function was tail called */
  685. ci = L->ci = oci; /* remove new frame */
  686. lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
  687. goto newframe; /* restart luaV_execute over new Lua function */
  688. }
  689. )
  690. vmcasenb(OP_RETURN,
  691. int b = GETARG_B(i);
  692. if (b != 0) L->top = ra+b-1;
  693. if (cl->p->sizep > 0) luaF_close(L, base);
  694. b = luaD_poscall(L, ra);
  695. if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */
  696. return; /* external invocation: return */
  697. else { /* invocation via reentry: continue execution */
  698. ci = L->ci;
  699. if (b) L->top = ci->top;
  700. lua_assert(isLua(ci));
  701. lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
  702. goto newframe; /* restart luaV_execute over new Lua function */
  703. }
  704. )
  705. vmcase(OP_FORLOOP,
  706. lua_Number step = nvalue(ra+2);
  707. lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */
  708. lua_Number limit = nvalue(ra+1);
  709. if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)
  710. : luai_numle(L, limit, idx)) {
  711. ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
  712. setnvalue(ra, idx); /* update internal index... */
  713. setnvalue(ra+3, idx); /* ...and external index */
  714. }
  715. )
  716. vmcase(OP_FORPREP,
  717. const TValue *init = ra;
  718. const TValue *plimit = ra+1;
  719. const TValue *pstep = ra+2;
  720. if (!tonumber(init, ra))
  721. luaG_runerror(L, LUA_QL("for") " initial value must be a number");
  722. else if (!tonumber(plimit, ra+1))
  723. luaG_runerror(L, LUA_QL("for") " limit must be a number");
  724. else if (!tonumber(pstep, ra+2))
  725. luaG_runerror(L, LUA_QL("for") " step must be a number");
  726. setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
  727. ci->u.l.savedpc += GETARG_sBx(i);
  728. )
  729. vmcasenb(OP_TFORCALL,
  730. StkId cb = ra + 3; /* call base */
  731. setobjs2s(L, cb+2, ra+2);
  732. setobjs2s(L, cb+1, ra+1);
  733. setobjs2s(L, cb, ra);
  734. L->top = cb + 3; /* func. + 2 args (state and index) */
  735. Protect(luaD_call(L, cb, GETARG_C(i), 1));
  736. L->top = ci->top;
  737. i = *(ci->u.l.savedpc++); /* go to next instruction */
  738. ra = RA(i);
  739. lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
  740. goto l_tforloop;
  741. )
  742. vmcase(OP_TFORLOOP,
  743. l_tforloop:
  744. if (!ttisnil(ra + 1)) { /* continue loop? */
  745. setobjs2s(L, ra, ra + 1); /* save control variable */
  746. ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
  747. }
  748. )
  749. vmcase(OP_SETLIST,
  750. int n = GETARG_B(i);
  751. int c = GETARG_C(i);
  752. int last;
  753. Table *h;
  754. if (n == 0) n = cast_int(L->top - ra) - 1;
  755. if (c == 0) {
  756. lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
  757. c = GETARG_Ax(*ci->u.l.savedpc++);
  758. }
  759. luai_runtimecheck(L, ttistable(ra));
  760. h = hvalue(ra);
  761. last = ((c-1)*LFIELDS_PER_FLUSH) + n;
  762. if (last > h->sizearray) /* needs more space? */
  763. luaH_resizearray(L, h, last); /* pre-allocate it at once */
  764. for (; n > 0; n--) {
  765. TValue *val = ra+n;
  766. luaH_setint(L, h, last--, val);
  767. luaC_barrierback(L, obj2gco(h), val);
  768. }
  769. L->top = ci->top; /* correct top (in case of previous open call) */
  770. )
  771. vmcase(OP_CLOSURE,
  772. Proto *p = cl->p->p[GETARG_Bx(i)];
  773. Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */
  774. if (ncl == NULL) /* no match? */
  775. pushclosure(L, p, cl->upvals, base, ra); /* create a new one */
  776. else
  777. setclLvalue(L, ra, ncl); /* push cashed closure */
  778. checkGC(L, ra + 1);
  779. )
  780. vmcase(OP_VARARG,
  781. int b = GETARG_B(i) - 1;
  782. int j;
  783. int n = cast_int(base - ci->func) - cl->p->numparams - 1;
  784. if (b < 0) { /* B == 0? */
  785. b = n; /* get all var. arguments */
  786. Protect(luaD_checkstack(L, n));
  787. ra = RA(i); /* previous call may change the stack */
  788. L->top = ra + n;
  789. }
  790. for (j = 0; j < b; j++) {
  791. if (j < n) {
  792. setobjs2s(L, ra + j, base - n + j);
  793. }
  794. else {
  795. setnilvalue(ra + j);
  796. }
  797. }
  798. )
  799. vmcase(OP_EXTRAARG,
  800. lua_assert(0);
  801. )
  802. }
  803. }
  804. }