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