OpenTTD Source  1.11.2
squirrel.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #include <stdarg.h>
11 #include <map>
12 #include "../stdafx.h"
13 #include "../debug.h"
14 #include "squirrel_std.hpp"
15 #include "../fileio_func.h"
16 #include "../string_func.h"
17 #include "script_fatalerror.hpp"
18 #include "../settings_type.h"
19 #include <sqstdaux.h>
20 #include <../squirrel/sqpcheader.h>
21 #include <../squirrel/sqvm.h>
22 #include "../core/alloc_func.hpp"
23 
32 /*
33  * If changing the call paths into the scripting engine, define this symbol to enable full debugging of allocations.
34  * This lets you track whether the allocator context is being switched correctly in all call paths.
35 #define SCRIPT_DEBUG_ALLOCATIONS
36 */
37 
39  size_t allocated_size;
41 
48 
49  static const size_t SAFE_LIMIT = 0x8000000;
50 
51 #ifdef SCRIPT_DEBUG_ALLOCATIONS
52  std::map<void *, size_t> allocations;
53 #endif
54 
55  void CheckLimit() const
56  {
57  if (this->allocated_size > this->allocation_limit) throw Script_FatalError("Maximum memory allocation exceeded");
58  }
59 
69  void CheckAllocation(size_t requested_size, const void *p)
70  {
71  if (this->allocated_size > this->allocation_limit && !this->error_thrown) {
72  /* Do not allow allocating more than the allocation limit, except when an error is
73  * already as then the allocation is for throwing that error in Squirrel, the
74  * associated stack trace information and while cleaning up the AI. */
75  this->error_thrown = true;
76  char buff[128];
77  seprintf(buff, lastof(buff), "Maximum memory allocation exceeded by " PRINTF_SIZE " bytes when allocating " PRINTF_SIZE " bytes",
78  this->allocated_size - this->allocation_limit, requested_size);
79  throw Script_FatalError(buff);
80  }
81 
82  if (p == nullptr) {
83  /* The OS did not have enough memory to allocate the object, regardless of the
84  * limit imposed by OpenTTD on the amount of memory that may be allocated. */
85  if (this->error_thrown) {
86  /* The allocation is called in the error handling of a memory allocation
87  * failure, then not being able to allocate that small amount of memory
88  * means there is no other choice than to bug out completely. */
89  MallocError(requested_size);
90  }
91 
92  this->error_thrown = true;
93  char buff[64];
94  seprintf(buff, lastof(buff), "Out of memory. Cannot allocate " PRINTF_SIZE " bytes", requested_size);
95  throw Script_FatalError(buff);
96  }
97  }
98 
99  void *Malloc(SQUnsignedInteger size)
100  {
101  void *p = malloc(size);
102  this->allocated_size += size;
103 
104  this->CheckAllocation(size, p);
105 
106 #ifdef SCRIPT_DEBUG_ALLOCATIONS
107  assert(p != nullptr);
108  assert(this->allocations.find(p) == this->allocations.end());
109  this->allocations[p] = size;
110 #endif
111 
112  return p;
113  }
114 
115  void *Realloc(void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size)
116  {
117  if (p == nullptr) {
118  return this->Malloc(size);
119  }
120  if (size == 0) {
121  this->Free(p, oldsize);
122  return nullptr;
123  }
124 
125 #ifdef SCRIPT_DEBUG_ALLOCATIONS
126  assert(this->allocations[p] == oldsize);
127  this->allocations.erase(p);
128 #endif
129 
130  void *new_p = realloc(p, size);
131 
132  this->allocated_size -= oldsize;
133  this->allocated_size += size;
134 
135  this->CheckAllocation(size, p);
136 
137 #ifdef SCRIPT_DEBUG_ALLOCATIONS
138  assert(new_p != nullptr);
139  assert(this->allocations.find(p) == this->allocations.end());
140  this->allocations[new_p] = size;
141 #endif
142 
143  return new_p;
144  }
145 
146  void Free(void *p, SQUnsignedInteger size)
147  {
148  if (p == nullptr) return;
149  free(p);
150  this->allocated_size -= size;
151 
152 #ifdef SCRIPT_DEBUG_ALLOCATIONS
153  assert(this->allocations.at(p) == size);
154  this->allocations.erase(p);
155 #endif
156  }
157 
159  {
160  this->allocated_size = 0;
161  this->allocation_limit = static_cast<size_t>(_settings_game.script.script_max_memory_megabytes) << 20;
162  if (this->allocation_limit == 0) this->allocation_limit = SAFE_LIMIT; // in case the setting is somehow zero
163  this->error_thrown = false;
164  }
165 
166  ~ScriptAllocator()
167  {
168 #ifdef SCRIPT_DEBUG_ALLOCATIONS
169  assert(this->allocations.size() == 0);
170 #endif
171  }
172 };
173 
180 #include "../safeguards.h"
181 
183 
184 /* See 3rdparty/squirrel/squirrel/sqmem.cpp for the default allocator implementation, which this overrides */
185 #ifndef SQUIRREL_DEFAULT_ALLOCATOR
186 void *sq_vm_malloc(SQUnsignedInteger size) { return _squirrel_allocator->Malloc(size); }
187 void *sq_vm_realloc(void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size) { return _squirrel_allocator->Realloc(p, oldsize, size); }
188 void sq_vm_free(void *p, SQUnsignedInteger size) { _squirrel_allocator->Free(p, size); }
189 #endif
190 
191 size_t Squirrel::GetAllocatedMemory() const noexcept
192 {
193  assert(this->allocator != nullptr);
194  return this->allocator->allocated_size;
195 }
196 
197 
198 void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
199 {
200  SQChar buf[1024];
201 
202  seprintf(buf, lastof(buf), "Error %s:" OTTD_PRINTF64 "/" OTTD_PRINTF64 ": %s", source, line, column, desc);
203 
204  /* Check if we have a custom print function */
205  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
206  engine->crashed = true;
207  SQPrintFunc *func = engine->print_func;
208  if (func == nullptr) {
209  DEBUG(misc, 0, "[Squirrel] Compile error: %s", buf);
210  } else {
211  (*func)(true, buf);
212  }
213 }
214 
215 void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
216 {
217  va_list arglist;
218  SQChar buf[1024];
219 
220  va_start(arglist, s);
221  vseprintf(buf, lastof(buf), s, arglist);
222  va_end(arglist);
223 
224  /* Check if we have a custom print function */
225  SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
226  if (func == nullptr) {
227  fprintf(stderr, "%s", buf);
228  } else {
229  (*func)(true, buf);
230  }
231 }
232 
233 void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
234 {
235  /* Set the print function to something that prints to stderr */
236  SQPRINTFUNCTION pf = sq_getprintfunc(vm);
237  sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc);
238 
239  /* Check if we have a custom print function */
240  SQChar buf[1024];
241  seprintf(buf, lastof(buf), "Your script made an error: %s\n", error);
242  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
243  SQPrintFunc *func = engine->print_func;
244  if (func == nullptr) {
245  fprintf(stderr, "%s", buf);
246  } else {
247  (*func)(true, buf);
248  }
249 
250  /* Print below the error the stack, so the users knows what is happening */
251  sqstd_printcallstack(vm);
252  /* Reset the old print function */
253  sq_setprintfunc(vm, pf);
254 }
255 
256 SQInteger Squirrel::_RunError(HSQUIRRELVM vm)
257 {
258  const SQChar *sErr = 0;
259 
260  if (sq_gettop(vm) >= 1) {
261  if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sErr))) {
262  Squirrel::RunError(vm, sErr);
263  return 0;
264  }
265  }
266 
267  Squirrel::RunError(vm, "unknown error");
268  return 0;
269 }
270 
271 void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
272 {
273  va_list arglist;
274  SQChar buf[1024];
275 
276  va_start(arglist, s);
277  vseprintf(buf, lastof(buf) - 2, s, arglist);
278  va_end(arglist);
279  strecat(buf, "\n", lastof(buf));
280 
281  /* Check if we have a custom print function */
282  SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
283  if (func == nullptr) {
284  printf("%s", buf);
285  } else {
286  (*func)(false, buf);
287  }
288 }
289 
290 void Squirrel::AddMethod(const char *method_name, SQFUNCTION proc, uint nparam, const char *params, void *userdata, int size)
291 {
292  ScriptAllocatorScope alloc_scope(this);
293 
294  sq_pushstring(this->vm, method_name, -1);
295 
296  if (size != 0) {
297  void *ptr = sq_newuserdata(vm, size);
298  memcpy(ptr, userdata, size);
299  }
300 
301  sq_newclosure(this->vm, proc, size != 0 ? 1 : 0);
302  if (nparam != 0) sq_setparamscheck(this->vm, nparam, params);
303  sq_setnativeclosurename(this->vm, -1, method_name);
304  sq_newslot(this->vm, -3, SQFalse);
305 }
306 
307 void Squirrel::AddConst(const char *var_name, int value)
308 {
309  ScriptAllocatorScope alloc_scope(this);
310 
311  sq_pushstring(this->vm, var_name, -1);
312  sq_pushinteger(this->vm, value);
313  sq_newslot(this->vm, -3, SQTrue);
314 }
315 
316 void Squirrel::AddConst(const char *var_name, bool value)
317 {
318  ScriptAllocatorScope alloc_scope(this);
319 
320  sq_pushstring(this->vm, var_name, -1);
321  sq_pushbool(this->vm, value);
322  sq_newslot(this->vm, -3, SQTrue);
323 }
324 
325 void Squirrel::AddClassBegin(const char *class_name)
326 {
327  ScriptAllocatorScope alloc_scope(this);
328 
329  sq_pushroottable(this->vm);
330  sq_pushstring(this->vm, class_name, -1);
331  sq_newclass(this->vm, SQFalse);
332 }
333 
334 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
335 {
336  ScriptAllocatorScope alloc_scope(this);
337 
338  sq_pushroottable(this->vm);
339  sq_pushstring(this->vm, class_name, -1);
340  sq_pushstring(this->vm, parent_class, -1);
341  if (SQ_FAILED(sq_get(this->vm, -3))) {
342  DEBUG(misc, 0, "[squirrel] Failed to initialize class '%s' based on parent class '%s'", class_name, parent_class);
343  DEBUG(misc, 0, "[squirrel] Make sure that '%s' exists before trying to define '%s'", parent_class, class_name);
344  return;
345  }
346  sq_newclass(this->vm, SQTrue);
347 }
348 
350 {
351  ScriptAllocatorScope alloc_scope(this);
352 
353  sq_newslot(vm, -3, SQFalse);
354  sq_pop(vm, 1);
355 }
356 
357 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
358 {
359  assert(!this->crashed);
360  ScriptAllocatorScope alloc_scope(this);
361 
362  int top = sq_gettop(this->vm);
363  /* Go to the instance-root */
364  sq_pushobject(this->vm, instance);
365  /* Find the function-name inside the script */
366  sq_pushstring(this->vm, method_name, -1);
367  if (SQ_FAILED(sq_get(this->vm, -2))) {
368  sq_settop(this->vm, top);
369  return false;
370  }
371  sq_settop(this->vm, top);
372  return true;
373 }
374 
375 bool Squirrel::Resume(int suspend)
376 {
377  assert(!this->crashed);
378  ScriptAllocatorScope alloc_scope(this);
379 
380  /* Did we use more operations than we should have in the
381  * previous tick? If so, subtract that from the current run. */
382  if (this->overdrawn_ops > 0 && suspend > 0) {
383  this->overdrawn_ops -= suspend;
384  /* Do we need to wait even more? */
385  if (this->overdrawn_ops >= 0) return true;
386 
387  /* We can now only run whatever is "left". */
388  suspend = -this->overdrawn_ops;
389  }
390 
391  this->crashed = !sq_resumecatch(this->vm, suspend);
392  this->overdrawn_ops = -this->vm->_ops_till_suspend;
393  this->allocator->CheckLimit();
394  return this->vm->_suspended != 0;
395 }
396 
398 {
399  assert(!this->crashed);
400  ScriptAllocatorScope alloc_scope(this);
401  sq_resumeerror(this->vm);
402 }
403 
405 {
406  ScriptAllocatorScope alloc_scope(this);
407  sq_collectgarbage(this->vm);
408 }
409 
410 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
411 {
412  assert(!this->crashed);
413  ScriptAllocatorScope alloc_scope(this);
414  this->allocator->CheckLimit();
415 
416  /* Store the stack-location for the return value. We need to
417  * restore this after saving or the stack will be corrupted
418  * if we're in the middle of a DoCommand. */
419  SQInteger last_target = this->vm->_suspended_target;
420  /* Store the current top */
421  int top = sq_gettop(this->vm);
422  /* Go to the instance-root */
423  sq_pushobject(this->vm, instance);
424  /* Find the function-name inside the script */
425  sq_pushstring(this->vm, method_name, -1);
426  if (SQ_FAILED(sq_get(this->vm, -2))) {
427  DEBUG(misc, 0, "[squirrel] Could not find '%s' in the class", method_name);
428  sq_settop(this->vm, top);
429  return false;
430  }
431  /* Call the method */
432  sq_pushobject(this->vm, instance);
433  if (SQ_FAILED(sq_call(this->vm, 1, ret == nullptr ? SQFalse : SQTrue, SQTrue, suspend))) return false;
434  if (ret != nullptr) sq_getstackobj(vm, -1, ret);
435  /* Reset the top, but don't do so for the script main function, as we need
436  * a correct stack when resuming. */
437  if (suspend == -1 || !this->IsSuspended()) sq_settop(this->vm, top);
438  /* Restore the return-value location. */
439  this->vm->_suspended_target = last_target;
440 
441  return true;
442 }
443 
444 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
445 {
446  HSQOBJECT ret;
447  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
448  if (ret._type != OT_STRING) return false;
449  *res = stredup(ObjectToString(&ret));
450  ValidateString(*res);
451  return true;
452 }
453 
454 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
455 {
456  HSQOBJECT ret;
457  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
458  if (ret._type != OT_INTEGER) return false;
459  *res = ObjectToInteger(&ret);
460  return true;
461 }
462 
463 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
464 {
465  HSQOBJECT ret;
466  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
467  if (ret._type != OT_BOOL) return false;
468  *res = ObjectToBool(&ret);
469  return true;
470 }
471 
472 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name)
473 {
474  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
475 
476  int oldtop = sq_gettop(vm);
477 
478  /* First, find the class */
479  sq_pushroottable(vm);
480 
481  if (prepend_API_name) {
482  size_t len = strlen(class_name) + strlen(engine->GetAPIName()) + 1;
483  char *class_name2 = (char *)alloca(len);
484  seprintf(class_name2, class_name2 + len - 1, "%s%s", engine->GetAPIName(), class_name);
485 
486  sq_pushstring(vm, class_name2, -1);
487  } else {
488  sq_pushstring(vm, class_name, -1);
489  }
490 
491  if (SQ_FAILED(sq_get(vm, -2))) {
492  DEBUG(misc, 0, "[squirrel] Failed to find class by the name '%s%s'", prepend_API_name ? engine->GetAPIName() : "", class_name);
493  sq_settop(vm, oldtop);
494  return false;
495  }
496 
497  /* Create the instance */
498  if (SQ_FAILED(sq_createinstance(vm, -1))) {
499  DEBUG(misc, 0, "[squirrel] Failed to create instance for class '%s%s'", prepend_API_name ? engine->GetAPIName() : "", class_name);
500  sq_settop(vm, oldtop);
501  return false;
502  }
503 
504  if (instance != nullptr) {
505  /* Find our instance */
506  sq_getstackobj(vm, -1, instance);
507  /* Add a reference to it, so it survives for ever */
508  sq_addref(vm, instance);
509  }
510  sq_remove(vm, -2); // Class-name
511  sq_remove(vm, -2); // Root-table
512 
513  /* Store it in the class */
514  sq_setinstanceup(vm, -1, real_instance);
515  if (release_hook != nullptr) sq_setreleasehook(vm, -1, release_hook);
516 
517  if (instance != nullptr) sq_settop(vm, oldtop);
518 
519  return true;
520 }
521 
522 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
523 {
524  ScriptAllocatorScope alloc_scope(this);
525  return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, nullptr);
526 }
527 
528 Squirrel::Squirrel(const char *APIName) :
529  APIName(APIName), allocator(new ScriptAllocator())
530 {
531  this->Initialize();
532 }
533 
535 {
536  ScriptAllocatorScope alloc_scope(this);
537 
538  this->global_pointer = nullptr;
539  this->print_func = nullptr;
540  this->crashed = false;
541  this->overdrawn_ops = 0;
542  this->vm = sq_open(1024);
543 
544  /* Handle compile-errors ourself, so we can display it nicely */
545  sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
546  sq_notifyallexceptions(this->vm, _debug_script_level > 5);
547  /* Set a good print-function */
548  sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
549  /* Handle runtime-errors ourself, so we can display it nicely */
550  sq_newclosure(this->vm, &Squirrel::_RunError, 0);
551  sq_seterrorhandler(this->vm);
552 
553  /* Set the foreign pointer, so we can always find this instance from within the VM */
554  sq_setforeignptr(this->vm, this);
555 
556  sq_pushroottable(this->vm);
558 }
559 
560 class SQFile {
561 private:
562  FILE *file;
563  size_t size;
564  size_t pos;
565 
566 public:
567  SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
568 
569  size_t Read(void *buf, size_t elemsize, size_t count)
570  {
571  assert(elemsize != 0);
572  if (this->pos + (elemsize * count) > this->size) {
573  count = (this->size - this->pos) / elemsize;
574  }
575  if (count == 0) return 0;
576  size_t ret = fread(buf, elemsize, count, this->file);
577  this->pos += ret * elemsize;
578  return ret;
579  }
580 };
581 
582 static WChar _io_file_lexfeed_ASCII(SQUserPointer file)
583 {
584  unsigned char c;
585  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
586  return 0;
587 }
588 
589 static WChar _io_file_lexfeed_UTF8(SQUserPointer file)
590 {
591  char buffer[5];
592 
593  /* Read the first character, and get the length based on UTF-8 specs. If invalid, bail out. */
594  if (((SQFile *)file)->Read(buffer, sizeof(buffer[0]), 1) != 1) return 0;
595  uint len = Utf8EncodedCharLen(buffer[0]);
596  if (len == 0) return -1;
597 
598  /* Read the remaining bits. */
599  if (len > 1 && ((SQFile *)file)->Read(buffer + 1, sizeof(buffer[0]), len - 1) != len - 1) return 0;
600 
601  /* Convert the character, and when definitely invalid, bail out as well. */
602  WChar c;
603  if (Utf8Decode(&c, buffer) != len) return -1;
604 
605  return c;
606 }
607 
608 static WChar _io_file_lexfeed_UCS2_no_swap(SQUserPointer file)
609 {
610  unsigned short c;
611  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (WChar)c;
612  return 0;
613 }
614 
615 static WChar _io_file_lexfeed_UCS2_swap(SQUserPointer file)
616 {
617  unsigned short c;
618  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
619  c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
620  return (WChar)c;
621  }
622  return 0;
623 }
624 
625 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
626 {
627  SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
628  if (ret == 0) return -1;
629  return ret;
630 }
631 
632 SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
633 {
634  ScriptAllocatorScope alloc_scope(this);
635 
636  FILE *file;
637  size_t size;
638  if (strncmp(this->GetAPIName(), "AI", 2) == 0) {
639  file = FioFOpenFile(filename, "rb", AI_DIR, &size);
640  if (file == nullptr) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
641  } else if (strncmp(this->GetAPIName(), "GS", 2) == 0) {
642  file = FioFOpenFile(filename, "rb", GAME_DIR, &size);
643  if (file == nullptr) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
644  } else {
645  NOT_REACHED();
646  }
647 
648  if (file == nullptr) {
649  return sq_throwerror(vm, "cannot open the file");
650  }
651  unsigned short bom = 0;
652  if (size >= 2) {
653  size_t sr = fread(&bom, 1, sizeof(bom), file);
654  (void)sr; // Inside tar, no point checking return value of fread
655  }
656 
657  SQLEXREADFUNC func;
658  switch (bom) {
659  case SQ_BYTECODE_STREAM_TAG: { // BYTECODE
660  if (fseek(file, -2, SEEK_CUR) < 0) {
661  FioFCloseFile(file);
662  return sq_throwerror(vm, "cannot seek the file");
663  }
664 
665  SQFile f(file, size);
666  if (SQ_SUCCEEDED(sq_readclosure(vm, _io_file_read, &f))) {
667  FioFCloseFile(file);
668  return SQ_OK;
669  }
670  FioFCloseFile(file);
671  return sq_throwerror(vm, "Couldn't read bytecode");
672  }
673  case 0xFFFE:
674  /* Either this file is encoded as big-endian and we're on a little-endian
675  * machine, or this file is encoded as little-endian and we're on a big-endian
676  * machine. Either way, swap the bytes of every word we read. */
677  func = _io_file_lexfeed_UCS2_swap;
678  size -= 2; // Skip BOM
679  break;
680  case 0xFEFF:
681  func = _io_file_lexfeed_UCS2_no_swap;
682  size -= 2; // Skip BOM
683  break;
684  case 0xBBEF: // UTF-8
685  case 0xEFBB: { // UTF-8 on big-endian machine
686  /* Similarly, check the file is actually big enough to finish checking BOM */
687  if (size < 3) {
688  FioFCloseFile(file);
689  return sq_throwerror(vm, "I/O error");
690  }
691  unsigned char uc;
692  if (fread(&uc, 1, sizeof(uc), file) != sizeof(uc) || uc != 0xBF) {
693  FioFCloseFile(file);
694  return sq_throwerror(vm, "Unrecognized encoding");
695  }
696  func = _io_file_lexfeed_UTF8;
697  size -= 3; // Skip BOM
698  break;
699  }
700  default: // ASCII
701  func = _io_file_lexfeed_ASCII;
702  /* Account for when we might not have fread'd earlier */
703  if (size >= 2 && fseek(file, -2, SEEK_CUR) < 0) {
704  FioFCloseFile(file);
705  return sq_throwerror(vm, "cannot seek the file");
706  }
707  break;
708  }
709 
710  SQFile f(file, size);
711  if (SQ_SUCCEEDED(sq_compile(vm, func, &f, filename, printerror))) {
712  FioFCloseFile(file);
713  return SQ_OK;
714  }
715  FioFCloseFile(file);
716  return SQ_ERROR;
717 }
718 
719 bool Squirrel::LoadScript(HSQUIRRELVM vm, const char *script, bool in_root)
720 {
721  ScriptAllocatorScope alloc_scope(this);
722 
723  /* Make sure we are always in the root-table */
724  if (in_root) sq_pushroottable(vm);
725 
726  SQInteger ops_left = vm->_ops_till_suspend;
727  /* Load and run the script */
728  if (SQ_SUCCEEDED(LoadFile(vm, script, SQTrue))) {
729  sq_push(vm, -2);
730  if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue, 100000))) {
731  sq_pop(vm, 1);
732  /* After compiling the file we want to reset the amount of opcodes. */
733  vm->_ops_till_suspend = ops_left;
734  return true;
735  }
736  }
737 
738  vm->_ops_till_suspend = ops_left;
739  DEBUG(misc, 0, "[squirrel] Failed to compile '%s'", script);
740  return false;
741 }
742 
743 bool Squirrel::LoadScript(const char *script)
744 {
745  return LoadScript(this->vm, script);
746 }
747 
748 Squirrel::~Squirrel()
749 {
750  this->Uninitialize();
751 }
752 
754 {
755  ScriptAllocatorScope alloc_scope(this);
756 
757  /* Clean up the stuff */
758  sq_pop(this->vm, 1);
759  sq_close(this->vm);
760 }
761 
763 {
764  this->Uninitialize();
765  this->Initialize();
766 }
767 
768 void Squirrel::InsertResult(bool result)
769 {
770  ScriptAllocatorScope alloc_scope(this);
771 
772  sq_pushbool(this->vm, result);
773  if (this->IsSuspended()) { // Called before resuming a suspended script?
774  vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
775  vm->Pop();
776  }
777 }
778 
779 void Squirrel::InsertResult(int result)
780 {
781  ScriptAllocatorScope alloc_scope(this);
782 
783  sq_pushinteger(this->vm, result);
784  if (this->IsSuspended()) { // Called before resuming a suspended script?
785  vm->GetAt(vm->_stackbase + vm->_suspended_target) = vm->GetUp(-1);
786  vm->Pop();
787  }
788 }
789 
790 /* static */ void Squirrel::DecreaseOps(HSQUIRRELVM vm, int ops)
791 {
792  vm->DecreaseOps(ops);
793 }
794 
796 {
797  return this->vm->_suspended != 0;
798 }
799 
801 {
802  return this->crashed;
803 }
804 
806 {
807  this->crashed = true;
808 }
809 
811 {
812  ScriptAllocatorScope alloc_scope(this);
813  return sq_can_suspend(this->vm);
814 }
815 
817 {
818  return this->vm->_ops_till_suspend;
819 }
Squirrel::PrintFunc
static void PrintFunc(HSQUIRRELVM vm, const SQChar *s,...) WARN_FORMAT(2
If a user runs 'print' inside a script, this function gets the params.
Definition: squirrel.cpp:271
ScriptAllocator::allocation_limit
size_t allocation_limit
Maximum this allocator may use before allocations fail.
Definition: squirrel.cpp:40
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:35
ScriptSettings::script_max_memory_megabytes
uint32 script_max_memory_megabytes
limit on memory a single script instance may have allocated
Definition: settings_type.h:358
Squirrel::ObjectToString
static const char * ObjectToString(HSQOBJECT *ptr)
Convert a Squirrel-object to a string.
Definition: squirrel.hpp:205
Squirrel::GetAPIName
const char * GetAPIName()
Get the API name.
Definition: squirrel.hpp:45
GAME_LIBRARY_DIR
@ GAME_LIBRARY_DIR
Subdirectory for all GS libraries.
Definition: fileio_type.h:122
Squirrel::CanSuspend
bool CanSuspend()
Are we allowed to suspend the squirrel script at this moment?
Definition: squirrel.cpp:810
Squirrel::AddClassBegin
void AddClassBegin(const char *class_name)
Adds a class to the global scope.
Definition: squirrel.cpp:325
ScriptAllocator
In the memory allocator for Squirrel we want to directly use malloc/realloc, so when the OS does not ...
Definition: squirrel.cpp:38
Squirrel::Reset
void Reset()
Completely reset the engine; start from scratch.
Definition: squirrel.cpp:762
Squirrel::vm
HSQUIRRELVM vm
The VirtualMachine instance for squirrel.
Definition: squirrel.hpp:29
Squirrel::CreateClassInstanceVM
static bool CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name=false)
Creates a class instance.
Definition: squirrel.cpp:472
ScriptAllocator::error_thrown
bool error_thrown
Whether the error has already been thrown, so to not throw secondary errors in the handling of the al...
Definition: squirrel.cpp:47
Squirrel::GetOpsTillSuspend
SQInteger GetOpsTillSuspend()
How many operations can we execute till suspension?
Definition: squirrel.cpp:816
Squirrel::Initialize
void Initialize()
Perform all initialization steps to create the engine.
Definition: squirrel.cpp:534
Squirrel
Definition: squirrel.hpp:23
Squirrel::global_pointer
void * global_pointer
Can be set by who ever initializes Squirrel.
Definition: squirrel.hpp:30
Squirrel::ObjectToInteger
static int ObjectToInteger(HSQOBJECT *ptr)
Convert a Squirrel-object to an integer.
Definition: squirrel.hpp:210
Squirrel::HasScriptCrashed
bool HasScriptCrashed()
Find out if the squirrel script made an error before.
Definition: squirrel.cpp:800
Squirrel::LoadScript
bool LoadScript(const char *script)
Load a script.
Definition: squirrel.cpp:743
Squirrel::AddClassEnd
void AddClassEnd()
Finishes adding a class to the global scope.
Definition: squirrel.cpp:349
AI_DIR
@ AI_DIR
Subdirectory for all AI files.
Definition: fileio_type.h:119
Squirrel::overdrawn_ops
int overdrawn_ops
The amount of operations we have overdrawn.
Definition: squirrel.hpp:33
GameSettings::script
ScriptSettings script
settings for scripts
Definition: settings_type.h:567
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
Squirrel::Uninitialize
void Uninitialize()
Perform all the cleanups for the engine.
Definition: squirrel.cpp:753
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:406
ScriptAllocatorScope
Definition: squirrel.hpp:288
Squirrel::ErrorPrintFunc
static void static void ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s,...) WARN_FORMAT(2
If an error has to be print, this function is called.
Definition: squirrel.cpp:215
Squirrel::GetAllocatedMemory
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition: squirrel.cpp:191
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
GAME_DIR
@ GAME_DIR
Subdirectory for all game scripts.
Definition: fileio_type.h:121
ScriptAllocator::allocated_size
size_t allocated_size
Sum of allocated data size.
Definition: squirrel.cpp:39
ValidateString
void ValidateString(const char *str)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:285
Squirrel::CallMethod
bool CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
Call a method of an instance, in various flavors.
Definition: squirrel.cpp:410
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:61
Squirrel::ObjectToBool
static bool ObjectToBool(HSQOBJECT *ptr)
Convert a Squirrel-object to a bool.
Definition: squirrel.hpp:215
squirrel_register_global_std
void squirrel_register_global_std(Squirrel *engine)
Register all standard functions that are available on first startup.
Definition: squirrel_std.cpp:94
Squirrel::AddConst
void AddConst(const char *var_name, int value)
Adds a const to the stack.
Definition: squirrel.cpp:307
Squirrel::allocator
std::unique_ptr< ScriptAllocator > allocator
Allocator object used by this script.
Definition: squirrel.hpp:35
Utf8Decode
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:499
Squirrel::ResumeError
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition: squirrel.cpp:397
Squirrel::CreateClassInstance
bool CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
Exactly the same as CreateClassInstanceVM, only callable without instance of Squirrel.
Definition: squirrel.cpp:522
Squirrel::CollectGarbage
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition: squirrel.cpp:404
Squirrel::MethodExists
bool MethodExists(HSQOBJECT instance, const char *method_name)
Check if a method exists in an instance.
Definition: squirrel.cpp:357
Squirrel::AddMethod
void AddMethod(const char *method_name, SQFUNCTION proc, uint nparam=0, const char *params=nullptr, void *userdata=nullptr, int size=0)
Adds a function to the stack.
Definition: squirrel.cpp:290
Squirrel::CrashOccurred
void CrashOccurred()
Set the script status to crashed.
Definition: squirrel.cpp:805
Squirrel::crashed
bool crashed
True if the squirrel script made an error.
Definition: squirrel.hpp:32
ScriptAllocator::SAFE_LIMIT
static const size_t SAFE_LIMIT
128 MiB, a safe choice for almost any situation
Definition: squirrel.cpp:49
Squirrel::RunError
static void RunError(HSQUIRRELVM vm, const SQChar *error)
The RunError handler.
Definition: squirrel.cpp:233
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:460
Squirrel::Resume
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition: squirrel.cpp:375
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:137
Script_FatalError
A throw-class that is given when the script made a fatal error.
Definition: script_fatalerror.hpp:16
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:132
AI_LIBRARY_DIR
@ AI_LIBRARY_DIR
Subdirectory for all AI libraries.
Definition: fileio_type.h:120
script_fatalerror.hpp
squirrel_std.hpp
Squirrel::IsSuspended
bool IsSuspended()
Did the squirrel code suspend or return normally.
Definition: squirrel.cpp:795
Squirrel::print_func
SQPrintFunc * print_func
Points to either nullptr, or a custom print handler.
Definition: squirrel.hpp:31
ScriptAllocator::CheckAllocation
void CheckAllocation(size_t requested_size, const void *p)
Catch all validation for the allocation; did it allocate too much memory according to the allocation ...
Definition: squirrel.cpp:69
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:456
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:84
Squirrel::CompileError
static void CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
The CompileError handler.
Definition: squirrel.cpp:198
MallocError
void NORETURN MallocError(size_t size)
Function to exit with an error message after malloc() or calloc() have failed.
Definition: alloc_func.cpp:18
Squirrel::DecreaseOps
static void DecreaseOps(HSQUIRRELVM vm, int amount)
Tell the VM to remove amount ops from the number of ops till suspend.
Definition: squirrel.cpp:790
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:385
SQFile
Definition: squirrel.cpp:560
Squirrel::LoadFile
SQRESULT LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
Load a file to a given VM.
Definition: squirrel.cpp:632
FioFCloseFile
void FioFCloseFile(FILE *f)
Close a file in a safe way.
Definition: fileio.cpp:288
Utf8EncodedCharLen
static int8 Utf8EncodedCharLen(char c)
Return the length of an UTF-8 encoded value based on a single char.
Definition: string_func.h:128
_squirrel_allocator
ScriptAllocator * _squirrel_allocator
In the memory allocator for Squirrel we want to directly use malloc/realloc, so when the OS does not ...
Definition: squirrel.cpp:182
Squirrel::_RunError
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition: squirrel.cpp:256