10 #include "../stdafx.h"
13 #include "../fileio_func.h"
14 #include "../string_func.h"
16 #include "../settings_type.h"
18 #include <../squirrel/sqpcheader.h>
19 #include <../squirrel/sqvm.h>
20 #include "../core/alloc_func.hpp"
52 #ifdef SCRIPT_DEBUG_ALLOCATIONS
53 std::map<void *, size_t> allocations;
56 void CheckLimit()
const
58 if (this->allocated_size > this->allocation_limit)
throw Script_FatalError(
"Maximum memory allocation exceeded");
72 if (this->allocated_size + requested_size > this->allocation_limit && !this->error_thrown) {
76 this->error_thrown =
true;
78 seprintf(buff,
lastof(buff),
"Maximum memory allocation exceeded by " PRINTF_SIZE
" bytes when allocating " PRINTF_SIZE
" bytes",
79 this->allocated_size + requested_size - this->allocation_limit, requested_size);
88 if (this->error_thrown) {
95 this->error_thrown =
true;
97 seprintf(buff,
lastof(buff),
"Out of memory. Cannot allocate " PRINTF_SIZE
" bytes", requested_size);
102 void *Malloc(SQUnsignedInteger size)
104 void *p = malloc(size);
108 this->allocated_size += size;
110 #ifdef SCRIPT_DEBUG_ALLOCATIONS
111 assert(p !=
nullptr);
112 assert(this->allocations.find(p) == this->allocations.end());
113 this->allocations[p] = size;
119 void *Realloc(
void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size)
122 return this->Malloc(size);
125 this->Free(p, oldsize);
129 #ifdef SCRIPT_DEBUG_ALLOCATIONS
130 assert(this->allocations[p] == oldsize);
131 this->allocations.erase(p);
137 void *new_p = malloc(size);
142 memcpy(new_p, p, std::min(oldsize, size));
145 this->allocated_size -= oldsize;
146 this->allocated_size += size;
148 #ifdef SCRIPT_DEBUG_ALLOCATIONS
149 assert(new_p !=
nullptr);
150 assert(this->allocations.find(p) == this->allocations.end());
151 this->allocations[new_p] = size;
157 void Free(
void *p, SQUnsignedInteger size)
159 if (p ==
nullptr)
return;
161 this->allocated_size -= size;
163 #ifdef SCRIPT_DEBUG_ALLOCATIONS
164 assert(this->allocations.at(p) == size);
165 this->allocations.erase(p);
171 this->allocated_size = 0;
173 if (this->allocation_limit == 0) this->allocation_limit =
SAFE_LIMIT;
174 this->error_thrown =
false;
179 #ifdef SCRIPT_DEBUG_ALLOCATIONS
180 assert(this->allocations.size() == 0);
191 #include "../safeguards.h"
196 #ifndef SQUIRREL_DEFAULT_ALLOCATOR
198 void *sq_vm_realloc(
void *p, SQUnsignedInteger oldsize, SQUnsignedInteger size) {
return _squirrel_allocator->Realloc(p, oldsize, size); }
213 seprintf(buf,
lastof(buf),
"Error %s:" OTTD_PRINTF64
"/" OTTD_PRINTF64
": %s", source, line, column, desc);
219 if (func ==
nullptr) {
220 Debug(misc, 0,
"[Squirrel] Compile error: {}", buf);
231 va_start(arglist, s);
237 if (func ==
nullptr) {
238 fprintf(stderr,
"%s", buf);
247 SQPRINTFUNCTION pf = sq_getprintfunc(
vm);
255 if (func ==
nullptr) {
256 fprintf(stderr,
"%s", buf);
262 sqstd_printcallstack(
vm);
264 sq_setprintfunc(
vm, pf);
269 const SQChar *sErr =
nullptr;
271 if (sq_gettop(
vm) >= 1) {
272 if (SQ_SUCCEEDED(sq_getstring(
vm, -1, &sErr))) {
287 va_start(arglist, s);
294 if (func ==
nullptr) {
301 void Squirrel::AddMethod(
const char *method_name, SQFUNCTION proc, uint nparam,
const char *params,
void *userdata,
int size)
305 sq_pushstring(this->
vm, method_name, -1);
308 void *ptr = sq_newuserdata(
vm, size);
309 memcpy(ptr, userdata, size);
312 sq_newclosure(this->
vm, proc, size != 0 ? 1 : 0);
313 if (nparam != 0) sq_setparamscheck(this->
vm, nparam, params);
314 sq_setnativeclosurename(this->
vm, -1, method_name);
315 sq_newslot(this->
vm, -3, SQFalse);
322 sq_pushstring(this->
vm, var_name, -1);
323 sq_pushinteger(this->
vm, value);
324 sq_newslot(this->
vm, -3, SQTrue);
331 sq_pushstring(this->
vm, var_name, -1);
332 sq_pushbool(this->
vm, value);
333 sq_newslot(this->
vm, -3, SQTrue);
340 sq_pushroottable(this->
vm);
341 sq_pushstring(this->
vm, class_name, -1);
342 sq_newclass(this->
vm, SQFalse);
349 sq_pushroottable(this->
vm);
350 sq_pushstring(this->
vm, class_name, -1);
351 sq_pushstring(this->
vm, parent_class, -1);
352 if (SQ_FAILED(sq_get(this->
vm, -3))) {
353 Debug(misc, 0,
"[squirrel] Failed to initialize class '{}' based on parent class '{}'", class_name, parent_class);
354 Debug(misc, 0,
"[squirrel] Make sure that '{}' exists before trying to define '{}'", parent_class, class_name);
357 sq_newclass(this->
vm, SQTrue);
364 sq_newslot(
vm, -3, SQFalse);
373 int top = sq_gettop(this->
vm);
375 sq_pushobject(this->
vm, instance);
377 sq_pushstring(this->
vm, method_name, -1);
378 if (SQ_FAILED(sq_get(this->
vm, -2))) {
379 sq_settop(this->
vm, top);
382 sq_settop(this->
vm, top);
402 this->
crashed = !sq_resumecatch(this->
vm, suspend);
405 return this->
vm->_suspended != 0;
412 sq_resumeerror(this->
vm);
418 sq_collectgarbage(this->
vm);
430 SQInteger last_target = this->
vm->_suspended_target;
432 int top = sq_gettop(this->
vm);
434 sq_pushobject(this->
vm, instance);
436 sq_pushstring(this->
vm, method_name, -1);
437 if (SQ_FAILED(sq_get(this->
vm, -2))) {
438 Debug(misc, 0,
"[squirrel] Could not find '{}' in the class", method_name);
439 sq_settop(this->
vm, top);
443 sq_pushobject(this->
vm, instance);
444 if (SQ_FAILED(sq_call(this->
vm, 1, ret ==
nullptr ? SQFalse : SQTrue, SQTrue, suspend)))
return false;
445 if (ret !=
nullptr) sq_getstackobj(
vm, -1, ret);
448 if (suspend == -1 || !this->
IsSuspended()) sq_settop(this->
vm, top);
450 this->
vm->_suspended_target = last_target;
455 bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance,
const char *method_name,
const char **res,
int suspend)
458 if (!this->
CallMethod(instance, method_name, &ret, suspend))
return false;
459 if (ret._type != OT_STRING)
return false;
465 bool Squirrel::CallIntegerMethod(HSQOBJECT instance,
const char *method_name,
int *res,
int suspend)
468 if (!this->
CallMethod(instance, method_name, &ret, suspend))
return false;
469 if (ret._type != OT_INTEGER)
return false;
474 bool Squirrel::CallBoolMethod(HSQOBJECT instance,
const char *method_name,
bool *res,
int suspend)
477 if (!this->
CallMethod(instance, method_name, &ret, suspend))
return false;
478 if (ret._type != OT_BOOL)
return false;
483 bool Squirrel::CreateClassInstanceVM(HSQUIRRELVM vm,
const char *class_name,
void *real_instance, HSQOBJECT *instance, SQRELEASEHOOK release_hook,
bool prepend_API_name)
487 int oldtop = sq_gettop(
vm);
490 sq_pushroottable(
vm);
492 if (prepend_API_name) {
493 size_t len = strlen(class_name) + strlen(engine->
GetAPIName()) + 1;
494 char *class_name2 = (
char *)alloca(len);
495 seprintf(class_name2, class_name2 + len - 1,
"%s%s", engine->
GetAPIName(), class_name);
497 sq_pushstring(
vm, class_name2, -1);
499 sq_pushstring(
vm, class_name, -1);
502 if (SQ_FAILED(sq_get(
vm, -2))) {
503 Debug(misc, 0,
"[squirrel] Failed to find class by the name '{}{}'", prepend_API_name ? engine->
GetAPIName() :
"", class_name);
504 sq_settop(
vm, oldtop);
509 if (SQ_FAILED(sq_createinstance(
vm, -1))) {
510 Debug(misc, 0,
"[squirrel] Failed to create instance for class '{}{}'", prepend_API_name ? engine->
GetAPIName() :
"", class_name);
511 sq_settop(
vm, oldtop);
515 if (instance !=
nullptr) {
517 sq_getstackobj(
vm, -1, instance);
519 sq_addref(
vm, instance);
525 sq_setinstanceup(
vm, -1, real_instance);
526 if (release_hook !=
nullptr) sq_setreleasehook(
vm, -1, release_hook);
528 if (instance !=
nullptr) sq_settop(
vm, oldtop);
539 Squirrel::Squirrel(
const char *APIName) :
553 this->
vm = sq_open(1024);
557 sq_notifyallexceptions(this->
vm, _debug_script_level > 5);
562 sq_seterrorhandler(this->
vm);
565 sq_setforeignptr(this->
vm,
this);
567 sq_pushroottable(this->
vm);
571 sq_pushconsttable(this->
vm);
572 sq_setdelegate(this->
vm, -2);
582 SQFile(FILE *file,
size_t size) : file(file), size(size), pos(0) {}
584 size_t Read(
void *buf,
size_t elemsize,
size_t count)
586 assert(elemsize != 0);
587 if (this->pos + (elemsize * count) > this->size) {
588 count = (this->size - this->pos) / elemsize;
590 if (count == 0)
return 0;
591 size_t ret = fread(buf, elemsize, count, this->file);
592 this->pos += ret * elemsize;
597 static WChar _io_file_lexfeed_ASCII(SQUserPointer file)
600 if (((
SQFile *)file)->Read(&c,
sizeof(c), 1) > 0)
return c;
604 static WChar _io_file_lexfeed_UTF8(SQUserPointer file)
609 if (((
SQFile *)file)->Read(buffer,
sizeof(buffer[0]), 1) != 1)
return 0;
611 if (len == 0)
return -1;
614 if (len > 1 && ((
SQFile *)file)->Read(buffer + 1,
sizeof(buffer[0]), len - 1) != len - 1)
return 0;
623 static WChar _io_file_lexfeed_UCS2_no_swap(SQUserPointer file)
626 if (((
SQFile *)file)->Read(&c,
sizeof(c), 1) > 0)
return (
WChar)c;
630 static WChar _io_file_lexfeed_UCS2_swap(SQUserPointer file)
633 if (((
SQFile *)file)->Read(&c,
sizeof(c), 1) > 0) {
634 c = ((c >> 8) & 0x00FF)| ((c << 8) & 0xFF00);
640 static SQInteger _io_file_read(SQUserPointer file, SQUserPointer buf, SQInteger size)
642 SQInteger ret = ((
SQFile *)file)->Read(buf, 1, size);
643 if (ret == 0)
return -1;
653 if (strncmp(this->
GetAPIName(),
"AI", 2) == 0) {
656 }
else if (strncmp(this->
GetAPIName(),
"GS", 2) == 0) {
663 if (file ==
nullptr) {
664 return sq_throwerror(
vm,
"cannot open the file");
666 unsigned short bom = 0;
668 [[maybe_unused]]
size_t sr = fread(&bom, 1,
sizeof(bom), file);
673 case SQ_BYTECODE_STREAM_TAG: {
674 if (fseek(file, -2, SEEK_CUR) < 0) {
676 return sq_throwerror(
vm,
"cannot seek the file");
680 if (SQ_SUCCEEDED(sq_readclosure(
vm, _io_file_read, &f))) {
685 return sq_throwerror(
vm,
"Couldn't read bytecode");
691 func = _io_file_lexfeed_UCS2_swap;
695 func = _io_file_lexfeed_UCS2_no_swap;
703 return sq_throwerror(
vm,
"I/O error");
706 if (fread(&uc, 1,
sizeof(uc), file) !=
sizeof(uc) || uc != 0xBF) {
708 return sq_throwerror(
vm,
"Unrecognized encoding");
710 func = _io_file_lexfeed_UTF8;
715 func = _io_file_lexfeed_ASCII;
717 if (size >= 2 && fseek(file, -2, SEEK_CUR) < 0) {
719 return sq_throwerror(
vm,
"cannot seek the file");
725 if (SQ_SUCCEEDED(sq_compile(
vm, func, &f, filename, printerror))) {
738 if (in_root) sq_pushroottable(
vm);
740 SQInteger ops_left =
vm->_ops_till_suspend;
742 if (SQ_SUCCEEDED(
LoadFile(
vm, script, SQTrue))) {
744 if (SQ_SUCCEEDED(sq_call(
vm, 1, SQFalse, SQTrue, 100000))) {
747 vm->_ops_till_suspend = ops_left;
752 vm->_ops_till_suspend = ops_left;
753 Debug(misc, 0,
"[squirrel] Failed to compile '{}'", script);
762 Squirrel::~Squirrel()
772 sq_pushroottable(this->vm);
773 sq_pushnull(this->vm);
774 sq_setdelegate(this->vm, -2);
781 assert(this->
allocator->allocated_size == 0);
793 void Squirrel::InsertResult(
bool result)
797 sq_pushbool(this->vm, result);
799 vm->GetAt(
vm->_stackbase +
vm->_suspended_target) =
vm->GetUp(-1);
804 void Squirrel::InsertResult(
int result)
808 sq_pushinteger(this->vm, result);
810 vm->GetAt(
vm->_stackbase +
vm->_suspended_target) =
vm->GetUp(-1);
817 vm->DecreaseOps(ops);
822 return this->vm->_suspended != 0;
838 return sq_can_suspend(this->vm);
843 return this->vm->_ops_till_suspend;