LCOV - code coverage report
Current view: top level - source/scriptinterface - Interface.h (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 28 31 90.3 %
Date: 2026-12-03 01:19:39 Functions: 26 35 74.3 %

          Line data    Source code
       1             : /* Copyright (C) 2026 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_SCRIPT_INTERFACE
      19             : #define INCLUDED_SCRIPT_INTERFACE
      20             : 
      21             : #include "lib/code_annotation.h"
      22             : #include "ps/Errors.h"
      23             : #include "scriptinterface/Conversions.h"
      24             : #include "scriptinterface/Exceptions.h"
      25             : #include "scriptinterface/Request.h"
      26             : 
      27             : #include <functional>
      28             : #include <js/CallArgs.h>
      29             : #include <js/Object.h>
      30             : #include <js/RootingAPI.h>
      31             : #include <js/TypeDecls.h>
      32             : #include <js/Value.h>
      33             : #include <js/ValueArray.h>
      34             : #include <memory>
      35             : #include <string>
      36             : #include <string_view>
      37             : #include <type_traits>
      38             : #include <unordered_map>
      39             : #include <utility>
      40             : 
      41             : class JSObject;
      42             : class Path;
      43             : namespace Script { class Context; }
      44             : namespace Script { class ModuleLoader; }
      45             : namespace Script { struct Interface_impl; }
      46             : namespace boost { namespace random { class rand48; } }
      47             : struct JSClass;
      48             : struct JSContext;
      49             : struct JSFunctionSpec;
      50             : struct JSPropertySpec;
      51             : 
      52             : 
      53             : ERROR_GROUP(Scripting);
      54             : ERROR_TYPE(Scripting, SetupFailed);
      55             : 
      56             : ERROR_SUBGROUP(Scripting, LoadFile);
      57             : ERROR_TYPE(Scripting_LoadFile, OpenFailed);
      58             : ERROR_TYPE(Scripting_LoadFile, EvalErrors);
      59             : 
      60             : ERROR_TYPE(Scripting, CallFunctionFailed);
      61             : ERROR_TYPE(Scripting, DefineConstantFailed);
      62             : ERROR_TYPE(Scripting, CreateObjectFailed);
      63             : ERROR_TYPE(Scripting, TypeDoesNotExist);
      64             : 
      65             : ERROR_SUBGROUP(Scripting, DefineType);
      66             : ERROR_TYPE(Scripting_DefineType, AlreadyExists);
      67             : ERROR_TYPE(Scripting_DefineType, CreationFailed);
      68             : 
      69             : // Set the maximum number of function arguments that can be handled
      70             : // (This should be as small as possible (for compiler efficiency),
      71             : // but as large as necessary for all wrapped functions)
      72             : #define SCRIPT_INTERFACE_MAX_ARGS 8
      73             : 
      74             : using VfsPath = Path;
      75             : 
      76             : // Using a global object for the context is a workaround until Simulation, AI, etc,
      77             : // use their own threads and also their own contexts.
      78         243 : extern thread_local std::shared_ptr<Script::Context> g_ScriptContext;
      79             : 
      80             : /**
      81             :  * Abstraction around a SpiderMonkey JS::Realm.
      82             :  *
      83             :  * Thread-safety:
      84             :  * - May be used in non-main threads.
      85             :  * - Each Script::Interface must be created, used, and destroyed, all in a single thread
      86             :  *   (it must never be shared between threads).
      87             :  */
      88             : 
      89             : namespace Script
      90             : {
      91             : 
      92             : class Interface
      93             : {
      94             :     NONCOPYABLE(Interface);
      95             : 
      96             :     friend class Request;
      97             : 
      98             : public:
      99             : 
     100             :     /**
     101             :      * Constructor.
     102             :      * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will
     103             :      *   be placed into, as a scoping mechanism; typically "Engine"
     104             :      * @param debugName Name of this interface for CScriptStats purposes.
     105             :      * @param context ScriptContext to use when initializing this interface.
     106             :      */
     107             :     Interface(const char* nativeScopeName, const char* debugName, Context& context,
     108             :         std::function<bool(const VfsPath&)> allowModule = {});
     109             : 
     110             :     template<typename Context>
     111         185 :     Interface(const char* nativeScopeName, const char* debugName, Context&& context,
     112             :         std::function<bool(const VfsPath&)> allowModule = {}) :
     113         233 :         Interface{nativeScopeName, debugName, *context, std::move(allowModule)}
     114             :     {
     115             :         static_assert(std::is_lvalue_reference_v<Context>, "`Interface` doesn't take ownership "
     116             :             "of the context.");
     117         185 :     }
     118             : 
     119             :     /**
     120             :      * Alternate constructor. This creates the new Realm in the same Compartment as the neighbor scriptInterface.
     121             :      * This means that data can be freely exchanged between these two script interfaces without cloning.
     122             :      * @param nativeScopeName Name of global object that functions (via Script::Function::Register) will
     123             :      *   be placed into, as a scoping mechanism; typically "Engine"
     124             :      * @param debugName Name of this interface for CScriptStats purposes.
     125             :      * @param scriptInterface 'Neighbor' scriptInterface to share a compartment with.
     126             :      * @param allowModule A predicate deciding wheter to import the given
     127             :      *  module.
     128             :      */
     129             :     Interface(const char* nativeScopeName, const char* debugName, const Interface& neighbor,
     130             :         std::function<bool(const VfsPath&)> allowModule = {});
     131             : 
     132             :     ~Interface();
     133             : 
     134             :     struct CmptPrivate
     135             :     {
     136             :         friend class Interface;
     137             :     public:
     138             :         static const Interface& GetScriptInterface(JSContext* cx);
     139             :         static void* GetCBData(JSContext* cx);
     140             :     protected:
     141             :         Interface* pScriptInterface; // the Interface object the compartment belongs to
     142             :         void* pCBData; // meant to be used as the "this" object for callback functions
     143             :     };
     144             : 
     145             :     void SetCallbackData(void* pCBData);
     146             : 
     147             :     /**
     148             :      * Convert the CmptPrivate callback data to T*
     149             :      */
     150             :     template <typename T>
     151      115030 :     static T* ObjectFromCBData(const Request& rq)
     152             :     {
     153             :         static_assert(!std::is_same_v<void, T>);
     154      114993 :         return static_cast<T*>(ObjectFromCBData<void>(rq));
     155             :     }
     156             : 
     157             :     /**
     158             :      * Variant for the function wrapper.
     159             :      */
     160             :     template <typename T>
     161      114482 :     static T* ObjectFromCBData(const Request& rq, JS::CallArgs&)
     162             :     {
     163      114482 :         return ObjectFromCBData<T>(rq);
     164             :     }
     165             : 
     166             :     ModuleLoader& GetModuleLoader() const;
     167             : 
     168             :     /**
     169             :      * GetGeneralJSContext returns the context without starting a GC request and without
     170             :      * entering the Interface compartment. It should only be used in specific situations,
     171             :      * for instance when initializing a persistent rooted.
     172             :      * If you need the compartmented context of the Interface, you should create a
     173             :      * Interface::Request and use the context from that.
     174             :      */
     175             :     JSContext* GetGeneralJSContext() const;
     176             :     Context& GetContext() const;
     177             : 
     178             :     /**
     179             :      * Load global scripts that most script interfaces need,
     180             :      * located in the /globalscripts directory. VFS must be initialized.
     181             :      */
     182             :     bool LoadGlobalScripts();
     183             : 
     184             :     /**
     185             :      * Replace the default JS random number generator with a seeded, network-synced one.
     186             :      */
     187             :     bool ReplaceNondeterministicRNG(boost::random::rand48& rng);
     188             : 
     189             :     /**
     190             :      * Call a constructor function, equivalent to JS "new ctor(arg)".
     191             :      * @param ctor An object that can be used as constructor
     192             :      * @param argv Constructor arguments
     193             :      * @param out The new object; On error an error message gets logged and out is Null (out.isNull() == true).
     194             :      */
     195             :     void CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const;
     196             : 
     197             :     JSObject* CreateCustomObject(const std::string & typeName) const;
     198             :     void DefineCustomObjectType(JSClass *clasp, JSNative constructor, unsigned int minArgs,
     199             :         JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs);
     200             : 
     201             :     /**
     202             :      * Set the named property on the global object.
     203             :      * Optionally makes it {ReadOnly, DontEnum}. We do not allow to make it DontDelete, so that it can be hotloaded
     204             :      * by deleting it and re-creating it, which is done by setting @p replace to true.
     205             :      */
     206             :     template<typename T>
     207             :     bool SetGlobal(const char* name, const T& value, bool replace = false, bool constant = true, bool enumerate = true);
     208             : 
     209             :     /**
     210             :      * Get an object from the global scope or any lexical scope.
     211             :      * This can return globally accessible objects even if they are not properties
     212             :      * of the global object (e.g. ES6 class definitions).
     213             :      * @param name - Name of the property.
     214             :      * @param out The object or null.
     215             :      */
     216             :     static bool GetGlobalProperty(const Request& rq, const std::string& name, JS::MutableHandleValue out);
     217             : 
     218             :     bool SetPrototype(JS::HandleValue obj, JS::HandleValue proto);
     219             : 
     220             :     /**
     221             :      * Load and execute the given script in a new function scope.
     222             :      * @param filename Name for debugging purposes (not used to load the file)
     223             :      * @param code JS code to execute
     224             :      * @return true on successful compilation and execution; false otherwise
     225             :      */
     226             :     bool LoadScript(const VfsPath& filename, const std::string& code) const;
     227             : 
     228             :     /**
     229             :      * Load and execute the given script in the global scope.
     230             :      * @param filename Name for debugging purposes (not used to load the file)
     231             :      * @param code JS code to execute
     232             :      * @return true on successful compilation and execution; false otherwise
     233             :      */
     234             :     bool LoadGlobalScript(const VfsPath& filename, const std::string& code) const;
     235             : 
     236             :     /**
     237             :      * Load and execute the given script in the global scope.
     238             :      * @return true on successful compilation and execution; false otherwise
     239             :      */
     240             :     bool LoadGlobalScriptFile(const VfsPath& path) const;
     241             : 
     242             :     /**
     243             :      * Evaluate some JS code in the global scope.
     244             :      * @return true on successful compilation and execution; false otherwise
     245             :      */
     246             :     bool Eval(const std::string_view code) const;
     247             :     bool Eval(const std::string_view code, JS::MutableHandleValue out) const;
     248             :     template<typename T> bool Eval(const std::string_view code, T& out) const;
     249             : 
     250             :     /**
     251             :      * Calls the random number generator assigned to this Interface instance and returns the generated number.
     252             :      */
     253             :     bool MathRandom(double& nbr) const;
     254             : 
     255             :     /**
     256             :      * JSNative wrapper of the above.
     257             :      */
     258             :     static bool Math_random(JSContext* cx, unsigned int argc, JS::Value* vp);
     259             : 
     260             :     /**
     261             :      * Name the reserved slots we may need to use in custom JSObjects.
     262             :      * When using JSCLASS_HAS_RESERVED_SLOTS in the definition of your JSClass, use the number
     263             :      * of the highest slot you need plus 1.
     264             :      */
     265             :     enum JSObjectReservedSlots {
     266             :         PRIVATE = 0
     267             :     };
     268             : 
     269             :     /**
     270             :      * Retrieve the private data field of a JSObject.
     271             :      */
     272             :     template <typename T>
     273             :     static T* GetPrivate(const Request& rq, JS::HandleObject thisobj)
     274             :     {
     275             :         T* value = JS::GetMaybePtrFromReservedSlot<T>(thisobj, JSObjectReservedSlots::PRIVATE);
     276             : 
     277             :         if (value == nullptr)
     278             :             Exception::Raise(rq, "Private data of the given object is null!");
     279             : 
     280             :         return value;
     281             :     }
     282             : 
     283             :     /**
     284             :      * Retrieve the private data field of a JS Object.
     285             :      * If an error occurs, GetPrivate will report it with the according stack.
     286             :      */
     287             :     template <typename T>
     288       37723 :     static T* GetPrivate(const Request& rq, JS::CallArgs& callArgs)
     289             :     {
     290       37723 :         if (!callArgs.thisv().isObject())
     291             :         {
     292           0 :             Exception::Raise(rq, "Cannot retrieve private JS object data because from a non-object value!");
     293           0 :             return nullptr;
     294             :         }
     295             : 
     296       37723 :         JS::RootedObject thisObj(rq.cx, &callArgs.thisv().toObject());
     297       37723 :         T* value = JS::GetMaybePtrFromReservedSlot<T>(thisObj, JSObjectReservedSlots::PRIVATE);
     298             : 
     299       37723 :         if (value == nullptr)
     300           0 :             Exception::Raise(rq, "Private data of the given object is null!");
     301             : 
     302       37723 :         return value;
     303       37723 :     }
     304             : 
     305             : private:
     306             :     bool SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate);
     307             : 
     308        6765 :     struct CustomType
     309             :     {
     310             :         JS::PersistentRootedObject m_Prototype;
     311             :         JSClass* m_Class;
     312             :         JSNative m_Constructor;
     313             :     };
     314             : 
     315             :     CmptPrivate m_CmptPrivate;
     316             : 
     317             :     // Take care to keep this declaration before heap rooted members. Destructors of heap rooted
     318             :     // members have to be called before the custom destructor of Interface_impl.
     319             :     std::unique_ptr<Interface_impl> m;
     320             : 
     321             :     std::unordered_map<std::string, CustomType> m_CustomObjectTypes;
     322             : };
     323             : 
     324             : } // namespace Script
     325             : 
     326             : // Explicitly instantiate void* as that is used for the generic template,
     327             : // and we want to define it in the .cpp file.
     328             : template <> void* Script::Interface::ObjectFromCBData(const Script::Request& rq);
     329             : 
     330             : template<typename T>
     331       13818 : bool Script::Interface::SetGlobal(const char* name, const T& value, bool replace, bool constant, bool enumerate)
     332             : {
     333       13818 :     Script::Request rq(this);
     334       13818 :     JS::RootedValue val(rq.cx);
     335       13818 :     Script::ToJSVal(rq, &val, value);
     336       13818 :     return SetGlobal_(name, val, replace, constant, enumerate);
     337       13818 : }
     338             : 
     339             : template<typename T>
     340           8 : bool Script::Interface::Eval(const std::string_view code, T& ret) const
     341             : {
     342           8 :     Script::Request rq(this);
     343           8 :     JS::RootedValue rval(rq.cx);
     344           8 :     if (!Eval(code, &rval))
     345             :         return false;
     346           8 :     return Script::FromJSVal(rq, rval, ret);
     347           8 : }
     348             : 
     349             : #endif // INCLUDED_SCRIPT_INTERFACE

Generated by: LCOV version 1.16