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