1 /*
2     see copyright notice in squirrel.h
3 */
4 #include <math.h>
5 #include "sqpcheader.h"
6 #include <stdlib.h>
7 #include "sqopcodes.h"
8 #include "sqvm.h"
9 #include "sqfuncproto.h"
10 #include "sqclosure.h"
11 #include "sqstring.h"
12 #include "sqtable.h"
13 #include "squserdata.h"
14 #include "sqarray.h"
15 #include "sqclass.h"
16 
17 #define TOP() (_stack._vals[_top-1])
18 #define TARGET _stack._vals[_stackbase+arg0]
19 #define STK(a) _stack._vals[_stackbase+(a)]
20 
BW_OP(SQUnsignedInteger op,SQObjectPtr & trg,const SQObjectPtr & o1,const SQObjectPtr & o2)21 bool SQVM::BW_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
22 {
23     SQInteger res;
24     if((sq_type(o1)| sq_type(o2)) == OT_INTEGER)
25     {
26         SQInteger i1 = _integer(o1), i2 = _integer(o2);
27         switch(op) {
28             case BW_AND:    res = i1 & i2; break;
29             case BW_OR:     res = i1 | i2; break;
30             case BW_XOR:    res = i1 ^ i2; break;
31             case BW_SHIFTL: res = i1 << i2; break;
32             case BW_SHIFTR: res = i1 >> i2; break;
33             case BW_USHIFTR:res = (SQInteger)(*((SQUnsignedInteger*)&i1) >> i2); break;
34             default: { Raise_Error(_SC("internal vm error bitwise op failed")); return false; }
35         }
36     }
37     else { Raise_Error(_SC("bitwise op between '%s' and '%s'"),GetTypeName(o1),GetTypeName(o2)); return false;}
38     trg = res;
39     return true;
40 }
41 
42 #define _ARITH_(op,trg,o1,o2) \
43 { \
44     SQInteger tmask = sq_type(o1)|sq_type(o2); \
45     switch(tmask) { \
46         case OT_INTEGER: trg = _integer(o1) op _integer(o2);break; \
47         case (OT_FLOAT|OT_INTEGER): \
48         case (OT_FLOAT): trg = tofloat(o1) op tofloat(o2); break;\
49         default: _GUARD(ARITH_OP((#op)[0],trg,o1,o2)); break;\
50     } \
51 }
52 
53 #define _ARITH_NOZERO(op,trg,o1,o2,err) \
54 { \
55     SQInteger tmask = sq_type(o1)|sq_type(o2); \
56     switch(tmask) { \
57         case OT_INTEGER: { SQInteger i2 = _integer(o2); if(i2 == 0) { Raise_Error(err); SQ_THROW(); } trg = _integer(o1) op i2; } break;\
58         case (OT_FLOAT|OT_INTEGER): \
59         case (OT_FLOAT): trg = tofloat(o1) op tofloat(o2); break;\
60         default: _GUARD(ARITH_OP((#op)[0],trg,o1,o2)); break;\
61     } \
62 }
63 
ARITH_OP(SQUnsignedInteger op,SQObjectPtr & trg,const SQObjectPtr & o1,const SQObjectPtr & o2)64 bool SQVM::ARITH_OP(SQUnsignedInteger op,SQObjectPtr &trg,const SQObjectPtr &o1,const SQObjectPtr &o2)
65 {
66     SQInteger tmask = sq_type(o1)| sq_type(o2);
67     switch(tmask) {
68         case OT_INTEGER:{
69             SQInteger res, i1 = _integer(o1), i2 = _integer(o2);
70             switch(op) {
71             case '+': res = i1 + i2; break;
72             case '-': res = i1 - i2; break;
73             case '/': if (i2 == 0) { Raise_Error(_SC("division by zero")); return false; }
74                     else if (i2 == -1 && i1 == INT_MIN) { Raise_Error(_SC("integer overflow")); return false; }
75                     res = i1 / i2;
76                     break;
77             case '*': res = i1 * i2; break;
78             case '%': if (i2 == 0) { Raise_Error(_SC("modulo by zero")); return false; }
79                     else if (i2 == -1 && i1 == INT_MIN) { res = 0; break; }
80                     res = i1 % i2;
81                     break;
82             default: res = 0xDEADBEEF;
83             }
84             trg = res; }
85             break;
86         case (OT_FLOAT|OT_INTEGER):
87         case (OT_FLOAT):{
88             SQFloat res, f1 = tofloat(o1), f2 = tofloat(o2);
89             switch(op) {
90             case '+': res = f1 + f2; break;
91             case '-': res = f1 - f2; break;
92             case '/': res = f1 / f2; break;
93             case '*': res = f1 * f2; break;
94             case '%': res = SQFloat(fmod((double)f1,(double)f2)); break;
95             default: res = 0x0f;
96             }
97             trg = res; }
98             break;
99         default:
100             if(op == '+' && (tmask & _RT_STRING)){
101                 if(!StringCat(o1, o2, trg)) return false;
102             }
103             else if(!ArithMetaMethod(op,o1,o2,trg)) {
104                 return false;
105             }
106     }
107     return true;
108 }
109 
SQVM(SQSharedState * ss)110 SQVM::SQVM(SQSharedState *ss)
111 {
112     _sharedstate=ss;
113     _suspended = SQFalse;
114     _suspended_target = -1;
115     _suspended_root = SQFalse;
116     _suspended_traps = -1;
117     _foreignptr = NULL;
118     _nnativecalls = 0;
119     _nmetamethodscall = 0;
120     _lasterror.Null();
121     _errorhandler.Null();
122     _debughook = false;
123     _debughook_native = NULL;
124     _debughook_closure.Null();
125     _openouters = NULL;
126     ci = NULL;
127     _releasehook = NULL;
128     INIT_CHAIN();ADD_TO_CHAIN(&_ss(this)->_gc_chain,this);
129 }
130 
Finalize()131 void SQVM::Finalize()
132 {
133     if(_releasehook) { _releasehook(_foreignptr,0); _releasehook = NULL; }
134     if(_openouters) CloseOuters(&_stack._vals[0]);
135     _roottable.Null();
136     _lasterror.Null();
137     _errorhandler.Null();
138     _debughook = false;
139     _debughook_native = NULL;
140     _debughook_closure.Null();
141     temp_reg.Null();
142     _callstackdata.resize(0);
143     SQInteger size=_stack.size();
144     for(SQInteger i=0;i<size;i++)
145         _stack[i].Null();
146 }
147 
~SQVM()148 SQVM::~SQVM()
149 {
150     Finalize();
151     REMOVE_FROM_CHAIN(&_ss(this)->_gc_chain,this);
152 }
153 
ArithMetaMethod(SQInteger op,const SQObjectPtr & o1,const SQObjectPtr & o2,SQObjectPtr & dest)154 bool SQVM::ArithMetaMethod(SQInteger op,const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &dest)
155 {
156     SQMetaMethod mm;
157     switch(op){
158         case _SC('+'): mm=MT_ADD; break;
159         case _SC('-'): mm=MT_SUB; break;
160         case _SC('/'): mm=MT_DIV; break;
161         case _SC('*'): mm=MT_MUL; break;
162         case _SC('%'): mm=MT_MODULO; break;
163         default: mm = MT_ADD; assert(0); break; //shutup compiler
164     }
165     if(is_delegable(o1) && _delegable(o1)->_delegate) {
166 
167         SQObjectPtr closure;
168         if(_delegable(o1)->GetMetaMethod(this, mm, closure)) {
169             Push(o1);Push(o2);
170             return CallMetaMethod(closure,mm,2,dest);
171         }
172     }
173     Raise_Error(_SC("arith op %c on between '%s' and '%s'"),op,GetTypeName(o1),GetTypeName(o2));
174     return false;
175 }
176 
NEG_OP(SQObjectPtr & trg,const SQObjectPtr & o)177 bool SQVM::NEG_OP(SQObjectPtr &trg,const SQObjectPtr &o)
178 {
179 
180     switch(sq_type(o)) {
181     case OT_INTEGER:
182         trg = -_integer(o);
183         return true;
184     case OT_FLOAT:
185         trg = -_float(o);
186         return true;
187     case OT_TABLE:
188     case OT_USERDATA:
189     case OT_INSTANCE:
190         if(_delegable(o)->_delegate) {
191             SQObjectPtr closure;
192             if(_delegable(o)->GetMetaMethod(this, MT_UNM, closure)) {
193                 Push(o);
194                 if(!CallMetaMethod(closure, MT_UNM, 1, temp_reg)) return false;
195                 _Swap(trg,temp_reg);
196                 return true;
197 
198             }
199         }
200     default:break; //shutup compiler
201     }
202     Raise_Error(_SC("attempt to negate a %s"), GetTypeName(o));
203     return false;
204 }
205 
206 #define _RET_SUCCEED(exp) { result = (exp); return true; }
ObjCmp(const SQObjectPtr & o1,const SQObjectPtr & o2,SQInteger & result)207 bool SQVM::ObjCmp(const SQObjectPtr &o1,const SQObjectPtr &o2,SQInteger &result)
208 {
209     SQObjectType t1 = sq_type(o1), t2 = sq_type(o2);
210     if(t1 == t2) {
211         if(_rawval(o1) == _rawval(o2))_RET_SUCCEED(0);
212         SQObjectPtr res;
213         switch(t1){
214         case OT_STRING:
215             _RET_SUCCEED(scstrcmp(_stringval(o1),_stringval(o2)));
216         case OT_INTEGER:
217             _RET_SUCCEED((_integer(o1)<_integer(o2))?-1:1);
218         case OT_FLOAT:
219             _RET_SUCCEED((_float(o1)<_float(o2))?-1:1);
220         case OT_TABLE:
221         case OT_USERDATA:
222         case OT_INSTANCE:
223             if(_delegable(o1)->_delegate) {
224                 SQObjectPtr closure;
225                 if(_delegable(o1)->GetMetaMethod(this, MT_CMP, closure)) {
226                     Push(o1);Push(o2);
227                     if(CallMetaMethod(closure,MT_CMP,2,res)) {
228                         if(sq_type(res) != OT_INTEGER) {
229                             Raise_Error(_SC("_cmp must return an integer"));
230                             return false;
231                         }
232                         _RET_SUCCEED(_integer(res))
233                     }
234                     return false;
235                 }
236             }
237             //continues through (no break needed)
238         default:
239             _RET_SUCCEED( _userpointer(o1) < _userpointer(o2)?-1:1 );
240         }
241         assert(0);
242         //if(type(res)!=OT_INTEGER) { Raise_CompareError(o1,o2); return false; }
243         //  _RET_SUCCEED(_integer(res));
244 
245     }
246     else{
247         if(sq_isnumeric(o1) && sq_isnumeric(o2)){
248             if((t1==OT_INTEGER) && (t2==OT_FLOAT)) {
249                 if( _integer(o1)==_float(o2) ) { _RET_SUCCEED(0); }
250                 else if( _integer(o1)<_float(o2) ) { _RET_SUCCEED(-1); }
251                 _RET_SUCCEED(1);
252             }
253             else{
254                 if( _float(o1)==_integer(o2) ) { _RET_SUCCEED(0); }
255                 else if( _float(o1)<_integer(o2) ) { _RET_SUCCEED(-1); }
256                 _RET_SUCCEED(1);
257             }
258         }
259         else if(t1==OT_NULL) {_RET_SUCCEED(-1);}
260         else if(t2==OT_NULL) {_RET_SUCCEED(1);}
261         else { Raise_CompareError(o1,o2); return false; }
262 
263     }
264     assert(0);
265     _RET_SUCCEED(0); //cannot happen
266 }
267 
CMP_OP(CmpOP op,const SQObjectPtr & o1,const SQObjectPtr & o2,SQObjectPtr & res)268 bool SQVM::CMP_OP(CmpOP op, const SQObjectPtr &o1,const SQObjectPtr &o2,SQObjectPtr &res)
269 {
270     SQInteger r;
271     if(ObjCmp(o1,o2,r)) {
272         switch(op) {
273             case CMP_G: res = (r > 0); return true;
274             case CMP_GE: res = (r >= 0); return true;
275             case CMP_L: res = (r < 0); return true;
276             case CMP_LE: res = (r <= 0); return true;
277             case CMP_3W: res = r; return true;
278         }
279         assert(0);
280     }
281     return false;
282 }
283 
ToString(const SQObjectPtr & o,SQObjectPtr & res)284 bool SQVM::ToString(const SQObjectPtr &o,SQObjectPtr &res)
285 {
286     switch(sq_type(o)) {
287     case OT_STRING:
288         res = o;
289         return true;
290     case OT_FLOAT:
291         scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)),sq_rsl(NUMBER_MAX_CHAR),_SC("%g"),_float(o));
292         break;
293     case OT_INTEGER:
294         scsprintf(_sp(sq_rsl(NUMBER_MAX_CHAR+1)),sq_rsl(NUMBER_MAX_CHAR),_PRINT_INT_FMT,_integer(o));
295         break;
296     case OT_BOOL:
297         scsprintf(_sp(sq_rsl(6)),sq_rsl(6),_integer(o)?_SC("true"):_SC("false"));
298         break;
299     case OT_TABLE:
300     case OT_USERDATA:
301     case OT_INSTANCE:
302         if(_delegable(o)->_delegate) {
303             SQObjectPtr closure;
304             if(_delegable(o)->GetMetaMethod(this, MT_TOSTRING, closure)) {
305                 Push(o);
306                 if(CallMetaMethod(closure,MT_TOSTRING,1,res)) {
307                     if(sq_type(res) == OT_STRING)
308                         return true;
309                 }
310                 else {
311                     return false;
312                 }
313             }
314         }
315     default:
316         scsprintf(_sp(sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR)),sq_rsl((sizeof(void*)*2)+NUMBER_MAX_CHAR),_SC("(%s : 0x%p)"),GetTypeName(o),(void*)_rawval(o));
317     }
318     res = SQString::Create(_ss(this),_spval);
319     return true;
320 }
321 
322 
StringCat(const SQObjectPtr & str,const SQObjectPtr & obj,SQObjectPtr & dest)323 bool SQVM::StringCat(const SQObjectPtr &str,const SQObjectPtr &obj,SQObjectPtr &dest)
324 {
325     SQObjectPtr a, b;
326     if(!ToString(str, a)) return false;
327     if(!ToString(obj, b)) return false;
328     SQInteger l = _string(a)->_len , ol = _string(b)->_len;
329     SQChar *s = _sp(sq_rsl(l + ol + 1));
330     memcpy(s, _stringval(a), sq_rsl(l));
331     memcpy(s + l, _stringval(b), sq_rsl(ol));
332     dest = SQString::Create(_ss(this), _spval, l + ol);
333     return true;
334 }
335 
TypeOf(const SQObjectPtr & obj1,SQObjectPtr & dest)336 bool SQVM::TypeOf(const SQObjectPtr &obj1,SQObjectPtr &dest)
337 {
338     if(is_delegable(obj1) && _delegable(obj1)->_delegate) {
339         SQObjectPtr closure;
340         if(_delegable(obj1)->GetMetaMethod(this, MT_TYPEOF, closure)) {
341             Push(obj1);
342             return CallMetaMethod(closure,MT_TYPEOF,1,dest);
343         }
344     }
345     dest = SQString::Create(_ss(this),GetTypeName(obj1));
346     return true;
347 }
348 
Init(SQVM * friendvm,SQInteger stacksize)349 bool SQVM::Init(SQVM *friendvm, SQInteger stacksize)
350 {
351     _stack.resize(stacksize);
352     _alloccallsstacksize = 4;
353     _callstackdata.resize(_alloccallsstacksize);
354     _callsstacksize = 0;
355     _callsstack = &_callstackdata[0];
356     _stackbase = 0;
357     _top = 0;
358     if(!friendvm) {
359         _roottable = SQTable::Create(_ss(this), 0);
360         sq_base_register(this);
361     }
362     else {
363         _roottable = friendvm->_roottable;
364         _errorhandler = friendvm->_errorhandler;
365         _debughook = friendvm->_debughook;
366         _debughook_native = friendvm->_debughook_native;
367         _debughook_closure = friendvm->_debughook_closure;
368     }
369 
370 
371     return true;
372 }
373 
374 
StartCall(SQClosure * closure,SQInteger target,SQInteger args,SQInteger stackbase,bool tailcall)375 bool SQVM::StartCall(SQClosure *closure,SQInteger target,SQInteger args,SQInteger stackbase,bool tailcall)
376 {
377     SQFunctionProto *func = closure->_function;
378 
379     SQInteger paramssize = func->_nparameters;
380     const SQInteger newtop = stackbase + func->_stacksize;
381     SQInteger nargs = args;
382     if(func->_varparams)
383     {
384         paramssize--;
385         if (nargs < paramssize) {
386             Raise_Error(_SC("wrong number of parameters"));
387             return false;
388         }
389 
390         //dumpstack(stackbase);
391         SQInteger nvargs = nargs - paramssize;
392         SQArray *arr = SQArray::Create(_ss(this),nvargs);
393         SQInteger pbase = stackbase+paramssize;
394         for(SQInteger n = 0; n < nvargs; n++) {
395             arr->_values[n] = _stack._vals[pbase];
396             _stack._vals[pbase].Null();
397             pbase++;
398 
399         }
400         _stack._vals[stackbase+paramssize] = arr;
401         //dumpstack(stackbase);
402     }
403     else if (paramssize != nargs) {
404         SQInteger ndef = func->_ndefaultparams;
405         SQInteger diff;
406         if(ndef && nargs < paramssize && (diff = paramssize - nargs) <= ndef) {
407             for(SQInteger n = ndef - diff; n < ndef; n++) {
408                 _stack._vals[stackbase + (nargs++)] = closure->_defaultparams[n];
409             }
410         }
411         else {
412             Raise_Error(_SC("wrong number of parameters"));
413             return false;
414         }
415     }
416 
417     if(closure->_env) {
418         _stack._vals[stackbase] = closure->_env->_obj;
419     }
420 
421     if(!EnterFrame(stackbase, newtop, tailcall)) return false;
422 
423     ci->_closure  = closure;
424     ci->_literals = func->_literals;
425     ci->_ip       = func->_instructions;
426     ci->_target   = (SQInt32)target;
427 
428     if (_debughook) {
429         CallDebugHook(_SC('c'));
430     }
431 
432     if (closure->_function->_bgenerator) {
433         SQFunctionProto *f = closure->_function;
434         SQGenerator *gen = SQGenerator::Create(_ss(this), closure);
435         if(!gen->Yield(this,f->_stacksize))
436             return false;
437         SQObjectPtr temp;
438         Return(1, target, temp);
439         STK(target) = gen;
440     }
441 
442 
443     return true;
444 }
445 
Return(SQInteger _arg0,SQInteger _arg1,SQObjectPtr & retval)446 bool SQVM::Return(SQInteger _arg0, SQInteger _arg1, SQObjectPtr &retval)
447 {
448     SQBool    _isroot      = ci->_root;
449     SQInteger callerbase   = _stackbase - ci->_prevstkbase;
450 
451     if (_debughook) {
452         for(SQInteger i=0; i<ci->_ncalls; i++) {
453             CallDebugHook(_SC('r'));
454         }
455     }
456 
457     SQObjectPtr *dest;
458     if (_isroot) {
459         dest = &(retval);
460     } else if (ci->_target == -1) {
461         dest = NULL;
462     } else {
463         dest = &_stack._vals[callerbase + ci->_target];
464     }
465     if (dest) {
466         if(_arg0 != 0xFF) {
467             *dest = _stack._vals[_stackbase+_arg1];
468         }
469         else {
470             dest->Null();
471         }
472         //*dest = (_arg0 != 0xFF) ? _stack._vals[_stackbase+_arg1] : _null_;
473     }
474     LeaveFrame();
475     return _isroot ? true : false;
476 }
477 
478 #define _RET_ON_FAIL(exp) { if(!exp) return false; }
479 
PLOCAL_INC(SQInteger op,SQObjectPtr & target,SQObjectPtr & a,SQObjectPtr & incr)480 bool SQVM::PLOCAL_INC(SQInteger op,SQObjectPtr &target, SQObjectPtr &a, SQObjectPtr &incr)
481 {
482     SQObjectPtr trg;
483     _RET_ON_FAIL(ARITH_OP( op , trg, a, incr));
484     target = a;
485     a = trg;
486     return true;
487 }
488 
DerefInc(SQInteger op,SQObjectPtr & target,SQObjectPtr & self,SQObjectPtr & key,SQObjectPtr & incr,bool postfix,SQInteger selfidx)489 bool SQVM::DerefInc(SQInteger op,SQObjectPtr &target, SQObjectPtr &self, SQObjectPtr &key, SQObjectPtr &incr, bool postfix,SQInteger selfidx)
490 {
491     SQObjectPtr tmp, tself = self, tkey = key;
492     if (!Get(tself, tkey, tmp, 0, selfidx)) { return false; }
493     _RET_ON_FAIL(ARITH_OP( op , target, tmp, incr))
494     if (!Set(tself, tkey, target,selfidx)) { return false; }
495     if (postfix) target = tmp;
496     return true;
497 }
498 
499 #define arg0 (_i_._arg0)
500 #define sarg0 ((SQInteger)*((const signed char *)&_i_._arg0))
501 #define arg1 (_i_._arg1)
502 #define sarg1 (*((const SQInt32 *)&_i_._arg1))
503 #define arg2 (_i_._arg2)
504 #define arg3 (_i_._arg3)
505 #define sarg3 ((SQInteger)*((const signed char *)&_i_._arg3))
506 
Suspend()507 SQRESULT SQVM::Suspend()
508 {
509     if (_suspended)
510         return sq_throwerror(this, _SC("cannot suspend an already suspended vm"));
511     if (_nnativecalls!=2)
512         return sq_throwerror(this, _SC("cannot suspend through native calls/metamethods"));
513     return SQ_SUSPEND_FLAG;
514 }
515 
516 
517 #define _FINISH(howmuchtojump) {jump = howmuchtojump; return true; }
FOREACH_OP(SQObjectPtr & o1,SQObjectPtr & o2,SQObjectPtr & o3,SQObjectPtr & o4,SQInteger SQ_UNUSED_ARG (arg_2),int exitpos,int & jump)518 bool SQVM::FOREACH_OP(SQObjectPtr &o1,SQObjectPtr &o2,SQObjectPtr
519 &o3,SQObjectPtr &o4,SQInteger SQ_UNUSED_ARG(arg_2),int exitpos,int &jump)
520 {
521     SQInteger nrefidx;
522     switch(sq_type(o1)) {
523     case OT_TABLE:
524         if((nrefidx = _table(o1)->Next(false,o4, o2, o3)) == -1) _FINISH(exitpos);
525         o4 = (SQInteger)nrefidx; _FINISH(1);
526     case OT_ARRAY:
527         if((nrefidx = _array(o1)->Next(o4, o2, o3)) == -1) _FINISH(exitpos);
528         o4 = (SQInteger) nrefidx; _FINISH(1);
529     case OT_STRING:
530         if((nrefidx = _string(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
531         o4 = (SQInteger)nrefidx; _FINISH(1);
532     case OT_CLASS:
533         if((nrefidx = _class(o1)->Next(o4, o2, o3)) == -1)_FINISH(exitpos);
534         o4 = (SQInteger)nrefidx; _FINISH(1);
535     case OT_USERDATA:
536     case OT_INSTANCE:
537         if(_delegable(o1)->_delegate) {
538             SQObjectPtr itr;
539             SQObjectPtr closure;
540             if(_delegable(o1)->GetMetaMethod(this, MT_NEXTI, closure)) {
541                 Push(o1);
542                 Push(o4);
543                 if(CallMetaMethod(closure, MT_NEXTI, 2, itr)) {
544                     o4 = o2 = itr;
545                     if(sq_type(itr) == OT_NULL) _FINISH(exitpos);
546                     if(!Get(o1, itr, o3, 0, DONT_FALL_BACK)) {
547                         Raise_Error(_SC("_nexti returned an invalid idx")); // cloud be changed
548                         return false;
549                     }
550                     _FINISH(1);
551                 }
552                 else {
553                     return false;
554                 }
555             }
556             Raise_Error(_SC("_nexti failed"));
557             return false;
558         }
559         break;
560     case OT_GENERATOR:
561         if(_generator(o1)->_state == SQGenerator::eDead) _FINISH(exitpos);
562         if(_generator(o1)->_state == SQGenerator::eSuspended) {
563             SQInteger idx = 0;
564             if(sq_type(o4) == OT_INTEGER) {
565                 idx = _integer(o4) + 1;
566             }
567             o2 = idx;
568             o4 = idx;
569             _generator(o1)->Resume(this, o3);
570             _FINISH(0);
571         }
572     default:
573         Raise_Error(_SC("cannot iterate %s"), GetTypeName(o1));
574     }
575     return false; //cannot be hit(just to avoid warnings)
576 }
577 
578 #define COND_LITERAL (arg3!=0?ci->_literals[arg1]:STK(arg1))
579 
580 #define SQ_THROW() { goto exception_trap; }
581 
582 #define _GUARD(exp) { if(!exp) { SQ_THROW();} }
583 
CLOSURE_OP(SQObjectPtr & target,SQFunctionProto * func)584 bool SQVM::CLOSURE_OP(SQObjectPtr &target, SQFunctionProto *func)
585 {
586     SQInteger nouters;
587     SQClosure *closure = SQClosure::Create(_ss(this), func,_table(_roottable)->GetWeakRef(OT_TABLE));
588     if((nouters = func->_noutervalues)) {
589         for(SQInteger i = 0; i<nouters; i++) {
590             SQOuterVar &v = func->_outervalues[i];
591             switch(v._type){
592             case otLOCAL:
593                 FindOuter(closure->_outervalues[i], &STK(_integer(v._src)));
594                 break;
595             case otOUTER:
596                 closure->_outervalues[i] = _closure(ci->_closure)->_outervalues[_integer(v._src)];
597                 break;
598             }
599         }
600     }
601     SQInteger ndefparams;
602     if((ndefparams = func->_ndefaultparams)) {
603         for(SQInteger i = 0; i < ndefparams; i++) {
604             SQInteger spos = func->_defaultparams[i];
605             closure->_defaultparams[i] = _stack._vals[_stackbase + spos];
606         }
607     }
608     target = closure;
609     return true;
610 
611 }
612 
613 
CLASS_OP(SQObjectPtr & target,SQInteger baseclass,SQInteger attributes)614 bool SQVM::CLASS_OP(SQObjectPtr &target,SQInteger baseclass,SQInteger attributes)
615 {
616     SQClass *base = NULL;
617     SQObjectPtr attrs;
618     if(baseclass != -1) {
619         if(sq_type(_stack._vals[_stackbase+baseclass]) != OT_CLASS) { Raise_Error(_SC("trying to inherit from a %s"),GetTypeName(_stack._vals[_stackbase+baseclass])); return false; }
620         base = _class(_stack._vals[_stackbase + baseclass]);
621     }
622     if(attributes != MAX_FUNC_STACKSIZE) {
623         attrs = _stack._vals[_stackbase+attributes];
624     }
625     target = SQClass::Create(_ss(this),base);
626     if(sq_type(_class(target)->_metamethods[MT_INHERITED]) != OT_NULL) {
627         int nparams = 2;
628         SQObjectPtr ret;
629         Push(target); Push(attrs);
630         if(!Call(_class(target)->_metamethods[MT_INHERITED],nparams,_top - nparams, ret, false)) {
631             Pop(nparams);
632             return false;
633         }
634         Pop(nparams);
635     }
636     _class(target)->_attributes = attrs;
637     return true;
638 }
639 
IsEqual(const SQObjectPtr & o1,const SQObjectPtr & o2,bool & res)640 bool SQVM::IsEqual(const SQObjectPtr &o1,const SQObjectPtr &o2,bool &res)
641 {
642     if(sq_type(o1) == sq_type(o2)) {
643         res = (_rawval(o1) == _rawval(o2));
644     }
645     else {
646         if(sq_isnumeric(o1) && sq_isnumeric(o2)) {
647             res = (tofloat(o1) == tofloat(o2));
648         }
649         else {
650             res = false;
651         }
652     }
653     return true;
654 }
655 
IsFalse(SQObjectPtr & o)656 bool SQVM::IsFalse(SQObjectPtr &o)
657 {
658     if(((sq_type(o) & SQOBJECT_CANBEFALSE)
659         && ( ((sq_type(o) == OT_FLOAT) && (_float(o) == SQFloat(0.0))) ))
660 #if !defined(SQUSEDOUBLE) || (defined(SQUSEDOUBLE) && defined(_SQ64))
661         || (_integer(o) == 0) )  //OT_NULL|OT_INTEGER|OT_BOOL
662 #else
663         || (((type(o) != OT_FLOAT) && (_integer(o) == 0))) )  //OT_NULL|OT_INTEGER|OT_BOOL
664 #endif
665     {
666         return true;
667     }
668     return false;
669 }
670 extern SQInstructionDesc g_InstrDesc[];
Execute(SQObjectPtr & closure,SQInteger nargs,SQInteger stackbase,SQObjectPtr & outres,SQBool raiseerror,ExecutionType et)671 bool SQVM::Execute(SQObjectPtr &closure, SQInteger nargs, SQInteger stackbase,SQObjectPtr &outres, SQBool raiseerror,ExecutionType et)
672 {
673     if ((_nnativecalls + 1) > MAX_NATIVE_CALLS) { Raise_Error(_SC("Native stack overflow")); return false; }
674     _nnativecalls++;
675     AutoDec ad(&_nnativecalls);
676     SQInteger traps = 0;
677     CallInfo *prevci = ci;
678 
679     switch(et) {
680         case ET_CALL: {
681             temp_reg = closure;
682             if(!StartCall(_closure(temp_reg), _top - nargs, nargs, stackbase, false)) {
683                 //call the handler if there are no calls in the stack, if not relies on the previous node
684                 if(ci == NULL) CallErrorHandler(_lasterror);
685                 return false;
686             }
687             if(ci == prevci) {
688                 outres = STK(_top-nargs);
689                 return true;
690             }
691             ci->_root = SQTrue;
692                       }
693             break;
694         case ET_RESUME_GENERATOR: _generator(closure)->Resume(this, outres); ci->_root = SQTrue; traps += ci->_etraps; break;
695         case ET_RESUME_VM:
696         case ET_RESUME_THROW_VM:
697             traps = _suspended_traps;
698             ci->_root = _suspended_root;
699             _suspended = SQFalse;
700             if(et  == ET_RESUME_THROW_VM) { SQ_THROW(); }
701             break;
702     }
703 
704 exception_restore:
705     //
706     {
707         for(;;)
708         {
709             const SQInstruction &_i_ = *ci->_ip++;
710             //dumpstack(_stackbase);
711             //scprintf("\n[%d] %s %d %d %d %d\n",ci->_ip-_closure(ci->_closure)->_function->_instructions,g_InstrDesc[_i_.op].name,arg0,arg1,arg2,arg3);
712             switch(_i_.op)
713             {
714             case _OP_LINE: if (_debughook) CallDebugHook(_SC('l'),arg1); continue;
715             case _OP_LOAD: TARGET = ci->_literals[arg1]; continue;
716             case _OP_LOADINT:
717 #ifndef _SQ64
718                 TARGET = (SQInteger)arg1; continue;
719 #else
720                 TARGET = (SQInteger)((SQInt32)arg1); continue;
721 #endif
722             case _OP_LOADFLOAT: TARGET = *((const SQFloat *)&arg1); continue;
723             case _OP_DLOAD: TARGET = ci->_literals[arg1]; STK(arg2) = ci->_literals[arg3];continue;
724             case _OP_TAILCALL:{
725                 SQObjectPtr &t = STK(arg1);
726                 if (sq_type(t) == OT_CLOSURE
727                     && (!_closure(t)->_function->_bgenerator)){
728                     SQObjectPtr clo = t;
729                     SQInteger last_top = _top;
730                     if(_openouters) CloseOuters(&(_stack._vals[_stackbase]));
731                     for (SQInteger i = 0; i < arg3; i++) STK(i) = STK(arg2 + i);
732                     _GUARD(StartCall(_closure(clo), ci->_target, arg3, _stackbase, true));
733                     if (last_top >= _top) {
734                         _top = last_top;
735                     }
736                     continue;
737                 }
738                               }
739             case _OP_CALL: {
740                     SQObjectPtr clo = STK(arg1);
741                     switch (sq_type(clo)) {
742                     case OT_CLOSURE:
743                         _GUARD(StartCall(_closure(clo), sarg0, arg3, _stackbase+arg2, false));
744                         continue;
745                     case OT_NATIVECLOSURE: {
746                         bool suspend;
747 						bool tailcall;
748                         _GUARD(CallNative(_nativeclosure(clo), arg3, _stackbase+arg2, clo, (SQInt32)sarg0, suspend, tailcall));
749                         if(suspend){
750                             _suspended = SQTrue;
751                             _suspended_target = sarg0;
752                             _suspended_root = ci->_root;
753                             _suspended_traps = traps;
754                             outres = clo;
755                             return true;
756                         }
757                         if(sarg0 != -1 && !tailcall) {
758                             STK(arg0) = clo;
759                         }
760                                            }
761                         continue;
762                     case OT_CLASS:{
763                         SQObjectPtr inst;
764                         _GUARD(CreateClassInstance(_class(clo),inst,clo));
765                         if(sarg0 != -1) {
766                             STK(arg0) = inst;
767                         }
768                         SQInteger stkbase;
769                         switch(sq_type(clo)) {
770                             case OT_CLOSURE:
771                                 stkbase = _stackbase+arg2;
772                                 _stack._vals[stkbase] = inst;
773                                 _GUARD(StartCall(_closure(clo), -1, arg3, stkbase, false));
774                                 break;
775                             case OT_NATIVECLOSURE:
776                                 bool dummy;
777                                 stkbase = _stackbase+arg2;
778                                 _stack._vals[stkbase] = inst;
779                                 _GUARD(CallNative(_nativeclosure(clo), arg3, stkbase, clo, -1, dummy, dummy));
780                                 break;
781                             default: break; //shutup GCC 4.x
782                         }
783                         }
784                         break;
785                     case OT_TABLE:
786                     case OT_USERDATA:
787                     case OT_INSTANCE:{
788                         SQObjectPtr closure;
789                         if(_delegable(clo)->_delegate && _delegable(clo)->GetMetaMethod(this,MT_CALL,closure)) {
790                             Push(clo);
791                             for (SQInteger i = 0; i < arg3; i++) Push(STK(arg2 + i));
792                             if(!CallMetaMethod(closure, MT_CALL, arg3+1, clo)) SQ_THROW();
793                             if(sarg0 != -1) {
794                                 STK(arg0) = clo;
795                             }
796                             break;
797                         }
798 
799                         //Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
800                         //SQ_THROW();
801                       }
802                     default:
803                         Raise_Error(_SC("attempt to call '%s'"), GetTypeName(clo));
804                         SQ_THROW();
805                     }
806                 }
807                   continue;
808             case _OP_PREPCALL:
809             case _OP_PREPCALLK: {
810                     SQObjectPtr &key = _i_.op == _OP_PREPCALLK?(ci->_literals)[arg1]:STK(arg1);
811                     SQObjectPtr &o = STK(arg2);
812                     if (!Get(o, key, temp_reg,0,arg2)) {
813                         SQ_THROW();
814                     }
815                     STK(arg3) = o;
816                     _Swap(TARGET,temp_reg);//TARGET = temp_reg;
817                 }
818                 continue;
819             case _OP_GETK:
820                 if (!Get(STK(arg2), ci->_literals[arg1], temp_reg, 0,arg2)) { SQ_THROW();}
821                 _Swap(TARGET,temp_reg);//TARGET = temp_reg;
822                 continue;
823             case _OP_MOVE: TARGET = STK(arg1); continue;
824             case _OP_NEWSLOT:
825                 _GUARD(NewSlot(STK(arg1), STK(arg2), STK(arg3),false));
826                 if(arg0 != 0xFF) TARGET = STK(arg3);
827                 continue;
828             case _OP_DELETE: _GUARD(DeleteSlot(STK(arg1), STK(arg2), TARGET)); continue;
829             case _OP_SET:
830                 if (!Set(STK(arg1), STK(arg2), STK(arg3),arg1)) { SQ_THROW(); }
831                 if (arg0 != 0xFF) TARGET = STK(arg3);
832                 continue;
833             case _OP_GET:
834                 if (!Get(STK(arg1), STK(arg2), temp_reg, 0,arg1)) { SQ_THROW(); }
835                 _Swap(TARGET,temp_reg);//TARGET = temp_reg;
836                 continue;
837             case _OP_EQ:{
838                 bool res;
839                 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
840                 TARGET = res?true:false;
841                 }continue;
842             case _OP_NE:{
843                 bool res;
844                 if(!IsEqual(STK(arg2),COND_LITERAL,res)) { SQ_THROW(); }
845                 TARGET = (!res)?true:false;
846                 } continue;
847             case _OP_ADD: _ARITH_(+,TARGET,STK(arg2),STK(arg1)); continue;
848             case _OP_SUB: _ARITH_(-,TARGET,STK(arg2),STK(arg1)); continue;
849             case _OP_MUL: _ARITH_(*,TARGET,STK(arg2),STK(arg1)); continue;
850             case _OP_DIV: _ARITH_NOZERO(/,TARGET,STK(arg2),STK(arg1),_SC("division by zero")); continue;
851             case _OP_MOD: ARITH_OP('%',TARGET,STK(arg2),STK(arg1)); continue;
852             case _OP_BITW:  _GUARD(BW_OP( arg3,TARGET,STK(arg2),STK(arg1))); continue;
853             case _OP_RETURN:
854                 if((ci)->_generator) {
855                     (ci)->_generator->Kill();
856                 }
857                 if(Return(arg0, arg1, temp_reg)){
858                     assert(traps==0);
859                     //outres = temp_reg;
860                     _Swap(outres,temp_reg);
861                     return true;
862                 }
863                 continue;
864             case _OP_LOADNULLS:{ for(SQInt32 n=0; n < arg1; n++) STK(arg0+n).Null(); }continue;
865             case _OP_LOADROOT:  {
866                 SQWeakRef *w = _closure(ci->_closure)->_root;
867                 if(sq_type(w->_obj) != OT_NULL) {
868                     TARGET = w->_obj;
869                 } else {
870                     TARGET = _roottable; //shoud this be like this? or null
871                 }
872                                 }
873                 continue;
874             case _OP_LOADBOOL: TARGET = arg1?true:false; continue;
875             case _OP_DMOVE: STK(arg0) = STK(arg1); STK(arg2) = STK(arg3); continue;
876             case _OP_JMP: ci->_ip += (sarg1); continue;
877             //case _OP_JNZ: if(!IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
878             case _OP_JCMP:
879                 _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg0),temp_reg));
880                 if(IsFalse(temp_reg)) ci->_ip+=(sarg1);
881                 continue;
882             case _OP_JZ: if(IsFalse(STK(arg0))) ci->_ip+=(sarg1); continue;
883             case _OP_GETOUTER: {
884                 SQClosure *cur_cls = _closure(ci->_closure);
885                 SQOuter *otr = _outer(cur_cls->_outervalues[arg1]);
886                 TARGET = *(otr->_valptr);
887                 }
888             continue;
889             case _OP_SETOUTER: {
890                 SQClosure *cur_cls = _closure(ci->_closure);
891                 SQOuter   *otr = _outer(cur_cls->_outervalues[arg1]);
892                 *(otr->_valptr) = STK(arg2);
893                 if(arg0 != 0xFF) {
894                     TARGET = STK(arg2);
895                 }
896                 }
897             continue;
898             case _OP_NEWOBJ:
899                 switch(arg3) {
900                     case NOT_TABLE: TARGET = SQTable::Create(_ss(this), arg1); continue;
901                     case NOT_ARRAY: TARGET = SQArray::Create(_ss(this), 0); _array(TARGET)->Reserve(arg1); continue;
902                     case NOT_CLASS: _GUARD(CLASS_OP(TARGET,arg1,arg2)); continue;
903                     default: assert(0); continue;
904                 }
905             case _OP_APPENDARRAY:
906                 {
907                     SQObject val;
908                     val._unVal.raw = 0;
909                 switch(arg2) {
910                 case AAT_STACK:
911                     val = STK(arg1); break;
912                 case AAT_LITERAL:
913                     val = ci->_literals[arg1]; break;
914                 case AAT_INT:
915                     val._type = OT_INTEGER;
916 #ifndef _SQ64
917                     val._unVal.nInteger = (SQInteger)arg1;
918 #else
919                     val._unVal.nInteger = (SQInteger)((SQInt32)arg1);
920 #endif
921                     break;
922                 case AAT_FLOAT:
923                     val._type = OT_FLOAT;
924                     val._unVal.fFloat = *((const SQFloat *)&arg1);
925                     break;
926                 case AAT_BOOL:
927                     val._type = OT_BOOL;
928                     val._unVal.nInteger = arg1;
929                     break;
930                 default: val._type = OT_INTEGER; assert(0); break;
931 
932                 }
933                 _array(STK(arg0))->Append(val); continue;
934                 }
935             case _OP_COMPARITH: {
936                 SQInteger selfidx = (((SQUnsignedInteger)arg1&0xFFFF0000)>>16);
937                 _GUARD(DerefInc(arg3, TARGET, STK(selfidx), STK(arg2), STK(arg1&0x0000FFFF), false, selfidx));
938                                 }
939                 continue;
940             case _OP_INC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, false, arg1));} continue;
941             case _OP_INCL: {
942                 SQObjectPtr &a = STK(arg1);
943                 if(sq_type(a) == OT_INTEGER) {
944                     a._unVal.nInteger = _integer(a) + sarg3;
945                 }
946                 else {
947                     SQObjectPtr o(sarg3); //_GUARD(LOCAL_INC('+',TARGET, STK(arg1), o));
948                     _ARITH_(+,a,a,o);
949                 }
950                            } continue;
951             case _OP_PINC: {SQObjectPtr o(sarg3); _GUARD(DerefInc('+',TARGET, STK(arg1), STK(arg2), o, true, arg1));} continue;
952             case _OP_PINCL: {
953                 SQObjectPtr &a = STK(arg1);
954                 if(sq_type(a) == OT_INTEGER) {
955                     TARGET = a;
956                     a._unVal.nInteger = _integer(a) + sarg3;
957                 }
958                 else {
959                     SQObjectPtr o(sarg3); _GUARD(PLOCAL_INC('+',TARGET, STK(arg1), o));
960                 }
961 
962                         } continue;
963             case _OP_CMP:   _GUARD(CMP_OP((CmpOP)arg3,STK(arg2),STK(arg1),TARGET))  continue;
964             case _OP_EXISTS: TARGET = Get(STK(arg1), STK(arg2), temp_reg, GET_FLAG_DO_NOT_RAISE_ERROR | GET_FLAG_RAW, DONT_FALL_BACK) ? true : false; continue;
965             case _OP_INSTANCEOF:
966                 if(sq_type(STK(arg1)) != OT_CLASS)
967                 {Raise_Error(_SC("cannot apply instanceof between a %s and a %s"),GetTypeName(STK(arg1)),GetTypeName(STK(arg2))); SQ_THROW();}
968                 TARGET = (sq_type(STK(arg2)) == OT_INSTANCE) ? (_instance(STK(arg2))->InstanceOf(_class(STK(arg1)))?true:false) : false;
969                 continue;
970             case _OP_AND:
971                 if(IsFalse(STK(arg2))) {
972                     TARGET = STK(arg2);
973                     ci->_ip += (sarg1);
974                 }
975                 continue;
976             case _OP_OR:
977                 if(!IsFalse(STK(arg2))) {
978                     TARGET = STK(arg2);
979                     ci->_ip += (sarg1);
980                 }
981                 continue;
982             case _OP_NEG: _GUARD(NEG_OP(TARGET,STK(arg1))); continue;
983             case _OP_NOT: TARGET = IsFalse(STK(arg1)); continue;
984             case _OP_BWNOT:
985                 if(sq_type(STK(arg1)) == OT_INTEGER) {
986                     SQInteger t = _integer(STK(arg1));
987                     TARGET = SQInteger(~t);
988                     continue;
989                 }
990                 Raise_Error(_SC("attempt to perform a bitwise op on a %s"), GetTypeName(STK(arg1)));
991                 SQ_THROW();
992             case _OP_CLOSURE: {
993                 SQClosure *c = ci->_closure._unVal.pClosure;
994                 SQFunctionProto *fp = c->_function;
995                 if(!CLOSURE_OP(TARGET,fp->_functions[arg1]._unVal.pFunctionProto)) { SQ_THROW(); }
996                 continue;
997             }
998             case _OP_YIELD:{
999                 if(ci->_generator) {
1000                     if(sarg1 != MAX_FUNC_STACKSIZE) temp_reg = STK(arg1);
1001                     _GUARD(ci->_generator->Yield(this,arg2));
1002                     traps -= ci->_etraps;
1003                     if(sarg1 != MAX_FUNC_STACKSIZE) _Swap(STK(arg1),temp_reg);//STK(arg1) = temp_reg;
1004                 }
1005                 else { Raise_Error(_SC("trying to yield a '%s',only genenerator can be yielded"), GetTypeName(ci->_generator)); SQ_THROW();}
1006                 if(Return(arg0, arg1, temp_reg)){
1007                     assert(traps == 0);
1008                     outres = temp_reg;
1009                     return true;
1010                 }
1011 
1012                 }
1013                 continue;
1014             case _OP_RESUME:
1015                 if(sq_type(STK(arg1)) != OT_GENERATOR){ Raise_Error(_SC("trying to resume a '%s',only genenerator can be resumed"), GetTypeName(STK(arg1))); SQ_THROW();}
1016                 _GUARD(_generator(STK(arg1))->Resume(this, TARGET));
1017                 traps += ci->_etraps;
1018                 continue;
1019             case _OP_FOREACH:{ int tojump;
1020                 _GUARD(FOREACH_OP(STK(arg0),STK(arg2),STK(arg2+1),STK(arg2+2),arg2,sarg1,tojump));
1021                 ci->_ip += tojump; }
1022                 continue;
1023             case _OP_POSTFOREACH:
1024                 assert(sq_type(STK(arg0)) == OT_GENERATOR);
1025                 if(_generator(STK(arg0))->_state == SQGenerator::eDead)
1026                     ci->_ip += (sarg1 - 1);
1027                 continue;
1028             case _OP_CLONE: _GUARD(Clone(STK(arg1), TARGET)); continue;
1029             case _OP_TYPEOF: _GUARD(TypeOf(STK(arg1), TARGET)) continue;
1030             case _OP_PUSHTRAP:{
1031                 SQInstruction *_iv = _closure(ci->_closure)->_function->_instructions;
1032                 _etraps.push_back(SQExceptionTrap(_top,_stackbase, &_iv[(ci->_ip-_iv)+arg1], arg0)); traps++;
1033                 ci->_etraps++;
1034                               }
1035                 continue;
1036             case _OP_POPTRAP: {
1037                 for(SQInteger i = 0; i < arg0; i++) {
1038                     _etraps.pop_back(); traps--;
1039                     ci->_etraps--;
1040                 }
1041                               }
1042                 continue;
1043             case _OP_THROW: Raise_Error(TARGET); SQ_THROW(); continue;
1044             case _OP_NEWSLOTA:
1045                 _GUARD(NewSlotA(STK(arg1),STK(arg2),STK(arg3),(arg0&NEW_SLOT_ATTRIBUTES_FLAG) ? STK(arg2-1) : SQObjectPtr(),(arg0&NEW_SLOT_STATIC_FLAG)?true:false,false));
1046                 continue;
1047             case _OP_GETBASE:{
1048                 SQClosure *clo = _closure(ci->_closure);
1049                 if(clo->_base) {
1050                     TARGET = clo->_base;
1051                 }
1052                 else {
1053                     TARGET.Null();
1054                 }
1055                 continue;
1056             }
1057             case _OP_CLOSE:
1058                 if(_openouters) CloseOuters(&(STK(arg1)));
1059                 continue;
1060             }
1061 
1062         }
1063     }
1064 exception_trap:
1065     {
1066         SQObjectPtr currerror = _lasterror;
1067 //      dumpstack(_stackbase);
1068 //      SQInteger n = 0;
1069         SQInteger last_top = _top;
1070 
1071         if(_ss(this)->_notifyallexceptions || (!traps && raiseerror)) CallErrorHandler(currerror);
1072 
1073         while( ci ) {
1074             if(ci->_etraps > 0) {
1075                 SQExceptionTrap &et = _etraps.top();
1076                 ci->_ip = et._ip;
1077                 _top = et._stacksize;
1078                 _stackbase = et._stackbase;
1079                 _stack._vals[_stackbase + et._extarget] = currerror;
1080                 _etraps.pop_back(); traps--; ci->_etraps--;
1081                 while(last_top >= _top) _stack._vals[last_top--].Null();
1082                 goto exception_restore;
1083             }
1084             else if (_debughook) {
1085                     //notify debugger of a "return"
1086                     //even if it really an exception unwinding the stack
1087                     for(SQInteger i = 0; i < ci->_ncalls; i++) {
1088                         CallDebugHook(_SC('r'));
1089                     }
1090             }
1091             if(ci->_generator) ci->_generator->Kill();
1092             bool mustbreak = ci && ci->_root;
1093             LeaveFrame();
1094             if(mustbreak) break;
1095         }
1096 
1097         _lasterror = currerror;
1098         return false;
1099     }
1100     assert(0);
1101 }
1102 
CreateClassInstance(SQClass * theclass,SQObjectPtr & inst,SQObjectPtr & constructor)1103 bool SQVM::CreateClassInstance(SQClass *theclass, SQObjectPtr &inst, SQObjectPtr &constructor)
1104 {
1105     inst = theclass->CreateInstance();
1106     if(!theclass->GetConstructor(constructor)) {
1107         constructor.Null();
1108     }
1109     return true;
1110 }
1111 
CallErrorHandler(SQObjectPtr & error)1112 void SQVM::CallErrorHandler(SQObjectPtr &error)
1113 {
1114     if(sq_type(_errorhandler) != OT_NULL) {
1115         SQObjectPtr out;
1116         Push(_roottable); Push(error);
1117         Call(_errorhandler, 2, _top-2, out,SQFalse);
1118         Pop(2);
1119     }
1120 }
1121 
1122 
CallDebugHook(SQInteger type,SQInteger forcedline)1123 void SQVM::CallDebugHook(SQInteger type,SQInteger forcedline)
1124 {
1125     _debughook = false;
1126     SQFunctionProto *func=_closure(ci->_closure)->_function;
1127     if(_debughook_native) {
1128         const SQChar *src = sq_type(func->_sourcename) == OT_STRING?_stringval(func->_sourcename):NULL;
1129         const SQChar *fname = sq_type(func->_name) == OT_STRING?_stringval(func->_name):NULL;
1130         SQInteger line = forcedline?forcedline:func->GetLine(ci->_ip);
1131         _debughook_native(this,type,src,line,fname);
1132     }
1133     else {
1134         SQObjectPtr temp_reg;
1135         SQInteger nparams=5;
1136         Push(_roottable); Push(type); Push(func->_sourcename); Push(forcedline?forcedline:func->GetLine(ci->_ip)); Push(func->_name);
1137         Call(_debughook_closure,nparams,_top-nparams,temp_reg,SQFalse);
1138         Pop(nparams);
1139     }
1140     _debughook = true;
1141 }
1142 
CallNative(SQNativeClosure * nclosure,SQInteger nargs,SQInteger newbase,SQObjectPtr & retval,SQInt32 target,bool & suspend,bool & tailcall)1143 bool SQVM::CallNative(SQNativeClosure *nclosure, SQInteger nargs, SQInteger newbase, SQObjectPtr &retval, SQInt32 target,bool &suspend, bool &tailcall)
1144 {
1145     SQInteger nparamscheck = nclosure->_nparamscheck;
1146     SQInteger newtop = newbase + nargs + nclosure->_noutervalues;
1147 
1148     if (_nnativecalls + 1 > MAX_NATIVE_CALLS) {
1149         Raise_Error(_SC("Native stack overflow"));
1150         return false;
1151     }
1152 
1153     if(nparamscheck && (((nparamscheck > 0) && (nparamscheck != nargs)) ||
1154         ((nparamscheck < 0) && (nargs < (-nparamscheck)))))
1155     {
1156         Raise_Error(_SC("wrong number of parameters"));
1157         return false;
1158     }
1159 
1160     SQInteger tcs;
1161     SQIntVec &tc = nclosure->_typecheck;
1162     if((tcs = tc.size())) {
1163         for(SQInteger i = 0; i < nargs && i < tcs; i++) {
1164             if((tc._vals[i] != -1) && !(sq_type(_stack._vals[newbase+i]) & tc._vals[i])) {
1165                 Raise_ParamTypeError(i,tc._vals[i], sq_type(_stack._vals[newbase+i]));
1166                 return false;
1167             }
1168         }
1169     }
1170 
1171     if(!EnterFrame(newbase, newtop, false)) return false;
1172     ci->_closure  = nclosure;
1173 	ci->_target = target;
1174 
1175     SQInteger outers = nclosure->_noutervalues;
1176     for (SQInteger i = 0; i < outers; i++) {
1177         _stack._vals[newbase+nargs+i] = nclosure->_outervalues[i];
1178     }
1179     if(nclosure->_env) {
1180         _stack._vals[newbase] = nclosure->_env->_obj;
1181     }
1182 
1183     _nnativecalls++;
1184     SQInteger ret = (nclosure->_function)(this);
1185     _nnativecalls--;
1186 
1187     suspend = false;
1188 	tailcall = false;
1189 	if (ret == SQ_TAILCALL_FLAG) {
1190 		tailcall = true;
1191 		return true;
1192 	}
1193     else if (ret == SQ_SUSPEND_FLAG) {
1194         suspend = true;
1195     }
1196     else if (ret < 0) {
1197         LeaveFrame();
1198         Raise_Error(_lasterror);
1199         return false;
1200     }
1201     if(ret) {
1202         retval = _stack._vals[_top-1];
1203     }
1204     else {
1205         retval.Null();
1206     }
1207     //retval = ret ? _stack._vals[_top-1] : _null_;
1208     LeaveFrame();
1209     return true;
1210 }
1211 
TailCall(SQClosure * closure,SQInteger parambase,SQInteger nparams)1212 bool SQVM::TailCall(SQClosure *closure, SQInteger parambase,SQInteger nparams)
1213 {
1214 	SQInteger last_top = _top;
1215 	SQObjectPtr clo = closure;
1216 	if (ci->_root)
1217 	{
1218 		Raise_Error("root calls cannot invoke tailcalls");
1219 		return false;
1220 	}
1221 	for (SQInteger i = 0; i < nparams; i++) STK(i) = STK(parambase + i);
1222 	bool ret = StartCall(closure, ci->_target, nparams, _stackbase, true);
1223 	if (last_top >= _top) {
1224 		_top = last_top;
1225 	}
1226 	return ret;
1227 }
1228 
1229 #define FALLBACK_OK         0
1230 #define FALLBACK_NO_MATCH   1
1231 #define FALLBACK_ERROR      2
1232 
Get(const SQObjectPtr & self,const SQObjectPtr & key,SQObjectPtr & dest,SQUnsignedInteger getflags,SQInteger selfidx)1233 bool SQVM::Get(const SQObjectPtr &self, const SQObjectPtr &key, SQObjectPtr &dest, SQUnsignedInteger getflags, SQInteger selfidx)
1234 {
1235     switch(sq_type(self)){
1236     case OT_TABLE:
1237         if(_table(self)->Get(key,dest))return true;
1238         break;
1239     case OT_ARRAY:
1240         if (sq_isnumeric(key)) { if (_array(self)->Get(tointeger(key), dest)) { return true; } if ((getflags & GET_FLAG_DO_NOT_RAISE_ERROR) == 0) Raise_IdxError(key); return false; }
1241         break;
1242     case OT_INSTANCE:
1243         if(_instance(self)->Get(key,dest)) return true;
1244         break;
1245     case OT_CLASS:
1246         if(_class(self)->Get(key,dest)) return true;
1247         break;
1248     case OT_STRING:
1249         if(sq_isnumeric(key)){
1250             SQInteger n = tointeger(key);
1251             SQInteger len = _string(self)->_len;
1252             if (n < 0) { n += len; }
1253             if (n >= 0 && n < len) {
1254                 dest = SQInteger(_stringval(self)[n]);
1255                 return true;
1256             }
1257             if ((getflags & GET_FLAG_DO_NOT_RAISE_ERROR) == 0) Raise_IdxError(key);
1258             return false;
1259         }
1260         break;
1261     default:break; //shut up compiler
1262     }
1263     if ((getflags & GET_FLAG_RAW) == 0) {
1264         switch(FallBackGet(self,key,dest)) {
1265             case FALLBACK_OK: return true; //okie
1266             case FALLBACK_NO_MATCH: break; //keep falling back
1267             case FALLBACK_ERROR: return false; // the metamethod failed
1268         }
1269         if(InvokeDefaultDelegate(self,key,dest)) {
1270             return true;
1271         }
1272     }
1273 //#ifdef ROOT_FALLBACK
1274     if(selfidx == 0) {
1275         SQWeakRef *w = _closure(ci->_closure)->_root;
1276         if(sq_type(w->_obj) != OT_NULL)
1277         {
1278             if(Get(*((const SQObjectPtr *)&w->_obj),key,dest,0,DONT_FALL_BACK)) return true;
1279         }
1280 
1281     }
1282 //#endif
1283     if ((getflags & GET_FLAG_DO_NOT_RAISE_ERROR) == 0) Raise_IdxError(key);
1284     return false;
1285 }
1286 
InvokeDefaultDelegate(const SQObjectPtr & self,const SQObjectPtr & key,SQObjectPtr & dest)1287 bool SQVM::InvokeDefaultDelegate(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest)
1288 {
1289     SQTable *ddel = NULL;
1290     switch(sq_type(self)) {
1291         case OT_CLASS: ddel = _class_ddel; break;
1292         case OT_TABLE: ddel = _table_ddel; break;
1293         case OT_ARRAY: ddel = _array_ddel; break;
1294         case OT_STRING: ddel = _string_ddel; break;
1295         case OT_INSTANCE: ddel = _instance_ddel; break;
1296         case OT_INTEGER:case OT_FLOAT:case OT_BOOL: ddel = _number_ddel; break;
1297         case OT_GENERATOR: ddel = _generator_ddel; break;
1298         case OT_CLOSURE: case OT_NATIVECLOSURE: ddel = _closure_ddel; break;
1299         case OT_THREAD: ddel = _thread_ddel; break;
1300         case OT_WEAKREF: ddel = _weakref_ddel; break;
1301         default: return false;
1302     }
1303     return  ddel->Get(key,dest);
1304 }
1305 
1306 
FallBackGet(const SQObjectPtr & self,const SQObjectPtr & key,SQObjectPtr & dest)1307 SQInteger SQVM::FallBackGet(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &dest)
1308 {
1309     switch(sq_type(self)){
1310     case OT_TABLE:
1311     case OT_USERDATA:
1312         //delegation
1313         if(_delegable(self)->_delegate) {
1314             if(Get(SQObjectPtr(_delegable(self)->_delegate),key,dest,0,DONT_FALL_BACK)) return FALLBACK_OK;
1315         }
1316         else {
1317             return FALLBACK_NO_MATCH;
1318         }
1319         //go through
1320     case OT_INSTANCE: {
1321         SQObjectPtr closure;
1322         if(_delegable(self)->GetMetaMethod(this, MT_GET, closure)) {
1323             Push(self);Push(key);
1324             _nmetamethodscall++;
1325             AutoDec ad(&_nmetamethodscall);
1326             if(Call(closure, 2, _top - 2, dest, SQFalse)) {
1327                 Pop(2);
1328                 return FALLBACK_OK;
1329             }
1330             else {
1331                 Pop(2);
1332                 if(sq_type(_lasterror) != OT_NULL) { //NULL means "clean failure" (not found)
1333                     return FALLBACK_ERROR;
1334                 }
1335             }
1336         }
1337                       }
1338         break;
1339     default: break;//shutup GCC 4.x
1340     }
1341     // no metamethod or no fallback type
1342     return FALLBACK_NO_MATCH;
1343 }
1344 
Set(const SQObjectPtr & self,const SQObjectPtr & key,const SQObjectPtr & val,SQInteger selfidx)1345 bool SQVM::Set(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,SQInteger selfidx)
1346 {
1347     switch(sq_type(self)){
1348     case OT_TABLE:
1349         if(_table(self)->Set(key,val)) return true;
1350         break;
1351     case OT_INSTANCE:
1352         if(_instance(self)->Set(key,val)) return true;
1353         break;
1354     case OT_ARRAY:
1355         if(!sq_isnumeric(key)) { Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key)); return false; }
1356         if(!_array(self)->Set(tointeger(key),val)) {
1357             Raise_IdxError(key);
1358             return false;
1359         }
1360         return true;
1361     case OT_USERDATA: break; // must fall back
1362     default:
1363         Raise_Error(_SC("trying to set '%s'"),GetTypeName(self));
1364         return false;
1365     }
1366 
1367     switch(FallBackSet(self,key,val)) {
1368         case FALLBACK_OK: return true; //okie
1369         case FALLBACK_NO_MATCH: break; //keep falling back
1370         case FALLBACK_ERROR: return false; // the metamethod failed
1371     }
1372     if(selfidx == 0) {
1373         if(_table(_roottable)->Set(key,val))
1374             return true;
1375     }
1376     Raise_IdxError(key);
1377     return false;
1378 }
1379 
FallBackSet(const SQObjectPtr & self,const SQObjectPtr & key,const SQObjectPtr & val)1380 SQInteger SQVM::FallBackSet(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val)
1381 {
1382     switch(sq_type(self)) {
1383     case OT_TABLE:
1384         if(_table(self)->_delegate) {
1385             if(Set(_table(self)->_delegate,key,val,DONT_FALL_BACK)) return FALLBACK_OK;
1386         }
1387         //keps on going
1388     case OT_INSTANCE:
1389     case OT_USERDATA:{
1390         SQObjectPtr closure;
1391         SQObjectPtr t;
1392         if(_delegable(self)->GetMetaMethod(this, MT_SET, closure)) {
1393             Push(self);Push(key);Push(val);
1394             _nmetamethodscall++;
1395             AutoDec ad(&_nmetamethodscall);
1396             if(Call(closure, 3, _top - 3, t, SQFalse)) {
1397                 Pop(3);
1398                 return FALLBACK_OK;
1399             }
1400             else {
1401                 Pop(3);
1402                 if(sq_type(_lasterror) != OT_NULL) { //NULL means "clean failure" (not found)
1403                     return FALLBACK_ERROR;
1404                 }
1405             }
1406         }
1407                      }
1408         break;
1409         default: break;//shutup GCC 4.x
1410     }
1411     // no metamethod or no fallback type
1412     return FALLBACK_NO_MATCH;
1413 }
1414 
Clone(const SQObjectPtr & self,SQObjectPtr & target)1415 bool SQVM::Clone(const SQObjectPtr &self,SQObjectPtr &target)
1416 {
1417     SQObjectPtr temp_reg;
1418     SQObjectPtr newobj;
1419     switch(sq_type(self)){
1420     case OT_TABLE:
1421         newobj = _table(self)->Clone();
1422         goto cloned_mt;
1423     case OT_INSTANCE: {
1424         newobj = _instance(self)->Clone(_ss(this));
1425 cloned_mt:
1426         SQObjectPtr closure;
1427         if(_delegable(newobj)->_delegate && _delegable(newobj)->GetMetaMethod(this,MT_CLONED,closure)) {
1428             Push(newobj);
1429             Push(self);
1430             if(!CallMetaMethod(closure,MT_CLONED,2,temp_reg))
1431                 return false;
1432         }
1433         }
1434         target = newobj;
1435         return true;
1436     case OT_ARRAY:
1437         target = _array(self)->Clone();
1438         return true;
1439     default:
1440         Raise_Error(_SC("cloning a %s"), GetTypeName(self));
1441         return false;
1442     }
1443 }
1444 
NewSlotA(const SQObjectPtr & self,const SQObjectPtr & key,const SQObjectPtr & val,const SQObjectPtr & attrs,bool bstatic,bool raw)1445 bool SQVM::NewSlotA(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,const SQObjectPtr &attrs,bool bstatic,bool raw)
1446 {
1447     if(sq_type(self) != OT_CLASS) {
1448         Raise_Error(_SC("object must be a class"));
1449         return false;
1450     }
1451     SQClass *c = _class(self);
1452     if(!raw) {
1453         SQObjectPtr &mm = c->_metamethods[MT_NEWMEMBER];
1454         if(sq_type(mm) != OT_NULL ) {
1455             Push(self); Push(key); Push(val);
1456             Push(attrs);
1457             Push(bstatic);
1458             return CallMetaMethod(mm,MT_NEWMEMBER,5,temp_reg);
1459         }
1460     }
1461     if(!NewSlot(self, key, val,bstatic))
1462         return false;
1463     if(sq_type(attrs) != OT_NULL) {
1464         c->SetAttributes(key,attrs);
1465     }
1466     return true;
1467 }
1468 
NewSlot(const SQObjectPtr & self,const SQObjectPtr & key,const SQObjectPtr & val,bool bstatic)1469 bool SQVM::NewSlot(const SQObjectPtr &self,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
1470 {
1471     if(sq_type(key) == OT_NULL) { Raise_Error(_SC("null cannot be used as index")); return false; }
1472     switch(sq_type(self)) {
1473     case OT_TABLE: {
1474         bool rawcall = true;
1475         if(_table(self)->_delegate) {
1476             SQObjectPtr res;
1477             if(!_table(self)->Get(key,res)) {
1478                 SQObjectPtr closure;
1479                 if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_NEWSLOT,closure)) {
1480                     Push(self);Push(key);Push(val);
1481                     if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) {
1482                         return false;
1483                     }
1484                     rawcall = false;
1485                 }
1486                 else {
1487                     rawcall = true;
1488                 }
1489             }
1490         }
1491         if(rawcall) _table(self)->NewSlot(key,val); //cannot fail
1492 
1493         break;}
1494     case OT_INSTANCE: {
1495         SQObjectPtr res;
1496         SQObjectPtr closure;
1497         if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_NEWSLOT,closure)) {
1498             Push(self);Push(key);Push(val);
1499             if(!CallMetaMethod(closure,MT_NEWSLOT,3,res)) {
1500                 return false;
1501             }
1502             break;
1503         }
1504         Raise_Error(_SC("class instances do not support the new slot operator"));
1505         return false;
1506         break;}
1507     case OT_CLASS:
1508         if(!_class(self)->NewSlot(_ss(this),key,val,bstatic)) {
1509             if(_class(self)->_locked) {
1510                 Raise_Error(_SC("trying to modify a class that has already been instantiated"));
1511                 return false;
1512             }
1513             else {
1514                 SQObjectPtr oval = PrintObjVal(key);
1515                 Raise_Error(_SC("the property '%s' already exists"),_stringval(oval));
1516                 return false;
1517             }
1518         }
1519         break;
1520     default:
1521         Raise_Error(_SC("indexing %s with %s"),GetTypeName(self),GetTypeName(key));
1522         return false;
1523         break;
1524     }
1525     return true;
1526 }
1527 
1528 
1529 
DeleteSlot(const SQObjectPtr & self,const SQObjectPtr & key,SQObjectPtr & res)1530 bool SQVM::DeleteSlot(const SQObjectPtr &self,const SQObjectPtr &key,SQObjectPtr &res)
1531 {
1532     switch(sq_type(self)) {
1533     case OT_TABLE:
1534     case OT_INSTANCE:
1535     case OT_USERDATA: {
1536         SQObjectPtr t;
1537         //bool handled = false;
1538         SQObjectPtr closure;
1539         if(_delegable(self)->_delegate && _delegable(self)->GetMetaMethod(this,MT_DELSLOT,closure)) {
1540             Push(self);Push(key);
1541             return CallMetaMethod(closure,MT_DELSLOT,2,res);
1542         }
1543         else {
1544             if(sq_type(self) == OT_TABLE) {
1545                 if(_table(self)->Get(key,t)) {
1546                     _table(self)->Remove(key);
1547                 }
1548                 else {
1549                     Raise_IdxError((const SQObject &)key);
1550                     return false;
1551                 }
1552             }
1553             else {
1554                 Raise_Error(_SC("cannot delete a slot from %s"),GetTypeName(self));
1555                 return false;
1556             }
1557         }
1558         res = t;
1559                 }
1560         break;
1561     default:
1562         Raise_Error(_SC("attempt to delete a slot from a %s"),GetTypeName(self));
1563         return false;
1564     }
1565     return true;
1566 }
1567 
Call(SQObjectPtr & closure,SQInteger nparams,SQInteger stackbase,SQObjectPtr & outres,SQBool raiseerror)1568 bool SQVM::Call(SQObjectPtr &closure,SQInteger nparams,SQInteger stackbase,SQObjectPtr &outres,SQBool raiseerror)
1569 {
1570 #ifdef _DEBUG
1571 SQInteger prevstackbase = _stackbase;
1572 #endif
1573     switch(sq_type(closure)) {
1574     case OT_CLOSURE:
1575         return Execute(closure, nparams, stackbase, outres, raiseerror);
1576         break;
1577     case OT_NATIVECLOSURE:{
1578         bool dummy;
1579         return CallNative(_nativeclosure(closure), nparams, stackbase, outres, -1, dummy, dummy);
1580 
1581                           }
1582         break;
1583     case OT_CLASS: {
1584         SQObjectPtr constr;
1585         SQObjectPtr temp;
1586         CreateClassInstance(_class(closure),outres,constr);
1587         SQObjectType ctype = sq_type(constr);
1588         if (ctype == OT_NATIVECLOSURE || ctype == OT_CLOSURE) {
1589             _stack[stackbase] = outres;
1590             return Call(constr,nparams,stackbase,temp,raiseerror);
1591         }
1592         return true;
1593                    }
1594         break;
1595     default:
1596         return false;
1597     }
1598 #ifdef _DEBUG
1599     if(!_suspended) {
1600         assert(_stackbase == prevstackbase);
1601     }
1602 #endif
1603     return true;
1604 }
1605 
CallMetaMethod(SQObjectPtr & closure,SQMetaMethod SQ_UNUSED_ARG (mm),SQInteger nparams,SQObjectPtr & outres)1606 bool SQVM::CallMetaMethod(SQObjectPtr &closure,SQMetaMethod SQ_UNUSED_ARG(mm),SQInteger nparams,SQObjectPtr &outres)
1607 {
1608     //SQObjectPtr closure;
1609 
1610     _nmetamethodscall++;
1611     if(Call(closure, nparams, _top - nparams, outres, SQFalse)) {
1612         _nmetamethodscall--;
1613         Pop(nparams);
1614         return true;
1615     }
1616     _nmetamethodscall--;
1617     //}
1618     Pop(nparams);
1619     return false;
1620 }
1621 
FindOuter(SQObjectPtr & target,SQObjectPtr * stackindex)1622 void SQVM::FindOuter(SQObjectPtr &target, SQObjectPtr *stackindex)
1623 {
1624     SQOuter **pp = &_openouters;
1625     SQOuter *p;
1626     SQOuter *otr;
1627 
1628     while ((p = *pp) != NULL && p->_valptr >= stackindex) {
1629         if (p->_valptr == stackindex) {
1630             target = SQObjectPtr(p);
1631             return;
1632         }
1633         pp = &p->_next;
1634     }
1635     otr = SQOuter::Create(_ss(this), stackindex);
1636     otr->_next = *pp;
1637     otr->_idx  = (stackindex - _stack._vals);
1638     __ObjAddRef(otr);
1639     *pp = otr;
1640     target = SQObjectPtr(otr);
1641 }
1642 
EnterFrame(SQInteger newbase,SQInteger newtop,bool tailcall)1643 bool SQVM::EnterFrame(SQInteger newbase, SQInteger newtop, bool tailcall)
1644 {
1645     if( !tailcall ) {
1646         if( _callsstacksize == _alloccallsstacksize ) {
1647             GrowCallStack();
1648         }
1649         ci = &_callsstack[_callsstacksize++];
1650         ci->_prevstkbase = (SQInt32)(newbase - _stackbase);
1651         ci->_prevtop = (SQInt32)(_top - _stackbase);
1652         ci->_etraps = 0;
1653         ci->_ncalls = 1;
1654         ci->_generator = NULL;
1655         ci->_root = SQFalse;
1656     }
1657     else {
1658         ci->_ncalls++;
1659     }
1660 
1661     _stackbase = newbase;
1662     _top = newtop;
1663     if(newtop + MIN_STACK_OVERHEAD > (SQInteger)_stack.size()) {
1664         if(_nmetamethodscall) {
1665             Raise_Error(_SC("stack overflow, cannot resize stack while in a metamethod"));
1666             return false;
1667         }
1668         _stack.resize(newtop + (MIN_STACK_OVERHEAD << 2));
1669         RelocateOuters();
1670     }
1671     return true;
1672 }
1673 
LeaveFrame()1674 void SQVM::LeaveFrame() {
1675     SQInteger last_top = _top;
1676     SQInteger last_stackbase = _stackbase;
1677     SQInteger css = --_callsstacksize;
1678 
1679     /* First clean out the call stack frame */
1680     ci->_closure.Null();
1681     _stackbase -= ci->_prevstkbase;
1682     _top = _stackbase + ci->_prevtop;
1683     ci = (css) ? &_callsstack[css-1] : NULL;
1684 
1685     if(_openouters) CloseOuters(&(_stack._vals[last_stackbase]));
1686     while (last_top >= _top) {
1687         _stack._vals[last_top--].Null();
1688     }
1689 }
1690 
RelocateOuters()1691 void SQVM::RelocateOuters()
1692 {
1693     SQOuter *p = _openouters;
1694     while (p) {
1695         p->_valptr = _stack._vals + p->_idx;
1696         p = p->_next;
1697     }
1698 }
1699 
CloseOuters(SQObjectPtr * stackindex)1700 void SQVM::CloseOuters(SQObjectPtr *stackindex) {
1701   SQOuter *p;
1702   while ((p = _openouters) != NULL && p->_valptr >= stackindex) {
1703     p->_value = *(p->_valptr);
1704     p->_valptr = &p->_value;
1705     _openouters = p->_next;
1706     __ObjRelease(p);
1707   }
1708 }
1709 
Remove(SQInteger n)1710 void SQVM::Remove(SQInteger n) {
1711     n = (n >= 0)?n + _stackbase - 1:_top + n;
1712     for(SQInteger i = n; i < _top; i++){
1713         _stack[i] = _stack[i+1];
1714     }
1715     _stack[_top].Null();
1716     _top--;
1717 }
1718 
Pop()1719 void SQVM::Pop() {
1720     _stack[--_top].Null();
1721 }
1722 
Pop(SQInteger n)1723 void SQVM::Pop(SQInteger n) {
1724     for(SQInteger i = 0; i < n; i++){
1725         _stack[--_top].Null();
1726     }
1727 }
1728 
PushNull()1729 void SQVM::PushNull() { _stack[_top++].Null(); }
Push(const SQObjectPtr & o)1730 void SQVM::Push(const SQObjectPtr &o) { _stack[_top++] = o; }
Top()1731 SQObjectPtr &SQVM::Top() { return _stack[_top-1]; }
PopGet()1732 SQObjectPtr &SQVM::PopGet() { return _stack[--_top]; }
GetUp(SQInteger n)1733 SQObjectPtr &SQVM::GetUp(SQInteger n) { return _stack[_top+n]; }
GetAt(SQInteger n)1734 SQObjectPtr &SQVM::GetAt(SQInteger n) { return _stack[n]; }
1735 
1736 #ifdef _DEBUG_DUMP
dumpstack(SQInteger stackbase,bool dumpall)1737 void SQVM::dumpstack(SQInteger stackbase,bool dumpall)
1738 {
1739     SQInteger size=dumpall?_stack.size():_top;
1740     SQInteger n=0;
1741     scprintf(_SC("\n>>>>stack dump<<<<\n"));
1742     CallInfo &ci=_callsstack[_callsstacksize-1];
1743     scprintf(_SC("IP: %p\n"),ci._ip);
1744     scprintf(_SC("prev stack base: %d\n"),ci._prevstkbase);
1745     scprintf(_SC("prev top: %d\n"),ci._prevtop);
1746     for(SQInteger i=0;i<size;i++){
1747         SQObjectPtr &obj=_stack[i];
1748         if(stackbase==i)scprintf(_SC(">"));else scprintf(_SC(" "));
1749         scprintf(_SC("[" _PRINT_INT_FMT "]:"),n);
1750         switch(sq_type(obj)){
1751         case OT_FLOAT:          scprintf(_SC("FLOAT %.3f"),_float(obj));break;
1752         case OT_INTEGER:        scprintf(_SC("INTEGER " _PRINT_INT_FMT),_integer(obj));break;
1753         case OT_BOOL:           scprintf(_SC("BOOL %s"),_integer(obj)?"true":"false");break;
1754         case OT_STRING:         scprintf(_SC("STRING %s"),_stringval(obj));break;
1755         case OT_NULL:           scprintf(_SC("NULL"));  break;
1756         case OT_TABLE:          scprintf(_SC("TABLE %p[%p]"),_table(obj),_table(obj)->_delegate);break;
1757         case OT_ARRAY:          scprintf(_SC("ARRAY %p"),_array(obj));break;
1758         case OT_CLOSURE:        scprintf(_SC("CLOSURE [%p]"),_closure(obj));break;
1759         case OT_NATIVECLOSURE:  scprintf(_SC("NATIVECLOSURE"));break;
1760         case OT_USERDATA:       scprintf(_SC("USERDATA %p[%p]"),_userdataval(obj),_userdata(obj)->_delegate);break;
1761         case OT_GENERATOR:      scprintf(_SC("GENERATOR %p"),_generator(obj));break;
1762         case OT_THREAD:         scprintf(_SC("THREAD [%p]"),_thread(obj));break;
1763         case OT_USERPOINTER:    scprintf(_SC("USERPOINTER %p"),_userpointer(obj));break;
1764         case OT_CLASS:          scprintf(_SC("CLASS %p"),_class(obj));break;
1765         case OT_INSTANCE:       scprintf(_SC("INSTANCE %p"),_instance(obj));break;
1766         case OT_WEAKREF:        scprintf(_SC("WEAKERF %p"),_weakref(obj));break;
1767         default:
1768             assert(0);
1769             break;
1770         };
1771         scprintf(_SC("\n"));
1772         ++n;
1773     }
1774 }
1775 
1776 
1777 
1778 #endif
1779