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