1 /* Copyright (C) 2017 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #ifndef INCLUDED_SCRIPTINTERFACE
19 #define INCLUDED_SCRIPTINTERFACE
20
21 #include <boost/random/linear_congruential.hpp>
22
23 #include "lib/file/vfs/vfs_path.h"
24
25 #include "maths/Fixed.h"
26 #include "ScriptTypes.h"
27 #include "ps/Errors.h"
28
29 ERROR_GROUP(Scripting);
30 ERROR_TYPE(Scripting, SetupFailed);
31
32 ERROR_SUBGROUP(Scripting, LoadFile);
33 ERROR_TYPE(Scripting_LoadFile, OpenFailed);
34 ERROR_TYPE(Scripting_LoadFile, EvalErrors);
35
36 ERROR_TYPE(Scripting, ConversionFailed);
37 ERROR_TYPE(Scripting, CallFunctionFailed);
38 ERROR_TYPE(Scripting, RegisterFunctionFailed);
39 ERROR_TYPE(Scripting, DefineConstantFailed);
40 ERROR_TYPE(Scripting, CreateObjectFailed);
41 ERROR_TYPE(Scripting, TypeDoesNotExist);
42
43 ERROR_SUBGROUP(Scripting, DefineType);
44 ERROR_TYPE(Scripting_DefineType, AlreadyExists);
45 ERROR_TYPE(Scripting_DefineType, CreationFailed);
46
47 // Set the maximum number of function arguments that can be handled
48 // (This should be as small as possible (for compiler efficiency),
49 // but as large as necessary for all wrapped functions)
50 #define SCRIPT_INTERFACE_MAX_ARGS 8
51
52 // TODO: what's a good default?
53 #define DEFAULT_RUNTIME_SIZE 16 * 1024 * 1024
54 #define DEFAULT_HEAP_GROWTH_BYTES_GCTRIGGER 2 * 1024 *1024
55
56 struct ScriptInterface_impl;
57
58 class ScriptRuntime;
59
60 extern shared_ptr<ScriptRuntime> g_ScriptRuntime;
61
62
63 /**
64 * Abstraction around a SpiderMonkey JSContext.
65 *
66 * Thread-safety:
67 * - May be used in non-main threads.
68 * - Each ScriptInterface must be created, used, and destroyed, all in a single thread
69 * (it must never be shared between threads).
70 */
71 class ScriptInterface
72 {
73 NONCOPYABLE(ScriptInterface);
74
75 public:
76
77 /**
78 * Returns a runtime, which can used to initialise any number of
79 * ScriptInterfaces contexts. Values created in one context may be used
80 * in any other context from the same runtime (but not any other runtime).
81 * Each runtime should only ever be used on a single thread.
82 * @param runtimeSize Maximum size in bytes of the new runtime
83 */
84 static shared_ptr<ScriptRuntime> CreateRuntime(shared_ptr<ScriptRuntime> parentRuntime = shared_ptr<ScriptRuntime>(), int runtimeSize = DEFAULT_RUNTIME_SIZE,
85 int heapGrowthBytesGCTrigger = DEFAULT_HEAP_GROWTH_BYTES_GCTRIGGER);
86
87
88 /**
89 * Constructor.
90 * @param nativeScopeName Name of global object that functions (via RegisterFunction) will
91 * be placed into, as a scoping mechanism; typically "Engine"
92 * @param debugName Name of this interface for CScriptStats purposes.
93 * @param runtime ScriptRuntime to use when initializing this interface.
94 */
95 ScriptInterface(const char* nativeScopeName, const char* debugName, const shared_ptr<ScriptRuntime>& runtime);
96
97 ~ScriptInterface();
98
99 struct CxPrivate
100 {
101 ScriptInterface* pScriptInterface; // the ScriptInterface object the current context belongs to
102 void* pCBData; // meant to be used as the "this" object for callback functions
103 } m_CxPrivate;
104
105 void SetCallbackData(void* pCBData);
106 static CxPrivate* GetScriptInterfaceAndCBData(JSContext* cx);
107
108 JSContext* GetContext() const;
109 JSRuntime* GetJSRuntime() const;
110 shared_ptr<ScriptRuntime> GetRuntime() const;
111
112 /**
113 * Load global scripts that most script contexts need,
114 * located in the /globalscripts directory. VFS must be initialized.
115 */
116 bool LoadGlobalScripts();
117
118 enum CACHED_VAL { CACHE_VECTOR2DPROTO, CACHE_VECTOR3DPROTO };
119 JS::Value GetCachedValue(CACHED_VAL valueIdentifier) const;
120
121 /**
122 * Replace the default JS random number geenrator with a seeded, network-sync'd one.
123 */
124 bool ReplaceNondeterministicRNG(boost::rand48& rng);
125
126 /**
127 * Call a constructor function, equivalent to JS "new ctor(arg)".
128 * @param ctor An object that can be used as constructor
129 * @param argv Constructor arguments
130 * @param out The new object; On error an error message gets logged and out is Null (out.isNull() == true).
131 */
132 void CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const;
133
134 JSObject* CreateCustomObject(const std::string & typeName) const;
135 void DefineCustomObjectType(JSClass *clasp, JSNative constructor, uint minArgs, JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
136
137 JS::Value GetGlobalObject() const;
138
139 /**
140 * Set the named property on the global object.
141 * If @p replace is true, an existing property will be overwritten; otherwise attempts
142 * to set an already-defined value will fail.
143 */
144 template<typename T>
145 bool SetGlobal(const char* name, const T& value, bool replace = false);
146
147 /**
148 * Set the named property on the given object.
149 * Optionally makes it {ReadOnly, DontDelete, DontEnum}.
150 */
151 template<typename T>
152 bool SetProperty(JS::HandleValue obj, const char* name, const T& value, bool constant = false, bool enumerate = true) const;
153
154 /**
155 * Set the named property on the given object.
156 * Optionally makes it {ReadOnly, DontDelete, DontEnum}.
157 */
158 template<typename T>
159 bool SetProperty(JS::HandleValue obj, const wchar_t* name, const T& value, bool constant = false, bool enumerate = true) const;
160
161 /**
162 * Set the integer-named property on the given object.
163 * Optionally makes it {ReadOnly, DontDelete, DontEnum}.
164 */
165 template<typename T>
166 bool SetPropertyInt(JS::HandleValue obj, int name, const T& value, bool constant = false, bool enumerate = true) const;
167
168 /**
169 * Get the named property on the given object.
170 */
171 template<typename T>
172 bool GetProperty(JS::HandleValue obj, const char* name, T& out) const;
173
174 /**
175 * Get the named property of the given object.
176 */
177 bool GetProperty(JS::HandleValue obj, const char* name, JS::MutableHandleValue out) const;
178 bool GetProperty(JS::HandleValue obj, const char* name, JS::MutableHandleObject out) const;
179
180 /**
181 * Get the integer-named property on the given object.
182 */
183 template<typename T>
184 bool GetPropertyInt(JS::HandleValue obj, int name, T& out) const;
185
186 /**
187 * Get the named property of the given object.
188 */
189 bool GetPropertyInt(JS::HandleValue obj, int name, JS::MutableHandleValue out) const;
190
191 /**
192 * Check the named property has been defined on the given object.
193 */
194 bool HasProperty(JS::HandleValue obj, const char* name) const;
195
196 bool EnumeratePropertyNamesWithPrefix(JS::HandleValue objVal, const char* prefix, std::vector<std::string>& out) const;
197
198 bool SetPrototype(JS::HandleValue obj, JS::HandleValue proto);
199
200 bool FreezeObject(JS::HandleValue objVal, bool deep) const;
201
202 bool Eval(const char* code) const;
203
204 template<typename CHAR> bool Eval(const CHAR* code, JS::MutableHandleValue out) const;
205 template<typename T, typename CHAR> bool Eval(const CHAR* code, T& out) const;
206
207 /**
208 * Convert an object to a UTF-8 encoded string, either with JSON
209 * (if pretty == true and there is no JSON error) or with toSource().
210 *
211 * We have to use a mutable handle because JS_Stringify requires that for unknown reasons.
212 */
213 std::string ToString(JS::MutableHandleValue obj, bool pretty = false) const;
214
215 /**
216 * Parse a UTF-8-encoded JSON string. Returns the unmodified value on error
217 * and prints an error message.
218 * @return true on success; false otherwise
219 */
220 bool ParseJSON(const std::string& string_utf8, JS::MutableHandleValue out) const;
221
222 /**
223 * Read a JSON file. Returns the unmodified value on error and prints an error message.
224 */
225 void ReadJSONFile(const VfsPath& path, JS::MutableHandleValue out) const;
226
227 /**
228 * Stringify to a JSON string, UTF-8 encoded. Returns an empty string on error.
229 */
230 std::string StringifyJSON(JS::MutableHandleValue obj, bool indent = true) const;
231
232 /**
233 * Report the given error message through the JS error reporting mechanism,
234 * and throw a JS exception. (Callers can check IsPendingException, and must
235 * return false in that case to propagate the exception.)
236 */
237 void ReportError(const char* msg) const;
238
239 /**
240 * Load and execute the given script in a new function scope.
241 * @param filename Name for debugging purposes (not used to load the file)
242 * @param code JS code to execute
243 * @return true on successful compilation and execution; false otherwise
244 */
245 bool LoadScript(const VfsPath& filename, const std::string& code) const;
246
247 /**
248 * Load and execute the given script in the global scope.
249 * @param filename Name for debugging purposes (not used to load the file)
250 * @param code JS code to execute
251 * @return true on successful compilation and execution; false otherwise
252 */
253 bool LoadGlobalScript(const VfsPath& filename, const std::wstring& code) const;
254
255 /**
256 * Load and execute the given script in the global scope.
257 * @return true on successful compilation and execution; false otherwise
258 */
259 bool LoadGlobalScriptFile(const VfsPath& path) const;
260
261 /**
262 * Construct a new value (usable in this ScriptInterface's context) by cloning
263 * a value from a different context.
264 * Complex values (functions, XML, etc) won't be cloned correctly, but basic
265 * types and cyclic references should be fine.
266 */
267 JS::Value CloneValueFromOtherContext(const ScriptInterface& otherContext, JS::HandleValue val) const;
268
269 /**
270 * Convert a JS::Value to a C++ type. (This might trigger GC.)
271 */
272 template<typename T> static bool FromJSVal(JSContext* cx, const JS::HandleValue val, T& ret);
273
274 /**
275 * Convert a C++ type to a JS::Value. (This might trigger GC. The return
276 * value must be rooted if you don't want it to be collected.)
277 * NOTE: We are passing the JS::Value by reference instead of returning it by value.
278 * The reason is a memory corruption problem that appears to be caused by a bug in Visual Studio.
279 * Details here: http://www.wildfiregames.com/forum/index.php?showtopic=17289&p=285921
280 */
281 template<typename T> static void ToJSVal(JSContext* cx, JS::MutableHandleValue ret, T const& val);
282
283 /**
284 * Convert a named property of an object to a C++ type.
285 */
286 template<typename T> static bool FromJSProperty(JSContext* cx, const JS::HandleValue val, const char* name, T& ret);
287
288 /**
289 * MaybeGC tries to determine whether garbage collection in cx's runtime would free up enough memory to be worth the amount of time it would take.
290 * This calls JS_MaybeGC directly, which does not do incremental GC. Usually you should prefer MaybeIncrementalRuntimeGC.
291 */
292 void MaybeGC();
293
294 /**
295 * Triggers a full non-incremental garbage collection immediately. That should only be required in special cases and normally
296 * you should try to use MaybeIncrementalRuntimeGC instead.
297 */
298 void ForceGC();
299
300 /**
301 * MathRandom (this function) calls the random number generator assigned to this ScriptInterface instance and
302 * returns the generated number.
303 * Math_random (with underscore, not this function) is a global function, but different random number generators can be
304 * stored per ScriptInterface. It calls MathRandom of the current ScriptInterface instance.
305 */
306 bool MathRandom(double& nbr);
307
308 /**
309 * Structured clones are a way to serialize 'simple' JS::Values into a buffer
310 * that can safely be passed between contexts and runtimes and threads.
311 * A StructuredClone can be stored and read multiple times if desired.
312 * We wrap them in shared_ptr so memory management is automatic and
313 * thread-safe.
314 */
315 class StructuredClone
316 {
317 NONCOPYABLE(StructuredClone);
318 public:
319 StructuredClone();
320 ~StructuredClone();
321 u64* m_Data;
322 size_t m_Size;
323 };
324
325 shared_ptr<StructuredClone> WriteStructuredClone(JS::HandleValue v) const;
326 void ReadStructuredClone(const shared_ptr<StructuredClone>& ptr, JS::MutableHandleValue ret) const;
327
328 /**
329 * Converts |a| if needed and assigns it to |handle|.
330 * This is meant for use in other templates where we want to use the same code for JS::RootedValue&/JS::HandleValue and
331 * other types. Note that functions are meant to take JS::HandleValue instead of JS::RootedValue&, but this implicit
332 * conversion does not work for templates (exact type matches required for type deduction).
333 * A similar functionality could also be implemented as a ToJSVal specialization. The current approach was preferred
334 * because "conversions" from JS::HandleValue to JS::MutableHandleValue are unusual and should not happen "by accident".
335 */
336 template <typename T>
337 static void AssignOrToJSVal(JSContext* cx, JS::MutableHandleValue handle, const T& a);
338
339 /**
340 * The same as AssignOrToJSVal, but also allows JS::Value for T.
341 * In most cases it's not safe to use the plain (unrooted) JS::Value type, but this can happen quite
342 * easily with template functions. The idea is that the linker prints an error if AssignOrToJSVal is
343 * used with JS::Value. If the specialization for JS::Value should be allowed, you can use this
344 * "unrooted" version of AssignOrToJSVal.
345 */
346 template <typename T>
AssignOrToJSValUnrooted(JSContext * cx,JS::MutableHandleValue handle,const T & a)347 static void AssignOrToJSValUnrooted(JSContext* cx, JS::MutableHandleValue handle, const T& a)
348 {
349 AssignOrToJSVal(cx, handle, a);
350 }
351
352 /**
353 * Converts |val| to T if needed or just returns it if it's a handle.
354 * This is meant for use in other templates where we want to use the same code for JS::HandleValue and
355 * other types.
356 */
357 template <typename T>
358 static T AssignOrFromJSVal(JSContext* cx, const JS::HandleValue& val, bool& ret);
359
360 private:
361
362 bool CallFunction_(JS::HandleValue val, const char* name, JS::HandleValueArray argv, JS::MutableHandleValue ret) const;
363 bool Eval_(const char* code, JS::MutableHandleValue ret) const;
364 bool Eval_(const wchar_t* code, JS::MutableHandleValue ret) const;
365 bool SetGlobal_(const char* name, JS::HandleValue value, bool replace);
366 bool SetProperty_(JS::HandleValue obj, const char* name, JS::HandleValue value, bool readonly, bool enumerate) const;
367 bool SetProperty_(JS::HandleValue obj, const wchar_t* name, JS::HandleValue value, bool readonly, bool enumerate) const;
368 bool SetPropertyInt_(JS::HandleValue obj, int name, JS::HandleValue value, bool readonly, bool enumerate) const;
369 bool GetProperty_(JS::HandleValue obj, const char* name, JS::MutableHandleValue out) const;
370 bool GetPropertyInt_(JS::HandleValue obj, int name, JS::MutableHandleValue value) const;
371 static bool IsExceptionPending(JSContext* cx);
372 static const JSClass* GetClass(JS::HandleObject obj);
373 static void* GetPrivate(JS::HandleObject obj);
374
375 struct CustomType
376 {
377 // TODO: Move assignment operator and move constructor only have to be
378 // explicitly defined for Visual Studio. VS2013 is still behind on C++11 support
379 // What's missing is what they call "Rvalue references v3.0", see
380 // https://msdn.microsoft.com/en-us/library/hh567368.aspx#rvref
CustomTypeCustomType381 CustomType() {}
382 CustomType& operator=(CustomType&& other)
383 {
384 m_Prototype = std::move(other.m_Prototype);
385 m_Class = std::move(other.m_Class);
386 m_Constructor = std::move(other.m_Constructor);
387 return *this;
388 }
CustomTypeCustomType389 CustomType(CustomType&& other)
390 {
391 m_Prototype = std::move(other.m_Prototype);
392 m_Class = std::move(other.m_Class);
393 m_Constructor = std::move(other.m_Constructor);
394 }
395
396 JS::PersistentRootedObject m_Prototype;
397 JSClass* m_Class;
398 JSNative m_Constructor;
399 };
400 void Register(const char* name, JSNative fptr, size_t nargs) const;
401
402 // Take care to keep this declaration before heap rooted members. Destructors of heap rooted
403 // members have to be called before the runtime destructor.
404 std::unique_ptr<ScriptInterface_impl> m;
405
406 boost::rand48* m_rng;
407 std::map<std::string, CustomType> m_CustomObjectTypes;
408
409 // The nasty macro/template bits are split into a separate file so you don't have to look at them
410 public:
411 #include "NativeWrapperDecls.h"
412 // This declares:
413 //
414 // template <R, T0..., TR (*fptr) (void* cbdata, T0...)>
415 // void RegisterFunction(const char* functionName) const;
416 //
417 // template <R, T0..., TR (*fptr) (void* cbdata, T0...)>
418 // static JSNative call;
419 //
420 // template <R, T0..., JSClass*, TC, TR (TC:*fptr) (T0...)>
421 // static JSNative callMethod;
422 //
423 // template <R, T0..., JSClass*, TC, TR (TC:*fptr) const (T0...)>
424 // static JSNative callMethodConst;
425 //
426 // template <T0...>
427 // static size_t nargs();
428 //
429 // template <R, T0...>
430 // bool CallFunction(JS::HandleValue val, const char* name, R& ret, const T0&...) const;
431 //
432 // template <R, T0...>
433 // bool CallFunction(JS::HandleValue val, const char* name, JS::Rooted<R>* ret, const T0&...) const;
434 //
435 // template <R, T0...>
436 // bool CallFunction(JS::HandleValue val, const char* name, JS::MutableHandle<R> ret, const T0&...) const;
437 //
438 // template <T0...>
439 // bool CallFunctionVoid(JS::HandleValue val, const char* name, const T0&...) const;
440 };
441
442 // Implement those declared functions
443 #include "NativeWrapperDefns.h"
444
445 template<typename T>
AssignOrToJSVal(JSContext * cx,JS::MutableHandleValue handle,const T & a)446 inline void ScriptInterface::AssignOrToJSVal(JSContext* cx, JS::MutableHandleValue handle, const T& a)
447 {
448 ToJSVal(cx, handle, a);
449 }
450
451 template<>
452 inline void ScriptInterface::AssignOrToJSVal<JS::PersistentRootedValue>(JSContext* UNUSED(cx), JS::MutableHandleValue handle, const JS::PersistentRootedValue& a)
453 {
454 handle.set(a);
455 }
456
457 template<>
458 inline void ScriptInterface::AssignOrToJSVal<JS::RootedValue>(JSContext* UNUSED(cx), JS::MutableHandleValue handle, const JS::RootedValue& a)
459 {
460 handle.set(a);
461 }
462
463 template <>
464 inline void ScriptInterface::AssignOrToJSVal<JS::HandleValue>(JSContext* UNUSED(cx), JS::MutableHandleValue handle, const JS::HandleValue& a)
465 {
466 handle.set(a);
467 }
468
469 template <>
470 inline void ScriptInterface::AssignOrToJSValUnrooted<JS::Value>(JSContext* UNUSED(cx), JS::MutableHandleValue handle, const JS::Value& a)
471 {
472 handle.set(a);
473 }
474
475 template<typename T>
AssignOrFromJSVal(JSContext * cx,const JS::HandleValue & val,bool & ret)476 inline T ScriptInterface::AssignOrFromJSVal(JSContext* cx, const JS::HandleValue& val, bool& ret)
477 {
478 T retVal;
479 ret = FromJSVal(cx, val, retVal);
480 return retVal;
481 }
482
483 template<>
484 inline JS::HandleValue ScriptInterface::AssignOrFromJSVal<JS::HandleValue>(JSContext* UNUSED(cx), const JS::HandleValue& val, bool& ret)
485 {
486 ret = true;
487 return val;
488 }
489
490 template<typename T>
SetGlobal(const char * name,const T & value,bool replace)491 bool ScriptInterface::SetGlobal(const char* name, const T& value, bool replace)
492 {
493 JSAutoRequest rq(GetContext());
494 JS::RootedValue val(GetContext());
495 AssignOrToJSVal(GetContext(), &val, value);
496 return SetGlobal_(name, val, replace);
497 }
498
499 template<typename T>
SetProperty(JS::HandleValue obj,const char * name,const T & value,bool readonly,bool enumerate)500 bool ScriptInterface::SetProperty(JS::HandleValue obj, const char* name, const T& value, bool readonly, bool enumerate) const
501 {
502 JSAutoRequest rq(GetContext());
503 JS::RootedValue val(GetContext());
504 AssignOrToJSVal(GetContext(), &val, value);
505 return SetProperty_(obj, name, val, readonly, enumerate);
506 }
507
508 template<typename T>
SetProperty(JS::HandleValue obj,const wchar_t * name,const T & value,bool readonly,bool enumerate)509 bool ScriptInterface::SetProperty(JS::HandleValue obj, const wchar_t* name, const T& value, bool readonly, bool enumerate) const
510 {
511 JSAutoRequest rq(GetContext());
512 JS::RootedValue val(GetContext());
513 AssignOrToJSVal(GetContext(), &val, value);
514 return SetProperty_(obj, name, val, readonly, enumerate);
515 }
516
517 template<typename T>
SetPropertyInt(JS::HandleValue obj,int name,const T & value,bool readonly,bool enumerate)518 bool ScriptInterface::SetPropertyInt(JS::HandleValue obj, int name, const T& value, bool readonly, bool enumerate) const
519 {
520 JSAutoRequest rq(GetContext());
521 JS::RootedValue val(GetContext());
522 AssignOrToJSVal(GetContext(), &val, value);
523 return SetPropertyInt_(obj, name, val, readonly, enumerate);
524 }
525
526 template<typename T>
GetProperty(JS::HandleValue obj,const char * name,T & out)527 bool ScriptInterface::GetProperty(JS::HandleValue obj, const char* name, T& out) const
528 {
529 JSContext* cx = GetContext();
530 JSAutoRequest rq(cx);
531 JS::RootedValue val(cx);
532 if (!GetProperty_(obj, name, &val))
533 return false;
534 return FromJSVal(cx, val, out);
535 }
536
537 template<typename T>
GetPropertyInt(JS::HandleValue obj,int name,T & out)538 bool ScriptInterface::GetPropertyInt(JS::HandleValue obj, int name, T& out) const
539 {
540 JSAutoRequest rq(GetContext());
541 JS::RootedValue val(GetContext());
542 if (!GetPropertyInt_(obj, name, &val))
543 return false;
544 return FromJSVal(GetContext(), val, out);
545 }
546
547 template<typename CHAR>
Eval(const CHAR * code,JS::MutableHandleValue ret)548 bool ScriptInterface::Eval(const CHAR* code, JS::MutableHandleValue ret) const
549 {
550 if (!Eval_(code, ret))
551 return false;
552 return true;
553 }
554
555 template<typename T, typename CHAR>
Eval(const CHAR * code,T & ret)556 bool ScriptInterface::Eval(const CHAR* code, T& ret) const
557 {
558 JSAutoRequest rq(GetContext());
559 JS::RootedValue rval(GetContext());
560 if (!Eval_(code, &rval))
561 return false;
562 return FromJSVal(GetContext(), rval, ret);
563 }
564
565 #endif // INCLUDED_SCRIPTINTERFACE
566