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