OpenTTD Source  12.0-beta2
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, const void *p)
71  {
72  if (this->allocated_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 - this->allocation_limit, requested_size);
80  throw Script_FatalError(buff);
81  }
82 
83  if (p == nullptr) {
84  /* The OS did not have enough memory to allocate the object, regardless of the
85  * limit imposed by OpenTTD on the amount of memory that may be allocated. */
86  if (this->error_thrown) {
87  /* The allocation is called in the error handling of a memory allocation
88  * failure, then not being able to allocate that small amount of memory
89  * means there is no other choice than to bug out completely. */
90  MallocError(requested_size);
91  }
92 
93  this->error_thrown = true;
94  char buff[64];
95  seprintf(buff, lastof(buff), "Out of memory. Cannot allocate " PRINTF_SIZE " bytes", requested_size);
96  throw Script_FatalError(buff);
97  }
98  }
99 
100  void *Malloc(SQUnsignedInteger size)
101  {
102  void *p = malloc(size);
103  this->allocated_size += size;
104 
105  this->CheckAllocation(size, p);
106 
107 #ifdef SCRIPT_DEBUG_ALLOCATIONS
108  assert(p != nullptr);
109  assert(this->allocations.find(p) == this->allocations.end());
110  this->allocations[p] = size;
111 #endif
112 
113  return p;
114  }
115 
116  void *Realloc(void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size)
117  {
118  if (p == nullptr) {
119  return this->Malloc(size);
120  }
121  if (size == 0) {
122  this->Free(p, oldsize);
123  return nullptr;
124  }
125 
126 #ifdef SCRIPT_DEBUG_ALLOCATIONS
127  assert(this->allocations[p] == oldsize);
128  this->allocations.erase(p);
129 #endif
130 
131  void *new_p = realloc(p, size);
132 
133  this->allocated_size -= oldsize;
134  this->allocated_size += size;
135 
136  this->CheckAllocation(size, p);
137 
138 #ifdef SCRIPT_DEBUG_ALLOCATIONS
139  assert(new_p != nullptr);
140  assert(this->allocations.find(p) == this->allocations.end());
141  this->allocations[new_p] = size;
142 #endif
143 
144  return new_p;
145  }
146 
147  void Free(void *p, SQUnsignedInteger size)
148  {
149  if (p == nullptr) return;
150  free(p);
151  this->allocated_size -= size;
152 
153 #ifdef SCRIPT_DEBUG_ALLOCATIONS
154  assert(this->allocations.at(p) == size);
155  this->allocations.erase(p);
156 #endif
157  }
158 
160  {
161  this->allocated_size = 0;
162  this->allocation_limit = static_cast<size_t>(_settings_game.script.script_max_memory_megabytes) << 20;
163  if (this->allocation_limit == 0) this->allocation_limit = SAFE_LIMIT; // in case the setting is somehow zero
164  this->error_thrown = false;
165  }
166 
167  ~ScriptAllocator()
168  {
169 #ifdef SCRIPT_DEBUG_ALLOCATIONS
170  assert(this->allocations.size() == 0);
171 #endif
172  }
173 };
174 
181 #include "../safeguards.h"
182 
184 
185 /* See 3rdparty/squirrel/squirrel/sqmem.cpp for the default allocator implementation, which this overrides */
186 #ifndef SQUIRREL_DEFAULT_ALLOCATOR
187 void *sq_vm_malloc(SQUnsignedInteger size) { return _squirrel_allocator->Malloc(size); }
188 void *sq_vm_realloc(void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size) { return _squirrel_allocator->Realloc(p, oldsize, size); }
189 void sq_vm_free(void *p, SQUnsignedInteger size) { _squirrel_allocator->Free(p, size); }
190 #endif
191 
192 size_t Squirrel::GetAllocatedMemory() const noexcept
193 {
194  assert(this->allocator != nullptr);
195  return this->allocator->allocated_size;
196 }
197 
198 
199 void Squirrel::CompileError(HSQUIRRELVM vm, const SQChar *desc, const SQChar *source, SQInteger line, SQInteger column)
200 {
201  SQChar buf[1024];
202 
203  seprintf(buf, lastof(buf), "Error %s:" OTTD_PRINTF64 "/" OTTD_PRINTF64 ": %s", source, line, column, desc);
204 
205  /* Check if we have a custom print function */
206  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
207  engine->crashed = true;
208  SQPrintFunc *func = engine->print_func;
209  if (func == nullptr) {
210  Debug(misc, 0, "[Squirrel] Compile error: {}", buf);
211  } else {
212  (*func)(true, buf);
213  }
214 }
215 
216 void Squirrel::ErrorPrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
217 {
218  va_list arglist;
219  SQChar buf[1024];
220 
221  va_start(arglist, s);
222  vseprintf(buf, lastof(buf), s, arglist);
223  va_end(arglist);
224 
225  /* Check if we have a custom print function */
226  SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
227  if (func == nullptr) {
228  fprintf(stderr, "%s", buf);
229  } else {
230  (*func)(true, buf);
231  }
232 }
233 
234 void Squirrel::RunError(HSQUIRRELVM vm, const SQChar *error)
235 {
236  /* Set the print function to something that prints to stderr */
237  SQPRINTFUNCTION pf = sq_getprintfunc(vm);
238  sq_setprintfunc(vm, &Squirrel::ErrorPrintFunc);
239 
240  /* Check if we have a custom print function */
241  SQChar buf[1024];
242  seprintf(buf, lastof(buf), "Your script made an error: %s\n", error);
243  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
244  SQPrintFunc *func = engine->print_func;
245  if (func == nullptr) {
246  fprintf(stderr, "%s", buf);
247  } else {
248  (*func)(true, buf);
249  }
250 
251  /* Print below the error the stack, so the users knows what is happening */
252  sqstd_printcallstack(vm);
253  /* Reset the old print function */
254  sq_setprintfunc(vm, pf);
255 }
256 
257 SQInteger Squirrel::_RunError(HSQUIRRELVM vm)
258 {
259  const SQChar *sErr = nullptr;
260 
261  if (sq_gettop(vm) >= 1) {
262  if (SQ_SUCCEEDED(sq_getstring(vm, -1, &sErr))) {
263  Squirrel::RunError(vm, sErr);
264  return 0;
265  }
266  }
267 
268  Squirrel::RunError(vm, "unknown error");
269  return 0;
270 }
271 
272 void Squirrel::PrintFunc(HSQUIRRELVM vm, const SQChar *s, ...)
273 {
274  va_list arglist;
275  SQChar buf[1024];
276 
277  va_start(arglist, s);
278  vseprintf(buf, lastof(buf) - 2, s, arglist);
279  va_end(arglist);
280  strecat(buf, "\n", lastof(buf));
281 
282  /* Check if we have a custom print function */
283  SQPrintFunc *func = ((Squirrel *)sq_getforeignptr(vm))->print_func;
284  if (func == nullptr) {
285  printf("%s", buf);
286  } else {
287  (*func)(false, buf);
288  }
289 }
290 
291 void Squirrel::AddMethod(const char *method_name, SQFUNCTION proc, uint nparam, const char *params, void *userdata, int size)
292 {
293  ScriptAllocatorScope alloc_scope(this);
294 
295  sq_pushstring(this->vm, method_name, -1);
296 
297  if (size != 0) {
298  void *ptr = sq_newuserdata(vm, size);
299  memcpy(ptr, userdata, size);
300  }
301 
302  sq_newclosure(this->vm, proc, size != 0 ? 1 : 0);
303  if (nparam != 0) sq_setparamscheck(this->vm, nparam, params);
304  sq_setnativeclosurename(this->vm, -1, method_name);
305  sq_newslot(this->vm, -3, SQFalse);
306 }
307 
308 void Squirrel::AddConst(const char *var_name, int value)
309 {
310  ScriptAllocatorScope alloc_scope(this);
311 
312  sq_pushstring(this->vm, var_name, -1);
313  sq_pushinteger(this->vm, value);
314  sq_newslot(this->vm, -3, SQTrue);
315 }
316 
317 void Squirrel::AddConst(const char *var_name, bool value)
318 {
319  ScriptAllocatorScope alloc_scope(this);
320 
321  sq_pushstring(this->vm, var_name, -1);
322  sq_pushbool(this->vm, value);
323  sq_newslot(this->vm, -3, SQTrue);
324 }
325 
326 void Squirrel::AddClassBegin(const char *class_name)
327 {
328  ScriptAllocatorScope alloc_scope(this);
329 
330  sq_pushroottable(this->vm);
331  sq_pushstring(this->vm, class_name, -1);
332  sq_newclass(this->vm, SQFalse);
333 }
334 
335 void Squirrel::AddClassBegin(const char *class_name, const char *parent_class)
336 {
337  ScriptAllocatorScope alloc_scope(this);
338 
339  sq_pushroottable(this->vm);
340  sq_pushstring(this->vm, class_name, -1);
341  sq_pushstring(this->vm, parent_class, -1);
342  if (SQ_FAILED(sq_get(this->vm, -3))) {
343  Debug(misc, 0, "[squirrel] Failed to initialize class '{}' based on parent class '{}'", class_name, parent_class);
344  Debug(misc, 0, "[squirrel] Make sure that '{}' exists before trying to define '{}'", parent_class, class_name);
345  return;
346  }
347  sq_newclass(this->vm, SQTrue);
348 }
349 
351 {
352  ScriptAllocatorScope alloc_scope(this);
353 
354  sq_newslot(vm, -3, SQFalse);
355  sq_pop(vm, 1);
356 }
357 
358 bool Squirrel::MethodExists(HSQOBJECT instance, const char *method_name)
359 {
360  assert(!this->crashed);
361  ScriptAllocatorScope alloc_scope(this);
362 
363  int top = sq_gettop(this->vm);
364  /* Go to the instance-root */
365  sq_pushobject(this->vm, instance);
366  /* Find the function-name inside the script */
367  sq_pushstring(this->vm, method_name, -1);
368  if (SQ_FAILED(sq_get(this->vm, -2))) {
369  sq_settop(this->vm, top);
370  return false;
371  }
372  sq_settop(this->vm, top);
373  return true;
374 }
375 
376 bool Squirrel::Resume(int suspend)
377 {
378  assert(!this->crashed);
379  ScriptAllocatorScope alloc_scope(this);
380 
381  /* Did we use more operations than we should have in the
382  * previous tick? If so, subtract that from the current run. */
383  if (this->overdrawn_ops > 0 && suspend > 0) {
384  this->overdrawn_ops -= suspend;
385  /* Do we need to wait even more? */
386  if (this->overdrawn_ops >= 0) return true;
387 
388  /* We can now only run whatever is "left". */
389  suspend = -this->overdrawn_ops;
390  }
391 
392  this->crashed = !sq_resumecatch(this->vm, suspend);
393  this->overdrawn_ops = -this->vm->_ops_till_suspend;
394  this->allocator->CheckLimit();
395  return this->vm->_suspended != 0;
396 }
397 
399 {
400  assert(!this->crashed);
401  ScriptAllocatorScope alloc_scope(this);
402  sq_resumeerror(this->vm);
403 }
404 
406 {
407  ScriptAllocatorScope alloc_scope(this);
408  sq_collectgarbage(this->vm);
409 }
410 
411 bool Squirrel::CallMethod(HSQOBJECT instance, const char *method_name, HSQOBJECT *ret, int suspend)
412 {
413  assert(!this->crashed);
414  ScriptAllocatorScope alloc_scope(this);
415  this->allocator->CheckLimit();
416 
417  /* Store the stack-location for the return value. We need to
418  * restore this after saving or the stack will be corrupted
419  * if we're in the middle of a DoCommand. */
420  SQInteger last_target = this->vm->_suspended_target;
421  /* Store the current top */
422  int top = sq_gettop(this->vm);
423  /* Go to the instance-root */
424  sq_pushobject(this->vm, instance);
425  /* Find the function-name inside the script */
426  sq_pushstring(this->vm, method_name, -1);
427  if (SQ_FAILED(sq_get(this->vm, -2))) {
428  Debug(misc, 0, "[squirrel] Could not find '{}' in the class", method_name);
429  sq_settop(this->vm, top);
430  return false;
431  }
432  /* Call the method */
433  sq_pushobject(this->vm, instance);
434  if (SQ_FAILED(sq_call(this->vm, 1, ret == nullptr ? SQFalse : SQTrue, SQTrue, suspend))) return false;
435  if (ret != nullptr) sq_getstackobj(vm, -1, ret);
436  /* Reset the top, but don't do so for the script main function, as we need
437  * a correct stack when resuming. */
438  if (suspend == -1 || !this->IsSuspended()) sq_settop(this->vm, top);
439  /* Restore the return-value location. */
440  this->vm->_suspended_target = last_target;
441 
442  return true;
443 }
444 
445 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_name, const char **res, int suspend)
446 {
447  HSQOBJECT ret;
448  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
449  if (ret._type != OT_STRING) return false;
450  *res = stredup(ObjectToString(&ret));
451  StrMakeValidInPlace(const_cast<char *>(*res));
452  return true;
453 }
454 
455 bool Squirrel::CallIntegerMethod(HSQOBJECT instance, const char *method_name, int *res, int suspend)
456 {
457  HSQOBJECT ret;
458  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
459  if (ret._type != OT_INTEGER) return false;
460  *res = ObjectToInteger(&ret);
461  return true;
462 }
463 
464 bool Squirrel::CallBoolMethod(HSQOBJECT instance, const char *method_name, bool *res, int suspend)
465 {
466  HSQOBJECT ret;
467  if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
468  if (ret._type != OT_BOOL) return false;
469  *res = ObjectToBool(&ret);
470  return true;
471 }
472 
473 /* static */ bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm, const char *class_name, void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook, bool prepend_API_name)
474 {
475  Squirrel *engine = (Squirrel *)sq_getforeignptr(vm);
476 
477  int oldtop = sq_gettop(vm);
478 
479  /* First, find the class */
480  sq_pushroottable(vm);
481 
482  if (prepend_API_name) {
483  size_t len = strlen(class_name) + strlen(engine->GetAPIName()) + 1;
484  char *class_name2 = (char *)alloca(len);
485  seprintf(class_name2, class_name2 + len - 1, "%s%s", engine->GetAPIName(), class_name);
486 
487  sq_pushstring(vm, class_name2, -1);
488  } else {
489  sq_pushstring(vm, class_name, -1);
490  }
491 
492  if (SQ_FAILED(sq_get(vm, -2))) {
493  Debug(misc, 0, "[squirrel] Failed to find class by the name '{}{}'", prepend_API_name ? engine->GetAPIName() : "", class_name);
494  sq_settop(vm, oldtop);
495  return false;
496  }
497 
498  /* Create the instance */
499  if (SQ_FAILED(sq_createinstance(vm, -1))) {
500  Debug(misc, 0, "[squirrel] Failed to create instance for class '{}{}'", prepend_API_name ? engine->GetAPIName() : "", class_name);
501  sq_settop(vm, oldtop);
502  return false;
503  }
504 
505  if (instance != nullptr) {
506  /* Find our instance */
507  sq_getstackobj(vm, -1, instance);
508  /* Add a reference to it, so it survives for ever */
509  sq_addref(vm, instance);
510  }
511  sq_remove(vm, -2); // Class-name
512  sq_remove(vm, -2); // Root-table
513 
514  /* Store it in the class */
515  sq_setinstanceup(vm, -1, real_instance);
516  if (release_hook != nullptr) sq_setreleasehook(vm, -1, release_hook);
517 
518  if (instance != nullptr) sq_settop(vm, oldtop);
519 
520  return true;
521 }
522 
523 bool Squirrel::CreateClassInstance(const char *class_name, void *real_instance, HSQOBJECT *instance)
524 {
525  ScriptAllocatorScope alloc_scope(this);
526  return Squirrel::CreateClassInstanceVM(this->vm, class_name, real_instance, instance, nullptr);
527 }
528 
529 Squirrel::Squirrel(const char *APIName) :
530  APIName(APIName), allocator(new ScriptAllocator())
531 {
532  this->Initialize();
533 }
534 
536 {
537  ScriptAllocatorScope alloc_scope(this);
538 
539  this->global_pointer = nullptr;
540  this->print_func = nullptr;
541  this->crashed = false;
542  this->overdrawn_ops = 0;
543  this->vm = sq_open(1024);
544 
545  /* Handle compile-errors ourself, so we can display it nicely */
546  sq_setcompilererrorhandler(this->vm, &Squirrel::CompileError);
547  sq_notifyallexceptions(this->vm, _debug_script_level > 5);
548  /* Set a good print-function */
549  sq_setprintfunc(this->vm, &Squirrel::PrintFunc);
550  /* Handle runtime-errors ourself, so we can display it nicely */
551  sq_newclosure(this->vm, &Squirrel::_RunError, 0);
552  sq_seterrorhandler(this->vm);
553 
554  /* Set the foreign pointer, so we can always find this instance from within the VM */
555  sq_setforeignptr(this->vm, this);
556 
557  sq_pushroottable(this->vm);
559 }
560 
561 class SQFile {
562 private:
563  FILE *file;
564  size_t size;
565  size_t pos;
566 
567 public:
568  SQFile(FILE *file, size_t size) : file(file), size(size), pos(0) {}
569 
570  size_t Read(void *buf, size_t elemsize, size_t count)
571  {
572  assert(elemsize != 0);
573  if (this->pos + (elemsize * count) > this->size) {
574  count = (this->size - this->pos) / elemsize;
575  }
576  if (count == 0) return 0;
577  size_t ret = fread(buf, elemsize, count, this->file);
578  this->pos += ret * elemsize;
579  return ret;
580  }
581 };
582 
583 static WChar _io_file_lexfeed_ASCII(SQUserPointer file)
584 {
585  unsigned char c;
586  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return c;
587  return 0;
588 }
589 
590 static WChar _io_file_lexfeed_UTF8(SQUserPointer file)
591 {
592  char buffer[5];
593 
594  /* Read the first character, and get the length based on UTF-8 specs. If invalid, bail out. */
595  if (((SQFile *)file)->Read(buffer, sizeof(buffer[0]), 1) != 1) return 0;
596  uint len = Utf8EncodedCharLen(buffer[0]);
597  if (len == 0) return -1;
598 
599  /* Read the remaining bits. */
600  if (len > 1 && ((SQFile *)file)->Read(buffer + 1, sizeof(buffer[0]), len - 1) != len - 1) return 0;
601 
602  /* Convert the character, and when definitely invalid, bail out as well. */
603  WChar c;
604  if (Utf8Decode(&c, buffer) != len) return -1;
605 
606  return c;
607 }
608 
609 static WChar _io_file_lexfeed_UCS2_no_swap(SQUserPointer file)
610 {
611  unsigned short c;
612  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) return (WChar)c;
613  return 0;
614 }
615 
616 static WChar _io_file_lexfeed_UCS2_swap(SQUserPointer file)
617 {
618  unsigned short c;
619  if (((SQFile *)file)->Read(&c, sizeof(c), 1) > 0) {
620  c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
621  return (WChar)c;
622  }
623  return 0;
624 }
625 
626 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
627 {
628  SQInteger ret = ((SQFile *)file)->Read(buf, 1, size);
629  if (ret == 0) return -1;
630  return ret;
631 }
632 
633 SQRESULT Squirrel::LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
634 {
635  ScriptAllocatorScope alloc_scope(this);
636 
637  FILE *file;
638  size_t size;
639  if (strncmp(this->GetAPIName(), "AI", 2) == 0) {
640  file = FioFOpenFile(filename, "rb", AI_DIR, &size);
641  if (file == nullptr) file = FioFOpenFile(filename, "rb", AI_LIBRARY_DIR, &size);
642  } else if (strncmp(this->GetAPIName(), "GS", 2) == 0) {
643  file = FioFOpenFile(filename, "rb", GAME_DIR, &size);
644  if (file == nullptr) file = FioFOpenFile(filename, "rb", GAME_LIBRARY_DIR, &size);
645  } else {
646  NOT_REACHED();
647  }
648 
649  if (file == nullptr) {
650  return sq_throwerror(vm, "cannot open the file");
651  }
652  unsigned short bom = 0;
653  if (size >= 2) {
654  [[maybe_unused]] size_t sr = fread(&bom, 1, sizeof(bom), file);
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 '{}'", 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:272
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: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:370
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:326
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: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:473
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:816
Squirrel::Initialize
void Initialize()
Perform all initialization steps to create the engine.
Definition: squirrel.cpp:535
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:350
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:579
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:255
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: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:216
Squirrel::GetAllocatedMemory
size_t GetAllocatedMemory() const noexcept
Get number of bytes allocated by this VM.
Definition: squirrel.cpp:192
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:53
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:411
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:308
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:574
Squirrel::ResumeError
void ResumeError()
Resume the VM with an error so it prints a stack trace.
Definition: squirrel.cpp:398
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:523
Squirrel::CollectGarbage
void CollectGarbage()
Tell the VM to do a garbage collection run.
Definition: squirrel.cpp:405
Squirrel::MethodExists
bool MethodExists(HSQOBJECT instance, const char *method_name)
Check if a method exists in an instance.
Definition: squirrel.cpp:358
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:291
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:50
Squirrel::RunError
static void RunError(HSQUIRRELVM vm, const SQChar *error)
The RunError handler.
Definition: squirrel.cpp:234
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:535
Squirrel::Resume
bool Resume(int suspend=-1)
Resume a VM when it was suspended via a throw.
Definition: squirrel.cpp:376
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
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: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:70
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:460
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:199
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:394
SQFile
Definition: squirrel.cpp:561
Squirrel::LoadFile
SQRESULT LoadFile(HSQUIRRELVM vm, const char *filename, SQBool printerror)
Load a file to a given VM.
Definition: squirrel.cpp:633
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:132
_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:183
Squirrel::_RunError
static SQInteger _RunError(HSQUIRRELVM vm)
The internal RunError handler.
Definition: squirrel.cpp:257