lvm.c 28 KB

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