squirrel.cpp

Go to the documentation of this file.
00001 /* $Id: squirrel.cpp 25560 2013-07-04 21:20:05Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include <stdarg.h>
00013 #include "../stdafx.h"
00014 #include "../debug.h"
00015 #include "squirrel_std.hpp"
00016 #include "../fileio_func.h"
00017 #include "../string_func.h"
00018 #include <sqstdaux.h>
00019 #include <../squirrel/sqpcheader.h>
00020 #include <../squirrel/sqvm.h>
00021 
00022 void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
00023 {
00024   SQChar buf[1024];
00025 
00026 #ifdef _SQ64
00027   scsnprintf(buf, lengthof(buf), _SC("Error %s:%ld/%ld: %s"), source, line, column, desc);
00028 #else
00029   scsnprintf(buf, lengthof(buf), _SC("Error %s:%d/%d: %s"), source, line, column, desc);
00030 #endif
00031 
00032   /* Check if we have a custom print function */
00033   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00034   engine->crashed = true;
00035   SQPrintFunc *func = engine->print_func;
00036   if (func == NULL) {
00037     DEBUG(misc, 0, "[Squirrel] Compile error: %s", SQ2OTTD(buf));
00038   } else {
00039     (*func)(true, buf);
00040   }
00041 }
00042 
00043 void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00044 {
00045   va_list arglist;
00046   SQChar buf[1024];
00047 
00048   va_start(arglist, s);
00049   scvsnprintf(buf, lengthof(buf), s, arglist);
00050   va_end(arglist);
00051 
00052   /* Check if we have a custom print function */
00053   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00054   if (func == NULL) {
00055     scfprintf(stderr, _SC("%s"), buf);
00056   } else {
00057     (*func)(true, buf);
00058   }
00059 }
00060 
00061 void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
00062 {
00063   /* Set the print function to something that prints to stderr */
00064   SQPRINTFUNCTION pf = sq_getprintfunc(vm);
00065   sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc);
00066 
00067   /* Check if we have a custom print function */
00068   SQChar buf[1024];
00069   scsnprintf(buf, lengthof(buf), _SC("Your script made an error: %s\n"), error);
00070   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00071   SQPrintFunc *func = engine->print_func;
00072   if (func == NULL) {
00073     scfprintf(stderr, _SC("%s"), buf);
00074   } else {
00075     (*func)(true, buf);
00076   }
00077 
00078   /* Print below the error the stack, so the users knows what is happening */
00079   sqstd_printcallstack(vm);
00080   /* Reset the old print function */
00081   sq_setprintfunc(vm, pf);
00082 }
00083 
00084 SQInteger Squirrel::_RunError(HSQUIRRELVM vm)
00085 {
00086   const SQChar *sErr = 0;
00087 
00088   if (sq_gettop(vm) >= 1) {
00089     if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sErr))) {
00090       Squirrel::RunError(vm, sErr);
00091       return 0;
00092     }
00093   }
00094 
00095   Squirrel::RunError(vm, _SC("unknown error"));
00096   return 0;
00097 }
00098 
00099 void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
00100 {
00101   va_list arglist;
00102   SQChar buf[1024];
00103 
00104   va_start(arglist, s);
00105   scvsnprintf(buf, lengthof(buf) - 2, s, arglist);
00106   va_end(arglist);
00107   scstrcat(buf, _SC("\n"));
00108 
00109   /* Check if we have a custom print function */
00110   SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
00111   if (func == NULL) {
00112     scprintf(_SC("%s"), buf);
00113   } else {
00114     (*func)(false, buf);
00115   }
00116 }
00117 
00118 void Squirrel::AddMethod(const char *method_name, SQFUNCTION proc, uint nparam, const char *params, void *userdata, int size)
00119 {
00120   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00121 
00122   if (size != 0) {
00123     void *ptr = sq_newuserdata(vm, size);
00124     memcpy(ptr, userdata, size);
00125   }
00126 
00127   sq_newclosure(this->vm, proc, size != 0 ? 1 : 0);
00128   if (nparam != 0) sq_setparamscheck(this->vm, nparam, OTTD2SQ(params));
00129   sq_setnativeclosurename(this->vm, -1, OTTD2SQ(method_name));
00130   sq_newslot(this->vm, -3, SQFalse);
00131 }
00132 
00133 void Squirrel::AddConst(const char *var_name, int value)
00134 {
00135   sq_pushstring(this->vm, OTTD2SQ(var_name), -1);
00136   sq_pushinteger(this->vm, value);
00137   sq_newslot(this->vm, -3, SQTrue);
00138 }
00139 
00140 void Squirrel::AddConst(const char *var_name, bool value)
00141 {
00142   sq_pushstring(this->vm, OTTD2SQ(var_name), -1);
00143   sq_pushbool(this->vm, value);
00144   sq_newslot(this->vm, -3, SQTrue);
00145 }
00146 
00147 void Squirrel::AddClassBegin(const char *class_name)
00148 {
00149   sq_pushroottable(this->vm);
00150   sq_pushstring(this->vm, OTTD2SQ(class_name), -1);
00151   sq_newclass(this->vm, SQFalse);
00152 }
00153 
00154 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
00155 {
00156   sq_pushroottable(this->vm);
00157   sq_pushstring(this->vm, OTTD2SQ(class_name), -1);
00158   sq_pushstring(this->vm, OTTD2SQ(parent_class), -1);
00159   if (SQ_FAILED(sq_get(this->vm, -3))) {
00160     DEBUG(misc, 0, "[squirrel] Failed to initialize class '%s' based on parent class '%s'", class_name, parent_class);
00161     DEBUG(misc, 0, "[squirrel] Make sure that '%s' exists before trying to define '%s'", parent_class, class_name);
00162     return;
00163   }
00164   sq_newclass(this->vm, SQTrue);
00165 }
00166 
00167 void Squirrel::AddClassEnd()
00168 {
00169   sq_newslot(vm, -3, SQFalse);
00170   sq_pop(vm, 1);
00171 }
00172 
00173 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
00174 {
00175   assert(!this->crashed);
00176   int top = sq_gettop(this->vm);
00177   /* Go to the instance-root */
00178   sq_pushobject(this->vm, instance);
00179   /* Find the function-name inside the script */
00180   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00181   if (SQ_FAILED(sq_get(this->vm, -2))) {
00182     sq_settop(this->vm, top);
00183     return false;
00184   }
00185   sq_settop(this->vm, top);
00186   return true;
00187 }
00188 
00189 bool Squirrel::Resume(int suspend)
00190 {
00191   assert(!this->crashed);
00192   /* Did we use more operations than we should have in the
00193    * previous tick? If so, subtract that from the current run. */
00194   if (this->overdrawn_ops > 0 && suspend > 0) {
00195     this->overdrawn_ops -= suspend;
00196     /* Do we need to wait even more? */
00197     if (this->overdrawn_ops >= 0) return true;
00198 
00199     /* We can now only run whatever is "left". */
00200     suspend = -this->overdrawn_ops;
00201   }
00202 
00203   this->crashed = !sq_resumecatch(this->vm, suspend);
00204   this->overdrawn_ops = -this->vm->_ops_till_suspend;
00205   return this->vm->_suspended != 0;
00206 }
00207 
00208 void Squirrel::ResumeError()
00209 {
00210   assert(!this->crashed);
00211   sq_resumeerror(this->vm);
00212 }
00213 
00214 void Squirrel::CollectGarbage()
00215 {
00216   sq_collectgarbage(this->vm);
00217 }
00218 
00219 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
00220 {
00221   assert(!this->crashed);
00222   /* Store the stack-location for the return value. We need to
00223    * restore this after saving or the stack will be corrupted
00224    * if we're in the middle of a DoCommand. */
00225   SQInteger last_target = this->vm->_suspended_target;
00226   /* Store the current top */
00227   int top = sq_gettop(this->vm);
00228   /* Go to the instance-root */
00229   sq_pushobject(this->vm, instance);
00230   /* Find the function-name inside the script */
00231   sq_pushstring(this->vm, OTTD2SQ(method_name), -1);
00232   if (SQ_FAILED(sq_get(this->vm, -2))) {
00233     DEBUG(misc, 0, "[squirrel] Could not find '%s' in the class", method_name);
00234     sq_settop(this->vm, top);
00235     return false;
00236   }
00237   /* Call the method */
00238   sq_pushobject(this->vm, instance);
00239   if (SQ_FAILED(sq_call(this->vm, 1, ret == NULL ? SQFalse : SQTrue, SQTrue, suspend))) return false;
00240   if (ret != NULL) sq_getstackobj(vm, -1, ret);
00241   /* Reset the top, but don't do so for the script main function, as we need
00242    *  a correct stack when resuming. */
00243   if (suspend == -1 || !this->IsSuspended()) sq_settop(this->vm, top);
00244   /* Restore the return-value location. */
00245   this->vm->_suspended_target = last_target;
00246 
00247   return true;
00248 }
00249 
00250 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
00251 {
00252   HSQOBJECT ret;
00253   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00254   if (ret._type != OT_STRING) return false;
00255   *res = strdup(ObjectToString(&ret));
00256   ValidateString(*res);
00257   return true;
00258 }
00259 
00260 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
00261 {
00262   HSQOBJECT ret;
00263   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00264   if (ret._type != OT_INTEGER) return false;
00265   *res = ObjectToInteger(&ret);
00266   return true;
00267 }
00268 
00269 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
00270 {
00271   HSQOBJECT ret;
00272   if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
00273   if (ret._type != OT_BOOL) return false;
00274   *res = ObjectToBool(&ret);
00275   return true;
00276 }
00277 
00278 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name)
00279 {
00280   Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
00281 
00282   int oldtop = sq_gettop(vm);
00283 
00284   /* First, find the class */
00285   sq_pushroottable(vm);
00286 
00287   if (prepend_API_name) {
00288     char *class_name2 = (char *)alloca(strlen(class_name) + strlen(engine->GetAPIName()) + 1);
00289     sprintf(class_name2, "%s%s", engine->GetAPIName(), class_name);
00290 
00291     sq_pushstring(vm, OTTD2SQ(class_name2), -1);
00292   } else {
00293     sq_pushstring(vm, OTTD2SQ(class_name), -1);
00294   }
00295 
00296   if (SQ_FAILED(sq_get(vm, -2))) {
00297     DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s%s'", prepend_API_name ? engine->GetAPIName() : "", class_name);
00298     sq_settop(vm, oldtop);
00299     return false;
00300   }
00301 
00302   /* Create the instance */
00303   if (SQ_FAILED(sq_createinstance(vm, -1))) {
00304     DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s%s'", prepend_API_name ? engine->GetAPIName() : "", class_name);
00305     sq_settop(vm, oldtop);
00306     return false;
00307   }
00308 
00309   if (instance != NULL) {
00310     /* Find our instance */
00311     sq_getstackobj(vm, -1, instance);
00312     /* Add a reference to it, so it survives for ever */
00313     sq_addref(vm, instance);
00314   }
00315   sq_remove(vm, -2); // Class-name
00316   sq_remove(vm, -2); // Root-table
00317 
00318   /* Store it in the class */
00319   sq_setinstanceup(vm, -1, real_instance);
00320   if (release_hook != NULL) sq_setreleasehook(vm, -1, release_hook);
00321 
00322   if (instance != NULL) sq_settop(vm, oldtop);
00323 
00324   return true;
00325 }
00326 
00327 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
00328 {
00329   return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, NULL);
00330 }
00331 
00332 Squirrel::Squirrel(const char *APIName) :
00333   global_pointer(NULL),
00334   print_func(NULL),
00335   crashed(false),
00336   overdrawn_ops(0),
00337   APIName(APIName)
00338 {
00339   this->vm = sq_open(1024);
00340 
00341   /* Handle compile-errors ourself, so we can display it nicely */
00342   sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
00343   sq_notifyallexceptions(this->vm, SQTrue);
00344   /* Set a good print-function */
00345   sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
00346   /* Handle runtime-errors ourself, so we can display it nicely */
00347   sq_newclosure(this->vm, &Squirrel::_RunError, 0);
00348   sq_seterrorhandler(this->vm);
00349 
00350   /* Set the foreign pointer, so we can always find this instance from within the VM */
00351   sq_setforeignptr(this->vm, this);
00352 
00353   sq_pushroottable(this->vm);
00354   squirrel_register_global_std(this);
00355 }
00356 
00357 class SQFile {
00358 private:
00359   FILE *file;
00360   size_t size;
00361   size_t pos;
00362 
00363 public:
00364   SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
00365 
00366   size_t Read(void *buf, size_t elemsize, size_t count)
00367   {
00368     assert(elemsize != 0);
00369     if (this->pos + (elemsize * count) > this->size) {
00370       count = (this->size - this->pos) / elemsize;
00371     }
00372     if (count == 0) return 0;
00373     size_t ret = fread(buf, elemsize, count, this->file);
00374     this->pos += ret * elemsize;
00375     return ret;
00376   }
00377 };
00378 
00379 static SQInteger _io_file_lexfeed_ASCII(SQUserPointer file)
00380 {
00381   char c;
00382   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
00383   return 0;
00384 }
00385 
00386 static SQInteger _io_file_lexfeed_UTF8(SQUserPointer file)
00387 {
00388   static const SQInteger utf8_lengths[16] =
00389   {
00390     1, 1, 1, 1, 1, 1, 1, 1, /* 0000 to 0111 : 1 byte (plain ASCII) */
00391     0, 0, 0, 0,             /* 1000 to 1011 : not valid */
00392     2, 2,                   /* 1100, 1101 : 2 bytes */
00393     3,                      /* 1110 : 3 bytes */
00394     4                       /* 1111 : 4 bytes */
00395   };
00396   static unsigned char byte_masks[5] = {0, 0, 0x1F, 0x0F, 0x07};
00397   unsigned char inchar;
00398   SQInteger c = 0;
00399   if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00400   c = inchar;
00401 
00402   if (c >= 0x80) {
00403     SQInteger tmp;
00404     SQInteger codelen = utf8_lengths[c >> 4];
00405     if (codelen == 0) return 0;
00406 
00407     tmp = c & byte_masks[codelen];
00408     for (SQInteger n = 0; n < codelen - 1; n++) {
00409       tmp <<= 6;
00410       if (((SQFile *)file)->Read(&inchar, sizeof(inchar), 1) != 1) return 0;
00411       tmp |= inchar & 0x3F;
00412     }
00413     c = tmp;
00414   }
00415   return c;
00416 }
00417 
00418 static SQInteger _io_file_lexfeed_UCS2_no_swap(SQUserPointer file)
00419 {
00420   wchar_t c;
00421   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (SQChar)c;
00422   return 0;
00423 }
00424 
00425 static SQInteger _io_file_lexfeed_UCS2_swap(SQUserPointer file)
00426 {
00427   unsigned short c;
00428   if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
00429     c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
00430     return (SQChar)c;
00431   }
00432   return 0;
00433 }
00434 
00435 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
00436 {
00437   SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
00438   if (ret == 0) return -1;
00439   return ret;
00440 }
00441 
00442 SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
00443 {
00444   size_t size;
00445   FILE *file;
00446   SQInteger ret;
00447   unsigned short us;
00448   unsigned char uc;
00449   SQLEXREADFUNC func;
00450 
00451   if (strncmp(this->GetAPIName(), "AI", 2) == 0) {
00452     file = FioFOpenFile(filename, "rb", AI_DIR, &size);
00453     if (file == NULL) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
00454   } else if (strncmp(this->GetAPIName(), "GS", 2) == 0) {
00455     file = FioFOpenFile(filename, "rb", GAME_DIR, &size);
00456     if (file == NULL) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
00457   } else {
00458     NOT_REACHED();
00459   }
00460 
00461   if (file != NULL) {
00462     SQFile f(file, size);
00463     ret = fread(&us, 1, sizeof(us), file);
00464     /* Most likely an empty file */
00465     if (ret != 2) us = 0;
00466 
00467     switch (us) {
00468       case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
00469         fseek(file, -2, SEEK_CUR);
00470         if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
00471           FioFCloseFile(file);
00472           return SQ_OK;
00473         }
00474         FioFCloseFile(file);
00475         return sq_throwerror(vm, _SC("Couldn't read bytecode"));
00476       }
00477       case 0xFFFE:
00478         /* Either this file is encoded as big-endian and we're on a little-endian
00479          * machine, or this file is encoded as little-endian and we're on a big-endian
00480          * machine. Either way, swap the bytes of every word we read. */
00481         func = _io_file_lexfeed_UCS2_swap;
00482         break;
00483       case 0xFEFF: func = _io_file_lexfeed_UCS2_no_swap; break;
00484       case 0xBBEF: // UTF-8
00485       case 0xEFBB: // UTF-8 on big-endian machine
00486         if (fread(&uc, 1, sizeof(uc), file) == 0) {
00487           FioFCloseFile(file);
00488           return sq_throwerror(vm, _SC("I/O error"));
00489         }
00490         if (uc != 0xBF) {
00491           FioFCloseFile(file);
00492           return sq_throwerror(vm, _SC("Unrecognized encoding"));
00493         }
00494         func = _io_file_lexfeed_UTF8;
00495         break;
00496       default: func = _io_file_lexfeed_ASCII; fseek(file, -2, SEEK_CUR); break; // ASCII
00497     }
00498 
00499     if (SQ_SUCCEEDED(sq_compile(vm, func, &f, OTTD2SQ(filename), printerror))) {
00500       FioFCloseFile(file);
00501       return SQ_OK;
00502     }
00503     FioFCloseFile(file);
00504     return SQ_ERROR;
00505   }
00506   return sq_throwerror(vm, _SC("cannot open the file"));
00507 }
00508 
00509 bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
00510 {
00511   /* Make sure we are always in the root-table */
00512   if (in_root) sq_pushroottable(vm);
00513 
00514   SQInteger ops_left = vm->_ops_till_suspend;
00515   /* Load and run the script */
00516   if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
00517     sq_push(vm, -2);
00518     if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue, 100000))) {
00519       sq_pop(vm, 1);
00520       /* After compiling the file we want to reset the amount of opcodes. */
00521       vm->_ops_till_suspend = ops_left;
00522       return true;
00523     }
00524   }
00525 
00526   vm->_ops_till_suspend = ops_left;
00527   DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
00528   return false;
00529 }
00530 
00531 bool Squirrel::LoadScript(const char *script)
00532 {
00533   return LoadScript(this->vm, script);
00534 }
00535 
00536 Squirrel::~Squirrel()
00537 {
00538   /* Clean up the stuff */
00539   sq_pop(this->vm, 1);
00540   sq_close(this->vm);
00541 }
00542 
00543 void Squirrel::InsertResult(bool result)
00544 {
00545   sq_pushbool(this->vm, result);
00546   if (this->IsSuspended()) { // Called before resuming a suspended script?
00547     vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00548     vm->Pop();
00549   }
00550 }
00551 
00552 void Squirrel::InsertResult(int result)
00553 {
00554   sq_pushinteger(this->vm, result);
00555   if (this->IsSuspended()) { // Called before resuming a suspended script?
00556     vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
00557     vm->Pop();
00558   }
00559 }
00560 
00561 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
00562 {
00563   vm->DecreaseOps(ops);
00564 }
00565 
00566 bool Squirrel::IsSuspended()
00567 {
00568   return this->vm->_suspended != 0;
00569 }
00570 
00571 bool Squirrel::HasScriptCrashed()
00572 {
00573   return this->crashed;
00574 }
00575 
00576 void Squirrel::ResetCrashed()
00577 {
00578   this->crashed = false;
00579 }
00580 
00581 void Squirrel::CrashOccurred()
00582 {
00583   this->crashed = true;
00584 }
00585 
00586 bool Squirrel::CanSuspend()
00587 {
00588   return sq_can_suspend(this->vm);
00589 }
00590 
00591 SQInteger Squirrel::GetOpsTillSuspend()
00592 {
00593   return this->vm->_ops_till_suspend;
00594 }