OpenTTD Source: src/script/squirrel.cpp Source File

OpenTTD Source 1.11.0-RC1

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