File: ScriptInterface.cpp

package info (click to toggle)
0ad 0.0.26-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 130,460 kB
  • sloc: cpp: 261,824; ansic: 198,392; javascript: 19,067; python: 14,557; sh: 7,629; perl: 4,072; xml: 849; makefile: 741; java: 533; ruby: 229; php: 190; pascal: 30; sql: 21; tcl: 4
file content (716 lines) | stat: -rw-r--r-- 20,648 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/* Copyright (C) 2022 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. 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, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "precompiled.h"

#include "FunctionWrapper.h"
#include "ScriptContext.h"
#include "ScriptExtraHeaders.h"
#include "ScriptInterface.h"
#include "ScriptStats.h"
#include "StructuredClone.h"

#include "lib/debug.h"
#include "lib/utf8.h"
#include "ps/CLogger.h"
#include "ps/Filesystem.h"
#include "ps/Profile.h"

#include <map>
#include <string>

#define BOOST_MULTI_INDEX_DISABLE_SERIALIZATION
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
#include <boost/flyweight/no_locking.hpp>
#include <boost/flyweight/no_tracking.hpp>

/**
 * @file
 * Abstractions of various SpiderMonkey features.
 * Engine code should be using functions of these interfaces rather than
 * directly accessing the underlying JS api.
 */

struct ScriptInterface_impl
{
	ScriptInterface_impl(const char* nativeScopeName, const std::shared_ptr<ScriptContext>& context, JS::Compartment* compartment);
	~ScriptInterface_impl();

	// Take care to keep this declaration before heap rooted members. Destructors of heap rooted
	// members have to be called before the context destructor.
	std::shared_ptr<ScriptContext> m_context;

	friend ScriptRequest;
	private:
		JSContext* m_cx;
		JS::PersistentRootedObject m_glob; // global scope object

	public:
		boost::rand48* m_rng;
		JS::PersistentRootedObject m_nativeScope; // native function scope object
};

/**
 * Constructor for ScriptRequest - here because it needs access into ScriptInterface_impl.
 */
ScriptRequest::ScriptRequest(const ScriptInterface& scriptInterface) :
	cx(scriptInterface.m->m_cx),
	glob(scriptInterface.m->m_glob),
	nativeScope(scriptInterface.m->m_nativeScope),
	m_ScriptInterface(scriptInterface)
{
	m_FormerRealm = JS::EnterRealm(cx, scriptInterface.m->m_glob);
}

ScriptRequest::~ScriptRequest()
{
	JS::LeaveRealm(cx, m_FormerRealm);
}

ScriptRequest::ScriptRequest(JSContext* cx) : ScriptRequest(ScriptInterface::CmptPrivate::GetScriptInterface(cx))
{
}

JS::Value ScriptRequest::globalValue() const
{
	return JS::ObjectValue(*glob);
}

const ScriptInterface& ScriptRequest::GetScriptInterface() const
{
	return m_ScriptInterface;
}

namespace
{

JSClassOps global_classops = {
	nullptr, nullptr,
	nullptr, nullptr,
	nullptr, nullptr, nullptr,
	nullptr, nullptr, nullptr,
	JS_GlobalObjectTraceHook
};

JSClass global_class = {
	"global", JSCLASS_GLOBAL_FLAGS, &global_classops
};

// Functions in the global namespace:

bool print(JSContext* cx, uint argc, JS::Value* vp)
{
	JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	ScriptRequest rq(cx);

	for (uint i = 0; i < args.length(); ++i)
	{
		std::wstring str;
		if (!Script::FromJSVal(rq, args[i], str))
			return false;
		debug_printf("%s", utf8_from_wstring(str).c_str());
	}
	fflush(stdout);
	args.rval().setUndefined();
	return true;
}

bool logmsg(JSContext* cx, uint argc, JS::Value* vp)
{
	JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	if (args.length() < 1)
	{
		args.rval().setUndefined();
		return true;
	}

	ScriptRequest rq(cx);
	std::wstring str;
	if (!Script::FromJSVal(rq, args[0], str))
		return false;
	LOGMESSAGE("%s", utf8_from_wstring(str));
	args.rval().setUndefined();
	return true;
}

bool warn(JSContext* cx, uint argc, JS::Value* vp)
{
	JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	if (args.length() < 1)
	{
		args.rval().setUndefined();
		return true;
	}

	ScriptRequest rq(cx);
	std::wstring str;
	if (!Script::FromJSVal(rq, args[0], str))
		return false;
	LOGWARNING("%s", utf8_from_wstring(str));
	args.rval().setUndefined();
	return true;
}

bool error(JSContext* cx, uint argc, JS::Value* vp)
{
	JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	if (args.length() < 1)
	{
		args.rval().setUndefined();
		return true;
	}

	ScriptRequest rq(cx);
	std::wstring str;
	if (!Script::FromJSVal(rq, args[0], str))
		return false;
	LOGERROR("%s", utf8_from_wstring(str));
	args.rval().setUndefined();
	return true;
}

JS::Value deepcopy(const ScriptRequest& rq, JS::HandleValue val)
{
	if (val.isNullOrUndefined())
	{
		ScriptException::Raise(rq, "deepcopy requires one argument.");
		return JS::UndefinedValue();
	}

	JS::RootedValue ret(rq.cx, Script::DeepCopy(rq, val));
	if (ret.isNullOrUndefined())
	{
		ScriptException::Raise(rq, "deepcopy StructureClone copy failed.");
		return JS::UndefinedValue();
	}
	return ret;
}

JS::Value deepfreeze(const ScriptInterface& scriptInterface, JS::HandleValue val)
{
	ScriptRequest rq(scriptInterface);
	if (!val.isObject())
	{
		ScriptException::Raise(rq, "deepfreeze requires exactly one object as an argument.");
		return JS::UndefinedValue();
	}

	Script::FreezeObject(rq, val, true);
	return val;
}

void ProfileStart(const std::string& regionName)
{
	const char* name = "(ProfileStart)";

	typedef boost::flyweight<
		std::string,
		boost::flyweights::no_tracking,
		boost::flyweights::no_locking
	> StringFlyweight;

	if (!regionName.empty())
		name = StringFlyweight(regionName).get().c_str();

	if (CProfileManager::IsInitialised() && Threading::IsMainThread())
		g_Profiler.StartScript(name);

	g_Profiler2.RecordRegionEnter(name);
}

void ProfileStop()
{
	if (CProfileManager::IsInitialised() && Threading::IsMainThread())
		g_Profiler.Stop();

	g_Profiler2.RecordRegionLeave();
}

void ProfileAttribute(const std::string& attr)
{
	const char* name = "(ProfileAttribute)";

	typedef boost::flyweight<
		std::string,
		boost::flyweights::no_tracking,
		boost::flyweights::no_locking
	> StringFlyweight;

	if (!attr.empty())
		name = StringFlyweight(attr).get().c_str();

	g_Profiler2.RecordAttribute("%s", name);
}

// Math override functions:

// boost::uniform_real is apparently buggy in Boost pre-1.47 - for integer generators
// it returns [min,max], not [min,max). The bug was fixed in 1.47.
// We need consistent behaviour, so manually implement the correct version:
static double generate_uniform_real(boost::rand48& rng, double min, double max)
{
	while (true)
	{
		double n = (double)(rng() - rng.min());
		double d = (double)(rng.max() - rng.min()) + 1.0;
		ENSURE(d > 0 && n >= 0 && n <= d);
		double r = n / d * (max - min) + min;
		if (r < max)
			return r;
	}
}

} // anonymous namespace

bool ScriptInterface::MathRandom(double& nbr) const
{
	if (m->m_rng == nullptr)
		return false;
	nbr = generate_uniform_real(*(m->m_rng), 0.0, 1.0);
	return true;
}

bool ScriptInterface::Math_random(JSContext* cx, uint argc, JS::Value* vp)
{
	JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
	double r;
	if (!ScriptInterface::CmptPrivate::GetScriptInterface(cx).MathRandom(r))
		return false;

	args.rval().setNumber(r);
	return true;
}

ScriptInterface_impl::ScriptInterface_impl(const char* nativeScopeName, const std::shared_ptr<ScriptContext>& context, JS::Compartment* compartment) :
	m_context(context), m_cx(context->GetGeneralJSContext()), m_glob(context->GetGeneralJSContext()), m_nativeScope(context->GetGeneralJSContext())
{
	JS::RealmCreationOptions creationOpt;
	// Keep JIT code during non-shrinking GCs. This brings a quite big performance improvement.
	creationOpt.setPreserveJitCode(true);
	// Enable uneval
	creationOpt.setToSourceEnabled(true);

	if (compartment)
		creationOpt.setExistingCompartment(compartment);
	else
		// This is the default behaviour.
		creationOpt.setNewCompartmentAndZone();

	JS::RealmOptions opt(creationOpt, JS::RealmBehaviors{});

	m_glob = JS_NewGlobalObject(m_cx, &global_class, nullptr, JS::OnNewGlobalHookOption::FireOnNewGlobalHook, opt);

	JSAutoRealm autoRealm(m_cx, m_glob);

	ENSURE(JS::InitRealmStandardClasses(m_cx));

	JS_DefineProperty(m_cx, m_glob, "global", m_glob, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

	// These first 4 actually use CallArgs & thus don't use ScriptFunction
	JS_DefineFunction(m_cx, m_glob, "print", ::print,        0, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, m_glob, "log",   ::logmsg,       1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, m_glob, "warn",  ::warn,         1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(m_cx, m_glob, "error", ::error,        1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
	ScriptFunction::Register<deepcopy>(m_cx, m_glob, "clone");
	ScriptFunction::Register<deepfreeze>(m_cx, m_glob, "deepfreeze");

	m_nativeScope = JS_DefineObject(m_cx, m_glob, nativeScopeName, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);

	ScriptFunction::Register<&ProfileStart>(m_cx, m_nativeScope, "ProfileStart");
	ScriptFunction::Register<&ProfileStop>(m_cx, m_nativeScope, "ProfileStop");
	ScriptFunction::Register<&ProfileAttribute>(m_cx, m_nativeScope, "ProfileAttribute");

	m_context->RegisterRealm(JS::GetObjectRealmOrNull(m_glob));
}

ScriptInterface_impl::~ScriptInterface_impl()
{
	m_context->UnRegisterRealm(JS::GetObjectRealmOrNull(m_glob));
}

ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, const std::shared_ptr<ScriptContext>& context) :
	m(std::make_unique<ScriptInterface_impl>(nativeScopeName, context, nullptr))
{
	// Profiler stats table isn't thread-safe, so only enable this on the main thread
	if (Threading::IsMainThread())
	{
		if (g_ScriptStatsTable)
			g_ScriptStatsTable->Add(this, debugName);
	}

	ScriptRequest rq(this);
	m_CmptPrivate.pScriptInterface = this;
	JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate);
}

ScriptInterface::ScriptInterface(const char* nativeScopeName, const char* debugName, const ScriptInterface& neighbor)
{
	ScriptRequest nrq(neighbor);
	JS::Compartment* comp = JS::GetCompartmentForRealm(JS::GetCurrentRealmOrNull(nrq.cx));
	m = std::make_unique<ScriptInterface_impl>(nativeScopeName, neighbor.GetContext(), comp);

	// Profiler stats table isn't thread-safe, so only enable this on the main thread
	if (Threading::IsMainThread())
	{
		if (g_ScriptStatsTable)
			g_ScriptStatsTable->Add(this, debugName);
	}

	ScriptRequest rq(this);
	m_CmptPrivate.pScriptInterface = this;
	JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate);
}

ScriptInterface::~ScriptInterface()
{
	if (Threading::IsMainThread())
	{
		if (g_ScriptStatsTable)
			g_ScriptStatsTable->Remove(this);
	}
}

const ScriptInterface& ScriptInterface::CmptPrivate::GetScriptInterface(JSContext *cx)
{
	CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx));
	ENSURE(pCmptPrivate);
	return *pCmptPrivate->pScriptInterface;
}

void* ScriptInterface::CmptPrivate::GetCBData(JSContext *cx)
{
	CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx));
	return pCmptPrivate ? pCmptPrivate->pCBData : nullptr;
}

void ScriptInterface::SetCallbackData(void* pCBData)
{
	m_CmptPrivate.pCBData = pCBData;
}

template <>
void* ScriptInterface::ObjectFromCBData<void>(const ScriptRequest& rq)
{
	return ScriptInterface::CmptPrivate::GetCBData(rq.cx);
}

bool ScriptInterface::LoadGlobalScripts()
{
	// Ignore this failure in tests
	if (!g_VFS)
		return false;

	// Load and execute *.js in the global scripts directory
	VfsPaths pathnames;
	vfs::GetPathnames(g_VFS, L"globalscripts/", L"*.js", pathnames);
	for (const VfsPath& path : pathnames)
		if (!LoadGlobalScriptFile(path))
		{
			LOGERROR("LoadGlobalScripts: Failed to load script %s", path.string8());
			return false;
		}

	return true;
}

bool ScriptInterface::ReplaceNondeterministicRNG(boost::rand48& rng)
{
	ScriptRequest rq(this);
	JS::RootedValue math(rq.cx);
	JS::RootedObject global(rq.cx, rq.glob);
	if (JS_GetProperty(rq.cx, global, "Math", &math) && math.isObject())
	{
		JS::RootedObject mathObj(rq.cx, &math.toObject());
		JS::RootedFunction random(rq.cx, JS_DefineFunction(rq.cx, mathObj, "random", Math_random, 0,
			JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT));
		if (random)
		{
			m->m_rng = &rng;
			return true;
		}
	}

	ScriptException::CatchPending(rq);
	LOGERROR("ReplaceNondeterministicRNG: failed to replace Math.random");
	return false;
}

JSContext* ScriptInterface::GetGeneralJSContext() const
{
	return m->m_context->GetGeneralJSContext();
}

std::shared_ptr<ScriptContext> ScriptInterface::GetContext() const
{
	return m->m_context;
}

void ScriptInterface::CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const
{
	ScriptRequest rq(this);
	if (!ctor.isObject())
	{
		LOGERROR("CallConstructor: ctor is not an object");
		out.setNull();
		return;
	}

	JS::RootedObject objOut(rq.cx);
	if (!JS::Construct(rq.cx, ctor, argv, &objOut))
		out.setNull();
	else
		out.setObjectOrNull(objOut);
}

void ScriptInterface::DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs)
{
	ScriptRequest rq(this);
	std::string typeName = clasp->name;

	if (m_CustomObjectTypes.find(typeName) != m_CustomObjectTypes.end())
	{
		// This type already exists
		throw PSERROR_Scripting_DefineType_AlreadyExists();
	}

	JS::RootedObject global(rq.cx, rq.glob);
	JS::RootedObject obj(rq.cx, JS_InitClass(rq.cx, global, nullptr,
	                                           clasp,
	                                           constructor, minArgs,     // Constructor, min args
	                                           ps, fs,                   // Properties, methods
	                                           static_ps, static_fs));   // Constructor properties, methods

	if (obj == nullptr)
	{
		ScriptException::CatchPending(rq);
		throw PSERROR_Scripting_DefineType_CreationFailed();
	}

	CustomType& type = m_CustomObjectTypes[typeName];

	type.m_Prototype.init(rq.cx, obj);
	type.m_Class = clasp;
	type.m_Constructor = constructor;
}

JSObject* ScriptInterface::CreateCustomObject(const std::string& typeName) const
{
	std::map<std::string, CustomType>::const_iterator it = m_CustomObjectTypes.find(typeName);

	if (it == m_CustomObjectTypes.end())
		throw PSERROR_Scripting_TypeDoesNotExist();

	ScriptRequest rq(this);
	JS::RootedObject prototype(rq.cx, it->second.m_Prototype.get());
	return JS_NewObjectWithGivenProto(rq.cx, it->second.m_Class, prototype);
}

bool ScriptInterface::SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate)
{
	ScriptRequest rq(this);
	JS::RootedObject global(rq.cx, rq.glob);

	bool found;
	if (!JS_HasProperty(rq.cx, global, name, &found))
		return false;
	if (found)
	{
		JS::Rooted<JS::PropertyDescriptor> desc(rq.cx);
		if (!JS_GetOwnPropertyDescriptor(rq.cx, global, name, &desc))
			return false;

		if (!desc.writable())
		{
			if (!replace)
			{
				ScriptException::Raise(rq, "SetGlobal \"%s\" called multiple times", name);
				return false;
			}

			// This is not supposed to happen, unless the user has called SetProperty with constant = true on the global object
			// instead of using SetGlobal.
			if (!desc.configurable())
			{
				ScriptException::Raise(rq, "The global \"%s\" is permanent and cannot be hotloaded", name);
				return false;
			}

			LOGMESSAGE("Hotloading new value for global \"%s\".", name);
			ENSURE(JS_DeleteProperty(rq.cx, global, name));
		}
	}

	uint attrs = 0;
	if (constant)
		attrs |= JSPROP_READONLY;
	if (enumerate)
		attrs |= JSPROP_ENUMERATE;

	return JS_DefineProperty(rq.cx, global, name, value, attrs);
}

bool ScriptInterface::GetGlobalProperty(const ScriptRequest& rq, const std::string& name, JS::MutableHandleValue out)
{
	// Try to get the object as a property of the global object.
	JS::RootedObject global(rq.cx, rq.glob);
	if (!JS_GetProperty(rq.cx, global, name.c_str(), out))
	{
		out.set(JS::NullHandleValue);
		return false;
	}

	if (!out.isNullOrUndefined())
		return true;

	// Some objects, such as const definitions, or Class definitions, are hidden inside closures.
	// We must fetch those from the correct lexical scope.
	//JS::RootedValue glob(cx);
	JS::RootedObject lexical_environment(rq.cx, JS_GlobalLexicalEnvironment(rq.glob));
	if (!JS_GetProperty(rq.cx, lexical_environment, name.c_str(), out))
	{
		out.set(JS::NullHandleValue);
		return false;
	}

	if (!out.isNullOrUndefined())
		return true;

	out.set(JS::NullHandleValue);
	return false;
}

bool ScriptInterface::SetPrototype(JS::HandleValue objVal, JS::HandleValue protoVal)
{
	ScriptRequest rq(this);
	if (!objVal.isObject() || !protoVal.isObject())
		return false;
	JS::RootedObject obj(rq.cx, &objVal.toObject());
	JS::RootedObject proto(rq.cx, &protoVal.toObject());
	return JS_SetPrototype(rq.cx, obj, proto);
}

bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& code) const
{
	ScriptRequest rq(this);
	JS::RootedObject global(rq.cx, rq.glob);

	// CompileOptions does not copy the contents of the filename string pointer.
	// Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary.
	std::string filenameStr = filename.string8();

	JS::CompileOptions options(rq.cx);
	// Set the line to 0 because CompileFunction silently adds a `(function() {` as the first line,
	// and errors get misreported.
	// TODO: it would probably be better to not implicitly introduce JS scopes.
	options.setFileAndLine(filenameStr.c_str(), 0);
	options.setIsRunOnce(false);

	JS::SourceText<mozilla::Utf8Unit> src;
	ENSURE(src.init(rq.cx, code.c_str(), code.length(), JS::SourceOwnership::Borrowed));
	JS::RootedObjectVector emptyScopeChain(rq.cx);
	JS::RootedFunction func(rq.cx, JS::CompileFunction(rq.cx, emptyScopeChain, options, NULL, 0, NULL, src));
	if (func == nullptr)
	{
		ScriptException::CatchPending(rq);
		return false;
	}

	JS::RootedValue rval(rq.cx);
	if (JS_CallFunction(rq.cx, nullptr, func, JS::HandleValueArray::empty(), &rval))
		return true;

	ScriptException::CatchPending(rq);
	return false;
}

bool ScriptInterface::LoadGlobalScript(const VfsPath& filename, const std::string& code) const
{
	ScriptRequest rq(this);
	// CompileOptions does not copy the contents of the filename string pointer.
	// Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary.
	std::string filenameStr = filename.string8();

	JS::RootedValue rval(rq.cx);
	JS::CompileOptions opts(rq.cx);
	opts.setFileAndLine(filenameStr.c_str(), 1);

	JS::SourceText<mozilla::Utf8Unit> src;
	ENSURE(src.init(rq.cx, code.c_str(), code.length(), JS::SourceOwnership::Borrowed));
	if (JS::Evaluate(rq.cx, opts, src, &rval))
		return true;

	ScriptException::CatchPending(rq);
	return false;
}

bool ScriptInterface::LoadGlobalScriptFile(const VfsPath& path) const
{
	if (!VfsFileExists(path))
	{
		LOGERROR("File '%s' does not exist", path.string8());
		return false;
	}

	CVFSFile file;

	PSRETURN ret = file.Load(g_VFS, path);

	if (ret != PSRETURN_OK)
	{
		LOGERROR("Failed to load file '%s': %s", path.string8(), GetErrorString(ret));
		return false;
	}

	CStr code = file.DecodeUTF8(); // assume it's UTF-8

	return LoadGlobalScript(path, code);
}

bool ScriptInterface::Eval(const char* code) const
{
	ScriptRequest rq(this);
	JS::RootedValue rval(rq.cx);

	JS::CompileOptions opts(rq.cx);
	opts.setFileAndLine("(eval)", 1);
	JS::SourceText<mozilla::Utf8Unit> src;
	ENSURE(src.init(rq.cx, code, strlen(code), JS::SourceOwnership::Borrowed));
	if (JS::Evaluate(rq.cx, opts, src, &rval))
		return true;

	ScriptException::CatchPending(rq);
	return false;
}

bool ScriptInterface::Eval(const char* code, JS::MutableHandleValue rval) const
{
	ScriptRequest rq(this);

	JS::CompileOptions opts(rq.cx);
	opts.setFileAndLine("(eval)", 1);
	JS::SourceText<mozilla::Utf8Unit> src;
	ENSURE(src.init(rq.cx, code, strlen(code), JS::SourceOwnership::Borrowed));
	if (JS::Evaluate(rq.cx, opts, src, rval))
		return true;

	ScriptException::CatchPending(rq);
	return false;
}